warning : Implicit conversion from enumeration type ' UIInterfaceOrientation' to different enumeration type 'UIDeviceOrientation'? - warnings

In this line: [self deviceInterfaceOrientationChanged:interfaceOrientation];
I get this warning
Implicit conversion from enumeration type ' UIInterfaceOrientation' to different enumeration type 'UIDeviceOrientation'?
Can u help me ?please. thank u
Here's the code:
-(void) receivedRotate: (NSNotification*) notification
{
NSLog(#"receivedRotate");
UIDeviceOrientation interfaceOrientation = [[UIDevice currentDevice] orientation];
if(interfaceOrientation != UIDeviceOrientationUnknown) {
[self deviceInterfaceOrientationChanged:interfaceOrientation];
} else {
NSLog(#"Unknown device orientation");
}
}

UIDeviceOrientation and UIInterfaceOrientation are different types, the first is the device orientation and includes other states like Face up or Face Down among others, while the second only covers 2D states, like Portrait and Landscape.
Don't get the device orientation from the device but from the status bar like this:
[[UIApplication sharedApplication] statusBarOrientation]
This method will return a UIInterfaceOrientation value and the problem will go away.

Related

Return value in rust function magically changing

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 hours ago.
Improve this question
I'm currently working on implementing MCTS for a game.
I have a method called
make_move
That looks like this:
(modified to be verbose for the sake of stackoverflow)
pub fn make_move(&mut self, index: usize, player: i8) -> MoveResult {
let mut result = MoveResult::Nothing;
// If the game is finished or the spot they're trying to play on is occupied set the result to be an error
// Otherwise make the move and return the result of that move (if someone won or if nothing happened)
if self.winner != 0 || self.board[index] != 0 {
self.display();
println!("Warning! Tried playing illegal move");
result = MoveResult::Error;
} else {
self.board[index] = player;
self.move_history.push(index);
result = self.check_for_win();
}
result
}
It uses this enumerator to return the result of a move
pub enum MoveResult {
// Completed meaning the move made the game over (either by win or draw)
Completed(i8),
Error,
Nothing
}
Originally, I just had a guard clause that returned an error for the first if statement, and then returned self.check_for_win() otherwise (which is always either Nothing or Completed). I've since modified it heavily in a desperate attempt to fix this bug.
The bug I'm referring to is when I use the method
let move_result = board.make_move(index, player);
move_result is always equal to either Nothing or Completed. It is never equal to Error.
In the terminal, it will even print out that there was an error, which means the if statement was true and the else shouldn't run, but it will still only return either Nothing or Completed.
I tried to check inside the method. If there was an error, the line before I return, I printed the value of result. And it printed it was equal to Error. But when I use the method and assign the return value to a variable, which I have confirmed through println's is of type Error, the variable is either Nothing or Completed!! It magically changes despite being equal to Error at every point in the process.
I have tried rewriting this method so many times in so many ways. It never works. I've been bashing my head into my keyboard all day and it simply will not cooperate. If anyone has any idea, I'd appreciate the help.
I cannot reproduce your error:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=cc3fc00a4cc4c486fd4d76b51f8f616d
#[derive(Debug, PartialEq)]
pub enum MoveResult {
// Completed meaning the move made the game over (either by win or draw)
Completed(i8),
Error,
Nothing
}
struct Game {
winner: i8,
board: Vec<i8>,
move_history: Vec<usize>
}
impl Game {
fn new(board_size: usize) -> Self {
Game{winner: 0, board: vec![0; board_size], move_history: Vec::new()}
}
fn check_for_win(&self) -> MoveResult {
MoveResult::Nothing // dummy because I don't know the win condition
}
fn display(&self) {
// pass
}
fn make_move(&mut self, index: usize, player: i8) -> MoveResult {
let mut result = MoveResult::Nothing;
// If the game is finished or the spot they're trying to play on is occupied set the result to be an error
// Otherwise make the move and return the result of that move (if someone won or if nothing happened)
if self.winner != 0 || self.board[index] != 0 {
self.display();
println!("Warning! Tried playing illegal move");
result = MoveResult::Error;
} else {
self.board[index] = player;
self.move_history.push(index);
result = self.check_for_win();
}
result
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn make_move_returns_error_when_winner_is_not_zero() {
let mut game = Game::new(10);
game.winner = 42;
let res = game.make_move(1, 2);
assert_eq!(res, MoveResult::Error);
}
#[test]
fn make_move_returns_error_when_playing_same_position_twice() {
let mut game = Game::new(10);
let res1 = game.make_move(1, 42);
assert_eq!(res1, MoveResult::Nothing);
let res2 = game.make_move(1, 55);
assert_eq!(res2, MoveResult::Error);
}
}
Of course all sorts of weird stuff might happen in your check_for_win method, but that method shouldn't even get executed if we're in the error-branch.

How to increase JSON perameter COUNT value for pagination in swift

from backend count start form 0. and 0,1,2,3...... . For each count 10 product is showing
I have taken initially count = 0 like below
var currentCount: Int = 0
and added count perameter in JSON like below in service call: but here always shows only 10 products in collectionview... even if there are more products then also not showing.. why?
fileprivate func serviceCall(){
self.currentCount+=0
let param = ["jsonrpc": "2.0",
"params": ["type" : type, "count": currentCount]] as [String : Any]
APIReqeustManager.sharedInstance.serviceCall(param: param, vc: self, url: getUrl(of: .productByFeature), header: header) {(responseData) in
if self.currentCount > 0 {
self.viewmoreDB?.result?.products! += ViewMoreBase(dictionary: responseData.dict as NSDictionary? ?? NSDictionary())?.result?.products ?? [ViewMoreProducts]()
}
else{
self.viewmoreDB = ViewMoreBase(dictionary: responseData.dict as NSDictionary? ?? NSDictionary())
}
self.productsData = self.viewmoreDB?.result?.products
self.collectionView.reloadData()
}
}
and trying to use pagination like below at the end of the collectionview activity indicator is showing but if there are more products then also not loading
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == collectionView{
if (scrollView.contentOffset.y + scrollView.frame.size.height) == scrollView.contentSize.height {
serviceCall()
}
}
}
please do help
It could be any of may issues. One of the possible things is that you do not update currentCount when you get the data and your statement if self.currentCount > 0 always fails and the else part executes which means that data is not added but overwritten and you again have just one page of data.
If this is true you are probably missing currentCount = self.productsData.count or even better, you should simply make your currentCount as a computed property doing
var currentCount: Int { productsData?.count ?? 0 }
Since this is a guess a more appropriate answer is that you need to improve your skills when debugging. One of the widely used feature which is available in most modern IDEs is using breakpoints. In most IDEs you simply click left of the line you wish to put your breakpoint and an icon shows there. When your code executes with debugger it will stop at a breakpoint and you will be able to see all the information that is currently in the stack and you will be able to execute line by line to see what is going on. So in your case you could place a breakpoint at a first line after serviceCall and see which path the code takes you and why.
If using Xcode there is another feature that you can use WHILE stopped on breakpoint. You can use console on your bottom right of your IDE to print out values as chunks of code. So while stopped there you could enter "po self.currentCount" and you could see the count. More interesting would be to see things like "ViewMoreBase(dictionary: responseData.dict as NSDictionary? ?? NSDictionary())?.result?.products" to check if you get any products from the backend.

Equivalent of Platform::IBoxArray in C++/WinRT

I am currently porting an UWP application from C++/CX to C++/WinRT. I encountered a safe_cast<Platform::IBoxArray<byte>^>(data) where data is of type Windows::Foundation::IInspectable ^.
I know that the safe_cast is represented by the as<T> method, and I know there are functions for boxing (winrt::box_value) and unboxing (winrt::unbox_value) in WinRT/C++.
However, I need to know the equivalent of Platform::IBoxArray in order to perform the cast (QueryInterface). According to https://learn.microsoft.com/de-de/cpp/cppcx/platform-iboxarray-interface?view=vs-2017, IBoxArray is the C++/CX equivalent of Windows::Foundation::IReferenceArray, but there is no winrt::Windows::Foundation::IReferenceArray...
Update for nackground: What I am trying to achieve is retrieving the view transform attached by the HoloLens to every Media Foundation sample from its camera. My code is based on https://github.com/Microsoft/HoloLensForCV, and I got really everything working except for this last step. The problem is located around this piece of code:
static const GUID MF_EXTENSION_VIEW_TRANSFORM = {
0x4e251fa4, 0x830f, 0x4770, 0x85, 0x9a, 0x4b, 0x8d, 0x99, 0xaa, 0x80, 0x9b
};
// ...
// In the event handler, which receives const winrt::Windows::Media::Capture::Frames::MediaFrameReader& sender:
auto frame = sender.TryAcquireLatestFrame();
// ...
if (frame.Properties().HasKey(MF_EXTENSION_VIEW_TRANSFORM)) {
auto /* IInspectable */ userData = frame.Properties().Lookup(MF_EXTENSION_VIEW_TRANSFORM);
// Now I would have to do the following:
// auto userBytes = safe_cast<Platform::IBoxArray<Byte> ^>(userData)->Value;
//viewTransform = *reinterpret_cast<float4x4 *>(userBytes.Data);
}
I'm also working on porting some code from HoloLensForCV to C++/WinRT. I came up with the following solution for a very similar case (but not the exact same line of code you ask about):
auto user_data = source.Info().Properties().Lookup(c_MF_MT_USER_DATA); // type documented as 'array of bytes'
auto source_name = user_data.as<Windows::Foundation::IReferenceArray<std::uint8_t>>(); // Trial and error to get the right specialization of IReferenceArray
winrt::com_array<std::uint8_t> arr;
source_name.GetUInt8Array(arr);
winrt::hstring source_name_str{ reinterpret_cast<wchar_t*>(arr.data()) };
Specifically, you can replace the safe_cast with .as<Windows::Foundation::IReferenceArray<std::uint8_t> for a boxed array of bytes. Then, I suspect doing the same cast as me (except to float4x4* instead of wchar_t*) will work for you.
The /ZW flag is not required for my example above.
I can't believe that actually worked, but using information from https://learn.microsoft.com/de-de/windows/uwp/cpp-and-winrt-apis/interop-winrt-cx, I came up with the following solution:
Enable "Consume Windows Runtime Extension" via /ZW and use the following conversion:
auto abi = reinterpret_cast<Platform::Object ^>(winrt::get_abi(userData));
auto userBytes = safe_cast<Platform::IBoxArray<byte> ^>(abi)->Value;
viewTransform = *reinterpret_cast<float4x4 *>(userBytes->Data);
Unfortunately, the solution has the drawback of generating
warning C4447: 'main' signature found without threading model. Consider using 'int main(Platform::Array^ args)'.
But for now, I can live with it ...

i just want to print several images that fetched from a method named repaint and to all these images seperatly on custom cells of table in ios

// custom delegate that takes value in retrieved data array ::
-(void)repaint:(NSMutableArray *)retrievedData
{
if (retrievedData.count > 0)
{
userObj = [retrievedData objectAtIndex:0];
url_Img1=#"http://kiascenehai.pk/assets/uploads/event-images/50x50-thumb/";
url_Img2=userObj.event_dpURL;
url_Img_FULL = [url_Img1 stringByAppendingPathComponent:url_Img2];
[tableData addObjectsFromArray:retrievedData];
[table reloadData];
}
}
This code is printing a single image several times.
[[cell imageView] setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url_Img_FULL]]]];
It's probably this line, where you always take the first object from the array:
userObj = [retrievedData objectAtIndex:0];
// ^
Use Fast Enumeration instead:
-(void)repaint:(NSMutableArray *)retrievedData
{
for (WhateverType *userObj in retrievedData)
{
url_Img1=#"http://kiascenehai.pk/assets/uploads/event-images/50x50-thumb/";
url_Img2=userObj.event_dpURL;
url_Img_FULL = [url_Img1 stringByAppendingPathComponent:url_Img2];
[tableData addObjectsFromArray:retrievedData];
[table reloadData];
}
}
Note: none of the variables in that method should be an instance variable, other than tableData and table. Also that URL manipulation code looks dodgy, but that's a different story...

