text:
Q: SED - insert a blank line after every input line that consists of capital letters and spaces I have a text file and I need a command using sed to insert a blank line after every line that that consists of capital letters and spaces only.

A: This might work for you (GNU sed):
sed '/^[[:blank:][:upper:]][[:blank:][:upper:]]*$/G' file

This appends the hold space (by default it contains a newline) to lines containing at least one or more whitespace or uppercase characters.

A: Given:
$ cat file
LINE LINE LINE
Line Line Line
Line 1
LINE 2
END!
====

You can use s/// to add a \n to the line:
With POSIX sed, use a literal new line in the sed script:
$ sed 's/^\([[:upper:][:blank:]]*\)$/\1\
/' file
LINE LINE LINE

Line Line Line
Line 1
LINE 2
END!
====

With GNU sed, you can use the representation of \n:
$ sed 's/^\([[:upper:][:blank:]]*\)$/\1\n/' file

You can also use a\ to append in sed. I have tried to get sed append to work but cannot reliably with POSIX, BSD and GNU sed since POSIX and BSD do not support \n
With GNU sed (note space after a\):
 $ sed '/^[[:upper:][:blank:]]*$/a\ ' file

BSD:
$ sed '/^[[:upper:][:blank:]]*$/a\
\
' file

Those are not exactly equivalent since the GNU version has a space on the blank line.
The version of POSIX sed I have did not work with either of those...

Given the platform and version differences of sed, you might consider awk to do this since simple awk's are easier to make universal.
This works on every awk I have:
$ awk '1; /^[[:upper:][:blank:]]*$/{print ""}' file

With awk you can also make it so that blank lines are not doubled by making sure there is at least non blank like so:
 $ awk '1; /^[[:upper:][:blank:]]+$/ && NF>1 {print ""}' file

A: Sure. Just insert lines with a:
sed '/^[[:blank:]A-Z]*$/a\'

The a command inserts the string after it after every matching line (end the string with a backslash). So the above command just inserts an empty line after all lines that contains solely of capital letters and spaces. That's exactly what you want.


text:
Q: Error putting S3 policy: MalformedPolicy: Invalid principal in policy I am trying to set multiple principals (IAM roles) on an S3 bucket's IAM policy, using terraform. The plan looks like this:
Terraform will perform the following actions:

  # module.log_bucket.aws_s3_bucket_policy.policy will be updated in-place
  ~ resource "aws_s3_bucket_policy" "policy" {
        id     = "log_bucket"
      ~ policy = jsonencode(
          ~ {
              ~ Statement = [
                  + {
                      + Action    = [
                          + "s3:PutObject",
                          + "s3:PutObjectAcl",
                        ]
                      + Effect    = "Allow"
                      + Principal = {
                          + AWS = [
                              + "arn:aws:iam::<account1-id>:role/my_log_role",
                              + "arn:aws:iam::<account2-id>:role/my_log_role",
                              + "arn:aws:iam::<account3-id>:role/my_log_role",
                              + "arn:aws:iam::<account4-id>:role/my_log_role",
                            ]
                        }
                      + Resource  = [
                          + "arn:aws:s3:::log_bucket/*",
                          + "arn:aws:s3:::log_bucket",
                        ]
                      + Sid       = "DelegateS3Access"
                    },
                ]
                # (1 unchanged element hidden)
            }
        )
        # (1 unchanged attribute hidden)
    }

but when I apply I get the following error:

│ Error: Error putting S3 policy: MalformedPolicy: Invalid principal in policy
│   status code: 400

