## c++ – Is there any way to use a single for Loop for this code?

I want to use only one for Loop for this code. Is this possible? If not then how can I optimise my code further?

It works well for the constraint 1 ≤ T ≤ 10, 2 ≤ N ≤ 10^3, 1 ≤ M ≤ 10^5,
but I am getting time limit exceeded for 1 ≤ T ≤ 100, 2 ≤ N ≤ 10^5, 1 ≤ M ≤ 10^5.

``````#include <iostream>
using namespace std;
#include <vector>
#include <bits/stdc++.h>
#include <iterator>
#include <utility>
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::cpp_int;

using namespace std;

int main() {
// your code goes here
ios_base::sync_with_stdio(false);
cin.tie(NULL);

cpp_int t,ans;
std::cin >> t;
while(t-->0) {

cpp_int n;
std::cin >> n;

cpp_int m;
std::cin >> m;

cpp_int count=0;

for(int a=1;a<=n;++a)
{
for(int b=1;b<=n;++b)
{

if(a<b)
{
if( ((m%a)%b) == ((m%b)%a) )
count++;
}
}
}

cout << count << "n";
}
return 0;
}
``````

## python – write Function Using While loop

Write a function named test_sqrt that prints a table like the following using a while loop, where “diff” is the absolute value of the difference between my_sqrt(a) and math.sqrt(a).
a = 1 | my_sqrt(a) = 1 | math.sqrt(a) = 1.0 | diff = 0.0
a = 2 | my_sqrt(a) = 1.41421356237 | math.sqrt(a) = 1.41421356237 | diff = 2.22044604925e-16

Here is what I have tried and not working.
import math

def my_sqrt(a):
x = 1
while True:
y = (x + a / x) / 2.0
if y == x:
break
x = y

``````return y
``````

def test_sqrt():
while True:
for a in range(1, 9):
approxsqrt = my_sqrt(a)
actualsqrt = math.sqrt(a)
print(“a =”, a,”my_sqrt(a) =”,
approxsqrt,”math.sqrt(a) =”,
actualsqrt,”diff =”,
abs(approxsqrt – actualsqrt))

## Running Program Again With Loop in Java

Running Program Again With Loop in Java – Code Review Stack Exchange

## python – Discord.py Task Loop Running Too Often and Not Completing

I’m currently running into an issue with Discord.py where I have a task loop which keeps reiterating instantly without actually finishing. Below you can find a snippet of my code.

``````import discord
from discord.ext import commands, tasks
import insider

@client.event
check_insider_activity.start()

async def check_insider_activity():
``````

Whenever I run my code, the output is as follows :

``````Bot is ready.
``````

It sends “Checking Insider Buys” roughly every second or two, and keeps on doing that until I exit the program. The function get_new_insider_buys() never seems to complete, and I never get to the print statement before the task seems to just restart.

For some context, get_new_insider_buys() is a function which returns a list of new insider buys. The function scrapes a webpage using BeautifulSoup and manipulates some data using a Pandas Dataframe, then writes it to a local file before returning a list.

get_new_insider_buys() runs perfectly on its own, but as soon as I want to put it into the Discord.py task loop, it never seems to execute.

I feel as though I’ve got some form of concurrency or task error happening within the function, though I don’t know how or why, and I’m at my wits end. I can get other tasks working just fine, but as soon as I add this one to the mix, it all breaks, and all of my tasks start behaving like this one.

## context free – Eliminating left recursion using a loop construct

I’m trying to merge a little bit of theory with a little bit of practice. I’m writing a parser-generator that generates a top-down parser based on a given grammar.

I’d like to handle left- and right recursion properly, so they would each yield the “left-recursive” and “right-recursive” tree respectively (I’m not sure if left- and rightmost derivative would be a correct term here, that would mean the whole tree). This is very important for PEG, where the associativity and order of operations is encoded in the tree. The problem is that top-down parsers can’t deal with left-recursion directly.

I know the elimination rule for left-recursion, which is given a rule in the form

$$A rightarrow A alpha_1 | dots | A alpha_n | beta_1 | dots | beta_m$$

We can rewrite it into right-recursion using the following 2 rules:

$$A rightarrow beta_1 A’ | dots | beta_m A’ \ A’ rightarrow alpha_1 A’ | dots | alpha_n A’ | varepsilon$$

