What I want is to optimize this part of my code. It is just repeating itself but I don't know how to use a repetition structure here using the defines I used.
I defined the GPIO_Ports and Pins.
And this go forward until SEL8.
if (out & (1 << 0)) {
GPIO_SetBits(SEL0_GPIO_Port, SEL0_Pin);
} else {
GPIO_ResetBits(SEL0_GPIO_Port, SEL0_Pin);
}
if (out & (1 << 1)) {
GPIO_SetBits(SEL1_GPIO_Port, SEL1_Pin);
} else {
GPIO_ResetBits(SEL1_GPIO_Port, SEL1_Pin);
}
if (out & (1 << 2)) {
GPIO_SetBits(SEL2_GPIO_Port, SEL2_Pin);
} else {
GPIO_ResetBits(SEL2_GPIO_Port, SEL2_Pin);
}
We don't know the types of variables used. The code could look something like this:
#include <assert.h>
// Indexas valid are from 0 to 8, some 9
#define IDX_MAX 9
typedef /* insert the type of SELx_GPIO_Port here */ gpio_port_type;
static gpio_port_type get_gpio_port_from_idx(size_t idx) {
const gpio_port_type ports[] = {
SEL0_GPIO_Port,
SEL1_GPIO_Port,
SEL2_GPIO_Port,
SEL3_GPIO_Port,
SEL4_GPIO_Port,
SEL5_GPIO_Port,
SEL6_GPIO_Port,
SEL7_GPIO_Port,
SEL8_GPIO_Port,
};
static_assert(IDX_MAX == sizeof(ports)/sizeof(*ports));
assert(idx < sizeof(ports)/sizeof(*ports));
return ports[idx];
}
typedef /* insert the type of SELx_Pin here */ pin_type ;
static pin_type get_sel_pin_from_idx(size_t idx) {
const pin_type pins[] = {
SEL0_Pin,
SEL1_Pin,
SEL2_Pin,
SEL3_Pin,
SEL4_Pin,
SEL5_Pin,
SEL6_Pin,
SEL7_Pin,
SEL8_Pin,
};
static_assert(IDX_MAX == sizeof(pins)/sizeof(*pins));
assert(idx < sizeof(pins)/sizeof(*pins));
return pins[idx];
}
void set_out(int out) {
for (size_t i = 0; i < IDX_MAX; ++i) {
(
(out & (1 << i)) ? GPIO_SetBits : GPIO_ResetBits
)(get_gpio_port_from_idx(i), get_gpio_pin_from_idx(i));
}
}
The first two functions map a static index from the range of 0 to 8 to SELx_GPIO_Port and SELx_Pin variables respectively. After that the set_out function checks each bit in the input variable int out and calls the GPIO_SetBits or GPIO_ResetBits depending if the bit is set or unset. I used ternary operator, if the function would have different prototype, or are macros, you could just:
void set_out(int out) {
for (size_t i = 0; i < IDX_MAX; ++i) {
if (out & (1 << i)) {
GPIO_SetBits(get_gpio_port_from_idx(i), get_gpio_pin_from_idx(i));
} else {
GPIO_ResetBits(get_gpio_port_from_idx(i), get_gpio_pin_from_idx(i));
}
}
}
Related
The code below demonstrate in C language so anyone could easily understand the need. But I use to know many other programming language as well.
Running the code as [1] will give me an error in some programming language & some programming language give warning
[1]:
int get_value(int number) {
if (number == 0) { return 12; }
else if (number == 1) { return 21; }
// return;
}
So, I must code something like [2] to clear the error/warning
[2]:
int get_value(int number) {
int ret = 0;
if (number == 0) { ret = 12; }
else if (number == 1) { ret = 21; }
return ret;
}
QUESTION:
How do I shorthanded the code in [2] as the code in [1] without any error/warning. And the expected code as short as [1]
imagine that the parameter number = 3
then what would you return ?
you can simply write at the end of the function return 0;
so:
int get_value(int number) {
if (number == 0) { return 12; }
else if (number == 1) { return = 21; }
return 0;
}
so you should think of different values of the parameter called number.
In the first code snippet compilers issue a message because the function returns nothing if number is not equal to 0 or 1.
You could write for example
int get_value(int number) {
if (number == 0) { return 12; }
else if (number == 1) { return 21; }
else { return 0; }
}
Or you could write
int get_value(int number) {
int ret[] = { 12, 21 };
if ( 0 <= number && number <= 1 ) { return ret[number]; }
else { return 0; }
}
Or you could use the conditional operator like for example
int get_value(int number) {
return number == 0 ? 12 : number == 1 ? 21 : 0;
}
By universal convention (including in C), 0 is regarded as false and all other values are true.
So it may make sense to code:
int get_value(int number) {
if (number == 0) {
return 12;
}
return 21;
}
As others point out you don't appear to have defined a return value for all possible inputs. It maybe that your function is only ever called with 0 or 1. If that's the case the parameter name number is poorly chosen.
But "defensive programming" says you should deal with all cases.
You either map all inputs into legitimate return values or introduce an error handler or trap.
Here's an error trap version using the assert() macro.
#include <assert.h>
int get_value(int number) {
assert((number==0)||(number==1));
if (number == 0) {
return 12;
}
return 21;
}
If the condition provided to the assert() macro is false, execution ends printing a diagnostic message.
These warnings/errors arise because your function declaration states that it should always return an int:
int get_value(int number) {
In the first version of your code, it would not do that for numbers other than 0 or 1:
int get_value(int number) {
if (number == 0) { return 12; }
else if (number == 1) { return 21; }
}
For example, what would this do if you called it with number set to 2?
The second example always returns an int, thus honouring the "contract" defined by the function declaration:
int get_value(int number) {
if (number == 0) { return 12; }
else if (number == 1) { return 21; }
return 0;
}
In some (non-C) programming languages -- such as Ruby or Javascript -- the former would be allowed due to nil/None/undefined being used as an implicit return value, but this is because function declarations do not specify that they "must" return an int value in those languages:
// Javascript example:
function get_value(number) {
if (number == 0) { return 12; }
else if (number == 1) { return 21; }
}
get_value(2) // Returns `undefined`.
How do I shorthanded the code..??
You can study the problem, and use branchless programming to give you the results that you want.
#include <stdio.h>
int get_value( unsigned int n ) {
return (n<2)*(0x2AC>>(5*n))&0x1F;
}
int main() {
for( int i = 0; i < 10; i++ )
printf( "%i: %2d %2d\n", i, get_value( i ), (i<2)*(0x2AC>>(5*i))&0x1F );
return 0;
}
0: 12 12
1: 21 21
2: 0 0
3: 0 0
4: 0 0
5: 0 0
6: 0 0
7: 0 0
8: 0 0
9: 0 0
I want to judge whether the specific window is minimized. But the coordinate is the same as not minimized. How to determine whether the window is minimized?
I find the question which had been marked solved, but it doesn't work.
Xlib: How to check if a window is minimized or not?
Based on your comment above, try this:
//try to get the atoms, don't create it if it does not exist
Atom wm_state = XInternAtom(dpy, "_NET_WM_STATE", True);
Atom wm_hidden = XInternAtom(dpy, "_NET_WM_HIDDEN", True);
//test if the atoms do exists
if (wm_state == None) { /*does not exist*/ }
if (wm_hidden == None) { /*does not exist*/ }
Then call the XGetWindowProperty function:
long max_length = 1024;
Atom actual_type;
int actual_format;
unsigned long bytes_after, num_states = 0;
Atom* states = NULL;
if (XGetWindowProperty(
dpy, //your display handle
id, //your windows handle
wm_state, //the atom you received earlier
0l, //no offset
max_length,
False, //do not delete
XA_ATOM, //requested type
&actual_type, //atom identifier that defines the actual type
&actual_format, //actual format of the property
&num_states, //actual number of items stored in the states data
&bytes_after, //number of bytes remaining on a partial read
(unsigned char**) &states //data in the specified format
) == Success) {
//iterate over the returned list of atoms
for (unsigned long i = 0; i < num_states; ++i) {
//test if the list contains the 'hidden' state
if (states[i] == wm_hidden) { /* state is set */ }
}
}
Reference:
Application Window Properties - _NET_WM_STATE
XInternAtom
XGetWindowProperty
Example (based on the discussion):
/* window states */
typedef enum {
WINDOW_STATE_NONE = 0,
WINDOW_STATE_MODAL = (1 << 0),
WINDOW_STATE_STICKY = (1 << 1),
WINDOW_STATE_MAXIMIZED_VERT = (1 << 2),
WINDOW_STATE_MAXIMIZED_HORZ = (1 << 3),
WINDOW_STATE_MAXIMIZED = (WINDOW_STATE_MAXIMIZED_VERT | WINDOW_STATE_MAXIMIZED_HORZ),
WINDOW_STATE_SHADED = (1 << 4),
WINDOW_STATE_SKIP_TASKBAR = (1 << 5),
WINDOW_STATE_SKIP_PAGER = (1 << 6),
WINDOW_STATE_HIDDEN = (1 << 7),
WINDOW_STATE_FULLSCREEN = (1 << 8),
WINDOW_STATE_ABOVE = (1 << 9),
WINDOW_STATE_BELOW = (1 << 10),
WINDOW_STATE_DEMANDS_ATTENTION = (1 << 11),
WINDOW_STATE_FOCUSED = (1 << 12),
WINDOW_STATE_SIZE = 13,
} window_state_t;
/* state names */
static char* WINDOW_STATE_NAMES[] = {
"_NET_WM_STATE_MODAL",
"_NET_WM_STATE_STICKY",
"_NET_WM_STATE_MAXIMIZED_VERT",
"_NET_WM_STATE_MAXIMIZED_HORZ",
"_NET_WM_STATE_SHADED",
"_NET_WM_STATE_SKIP_TASKBAR",
"_NET_WM_STATE_SKIP_PAGER",
"_NET_WM_STATE_HIDDEN",
"_NET_WM_STATE_FULLSCREEN",
"_NET_WM_STATE_ABOVE",
"_NET_WM_STATE_BELOW",
"_NET_WM_STATE_DEMANDS_ATTENTION",
"_NET_WM_STATE_FOCUSED"
};
/* some window struct */
typedef struct {
Display *dpy;
Window id;
struct {
Atom NET_WM_STATE;
Atom NET_WM_STATES[WINDOW_STATE_SIZE];
} atoms;
} window_t;
window_t win;
/* in window initialization function */
win->atoms.NET_WM_STATE = XInternAtom(win->dpy, "_NET_WM_STATE", False);
for (i=0; i < WINDOW_STATE_SIZE; ++i) {
win->atoms.NET_WM_STATES[i] = XInternAtom(win->dpy, WINDOW_STATE_NAMES[i], False);
}
/* a function to retrieve the current state of the window */
window_state_t get_window_state(window_t *win)
{
long max_length = 1024;
Atom actual_type;
int actual_format;
unsigned long bytes_after, i, num_states = 0;
Atom* states = NULL;
window_state_t state = WINDOW_STATE_NONE;
if (XGetWindowProperty(win->dpy,
win->id,
win->atoms.NET_WM_STATE,
0l,
max_length,
False,
XA_ATOM,
&actual_type,
&actual_format,
&num_states,
&bytes_after,
(unsigned char**) &states) == Success)
{
//for every state we get from the server
for (i = 0; i < num_states; ++i) {
//for every (known) state
for (int n=0; n < WINDOW_STATE_SIZE; ++n) {
//test the state at index i
if (states[i] == win->atoms.NET_WM_STATES[n]) {
state |= (1 << n);
break;
}
}
}
XFree(states);
}
return state;
}
I've been trying to figure out which parts of this code involve the 2-bit counter, because I have to make it into a 3-bit counter.
For the GSHARE_SIZE table size, I think the correct size for a 3-bit counter would be 17 instead of the 2-bit 18, because there is one more counter and 18 is too large for for the allocated memory space (64k).
Additionally, I believe the counter in the ---//update predictor--- section needs to be changed from:
// update predictor
bool t = uop->br_taken;
if (t && gtable[gidx] < 1)
gtable[gidx] ++;
else if (!t && gtable[gidx] > -2)
gtable[gidx] --;
to
// update predictor
bool t = uop->br_taken;
if (t && gtable[gidx] < 2)
gtable[gidx] ++;
else if (!t && gtable[gidx] > -3)
gtable[gidx] --;
Besides, these two things, I'm unsure of how to change this 2-bit counter into a 3-bit counter. Below is the code for the 2-bit predictor.
#include <stdio.h>
#include <cassert>
#include <string.h>
#include <inttypes.h>
using namespace std;
#include "cbp3_def.h"
#include "cbp3_framework.h"
#define GSHARE_SIZE 18 // 256K 2-bit counters = 64 KB cost
// predictor tables
int8_t *gtable;
// cost: depending on predictor size
uint32_t brh_fetch;
uint32_t brh_retire;
// count number of runs
uint32_t runs;
void PredictorInit() {
runs = 0;
gtable = new int8_t[1 << GSHARE_SIZE];
assert(gtable);
}
void PredictorReset() {
// this function is called before EVERY run
// it is used to reset predictors and change configurations
printf("Predictor:gshare\nconfig: %i counters, %i KB cost\n", 1 << GSHARE_SIZE, (1 << GSHARE_SIZE) * 2 / 8 / 1024);
for (int i = 0; i < (1 << GSHARE_SIZE); i ++)
gtable[i] = 0;
brh_fetch = 0;
brh_retire = 0;
}
void PredictorRunACycle() {
// get info about what uops are processed at each pipeline stage
const cbp3_cycle_activity_t *cycle_info = get_cycle_info();
// make prediction at fetch stage
for (int i = 0; i < cycle_info->num_fetch; i++) {
uint32_t fe_ptr = cycle_info->fetch_q[i];
const cbp3_uop_dynamic_t *uop = &fetch_entry(fe_ptr)->uop;
if (runs == 0 && uop->type & IS_BR_CONDITIONAL) {
// get prediction
uint32_t gidx = (brh_fetch ^ uop->pc) & ((1 << GSHARE_SIZE) - 1);
bool gpred = (gtable[gidx] >= 0);
assert(report_pred(fe_ptr, false, gpred));
}
// update fetch branch history
if (uop->type & IS_BR_CONDITIONAL)
brh_fetch = (brh_fetch << 1) | (uop->br_taken ? 1 : 0);
else if (uop_is_branch(uop->type))
brh_fetch = (brh_fetch << 1) | 1;
}
for (int i = 0; i < cycle_info->num_retire; i++) {
uint32_t rob_ptr = cycle_info->retire_q[i];
const cbp3_uop_dynamic_t *uop = &rob_entry(rob_ptr)->uop;
if (runs == 0 && uop->type & IS_BR_CONDITIONAL) {
uint32_t gidx = (brh_retire ^ uop->pc) & ((1 << GSHARE_SIZE) - 1);
// update predictor
bool t = uop->br_taken;
if (t && gtable[gidx] < 1)
gtable[gidx] ++;
else if (!t && gtable[gidx] > -2)
gtable[gidx] --;
// update retire branch history
if (uop->type & IS_BR_CONDITIONAL)
brh_retire = (brh_retire << 1) | (uop->br_taken ? 1 : 0);
else if (uop_is_branch(uop->type))
brh_retire = (brh_retire << 1) | 1;
}
}
void PredictorRunEnd() {
runs ++;
if (runs < 1) // set rewind_marked to indicate that we want more runs
rewind_marked = true;
}
void PredictorExit() {
delete [] gtable;
}
I'm unsure which parts of this predictor are relevant to the "2-bit counter" component of this predictor.
Below code is for a test sample given in https://www.testdome.com/for-developers/solve-question/9780
The question is: Implement the inspect_bits function that checks if given number contains 2 or more consecutive ones in its binary representation. If it does, the function should return 1. Otherwise, it should return 0.
For example, inspect_bits(13) should return 1 as it contains 2 consecutive ones in its binary representation (1101).
My code is:
#include <stdlib.h>
#include <stdio.h>
int inspect_bits(unsigned int number)
{
unsigned int ref = 1;
int comp;
for (int i = 0; i< sizeof(number) * 8; i++)
{
int a = number& (ref << i);
printf("%d: a is %d\n", i, a);
int b = number& (ref << (i + 1));
printf("%d: b is %d\n", i, b);
if ((a != 0) && (b != 0))
{
return 1;
}
}
return 0;
}
#ifndef RunTests
int main()
{
printf("%d", inspect_bits(13));
}
#endif
The result seems ok, but the system tells:
Various numbers: Wrong answer
Can you help to modify my code?
Regards
To be honest, I think it's an issue with the test site itself. Your code returns the proper results for each test case given to it, and I even modified the code as such:
int inspect_bits(unsigned int number)
{
for (int i = 0; i < sizeof(number) * 8; ++i) {
if (((number & (1 << i)) != 0) && ((number & (1 << (i + 1))) != 0)) {
return 1;
}
}
return 0;
}
The test cases return 1 where there are 2 binary values together and works for 3 and above; however, running this code on the test site and it gives the error that the Various Numbers test fails.
Interestingly, using this code:
int inspect_bits(unsigned int number)
{
while (number >= 3) {
if ((number & 3) == 3) { return 1; }
number >>= 1;
}
return 0;
}
Which does basically the same thing, only using bit-shifting on a single number, and the test passes 100% ..
You could submit an e-mail explaining the error; but beyond that, I'm not sure what else it could be.
Hope that helps.
int flag = 0;
int inspect_bits(unsigned int number)
{
int *arr;
int i = 0;
number = convert(number);
while(number)
{
arr[i] = number % 10;
number /= 10;
i++;
}
for(int j = 0; j < i-1; j++)
{
if(arr[j] == arr[j+1])
{
flag = 1;
return flag;
}
}
return flag;
}
int convert (int num)
{
if(num == 0)
{
return 0;
}
else
{
return (num % 2 + 10 * convert(num / 2));
}
}
This is what I did and it said Various Words: Wrong Answer. It appears to be an issue with the test site. Some other questions on their site evaluates questions incorrectly. The ones that I've come across are all C programs. C++ works fine in my experience.
By my experience in testdome almost any exercise right solution has to do with efficiency of the algorithm
This code worked for me:
#include <stdlib.h>
#include <stdio.h>
int inspect_bits( unsigned int number ) {
do {
if( ( number&3 )==3 ) return 1;
} while( number>>=1 );
return 0;
}
#ifndef RunTests
int main () {
printf( "%d", inspect_bits( 13 ) );
}
#endif
In the code you posted, the for loop checks all the bits from the function's input argument 'number'. That's not enough efficient.
The point is that we don't have to wait until the complete number has been completely right shifted.
They say, we must check if there are 2 or more consecutive ones in its binary representation, in other words, function returns 1 if a minimum of 2 consecutive bits with value 1 are found, and the fewer value with 2 consecutive ones is a decimal 3 ( 3 = 0b00000011 ).
So we are able to check it comparing the number with 3 using an AND gate, and right shift to 'number' until it happens.
Let's take a different number than the example's one:
221 = 0b11011101 we just only need to compare 3 times and shift it 2 times.
0b11011101 (221)
& 0b00000011 ( 3)
------------------
= 0b00000001 ( 1)
0b11011101(221) >> 1 = 0b01101110(110)
0b01101110 (110)
& 0b00000011 ( 3)
------------------
= 0b00000010 ( 2)
0b01101110(110) >> 1 = 0b00110111(55)
0b00110111 (55)
& 0b00000011 ( 3)
------------------
= 0b00000011 ( 3) ----> FOUND! return 1
I want to get the loop bounds by using LLVM API. Here is the part of the code as follows. I don't know whether it is right to get the bounds. So, is there any other situation that I haven't thought about?
typedef std::vector<Loop*> LoopNest;
typedef std::vector<const Value*> LoopNestBounds;
...
void getLoopNestBounds(const LoopNest &Nest, LoopNestBounds &LBounds) {
ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
for (unsigned d = 0, n = Nestsize(); d != n; ++d) {
if (SE.hasLoopInvariantBackedgeTakenCount(Nest[d])) {
const SCEV *C = SE.getBackedgeTakenCount(Nest[d]);
const SCEVConstant *CC = dyn_cast<const SCEVConstant>(C);
LBounds.push_back(CC->getValue());
errs() << CC->getValue()->getValue() << " iterations\n";
}
else {
LBounds.push_back(0);
errs() << "---- 0 iterations for the nest ----" << "\n";
}
}
}
Note: the version of LLVM is 3.0.