mardi 4 août 2015

Using SDL2 for software development

I was surfing the internet this morning and I came upon reading about SDL2 game programing library for c++. Looking at how SDL2 works, I wonder if actual software applications can be developed with game programing libraries like SDL2. Why or why not would be really helpful for me to understand the reasons why you would ever do this. Thanks!!



via Chebli Mohamed

How can a bitwise operator be used to read a file?

I'm trying to read from a .dat file using the following code:

ifstream input_file; 
double x;
while (input_file >> x) {...}

I don't understand how this actually works though - input_file >> x seems like it's using the right bit-shift operator. In what way does that actually read the file?



via Chebli Mohamed

How to call a value template inside a type template [duplicate]

This question already has an answer here:

The idea is to provide a compile time integer element to a specific function of type S, for different types such as S.

G++ does not allow code below. Who can help me to fix this?

template <class T, int s>
void fn1(T &t)
{
    t.fn2<s>();
}

struct S
{
    template <int s> void fn2 ()
    {
    }
};

void test()
{
    S s;

    fn1<S,3>(s);
}

which leads to:

$ g++ -c t.cpp
t.cpp: In function ‘void fn1(T&)’:
t.cpp:4:11: error: expected primary-expression before ‘)’ token
  t.fn2<s>();
           ^
t.cpp: In instantiation of ‘void fn1(T&) [with T = S; int s = 3]’:
t.cpp:18:12:   required from here
t.cpp:4:7: error: invalid operands of types ‘<unresolved overloaded function type>’ and ‘int’ to binary ‘operator<’
  t.fn2<s>();



via Chebli Mohamed

How to return the derived type from a template class

I want to be able to call makeAnother() this without providing a template argument. I've tried using different forms of decltype(this) both in and outside of the function body with no success.

#include <vector>

template <class T>
class A {
    template <class Derived>
    Derived makeAnother() {
        Derived result;
        /* do stuff */
        return result;
    }
    std::vector<T> v;
};

class B : A<int>
{
    /* stuff */
};

int main() {
    B foo;
    B result = foo.makeAnother(); // this doesn't work
}



via Chebli Mohamed

googletest SetUp Method not called

I'm using Google Test to unit test my C++ project. The getting started guide says:

If necessary, write a default constructor or SetUp() function to prepare the objects for each test. A common mistake is to spell SetUp() as Setup() with a small u - don't let that happen to you.

SetUp() is spelled correctly, but I still can't get SetUp to work. Any ideas?

#include "gtest/gtest.h"

class SampleTest : public testing::Test {
 protected:
  virtual void SetUp() { std::cout << "SetUp called." << std::endl; }
};

TEST(SampleTest, OneEqualsOne) {
  int one = 1;
  ASSERT_EQ(1, one);
}

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

g++ -g -Wno-deprecated -I gtest/include SampleTest.cpp gtest/libgtest.a -o SampleTest

Output:

