Q: SharePoint 2013 central administration and all other SP sites give HTML 404 error message Today morning I was able to access the SP central administration site and all other SharePoint sites. Then, I created a new web application. Then, clicked on create new site collection. The 'create new site collection' form was open. I went for a cofee and came back after 15 mins and filled in the site collection name and hit 'OK' button to create this site colelction. It gave some correlation id and critical error 2aaf7e9c-46bb-80de-156d-16417c217c0b.
After this, I am unable to access any of SP site or central admin site.
I get the error as:

Info icon   The webpage cannot be found
      HTTP 404
 Most likely causes: •There might be a typing error in the address. •If you clicked on a link, it may be out of date.

 What you can try:

Retype the address.
Go back to the previous page.
Go to  and look for the information you want.
More information  More information
This error (HTTP 404 Not Found) means that Internet Explorer was able
  to connect to the website, but the page you wanted was not found. It's
  possible that the webpage is temporarily unavailable. Alternatively,
  the website might have changed or removed the webpage.
For more information about HTTP errors, see Help.

I tried iisreset and also system restart. Still the same issue. However, if I enter the website URL as: http://<centraladmin url>/_layouts/15/settings.aspx then it opens up the settings page of central administration site.
Incase of a site if I enter the Sp siteurl in browser as:
http://<siteurl>/. Then, it gives the same error 404 as pasted above. However, if I type in URL as http://<siteurl>/_layouts/15/viewlsts.aspx then I can see all the lists on that site. Then, if I click on say 'Site Pages' again it gives above pasted 404 error.
Any idea what is causing this issue?
SharePoint 2013 and SQL Server is on the same VM machine.

A: We ran the SharePoint 2013 Configuration Wizard and the central admin as well as the other sites are opening and working well.

A: When the _layouts folders work, that does not mean much, since they're not really inside t he web applications (CA, custom). They are virtual directories outside of these web applications. A good first thing to check if you can access any content that is located in the Content DB's (i.e. pages in site, list items etc).
One problem that may cause this (unlikely for CA) is that the welcome page for the site collection was not set or set to something that does not exist (check with _layouts/settings.aspx).
From experience, I learned the following thing may prevent SharePoint from running:

*

*Services

*

*On SP Servers

*

*"Windows Process Activation Service",

*"World Wide Web Publishing Service"

*"SharePoint 2010 Administration",

*On SQL Server

*

*"SQL Server (MSSQLSERVER)",

*"SQL Server Agent (MSSQLSERVER)",

*SQL DB's

*

*Check that any relevant SP Sql Databases are not corrupted or in a state other than online

*App pools & IIS Sites

*

*Check that the relevant app pools are running, same for IIS Sites

*Web.config's of the virtual directories hosting the sites

*

*Local_Drive:\Inetpub\wwwroot

A: Please check if you have global directory exists and all its file in it on the server. it should be located at ed both "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\Template\gobal. If it is not exist copy it from another app/wfe server and paste it here.
Rahul

A: Run the wizard to reconfigure config data base in wfe that hosts the central admin site .This was the solution for me


Q: How to write unit test for the function which is accessing aws resources? I have a function which is accessing multiple aws resources and now need to test this function, but I don't know how to mock these resources.
I have tried following github of aws-sdk-mock, but didn't get much there.
function someData(event, configuration, callback) {

    // sts set-up
    var sts = new AWS.STS(configuration.STS_CONFIG);

    sts.assumeRole({
      DurationSeconds: 3600,
      RoleArn: process.env.CROSS_ACCOUNT_ROLE,
      RoleSessionName: configuration.ROLE_NAME
    }, function(err, data) {
      if (err) {
        // an error occurred
        console.log(err, err.stack);
      } else {
        // successful response

        // resolving static credential
        var creds = new AWS.Credentials({
          accessKeyId: data.Credentials.AccessKeyId,
          secretAccessKey: data.Credentials.SecretAccessKey,
          sessionToken: data.Credentials.SessionToken
        });

         // Query function
         var dynamodb = new AWS.DynamoDB({apiVersion: configuration.API_VERSION, credentials:  creds, region: configuration.REGION});
         var docClient = new AWS.DynamoDB.DocumentClient({apiVersion: configuration.API_VERSION, region: configuration.REGION, endpoint: configuration.DDB_ENDPOINT, service: dynamodb });

            // extract params
            var ID = event.queryStringParameters.Id;
            console.log('metrics of id ' + ID);

            var params = {
                TableName: configuration.TABLE_NAME,
                ProjectionExpression: configuration.PROJECTION_ATTR,
                KeyConditionExpression: '#ID = :ID',
                ExpressionAttributeNames: {
                    '#ID': configuration.ID
                },
                ExpressionAttributeValues: {
                    ':ID': ID
                }
            };

            queryDynamoDB(params, docClient).then((response) => {
                console.log('Params: ' + JSON.stringify(params));
                // if the query is Successful
                if( typeof(response[0]) !== 'undefined'){
                    response[0]['Steps'] = process.env.STEPS;
                    response[0]['PageName'] = process.env.STEPS_NAME;
                }
                console.log('The response you get', response);
                var success = {
                    statusCode: HTTP_RESPONSE_CONSTANTS.SUCCESS.statusCode,
                    body: JSON.stringify(response),
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    isBase64Encoded: false
                };
                return callback(null, success);
            }, (err) => {
                // return internal server error
                return callback(null, HTTP_RESPONSE_CONSTANTS.BAD_REQUEST);
            });
      }

    });

}

This is lambda function which I need to test, there are some env variable also which is being used here.
Now I tried writing Unit test for above function using aws-sdk-mock but still I am not able to figure out how to actually do it. Any help will be appreciated. Below is my test code
describe('test getMetrics', function() {

    var expectedOnInvalid = HTTP_RESPONSE_CONSTANTS.BAD_REQUEST;

    it('should assume role ', function(done){
        var event = {
          queryStringParameters : {
              Id: '123456'
          }
        };

        AWS.mock('STS', 'assumeRole', 'roleAssumed');
        AWS.restore('STS');
        AWS.mock('Credentials', 'credentials');
        AWS.restore('Credentials');
        AWS.mock('DynamoDB.DocumentClient', 'get', 'message');
        AWS.mock('DynamoDB', 'describeTable', 'message');
        AWS.restore('DynamoDB');
        AWS.restore('DynamoDB.DocumentClient');

        someData(event, configuration, (err, response) => {
            expect(response).to.deep.equal(expectedOnInvalid);
            done();
        });

    });

});

