Any way to give names to each of a set of successive integers? - objective-c

I have an int called setupStage. This is simply a value I increment at the completion of each stage, so I can say, if (setupStage == 2), and I know that I am at the third stage (it defaults to 0).
Is there a way I can refer to these numbers in a better way? For example:
if (setupStage == stageEnterName)
Instead of having to refer to its actual raw int value.
It may be a misconception, but does what I am trying to achieve have anything to do with defining macros?

Yes!
Try this:
typedef enum {
MyType0,
MyType1,
MyType2,
MyType3
} MyType;
This is the same thing as this:
typedef enum {
MyType0 = 0,
MyType1,
MyType2,
MyType3
} MyType;
The values default to 0 at the first slot and then increment by 1 automatically. Note that the token names (MyTypeX) are arbitrary string values you set.
In this case they go from 0 to 3. Then you can say something like this:
if (setupStage == MyType3)
Which is identical to
if (setupStage == 3)

It sounds to me like you do want a macro like solution, and fortunately one exists.
STAGE_ONE = 0
STAGE_TWO = 1
STAGE_THREE = 2
# ...
if setupStage == STAGE_THREE:
will work.

Related

How do I reverse each value in a column bit wise for a hex number?

I have a dataframe which has a column called hexa which has hex values like this. They are of dtype object.
hexa
0 00802259AA8D6204
1 00802259AA7F4504
2 00802259AA8D5A04
I would like to remove the first and last bits and reverse the values bitwise as follows:
hexa-rev
0 628DAA592280
1 457FAA592280
2 5A8DAA592280
Please help
I'll show you the complete solution up here and then explain its parts below:
def reverse_bits(bits):
trimmed_bits = bits[2:-2]
list_of_bits = [i+j for i, j in zip(trimmed_bits[::2], trimmed_bits[1::2])]
reversed_bits = [list_of_bits[-i] for i in range(1,len(list_of_bits)+1)]
return ''.join(reversed_bits)
df['hexa-rev'] = df['hexa'].apply(lambda x: reverse_bits(x))
There are possibly a couple ways of doing it, but this way should solve your problem. The general strategy will be defining a function and then using the apply() method to apply it to all values in the column. It should look something like this:
df['hexa-rev'] = df['hexa'].apply(lambda x: reverse_bits(x))
Now we need to define the function we're going to apply to it. Breaking it down into its parts, we strip the first and last bit by indexing. Because of how negative indexes work, this will eliminate the first and last bit, regardless of the size. Your result is a list of characters that we will join together after processing.
def reverse_bits(bits):
trimmed_bits = bits[2:-2]
The second line iterates through the list of characters, matches the first and second character of each bit together, and then concatenates them into a single string representing the bit.
def reverse_bits(bits):
trimmed_bits = bits[2:-2]
list_of_bits = [i+j for i, j in zip(trimmed_bits[::2], trimmed_bits[1::2])]
The second to last line returns the list you just made in reverse order. Lastly, the function returns a single string of bits.
def reverse_bits(bits):
trimmed_bits = bits[2:-2]
list_of_bits = [i+j for i, j in zip(trimmed_bits[::2], trimmed_bits[1::2])]
reversed_bits = [list_of_bits[-i] for i in range(1,len(list_of_bits)+1)]
return ''.join(reversed_bits)
I explained it in reverse order, but you want to define this function that you want applied to your column, and then use the apply() function to make it happen.

How to chose options in a while loop

My program --> I Will ask the user to introduce a number and I want to make that if the number is not in a random sequence (I choose 1,2,3) of numbers, the user need to write again a number until the number they enter is in the sequence:
a = (1,2,3)
option = int(input(''))
while option != a:
print('Enter a number between 1 and 3 !!')
option = int(input(''))
So as you can see I use the variable as a tuple but I don't know how to do it.. =(
Assuming the use of a tuple is obligatory, you will need to get input as a string, because it is iterable type. It will alow you easily convert to int, sign by sign, thru list comprehension. Now you have a list of ints, which you simply convert to a tuple. The final option variable looks:
option = tuple([int(sign) for sign in str(input(''))])
But consider keeping your signature in int instead of tuple. Int number is also unequivocal if its about sequence. In python 123 == 132 returns False. That way, you need only to replace:
a = (1,2,3)
by a:
a = 123
And script will works.

What is the most elegant way to pick a random value from a set defined in NS_OPTION in objective-c?