[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from SampleTest
[ RUN      ] SampleTest.OneEqualsOne
[       OK ] SampleTest.OneEqualsOne (1 ms)
[----------] 1 test from SampleTest (1 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (1 ms total)
[  PASSED  ] 1 test.



via Chebli Mohamed

Bridging objective-c library in swift project does not work

In my swift project in need to use snmp++ project ( http://ift.tt/1fyN2Ff ). The snmp++ project is written in c++ and then objective-c wrapper is created for functions.

The project generates libMobileSNMP_PP.a file which i include in my swift project and then create a bridging header and in the bridging header inport "XISMobile_SNMP_PP.h".

Also included .mm and .h files in the swift project as shown in the attached image example1

enter image description here

at compile it gives "could not reference bridging file in the app".

I refered link Can I mix Swift with C++? Like the Objective - C .mm files but still issue exist.

I even tried steps as given in example as shown http://ift.tt/1P42pSz but no success.

Please tell where i'm doing or missing any step.



via Chebli Mohamed

OpenMP Single Producer Multiple Consumer

I am trying to achieve something contrived using OpenMP.

I have a multi-core system with N available processors. I want to have a vector of objects of length k*P to be populated in batches of P by a single thread (by reading a file), i.e. a single thread reads this file and writes in vecObj[0 to P-1] then vecObj[p to 2P-1] etc. To make things simple, this vector is pre-resized (i.e. inserting using = operator, no pushbacks, constant length as far as we are concerned).

After a batch is written into the vector, I want the remaining N-1 threads to work on the available data. Since every object can take different time to be worked upon, it would be good to have dynamic scheduling for the remaining threads. The below snippet works really well when all the threads are working on the data.

#pragma omp parallel for schedule(dynamic, per_thread)
    for(size_t i = 0; i < dataLength(); ++i) {
        threadWorkOnElement(vecObj, i);
    }

Now, according to me, the the main issue I am facing in thinking up of a solution is the question as to how can I have N-1 threads dynamically scheduled over the range of available data, while another thread just keeps on reading and populating the vector with data?

I am guessing that the issue of writing new data and messaging the remaining threads can be achieved using std atomic.

I think that what I am trying to achieve is along the lines of the following pseudo code

std::atomic<size_t> freshDataEnd;
size_t dataWorkStart = 0;
size_t dataWorkEnd;
#pragma omp parallel
{
    #pragma omp task
    {
        //increment freshDataEnd atomically upon reading every P objects
        //return when end of file is reached
        readData(vecObj, freshDataEnd);
    }
    #pragma omp task
    {
        omp_set_num_threads(N-1);           
        while(freshDataEnd <= MAX_VEC_LEN) {
            if (dataWorkStart < freshDataEnd) {
                dataWorkEnd = freshDataEnd;
                #pragma omp parallel for schedule(dynamic, per_thread)
                for(size_t i = dataWorkStart; i < dataWorkEnd; ++i) {
                    threadWorkOnElement(vecObj, i);
                }
                dataWorkStart = dataWorkEnd;
            }
        }
    }
}

Is this the correct approach to achieve what I am trying to do? How can I handle this sort of nested parallelism? Not so important : I would have preferred to stick with openmp directives and not use std atomics, is that possible? How?



via Chebli Mohamed

VLC and MPlayer doesn't play video stream with ortp library

I need example of rtp video streaming with ortp library. My implementation of video streaming doesn't work with VLC and MPlayer.



via Chebli Mohamed

Invalid conversion from void * when using ibpp in c++

One of my class members has void * type:

void * conn;

In Connection method I set connection to Firebird database and set conn member like this:

IBPP::Database conn = IBPP::DatabaseFactory(host, dbname, user, pass);
conn->Connect();
this->conn = static_cast<void *>(conn);

This way of doing things works well for other multiple databases, but breaks when I try to use it with Firebird. So, this is what happens. In another method I use conn member to fetch data from a particular database. When it comes to Firebird, I do it like this:

IBPP::Transaction tr = IBPP::TransactionFactory(static_cast<IBPP::Database>(this->conn));

However, this line of code results in an error message:

error: invalid conversion from 'void *' to 'IBPP::IDatabase *'

I do not know what I'm doing wrong.



via Chebli Mohamed

Qt TableView: How to get rid of the extended grey rectangle from the row headers

How do I get rid of grey area as seen in the image below. It seems like if the table does not fill the entire space, the grey color just extends until the end.

I coded something similar to this image in C++.

enter image description here



via Chebli Mohamed

c++ writing and reading text file is very slow, any alternatives?

I am currently writing code for a game and I'm a little bit stuck on saving and loading the level. For writing I use this piece of code:

    bool WorldGen::GenerateNewWorld(unsigned int seed, int width)
{
    std::cout << "World generating..." << std::endl;
    int heigth = 1; //2D perlin noise instead of 3D
    m_WorldSizeX = width;
    m_WorldSizeY = 1800; //add a int height if implementing different world sizes

    // Create a PerlinNoise object with a random permutation vector generated with seed
    PerlinNoise(seed);

    std::vector<byte> arrMaxHeight;

    // looping through all the x locations and deciding the y value
    for (unsigned int i = 0; i < heigth; ++i) {     // y
        for(unsigned int j = 0; j < width; ++j) {  // x
            double x = (double)j / ((double)width);
            double y = (double)i / ((double)heigth);

            // Typical Perlin noise
            double n = noise(10 * x, 10 * y, 0.8);

            //n is the ground added on top of the base layer (n = highest peak at point j)
            arrMaxHeight.push_back((int)(n * 255));
        }
    }

    std::wofstream fileStream;
    fileStream.open(L"GameSave/world/World.txt");

    if (fileStream.fail())
    {
        return false;
    }

    //fileStream << L"[I could put something up here but that's still in development!]" << std::endl;

    byte blockType = 0;
    std::vector<byte> arrBlockType;

    for (int i = 0; i < m_WorldSizeX; i++)
    {
        for (int j = 0; j < m_WorldSizeY; j++)
        {
            if (j > arrMaxHeight.at(i))
            {
                //block is not air
                blockType = 1;
            }
            else
            {
                //block is air
                blockType = 0;
            }

            arrBlockType.push_back(blockType);
            fileStream << blockType << "/n";
        }
    }

    fileStream.close();

    return true;
}

Now this not too bad, generates the world in around 5 minutes and sends it to world.txt without any issues, my loading(reading world.txt line per line) however takes ages. Around 30+ minutes to fully read all the lines from the text file using std::wifstream and its getline() function. It reads all the lines and adds them to a std::vector and later creates "blocks" from this vector. The creation of the blocks is done in a few seconds but the wifstream is really slow.

Any idea on how to optimise this? I was thinking about only reading blockTypes around the player but that would still require me putting all the blocks into a vector before being able to operate on them.

Kind regards, Jannes

PS: if you need the loading snippet as well I will edit it in later.



via Chebli Mohamed

cutting first string from second string and show remaining characters

i want to code a program in which we take two strings separated by space as an input from user. then first string will be cut from second one, if resultant again have first string then again cut it from that string until there is no first string in second string as a result. output will b the remaining characters in separated line. and at the end a number that shows the quantity of those characters.

#include<iostream>
using namespace std;


int main(){
    string ch1,ch2,ch3;
    cout<<" Enter  two strings values...separated by space..."<<endl;
    cin>>ch1>>ch2;
    //cout<<aa<<" 2nd  "<<bb<<endl;
    // ch1[]={"ab"},ch2[]={"caabbefcdeab"},ch3[50];
    int a=0 ,b=0 ,c;
    string s,t,r;
   int check = true;

    for(int i=0 ; ch2[i]!='\0' ; i++)
    {
         int w=i;
            check=1;
            b=0;
            if(ch1[0]==ch2[i])
            {
                for(int p=0 ; ch1[p]!='\0' && check==1 ; p++)
                   {
                 if(ch1[p]==ch2[w])
                      {
                      check=1;
                       w=w+1;
                      }


                    }

                   if(check==1)
                   {

                                  for(int e=i;e<w;e++)
                                  {
                                   ch2[e]='\0';       
                                   ch2[e]='~';

                                  }
                       i=-1;
                         for(int l=0;ch2[l]!='\0';l++)
                            {
                                  ch3[l]='\0';

                                  if (ch2[l]!='~')
                                  { 
                                // cout<<" ch2 "<<ch2[l]<<endl;
                                   ch3[b]=ch2[l];

                                  // cout<<" ch3 "<<b<<" contains.."<<ch3[b]<<endl;
                                   b=b+1;
                                   }



                            }
                             for(int l=0;ch2[l]!='\0';l++)
                            {
                                  ch2[l]='\0';
                                  ch2[l]=ch3[l];




                            }  

                   }

            }      

    }
    for(int u=0;ch2[u]!='\0';u++)
    {
   cout<<ch2[u]<<endl;
     a=a+1;
   //  cout<<" ch3 "<<u<<" contains "<<ch3[u]<<endl;
    }
   cout<<a<<endl;

    system("pause");
    return 0 ;
    }

sample input ::: cde ccdedefcde

sample output ::: f 1

but my output is :::

d e f 3



via Chebli Mohamed

Set cipher suites used by WinHTTP

I would like to use WinHTTP to verify the correctness of some cipher suites which are a modified version of OpenSSL ciphers.

However, I am not able to set what cipher WinHTTP uses when contacting a TLS/SSL server. I tried a couple of things, but none worked.

Here is what I tried:

  1. Using the CryptoAPI to remove cipher suites: I basically removed all cipher suites and added the one I wanted to test using the API functions: BCryptAddContextFunction() and BCryptRemoveContextFunction(). Here is a link.
  2. Followed instructions here to in the section "To configure the SSL Cipher Suite Order group policy setting".

But none of these worked. Is there any clue how to do this?

btw, I am using Windows 7 Enterprise. And I am verifying what ciphers are being used using Wireshark.

Thank you in advance.



via Chebli Mohamed

STD Set Unique Pointer

struct departure_compare {
    bool operator() (const Leg* lhs, const Leg* rhs) const
    {
        return lhs->CurrentDepartureTime() < rhs->CurrentDepartureTime();
    }
};

class Station
{
    uint station_number_;
    std::set<Leg *, departure_compare> departure_legs_in_order_; // legs that depart from this station in order of departure time
public:
    Station(uint station_number) : station_number_(station_number) {};
    void addDepartureLeg(Leg *leg) { departure_legs_in_order_.insert(leg); };
    const std::set<Leg *, departure_compare>& DepartureLegs() const { return departure_legs_in_order_; };
    uint StationNumber() { return station_number_; };
};

I call this in a loop

Leg *new_leg = new Leg();
start_station->addDepartureLeg(new_leg); // start_station of type station

Now i recognized that some times, it doesn't insert the new_leg into this structure. Now i looked at the documentation which says that if it is already in the set structure that it doesn't insert new_leg. But how is this possible, if i always create a new Pointer (Shouldn't the address be unique)?



via Chebli Mohamed

What is the syntax for parameter pack expansion with alignas?

I'm trying to expand a parameter pack in an alignment specifier. I can't get the syntax right. Here's a simple example:

#include <cstdint>
#include <tuple>

template <typename... Ts>
struct C
{
    using Tuple_Type = std::tuple <Ts...>;

    void f()
    {
        uint8_t i1;
        uint8_t i2 alignas (2);
        uint8_t i3 alignas (typename std::tuple_element<0, Tuple_Type>::type);
        uint8_t i4 alignas (Ts...);
    }
};

//template class C <>;  // not compatible with i3 declaration above
template class C <uint64_t>;

This fails to compile with gcc 4.8.3:

foo.cpp: In member function 'void C<Ts>::f()':
foo.cpp:14:31: error: expected ')' before '...' token
         uint8_t i4 alignas (Ts...);
                               ^
foo.cpp:14:31: error: expected ')' before '...' token
foo.cpp:14:31: error: expected initializer before '...' token

The C++ standard ([dcl.align]) says "An alignment-specifier with an ellipsis is a pack expansion", so it seems like it should be possible to do what I want.

I've been unable to find an example of this kind of parameter pack expansion, and my search for a possible bug in gcc didn't find anything.



via Chebli Mohamed

Using GL_TEXTURE_2D_ARRAY as a draw target

I've created an array of 2D textures and initialized it with glTexImage3D. Then I attached separate textures to color attachments with glFramebufferTextureLayer, Framebuffer creation doesn't throw an error and everything seems fine until the draw call happens.

When shader tries to access color attachment the following message appears:

OpenGL Debug Output message : Source : API; Type : ERROR; Severity : HIGH;
GL_INVALID_OPERATION error generated. <location> is invalid.

Shaders are accessing layers of an array with location qualifier:

layout (location = 0) out vec3 WorldPosOut; 
layout (location = 1) out vec3 DiffuseOut; 
layout (location = 2) out vec3 NormalOut; 
layout (location = 3) out vec3 TexCoordOut; 

Documentation says that glFramebufferTextureLayer works just like glFramebufferTexture2D, except the layer parameter, so can I use location qualifiers with texture array, or some other way exsists?



via Chebli Mohamed

Iterating a vector from end to somewhere (not begin)

I'm trying to iterate over a std::vector using rbegin() and an iterator coming from a std::find_if(). Of course iterator and reverse_iterator are not compatible. How can I do it ?

auto my_it = std::find_if(vec.begin(), vec.end(), 
    // irrelevant lambda
});

for (auto rit = vec.rbegin(); rit != my_it; ++rit)   // doesn't compile, iterators not compatible
{
    // do something
}

There are plenty of question on how to iterate from rbegin() to rend(), but I can't find anything for when I want to stop before rend().



via Chebli Mohamed

Strange behavior of bit-shift [duplicate]

Can't understand behavior of this bit shift:

int container = 1;

cout<<(container>>32)<<endl;

If it's logical shift the output should be 0, but it's 1 instead, as if it was cyclic shift. When looking at disassembly I see that command used is SAR. Please explain this behavior to me.



via Chebli Mohamed

Is there a data structure that works like a map but also allows the sequence of values to be used independently of the keys?

Often I have a map for which the keys are only used for importing, exporting and setup. During the performance critical stage, the values are of importance, not the keys.

I would like to use a data structure that acts like a map but gives me the option to just use a simple vector of mapped values when the keys are irrelevant.

The implementation seems reasonably simple. Just use a pair of equally sized vectors in which to store the key and value respectively, sorted with respect to the key vector. Insertions and deletions will be less efficient than in boost::flat_map, but that is a compromise I'm willing to make in order to get instant access to the vector of key unencumbered values.

Is this a terrible idea? If not, is there an existing implementation I can use?



via Chebli Mohamed

Taking camera photos in Cocos2d-x?

I saw Fennex attempt to access the camera api of Android within Cocos2dx. But on the project listed, I am not sure how I am going to access the camera and the photogallery. Is there a way to do this in Cocos2dx just as you do with Cocos2d?

Thank you!



via Chebli Mohamed

Is function defined in class always inline?

As per some of the books, function defined(along with definition in header) in class are always inline. Is that true?

How we can create such scenario using test app?



via Chebli Mohamed

Delegated constructors

I have two questions. Consider this code:

#include <iostream>

struct A {
    A(int n, char c, bool b) 
        /* : some complex initialization list that you don't want to repeat. */
        {initialize();}
    A(int n) : A(n, default_char, default_bool) {}
    A(char c) : A(default_int, c, default_bool) {}  // Do not want initialize() called!
    A(bool b) : A(default_int, default_char, b) {}
    A(int n, char c) : A(n, c, default_bool) {}
    A(int n, bool b) : A(n, default_char, b) {}  // Do not want initialize() called!
    A(char c, bool b) : A(default_int, c, b) {}
private:
    static const int default_int = 3;
    static const char default_char = 't';
    static const bool default_bool = true;
    void initialize() {std::cout << "A ctor.\n";}
};

int main() {
    A a(5,'a',false);
    A b(5);
    A c('a');
    A (5,'a');
    A (5,false);
    A ('a',false);
}

First of all, assuming I want initialize(); to be called for all the constructors of A, is there a way to avoid explicitly repeating the use of default_int, default_char, default_bool, and have them called automatically somehow? Something like

template <typename... Args> A(Args...args) : A(???) {}

Second of all, assume I do NOT want initialize(); to be called for some of the constructors (e.g. stated in the code). How to avoid that without repeating the "complex initialization list" of A(int,char,bool) 's constructor (so as to avoid future maintenance issues)?



via Chebli Mohamed

Creating compiler independent shared objects (C++ with C interface)

On Windows DLLs with C interfaces can be used to call C++ code compiled with one compiler (e.g., GCC) from an executable compiled with another one (e.g., MSVC). However, trying to do the same on Linux using SOs has proven to be less easy.

For example, I have the following code:

#include <vector>
#include <string>

extern "C" void __attribute__ ((visibility ("default"))) foo()
{
    [&] () noexcept { std::vector<std::string> bar; bar.emplace_back("foo"); }();
}

And create a shared object as follows:

g++ -std=c++14 -shared -fvisibility=hidden -fPIC -o libso_test.so so_test.cpp

Where g++ is G++ 5.2.0.

And another file for the main executable:

extern "C" void foo();

int main(int, char**)
{
    foo();
    return 0;
}

When trying to compile it with the following command:

g++-4.8 -L. -o so_test_main so_test_main.cpp -lso_test

Where g++-4.8 is G++ 4.8.1 I get a number of errors (using g++ instead of g++-4.8 works fine but defeats the purpose):

./libso_test.so: undefined reference to `std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&)@GLIBCXX_3.4.21'
./libso_test.so: undefined reference to `std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&&)@GLIBCXX_3.4.21'
./libso_test.so: undefined reference to `std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()@GLIBCXX_3.4.21'
collect2: error: ld returned 1 exit status

According to the output of nm -g -D --defined-only libso_test.so, aside from the expected symbols _init _fini and foo (marked T) a large number of other symbols are exported marked W.

How can I hide these symbols properly?



via Chebli Mohamed

Using right and left justification on the same line and replacing that line in the console

This is my first question on here, so I hope I'm being clear enough. I'm finishing up a little programming project for a class at the moment. I'm done with all of the actual requirements for the project, but I'd really like to make it look nicely formatted now.

How can I send two separate statements of output, from say, two different classes, to the same line on the console with one being left justified and one being right justified. At the moment when I attempt to do this it smushes the two together with both being on the left side. I also need to delete and update the same line of code during this process as well if it is to end up looking how I want it.

Here is as far as I got fiddling around with some test code:

for (int x = 0; x < 10; ++x)
{
    cout << '\r' << left << "stuff on the left" << right << "stuff on the right" << flush;
    this_thread::sleep_for(chrono::seconds(1));
}

Any help or suggestions would be greatly appreciated!



via Chebli Mohamed

Save generated code in a special folder in "rtwbuild"

I am using rtwbuild to generated C++ code from a Simulation diagrams and would like to save generated code to an arbitrary directory. Is there any way to do so?



via Chebli Mohamed

Adding Event Handler for Windows Application Dialog box

I would like to an add event handler to my simple GUI application made with a windows application in Visual Studio 2013. I have seen that you can use the Resource View to create windows, buttons, etc. However, whenever I right-click and see the option to "Add Event Handler..." it is always grayed out. I saw in this post Visual Studio 2013 and C# - Unable to add event handler to try creating a new project and/or restart VS, both of which I tried. Am I making some newbie mistake?? Why can't I add an event handler? Any suggestions would be great. Thanks.



via Chebli Mohamed

Changing type for each variadic template argument [on hold]

I have some class:

template<typename... Args>
class X
{
    using F = void(*)(Args...);
};

Now I want variadic parameters in F definition become converted with a specific condition:

template<typename T>
using custom_t = typename std::conditional<std::is_fundamental<Args>::value, T, T&&>::type;

using F = void(*)(custom_t<Args>...);

So, for example, for class X<int, MyCustomT> definition X::F should become void(*)(int, MyCustomT&&)



via Chebli Mohamed

Concatenating string to char*

I am a C# developer and I find strange that when I run the following code in C++:

std::string original = "Hello";

std::string st = original + "World";
const char *c = st.c_str();

const char *c2 = (original + "World").c_str();

std::cout << "c  = '" << c << "'" << std::endl;
std::cout << "c2 = '" << c2 << "'" << std::endl;

I get the following output:

c  = 'HelloWorld'
c2 = ''

In C# a similar construct will result in c and c2 having the same value ("Hello World"). My guess would be that the scope of the result of (original + "World") ends on the right ), so c_str() is called on an invalid input. Is that correct? Is there a better way of achieving this other than creating variables to hold temporary results?

Thanks!



via Chebli Mohamed

CUDA detecting busy waiting / conflicts via tool

Is there any possibility (some tool) to check if my code does busy waiting (has some conflicts) in CUDA? I've checked nvprof but haven't seen such option (just general information about kernel's execution time, not from kernel itself).

I have some code that works about 2,5sec sequential and about 4,5sec asynchronus and I don't know which part of code can be improved.



via Chebli Mohamed

how to familiarise oneself with C++ libraries [on hold]

from: http://ift.tt/OCf0lV, c++ has a lot of libraries for accomplishing many different tasks-this i appreciate,however i'm not sure how to go about being familiar with all these libraries.Should I look for books on most of the libraries and go through them chapter after chapter or should i just get a tutorial on each and get an overview of them? what is the best way for me to familiarise myself with all these libraries?



via Chebli Mohamed

error message : no match for call to ‘(cv::Rect) (cv::Mat&, cv::Point_

I have looked quite a bit everywhere and cannot find an answer to my problem. I tried to replicate a text detection software form this thread (Extracting text OpenCV) but at the end of the code there is a message error saying there is no match for the rectangle even though i have drawn one just above and we enter the loop. I have tested all the values i could think of and everything seems correct.

here is the complete code ;

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <opencv2/imgproc/imgproc.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>


using namespace cv;
using namespace std;





int main( int argc, char** argv )
{

namedWindow("source_window2",WINDOW_AUTOSIZE);
namedWindow("source_window3",WINDOW_AUTOSIZE);
Mat input = imread(argv[1], CV_LOAD_IMAGE_COLOR);
Mat in_gray = imread(argv[1],CV_LOAD_IMAGE_GRAYSCALE);
Mat gradient;

Mat Kernelellipse = getStructuringElement(MORPH_ELLIPSE, Size(3,3));
morphologyEx(in_gray, gradient, MORPH_GRADIENT, Kernelellipse);
Mat thresh;
//on convertit en binaire
threshold(gradient, thresh, 0.0, 255.0, THRESH_BINARY | THRESH_OTSU);
rectangle(input,Point(0,0),Point(50,50),Scalar(255,255,255),2);
Mat Kernelrectangle = getStructuringElement(MORPH_RECT, Size(9,1));
Mat fermee;
morphologyEx(thresh, fermee, MORPH_CLOSE, Kernelrectangle);
imshow("source_window3", fermee);

Mat noire = Mat::zeros(thresh.size(), CV_8UC1);
//on cheche les contours
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours(fermee, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
for (int i = 0; i < contours.size(); ++i)
{
    Rect rectangle = boundingRect(contours[i]);
    Mat noirerectangle(noire, rectangle);
    noirerectangle = Scalar(0, 0, 0);
    //on les dessine
    drawContours(noire, contours, i, Scalar(255, 255, 255), CV_FILLED);
    double proportion_de_blanc = (double)countNonZero(noirerectangle)/(rectangle.width*rectangle.height);

    if (proportion_de_blanc > 0.45 && (rectangle.height > 8 && rectangle.width > 8))
    {
        rectangle(input,rectangle.tl(),rectangle.br(),Scalar(0,255,0),2);
    }


}
imshow("source_window2",input);





waitKey(0);
return(0);

}

My issue is within the last loop :

    if (proportion_de_blanc > 0.45 && (rectangle.height > 8 && rectangle.width > 8))
    {
        rectangle(input,rectangle.tl(),rectangle.br(),Scalar(0,255,0),2);
    }



via Chebli Mohamed

Using temporary objects to do some tasks like log writing a good idea?

So I was searching for a good way to make a log manager to use in my programs, and I found an article, with a class similar to this(I simplified it to a few lines of code just to show it here) :

class Log
{
public:
   Log();
   virtual ~Log();
   std::ostringstream& Get();
protected:
   std::ostringstream os;
};
std::ostringstream& Log::Get()
{
      return os;
}
Log::~Log()
{
   //  Write the data from ostringstream;
}

The log record is written in the destructor, so to write a log record, you do this:

Log().Get() << "Log record";

It's a temporary object, so the log record would be written when this object is destroyed. Is it ok to do it like this ? Is this a better way than using a singleton ? Article with the class can be found here



via Chebli Mohamed

Create Pango Layout Before Cairo Surface

In my application, I am using Pango and Cairo to create text textures. These textures have their width fixed, but should scale their height to fit text contents. The parent objects involved in this situation will then scale their heights to match the text.

The problem is, the way I have been initializing Pango and Cairo does not allow for this. Currently, the system is set up by:

cairo_surface_t* cairoSurface = cairo_image_surface_create( CAIRO_FORMAT_ARGB32, sizeX, sizeY );
cairo_t* cairoContext = cairo_create( cairoSurface );
PangoLayout* pangoLayout = pango_cairo_create_layout( cairoContext );

Which fixes the height, at least of the surface - something I do not want to do, at least not all the time.

My understanding is that if the layout height is not specified, it will automatically scale the height, which can then be found via pango_layout_get_size(). I would like to create the layout first and then use the output of this function to create the surface.

However, pango_cairo_create_layout() requires the surface to already be created, and I have been unable to find a way to render a layout from pango_layout_new() via Cairo. The API docs one of the render functions, pango_cairo_update_layout(), specify that pango_cairo_create_layout() had to be used to create the layout; however, the more important function, pango_cairo_show_layout(), notes no such requirement, and I am not sure if that means that any Pango layout is allowed or not. While I could test if it works, I'm afraid that trial and error could lead me to undefined behavior.

I feel like I'm stuck in a chicken and egg situation, and the documentation for Pango is mostly an API reference with little explanation of how the library is intended to be used. Is there a way to do this properly?



via Chebli Mohamed

Using GCC Undefined Behavior Sanitizer

Today I have read an article about GCC Undefined Behavior Sanitizer (ubsan). However, when I follow steps there (add -fsanitize=undefined to my code), the compiler (GCC 4.9.2 on Ubuntu 15.04) says that some references are not defined:

||=== Build: Debug in Entangle (compiler: GNU GCC Compiler) ===|
obj/Debug/EntangleApp.o||In function `EntangleApp::OnInit()':|
/home/ilya/Projects/Entangle/EntangleApp.cpp|31|undefined reference to `__ubsan_handle_type_mismatch'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|31|undefined reference to `__ubsan_handle_load_invalid_value'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|32|undefined reference to `__ubsan_handle_type_mismatch'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|34|undefined reference to `__ubsan_handle_type_mismatch'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|34|undefined reference to `__ubsan_handle_load_invalid_value'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|34|undefined reference to `__ubsan_handle_type_mismatch'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|34|undefined reference to `__ubsan_handle_load_invalid_value'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|35|undefined reference to `__ubsan_handle_type_mismatch'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|37|undefined reference to `__ubsan_handle_type_mismatch'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|37|undefined reference to `__ubsan_handle_load_invalid_value'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|43|undefined reference to `__ubsan_handle_type_mismatch'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|43|undefined reference to `__ubsan_handle_load_invalid_value'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|52|undefined reference to `__ubsan_handle_type_mismatch'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|52|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o||In function `EntangleApp::OnCmdLineParsed(wxCmdLineParser&)':|
/home/ilya/Projects/Entangle/EntangleApp.cpp|75|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o||In function `EntangleApp::OnRun()':|
/home/ilya/Projects/Entangle/EntangleApp.cpp|128|undefined reference to `__ubsan_handle_type_mismatch'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|128|undefined reference to `__ubsan_handle_load_invalid_value'|
obj/Debug/EntangleApp.o||In function `wxPrivate::UntypedBufferData::~UntypedBufferData()':|
/usr/include/wx-3.0/wx/buffer.h|43|undefined reference to `__ubsan_handle_type_mismatch'|
/usr/include/wx-3.0/wx/buffer.h|43|undefined reference to `__ubsan_handle_load_invalid_value'|
/usr/include/wx-3.0/wx/buffer.h|44|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o||In function `std::exception::exception()':|
/usr/include/c++/4.9/exception|63|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o||In function `wxCriticalSectionLocker::wxCriticalSectionLocker(wxCriticalSection&)':|
/usr/include/wx-3.0/wx/thread.h|305|undefined reference to `__ubsan_handle_type_mismatch'|
/usr/include/wx-3.0/wx/thread.h|307|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o||In function `wxCriticalSectionLocker::~wxCriticalSectionLocker()':|
/usr/include/wx-3.0/wx/thread.h|312|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o:/usr/include/wx-3.0/wx/thread.h|767|more undefined references to `__ubsan_handle_type_mismatch' follow|
obj/Debug/EntangleApp.o||In function `wxThreadHelperThread::Entry()':|
/usr/include/wx-3.0/wx/thread.h|775|undefined reference to `__ubsan_handle_load_invalid_value'|
/usr/include/wx-3.0/wx/thread.h|776|undefined reference to `__ubsan_handle_type_mismatch'|
/usr/include/wx-3.0/wx/thread.h|776|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o||In function `std::type_info::name() const':|
/usr/include/c++/4.9/typeinfo|100|undefined reference to `__ubsan_handle_type_mismatch'|
/usr/include/c++/4.9/typeinfo|100|undefined reference to `__ubsan_handle_type_mismatch'|
/usr/include/c++/4.9/typeinfo|100|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o:/usr/include/c++/4.9/typeinfo|100|more undefined references to `__ubsan_handle_type_mismatch' follow|
obj/Debug/EntangleApp.o||In function `wxObjectEventFunctor::operator()(wxEvtHandler*, wxEvent&)':|
/usr/include/wx-3.0/wx/event.h|3757|undefined reference to `__ubsan_handle_add_overflow'|
/usr/include/wx-3.0/wx/event.h|3757|undefined reference to `__ubsan_handle_type_mismatch'|
/usr/include/wx-3.0/wx/event.h|3757|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o||In function `wxLocale::wxLocale()':|
/usr/include/wx-3.0/wx/intl.h|154|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o||In function `wxAppConsoleBase::CallOnInit()':|
/usr/include/wx-3.0/wx/app.h|93|undefined reference to `__ubsan_handle_type_mismatch'|
/usr/include/wx-3.0/wx/app.h|93|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o:/usr/include/wx-3.0/wx/app.h|592|more undefined references to `__ubsan_handle_type_mismatch' follow|
obj/Debug/EntangleApp.o||In function `wxAppBase::IsActive() const':|
/usr/include/wx-3.0/wx/app.h|592|undefined reference to `__ubsan_handle_load_invalid_value'|
obj/Debug/EntangleApp.o||In function `wxAppBase::SetTopWindow(wxWindow*)':|
/usr/include/wx-3.0/wx/app.h|595|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o||In function `EntangleApp::EntangleApp()':|
/home/ilya/Projects/Entangle/EntangleApp.h|19|undefined reference to `__ubsan_handle_type_mismatch'|
/home/ilya/Projects/Entangle/EntangleApp.h|19|undefined reference to `__ubsan_handle_type_mismatch'|
/home/ilya/Projects/Entangle/EntangleApp.h|19|undefined reference to `__ubsan_handle_type_mismatch'|
/home/ilya/Projects/Entangle/EntangleApp.h|19|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o:/home/ilya/Projects/Entangle/EntangleFrame.h|32|more undefined references to `__ubsan_handle_type_mismatch' follow|
obj/Debug/EntangleApp.o||In function `std::_Vector_base<unsigned long long, std::allocator<unsigned long long> >::~_Vector_base()':|
/usr/include/c++/4.9/bits/stl_vector.h|161|undefined reference to `__ubsan_handle_sub_overflow'|
/usr/include/c++/4.9/bits/stl_vector.h|161|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o||In function `std::_Vector_base<unsigned long long, std::allocator<unsigned long long> >::_Vector_impl::_Vector_impl()':|
/usr/include/c++/4.9/bits/stl_vector.h|87|undefined reference to `__ubsan_handle_type_mismatch'|
/usr/include/c++/4.9/bits/stl_vector.h|87|undefined reference to `__ubsan_handle_type_mismatch'|
||More errors follow but not being shown.|
||Edit the max errors limit in compiler options...|
||=== Build failed: 50 error(s), 0 warning(s) (0 minute(s), 23 second(s)) ===|

How can I fix this?



via Chebli Mohamed

displaying 16bit unsigned integers in opengl

I would like a simple way of achieving this, but seem to be bjorking the parameters to glTexImage2D. I have an std::vector<uint16_t> depth_buffer that, on a frame-by-frame basis has depth measurements coming from a kinect. There are exactly 640 x 480 of them, one depth measurement per pixel. If the world went my way, the call should be

glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE16, 640, 480, 0, GL_LUMINANCE16, GL_UNSIGNED_SHORT, depth_buffer.data());

Where internalFormat (third parameter) is GL_LUMINANCE16 because they are 16 bit unsigned integers, and format is the same because that is exactly how the data is coming in. The type parameter should be GL_UNSIGNED_SHORT...because these are shorts and not bytes.

Surprisingly, if I change it to be

glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE16, 640, 480, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, depth_buffer.data());

where internalFormat is still GL_LUMINANCE16, format is just GL_LUMINANCE without the 16, and type is GL_UNSIGNED_BYTE, then I get something. Things are clearly being skipped, but just changing to GL_UNSIGNED_SHORT doesn't cut it.

Depending on which documentation you read, format (the second GL_LUMINANCE) may or may not allow the 16 after it (anybody know why? experimentation seems to confirm this). But my chief concern here is why GL_UNSIGNED_**SHORT** seems to be invalid (either all black or all white) depending on the internalFormat -- format combination.

I've tried an obscene amount of combinations here, and am looking for the right approach. Anybody have some advice for achieving this? I'm not opposed to using fbo's, but would really like to avoid it if possible...since it definitely should be doable.



via Chebli Mohamed

How to build BOOST 64bit under Windows with libiconv?

I built libiconv as a 64bit DLL for Windows.

I have,

I:\libiconv\src

  • iconv.c
  • libiconv.rc
  • localcharset.c
  • localcharset.h
  • relocatable.c
  • relocatable.h

and

I:\include

  • config.h
  • iconv.h
  • other files

and

I:\libiconv\x64\Release

  • libiconv.lib
  • libiconv.dll
  • Other files

I tried running:

b2 address-model=64 --with-locale -sICONV_PATH=I:\libiconv\

Performing configuration checks

- 32-bit                   : yes (cached)
- arm                      : no  (cached)
- mips1                    : no  (cached)
- power                    : no  (cached)
- sparc                    : no  (cached)
- x86                      : yes (cached)

Building the Boost C++ Libraries.

- iconv (libc)             : no  (cached)
- iconv (separate)         : no  (cached)
- icu                      : no  (cached)
- icu (lib64)              : no  (cached)

Yet, every time iconv is listed as no, so what other magic do I need in this build process?



via Chebli Mohamed

How To Start another app while running a program in Turbo C++

I was making a program that would help me keep track of all the other programs I was making.In the program I would hit the key corresponding to a particular app and the the app should open up.

But I am not able to find a way to do that.{ system(D:\\APPS\\calc.exe) is not working}. I Need Help for this :) Both are Dos Apps and are running on DosBox Emulator. (Drive D: is Mounted-No problem about that)



via Chebli Mohamed

Visual C++ 2015 redistribution DLLs?

Up to Visual Studio 2013 all you needed was msvcr[version].dll and msvcp[version].dll. Now they changed the DLLs with 2015. What do I need to include in order to avoid a redist installer?



via Chebli Mohamed

Invalid read of size 8, but no memory leaks

I am doing C++ Kafka Client http://ift.tt/1SI5yNs.

In my KafkaProducer class, there are several pointers.

RdKafka::Conf* m_conf;
RdKafka::Conf* m_tconf;
RdKafka::Producer* m_producer;
RdKafka::Topic* m_topic;

m_conf = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL);
m_producer = RdKafka::Producer::create(m_conf, m_errstr);
m_tconf = RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC);
m_topic = RdKafka::Topic::create(m_producer, m_topic_str, m_tconf, m_errstr);

In the destructor, I did the following:

if(m_producer)
    delete m_producer;

if(m_topic)
    delete m_topic;

if(m_tconf)
    delete m_tconf;

if(m_conf)
    delete m_conf;

I used valgrind to check my program, there is no leaks. But there are some problems of "Invalid read". Some memory are freed twice. But I have do idea which memory. The following are part of the valgrind output.

==4627== 2 errors in context 10 of 12:
==4627== Invalid read of size 8
==4627==    at 0x52887A7: RdKafka::log_cb_trampoline(rd_kafka_s const*, int, char const*, char const*) (in /usr/lib/x86_64-linux-gnu/librdkafka++.so.1)
==4627==    by 0x5493C8F: ??? (in /usr/lib/x86_64-linux-gnu/librdkafka.so.1)
==4627==    by 0x549A531: ??? (in /usr/lib/x86_64-linux-gnu/librdkafka.so.1)
==4627==    by 0x54A0219: ??? (in /usr/lib/x86_64-linux-gnu/librdkafka.so.1)
==4627==    by 0x54A1A13: ??? (in /usr/lib/x86_64-linux-gnu/librdkafka.so.1)
==4627==    by 0x506C181: start_thread (pthread_create.c:312)
==4627==    by 0x5EE747C: clone (clone.S:111)
==4627==  Address 0x68df7f8 is 24 bytes inside a block of size 64 free'd
==4627==    at 0x4C2C2BC: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4627==    by 0x407E90: KafkaProducer::disconnect() (kafkaproducer.cpp:57)
==4627==    by 0x407D29: KafkaProducer::~KafkaProducer() (kafkaproducer.cpp:32)
==4627==    by 0x407DF1: KafkaProducer::~KafkaProducer() (kafkaproducer.cpp:38)
==4627==    by 0x409DC0: KafkaProducerFactory::~KafkaProducerFactory() (kafkaproducerfactory.cpp:22)
==4627==    by 0x4045A8: main (test_kafkaproducerfactory.cpp:14)

kafkaproducer.cpp lines 56-67 (double-spacing preserved):

 if(m_producer)           // line 56
     delete m_producer;

 if(m_topic)
     delete m_topic;


 if(m_tconf)
     delete m_tconf;

 if(m_conf)
     delete m_conf;       // line 67

Any help is welcome.

UPDATE

I already found the following codes caused this problem. If I commented the following part (If I did not set the event call back function.), the problem would disappear. But I have no idea why it caused the problem. I used the same way to set delivery call back function, which did not cause any problem. It is wired.

//defination
    class MyEventCb : public RdKafka::EventCb
    {
    public:
        void event_cb (RdKafka::Event &event)
        {
        }
    private:

    };

//set the callback function
    if( m_conf->set("event_cb", &m_event_cb, m_errstr) != RdKafka::Conf::CONF_OK)
    {
        DBG_PRINT( 1, "Kafka::Failed to set event callback : %s\n", m_errstr.c_str() );
        return false;
    }
    // Class member
MyEventCb m_event_cb; // event callback



via Chebli Mohamed

How to make a program in c++ that monitors news from RSS feeds

I am trying to create a program in c++ that will monitor news feeds from different RSS feeds and then sort it and display news according to the user's interests. How do i get Started? Is there any Library which already does this? Im an Intermediate c++ Programmer and i would really appreciate it if someone could guide me on the difficulty, depth and perhaps, the way i can implement this.



via Chebli Mohamed

Starting problems with OTL 4.0 MS SQL, ODBC and Code:Blocks

I have to insert some values into a MS SQL-Database on a Windows Machine, but also have to insert some values in a MySQL-Database on Linux soon. So I looked around and found SOCI and OTL 4.0.

I decided to use OTL 4.0 because it looked more easy for one, who haven't worked with C++ and databases before.

I tried to compile a modification of an example ( made it easier) and stumbled serveral times.

My Code so far:

    #include "db.h"
#include <iostream>
#include <fstream>
#include <stdio.h>

#include "plc.h"

#include <sqlncli.h>
#include <oledbdm.h>

using namespace std;


#define OTL_ODBC_MSSQL_2008 // Compile OTL 4/ODBC, MS SQL 2008
//#define OTL_ODBC // Compile OTL 4/ODBC. Uncomment this when used with MS SQL 7.0/ 2000
#include "otlv4.h" // include the OTL 4.0 header file

otl_connect db; // connect object

void insert(TIMESTAMP_STRUCT tm, string table)
{

 string sql_statement;
 //sql_statement = "insert into " << table << " values (:"
 otl_stream o(50, // buffer size
              "insert into test_tab2 values(:f1<float>,:f2<timestamp>)",
                 // SQL statement
              db // connect object
             );

 for(int i=1;i<=10;++i){
  tm.year=1998;
  tm.month=10;
  tm.day=19;
  tm.hour=23;
  tm.minute=12;
  tm.second=12;
  tm.fraction=0;
  o<<(float)i<<tm;
 }
}



void getDataIntoDB(plcdata &data)
{
    otl_connect::otl_initialize(); // initialize ODBC environment
    try{

        db.rlogon("UID=scott;PWD=tiger;DSN=mssql2008"); // connect to ODBC

        }

 catch(otl_exception& p){ // intercept OTL exceptions
  cerr<<p.msg<<endl; // print out error message
  cerr<<p.stm_text<<endl; // print out SQL that caused the error
  cerr<<p.sqlstate<<endl; // print out SQLSTATE message
  cerr<<p.var_info<<endl; // print out the variable that caused the error
 }

 db.logoff(); // disconnect from Oracle


}

Build log:

-------------- Build: Debug in TimeLogger (compiler: GNU GCC Compiler)---------------

mingw32-g++.exe -Wall -fexceptions -g -DOTL_ODBC -IC:\Users\bauermar\GTK -IC:\Users\bauermar\Documents\Sources\EN3 -I"C:\Program Files\Microsoft SQL Server\90\SDK\Include" -c C:\Users\bauermar\Documents\Sources\TimeLogger\db.cpp -o obj\Debug\db.o In file included from C:\Users\bauermar\Documents\Sources\TimeLogger\db.cpp:8:0: C:\Program Files\Microsoft SQL Server\90\SDK\Include/sqlncli.h:17:0: warning: ignoring #pragma warning [-Wunknown-pragmas] In file included from C:\Users\bauermar\Documents\Sources\TimeLogger\db.cpp:8:0: C:\Program Files\Microsoft SQL Server\90\SDK\Include/sqlncli.h:133:19: fatal error: oledb.h: No such file or directory compilation terminated. Process terminated with status 1 (0 minute(s), 0 second(s)) 1 error(s), 1 warning(s) (0 minute(s), 0 second(s))

I installed the Microsoft SQL Native Client with SDK, I included all libs and headers in the IDE of Code::Blocks I also included the sqlncli.h like it is said here

But I have no idea how to continue

I'm using Windows 7, Code::Blocks and MinGW32

Does anybody knows a good tutorial for working on DBs with C++ on several OS? Had someone the same problem? Is there a easier way to handle that with C++?

Thanks in advice!



via Chebli Mohamed

Should a theoretically, but not practically, throwing function be declared noexcept?

Is it safe to declare the following function noexcept even though v.at(idx) could theoretically throw a out_of_range exception, but practically not due to the bounds check?

int get_value_or_default(const std::vector<int>& v, size_t idx) noexcept {
    if (idx >= v.size()) {
        return -1;
    }
    return v.at(idx);
}



via Chebli Mohamed

Calling C from C#

I am from electric engineer background, therefore my knownledge is small about C#,DLL,etc.... I want to use c function into a C#. I know there is a couple post about that but I didn't find one that is enough simple.

Currently, I got C function call windows API to read/write on the USB port. First to create a .dll do I need a header file? Because I got the following function decleration function into a header. The examples that I saw on stack overflow and Internet only use a simple .c file, Can I get rid of the header files?

__declspec(dllexport) LMUSB_HANDLE  __stdcall InitializeDevice(unsigned short usVID,
                                    unsigned short usPID,
                                    LPGUID lpGUID,
                                    BOOL *pbDriverInstalled);
__declspec(dllexport) LMUSB_HANDLE  __stdcall InitializeDeviceByIndex(unsigned short usVID,
                                           unsigned short usPID,
                                           LPGUID lpGUID,
                                           DWORD dwIndex,
                                           BOOL bOpenDataEndpoints,
                                           BOOL *pbDriverInstalled);
__declspec(dllexport) BOOL  __stdcall TerminateDevice(LMUSB_HANDLE hHandle);
__declspec(dllexport) BOOL  __stdcall WriteUSBPacket(LMUSB_HANDLE hHandle,
                          unsigned char *pcBuffer,
                          unsigned long ulSize,
                          unsigned long *pulWritten);
__declspec(dllexport) DWORD  __stdcall ReadUSBPacket(LMUSB_HANDLE hHandle,
                         unsigned char *pcBuffer,
                         unsigned long ulSize,
                         unsigned long *pulRead,
                         unsigned long ulTimeoutMs,
                         HANDLE hBreak);
 __declspec(dllexport) BOOL  __stdcall Endpoint0Transfer(LMUSB_HANDLE hHandle, UCHAR ucRequestType,
                             UCHAR ucRequest, USHORT usValue,
                             USHORT usIndex, USHORT usLength,
                             PUCHAR pucBuffer, PUSHORT pusCount);

Second point, do I need to write __declspec(dllexport) in the cpp file? Here an function from the cpp:

extern "C" __declspec(dllexport) BOOL PASCAL EXPORT TerminateDevice(LMUSB_HANDLE hUSB)

I got no idea what "BOOL PASCAL EXPORT" does, this code is recycled from a furnisher project.

Finaly, when the DLL is properly build. How I import it in the C# project? I tried the following but without success :

[DllImport("lmusbdll.dll")]

I see that you could use right click on the project and add reference but Visual Studio pop-up an error message:

A reference to "DLL path" could not be added. Please make sure that the file is accessible, and that it is a valid assembly or COM component.

[EDIT]

I tried the following solution , but when I tried to reference the header file in my c# project. I still get the message that I cannot reference the file.



via Chebli Mohamed

Get user who initiates Windows Portable Device (MTP) event

I am detecting files being copied to a mobile phone, and I have IPortableDeviceValues available so I can get the file name (WPD_OBJECT_ORIGINAL_FILE_NAME) and device name (WPD_EVENT_PARAMETER_PNP_DEVICE_ID), but I'm not able to get a PSID or anything else that I can use to identify the person who performed the action.

Any ideas how I can get the user?



via Chebli Mohamed

OpenGL "glGenBuffers' cause segmentation fault

I am not sure what's going on, this was working before and all of a sudden it's just acting really crazy on me.

this is a cmake and sdl project. cmakelists.txt

PROJECT(ren_opengl)

SET(SRC_FILES ren_opengl.c)
set(CMAKE_MACOSX_RPATH 1)

FIND_PACKAGE(SDL2 REQUIRED)
INCLUDE_DIRECTORIES(${SDL2_INCLUDE_DIR})

FIND_PACKAGE(OPENGL REQUIRED)
INCLUDE_DIRECTORIES( ${OPENGL_INCLUDE_DIR})

ADD_EXECUTABLE(ren_opengl ${SRC_FILES})
TARGET_LINK_LIBRARIES(ren_opengl ${SDL2_LIBRARY} ${OPENGL_LIBRARIES})

included headers

#include <SDL2/SDL.h>
#include <OpenGL/gl3.h>
#include <SDL2/SDL_opengl.h>

Init SDL in ren_opengl.c

int init_sdl(int width, int height, char* title, double fps)
{

if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
  {
    SDL_Log("sdl failed to init");
    SDL_Quit();
    return -1;
  }

    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);

    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);


  window = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
  if(window == NULL)
  {
    SDL_Log("sdl failed to create window");
    SDL_Quit();
    return -1;
  }

  maincontext = SDL_GL_CreateContext(window);
  if(maincontext == NULL)
  {
    SDL_Log("sdl failed to create opengl context");
    SDL_Quit();
    return -1;
  }
    SDL_GL_SetSwapInterval(1);


  return 1;

}

at the end of init sdl everything is working, I ca

void render()
{
    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    SDL_GL_SwapWindow(window);
}

if I create a GLuint vao; that causes no problems, as soon as I try to do glGenBuffers(1, &vao); That line above keeps giving segmentation fault.

I even just updated to sdl 2.0.4 but i am really not sure what's going on now.



via Chebli Mohamed

Launch application inside app container

I'm currently looking for a way to programmatically launch a modern (uwp) application inside an app container using the available Win32 APIs.

I don't want to launch the app through a protocol '://app', Instead I want to create the app container myself and then load the UWP app inside that to have access to all memory etc.

Is this possible, and if so how?



via Chebli Mohamed

implement factory pattern for products with conditional compiling

I'd like to implement factory (or some other pattern) in a way that will allow me to compile the code without introducing type dependency.

enum CarType
{
 BMW,
 PORSCHE,
 MERC
};

class CarFactory
{
  public:
 static Car* create(CarType type)
 {
  switch(type)
  {
    case BMW : return new BMWCar();
    case PORSCHE : return new PorscheCar();
    default : return new MercCar();
  }
 }
};

When I compile CarFactory, I need to include BMWCar, PorscheCar and MercCar as a part of my compilation/linking unit.

The way my codebase is setup, we may want to ship BMWCar only, or two or all three of them. So, I cannot make the create() dependent on the type.

How can I adapt the factory pattern for this ? Also, I'd like to avoid doing ifdefs since this is just a sample of my problem. The real codebase is huge and is not a practical solution to ifdef the code.

Update: Also, I am not allowed to use:

  • templates
  • has to conform to c++ 98 standard
  • cannot use boost

These are mostly due to customer build toolchain restrictions. I don't have a choice in changing these.



via Chebli Mohamed

CMake on windows cannot link to executable with exposed symbols

I have a main executable that dynamically loads a shared library, both are compiled in the same CMake file. The library calls a function defined in the main executable, in Linux this is done successfully and the program works as expected, however in Windows the library fails to link the executable and the program crashes during compilation.

I am using this cmake file to construct an executable and a library that I modified from the Unix version I found here.

CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR)
PROJECT(EXPORTS C)
SET(CMAKE_VERBOSE_MAKEFILE ON)
SET(CMAKE_SHARED_LIBRARY_LINK_C_FLAGS "")
FILE(WRITE ${CMAKE_BINARY_DIR}/main.c
"#include <windows.h>
#include <stdio.h>
void internal(void){printf(\"internal()\\n\");}
int main(void)
{
    HMODULE plugin_library = LoadLibrary (\"./plugin.dll\");
    FARPROC initizer = GetProcAddress(plugin_library, \"external\");
    initizer();
}\n")
ADD_EXECUTABLE(main main.c)
target_link_libraries(main ${CMAKE_DL_LIBS})
SET_TARGET_PROPERTIES(main PROPERTIES
    ENABLE_EXPORTS TRUE)
FILE(WRITE ${CMAKE_BINARY_DIR}/plugin.c
"void external(void){internal();}\n")
ADD_LIBRARY(plugin MODULE plugin.c)
TARGET_LINK_LIBRARIES(plugin main)

When I try to build the program I get this output which throws the error fatal error U1073: don't know how to make 'main.lib'.

C:\Users\User\Desktop\linkingdemo\build>cmake -G "NMake Makefiles" ..
-- The C compiler identification is MSVC 19.0.23026.0
-- Check for working C compiler: C:/Program Files/Microsoft Visual Studio 14.0/VC/bin/cl.exe
-- Check for working C compiler: C:/Program Files/Microsoft Visual Studio 14.0/VC/bin/cl.exe -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Configuring done
-- Generating done
-- Build files have been written to: C:/Users/User/Desktop/linkingdemo/build

C:\Users\User\Desktop\linkingdemo\build>nmake

Microsoft (R) Program Maintenance Utility Version 14.00.23026.0
Copyright (C) Microsoft Corporation.  All rights reserved.

        "C:\Program Files\CMake\bin\cmake.exe" -HC:\Users\User\Desktop\linkingdemo -BC:\Users\User\Desktop\linkingdemo\build --check-build-system CMakeFiles\Makefile.cmake 0
        "C:\Program Files\CMake\bin\cmake.exe" -E cmake_progress_start C:\Users\User\Desktop\linkingdemo\build\CMakeFiles C:\Users\User\Desktop\linkingdemo\build\CMakeFiles\progress.marks
        "C:\Program Files\Microsoft Visual Studio 14.0\VC\BIN\nmake.exe" -f CMakeFiles\Makefile2 /nologo -                   all
        "C:\Program Files\Microsoft Visual Studio 14.0\VC\BIN\nmake.exe" -f CMakeFiles\main.dir\build.make /nologo -L                  CMakeFiles\main.dir\depend
        "C:\Program Files\CMake\bin\cmake.exe" -E cmake_depends "NMake Makefiles" C:\Users\User\Desktop\linkingdemo C:\Users\User\Desktop\linkingdemo C:\Users\User\Desktop\linkingdemo\build C:\Users\User\Desktop\linkingdemo\build C:\Users\User\Desktop\linkingdemo\build\CMakeFiles\main.dir\DependInfo.cmake --color=
Scanning dependencies of target main
        "C:\Program Files\Microsoft Visual Studio 14.0\VC\BIN\nmake.exe" -f CMakeFiles\main.dir\build.make /nologo -L                  CMakeFiles\main.dir\build
        "C:\Program Files\CMake\bin\cmake.exe" -E cmake_progress_report C:\Users\User\Desktop\linkingdemo\build\CMakeFiles 1
[ 50%] Building C object CMakeFiles/main.dir/main.c.obj
        C:\PROGRA~1\MICROS~1.0\VC\bin\cl.exe  @C:\Users\User\AppData\Local\Temp\nm3E0E.tmp
main.c
Linking C executable main.exe
        "C:\Program Files\CMake\bin\cmake.exe" -E vs_link_exe C:\PROGRA~1\MICROS~1.0\VC\bin\link.exe /nologo @CMakeFiles\main.dir\objects1.rsp @C:\Users\User\AppData\Local\Temp\nm3FE4.tmp
        "C:\Program Files\CMake\bin\cmake.exe" -E cmake_progress_report C:\Users\User\Desktop\linkingdemo\build\CMakeFiles  1
[ 50%] Built target main
        "C:\Program Files\Microsoft Visual Studio 14.0\VC\BIN\nmake.exe" -f CMakeFiles\plugin.dir\build.make /nologo -L                  CMakeFiles\plugin.dir\depend
        "C:\Program Files\CMake\bin\cmake.exe" -E cmake_depends "NMake Makefiles" C:\Users\User\Desktop\linkingdemo C:\Users\User\Desktop\linkingdemo C:\Users\User\Desktop\linkingdemo\build C:\Users\User\Desktop\linkingdemo\build C:\Users\User\Desktop\linkingdemo\build\CMakeFiles\plugin.dir\DependInfo.cmake --color=
Scanning dependencies of target plugin
        "C:\Program Files\Microsoft Visual Studio 14.0\VC\BIN\nmake.exe" -f CMakeFiles\plugin.dir\build.make /nologo -L                  CMakeFiles\plugin.dir\build
        "C:\Program Files\CMake\bin\cmake.exe" -E cmake_progress_report C:\Users\User\Desktop\linkingdemo\build\CMakeFiles 2
[100%] Building C object CMakeFiles/http://ift.tt/1N7p27p
        C:\PROGRA~1\MICROS~1.0\VC\bin\cl.exe  @C:\Users\User\AppData\Local\Temp\nm43BB.tmp
plugin.c
C:\Users\User\Desktop\linkingdemo\build\plugin.c(1): warning C4013: 'internal' undefined; assuming extern returning int
NMAKE : fatal error U1073: don't know how to make 'main.lib'
Stop.
NMAKE : fatal error U1077: '"C:\Program Files\Microsoft Visual Studio 14.0\VC\BIN\nmake.exe"' : return code '0x2'
Stop.NMAKE : fatal error U1077: '"C:\Program Files\Microsoft Visual Studio 14.0\VC\BIN\nmake.exe"' : return code '0x2'
Stop.

C:\Users\User\Desktop\linkingdemo\build>

What do I need to do on Windows to get this program to work correctly across multiple platforms?



via Chebli Mohamed

When can return type affect function arguments in C?

I noticed a function in an Arduino example that goes like this:

uint8_t getPrint(int id){
    ......
    p = finger.storeModel(id);
    Serial.println();
    if (p == FINGERPRINT_OK) {
        Serial.println("Stored!");
    } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
        Serial.println("Communication error");
        return p;
    } else if (p == FINGERPRINT_BADLOCATION) {
        Serial.println("Could not store in that location");
        return p;
    } else if (p == FINGERPRINT_FLASHERR) {
        Serial.println("Error writing to flash");
        return p;
    } else {
        Serial.println("Unknown error");
        return p;
    }
}

I didn't include the rest of the function because the argument was used only once as above. Whenever i pass a value greater that 255 to the function, the serial monitor prints id % 256 e.g. 300 changes to 44. As soon as i changed the return type to int, it began to behave normally. Is this possible? What can make a return type affect the arguments? I also noticed that the function does not return a value when it completes successfully (the if statement). Can this be the cause? The return value of the getPrint() function is used in this way by the loop() function:

void loop(){
    //code that obtains an id (declared int) from the user
    .......
    while (!  getPrint(id) );
}

I also need to ask: what value is returned to the while statement? When i run the code, the loop() function seems to restart each time the getPrint() function either returns or reaches the end, regardless of the success or failure of the function; i cant see the effect of the while statement. Thoughts? **All the constants are non-zero 8-bit values except FINGERPRINT_OK



via Chebli Mohamed

How to create a console application in Code::Blocks?

I need to create a console application in Code::Blocks using some of wxWidgets classes (such as wxThread, wxHTTP, ...).

There are no "wxWidgets console application" wizard in Code::Blocks, so I choose just a "Console application", getting main.cpp created with the following code:

#include <iostream>

using namespace std;

int main()
{
    cout << "Hello world!" << endl;
    return 0;
}

It compiles and runs Ok. When I replace it with a contents of examples/samples/console/console.cpp from wxWidgets's examples (skipped some text to be shorter):

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
    #include "wx/wx.h"
#endif
#include <wx/app.h>
#include <wx/cmdline.h>

// implementation
static const wxCmdLineEntryDesc cmdLineDesc[] =
{
    ...
};

int main(int argc, char **argv)
{
    wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE, "program");
    //!: **ERROR HERE:^**

    wxInitializer initializer;
    if ( !initializer )
    {
        fprintf(stderr, "Failed to initialize the wxWidgets library, aborting.");
        return -1;
    }
    ...
    // do something useful here
    return 0;
}

I got "undefined reference to wxAppConsoleBase::CheckBuildOptions(char const*, char const*)" error (gcc) at specified line.

What am I doing wrong?

How to fix this?

I can compile my GUI projects with wxWidgets (version 3.0) with no problem, so it looks like I need to specify some defines, includes or any other magic to make it work. I tried to understand example's makefile, but with no luck.



via Chebli Mohamed

dimanche 28 juin 2015

Slide Out Menu without a back Button

I use SWRevealViewController for my Slide Out Menu. I did actually the same like he did it here: https://www.youtube.com/watch?v=5SUV1YY2yxQ, but even I add a new ViewController and connect it with the segue "reveal view controller", start the app and click on the row to open the view controller, it will works, but I don't have a back Button. Why?

Can this dispatch_once singleton ever return nil?

Trying to find an issue we are experiencing intermittently, that seems to be occurring on devices with low memory conditions. The suspected cause is the NSDateFormatter singleton being nil.

Is there any possible situation where the singleton pattern below could return nil?

+ (NSDateFormatter *)dateFormatterUTC {

    static NSDateFormatter *formatter;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat=@"yyyy-MM-dd HH:mm:ss ZZZ";
    });

    return formatter;
}

Dynamic replaceable uiviewcontroller in side a view with bottom static menu ios

How will achieve the above with a bottom static menu and replaceable uiviewcontrollers like fragments in android in the middle part?

iOS Push Notifications handle

Looking for a good practice regarding push notifications handle. currently in my app i'm handling the push notifications in the didFinishLaunchingWithOptions and in the didReceiveRemoteNotification delegates. I noticed that both handling logics are "firing" when i receive a push notifications when the app is "Dead". My remote notifications flag in Background Modes is ON in my app. Is there a good practice for handling this scenario ? why am i getting the push data in the didFinishLaunchingWithOptions(launchOptions) and didReceiveRemoteNotification is getting called too ? to my knowledge the didReceiveRemoteNotification is not spoused to get called when the app is "Dead".

After tableview reload cell not deleted

I have one UIView and inside one table view.After reload data visible cell remains and overlapping another cell in table view.I am using pull to refresh control and using reloadRowsAtIndexPaths.

[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];

If I put something like this :

 if(indexPath.row >5){

                                             [self.tableView beginUpdates];
                                             [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                                             [self.tableView endUpdates];
                                         }
                                         else {

                                             [self.tableView reloadData];


                                         }

In this scenario there is no overlapping but this is not best solution.

iOS/ObjC: "Fallback" tap gesture recognizer?

I have a UIViewController subclass whose view will generally contain some number of UIButtons and other interactive elements which may have one or more gesture recognizes attached to them.

What I'm trying to do is provide some visual feedback in the event that the user taps on a part of the screen that is not interactive. In other words: when the user taps the screen anywhere, if and only if no other control in the view responds to the touch event (including if it's, say, the start of a drag), then I want to fire off a method based on the location of the tap.

Is there a straightforward way to do this that would not require my attaching any additional logic to the interactive elements in the view, or that would at least allow me to attach such logic automatically by traversing the view hierarchy?

It takes long time to fetch images (Objective-C)

I am a beginner ios developer and i want to create a photo album app. I find some codes from internet and try to learn from there. In the app, when i click an album, it takes so much time for the album's collectionview of images to load. To fetch the images, my code is in ViewWillAppear. Can you help me optimize this code for better performance. If there is more than 10-15 images, this takes so long to load. Thanks in advance and sorry if my English is bad.

-(void)viewWillAppear:(BOOL)animated
{
    // Call to the super classes implementation of viewWillAppear
    [super viewWillAppear:YES];
    /* The Photos are stored in Core Data as an NSSet. */
    NSSet *unorderedPhotos = self.album.photos;
    /* To organize them we use a NSSort descriptor to arrange the photos by date. */
    NSSortDescriptor *dateDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES];
    NSArray *sortedPhotos = [unorderedPhotos sortedArrayUsingDescriptors:@[dateDescriptor]];
    self.photos = [sortedPhotos mutableCopy];

    /* Now that the photos are arranged we reload our CollectionView. */
    [self.collectionView reloadData];

}

Objective C: when valueForKey is an instance with properties

i am trying to extract a property of an instance of a class that is a property of another class! easier shown by example...

// Person is a class with properties: name and age
Person *person = [[Person alloc] init];
[person setName:@"Alex"];

// Age is a class with properties value (i.e. 100) and unit (i.e. year)
Age *age = [[Age alloc] init];
[age setValue:@100];
[person setAge:age];

NSMutableArray *people = [[NSMutableArray alloc] init];
[people addObject:person];

for (id person in people) {

how can i extract the value property of the age instance associated to the person?

    //[person valueForKey:@"age.value")];

i expect to get @100 - i get 'NSInvalidArgumentException'

this gives me the instance of Age - but i would rather have the value property.

    //[person valueForKey:@"age")];
}

is this possible? any help is much appreciated.

Add Object to NSMutableArray even it is check marked

I try to add the cell.textlabel.text to an NSMutableArray even it is check marked. I do this with following code:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    else{
        cell.accessoryType = UITableViewCellAccessoryCheckmark;

        self.selectedDays = [[NSMutableArray alloc] init];
        [self.selectedDays addObject:cell.textLabel.text];

        NSLog(@"%@", self.selectedDays);

    }
}

But it does not add, but replace.

    2015-06-28 xx:xx:xx xxxx - xxxx[xxx:xxx] (
    Monday
    )
    2015-06-28 xx:xx:xx xxxx - xxxx[xxx:xxx] (
    Tuesday
    )
    2015-06-28 xx:xx:xx xxxx - xxxx[xxx:xxx] (
    Wednesday
    )

How to push UIViewController from AppDelgate

I am building an iOS Application where there are 4 screen as - verify phone number,fb login, set your profile and home. Now what I need is that if a user have set her profile info and after clicking on next if he close the app. On the restarting of the app it should directly get navigated to the home screen and there should not be repetition of all the 3 screens again.

What happens is, the screen 1 ( verify phone no ) is shown for a short period of time and then home screen appears. I want home screen to appear immediately after the splash screen when I reopen the app.

I am using below code.

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UINavigationController *mvc = [storyboard instantiateViewControllerWithIdentifier:@"Home"];
    [self.window.rootViewController presentViewController:mvc animated:YES completion:nil];

importing swift framework into a objective-c project

I am importing swift framework into objective-c project like this:

@import MyFramework;

The problem is that only some of the classes are recognized by the class i am importing the framework.

The class which is recognized:

public class RecognizedClass:UIViewController, WKNavigationDelegate, WKScriptMessageHandle 
 { ... } 

The class which is not:

public class VeediUtils
{ ... } 

They are both public so why the first is recognized in the workspace and the other not?

Also i see in the header file MyFramework-Swift.h that a class

@interface RecognizedClass : UIViewController <WKNavigationDelegate, WKScriptMessageHandler>

Appear while the other dont

Why is that?

Also to point that this same procedure work when i am importing swift framework to swift project

Disable horizontal shift of webview content

I have the following code:

[myWebView.scrollView.panGestureRecognizer requireGestureRecognizerToFail:swipe];
[myWebView.scrollView.panGestureRecognizer requireGestureRecognizerToFail:swipe2];

which disables mywebview to scroll horizontaly. Instead it should perform an other method after swiping. It works with iOS 8+ but in iOS 7.1 the content of the webview still gets "scrolled" horizontally. I´ve attached a screenshot to illustrate my problem. I don´t want the gray area on the right to happen:

http://ift.tt/1ID2E1V

As you can see not the whole content is shiftet to the left. How can I prevent this "inner" horizontal shift and perform instead a method while swiping to the left? Thx.

Is it possible to use the location indicator outside MKMapView?

Does anyone know if it's possible to use the little blue dot outside the context of an MKMapView (and if so how)?

I've seen it done in a few other apps, however I don't know whether they've just tried to manually recreate it or whether the component is available. I tried searching online, but I don't actually know the name of the component which is making it very challenging.

enter image description here

How to debug uncaught NSRange exception in Xcode?

I am getting the following exception. How can I find from looking at this as to where I am having a problem with my NSArray

*** Terminating app due to uncaught exception 'NSRangeException', reason:

'*** -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000109ba4a75 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x000000010983dbb7 objc_exception_throw + 45
    2   CoreFoundation                      0x0000000109a9c97e -[__NSArrayI objectAtIndex:] + 190
    3   UIKit                               0x00000001076bd506 -[UITableViewDataSource tableView:heightForRowAtIndexPath:] + 109
    4   UIKit                               0x00000001073f0afb __66-[UISectionRowData refreshWithSection:tableView:tableViewRowData:]_block_invoke + 302
    5   UIKit                               0x00000001073f018e -[UISectionRowData refreshWithSection:tableView:tableViewRowData:] + 4125
    6   UIKit                               0x00000001073f250b -[UITableViewRowData _ensureSectionOffsetIsValidForSection:] + 131
    7   UIKit                               0x00000001073f56f5 -[UITableViewRowData rectForFooterInSection:heightCanBeGuessed:] + 352
    8   UIKit                               0x00000001073f57ca -[UITableViewRowData heightForTable] + 56
    9   UIKit                               0x000000010724e553 -[UITableView _adjustExtraSeparators] + 216
    10  UIKit                               0x00000001072637b2 -[UITableView layoutSubviews] + 251
    11  UIKit                               0x00000001071f01c3 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 521
    12  QuartzCore                          0x0000000108ad1c58 -[CALayer layoutSublayers] + 150
    13  QuartzCore                          0x0000000108ac687e _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
    14  QuartzCore                          0x0000000108ac66ee _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
    15  QuartzCore                          0x0000000108a3436e _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 242
    16  QuartzCore                          0x0000000108a35482 _ZN2CA11Transaction6commitEv + 390
    17  QuartzCore                          0x0000000108a35aed _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 89
    18  CoreFoundation                      0x0000000109ad9507 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
    19  CoreFoundation                      0x0000000109ad9460 __CFRunLoopDoObservers + 368
    20  CoreFoundation                      0x0000000109acf293 __CFRunLoopRun + 1123
    21  CoreFoundation                      0x0000000109acebc6 CFRunLoopRunSpecific + 470
    22  GraphicsServices                    0x000000010a460a58 GSEventRunModal + 161
    23  UIKit                               0x0000000107176580 UIApplicationMain + 1282
    24  APP_NAME                            0x0000000106d0dfc3 main + 115
    25  libdyld.dylib                       0x000000010aa68145 start + 1
    26  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

Objective-C dot accessor behaves differently with implicit getter

Can one of you kind people please help me to understand why I get '(null)' for the second line in the output but not the fourth? Many thanks in advance

MyClass.h

@interface MyClass : NSObject
@property (readonly) NSString *foo;
@property (getter=getBar, readonly) NSString *bar;
@end

main.m

@implementation MyClass
- (NSString *)getFoo { return @"foo"; }
- (NSString *)getBar { return @"bar"; }
@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {     
        MyClass *myClassInstance = [MyClass new];

        NSLog(@"%@", myClassInstance.getFoo);
        NSLog(@"%@", myClassInstance.foo);

        NSLog(@"%@", myClassInstance.getBar);
        NSLog(@"%@", myClassInstance.bar);
    }
    return 0;

output

foo
(null)
bar
bar

Send a busy signal when the app is in another call

I am using twilio iOS SDK. Is it possible to send a busy signal from the app if it is in another call?

Query PFRelation of blocked users

I'm trying to query the 'friend' relation while excluding any friends that have blocked the user (which is stored as a relation<_user>) on the friends user with a relation to the user they are blocking (potentially the user checking their friends). I tried querying like below, but it isn't excluding the record like I would think:

[SVProgressHUD showWithStatus:@"Loading ..."];

[friends removeAllObjects];

PFRelation *friendRelation = [[PFUser currentUser] objectForKey:@"friendsRelation"];
if (friendRelation)
{
PFQuery *friendsQuery = [friendRelation query];
    [friendsQuery orderByAscending:@"firstname"];
    [friendsQuery whereKey:@"disabled" notEqualTo:[NSNumber numberWithBool:YES]];
    [friendsQuery whereKey:@"Blocked" notEqualTo:[PFUser currentUser]];
[friendsQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error)
 {
     if (!error)
     {
         friends = [objects mutableCopy];
         [self.myTableView reloadData];
         [SVProgressHUD dismiss];
     }
     else
     {
         [SVProgressHUD showErrorWithStatus:@"Loading failed. Please try again."];
     }
 }];
}
else
{
    [SVProgressHUD dismiss];
}

Is there a way to accomplish what I am trying to do?

is it able to override NSObject init method to add every object into a single NSMutableArray?

I have a singleton object obj1, having a NSMutableArray member called Objects

and i added a category called NSObject (Register)

@implementation NSObject (Register)
-(id)init
{
    [[obj1 defaultObject] addObjectToView:self];
    return self;
}
@end

the addObjectToView method just simply add the object to the array

-(void)addObjectToView:(id)object
{
    [object retain];
    [Objects addObject:object];
}

(Object is a NSMutableArray)

the problem is, when i tried to test it, i did

NSWindow *window = [[NSWindow alloc] init];

and then i got 505 scary objects in the array,

(sorry, unable to post image) http://ift.tt/1QWWq6G

did i do anything wrong?

BTW, it is possible to manage the relationship of all objects and send isolate objects dealloc message to implement a garbage collector in Objective-C ?

Parse object containing array elements

I have a Parse object called Recipes and a column called ingredients, which is an array. I want to query my object list and retrieve a recipe based on some ingredients that I select.

If I use the whereKey:containsAllObjectsInArray: message on the query object, I will get recipes with more ingredients. Also, whereKey:containedIn: does not solve my problem. The retrieved objects should have an array of ingredients containing all my selected ingredients or only some of them. It should never have more ingredients than those I've selected.

Any ideas?

call class method within a framework

In objective-c how can i call class method inside a framework?

This is the method declaration:

public class func setGameLevel(level:Int)
{
    current_level = level
}

That is the class declaration (of the framework class):

public class MyClass
{

I imported the framework, now how can i call the method setGameLevel of the MyClass method?

In swift its called using:

MyClass.setGameLevel(1)

EXC_BAD_ACCESS tapping uisearchbar three times

I am trying to implement a search bar in a UICollectionView as a UICollectionViewReusableView

This way I am not using a UISearchController but I am changing the datasource of the collectionview

In my custom layout I am adding the searchbar this way:

override func prepareLayout() {
    super.prepareLayout()
    var searchBarAttributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: TeacherSearchbarIdentifier, withIndexPath: NSIndexPath(forItem: 0, inSection: 0))
    searchBarAttributes.frame = CGRectMake(0, 0, collectionViewContentSize().width, 44)
    searchBarAttributes.zIndex = 100
    miscAttributes.append(searchBarAttributes)
}

override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
    var attributes = [UICollectionViewLayoutAttributes]()
    for (idx, attr) in enumerate(miscAttributes) {
        if CGRectIntersection(rect, attr.frame) != CGRectNull {
            attributes.append(attr)
        }
    }

    return attributes
}

I am setting the delegate like this:

func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
    var view = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: kind, forIndexPath: indexPath) as! UICollectionReusableView
    if kind == TeacherSearchbarIdentifier {
        controller.searchBar = (view as! TeacherSearchView).searchBar
        return view
    }
}

The variable controller is the UICollectionViewController which implements the UISearchBarDelegate Protocol

The delegate is set in didSet of the searchBar variable. These are my delegates:

override func scrollViewDidScroll(scrollView: UIScrollView) {
    self.view.endEditing(true)
}

func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
    searchBar.setShowsCancelButton(true, animated: true)
    return true
}

func searchBarShouldEndEditing(searchBar: UISearchBar) -> Bool {
    searchBar.setShowsCancelButton(false, animated: true)
    searchBar.resignFirstResponder()
    return true
}

func searchBarCancelButtonClicked(searchBar: UISearchBar) {
    searchBar.setShowsCancelButton(false, animated: true)
    searchBar.resignFirstResponder()
}

Now my problem!

When I am tapping on the search bar, the keyboard appears. If I press the cancel button or scroll, it dissappears. Just as I want it to. This also works a second time.

BUT!

If I do this a third time, I get a EXC_BAD_ACCESS:

EXC_BAD_ACCESS (code=1, address=0x14ac0beb8)

I tried turning on Enabling Zombie Objects, but no information was provided. I also tried profiling for Zombie Objects, it just crashes without any noticeable information.

Please help me on how I can resolve this error, or give me further debugging instructions.

Displaying NSMutable array using User Defaults

I am working on an app that has a mutable array of custom object ToDoItem(kind of morphed the dev example into my own app, will change later). I know its not the best way to do it, but I am using the user defaults to save it. Now, in the commented out code at the top, simply calling "addObject" loads the info into the table view. I don't know the intricacies of how this works, can somebody please explain why nothing is loading to the table view when I load it from user defaults? I am a beginner, so please explain thoroughly. Thank you for any help!

@interface ToDoListTableViewController ()
@property NSMutableArray *toDoItems;

@end

@implementation ToDoListTableViewController
- (void)loadInitialData1 {

   /*
ToDoItem *item1 = [[ToDoItem alloc] init];
item1.location = @"BDK";
item1.total = [[NSNumber alloc] initWithFloat:15.0];
item1.tip = [[NSNumber alloc] initWithFloat:5.567];
item1.percentage = [[NSNumber alloc] initWithFloat:33.0];
[self.toDoItems addObject:item1];
ToDoItem *item2 = [[ToDoItem alloc] init];
item2.location = @"Emrick";
item2.total = [[NSNumber alloc] initWithFloat:10.0];
item2.tip = [[NSNumber alloc] initWithFloat:2.0];
item2.percentage = [[NSNumber alloc] initWithFloat:20.0];
[self.toDoItems addObject:item2];
ToDoItem *item3 = [[ToDoItem alloc] init];
item3.location = @"PPM";
item3.total = [[NSNumber alloc] initWithFloat:20.0];
item3.tip = [[NSNumber alloc] initWithFloat:20.0];
item3.percentage = [[NSNumber alloc] initWithFloat:100.0];
[self.toDoItems addObject:item3];
*/


self.toDoItems = [[[NSUserDefaults standardUserDefaults]objectForKey:@"key"]mutableCopy];

}

- (IBAction)unwindToList:(UIStoryboardSegue *)segue {
AddToDoItemViewController *source = [segue sourceViewController];
ToDoItem *item = source.toDoItem;
if (item != nil) {

    [self.toDoItems addObject:item];
    [self.tableView reloadData];

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    [defaults setObject:self.toDoItems forKey:@"key"];

    [defaults synchronize];

    NSLog(@"Data saved");

    }
}

MySQL server and iOS

I run a site write now with a quite big MySQL database. Now, I want to create an app. I will need to use obviously a database de to the fact my data are already there.

Thus,

1) Should I keep using the MySQL server and my iOS app will connect to this MySQL serve for getting data?

2) is there any problem if I use the MySQL server ? Security issues maybe?

3) if I have to change the MySQL server, what database infrastructure I need to build and work with?

I am totally newbie on iOS apps. And now I planning to face any issues my iOS app will have.

Google map cocoa pods integration issue

Hi I am integrating google maps with cocoa pods. I have done the integration but when i an running the project I Am getting following issue

ld: warning: Auto-Linking supplied '/Users/SANDY/Robert/Office/ProjectName/Pods/GoogleMaps/Frameworks/GoogleMaps.framework/GoogleMaps', framework linker option at /Users/SANDY/Robert/Office/ProjectName/Pods/GoogleMaps/Frameworks/GoogleMaps.framework/GoogleMaps is not a dylib
Undefined symbols for architecture i386:
  "_OBJC_CLASS_$_GMSCameraPosition", referenced from:
      objc-class-ref in EzTripInfoViewController.o
      objc-class-ref in TrackOrderViewController.o
      objc-class-ref in DriverInfoViewController.o
      objc-class-ref in DashboardViewController.o
  "_OBJC_CLASS_$_GMSCameraUpdate", referenced from:
      objc-class-ref in EzTripInfoViewController.o
      objc-class-ref in TrackOrderViewController.o
      objc-class-ref in DriverInfoViewController.o
      objc-class-ref in DashboardViewController.o
  "_OBJC_CLASS_$_GMSCoordinateBounds", referenced from:
      objc-class-ref in EzTripInfoViewController.o
      objc-class-ref in TrackOrderViewController.o
      objc-class-ref in DriverInfoViewController.o
      objc-class-ref in DashboardViewController.o
  "_OBJC_CLASS_$_GMSMapView", referenced from:
      objc-class-ref in EzTripInfoViewController.o
      objc-class-ref in TrackOrderViewController.o
      objc-class-ref in DriverInfoViewController.o
      objc-class-ref in DashboardViewController.o
  "_OBJC_CLASS_$_GMSMarker", referenced from:
      objc-class-ref in EzTripInfoViewController.o
      objc-class-ref in TrackOrderViewController.o
      objc-class-ref in DriverInfoViewController.o
      objc-class-ref in DashboardViewController.o
  "_OBJC_CLASS_$_GMSPath", referenced from:
      objc-class-ref in EzTripInfoViewController.o
      objc-class-ref in TrackOrderViewController.o
      objc-class-ref in DriverInfoViewController.o
      objc-class-ref in DashboardViewController.o
  "_OBJC_CLASS_$_GMSPolyline", referenced from:
      objc-class-ref in EzTripInfoViewController.o
      objc-class-ref in TrackOrderViewController.o
      objc-class-ref in DriverInfoViewController.o
      objc-class-ref in DashboardViewController.o
  "_OBJC_CLASS_$_GMSServices", referenced from:
      objc-class-ref in EzAppDelegate.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Thanks for help in advance.