text:
Q: What is the default file to be visited behind a website? When I open a website's url such as www.stackoverflow.com via curl, which file is actually being visited in the server? I know usually it is index.html. But I cannot find such a convention in the RFC2616 document. How can I know it?
BR

A: The document dilivered by calling a website without a path in the URL is configured by the webserver. So you have no standard there. Is a users joice.
Curl will download the file the webserver is delivering him, or follow the redirect (if -L option is given) when webserver responses a redirect.

A: There is no way for the client to know how the data for the HTTP response was generated. It might not even be related to a specific file.
The last time I wrote a significant bit of server side code, everything outside of /static/ was routed (via mod_rewrite) though a FastCGI program that got its data from a few different controller libraries, a dozen database schema libraries, a database and a dozen template files.
The WWW is built on links between URLs, not files. Don't worry about files if you are writing client code.

A: It's not necessarily index.html, and you can't actually know that it could be anything depending on the Server Configuration, for instance in Apache you can change the directory index to the one that suits you
DirectoryIndex home.php

in this case the default file accessed is home.php
in IIS you can take a look about default index and how to change it
but the defaults are
in Apache
index.php (usually: depending on the server configuration)
index.html (is the default that comes with a fresh install)

in IIS
Default.htm
Default.asp
Index.htm
Index.html
Iisstart.htm


text:
Q: gcc error: expected '=', ',', 'ASM', or '__attribute__' before 'dequeue' I am very new to C and could not resolve my issue looking through some of the past threads on this compile error.
This is my code:
#include <stdio.h>
#include <stdlib.h>

struct PCB{
/*various data fields within the PCB structure*/
/*in this implementation just ID is included*/
int ID;
struct PCB *next;
struct PCB *prev;
}typedef PCB;

void enqueue(PCB **pntrHN, PCB **pntrTL, PCB passedPCB);
PCB dequeue(PCB **pntrHN, PCB **pntrTL);
void print_queue(PCB **pntrTL);
int size_of_queue(PCB **pntrTL);
void clear_queue(PCB **pntrHN, PCB **pntrTL);

int main(int argc, char * argv[])
{
PCB **headOfQueue;
PCB **tailOfQueue;
PCB pcbNode;

headOfQueue = malloc(sizeof(PCB*));
tailOfQueue = malloc(sizeof(PCB*));
*headOfQueue = 0;
*tailOfQueue = 0;
for(i=0; j<100; j++)
{
    PCB temp;
    temp.ID = rand()%30000+20001;
    enqueue(headOfQueue,tailOfQueue,temp);
}

print_queue(tailOfQueue);
int size = size_of_queue(tailOfQueue);
printf("Size of queue: %d\n", size);
clear_queue(headOfQueue, tailOfQueue);
size = size_of_queue(tailOfQueue);
printf("Size of queue now: %d\n", size);
return(0);
}
/*enqueue is here*/
PCB dequeue(PCB **pntrHN, PCB **pntrTL)
{
PCB *tempHead; /*temp var for new head*/
PCB returnVal;

if((*pntrHN)->next !=0){
printf("nodes next is not 0");
exit(0);
}
if(*pntrHN == 0){
printf("dequeued an empty queue");
exit(0);
}
if(*pntrTL == 0){
printf("dequeued empty queue");
printf("head is not zero but tail is");
exit(0);
}
returnVal = **pntrHN; /*get data for return*/

if(*pntrHN == *pntrTL){
*pntrTL = 0;
tempHead = 0;
}else{
tempHead = (*pntrHN)->prev; /*get new head*/
tempHead ->next = 0;
}
free(*pntrHN); /*free old head*/
*pntrHN = tempHead; /*set class attribute to new tail*/
return returnVal;
}

void clear_queue(PCB **pntrHN, PCB **pntrTL)
{
PCB holder;
if(*pntrTL != 0){
    while(*pntrHN != 0){
        (*pntrHN)->prev = *pntrHN;
        holder = dequeue(**pntrHN, **pntrTL);
    }
}
}
}

Is my syntax alright? I really can't tell where I went wrong right now. I'm using notepad++ and gcc via ssh.

A: Update your structure as
typedef struct {
   /*various data fields within the PCB structure*/
   /*in this implementation just ID is included*/
   int ID;
   struct PCB *next;
   struct PCB *prev;
}PCB;

1.
In function main:<br/>
undefined reference to enqueue
undefined reference to print_queue
undefined reference to size_of_queue
undefined reference to size_of_queue

2. Change
for(i=0; j<100; j++)

to
for(j=0; j<100; j++)

and declare j;
As per syntax
change dequeue(**pntrHN, **pntrTL); to dequeue(pntrHN, pntrTL);

redpajama_set_name: RedPajamaStackExchange


text:
Q: About a definition of an algebra over a field $K$ I'm reading page 122 of Amann's Analysis I.

A $K$-vector space $\mathcal{A}$ together with an operation
$$
\mathcal{A} \times \mathcal{A} \rightarrow \mathcal{A}, \quad(a, b) \mapsto a \odot b
$$
is called an algebra over $K$ if the following hold:

*

*A1: $(\mathcal{A},+, \odot)$ is a ring.

*A2: The distributive law holds:
$$
\begin{aligned}
&(\lambda a+\mu b) \odot c=\lambda(a \odot c)+\mu(b \odot c) \\
&a \odot(\lambda b+\mu c)=\lambda(a \odot b)+\mu(a \odot c)
\end{aligned}
$$
for all $a, b, c \in \mathcal{A}$ and $\lambda, \mu \in K$.

For the ring multiplication $\odot$ in $\mathcal{A}$, we again write $a b$ instead of $a \odot b$. This leads to no misunderstanding since it is always clear from context which multiplication is intended. This notation is also justified by the distributive laws which hold in $\mathcal{A}$. In general, the algebra (that is, the ring $(\mathcal{A}, \odot)$ ) is neither commutative nor contains a unity element.

My understanding: Because $(\mathcal{A},+, \odot)$ is a ring, we already have $(\lambda a+\mu b) \odot c = (\lambda a) \odot c + (\mu b) \odot c$. Then the distributive law A2 can be reduced to
$$
(\lambda a) \odot c= a \odot ( \lambda c) =\lambda(a \odot c)
$$
for all $a, c \in \mathcal{A}$ and $\lambda\in K$.

Could you confirm if my understanding is correct?


text:
Q: Unable to click radio button even after using explicit wait on selenium I am trying to select 'Female' Radio Button in the webpage
import time
import selenium.common.exceptions
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Chrome(executable_path="C:\Drivers\chrome\chromedriver.exe")
driver.get("https://fs2.formsite.com/meherpavan/form2/index.html?1537702596407")

wait = WebDriverWait(driver, 60)
element = wait.until(EC.element_to_be_clickable((By.ID, "RESULT_RadioButton-7_1")))
driver.execute_script("arguments[0].click();",element)
#element.click()

#driver.find_element_by_id("RESULT_RadioButton-7_1").click()
print(driver.find_element_by_id("RESULT_RadioButton-7_0").is_selected())
print(driver.find_element_by_id("RESULT_RadioButton-7_1").is_selected())

Error:
C:\Users\kkumaraguru\PycharmProjects\pythonProject\venv\Scripts\python.exe C:/Users/kkumaraguru/PycharmProjects/SeleniumProject/RadioButtons.py
Traceback (most recent call last):
  File "C:\Users\kkumaraguru\PycharmProjects\SeleniumProject\RadioButtons.py", line 14, in <module>
    element = wait.until(EC.element_to_be_clickable((By.ID, "RESULT_RadioButton-7_1")))
  File "C:\Users\kkumaraguru\PycharmProjects\pythonProject\venv\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:

Process finished with exit code 1

A: It seems that it times out waiting for an element with ID RESULT_RadioButton-7_1 to be present on the page. I'd open the page yourself to make sure such element is present. You can do this using javascript in the browser's console: document.getElementById("RESULT_RadioButton-7_1"). If this doesn't work then try to debug through the code, and check what HTML Selenium is looking at to make sure is what you expect.

A: You can do that using JS intervention, Also make sure to maximize the windows size like below :
driver = webdriver.Chrome(driver_path)
driver.maximize_window()
driver.implicitly_wait(30)
driver.get("https://fs2.formsite.com/meherpavan/form2/index.html?1537702596407")

#time.sleep(5)
element = driver.find_element(By.ID, "RESULT_RadioButton-7_1")
driver.execute_script("arguments[0].click();", element)


text:
Q: Share content to whats app using html jquery ON LOAD I am working on content sharing to what's app on window load event. But it is not redirecting to below url:
"whatsapp://send?text=Mytextwriteenhere-http://someurl.com"
Below is my code which is already taken from stack over flow:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script><script>
$(document).ready(function () {
    var isMobile = {
        Android: function () {
            return navigator.userAgent.match(/Android/i);
        },
        BlackBerry: function () {
            return navigator.userAgent.match(/BlackBerry/i);
        },
        iOS: function () {
            return navigator.userAgent.match(/iPhone|iPad|iPod/i);
        },
        Opera: function () {
            return navigator.userAgent.match(/Opera Mini/i);
        },
        Windows: function () {
            return navigator.userAgent.match(/IEMobile/i);
        },
        any: function () {
            return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
        }
    };
    if (isMobile.any()) {
        var text = "yyyyyyyy";
        var url = "http://google.com";
        alert(text);
        var message = encodeURIComponent(text) + " - " + encodeURIComponent(url);
        var whatsapp_url = "whatsapp://send?text=" + message;
        document.location.replace(whatsapp_url);
        // window.location.href = whatsapp_url;
    } else {
        var text = "yyyyyyyy";
        var url = "http://google.com";
        alert(text);
        alert("Please share this article in mobile device");
        window.close();
    }
});


text: Q: sql exception: " Sql anywhere error:  has the row in  locked"? sql exception: " Sql anywhere error:  has the row in  locked" ? I have also used commit/rollback in the end of every procedure where  is used. I have to restart the server everytime to release the locks.


text:
Q: Get content of first 5 rows and echo them Here I have written query for this. Query is correct but dont know why it does not echo anything:
$sql3= mysqli_query($con,"select post from facebook_posts where p_id >  (select MAX(p_id) - 5 from facebook_posts);");
while ($row = @mysql_fetch_array($sql3))
{
    echo $row['post'];
    echo '
';

}

Table has data already. When I test query in mysql it gives 5 row content;

A: First you use mysqli library for query and then you try to use mysql to fetch a row.
mysql and mysqli are different libraries. You should use only one of them. Since mysql is deprecated, you should use mysqli from these two.

A: You are mixing up the mysqli_* and mysql_* functions. The mysql_fetch_array function cannot fetch any results when you executed the query with mysqli_query. You shouldn't be using the mysql_* functions anymore since they are deprecated.
Also, if you want to limit your results in MySQL, you can use the LIMIT-clause instead of calculating a maximum/minimum id.
If you change your code into the following, it should work.
$result = mysqli_query($con,"select post from facebook_posts where p_id >  (select MAX(p_id) - 5 from facebook_posts)");
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
  echo $row['post'];
  echo '
