text:
Q: Find all unique longest paths with Cypher? This is unrelated to how to find all the longest paths with cypher query?, and somewhat related to the answer in Find all relationship disjoint longest paths in cypher/traversal API ordered by size except my condition is a bit different:
I would like to write a cypher query that returns paths whose collections of nodes are "unique", in the sense that no two nodes in the path share the same name property.
Here's an example graph:

and the cypher to make it:
CREATE (a1:Node {name: 'A', time:1}),
(c1:Node {name: 'C', time:2}),
(b1:Node {name: 'B', time:3}),
(d1:Node {name: 'D', time:4}),
(c2:Node {name: 'C', time:5}),
(a2:Node {name: 'A', time:6}),
(a3:Node {name: 'A', time:7}),
(b2:Node {name: 'B', time:8}),
(d2:Node {name: 'D', time:9})

CREATE (a1)-[:NEXT]->(b1)-[:NEXT]->(c2)-[:NEXT]->(a2)-[:NEXT]->(b2),
(a2)-[:NEXT]->(a3)-[:NEXT]->(d2),
(c1)-[:NEXT]->(b1),
(d1)-[:NEXT]->(c2)

RETURN *

In this graph, the following paths are considered longest, and unique:
(a1)-->(b1)-->(c2)
(c1)-->(b1)
(d1)-->(c2)-->(a2)-->(b2)
(a3)-->(d2)

Some example of paths that should not be returned from the query are

*

*(c1)-->(b1)-->(c2) since it contains two instances of nodes with name, "C"

*(a2)-->(b2) since it is contained in the larger path (d1)-->(c2)-->(a2)-->(b2)
Any help would be much appreciated.

A: //
// Find all path:
MATCH path = (a:Node)-[:NEXT*1..]->(b:Node)
//
// Check that the names of the nodes in a path is unique
UNWIND nodes(path) as node
WITH path, nodes(path) as nodes,
     collect(DISTINCT node.name) as unames
  //
  // And sort by path length
  ORDER BY length(path) ASC
  WHERE length(path)+1 = size(unames)
//
// Putting the appropriate path to the collection
WITH collect({f: id(HEAD(nodes)), // Fist node in path
              l: id(LAST(nodes)), // Last node in path
              ns: EXTRACT(n in nodes(path) | id(n)),
              p: path
     }) + {f: NULL, l: NULL, ns: [NULL]} as paths
//
// Loop through the paths in a double loop
// and check that the start and end nodes
// are not included in the following ascending path
UNWIND RANGE(0,size(paths)-2) as i
  UNWIND RANGE(i+1,size(paths)-1) as j
    WITH i, paths, paths[i]['p'] as path,
         sum( size( FILTER(n in paths[j]['ns'] WHERE n=paths[i]['f']) )) as fc,
         sum( size( FILTER(n in paths[j]['ns'] WHERE n=paths[i]['l']) )) as fl
    WHERE fl=0 OR fc=0
//
// Return all appropriate ways
RETURN path ORDER BY length(path)

Upd: (let's try to add elegance)
//
// Find all path:
MATCH path = (a:Node)-[:NEXT*1..]->(b:Node)
//
// Check that the names of the nodes in a path is unique
UNWIND nodes(path) as node
WITH a, b, path,
     collect(DISTINCT node.name) as unames
  //
  // And sort by path length
  ORDER BY length(path) ASC
  WHERE length(path)+1 = size(unames)
//
// Putting the appropriate path and first and last nodes to the collection
WITH collect({first: a, last: b, path: path}) + {} as paths
//
// Loop through the paths in a double loop
// and check that the start and end nodes
// are not included in the following ascending path
UNWIND RANGE(0,size(paths)-2) as i
  WITH i, paths[i]['path'] as path, paths
    UNWIND RANGE(i+1,size(paths)-1) as j
      WITH path,
           collect(distinct paths[i]['first'] IN nodes(paths[j]['path'])) as cFirst,
           collect(distinct paths[i]['last']  IN nodes(paths[j]['path'])) as cLast
        WHERE (size(cFirst)=1 AND cFirst[0] = false) OR
              (size(cLast )=1 AND cLast [0] = false)
//
// Return all appropriate ways
RETURN path ORDER BY length(path)


text:
Q: ¿Como Usar O Acceder A Un Fichero Que Se Encuentra En Google Drive? Quiero saber si es posible usar un archivo que se encuentra en la nube como si estuviera en la memoria del dispositivo estilo enlace, que este archivo que se encuentra en la nube se pueda acceder a el mediante el enlace que se creara en la memoria, pero solo abriendo o explorando el contenido de este sin tener que desencadenar ningún proceso de descarga que retrase la ejecución del archivo. Si saben si es posible lograr lo que he comentado por favor comunicármelo. Gracias

A:  Uri uri = Uri.parse("http://www.tuenlance.com");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);

Esto te abrirá tu navegador con el enlace por defecto, espero te ayude.
Nota: lo puedes usar en un botón u otro control

redpajama_set_name: RedPajamaStackExchange


text:
Q: Model Comparison for Weighted Network I have a weighted network data and I want to know whether this network possesses small-world features or the features of a scale-free network.
I know for unweighted networks, I can create comparable small world networks and scale-free networks (same number of nodes and similar number of edges) via igraph and then compare clustering coefficients and average path lengths.
However, I wonder for a weighted network, can I create comparable weighted small-world and scale-free networks? Thanks!

A: I suggest you have a look at:
The architecture of complex weighted networks
by Alain Barrat, Marc Barthelemy, Romualdo Pastor-Satorras, and Alessandro Vespignani,
Where the authors investigate typical small-world and scale-free properties of various real-world weighted networks. They have in particular weighted extensions of clustering coefficients.


text:
Q: experimental nvidia drivers, no normal boot? how to remove nvidia drivers from recovery mode? After I installed experimental Nvidia drivers, Ubuntu will not boot. How can I remove the drivers from recovery mode?
If I choose recovery mode and in the menu choose "root" (drop to root shell prompt), and then try to use the command sudo apt-get remove --purge nvidia-*
it says:
sudo: unable to open /var/lib/sudo/thakang/console: read-only file system

W: Not using locking for read only lock file /var/lib/dpkg/lock
E: Unable to write to /var/cache/apt/
E: the package lists or status file could not be parsed or opened.

I have used login and logged in so my shell now shows :~$
Thank you

A: You need to mount your system first in read/write mode:
mount -o remount,rw /


text:
Q: Ionic ReactJS-Redux does not re-render after dispatch() I'm using Ionic with ReacJS and Redux and I have a problem where the elements are not re-rendered after the first load, even though the state changes.
Here is the code
var categoriesTemplate = [{name:'Science', selected:false}, ... ]

const categories = useSelector((state: any) => {
    console.log("Updating State")
    let cat = state.categories
    for (let c of cat) {
      for (var category of categoriesTemplate) {
        if (category.name === c) {
          category.selected = true
        }
      }
    }
    return categoriesTemplate
  })

  const dispatch = useDispatch()

  const toggleCategory = (categorySelected: string) => {
    console.log("Toggle + Dispatch")
    for (var category of categories) {
      if (category.name === categorySelected) {
        category.selected = !category.selected
      }
    }

    let newCategories = categories.filter(c => { return c.selected }).map(c => c.name)
    dispatch(setCategoriesState(newCategories))
  }

the first run which loads all the categoriesTemplate with property selected to false works fine.
When I trigger the toggleCategory() I see that category (fetched from Redux after dispatch()) is correctly updated with the new values, but the elements are not re-rendered.
I've logged both the state update and the rendering code which is
return (
      // Some React Components
      {
          categories.map(l => {
            console.log("Rendering")
            return ( ... )
        })
     }
     // Some React Components
     )

here is the log, as you can see the initialization is rendered correctly (first "Updating State" + "Rendering"), but after the trigger of toggleCategory() the state is updated from Redux "Updating State" while the elements are not "Rendering"

Am I missing something?
Ps I'm not posting code from reducer and action because it works, since the updated value reaches my category state, and didn't want to add entropy, but if you need I can post it.

A: Here is an example using local state and reselect to memoize the categories with selected property.

const { createSelector } = Reselect;

const categoriesTemplate = [
  { name: 'Science', selected: false },
  { name: 'Technology', selected: false },
];
//selectors
const selectCategoriesWithSelected = createSelector(
  [
    (allCategories) => allCategories,
    (_, selectedNames) => selectedNames,
  ],
  (allCategories, selectedNames) =>
    allCategories.map((category) => ({
      ...category,
      selected: selectedNames.includes(category.name),
    }))
);
//Category is a pure component, does not realy matter in this case
//  all category items are re created when you toggle one
//  selected, that's just the way you implemented it and can be
//  implemented better
const Cateory = React.memo(function Category({
  toggleCategory,
  category,
}) {
  return (

       {
          e.preventDefault();
          toggleCategory(category.name);
        }}
        href="/"
      >
        {category.name}{' '}
        {category.selected ? 'selected' : ''}

  );
});
function App() {
  const [
    selectedCategoriesNames,
    setSelectedCategoriesNames,
  ] = React.useState(() =>
    categoriesTemplate
      .filter(({ selected }) => selected)
      .map(({ name }) => name)
  );
  const toggleCategory = React.useCallback(
    (categoryName) =>
      //this is the action and reducer combined because
      //  we are using local state
      setSelectedCategoriesNames(//add or remove category name to selected list
        (selectedCategoriesNames) =>
          selectedCategoriesNames.includes(categoryName)
            ? selectedCategoriesNames.filter(
                (c) => c !== categoryName
              )
            : selectedCategoriesNames.concat(categoryName)
      ),
    []
  );
  const categoriesWithSelected = selectCategoriesWithSelected(
    categoriesTemplate,
    selectedCategoriesNames
  );
  return (

      {categoriesWithSelected.map((category) => (
        <Cateory
          key={category.name}
          category={category}
          toggleCategory={toggleCategory}
        />
      ))}

  );
}
ReactDOM.render(<App />, document.getElementById('root'));

If you just put categoriesTemplate in state and change selected it would be both simpler and can be optimized:

const Cateory = React.memo(function Category({
  toggleCategory,
  category,
}) {
  console.log('rendering', category.name);
  return (

       {
          e.preventDefault();
          toggleCategory(category.name);
        }}
        href="/"
      >
        {category.name}{' '}
        {category.selected ? 'selected' : ''}

  );
});
function App() {
  const [categories, setCategories] = React.useState([
    { name: 'Science', selected: false },
    { name: 'Technology', selected: false },
  ]);
  const toggleCategory = React.useCallback(
    (categoryName) =>
      //this is the action and reducer combined because
      //  we are using local state
      setCategories((categories) =>
        categories.map((c) =>
          c.name === categoryName
            ? { ...c, selected: !c.selected }
            : c
        )
      ),
    []
  );
  return (

      {categories.map((category) => (
        <Cateory
          key={category.name}
          category={category}
          toggleCategory={toggleCategory}
        />
      ))}

  );
}
ReactDOM.render(<App />, document.getElementById('root'));


text:
Q: How to optimize this query? I have tables:
A (ID_A, VALID_FROM, DATA ...)
B (ID_B, ID, T1, T2, T3, DATE)
Table A can contain historical data (eg. data valid for given period)
I need to select records from table B joined with appropritate records from table A (from table A I need row where b.id = a.id_a and record was valid at b.date)
select *
from B, (select * from (select * from A where a.id_a = b.id and a.valid_from <= b.date order by valid_from desc) where rownum = 1)
where b.id = a.id_a