│   with module.log_bucket.aws_s3_bucket_policy.policy,
│   on .terraform/mypath/main.tf line 63, in resource "aws_s3_bucket_policy" "policy":
│   63: resource "aws_s3_bucket_policy" "policy" {
│

It seems correct to me, why is it throwing an error?

A: As per the comments, this is because the roles you specified have to exist at the time of policy creation.
Relevant documentation

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python 2.7 (with Tkinter) project into a stand-alone exe? I've searched this for ages and tried everything. Just can't make it work.
What I want to do is to make a stand-alone exe of my small program that uses Tkinter, for Windows. This far I've accomplished to make it an exe, however the dist/ folder including a folder tcl/ and an extra exe-file. How to get rid of these?
Also, I haven't been able to make a working exe. Here's my setup.py:
from distutils.core import setup
import py2exe
import sys
if len(sys.argv) == 1:
    sys.argv.append("py2exe")

setup(
    options = {
        "py2exe": {"compressed": 1, "optimize": 2, "ascii": 1, "bundle_files": 1, "includes": ["Tkinter"]}
        },
        zipfile = None,
        windows = [
        {
            "script": "hello.py",
            "icon_resources": [(0, "icon_16.ico")]
        }
    ]
)

With this code I get a notice "This program has stopped responding" instantly after running it.
By removing the option "ascii", the program doesn't work and leaves a logfile:
Traceback (most recent call last):
  File "hello.py", line 1, in <module>
  File "zipextimporter.pyo", line 82, in load_module
  File "Tkinter.pyo", line 38, in <module>
  File "zipextimporter.pyo", line 82, in load_module
  File "FixTk.pyo", line 56, in <module>
  File "FixTk.pyo", line 23, in convert_path
LookupError: unknown encoding: mbcs

I was very optimistic about Python as it seemed really nice to code and find help for, but this is something I can't code anything without. Any help is appreciated. I'm a total newcomer.

A: I think there is a bug with the way that it bundles tkinter, you cannot optimize or bundle tkinter in python, take those options out and try running it.

A: Anything in the "tcl" folder is required by Tkinter. Tkinter is actually linking to a Tcl interpreter (which means you can run Tcl commands in Python!). Because of this, you need everything that a Tcl interpreter needs (including support for Tk).
The error you get is an encoding error, and in your options I see "ascii": 1. Get rid of that and it should solve the problem.
Also, if you plan on making an installer for this compiled program, there is no real reason to compress the program with "compressed": 1 (it only needs to be small when it's distributed).

A: You could try using an alternate solution provided at the location below which basically uses an installer method. I wasn't able to bundle that tcl folder in the exe as well, so I guess this should be a better solution.
http://www.py2exe.org/index.cgi/SingleFileExecutable


text:
Q: Facebook SDK + SlidingMenu SDK = Jar mismatch! Fix your dependencies So I have added the Facebook SDK and the SlidingMenu SDK into my Android project, however I am getting those nasty "Jar mismatch" errors.
I have already removed the android-support-v4.jar file from my libs folder, yet the error persists.
Any ideas on how to fix this?
(I have also tried deleting the files from the folders, but I get the 'file not found' errors)
Image: http://i.stack.imgur.com/9JOvg.png

A: Delete the android-support-v4.jar from the SlidingMenu library. And copy the android-support-v4.jar file from the Facebook SDK's libs folder and paste it in to your SlidingMenu's libs folder.
And then refresh the SlidingMenu project and  finally clean all projects after doing the above.

A: Remove the support library from both library projects and re-add it to your project.

A: Try using the remove the android-support-v4.jar file from the libs folder from your project.
Good Luck.


text:
Q: why does ejs and jquery(jquery-advanced-news-ticker) collide in this code? I have a node application I am using with ejs as my views driver, and i am trying to use this great plugin.
the code by itself works great, but when I load a dynamic code using ejs it stops. (if i try that with static html it works perffectly).
my ejs:
<% if(jobs !== undefined){ %>

            <% jobs.forEach(function(item){ %>

<%= item.message %>

            <% }); %>

<% } %>

and the script:
jQuery(document).ready(function() {
      setTimeout(function() {
         $('.newsticker').newsTicker({
            max_rows: 1,
            speed: 600,
            direction: 'down',
            duration: 4000,
            pauseOnHover: 1
            });
      }, 2000);
   });

why do they collide?

A: i ended up using the plugin's method for stopping and then starting and it worked.


text:
Q: Is there any way to move RSI Indicator position of Syncfusion Cartesian Chart? I am trying to RSI Indicator in CandleStick chart using Syncfusion package.
Everything works but if the y axis value is very large say it starts at higher than 10000. But RSI is only shown below 100. So, there is large gap 100-10000 in the chart. How can I remove the gap?

A: We have analyzed your requirement and the scenario can be achieved by rendering the RSI indicator in the secondary y-axis. Find the code below to accomplish this.
SfCartesianChart(
        axes: [
          NumericAxis(
            opposedPosition: true,
            name: 'yAxis',

          )
        ],
        indicators: <TechnicalIndicators<_SalesData, DateTime>>[
          RsiIndicator<_SalesData, DateTime>(
              seriesName: 'AAPL',
              yAxisName: 'yAxis',
              //Other configurations
          ),
        ],
        series: <ChartSeries<_SalesData, DateTime>>[
          CandleSeries<_SalesData, DateTime>(
              name: 'AAPL'
              //Other configurations
         )
        ]
       )

We have attached main.dart file here for your reference.


text:
Q: Expanding nested brackets In comparison with the other questions on the front page, this seems utterly trivial, and I'm almost embarrassed to ask it! But anyway...
I'm trying to improve my maths by using a couple of recommended textbooks.  One (Basic Maths for the Physical Sciences) has the following question:
Expand the following for $z$ by removing all the brackets
$$
   z = [2xy - (x+y)^2]^2
   $$
The first line of the (semi-worked) given answer is
$$
z = 4x^2y^2 - 4xy(x+y)^2 + (x+y)^4
$$
It took me ages to work out how they got this, before realising they were treating the the $(x+y)^2$ has a single entity.  But, I tried to approach it by dealing with the nested bracket first (which I thought should be the correct way!), and then expanding, to get
$$
(2xy - (x^2 + 2xy + y^2))(2xy - (x^2 + 2xy + y^2))
$$
$$
(2xy - x^2 - 2xy - y^2)(2xy - x^2 - 2xy - y^2)
$$
but this removes all $xy$ terms, whereas the correct answer is
$$
x^4 + 2x^2y^2 + y^4
$$
What step have I missed?

A: you just didn't take you answer far enough. The result of your last step was
$$
(2xy - x^2 - 2xy - y^2)(2xy - x^2 - 2xy - y^2)
$$
Noting that $2xy-2xy=0$ we have
$$(-x^2-y^2)(-x^2-y^2) = ((-1)(x^2+y^2))((-1)(x^2+y^2))$$
$$=(-1)(-1)(x^2+y^2)^2=(x^2+y^2)^2$$
$$=x^4 + 2x^2y^2 + y^4$$

A: All the xy terms canceling, meaning that 2xy and -2xy disappear.  So, we have
(-x$^2$-y$^2$)(-x$^2$-y$^2$).
Expanding we have
(--x$^4$--y$^2$x$^2$--x$^2$y$^2$--y$^4$).
Which in turn yields
x$^4$+2x$^2$y$^2$+y$^4$.

A: You could firt notice that $$2xy - (x+y)^2=-(x^2+y^2)$$ so $$z=(x^2 +y^2)^2$$ If you take the long way you chose, you arrive, after expansion, to $$z=x^4 + 2x^2y^2 + y^4=(x^2 +y^2)^2$$ I suppose that the goal was effectively to remove all $xy$ terms.


text:
Q: conditionalPanel in Shiny: condition based on class of variable in a dataset I'm building a Shiny app which contains various options for mapping/visualising data from a particular dataset. I have a selectInput where the user selects the variable from the dataset they would like to visualise.
I would like to have a conditionalPanel which displays when a user selects a numeric variable only.
I'm sure it's quite simple, but I'm having trouble writing the condition argument of conditionalPanel as I'm not familiar with Javascript. In R language, I could use is.numeric(), but I'm not familiar with how to do that in Javascript. I've tried condition = "isNaN(input.variables) == FALSE", but I think this just tests whether the name of the variable is a number or not, not the data therein.
I'm aware that I could write a condition in R using a reactive expression on the server side as per this tutorial, but I'd rather avoid it since it's more computationally intensive.
Any help would be very much appreciated!
Sample code below. To be clear, the radio buttons should display ONLY when the "nums" variable is selected (containing numeric data) but NOT when the "letters" variable is selected.
letters <- c("a","b","c")
nums <- 1:3
dat <- data.frame(letters,nums)

ui <- fluidPage(
  sidebarPanel(
    selectInput("variables", h4("Pick variable to plot:"), choices = colnames(dat)),
    conditionalPanel(
      condition = "isNaN(input.variables) == FALSE",
      radioButtons("seq_div", "Colours should be...", c("sequential", "divergent"))
    )
  ),
  mainPanel()
)

shinyApp(ui = ui, server = server)

A: If you don't know beforehand which columns are numeric (which I think is the case here) you can do:
letters <- c("a","b","c")
nums <- 1:3
num2 <- 4:6
dat <- data.frame(letters,nums, num2)

numeric_cols = paste("'",colnames(dat)[sapply(dat, is.numeric)],"'", collapse = ',', sep = '')

ui <- fluidPage(
    sidebarPanel(
        selectInput("variables", h4("Pick variable to plot:"), choices = colnames(dat)),
        conditionalPanel(
            condition = paste0("[", numeric_cols, "].indexOf(input.variables) >= 0"),
            radioButtons("seq_div", "Colours should be...", c("sequential", "divergent"))
        )
    ),
    mainPanel()
)

server <- shinyServer(function(input, output) {
})

shinyApp(ui = ui, server = server)

It basically find which columns are numeric, paste them in a JS array form, and then check if the selected item is inside that array.


text:
Q: Plotting of residuals by fitted values vs. sorted by fitted values My question concerns two methods for plotting regression residuals against fitted values.
The standard method:  You make a scatterplot with the fitted values (or regressor values, etc.) on one axis (generally $x$-axis), and the residuals on the other (generally $y$). This is what I've always been taught.
The sorted method: I recently saw someone plotting residuals in a slightly different way: he would sort the residuals using the fitted values as a key, and then plot the residuals in sorted order.  In this case, the $x$-axis would be the ranked ordering of the residuals by fitted values, $i=1, 2, ..., n$ for $n$ residuals.  To be clear this is not a normal probability plot, where we have to sort the residuals by their own values.
My question is, is this sorted method valid, or does it present any benefits not captured in the standard method?
To illustrate a scenario where the difference is very apparent, say I have a data set where a value is repeated quite a bit.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

np.random.seed(0)

df = {}
df['x'] = list(np.random.randint(1, 20, 20)) + ([0] * 10) #Fitted values
df['y'] = np.random.uniform(-2, 2, 30) #Residuals
df = pd.DataFrame(df)

ax = df.plot.scatter('x', 'y')
ax.set_title('Standard method')
ax.set_xlabel('Fitted value')
ax.set_ylabel('Residual')
plt.show()
plt.close()

keyed_values = sorted(zip(df['x'], df['y']), key=lambda x: x[ 0])
sorted_residuals = [x[ 1] for x in keyed_values]
fig = plt.figure(figsize=(6, 4))
ax = fig.add_subplot(1, 1, 1)
ax.plot(range(0, len(residuals)), sorted_residuals, '.', alpha=0.75, markersize=10, color='C0')
ax.set_title('Sorted method')
ax.set_xlabel('Ranked order of residual by fitted value')
ax.set_ylabel('Residual')
plt.show()
plt.close()

Same residuals, same fitted values, two very different plots that could lead to different interpretations.  The sorted method guarantees that no two values would ever be plotted at the same value of the $x$-axis, but breaks ties somewhat arbitrarily.  It also forces equal spacing of residuals over the $x$-axis.  Is this a valid way to reveal a pattern otherwise not shown by the standard method?

A: On the contrary I would say that the standard method is way better.
The "ranked method", which is not a standard method and should probably not be called a "method" at all, masks the true relationship between predicted values and residuals.
If in a certain interval your model is really bad, you would notice that you have many high (in absolute value) residuals. By ranking them (and breaking the ties in the ranks randomly - if they were any), you visually spread these residuals which makes them appear less grave. Moreover, it would be more difficult to identify where your model is bad, since you have only ranks and no values on the response scale. Lastly, it would also be more difficult to identify heteroscedasticity...


text:
Q: Ansible playbook not woking with multivalued lists I am trying to write a playbook that creates multiple users but it does not work when i put my variables in a list form.
Not working playbook
[root@ansible-master playbooks]# cat users_list_new.yml
---
users:
  - username:
      - amba
      - ruchita

[root@ansible-master playbooks]# cat multi_users_new.yml
---
- name: Creating the multi users with a new approach
  hosts: california
  become: true
  vars_files:
    - users_list_new.yml
  tasks:
    - name: Create the user
      user:
        name: "{{ item.username[0] }}"
      loop: "{{ users }}"

It only creates the first user because I have put the subscript 0 in the user module. My question is how we can create a loop over username . For instance I modified my playbook but it didn't work
---
- name: Creating the multi users with a new approach
  hosts: california
  become: true
  vars_files:
    - users_list_new.yml
  tasks:
    - name: Create the user
      user:
        name: "{{ item }}"
      loop: "{{ users.username }}"

It threw below error when I ran the playbook
PLAY [Creating the multi users with a new approach] ********************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************************************************
ok: [10.128.0.5]

TASK [Create the user] *************************************************************************************************************************************************
fatal: [10.128.0.5]: FAILED! => {"msg": "'list object' has no attribute 'username'"}

PLAY RECAP *************************************************************************************************************************************************************
10.128.0.5                 : ok=1    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

[root@ansible-master playbooks]#

Please help me to figure out the solution
****EDIT ****
Suppose I want to create two users . What is the best practice of variable declaration ?
First Approach
users:
  - username:
      - amba
      - ruchita
  - shell:
      - /bin/bash
      - /bin/ksh

Second Approach
users:
  - username: amba
    shell: /bin/bash
  - username: ruchita
    shell: /bin/bash

A: Your issue is that your variable structure users contains a list not a dict so you cant access username as a key of it since its a list not a dict. You would need to access as users[0] to get access to the list of usernames.
---

- name: Creating the multi users with a new approach
  hosts: localhost
  vars_files:
    - users_list_new.yml
  tasks:
    - name: Create the user
      user:
        name: "{{ item }}"
      loop: "{{ users[0].username }}"

TASK [Create the user] ********************************************************************************************************************************************************************
Sunday 23 October 2022  08:47:41 +0100 (0:00:07.567)       0:00:08.179 ********
changed: [localhost] => (item=amba)
changed: [localhost] => (item=ruchita)

PLAY RECAP ********************************************************************************************************************************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

BEFORE
root@ff9c44b4c94f:/local# id amba; id ruchita
id: 'amba': no such user
id: 'ruchita': no such user

AFTER
root@ff9c44b4c94f:/local# id amba; id ruchita
uid=8257(amba) gid=8257(amba) groups=8257(amba)
uid=8258(ruchita) gid=8258(ruchita) groups=8258(ruchita)


text:
Q: Is | (or) short circuited when pattern matching in scala? I noticed that there is no || operator available when pattern matching - is | short circuited?

A: | short-circuits.
object First {
    def unapply(str: String): Boolean = {
        println("in First")
        str == "first"
    }
}

object Second {
    def unapply(str: String) = {
        println("in Second")
        str == "second"
    }
}

object Run extends App {
    "first" match {
        case First() | Second() => None
    }

    //Output: In First

    "first" match {
        case Second() | First() => None
    }

    //Output: In Second\nIn First
}

A: In pattern matching, | is short circuited.  You can't call unapply or the like (with returned parameters) with the or-operator, where side-effects might be more likely.  So short-circuiting is purely an optimization technique (won't affect the correctness of the code except in extraordinary cases such as a side-effecting equals method).  This does mean you are limited in your ability to short circuit or not for performance or side-effecting reasons.
To see this, if we write this code:
def matchor(s: String) = s match {
  case "tickle" | "fickle" => "sickle"
  case _ => "hammer"
}

We see this bytecode (in part)
public java.lang.String matchor(java.lang.String);
  Code:
   0:   aload_1
   1:   astore_2
   2:   ldc #12; //String tickle
   4:   aload_2
   5:   astore_3
   6:   dup
   7:   ifnonnull   18
   10:  pop
   11:  aload_3
   12:  ifnull  25
   15:  goto    31
   18:  aload_3
   19:  invokevirtual   #16; //Method java/lang/Object.equals:(Ljava/lang/Object;)Z
   22:  ifeq    31
   25:  iconst_1
   26:  istore  4
   28:  goto    66
   31:  ldc #18; //String fickle
   33:  aload_2
   ...
   66:  iload   4
   68:  ifeq    78
   71:  ldc #20; //String sickle
   73:  astore  6
   75:  goto    82
   ...
   82:  aload   6
   84:  areturn

See the jump on line 28 to avoid testing the "fickle" case?  That's the short-circuit.


text:
Q: Keep persist/merge after a ConstraintViolationException using JPA How can I merge and update an entity after a ConstraintViolationException using JPA + Hibernate and Open Session in View strategy?
userTransaction.begin();

try {
    em.persist(entity);
} catch (PersistenceException ce){
    ConstraintViolationException t = (ConstraintViolationException) ce.getCause();
    String constraint = t.getConstraintName();
    if (constraint.equals(ConstantesUtil.MY_UK_CONFIG) == false ){
        throw new Exception(ce);
    } else {
        entity = findByUk(entity);
    }
} catch (Exception e){
    throw new Exception(e);
}

entity.setOtherPropertyValue('forExample');

em.merge(entity);

userTransaction.commit();

I know that after an exception the transaction/session becomes dirty. Does have any way to clean it and persist ou merge?


text:
Q: Camel Rest DSL with jetty component fails to populate CORS headers correctly I am having a hard time figuring out how camel rest dsl populates the CORS response headers when using jetty component as container. I have set the cors headers as follows
camel.rest.cors-headers.Access-Control-Allow-Credentials=true
camel.rest.cors-headers.Access-Control-Max-Age=3600
camel.rest.cors-headers.Access-Control-Allow-Methods=GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH
camel.rest.cors-headers.Access-Control-Allow-Headers=Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, Accept-Language, Host, Referer, User-Agent, Authorization, x-omit
camel.rest.cors-headers.Access-Control-Allow-Origin=*.example.com,*.example1.com,*.example2.com

However it always returns the list of origins rather than the value passed in Origin header.
I have tried enabling the CORS on jetty component and writing a custom JettyHttpBinding however, camel rest is still somehow overriding the values. My expected result is if origin value is in list of allowed origins then it should return Access-Control-Allow-Origin header as origin value otherwise return an error/throw an exception. Is there a way to customize this? Any help would be really appreciated

A: I was finally able to do this after getting some idea from following question.
Add CORSHandler to a camel-jetty component
However, I had to extend HandlerWrapper class instead of AbstractHandler
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.HandlerWrapper;

import javax.servlet.DispatcherType;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CORSHandler extends HandlerWrapper {

    @Override
    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        if (baseRequest.getDispatcherType() == DispatcherType.REQUEST) {
        // Custom code for adding CORS headers - similar to org.eclipse.jetty.servlets.CrossOriginFilter::handle;
        }

        if (this._handler != null) {
            this._handler.handle(target, baseRequest, request, response);
        }

    }

}