';
}

For more information about fetching results using mysqli, you can look here.


text:
Q: Transform Xml content in a table I have one table with a field that contains a XML content and I would to transform this XML content in a table where each tag would be a column.
Does Anyone know how to do that?

A: You need to know the tags in advance, but you can then use XMLTABLE for this, eg if table table_with_employee_xml has a column xml_col, as per below
<employees>
  <employee>
    <empno>7369</empno>
    <ename>SMITH</ename>
    <job>CLERK</job>
    <hiredate>17-DEC-1980</hiredate>
  </employee>
  <employee>
    <empno>7499</empno>
    <ename>ALLEN</ename>
    <job>SALESMAN</job>
    <hiredate>20-FEB-1981</hiredate>
  </employee>
  ...
  ...

select x.*
from   table_with_employee_xml e,
       xmltable('/employees/employee'
         passing e.xml_col
         columns
           empno     varchar2(4)  path 'empno',
           ename     varchar2(10) path 'ename',
           job       varchar2(9)  path 'job',
           hiredate  varchar2(11) path 'hiredate'
         ) x;

A: You can use the following code:
CREATE TABLE EDMU_XML (
  id        NUMBER,
  xml_data  XMLTYPE
);

insert into EDMU_XML values (1,'<employees>
  <employee>
    <empno>1</empno>
    <ename>EDMU1</ename>
    <job>SALESMAN</job>\
  </employee>
  <employee>
    <empno>2</empno>
    <ename>EDMU2</ename>
    <job>MANAGER</job>
  </employee>
  <employee>
    <empno>3</empno>
    <ename>EDMU3</ename>
    <job>MANAGER</job>
  </employee>
  <employee>
    <empno>4</empno>
    <ename>EDMU4</ename>
    <job>ANALYST</job>
  </employee>
</employees>');

CREATE TABLE EDMU_NORMAL AS
SELECT xt.*
FROM   EDMU_XML x,
       XMLTABLE('/employees/employee'
         PASSING x.xml_data
         COLUMNS
           empno     VARCHAR2(4)  PATH 'empno',
           ename     VARCHAR2(10) PATH 'ename',
           job       VARCHAR2(9)  PATH 'job'
         ) xt;

Demo


text:
Q: Grammatical Implications in "Opportunity" and "Possibility" Usage
a.1) You have the opportunity to go to Norfolk next month.
  a.2) *There is the opportunity of your going to Norfolk next month.
b.1) *You have the possibility to go to Norfolk next month.
  b.2) There is the possibility of your going to Norfolk next month.

How are these two words different in their own usage to refer to future events when they are used in sentences like those shown above?
Searching on Google would prove that a.1) and b.2) are grammatical, but a.2) and b.1) are not. If so, why?

A: First and foremost, all four of those sentences are in fact grammatically correct. What Google demonstrates is that a.2 and b.1 are really awkward and therefore much less common.
In terms of the implications of the words themselves:
Opportunity often implies that it is an offer being extend or provided to you by a specific entity or person who is providing you with means or privilege otherwise unavailable to you. Sometimes there is no other party offering the opportunity, but there is always the sense of urgency, that it is a limited time deal, something that must be seized or it will be lost. There is generally a positive connotation: an opportunity is a good thing, something to be excited about.
Possibility simple implies that it is something that can happen, either because you decide to make it happen or because circumstances cause it to happen. There is no implicit positive or negative connotation here. There is also no implicit implication of the likelihood of the event happening. If it is possible, it may or may not happen.
In general, opportunities imply possibility, but not the other way around. If you are given the opportunity to go to Norway, then of course it is possible. But if you lived within driving distance of Norway, you wouldn't usually refer to your possibility of driving there at any moment as an "opportunity".
Some examples:

There is a distinct possibility that I may lose my job next week, but I have been given the opportunity to work at an exclusive Swedish design firm, so I'm not too bummed.
I really needed to talk to my professor. He was a busy man, so this was nearly impossible, but I happened to see him walking alone one day, so I seized the opportunity.

Interestingly, this Ngram suggests that in fact the usage of "opportunity to go" and "opportunity of going" have reversed in the last 200 years, with both being approximately equal in use around AD 1890-1900.

A: Although opportunity and possibility have similar meaning, they are quite different by usage and grammar:

*

*Possibility conveys a meaning that something might be true (both currently or in the future). It is used with  of or that:

There is a possibility that our project will fail;
  There is a possibility of project failure;

Note the former is a complete sentence but latter is a bare noun.

*

*Opportunity conveys a meaning that it is possible for someone to accomplish some goal (because of the luck or changed circumstances). It is used with a verb phrase:

After graduation, I will have an opportunity to find a good job;

Compare:

Despite the possibility of storms, I decided to take an opportunity to go to islands.

Note that opportunity usually means what someone is trying to accomplish, while possibility is just a matter or randomness.

A: I would word your example sentences slightly differently. Specifically, I'd be more inclined to use an indefinite article, and I'd probably use the prepositional phrase of you going in lieu of of your going. Thus:

a.1) You have an opportunity to go to Norfolk next month.
   a.2) *There is an opportunity of you going to Norfolk next month.
b.1) *You have a possibility to go to Norfolk next month.
   b.2) There is a possibility of you going to Norfolk next month.

With that said, your hunch is correct about how possibility and opportunity should be used. Possibilities are more impersonal, and describe circumstances; opportunities are tied to something positive for an individual. One might say that people live among possibilities, but they have opportunities. So, I might write:

There's a possibility I will get a new job.

or:

I have an opportunity to get a new job.

but I wouldn't swap those words in that context.


text:
Q: LIKE query compatible with SQLite and PostgreSQL I am trying to make a LIKE query work in my SQLite in development and PostgreSQL in production (Heroku) without using an if-else statement for either environment. If-else statement doesn't seem like a viable option.
My answer right now was based off the solution provided here: Generic Ruby solution for SQLite3 "LIKE" or PostgreSQL "ILIKE"?
This is what my course model looks like:
class Course < ApplicationRecord
  has_many :enrollments
  has_many :users, through: :enrollments

  has_many :course_subjects
  has_many :subjects, through: :course_subjects

  def self.search(search)
    where("lower(name) LIKE lower(?)", "%#{search}%")
  end
end

How can I structure my LIKE query to be compatible with both SQLite and PostgreSQL?

A: If I may suggest something, it would be adviseable to have the same DBs in all the environments, so that you are later able to have Postgresql-SQL parts in your code (for optimisation purposes and the like).

A: Using Arel is an easy fix to this problem:
def self.search(search)
    Course.where(Course.arel_table[:name].matches("%#{search}%"))
end


text:
Q: Dropdownlilst DropDownList1_SelectedIndexChanged in gridview not working in asp.net Dropdownlist list is not working in my following grid.I want to change label text when  drop downlist changed dropdownlisth the label text is not working

         <asp:TemplateField HeaderText="sup_rec_id">
      <ItemTemplate>
        <asp:Label runat="server"    ID="lblFirstLastName"  Text='<%# Eval("sup_rec_id") %>'></asp:Label>
      </ItemTemplate>
    </asp:TemplateField>

     <asp:TemplateField HeaderText="Quantity">
      <ItemTemplate>
        <asp:Label runat="server"    ID="quantity"  Text='<%# Eval("quantity") %>'></asp:Label>
      </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Code">
      <ItemTemplate>
        <asp:Label runat="server"    ID="code"  Text='<%# Eval("code") %>'></asp:Label>
      </ItemTemplate>
    </asp:TemplateField>
          <asp:TemplateField HeaderText="Action">
      <ItemTemplate>
 <asp:DropDownList ID="DropDownList1" runat="server"
     AutoPostBack="true" EnableViewState="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
        <asp:ListItem>A</asp:ListItem>
        <asp:ListItem>B</asp:ListItem>
        <asp:ListItem>C</asp:ListItem>
        <asp:ListItem>D</asp:ListItem>
    </asp:DropDownList>

      </ItemTemplate>
    </asp:TemplateField>

     </Columns>
    </asp:GridView>
    </div>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

filename.Aspx.cs
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    Label1.Text = "Test text";
}

Guide me what i do?


text:
Q: Paste values from one Google Sheet to another and remove duplicates based on ID column I have a similar situation to the one described on this question: two worksheets, with input data coming into the Feed sheet using the importxml function and a Data sheet where new rows get copied thanks to a script set to run daily.
However, the current script is creating daily duplicates. As such, I would like to adapt the answer provided on the question above so that the script checks the IDs on column F and only copies the rows with new IDs.
How should I update the section below that creates a hash to one that looks for the IDs on column F instead? Also my rows are consistent, so is it correct to assume I can just remove the relevant code lines towards the end?
The sample Google Sheet is available here.

function appendUniqueRows() {
  var ss = SpreadsheetApp.getActive();
  var sourceSheet = ss.getSheetByName('Get Data');
  var destSheet = ss.getSheetByName('Final Data');

  var sourceData = sourceSheet.getDataRange().getValues();
  var destData = destSheet.getDataRange().getValues();

  // Check whether destination sheet is empty
  if (destData.length === 1 && "" === destData[0].join('')) {
    // Empty, so ignore the phantom row
    destData = [];
  }

  // Generate hash for comparisons
  var destHash = {};
  destData.forEach(function(row) {
    destHash[row.join('')] = true; // could be anything
  });

  // Concatentate source rows to dest rows if they satisfy a uniqueness filter
  var mergedData = destData.concat(sourceData.filter(function (row) {
    var hashedRow = row.join('');
    if (!destHash.hasOwnProperty(hashedRow)) {
      // This row is unique
      destHash[hashedRow] = true;   // Add to hash for future comparisons
      return true;                  // filter -> true
    }
    return false;                   // not unique, filter -> false
  }));

  // Check whether two data sets were the same width
  var sourceWidth = (sourceData.length > 0) ? sourceData[0].length : 0;
  var destWidth = (destData.length > 0) ? destData[0].length : 0;
  if (sourceWidth !== destWidth) {
    // Pad out all columns for the new row
    var mergedWidth = Math.max(sourceWidth,destWidth);
    for (var row=0; row<mergedData.length; row++) {
      for (var col=mergedData[row].length; col<mergedWidth; col++)
        mergedData[row].push('');
    }
  }

  // Write merged data to destination sheet
  destSheet.getRange(1, 1, mergedData.length, mergedData[0].length)
           .setValues(mergedData);
}

I'm a novice in this world of Google Apps scripts, so do please let me know if I'm missing any crucial information. Thanks in advance for the help.

A: *

*You want to copy the values from "Feed" sheet to "Data" sheet.

*When the values are copied, you want to copy only new values which are not included in "Data" sheet.

*You want to choose the new values using the values of column "F".

If my understanding for your question is correct, how about this modification? In this modification, I modified the script in your shared spreadsheet.
Modification points:

*