A: Sounds like you're looking for a JOIN: http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/queries006.htm

A: This isn't much more optimal, but is probably more readable:
select *
from A a, B b
Where
a.id_a = b.id
and a.valid_from = (select max(valid_from)
                    from A
                    where id_a = b.id
                    and valid_from <= b.date)
order by valid_from desc

I've seen this problem before, and the best way I know of to optimise it is to put a valid_to column onto table A.
For the latest record, this should contain the biggest date Oracle can handle.
Whenever you create a newer version of the record, update it with the time the new record is created (minus a millisecond to avoid overlaps) so you have something like this:
ID Valid_from                Valid_to
1  01/01/2011 12.34.56.0000  02/01/2011 12.34.56.0000
1  02/01/2011 12.34.56.0001  03/01/2011 12.34.56.0000
1  03/01/2011 12.34.56.0001  31/12/9999 23.59.59.9999

Then you can query it like this:
select *
from A a, B b
Where
a.id_a = b.id
and b.date between a.valid_from and a.valid_to
order by valid_from desc

With an index on the date columns, the performance should be ok..

A: I've taken StevieG's answer and expanded on it. Without a valid_to column there are tricky subqueries to write. I would propose using the LEAD analytic function to find the end of the current validity period and work with that. This is an alternative to the subqueries and the valid_to column.
The LEAD analytic function looks over the rows in the current data set and finds the next valid_from date and uses that as the end of the current period.
My query is shown below. It incorporates the sample data you provided, in a with clause.
with table_a as (
  select 1 as id, 'XXX1' as data, date '2009-01-01' as valid_from from dual union all
  select 1 as id, 'XXX2' as data, date '2009-05-30' as valid_from from dual union all
  select 1 as id, 'XXX3' as data, date '2010-01-11' as valid_from from dual union all
  select 2 as id, 'YYY' as data, date '1999-01-01' as valid_from from dual
),
table_b as (
  select 1 as id, 1 as id_a, date '2009-02-01' as date_col from dual union all
  select 2 as id, 2 as id_a, date '2009-09-12' as date_col from dual union all
  select 3 as id, 1 as id_a, date '2009-06-30' as date_col from dual
)
select *
from table_b b
  join (
    select
      id,
      valid_from,
      lead(valid_from, 1, date '9999-12-31') over (partition by a.id order by a.valid_from) as valid_to
    from table_a a
) a on (a.id = b.id_a)
where
  a.valid_from <= b.date_col and
  b.date_col < a.valid_to


text:
Q: Pandas rows do columns Hello I have this hull line rows that I want to convert to this keeping x and y coordinates as columns. I try many things, but I could not took results

A: if u want each row to list do something like this
Row_list =[]

for index, rows in df.iterrows():
    new_list =[rows.column1, rows.column2, rows.column3]
    Row_list.append(new_list)

df is the dataframe


text:
Q: Shortest path between two points via two disks
Hallo everybody,
I have the following problem regarding shortest paths in $R^2$.
Suppose you are given two points $p$ and $q$ and two unit disks, as in the picture.
I am looking for a path from $p$ to $q$ through a point $c_1$ in the first disk and $c_2$ in the second disk such that the sum $\overline{p c_1}+\overline{c_1 c_2}+\overline{c_2 q}$ is minimum.
I know how to find a path if there is only one disk, via reflection properties of ellipses. However, the case for two disks eludes me. I was hoping that you could have some suggestions, or some pointers to something to read.
Thanks in advance for your answers.

A: Let's name the circles $S_1,S_2$ so that $c_i \in S_i$. Using calculus you can prove that if the minimum is achieved with the configuration that you have shown then at each of the two points $c_i$, the two angles of incidence must be equal, meaning the angles that the two arcs make with the circle $S_i$ at the point $c_i$.

A: I will elaborate Narasimham' comment :
Consider the case where $c_1$ is fixed. If center of cicle containing point $c_i$ is $O_i$, then the minimum is attained when $Oc_2$ bisects the angle $\angle c_1c_2q $.
Now assume that $c_i$ are movable : For some $c_i$ if minimum of total length $|pc_1|+|c_1c_2|+|c_2q|$ is obtained and if we assume that there are not two bisections, then we can assume that there is no bisection at a point $c_2$. Then we fixes $c_1$ and we move $c_2$ so that there is bisection. Hence we have length decreasing which is a contradiction. Hence minimum of total length can happen when there are two bisections.


text:
Q: Convert device time to unix timestamp based on device timezone I am able to get the correct date with time according to the device timezone. But when I convert that time to timestamp, I am getting timestamp of local timezone (checked in epochconverter), not the device based timezoned timestamp.
I have tried below code to get timestamp from date:
1. new Date().valueOf()

2. var tzt = moment
          .unix(Date.now())
          .tz(DeviceInfo.getTimezone())
          .toDate()
          .getTime()

3. +new Date(Moment(new Date().toISOString()))

4. Moment(new Date().toISOString()).unix()

5. Date.now()

6. var forDate = Moment(new Date()).format('DD/MM/YYYY hh:mm a');
   var forDateTime = Moment(forDate, "DD/MM/YYYY hh:mm a").toDate().getTime();

For e.g. I have set America/Chicago timezone in device. I get date as Fri Feb 21 2020 23:59:12 GMT-0600 (CST) which is correct for chicago but timestamp as 1582351152244 which is local timestamp of India.
My expected result is:  1582329552000

A: You appear to misunderstand the value returned by the valueOf method of a Date instance: it's a millisecond offset from 1970-01-01 00:00:00 UTC (the ECMAScript epoch, which is common to a number of computer languages and systems such as Java and UNIX). It does not have a timezone, nor should you infer that it has one. valueOf is equivalent to the getTime method.
ECMAScript Date objects are just a time value, an offset from the ECMAScript epoch, plus some basic methods to get and set date and time values either based on local (host offset) or UTC values and rules. They don't have a timezone and are inherently UTC. Timezone information is obtained from the host system (or whatever other API an implementation may implement that satisfies ECMA-262).

I get date as Fri Feb 21 2020 23:59:12 GMT-0600 (CST) which is correct for chicago[sic] but timestamp as 1582351152244 which is local timestamp of India

1582351152244 is not a "timestamp of India", it's a millisecond offset from the ECMAScript epoch and represents 2020-02-22T05:59:12.244Z, 2020-02-21T23:59:12GMT-06:00 (Chicago) and 2020-02-22T11:29:12.244GMT+05:30 (India Standard Time). It represents all those timestamps at the same time, as they all represent the same instant in time in different timezones.
When you adjust the value by the host timezone offset, the result is a time value that represents a different moment in time. The code in your answer is equivalent to:

// OP code
var currentTime = new Date().getTime();
var localOffset = (-1) * new Date().getTimezoneOffset() * 60000;
var stamp = Math.round(new Date(currentTime + localOffset).getTime());
console.log(stamp)

// Concise equivalent, might be 1 ms different sometimes
let d = new Date();
let stamp2 = d.getTime() - d.getTimezoneOffset() * 6e4;
console.log(stamp2);

Without knowing why you feel the need to adjust the time value or the outcome you're trying to achieve, it's impossible to suggest a better way of going about it.

A: I have found the answer to my question. I used below code to convert timestamp according to device timezone.
var currentTime = new Date().getTime();

var localOffset = (-1) * new Date().getTimezoneOffset() * 60000;

var stamp = Math.round(new Date(currentTime + localOffset).getTime());


text:
Q: What is the likelihood of a long-period comet impact? I always see lots of information about asteroid impacts, but very little is said about comet impacts. As I see, a long period comet impact is much more dangerous because a) we wouldn't have time to prepare for it, and b) even small bodies would have high kinetic energy, equivalent to large asteroids.
On the flip side, I think that a long period comet would have trouble hitting the Earth, as it wouldn't have time to interact with our planet as an asteroid does. It would just hit us if, by chance, it was crossing the ecliptic plane at 1 AU from the Sun and we happened to be at the same place as well. So, my question boils down to the following:

*

*Do long period comets cross the ecliptic plane at a preferential distance from the sun (or: what is the chance of them crossing at approximately 1 AU)?

*What is the area of the hitting plane, versus the cross section of our planet?

*Does the assumption that a comet wouldn't have time to interact with us holds?

A: An estimate of impacts from long-period comets is available at this NASA JPL site.
They appear to be randomly distributed . Given detection at about 5 AU, we'd only have a year of warning for potential impactors. Their mean impact velocity is in the order of 52 km/s with an impact probability crossing Earth's orbit of 2.2 - 2.5x${10^{ - 9}}$ per perihelion passage. Nuclei large enough to initiate global climate disturbances occur on average, every 16 Myr.
With our current technology, it appears we would have no way to avoid disaster from a long-term comet should we be in the cross-hairs of one of them. Fortunately, impact probability is very small.


text:
Q: Why does dependency injecting a scoped instance of a DBContext and a singleton in a controller, throws an invalid operation exception? I have an interface and it's implementation registered as a singleton service alongside a DBContext at the services container. I've used dependency injection in a controller for both of these services but it throws the following exception:
InvalidOperationException: Cannot consume scoped service 'DepartmentOrders.Data.OrderTypeContext' from singleton 'DepartmentOrders.ShoppingCart.ICartDB'.

I did not intend to make the singleton service consume dbcontext, and thought they would be separate services, meaning that no kind of parent-child relationship should exist, but I'm barely familiar services so I'm missing something here for sure.
If I remove any of the injections in the controller and leave one, the program works as intended.
The ConfigureServices method:
public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<ICartDB, CartDB>();

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    services.AddDbContext<OrderTypeContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DP_Orders") ));
}

The controller:
ICartDB Cart;
private readonly OrderTypeContext Data;

public HomeController(OrderTypeContext _Data, ICartDB _Cart)
{
    this.Cart = _Cart;
    this.Data = _Data;
}

public async Task<IActionResult> Index()
{
    return View(await Data.Departments.ToListAsync());
}

The singleton:
public interface ICartDB
{
    bool Exists(int ItemId);
    bool IsEmpty();
    Dictionary<int, int> GetCart();
    void DeleteItem(string ItemId);
    void AddItem(int ItemId, int Quantity);
    void EditItem(int ItemId, int Quantity);
}


text:
Q: Enable listview columHeader checkBox Click Here I just wants to have checkbox in my listview header. and i wrote the below code for that, can anyone help me out here to enable the check-box .
Now I could only be able to see the checkbox- not to click on it.
Does anyone has any idea on this ,  can it be handled by listView3_ColumnClick event..??
Thanks in advance.
private void listView3_DrawColumnHeader_1(object sender, DrawListViewColumnHeaderEventArgs e)
    {

        TextFormatFlags flags = TextFormatFlags.LeftAndRightPadding;
        e.DrawBackground();

        //CheckBoxRenderer.DrawCheckBox(e.Graphics, ClientRectangle.Location, System.Windows.Forms.VisualStyles.CheckBoxState.UncheckedNormal);
        CheckBoxRenderer.DrawCheckBox(e.Graphics, ClientRectangle.Location, TextRectangle, "", this.Font, TextFormatFlags.HorizontalCenter, clicked, state);

        e.DrawText(flags);
    }

