Q: YAML issue when knitting to pdf I have a paper written in rnotebook, which I want to knit to pdf.
this is the beginning of it, including the YAML:
---
title: "Are shifts between points of view challenging for readers? An examination of readers' eye movements in response to Woolf's *To the Lighthouse* and *Mrs Dalloway*"
author: "Giulia Grisot, Kathy Conklin, Violeta Sotirova - The University of Nottingham"
date: '`r format(Sys.time(), "%d %B %Y")`'
output:
  html_notebook:
    fig_caption: yes
    force_captions: yes
    #highlight: pygments
    number_sections: false
    theme: readable
# csl: sage-harvard.csl
csl: apa.csl
bibliography: library.bib
link-citations: yes
nocite: |
  @Grisot2018

---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, warning=FALSE, message=FALSE)
```

```{r, include=F}
library(tidyverse)
library(ggpubr)
```

# Abstract

The emergence of empirical approaches within stylistics has increased interest in how literary texts are processed by readers. Techniques of speech and thought representation represent an area ripe for empirical investigation in this respect, especially when these cause interpretative ambiguities.

I have installed tinytex, and I have got miktex installed and pandoc.
I have tried to just use the "knit to pdf" command in RStudio but it gives me this error and i don't know what to do
Error in yaml::yaml.load(..., eval.expr = TRUE) :
  Scanner error: while scanning for the next token at line 4, column 31 found character that cannot start any token at line 4, column 31
Calls: <Anonymous> ... parse_yaml_front_matter -> yaml_load -> <Anonymous>
Execution halted

A: I think this is down to the formatting in your yaml. When I knitted your code R Studio did some re-formatting of the title, but in the process replaced the ' with " in your date, causing the error. I don't have your .bib file so I can't test your exact code, but the following worked for me:
---
title: Are shifts between points of view challenging for readers? An examination of
  readers' eye movements in response to Woolf's *To the Lighthouse* and *Mrs Dalloway*
author: "Giulia Grisot, Kathy Conklin, Violeta Sotirova - The University of Nottingham"
date: '`r format(Sys.time(), "%d %B %Y")`'
output:
  pdf_document: default
  html_notebook:
    fig_caption: yes
    force_captions: yes
    number_sections: no
    theme: readable
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, warning=FALSE, message=FALSE)
```

```{r, include=F}
library(tidyverse)
#library(ggpubr)
```

# Abstract


Q: Using string.prototype.replace with a regexp and a function The following returns 'entiy'. I want it to return 'entity'. How can I achieve this?
'entities '.replace(/\w(ies)(?:[\W|$|_])+/g, 'y');

A: You could change the \w to \B to verify that there is not a word boundary.

console.log('entities '.replace(/\Bies\b/g, 'y'));

A: Just capture the character before the "ies":
'entities '.replace(/(\w)(ies)(?:[\W|$|_])+/g, '$1y');

Now your question asked about using a function; you can do that too:
'entities '.replace(/(\w)(ies)(?:[\W|$|_])+/g, function(_, before, repl) {
  return before + "y";
});

I don't know what you want to do with the subsequent stuff after "ies"; you can either capture it and glue it back into the replacement, or else use positive look-ahead. Portions of the input text matched by look-ahead are not part of the match involved with the replacement operation. In other words, the look-ahead does succeed or fail based on the pattern, but the characters matched are not made part of the "to be replaced" grouping.


Q: How to serve static images in nodejs server using absolute path in Angular 10 img tag? I have been searching here and not finding a solution, so I am asking. How can I serve my static images located in the nodejs server:
public/img

Nodejs (before app.listen()):
app.use("/api", routesIndex);
app.use(express.static(__dirname + '/public/img'));

Angular 10 template:

The [src] resolves to the absolute correct path of:
http://localhost:5000/api/public/img/shark.jpg

But it shows 404 still. Any ideas?
Thanks

A: There is no need to add path of statically served directory. Just remove '/public/img/'

You can access the all file of your served directory directly. like:
http://localhost:5000/shark.jpg

A: Follow the below steps,
your image is at path Public/img/shark.jpg

in your app.js, this should be before any route is created
app.use(express.static(__dirname + '/public/img'));

create a route as below
app.get('/Image/:id', function (req, res) {
    // logic to find image based on id passed, we will assume it results in shark.jpg
    const filepath = `${__dirname}/public/img/shark.jpg`;
    res.sendFile(filepath);
});

Now consume this endpoint from your angular code
localhost:{PORT_NUMBER}/Image/{ID_FOR_SHARK_IMAGE}

A: I got it working by doing the following:
Nodejs added path:
const path = require("path");

app.use(express.static(path.join(__dirname, 'public/img')));

Then in Angular created a separate assetUrl that omits the "/api" part of the baseUrl:
[src]="quizService.assetUrl+'/'+quizService.questions[quizService.questionProgress].imageName+'.jpg'"

and now my images are served.


Q: Filter Data in Shiny by Clicking on Plot Data Point I Want to filter data by click on data points of plot in Shiny, like we have in powerbi.
i have developed a dashboard in powerbi i want to have a same effect in shiny,
like if i click the data point of plot in shiny dashboard the other plots should drill down in response to that point, i have build a complete dashboard in shiny but i need to add these function.
there can also be multiple data points drill down like if i want to know the february(datapoint) month sales of John(datapoint).

A: In the UI, you should add, click,doubleclick or hover:
 plotOutput("plot1", click = "plot_click")

And in the Server will be input$plot_click, X and Y coordinates
Here a Shiny explanation:
https://shiny.rstudio.com/articles/plot-interaction.html
And I wrote for you a simple example:
library(shiny)
library(ggplot2)
library(MASS)

ui<- shinyUI(
       fluidPage(
                plotOutput("grafica", hover="clickGrafica"),
                tableOutput("miverbatini")
        )
)
server<- shinyServer(function(input,output) {

        output$grafica <- renderPlot({

                ggplot(mpg,aes(x=cty, y=hwy)) +
                        geom_point()
        })

        output$miverbatini <- renderTable({
                nearPoints(mpg,input$clickGrafica, threshold = 10)  # near points 20
        })
})
shinyApp(ui, server)


Q: Why Radio button selects multiple options when label values are different Having a reusable Radio button component, when the options are using the same value for name it works fine:
  const drinks = [
    {
      label: "Coffee",
      name: "a"
    },
    {
      label: "Tea",
      name: "a"
    },
    {
      label: "Water",
      name: "a",
      disabled: true
    }
  ];

But when they are different values, it doesn't work fine, it lets the user select multiple options:
  const drinks = [
    {
      label: "Coffee",
      name: "1"
    },
    {
      label: "Tea",
      name: "2"
    },
    {
      label: "Water",
      name: "3",
      disabled: true
    }
  ];

Here is a working sandbox of it as it's complicated to create a working example here: https://codesandbox.io/s/custom-radio-button-group-forked-1do5u4?file=/src/App.tsx

A: As i mentioned in comment,
the code is working as expected
const drinks = [
    {
      label: "Coffee",
      name: "a"
    },
    {
      label: "Tea",
      name: "a"
    },
    {
      label: "Water",
      name: "a",
      disabled: true
    }
  ];

the name attribute is used to group radio buttons,and only one radio button in the group can be selected at a time.

A: It is working as expected. If it's a radio button, then it's ONE name and multiple possible values. Only one of them can be selected at a time.
  const drinks = [
  {
    label: "Coffee",
    name: "drinkType"
  },
  {
    label: "Tea",
    name: "drinkType"
  },
  {
    label: "Water",
    name: "drinkType",
    disabled: true
  }
  ];


Q: How to correctly use two DatePickerSingle in a Dash Application Hope you all doing well.
I have two DatePickerSingle  that I want to integer in a dash application to use them as a filter further. The problem is that my Dash app only returns values of the first DatePickerSingle, but not the second one ..

from datetime import date
import dash
from dash.dependencies import Input, Output, State
import dash_html_components as html
import dash_core_components as dcc

Min_d =datetime.strptime(str(df_sub['From'].min()), "%Y-%m-%d %H:%M:%S")
Max_d = datetime.strptime(str(df_sub['From'].max()), "%Y-%m-%d %H:%M:%S")

app = dash.Dash(__name__)
app.layout = html.Div([
    html.H2("Date for the First period"),
    dcc.DatePickerRange(
        id='my-date-picker-range',
    min_date_allowed = date(2021,4,1),
    max_date_allowed = date(2021,9,30)
    ),

    html.H2("Date for the Second period"),

    dcc.DatePickerRange(
        id='my-date-picker-range2',
    min_date_allowed = date(2021,4,1),
    max_date_allowed = date(2021,9,30)
    ),

    html.Div(id='output-container-date-picker-range')
])

@app.callback(
    Output('output-container-date-picker-range', 'children'),

    Input('my-date-picker-range', 'start_date'),
    Input('my-date-picker-range', 'end_date'),
    Input('my-date-picker-range2', 'start_date2'),
    Input('my-date-picker-range2', 'end_date2')
)

def update_output(start_date , end_date , start_date2 , end_date2):

        return ( str(start_date) + '   ' + str(end_date)+ '   ' +str(start_date2)+ '   ' +  str(end_date2))

if __name__ == '__main__':
    app.run_server(debug=False)

Here is what I got when I run the app :

A: The problem is with these lines:
Input('my-date-picker-range2', 'start_date2'),
Input('my-date-picker-range2', 'end_date2')

start_date2 and end_date2 are not valid properties of dcc.DatePickerRange, so change these instances to start_date and end_date.


Q: VB 2008 Express edition vs VB 6 Can any tell me what are the advantages of VB.NET(2008 Express Edition) over VB 6?
Thank you

A: Good comparison you can find in Wiki:
VB.NET
In short: the greatest feature in VB.NET is Managed Code. It also contains a little difference between Long and Integer in VB6 and VB.NET. There are also many small syntax changes (for example, VB.NET support structured exception handling).

A: VB6 is a old fashioned programming software from microsoft. It doesn't use as a base .NET framework which is used on every machine. Also visit Wkipedia VB

A: .NET have multithreading and more functional components (for work with network for example).