I have an NS_OPTION that I'm defining as such :
typedef NS_OPTIONS(NSInteger, PermittedSize) {
SmallSize = 1 << 0,
MediumSize = 1 << 1,
LargeSize = 1 << 2
};
And later I set the values I need :
PermittedSize size = SmallSize | MediumSize;
I'm using it to randomly generate an various objects of small and medium sizes(duh) for a particular level of a game.
What is the best way to go about selecting which size of an object to generate? Meaning, I'd like to choose randomly for each object I'm generating whether it will be one of the 2 options allowed (small and medium in this case). Normally I would use an arc4random function with the range of numbers I need - but in this case, how can it be done with bits? (and then mapped back to the values of the PermittedSize type?
Use the result from arc4random to determine the amount of bit shifting you want to do. Something like this:
int bitShiftAmount = arc4random_uniform(numberOfPermittedSizes);
PermittedSize size = 1 << bitShiftAmount;
You are still working with integers. SmallSize is 1. MediumSize is 2. And LargeSize is 4.
So pick a random number from 1 to 3. 1 is small, 2 is medium, 3 is both.
Once you have a random number, assign it.
NSInteger val = arc4random_uniform(3) + 1; // give 1-3
PermittedSize size = (PermittedSize)val;

MATLAB: Checking type of table

I want to ask how to check if a variable is table 1x8 or 8x1 of type logical?
I know I can check the class of an array for logical like this:
strcmp(class(a),'logical')
I know I can get the size of table like this:
[h w] = size(a);
if(w==1 & h==8 | w==8 & h==1)
But what if table has more than 2 dimensions? How can I get number of dimensions?
To get the number of dimensions, use ndims
numDimensions = ndims(a);
However, you can instead request size to return a single output, which is an array [sizeX,sizeY,sizeZ,...], and check its length. Even better, you can use isvector to test whether it's a 1-d array.
So you can write
if isvector(a) && length(a) == 8
disp('it''s a 1x8 or 8x1 array')
end
Finally, to test for logical, it's easier to write
islogical(a)

VB.Net Enum ToString returns an unknown number

I built a simple vb.net winforms project that pings IP addresses and logs the results. It works fine on most machines I've tried it on. I log the status result of the ping (System.Net.NetworkInformation.IPStatus) by using the IPStatus.tostring method.
Normally this returns a text result such as "Success" or "TimedOut"
Yesterday, on one machine it returned "65" ...which is not one of the enum values. I have a feeling it might be a combination of values. I ran some test code:
Dim status As System.Net.NetworkInformation.IPStatus
status = Net.NetworkInformation.IPStatus.Success
MsgBox(status.ToString)
Which returns "Success"
And this:
status = Net.NetworkInformation.IPStatus.BadDestination Or Net.NetworkInformation.IPStatus.BadHeader
MsgBox(status.ToString)
Which returns "11050"
I suspect the "65" I saw was the result of some combination of enum values. Is there any way I can change the code in my second example to show the text names of both values? That is... any way I can see ALL values in this variable?
IPStatus is NOT a Flags enum, therefore it is not appropriate to combine its member values in this way. This is its definition via Reflector:
Public Enum IPStatus
' Fields
BadDestination = &H2B0A
BadHeader = &H2B22
BadOption = &H2AFF
BadRoute = &H2B04
DestinationHostUnreachable = &H2AFB
DestinationNetworkUnreachable = &H2AFA
DestinationPortUnreachable = &H2AFD
DestinationProhibited = &H2AFC
DestinationProtocolUnreachable = &H2AFC
DestinationScopeMismatch = &H2B25
DestinationUnreachable = &H2B20
HardwareError = &H2B00
IcmpError = &H2B24
NoResources = &H2AFE
PacketTooBig = &H2B01
ParameterProblem = &H2B07
SourceQuench = &H2B08
Success = 0
TimedOut = &H2B02
TimeExceeded = &H2B21
TtlExpired = &H2B05
TtlReassemblyTimeExceeded = &H2B06
Unknown = -1
UnrecognizedNextHeader = &H2B23
End Enum
How you are getting an IPStatus value of 65 - now that's the real question :)
Try using System.Enum to get the name of the value.
In your example, use:
MsgBox(System.Enum.GetName(GetType(Net.NetworkInformation.IPStatus), status))
It looks like apart from Success (0) and Unknown (-1), the defined enum values range from 11002 to 11045, so 65 is not a combination of any of the defined enum values.
If you are getting 65 back, you will not be able to resolve this to a string.
That enum is not marked with the FlagsAttribute and therefore should not be or'd together because the result could overlap. You are better off creating your own enum to contain the values you are looking for.
You should be able to loop over the enum's range using something like [1], test whether the current enum bit is represented in the value and add it to a string builder.
I find it hard to write up a working sample in VB.NET in this little text box, but I'm sure someone else will oblige.
[1] http://damieng.com/blog/2008/04/10/using-linq-to-foreach-over-an-enum-in-c