text:
Q: Prophet not fitting data correctly I'm currently looking to build a time-series model to do change point detection on a churn dataset, in order to check that the covid19 measures taken during the pandemic had an influence on churn.
I'm currently using Prophet to create the model, but i don't seem to be able to predict correctly the change points during the pandemic, nor are the data points fitted correctly:

As you can see in the second image, the data is clearly not fitted well, and cant capture the churn variation over time. Furthermore, there are a lot of changepoints in locations with not much change, and no points in some of the events. Below is what i've tried:
model.fit(data)
future = model.make_future_dataframe(periods=100)
forecast = model.predict(future)

Can you guys help me out figuring out what i'm doing wrong? Or if Prophet is the right tool for this task (detecting changepoints, and hopefully matching them with the ones from real covid events)?
thank you in advance!


text:
Q: MongoDB find() returns empty array I have a simple flask app that does CRUD operations. I have a python module where I defined all functions and they all work fine; I can create, read, update and delete. I added a retrieve method where I call find() and it does retrieve the cursor. The problem is I can't get it to populate the data, all I get is an empty array []. I looped through the cursor and I used loads and dumps from bson.json_util, but I get the same result. Here is what the class looks like:
from pymongo import MongoClient

class AnimalShelter(object):

    def __init__(self, username, password):

        # Access the MongoDB databases and collections.
        self.client = MongoClient('localhost', ####)
        self.db = self.client['project']
        self.username = username
        self.password = password

# Create
    def create(self, data):
        if data is not None:
            return self.db.collection.insert(data)
        else:
            print("Nothing to save, because data parameter is empty")
            return False

# Read
...
# Update
...
# Delete
...

# Retrieve
    def retrieve(self, data, projection):
        if data is not None:
            return self.db.collection.find(data, projection)
        else:
            return False

In the test file, I have:
animals = AnimalShelter(username, password)
            try:
                dog = dumps(list(animals.retrieve({"animal_type": "Dog", "name": "Flow"}, {"_id": False})))
                print(dog)

            except:
                print("Unable to find the outcome")

Any help would be appreciated!


text:
Q: How to fill a SQL column with data (calculated) from another table I have a question and don't know how to approach the problem exactly.
I have two tables as following:
Clients
| c_id | name    | reference |
| ---- | ------- | --------- |
| 1    | ClientA | 1         |
| 2    | ClientB | 1         |
| 3    | ClientC | 2         |
| 4    | ClientD | 2         |
| 5    | ClientE | 1         |
| 1    | ClientF | 3         |

Tour
| t_id | name    | count |
| ---- | ------- | ----- |
| 1    | TourA   | 3     |
| 2    | TourB   | 2     |
| 3    | TourC   | 1     |

"Reference" in the "Client" table is defined as foreign key.
Is it possible to fill the column "count" in the table "Tour" with an automated formula where it counts how many times the t_id appears in the "Client" table?
Something like: COUNT(c_id) FROM clients WHERE reference = t_id
I have read about to create a view but not sure how to fetch the data correctly.
Thanks for your help,
Raphael
UPDATE #1:
The workflow as described with the view works perfectly. I'm trying now to fill the column via a trigger but I'm getting an SQL error with the following code:
CREATE TRIGGER client_count
AFTER UPDATE
ON clients FOR EACH ROW

SELECT t.*,
    (
        SELECT COUNT(*) FROM clients c where c.tour_id = t.tour_id
    ) AS tours.tour_bookedspace
FROM tours t

A: The view you have referred to is indeed the way to go here. The view you need to create needs to join the two tables and perform a count aggregation as follows:
CREATE VIEW vwTour
AS
SELECT  t.t_id,
        t.name,
        COUNT(t.name) AS Cnt
FROM    tour t
        JOIN Clients c
            ON t.t_id = c.reference
GROUP BY t_id,
        t.name

A: No you can't. Generated columns can only use data from the same table.
The options you have are:
1. Use a view
You can select from a view that computes the extra value(s) you want. For example:
create view tour_data as
select t.*,
  (
    select count(*) from clients c where c.reference = t.t_id
  ) as number_of_clients
from your t

2. Use a trigger
Alternatively, you can add the extra column number_of_clients and populate it using a trigger every time a row is added, modified, or deleted from the table clients.


text:
Q: I'm having a problem with a char variable (New to programming with C) I keep getting one bug in the terminal which says:
warning: format specifies type 'char *' but the argument has type 'int' [-Wformat]
    scanf("%c", namehumaninput);
           ~~   ^~~~~~~~~~~~~~

The course I am taking is saying that all I need to do is have a char variable and thats it, use that with nothing else but clearly something is wrong.
Here is the code I am having trouble with:
    //Lesson 9
    int inputage;
    double gpainput;
    char namehumaninput;
    printf("Wat ur age?\n");
    scanf("%d", &inputage); // scanf(); is how you do an input. You MUST have & behind a variable after a %d!!
    printf("You are %d years old\n", inputage);
    printf("Was yo GPA?\n");
    scanf("%lf", &gpainput); // %lf is for double variables when using scanf() but using printf() it uses %s for variables. Confusing, I know.
    printf("Your GPA is %f\n", gpainput);
    printf("Wos yo name now that ive asked yo fo yo gpa and age\n");
    scanf("%c", namehumaninput); // %c is universal for both
    printf("Really? Yo name is %c?\n", namehumaninput);

I have the stdio and stdlib libraries imported and am using MacOS.

A: This call of scanf
scanf("%c", namehumaninput);

you need to rewrite at least
scanf(" %c", &namehumaninput);

The leading space in the format string allows to skip white space characters in the input stream and you need to provide a pointer to a character as the second argument expression.
However this call allows to enter only a single character.
If you want to enter a word then you should write for example
char namehumaninput[20];
//...

scanf("%19s", namehumaninput);
printf("Really? Yo name is %s?\n", namehumaninput);


text:
Q: Multiple inheritance and method overriding issue in java I have asked a similar question in another post (How to implement a method from a derived class that does not require cast) but this is a little more specific.
Suppose I have 3 classes: Vehicle, Car, Convertible. Car extends Vehicle, and Convertible extends Car. I want a method for each class that returns a list that does not require cast at runtime. I believe it to be impossible after some thought but I also want to hear your opinion
public class Vehicle {
    public List<? extends Vehicle> getList() {
        return new ArrayList<Vehicle>();
    }
}

public class Car extends Vehicle {
    @Override
    public List<? extends Car> getList() {
        return new ArrayList<Car>();
    }
}

public class Convertible extends Car {
    @Override
    public List<? extends Convertible> getList() {
        return new ArrayList<Convertible>();
    }
}

In order to not use a cast I would have to return a specific type of element in the list (List<Convertible>) but then if I wanted to extend the class Convertible I could not do it anymore.
Is there any way around this situation?

A: You can write
public class Vehicle<V extends Vehicle> {
    public List<V> getList() {
        return new ArrayList<V>();
    }
}

public class Car<C extends Car> extends Vehicle<C> {
}

public class Convertible extends Car<Covertible> {
}

A: If you want to be able to write
List<Vehicle> list1 = new Vehicle().getList();
List<Car> list2 = new Car().getList();
List<Convertible> list3 = new Convertible().getList();

you are out of luck. List<Car> is not a subtype of List<Vehicle> so the return types are incompatible. You can get rid of the compiler warnings using your code by writing, for example
List<Car> list = new ArrayList<Car>(new Car().getList());

However, I'm not really sure why the method getList() needs to be inherited. If you always know the type of Vehicle that you are calling the method on you may as well have a separate method in each class, called getVehicleList(), getCarList() and getConvertibleList(), returning a List<Vehicle>, a List<Car> and a List<Convertible> respectively.


text:
Q: rtk query ts error jwt does not exists on type Why I get this error ?
Property 'jwt' does not exist on type '{ data: IAuthResponse; } | { error: FetchBaseQueryError | SerializedError; }'.
  Property 'jwt' does not exist on type '{ data: IAuthResponse; }'.ts(2339)

I use RTK Query and want to handle my response:
Query.tsx
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import { IAuthLoginForm } from '../../../components/Login/Model';
import { IAuthResponse } from './Model';

export interface IAuthResponse {
  jwt: string;
  name: string;
  username: string;
  profile_name: string;
}

export const AuthFlow = createApi({
  reducerPath: 'AuthFlow',
  baseQuery: fetchBaseQuery({ baseUrl: 'http://192.168.0.249:4000/' }),
  endpoints: (builder) => ({
    login: builder.mutation<IAuthResponse, IAuthLoginForm>({
      query: (form) => ({
        url: '/login',
        method: 'POST',
        body: form
      })
    })
  })
});

export const { useLoginMutation } = AuthFlow;

Home.tsx
...
const [register, { data, error, isLoading }] = useLoginMutation();

const Submit = () => {
 const response = await register('test');

 if(response.jwt) {
   // ERROR above jwt not exists on property
 }
};

Why I get this error if I want to access .jwt ? I use it in my Model..
can anyone help me to solve this issue ?

A: From the RTK Query docs:

The "mutation trigger" is a function that when called, will fire off the mutation request for that endpoint. Calling the "mutation trigger" returns a promise with an unwrap property, which can be called to unwrap the mutation call and provide the raw response/error. This can be useful if you wish to determine whether the mutation succeeds/fails inline at the call-site.

Your mutation trigger here is the register, so to access the data from your response with rtk query you should use one of this approaches:
const Submit = async (data: IAuthLoginForm) => {
 // note the unwrap here, you always use it to get the data
 await register(data).unwrap().then((response) => {
   // Handle the response here
   console.log(response)
 });
};

Or use the useEffect hook to get the response data
const Submit = (data: IAuthLoginForm) => {
 register(data)
};

useEffect(() => {
   // use the const data to get the response
   console.log(data)
}, [data])

to handle errors you can call .catch nested to .then like this:
const Submit = async (data: IAuthLoginForm) => {
 await register(data).unwrap().then((response) => {
   // Handle the response here
   console.log(response)
 }).catch((error) => {
   // Handle the error here
   console.log(error)})
};

Or you can use the const error from your useLoginMutation inside an useEffect just like i did with the const data:
useEffect(() => {
   // use the const error to get the error
   console.log(error)
}, [error])

One last thing, to send the data properly to the server, the data that comes from the submit should be the same type of the data that you defined in your builder.mutation<IAuthResponse, IAuthLoginForm>
So you have also two approaches here:
const Submit = async (data: IAuthLoginForm) => {
 // send the same data type from submit and just pass to register
 await register(data).unwrap().then((response) => {
   // Handle the response here
   console.log(response)
 });
};

Or pass each data individually to register like so:
const Submit = async (data: IAuthLoginForm) => {
 // note that i used an example here because i don't know how your interface IAuthLoginForm looks like
 await register({data1: data.data1, data2: data.data2 }).unwrap().then((response) => {
   // Handle the response here
   console.log(response)
 });
};

Some reference about the unwrap and mutations for you: Frequently Used Mutation Hook Return Values


text:
Q: Existentially closed Field property Let $\mathcal{L}$ be the first-order language of theory of rings. Let A,B be two infinite fields. Suppose that A is existentially closed in B. We know that

A is existentially closed in B iff B can be embedded in a $\mathcal{L}$-structure B* which is elementary extension of A

Since A is existentially closed in B, A is also algebraically closed in B. The above proposition also tell us that A is algebraically closed in B* since B*/A is a regular extension. Here is my question :

Is B necessary algebraically closed in B* ?

I guess $\mathbb{C}$ and the rational function field $\mathbb{C}(T)$ may be a counterexample.

A: Your counterexample works. $\mathbb{C}$, being an existentially closed field, is existentially closed in $\mathbb{C}(T)$. So we can find an extension field $K$ with $\mathbb{C}(T)\subseteq K$ and $\mathbb{C}\preceq K$ (for example, $\overline{\mathbb{C}(T)}$ works). Then $K$ is algebraically closed, so $\mathbb{C}(T)$ is not algebraically closed in $K$ (for example, $K$ contains $\sqrt{T}$).


text:
Q: Passing calculated variable to another View I am trying to create my own grid, which resizing to every element. It's okay with that. Here is a code
GeometryReader { geo in
            let columnCount = Int((geo.size.width / 250).rounded(.down))
            let tr = CDNresponse.data?.first?.translations ?? []
            let rowsCount = (CGFloat(tr.count) / CGFloat(columnCount)).rounded(.up)
            LazyVStack {
                ForEach(0..<Int(rowsCount), id: \.self) { row in // create number of rows
                    HStack {
                        ForEach(0..<columnCount, id: \.self) { column in // create columns
                            let index = row * columnCount + column
                            if index < (tr.count) {
                                VStack {
                                    MovieCellView(index: index, tr: tr, qualities: $qualities)
                                }
                            }
                        }
                    }
                }
            }
        }

But since I don't know the exact number of elements and their indices, I need to calculate them in view.
let index = row * columnCount + column

And that's the problem - if I pass them as usual (MovieCellView(index: index  ... )) when the index changing, the new value is not passed to view.
I cannot use @State and @Binding, as I cannot declare it directly in View Builder and can't declare it on struct because I don't know the count. How to pass data correctly?
Code of MovieCellView:
struct MovieCellView: View {
    @State var index: Int
    @State var tr: [String]
    @State var showError: Bool = false
    @State var detailed: Bool = false

    @Binding var qualities: [String : [Int : URL]]

    var body: some View {
        ...
    }

}

The most simple example
Just added Text("\(index)") in VStack with MovieCellView and Text("\(index)") in MovieCellView body. Index in VStack always changing, but not in MovieCellView.

It is necessary to clarify, my application is on a macOS and the window is resized

A: This is my solution (test code) to your issue of passing calculated variable to another View.
I use an ObservableObject to store the information needed to achieve what you are after.
import SwiftUI

@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

class MovieCellModel: ObservableObject {
    @Published var columnCount: Int = 0
    @Published var rowCount: Int = 0

    // this could be in the view
    func index(row: Int, column: Int) -> Int {
        return row * columnCount + column
    }
}

struct ContentView: View {
    @StateObject var mcModel = MovieCellModel()
    @State var qualities: [String : [Int : URL]] = ["":[1: URL(string: "https://example.com")!]] // for testing
    let tr = CDNresponse.data?.first?.translations ?? [] // for testing

    var body: some View {
        VStack {
            GeometryReader { geo in
                LazyVStack {
                    ForEach(0..<Int(mcModel.rowCount), id: \.self) { row in // create number of rows
                        HStack {
                            ForEach(0..<mcModel.columnCount, id: \.self) { column in // create 3 columns
                                if mcModel.index(row: row, column: column) < (tr.count) {
                                    VStack {
                                        MovieCellView(index: mcModel.index(row: row, column: column), tr: tr, qualities: $qualities)
                                    }
                                }
                            }
                        }
                    }
                }.onAppear {
                    mcModel.columnCount = Int((geo.size.width / 250).rounded(.down))
                    mcModel.rowCount = Int((CGFloat(tr.count) / CGFloat(mcModel.columnCount)).rounded(.up))
                }
            }
        }

    }
}

struct MovieCellView: View {
    @State var index: Int

    @State var tr: [String]
    @Binding var qualities: [String : [Int : URL]]

    @State var showError: Bool = false
    @State var detailed: Bool = false

    var body: some View {
        Text("\(index)").foregroundColor(.red)
    }
}

A: The only variable that changes outside of a ForEach in your index calculation is columnCount. row and column are simply indices from the loops. So you can declare columnCount as a @State variable on the parent view, hence when it changes, the parent view will update and hence all of the cells will also update with the new columnCount.
@State private var columnCount: CGFloat = 0

var body: some View {
    GeometryReader { geo in
        columnCount = Int((geo.size.width / 250).rounded(.down))
        let tr = CDNresponse.data?.first?.translations ?? []
        let rowsCount = (CGFloat(tr.count) / CGFloat(columnCount)).rounded(.up)
        LazyVStack {
            ForEach(0..<Int(rowsCount), id: \.self) { row in // create number of rows
                HStack {
                    ForEach(0..<columnCount, id: \.self) { column in // create 3 columns
                        let index = row * columnCount + column
                        if index < (tr.count) {
                            VStack {
                                MovieCellView(index: index, tr: tr, qualities: $qualities)
                            }
                        }
                    }
                }
            }
        }
    }
}

A: Since none of the answers worked, and only one worked half, I solved the problem myself. You need to generate a Binding, and then just pass it
var videos: some View {
        GeometryReader { geo in
            let columnCount = Int((geo.size.width / 250).rounded(.down))
            let rowsCount = (CGFloat((CDNresponse.data?.first?.translations ?? []).count) / CGFloat(columnCount)).rounded(.up)
            LazyVStack {
                ForEach(0..<Int(rowsCount), id: \.self) { row in // create number of rows
                    HStack {
                        ForEach(0..<columnCount, id: \.self) { column in // create 3 columns
                            let index = row * columnCount + column
                            if index < ((CDNresponse.data?.first?.translations ?? []).count) {
                                MovieCellView(translation: trBinding(for: index), qualities: qualityBinding(for: (CDNresponse.data?.first?.translations ?? [])[index]))
                            }
                        }
                    }
                }
            }
        }
    }
    private func qualityBinding(for key: String) -> Binding<[Int : URL]> {
        return .init(
            get: { self.qualities[key, default: [:]] },
            set: { self.qualities[key] = $0 })
    }
    private func trBinding(for key: Int) -> Binding<String> {
        return .init(
            get: { (self.CDNresponse.data?.first?.translations ?? [])[key] },
            set: { _ in return })
    }

struct MovieCellView: View {
    @State var showError: Bool = false
    @State var detailed: Bool = false
    @Binding var translation: String

    @Binding var qualities: [Int : URL]

    var body: some View {
        ...
    }

}


text:
Q: IDEA 2021.2 NPM SCRIPTS : No Scripts found I cannot find any npm scripts , but package.json has:

A: Package.json isn't correctly recognized. Check Settings/Preferences > Editor > File types, package.json is probably added as a pattern to Text or Auto-detect file type by content file types .


text:
Q: RxSwift - subscribe to a method Is there a way with RxSwift to subscribe to a method which returns a completion block?
Example, let's have this object:
struct Service {

    private var otherService = ...
    private var initSucceeded = PublishSubject<Bool>()

    var initSucceededObservale: Observable<Bool> {
        return initSucceeded.asObservable()
    }

    func init() {
        otherService.init {(success) in
            self.initSucceeded.onNext( success)
        }
    }
}

And in a different place have a way to be notified when the service has been initialised:
service.initSucceededObservable.subscribe(onNext: {
    [unowned self] (value) in
    ...
}).addDisposableTo(disposeBag)

service.init()

Would be there a simpler solution?

A: I like to use Variables for this sort of thing. Also, I'd recommend using class here because you're tracking unique states and not just concerning yourself with values.
class Service {
    private let bag = DisposeBag()
    public var otherService: Service?

    private var isInitializedVariable = Variable<Bool>(false)

    public var isInitialized: Observable<Bool> {
        return isInitializedVariable.asObservable()
    }

    public init(andRelyOn service: Service? = nil) {
        otherService = service

        otherService?.isInitialized
            .subscribe(onNext: { [unowned self] value in
                self.isInitializedVariable.value = value
            })
            .addDisposableTo(bag)
    }

    public func initialize() {
        isInitializedVariable.value = true
    }

}

var otherService = Service()
var dependentService = Service(andRelyOn: otherService)

dependentService.isInitialized
                .debug()
                .subscribe({
                    print($0)
                })

otherService.initialize() // "Initializes" the first service, causing the second to set it's variable to true.

A: You could use a lazy property:
lazy let initSucceededObservale: Observable<Bool> = {
    return Observable.create { observer in
        self.otherService.init {(success) in
            observer.on(.next(success))
            observer.on(.completed)
        }
        return Disposables.create()
    }
}()

and then you can use:
service.init()
service.initSucceededObservable.subscribe(onNext: {
    [unowned self] (value) in
    ...
}).addDisposableTo(disposeBag)

Let me know in the comments if you have problems before downvoting, thanks.


text:
Q: How to get chrome version using command prompt in windows Is it possible to get version installed chrome version using command prompt in windows?
Tried,
 "C:\Program Files\Google\Chrome\Application\chrome.exe" -version
 "C:\Program Files\Google\Chrome\Application\chrome.exe" --version
 "C:\Program Files\Google\Chrome\Application\chrome.exe" -product-version
 "C:\Program Files\Google\Chrome\Application\chrome.exe" --product-version

When i do that, a browser instance is opening. What flag should I be using to get the version.
I am using Windows 7. Google Chrome version is 67.0.3396.87.
Thanks in advance

A: Using only commandline utils
dir /B/AD "C:\Program Files (x86)\Google\Chrome\Application\"|findstr /R /C:"^[0-9].*\..*[0-9]$"
78.0.3904.97

List only directories /AD within the Chrome application folder in short form /B.
findstr /R /C:"..." applies the following regex to the list of directories. The regex matches every foldername starting with a digit ^[0-9] and ending with ad digit [0-9]$.
Between the first and last digit there are any characters .* allowed but at least one dot should appear \.

A: As of today user4851's is still working. I took a look at his linked bug report and the proposed work around did not work for me anymore.
Anways a new hkey is present in my directory which allows you to query the chrome version without being aware of the actual installation location:
reg query "HKEY_CURRENT_USER\Software\Google\Chrome\BLBeacon" /v version

A: There's a bug filed about this: https://bugs.chromium.org/p/chromium/issues/detail?id=158372
Original Answer (but see the update below)
What works for me is
wmic datafile where name="C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe" get Version /value

It prints
Version=67.0.3396.99

surrounded by some blank lines.
There are some other suggestions in the bug comments, like querying the registry.
Update
Someone from the Chromium team posted this "totally unsupported" batch file in the bug comment thread:
@ECHO OFF

:: Look for machine-wide Chrome installs (stable, Beta, and Dev).
:: Get the name, running version (if an update is pending relaunch), and
:: installed version of each.
FOR %%A IN (
    {8A69D345-D564-463c-AFF1-A69D9E530F96},
    {8237E44A-0054-442C-B6B6-EA0509993955},
    {401C381F-E0DE-4B85-8BD8-3F3F14FBDA57}) DO (
  reg query HKLM\Software\Google\Update\Clients\%%A /v name /reg:32 2> NUL
  reg query HKLM\Software\Google\Update\Clients\%%A /v opv /reg:32 2> NUL
  reg query HKLM\Software\Google\Update\Clients\%%A /v pv /reg:32 2> NUL
)

:: Look for Chrome installs in the current user's %LOCALAPPDATA% directory
:: (stable, Beta, Dev, and canary).
:: Get the name, running version (if an update is pending relaunch), and
:: installed version of each.
FOR %%A IN (
    {8A69D345-D564-463c-AFF1-A69D9E530F96},
    {8237E44A-0054-442C-B6B6-EA0509993955},
    {401C381F-E0DE-4B85-8BD8-3F3F14FBDA57},
    {4ea16ac7-fd5a-47c3-875b-dbf4a2008c20}) DO (
  reg query HKCU\Software\Google\Update\Clients\%%A /v name /reg:32 2> NUL
  reg query HKCU\Software\Google\Update\Clients\%%A /v opv /reg:32 2> NUL
  reg query HKCU\Software\Google\Update\Clients\%%A /v pv /reg:32 2> NUL
)

That should probably be seen as the right way to go for the time being.

A: I tried Kilian's answer, however in my case, I was running it against a bunch of machines remotely via a service, so I don't think HKEY_CURRENT_USER was valid:
ERROR: The system was unable to find the specified registry key or value.

Assuming you know where the exe is, you can try a different approach and read the version property of the exe file:
# Powershell
# Older versions install to the 32-bit directory
(Get-Item "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe").VersionInfo

# Newer versions use the 64-bit directory
(Get-Item "C:\Program Files\Google\Chrome\Application\chrome.exe").VersionInfo

ProductVersion   FileVersion      FileName
--------------   -----------      --------
76.0.3809.100    76.0.3809.100    C:\Program Files (x86)\Google\Chrome\Application\chrome.exe

To using it in cmd.exe or via any subprocess calls (python, go os/exec, etc.) you can do,
powershell -command "&{(Get-Item 'Absolute\path\to\chrome.exe').VersionInfo.ProductVersion}"

A: user1425134's solution worked for me, but if you are allowed to assume that Chrome is part of %PATH% (if you can open Command Prompt and type chrome to start the browser), then it can be greatly simplified.
From Powershell you can type (Get-Command "chrome").Version.ToString()
Or from cmd.exe you can type powershell -c "(Get-Command "chrome").Version.ToString()"
(same for Chromium, just replace the command name)

A: I was able to use the rust kitty's solution without having chrome on my path, as:

*

*from PowerShell:

(Get-Command C:\Program Files (x86)\Google\Chrome\Application\chrome.exe').Version.ToString()

*

*from cmd:

powershell -command "(Get-Command C:\Program Files (x86)\Google\Chrome\Application\chrome.exe').Version.ToString()"

A: Via Powershell the command is -
Get-WmiObject -Class Win32_Product | ? {$_.name -eq 'Google Chrome'} |select Name,Version


text:
Q: How to change border of this image I am making a game using this function:
if (CGRectIntersectsRect(object.frame, object2.frame)) {
   [self GameOver];
}

Both objects are square however the image of object #2 is not. Therefore when the borders collide (but not the actual pictures) the game ends. Is there a way I can have the border "fit" to the image, so that the game only ends when the actual pictures collide.
Thanks :)
**my image is a shark and therefore a rectangle cannot be used

A: A view's frame is always a CGRect, which is a rectangle. You can use UIKit Dynamics for collision detection with views, but that only support rectangles too.
As @jammycoder mentioned, try out SpriteKit or other game engines, if you need to detect custom shape bounds.


text:
Q: Geometric interpretation of an integral inequality Let $f: [a, b] \to \mathbb [0, \infty)$ be an integrable function.
By the Cauchy-Schwarz inequality:
$$ \left(\int_a^b f(x) dx\right)^2 \leq (b-a) \int_a^b f(x)^2 dx$$
with equality iff $f$ is constant.
If we notate $\mu(f) := \frac{1}{b-a} \int_a^b f$, dividing with $\frac{1}{(b-a)^2}$ we get
$$\mu(f)^2 \leq \mu(f^2)$$
i.e. the square of the mean of a function is no larger than the mean of the square of a function, and the equality occurs iff $f$ is constant.
Is there an elegant intuitive way to see this geometrically? The best I can do is to use a discrete analogue while approximating $f$ and $f^2$ with rectangles (the definition of the integral).
Is there a more visual approach?

A: Here's one way to look at it. I don't know how intuitive it is, because I can't find a good way to express the geometric reasoning, but maybe it says something to someone.
If the curve $f$ between $a$ and $b$ rotates around the $x$-axis, the resulting object $A$ has volume
$$
V_A = \pi \int_a^b f(x)^2\,\mathrm{d}x = \pi (b-a) \mu(f^2).
$$
Let $g=\mu(f)$, the average of $f$. If the curge $g$ rotates around the $x$ axis, the resulting object $B$ is a cylinder with volume
$$
V_B = \pi (b-a) \mu(f)^2.
$$
Now compare $A\setminus B$, that is, the part of $A$ which is outside $B$, with $B\setminus A$, the part of $B$ which is outside $A$. Your result is equivalent to the fact that the volume of $A\setminus B$ is larger than the volume of $B \setminus A$.
Unfortunately I can't think of a good way to explain this geometrically, but it feels intuitive, if you remember that the radius of $B$ is the average of the radius of $A$. My intuitive idea is similar to comparing three circles of radii $r-r'$, $r$, and $r+r'$: clearly the difference between the areas of the two smallest circles is smaller than the difference between the areas of the two largest circles.

A: Combining JiK's (and implicitly john mangual's) answer, and Semiclassical's comments: If the region enclosed by the $x$-axis and the graph $y = f(x) - \mu(f)$ (subject to $a \leq x \leq b$) is revolved about the $x$-axis, the (non-negative) volume swept out (multiplied by $1/\pi$) is given by
\begin{align*}
\int_{a}^{b} \bigl[f(x) - \mu(f)\bigr]^{2}\, dx
  &= \int_{a}^{b} \bigl[f(x)^{2} - 2f(x)\mu(f) + \mu(f)^{2}\bigr]\, dx \\
  &= \left[\int_{a}^{b} f(x)^{2}\, dx\right] - \mu(f)^{2}.