I am getting the following error :
{ MultipleValidationErrors: There were 2 validation errors:
* MissingRequiredParameter: Missing required key 'RoleArn' in params
* MissingRequiredParameter: Missing required key 'RoleSessionName' in params

A: I strongly disagree with @ttulka's answer, so I have decided to add my own as well.
Given you received an event in your Lambda function, it's very likely you'll process the event and then invoke some other service. It could be a call to S3, DynamoDB, SQS, SNS, Kinesis...you name it. What is there to be asserted at this point?
Correct arguments!
Consider the following event:
{
   "data": "some-data",
   "user": "some-user",
   "additionalInfo": "additionalInfo"
}

Now imagine you want to invoke documentClient.put and you want to make sure that the arguments you're passing are correct. Let's also say that you DON'T want the additionalInfo attribute to be persisted, so, somewhere in your code, you'd have this to get rid of this attribute
delete event.additionalInfo

right?
You can now create a unit test to assert that the correct arguments were passed into documentClient.put, meaning the final object should look like this:
 {
   "data": "some-data",
   "user": "some-user"
 }

Your test must assert that documentClient.put was invoked with a JSON which deep equals the JSON above.
If you or any other developer now, for some reason, removes the delete event.additionalInfo line, tests will start failing.
And this is very powerful! If you make sure that your code works the way you expect, you basically don't have to worry about creating integration tests at all.
Now, if a SQS consumer Lambda expects the body of the message to contain some field, the producer Lambda should always take care of it to make sure the right arguments are being persisted in the Queue. I think by now you get the idea, right?
I always tell my colleagues that if we can create proper unit tests, we should be good to go in 95% of the cases, leaving integration tests out. Of course it's better to have both, but given the amount of time spent on creating integration tests like setting up environments, credentials, sometimes even different accounts, is not worth it. But that's just MY opinion. Both you and @ttulka are more than welcome to disagree.
Now, back to your question:
You can use Sinon to mock and assert arguments in your Lambda functions. If you need to mock a 3rd-party service (like DynamoDB, SQS, etc), you can create a mock object and replace it in your file under test using Rewire. This usually is the road I ride and it has been great so far.

A: Try setting aws-sdk module explicitly.
Project structures that don't include the aws-sdk at the top level node_modules project folder will not be properly mocked. An example of this would be installing the aws-sdk in a nested project directory. You can get around this by explicitly setting the path to a nested aws-sdk module using setSDK().
const AWSMock = require('aws-sdk-mock');
import AWS = require('aws-sdk');
AWSMock.setSDKInstance(AWS);

For more details on this : Read aws-sdk-mock documentation, they have explained it even better.

A: I see unit testing as a way to check if your domain (business) rules are met.
As far as your Lambda contains exclusively only integration of AWS services, it doesn't make much sense to write a unit test for it.
To mock all the resources means, your test will be testing only communication among those mocks - such a test has no value.
External resources mean input/output, this is what integration testing focuses on.
Write integration tests and run them as a part of your integration pipeline against real deployed resources.

A: This is how we can mock STS in nodeJs.
import { STS } from 'aws-sdk';

export default class GetCredential {
  constructor(public sts: STS) { }

  public async getCredentials(role: string) {
    this.log.info('Retrieving credential...', { role });

    const apiRole = await this.sts
      .assumeRole({
        RoleArn: role,
        RoleSessionName: 'test-api',
      })
      .promise();
    if (!apiRole?.Credentials) {
      throw new Error(`Credentials for ${role} could not be retrieved`);
    }

    return apiRole.Credentials;
  }
}

Mock for the above function
import { STS } from 'aws-sdk';
import CredentialRepository from './GetCredential';

const sts = new STS();
let testService: GetCredential;

beforeEach(() => {
  testService = new GetCredential(sts);
});

describe('Given getCredentials has been called', () => {
  it('The method returns a credential', async () => {
    const credential = {
      AccessKeyId: 'AccessKeyId',
      SecretAccessKey: 'SecretAccessKey',
      SessionToken: 'SessionToken'
    };

    const mockGetCredentials = jest.fn().mockReturnValue({
      promise: () => Promise.resolve({ Credentials: credential }),
    });
    testService.sts.assumeRole = mockGetCredentials;
    const result = await testService.getCredentials('fakeRole');
    expect(result).toEqual(credential);
  });
});


Q: Making side effects explicit even in non-pure functions I try to have as many pure functions as possible, but if I can't, I at least try to make the side effects as explicit as possible.
Here is an example (in Go)
type State struct {
    count int
}

func (s *State) IncreaseCount() *State {
    s.count += 1
    return s
}

func main() {
    s := new(State)
    s = s.IncreaseCount()
}

Since s is a pointer, s.IncreaseCount() would be sufficient.
I find s = s.IncreaseCount() makes it more obvious that s has changed.
But is this a good practise? Or it just makes the code more complicated than it could be?
As a side note, removing the pointer would actually make IncreaseCount a pure function:
func (s State) IncreaseCount() State {
    s.count += 1
    return s
}

but imagine State is a big complicated struct and we cannot afford copying it.

A: A statement like
   s = s.IncreaseCount()

can have the opposite effect of what you are trying to accomplish: it can give the reader the impression IncreaseCount does not mutate s by itself and instead returns a new object exactly because of this. Hence the assignment looks like it would be required. This makes the next dev (or yourself in 6 months) think
  s2 = s.IncreaseCount()

leaves s unchanged.
Instead
  s.IncreaseCount()

is much clearer to me for two reasons:

*

*the name of the method is quite clear

*since there is no return value, the method must have some side effect, otherwise it would be superfluous
See also my former answer here to the question Is modifying an object passed by reference a bad practice?


Q: microcrontroller output to python cgi script I bought this temperature sensor logger kit: http://quozl.netrek.org/ts/. It works great with the supplied C code, I like to use python because of its simplicity, so I wrote a script in python that displays the output from the microcontroller. I only have one temperature sensor hooked up to the kit. I want the temperature to be displayed on a web page, but can't seem to figure it out, I'm pretty sure it has something to do with the output from the micro having a \r\n DOS EOL character and linux web servers do not interpret it properly. The book I have says "Depending on the web server you are using, you might need to make configuration changes to understand how to serve CGI files." I am using debian and apache2 and basic cgi scripts work fine.
Here is my code for just displaying the sensor to the console (this works fine):
import serial

ser = serial.Serial('/dev/ttyS0', 2400)

while 1:
   result = ser.readline()
   if result:
      print result

Here is my test.cgi script that works:
#!/usr/bin/python
print "Content-type: text/html\n"
print "<title>CGI Text</title>\n"
print "
cgi works!
"

Here is the cgi script I have started to display temp (doesn't work - 500 internal server error):
#!/usr/bin/python
import sys, serial

sys.stderr = sys.stdout

ser = serial.Serial('/dev/ttyS0', 2400)

print "Content-type: text/html\n"

print """
<title>Real Time Temperature</title>

Real Time Temperature:

"""

#result = ser.readline()
#if result:
print ser.readline()

If i run python rtt.cgi in the console it outputs the correct html and temperature, I know this will not be real time and that the page will have to be reloaded every time that the user wants to see the temperature, but that stuff is coming in the future.. From my apache2 error log it says:
malformed header from script. Bad header=  File "/usr/lib/cgi-bin/rtt.c: rtt.cgi

A: I'm guessing that the execution context under which your CGI is running is unable to complete the read() from the serial port.
Incidentally the Python standard libraries have MUCH better ways for writing CGI scripts than what you're doing here; and even the basic string handling offers a better way to interpolate your results (assuming you code has the necessary permissions to read() them) into the HTML.
At least I'd recommend something like:
#!/usr/bin/python
import sys, serial

sys.stderr = sys.stdout
ser = serial.Serial('/dev/ttyS0', 2400)

html = """Content-type: text/html

<title>Real Time Temperature</title>

Real Time Temperature:

%s

"""  % ser.readline()   # should be cgi.escape(ser.readline())!
ser.close()
sys.exit(0)

Notice we just interpolate the results of ser.readline() into our string using the
% string operator.  (Incidentally your HTML was missing , , , and
 (paragraph) tags).
There are still problems with this.  For example we really should at least import cgi wrap the foreign data in that to ensure that HTML entities are properly substituted for any reserved characters, etc).
I'd suggest further reading: [Python Docs]: http://docs.python.org/library/cgi.html

A: one more time:
# Added to allow cgi-bin to execute cgi, python and perl scripts
ScriptAlias /cgi-bin/ /var/www/cgi-bin/
AddHandler cgi-script .cgi .py .pl
<Directory /var/www>
Options +Execcgi
AddHandler cgi-script .cgi .py .pl
</Directory>

A: Michael,
It looks like the issue is definitely permissions, however, you shouldn't try to make your script have the permission of /dev/ttyS0. What you will probably need to do is spawn another process where the first thing you do is change your group to the group of the /dev/ttyS0 device. On my box that's 'dialout' you're may be different.
You'll need to import the os package, look in the docs for the Process Parameters, on that page you will find some functions that allow you to change your ownership. You will also need to use one of the functions in Process Management also in the os package, these functions spawn processes, but you will need to choose one that will return the data from the spawned process. The subprocess package may be better for this.
The reason you need to spawn another process is that the CGI script need to run under the Apache process and the spawn process needs to access the serial port.
If I get a chance in the next few days I'll try to put something together for you, but give it a try, don't wait for me.
Also one other thing all HTTP headers need to end in two CRLF sequences. So your header needs to be:
print "Content-type: text/html\r\n\r\n"
If you don't do this your browser may not know when the header ends and the entity data begins. Read RFC-2616
~Carl


Q: Select top N after aggregating by key and another field in pyspark RDD assuming a data set like this:
(teamId, player, minutesPlayed)
(1, 'A', 33)
(1, 'A', 12)
(1, 'B', 5)
(2, 'C', 22)
(2, 'C', 15)
(2, 'C', 33)
(2, 'D', 0)
......

So every tuple represents how many minutes player played in a game per team.
So I would like to aggregate data per player per team and select top 10 most playing players per team. Assuming a much larger data set of course.
So let's assume team 1 has 15 players, we want to get top 10 by minutesPlayed
Resulting data set would be:
(1, 'A', 350)
(1, 'B', 330)
#... rest 8 players of team 1
(2, 'C', 500)
(2, 'D', 330)
(2, 'E', 250)
#... rest 7 players of team 2
#.... rest of team with 10 players with most minutes

def map_players(data):
    teamId = data[0],
    player = data[1],
    minutesPlayed = data[2]

    return ((teamId, player), minutesPlayed) # returning the combination of team and player (assuming this is the way to do it)

def reduce_players(p1, p2):
    # really not sure what to do here
    # p1 and p2 are just then minutes played (int)

result:
player_data_set.map(map_players).reduceByKey(reduce_players).collect() # take(10)?

(1, 'A', 350)
(1, 'B', 330)
#... rest 8 players of team 1
(2, 'C', 500)
(2, 'D', 330)
(2, 'E', 250)
#... rest 7 players of team 2
#.... rest of team with 10 players with most minutes

I would like to do everything within reduceByKey reducer and use only .map method for mapping.

A: If you convert your data into a pyspark Dataframe you could do it like this:
from pyspark.sql import functions as F, Window
(
    df
    .groupBy('teamId', 'player')
    .agg(F.sum('minutesPlayed').alias('minutesPlayedTotal'))
    .withColumn('rank', F.row_number().over(Window.partitionBy('teamId').orderBy(F.desc('minutesPlayedTotal')))
    .where('rank <= 10')
    .show()
)

A: If you want to use RDD then you can do something like this:

*

*reduce using teamId + player as key to calculate the total minutes played by each player

*reduce using this time only teamId as key to get the list of players with their count of minutes played for each team

*flatmap values to sort the list of (player, count) on descending  order and take first 10 values

Example:
from operator import add

rdd = spark.sparkContext.parallelize([
    (1, 'A', 33), (1, 'A', 12), (1, 'B', 5), (2, 'C', 22),
    (2, 'C', 15), (2, 'C', 33), (2, 'D', 0)
])

rdd1 = rdd.map(lambda x: ((x[0], x[1]), x[2])) \
    .reduceByKey(add) \
    .map(lambda x: (x[0][0], [(x[0][1], x[1])])) \
    .reduceByKey(add)\
    .flatMapValues(lambda x: sorted(x, key=lambda a: a[1], reverse=True)[:10])

for p in rdd1.collect():
    print(p)
#(1, ('A', 45))
#(1, ('B', 5))
#(2, ('C', 70))
#(2, ('D', 0))


Q: Updating state in a class based component and re-rendering it first i am defining a state in class and rendering it using props, after that I am trying to update the state on clicking a button and on adding an event handler to the button  but
when I am trying to console log the updated state after the nameChangeHandler and I am not able to see the updated state but I can see the previous state though
this is my App.js file

import React, { Component } from 'react';
import Person from './Person/Person';

import './App.css';

class App extends Component {
  state = {
    persons: [
      { name: 'sagar', age: 22 },
      { name: 'nitin', age: 18 },
      { name: 'ankita', age: 21 },
    ],
    otherData: 'some other value',
  };
  changeNameHandler = () => {
    this.setState({
      persons: [
        { name: 'sagar', age: 22 },
        { name: 'nitin', age: 18 },
        { name: 'ankita-nanda', age: 91 },
      ],
    });
    console.log(this.state);
  };
  render() {
    return (

Hello world!!!!

        <Person
          name={this.state.persons[0].name}
          age={this.state.persons[0].age}
        />
        <Person
          name={this.state.persons[1].name}
          age={this.state.persons[1].age}
        >
          i'm going to college
        </Person>
        <Person
          name={this.state.persons[2].name}
          age={this.state.persons[2].age}
        />
        <button onClick={this.changeNameHandler}>Switch Names</button>

    );
    // return React.createElement(
    //   'div',
    //   { className: 'App' },
    //   React.createElement('h1', null, 'hope this works!!')
    // );
  }
}

export default App;

and this is my Person.js file

import React from 'react';

const person = (props) => {
  return (

        Hey, my name is {props.name} and I'm {props.age} yeras old!

        {props.children}--{props.name}

  );
};

export default person;

this is the screenshot of the image

A: setState is async so if you try to console log after your click event the same state will be there.
If you want to check the updated state you can try to console.log it above render.
render() {
console.log(this.state)
    return (

Hello world!!!!

        <Person
          name={this.state.persons[0].name}
          age={this.state.persons[0].age}
        />
        <Person
          name={this.state.persons[1].name}
          age={this.state.persons[1].age}
        >
          i'm going to college
        </Person>
        <Person
          name={this.state.persons[2].name}
          age={this.state.persons[2].age}
        />
        <button onClick={this.changeNameHandler}>Switch Names</button>

    );
    // return React.createElement(
    //   'div',
    //   { className: 'App' },
    //   React.createElement('h1', null, 'hope this works!!')
    // );
  }

A: try this:
changeNameHandler = () => {
  this.setState({
    persons: [
      { name: 'sagar', age: 22 },
      { name: 'nitin', age: 18 },
      { name: 'ankita-nanda', age: 91 }
    ]
  });
  setTimeout(() => {
   console.log(this.state);
  }, 0);
};

setState() is async function, so, it take some fraction of time to run and next line of code is executed.
As state is not updated yet, you will get the previous state.
setTimeOut() does the trick and runs after state updated.


Q: Send the active sheet as an email attachment from google sheets I have a google form that captures responses in a spreadsheet. It currently creates a new sheet everytime a new response is made.
I'm now trying to add a "mail the active sheet script" to the existing script that creates a new sheet.
However I get an error "Request failed for https://docs.google.com/spreadsheets/d/SS_ID/export?" around the following
var result = UrlFetchApp.fetch(url, {
      headers: {
        'Authorization': 'Bearer ' +  token
      }
    });

I have used this article as a guide for the send email part.
This is the entire script I am using.
    function onSubmit(e){
  Logger.log('submit ran');

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();

  //Get last row of data
  var lastRow = sheet.getLastRow();
  var colB_Data = sheet.getRange(lastRow, 2).getValue();

  //create sheet name with order no.
  ss.insertSheet(colB_Data);

  //order formula
  var sheets = ss.getSheets()[1];

  var cell = sheets.getRange("b2");
  cell.setFormula("=TRANSPOSE('Form Responses 1'!B1:AR1)");

  var cell = sheets.getRange("c2");
  cell.setFormula("=sheetName()");

  var cell = sheets.getRange("c3");
  cell.setFormula("=transpose(FILTER('Form Responses 1'!C:AR,'Form Responses 1'!B:B=C2))");

  var cell = sheets.getRange("d5:d44");
  cell.setFormula("=C5*vlookup(B5,'RG Cost'!B:E,4,0)");

  var cell = sheets.getRange("d5:d44");
  cell.setNumberFormat("[$₹][>9999999]##\,##\,##\,##0;[$₹][>99999]##\,##\,##0;[$₹]##,##0")

  var cell = sheets.getRange("c47");
  cell.setFormula("=sum(C5:C44)");

  var cell = sheets.getRange("d47");
  cell.setFormula("=sum(D5:D44)");

  var cell = sheets.getRange("b47");
  cell.setValue('TOTAL');

  //Send active sheet as email attachment

  var ssID = SpreadsheetApp.getActiveSpreadsheet();
  var email = Session.getUser().getEmail();
  var subject = "Order no.";
  var body = "Hello";

  var token = ScriptApp.getOAuthToken();

  var url = "https://docs.google.com/spreadsheets/d/SS_ID/export?" + "format=xlsx" +  "&gid=" + "&portrait=true" + "&exportFormat=xlsx";

  var result = UrlFetchApp.fetch(url, {
      headers: {
        'Authorization': 'Bearer ' +  token
      }
    });

  var contents = result.getContent();

  MailApp.sendEmail("xyz@xyz.com",subject ,body, {attachments:[{fileName:colB_Data+".pdf", content:contents, mimeType:"application//pdf"}]});

};

A: As mentioned by @cooper before, the ssID wasn't properly added to the URL, and also there's a few changes to be made the url and your fetchapp
  //Send active sheet as email attachment

  var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
  var sheetgId = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getSheetId();
  var email = Session.getUser().getEmail();
  var subject = "Order no.";
  var body = "Hello";

  var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?" + "format=xlsx" +  "&gid="+sheetgId+ "&portrait=true" + "&exportFormat=pdf";

  var result = UrlFetchApp.fetch(url)

  var contents = result.getContent();

  MailApp.sendEmail("abc@abc.abc",subject ,body, {attachments:[{fileName:colB_Data+".pdf", content:contents, mimeType:"application//pdf"}]});

You're sending an HTTP GET directly to your same drive, so the user, I assume, is logged to a google account and has access to the spreadsheet, therefore you don't really need a token again.
Second you forgot to add the variables to the parameters in the export mode URL and I changed the export format to pdf.

A: It didn't work without token so I used this:
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheetgId = ss.getActiveSheet().getSheetId();
var sheetName = ss.getName();

var token = ScriptApp.getOAuthToken();

var email = "name@domain.com";
var subject = "Important Info!";
var body = "PFA the report \n\nCheers,\n Roportobot";

var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?" + "format=xlsx" +  "&gid="+sheetgId+ "&portrait=true" + "&exportFormat=pdf";

var result = UrlFetchApp.fetch(url, {
headers: {
  'Authorization': 'Bearer ' +  token
}
});

var contents = result.getContent();

MailApp.sendEmail(email,subject ,body, {attachments:[{fileName:sheetName+".pdf", content:contents, mimeType:"application//pdf"}]});


Q: How can I store characters in flash memory STM32F4 HAL with C++? So I have a buffer:
uint32_t buff[2];
buff[0] = 12;
buff[1] = 13;
...

I can write this to the flash memory with the method:
HAL_FLASH_Program(TYPEPROGRAM_WORD, (uint32_t)(startAddress+(i*4)), *buff)

The definition of HAL_FLASH_Program is:
HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint64_t Data)

That works perfectly. Now is there a way I can store chars instead or ints?

A: You can use HAL_FLASH_Program with TYPEPROGRAM_BYTE to write a single 1-byte char.
If your data is a bit long (a struct, a string...), you can also write the bulk with TYPEPROGRAM_WORD, or even TYPEPROGRAM_DOUBLEWORD (8 bytes at a time), and then either complete with single bytes as needed or pad the excess with zeros. That would certainly be a bit faster, but maybe it's not significant for you.


Q: How to refactor to remove the control statements from @ngrx effects? I have a if control statement in an effect to return an action in the case of data has been retrieved from a service, if not return another action to get data from another Web API. It is a chained effects operation where there is another effect to handle the LOADFROMWEBAPI action.
Is there a better way and avoid the if control statement, and return one action like LoadFromWebAPI only? Where the action SearchCompleteAction can be returned is the question - in effect or reducer?
@Effect()
  search$: Observable<Action> = this.actions$
    .ofType(book.SEARCH)
    .debounceTime(300)
    .map(toPayload)
    .switchMap(query => {
      if (query === '') {
        return empty();
      }

      const nextSearch$ = this.actions$.ofType(book.SEARCH).skip(1);

      return this.googleBooks.searchBooks(query)
        .takeUntil(nextSearch$)
        .map(books => {
        if (data === undefined) {
            return new book.LoadFromWebAPI(query);
        } else {
            return new book.SearchCompleteAction(books);
        }
    })
        .catch(() => of(new book.SearchCompleteAction([])));
    });

A: @Effect()
search$: Observable<Action> = this.actions$
  .ofType(book.SEARCH)
  .debounceTime(300)
  .map(toPayload)
  .filter(query => query !== '')
  .switchMap(query => {
    const nextSearch$ = this.actions$.ofType(book.SEARCH).skip(1);
    return this.googleBooks.searchBooks(query)
      .takeUntil(nextSearch$)
      .map(books => data === undefined ? new book.LoadFromWebAPI(query) : new book.SearchCompleteAction(books))
      .catch(() => of(new book.SearchCompleteAction([])));
  });


Q: Clicking Google reCAPTCHA checkmark does nothing on IE9 Google reCAPTCHA is not working on IE9 (compatibility view is disabled). It loads correctly but the checkmark is not clickable. After some seconds, the checkmark disappears and it shows:

Please upgrade to a supported browser to get a reCAPTCHA challenge.
Alternatively if you think you are getting this page in error, please
  check your internet connection and reload.

It also throws the following error:
'MessageChannel' is undefined
It looks like Google reCAPTCHA is no longer supported on IE<10 since the Channel Messaging API is not supported.
Is there any way to make it work on IE9? Has anyone been able or at least tried to port the Channel Messaging API?
Thanks!

A: Did you installed any windows security updates?
Did you change any group policy like 'Turn off Data URI support'?
If yes, then try to enable this policy or for a testing purpose try to remove that security update may solve the issue.
Also try to make a test with other browsers and check whether you have same issue with those browsers or it works correctly.
It can help us to narrow down the issue.
You can let us know about your testing results. We will try to provide you further suggestions.
Regards
Deepak


Q: SQLAlchemy: @event.listens_for(Engine, 'handle_error') always re-raises the error I need to catch errors such as "database does not exist" or "table does not exist".
Here's what I'm trying to do:
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import event
from sqlalchemy.engine import Engine

class MultiTenantSQLAlchemy(SQLAlchemy):  # type: ignore
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        @event.listens_for(Engine, 'handle_error')
        def receive_handle_error(exception_context):
            print("listen for the 'handle_error' event")
            print(exception_context)

db = MultiTenantSQLAlchemy(flask_app)
db.session.execute('SELECT * FROM `table_that_does_not_exit`').fetchone()

Output:
listen for the 'handle_error' event
<sqlalchemy.engine.base.ExceptionContextImpl object at 0x1140c5710>

but I still get this exception:
ProgrammingError: (MySQLdb._exceptions.ProgrammingError) (1146, "Table 'somedb.some_fake_table' doesn't exist")

How can I suppress the exception?

A: you can use try except and catch the error
from sqlalchemy import exc
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import event
from sqlalchemy.engine import Engine

class MultiTenantSQLAlchemy(SQLAlchemy):  # type: ignore
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        @event.listens_for(Engine, 'handle_error')
        def receive_handle_error(exception_context):
            print("listen for the 'handle_error' event")
            print(exception_context)

db = MultiTenantSQLAlchemy(flask_app)

try:
  db.session.execute('SELECT * FROM `table_that_does_not_exit`').fetchone()
except exc.SQLAlchemyError:
  pass # do something intelligent here


Q: Peak at the sys.stdin before piping it to a subprocess (e.g. gzip) Data is coming in from the sys.stdin, but it could be either compressed (gzip) or uncompressed.
To solve this mystery, one could take a peek at the first 4 bytes of the stream. If they equal "\x1f\x8b\x08\x04" it's a gzip compressed file.
If the file is indeed compressed, one could decompress it with:
p = subprocess.Popen(['pigz','--stdout','--decompress' , sys.stdin], stdout=subprocess.PIPE)

However, if the first 4 bytes have already been consumed, pigz is going to reject this stream as not-a-gzip-compressed-file.
How can one read a few bytes from the sys.stdin without .read()'ing from it?
Alternatively, how can one send pigz the correct first 4 bytes and then the rest of the stream without getting into a deadlock?
EDIT2: I tried using the Peeker() class suggested in python 3: reading bytes from stdin pipe with readahead , however it results in the error:
  File "./subprocess.py", line 1155, in _get_handles
    p2cread = stdin.fileno()
AttributeError: 'Peeker' object has no attribute 'fileno'

Perhaps i need to create a named pipe, write my four bytes to it, then somehow redirect the sys.stdin to that named pipe. Note that there could be many gigabytes of compressed data coming in, so it would have to be somewhat automatic as Popen(stdin=file_obj) is.


Q: How to get ip address of forwarded domain using java Here i have problem in getting ip address of sub-domain so can any one help me to find ip. here is my code
import java.net.InetAddress;

public class NewTest {

  public static void main(String[] args) {
      String address = null;
    try {
            InetAddress giriAddress = java.net.InetAddress.getByName("x.x.x");//ex :: mail.vinoth.com
            address = giriAddress.getHostAddress();
        } catch (Exception e) {
    e.printStackTrace();
    }
 System.out.println("Ip Address :: "+address);
  }

}

A: Try this i think it will work for you.
                  public class AnsTest {

  public static void main(String[] args) {

try {

 String url = "http://mail.google.com";

   URL obj = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
    conn.setReadTimeout(5000);
     conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
    conn.addRequestProperty("User-Agent", "Mozilla");
     conn.addRequestProperty("Referer", "google.com");

      System.out.println("Request URL ... " + url);

      boolean redirect = false;

       // normally, 3xx is redirect
            int status = conn.getResponseCode();
       if (status != HttpURLConnection.HTTP_OK) {
     if (status == HttpURLConnection.HTTP_MOVED_TEMP
     || status == HttpURLConnection.HTTP_MOVED_PERM
      || status == HttpURLConnection.HTTP_SEE_OTHER)
     redirect = true;
 }

      System.out.println("Response Code ... " + status);

      if (redirect) {

       // get redirect url from "location" header field
         String newUrl = conn.getHeaderField("Location");

      // get the cookie if need, for login
      String cookies = conn.getHeaderField("Set-Cookie");

     // open the new connnection again
        conn = (HttpURLConnection) new URL(newUrl).openConnection();
     conn.setRequestProperty("Cookie", cookies);
      conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
     conn.addRequestProperty("User-Agent", "Mozilla");
     conn.addRequestProperty("Referer", "google.com");

    System.out.println("Redirect to URL : " + newUrl);

      }
System.out.println("Done");

    } catch (Exception e) {
    e.printStackTrace();
      }

       }

    }


Q: Find the volume of the region bounded by a sphere and a paraboloid using cylindrical and spherical coordinates. The sphere is $x^2 + y^2 + z^2 = 4$ and the paraboloid is $x^2 + y^2 = 3z$
I've already done for the cylindrical coordinates and got:
$$\int^{2\pi}_0\int_0^1\int_{\frac{r^2}{3}}^\sqrt{4-r^2}rdzdrd\theta = \frac{\pi(31-12\sqrt{3})}{6}$$
But I'm having troubles when building the integral for spherical coordinates. So far I've found the bounds of integration for $d\rho$ and $d\theta$.
$$\int^{2\pi}_0\int\int_0^2\rho ^2\sin\phi \,\,\,d\rho d\phi d\theta$$
What about the bounds for $d\phi$? Done a small search and had to solve $3\rho\cos\phi = \rho^2\sin^2\theta$, but this is the point where I'm stuck. Is this right? If yes, how to solve this?

A: In cylindrical coordinates, the volume is
$$\int^{2\pi}_0 \int_0^{\sqrt3} \int^{-\frac{r^2}{3}}_{-\sqrt{4-r^2}} r\>dr d\theta
= \frac{19\pi}6$$
and, in spherical coordinates
$$\int^{2\pi}_0 \int_{\pi/2}^{2\pi/3} \int_0^{-\frac{3\cos\phi}{\sin^2\phi}}
\rho ^2\sin\phi \,d\rho d\phi d\theta
+\int^{2\pi}_0 \int^{\pi}_{2\pi/3} \int_0^{2}
\rho ^2\sin\phi \,d\rho d\phi d\theta = \frac{19\pi}6$$

A: At the intersection of paraboloid and sphere,
$x^2 + y^2 + z^2 = 4, x^2+y^2 = 3z \implies z^2 + 3z - 4 = 0$.
i.e, $z = 1, x^2+y^2 = 3$.
So in cylindrical coordinates, $0 \leq r \leq \sqrt3$.
Now in spherical coordinates,
$x = \rho \cos\theta \sin\phi,y = \rho \sin\theta \sin\phi, z = \rho \cos\phi$
At the intersection of paraboloid and sphere,
$\rho = 2, z = \rho \cos\phi = 1,  \implies \cos\phi = \frac{1}{2}$
So for $0 \leq \phi \leq \frac{\pi}{3}$, the region is bound by the sphere and for $\frac{\pi}{3} \leq \phi \leq \frac{\pi}{2}$, the region is bound by the paraboloid.
$3z = x^2 + y^2 \implies 3 \rho \cos\phi = \rho^2 \sin^2\phi$
$\rho = 3 \cos\phi \csc^2\phi$
So bounds for the second integral are,
$\frac{\pi}{3} \leq \phi \leq \frac{\pi}{2}, 0 \leq \rho \leq 3 \cos\phi \csc^2\phi $


Q: Load data from NSUserDefaults in ViewDidLoad In the start screen of my app you are able to choose language between English and Swedish by clicking on either the flag of UK or Sweden.
The problem is that the ViewDidLoad does not recognize changes in the NSUserDefaults when you click a button. But when you restart the app, the language is the latest flag you clicked! So it saves the NSUserDefault but it only loads it the first time in ViewDidLoad..
When you click the English flag, sprakval sets to 0, and if you click the swedish flag, sprakval sets to 1. When you click a flag, it changes to a image with a tick icon in front of the flag.
Code:
-(IBAction) sprakEN
 {
    sprakval=0;
    NSUserDefaults *sprakvalet = [NSUserDefaults standardUserDefaults];
    [sprakvalet setInteger:sprakval  forKey:@"Sprak "];
    [sprakvalet synchronize];

    [super viewDidLoad];
}

-(IBAction) sprakSE
 {
     sprakval=1;
     NSUserDefaults *sprakvalet = [NSUserDefaults standardUserDefaults];
     [sprakvalet setInteger:sprakval  forKey:@"Sprak "];
     [sprakvalet synchronize];

      [super viewDidLoad];
 }

  - (void)viewDidLoad
    {
        [super viewDidLoad];

        NSUserDefaults *sprakvalet = [NSUserDefaults standardUserDefaults];
        sprakval2  = [sprakvalet integerForKey:@"Sprak "];

        if (sprakval2==0)
        {
            spraklabel.text = [NSString stringWithFormat:@"Language:"];

            [lhb setTitle:@"english" forState:UIControlStateNormal];
            [hlb setTitle:@"english" forState:UIControlStateNormal];
            [fhb setTitle:@"english." forState:UIControlStateNormal];
            [blandatb setTitle:@"english.." forState:UIControlStateNormal];

            UIImage *encheck = [UIImage imageNamed:@"United_Kingdomchecked.png"];
            [enbutton setImage:encheck forState:UIControlStateNormal];

            UIImage *seuncheck = [UIImage imageNamed:@"Sweden.png"];
            [sebutton setImage:seuncheck forState:UIControlStateNormal];

            self.title = @"Game";
        }
        else if(sprakval2==1)
        {
            spraklabel.text = [NSString stringWithFormat:@"Språk:"];

            [lhb setTitle:@"swedish" forState:UIControlStateNormal];
            [hlb setTitle:@"swedish" forState:UIControlStateNormal];
            [flb setTitle:@"swedish" forState:UIControlStateNormal];
            [fhb setTitle:@"swedish" forState:UIControlStateNormal];
            [blandatb setTitle:@"swedish" forState:UIControlStateNormal];

            self.title = @"Spel";
            UIImage *secheck = [UIImage imageNamed:@"Swedenchecked.png"];
            [sebutton setImage:secheck forState:UIControlStateNormal];

            UIImage *enuncheck = [UIImage imageNamed:@"United_Kingdom.png"];
            [enbutton setImage:enuncheck forState:UIControlStateNormal];
        }

    // Do any additional setup after loading the view, typically from a nib.
     }

A: viewDidLoad is a method invoked after view has been loaded from nib file. You are not supposed to call it manually.
If you have written the code to refresh the controls in viewDidLoad move that into a different method and invoke that method from your button event handler.
- (void)adjustControlsForLanguage
{
    NSUserDefaults *sprakvalet = [NSUserDefaults standardUserDefaults];
    sprakval2  = [sprakvalet integerForKey:@"Sprak "];

    if (sprakval2==0)
    {
        spraklabel.text = [NSString stringWithFormat:@"Language:"];

        [lhb setTitle:@"english" forState:UIControlStateNormal];
        [hlb setTitle:@"english" forState:UIControlStateNormal];
        [fhb setTitle:@"english." forState:UIControlStateNormal];
        [blandatb setTitle:@"english.." forState:UIControlStateNormal];

        UIImage *encheck = [UIImage imageNamed:@"United_Kingdomchecked.png"];
        [enbutton setImage:encheck forState:UIControlStateNormal];

        UIImage *seuncheck = [UIImage imageNamed:@"Sweden.png"];
        [sebutton setImage:seuncheck forState:UIControlStateNormal];

        self.title = @"Game";
    }
    else if(sprakval2==1)
    {
        spraklabel.text = [NSString stringWithFormat:@"Språk:"];

        [lhb setTitle:@"swedish" forState:UIControlStateNormal];
        [hlb setTitle:@"swedish" forState:UIControlStateNormal];
        [flb setTitle:@"swedish" forState:UIControlStateNormal];
        [fhb setTitle:@"swedish" forState:UIControlStateNormal];
        [blandatb setTitle:@"swedish" forState:UIControlStateNormal];

        self.title = @"Spel";
        UIImage *secheck = [UIImage imageNamed:@"Swedenchecked.png"];
        [sebutton setImage:secheck forState:UIControlStateNormal];

        UIImage *enuncheck = [UIImage imageNamed:@"United_Kingdom.png"];
        [enbutton setImage:enuncheck forState:UIControlStateNormal];
    }

}

viewDidLoad
- (void)viewDidLoad{
    [super viewDidLoad];
    [self adjustControlsForLanguage];
}

Button Event Handlers
-(IBAction) sprakEN {
    sprakval=0;
    NSUserDefaults *sprakvalet = [NSUserDefaults standardUserDefaults];
    [sprakvalet setInteger:sprakval  forKey:@"Sprak "];
    [sprakvalet synchronize];

    [self adjustControlsForLanguage];
}

-(IBAction) sprakSE {
     sprakval=1;
     NSUserDefaults *sprakvalet = [NSUserDefaults standardUserDefaults];
     [sprakvalet setInteger:sprakval  forKey:@"Sprak "];
     [sprakvalet synchronize];

      [self adjustControlsForLanguage];
 }

EDIT : Since you are using tabBar based app, it's better to use the viewWillAppear to reload the language specific controls
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self adjustControlsForLanguage];
}

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