Speech API (SAPI) floating point division by zero in C++ Builder on Windows 7

I use the following code for Text-To-Speech application controls for blind persons in C++ Builder (most likely similar example can be used in Delphi). Main form has KeyPreview property checked to enable key F11 preview to start speaking active (focused) control. The code as it is works but there are some problems. This example is in C++ Builder code but from what I've found, Delphi suffers from same problem and the solution I found is the same. If you have Delphi solution, feel free to post it, it is similar anyway.
#include <sapi.h>
#include <WTypes.h>
//---------------------------------------------------------------------------
// Speak text string (synchronous function)
//---------------------------------------------------------------------------
bool SpeakText(UnicodeString Text)
{
ISpVoice* pVoice = NULL;
if (FAILED(::CoInitialize(NULL))) return false;
Word Saved8087CW = Default8087CW; // Disable floating point division by zero exception caused by Speak
Set8087CW(0x133f);
HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);
if (SUCCEEDED(hr))
{
//pVoice->SpeakCompleteEvent()
//pVoice->SetSyncSpeakTimeout(1000);
hr = pVoice->Speak(WideString(Text).c_bstr(), SPF_DEFAULT, NULL);
pVoice->Release();
pVoice = NULL;
}
Set8087CW(Saved8087CW);
::CoUninitialize();
return true;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormKeyUp(TObject *Sender, WORD &Key, TShiftState Shift)
{
UnicodeString Speaker;
if (Key == VK_F11)
{
if (Screen->ActiveControl->InheritsFrom(__classid(TButton))) { Speaker += "Button, " + static_cast<TButton*>(Screen->ActiveControl)->Caption + "."; }
else if (Screen->ActiveControl->InheritsFrom(__classid(TEdit))) { Speaker += "Edit box, " + static_cast<TEdit*>(Screen->ActiveControl)->Text + "."; }
}
if (Speaker != "") SpeakText(Speaker);
}
//---------------------------------------------------------------------------
Problems:
pVoice->Speak causes Floating point division by zero if I don't override the exception using the Set8087CW function. This happens only on Windows 7 (possibly Vista and Windows 8 too) but not on Windows XP in the same program (compiled exe). Is there a solution without using Set8087CW? Removing these lines will cause the problem and exception. I have BCB2010.
Function is synchronous and won't shut up or return control to program until it finishes reading text. This is a problem for longer text. It also blocks program events. Is there a way to make it asynchronous or introduce an event to periodically check for F11 key status and if F11 is pressed again it stops reading and uninitializes object? For example poll every 300 ms (or after each word etc.) for key-press F11 and if pressed, stop speaking? Or run it threaded?
Does SAPI has memory leaks as some write on various sites?
Can above code use OleCheck instead of CoCreateInstance and CoUninitialize?
UPDATE for those looking for solution as suggested by Remy Lebeau:
SavedCW = Get8087CW();
Set8087CW(SavedCW | 0x4);
hr = pVoice->Speak(WideString(Text).c_bstr(), SPF_DEFAULT | SPF_ASYNC, NULL);
pVoice->WaitUntilDone(-1); // Waits until text is done... if F11 is pressed simply go out of scope and speech will stop
Set8087CW(SavedCW);
Also found detailed example in CodeRage 4 session: http://cc.embarcadero.com/item/27264
The error does occur in Vista as well. Masking floating point exceptions is the only solution.
To make Speak() run asynchronously, you need to include the SPF_ASYNC flag when calling it. If you need to detect when asynchronous speaking is finished, you can use ISpVoice::WaitUntilDone(), or call ISpVoice::SpeakCompleteEvent() and pass the returned HANDLE to one of the WaitFor...() family of functions, like WaitForSingleObject().
What kind of leaks do other sites talk about?
Not instead of, no. OleCheck() merely checks the value of an HRESULT value and throws an exception if it is an error value. You still have to call COM functions that return the actual HRESULT values in the first place. If anything, OleCheck() would be a replacement for SUCCEEDED() instead.
For what you are attempting, I would suggest the following approach instead:
struct s8087CW
{
Word Saved8087CW;
s8087CW(Word NewCW)
{
Saved8087CW = Default8087CW;
Set8087CW(NewCW);
// alternatively, the VCL documentation says to use SetExceptionMask() instead of Set8087CW() directly...
}
~s8087CW()
{
Set8087CW(Saved8087CW);
}
};
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent *Owner)
: TForm(Owner)
{
::CoInitialize(NULL);
}
//---------------------------------------------------------------------------
__fastcall TForm1::~TForm1()
{
if (pVoice) pVoice->Release();
::CoUninitialize();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormKeyUp(TObject *Sender, WORD &Key, TShiftState Shift)
{
if (Key == VK_F11)
{
TWinControl *Ctrl = Screen->ActiveControl;
if (Ctrl)
{
TButton *btn;
TEdit *edit;
if ((btn = dynamic_cast<TButton*>(Ctrl)) != NULL)
SpeakText("Button, " + btn->Caption);
else if ((edit = dynamic_cast<TEdit*>(Ctrl)) != NULL)
SpeakText("Edit box, " + edit->Text);
}
}
}
//---------------------------------------------------------------------------
ISpVoice* pVoice = NULL;
bool __fastcall TForm1::SpeakText(const String &Text)
{
s8087CW cw(0x133f);
if (!pVoice)
{
if (FAILED(CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice)))
return false;
}
SPVOICESTATUS stat;
pVoice->GetStatus(&stat, NULL);
while (stat.dwRunningState == SPRS_IS_SPEAKING)
{
ULONG skipped;
pVoice->Skip(L"SENTENCE", 1000, &skipped);
pVoice->GetStatus(&stat, NULL);
}
return SUCCEEDED(pVoice->Speak(WideString(Text).c_bstr(), SPF_ASYNC, NULL));
}