*In your script, all values of "Feed" sheet are copied to "Data" sheet. So in order to choose only new values, I used the following flow.

*

*Retrieve the values from column "F". This is used for choosing the new values.

*Retrieve the new values using the values from column "F".

*Put the new values to "Data" sheet.

The script which reflected above flow is as follows.
Modified script:

From:

This is your script in the shared spreadsheet. Please modify this script to below one.
function Copy() {
  var sss = SpreadsheetApp.openById('#####'); // this is your Spreadsheet key
  var ss = sss.getSheetByName('Feed'); // this is the name of your source Sheet tab
  var range = ss.getRange('A3:H52'); //assign the range you want to copy
  var data = range.getValues();
  var tss = SpreadsheetApp.openById('#####'); //replace with destination ID
  var ts = tss.getSheetByName('Data'); //replace with destination Sheet tab name
  ts.getRange(ts.getLastRow()+1, 1,50,8).setValues(data);// 49 value refers to number of rows, 8 to columns
}

To:

function Copy() {
  var sss = SpreadsheetApp.openById('#####'); // this is your Spreadsheet key
  var ss = sss.getSheetByName('Feed'); // this is the name of your source Sheet tab
  var range = ss.getRange('A3:H52'); //assign the range you want to copy
  var data = range.getValues();
  var tss = SpreadsheetApp.openById('#####'); //replace with destination ID
  var ts = tss.getSheetByName('Data'); //replace with destination Sheet tab name

  // Below script was added.
  var values = ts.getRange("F3:F").getValues().filter(String);
  var copiedValues = data.filter(function(e) {return !values.some(function(f){return f[0] == e[5]}) && e.filter(String).length > 0});
  ts.getRange(ts.getLastRow() + 1, 1, copiedValues.length, copiedValues[0].length).setValues(copiedValues);
}


text:
Q: Mosfet driver ir2301s I try to implement brushless motor driver using IR2301s driver. I start with testing the driver without MOSFET's. Here is scheme:

In datasheet for IR2301s given this picture:

If I understood correctly I expect to see oscillating on LO if there is oscillating signal on LIN and unconnected HIN, VS. I got it. But when I send oscillating signal on HIN while LIN and VS are unconnected I don't see oscillating on HO. THere is stable 6 V on HO. Input signal amplitude is 3.3 V. I've tried to change VCC up to 12 V, change capacity of C1 and C4 from 1uF to 100uF without luck. Where I am mistaken?

A: Here is the block diagram: -

Without connecting Vs to 0V and Vb to +V you will see nothing on HO


text:
Q: How do you access params[:model][:field] in Rails 4? From what I understand...

*

*If you have a form_for @model, params[:model] is available when the form is submitted. Furthermore, if the form has 2 attributes attr1 and attr2, params[:model][:attr1] and params[:model][:attr2] are available when the form is submitted.

*In Rails 4, you're supposed to write a method model_params that says params.require(:model).permit(:attr1, :attr2).

*You'd then use model_params like so: Model.new(model_params).

However, what do you do if you only need one of the fields from the form? Like if you only needed params[:model][:attr1]?
Example:
def create
  @user = User.new(user_params)
  if @user.save
    # need access to params[:user][:password] here
    redirect_to root_url, :notice => "Signed up!"
  else
    render :new
  end
end

private

    def user_params
        params.require(:user).permit(:email, :password, :password_confirmation)
    end

A: The gem responsible for this behaviour is strong_parameters. The permit() method decides what to pass on to the model based on the attributes you pass to it.
In your case, you passed it :attr1 and :attr2:
params.require(:model).permit(:attr1, :attr2)

This means the model will have attr1 and attr2 set to whatever values were passed from the form.
If you only wanted to set attr1, just remove attr2 from the permit() call.
params.require(:model).permit(:attr1)

You model will not have attr1 set, but not attr2. It's that simple.
You can even permit everything (not recommended) by calling permit! with a bang and no arguments.
You can read more about this behaviour on the gem's Github project page.
Update based on the OP's edit
If you need access to params[:user][:password] in the controller... well, you just accessed it in your example. You accessed it by typing params[:user][:password].
Nothing prevents you from accessing the params hash directly. strong_parameter's job is to prevent you from mass assigning a hash to a model, that's all.


text:
Q: Where should I run the function if I only want it to execute once @foreach($data as $row)
@php
App\Http\Livewire\Teamusers::edit($row->id,$row->user_id,$row->team_id);
@endphp
{{--call edit() function from teamusers component--}}
<input type="text"  wire:model = "username"  class="bg-transparent">
<input type="text" wire:model = "email" value="{{$row->email}}" class="bg-transparent" >

   <select value="team" wire:model = "team" class="bg-transparent" >
      @if($row->name == 'Fieldwork')
      <option value="1" selected>Fieldwork</option>
      <option value="2">Labs</option>
      @endif
      @if($row->name == 'Labs')
      <option value="1" >Fieldwork</option>
      <option value="2" selected>Labs</option>
      @endif
   </select>

   <select value="role" class="bg-transparent" wire:model = "role">
      @if($row->role == 'management')
      <option value="management" selected>management</option>
      <option value="general">general</option>
      @endif
      @if($row->role == 'general')
      <option value="management" >management</option>
      <option value="general" selected>general</option>
      @endif
   </select>

   <button type="button" wire:click="edit({{ $row->id }},{{ $row->user_id }})" class="mr-3 text-sm bg-blue-500 hover:bg-blue-700 text-white py-1 px-2 rounded focus:outline-none focus:shadow-outline">Save</button>
   <button type="button" class="text-sm bg-red-500 hover:bg-red-700 text-white py-1 px-2 rounded focus:outline-none focus:shadow-outline">Delete</button>

@endforeach

edit.php
public function edit($id,$user_id,$team_id)
    {

        $user = Teamuser::findOrFail($id);
        $real = User::findOrFail($user_id);
        $third = Team::findOrFail($team_id);
        $this->username = $real->name;
        $this->email = $real->email;
        $this->team = $third->name;
        $this->role = $user->role;

    }

The edit() function binds the data to the columns in for each loop. But as a result, it keeps refreshing everytime.

What should i do if i still want the data binding but without the refreshing?

A: Did you tried to use .defer on your livewire model data binding ? This will makes your component not real time and will only submit your data when you click on save button.
Does it help you ?


text:
Q: Show the component at first time to the website in angular angular project: show the video only at first time, when the cookie created, then it should be hidden.
Already I tried with ng-show ng-if ....
<div ng-hide="about-video">

and at component.ts
ngOnInit(){
}

there are many sites shows video while entering first time(component initialization) but later hidden them
Want to know how they achieved it

A: The idea of using a cookie is ok, but local storage is a better solution for you problem.
Juste create a boolean in your component, set it to false.
Then in your ngOnInit read the cookie, if notPresent or contain false then set your boolean to true.
export class SomeComponent implements OnInit{
    showVideo:boolean = false

    ngOnInit(){
        this.showVideo = window.localStorage.getItem('showIntroVideo') !== 'true';
        if(!this.showVideo){
            window.localStorage.setItem('showIntroVideo', 'true');
        }
    }
}

And in your template :
<ng-container *ngIf="showVideo">
    <!-- your video goes there -->
</ng-container>


text:
Q: How to create JPA Specification join between entities I would like to create filter based on JPA Specification. I'm using spring-data.
My entites:
public class Section {

    /*some other fields*/

    @OneToMany
    @JoinTable(
            name = "section_objective",
            joinColumns = @JoinColumn(name = "section_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "objective_id", referencedColumnName = "id")
    )
    private List<Objective> objectives;

}

public class Objective {

    /*some other fields*/

    @OneToMany
    @JoinTable(
            name = "objective_question",
            joinColumns = @JoinColumn(name = "objective_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "question_id", referencedColumnName = "id")
    )
    private List<Question> questions = new ArrayList<>();
}

public class Question {

    /*some fields, below code is not important*/

}

Entity dependencies are: Section - one to many -> Objective - one to many -> Question
Entities do not have information about parent relationship (ex. I cannot go from Question to Objective the question is assigned to in Java code).
I have a Question filter class that converts to Specification. I would like to get all questions in section.
Normally I would use SQL query I've written below to get all questions in Section.
SELECT q.*
FROM
  question q
JOIN
  objective_question oq ON oq.question_id = q.id
JOIN
  objective o ON o.id = oq.objective_id
JOIN
  section_objective so ON so.objective_id = o.id
JOIN
  section s ON s.id = so.section_id
WHERE
  s.id IN (1,2);

I've tried creating specification with Join, but don't know how to create join when the reference to Objective on Question is not available.
Specification.<Question>where((root, query, criteriaBuilder) ->
        root.join("section") /*throws error because **section** is not a part of attribute on Question */
                .in(List.of(1L, 2L)));

A: You may use the following library: https://github.com/turkraft/spring-filter
It will let you run search queries such as:

/search?filter= average(ratings) > 4.5 and brand.name in ('audi', 'land rover') and (year > 2018 or km < 50000) and color : 'white' and accidents is empty

You can also run search queries even if you don't have an API, the library basically compiles a search input to JPA predicates or to Specification if you desire so. It will smoothly handle all your join queries without having to worry about the well known n+1 query problem.
You may build specifications as follows:
import static com.turkraft.springfilter.FilterBuilder.*;
Specification<Section> spec = new FilterSpecification<Section>(
  and(
    in("id", numbers(1, 2, 3)),
    equal("objectives.questions.field", "some value")
  )
);
// basically telling: get the sections which have id 1, 2 or 3, AND which have the field 'field' of the objectives questions' equal to 'some value'

You don't need to configure anything, just import the dependency:
<dependency>
    <groupId>com.turkraft</groupId>
    <artifactId>spring-filter</artifactId>
    <version>1.0.2</version>
</dependency>


text:
Q: How to collect code coverage with Istanbul when executing HTTP endpoints via Postman or Karate I have a JS project that provides a set of endpoints leveraging Express with a typical express/router pattern.
const express = require('express');
const router = new express.Router();

router.post('/', async (req, res, next) => { });
router.get('/:abc', async (req, res, next) => { });

module.exports = router;

I can successfully start the server with npm start which calls node ./src/index.js and makes the endpoints available at https://localhost:8080
I can also successfully test these endpoints utilizing a tool like Postman or automation like Karate.
The problem i'm having is that I can't seem to collect code coverage using Istanbul when exercising the product source JS through http://localhost:8080.
I've tried npm start followed by nyc --all src/**/*.js gradlew test.  The latter being automation that tests the endpoints.  This results in 0% coverage which i'm assuming was due to not running nyc with npm start.
Next I tried nyc --all src/**/*.js npm start and noticed some coverage, but this was just coverage from starting the Express server.
Next I tried nyc --all src/**/*.js npm start followed by gradlew test and noticed the code coverage results were the same as when no endpoint tests were run.
Next I tried putting the prior two commands into a single JS script(myscript.js) running each asynchronously wherein the Express server was started before the gradle tests started running and ran nyc --all src/**/*.js myscript.js.  The results from this were the same as my previous trial wherein only npm start received code coverage.
Next I tried nyc --all src/**/*.js npm start followed by nyc --all src/**/*.js -no-clean gradlew test and noticed the code coverage results were the same as when no endpoint tests were run.
Next I tried all of the attempts above by wrapping them into package.json scripts and running npm run <scriptName> getting the same exact behavior.
Finally I tried nyc instrument src instrumented/src --compact=false followed by npm run start:coverage wherein this start:coverage script calls the instrumented index.js at node ./instrumented/src/index.js followed by gradlew test followed by nyc report --reporter=lcov.  This attempt also failing to produce any additional code coverage from the gradlew endpoint tests.
Doing some research online I came across this post
How do I setup code coverage on my Express based API?
And thought this looks eerily similar to my problems.  Eg Istanbul doesn't know how to cover code when exercising the code through executing endpoints.
I decided to still post this as the above post is quite a bit old and wanted to get opinions and see if there is a better solution than
https://github.com/gotwarlost/istanbul-middleware
EDIT
Adding more specifics about how we start the Express server and run automation without Istanbul today.  Just to clarify what we're working with and automation tools we're invested in. (Mainly Karate and Java)
/*
  calls --> node -r dotenv/config src/index.js
*/
npm start

/*
  calls --> gradlew clean test
  this effectively calls a tool called Karate
  Karate's base url is pointed to: https://locahost:8080
  Karate tests execute endpoints on that base url
  This would be akin to using Postman however Karate has quite a bit of configuration options
  https://github.com/intuit/karate
*/
npm test

A: Through many hours of investigation we've managed to solve this.  Prior project posted by @balexandre has been updated to illustrate how to do this.
https://github.com/kirksl/karate-istanbul

A: As said on the comments, you never start your server to run the tests... the tests will point to your server when you require the server file.
in my example, I'm running mocha with chai and the chai-http package helps to call the server
server.js
const app = require("express")();

// everything else ...

exports.server = app;

in your end-to-end tests, you can easily have:
const chai = require('chai');
const chaiHttp = require('chai-http');
chai.use(chaiHttp);

const server = require("./server.js").server;

...

it("should calculate the circumference", done => {
    chai
       .request(server) // <-- attach your server here
       .get('/v1/circumference/10')
       .end((err, res) => {
         expect(res.status).to.be.eql(200);
         expect(res.type).to.be.eql('application/json');
         expect(res.body.result).to.eql(62.83185307179586);
         done();
       });
    });
});