\end{align*}

The same volume is swept out by revolving the graph $y = \bigl|f(x) - \mu(f)\bigr|$, if you want to avoid revolving a region that dips below the $x$-axis.

A: In physics this is known as the parallel axis theorem.

The Moment of intertia of a body $A \in \mathbb{R}^2$ is the average distance squared relative to the center of Mass:
$$ I_{CM} = \mathbb{E}\big[ || r - \overline{r}||^2\big] = \int_A \big[(x-x_0)^2 + (y-y_0)^2\big] \;dA$$
How do you compute moments relative to other axes?  Then we have formula:
$$ I = I_{CM} + m d^2 $$
$m$ is the mass of your object and $d$ is the distance between the center of your two axes.  In probability theory we could say:
$$ \mathbb{E}[ (X - a)^2] =  \mathbb{E}[ X^2] -  2a  \mathbb{E}[ X] +  a^2 \geq 0 $$
So this is certainly minimized when $a = \mathbb{E}[X]$


text:
Q: USB 3.0 ports backwards compatibility problems with 2.0 devices? I see some info on the net that suggest that I should be able to get my USB 2.0 devices to work in 3.0 ports.  I only have two 2.0 ports on my new computer, and six 3.0 ports.  I have installed drives. There's two different drivers, I guess some of the ports are supported by the intel board and some supported by some other chipset on the motherboard.
I however have yet to get any of the 3.0 ports to work, and my brother had had the same issue with his devices not working in 3.0 ports on his computer.  So I am beginning to wonder if the backwards compatibility isn't reliable for some reason.  Maybe manufacturers opting not to implement 2.0 support on the 3.0 ports.  I understand that physically the wiring is there, but that is only half the story.
Beyond my brother's and my own computers (different motherboards/everything), I have yet to see a 2.0 device work in a 3.0 port. Is there any reason for this apparent device incompatibility?  I.e. looking for responses that would indicate what areas to explore for issues or if there is any known cases of manufacturers deviating from spec in hardware or drivers.  I am aware it's "supposed" to work :)
Update:  Does this have any relation to "USB Legacy Support" options in the BIOS?  There several options combinations of options with "USB Legacy Support" and "USB 3.0 Legacy Support" and the description for these is a bit confusing, sounds like a bad translation.