A: This is because you are calling ViewDidload method through its super class in -(IBAction) sprakSE
 and -(IBAction) sprakEN
 methods. So replace
      [super viewDidLoad]; with
      [self viewDidLoad]; in both methods. It will work properly.
Hope it helps you.


Q: 'SELECT IN' with item list containing duplicates I'm doing
SELECT Name WHERE Id IN (3,4,5,3,7,8,9)

where in this case the '3' Id is duplicated.
The query automatically excludes the duplicated items while for me would be important to get them all.
Is there a way to do that directly in SQL?

A: The query doesn't exclude duplicates, there just isn't any duplicates to exclude. There is only one record with id 3 in the table, and that is included because there is a 3 in the in () set, but it's not included twice because the 3 exists twice in the set.
To get duplicates you would have to create a table result that has duplicates, and join the table against that. For example:
select t.Name
from someTable t
inner join (
  select id = 3 union all
  select 4 union all
  select 5 union all
  select 3 union all
  select 7 union all
  select 8 union all
  select 9
) x on x.id = t.id

A: Try this:
SELECT Name FROM Tbl
    JOIN
     (
       SELECT 3 Id UNION ALL
       SELECT 4 Id UNION ALL
       SELECT 5 Id UNION ALL
       SELECT 3 Id UNION ALL
       SELECT 7 Id UNION ALL
       SELECT 8 Id UNION ALL
       SELECT 9 Id
     ) Tmp
     ON tbl.Id = Tmp.Id