I've made a very simple project and pushed to GitHub so you can checkout and run everything, in order to see how all work together
GitHub Project

Added
I've added a route so it can show the coverage report (I used the html report) and created a static route to it ...
when you run the coverage npm run coverage it will generate the report inside ./report folder and a simple express route pointed to that folder, will enable one to see it as an endpoint.

commit info for such change


text: Q: Images not loading for lastpass in Chrome In my Google Chrome. I have the lastpass plugin installed but it does not load the images. You can see this in action in this screen recording: http://youtu.be/RllVrSiPKvM


text:
Q: Issue with Memcached with session storing Today i had to move to MemcacheD because of php7* .ver
after installing Memcached pecl for php7 i tried to store my session to Memcached but i saw it will take too much longer than default session store ( files )
Page load without Sess. Memcached < 200 ms
Page load with Sess. Memcached ABOVE 5 sec
And the problem is only with session ! i tried to store other datas in memcached and retrieved them asap without any lag or so.
My MemcacheD setting is:
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="512"
OPTIONS="-l 127.0.0.1"

And my Pecl PHP Memcached Setting ( shown in phpinfo too ) is:
extension=memcached.so

session.save_handler=memcached
session.save_path="localhost:11211"

[memcached]
memcached.sess_locking = On
memcached.sess_lock_wait_min = 1000;
memcached.sess_lock_wait_max = 2000;
memcached.sess_lock_retries = 10;
memcached.sess_lock_expire = 0;
memcached.sess_prefix = "memc.sess.key."
memcached.sess_persistent = Off
memcached.sess_consistent_hash = On
memcached.sess_remove_failed)
memcached.sess_remove_failed_servers = Off
memcached.sess_number_of_replicas = 0
memcached.sess_binary_protocol = On
memcached.sess_randomize_replica_read = Off
memcached.sess_connect_timeout = 1000
memcached.sess_sasl_username = NULL
memcached.sess_sasl_password = NULL
memcached.compression_type = "fastlz"
memcached.compression_factor = "1.3"
memcached.compression_threshold = 2000
memcached.serializer = "igbinary"
memcached.store_retry_count = 2
memcached.default_consistent_hash = Off
memcached.default_binary_protocol = Off
memcached.default_connect_timeout = 0

+ I checked with session_write_close() and the result was the same so i assume its not session lock problem
And the php is running with FPM unix socket if it is relevant
regards

A: Problem was fixed by updating libmemcached 1.0.16 to 1.0.18 manually since the yum repos only had 1.0.16
With update now session store use memcached asap without any delay.
regards


text:
Q: Translating a piece of Java code to Haskell I am solving the Baby Blocks problem. I have a peice of java code that I want to translate to Haskell:
Java:
for (int i = 1; i <optHeight.length ; i++) {
    int maxHeightIndex = 0;
        for (int j = i-1; j >=0 ; j--) {
            // Need help from here
            if(boxes[j].width>boxes[i-1].width && boxes[j].depth>boxes[i-1].depth) {
                if(optHeight[maxHeightIndex]<optHeight[j+1]) { <-- How do I write this condition
                    maxHeightIndex = j+1;
                }
            }
        }
        optHeight[i]=optHeight[maxHeightIndex] + boxes[i-1].height;
}

where optHeight is a 1-D array and boxes is an object consiting of height, width, depth as data members. In Haskell, it is just a list of list. Due to lack of mutable arrays / variables, I am totally helpless.
Haskell:
b list = do
 forM_ [1..length list] $ \i -> do
  let maxHeight = 0
  forM_ [0..(i-1)] $ \j  -> do
   if list!!j!!1 > list!!i-1!!1 && list!!j!!2 > list !!j!!2 then
    maxHeight = j + 1

PS: I am totally a beginner in Haskell

A: This problem can be solved in a very readable way by composing very simple functions to find the overall solution. A possible strategy is as follows:

*

*Take all the available blocks and declare them as an initial set of towers.

*Combine each tower with each available block (if possible). This results in a new set of towers.

*Repeat step 2 until the set of towers does not change anymore.

*Extract the tower of the set which is the highest.

The corresponding code is as follows (explanation below):
type Block = (Int,Int,Int)
type Tower = [Block]

babyBlocks :: [Block] -> Int
babyBlocks blocks = highest $ converge allBlocks initialTowers
    where allBlocks = possibleBlocks blocks
          initialTowers = map (:[]) allBlocks

possibleBlocks :: [Block] -> [Block]
possibleBlocks = concatMap (\(w,d,h) -> [(w,d,h),(w,h,d),(d,h,w)])

canStack :: Block -> Block -> Bool
canStack (w1,d1,_) (w2,d2,_) = w2 < w1 && d2 < d1 || w2 < d1 && d2 < w1

expand :: Tower -> [Block] -> [Tower]
expand tower@(top:_) = map (:tower) . filter (canStack top)

converge :: [Block] -> [Tower] -> [Tower]
converge blocks towers | null newTowers = towers
                       | otherwise = converge blocks newTowers
    where newTowers = concatMap (flip expand blocks) towers

height :: Tower -> Int
height = sum . map (\(_,_,h) -> h)

highest :: [Tower] -> Int
highest = maximum . map height

*

*babyBlocks : This function generates all possible blocks for the given block types (by rotating them), converts them into an initial tower set (by wrapping them into simple list with one element) and starts the convergence of the initial tower set into a final tower set.

*possibleBlocks : For a given set of block types, this function returns all possible blocks by rotating them. Strictly, there should be 3! = 6 rotations (all permutations of the three coordinates), but we only need to consider half of them because we can treat rotations with swapped widths and depths as duplicates.

*canStack : Checks if a given block can be placed onto another block.

*expand : For a given tower, the function checks all the available blocks if they can be put on the top of the tower. A new tower is created for each compatible block that can be put on top.

*converge : This function essentially repeats expand for a set of towers until no more block can be put on one of them. The solution must be the maximum height of the remaining towers.

*height : Returns the height of a given tower by summing up its block heights.

*highest : For a given set of towers, identifies the maximum height.