A: Visual Basic is a third-generation event-driven programming language and integrated development environment (IDE) from Microsoft for its Component Object Model (COM) programming model first released in 1991, final release was version 6 in 1998 (VB6) and declared legacy during 2008.
Visual Basic.net is part of the .net framework (like C# or F#), first released in 2002, with constant Microsoft updates.
You can use VB.Net in Visual Studio 2008 Express (free) or in any Visual Studio IDE, like the Visual Studio 2017 Community edition (also free).
https://en.wikipedia.org/wiki/Comparison_of_Visual_Basic_and_Visual_Basic_.NET
VB6 uses legagy frameworks like Dynamic Data Exchange (DDE) and DAO. The VB6 IDE is hard to install on new operating system (original setup gives errors on Windows 7, 8 or 10).


Q: VNC feed from a remote server I want to measure the performance of the VNC feed from a remote server. The use case is, there will be a  user login to the remote server and doing some operations. There will be many other users viewing these operations through the VNC viewer (ssh connection). Based on the different network speed I want to measure the performance of the VNC feeds of the users who are viewing. How to achieve this through JMeter?
Note that the users who are viewing are not doing any operations on the remote server.

A: VNC and SSH are different beasts so your VNC viewer (ssh connection) stanza doesn't make a lot of sense, VNC is a separate protocol and JMeter doesn't support it either via its samplers or via plugins
If you still want to use JMeter for load testing your VNC server you will need to implement the client login and getting initial image using some form of VNC Java client library like Vernacular VNC from JSR223 Sampler or come up with your own JMeter plugin


Q: How to set a Sharepoint lookup field when inserting a new record in PowerApps I am using the Collect function to insert a new record into a Sharepoint list using PowerApps. There is a Gallery with a list of values from another Sharepoint List. I want to use the Selected value from the Gallery to set one of the fields in the Insert List.
I thought it would be as easy as this:
Collect('Concert Log List',{Attendee: BrowseGallery1.Selected});

Essentially I want to add a new record to the Content Log List and reference the Attendee (which is the lookup list) every time the Attendee is referenced. Now the field just ends up being blank.

A: Hm. Gallery1.Selected represents the entire record in the Sharepoint List. Can you add another . to Selected to get to the actual field you want to write?
Gallery1.Selected.Attendee (or the like)

A: Got it:
Patch('Child List',
  Defaults('Child List'),
  {
    Title:"test",
    ParentItem:
      {
        Id:Gallery1.Selected.ID,
        Value:Gallery1.Selected.Title
      }
  }
)


Q: Apex: Find the user an event was created by I'm new to Apex, I'm trying to determine the ID of the User whom an event was created by in a trigger I'm making.
I can determine the ID of the Contact and the User assigned to the event:
String whoID = String.valueOf(Trigger.new[0].WhoId); // ID of the Contact the event is assigned to
String ownerID = String.valueOf(Trigger.new[0].OwnerId); // ID of the User assigned to the event

I want the ID of the user who created the event. For example, though obviously this doesn't work:
String createdByUserID = String.valueOf(Trigger.new[0].CreatedBy); // Doesn't work

There doesn't appear to be such a field for the Event object.

A: The field name is CreatedById.
One way to see all the field names for objects is to open the .schema file in the Force.com IDE.
PS
Its worth using Apex's Id datatype:
Id whoID = Trigger.new[i].WhoId;

rather than String both for code clarity and because there are some unique methods available there - see the "Id Methods" section of Id Class.


Q: Gseapy: how to get gene list used for each pathway I am running an enrichment analysis with gseapy enrichr on a list of genes.
I am using the following code:
enr_res = gseapy.enrichr(gene_list = glist[:5000],
                            organism = 'Mouse',
                            gene_sets = ['GO_Biological_Process_2021'],
                            description = 'pathway',
                            #cutoff = 0.5
                            )

The result looks like this:
enr_res.results.head(10)

The question I have is, how do I get the full set of Genes (very right column in the picture) used for the individual pathways?
If I try the following code, it will just give me the already displayed genes. I added some correction to have a list that I then could further use for the analysis.
x = 'fatty acid beta-oxidation (GO:0006635)'

g_list = enr_res.results[enr_res.results.Term == x]['Genes'].to_string()

deliminator = ';'
g_list = [section + deliminator for section in g_list.split(deliminator) if section]

g_list = [s.replace(';', '') for s in g_list]
g_list = [s.replace(' ', '') for s in g_list]
g_list = [s.replace('.', '') for s in g_list]

first_gene = g_list[0:1]
first_gene = [sub[1 : ] for sub in first_gene]

g_list[0:1] = first_gene
for i in range(len(g_list)):
    g_list[i] = g_list[i].lower()
for i in range(len(g_list)):
    g_list[i] = g_list[i].capitalize()

g_list

I think my approach might be wrong to get all the Genes and I just get the displayed genes. Does somebody has an idea, how it is possible to get all genes?

A: pd.set_option('display.max_colwidth', 3000)

This increases the number of displayed characters and somehow this solves the problem for me. :)


Q: Disable a command box in Databricks notebook I have a Databricks Notebook. My notebook has several command. some of them is just for my test and I do not want ran them on production.
Is there any way to just disable a command. I do not want to delete them permanently.

A: Late ... but ... my solution is to set %md as first line. So no command would be executet.
David