Q: Populate a DataGridView correctly I'm writing a winforms application, with a datagrid, using some search field to filter the content of the dataGrid.
To fill my dataGrid, I load data using a query.
The result of the query is either a DataTable, or a List<Object> created with the dataTable.
I read that to use search field, I had to populate my dataGrid like this :
    liste = Echange.GetListEchange(contextExecution.ChaineConnexion, criteres);
    dataGridView1.DataSource = liste;

And building the query like this :
" AND UPPER(titre) like '%" + tbSearchTitre.Text.ToUpper() + "%' AND ";

Then adding as parameter in GetListEchange.
This works.
I got columns, binding of properties on the liste .
But the thing is, I got aside, a Select column (CheckBoxColumn) binding on a property.
And when I set the property to true, then, the checkBox should check, but nothing happened.
    foreach (Echange itm in liste)
    {
        itm.IsSelect = false;
    }

It seems the dataGrid don't update.
But when I go through all the Echange in the liste, and I checked 'graphically' the checkbox, then, IsSelect is true.
So why, when I set IsSelect to true, the checkBox is not checked?
Is there a better way to fill my dataGrid, using search fields, and that update the display of the dataGrid?


Q: MYSQL Query matching column names to rows in another table I have two tables in MYSQL, one contain a list of options a customer can pick from and the other has the cost of the options. I would like a view that returns the cost of each customers option set. For my example I'll use the analogy of buying a new car.
Customers table
customer - sunroof - mag_wheels - spoiler
--------------------------------------------------
John     - true    - true       - false
Steve    - false   - true       - false
Lucy     - false   - false      - false