This is fine for the “formal” part, but the grammar became right-recursive. To me this rule seems like it’s just using right-recursion to essentially loop parts of the grammar.

So my idea was to introduce a looping construct that would account for folding the tree left. If I introduce a new postfix operator `*` that would mean repeating the construct 0 or more times, would the following also be a valid equivalent left-recursion elimination for A?

$$A rightarrow (beta_1 | dots | beta_m) (alpha_1 | dots | alpha_n)^*$$

Note that since the repetition can occur 0 times, this should account for the “epsilon-case” too.

I have a strong suspicion that this is equivalent, as I did something very similar when manually parsing left-associative operators in math expressions. I’d like confirmation before introducing it in a general tool.

## r – For loop results

here I’m using a subset of my big data.
I divided my data into two sets where the first one predicting each study in the second set. my code id running correctly except for the “for loop”. its only show the last row results

``````library(metafor)
year <- c(1978, 1983, 1974, 1989, 1974, 2002, 1990, 1974, 1998)
study.name <- c("Banninger 1978", "Roberts 1983", "Beard 1974", "Mahomed 1989", "Livingstone 1974", "Upton 2002", "Olah 1990", "Rogers 1974", "Mackrodt 1998")
y <- c(-0.81, -8.12, -0.67, -0.77, -0.03, -0.94, -6.78, -0.12, -0.34)
s2 <- c(0.11, 0.19, 0.05, 0.17, 0.09, 0.03, 0.08, 0.22, 0.21)
data <- as.data.frame(cbind(year, study.name, y, s2))
data\$y <- as.numeric(data\$y)
data\$s2 <- as.numeric(data\$s2)

results.all <- data.frame(proportion=NA, first.pred=NA)

data <- data(order(data\$year),)           # sorting MA by year

dd <- data(1:3,)                          # first data

result <- rma(yi = dd\$y, vi = dd\$s2)
alpha <- 0.05
n <- result\$k

remaining <- data( !(data\$study.name %in% dd\$study.name), )  # the remaming studies

NS <- nrow(remaining)   # 6 studies

# using y and s2 for each remaming studies
for (i in NS) {
lower.PI <- result\$b - qt(1-alpha/2,n-2)*sqrt(result\$tau2 + (result\$se)^2 + remaining\$s2(i))
upper.PI <- result\$b + qt(1-alpha/2,n-2)*sqrt(result\$tau2 + (result\$se)^2 + remaining\$s2(i))
decision <- as.numeric(ifelse(sapply(remaining\$y(i), function(p)
any(lower.PI <= p & upper.PI >= p)),"1", "0"))              # decision should be 1,0,1,0,1,1
}

proportion <- mean(decision)      # should be 0.666667
first.pred <- decision(1)         # should be 1

results.all <- c(proportion = proportion, first.pred = first.pred)
``````

My final results should be

``````proportion     first.pred
0.666667           1
``````

Is anyone able to find what I’m missing in for loop to be able to get the correct results for each row and find the correct results?

## recursion – Perform sum of squared numbers without using for loop

There is a base case… it’s the line `if x > 0 {`

compare to the for loop version

`for x=input: x>0: x=x-1 {`

`findSquareSum(input,a,x)` sets x=input

`if x > 0 {` is the condition check

`findSquareSum(x-1, a, iteration)` decrements x

also consider the modified fucntion

``````func findSquareSum(x int, a ()int, iteration int) {
var num int
if x <= 0 { return }

fmt.Scanf("%d", &num)
if num > 0 {
a(iteration-1) += num * num
}
findSquareSum(x-1, a, iteration)
}
``````

now it should look more like the base cases we are to seeing. It should also be clear that this is equivalent to the askers version (unless my go syntax is wrong!)

similarly

``````func readTest(x int, a ()int){
var input int
if x <= 0 { return }
fmt.Scanf("%d", &input)
findSquareSum(input,a,x)
}
``````

## categories – I want to show the category image (set with ACF) inside a loop that shows it inside the cards, how can I do it?

``````<?php get_header();

\$category = get_category( get_query_var( 'cat' ) );
\$cat_id = \$category->cat_ID;

\$id_cat = array('parent' => \$cat_id);
\$categories = get_categories( \$id_cat );
``````