A: I think I have got that
private void listView_ColumnClick(object sender, ColumnClickEventArgs e)
    {
        if (!clicked)
        {
            clicked = true;
            state = CheckBoxState.CheckedPressed;

            foreach (ListViewItem item in listView.Items)
            {
                item.Checked = true;
            }

            Invalidate();
        }
        else
        {
            clicked = false;
            state = CheckBoxState.UncheckedNormal;
            Invalidate();

            foreach (ListViewItem item in listView.Items)
            {
                item.Checked = false;
            }
        }
    }

wheres state =>
 private CheckBoxState state = CheckBoxState.UncheckedNormal;


text:
Q: How to prevent default click behavior of a routerlink in angular app? Even though this is not angular specific in theory it needs to be solved in ng app and none of the examples work. I've seen all the answers in SO but none of those solutions seem to work in real life Angular7 app. For example none of the following work :

Properties

Properties

Properties

Properties

Creating a method for handler in component.ts and calling either function with or without returning false does not work either.
In addition, I don't want to disable link because it needs to be draggable / openable in other browser tab/window.
EDIT: Here is https://github.com/angular/angular/issues/21457 and I can make it to work by adding an element inside anchor and have the click for the inside element like this:
(click)="$event.stopPropagation();$event.preventDefault()"

My real world example has mat-icon inside anchor so I use that but in link above a span inside is suggested.

A: The reason routerLink does not respect preventDefault is described here.
The solution is to create inner element for anchor if there already isn't one (like icon). In the link above a span is created inside but I have icons inside anchors which I omitted from the question for clarity:

    <mat-icon class="tab-nav-item-icon" (click)="$event.stopPropagation();$event.preventDefault()">map</mat-icon>


text:
Q: How to scrape older html with nested tables in R? I'm struggling to scrape an older html file (hundreds actually) that does not have css, so css selection doesn't work.
Example page: http://home.business.utah.edu/u0982704/ipeds/gr2002.html
I need to get all the info that is in bordered tables, though I'll also need certain other elements such as the variable code after each horizontal rule (ie "CHRTSTAT-1919-Graduation rate status in cohort") in order to attach that to the bordered table info below it.

I'd like to end up with something like this:

The file contains all text within a table, and then has tables within tables.  I am unsure of how to use html_nodes() and html_table() to get a clear result.  Using html_table gives me a massive list of lists of lists, and there is no obvious way I"m seeing to flatten it out in a useful way.
One thing I've tried: using html_text() and then read_table() gets me most of the way there, but the actual bordered tables on the page don't parse due to the fact that there are no line returns - these seem to be the deepest nested tables.  So if I could identify these and parse them using some other method, that might work.
Currently using rvest but open to other packages.
suppressPackageStartupMessages(require(tidyverse))
suppressPackageStartupMessages(require(rvest))

xh <- read_html("http://home.business.utah.edu/u0982704/ipeds/gr2002.html")

htable <- xh %>%
  html_table(fill = T)

htext <- xh %>%
  html_nodes("table") %>%
  html_text(xh)

text_table <- read_table(htext) #This gets me most of the way there, but the tables from the page (ie the "Value Label", "Code Value", "Frequency", "Percentage" gets smashed because there are no line returns since it is seperate table rows)

Created on 2020-02-19 by the reprex package (v0.3.0)
EDIT: I just noticed that my read_table method seems to not get all the data from the table:
text_table %>% slice(15) %>% pull only has part of the table:
[1] "4-year institutions total12,0104.74%4-year institutions, Adjusted cohort (revised cohort minus exclusions)22,0104.74%4-year institutions, Completers within 150% of normal time31,9804.67%4-year institutions, Tranfer-out students47671.81%4-year institutions, Still enrolled in long programs5950.22%Bachelor's or equiv subcohort (4-yr institution)61,8464.35%Bachelor's or equiv subcohort (4-yr institution) adjusted cohort (revised cohort minus exclusions)81,8464.35%Bachelor's or equiv subcohort (4-yr institution) Completers within 150% of normal time total91,8204.29%Bachelor's or equiv subcohort (4-yr institution) Completers of programs of < 2 yrs (150% of normal time)10920.22%Bachelor's or equiv subcohort (4-yr institution) Completers of programs of 2 but <4 yrs (150% of normal time)114020.95%Bachelor's or equiv"


text:
Q: Plot graphs in R by loop and save it like jpeg I am trying to plot graphs by loop.
Input data: Tables, which have the same ending *depth.txt, there are 2 tab delimited columns in the table:
Baba"\t"58.38

Tata"\t"68.38

Mama"\t"30.80

jaja"\t"88.65

OUTPUT: I would like to get a jpeg file with plot() for each *depth.txt (their names will be the same as the tables' names) for all files (axis x will be the first column from the table and axis y will be second column)
I created a part of the script, but it doesn't work:
files <- list.files(path="/home/fil/Desktop/", pattern="*depth.txt", full.names=T,recursive=FALSE)

for (i in 1:length(files))
plot(read.table(files[i],header=F,sep="\t")$V1,read.table(files[i],header=F,sep="\t")$V2)
dev.copy(jpeg,filename=files[i])
dev.off

It doesn't work, could you help me please? I am a beginner with R.

A: Will the following do what you want?
for (i in 1:length(files)) {
  dat <- read.table(files[i], header = FALSE, sep = '\t')
  jpeg(file = paste(files[i], '.jpeg', sep = ''))
  plot(dat$V1, dat$V2)
  dev.off()
}

A: Similar to the first two but changing the file name for the plots
files <- paste("fil",1:3,"depth.txt",sep="")      #  example file names
for( i in 1:length(files))  {
     filename <-  sub(".txt",".jpg",files[i])
     jpeg(file=filename)
     plot(1:(10*i))                             # example plots
     dev.off()
}

A: renameing the file?
for (i in 1:length(files)) {
    file = files[i]
    file = paste("jpg",file,sep="_")
    jpeg(file)
    plot(read.table(files[i],header=F,sep="\t")$V1,read.table(files[i],header=F,sep="\t")$V2)
   dev.off()
}


text:
Q: How Can I Prevent The User From Entering The Same Input? Here is my code and I would like you to tell me how can I prevent the user from entering the same input 2 times?:
Name=input("enter Your Name: ")
Friend_name=input("Enter Your Friend's Name?")

A: You could use a wrapper that won't return until the answer was not seen before. For example:
def no_dupe_response_input(prompt):
    try:
        seen = no_dupe_response_input.seen
    except AttributeError:
        seen = no_dupe_response_input.seen = set()

    while True:
        response = input(prompt)
        if response in seen:
            print(f'You already responded "{response}". Please respond something else.')
        else:
            seen.add(response)
            return response

name = no_dupe_response_input('Enter Your Name: ')
friend_name = no_dupe_response_input('Enter Your Friend\'s Name? ')

print(f'You are {name} and your friend is {friend_name}!')

Result:
Enter Your Name: foo
Enter Your Friend's Name? foo
You already responded "foo". Please respond something else.
Enter Your Friend's Name? foo
You already responded "foo". Please respond something else.
Enter Your Friend's Name? bar
You are foo and your friend is bar!


text:
Q: Rajawali live wallpaper slow back from sleep Im working on a 3D live wallpaper for android using rajawali. When I turn the screen off and on, its loading the whole scene again what takes some seconds depending on device and scene complexity. Id like to keep my wallpaper in memory "forever" to have the wallpaper visible instantly after the screen turn on.
From what I have found this behavior is because openGL loose context when calling OnPause and OnResume events. I tried setPreserveEglContextOnPause which "may" preserve context, but actually it changes nothing.
Can anybody help me to solve this problem?


text:
Q: Using Pattern singleton on Android I am developping an application that retrieves some data from a server.
I have two options:

*

*Get the whole data set from the server and then work with it using the pattern 'singleton' to reduce the number of queries

*For each query, get the corresponding data set from the server
What is the best choice?

A: In my opinion it depends.
It depends on the size of the data and if it even makes sense to return data that your user may not even need.
Personally, in my app that I am building I will be returning only the data that is required at that time. Obviously though, once I have the data I won't be fetching it again if it makes sense to keep hold of it for good or even just temporarily.

A: I agree with C0deAttack's answer. Your goal should be to minimize network traffic within the constraints of your app being a "good citizen" on the phone. (That means that your app does not negatively impact the user or other applications by using too many resources — including memory and file space.)
From the sound of it, I'm guessing that the data are not that voluminous. If so, I would recommend caching the response and use it locally, thus avoiding repeated queries to the server. Depending on how often the data changes, you might even consider making it persistent, so that the app doesn't have to query the server the next time it starts up. If the response includes an estimated time before it is considered outdated, that would help in establishing an update schedule. (Google's license server uses this idea.)
P.S. I don't see that this has anything (directly) to do with a singleton pattern.

A: How about storing your data in an sqlite database and do your queries with sql? Since you get sorting and ordering for free, it can help you writing less code. Also you have instant offline functionality if your user has no internet connection. :)


text:
Q: Accessing CI features on non-CI class So for example, i want to access config on CI from my class library.
Class A {
  funcion x() {
   $this->config->load('my_config'); // accessing my_config
  }
}

that obviously won't work unless you extends and then call parent::__construct().
As far as i know, it can only be done from classes that extend CI_Controller or CI_Model. How to access CI stuff (config, helper, model, etc) on non-CI class ?
Thanks.

A: How about initiating the class from the construct?
  include ("CI_Page.php");
class A {
     protected $_CIInstance1;
     protected $_CIInstance2;
    public function __construct(){

     $this->_CIInstance1 = new xxxx();
     $this->_CIInstance2 = new yyyy();
    }

    public function x(){
      $this->_CIInstance1->load('my_config');
    }
}

A: You probably want to access the instance of CI as if it were the super variable, $this. In reality what you need is the ability to access the same functionality as $this and in order to do this, you'll need to use $CI =& get_instance();
You can find it directly in the documentation for Creating Libraries


text:
Q: The need for branches in Git I have been using Git for a while, and I am wondering if the construct of "branches" in Git is really necessary.
The Git branch can be thought of as a pointer to a specific commit. Here is one workflow:
1. git checkout master //on master branch
2. Develop
3. git checkout -b newFeature
4. git commit -a -m "shiny new feature done!"
5. git checkout master
6. git merge newFeature //fast-forward
7. git branch -d newFeature
Such a straightforward task involved 7 steps. Of course, the creation of the newFeature branch is probably unnecessary - we could have just worked on master itself. But if we eliminate the concept of branches, steps 5 to 7 would be unnecessary.
Getting rid of branches would also save us from the "detached HEAD" state, and the warning that is displayed every time a commit that is not associated with a branch is checked out.
Branches may be necessary for some other VCSs. But why does Git need branching? Can't one do everything, and with added efficiency, if one just use and refer to commits? Every Git commit already has one or more pointer(s) that record its parental relationship(s).

A: You are correct that branch names are merely a convenience.  Getting rid of them would not save us from "detached HEAD" though: it would mean that we always have a "detached HEAD".  (This has far-reaching implications, because references—including branch names—also retain commits.  But we can imagine a system where this is not true, such as that in Mercurial.)
Note that in any commit-based version control system, we have the notion of a current commit.  That's the commit we have extracted from the VCS into our work-tree, so that we can use it or work on it.  Since the true name of each Git commit is an apparently random hash ID like deadc0ffee or feedbeef or whatever, we will have to note "interesting" hash IDs down somewhere.  The most interesting one is, of course, the current one; so we note that down, writing a hash ID into something we can access using the name @ or HEAD.
That's a detached HEAD in Git-as-it-is.  It would just be "the head", which is always detached (so that we don't need the adjective "detached" at all), in your proposed setup.
Now, of course, we need to allow distributed development.  While I may work on my copy of things, Alice and Bob have their own copies, and do their own work.  They have their current commits, which may be different, especially as they add new commits.
Suppose Alice has finished up the new widget feature and Bob has documented the frammitz.  I now go to pick up their work (by whatever means), so I get some commit(s) from Alice that I never had before.  I need to know their hash IDs—at the least, I need the ID of her newest commit, which has her earlier commit hashes.  I pick up Bob's documentation commit(s) that I never had before, and need his IDs too, or at least one of them.
I'd better attach a name to each of these two commit IDs, lest I forget whether badcafe is Alice's or Bob's.  Perhaps I could use alice/master as the name for badcafe.  Hm, wait, I think I have just invented the remote-tracking branch name.