Options table
option      - price
-----------------
sunroof     - 100
mag_wheels  - 150
spoiler     -  75

Desired results
customer   - cost
-----------------
John       - 250
Steve      - 150
Lucy       - 0

or this would do, as I good easily multiply selected by price and then group by customer
customer   - option     - selected - price
------------------------------------------
John       - sunroof    - true     - 100
John       - mag_wheels - true     - 150
John       - spoiler    - false    -  75
Steve      - sunroof    - false    - 100
Steve      - mag_wheels - true     - 150
Steve      - spoiler    - false    -  75
Lucy       - sunroof    - false    - 100
Lucy       - mag_wheels - false    - 150
Lucy       - spoiler    - false    -  75

I've been puzzling over this for hours now and I can't even figure out where to start, a join seems out of the question as there are no common elements to match. I wonder if using UNION is the answer but I can't figure out how to combine row values with column headings.
If anyone could point me in the right direction I'd be ever so grateful, double points if you come up with a solution that dynamically picks up the different options so I could add more in the future without rewriting the query.
Many thanks in advance.
The reason I wanted to have all the options as a single row is I was hoping to use Access to make a form for picking the options and I couldn't figure out how a single form could create multiple rows.

A: This is a horrible data layout.  You should have an association table, with one row per customer and option.
But, you can do it:
select c.customer, sum(o.cost) as cost
from customers c left outer join
     options o
     on (c.sunroof = true and o.option = 'sunroof' or
         c.mag_wheels = true and o.option = 'mag_wheels' or
         c.spoiler = true and o.option = 'spoiler'
        )
group by c.customer;

EDIT:
You do not want all options in a single record.  Instead, you need an association table:
create table customer_options (
    customer_optionid unsigned auto_increment,
    customer varchar(255) references customer(name),
    option varchar(255) references option(option)
);

Actually you should really have integer primary keys for all the tables, and use them for the foreign key references.  If you need data in the output in the question, then just write a query to return it in that format.

A: Looking at the table structure, even I think it will not be possible to write joins because as you mentioned, the table structure doesn't have a relation between them.
I am assume you have just started the project, so it's time you first re-visit your DB structure and correct it.
Ideally, you should have a customer table with a customer id.
Then you should have products table with product id.
One table which will have data on what products customers have purchased - something like customer_products. This will be a one to many relation. So customer 1 can have product 1,3 and 5. Which would means in customer_product there will be three entries.
And then when you want to do a sum total, you can first join the table customer, product based on customer_product and then do a sum of the price also to get the total amount for individual customer.

A: Bad design.  You must a have a customers table like this:
custumer_id
customer_name
other fileds...

On the other hand you should have an accesories table,  where you usually describe each item-
accesory_id
accesory_name
supplier_id
country_of_origin
other stuff

Also an accesory_price table,  where prices are added due the fact that prices change.
accesory_id
price
active_price
date_price_added

An finally you should relate all in a customer_accesory table:
customer_id
accesory_id

By having this,  you can join tables and select both customer basket size and customer preferences of accesories.  Basket size,  or the amount purchased by each customer can be summarized  SUM,  AVG,  COUNT or you can pivot data using GROUP_CONCAT in order to generate high quality reports.


Q: Cakephp MYSQL query: SELECT where date is greater than I have to run a MYSQL select query where the query returns all values that have the beginning date 10 days after today. I have tried these two methods none of which seem to work, where do I need to make a change?
$fix_d_table = TableRegistry::get('fixed_departures');
$f_dates_march = $fix_d_table   ->find("all")
    ->where(['trek_id' => 3])
    ->andWhere(['month(date_from)' => 03])
    ->andWhere(['date_from' >= date("Y-m-d",strtotime("+10 days"))])
    ->order(['date_from'=>'asc'])
    ->select(['date_from', 'date_to', 'seats_available','id'])
    ->toArray();

$fix_d_table = TableRegistry::get('fixed_departures');
$f_dates_march = $fix_d_table   ->find("all")
    ->where(['trek_id' => 3])
    ->andWhere(['month(date_from)' => 03])
    ->andWhere(['date(date_from)' >= date("Y-m-d",strtotime("+10 days"))])
    ->order(['date_from'=>'asc'])
    ->select(['date_from', 'date_to', 'seats_available','id'])
    ->toArray();

A: Try below one
$fix_d_table = TableRegistry::get('fixed_departures'); $f_dates_march
= $fix_d_table   ->find("all")
    ->where(['trek_id' => 3])
    ->andWhere(
        function ($exp) {
            return $exp->or_([
                'date_from <=' => date('Y-m-d', strtotime("+10 days")),
                'date_from >=' => date('Y-m-d')
            ]);
    })
    ->order(['date_from'=>'asc'])
    ->select(['date_from', 'date_to', 'seats_available','id'])
    ->toArray();

A: should be
'date_from >=' => date("Y-m-d",strtotime("+10 days"))

if you can rely on mysql server date you can use NOW() inside your query
 ->where(function($exp, $q) {
        return $exp->gte($q->func()->dateDiff([
            'date_from ' => 'identifier',
            $q->func()->now() ]),  10);
    });

this will give you the following SQL condition
WHERE
(
  DATEDIFF(date_from , NOW())
)  >= 10


Q: How to use subqueries in MySQL I have two tables.
Table user:
CREATE TABLE IF NOT EXISTS `user` (
  `user_id` int(20) NOT NULL AUTO_INCREMENT,
  `ud_id` varchar(50) NOT NULL,
  `name` text NOT NULL,
  `password` text NOT NULL,
  `email` varchar(200) NOT NULL,
  `image` varchar(150) NOT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB

and mycatch:
CREATE TABLE IF NOT EXISTS `mycatch` (
  `catch_id` int(11) NOT NULL AUTO_INCREMENT,
  `catch_name` text NOT NULL,
  `catch_details` text NOT NULL,
  `longitude` float(10,6) NOT NULL,
  `latitude` float(10,6) NOT NULL,
  `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `image` varchar(150) NOT NULL,
  `user_id` int(20) NOT NULL,
  PRIMARY KEY (`catch_id`),
  KEY `user_id` (`user_id`)
) ENGINE=InnoDB;
ALTER TABLE `mycatch`
  ADD CONSTRAINT `mycatch_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE;

My goal is: I want to retrieve longitude and latitude from mycatch against given ud_id (from user) and catch_id (from mycatch) where ud_id = given ud_id and catch_id > given catch_id.
I used the query but fail to retrieve
SELECT ud_id=$ud_id FROM user
WHERE user_id =
(
SELECT user_id,longitude,latitude from mycatch
WHERE catch_id>'$catch_id'
)

The error is:

#1241 - Operand should contain 1 column(s)

A: First, try not to use subqueries at all, they're very slow in MySQL.
Second, a subquery wouldn't even help here.  This is a regular join (no, Mr Singh, not an inner join):
SELECT ud_id FROM user, mycatch
WHERE catch_id>'$catch_id'
AND user.user_id = mycatch.user_id

A:  Select m.longitude,m.latitude from user u left join mycatch m
on u.user_id =m.user_id
where u.ud_id=$ud_id and
m.catch_id >$catch_id


Q: I don't know what to do because an error occurs --> Uncaught TypeError: Cannot read property 'getContext' of null window.onload=function() {
    c=document.getElementById('gc');
    cc=c.getContext('2d')
    setInterval(update,1000/30);
    c.addEventListener('mousemove',function(e) {
        p1y=e.clientY-ph/2;
    });
}

I am creating a pingpong game but as am fixing it an error occurs and I can't solve it. I have an onload but it doesn't work..

A: HTML
Add below code in HTML body
 <body>
        <canvas id="gc"></canvas>
</body>

JS
 <script>
    window.onload=function() {
    c=document.getElementById('gc');
    cc=c.getContext('2d')
    setInterval(update,1000/30);
    c.addEventListener('mousemove',function(e) {
        p1y=e.clientY-ph/2;
    });
   }
</script>


Q: Update grouped records with sequence in sql I have following structure of data in sql table
COL1    COL2    COL2   GRP_ID
A       A       B      100
A       A       B      100
A       A       C      101
A       A       B      100
A       D       E      102
A       D       E      102
F       G       H      103
F       G       H      103

i have the code same this one but it is for oracle,  in sql it is not possible to define a function for next value for. How to change this code for sql?
CREATE FUNCTION NEXT
      RETURN NUMBER IS
      v_nextval NUMBER;
    BEGIN
      v_nextval := NEW_SEQUENCE.nextval;

      RETURN(v_nextval);
   END;
/

UPDATE EXAMPLE
SET EXAMPLE.GroupID =
  (
   SELECT G.GroupID FROM
   (
     SELECT B.Column1, B.Column2, B.Column3, MY_SCHEMA.NEXT() AS GroupID
     FROM EXAMPLE B
     GROUP BY B.Column1, B.Column2, B.Column3
   ) G
   Where G.Column1 = EXAMPLE.Column1 AND G.Column2 = EXAMPLE.Column2
   AND G.Column3 = EXAMPLE.Column3);

SELECT *
FROM EXAMPLE

A: The GRP_ID can be calculated using DENSE_RANK():
select col1, col2, col3,
       dense_rank() over (order by col1, col2, col3) as grp_id
from t;

If you want to update the value, one method is:
update t
    set grp_id = (select count(distinct col1, col2, col3) + 1
                  from t t2
                  where t2.col1 < t.col1 or
                        (t2.col1 = t.col1 and t2.col2 < t.col2) or
                        (t2.col1 = t.col1 and t2.col2 = t.col2 and t2.col3 <= t.col3)
                 );

Note that not all database support count(distinct) on multiple columns.  In those databases, you can concatenate the values together.


Q: Cannot change to front copper layer in KiCAD I am learning to design PCB using KiCAD. I followed a tutorial on youtube.  I got stuck at changing the layer of the PCB. From the video, the layers can be interchange by pressing page up (front copper) or page down (back copper). My filled zone layer is b.cu and net is GND. The B.Cu layer is just fine but when i change to F.Cu layer, it is still the same as before.
I have inserted a picture showing my issue. As you can see the selected layer is F.Cu but it is showing the back side. What have I done wrong and how can I change to front layer?

A: Turn off the preview for things that you don't want to see from the backside.
It basically shows you front and back part of PCB in same screen. You need to chose what you want to see.

A: Personally, I do the copper pour after routing is done. But any way, you can untick B.Cu layer to hide the bottom layer. Also you can click on "Do not show filled areas in zone" on the left side toolbar(11th button from top), to hide the copper pour. Doing this is a must when routing on bottom layer, as you will not be able to see the tracks as lay them down and you will need to rebuild the copper pour every time after the wire is connected by pressing 'b'.
Another thing, in the tutorial, he is using openGL mode while routing, and from the screenshot its seems you are in default mode. To switch to openGL mode go to View>Switch to OpenGL or press 'F11' key.

A: There is a bug in a few nightly builds that makes copper rendering opaque, and then saves that as new default.
You can correct that by double-clicking the color swatch next to the layer name and reducing opacity to a sensible value. We use 60% by default.


Q: flash video smoothing I have a short flv I want to play on my website. I use the below actionscript 2 code to play the video, but the anti-aliasing of text is really poor quality. I added a line to introduce "smoothing" to the video, but it appears to have no visible effect.
var my_video:Video;
var my_nc:NetConnection = new NetConnection();
my_nc.connect(null);
var my_ns:NetStream = new NetStream(my_nc);
my_video.attachVideo(my_ns);
my_ns.setBufferTime(2);
my_ns.play("thevideo.flv");
my_video.smoothing = true; //does nothing

Incidentally, I am exporting the flv video from aftereffects, and when I export the movie as a (larger) "lossless" quicktime movie, the movie looks perfect when played in quicktime, but has the same poor anti-aliasing when viewed in adobe media player, VLC, or mplayer.
Any clue on what the problem is, or if there's a better way for me to go about doing this?

A: The smoothing attribute only affects how the video is scaled - that is, whether or not the video is smoothed if you play it at double size or the like. If your Video component is scaled the same size as the source video, this attribute won't do anything.
With that said, please understand that there's no such thing as anti-aliasing going on at the player end of things. Assuming that everything is the right size (so your video isn't being scaled up to 103% or anything), what you see in the Flash player is exactly the data in the source FLV. So any aliasing you see happened when the video was encoded, not at runtime.
So assuming your sizes are right, my guess would be that you should look at the encoding end of things to solve the problem. Is your FLV of a comparable size as the lossless quicktime? If it's a lot smaller, then you're probably compressing it a lot, and increasing the quality settings might help. Likewise, what codec did you use? If you're using the newest codec (H264), the quality ought to be very similar to a quicktime movie of similar size. But the older codecs can have significantly less quality. Especially the old Sorenson Sparc codecs (the ones that require player 6/7 or better to view) are pretty sad by today's standards. And especially the Sorenson codec was heavily customized for low-bandwidths, so even if you encode with very high quality settings you tend to get big increases in file size but very little increase in quality. For these reasons it's highly recommended to make sure you're using the newest codec available for the player version you're targeting.
If none of that helps, please update with some details about what codecs and encode settings you're using.