// Get particular category’s object info.
\$queried_object = get_queried_object();

// (Optional depending on desired outcome) If you wanted to get the type of taxonomy.
\$taxonomy = \$queried_object->taxonomy;

// (Optional depending on desired outcome) If you wanted to get the associated ID.
\$term_id = \$queried_object->term_id;

// Get image ID for this field.
\$attachment_id = get_field( ‘category_image’, \$queried_object );

// URL of image at specific size.
\$image = \$attachment_id(‘sizes’)(‘chosen-image-size’);

``````?>
``````
``````<section class="p-5">
<div class="container">
<div class="row text-center">
<h3><?php single_cat_title(); ?></h3>
<p><?php category_description(); ?></p>
</div>
</div>
</section>

<section>
<div class="container animated">
<div class="row d-flex" data-masonry='{"percentPosition": true }'>
``````

‘.’
term_id ).'”>’ .\$category->name.”.’

‘;
}

?>

### In evidenza

``````            <?php while(have_posts()): the_post(); ?>
<div class="col-6 col-md-4 col-xl-3 mb-4">
<div class="card text-center">
<a href="<?php the_permalink() ?>">
<!-- Immagine Articolo -->
<?php if(has_post_thumbnail()): ?>
<div class="m-1"><?php the_post_thumbnail('thumbnail') ?></div>
<?php endif; ?>
</a>
<div>
<h3><?php the_title(); ?></h3>
<p><?php the_excerpt(); ?></p>
</div>
<a href="<?php the_permalink() ?>" class="btn btn-outline-dark btn-sm">Continua a
Leggere</a>
</div>
</div>
<?php endwhile; ?>
<?php else: ?>
<?php echo wpautop('ops.. non ho trovato nulla');?>
<?php endif; ?>
</div>
</div>
</section>
``````

## How to add a shortcode function that returns the taxonomy slug of the actual post within the loop

Circumstances: I have a CPT called “designs” and a taxonomy related to it, called “project_category” so that I can assign a category to each design. I’m building the template for each ‘design’ and I need a shortcode that returns the assigned project category SLUG of the current design within the loop.

It’s important that I retrieve the slug instead of the ID because I’ll be using the shortcode to wrap the whole template and assign it an #ID name so I can then target it with a link.

Example: I have a design post called “New logo for Pepsi” which has “Visual Identity” as it’s project category. So I’d need the shortcode to return “visual_identity” instead of “Visual Identity”.

Facts to consider: each design will have only one category assigned, so I don’t need the shortcode to return an array, only a single slug.

I guess it should be something like this:

``````add_shortcode( 'return_taxonomy_slug', 'my_shortcode_return_taxonomy_slug' );

function my_shortcode_return_taxonomy_slug() {
return get_the_terms( \$designs, \$project_category->slug );
}
``````

…or maybe something like this to work-around:

``````add_shortcode( 'return_taxonomy_slug', 'my_shortcode_return_taxonomy_slug' );

\$terms = wp_get_post_terms( get_the_ID(), 'project_category');

function my_shortcode_return_taxonomy_slug() {
return \$terms->slug;
}
``````

## python – Using a for loop to separate nested lists into its own variable

I am trying to iterate and separate nested lists.
My data input is currently something like this. .

``````mainlist = (('1', 'HiII', '0', '1407', '0', 'Commander', '11.06.2018'), ('2', 'wEEDzy', '0', '1184', '0', 'Private', '24.03.2021'))
``````

My goal is to use a for loop to separate each list into its own list, then pull specific variables from that list, then output it to a text file. I want to pull only values 1,3 & 5 from each list.

Now that you know my objective, I am trying to use a for loop to separate each list into its own variable and make that list only those 3 values that are needed.

This is the desired output (each assigned to a variable, then added to a .txt value)

``````('HiII', '1407', 'Commander')
('wEEDzy','1184', 'Private')
``````

My current code is this: , which separates a list and then adds only the things I want from the list to it.

``````member1 = list(mainlist(0))
templist = ()
templist.append(member1(1))
templist.append(member1(3))
templist.append(member1(5))
``````

What I cant figure out is how to do this for each one for x amount of members so I dont copy and paste it everytime. Can anyone help?