Q: Canceling pending sends errors I am running Selenium WebDriver scripts on Chrome Browser, version 23.
The tests run successfully without any error but there is a message:
[0103/143909:ERROR:ipc_sync_channel.cc(378)] Canceling pending sends
[0103/143909:ERROR:ipc_sync_channel.cc(378)] Canceling pending sends
And because of the above error, the result of the test is FAILED.
Here is how I instantiate a chrome browser session:
public static boolean setup(String browserType){
    if(browserType.equals("IE")){
        webdriver1 = new InternetExplorerDriver();
    } else if(browserType.equals("Chrome")){
        System.setProperty("webdriver.chrome.driver","path to  chromedriver.exe");
        webdriver1 = new ChromeDriver();
}

Appreciate any feedback from anyone who has resolved this issue.

A: According to https://code.google.com/p/chromedriver/issues/detail?id=159 it has something to do with your browser has not yet finished loading a page, while selenium closes and quits the driver.


Q: Deleting table data from tablespace in Oracle I tried to delete the data from tablespace using the command

DROP USER xyz CASCADE;

I found that user was dropped but size of my tablespace did not decreased.
Is my data fom the tablespace have been deleted? If yes, how can I confirm that? And why was the space not deallocated?

A: Oracle does not automatically shrink datafiles, which is what a tablespace is made of.  Oracle simply marked the space which had been used by user XYZ's segments (tables, indexes, and the like) as free for some other user's segments to use.
SELECT * FROM DBA_OBJECTS WHERE OWNER = 'XYZ'; should demonstrate that user XYZ no longer owns any physical (tables, indexes, clusters) or logical (sequences, procedures, packages, triggers, types) objects in the database.

A: You can shrink datafile, under certain circumstances, with following command:
ALTER DATABASE DATAFILE 'filename2' RESIZE new_size;

Datafile size can be reduced if there is no data at the end of file. See "Managing Tablespaces" for detailed information.


Q: Influxdb python write_api not write specific fields I am trying to write several points into influxdb by using the python client.
Most of them are working but some specific fields of points are not saving.
Here's my code.
def getPoints(p_zones):
  # Writing max values to p_zones and then add to write_api
  points = []
  for p_zone in p_zones:
    point = Point("mem") \
      .tag("zone", p_zone.zone) \
      .field("historic", p_zone.historic) \
      .field("current", float(p_zone.current)) \
      .field("hourMaxValue", p_zone.hourMaxValue) \
      .time(p_zone.timestamp.astimezone(eastern), WritePrecision.NS)
      # .tag("label", p_zone.label) \
    points.append(point)
  return points

points = getPoints(p_zones)

# Writing to influx
with client.write_api(write_options=WriteOptions(retry_interval=15, max_retries=2, write_type=SYNCHRONOUS)) as write_api:
      write_api.write(bucket=bucket, org=org, record=points)

And here is the log of points before writing to influxdb.
mem,zone=Pool\ Deck current=0,historic=25,hourMaxValue=25 1653931921000000000
mem,zone=Pool\ Deck current=25,historic=25,hourMaxValue=25 1653931920000000000
mem,zone=Pool\ Deck current=25,historic=25,hourMaxValue=25 1653931915000000000
mem,zone=Game\ Room current=0,historic=0,hourMaxValue=0 1653931920000000000
mem,zone=Meeting\ Area\ EAST current=0,historic=0,hourMaxValue=0 1653931920000000000
mem,zone=Meeting\ Area\ WEST current=0,historic=0,hourMaxValue=0 1653931920000000000
mem,zone=Pool\ Club\ Room current=0,historic=0,hourMaxValue=0 1653931920000000000
mem,zone=TV\ Area\ WEST current=0,historic=0,hourMaxValue=0 1653931920000000000
mem,zone=Weight\ Room current=2,historic=2,hourMaxValue=2 1653931920000000000
mem,zone=Movie\ Theater current=0,historic=0,hourMaxValue=0 1653931920000000000
mem,zone=Business\ Conference\ Room current=0,historic=0,hourMaxValue=0 1653931920000000000
mem,zone=Cardio\ Room current=1,historic=1,hourMaxValue=1 1653931920000000000
mem,zone=TV\ Area\ EAST current=0,historic=0,hourMaxValue=0 1653931920000000000

But in online influxdb, I can see every points are looking good but the Pool Deck point's current andhourMaxValue fields are not saving.


Q: regex excluding time from text I would like to extract time from the text below using regex.
Text: "Media: a few minutes ago, 3:25 pm uts"
Regex pattern to select only time (ex: 3:25) from the above text?

A: Use regex /\b[0-9]+:[0-9]+\b/. Explanation:

*

*\b - word boundary

*[0-9]+ - 1+ digits

*: - literal colon

*[0-9]+ - 1+ digits

*\b - word boundary

I do not know your specific use in selenium, but here is an example:
src = 'Media: a few minutes ago, 3:25 pm uts'
pattern = re.compile(r'(\\b[0-9]+:[0-9]+\\b)')
match = pattern.search(src)
print match.groups()[0]

Output:
3:25


Q: Zend_Log with multiple writers in application.ini i have a logger in my config like this:
resources.log.stream.writerName = "Stream"
resources.log.stream.writerParams.stream = APPLICATION_PATH "/../logs/err.log"
resources.log.stream.writerParams.mode = "a"
resources.log.stream.filterName = "Priority"
resources.log.stream.filterParams.priority = 3

But i want to use it for only error logs. For another logs wanna use another log file. For that reason i added these lines to app.ini
resources.log.stream.writerName = "Stream"
resources.log.stream.writerParams.stream[] = APPLICATION_PATH "/../logs/debug.log"
resources.log.stream.writerParams.stream[] = APPLICATION_PATH "/../logs/info.log"
resources.log.stream.writerParams.mode = "a"
resources.log.stream.filterName = "Priority"
resources.log.stream.filterParams.priority[] = 7
resources.log.stream.filterParams.priority[] = 5

But this is not working i wanna use differetn files for different priorities. But logger overrides the first logger. How ?

A: Example of application.ini:
resources.log.err.writerName = "Stream"
resources.log.err.writerParams.stream =  APPLICATION_PATH "/../data/logs/ERR.log"
;resources.log.stream.formatterParams.format = "%priority%:%message% %timestamp% %priorityName%  %info% PHP_EOL"
resources.log.err.filterName = "Priority"
resources.log.err.filterParams.priority = 3
resources.log.err.filterParams.operator = "=="

resources.log.warn.writerName = "Stream"
resources.log.warn.writerParams.stream = APPLICATION_PATH "/../data/logs/WARN.log"
;resources.log.warn.formatterParams.format = "%priority%:%message%:%ip%:%userid% %timestamp% %priorityName%  %info% PHP_EOL"
resources.log.warn.filterName = "Priority"
resources.log.warn.filterParams.priority = 4
resources.log.warn.filterParams.operator = "=="

In bootstrap:
protected function _initLog() {
    $options = $this->getOption('resources');
    $partitionConfig = $this->getOption('log');
    $logOptions = $options['log'];
    $logger = Zend_Log::factory($logOptions);
    $logger->addPriority('USERACTION', 8);
    $logger->addPriority('DBLOG', 9);
    Zend_Registry::set('logger', $logger);
}

Then in codes:
$this->logger = Zend_Registry::get('logger');
$this->logger->setEventItem('ip', $_SERVER['REMOTE_ADDR']);
$this->logger->setEventItem('userid', $this->userId);

Use this way:
$this->logger->log('Test error', Zend_Log::WARN);

Or this way:
$this->logger->warn('Test error');

Or this way:
$this->logger->log('Test error', 4);

A: You can use filters to accomplish this. Just let higher priority events pass through the filters until you want to log them.
http://framework.zend.com/manual/en/zend.log.filters.html
What's wrong in your setup is that you are trying to use the same writer which you should not. Use the filters to choose the writers and associate certain log files with certain writers, as shown in the second part of the example.
I think something like that should do the trick:
resources.log.stream.writerName = "myDebugWriter"
resources.log.stream.writerParams.stream = APPLICATION_PATH "/../logs/debug.log"
resources.log.stream.filterName = "Priority"
resources.log.stream.filterParams.priority = Zend_Log::WARN
resources.log.stream.writerName = "myInfoWriter"
resources.log.stream.writerParams.stream = APPLICATION_PATH "/../logs/info.log"
resources.log.stream.filterName = "Priority"
resources.log.stream.filterParams.priority = Zend_Log::INFO


Q: Is there any Number recognition SDK or frameworks or libraries for iPhone I need number recognition for my project, as i will write the number using touches. i want that to be recognized.
Can anyone Please Help me, provide me any ideas or frameworks or libraries related to this.

A: this might get you started http://code.google.com/p/dollar-touch/


Q: Memory Problem when creating large Access reports We are having a problem. We have a complex Access 2003 application. When our main user is trying to create a particularly long report he getting a message “2004 - There isn't enough memory to perform this operation. Close unneeded programs and try the operation again”. The problem is the rest of us are able to run the same report fine. Our user is able to run the same report ok with fewer amounts of data. We looked at the obvious things such as the amount of memory on his machine and the disk space available. That seems to be ok compared to those of are able to run ok.
The failure occurs when he tries to write the report to a word file. He is able to create the report when he writes directly to a printer, but since the report is so long what we do is to write the output to a pdf file.
The report runs 4500 pages. These are oversize pages meaning that the data would be truncated if you use a normal size printer and page.
I have search the internet but none of the suggestions seem to work for us. Any suggestions you have will be appreciated.
Bob Avallone

A: Do you have graphics on the report?  Even a small one on the page header?  If so don't use the format event to fill the graphic.  Or change the grapic to a BMP.


Q: There was a problem with order creation. Notice: Array to string conversion in /vendor/magento/framework/DB/Adapter/Pdo/Mysql.php I have received this error only once. The customer tried to place an order using afterpay payment method and afterpay approved the payment but while creating order in Magento it threw this error:

There was a problem with order creation. Notice: Array to string
  conversion in /vendor/magento/framework/DB/Adapter/Pdo/Mysql.php on
  line 3088

The problem is I cannot reproduce it again. How do I fix this?
Is this a core bug?


Q: service / subscription manager engine Is there a good opensource service/subscription manager engine that contains things like service dependencies (i.e. if I choose service A, I also need Service B and Service C), subscription types, start and termination etc...
I'm building a site that sells various services and subscriptions and would prefer not to have to write that code as I'm pretty sure it's been done many times over (e.g. in e-commerce sw), but I'd prefer a small library / egine instead of having to integrate with an e-shop.

A: If your "Service" is just Java classes/package/modules then you can use Spring or any other DI container that supports lifecycle hookups.
If by "Service" you mean something big/bloated/enterprise you can also look into OSGI.
But for a small/library engine I suggest you look at plexus and picocontainer.


Q: How do I grab the AR1 estimate and its SE from the gls function in R? I am attempting to get the lag one autocorrelation estimates from the gls function (package {nlme}) with its SE. This is being done on a non-stationary univariate time series. Here is the output:
Generalized least squares fit by REML
  Model: y ~ year
  Data: tempdata
       AIC      BIC    logLik
  51.28921 54.37957 -21.64461

Correlation Structure: AR(1)
 Formula: ~1
 Parameter estimate(s):
      Phi
0.9699799

Coefficients:
                 Value Std.Error    t-value p-value
(Intercept) -1.1952639  3.318268 -0.3602072  0.7234
year        -0.2055264  0.183759 -1.1184567  0.2799

 Correlation:
        (Intr)
year    -0.36

Standardized residuals:
        Min          Q1         Med          Q3         Max
-0.12504485 -0.06476076  0.13948378  0.51581993  0.66030397

Residual standard error: 3.473776
Degrees of freedom: 18 total; 16 residual

The phi coefficient seemed promising since it was under the correlation structure in the output
Correlation Structure: AR(1)
 Formula: ~1
 Parameter estimate(s):
      Phi
0.9699799

but it regularly goes over one, which is not possible for correlation. Then there is the
Correlation:
        (Intr)
Yearctr -0.36

but I was advised that this was likely not a correct estimate for the data (there were multiple test sites so this is just one of the unexpected estimates). Is there a function that outputs an AR1 estimate and its SE (other than arima)?
sample of autocorrelated data:
set.seed(29)
y = diffinv(rnorm(500))
x = 1:length(y)
gls(y~x, correlation=corAR1(form=~1))

Note: I am comparing the function arima() to gls() (or another method) to compare AR1 estimates and SE's. I am doing this under adviser request.


Q: Editing repeating table INfoPath Form in form library? I created repeating table and I added two fields in it.while publishing its not giving me option to edit those properties in my document library...when we generally publish we get the option to edit those properties in document library but its disable while creating repeating table any suggestions how to do that?

A: Check the box to enable editing in SP during your form publish.


Q: Cannot link to libclang in OSX High Sierra I have installed llvm and clang through brew.
When I compile a program with the header file "clang-c/Index.h", I get
Undefined symbols for architecture x86_64:
"_clang_createIndex", referenced from:
  _main in t-c9baef.o
....

Here is the command I used for compiling my program:
CXX=/usr/local/opt/llvm/bin/clang++ CPPFLAGS=-I/usr/local/opt/llvm/include make prog

I am using OSX High Sierra.

A: I have managed to fix the issue.
The command I used for building is:
CXX=/usr/local/opt/llvm/bin/clang++ \
LDFLAGS+='-L/usr/local/opt/llvm/lib \
-L/usr/local/Cellar/llvm/5.0.1/lib -lclang' \
CPPFLAGS=-I/usr/local/opt/llvm/include \
make myprog

I had to link against the libclang.dylib and add -lclang


Q: checkbox onchange not working What am I missing. None of these checkboxes, when checked or unchecked, produces any messages, even if I just past this into a clean html file. It also doesn't work even in an html file where everything else is working fine in terms of the javascript.
Here is the form declaration:
 <form>
 <input type="checkbox" name="all"  id="all" onChange="alert('hi')">
 <input type="checkbox" name="all"  id="all" onClick="alert('hi')">
 <input type="checkbox" name="all"  id="all" onClick="javascript: alert('hi')">
 <input type="checkbox" name="all"  id="all" onclick="alert('hi')">
</form>

None of these work. I also tried radiobuttons, which also don't work. What gives?

A: Check if you have JavaScript disabled in your browser, running this example on jsFiddle does output the alert messages:

To enable JavaScript in Chrome

*

*Click the Chrome menu in the top right hand corner of your browser.

*Select Settings

*Click Show advanced settings

*Under the "Privacy" section, click the Content settings button.

*In the "Javascript" section, select "Allow all sites to run JavaScript (recommended)"

To enable JavaScript in Firefox
Click the Tools drop-down menu and select Options. Check the boxes next to Block pop-up windows, Load images automatically, and Enable JavaScript. Refresh your browser by right-clicking anywhere on the page and selecting Reload, or by using the Reload button in the toolbar.

As the poster mentioned above, if you have any other scripts running somewhere they might be throwing up errors and has nothing to do with JavaScript being disabled.


Q: Material properties databases (BRDF) I am working on a new Ray Tracing project which has to provide highly realistic simulation.
I have a problem with calculating reflection on target. I wanted to use the BRDF (bidirectional reflectance distribution function) model which gives information about diffuse and specular reflection to calculate how much energy was reflected from the target
What I wanted to ask:

*

*I was wondering if there are any databases with measurements of BRDF for different materials (including incoming light direction and outgoing direction) and for different wavelengths of the light source (the most interesting for me is the laser source 800-1600nm)?

*The second thing, do you know any good databases with material properties like: ambient, diffuse, specular, shininess and roughness of surface values.

What I've already found:
http://www.merl.com/brdf/
https://globe3d.sourceforge.io/g3d_html/gl-materials__ads.htm
http://www.cs.columbia.edu/CAVE/software/curet/
https://github.com/POV-Ray/povray/tree/master/distribution/include
But if I understand correctly all of them used a lamp as a light source and I don't see any references to the wavelengths of the light source. Moreover, there aren't any good values of material properties.
I am quite new in this so if you have any advice or I wrote something wrong, I will be grateful for any correction and information connecting with this topic.


Q: Bitrate by default for Audio Recording with MediaRecorder With java class MediaRecorder, you can record audio with encoder AMR NB (4.75 to 12.2 kbps sampled @ 8kHz)
I developed an app for a mobile with Android 2.2 and the bit rate used was 12.2 kbps by default, but I installed the same apk in a mobile with Android 2.3.3 and I think that bit rate changed to 4.75 kbps by default. Is it normal? The mobile used is Nexus One.
The codec lines for this issue are:
mrecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mrecorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
mrecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

I tried to force MediaRecorder to use a specific bitrate with setAudioEncodingBitRate(int bitRate) but it didn´t work.
I don´t understand why bitrate has decreased.

A: setAudioEncodingBitRate(int bitRate) is not decreased, it is working since API 8 (2.2), and some encoding formats and frequencies, like AAC 44,1KHz, only since API 10 (2.3.3) :(


Q: How to define records count to a table that updated only when the table is updated
*

*I want to defint a view (or something else)
that will save a static variable of the table count.
I want this variable to be update only when the table is updated,
this way each time I call the view it will not calculate the count, just return the value.

in the past someone told me that "select count_bit(Id) from table1" will do the job.
is it right?

*

*I want to use the variable in mvc site using entity-framework . How do I do it?

A: Create a separate table to store the count value.
Create insert, update and delete triggers for table1, which calculates the new count and updates the count value.
But do you really need to do this? Are you having performance problems with select count(*) from table1? You know, triggers will slow down all update, delete and inserts a bit.

A: Just use a Select Count to  the  table ,even if you select just a column and count that for your rows or select the the whole table to count the complete table data...put  your count expression after your update is done .


Q: Why isn't xsl:for-each select="" working with this xml file? I am trying to display an xml file with an xsl stylesheet. I just canNOT seem to get it to work.
The feed I'm using is this: http://screamingdeals.tdn.travelscream.com/atom.xml
Here is an abbreviated copy of the xml for it:
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:ts="http://www.travelscream.com">
    <title type="text">Travelscream Deal Alerts</title>
    <updated>2012-08-08T11:09:44-06:00</updated>
    <id>http://screamingdeals.tdn.travelscream.com/</id>
    <link rel="alternate" type="text/html" hreflang="en" href="http://screamingdeals.tdn.travelscream.com"/>
    <link rel="self" type="application/atom+xml" href="http://screamingdeals.tdn.travelscream.com/atom.xml"/>
    <generator uri="http://screamingdeals.tdn.travelscream.com" version="1.0">screamingdeals.tdn.travelscream.com</generator>
    <entry>
        <title>New York City: Best Western President Hotel - $152</title>
        <link rel="alternate" type="text/html" href="http://screamingdeals.tdn.travelscream.com/a477908344.htm"/>
        <id>http://screamingdeals.tdn.travelscream.com/a477908344.htm</id>
        <updated>2012-08-08T11:09:44-06:00</updated>
        <published>2012-08-08T00:00:00-06:00</published>
        <author>
            <name>screamingdeals.tdn.travelscream.com</name>
            <uri>http://screamingdeals.tdn.travelscream.com</uri>
        </author>
        <content type="html" xml:base="screamingdeals.tdn.travelscream.com" xml:lang="en"> <table> <tr> <td valign="middle"> <img width="80" width="60"
            src="http://www.dealbase.com/assets/hotels/photos/000/002/953/icon.jpg"> </td> <td valign="top"> $152/night & up - Best Western President Hotel (New York City, NY) - 46%
            Off Travel Dates: Through Dec 31, 2012 </td> </tr> </table> </content>
        <ts:data>
            <ts:primarykey>477908344</ts:primarykey>
            <ts:location_data>
                <ts:location id="50" selected="0" airport_codes="EWR,JFK,LGA" type="dest">New York</ts:location>
                <ts:location id="55" selected="1" airport_codes="EWR,JFK,LGA" type="dest">New York City</ts:location>
                <ts:location id="199" selected="0" airport_codes="" type="dest">United States</ts:location>
                <ts:location id="288" selected="0" airport_codes="" type="dest">North America</ts:location>
                <ts:location id="524" selected="0" airport_codes="EWR,JFK,LGA,NYC" type="dest">Manhattan</ts:location>
                <ts:location id="525" selected="0" airport_codes="EWR,JFK,LGA,NYC" type="dest">Bronx</ts:location>
                <ts:location id="526" selected="0" airport_codes="EWR,JFK,LGA,NYC" type="dest">Brooklyn</ts:location>
                <ts:location id="527" selected="0" airport_codes="EWR,JFK,LGA" type="dest">Queens</ts:location>
                <ts:location id="528" selected="0" airport_codes="EWR,JFK,LGA" type="dest">Staten Island</ts:location>
                <ts:location id="613" selected="0" airport_codes="" type="dest">SoHo</ts:location>
            </ts:location_data>
            <ts:pkg_attributes>
                <ts:attribute id="3" type="TYPE">Honeymoon</ts:attribute>
                <ts:attribute id="40" type="MAIN">Hotel</ts:attribute>
                <ts:attribute id="62" type="DTYP">City</ts:attribute>
            </ts:pkg_attributes>
            <ts:deal_expires>2012-09-07T14:54:05-06:00</ts:deal_expires>
            <ts:deal_supplier>DealBase.com</ts:deal_supplier>
            <ts:feed_image>http://www.dealbase.com/assets/hotels/photos/000/002/953/icon.jpg</ts:feed_image>
            <ts:fullscreen_image/>
            <ts:price1>15200</ts:price1>
            <ts:alpha>0</ts:alpha>
            <ts:coord>
                <ts:lat>40.7606</ts:lat>
                <ts:long>-73.9864</ts:long>
                <ts:latlong>40.7606,-73.9864</ts:latlong>
            </ts:coord>
            <ts:desc>$152/night & up - Best Western President Hotel (New York City, NY) - 46% Off Travel Dates: Through Dec 31, 2012</ts:desc>
            <ts:tacomm/>
            <ts:direct>true</ts:direct>
            <ts:top>false</ts:top>
            <ts:traveldates>
                <ts:from>01/01/2050</ts:from>
                <ts:to>01/01/2050</ts:to>
            </ts:traveldates>
        </ts:data>
    </entry>
</feed>

the php page that loads up the stylesheet and tells it to transform the xml is coded thusly:
$xp = new XsltProcessor();
// create a DOM document and load the XSL stylesheet
$xsl = new DomDocument;
$xsl->load('deals_stylesheet.xsl');

// import the XSL styelsheet into the XSLT process
$xp->importStylesheet($xsl);

// create a DOM document and load the XML datat
$xml_doc = new DomDocument;
$xml_doc->load('http://screamingdeals.tdn.travelscream.com/atom.xml');

// transform the XML into HTML using the XSL file
if ($html = $xp->transformToXML($xml_doc)) {
    echo $html;
} else {
    trigger_error('XSL transformation failed.', E_USER_ERROR);
} // if

So far...so good. I'm not getting an error.
Here is the xsl file contents:
<?xml version='1.0'?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

    <xsl:template match="/">

                <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
                <title>Facebook Deals Page</title>

                        Title
                        ID

                    <xsl:for-each select="feed/entry">

                            <xsl:value-of select="title"/>
                            <xsl:value-of select="id"/>

                    </xsl:for-each>

    </xsl:template>
</xsl:stylesheet>

And here is a display of it not working: http://www.margaretpickarddesign.com/clients/travelscream/facebook_deals/facebook_rss.php
Looking at the xml structure, the node "feed" is followed by node "entry" which has child nodes "title" and "id". So why isn't it working? What am I missing?

A: Adding comment as an actual answer...
The ts prefixed namespace isn't the problem because you're not accessing any elements in that namespace. The problem is the default namespace (the xmlns with no prefix).
What you need to do is add xmlns:a="http://www.w3.org/2005/Atom" to xsl:stylesheet and use that prefix in your selects. (select="a:feed/a:entry", select="a:title", and select="a:id")
Also note that you can use any prefix, not just "a". The only thing that has to be the same is the namespace itself (http://www.w3.org/2005/Atom).


Q: typeof operator on Folder returns error In a google apps script function, I have a Folder parameter. So, this statement
Logger.log(typeof folder);

logs 'undefined' when the parameter is not supplied, which is right. But when a folder is supplied, I get this error:

Invalid JavaScript value of type $Proxy686. (line 15)

Not able to diagnose why. Need some help. Thanks.
Sanjay
Update: Here is the code reproducing the issue:
function typeOfTest() {

  var folders = DocsList.getAllFolders();
  for (var i = 0; i < folders.length; i++)
    Logger.log(typeof folders[i]);

};

A: In fact. I have the same behavior. I don't know either it is a bug or a feature. A possible workaround is to use the Folder's toString() function. Something like
function typeOfTest() {

  var folders = DocsList.getAllFolders();
  for (var i = 0; i < folders.length; i++)
    Logger.log(folders[i].toString());

};


Q: Find all distinct non negative integers numbers $x,y,w,z,t$ that $x+y+z+t+w=16$. Find all distinct non-negative integers numbers $x,y,w,z,t$ that $x+y+z+t+w=16$.
If they weren't distinct the answer would be $\binom{15}{4}$.For calculating distinct cases I calculate the cases where two are equal then reduce from the main number then calculate cases where three are equal and so on.But it takes a long time.Isn't there an easier solution?

A: $\{x,y,w,z,t\}=\{0,1,2,3,10\}$,
$\{0,1,2,4,9\}$,
$\{0,1,2,5,8\}$,
$\{0,1,2,6,7\}$,
$\{0,1,3,4,8\}$,
$\{0,1,3,5,7\}$,
$\{0,1,4,5,6\}$,
$\{0,2,3,4,7\}$,
$\{0,2,3,5,6\}$ or
$\{1,2,3,4,6\}$.
There are totally $10\times 5!=1200$ solutions.
(If $x,y,w,z,t$ are not necessarily distinct, the number of solutions should be $C_4^{20}$.)
Note: If $x,y,w,z,t$ are distinct positive integers, then $\{x,y,w,z,t\}=\{1,2,3,4,6\}$. There are totally $5!=120$ solutions.


Q: is there any way to add a custom library to jre there are some codes that I use very often in my programs and its kind of annoying to add it to my program every time I'm wondering if there is any way to solve this problem like adding


Q: AttributeError: 'NoneType' object has no attribute 'da' I am calling another program(script2.py) from the script1.py. The script1.py contains a button when i press it, it will start to execute the script2.py. I want to use a variable of script1 in script2. I have tried 2 way to fetch it but giving the error or the empty list. Please help me with this and let me know if any other information is needed. Thank you.
script1.py

class window2:  #i have tried to use d but even the value changes in the __init__function it is giving me a empty list in script2 print function
    d=[]
    def __init__(data):
        self.data=data
        window2.d=data
        data_copy()

def data_copy(): #so created this function to fetch da but giving the following error
    da=window2.d

script2.py

from script1 import data_copy
from script1 import window2

def view():
    print(window2.d) #giving empty list
    print(data_copy().da) #giving error

Error for data_copy:
Traceback (most recent call last):
  File "C:\Users\Desktop\Status\script2.py", line 59, in <module>
    view()
  File "C:\Users\Desktop\Status\script2.py", line 13, in view
    print(data_copy().da)
AttributeError: 'NoneType' object has no attribute 'da'

A: A common reason you have NoneType where you don't expect it is the assignment of an in-place operation on a mutable object. For example:
 mylist = mylist.sort()

The sort() method of a list sorts the list in-place, that is, mylist is modified. But the actual return value of the method is None and not the list sorted. So you've just assigned None to mylist. If you next try to do, say, mylist.append(1),
Python will give you this error.

A: You can try to create a function in the second script which takes your data as an argument and call it in the first script.
from script2 import view

class Window2:
    def __init__(self, data):  # init should take self, it is an instance of class
        self.data = data

window_2 = Window2('some data')  # creating instance

view(window_2.data)  # call function from script2

# script2

def view(data):
    print(data)

# > 'some data'


Q: Python urllib2 does not respect timeout The following two lines of code hangs forever:
import urllib2
urllib2.urlopen('https://www.5giay.vn/', timeout=5)

This is with python2.7, and I have no http_proxy or any other env variables set. Any other website works fine. I can also wget the site without any issue. What could be the issue?

A: If you run
import urllib2

url = 'https://www.5giay.vn/'
urllib2.urlopen(url, timeout=1.0)

wait for a few seconds, and then use C-c to interrupt the program, you'll see
  File "/usr/lib/python2.7/ssl.py", line 260, in read
    return self._sslobj.read(len)
KeyboardInterrupt

This shows that the program is hanging on self._sslobj.read(len).
SSL timeouts raise socket.timeout.
You can control the delay before socket.timeout is raised by calling
socket.setdefaulttimeout(1.0).
For example,
import urllib2
import socket

socket.setdefaulttimeout(1.0)
url = 'https://www.5giay.vn/'
try:
    urllib2.urlopen(url, timeout=1.0)
except IOError as err:
    print('timeout')

% time script.py
timeout

real    0m3.629s
user    0m0.020s
sys 0m0.024s

Note that the requests module succeeds here although urllib2 did not:
import requests
r = requests.get('https://www.5giay.vn/')

How to enforce a timeout on the entire function call:
socket.setdefaulttimeout only affects how long Python waits before an exception is raised if the server has not issued a response.
Neither it nor urlopen(..., timeout=...) enforce a time limit on the entire function call.
To do that, you could use eventlets, as shown here.
If you don't want to install eventlets, you could use multiprocessing from the standard library; though this solution will not scale as well as an asynchronous solution such as the one eventlets provides.
import urllib2
import socket
import multiprocessing as mp

def timeout(t, cmd, *args, **kwds):
    pool = mp.Pool(processes=1)
    result = pool.apply_async(cmd, args=args, kwds=kwds)
    try:
        retval = result.get(timeout=t)
    except mp.TimeoutError as err:
        pool.terminate()
        pool.join()
        raise
    else:
        return retval

def open(url):
    response = urllib2.urlopen(url)
    print(response)

url = 'https://www.5giay.vn/'
try:
    timeout(5, open, url)
except mp.TimeoutError as err:
    print('timeout')

Running this will either succeed or timeout in about 5 seconds of wall clock time.


Q: I'm trying to automatically reload a div after some seconds but it doesn't work in Chrome Here is the Main code. Please check it. what is making this conflict.
<script type="text/javascript">
$(document).ready(function ()
{
  setInterval(function()
  {
    $.get("ajax_files/manage_friend_requests.php", function (result)
    {
      $('#all_friends_requests').html(result); // This is the div i am reloading again and again after some seconds.
          });
        }, 9000);
    });
</script>

A: You should be safer with something like this:
$(document).ready(function(){
    setInterval(function(){
        $.ajax({
            type: "GET",
            url: "ajax_files/manage_friend_requests.php"
        }).done(function(result) {
            var $friends_requests = $('#all_friends_requests');
            if ($friends_requests.length > 0) {
                console.log('Received: '+result);
                $friends_requests.html(result);
                console.log('UPDATED friends requests');
            } else {
                console.log('CANNOT access friends requests container');
            }
        });
    }, 9000);
});

Depending on what the console will display, you will probably put the issue in evidence.


Q: How to submit dropzone js form and django form with one submit button I am using dropzone js to make a form where users can upload information along side images. Dropzone js requires that dropzone has a form with a class of dropzone for the drag and drop image uploads to work, this now leaves me with two forms. The first is the normal input form and the second is the dropzone js form. My question is how can I submit both the dropzone js form and the normal input form with one submit button. Please note I am using html forms, not django crispy forms.
 <form method="POST" enctype="multipart/form-data" id="inputform" name="form1">
       {% csrf_token %}
       <button type="submit" id="add">Save</button>
  </form>

    <form method="POST" enctype="multipart/form-data" id="inputform" name="form1">
    {% csrf_token %}

Title

    <input type="text" name="product_title" id="product_title" placeholder="Give your product a name">

Price

    <input type="text" name="product_price" id="product_price" placeholder="0.00">

Description

    <input type="text" name="product_description" id="product_description" placeholder="Write a description about your product">
    </form>

Images

      <form method="POST"  action="#" class="dropzone col-sm-8 col-lg-8" id="dropzone" name="form2">
        {% csrf_token %}
      </form>

def add(request):
if request.method == "POST":
    title = request.POST.get("product_title")
    price = request.POST.get("product_price")
    description = request.POST.get("product_description")
    print(title,price,description)
return render(request,"main/add.html")

A: You don't need separate form for dropzone. Use first form and give it class name dropzone.
 <form method="POST" enctype="multipart/form-data" id="inputform" name="form1" class="dropzone">
   {% csrf_token %}

Title

    <input type="text" name="product_title" id="product_title" placeholder="Give your product a name">

Price

    <input type="text" name="product_price" id="product_price" placeholder="0.00">

Description

    <input type="text" name="product_description" id="product_description" placeholder="Write a description about your product">
    <button type="submit" id="add">Save</button>
  </form>

PS. In order to submit files you need to have
<input type="file" name="file" />

in your form.


Q: Automate a user assignment to a specific app role within an application I'm automating an app setup and having registered an applicatioin with az ad app create --app-roles with the manifest:
[{
    "allowedMemberTypes": [
      "User",
      "Application"
    ],
    "description": "Read items",
    "displayName": "Reader",
    "isEnabled": "true",
    "value": "items/r"
}]

I'm trying to figure a way to assign above mentioned Reader to a principal without PowerShell's New-AzureADUserAppRoleAssignment and coming up empty. I'd take ARM template, .NET SDK or az CLI way of doing it, but none seem to support it.
Not interested in the portal/ui as I'm trying to script this, any ideas?

A: Just use az cli rest to assign a custom app role to a principal via Azure AD Graph Rest API :
az rest --method post --uri "https://graph.windows.net/<your tenant ID>/servicePrincipals/<your principle object Id>/appRoleAssignments?api-version=1.6" --body "{\"id\":\"<your custom role app ID>\",\"principalId\":\"<your principle object Id>\",\"resourceId\":\"<your app object id>\"}" --headers "Authorization=Bearer <access token>"

You can get access token via az account get access token :
az account get-access-token --resource "https://graph.windows.net"

Test request on Azure cli :

Result, as you can see the role has been assigned to principle successfully  :


Q: Calculating a Sum with case sensitive Picture of the table

{
        "_id" : ObjectId("62f6e11df737d6c2b49b9b9f"),
        "_ID" : 345,
        "name" : "Ron",
        "age" : 25,
        "city" : "Holon",
        "Number_Days_booked" : 2
}
{
        "_id" : ObjectId("62f6e11df737d6c2b49b9ba0"),
        "_ID" : 459,
        "name" : "Ifat",
        "age" : 25,
        "city" : "Holon",
        "Number_Days_booked" : 4
}
{
        "_id" : ObjectId("62f6e11df737d6c2b49b9ba1"),
        "_ID" : 789,
        "name" : "Oren",
        "age" : 26,
        "city" : "ramla",
        "Number_Days_booked" : 3
}
{
        "_id" : ObjectId("62f6e11df737d6c2b49b9ba2"),
        "_ID" : 324,
        "name" : "Gali",
        "age" : 28,
        "city" : "Ramla",
        "Number_Days_booked" : 5
}
{
        "_id" : ObjectId("62f6e11df737d6c2b49b9ba3"),
        "_ID" : 123,
        "name" : "Adi",
        "age" : 34,
        "city" : "Tel_aviv",
        "Number_Days_booked" : 3
}
{
        "_id" : ObjectId("62f6e11df737d6c2b49b9ba4"),
        "_ID" : 456,
        "name" : "Dan",
        "age" : 36,
        "city" : "tel_aviv",
        "Number_Days_booked" : 4
}
{
        "_id" : ObjectId("62f6e11df737d6c2b49b9ba5"),
        "_ID" : 678,
        "name" : "Ronht",
        "age" : 39,
        "city" : "Holon",
        "Number_Days_booked" : 6
}

I am trying to calculate the Sum of Number_days_booked only for Tel Aviv, but I have case sensitivity issue.
I have tried so far ->
db.Customers.aggregate({ $group: { "_id": { $toLower: "$city" }, "count": { $sum: "$Number_Days_booked" } } })

But that produces the sum of all cities and I want to represent only Tel Aviv, how can I do so?

A:         db.Customers.aggregate({
    $group: { "_id": { $toLower: "$city" }, "count": { $sum: "$Number_Days_booked" } } },
{$match:{_id:"tel_aviv"}})

matching at the end did the trick.


Q: Can't make an onClick with Zepto Hello I have a simple HTML page like this:

Test page

The content of script.js is the following:
// Zepto include
...

// My code
var app = app || (function(){
    var _args = {};

    return {
        init : function(Args) {
            _args = Args;
        },
        execute : function() {
            ...
        },
        edit: function() {

            $('body').on('click', function(e){
                alert('aa');
            });

        },
    };
}());

My problem is with this instruction $('body').on('click', function(e){.
I do not understand why.
It do not work.
Anyone to help me ?


Q: How to extract a meta tag from XML/HTML using Linq? I am trying to parse a bit of data from an HTML file, but my Linq statement is not working.  Here is the XML/HTML.  Below, how can I extract the string "41.8;12.23" from the geo.position meta tag?  Thx!!
Here is my Linq
   String longLat = (String)
        from el in xdoc.Descendants()
              where
               (string)el.Name.LocalName == "meta"
               & el.FirstAttribute.Name == "geo.position"
                select (String) el.LastAttribute.Value;

Here is my Xdocument

      <meta content="application/xhtml+xml; charset=utf-8" http-equiv="Content-Type" />
      <meta content="text/css" http-equiv="Content-Style-Type" />
      <meta name="geo.position" content="41.8;12.23" />
      <meta name="geo.placename" content="RomeFiumicino, Italy" />
      <title>RomeFiumicino, Italy</title>

Edit: My query as given returns nothing.  The "inner" query seems to return a list of all the meta elements instead of just the one element I want.
Edit: The following Linq query works against the same XDocument to retreive a table with class name = "data"
    var dataTable =
        from el in xdoc.Descendants()
        where (string)el.Attribute("class") == "data"
        select el;

A: A span around your html tag?
You could do this with XLinq, but it would only support well-formed XML. You might want to look at the HTML Agility Pack instead.
Edit - This works for me:
string xml = "...";
var geoPosition = XElement.Parse(xml).Descendants().
    Where(e => e.Name.LocalName == "meta" &&
        e.Attribute("name") != null &&
        e.Attribute("name").Value == "geo.position").
    Select(e => e.Attribute("content").Value).
    SingleOrDefault();

A: I'd bet that the problem you're having comes from not referencing the namespace correctly with an XmlNamespaceManager.  Here are two ways to do it:
string xml =
        @"

     <meta content=""application/xhtml+xml; charset=utf-8"" http-equiv=""Content-Type"" />
      <meta content=""text/css"" http-equiv=""Content-Style-Type"" />
      <meta name=""geo.position"" content=""41.8;12.23"" />
      <meta name=""geo.placename"" content=""RomeFiumicino, Italy"" />
      <title>RomeFiumicino, Italy</title>

    ";

    string ns = "http://www.w3.org/1999/xhtml";
    XmlNamespaceManager nsm;

    // pre-Linq:
    XmlDocument d = new XmlDocument();
    d.LoadXml(xml);
    nsm = new XmlNamespaceManager(d.NameTable);
    nsm.AddNamespace("h", ns);

    Console.WriteLine(d.SelectSingleNode(
        "/span/h:html/h:head/h:meta[@name='geo.position']/@content", nsm).Value);

    // Linq - note that you have to create an XmlReader so that you can
    // use its NameTable in creating the XmlNamespaceManager:
    XmlReader xr = XmlReader.Create(new StringReader(xml));
    XDocument xd = XDocument.Load(xr);
    nsm = new XmlNamespaceManager(xr.NameTable);
    nsm.AddNamespace("h", ns);

    Console.WriteLine(
        xd.XPathSelectElement("/span/h:html/h:head/h:meta[@name='geo.position']", nsm)
            .Attribute("content").Value);

A: I agree with Thorarin - use the HTML Agility pack, it's much more robust.
However, I suspect the problem you are having using LinqToXML is because of the namespace. See MSDN here for how to handle them in your queries.
" If you have XML that is in a default namespace, you still must declare an XNamespace variable, and combine it with the local name to make a qualified name to be used in the query.
One of the most common problems when querying XML trees is that if the XML tree has a default namespace, the developer sometimes writes the query as though the XML were not in a namespace."


Q: Misinterpreted explanation in book? The text describes "Internal Weak Pull-Ups and Pull-Downs" in the book Microcontrollers From Assembly Language to C Using the PIC24 Family:
"The term weak is used because the resistance is high enough that an
external driver can overpower the pull-up resistor and pull the
current to near ground, producing a 0 input.
The weak pull-up is implemented as a high-resistance P-transistor and
when enabled, the gate of this transistor is 0, turning it on."

I get that a high resistance leads to a weak current output from the resistor. It's the way it is worded that doesn't register based on the previous definition of a pull-up resistor which is simply to ensure that there exists a logic level and not a float, and with the control being dictated by a pushbutton.
How can an external driver [a device that controls high and low output to the input of circuit in question] "overpower" the pull-up resistor? By increasing this current? If that is the case, doesn't V = IR imply that an increase in current increases the voltage? If this is true, how can a 0 input be generated when both scenarios have two different levels of currents flowing, which both take the same path down the pull-up resistor and either to the input, or to ground, based on whether or not the pushbutton was pressed? I am assuming based on my careful analysis of wording that the effect of "pull[ing] the current to near ground, producing a 0 input" can only happen if an external driver "overpowers" the pullup resistor.
Thanks for any help.

A: Like this:

simulate this circuit – Schematic created using CircuitLab
M1 draws all the current from the pull-up, drawing the voltage towards 0.

A: The pull-up is just a resistor connected between input pin and power rail. Weak pull-up is usually equivalent to about 50 kOhm, but sometimes it gets specified in terms of "pull-up current". This resistor pulls the input state to HIGH level, providing a defined state and avoid uncertainty related to manufacturing imperfections.
How an external driver can "overpower" the resistor? Very simple, it just drives whatever it wants, ignoring the resistor, because the resistor is weak (3V / 50k = ~ 60 uA), and the usual external driver is "strong", at least 2 mA. So it overpowers the high level to any level the driver wants. What is the problem here?
The rest of the wording refers to a particular implementation of this weak resistor, in a form of FET, apparently to be able to configure/disable this pull-up if necessary.

A: It sounds like it might just be the terminology that's confusing you. To look at this a different way, imagine a standard pushbutton interface:

When the button is not being pressed, R1 holds the Input node to V+.  When the button gets pressed, the Input node gets shorted to ground.  R1 is large enough that very little current flows through the resistor during this time.
In this case, your textbook might say that the "...button is providing a short-circuit to ground which will overpower the pull-up resistor..."
I hope this helps.  Also, it's a good demonstration of why we choose a large pull-up (or pull-down) resistor.  If the resistance was too small, a large current would flow when the button was pushed!


Q: Property Names of MultiDimensional array I am new to JS. Programmatically I need to find propery names of multidimensional array. Expected Output -  ["name", "position", "salary", etc.]
When I am using map I am getting values of "name" data.map(item => item.name).
var data = [
        {
            "name": "Tiger Nixon",
            "position": "System Architect",
            "salary": "320800",
            "start_date": "2011\/04\/25",
            "office": "Edinburgh",
            "rating": "5421"
        },
        {
            "name": "Garrett Winters",
            "position": "Accountant",
            "salary": "170750",
            "start_date": "2011\/07\/25",
            "office": "Tokyo",
            "rating": "8422"
        },
        {
            "name": "Ashton Cox",
            "position": "Junior Technical Author",
            "salary": "86000",
            "start_date": "2009\/01\/12",
            "office": "San Francisco",
            "rating": "1562"
        },
        {
            "name": "Cedric Kelly",
            "position": "Senior Javascript Developer",
            "salary": "433060",
            "start_date": "2012\/03\/29",
            "office": "Edinburgh",
            "rating": "6224"
        }]

A: Using Object#keys:

const getPropertyNames = (arr = []) => arr.length > 0 ? Object.keys(arr[0]) : [];

const data = [ { "name": "Tiger Nixon", "position": "System Architect", "salary": "320800", "start_date": "2011\/04\/25", "office": "Edinburgh", "rating": "5421" }, { "name": "Garrett Winters", "position": "Accountant", "salary": "170750", "start_date": "2011\/07\/25", "office": "Tokyo", "rating": "8422" }, { "name": "Ashton Cox", "position": "Junior Technical Author", "salary": "86000", "start_date": "2009\/01\/12", "office": "San Francisco", "rating": "1562" }, { "name": "Cedric Kelly", "position": "Senior Javascript Developer", "salary": "433060", "start_date": "2012\/03\/29", "office": "Edinburgh", "rating": "6224" } ];
console.log( getPropertyNames(data) );


Q: Error occurred while trying to connect to db in aws I deployed war file to aws which is spring project. and I installed oracle rds on aws. When I try to connect to oracle rds on aws from my local computer with root-context.xml. It worked. It can connect to oracle rds on aws from my local computer with my spring project. But when I try to run spring war file on aws. http://ip address:8080 it gives me an error message. Would you please help me with this?
I have been struggling with this for three days...any help would be appreciated.
java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection

here is the root-context.xml
<bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="net.sf.log4jdbc.sql.jdbcapi.DriverSpy"></property>

        <property name="url"
            value="jdbc:log4jdbc:oracle:thin:@database ip address on aws:1521:orcl" />
        <property name="username" value="id" />
        <property name="password" value="password" />
    </bean>

aws security inbound setting:
http tcp 80 0.0.0.0/0
custom tcp rule 8080 0.0.0.0/0
custom tcp rule 8080 ::/0
[database setting][1]

[security group][2]

  [1]: https://i.stack.imgur.com/869s0.png
  [2]: https://i.stack.imgur.com/hqaeU.png

A: After trying and trying - created another RDS DB, copying existing one, created another VPC to try it out there are few things that need to be considered (obviously, they are all documented, but it's not an easy task to find all the information, since - at least in my case - it wasn't documented in one place:

*

*If you want your DB instance in the VPC to be publicly accessible, you must enable the VPC attributes DNS hostnames and DNS resolution (existing VPC can be changed too).

*Check the VPC security group and enable the DB access port (in case of the standard MS SQL deployment - 1433) - since starting the 2013, VPC security groups have replaced the RDS security group.

*Check thoroughly the RDS DB information for Security Groups, port and other info that can be misidentified.

*Somehow not obvious (at least for me at first), but when using SQL Management Studio to access the RDS DB - do not use the ":1433" or other port identifier at the end of DB instance name.

*If nothing of the above works, ask the question here and keep googling... :)

Most of the info found here: http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Overview.RDSVPC.html


Q: Design and implement SharePoint 2010 authentication for internet site I am currently trying to design the authentication for internal users and client.
Currently for internal user authenticates using Claim based which used Active Directory.
Question:

*

*Currently for client i create Form Based Authentication. I run aspnet_regsql.exe. Then on choosing the database should i point it to WSS_content or creating new database?

*How i can authenticate internal employee if currently not using internal network?. How I should design this?. So the internal employee still authenticate using Active Directory by entering username and password using login.aspx
Please advise, how should i design this?

A: aspnet_regsql will create a new aspnetdb database.  This database has its own schema, etc. where users reside.  You will need to come up with the application logic (if needed) to create, delete, edit accounts, as well as manage passwords.  There is also a free solution at http://sharepoint2010fba.codeplex.com that takes care of this for you.
You will want to leave Windows (NTLM) authentication on for the zone that you have FBA enabled on.  This will allow users to choose between your FBA login or Windows login.  If you do not like the default auth selector page, you again will need to come up with a custom solution.


Q: Android: updating the screen during computer controlled UI changes I've checked the other questions asked here and didn't succeed in implementing the solutions.  My application uses controls, not drawing on the canvas.  Basically this sums up my issue: -
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    btn1 = (ToggleButton) findViewById(R.id.btn1);
    btn2 = (ToggleButton) findViewById(R.id.btn2);
    btn3 = (ToggleButton) findViewById(R.id.btn2);
    btn4 = (ToggleButton) findViewById(R.id.btn4);
    btn5 = (ToggleButton) findViewById(R.id.btn5);
    btn6 = (ToggleButton) findViewById(R.id.btn6);
    btn7 = (ToggleButton) findViewById(R.id.btn7);
 //blah blah blah
    btn1.requestFocus();
    wait(100);
    btn2.requestFocus();
    wait(100);
    btn3.requestFocus();
    wait(100);
    btn3.setChecked(true);
    wait(100);
    btn4.requestFocus();
    wait(100);
    btn4.setChecked(true);
    wait(100);
    btn5.requestFocus();
    wait(100);
    btn6.requestFocus();
    wait(100);
    btn6.setChecked(true);
    wait(100);
    btn7.requestFocus();
    wait(100);
 //etc
}

The point being the computer animates the moving to a the buttons and checking them so the user can see what it is doing.  So, my issue is, what goes in my wait() method that will pause for 100ms and also update the screen, and the focus?  Any help really appreciated, cheers Jonathan.
Solution applies, thanks Andrew :)
int timerCounterInterval = 0;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    final ToggleButton btn1 = (ToggleButton) findViewById(R.id.btn1);
    final ToggleButton btn2 = (ToggleButton) findViewById(R.id.btn2);
// more btns
    timerCounterInterval = 0; //reset, for each pass of automation
    setFocus(btn1);
    setFocus(btn2);
    setChecked(btn2);
// tidy up
    timerCounterInterval++;
    new Handler().postDelayed(new Runnable() {
        public void run() {
            btn2.clearFocus(); //whatever button that had the focus last
            }
    }, 100*(timerCounterInterval));
// etc - note any code from here will execute *before* the above timer
}

public void setFocus(final ToggleButton btn) {
    timerCounterInterval++;
    new Handler().postDelayed(new Runnable() {
        public void run() {
            btn.setFocusableInTouchMode(true); //eww, messy i know
            btn.requestFocus();
            btn.setFocusableInTouchMode(false);
        }
    }, 100*timerCounterInterval);
}

public void setChecked(final ToggleButton btn) {
    timerCounterInterval++;
    new Handler().postDelayed(new Runnable() {
        public void run() {
            btn.setChecked(true);
        }
    }, 100*timerCounterInterval);
}

Hope this helps other people!

A: I highly suggest you look into the Handle object and in particular the postDelayed method. That way you can keep everything on the UI thread while not causing the thread to actually be tied up in an animate method. This also keeps the Activity from giving that dreaded this-application-is-not-responding message.
In fact, simply wrapping your calls to the control's setters in a runnable and passing them to postDelayed should be enough to update the GUI controls.
[Update]
As an example per your comments you might try something like this. I haven't actually tested this but I think the idea is still there...
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    final ToggleButton btn1 = (ToggleButton) findViewById(R.id.btn1);
    final ToggleButton btn2 = (ToggleButton) findViewById(R.id.btn2);
    // more btns

    Handler handler = new Handler();

    /* tell the handler run these bits after 1 sec, 2 sec, 3 sec, ect... */
    handler.postDelayed(new Runnable() { void run () { btn1.requestFocus(); } }, 1000);
    handler.postDelayed(new Runnable() { void run () { btn2.requestFocus(); } }, 2000);
    handler.postDelayed(new Runnable() { void run () { btn2.setChecked(true); } }, 3000);
}


Q: How to get a notify email with file attatchment , whenever we place new file in shared location? I will explain my requirement here.
We have shared location in Network(like http://emea.com/ABC/Files), Every month some other team folks  will place some excel sheet in that location. we manully check that location and pick up that file.
Requirement is :- whenever A new file will place in that location we need to get email automatically with the latest file attached.
How can i achieve  this in java , or do we have any open source tools for this ,
Please share your thoughts on this :)


Q: Trying to Reach the Apex of an SPD WF My company uses a homegrown Apex (Oracle Application Express) ticketing system to assign internal tickets to our various teams.  My present challenge is to use SharePoint Designer (SPD) to programmatically logon to the ticketing system, and pass the required parameters to it to create a new ticket.
I've tried to setup a database connection in SPD, but it looks like I can only surface read-only data that way (am I wrong?)
If the database connection won't work, how can I build an ECT to hit an Apex database?
If that won't work, is a custom activity my best shot?
Thank you in advance for your help, it's greatly appreciated!!

A: Since what you are trying to accomplish can't be done via a simple web service call (with an authentication method SPD support), a custom workflow action would be the way to go.  Microsoft has a good tutorial on how to create custom workflow actions: http://msdn.microsoft.com/en-us/office365trainingcourse_lab_3_2_topic3.aspx

A: Anything that has to do with a programmatic procedure should be done using a custom workflow, and cannot be solved using SPD. You need to look into doing a custom workflow with Visual Studios. Go here to get you started: http://msdn.microsoft.com/en-us/vstudio/ff623018.aspx


Q: Play Framework 2.2 log output to console in tests How do I configure the logger in Play Framework 2.2 in order that I see log output in the console during play integration tests?
The configuration for Play Framework 2.1 does not work anymore.
BR Rene

A: Update To understand more about how logback is configured you should pass -Dlogback.debug=true property to the jvm/play. This might save you hours of debbugging.
Add a file in test/logback-test.xml (needs to be on classpath so it might depend on how the play application is configured to find tests resources) with a content like
<configuration>

    <conversionRule conversionWord="coloredLevel"
        converterClass="play.api.Logger$ColoredLevel" />

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>${application.home:-.}/logs/application.log</file>
        <encoder>
            <pattern>%date - [%level] - from %logger in %thread
                %n%message%n%xException%n</pattern>
        </encoder>
    </appender>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%coloredLevel %logger{15} - %message%n%xException{5}</pattern>
        </encoder>
    </appender>

    <logger name="play" level="INFO" />
    <logger name="application" level="INFO" />

    <root level="ERROR">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE" />
    </root>

</configuration>

A: I have not done this yet, but you have to configure a logback configuration file. See the play documentation for additional information: http://www.playframework.com/documentation/2.2.x/SettingsLogger
Once you defined a specific logback configuration file, this needs to be placed in the test package, see this issue for details:https://github.com/playframework/playframework/issues/1669#issuecomment-24452132
See message from @benmccann: you can configure the logger in test mode by placing a logback-test.xml in test/resources (took me hours to figure out!).


Q: How to write multiple ArrayList in a text file
In below code , i'm trying to create a txt file and there i want to add some list of values.
So here my approach is create a new file if file is not present and add the respective elements into it.

Please see below , i'm unable to get my expected output, So can you help me with some idea so it will be very helpful
   public class MyTest {

    public static void main(String[] args) throws Exception  {
        // TODO Auto-generated method stub
        SftpConn sftp = new SftpConn();
        //sftp.sftpGetConnect();
        List<String> list =  new ArrayList<>();
        list.add("AAAA");
        list.add("BBBB");
        list.add("CCCC");
        sftp.writeIntoText(list);
        List<String> list1 =  new ArrayList<>();
        list1.add("AAAA1111");
        list1.add("BBBB2222");
        list1.add("CCCC2222");
        sftp.writeIntoText(list1);
    }

    }

 public class SftpConn
      {
    public void writeIntoText(List<String> result) throws Exception
        {
                    connect();
                    List<String> resultdata= result;
                    System.out.println("Result Updated");
                    channelSftp = (ChannelSftp) session.openChannel("sftp");
                    channelSftp.connect();
                    fileOutStream = channelSftp.put("/home/dasrsoum/RM.txt");
                    PrintWriter writer = new PrintWriter(fileOutStream,true);
                    writer.println("------------------");
                    for (String value : resultdata) {
                        writer.println(value+ System.lineSeparator());
                        System.out.println(value);

                    }

            writer.close();
   }

Actual output
 AAAA1111
   BBBB2222
   CCCC2222

Excepted OutPut
  AAAA
  BBBB
  CCCC
  AAAA1111
  BBBB2222
  CCCC2222

A: You first file is overwritten by the second call to the function


Q: Why is Excel warning about user-defined function conflicts with ISFORMULA? Every time I open a particular .XLSB in Office 365 (Excel 2016) I get the following warning.  I did a case-insensitive search of the entire workbook formulas for "isformula" and came up empty.  I checked the VBA editor and find nothing defined there.  I checked Conditional Formatting rules and again came
up with nothing.  Nothing in the Name Manager names, values, or references contains that text.  What else could be prompting this warning?


Q: Sum of an infinite series with continued fractions I'm trying to determine if it is possible to sum an infinite series of the form:
\begin{equation}
\frac{1}{x}+\frac{a}{x^2(x-\frac{a}{x})}+\frac{a^2}{x^2(x-\frac{a}{x})^2(x-\frac{a}{x-\frac{a}{x}})}+\frac{a^3}{x^2(x-\frac{a}{x})^2(x-\frac{a}{x-\frac{a}{x}})^2(x-\frac{a}{x-\frac{a}{x-\frac{a}{x}}})}+\ldots
\end{equation}
where you can see that each successive term can be obtained from the previous one, by multiplying by $a$, squaring one of the terms in the denominator and adding a continued fraction with an extra contribution.
I know how to sum the infinite continued fraction that one gets for the "last" term, but I do not know how could I sum the whole expression, or even if it is possible. I have checked that numerically it converges, at least for a certain range.

A: A simple question unanswered for such a long time. I'm assuming $a,x\in\mathbb{R}$ and $a\neq 0$.
Let $x_0=x$ and $x_{n+1}=x-a/x_n$; then the question asks for $\sum_{n=0}^\infty y_n$, where $y_0=1/x$ and $y_{n+1}=(ay_n)/(x_n x_{n+1})$. But we have $\color{blue}{\sum_{n=0}^m y_n=1/x_m}$ (easy to check using induction on $m$). Hence the given sum converges if and only if the sequence $(x_n)$ converges (and is well-defined).
The latter happens if and only if $\color{blue}{x^2\geqslant 4a}$; this (together with the limit itself) can be deduced from the closed form $x_n=z_{n+2}/z_{n+1}$, where $z_n=(\lambda_1^n-\lambda_2^n)/(\lambda_1-\lambda_2)$ and $\lambda_1,\lambda_2$ are the (possibly complex) roots of $\lambda^2-x\lambda+a=0$; in the case $\lambda_1=\lambda_2=\lambda$ we take $z_n=n\lambda^{n-1}$.

A: Just trying to understand how metamorhy obtained his answer...
we define:
$y_m \equiv \frac{1}{x_m}-\frac{1}{x_{m-1}} \ (0)$
and we show that this definition respects the (recursive) definition of metamorphy:
$y_{m+1}=\frac{y_ma}{x_mx_{m+1}}\ (1)$.
To show Eq. (1) observe that from the definition $(0)$ we obtain:
$\frac{y_{m+1}}{y_m}=\frac{x_m-x_{m+1}}{x_{m-1}-x_{m}} \frac{x_{m-1}}{x_{m+1}} \ (2)$
Substracting the equations $x_{m+1}=x-a/x_m$ and $x_{m}=x-a/x_{m-1}$ we have that $\frac{x_m-x_{m+1}}{x_{m-1}-x_{m}}=\frac{a}{x_mx_{m-1}}$. Substituting this relation in (2) we obtain (1), which is the definition/relation that metamorphy used.
Problem is, here I started from (0) and obtained (1), whereas metamorphy did the opposite. So either he guessed the result ( Eq. (0)), or he followed a different set of manipulations to start from (1), the Eq. that sounds more natural to start with the problem, and obtain (0), which is what makes the sum a telescopic one...


Q: Is there a list of all possible fields for sorting in WooCommerce? I see that it is possible to add your custom field for sorting products in WooCommerce (e.g. this question) Copying from the example:
add_filter( 'woocommerce_get_catalog_ordering_args', 'enable_catalog_ordering_by_modified_date' );
function enable_catalog_ordering_by_modified_date( $args ) {
    if ( isset( $_GET['orderby'] ) ) {
        if ( 'modified_date' == $_GET['orderby'] ) {
            return array(
                'orderby'  => 'modified',  //This is the custom field to be sorted by, and what I am asking for
                'order'    => 'DESC',
            );
        }
    }
    return $args;
}

Is there a list of all fields that I can use for sorting?

P.S. Thanks for the comment, but what I need is not sorting normal posts in WordPress, but the products in WooCommerce.

A: These are the default list of orderby options available( id, title, relevance, rand, date, price, popularity, rating). The case of the switch case may be what you are looking for.
switch ( $orderby ) {
        case 'id':
            $args['orderby'] = 'ID';
            break;
        case 'menu_order':
            $args['orderby'] = 'menu_order title';
            break;
        case 'title':
            $args['orderby'] = 'title';
            $args['order']   = ( 'DESC' === $order ) ? 'DESC' : 'ASC';
            break;
        case 'relevance':
            $args['orderby'] = 'relevance';
            $args['order']   = 'DESC';
            break;
        case 'rand':
            $args['orderby'] = 'rand'; // @codingStandardsIgnoreLine
            break;
        case 'date':
            $args['orderby'] = 'date ID';
            $args['order']   = ( 'ASC' === $order ) ? 'ASC' : 'DESC';
            break;
        case 'price':
            $callback = 'DESC' === $order ? 'order_by_price_desc_post_clauses' : 'order_by_price_asc_post_clauses';
            add_filter( 'posts_clauses', array( $this, $callback ) );
            break;
        case 'popularity':
            add_filter( 'posts_clauses', array( $this, 'order_by_popularity_post_clauses' ) );
            break;
        case 'rating':
            add_filter( 'posts_clauses', array( $this, 'order_by_rating_post_clauses' ) );
            break;
    }

The above code is from woocommerce/includes/class-wc-query.php line 586...

A: You need to know what is inside of an product object. You can sort your products by any of this product data.
Here is a list I found where you can access all the data inside of a product object.
(source: https://wpdavies.dev/how-to-get-all-product-info-in-woocommerce/)
<?php

/**
 *
 *  General Product Data
 *
 */
$product->get_id(); // Returns the unique ID for this object.
$product->get_description(); // Get product description.
$product->get_formatted_name(); // Get product name with SKU or ID. Used within admin.
$product->get_featured(); // If the product is featured.
$product->get_name(); // Get product name.
$product->get_title(); // Get the product's title. For products this is the product name.
$product->get_type(); // Get internal type. Should return string and *should be overridden* by child classes.
$product->get_virtual(); // Get virtual.
$product->get_total_sales(); // Get number total of sales.
$product->get_short_description(); // Get product short description.
$product->get_sku(); // Get SKU (Stock-keeping unit) - product unique ID.
$product->get_slug(); // Get product slug.
$product->get_status(); // Get product status.
$product->get_permalink(); // Product permalink.
$product->get_catalog_visibility(); // Get catalog visibility.

/**
 *
 *  Pricing Data
 *
 */
$product->get_price(); // Returns the product's active price.
$product->get_date_on_sale_from(); // Get date on sale from.
$product->get_date_on_sale_to(); // Get date on sale to.
$product->get_display_price(); // Returns the price including or excluding tax, based on the 'woocommerce_tax_display_shop' setting.
$product->get_price_excluding_tax(); // Returns the price (excluding tax) - ignores tax_class filters since the price may *include* tax and thus needs subtracting.
$product->get_price_html(); // Returns the price in html format.
$product->get_price_html_from_text(); // Functions for getting parts of a price, in html, used by $product->get_price_html.
$product->get_price_html_from_to(); // Functions for getting parts of a price, in html, used by $product->get_price_html.
$product->get_price_including_tax(); // Returns the price (including tax). Uses customer tax rates. Can work for a specific $qty for more accurate taxes.
$product->get_price_suffix(); // Get the suffix to display after prices > 0.
$product->get_sale_price(); // Returns the product's sale price.
$product->get_regular_price(); // Returns the product's regular price.
$product->get_tax_class(); // Returns the tax class.
$product->get_tax_status(); // Returns the tax status.

/**
 *
 *  Image Related Data
 *
 */
$product->get_image(); // Returns the main product image.
$product->get_image_id(); // Get main image ID.
$product->get_gallery_attachment_ids(); // Returns the gallery attachment ids.
$product->get_gallery_image_ids(); // Returns the gallery attachment ids.

/**
 *
 *  Stock or Inventory Data
 *
 */
$product->get_backorders(); // Get backorders.
$product->get_availability(); // Returns the availability of the product.
$product->get_max_purchase_quantity(); // Get max quantity which can be purchased at once.
$product->get_min_purchase_quantity(); // Get min quantity which can be purchased at once.
$product->get_stock_managed_by_id(); // If the stock level comes from another product ID, this should be modified.
$product->get_stock_quantity(); // Returns number of items available for sale.
$product->get_stock_status(); // Return the stock status.
$product->get_total_stock(); // Get total stock - This is the stock of parent and children combined.
$product->get_sold_individually(); // Return if should be sold individually.
$product->get_low_stock_amount(); // Get low stock amount.

/**
 *
 *  Shipping Data
 *
 */
$product->get_height(); // Returns the product height.
$product->get_length(); // Returns the product length.
$product->get_weight(); // Returns the product's weight.
$product->get_width(); // Returns the product width.
$product->get_dimensions(); // Returns formatted dimensions.
$product->get_manage_stock(); // Return if product manage stock.
$product->get_shipping_class(); // Returns the product shipping class SLUG.
$product->get_shipping_class_id(); // Get shipping class ID.

/**
 *
 *  Product Variations / Parent Data
 *
 */
$product->get_child(); // Returns the child product.
$product->get_children(); // Returns the children IDs if applicable. Overridden by child classes.
$product->get_formatted_variation_attributes(); // Get formatted variation data with WC < 2.4 back compat and proper formatting of text-based attribute names.
$product->get_matching_variation(); // Match a variation to a given set of attributes using a WP_Query.
$product->get_parent(); // Get the parent of the post.
$product->get_parent_id(); // Get parent ID.
$product->get_variation_default_attributes(); // If set, get the default attributes for a variable product.
$product->get_variation_description(); // Get product variation description.
$product->get_variation_id(); // Get variation ID.

/**
 *
 *  Product Downloads
 *
 */
$product->get_download_expiry(); // Get download expiry.
$product->get_download_limit(); // Get download limit.
$product->get_downloadable(); // Get downloadable.
$product->get_downloads(); // Get downloads.
$product->get_file(); // Get a file by $download_id.
$product->get_file_download_path(); // Get file download path identified by $download_id.
$product->get_files(); // Same as $product->get_downloads in CRUD.

/**
 *
 *  Attributes, Tags, Categories & Associated Data Objects
 *
 */
$product->get_attribute(); // Returns a single product attribute as a string.
$product->get_attributes(); // Returns product attributes.
$product->get_categories(); // Returns the product categories.
$product->get_category_ids(); // Get category ids.
$product->get_default_attributes(); // Get default attributes.
$product->get_cross_sell_ids(); // Get cross sell IDs.
$product->get_cross_sells(); // Returns the cross sell product ids.
$product->get_related(); // Get and return related products.
$product->get_tag_ids(); // Get tag ids.
$product->get_tags(); // Returns the product tags.
$product->get_upsell_ids(); // Get upsell IDs.
$product->get_upsells(); // Returns the upsell product ids.
$product->get_meta(); // Get Meta Data by Key.
$product->get_meta_data(); // Get All Meta Data.

/**
 *
 *  Ratings and Reviews
 *
 */
$product->get_rating_count(); // Get the total amount (COUNT) of ratings, or just the count for one rating e.g. number of 5 star ratings.
$product->get_rating_counts(); // Get rating count.
$product->get_rating_html(); // Returns the product rating in html format.
$product->get_review_count(); // Get review count.
$product->get_reviews_allowed(); // Return if reviews is allowed.
$product->get_average_rating(); // Get average rating.

/**
 *
 *  Other Product Data
 *
 */
$product->get_changes(); // Return data changes only.
$product->get_data(); // Returns all data for this object.
$product->get_data_keys(); // Returns array of expected data keys for this object.
$product->get_data_store(); // Get the data store.
$product->get_date_created(); // Get product created date.
$product->get_date_modified(); // Get product modified date.
$product->get_extra_data_keys(); // Returns all "extra" data keys for an object (for sub objects like product types).
$product->get_menu_order(); // Get menu order.
$product->get_meta_cache_key(); // Helper method to compute meta cache key. Different from WP Meta cache key in that meta data cached using this key also contains meta_id column.
$product->get_object_read(); // Get object read property.
$product->get_post_data(); // Get the product's post data.
$product->get_post_password(); // Get post password.
$product->get_purchase_note(); // Get purchase note.

With this you can see under "other product data", that there is a date_modified you can order your products by.
It is not directly a list of all fields you can sort by. But it indirectly shows you which fields are available inside a product and what the fields are called. With the name, you are able to access them.
Custom meta:
Unfortunatelly there is no data saved for "published_date". But you could create a custom field for your product post type and save the date inside product. Via the meta key you can than access the data of the product and sort your products by your custom meta data.

A: If the point of the question is whether there is a list that returns all the fields that can be used for sorting, the short answer is no.
The woocommerce_get_catalog_ordering_args filter allows you to add your own ordering args, but there is no list that would store these fields. This filter is used to overwrite args, not to store it as an array.
Within the get_catalog_ordering_args() function, some orderby defaults are statically specified: id, menu_order, title, relevance, rand, date, price, popularity, rating.
But there is no way to tell what values have been added using a filter by WordPress plugins.

Possible solution:
There is a woocommerce_catalog_orderby filter that stores sorting options as an array.
This is used to display sorting options in the view. So you can assume that WordPress plugins will add options to this as well.
/**
 * Add orderby option by plugin
 */
add_filter( 'woocommerce_catalog_orderby', function ( $options ) {
    $options['order_by_plugin'] = __( 'Order by plugin setting', 'text-domain' );

    return $options;
} );

/**
 * Get orderby options
 */
$catalog_orderby_options = apply_filters( 'woocommerce_catalog_orderby', array(
    'menu_order' => __( 'Default sorting (custom ordering + name)', 'woocommerce' ),
    'popularity' => __( 'Popularity (sales)', 'woocommerce' ),
    'rating'     => __( 'Average rating', 'woocommerce' ),
    'date'       => __( 'Sort by most recent', 'woocommerce' ),
    'price'      => __( 'Sort by price (asc)', 'woocommerce' ),
    'price-desc' => __( 'Sort by price (desc)', 'woocommerce' ),
) );

You can use $catalog_orderby_options in which the sorting options are stored, if you only need the orderby fields, use the array_keys() function.
Note: you must specify the default value in apply_filters(), because WooCommerce added these statically, not using add_filter(). So you have to add it statically too.


Q: How to convert database table entry to an enum? In my web application I have many tables which have fixed data, when I use them in my project then I use enums for that purpose.
I want to convert these tables to enums automatically.
After little looking up I did this by using T4, TextTemplates: see my code here.
But I wanted to do this by using Entity Framework, according to the official documentation enums are supported in .NET Framework 4.5 and above, but I am using .NET 3.5.
How can I achieve this, potentially by using custom text templates?

A: So I finally solved it. Made a T4 template and replaced that with the default generated tt file.
My code is here, please star it if you found it helpful and add comments in case of help or suggestions.


Q: Making an image control invert its colors depending on theme I'm trying to work out how to have an Image control in my Windows Phone application invert its colors based on the global background setting (either "Dark" or "Light") chosen by the user in Settings->Themes->Background.

A: There is no built-in way to invert image colors within the framework.
Instead, because of the overhead of doing this on the phone, you should create both versions of the image at design/build time and then choose which version to display from your code by detecting Theme Visibility and Opacity.

A: I must add that what i did in the end was a continuation of what Matt wrote.

*

*create two different images that have different versions of the image (dark and light) and place them in the exact same position

*set their visibility based on the theme resource

the code looks like this:
<Image Height="30" HorizontalAlignment="Center" Margin="0,0,0,220" Name="imgDark" Stretch="Fill" Visibility="{StaticResource PhoneLightThemeVisibility}" VerticalAlignment="Center" Width="30" Source="/MyApplication;component/imageDarkTheme.png" />
<Image Height="30" HorizontalAlignment="Center" Margin="0,0,0,220" Name="imgLoading" Stretch="Fill" Visibility="{StaticResource PhoneDarkThemeVisibility}" VerticalAlignment="Center" Width="30" Source="/MyApplication;component/imageLightTheme.png" />

A: This Question is 1.5 years old now. But here is the easiest way to do what you want. The example given there is very simple like
<Button>
    <Image Stretch="None" Source="{Binding Converter={StaticResource ThemedImageConverter}, ConverterParameter={StaticResource PhoneBackgroundColor} }"
           DataContext="/WP7SampleProject4;component/Images/{0}/appbar.feature.camera.rest.png" />
</Button>


Q: Calling drawnow causes heap corruption I'm still new to Matlab and Simulink and I'm seeing a strange problem.
I have a series of Simulink blocks (processA, processB, etc) which are Matlab functions connected serially. They all have the same format.
function outConfig = run_processA_Fcn(inConfig)

coder.extrinsic('hilite_system');
hilite_system('myModel/processA');
drawnow;

coder.extrinsic('run_processA_mex');
run_processA_mex(inConfig);

hilite_system('myModel/processA', 'none');
drawnow;

outConfig = inConfig;

The function run_processA_mex() is a .mexw64 MEX function which take in pointers to the heap (via inConfig). Inside these MEX functions I am calling my Visual Studio compiled C code (within a DLL).
Each Simulink block could take some time to process, so I wanted it to highlight the current block. The problem is when I call drawnow, the data from my pointers change to some invalid values. The pointers themselves point to the same address, just the values they point to are wrong. If I just comment out the drawnow, my data is okay.
I'm not clear on the best way around this. I don't know why calling drawnow would corrupt my heap. Any help would be great.

A: Okay, this was silly of me. The pointers I was passing were pointing to the heap but they were pointers to pointers. The final data was sitting on the stack, so I was losing that data because of the additional function calls I introduced.
I've properly allocated the data onto the heap now and it seems to be working now.