There are other ways to organize all of this.  For instance, Mercurial uses permanent, global branch names, and allows anonymous heads1 within each branch.  It turns out that these permanent, global branch names have their own issues, so instead, Mercurial users often use lightweight names called bookmarks to track anonymous heads.  These bookmarks are, as it turns out, direct analogues to Git's branch pointers: names for commit-IDs.
In the end, we find that we want these things.  Git's history, and (in my opinion) poor nomenclature—which has too many similar-sounding words that mean different things—make it a rough ride to get used to Git's words for the things, but the things themselves are quite desirable.

1These heads are similar in some ways to Git's HEAD, but different in others.  Once they have attached bookmarks, though, they are extremely similar to Git's branches.

A: "Branch" has two meanings in git. Trivially, it is just a temporary and otherwise irrelevant name/alias we give to a commit so we do not have to remember the hash. This has obvious benefits, working directly with commit hashes is very awkward and usually reserved for special occasions. Theoretically, we could work without these, but it would be very cumbersome indeed.
The other meaning, of "branch" is the phenomenon that a commit can have more than one child commit. This is the real "meat" of a branch. Funnily, this meaning is not actually represented in any technical/physical way in git beyond the fact that a commit had more than one child.
This latter act of branching, and conversely merging, is what makes the git commits a directed acyclic graph DAG. And this is absolutely, totally crucial for git, it is the magic behind it. Other systems, for example Subversion, had nothing like it, so it is definitely worthy of mention.
For more in depth information on it, check out the git book at https://git-scm.com/book/en/v2, especially its chapter on branching and merging, and on internal data structures.


text:
Q: OAuth2 flow in web frontend and REST API I'm working on a project based on Phalcon which consists in two different stand-alone subprojects: a php + angular frontend and a php REST API.
I protected the API with OAuth2, using PhpLeague OAuth2 Server. The API server is the OAuth2's authorization server AND resource server.
This is the actual flow:

*

*The user can browse the public endpoints of the frontend, and when hits a private page, gets redirected to the login page;

*The login page has username and password, POSTs them to the frontend server;

*The frontend server calls a public method on the API server, which is expecting a Password Credential Grant: it validates the credentials and sends back an access token and a refresh token;

*The frontend server caches both the access and refresh token in session and uses it for some API calls: the first of those is the '/users/me', which gets info about the current user and its ACL on the frontend sections;

*The frontend server sends the page to the browser, which loads its javascript files.

Now, OAuth2 states that access tokens should be short-lived and refresh-token should be long-lived: in the frontend server logic, the API calls which receives a 401 (caused by the expired access token) are retried by sending first the refresh token to obtain a new access token via a Refresh Token Grant. If this second call is rejected, I assume the user is no more logged in (refresh token expired / revoked).
The pages are using Angular to perform data and ux/ui management. My question is:
should the Angular code call directly the API server?
Actually the first thing my javascript code does is to get a config object from the frontend server, which contains the access token too, and uses it to make the calls to the API server. The problem with this is that i should rewrite again the "refresh token logic" in javascript (after it expires, i get 401s), and by what I have read on the subject i understood that it is better to not make the refresh token visible to the client (as it can generate new access tokens).
So i was thinking about a "two step approach", where every javascript API call goes to an endpoint on the frontend server which relays it to the API server, but this is obviously slower (JS -> FRONTEND -> API and API -> FRONTEND -> JS).
What is the correct approach? It's not very clear to me if the frontend should be considered as two clients (php + js) which should work separately or not, as I imagine that an hypothetical iOS app would be making calls 100% against the API server.

A: I have used the same approach in my own projects. The problem that we have is that the client is not secure. In order to generate / refresh a token, you need to pass secure information to the authorization server.
I have done the same as you basically, let the back-end handle the tokens and their temporary storage. You cannot and should not trust the client with important information which lets you generate tokens. In terms of delays, I wouldn't worry about it too much since you're not going to be doing that much extra work, you won't even notice the delays. I have a system like this built and used by hundreds of thousands of users with absolutely no issues.
Now, you have said a few things in here which make me wonder what you are doing.
OAuth2 is not a user authentication system, it's an application authentication system. You don't pass a user and their password and generate a token for them, you pass a ClientID and ClientSecret and they generate a token for you. Then you have an endpoint which gives you the user details for this user, you pass your userid or username and get the details of that user.
A token expired does not mean your user is logged out. Those are two completely different things. How are you going to expire a token for example, when your user wants to log out? You can't, your token will still be valid until it expires after the set amount of time has passed.
A token can be used for let's say half an hour, but your user may use the website for 1 hour. So before you hit any API endpoint, you could check ... has this token expired yet? if yes then you can go and refresh it and keep working without having to bother your user with a new login screen.
The whole point of an OAuth2 system is to make sure that only authorised clients can access it. A client is not a user, it's an application. You can have a  website for example and you only want users of that website to access your API.
You can have endpoints like ValidateUser for example, where you take a username and a password and return a yes or no and then you log your user in based on that.

A: Irrespective of language/framework, second approach is secure and better than first one because to get access token by providing refresh token to Authorization server, it still requires Client ID and Secret which should never be passed to Browser for security reasons.
In first approach, to make a direct call it will not work if your Authz Server is hosted on different domain than your frontend server because of Same Origin policy of browsers. Even if they are on same domain, still you are exposing Client ID and Secret which will compromise your frontend server


text:
Q: Specified module does not exist Angular 6 Can you tell me why I cannot use below CLI? It says Specified module does not exist. Same error for both CLI commands.
Note: I have upgraded this app from ng 5 to ng 6. Is that this error due to some issue on upgrading?
ng generate component messages --module=core

ng generate component messages --module=app

app.core.module.ts
export class CoreModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: CoreModule
    };
  }
}

app.module.ts
export class AppModule { }

ng --version
Angular CLI: 6.0.8
Node: 8.11.2
OS: win32 x64
Angular: 6.0.7
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, platform-server, router
... service-worker

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.6.8
@angular-devkit/build-angular     0.6.8
@angular-devkit/build-optimizer   0.6.8
@angular-devkit/core              0.6.8
@angular-devkit/schematics        0.6.8
@angular/cdk                      6.3.2
@angular/cli                      6.0.8
@angular/material                 6.3.2
@angular/tsc-wrapped              0.5.2
@ngtools/webpack                  6.0.8
@schematics/angular               0.6.8
@schematics/update                0.6.8
rxjs                              6.2.1
typescript                        2.7.2
webpack                           4.8.3

package.json
{
  "name": "Abc",
  "version": "0.0.1",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "run-s build:client build:aot build:server",
    "buildclient": "ng build --prod --build-optimizer --app 0",
    "build:aot": "ng build --aot --app 1",
    "build:server": "webpack -p",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "dev": "ng build --prod =cd dist http-server",
    "build:firebase": "ng build --prod && cp src/manifest_app.json dist && firebase deploy"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "6.0.7",
    "@angular/cdk": "^6.3.2",
    "@angular/common": "6.0.7",
    "@angular/compiler": "6.0.7",
    "@angular/core": "6.0.7",
    "@angular/forms": "6.0.7",
    "@angular/http": "6.0.7",
    "@angular/material": "^6.3.2",
    "@angular/platform-browser": "6.0.7",
    "@angular/platform-browser-dynamic": "6.0.7",
    "@angular/platform-server": "6.0.7",
    "@angular/router": "6.0.7",
    "@angular/service-worker": "6.0.7",
    "@auth0/angular-jwt": "^2.0.0",
    "@cloudinary/angular": "^2.1.1",
    "@jaspero/ng2-confirmations": "^0.3.3",
    "@ng-bootstrap/ng-bootstrap": "^1.0.0-beta.8",
    "@ng-select/ng-select": "^0.36.2",
    "@nguniversal/module-map-ngfactory-loader": "^5.0.0",
    "@types/moment": "^2.13.0",
    "angular2-useful-swiper": "^5.0.1",
    "cloudinary-core": "^2.4.0",
    "core-js": "^2.4.1",
    "hammerjs": "^2.0.8",
    "jquery": "^3.2.1",
    "moment": "^2.20.1",
    "ng-pwa-tools": "0.0.15",
    "ng2-cloudinary": "^0.9.2",
    "ng2-file-upload": "^1.3.0",
    "ng2-img-max": "^2.1.15",
    "ng4-geoautocomplete": "^0.1.0",
    "ng4-loading-spinner": "^1.1.1",
    "ngx-bootstrap": "^2.0.2",
    "ngx-toastr": "^6.5.0",
    "ngx-youtube-player": "^0.1.0",
    "raven-js": "^3.26.3",
    "rxjs": "^6.2.1",
    "rxjs-compat": "^6.2.1",
    "swiper": "^3.4.2",
    "webrtc-adapter": "^6.1.4",
    "zone.js": "^0.8.26"
  },
  "devDependencies": {
    "@angular/cli": "6.0.8",
    "@angular/compiler-cli": "6.0.7",
    "@angular/language-service": "6.0.7",
    "@types/googlemaps": "^3.30.8",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/jquery": "^3.2.18",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.2.0",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "npm-run-all": "^4.1.2",
    "protractor": "~5.1.2",
    "ts-loader": "^3.5.0",
    "ts-node": "~3.2.0",
    "tslint": "~5.7.0",
    "typescript": "2.7.2",
    "webpack-node-externals": "^1.6.0",
    "@angular-devkit/build-angular": "~0.6.8"
  }
}

A: I stumbled upon this issue and solved it by using a command like below:
ng g c core/header --module core/core.module.ts

I used this command and got error:
ng g c core/header --module core.module.ts