A: From Wikipedia:

Compatibility of USB 3.0 connectors

*

*Type A plugs and receptacles from both USB 3.0 and USB 2.0 are designed to interoperate.

*Type B receptacles in USB 3.0 are somewhat larger than would be required for a Type B plug in USB 2.0 and earlier. This is intended to allow connecting an older Type B plug into a newer USB 3.0 Type B receptacle. Accordingly, a USB 3.0 Type B receptacle on a peripheral device can be connected using the corresponding plug end of a USB 2.0 Type B cable.

*Type B plugs in USB 3.0 are somewhat larger; therefore, a USB 3.0 Type B plug cannot enter a USB 2.0 or earlier Type B receptacle. Accordingly, normal USB 3.0 Type B plugs cannot be inserted into normal USB 2.0 Type B receptacles found on peripheral devices (and connect them to a computer).

*A receptacle for eSATAp (eSATA/USB Combo) is designed to accept USB Type A plugs from USB 2.0 and USB 3.0.

In theory, there should not be a problem at the hardware level.  However, there may be a problem with the drivers or the underlying controller for the ports.
To determine if this is a hardware or software problem, try booting into a Linux live CD and see if USB 2.0 devices work in the USB 3.0 ports. If they do work, the problem is in the drivers. If not, the problem is in the hardware.
Legacy support in the BIOS only applies to systems that do not natively support USB in general.  When this setting is enabled, the BIOS attempts to provide a compatibility layer for very old operating systems such as Windows 95 or MS-DOS, so that storage devices attached to these ports can be used (probably with some restrictions such as no hot-plugging).  I'm not sure about this, but USB 3.0 legacy support setting is probably to allow USB 3.0 devices on such operating systems to communicate at USB 3.0 speeds.  An operating system that supports USB should not be affected by these settings, as they can communicate with the USB hub controllers directly without having to rely on the BIOS.

A: I've tried plugging in USB 2.0 devices such as flash drives, external HDDs, keyboards, mice, etc into USB 3.0 ports on the HP ENVY 15 and the Macbook Pro Retina without any issues.
If you guys built the computer yourselves, make sure you have the latest drivers installed.
P.S. I am aware of some people having issues with USB 3.0 compatibility on some very early USB 3.0 capable hardware that rolled out about 2 years ago.