Q: Retain colour but change transparency in photoshop How can I retain a specific colour of an object (or layer) but change the transparency?
I have 2 objects which I want to have a specific colour but currently the opacity is 100%. I need to maintain the current colours but with a opacity of 50%.
Obviously if I change the opacity the colours change (dependent on the background). I need to know how to get an original colour at 100% opacity to make my desired colour at 50% opacity.

A: Okay so couldn't find a specific way to do it with photoshop so I worked out the math based off the RGB values and came up with a formula to do the job.
For each colour channel I used this formula:
Colour value = Desired Colour + (Background Colour - Desired Colour)*(1-1/Desired Opacity)
eg. 30 = 120 + (255-120)*(1-1/0.6)
Obvious only values between 0-255 are applicable and you may need to round values. This also needs to be done 3 times for red, green and blue.


Q: Rearranging a set with limitations on how far each element can move Suppose we have a set of elements, which we want to rearrange. However, no elements can be moved more than 1 slot away from its original position (items can also be kept in the same position).
For instance, with a 3-element set, $ABC$, there are 3 such arrangements: $ABC$, $BAC$, $ACB$.
With a 4 element set, $ABCD$, there are 5 arrangements: $ABCD$, $ABDC$, $ACBD$, $BACD$, $BADC$.
Let $M(n,1)$ be the number of ways to rearrange a set with $n$ elements such that each element can only be moved 1 slot.
Each reordering can either start with $A$... (remaining n-1 elements) or $BA$... (remaining n-2 elements). Hence:
$M(n,1)$ = $M(n-1,1)$ + $M(n-2,1)$
That is, the Fibonacci sequence.
The situation becomes much more complex when we consider $M(n,2)$; that is, each element can be moved up to 2 slots. We can easily calculate the first few terms:
$M(2,2)$ = 2
$M(3,2)$ = 6
$M(4,2)$ = 14
$M(5,2)$ is harder to calculate, but I think it is 32. It is hard to count the number of ways systematically, though. Any ideas of how to go about the problem? Is there any way to find a general formula for $M(n,x)$?

A: I think I've managed to crack the case for $M(n,2)$.
For notational simplicity, let $M(n,2)$ = $F(n)$. We now need to introduce a new function, $G(n)$, defined as the same as $F(n)$ except that, while all other elements of the set may move up to 2 slots either direction, the first element may only move one slot.
Again, we go for a recursive approach. The first element of the sequence can be either $A, B$  or $C$.

*

*If it starts with $A$, there are $F(n-1)$ ways to rearrange the
remaining elements.

*If it starts with $B$, there are $G(n-1)$ ways,
as all other elements face the same constraints, but now the $A$ has
only 2 positions it can go in.

*If the sequence starts with $C$, we must further consider three cases: it can start either $CA$, $CB$ or $CD$. Starting $CA$ is analogous to $G(n-2)$, as all remaining elements face the same constraints except the $B$ has only 2 positions it can go in. Starting $CB$ forces the $A$ to go next, leaving $F(n-3)$ ways to rearrange the remaining elements, while similarly starting $CD$ forces the next terms of the sequence to be $AB$, leaving $F(n-4)$ ways.

This reasoning is represented in the tree diagram below. All said and done, we find that:
$F(n) = F(n-1) + F(n-3) + F(n-4) + G(n-1) + G(n-2)$

Now we must unpack $G(n)$. Using a similar process, we observe that the set can start in one of three ways: $A, BA$ or $CA$. This corresponds to the equation:
$G(n) = F(n-1)+F(n-2)+G(n-2)$
Since $G(n-2) = F(n-3) + F(n-4) + G(n-4)$, we can expand the equation to yield:
$G(n) = F(n-1)+F(n-2)+F(n-3)+F(n-4)+...$
Now we can use this equation to expand the earlier equation for $F(n)$.
$F(n) = F(n-1)+F(n-2)+3F(n-3)+3F(n-4)+2F(n-5)+2F(n-6)+2F(n-7)...$
That is, the coefficients of this unending equation go 1,1,3,3,2,2,2,2.... Thankfully, this can be simplified with a nifty trick: simply add $F(n-1)$ to the right hand side while subtracting its expansion. This leaves us with:
$F(n)=2F(n-1)+2F(n-3)-F(n-5)$
This allows us to easily compute the series $M(n,2)$: 1,2,6,14,31,73,172...


Q: Euler characteristic - reference question Let $X$ be an algebraic variety over $\mathbb C$ and let $\mathcal F$ be a constructible sheaf on $X$. It is well-known that the Euler characteristic of the cohomology of $\mathcal F$ is equal to the Euler characteristic of cohomology with compact support. What is the right reference for this result?
In $l$-adic cohomology this was proved first by Laumon (I think) but over $\mathbb C$ this should have been known before.

A: The paper you refer to by Gérard Laumon appears to be:
Comparaison de caractéristiques d'Euler-Poincaré en cohomologie l-adique,
C. R. Acad. Sci. Paris Sér. I Math. 292 (1981), no. 3, 209–212.
According to the MathSciNet Review of this paper (reference MR0610321) by William E. Lang:

"As a corollary, the author deduces that if $k$ is algebraically closed, and if $X$ is a separated scheme of finite type over $k$, then for all $E_\lambda$-sheaves $\mathcal{F}$ on $X$, $\chi(X,\mathcal{F})=\chi_c(X,\mathcal{F})$. This corollary had been previously proved by A. Grothendieck for curves in all characteristics [ibid., (SGA 5 X), pp. 372–406], and in all dimensions when the characteristic of $k$ is zero."

According to the reference, that was in 1965–1966.


Q: Multiple iterations of vector with structs "cannot move out of borrowed content" I need to iterate a vector with structs in each iteration in a loop. It works fine as long as the vector doesn't contain structs. I have tried many different solutions but always get some kind of ownership problem.
What am I doing wrong?
struct Element {
    title: String,
}

impl Element {
    pub fn get_title(self) -> String {
        self.title
    }
}

fn main() {
    let mut items: Vec<Element> = Vec::new();
    items.push(Element {
        title: "Random".to_string(),
    });
    items.push(Element {
        title: "Gregor".to_string(),
    });

    let mut i = 0;
    while i < 10 {
        for item in &items {
            println!("Loop {} item {}", i, item.get_title());
        }
        i = i + 1;
    }
}

playground
error[E0507]: cannot move out of borrowed content
  --> src/main.rs:23:44
   |
23 |             println!("Loop {} item {}", i, item.get_title());
   |                                            ^^^^ cannot move out of borrowed content

A: The problem is, that your get_title method consumes the Element and therefore can only be called once.
You have to accept &self as parameter instead and can do the following:
Either return a &str instead of String:
pub fn get_title(&self) -> &str {
    &self.title
}

or clone the String if you really want to return a String struct.
pub fn get_title(&self) -> String {
    self.title.clone()
}

Also have a look at these questions for further clarification:

*

*What are the differences between Rust's `String` and `str`?

*What types are valid for the `self` parameter of a method?

A: Here is a solution to the problem, it required borrowing self object and lifetime specifications.
Moving from &String to &str is only for following better practices, thanks @hellow Playground 2
struct Element<'a> {
    title: &'a str
}

impl <'a>Element<'a> {
    pub fn get_title(&self) -> &'a str {
        &self.title
    }
}

fn main() {
    let mut items: Vec<Element> = Vec::new();
    items.push(Element { title: "Random" });
    items.push(Element { title: "Gregor" });

    let mut i = 0;
    while i < 10 {
        for item in &items {
            println!("Loop {} item {}", i, item.get_title());
        }
        i = i + 1;
    }
}


Q: Ant  and  sqlcmd - Different Outputs I have one .sql file that is execute using ant, when I execute it with the  tag I recived a different output as when i used  calling "sqlcmd".
sql tag output:
  [sql] Executing resource: C:\SqlTesting\TestScriptDependencies\Executor.sql
  [sql] Failed to execute:  Use Library Exec CallSelectSP
  [sql] com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name'Libraty.dbo.libraryDocumentType'.
  [sql] 0 of 1 SQL statements executed successfully

exec tag output:
 [exec] First SP
 [exec] Msg 208, Level 16, State 1, Server MyPC-PC, Procedure getFirstDocumentType, Line 3
 [exec] Invalid object name 'Libraty.dbo.libraryDocumentType'.
 [exec] Second SP
 [exec] Msg 208, Level 16, State 1, Server MyPC-PC, Procedure badSP, Line 3
 [exec] Invalid object name 'Libraty.dbo.libraryDocumentType'.