A: You can save yourself time and effort, instead of adding the command --module ../path/to/name.module each time for a new component, just add this configuration in your angular.json file:
 "projects": {
    "projectName": {
      "schematics": {
        "@schematics/angular:component": {
          "module": "../path/to/name.module"
       //.... other config

After that you can add a component as you would normally.

A: Just to update below command worked for me :

ng g c complete-path-of-folder/ComponentName --module
../complete-path-of-folder/home.module.ts

A: Below code works on latest CLI version.
ng generate component messages --module app.core.module
It doesn't requires .ts
If we want to create new component which points to specified module inside the folder, specify folder path. Folder path should root of app folder.
ng g c ./components/messages/messages --module message.module

Hope this helps.

A: Please use the path relative to your base-href that is src/app
Try
ng generate component messages --module ./app.core.module.ts


text:
Q: Derivation of the general forms of partial fractions I'm learning about partial fractions, and I've been told of 3 types or "forms" that they can take
(1) If the denominator of the fraction has linear factors:
$${5 \over {(x - 2)(x + 3)}} \equiv {A \over {x - 2}} + {B \over {x + 3}}$$
(2) If the denominator of the fraction has quadratic factors that don't factorise:
$${{2x + 3} \over {(x - 1)({x^2} + 4)}} \equiv {A \over {x - 1}} + {{Bx + C} \over {{x^2} + 4}}$$
(3) If the denominator has a factor that repeats:
$${{5x + 3} \over {(x - 2){{(x + 3)}^2}}} \equiv {A \over {x - 2}} + {B \over {x + 3}} + {C \over {{{(x + 3)}^2}}}$$

I'd appreciate it if someone could explain to me how these equivalence relationships are derived, essentially how do they take the forms that they do? I sort of understand the first one, but the other two I don't.
Thank you

A: Your first and second cases are equivalent. You need to understand complex numbers to be able to see that. The complex numbers, written $\mathbb{C}$ are of the form $x+iy$ where $x$ and $y$ are real numbers that you already know and $i$ is a special number with $i^2 = -1$. Usually, we have $i = \sqrt{-1}$. To see that the second case is the same as the first, notice that:
$$\frac{2x+3}{(x-1)(x^2+4)} \equiv \frac{A}{x-1}+\frac{B}{x-2i}+\frac{C}{x+2i}$$
where $A=1$, $B=-\frac{1}{2}-i\frac{1}{4}$ and $C=-\frac{1}{2}+i\frac{1}{4}$. The only reason you are taught the second form is that you don't know about $x\pm 2i$ and they recombine them:
$$\frac{B}{x-2i} + \frac{C}{x+2i} \equiv \frac{1-x}{x^2+4}$$
The third case isn't quite the same. But notice that the denominator is a cubic. When you multiply it out, you'll have an $x^3$ and lower powers. We couldn't get away with just two fraction because
$$\frac{A}{x-a}+\frac{B}{x-b} \equiv \frac{A(x-b)+B(x-a)}{(x-a)(x-b)}$$
and this only has a quadratic expression as the denominator.

A: As requested, I'm distilling and simplifying the information from this link:
http://caicedoteaching.wordpress.com/2008/11/18/175-partial-fractions-decomposition-2/
First, we need a concept. An irreducible polynomial is one that can't be reduced as a product of smaller-degree polynomials. These are the building blocks of all polynomials and, as you can see with partial fractions, we can usually break the study of composite polynomials into irreducible ones. We also need some facts. First, any polynomial of odd degree has a root. Intuitively, given such a polynomial $p(x)$, if $x$ is large then we can just ignore the lower order terms, so $p$ takes on some positive value, and if $x$ is very negative then the same thing happens but it takes on a negative value (if $p$ had even degree the negative sign would cancel, giving us nothing). So $p$ has to pass through zero somewhere. Second, we can write any quadratic polynomial as the sum of a square and a real number; for instance, $x^2 + 2x + 2 = (x+1)^2 + 1$. This is just completing the square. Third, any polynomial can be written as the product of linear factors and irreducible quadratic factors. This is not a trivial result, and I'm going to assume that you've seen it in the form of the Fundamental Theorem of Algebra, but I'm not going to prove it. The interpretation here is that $q$ is the denominator polynomial we're looking for, and we can really just reduce to the case where $q$ is a product of linear and quadratic factors. The case where these are just linear factors corresponds to your part 1, where the case with quadratic factors is part of your other parts. The "repeated factors" case will fall out of this naturally.
So, given some polynomial $q$ we can write it as $q(x) = C \cdot \prod_{i=1}^k(x-a_i)^{r_i} \cdot \prod_{i=1}^l ((x+b_i) + c_i)^{s_i}$. Then given any polynomial $p$ we can write $\frac{p(x)}{q(x)} = \sum_{i=1}^k \left( \sum_{j=1}^{r_i} \frac{a_{i,j}}{(x-a_i)^{r_i}} \right) + \sum_{i=1}^l \left( \sum_{j=1}^{s_i} \frac{b_{i,j}x + c_{i,j}}{((x+b_i)^2+c_i)^j} \right)$. I'm abusing notation a little, but know that the double-subscripted $a_{i,j}, b_{i,j},c_{i,j}$ are the constants we're looking for in the method of partial fractions, while the single-subscripted ones are the input.
This looks daunting, but it's exactly what you want to show. If $q(x) = (x-1)^2(x^2 + 2x + 2)$ then all we're saying is that, for example, there are the right constants to make the equality we want, $\frac{1}{(x-1)^2(x^2+2x+2)} = \frac{a}{x-1} + \frac{b}{(x-1)^2} + \frac{c}{x^2 + 2x + 2}$, hold. The interpretation in that awful sum is that the inner sums are going over the powers of each factor, i.e. how many times the factors appear in $q$, while the outer ones are going over the factors themselves.
We need a little preparation. First, if $p_1$ and $p_2$ are polynomials and for every $x$ we have $p_1(x) = p_2(x)$, then the coefficients of the polynomials are equal. This is "obvious" and I won't go into it unless requested. Second, if we have polynomials $p_1(x), p_2(x)$, with $p_2(x)$ not just the zero poylnomial, then there are unique polynomials $Q(x)$ and $R(x)$ with $p_1(x) = Q(x)p_2(x) + R(x)$. The $R$ stands for remainder and the $Q$ for quotient; this is just polynomial long division. If you haven't seen it I can explain, but for now I'll leave it be. Third, we need the notion of a greatest common divisor. If $p_1$ and $p_2$ are two polynomials then we can take the factors they have in common and throw them into another polynomial $D$; for instance, if $p_1(x) = (x-1)^2(x^2 + 2x + 2)(x-3)$ and $p_2(x) = (x-1)^2(x^2 + 1)(x^2 + 2)$ then $D = (x-1)^2$. Then $D$ is called the greatest common divisor of $p_1$ and $p_2$, or $\gcd(p_1,p_2) = D$.
Four, a theorem. If $p_1, p_2$ are polynomials and $D$ is their $\gcd$, then there are polynomials $q_1, q_2$ with $p_1Q_1 + p_2q_2 = D$. That is, we can multiply and combine polynomials to get their greatest common divisor. This is known as the Euclidean Algorithm. To prove this, we'll really just apply long division many times. We can assume that the degree of $p_1$ is greater than that of $p_2$, renaming them if necessary. Polynomial long division gives us $Q_0$ and $R_0$ with $p_1 = Q_0p_2 + R$. If $R_0 = 0$ then we can stop; $p_2$ actually divides $p_1$ evenly. If it's not zero we can continue, finding $Q_1, R_1$ with $p_2 = Q_1R_0 + R_1$. Each time, we divide the dividend of the previous step by the remainder of the previous step to get a new remainder. We have to stop eventually, because each time the degree of the dividend goes down at least by 1. When it does stop you end up with, say, the step right before you finish being $d = fg + h$ and the last step being $f = ih$, and for illustration the third-to-last step as $b = de + f$. Then we can use these equations to get $h = d - fg = d - (b - de)g = \cdots$. Eventually this will get you back to an equation like $h = Ap_1 + Bp_2$. But by the last step we had, $h$ divides $f$, and then $h$ divides $fg$ so by the second-to-last step $h$ divides $d$, and then by the same argument it divides $b$, and $\cdots$. Eventually you get that it divides $p_2$ and then $p_1$ by the first two steps. But if $h$ divides both of those then it certainly must divide their greatest common divisor as well, so $h$ divides $D$. Now if $h$ is missing some factors, we can just multiply the equation $h = Ap_1 + Bp_1$ by those missing factors to get what we want. If it's not missing some factors then that's the equation we're looking for.
We're getting close to the result. Let's write $q = d_1\ldots d_k$ where the $d_i$ are irreducible and have no common factors. Basically, we're getting those linear and quadratic terms I talked about early on. If $p$ is any polynomial, we should be able to write $\frac{p}{q} = a_0 + \sum_i \frac{b_i}{d_i}$ where the $b_i$ are some polynomials and $a_0$ is too, but with the degree of $b_i$ necessarily less than the degree of $d_i$. This sort of decomposition has to be true if we want partial fractions to work. We'll argue by induction on the number of irreducible factors of $q$. If $q = d_1$ then we can just use polynomial long division to get a $b_1$ with $p = a_0d_1 + b_0$, or rather $\frac{p}{q} = a_0 + \frac{b_0}{d_1}$. Now we'll move to the induction step. Let's assume that the result is true for $q$ a product of $m - 1$ polynomials that have no common factors. Let $q = d_1\ldots d_m$. Let's define $d = d_2 \ldots d_m$, so the product of all of the factors but the first one. By assumption $d_1$ and $d$ don't have any common factors, so their greatest common divisor is 1, so by the previous paragraph we can find some $e,f$ with $d_1e + df = 1$. Then $\frac{p}{q} = \frac{p\cdot 1}{q} = \frac{ped_1 + pdf}{q} = \frac{ped_1 + pdf}{d_qd} = \frac{pf}{d_1} + \frac{pe}{d}$. But we assumed we proved all the cases $1,\ldots,m-1$ so far, so if we apply the $m=1$ case using $pf$ for $p$ and $d_1$ for $q$ we get $\frac{pf}{d_1} = l_0 + \frac{b_1}{d_1}$ with the degree of $b_1$ less than that of $d_1$. Applying the $m = m-1$ case using $pe$ for $p$ and $d$ for $q$ we get $\frac{pe}{d} = k_0 + \sum_{i=2}^m \frac{b_i}{d_i}$. If you add these you get $\frac{pe}{d} + \frac{pf}{d_1} = (l_0 + k_0) + \sum_i \frac{b_i}{d_i}$ so $\frac{p}{q} = a_0 + \sum \frac{b_i}{d_i}$. We're done with this claim.
Now, can you see how to apply the previous paragraph to prove the result? In this case, $q = \prod (x-a_i){r_i} \prod ((x+b_i)^2+c_i)^{s_i}$ so we can just let each factor $d_i$ be something like $(x-a_i)^{r_i}$ or $((x+b_i)^2+c_i)^{s_i}$. Then we can use the above paragraph to get $\frac{p}{q} = \sum \frac{b_i}{d_i}$. Let's assume for a second that $d_i$ is a power of a linear factor. We can, using polynomial long division, write $b_i = \alpha_0 + \ldots + \alpha_{r_i}(x-a_i)^{r_i}$. Thus when we divide through by $d_i = (x-a_i)^{r_i}$ we get $\frac{b_i}{d_i} = \frac{\alpha_0}{(x-a_i)^{r_i}} + \ldots + \frac{\alpha_{r_i}}{1} = \sum_{j=1}^{r_i} \frac{a_{i,j}}{(x-a_i)^j}$, just as in the statement of the theorem.
Now, if $d_i = ((x + b_i)^2 + c_i)^{s_i}$, the exact same thing happens, except that we don't necessarily have to have a constant in the numerator. When you try to write $b_i = \alpha_0 + \ldots + \alpha_{s_i}((x + b_i)^2 + c_i)^{s_i}$ you're not totally guaranteed that it looks exactly like this. The reason for this is that in polynomial long division, the remainder always has a lower degree than the dividend. In the case of a linear factor this was fine; the only thing lower than linear is just a real number. But in the quadratic case we might end up with a linear remainder, which gives us the $b_{i,j}x + c_{i,j}$ in the theorem statement.

A: It comes from two facts for polynomials $f(x)$ and $g(x)$:

*

*We can find $a(x)$ and $b(x)$ such that $\gcd(f(x),g(x))=a(x)f(x)+b(x)g(x)$.

*We can write $f(x)=q(x)g(x)+r(x)$, where $\deg(r)<\deg(g)$.

For your second example, we can use fact 1 to write $1=a(x)(x-1)+b(x)(x^2+4)$. Multiplying by $2x+3$ yields:
$$2x+3=[(2x+3)a(x)](x-1)+[(2x+3)b(x)](x^2+4)$$
If $\deg((2x+3)a(x))\ge \deg(x^2+4)=2$, then we can use fact 2 to write $(2x+3)a(x)=q(x)(x^2+4)+r(x)$, where $\deg(r)<2$. Then:
$$2x+3=r(x)(x-1)+[q(x)(x-1)+(2x+3)b(x)](x^2+4)$$
Comparing degrees, we see that:
$$2x+3=r(x)(x-1)+s(x)(x^2+4)$$
where $\deg(r)<2$, and $\deg(s)<1$. Then:
$$\frac{2x+3}{(x-1)(x^2+4)}=\frac{r(x)(x-1)+s(x)(x^2+4)}{(x-1)(x^2+4)}=\frac{r(x)}{x^2+4}+\frac{s(x)}{x-1}=\frac{Ax+B}{x^2+4}+\frac{C}{x-1}$$

A: Assad, remember these are fractions, where the NUM has to be of lesser degree than the DENOM or than any factor of the DENOM. So if the DENOM is a non factorable quadratic, the NUM is allowed to be linear, as you are indicating.
If the DENOM is repeating, where the lowest term is linear, as in your example, than all of its factors have to be considered with constants in each NUM.
I don't think there is more to it, except that if you add them, you should get your original fractions back. Fraction addition ought to be the previous section of partial fraction decomposition. Once you understand the rudiments of fraction addition, you get a grip on PFD. Other than that, it's a matter of practice. Classify your DENOM, set up the partial fractions' DENOM's and work it out.
You may post some examples in seperate posts and we can help you to solve them.

A: I 'll give you what happens with the 2nd type, and the others work in the same way:
$${{2x + 3} \over {(x - 1)({x^2} + 4)}} =\dfrac{A}{x-1}+\dfrac{B}{x+2i}+\dfrac{C}{x-2i}=$$
$$\dfrac{A}{x-1}+\dfrac{Bx-2Bi+Cx+2Ci}{x^2+4}=$$
$$\dfrac{A}{x-1}+\dfrac{(B+C)x+(2Ci-2Bi)}{x^2+4}$$
Now it can be seen that $B+C,2Ci-2Bi$ must be reals, therefore $B+C=B',2Ci-2Bi=C'\in\mathbb R$
The same should happen in all cases, however you only need to learn by heart some rules and not apply always this decomposition in complex fractions.

A: To look at your third problem, consider the following example: $${{x^2 + 4} \over {(x)(x + 2){{(3x-2)}}}} = {A \over {x}} + {B \over {x + 2}} + {C \over {{{(3x-2)}}}}$$
Next, set the numerators equal. $$x^2+4 = A(x+2)(3x-2) + Bx(3x-2) + Cx(x+2)$$ Now pick few x values and find the constants. For $x=0,$ $4=A(2)(-2).$ So $A=-1$. Following the same procedure for $x=-2$ and $x=2/3,$ we find that $B = 1/2$ and $C = 5/2.$ Substituting our values give us $${{x^2 + 4} \over {(x)(x + 2){{(3x-2)}}}} = {1 \over {x}} + {1/2 \over {x + 2}} + {5/2 \over {{{(3x-2)}}}}$$
This is not an answer to your question but to show you how its usually done.

A: Let me take a stab at this from a linear algebra perspective, which is sadly not my strong point.  Let's consider a problem with the denominator of your second case.  Since the denominator is cubic, the numerator should be degree 2 or less, otherwise, we would use polynomial division first and perform partial fractions on the remainder, which would be degree 2 or less.  So we have
$$\frac{Dx^2+Ex+F}{(x-1)(x^2+4)}=\frac A{x-1}+\frac{Bx+C}{x^2+4}$$
and of course we are looking for something which is true for all $x$ for which our function is defined.  So if $x\ne1$ we have
$$Dx^2+Ex+F(1)=A(x^2+4)+Bx(x-1)+C(x-1)$$
Time to introduce some linear algebra terminology (which is hopefully more right than wrong...).  I don't know what the best way to define this is, but the given form of the left side is referred to a linear combination of $x^2,x,$ and $1$ just as the right side is a linear combination of $x^2+4,x(x-1),$ and $x-1$.  Since all degree 2 polynomials can be written as a linear combination of $x^2,x,$ and $1$, the set $\{x^2,x,1\}$ is said to span degree 2 polynomials.  The set is also said to be linear dependent since a linear combination of its elements (again, $Dx^2+Ex+F(1)$) equals $0$ (for all $x$) if and only if all coefficients equal $0$.  Since these elements span degree 2 polynomials and are linearly independent, they are said to form a basis for degree 2 polynomials.
Now, we have found the set of all polynomials with degree 2 or less has a basis of size 3.  Now it turns out since we have found a basis of dimension (size) 3 for the set of all polynomials of degree 2 or less, all such bases must also have size 3.  This explains why we need 3 coefficients, whether written as above or using complex numbers as others have done.
$$\frac{Dx^2+Ex+F}{(x-1)(x-2i)(x+2i)}=\frac A{x-1}+\frac B{x-2i}+\frac C{x+2i}$$

A: By no means an answer but too long for a comment and possibly useful.
Assuming $\operatorname{deg}Q>\operatorname{deg}P$ for $P/Q$, one may look at the simpler $1/Q$. Under the assumption one succeeds in decomposing into the zeroes of $Q$, a conjectured decomposition is
\begin{align}
\prod_{i=1}^N \frac1{x-x_i} &= \sum_{i=1}^N \left(\prod_{j\neq i} \frac1{x_{ij}}\right) \frac1{x-x_i}
\end{align}
The Heaviside cover-up method gives the generalization of this
\begin{align}
\prod_{i=1}^N \frac{x-a_i}{x-b_i} &= 1+ \sum_{i=1}^N \frac{b_i-a_i}{x-b_i} \left[\prod_{\substack{j\neq i\\1}}^N \frac{b_i-a_j}{b_i-b_j}\right]
\end{align}
If the zeroes of $Q$ are not known, then one wouldn't use PFD anyway. Hope this helps anyone.


text:
Q: Host Checker issue with Juniper Network Connect (VPN) on Windows 7 A company I am working for uses Juniper to provide a VPN access from outside (or from inside with a "foreign" computer).
When I try to connect to the VPN from inside but with a "foreign" computer, I get the error: "You're not allowed to open a session. Contact your administrator"
I tried with several browsers and Chrome is more verbose ^^. It says:
" your computer security is not satisfactory.
Host checker is not supported. Please contact your administrator"
And then I can clic a "retry" button.
When I do so, after a while I have some more messages:
"your system is not compatible with Host Checker"

*

*you must activate Active-X components to get a compatibility with Host Checker [...]

*OR you must install a JVM [...]"
Juniper VPN error on retry image
Well, getting this message on Chrome seems a bit strange as I understand only IE uses Active-X but OK, on Active-X controls are activated.
And I also updated my Java plugins to have them up-to-date and it still doesn't work.
I also tried several things with no effect:
- I have tried to turn the firewall off prior to connect to the VPN
- change the way my computer connects to the internet (proxy, no proxy etc.) but there is no change. - and obviously I do have access to the internet.
I am also able to get to another company's network through another VPN (cisco) with the same computer and from the same location.
- I tried to connect to Juniper VPN while running the other VPN /or not and still no change...
Does anyone have any idea please?
Thanks for your help !
Stéphanie


text:
Q: delete folder but the process cannot access the file because being used so i made a simple project where when i click a button the picture edit get an image from a folder file, but when i want to delete the folder  that contains the image, it gives me an error. the code as following
 private void button1_Click(object sender, EventArgs e)
    {
        string pathx = AppDomain.CurrentDomain.BaseDirectory + "\\TempImage\\" + "naruto" + ".png";
        pictureEdit1.Image = Image.FromFile(pathx);
    }

    private void button2_Click(object sender, EventArgs e)
    {
        string dir = AppDomain.CurrentDomain.BaseDirectory + "\\TempImage";
        try {
            if (Directory.Exists(dir))
            {
                //////give me an error in here///////
                Directory.Delete(dir, true);
            }
            else
            {
                MessageBox.Show("folder not found");
            }
        }
        catch (Exception ex)
            {
            MessageBox.Show(ex.Message);
        }

    }

the purpose of this, is in my main project, for cache purpose. so i get an image from a certain folder after coping it from server to local. and when i want to close the main project i need to clear the cache or folder
Update
which is better alternate 1 or alternate 2 (to dispose)
   private void button1_Click(object sender, EventArgs e)
    {
        string pathx = AppDomain.CurrentDomain.BaseDirectory + "\\TempImage\\" + "naruto" + ".png";

        //alternate1
        using (FileStream stream = new FileStream(pathx, FileMode.Open, FileAccess.Read))
        {
            pictureEdit1.Image = Image.FromStream(stream);
            //stream.Dispose();
        }

        //alternate2
        //Image img = new Bitmap(pathx);
        //pictureEdit1.Image = img.GetThumbnailImage(pictureEdit1.Width, pictureEdit1.Height, null, new IntPtr());
        //img.Dispose();

    }

A: The documentation on System.Drawing.Bitmap (http://msdn.microsoft.com/en-us/library/0cbhe98f.aspx) says:

The file remains locked until the Bitmap is disposed.

To get around this, you should replace this line:
pictureEdit1.Image = Image.FromFile(pathx);

With this:
Image img = new Bitmap(pathx);
pictureEdit1.Image = img.GetThumbnailImage(pictureEdit1.Width, pictureEdit1.Height, null, new IntPtr());
img.Dispose();

This should load the Bitmap only long enough to create a thumbnail version of the image for use in the PictureBox control, then dispose of it immediately, releasing the lock on the file but still displaying the image on the screen.
Hope this helps!
Edit: Here's the version using using that does the same thing:
using (Image img = new Bitmap(pathx)) {
  pictureEdit1.Image = img.GetThumbnailImage(pictureEdit1.Width, pictureEdit1.Height, null, new IntPtr());
}


text:
Q: I am getting an error while i am pushing an object to the array property in node js using monogoose My Problem is i want after i create the categoryName and then i create the product properties, then i can push the product properties to the categoryProduct field.
I tried that using $push and it gives me an empty array in the db.
CallBack Function for creating a product
//Here i am getting the values from the body

//create an object

const productObject = new productSchema({

    productName: req.body.productName,
    productPrice: req.body.productPrice,
    productCategory: req.body.productCategory,
    productQuantity: req.body.productQuantity,
    productSection: req.body.productSection,
    productExDate: req.body.productExDate

})

    //saving
    productObject
        .save()
        .then(data => {
            res.redirect('/halalMunchies/all-products');
        })
        .catch(err => {
            res.status(500).send({
                message: err.message || "Some error occured while creating a create operation"
            });
        });

    //pushing inside the productCategory in the category model

    categoryDB.findOneAndUpdate({ categoryName: req.body.productCategory }, { $push: { productsCategory: productObject._id } })
        .then(result => {
            console.log(result);
        })
        .catch(err => {
            console.log(err);
        })

the output
  {
  _id: new ObjectId("61a62e619c17c622153c4d1a"),
  categoryName: 'meat',
  productsCategory: [],
  __v: 0
}

In the categoryschema i have categoryname and productsCategory contains all the products that this category has.
Category Schema
    var categorySchema = new mongoose.Schema({

    //properties // shape of the documentation

    categoryName: {
        type: String,
        required: true,
        unique: true

    },

    productsCategory: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'productSchema',
        required: true
    }]

});

const categoryDB = mongoose.model('categorySchema', categorySchema);

In the productSchema one of it's properties is productCategory which it references to the categorySchema
    var productSchema = new mongoose.Schema({

    //defining the properties

    productName: {
        type: String,
        unique: true,
        required: [true, 'Product name is required'] // we can pass a message like this
    },

    productCategory: {
        type: mongoose.Schema.Types.String,
        ref: 'categorySchema',
        required: [true, 'Category name is required'] // we can pass a message like this
    },

    productPrice: {
        type: Float,
        required: [true, 'Price name is required'] // we can pass a message like this
    },

    productQuantity: {
        type: Number,
        required: [true, 'Quantity name is required'] // we can pass a message like this
    },

    productSection: {
        type: String,
        required: [true, 'Section name is required'] // we can pass a message like this
    },

    productExDate: {
        type: String,
        required: [true, 'ExDate name is required'] // we can pass a message like this
    }

})

const productDB = mongoose.model('productSchema', productSchema);

A: You can try it this way, assuming we're using an async function for the sake of simplicity to avoid .then .catch painful process:
const {
  productData,
  productCategory,
} = req.body;

const productObject = new productSchema({ ...productData });

await productObject.save();

const categoryObject = await categorySchema.findOne({ categoryName: productCategory });

if (!categoryObject) {
  // Throw some error
}

await categoryObject.productsCategory.push(productObject._id);
await categoryObject.save();

// then make your redirect to /halalMunchies/all-products

EDIT
const {
  productName,
  productPrice,
  productQuantity,
  productSection,
  productExDate,
  productCategory,
} = req.body;

const productObject = new productSchema({
  productName,
  productPrice,
  productCategory,
  productQuantity,
  productSection,
  productExDate,
});

await productObject.save();

If you mean by productCategory "category id", then you should fetch by _id:
const categoryObject = await categorySchema.findOne({ _id: productCategory });

if (!categoryObject) {
  // Throw some error
}

await categoryObject.productsCategory.push(productObject._id);
await categoryObject.save();

// then make your redirect to /halalMunchies/all-products


text:
Q: When I delete a file from a separate partition, it does not go to Trash I'm using Ubuntu in Dual boot with Windows 7. I have three partitions: one for Windows, one for Ubuntu, and one for my files (it is used in both OSs; let's call it D).
When I use Ubuntu and I delete a file from D, deleted files aren't going to Ubuntu trash (they are deleted directly). How can I fix this?

A: You can enable Trash on Windows partition by making yourself its owner.
Find out your user id:
$ id

Open the fstab file, which holds partition mounting configuration:
$ sudo gedit /etc/fstab

Find your Windows partition (the one of ntfs type). It will look like this:
/dev/sda3 /home/user/shared    ntfs    defauls,noatime 0 0

(Note, that it doesn't have to be /dev/sda3, and the mount point and options may differ).
Add uid=xxxx to its list of options, where xxxx is your user ID:
/dev/sda3 /home/user/shared    ntfs    defauls,noatime,uid=xxxx 0 0

Save the fstab file and unmount/remount the Windows partition or simply reboot the computer. If it doesn't help, you might have to also add your group ID as gid=yyyy.
Taken from here.

A: Check permission:
cd  ~/.local/share/
ls  -la | grep Trash

If it says root then change the permission using:
sudo chown username:username Trash

Also, if you are using the rm command, then files are deleted permanently.


text:
Q: jQuery, get click on frame B from within frame A I have several frames on my parent document. From within frame A I would like to detect a click on frame B with id="frameB".
I think I need to access the parent document first. I can get detect a click on the parent document with:
$(parent.document).click(function(){});

But I don't know how to get frameB in particular.

A: What about something like
$(parent.document).find('#frameB').contents().find('body').on('click', function() {
  // do stuff
});

A: If you wanted  a text box to do something that resides in FrameA, why not just bind the FrameB object to the click event, then trigger the event "click" on the element in framA


text:
Q: How can I repeat a specific iteration in a foreach loop in PHP? As there is no iterator in PHP, the only way to loop through an array without getting the length of the array is to use foreach loop.
Let say I have the following loop:
foreach ($testing_array as $testing_entry) {
    $result = my_testing_api_call($testing_entry);
    if ($result == 'server dead')
        break;
    else if ($result == 'done') {
        // do something to handle success code
        continue;
    }
    else {
        sleep(5);
        // I want to retry my_testing_api_call with current $testing entry, but don't know what to write
    }
}

One way to do that is to use for loop instead.
for ( $i=0; $i < count($testing_array); $i++ ) {
    $result = my_testing_api_call($testing_entry[$i]);
    if ($result == 'server dead')
        break;
    else if ($result == 'done') {
        // do something to handle success code
        continue;
    }
    else {
        sleep(5);
        $i--; //so it will repeat the current iteration.
    }
}

The problem is that the $testing_array is not originally using number as index, so I have to do some data massage to use a for loop. Is there a way I can repeat a specific iteration in a foreach loop?

A: Perhaps a do-while will work for you.
Untested Code:
foreach ($testing_array as $testing_entry) {
    do {
        $result = my_testing_api_call($testing_entry);
        if ($result == 'server dead') {
            break 2;  // break both loops
        } elseif ($result == 'done') {
            // do something to handle success code
        } else {
            sleep(5);
            // I want to retry my_testing_api_call with current $testing entry, but don't know what to write
        }
    } while ($result !== 'done');
}

Or a single loop structure that destroys the input array as it iterates.
Untested Code:
$result = '';
while ($testing_array && $result !== 'server dead') {
    $result = my_testing_api_call(current($testing_array));
    if ($result == 'done') {
        // do something to handle success code
        array_shift($testing_array);
    } elseif ($result !== 'server dead') {
        sleep(5); // I want to retry my_testing_api_call with current $testing entry, but don't know what to write
    }
}

Or you can use your for loop by indexing $test_array with array_values() if you don't need the keys in your // do something.
$testing_array = array_values($testing_array);
for ($i=0, $count=count($testing_array); $i < $count; ++$i) {
    $result = my_testing_api_call($testing_entry[$i]);
    if ($result == 'server dead') {
        break;
    } else if ($result == 'done') {
        // do something to handle success code
    } else {
        sleep(5);
        --$i; //so it will repeat the current iteration.
    }
}

If you do need the keys down script, but you want to use for, you could store an indexed array of keys which would allow you to use $i to access the keys and maintain data synchronicity.

 My final suggestion:
Use while (key($testing_array) !== null) {...} to move the pointer without destroying elements.
Code: (Demo)
$array1 = [
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "four" => 4
];

while (key($array1)!==null) {  // check if the internal pointer points beyond the end of the elements list or the array is empty
    $current = current($array1);
    $key = key($array1);
    echo "$key => $current\n";         // display current key value pair
    if ($current < 3) {                // an arbitrary condition
        echo "\t";
        $array1[$key] = ++$current;    // increment the current value
    } else {                           // current value is satisfactory
        echo "\t(advance pointer)\n";
        next($array1);                 // move pointer
    }
}

Output:
one => 1
    one => 2
    one => 3
    (advance pointer)
two => 2
    two => 3
    (advance pointer)
three => 3
    (advance pointer)
four => 4
    (advance pointer)

A: To repeat a single specific iteration you need to add a control mechanism, it is not an intended behavior after all.
There are many suggestions here, all of them are kinda over-engineered.
PHP is a high level derivate of C and both languages have the 'goto' operator, it has a bad reputation because people have historically used it too much.
In the end a foreach/while loop is internally nothing else than a 'goto' operation.
Here is the code:
foreach ($array as $key => $value)
{
restart:
if ($value === 12345) goto restart;
}

That's how this should be done just keep in mind that this can cause an endless loop, like in the example.
Look at the next complicated version without goto:
foreach ($array as $key => $value) while(1)
{
if ($value === 12345) continue;
break;
}

This is essentially the same as the goto, just with more code.
If you'd want to "break" or "continue" the foreach loop you'd write "break 2"  or "continue 2"

A: You are trying to handle two different things in your loop, that makes it hard to write clean control flow. You could separate the retry-logic from the result handling:
function call_api_with_retry($entry) {
  do {
    if (is_defined($result)) sleep(5);
    $result = my_testing_api_call($entry);
  } while ($result != 'done' && $result != 'server dead');
  return $result;
}

foreach ($testing_array as $testing_entry) {
    $result = call_api_with_retry($testing_entry);
    if ($result == 'server dead')
        break;
    else if ($result == 'done') {
        // do something to handle success code
        continue;
    }
}

(there might be syntax errors, it's been a while since I wrote PHP code)


text:
Q: Network connection error- react native using expo cli I'm building an API and react-native application. The server works well (tested with PostMan) but the application doesn't call the server. It blocks when axios has to send the post request.
I also tried to type ip address instead of localhost but it didn't worked as well. (HERE IS MY CODE)
 const LoginScreen = ({ navigation }) => {
  const [hidePassword, setHidePassword] = useState(true);
  const [message, setMessage] = useState();
  const [messageType, setMessageType] = useState();

  const handleSubmit = (credentials, setSubmitting) => {
    handleMessage(null);
    const url = "http://192.168.1.110:5000/bankrate/login/login";
    axios
      .post(url, credentials)
      .then((res) => {
        const result = res.data;
        const { message, status, data } = result;

        if (status !== "SUCCESS") {
          handleMessage(message, status);
        } else {
          navigation.navigate("HomeScreen", { ...data[0] });
        }
        setSubmitting(false);
      })
      .catch((error) => {
        console.log(error);
        setSubmitting(false);
        handleMessage(
          "An error occurred! Check your network connection and try again!"
        );
      });
  };

A: Use JavaScript's Fetch API instead:
const handleSubmit = (credentials,setSubmitting) => {
fetch("http://192.168.1.110:5000/bankrate/login/login", {
method: "post",
headers: { "Content-Type": "insert-mime-type-here (see below)" }
body: // whatever you're sending to the server
}}).then((response) => { if (response.status() === 400) {
// return either response.json() or response.body() or whatever (see below for details)
else {
return Promise.reject();
}).then((data) => { // do whatever you want to with the data you get from the server }).catch((error) => // promise rejected);

The MIME type you use is the MIME type of whatever you send to the server.
If the server responds with a JSON object, use response.json(), and then data will be a JavaScript object.
If the server responds with anything else, use response.text() and then data will be text.


text:
Q: Defining a type cast in Java I want to define a type cast from an arbitrary type to a primitive data type in Java. Is it possible to define a cast from one arbitrary type to another arbitrary type?
public class Foo{
    //methods, constructor etc for this class
    ...
    //make it possible to cast an object of type Foo to an integer
}
//example of how an object of type foo would be cast to an integer
public class Bar(){
    public static void main(String[] args){
        Foo foo1 = new Foo();
        int int1 = (int)foo1;
        System.out.println(int1+"");
    }
}

A: You can't cast it, but you can provide a conversion function:
public class Foo{
    //methods, constructor etc for this class
    ...
    public int toInt(){
        //convert to an int.
    }
}

Bar then becomes:
public class Bar(){
    public static void main(String[] args){
        Foo foo1 = new Foo();
        int int1 = foo1.toInt();
        System.out.println(int1+"");
    }
}

A: It is not possible to convert from a class type (eg. Foo) to a primitive type directly. Instead you should define methods (eg. int asInteger()) that return the value of a Foo object as an integer.

A: No, it's not. It wouldn't really make sense: how could a Foo become an int?
Rather define a sequence of appropriate methods, such as:
public int toInt() { return 42; }

Typecasting between primitive types and Java types, such as between int and Integer, was not even originally part of Java.

A: class Foo must extend Number. Why would you want to do that though? why not just access an int variable inside of foo.


text:
Q: "not in" identity operator not working when checking empty string for certain characters When checking if an empty string variable is populated with certain characters, the expression is always evaluated as true. If the newly created string value is empty, it should be false, it does not contain any characters let alone the ones being checked for.
When I hard-code a random character that is not the character being checked for the expression is evaluated as false.
difficulty = ''

while difficulty not in 'EMH':
    print('Enter difficulty: E - Easy, M - Medium, H - Hard')
    difficulty = input().upper()

I expect to see the debugger enter the while loop. What actually happens is it continues past the while block without executing.

A: An empty string is present in any string. Therefore your condition, difficulty not in 'EMH' will evaluate to False when difficulty equals ''; so the while loop's body won't be executed.
In [24]: '' not in 'EMH'
Out[24]: False

In [33]: '' in 'EMH'
Out[33]: True

A better approach might be to convert the string EMH to a list via list('EMH') so that something like EM or EH, or a empty character doesn't break your loop, or avoid it from starting in the first place
Also as @Blckknght suggested, a better alternative is use a default value of None for difficulty.
In [3]: difficulty = None

In [4]: while difficulty not in list('EMH'):
   ...:     print('Enter difficulty: E - Easy, M - Medium, H - Hard')
   ...:     difficulty = input().upper()
   ...:
Enter difficulty: E - Easy, M - Medium, H - Hard
A
Enter difficulty: E - Easy, M - Medium, H - Hard
B
Enter difficulty: E - Easy, M - Medium, H - Hard
C
Enter difficulty: E - Easy, M - Medium, H - Hard
EM
Enter difficulty: E - Easy, M - Medium, H - Hard
E

In [5]:

A: I think what you need to use is a list, instead of a string:
difficulty = ''

while difficulty not in ['E','M','H']:
    print('Enter difficulty: E - Easy, M - Medium, H - Hard')
    difficulty = input().upper()

A: This is a good case for a do-while loop condition. But, python doesn't have it. Please check if the below style suits you:
while True:
    print('Enter difficulty: E - Easy, M - Medium, H - Hard')
    difficulty = input().upper()
    if difficulty not in 'EMH': #or in ['E', 'M', 'H']
        continue
    else:
        #do some logic
        break

I do like @Emmet B's suggestion to use ['E', 'M', 'H'] in a loop rather than as a string. It makes sense also as you are expecting one of the character as input and not set of characters.

A: If you're inclined to live on the bleeding edge of Python, you might be interested in trying out Python 3.8, which is currently being developed (but alpha releases are available). A somewhat controversial new feature (introduced in PEP 572) is assignment expressions, which let you use := to do an assignment in the middle of another expression.
The loop you're doing could take advantage of such an assignment to do the input and value checking all in one go, without needing to assign a bogus initial value to difficulty before entering the loop.
Note that you probably still want to use a list rather than using not in with a string on the right side, as the latter does a substring check, not a strict sequence membership test. A substring test like difficulty not in 'EMH' will give unintended results for the empty string or the multi-letter inputs 'EM', 'MH' and 'EMH'. If you might use your different difficulty strings as dictionary keys somewhere (e.g. to look up stats that vary with the difficulty setting), you might test if the input is a key in the dictionary directly, rather than building a separate list.
prompt = 'Enter difficulty: E - Easy, M - Medium, H - Hard\n'
while (difficulty := input(prompt).upper()) not in ['E', 'M', 'H']:
    pass  # or maybe: print("I'm sorry, I didn't understand that.")

# you can use `difficulty` down here

Note that while you can use assignment expressions here, it's not necessarily a good idea to do so, just to avoid initializing a variable. You end up bundling up so many different things into a single line (the while, the input and upper calls, the assignment with :=, and the not in test) that it can be easy to get confused about what is going on. Indeed, in my example above, I ended up creating a different variable (prompt) because the line would have been too long otherwise.

A: The solution is already mentioned (using a list will solve the problem, and initializing the variable to None is pretty clean, IMHO), but there are so many different ways to do this (despite rule #13 of the Zen of Python).
One suggestion I have not seen mentioned yet is to use a separate boolean in the while expression, so you don't have to initialize the difficulty variable with an arbitrary invalid value, and don't need other continue / break / else / pass statements:
valid_input = False
while not valid_input:
    print('Enter difficulty: E - Easy, M - Medium, H - Hard')
    difficulty = input().upper()
    valid_input = difficulty in ['E', 'M', 'H']


text:
Q: T-Sql cursor not proceeding on fetch I know that cursors are frowned upon and I try to avoid their use as much as possible, but there may be some legitimate reasons to use them. I have one and I am trying to use a pair of cursors: one for the primary table and one for the secondary table. The primary table cursor iterates through the primary table in an outer loop. the secondary table cursor iterates through the secondary table in the inner loop.
The problem is, that the primary table cursor though apparently proceeding and saving the primary key column value [Fname] into a local variable @Fname, but it does not get the row for the corresponding foreign key column in the secondary table. For the secondary table it always returns the rows whose foreign key column value matches the primary key column value of the first row of the primary table.
Following is a very simplified example for what I want to do in the real stored procedure.
Names is the primary table
SET NOCOUNT ON
DECLARE
    @Fname varchar(50) -- to hold the fname column value from outer cursor loop
    ,@FK_Fname varchar(50) -- to hold the fname column value from inner cursor loop
    ,@score int
;

--prepare primary table to be iterated in the  outer loop
DECLARE @Names AS Table (Fname varchar(50))
INSERT @Names
    SELECT 'Jim' UNION
    SELECT 'Bob' UNION
    SELECT 'Sam' UNION
    SELECT 'Jo'

--prepare secondary/detail table to be iterated in the inner loop
DECLARE @Scores AS Table (Fname varchar(50), Score int)
INSERT @Scores
    SELECT 'Jo',1 UNION
    SELECT 'Jo',5 UNION
    SELECT 'Jim',4 UNION
    SELECT 'Bob',10 UNION
    SELECT 'Bob',15

--cursor to iterate on the primary table in the outer loop
DECLARE curNames CURSOR
FOR SELECT Fname FROM @Names

OPEN curNames
FETCH NEXT FROM curNames INTO @Fname

--cursor to iterate on the secondary table in the inner loop
DECLARE curScores CURSOR
FOR
    SELECT FName,Score
    FROM @Scores
    WHERE Fname = @Fname
 --*** NOTE: Using the primary table's column value @Fname from the outer loop

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT 'Outer loop @Fname = ' + @Fname

    OPEN curScores
    FETCH NEXT FROM curScores INTO @FK_Fname, @Score

    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT ' FK_Fname=' + @FK_Fname + '. Score=' + STR(@Score)
        FETCH NEXT FROM curScores INTO @FK_Fname, @Score
    END
    CLOSE curScores
    FETCH NEXT FROM curNames INTO @Fname
END

DEALLOCATE curScores

CLOSE curNames
DEALLOCATE curNames

Here is what I get for the result. Please note that for the outer loop it DOES show the up-to-date Fname, but when that Fname is used as @Fname to fetch the relevant row from the secondary table for the succeeding iterations, it still get the rows that match the first row (Bob) of the primary table.
Outer loop @Fname = Bob
    FK_Fname=Bob. Score=10
    FK_Fname=Bob. Score=15
Outer loop @Fname = Jim
    FK_Fname=Bob. Score=10
    FK_Fname=Bob. Score=15
Outer loop @Fname = Jo
    FK_Fname=Bob. Score=10
    FK_Fname=Bob. Score=15
Outer loop @Fname = Sam
    FK_Fname=Bob. Score=10
    FK_Fname=Bob. Score=15

Please let me know what am I do wrong.
Thanks in advance!

A: The value of @fName is evaluated at :DECLARE curScores CURSOR and not in the primary loop.
You must Declare and then deallocate the secon cursor in the primary loop.

A: Thanks to few hints, I was able to find the solution.
I had to DECLARE and DEALLOCATE the secondary cursor within the first loop. I initially hated to do it as I thought alocating and deallocating resources in the loop was not a good idea, but I think there is no other way to avoid this in this particular situation. Noew the working code looks some thing like this:
SET NOCOUNT ON
DECLARE
    @Fname varchar(50) -- to hold the fname column value from outer cursor loop
    ,@FK_Fname varchar(50) -- to hold the fname column value from inner cursor loop
    ,@score int
;

--prepare primary table to be iterated in the  outer loop
DECLARE @Names AS Table (Fname varchar(50))
INSERT @Names
    SELECT 'Jim' UNION
    SELECT 'Bob' UNION
    SELECT 'Sam' UNION
    SELECT 'Jo'

--prepare secondary/detail table to be iterated in the inner loop
DECLARE @Scores AS Table (Fname varchar(50), Score int)
INSERT @Scores
    SELECT 'Jo',1 UNION
    SELECT 'Jo',5 UNION
    SELECT 'Jim',4 UNION
    SELECT 'Bob',10 UNION
    SELECT 'Bob',15

--cursor to iterate on the primary table in the outer loop
DECLARE curNames CURSOR
FOR SELECT Fname FROM @Names

OPEN curNames
FETCH NEXT FROM curNames INTO @Fname

--cursor to iterate on the secondary table in the inner loop
DECLARE curScores CURSOR
FOR
    SELECT FName,Score
    FROM @Scores
    WHERE Fname = @Fname
 --*** NOTE: Using the primary table's column value @Fname from the outer loop

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT 'Outer loop @Fname = ' + @Fname

    OPEN curScores
    FETCH NEXT FROM curScores INTO @FK_Fname, @Score

    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT ' FK_Fname=' + @FK_Fname + '. Score=' + STR(@Score)
        FETCH NEXT FROM curScores INTO @FK_Fname, @Score
    END
    CLOSE curScores
    FETCH NEXT FROM curNames INTO @Fname
END

DEALLOCATE curScores

CLOSE curNames
DEALLOCATE curNames

And I am getting the right results:
Outer loop @Fname = Bob
    FK_Fname=Bob. Score=        10
    FK_Fname=Bob. Score=        15
Outer loop @Fname = Jim
    FK_Fname=Jim. Score=         4
Outer loop @Fname = Jo
    FK_Fname=Jo. Score=         1
    FK_Fname=Jo. Score=         5
Outer loop @Fname = Sam

A: I think you could do this so much easier with temp tables that have row numbers:
create table #temp1
(
 row int identity(1,1)
 , ...
)

It really looks like you're asking SQL to behave like a language that likes loops. It doesn't. Whenever I find myself writing a loop in SQL I ask myself, does it have to be done this way? 7/10 times the answer is no, I can do it with sets instead.

A: I'd try placing the
DECLARE curScores CURSOR
FOR
    SELECT FName,Score
    FROM @Scores
    WHERE Fname = @Fname

inside the first while, beacuse you're declaring the cursor only for the first name value