A: I put BIOS settings back to original values, gave up on hunting for newer drivers, and decided to focus on Device Manager.
In my case I could see under Device Manager(go to Control Panel and enter Device Manager in the upper right search field) a couple "Unknown device" entries under the Other node.  Right click->Properties->Details->Hardware Ids, I Googled each.  One was Intel Smart Connect which I deliberately didn't install and unrelated to USB so I ignored it and moved on to the other Unknown device.  The other had "USB" as part of the hardware ID(but not all will be this obvious), but you can right click one of them from the Values section and clicked Copy then google it, and there are some driver sites out there that will have that ID and give you a clue as to what it is.  In my case it was a "Intel(R) USB 3.0 Root Hub".  This is the screen:

This screen was after fixing it, while it is Unknown it won't have the name or icon up top, but you can still copy the hardware IDs for Googling.
I strongly distrust the driver sites as some might have malware/adware.  I would only download drivers from Microsoft or the manufacturers.
In my case, I had already exhausted the Intel USB drivers with several installs/updates/reboots with no luck.
Having found the specific device that was having problems though, I went to the Driver tab and chose Update Drive...

And then chose "Search automatically...".  To my surprise it found the driver and installed it.  Give device manager some time to refresh.  There was then another entry in the Other Devices node,  as if once it had the first device working it could then see a "USB Root Hub", I opened it and did Update Drives->Search as well.  It seemed like the 3.0 Hub was fixed, then the system could see the other hub which I assume is the 2.0 Hub.
After installing the drivers for both of these via the search online feature, I could then plug in a 2.0 device to a 3.0 port, and get a Installing device notification, and shortly it would be working.
I can't remember the "Search online" for drivers feature ever working before.  I doubted it would work also because I had already run Windows Update, and at some point in the past Windows Update used to download drivers in the optional section(which is worth a try for others having similar issues).
By the time I was done, I had entries for the USB 3.0 Host Controller, USB 3.0 Root Hub, and USB Root Hub.