And this is the .sql file.
Print 'First SP'
Exec getFirstDocumentType
Print 'Second SP'
Exec badSP
Go

I wonder if it is a way of the SQL tag reproduce the same output as the EXEC tag.
Thanks.

A: Looks like the first one is submitting the whole script as a single batch via jdbc. Whereas the second appears to be sending each sql statement via sqlcmd - hence the print statements succeed (and result in synchronized output - which is not always guaranteed with print - raiserror(str, 10, 1) with nowait; is the only guarantee of timely messaging) and both sp calls are attempted, each producing their own (sql) error.


Q: How to create an multipurpose event receiver I want to create an event receiver that I'll attach it to content types across 4 site collections. The content type is being made programmatically, so no XML definition.
Also, I want to create an event receiver that I'll attach it to multiple lists across 4 site collections.
Are these possible?The problem I ran is that I need to "hook" it to a list, so which list?

A: You can create your content type, attach an event receiver to it, you don't need to create the event receiver by adding a new item in Visual Studio. Instead you add a class file write your event receiver from scratch inherting from SPItemEventReceiver, then add your content type to your lists. That way, the content type (with the event receiver) will be reusable on all lists it's added to.
Refer to this article for more info:
http://sharepoint-magic.blogspot.com/2013/06/content-type-event-receiver.html
And this one:
https://karinebosch.wordpress.com/walkthroughs/event-receivers-walkthrough3/


Q: log4j.properties file disappears in the project/Classes location I'm configuring log4j in my standalone Java project. I created the property file under project/classes folder but everyday when I run the my application I get errors like
log4j:WARN No appenders could be found for logger (cafcontroller.CAFController).
log4j:WARN Please initialize the log4j system properly.

Then when I check the project/classes folder I find the log4j.properties file missing. Then I create one manually in it. I don't understand why it goes missing.
Please help me to fix this .

A: Whenever you rebuild your project, classes folder gets completely refreshed, deleting and recreating all the class files. Put your log4j.properties file inside your project/src folder. It will be copied to your classes folder on rebuild.


Q: No boot record when installing 13.04 from USB on WinXP I'm replacing WinXP with 13.04 on an older PC using wubi.exe on a USB stick.  I had no problem changing the BIOS on another system that was a bit newer but when I change the settings on the older PC to boot from USB, I get a DOS message saying "Searching for boot record...Not found" & asked to try again.  I don't have the ability to boot from a live CD so is there a reason why I can boot from a USB on a newer computer but can't from an older one?  Both have options to choose to boot from USB, but the older one can find no boot record.  The system was built on 12/13/01 by American Megatrends.
Since I don't have enough "reputation points" to post the screen shot image, you can see it at http://img.photobucket.com/albums/v633/boonevillephil/1029131748-00.jpg.

A: I had the exact same issue and struggled for hours, untill I booted from USB pendriveLinux to set up the USB stick with 13.10
http://www.pendrivelinux.com/
Tor-André

A: Yout should run Boot reapair from the usb or live cd
https://help.ubuntu.com/community/Boot-Repair


Q: List available library - SQL Linked Server AS400 I'm using SQL server 2005 (64bit version) and have successfully connect to as400 using IBM DB2 UDB for iSeries IBMDA400 OLE DB Provider.
Anyone know how to list available library/table and get the field name & description?
already looking around, and have tried this query, but still no luck
select * from OpenQuery(AS400, 'select * from QSYS.qadbxatr');

A: The information is available through the catalog views in the SYSIBM schema.
Schema (library) information is available in SQLSCHEMAS.
Table (file) information is available in SQLTABLES.
Column (field) information is available in SQLCOLUMNS.

*

*V7R1: IBM i catalog tables and views

*V5R4: ODBC and JDBC catalog views


Q: Using sqlite how can i update or insert to a table using a condition? Having a blank table with three columns
CREATE TABLE AssyData    ( AID int NOT NULL PRIMARY KEY UNIQUE , MaxDef float  , MaxDefLC int  , MaxDefNID int , Comps text , SubAssys text )

I would like to Update or insert new values if the new MaxMag is larger than the current one and if the AID is the same. AID is a unique Primary key. Assuming an AID of 100 I have tried the following, but with no success:
INSERT INTO AssyData
(AID  , MaxDef  , MaxDefLC  , MaxDefNID , Comps  , SubAssys)
VALUES( 100 , 101 , 202 , 203 , "" , "")
ON CONFLICT(AID)
DO UPDATE
SET
MaxDef = excluded.MaxDef ,
MaxDefNID = excluded.MaxDefNID ,
MaxDefLC = excluded.MaxDefLC ,
Comps = excluded.Comps ,
SubAssys = excluded.SubAssys
WHERE excluded.MaxDef > 100

I get the error "near "ON": syntax error"
What is wrong with my statement?
Thanks Shawn for the Approach.

A: Assuming you're using a somewhat recent (3.24 or newer) version of sqlite, you can use what's known as UPSERT:
INSERT INTO AssyData(AID, MaxMag, MaxDefNID) VALUES (?, ?, ?)
ON CONFLICT(AID) DO UPDATE SET MaxMag = excluded.MaxMag
                             , MaxDefNID = excluded.MaxDefNID
                    WHERE excluded.MaxMag > MaxMag;

A: In case your vesrsion of SQLite does not allow the use of UPSERT you can achieve what you need in 2 steps:
INSERT OR IGNORE INTO AssyData
(AID, MaxDef, MaxDefLC, MaxDefNID, Comps, SubAssys)
VALUES(100, 111, 202, 203, '', '');

This INSERT OR IGNORE will fail without an error if you try to insert a row with an AID that already exists in the table.
Then:
UPDATE AssyData
SET
  MaxDef = 111,
  MaxDefLC = 202,
  MaxDefNID = 203,
  Comps = '',
  SubAssys = ''
WHERE AID = 100 AND MaxDef < 111;

This will fail if the row to be updated contains MaxDef equal or greater than the value 111.
See the demo.
In general such code needs special care when implemented, because as you can see the value  of MaxDef (111 in this example) must be set 3 times.


Q: Adding new server to Farm not firing event receivers Experts-
We have deployed WSP (with features and feature activation event receivers) in farm environment. Event receivers creates timer jobs to perform few changes to all servers in farm.
Issue:
When new server is added to farm, WSP is getting deployed automatically(can see deployed files), but event receivers are not being fired on newly added server. Hence missing our project related configuration changes in new server.
Please suggest .
Bala


Q: Oracle Apex Office Print: cannot generate excel report when source query returns null value I have a query very similar to this test query:
select
'file1' as "filename",
cursor (
    select
        cursor (
            select
                cursor (
                    select
                        'Test Customer' as CUSTOMER,
                        'Test Country' as COUNTRY,
                        'Test Port' as PORT
                    from
                        dual
                    where
                        1 = 2
                ) as "table_without_rows",
                cursor (
                    select
                        'Test Customer' as CUSTOMER,
                        'Test Country' as COUNTRY,
                        'Test Port' as PORT
                    from
                        dual
                    where
                        1 = 1
                ) as "table_with_rows"
            from
                DUAL
        ) as "list"
    from
        DUAL
    ) as "data"
from
    DUAL

Using AOP PLSQL api I am able to generating a report but with no data in it. If all the cursors return rows it works correctly. As its not throwing any errors I am not sure what is causing this behavior.
The template structure for excel file is given below:
{#list}{#table_without_rows}..(Column names)..{/table_without_rows}
... Some text and styles ...
{#table_with_rows}..(Column names)..{/table_with_rows}{/list}

(edited)
Apex Version: 5.1.3.00.05
AOP Version: 3.0

A: which version of AOP are you using? does the error occur if you set the AOP url to apexofficeprint.com/api?
if you set the debugging to local from the AOP components settings, you should receive a JSON, if you send it to support@apexofficeprint.com we would gladly help you out with this issue.
EDIT: Bug on version 3.0, issue was fixed from version 3.1.


Q: macOS terminal asking for password every time I run copy command I'm running a bash command on mac that moves a file to private/etc/app_name/.
sudo cp my_file.cpp private/etc/app_name/

Every time the I want to run the bash file, the OS asks for my system password.
> ./run_copy.sh
Password: *******

Is there a way to by-pass this or configure in such way that I only have to enter the password once.

A: Apparently, on my Macbook, I see /etc directory having symlinks with the /private/etc directory which is owned by the wheel group & root is part of that group. So, you would need to use sudo to copy to that directory.
With that said on a Linux machine, you can work around this by adding your group to a new file in the /etc/sudoers.d/<group-name> path.
<grp-name> ALL=(ALL) NOPASSWD:ALL

I've just tried this on my mac, I could copy files onto /private/etc directory without entering the sudo password prompt.
Unfortunately, this comes up with some risks as users of your group get privileged access without entering any password prompt. You might accidentally delete important system files etc.,
A more niche approach could be to allow selectively like <group> ALL = (ALL) NOPASSWD: /usr/local/bin/copy-script. This way, they can't run all scripts/commands with sudo privileges.


Q: A Question concerning $\ell^1$ Let $a_n >0$ and $\sum_{n=1}^\infty a_n < \infty$.
Define $$
M=\{ \{x_n\}_{n=1}^\infty \in \ell^1 : \forall n, |x_n|\le a_n\}
$$
Then I want to prove that $M$ is compact and $M$ cannot be included any finite-dimensional subspace of $\ell^1$.

A: First of all $M$ contains the sequences
$$
(\overline x^n)_m:=\delta_{m,n} a_n,\quad a_n>0
$$
Therefore, any subspace which contains $M$, has to include all the linearly independent sequences $(e^n)_m:=\delta_{m,n},$ therefore cannot be finite dimensional.
As for the compactness, the direct way is to show that any sequence $\{x^n\}$ in $M$ (which is necesessarly bounded) has a convergent subsequence $\{\bar x^m\}$. Here you can use a standard diagonal argument. Let $x_1^{k_1}$ be a convergent subsequence of $ (x^n)_1$, $x_2^{k_2}$ be a convergent subsequence of $ (x^{k_1})_2$, $x_3^{k_3}$ be a convergent subsequence of $ (x^{k_2})_3$,... This subsequences exist,  since for any $k$, $|(x^n)_k|\leq a_k $. Then define
$$
\overline x^\ell=((x^{k_\ell})_1, (x^{k_\ell})_2,(x^{k_\ell})_3,\ldots).
$$
A little of work is needed to show the convergence of  $\{\bar x^\ell\}$. Here you have to use that $ |(\bar x^\ell)_k|\leq a_k$ and so
$$
\sum_{k=N}^\infty|(\bar x^\ell)_k|\leq \sum_{k=N}^\infty a_k=R_N,\qquad \lim_{N\to \infty} R_N=0.
$$


Q: MS-DOS delete with wildcards on ends What I want is a wildcard that means "contains"
So if I have a directory with
a.txt
b.param
b.param.config

I would like to delete only b.param and b.param.config
I have tried del *.param*, del *param* ... but nothing seems to match anything for the beginning and end of the file but containing param.
I am running the command from a batch file, so if the solution is in batch that will work as well.

A: I think del *param* should work for this...
c:\test>dir /w
 Volume in drive C is HP
 Volume Serial Number is 0EBF-B242

 Directory of c:\test

[.]              [..]             a.txt            b.param
b.param.config
               3 File(s)             29 bytes
               2 Dir(s)  185,518,833,664 bytes free

c:\test>dir /w *param*
 Volume in drive C is HP
 Volume Serial Number is 0EBF-B242

 Directory of c:\test

b.param          b.param.config
               2 File(s)             20 bytes
               0 Dir(s)  185,518,833,664 bytes free

c:\test>del *param*

c:\test>dir /w
 Volume in drive C is HP
 Volume Serial Number is 0EBF-B242

 Directory of c:\test

[.]     [..]    a.txt
               1 File(s)              9 bytes
               2 Dir(s)  185,518,833,664 bytes free

What happened when you tried this? What version of MS-DOS are you running?


Q: How can I allow multiple users to access the same amazon instance at the same time? I am new to Amazon Cloud, and trying to create an EC2 instance that can allow multiple users to access at the same time.
While there are plenty of documentations, I haven't found an answer to my question. Whenever those documentations say "user", it refers me. But I want to have an application installed in the instance, and allow more than one of my users to access it simultaneously.
How can I achieve this? Thank you very much!

A: The same way you would add multiple users to a normal instance. I am going to assume you are using linux and can login to the instance, if not, see this post. Now you just need to add a user, and setup the ssh keys.


Q: Adding some input nodes in the middle of a DNN In this bioinformatics paper: paper link is used the following DNN (Deep Neural Network):

where some input nodes were added (concatenated) to the first hidden layer.
Does anybody know the name of this technique? I would like to know more but I can not find any information about it.


Q: How to realize these transfer functions as a circuit? While I am well aware of some of the technique about implementing transfer functions I wanted some input about how can i realize this transfer function with active filters (OpAmps are preferred):
1) $$
\frac{1} {(1-sT)}$$
it is unstable, it should be e^x (where x >0...unstable for step response input) Maybe can be pulled off with just a mosfet transistor?
2) Multiply the top equation by its complex conjugate
$$
\frac{(1+sT)} {(1+(sT)^2)}$$
What are some realizations of both of these Transfer functions?