A: The way to solve this problem (I think), is to consider every rotation of every box (so you have 3n total rotations). Then, you order these based on increasing size of their base. The problem then is just to pick the longest subsequence of boxes that "fit" with each other (you don't need to worry about picking the same box twice because a box could never fit on itself). This sounds a lot like the canonical longest increasing subsequence problem, which suggests we will want a dynamic programming solution. We will have an array of length 3n where the ith element represents the maximum height of the stack you can make with the ith box at the top.
maxHeight(i) = { height(i) + max[ maxHeight(j) ] such that
                 width(j) > width(i), depth(j) > depth(i), 0 <= j < i }

Now, lets get started on the Haskell solution. I will assume your input is a list of the dimensions. Notice how closely the code mirrors the solution I described - the trick is to write things declaratively.
import Data.List (sortOn)
import Data.Vector (fromList, (!), generate)
import Data.Ord (Down(..))

babyBlocks :: [(Int,Int,Int)] -> Int
babyBlocks blocks = maxHeights ! (3*n - 1)
  where
    -- get the number of blocks
    n = length blocks

    -- generate the `3n` blocks formed by rotating the existing blocks,
    -- sort them by their base size, and store them in a vector for
    -- fast retrieval
    sortedBlocks = fromList
                 . sortOn (\(x,y,z) -> Down (x*y))
                 . concatMap (\(x,y,z) -> [(x,y,z),(y,z,x),(z,x,y)])
                 $ blocks

    -- we'll make ourselves a couple helper functions, just so
    -- our translation of the recurrence relation looks better
    height n    = let (_,_,z) = sortedBlocks ! n in z
    width n     = let (_,y,_) = sortedBlocks ! n in y
    depth n     = let (x,_,_) = sortedBlocks ! n in x
    maxHeight n = maxHeights ! n

    -- state the dynamic programming
    maxHeights = generate (3*n) (\i ->
                   height i + maximum (0 : [ maxHeight j | j<-[0..(i-1)]
                                                         , width j > width i
                                                         , depth j > depth i ]))

The part you seemed to be having trouble with is the dynamic programming in the last part. Because Haskell is lazy, it is actually completely OK for me to use maxHeight while defining maxHeights, even if I don't know what order my vector is going to be initialized in!


text:
Q: Semi direct product group Suppose $G=V \rtimes M$, is a semi product group of an elementary abelian p-group of size $|V|=p^e$ and $M$
is a subgroup of $G$. If $f$ is the natural projection from $G$ onto $M$.
$C_x=\{x^G\}$ is a conjugacy class.
I would like to prove $|f^{-1}(m)\cap C_x|\geq p, m\in M$. Do you think such result is true?
Best regards
Ha.

A: In general it is false.  Let $M$ be abelian and act trivially on $V$.  Then $G$
is just the product of $M$ and $V$ so $G$ is commutative.  Then $C_x$ contains only one element.


text:
Q: Is there any way to find out general form of proper 2 by 2 matrix? 2 x 2 orthogonal matrix $A$ is called proper if detA=1.  I know this is a rotation matrix through an angle, and entries of this matrix is composed of $\sin$ and $\cos$.
If you are only given the fact that $2\times 2$ matrix is proper matrix, can I still
find out the general form of this matrix?  If so, how?

A: Suppose that $A = \begin{bmatrix} a & b \\ c & d \end{bmatrix}$ and $A$ is orthogonal.
Then the rows (and columns) are orthogonal and unit length. So $a^2 + b^2 =1$. So that $(a,b)$ lies on the unit circle. Thus $a = \cos(\theta)$ and $b = \sin(\theta)$ for some angle $\theta$. Likewise $a^2+c^2=1$ so $c^2=1-a^2=1-\cos^2(\theta)=\sin^2(\theta)$. Thus $c=\pm \sin(\theta)$. Likewise, $d=\pm \cos(\theta)$.
Suppose that $c = +\sin(\theta)$, then we need $ac+bd=0$ so $\sin(\theta)\cos(\theta)\pm\sin(\theta)\cos(\theta)=0$. Thus $d=-\cos(\theta)$.
Otherwise, $c=-\sin(\theta)$ and we'll need to have $d=\cos(\theta)$.
This leaves us with two options:
$A = \begin{bmatrix} \cos(\theta) & \sin(\theta) \\ \sin(\theta) & -\cos(\theta) \end{bmatrix}$ or $A = \begin{bmatrix} \cos(\theta) & \sin(\theta) \\ -\sin(\theta) & \cos(\theta) \end{bmatrix}$
The first option has $\mathrm{det}(A)=-\cos^2(\theta)-\sin^2(\theta)=-1$ while the second has $\mathrm{det}(A)=\cos^2(\theta)+\sin^2(\theta)=1$.
So every "proper" $2 \times 2$ orthogonal matrix must look like $A = \begin{bmatrix} \cos(\theta) & \sin(\theta) \\ -\sin(\theta) & \cos(\theta) \end{bmatrix}$ for some $\theta$.
$$A = \begin{bmatrix} \cos(\theta) & \sin(\theta) \\ -\sin(\theta) & \cos(\theta) \end{bmatrix} = \begin{bmatrix} \cos(-\theta) & -\sin(-\theta) \\ \sin(-\theta) & \cos(-\theta) \end{bmatrix} = \begin{bmatrix} \sin(\pi/2-\theta) & -\cos(\pi/2-\theta) \\ \cos(\pi/2-\theta) & \sin(\pi/2-\theta) \end{bmatrix} = \mbox{etc.}
$$


text:
Q: how pass $index of ng-repeat to another ng-repeat in Angularjs I want show a json in 2 select in angularjs.
For this, I get below json from server:
$scope.bolouks:
{
  "dbId": 1,
  "boloukCode": "1-11-1",
  "north":  "...",
  "west":  "...",
  "radifs": [
    {
      "dbId": 1,
      "description": "...",
      "price": 698000
    },
    {
      "dbId": 2,
      "description":  "...",
      "price": 604000
    },
  ]
}

I want show first part of this json in a select and show radifs in other select.
For this, I try below code, but I'm not successful to manage second select:
<select ui-select2 name="bolouk" class="ui-select2" ng-model="br.bolouk" required ng-options="bolouk.dbId as bolouk.boloukCode for bolouk in bolouks">
   <option value=""></option>
 </select>
<select ui-select2 name="radif" class="ui-select2" ng-model="br.radif" ng-change="br.radif" required ng-options="radif.dbId as radif.description for radif in bolouks[br.bolouk].radifs">
  <option value=""></option>
</select>

I want use $index of bolouks in second select (ng-repeat="radif in bolouks[$index].radifs"), but it's not correct. How can I pass index of bolouks to second select?

A: Only ng-repeat supports $index, not ng-options
The simplest way to cascade your selects is to simply set your ng-model as the selected "bolouk" and then have the second select run off the selected "bolouk's" "radifs".
<select ui-select2 name="bolouk" class="ui-select2" ng-model="br.bolouk" required ng-options="bolouk.boloukCode for bolouk in bolouks">
   <option value=""></option>
 </select>
<select ui-select2 name="radif" class="ui-select2" ng-model="br.radif" ng-change="br.radif" required ng-options="radif.dbId as radif.description for radif in br.bolouk.radifs">
  <option value=""></option>
</select>

Here's a fiddle showing something similar

A: You should use chosen Model from the first select and use it in the second select.
For example:
<div ng-controller="MyCtrl">
    <select ng-model="firstChoise" ng-options="item as item.name for item in complexArray"></select>

    <select ng-model="secondChoise" ng-options="item for item in firstChoise.array"></select>
</div>

function MyCtrl($scope) {
    $scope.complexArray = [
        {name: "A", array: ["A1", "A2", "A3"]},
        {name: "B", array: ["B1", "B2", "B3"]},
        {name: "C", array: ["C1", "C2", "C3"]}
    ];
}

This is JSFiddle with working example.


text:
Q: Can't seem to get Scipy curve_fit Sigmoid to work in Python There are a few posts about this and normally the answer is to have a good initial guess and bounds. I've played around with it for a while and cannot find a configuration that produces any sort of curve.
import numpy as np
array1 = np.array(column1).astype(float)
array2 = np.array(column2).astype(float)
print(array1)
print(array2)

Output:
[18.7327  9.3784  6.6293 20.8361 11.2603 19.3706  5.4302 10.1293 13.7516
8.0567 16.8688  4.969   3.94   19.4793 11.7527 13.2811 13.338   0.5944
7.4406 11.2338  6.2283  3.4818 10.1056 16.2689 22.442  18.7345  5.2605
5.6405 12.7186 18.2497  5.4315 14.2651 16.7544 12.9192 13.5955 10.9256
5.7798  8.4485  8.5229 11.879   6.5271 10.3376  7.781  31.4558  8.0236
2.3527 10.8926 16.1995 11.1924 25.8071 13.9692 20.7791 10.3045 12.2833
7.4066 15.9807 11.4462 15.1504  5.9021 19.1184]
[83.85 52.45 41.2  92.59 62.65 86.77 30.63 53.78 73.34 48.55 82.53 28.3
23.87 90.99 62.95 68.82 71.06 20.74 45.25 60.65 39.07 21.93 53.35 79.61
93.27 85.88 28.95 32.73 65.89 83.51 30.74 75.22 79.8  67.43 71.12 58.41
35.83 49.61 50.72 63.49 40.67 55.75 46.49 96.22 47.62 21.8  56.23 76.97
59.07 94.67 74.9  92.52 55.61 63.51 41.34 76.8  62.81 75.99 36.34 85.96]
import pylab
from scipy.optimize import curve_fit

def sigmoid(x, a, b):
     y = 1 / (1 + np.exp(-b*(x-a)))
     return y

popt, pcov = curve_fit(sigmoid, array1, array2, p0 = [5,20], method='dogbox', bounds=([0, 20],[40, 100]))
print(popt)

x = np.linspace(0, 35, 50)
y = sigmoid(x, *popt)

pylab.plot(array1, array2, 'o', label='data')
pylab.plot(x,y, label='fit')
pylab.ylim(0, 100)
pylab.legend(loc='best')
pylab.show()

Output:
Graph
As you can see it just not doing anything at all. Would really appreciate any help on this to get a rough sigmoid curve. Doesn't need to be super accurate.
Many Thanks.

A: In your case, the problem wasn't a good initial guess, but an inappropriate model. Note how your sigmoid cannot be larger than 1, yet your data is in the range of ~10 - 100.
xs = np.linspace(0, 15)
as_ = np.linspace(0, 5, num=10)
bs_ = np.linspace(0, 5, num=10)
for a in as_:
    for b in bs_:
        plt.plot(xs, sigmoid(xs, a, b))

Therefore, you either have to modify your model to accept a scaling parameter, or scale down your data to a range your model can fit. Here's the two solutions:
Preamble
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import pandas as pd

array1 = np.array([18.7327,9.3784,6.6293,20.8361,11.2603,19.3706,5.4302,10.1293,13.7516,8.0567,16.8688,4.969,3.94,19.4793,11.7527,13.2811,13.338,0.5944,7.4406,11.2338,6.2283,3.4818,10.1056,16.2689,22.442,18.7345,5.2605,5.6405,12.7186,18.2497,5.4315,14.2651,16.7544,12.9192,13.5955,10.9256,5.7798,8.4485,8.5229,11.879,6.5271,10.3376,7.781,31.4558,8.0236,2.3527,10.8926,16.1995,11.1924,25.8071,13.9692,20.7791,10.3045,12.2833,7.4066,15.9807,11.4462,15.1504,5.9021,19.1184])
array2 = np.array([83.85,52.45,41.2,92.59,62.65,86.77,30.63,53.78,73.34,48.55,82.53,28.3,23.87,90.99,62.95,68.82,71.06,20.74,45.25,60.65,39.07,21.93,53.35,79.61,93.27,85.88,28.95,32.73,65.89,83.51,30.74,75.22,79.8,67.43,71.12,58.41,35.83,49.61,50.72,63.49,40.67,55.75,46.49,96.22,47.62,21.8,56.23,76.97,59.07,94.67,74.9,92.52,55.61,63.51,41.34,76.8,62.81,75.99,36.34,85.96])
df = pd.DataFrame({'x':array1, 'y':array2})
df = df.sort_values('x')

Scaling data to match parameter
def sigmoid(x, a, b):
    y = 1 / (1 + np.exp(-b*(x-a)))
    return y

popt, pcov = curve_fit(sigmoid, df['x'], df['y'] / df['y'].max(), p0 = [5,20], method='dogbox', bounds=([0, 0],[40, 100]))

plt.plot(df['x'], df['y'] / df['y'].max(), label='data')
plt.plot(df['x'], sigmoid(df['x'], *popt))

popt is [8.56754823 0.20609918]

Adding new parameter to function
def sigmoid2(x, a, b, scale):
    y = scale / (1 + np.exp(-b*(x-a)))
    return y

popt, pcov = curve_fit(sigmoid2, df['x'], df['y'], p0 = [5,20, 100], method='dogbox', bounds=([0, 0, 0],[40, 100, 1E5]))

plt.plot(df['x'], df['y'], label='data')
plt.plot(df['x'], sigmoid2(df['x'], *popt))

popt is array([ 8.81708442,  0.19749557, 98.357044  ])


text:
Q: Redirecting audio output I need a method to redirect my Mac's audio output to a different computer on the same network as the Mac doesn't have audio output. I'm on Snow Leopard while the other computer which has speakers attached does not have any operating system at the moment.

A: Probably the simplest solution is to use Rogue Amoeba's Nicecast. It can hijack system audio and stream it locally so you can pick it up on another machine with any MP3 player that supports streams.

A: What's the software source of the audio?  If the audio source is iTunes, there are a few things you can do specifically dealing with the support for Airport Express hardware.  If you don't wish to spend more money on Team Apple, then the Enlightenment Sound Daemon runs on pretty much any hardware (Linux, OS/X, or Windows/Cygwin).
There's a quick tutorial here.  It uses Rogue Audio's Hijack; looks like someone's recommended another Rogue Audio project as well.  I'm a fan of Airfoil from them, as it lets me stream Pandora to the Airport Express in the main room.


text:
Q: MySQL Wrong Restore Data Recovery I'm almost certain about the answer, but the situation is so critical that I have to ask this question even though I'm %99 sure about the answer.
Someone in our office made a backup of a MySQL database and he restored it on a wrong destination database overwriting everything on that destination (The schema of both databases were the same). According to the structure of the MySQL backup files I know that the restore operation drops all the tables first and then creates them and fills them up with the backed up data. The question is does the restore module keeps the old data anywhere? Is there anyway of retrieving any of the old data? (logs?.. etc.)

A: Only if you have replicated slaves, or you used to, and have binary logs. Even then you'd need an old copy of the database you can restore, and to configure replication again.


text:
Q: Finding an orthonormal basis of the space of all functions in P2 that are orthogonal to $f(t) = t$.
Consider the space P2 with inner product
  $$
\frac 12 \int_{-1}^1 f(t)g(t)\,dt
 $$
  Find an orthonormal basis of the space of all functions in P2 that are orthogonal to $f(t) = t$.

I'm trying to figure out the basis for W. If we solve $\int_{-1}^1 t(at^2 + bt + c)dt = 0 $ we get:
$$\frac a4 + \frac b3 + \frac c2 - (\frac a4 - \frac b3 + \frac c2) = 0 $$
This gives us
$$ \frac {2b}3 = 0$$
So W includes all the functions in P2 where b = 0. I'm still struggling to get to the last step, find an orthonormal basis. W -> (1, 0, 1) * (a, b, c).
EDIT: This gives us a basis of 1 and x^2. Doing grahm schmidt we get:
$$v1 = 1 $$
$$ v2 = x^2 - \frac {<x^2, 1>}{<1, 1>} * 1$$
Integrating for $<x^2, 1>$ we get $\frac 23$ this gives us $x^2 - \frac 23$
So our orthonormal basis is:
$ 1 $ and $ x^2 - \frac 23$

A: $P2$ is not a sufficiently "standard" notation to use without explanation.  I would suspect that the polynomials of degree $\le 2$ are meant here, but you should go to your instructor (or the source of the problem) to clarify this.
Assuming the polynomials of degree $\le 2$ are meant, you should calculate
$$ \int_{-1}^1 t (a_0 + a_1 t + a_2 t^2)\; dt$$
to see what is the condition on the coefficients $a_0$, $a_1$ and $a_2$ needed for such a polynomial to be orthogonal to $t$.

A: You are integrating with limits $-1$ and $+1$; if the function is an odd function this would result in zero. Which polynomials $g(t)$ of degree at most 2, would make $tg(t)$ an odd function?
Those with $tg(t)$ having no $t^2$ term would fit the bill. This translates to  $g(t)$ be of the form $a+bt^2$,; so the two functions $g_0(t)\equiv1$ and $g_1(t)=t^2$ which are linearly independent  form a basis (as this has to be a proper subspace of $P_2$, a 3-dimensional vector space, they should be all). But their inner product is not zero. So they do not form an orthogonal  basis.  But now you can try out integrating $a+bt^2$ and find the answer.

A: You have already had
$$
W=\{at^2+bt+c\mid b=0,a,c\in\mathbb{R}\}=\{a\cdot t^2+c\cdot 1\mid a,c\in\mathbb{R}\}\tag{1}
$$
Note that $W$ is a vector space. Here are the simpler related questions you should try

*

*Do you know what it means by a basis for $W$?

*By looking at (1), can you identify a basis for $W$?

*Once you have a basis of $W$, do you know how to turn it to an orthonormal one?

There seems to be confusion about a vector in $P_2$ and its coordinate with respect to some basis. I assume here that $P_2$ means the set of real polynomials with degree at most $2$. Considers the basis $\{1,t,t^2\}$ for $P_2$, then $(1,0,1)$ is the coordinate of the vector $1+t^2$. It is not an element of $P_2$, but the vector $1+t^2$ is.


text:
Q: How to get value of this HTML on WebBrowser and Put to Textbox? By pressing the button, I would like to get the value="your@mail.com" from that HTML snippet and put it inside the textbox. Any idea to do this?
<input id="mail" onclick="select(this);" data-original-title="Your temporary Email address" class="mail opentip" value="your@mail.com" data-placement="bottom" title="" type="text" readonly="">

I'm trying this code but don't work.
WebBrowser1.Document.GetElementById("value").InvokeMember("click")
TxtBox_Email.Text = Clipboard.GetText()

A: You can use the GetAttribute() method to get the value of the value attribute (hah!). The attribute holds the value of whatever's written in an input element.
By the way, GetElementById() expects the id of the element, which in this case is "mail", not "value".
Dim MailElement As HtmlElement = WebBrowser1.Document.GetElementById("mail")

If MailElement IsNot Nothing Then 'Necessary check: Was the element found?
    TxtBox_Email.Text = MailElement.GetAttribute("value")
End If


text:
Q: Skip 3 images in slider as the example
Hello everyone, I'm trying, without much success, to reproduce this slider to skip 3 images at once, what I achieved here was to jump from 1 to 1 using SWIPER, a JS script to skip the slider, but I imagine there is an easier way to do it using the
Example of the code I'm using:
var swiper = new Swiper(".slide-content", {
  slidesPerView: 3,
  spaceBetween: 25,
  loop: true,
  centerSlide: "true",
  fade: "true",
  grabCursor: "true",
  pagination: {
    el: ".swiper-pagination",
    clickable: true,
    dynamicBullets: true,
  },
  navigation: {
    nextEl: ".swiper-button-next",
    prevEl: ".swiper-button-prev",
  },

  breakpoints: {
    0: {
      slidesPerView: 1,
    },
    520: {
      slidesPerView: 2,
    },
    950: {
      slidesPerView: 3,
    },
  },
});

A: You need to add slidesPerGroup attribute
slidesPerGroup="3"

codesandbox example

A: Add the
slidesPerGroup: 3

to your existing config and it should work
see an example here

A: add slidesPerGroup : 3
read the docs here SwiperJs SlidesPerGroup


text:
Q: How to redirect to action on custom page within admin section Currently I'm developing(well at least trying to;) plugin which will handle custom gallery of images. I stumbled upon one problem though. I'll try to picture it.
I've created custom menu page on which I can edit gallery options as well as I can add/delete/edit elements of gallery. I did add link to every gallery item so after choosing 'edit' I could be able to modify element.
function column_rls_name($item) {
  $actions = array(
            'edit'      => sprintf('Edit',$_REQUEST['page'],'edit',$item['rls_name']),
        );
  return sprintf('%1$s %2$s', $item['rls_name'], $this->row_actions($actions) );
}

Problem begins when 'edit' on element is clicked. It should redirect to settings page.
Here I have a question. What is the best way to do this. Are there any helper functions/hooks/etc out there which would help in creating such page (and detect redirection).
Of course I could do it in function responsible for displaying main gallery options like:
if($_GET['action']=='edit')
    //then do sth
else
    //display main gallery options

but I don't think it's the best way.
I would like to know which functions I could use, from creating custom link, creating custom page and registering them.
What method should be used when action=edit is triggered. How to spot it was requested on the actual page. How to show then page related to the content.
wp-admin/options-general.php?page=rls_logotypes&action=edit&rls_element=element1

A: Get the url of a specific admin page (e.g. the settings page (options-general.php)):
admin_url( 'options-general.php' )

Codex admin_url()
Adding query arguments to an url:
$params = array(
    'page'          => $_REQUEST['page'],
    'action'        => 'edit',
    'rls_element'   => $item['rls_name']
);

$url = add_query_arg( $params, $org_url );

Codex add_query_arg()
Put a and b together:
$params = array(
    'page'          => $_REQUEST['page'],
    'action'        => 'edit',
    'rls_element'   => $item['rls_name']
);

$url = add_query_arg( $params, admin_url( 'options-general.php' ) );

Now we can create links:
public function column_rls_name( $item ){

    $actions = array(
    'edit'  => $this->create_admin_link(
                        array(
                            'text'      => 'Edit',
                            'action'    => 'edit',
                            'item'      => $item['rls_name']
                        )
                )
    );

    return sprintf( '%1$s %2$s', $item['rls_name'], $this->row_actions( $actions ) );

}

public function create_admin_link( $args = array() ){

    $params = array(
        'page'          => $_REQUEST['page'],
        'action'        => $args['action'],
        'rls_element'   => $args['item']
    );

    $url = add_query_arg( $params, admin_url( 'options-general.php' ) );

    return sprintf( '%s', $url, $args['text'] );

}


text:
Q: libgit2sharp not able to commit files only to particular Branch. Help required I have cloned a repo in my local drive. And was able to create branches using libgit2sharp. Below is the code I have used.
//Clone
var WorkDir = Repository.Clone(<git-url>, <local-path>);

//Branch create
var branch = repo.CreateBranch("<branchName>");

repo.Branches.Update(branch,
    b => b.Remote = repo.Network.Remotes["origin"].Name,
    b => b.UpstreamBranch = branch.CanonicalName);

repo.Network.Push(branch);

The above code works and I am able to see the branches on both local .git folder and the git server.
However, When I try to commit files into the created branch they are not visible in the remote git.
Below is the code.
Commands.Stage(repo, <local-clone-path-with-file>);
serName = System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split(new string[] { "\\" }, StringSplitOptions.None)[1];

// Create the committer's signature and commit
Signature author = new Signature(userName,userName+"@atkinsglobal.com", DateTime.Now);
Signature committer = author;

string comment = timeStamp + "_" + "<BranchName>" + "_" + userName;

//// Commit to the repository
Commit commit = repo.Commit(comment+"_initial", author, committer);

Remote remote = repo.Network.Remotes["origin"];

repo.Network.Push(remote, @"refs/heads/"+<BranchName>, new PushOptions());

Please Note: Requirement is that files must be committed to only specified branch, master branch must not have these files.

A: In the first snippet, you are creating a branch and pushing it.  In the second, you are committing.  Unless you've omitted some code, at no point are you switching to the branch that you created.
LibGit2Sharp.Commands.Checkout(repo, branch);

Once you've done that, you can commit to it and then push the branch.


text:
Q: Varnish - how to parse StatSess lines from varnishlog I'm trying to analyze the output of varnishlog, but I'm having trouble finding a good reference on what data is presented by the individual tags - in particular, I'm insteresed in the StatSess tag, as I suspect it holds most of the information I'm interested in (i.e. did the session result in a cache hit? how many bytes were served? etc).  My overall goal is to determine per host cache usage (I have multiple host names/domains behind varnish instance)
Can some one point me in the direction of a useful glossary of these tags, or give me any tips on how I might get the result I'm trying to achieve?
Thanks in advance.


text:
Q: How do I make an element fit the page fold exactly Check out the demo on Stripe's global page. How do they make it so that the blue area (the animation with the globe) fits the window width and height exactly.
Note: This only works on page load. Try resizing the browser window and hit refresh. You'll notice that the blue area fits the window height perfectly.

A: Here's an example, FIDDLE


text:
Q: The phrase "Thank you kindly" If the phrase "Thank you kindly,..." is considered archaic, could someone suggest an alternative?
Thanks
Bill

A: It could be replaced with "Highly obliged" or simply "Obliged" but even these words are considered overly formal and archaic. In modern English, one simply uses "Thank you", "Thanks a lot" or rarely "Many thanks".

A: Two common simple ones:

Much appreciated.
Many thanks.


text:
Q: Add parentheses if double superscript I'd like to set up a macro able to add parenthesis if the argument has already one superscript. It similar to this question, unfortunately the compilation of the following MWE doesn't end…
\documentclass[11pt]{article}

\usepackage{xparse}
\RequirePackage{unicode-math}
\usepackage{listofitems}
\NewDocumentCommand{\dans}{mG{\BbbR}e{^}}{%
    \ensuremath{#1\in\IfValueTF{#3}{{\left(#2\right)}^{#3}}{#2}}%
    }
\NewDocumentCommand{\Dans}{mG{\BbbR}e{^}}{%
    \setsepchar{_||^}%
    \readlist\mymat{#2}%
    \ensuremath{#1\in\IfValueTF{#3}{\ifnum\mymatlen>1\left(#2\right)^{#3}\else#2^{#3}\fi}{#2}}%
    }

\begin{document}
    \dans{x}, \dans{(x, y)}{\BbbC^2}, \dans{(x, y)}{\BbbC}^2, \dans{(x, y)}{\BbbC^\star}^2

    %\Dans{x}, \Dans{(x, y)}{\BbbC^2}, \Dans{(x, y)}{\BbbC}^2, \Dans{(x, y)}{\BbbC^\star}^2
\end{document}

Problem arises when uncommenting the line.

A: Using expl3 to check for an ^ inside of the second argument with \tl_if_in:nnTF, one could add the braces based on this test:
\documentclass[11pt]{article}

\usepackage{unicode-math}
\usepackage{xparse}
\ExplSyntaxOn
\cs_new:Npn \NBur_superscript:n #1
  {
    \tl_if_in:nnTF { #1 } { ^ }
      { \left( #1 \right) }
      { #1 }
  }
\NewDocumentCommand{\dans}{mG{\BbbC}e{^}}
  {%
    \ensuremath
      {%
        #1\in\IfValueTF{#3}{\NBur_superscript:n{#2}^{#3}}{#2}%
      }%
  }
\ExplSyntaxOff

\begin{document}
\dans{x}^2,
\dans{x}{A}^2,
\dans{x}{A^*}^2
\end{document}

If you hide the superscript inside a macro above test won't find it. A possible solution would be to fully expand the argument, in order to look for superscript chars then:
\documentclass[11pt]{article}

\usepackage{unicode-math}
\usepackage{xparse}
\newcommand\Test{A^*}
\ExplSyntaxOn
\cs_generate_variant:Nn \tl_if_in:nnTF { xnTF }
\cs_new:Npn \NBur_superscript:n #1
  {
    \tl_if_in:xnTF { #1 } { ^ }
      { \left( #1 \right) }
      { #1 }
  }
\NewDocumentCommand{\dans}{mG{\BbbC}e{^}}
  {%
    \ensuremath
      {%
        #1\in\IfValueTF{#3}{\NBur_superscript:n{#2}^{#3}}{#2}%
      }%
  }
\ExplSyntaxOff

\begin{document}
\dans{x}^2,
\dans{x}{A}^2,
\dans{x}{A^*}^2
\dans{x}{\Test}^2
\end{document}

The above still might fail, e.g. if the superscript is hidden inside something unexpandable or if something shouldn't be expanded there (the former leading to wrong behaviour, the latter possibly to an error or really bad behaviour). The latter should be rare with normal use cases (I hope).


text:
Q: trying to get VB.NET to call IronPython to increment a VB variable Can't get IronPython called by VB to return an incremented integer.
Value returned is same as passed to IronPython.
I want my VB.NET windows forms app to pass a variable 123 to IronPython, have IronPython add 10 to the variable, then have VB  fetch it back.
But, it comes back still 123.
Imports System
Imports System.IO

Imports Microsoft.Scripting
Imports Microsoft.Scripting.Hosting
Imports IronPython.Hosting

Public Class Form1
     Private Sub Button_GO_Click(sender As Object, e As EventArgs) Handles Button_GO.Click
         ' HELLO WORLD...
         ' bring up an IronPython runtime
        dim engine = Python.CreateEngine()
        dim  scope = engine.CreateScope()

        ' create a source tree from code '
        dim source =  engine.CreateScriptSourceFromString("print 'hello from python'")
        ' run the script in the IronPython runtime'
        source.Execute(scope)

        ' MODIFY VARIABLE: BUG:  returns 1 instead of 11'
        engine = Python.CreateEngine()
        scope = engine.CreateScope()

        ' create a Python variable "i" with the value 1'
        scope.SetVariable( "i", 1 )

        ' this script will simply add 1 to it '
        source = engine.CreateScriptSourceFromString( "i += 10" )

        ' pull the value back out of IronPython and display it:'
        dim response = scope.GetVariable("i")
        debug.print(     response )
    End Sub
End Class

A: I fixed it.  Behold....
Imports System
Imports System.IO

Imports Microsoft.Scripting
Imports Microsoft.Scripting.Hosting
Imports IronPython.Hosting

Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ' VB SENDS A VARIABLE TO IRONPYTHON, WHICH INCS AND RETURNS IT......             http://www.chrisumbel.com/article/scripting_ironpython_dlr
       '/* bring up an IronPython runtime */
        dim engine = Python.CreateEngine()
        dim  scope = engine.CreateScope()

        ' create a Python variable "i" with the value 1
        scope.SetVariable( "i", 123 )

        ' this script will simply add 1 to it
        dim source = engine.CreateScriptSourceFromString( "i += 10" )

        '/* run the script in the IronPython runtime */
        source.Execute(scope)

       '     /* pull the value back out of IronPython and display it */
            Console.WriteLine(scope.GetVariable("i").ToString())

End Sub

End Class


text:
Q: Adobe Illustrator и пакетный экспорт в SVG Есть файл (Ai и EPS) с иконками, которые расположены на одном листе в ряд, подскажите, пожалуйста, как можно пакетно экспортировать каждую иконку по отдельности? Пробовал пару скриптов, MultiExporter.jsx и SVG Exporter.jsx, первый делает видимость работы, но в итоге ни одного файла не экспортирует. Может, есть какой-то хороший и рабочий скрипт для этого, или как-то другому можно наименьшими усилиями/действиями экспортировать все значки на листе по отдельности?
Вопрос можно сказать решён, с помощью двух скриптов.


text:
Q: Why do I need web api to link between django and other js framworks why do i need a web API to link between django and other JS frameworks for example django with angular?
And is it necessary to build a web API like (REST API) to link between back end and front end?

A: Without more work than it is worth, the DJango and Angular frameworks probably cannot pass data between one and the other, since both run at the same logical level in the stack.
REST APIs are the generally accepted mechanism for communicating between SPAs implemented in different frameworks.

A: Django is not JS library. It's a Python-based server framework. But your JS library communicates with a server via REST Api. So you need a web API to link between django and other JS frameworks.


text:
Q: Get the max month from a query that returns several years I have a table with dates, one date per month (some months will be missing but that is expected) but several years are return. I need to get the latest month only. So if I have data for say months 8, 7, 6, etc. in 2020 then return those startDate. And for months 10, 11, and 12 it should return the StartDate from 2019 or wherever it finds it that is the latest. id and courseLength are part of the table but irrelevant for this task. StartDate is of type date.
This is the top 15 rows of the table
id  StartDate   courseLength
153 2020-08-31  63
153 2020-07-31  35
153 2020-06-30  60
153 2020-05-31  17
153 2020-03-31  51
153 2020-01-31  59
153 2019-12-31  30
153 2019-10-31  51
153 2019-08-31  59
153 2019-06-30  54
153 2019-05-31  17
153 2019-03-31  56
153 2019-01-31  55
153 2018-12-31  27
153 2018-10-31  54

And this is what I am expecting
id  StartDate   courseLength
153 2020-08-31  63
153 2020-07-31  35
153 2020-06-30  60
153 2020-05-31  17
153 2020-03-31  51
153 2020-01-31  59
153 2019-12-31  30
153 2019-10-31  51
153 2018-11-30  65
153 2018-09-31  53
153 2019-05-31  17
153 2018-04-30  13

A: You can use window functions:
select *
from (
    select t.*,
        row_number() over(partition by id, month(startdate) order by startdate desc) rn
    from mytable t
) t
where rn = 1

A: try with this
SELECT
    R.id, R.StartDate, R.courseLength
FROM (
    SELECT
        id, StartDate, courseLength, RANK() OVER(PARTITION BY MONTH(StartDate) ORDER BY StartDate DESC) as rank
    FROM
        #t
    ) R
WHERE
    R.rank = 1

A: or  you can use this :
select * from table
 join in (
        select
          max(date) maxdate
          , id
        from table
        group by
          month(date) , id
    ) max
  on max.id = table.id
  and max.maxdate = table.date


text:
Q: prove that $\operatorname{fib}(n)<{(5/3)}^n$ I am trying to prove that

$$ \operatorname{fib}(n)<\left(\frac{5}{3}\right)^n $$

where  $\operatorname{fib}(n)$ is the $n^{th}$ fibonacci number. For a proof I used induction, as we know
$$\operatorname{fib}(1)=1,\, \operatorname{fib}(2)=1,\, \operatorname{fib}(3)=2$$
and so on. So for $n=1$; $\operatorname{fib}(1)<\frac{5}{3}$, and for general $n>1$ we  will have
$$\operatorname{fib}(n+1)<\left(\frac{5}{3}\right)^{n+1}$$
First of all, $$\left(\frac{5}{3}\right)^{n+1} = \left(\frac{5}{3}\right)^{n} \cdot \left(\frac{5}{3}\right)$$
We have  $\operatorname{fib}(n)<\left(\frac{5}{3}\right)^n$  and $\operatorname{fib}(n+1)=\operatorname{fib}(n)+\operatorname{fib}(n-1)$, so by induction we would have
$\operatorname{fib}(n-1)<\left(\frac{5}{3}\right)^{n-1}$, and because $\frac{5}{3}>1$, we have $\left(\frac{5}{3}\right)^{n}>1$, so we get the correct result. Are there any flaws in my proof?

A: I don't quite understand how you claim you have proved $fib(n + 1) < (5/3)^{n+1}$. You have not even used $fib(n+1) = fib(n) + fib(n-1)$. I only see that $(5/3)^{n+1} > 1$ from your proof.
This is what the induction step is supposed to look like:
$$fib(n + 1) = fib(n) + fib(n - 1) < \left(\frac 53\right)^{n} + \left(\frac 53\right)^{n-1} = \left(\frac 53\right)^{n-1}\left(\frac 83\right) < \left(\frac 53\right)^{n+1}.$$


text:
Q: Appending compiler flags to a file with CMake How do I add a compiler flag (I want to APPEND it, not overwrite the others) to a single translation unit with cmake?
I tried with
set_source_files_properties(MyFile.cpp PROPERTIES CMAKE_CXX_FLAGS "-msse4.1")

but it isn't working.. any advice on how to do that?

A: You're almost there, this should work:
set_property(SOURCE MyFile.cpp APPEND PROPERTY CMAKE_CXX_FLAGS -msse4.1)

The kind-specific helpers (like set_source_files_properties()) can be handy at times, but they have a very simiplified interface. For non-trivial things, you have to use set_property(). I've found that I actually rarely use the helpers at all.

A: Try this:
set_property(SOURCE MyFile.cpp APPEND PROPERTY CMAKE_CXX_FLAGS "-msse4.1")

By the way, a few properties are always appended, for example, COMPILE_FLAGS.  For those you don't need to do anything special, just set them and they get appended :)

A: For CMake 3.0 or later, use the COMPILE_OPTIONS property to add a flag to a single translation unit, i.e.:
set_property(SOURCE MyFile.cpp APPEND PROPERTY COMPILE_OPTIONS "-msse4.1")

For earlier versions of CMake, use the COMPILE_FLAGS property. COMPILE_FLAGS is a string property. Therefore the correct way to append additional options to it is to use the APPEND_STRING variant of the set_property command:
set_property(SOURCE MyFile.cpp APPEND_STRING PROPERTY COMPILE_FLAGS " -msse4.1 ")


text:
Q: How to prepare month by month time series data in R from aggregated data containing part wise sales vs month? I am having a dataframe which consists of month wise sales data for many parts:
For eg
Partno   Month      Qty
Part 1   June 2019    20
Part 1   July 2019     25
Part 1   Sep  2019    30
Part 2   Mar  2019    45
Part 3   Aug  2019   40
Part 3   Nov  2019   21
I want to convert this data into a month by month time series, which makes it easier for time series forecasting, Once I make it into a ts object
Month   Part1   Part 2  Part 3
Jan        0    0         0
Feb        0    0         0
Mar        0    45        0
Apr        0    0         0
May        0    0         0
June       20   0         0
July       25   0         0
Aug         0   0         0
Sept        0   30        0
Oct         0    0        20
Nov         0     0       21
Dec         0      0       0
I am quite baffled as to how this can be carried out in R. Any solutions for the same would be highly useful, as I plan build some forecasting models in R.
Looking forward to hearing from you all!

A: Assume the data DF shown reproducibly in the Note at the end.
First convert DF to zoo splitting it by the first column and converting the Month column to yearmon class.  Then convert that to ts class, extend it to Jan to Dec, and set any NAs to 0.  (If you don't need the 0 months at the beginning and end omit the yrs and window lines.)
library(zoo)

z <- read.zoo(DF, split = 1, index = 2, FUN = as.yearmon, format = "%b %Y")
tt <- as.ts(z)
yrs <- as.integer(range(time(tt))) # start and end years
tt <- window(tt, start = yrs[1], end = yrs[2] + 11/12, extend = TRUE)
tt[is.na(tt)] <- 0
tt

giving:
         Part 1 Part 2 Part 3
Jan 2019      0      0      0
Feb 2019      0      0      0
Mar 2019      0     45      0
Apr 2019      0     20      0
May 2019      0      0      0
Jun 2019     20      0      0
Jul 2019     25      0      0
Aug 2019      0      0      0
Sep 2019     30      0      0
Oct 2019      0      0     20
Nov 2019      0      0     21
Dec 2019      0      0      0

Note
Lines <- "Partno, Month, Qty
Part 1, Jun 2019, 20
Part 1, Jul 2019, 25
Part 1, Sep 2019, 30
Part 2, Mar 2019, 45
Part 2, Apr 2019, 20
Part 3, Oct 2019, 20
Part 3, Nov 2019, 21"
DF <- read.csv(text = Lines, strip.white = TRUE)


text:
Q: Obtain Micronaut ResourceLoader in Method Call I'm trying to get ahold of a ResourceLoader for a utility method by using injections, but I keep getting the following error:
Caused by: kotlin.UninitializedPropertyAccessException: lateinit property resourceResolver has not been initialized

@Singleton
class Injections {
    @Inject
    lateinit var resourceResolver: ResourceLoader
}

val inj = Injections()

fun <T> parseYaml(filePath: String): T {
    if (!inj.resourceResolver.getResource(filePath).isPresent) {
        throw IllegalArgumentException("Could not find file '$filePath'")
    }
    val inputStream = inj.resourceResolver.getResourceAsStream(filePath).get()
    return Yaml().load(inputStream) as T
}

I don't need to be using injections to make this happen, I just need to access a ResourceResolver from the parseYaml method.

A:
I don't need to be using injections to make this happen

You kind of do need to be using injections.  That is why your code makes use of @Inject.
The problem is you are creating a new instance of Injections instead of using the one provided by the container, so your instance won't be initialized the way you want it to be.  Instead of val inj = Injections() if you @Inject the Injections instance into whatever bean(s) need access to it, that will work.


text:
Q: How to change the color of seperator in tableView? I am currently creating collectionView cells inside of TableViewCell but I want to separate each TableViewCell with default separator but changing its color. Please help me with this. Or Can I remove all separator lines and use custom UIView to separate them?

A: Simply update the separatorColor property of tableView with the required UIColor instance.
tableView.separatorColor = .red

In case you want to update it via storyboard, you can with the tableView's attributes inspector like,

A: You can also set the separatorColor from storyboard.


text:
Q: Android Base Activity's onActivityResult() result need from child activity My Base Activity code -
public abstract class SpeechToTextActivity extends Activity {

private final int REQ_CODE_SPEECH_INPUT = 100;

/**
 * Showing google speech input dialog
 * */
public void promptSpeechInput() {
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
            getString(R.string.speech_prompt));
    try {
        startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
    } catch (ActivityNotFoundException a) {
        Toast.makeText(getApplicationContext(),
                getString(R.string.speech_not_supported),
                Toast.LENGTH_SHORT).show();
    }
}

/**
 * Receiving speech input
 * */
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
    case REQ_CODE_SPEECH_INPUT: {
        if (resultCode == RESULT_OK && null != data) {

            ArrayList<String> result = data
                    .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

        }
        break;
    }

    }
}

}
Now I need the result of onActivityResult() from another child activity which extends SpeechToTextActivity  .
Please help me .

A: override onActivityResult in the child, and retrieve the result. The code is the same. If the child is responsible to manage the data, you should remove the case from the parent and have the code just in the derived class(es)


text:
Q: ui slider and multiple checkbox search filter Can we make that work using selecting multiple brands. Currently its taking 1 brand at a time. How can we make that using multiple brand selection so if i check brand ankit and honey then both entries should show and tags are working as it is.

A:

$(document).ready(function(){
      // cache ref to all checkbox elements
      var checkboxes = $('input:checkbox[name^="mchkboxs"]'),
      checkboxes2 = $('input:checkbox[name^="f1"]'),
          // cache ref to results
          //results = $('#results'),
          // cache ref to our list
          listItems = $('.tabela > li'),
          // cache amount ref
          amount = $('#amount'),
          // collection of selected checkbox elements
          selectedItems = [],
          selectedItems2 = [],
          // slider config
          slideOptions = {
            min: 0,
            max: 100000,
            step: 20,
            values: [10000],
            slide: function(event, ui) {
              amount.val(ui.values[0] + " USD");
            },
            change: function(event, ui) {
              updateList();
            }
          };

      // render our slider
      var slider = $("#price").slider(slideOptions);

      amount.val($("#price").slider("values", 0) + " USD");

      checkboxes.on('change', function(){
        var id = this.id;

        if(this.checked){
          // push the element vs the value
          selectedItems.push(this.value);
        }else{
          // remove items on uncheck
          selectedItems.splice(selectedItems.indexOf(this.value), 1);
        }

        updateList();
      });

      checkboxes2.on('change', function(){
        var id = this.id;

        if(this.checked){
          // push the element vs the value
          selectedItems2.push(this.value);
        }else{
          // remove items on uncheck
          selectedItems2.splice(selectedItems2.indexOf(this.value), 1);
        }

        updateList();
      });

      var updateList = function(){
        // create map of values for joining
        var selectedItemsValues = selectedItems.sort().join('*'),
        selectedItemsValues2 = selectedItems2.sort().join('*'),
            // min value
                  minPrice = slider.slider('values', 0);

        console.log(selectedItemsValues);
        console.log(selectedItemsValues2);
        // filter list items
        listItems.hide().filter(function(){
          // get data attributes
          var data = this.dataset;
          // restrict list to price band and selections

          return Number(data.price) >= minPrice && (selectedItems.length ? data.category.includes(selectedItemsValues) : true) && (selectedItems2.length ? data.vendor.includes(selectedItemsValues2) : true);

        })
        .show();

      }

    });

<link href="https://code.jquery.com/ui/1.12.1/themes/hot-sneaks/jquery-ui.css" rel="stylesheet" type="text/css" media="all" />

<input type="text" id="amount" readonly>

Tags

  <input type="checkbox" name="mchkboxs-1" value="1" id="1" /> 1
  <input type="checkbox" name="mchkboxs-1" value="2" id="2" /> 2
  <input type="checkbox" name="mchkboxs-1" value="3" id="3" /> 3
  <input type="checkbox" name="mchkboxs-1" value="4" id="4" /> 4
  <input type="checkbox" name="mchkboxs-1" value="5" id="5" /> 5
  <input type="checkbox" name="mchkboxs-1" value="6" id="6" /> 6
  <input type="checkbox" name="mchkboxs-1" value="7" id="7" /> 7
  <input type="checkbox" name="mchkboxs-1" value="8" id="8" /> 8

Brands

  <input type="checkbox" name="f1-1" value="honey" id="honey" /> honey
  <input type="checkbox" name="f1-1" value="ankit" id="ankit" /> ankit

10 000 USD contains 1 2 3 4

12 000 USD contains 2 3

13 000 USD contains 4 5

14 000 USD contains 5 6

12 000 USD contains 5

14 000 USD contains 1 2

16 000 USD contains 1 2 3

20 000 USD contains 7 8