A: Some motherboards support 3.0 using more than one chipset.  In my case the front and 2 of the back USB 3.0 ports were Intel ports, 2 were Intel 2.0 ports, and 2 other 3.0 ports were supported by ASMedia ASM1042 drivers.
So I needed to try each port to determine which back ports were not working and which were.  It was important to leave the device plugged in for at least 10 seconds or so to give Windows time to start installing drivers and then wait for the notification to indicate it was successful.  Once I knew which ports were working, I then uninstall both ASMedia and Intel drivers, rebooted, installed only the ASMedia drivers, and the ports started working, indicating that the ASMedia ports+drivers worked(although a reboot might be required, it wasn't for me).  So now I know the others not working are Intel ports.
Then I could plug my device into the other non-working ports and be certain of which ports were and were not working and which drivers went with the non-working ports, so I could focus on that and not keep wondering which driver was the problem.
Also I focused on the back ports because if there was a connection issue with the front ports, then I wanted to not let that prevent me from determining when/if the drivers were installed correctly.  (When you have more than one thing wrong it is difficult to fix because you fix one thing but don't know it's fixed cause something else is also wrong, so you undo your fix thinking it wasn't really a fix.)


text:
Q: When checking whether a formula is a logical consequence of a set of premises, is it always necessary to check whether the set is satisfiable before? (Propositional logic problem):
Lets say that I have to decide whether this formula B really is a logical consequence of a set of premises {A, ¬A∨B}. Formally written: {A, ¬A∨B}⊧B . To find out, I can can reduce it to a problem of whether this formula is a tautology: (A∧(¬A∨B))⇒B. If this formula is a tautology, it means that formula B is a logical consequence of the premises. But it is possible that the premises are unsatisfiable (=they have no model). In that case anything could be a logical consequence.
I can also reduce the problem of whether B is a logical consequence of premises {A, ¬A∨B} to a problem of whether formula A∧(¬A∨B)∧¬B is unsatifiable. If the formula is unsatifiable it means that the formula B is a consequence. If the premises are unsatifiable the formula B will be a logical consequence and any other formula as well.
My question is: Is it always necessary to check whether a set of premises are satifiable in order to find out whether the formula really flows from these premises? In my textbook they never check whether premises are satifiable and just solve whether the problem reduced to previous problems is a tautology/contradiction. Because of my textbook I am confused if it is always really necessary (because it takes time to check if premises are satifiable).

A: The statement $\Gamma\vDash \phi$ has the meaning "in all models where the formulas in $\Gamma$ are true, also the formula $\phi$ is true."
If we want to show that $\Gamma\vDash\phi$, two methods seem reasonable:

*

*If we show that $\phi$ is a direct consequence of (some of) the formulas in $\Gamma$, then we have proved that $\Gamma\vDash\phi$.

*If we show that $\Gamma$ is insatisfiable, then we have also proved that $\Gamma\vDash\phi$, since vacuously $\phi$ will hold in any model where $\Gamma$ holds.

Showing that $\Gamma$ is satisfiable only proves that the second method will not work. So, although it is perhaps helpful to know that there exist models of $\Gamma$, it does not help in any way to show that $\Gamma\vDash\phi$.

In fact, showing that $\Gamma$ is satisfiable can be very hard or even impossible. Take for example a set $\Gamma$ that contains a lot of formulas, as well as $\phi$ itself. Then $\Gamma\vDash\phi$, since $\phi\vDash\phi$. But, finding out if $\Gamma$ is satisfiable will take a lot more effort.
In first-order logic, Gödel's Second Incompleteness Theorem shows that no set of formulas that is strong enough to formulate arithmetic in (for example the set of axioms for Peano Arithmetic) can prove its own consistency. What this means, is that such a set of axioms might be satisfiable, but it is impossible to prove it (within the system itself).
But even if we just look at propositional logic, the task of determining whether a set of formulas is satisfiable is computationally very difficult, and cannot be done efficiently (as far as we know). In fact, it is an archetype of a difficult problem, know as the SAT problem.


text:
Q: SQL Server Management Studio - Query using text file Let's say I have a text file that has the following lines
102
333
534

Then, in my SQL table, I have a few different columns:
  AutoID | Name     | Description
  --------------------------------------
    102  | Jackson  | [Description Here]
    241  | Edward   | [Description Here]
    333  | Timothy  | [Description Here]
    437  | Nikky    | [Description Here]
    534  | Jeremy   | [Description Here]

Is there anyway I can parse the text file through SQL Server Management Studio so that it will query the table and pull out every row that has a column (AutoID, in this case) that matches a line in the text file (Note, I only want the rows from a table that I would specify)?
This way I could edit them or update the rows that only match IDs in the text file.
The rows displayed in management studio would look like this.
  AutoID | NAME     | Description
  --------------------------------------
    102  | Jackson  | [Description Here]
    333  | Timothy  | [Description Here]
    534  | Jeremy   | [Description Here]

A: --What you need to do is import the text file into a table in your SQL database, and then compare its values to the table you want to query (which I have called AutoIDTest in my example).
--Using your example data, I've put together the following code that accomplishes this process.
--1. I created a destination table for the text file's values called TextImport.  I've called the test text file E:\TestData.txt.  Additionally, I'm assuming this text file only has one column, autoID.
--2. Then, I imported the data into the destination table using the BULK INSERT statement.
--3. Finally, I compared the data in TextImport to the table from which you are seeking values using an INNER JOIN statement.
CREATE TABLE AutoIDTest ---Create test table.  Since your first column doesn't have a name, I'm calling it ID. I'm assuming AutoID and ID are both of type int.
    (
    ID int,
    AutoID int,
    Name varchar(25),
    Description varchar(50)
    )

INSERT INTO AutoIDTest -- Populate test table
VALUES
    ( 1, 102, 'Jackson', 'Description1'),
    ( 2, 241, 'Edward', 'Description2'),
    ( 3, 333, 'Timothy', 'Description3'),
    ( 4, 437, 'Nikky', 'Description4'),
    ( 5, 534, 'Jeremy', 'Description5')

CREATE TABLE TextImport --Create destination table for text file.
    (
    AutoID varchar(20),
    )

BULK INSERT TextImport --Load Data from text file into TextImport table
   FROM 'E:\TestData.txt'  ---The name and location of my test text file.
   WITH
      (
         ROWTERMINATOR ='\n'
      );

SELECT   ---Produce Output Data
    ID,
    t1.AutoID,
    Name,
    Description
FROM
    AutoIDTest AS t1
INNER JOIN
    TextImport AS t2
    ON t1.autoID = cast(t2.autoID AS int) --convert varchar to int

OUTPUT
--    ID          AutoID      Name                      Description
--    --------- ----------- ------------------------- -------------------
--    1           102         Jackson                   Description1
--    3           333         Timothy                   Description3
--    5           534         Jeremy                    Description5


text:
Q: TensorFlow GPU doesn't work, How to install it? I started learning about the tensorflow recently and decided to switch to the GPU version, because it is much faster, but I can not import it, it always gives the same error.
I already tried:

*

*Installing it by pip, in python 3.6.8, cuda 10 and the most recent cuDNN for cuda 10

*I tried reinstalling python, CUDA and cuDNN

*Tried installing Visual Studio and installed CUDA 9 and cuDnn

*I tried installing the latest Anaconda, created a "default" env and another in python 3.6 (also tried in 3.5), pip install tensorflow-gpu in both cases

*my last attempt was to follow a tutorial on youtube, I did exactly as demonstrated (https://www.youtube.com/watch?v=KZFn0dvPZUQ)

Everything i tried returned the same error.
Traceback: https://pastebin.com/KMEsZAmq
The complete code: https://pastebin.com/7tS0Rd5S (was working on CPU version)
    .

My Specs:

*

*i5-8400

*8 GB Ram

*GTX 1060 6GB

*W10 home x64

A: just have a look here:
https://www.tensorflow.org/install/gpu
Tensorflow supports CUDA 9.0, you will need to downgrade your CUDA or use one of the tensorflow's docker images:
https://www.tensorflow.org/install/docker
via docker it won't use your CUDA drivers


text:
Q: Why can a static method be accessed without a fully-qualified name in a subclass? The following code demonstrates that the subclass named SubClass has a direct access to a final static synchronized method named staticMethod. There is no need to associate it with its class name.
package synchronizedpkg;

class SuperClass
{
    public final static synchronized void staticMethod()
    {
        System.out.println("Method called.");
    }
}

final class SubClass extends SuperClass
{
    public void woof()
    {
        staticMethod();
    }
}

final public class Main
{
    public static void main(String[] args)
    {
        new SubClass().woof();
    }
}

This is somewhat confusing in terms of inheritance because a final method can not be inherited and consequently should not directly be accessed by it's subclasses. How does a final static method as shown above have a direct access from its child class?

A: The static method is inherited just like instance methods. From section 8.4.8 of the JLS:

A class C inherits from its direct superclass and direct superinterfaces all non-private methods (whether abstract or not) of the superclass and superinterfaces that are public, protected or declared with default access in the same package as C and are neither overridden (§8.4.8.1) nor hidden (§8.4.8.2) by a declaration in the class.

That doesn't say anything about only inheriting instance methods.

A: Your understanding is wrong:

This is somewhat confusing in terms of inheritance because a final
  method can not be inherited and consequently should not directly be
  accessed by it's subclasses. How does a final static method as shown
  above have a direct access from its child class?

A final method cannot be overridden, or in the case of a static method hidden, it is still inherited. If you want to prevent the subclass from seeing it, then you must make it private.
So, it is visible, hence you can access it. And it is a member, hence you don't need to qualify it.

A: From Understanding Instance and Class Members:
"The Java programming language supports static methods as well as static variables. Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as in
ClassName.methodName(args)

Note:
You can also refer to static methods with an object reference like
instanceName.methodName(args)

but this is discouraged because it does not make it clear that they are class methods."
Hence, you can call a static method from an instance that inherits it OR from its class name.  This means that for all intents and purposes, you can imagine the above method as not being static, and you can inherit it normally.
EDIT: As to the final modifier, this just means that the method cannot be overridden in a subclass. Far as I can see, you aren't doing that, so it does not affect the outcome. You can read about this here.

A: Static means which is same for all objects. So, it doesn't really matter if you call it with object reference or class reference because it is same for every object.
Example: Suppose you have teacher who teaches to all the students in all grades. So, it doesnt really matter if 1st grade student calls her 1st grade teacher and 2nd grade student calls her 2nd grade teacher or somebody else calls her school teacher. They are all refering to same teacher.
Students can refer to her by name and every other student can know that he is refering to her. But people from outside school, if they have to refer to her they have to say the school name and teachers name.
That's how it works even in java. Java is probably the only language which relates to real world scenarios. Hope this helps..... :)

A: static means class level, it has nothing to do with the objects of the class, you don't need a n object to access static methods


text:
Q: How to create a node in c# I am new to c# and switched from c to c#. I want to do equivalent of c to c#. The same i have in c like this:
  temp = (struct Node*)malloc(sizeof(struct Node));

where Node is:
struct Node
{
    unsigned int symbol ;
    int freq;
    struct Node * next,  * left, * right;
}

And in c# i have used class instead of struct.
I tried to do this way:
 Node temp = new Node();

Where Node is same except that it's a class and used public (I am sure that's correct).
Could you please help me if i am wrong ? Does it correctly create a node equivalent to that i created using malloc() ?

A: Your class should look something like
public class Node
{
    public unsigned int symbol;
    public int freq;
    public Node next;
    public Node left;
    public Node right;
}

If you assign to next, left, and right similar to
Node root = new Node();
root.next = new Node();

You will see behavior very similar to what you were doing in C.
Storage is automatically managed by the runtime, so there are no explicit calls to equivalents of malloc or free.  That all happens behind the scenes.
Also, as a general rule do not use pointers in C#.  While you can do that if you mark your code as unsafe, there are very few instances where unsafe code is the right path for a C# app.
NOTE: The example uses public access to the class and fields.  You may want to restrict that somewhat based on your specific use.

A: It looks correct to me.
As an added bonus, it will also call Node()'s constructor if you have one and initialize the values.

A: class Node
{
    public int symbol ;
    public int freq;
    public Node next;
}

class Program
{
    static void Main(string[] args)
    {
        Node temp = new Node() ;
        temp.symbol = 1;
        temp.freq = 2;
        temp.next = null;
    }
}


text:
Q: how to use rapidxml get all string inside  if I have xml content as below
<node>
   <content> hello <b>world</b>
          <image src="src/image.jpg"/>
   </content>
</node>

I would like to get value as string which have all data inside
or let say
string all_data = node->get_XXXX????();

Finally all_data =="< content > hello < b >world < /b > \n < image src=\"src/image.jpg\"/>\n  < /content > "

A: You need to print it using functions in rapidxml_print.hpp
See here. http://rapidxml.sourceforge.net/manual.html#namespacerapidxml_1printing
// Print to string using output iterator
std::string s;
print(std::back_inserter(s), node, 0);

Be aware that this will potentially reformat whitespace, etc around tags. If that's critical to you, you should find a different way of encoding your document.


text:
Q: Find a file and then use its name as a variable Command Prompt How do I look for a file and assign file name to a variable?
Example:
Let's say I am looking for a file in below location.  File name constantly changes and only way to pick up the right file is by looking for today's date in file name string:
X:\VoyagerBackups\PickupLocation\tsiuiolou_live_Full_PCV048DB42_201812140000.Lts.bak

Here's what I have so far in my .bat file.  Execution works as expected if I hard-code file name:
echo on
Rem Determine date
Set mm1=%date:~4,2%
Set dd1=%date:~7,2%
Set yyyy1=%date:~10,4%

Set rundate1=%yyyy1%%mm1%%dd1%

Set executefile1=tsiuiolou_live_Full_PCV048DB42_%rundate1%0000.Lts.bak
set downloadfile=tsiuiolou_live_Full_PCV048DB42_%rundate1%0000.bak

extractor64.exe -F %executefile1% -E %downloadfile%

move %executefile1% X:\VoyagerBackups\BackupFiles

A: Don't use the locale/user settings dependant %date% variable.
Use either wmic or PowerShell instead, they both have more stable methods.
:: Q:\Test\2018\12\14\SO_53787816.cmd
@Echo off

for /f "usebackq" %%A in (`
  powershell -NoP -C "(Get-Date).ToString('yyyyMMdd')"
`) Do Set "Today1=%%A"
Echo PowerShell today:%Today1%

for /f "tokens=1-3 delims=.+-" %%A in (
  'wmic os get LocalDateTime^|findstr ^^[0-9]'
) do Set "Today2=%%A"
Set "Today2=%Today2:~0,8%"
Echo       wmic today:%Today2%

Set "Base=X:\VoyagerBackups\PickupLocation\"
PushD "%Base%" || (Echo can't find base:%Base%&Pause&Goto :Eof)

For /f "delims=" %%A in ('Dir /B "*%Today1%*" ') Do (
    Echo found file:%%~fA
)
PopD


text:
Q: Slope code not working with movement code I was coding movement code for my game using this video: Movement code video.
Pardon my garbage code...
    void Move(float dir,bool crouchFlag)
    {

        if(!crouchFlag)
        {
            if(Physics2D.OverlapCircle(OverheadChecker.position,CelingCirSize,gLayerMask))
            {
                crouchFlag = true;
            }

        }

        Stand.enabled = !crouchFlag;
        Stand2.enabled = !crouchFlag;
        Croucher.enabled = crouchFlag;

        #region Move & run

        if (isGrounded && !crouchFlag && !isOnSlope)
        {
            Controller.XMove(dir,Speed,rb2d,velPower,acceleration,decceleration);
        } else if (isGrounded && isOnSlope && canWalkOnSlope)
        {
            float TargetSpeed = -dir * Speed;

            float TargetSpeedDif = TargetSpeed - rb2d.velocity.x;

            float accelerRate = (Mathf.Abs(TargetSpeed) > 0.01f) ? airacceleration : airdecceleration;

            float MoveDir = Mathf.Pow(Mathf.Abs(TargetSpeedDif) * accelerRate, velPower) * Mathf.Sign(TargetSpeedDif);

            float MoveDirX = MoveDir * slopeNormalPerp.x * MultSlope;
            float MoveDirY = MoveDir * slopeNormalPerp.y * MultSlope;

            rb2d.AddForce(MoveDirX * Vector2.right);
            rb2d.AddForce(MoveDirY * Vector2.up);
        }
        else if (!isGrounded)
        {
            float TargetSpeed = dir * Speed;

            float TargetSpeedDif = TargetSpeed - rb2d.velocity.x;

            float accelerRate = (Mathf.Abs(TargetSpeed) > 0.01f) ? airacceleration : airdecceleration;

            float MoveDir = Mathf.Pow(Mathf.Abs(TargetSpeedDif) * accelerRate, velPower) * Mathf.Sign(TargetSpeedDif);
            if (rb2d.velocity.y > 0 && !Input.GetButton("Jump"))
            {
                MoveDir = MoveDir * xJumpForce;
            }
            rb2d.AddForce(MoveDir * Vector2.right);
        }else if (isGrounded && crouchFlag)
        {
            rb2d.sharedMaterial = noFriction;
            float TargetSpeed = dir * CrouchSpeed;

            float TargetSpeedDif = TargetSpeed - rb2d.velocity.x;

            float accelerRate = (Mathf.Abs(TargetSpeed) > 0.01f) ? acceleration : Crouchdecceleration;

            float MoveDir = Mathf.Pow(Mathf.Abs(TargetSpeedDif) * accelerRate, velPower) * Mathf.Sign(TargetSpeedDif);

            rb2d.AddForce(MoveDir * Vector2.right);
        }

        if (isGrounded && Mathf.Abs(HorizontalValue) < 0.01f)
        {
            float amount = Mathf.Min(Mathf.Abs(rb2d.velocity.x), Mathf.Abs(fricAmount));

            amount *= Mathf.Sign(rb2d.velocity.x);

            rb2d.AddForce(Vector2.right * -amount, ForceMode2D.Impulse);
        }

        Vector3 CurrentScale = transform.localScale;

        if(Right && dir > 0)
        {
            transform.localScale = new Vector3(1.4f, 1.4f
            , 1);
            Right = false;
        }

        else if (!Right == dir < 0)
        {
            transform.localScale = new Vector3(-1.4f, 1.4f, 1);
            Right = true;
        }

        #endregion

    }

Then I made slopes using a Sprite Shape Controller:
But, the character got stuck on the slopes when going up them, so I used this video for slopes:Fixing slopes video
Irrelevant code is removed:

    private void SlopeCheck()
    {
        checkPos = transform.position - (Vector3)(new Vector2(0.0f, colliderSize.y / 2));

        SlopeCheckHorizontal(checkPos);
        SlopeCheckVertical(checkPos);
    }

    private void SlopeCheckHorizontal(Vector2 checkPos)
    {
        RaycastHit2D slopeHitFront = Physics2D.Raycast(checkPos, transform.right, slopeCheckDistance, gLayerMask);
        RaycastHit2D slopeHitBack = Physics2D.Raycast(checkPos, -transform.right, slopeCheckDistance, gLayerMask);

        if (slopeHitFront)
        {
            isOnSlope = true;

            slopeSideAngle = Vector2.Angle(slopeHitFront.normal, Vector2.up);

        }
        else if (slopeHitBack)
        {
            isOnSlope = true;

            slopeSideAngle = Vector2.Angle(slopeHitBack.normal, Vector2.up);
        }
        else
        {
            slopeSideAngle = 0.0f;
            isOnSlope = false;
        }

    }
    private void SlopeCheckVertical(Vector2 checkPos)
    {
        RaycastHit2D hit = Physics2D.Raycast(checkPos, Vector2.down, slopeCheckDistance, gLayerMask);

        if (hit)
        {

            slopeNormalPerp = Vector2.Perpendicular(hit.normal).normalized;

            slopeDownAngle = Vector2.Angle(hit.normal, Vector2.up);

            if(slopeDownAngle != lastSlopeAngle)
            {
                isOnSlope = true;
            }

            lastSlopeAngle = slopeDownAngle;

            Debug.DrawRay(hit.point, slopeNormalPerp, Color.blue);
            Debug.DrawRay(hit.point, hit.normal, Color.green);

        }

        if (slopeDownAngle > maxSlopeAngle || slopeSideAngle > maxSlopeAngle)
        {
            canWalkOnSlope = false;
        }
        else
        {
            canWalkOnSlope = true;
        }

        if (isOnSlope && canWalkOnSlope && HorizontalValue == 0.0f)
        {
            rb2d.sharedMaterial = fullFriction;
        }
        else
        {
            rb2d.sharedMaterial = noFriction;
        }
    }

    void Update()
    {

        if(slopeDownAngle != 0)
        {
            isOnSlope = true;
        } else {
            isOnSlope = false;
        }

        if (CanMove() == true){

            HorizontalValue = Input.GetAxisRaw("Horizontal");

        }
    }

    void FixedUpdate()
    {
        Gcheck();
        Move(HorizontalValue, Crouch);
        SlopeCheck();

    }

Rigidbody>
Mass:0.5
BodyType: Dynamic
LinearDrag: 0
AngularDrag: 0
Gravity: 11
FreezeRotation: Only Z axis
::Friction Is Handled In The Movement Code::
But, when I finished the character got stuck again,
so I tried multiplying the slopeNormalPerp by a variable(MultSlope) and he just bounced up and down if made made it too high and if it was too low nothing happened.
I tried messing with varibles such as the ground-checking circles size, various colliders, the aforementioned MultSlope ,and slopeCheckDistance...
Nothing Helped...
I've been working on this for 7 months(with breaks working on other code) and I have improved greatly in coding, but I still can't fix it.
I tried messing with every relevant variable, watching the video many time, downloading and copy-pasting the code ,and following other tutorials of the slope code, No Dice.


text:
Q: Unable to upload images to S3 from Scrapy My spider works fine if I use local file to store the downloaded images.
But when trying to upload to Amazon S3, it shows this error
    2018-02-24 14:37:06 [scrapy.core.scraper] ERROR: Error processing {'category': {'level_1': {'name': u'Electronics', 'url': u'electronics'},
                  'level_2': {'name': u'Accessories',
                              'url': u'electronics-computers-office-accessories'}},
     'image_urls': [u'http://www.some.com/media/catalog/product/cache/1/small_image/165x/9df78eab33525d08d6e5fb8d27136e95/r/s/rs500.jpg'],
},
     'name': u'Gift Card Rupees 500',
}
    Traceback (most recent call last):
      File "/usr/local/lib/python2.7/site-packages/twisted/internet/defer.py", line 653, in _runCallbacks
        current.result = callback(current.result, *args, **kw)
      File "/scraper/scraper/pipelines.py", line 32, in process_item
        if not item['images']:
      File "/usr/local/lib/python2.7/site-packages/scrapy/item.py", line 59, in __getitem__
        return self._values[key]
    KeyError: 'images'

I have below settings for AWS
IMAGES_STORE = 's3://myproject-products-images/'
IMAGES_EXPIRES = 180
AWS_ACCESS_KEY_ID = 'sdfasfasfsaf'
AWS_SECRET_ACCESS_KEY = 'adfasfasfasf'

I have a fresh s3 account all default settings.
Here is my pipeline to check for images which is throwing the above error
class ImageCheckPipeline(object):
    """
    Pipeline to check if image is present in the scraped product
    If not then remove that product from the process
        :param object:
    """

    def process_item(self, item, spider):
        """
            :param self:
            :param item:
            :param spider:
        """
        if not item['images']:
            spider.logger.error('Images not found', {'item': item})
            raise DropItem

        return item

A: In order for the images field to be populated, the item has to go through the images pipeline.
This means the images pipeline has to be used before your checking one.
To achieve this, give the images pipeline the higher priority (lower order) in your settings:
ITEM_PIPELINES = {
    'scrapy.pipelines.images.ImagesPipeline': 100,
    'scraper.pipelines.ImageCheckPipeline': 200,
}

Also, to avoid KeyError, you will have to rewrite your code like so (checking for the existence of a key, instead of its value):
if 'images' not in item:
    spider.logger.error('Images not found', {'item': item})
    raise DropItem


text:
Q: Eclipse RCP: Parallel jobs presented in one progress dialog? I would like to show progress of multiple Jobs running in parallel, but in only one progress dialog.
But each call to Job.setUser() seems to result in a new progress dialog.
I've tried:

*

*Setting a common progress group on all the jobs (obtained via IJobManager.createProgressGroup()).

*Having one parent job call setUser() and join a job family to which all the parallel jobs belong. (This results in a message that progress is blocked on the parent job, by the background tasks.)

What pattern can I follow to result in all the parallel jobs appearing in one progress dialog?

A: Have you tried using org.eclipse.ui.progress.UIJob.  Checkout this link http://www.jdg2e.com/ch29.jobs/doc/index.html. https://web.archive.org/web/20090406175007/http://www.jdg2e.com:80/ see the download link at the bottom of the page, though I am not sure how relevant the solution is after 6 years.
The tutorial executes two jobs simultaneously.

The good thing about eclipse is that the source code is readily available :) . Just hack through the progress view source. Essentially the idea is same, what you need to translate is Progress View -> Composite to Your Dialog -> Composite.
Hope this will help.

A: The ProgressMonitorFocusJobDialog can show the progress of only one job. If you need to show progress of multiple jobs, then Progress View is your answer. The dialog will go away if the user clicks the "Run in background" checkbox


text:
Q: Issue with ubuntu writing a MBR on an SSD So far I have two disks, one SSD for my main os(FreeBSD) that is connected with the NVME bus and one SATA3 HDD for ubuntu.
I installed ubuntu much later than FreeBSD for a project that required some libraries that are not available on FreeBSD on the HDD, but for some reason it created an entry on the SSD.
The point is, ubuntu is not on the SSD, yet it created the entry(I am guessing it is the Master Boot Record because the disk size did not change, it is a 500kb partition).
Is there a way to delete this partition from the SSD and completely isolate ubuntu on its own disk?
I don't mind changing the booting disk when I need to, I just want them to be completely separated.
Thank you for your time in advance!


text:
Q: Dynamic column height in free form powerbuilder I want to get height of my auto size column to re allign other columns in freeform datawindow

A: What have you tried so far? I found this with a quick google search:
http://nntp-archive.sybase.com/nntp-archive/action/article/%3C508e4eeb.65c9.1681692777@sybase.com%3E


text:
Q: lightweight-charts: timeScale() changes visibleRange on setData() I need to load data until it fills the visible area. But on setData the graph changes the visible area, which leads to endless data loading. It looks something like this https://jsfiddle.net/beholderrk/916g3tcf/3/
Is there any way to setData did not lead to a shift in the visible region of timeScale()?

A: It seems that there is a bug when you set data via setData and the library moves visible range and I think that it shouldn't do it (it should work the same as if you have the last bar visible). I'd suggest you file an issue on github so we can mark it as a bug and fix in future versions.

A: I have forked the fiddle with what I think you want to achieve. You just need to add:
chart.applyOptions({
  priceScale:{
    autoScale: false,
  }
})

after the declaration. I also added a commented section in case you want to change the price scale:
// To set a different scale
  /*autoscaleInfoProvider: () => ({
    priceRange: {
      minValue: 170,
      maxValue: 300,
    },
  }),*/

I did not find any condition where the animation stops, though. Only when you press the stop button. You would need to add that part.


text:
Q: In ArrayBlockingQueue, why copy final member field into local final variable? In ArrayBlockingQueue, all the methods that require the lock copy it to a local final variable before calling lock().
public boolean offer(E e) {
    if (e == null) throw new NullPointerException();
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        if (count == items.length)
            return false;
        else {
            insert(e);
            return true;
        }
    } finally {
        lock.unlock();
    }
}