A: The first equation can be rearranged as:

This facilitates synthesis using R's & C's.  A C is a 1/sc kind of impedance.  So rearranging to get 1/sT makes following synthesis steps easier.
Next consider this transfer function if it were implemented with a closed loop:

The closed loop transfer function would work out the same as the equation above.
The forward gain block and the difference operator can be syntensized with op-amps by inspection:

Now there are some tricks to ease the synthesis of the op-amp circuit by inspection.  That is the subject of a whole other post.  There was a great white-paper on it back in the mid 90's.  Never found the white paper again.  Wrote my own version of the white paper and ran it by Bob Pease. (RIP Bob, we love you).  Bob was horrified by the methodology so I mothballed the white paper.  It does ease synthesis though so I still use it personally.
There are a bunch of other considerations about the use of the amps around stabilization and compensation, which may/not apply depending on the amps used and the frequencies of interest.
Now having a circuit that synthesizes the transfer function may not get you where you want to go.  As suggested this is astable.  It is likely to rail out depending on the input signal.  If you're looking for an analog latch - you're in luck, although there are perhaps better ways of doing it.  If you're looking for a real ac signal gain, then there's more to consider.  For example the synthesis above extends the transfer function all the way down to DC.  If this is for ac signal gain, then the amps could be biased in a reasonable way and the ac signals coupled by caps in the right places.  Judicious choice would be required for the DC/ac cutover and the GBW of the amps.
It is quite possible that there is a better way to go about this all.  More information about what one is trying to achieve with this circuit, and the design goals may facilitate a better answer.  I'm sensing a microcontroller solution for this one.
PS. Pardon the rough sketches.


Q: Get substring with code from different strings I'm working on a web scraper. Among the fields it scrapes there is a Description tag like this one, different for each product:

Black Tshirt

REF.: V23T87C88EC

COMPOSIÇÃO:

90% Poliamida

I can get the content of the description tag without problems, but I also need to get the value of REF inside the description (V23T87C88EC for this example).
The problem is this description is always different for all products, HOWEVER there is ALWAYS a "REF.: XXXXXXXXX" substring in there.
The length of the REF id can change, and it can be anywhere in the string.
What's the best way to always get the REF id?

A: Possible solution is the following:
html = """

Black Tshirt

REF.: V23T87C88EC

COMPOSIÇÃO:

90% Poliamida

"""

import re

pattern = re.compile(r'REF\.: (.+?)$')

found = pattern.findall(html)

Returns ['V23T87C88EC']

REGEX DEMO

A: You can do this with a regex (read more about regex: https://docs.python.org/3/howto/regex.html) :
html = '''

Black Tshirt

REF.: V23T87C88EC

COMPOSIÇÃO:

90% Poliamida

'''

import re

myref = re.search (r"(?<=REF.: )\w+", html)[0]

print(myref)

# V23T87C88EC


Q: Using VBS Script in AAE and getting 1024 Expect Statement I am new to coding in VBS and all the time I am getting 1024 Expect Statement Error in my VBScript. If anyone could point me where is a mistake I would be gratefull.
Dim Path
Dim BeginDate
Dim EndDate
Path = WScript.Arguments.Item(0)
BeginDate = WScript.Arguments.Item(1)
EndDate = WScript.Arguments.Item(2)
Set objExcel = CreateObject("Excel.Application")
Set objWorkBook = objExcel.Workbooks.Open(Path)
objExcel.Visible = True
Worksheets("PO Buy Update").Range("H3").AutoFilter Field:=8, Criteria1:="<>"
Worksheets("PO Buy Update").Range("Q3").AutoFilter Field:=17, Criteria1:="<>"
Worksheets("PO Buy Update").Range("P3").AutoFilter Field:=16, Criteria1:=">=" & BeginDate, Operator:=xlAnd, Criteria2:="<=" & EndDate

Till filtering part everything goes correct. When I try to run filtering part as a Macro in Excel it works but when I am implementing it into Script it throws me an error.

A: In VBScript, you don't have to mention the name of the parameters while calling a function/method. You just need to pass the values. The parameters names are required in excel-vba, not in VBScript.
So, try replaying,
Worksheets("PO Buy Update").Range("H3").AutoFilter Field:=8, Criteria1:="<>"
Worksheets("PO Buy Update").Range("Q3").AutoFilter Field:=17, Criteria1:="<>"
Worksheets("PO Buy Update").Range("P3").AutoFilter Field:=16, Criteria1:=">=" & BeginDate, Operator:=xlAnd, Criteria2:="<=" & EndDate

with
Worksheets("PO Buy Update").Range("H3").AutoFilter 8,"<>"
Worksheets("PO Buy Update").Range("Q3").AutoFilter 17,"<>"
Worksheets("PO Buy Update").Range("P3").AutoFilter 16,">=" & BeginDate,1,"<=" & EndDate

Reference to the Autofilter Method
Reference to the enumerated constant xlAnd

A: VBScript can't handle named parameters. Change the last lines to
Worksheets("PO Buy Update").Range("H3").AutoFilter 8, "<>"
Worksheets("PO Buy Update").Range("Q3").AutoFilter 17, "<>"
Worksheets("PO Buy Update").Range("P3").AutoFilter 16, ">=" & BeginDate, xlAnd, "<=" & EndDate

and it'll hopefully get you a step closer. You might need to define xlAnd and other constants as well.

A: VBScript, as the other answers state, does not handle the named parameters.
Therefore it doesn't know what you mean by Worksheets.  They will need to be fully qualified as references belonging to the parent objWorkbook object.
objWorkbook.Worksheets("PO Buy Update").Range("H3").AutoFilter 8, "<>"

will work just fine.  You will need to replace any and all excel named values (such as xlAnd) with the enumerated value equivalent, or declare them as constants and set the value to match the enumerated value if you want to use the named parameter.

A: Thanks for your answers and pointing me, my mistakes. My final solution is below
Dim Path
Dim BeginDate
Dim EndDate
Path = WScript.Arguments.Item(0)
BeginDate = WScript.Arguments.Item(1)
EndDate = WScript.Arguments.Item(2)
Set objExcel = CreateObject("Excel.Application")
Set objWorkBook = objExcel.Workbooks.Open(Path)
Set c=objWorkBook.Worksheets("PO Buy Update") // Attached WorkbookSheet(name) into variable and then specified which row, column is a header
objExcel.Visible = True
c.cells(3,8).AutoFilter 8, "<>"
c.cells(3,17).AutoFilter 17, "<>"
c.cells(3,16).AutoFilter 16, ">=" & BeginDate, 1, "<=" & EndDate

I believe my main problem was that I have header in third row and when I did not specified that Script was searching for filtering option in first row.
Once again thanks for your time !


Q: Find certain value/element in two-dimensional ArrayList I have a two dimensional arraylist
List<List<String>> movies_info = new ArrayList<>();

which I populate creating new rows
movies_info.add(new ArrayList<String>());

and adding elements
movies_info.get(i).add(title);

.
I would like to be able to check if the element I'm adding already exist in the entire ArrayList. Is it possible to achieve this result without using the following for.loop?
boolean found = false;
for (int i = 0; i < movies_info.size(); i++) {
    if(movies_info.get(i).contain(title)) {
    found = true;
}
if (!found) {
    movies_info.add(new ArrayList<String>());
    movies_info.get(i).add(title);
}

A: You can replace your second ArrayList by a HashMap  and check if it is already there.
movies_info.add(new HashMap<String,String>());

if (!movies_info.get(i).containsKey(title)){
    movies_info.get(i).put(title,title);
}

Both the search for a key in the HashMap and also adding a new element have constant time complexity O(1)
To get the values afterwards you can use this code
for (String title : movie_info.get(i).keySet()){
      // Use title
}

A: I would suggest a different approach. Instead of creating a list of lists of String-s, you can have a class called Movie and create a list of Movie objects. Then you can directly query the list by calling the contains method.
Note: you need to override two methods in the Movie class, hashCode and equals, for the contains method to work. By overriding these two methods, you will tell the list object how to compare two Movie objects.
UPDATE: you don't have to manually write the equals and hashCode methods (at least not if you are using the Eclipse IDE). You can just right-click anywhere inside the class's body and choose Source -> Generate hashCode and equals ..., it will prompt you on which fields of the class you want to compare two objects, select the fields, hit OK and off you go, these two methods will be automatically generated for you.
Here's a simple example:
public class Movie
{
    String title;

    public Movie(String t)
    {
        this.title = t;
    }

    public String getTitle()
    {
        return title;
    }

    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((title == null) ? 0 : title.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Movie other = (Movie) obj;
        if (title == null)
        {
            if (other.title != null)
                return false;
        } else if (!title.equals(other.title))
            return false;
        return true;
    }
}

You can test it like this:
import java.util.ArrayList;
import java.util.List;

public class Test
{
    public static void main(String[] args)
    {
        List<Movie> movies = new ArrayList<Movie>();
        movies.add(new Movie("Movie 1"));
        movies.add(new Movie("Movie 2"));

        System.out.println(movies.contains(new Movie("Movie 1")));
    }
}

A: Something like this? it simplifies a bit..
for(List<String> mInfo : movies_info) {
   if(!mInfo.contains(title)) {
      //do stuff
   }
}