Is there any reason to copy this.lock to a local variable lock when the field this.lock is final?
Additionally, it also uses a local copy of E[] before acting on it:
private E extract() {
    final E[] items = this.items;
    E x = items[takeIndex];
    items[takeIndex] = null;
    takeIndex = inc(takeIndex);
    --count;
    notFull.signal();
    return x;
}

Is there any reason for copying a final field to a local final variable?

A: It's an extreme optimization Doug Lea, the author of the class, likes to use. Here's a post on a recent thread on the core-libs-dev mailing list about this exact subject which answers your question pretty well.
from the post:

...copying to locals produces the smallest
  bytecode, and for low-level code it's nice to write code
  that's a little closer to the machine

A: This thread gives some answers. In substance:

*

*the compiler can't easily prove that a final field does not change within a method (due to reflection / serialization etc.)

*most current compilers actually don't try and would therefore have to reload the final field everytime it is used which could lead to a cache miss or a page fault

*storing it in a local variable forces the JVM to perform only one load


text:
Q: how to trim the dataframe using ranks in python and reshape them in a new dataframe hi I have data frame as below
my df
MobileNumber    Item     score    rank
999999999       a        45       1
999999999       b        44       2
999999999       c        43       3
999999999       d        42       4
888888888       h        65       1
888888888       t        54       2
888888888       yy       43       3
888888888       h        32       4

now I want to groupby mobile number and from rank 1 to 3 in my data set I have 40 ranks for each mobilenumber so I need to trim of them as I need only top 3 ranks
expected output :-
 MobileNumber    Item
    999999999       a,b,c
    888888888       h.t.yy

can any one help me with this

A: let us use query filter before groupby
df.query('rank<=3').groupby('MobileNumber').Item.apply(','.join)
Out[29]:
MobileNumber
888888888    h,t,yy
999999999     a,b,c
Name: Item, dtype: object

A: Since you have ordered ranks already, just get head(3) to get top 3.
df.groupby('MobileNumber')['Item'].agg(lambda s: ','.join(s.head(3)))

MobileNumber
888888888    h,t,yy
999999999     a,b,c
Name: Item, dtype: object


text:
Q: indecidability, independency and company It might be a stupid question, but I am having a look at independence and this question came to my mind :
Let say you have a proposition P1 independent of ZFC.
If you find, in this same axiomatic system, a proposition :

*

*P2 that imply P1

*P3 that imply (not P1)

*P4 equivalent to P1
Does it mean that P2 is false, that P2 is undecidable, or just nothing ?
Does it mean that P3 is false, that P3 is undecidable, or just nothing ?
Does it mean that P4 is false, that P4 is undecidable, or just nothing ?
If you can advise me good reading about independence, and undecidability it would be nice.
If you want to change the tags or the title it could be nice too... I don't know what to write.
Thanks in advance

A: If $P_1$ is independent of the theory $T$ it means that $T\cup\{P_1\}$ has no new contradictions, as well $T\cup\{\lnot P_1\}$ has no new contradictions (that is if $T$ was consistent then so are the new theories).
If $T$ proves that $P_2\rightarrow P_1$ then either $T$ proves $\lnot P_2$ and then $P_2\rightarrow P_1$ is always true in models of $T$; or $P_2$ is also independent.
For example $GCH$ (the Generalized Continuum Hypothesis) implies that Axiom of Choice. Both of these claims are independent of $ZF$. However $0=1$ also implies $GCH$ (simply because contradiction implies everything), but $0=1$ is provabily false from $ZF$ (since $0=\varnothing$ and $1={\varnothing}$).
The same deal goes for $P_3$ such that $T$ proves $P_3\rightarrow\lnot P_1$, simply because $P_1$ is independent if and only if $\lnot P_1$ is independent of $T$.
For $P_4$ note that equivalency means that it implies $P_1$ and therefore independent as well, but also that $P_1$ implies it so if $T\cup\{P_1\}$ is consistent so is $T\cup\{P_4\}$, and therefore in this case $T$ cannot prove $P_4$ to be false.