问:
How to match .c and .h properly?
I have a C project and I really don't get how to manage .c and .h.
I've been using a method for years but now I have to create codes without any warnings, so I need to change the way I do it.

Here is how I'm doing it:

Each .c have a .h with the same name. Even main.c has a main.h.

In each .c, I include the matching .h, so I have only one include per .c.
In main.h, I include all the libraries I need, like stdio stdlib and so on. I also declare my enumerations and structures there.

Finally, in every  other .h, I include the main.h which contains the structures, enums and libraries.

I understand that by doing that, I call main.h a lot of time, but I use the #ifndef and #define in every .h.
Also, I each .h contains the prototypes of the functions in their corresponding .c

How should I manage .c and .h?

I forgot to mention that the problem is that I get a warning for every single function: "implicit declaration of function"

Here is an example with four files :

main.c :

```<code>#include "main.h"

int main()
{
    // code
}
int save(Player players[2], int currentPlayer)
{
    // code
}
int load(Player players[2], int* currentPlayer)
{
    // code
}
</code>```

main.h :

```<code>#ifndef MAIN_H
#define MAIN_H

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
#include <string.h>
#include <math.h>

typedef enum Direction Direction;
typedef enum Orientation Orientation;
typedef enum ShipType ShipType;
typedef enum CaseType CaseType;
typedef enum Status Status;
typedef enum PlayerType PlayerType;

enum Direction
{
    Nord=0, Est=1, Sud=2, Ouest=3
};
enum Orientation
{
    None=0, Horizontal=1, Vertical=2
};
enum ShipType
{
    SousMarin=1, Destroyer=2, Croiseur=3, Cuirasse=4
};
enum CaseType
{
    Undiscovered=0, Empty=1, Hit=2, Detected=3, Discovered=5
};

enum Status
{
    Undamaged=0, Damaged=1, Drowned=2
};

enum PlayerType
{
    Human=0, Computer=1
};

typedef struct Map Map;
typedef struct Ship Ship;
typedef struct Player Player;

struct Map
{
    int width, height;
    int* cases;
};

struct Ship
{
    int x, y, length, firstShoot, color;
    int hasBeenDiscovered;
    Orientation orientation;
    ShipType type;
    Status status;
};

struct Player
{
    int totalShips;
    int activeShips;
    Map map[2];
    char lastMoves[5][128];
    Ship* ships;
    PlayerType type;
    int shipcolor[4];
    int shipNumber[4];
    int color;
};

int save(Player players[2], int currentPlayer);
int load(Player players[2], int* currentPlayer);

#endif // MAIN_H
</code>```

IA.c :

```<code>#include "IA.h"

int IA(Player* IA, Player* enemy)
{
    // code
}

// And all my other functions
</code>```

IA.h :

```<code>#ifndef IA_H
#define IA_H

#include "main.h"

int IA(Player* IA, Player* enemy);
void endIATurn(Player* IA);

int enemyShipDiscovered(Map map, int* x, int* y, int SousMarinSpecific);
Ship* bestFriendlyActiveShip(Ship* ships, int totalShips, int SousMarinSpecific);
int friendlyShipDiscovered(Ship** ship, Ship* ships, Map map, int totalShips, int SousMarinSpecific);
int hitShipButNotDrowned(Player* IA, Player enemy, int totalShips, int* x, int* y);

int hasAtLeastOneMoveableShip(Player player);
int hasUndiscoveredCases(Player player);

void getUndiscoveredCoordoonnees(Map map, int* x, int* y);
int findNextCaseToShootAt(Map map, Ship ship, int* a, int* b);

#endif // IA_H
</code>```

All my other .h are like IA.h

答:
For foo.h and foo.c:

Use foo.h to tell other source files about things that foo.c provides. So foo.h will declare functions that are (a) defined in foo.c and (b) called from other source files. It will also declare any types or other things that those functions need or that other source files need in able to be able to use the functions.

In foo.h, only use #include to include header files that foo.h itself needs.

In foo.c, use #include "foo.h". This has two purposes: (1) It declares things that foo.c may need, without having to duplicate those declarations in foo.c. (2) It ensures that foo.c is using the same declarations that other source files see when they include foo.h, so any conflicts between declarations in foo.h and definitions in foo.c will produce compiler warnings or error messages.

If foo.c needs any headers that foo.h, include them in foo.c, not foo.h. Similarly, if foo.c has any functions that it uses for itself but does not expect other source files to use, declare them only in foo.c. Keep things that are just for foo.c inside foo.c. Use foo.h only for exporting things to other source files.

If there are any types or other declarations used by your program generally:

Put them in a suitably named file (e.g., bar.h for types involving some bar concept) and include it. Largely, you can treat bar.h as a pair bar.h and bar.c described above except that bar.cis empty.

Generally, there is no reason to make a main.h. Usually, main.c uses things that other source files provide and does not provide things for other sources to use (except that main is called by the C run-time start-up code).

Title: How to match .c and .h properly?

Body:
I have a C project and I really don't get how to manage .c and .h.
I've been using a method for years but now I have to create codes without any warnings, so I need to change the way I do it.

Here is how I'm doing it:

Each .c have a .h with the same name. Even main.c has a main.h.

In each .c, I include the matching .h, so I have only one include per .c.
In main.h, I include all the libraries I need, like stdio stdlib and so on. I also declare my enumerations and structures there.

Finally, in every  other .h, I include the main.h which contains the structures, enums and libraries.

I understand that by doing that, I call main.h a lot of time, but I use the #ifndef and #define in every .h.
Also, I each .h contains the prototypes of the functions in their corresponding .c

How should I manage .c and .h?

I forgot to mention that the problem is that I get a warning for every single function: "implicit declaration of function"

Here is an example with four files :

main.c :

#include "main.h"

int main()
{
    // code
}
int save(Player players[2], int currentPlayer)
{
    // code
}
int load(Player players[2], int* currentPlayer)
{
    // code
}

main.h :

#ifndef MAIN_H
#define MAIN_H

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
#include <string.h>
#include <math.h>

typedef enum Direction Direction;
typedef enum Orientation Orientation;
typedef enum ShipType ShipType;
typedef enum CaseType CaseType;
typedef enum Status Status;
typedef enum PlayerType PlayerType;

enum Direction
{
    Nord=0, Est=1, Sud=2, Ouest=3
};
enum Orientation
{
    None=0, Horizontal=1, Vertical=2
};
enum ShipType
{
    SousMarin=1, Destroyer=2, Croiseur=3, Cuirasse=4
};
enum CaseType
{
    Undiscovered=0, Empty=1, Hit=2, Detected=3, Discovered=5
};

enum Status
{
    Undamaged=0, Damaged=1, Drowned=2
};

enum PlayerType
{
    Human=0, Computer=1
};

typedef struct Map Map;
typedef struct Ship Ship;
typedef struct Player Player;

struct Map
{
    int width, height;
    int* cases;
};

struct Ship
{
    int x, y, length, firstShoot, color;
    int hasBeenDiscovered;
    Orientation orientation;
    ShipType type;
    Status status;
};

struct Player
{
    int totalShips;
    int activeShips;
    Map map[2];
    char lastMoves[5][128];
    Ship* ships;
    PlayerType type;
    int shipcolor[4];
    int shipNumber[4];
    int color;
};

int save(Player players[2], int currentPlayer);
int load(Player players[2], int* currentPlayer);

#endif // MAIN_H

IA.c :

#include "IA.h"

int IA(Player* IA, Player* enemy)
{
    // code
}

// And all my other functions

IA.h :

#ifndef IA_H
#define IA_H

#include "main.h"

int IA(Player* IA, Player* enemy);
void endIATurn(Player* IA);

int enemyShipDiscovered(Map map, int* x, int* y, int SousMarinSpecific);
Ship* bestFriendlyActiveShip(Ship* ships, int totalShips, int SousMarinSpecific);
int friendlyShipDiscovered(Ship** ship, Ship* ships, Map map, int totalShips, int SousMarinSpecific);
int hitShipButNotDrowned(Player* IA, Player enemy, int totalShips, int* x, int* y);

int hasAtLeastOneMoveableShip(Player player);
int hasUndiscoveredCases(Player player);

void getUndiscoveredCoordoonnees(Map map, int* x, int* y);
int findNextCaseToShootAt(Map map, Ship ship, int* a, int* b);

#endif // IA_H

All my other .h are like IA.h


来源: stackexchange

问:
Extract string in parentheses using c#
I have a string ---TIMESTAMP Tue, 24 Oct 2017 02:11:56 -0400 [1508825516987]---

I want to get the value within the [] (i.e. 1508825516987)

How can I get the value using Regex?

答:
You can use the following code to get the outcome what you want!

```<code> MatchCollection matches = Regex.Matches("---TIMESTAMP Tue, 24 Oct 2017 02:11:56 -0400 [1508825516987]---", @"\[(.*?)\]", RegexOptions.Singleline);
 Match mat = matches[0];
 string val = mat.Groups[1].Value.ToString();
</code>```

whereas the string val will contain the value what you required.

ContentLicense: CC BY-SA 3.0

Title: Extract string in parentheses using c#

Body:
You can use the following code to get the outcome what you want!

 MatchCollection matches = Regex.Matches("---TIMESTAMP Tue, 24 Oct 2017 02:11:56 -0400 [1508825516987]---", @"\[(.*?)\]", RegexOptions.Singleline);
 Match mat = matches[0];
 string val = mat.Groups[1].Value.ToString();

whereas the string val will contain the value what you required.


问:
Can I test my iPad app on someone else's iPad?
I'm developing an iPad app, and want to test it on a friend's iPad.  Before I buy the $99 developer account, I just want to make sure that this will work.

Does my friend's device have to use my apple ID in order to install the provisioning profile?  Is there anything that would change about his iPad (besides the ability to install my app, of course)?

Thanks!

答:
Before I buy the $99 developer account, I just want to make sure that this will work

You don't have the developer account? If so, you won't be able to test apps on the device, no matter who that device belongs to

ContentLicense: CC BY-SA 2.5


问:
Best practice for having a nav at the top of all the pages in a site?
What is the best practice for having my nav at the the top of all mt web pages. E.g, home and about both have the nav. Do I have to repeat the code or is there a better practice?</p>

答: use a single file for header and include it on any page you want, not possible in html you need something like php to do it.</p>


问:
Transposition cipher too long compilation
I need to do a program that decodes Transposition cipher. On start I have one word, which is in encrypted text. the length of the key is equal to the -1 length of the received word. key is random.

Examples:

```<code>input text:Uniz isvrh tiesiime ffrmfbi jz tpywjhpf gx ucs zgvey eoj e igpg himua xgxfx qbxo xgw b xihapbx vftx jt xik jpxq pl eo owpygfrit zvjgrhri
input word: mark
output:They could scarcely believe it possible at two yards and a half below water mark was a regular rent in the form of an isosceles triangle
</code>```

```<code>input text:Qr oc cvtmxen ev Rga Asto vlg uwiuxksp acw cx kxu lgmilv
input word:was
output:On my arrival at New York the question was at its height
</code>```

```<code>input text: Rt kolniz qufkbnx R gjvoczkm zqk kgobzkwin ul cnn suwyckx
input word: effect
output:In effect however I admitted the existence of the monster
</code>```

For examples 1 and 2 the program compiles quite quickly, but for example 3
the program compiles for a very long time because i have too many for loops.

```<code>#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>

int main()
{
    unsigned int i = 0;
    int key[10];
    unsigned int k = 0;
    int check;
    unsigned int j, jj, jjj, jjjj, jjjjj, jjjjjj;
    int n = 50;
    char slowo[10];
    char plain[500], cipher[500];

    fflush(stdin);
    printf("Enter text:");
    fgets(plain, 500, stdin);
    printf("Enter word:");
    fgets(slowo, 500, stdin);

    if (strlen(slowo) == 4)
    {
        for (j = n; j != 0; j--)
        {
            key[0] = (j - 25);
            for (jj = n; jj != 0; jj--)
            {
                key[1] = (jj - 25);
                for (i = 0; i<strlen(plain); i++)
                {
                    if (isalpha(plain[i]))
                    {
                        if (islower(plain[i]))
                        {
                            check = plain[i];

                            if (islower(plain[i]) && check + key[k]>96 && check + key[k]<123)
                            {
                                cipher[i] = (plain[i] + key[k] - 'a') % 26 + 'a';
                            }
                            else
                            {
                                check = 123 + (check - 97 + key[k]);
                                cipher[i] = (check - 'a') % 26 + 'a';
                                check = 0;
                            }
                        }
                        else
                        {
                            check = plain[i];
                            if (isupper(plain[i]) && check + key[k]>64 && check + key[k]<91)
                            {
                                cipher[i] = (plain[i] + key[k] - 'A') % 26 + 'A';
                            }

                            else
                            {
                                check = 91 + (check - 65 + key[k]);
                                cipher[i] = (check - 'A') % 26 + 'A';
                                check = 0;

                            }
                        }
                    }
                    else
                        if (isspace(plain[i]))
                        {
                            k--;

                            cipher[i] = plain[i];
                        }
                    k++;
                    if (k>strlen(slowo) - 3)//ostatniznak + \0
                        k = 0;
                }
                for (i = 0; i<strlen(plain); i++)
                {

                    if (isspace(cipher[i]) && cipher[i + 1] == slowo[0] && cipher[i + 2] == slowo[1] && cipher[i + 3] == slowo[2] && isspace(cipher[i + 4]))
                    {

                        cipher[strlen(plain) - 1] = '\0';
                        printf("%s", cipher);
                        return 0;

                    }
                }

            }
        }
    }

    if (strlen(slowo) == 5)
    {
        for (j = n; j != 0; j--)
        {
            key[0] = (j - 25);

            for (jj = n; jj != 0; jj--)
            {
                key[1] = (jj - 25);

                for (jjj = n; jjj != 0; jjj--)
                {
                    key[2] = (jjj - 25);

                    for (i = 0; i<strlen(plain); i++)
                    {
                        if (isalpha(plain[i]))
                        {
                            if (islower(plain[i]))
                            {
                                check = plain[i];

                                if (islower(plain[i]) && check + key[k]>96 && check + key[k]<123)
                                {
                                    cipher[i] = (plain[i] + key[k] - 'a') % 26 + 'a';
                                }
                                else
                                {
                                    check = 123 + (check - 97 + key[k]);
                                    cipher[i] = (check - 'a') % 26 + 'a';
                                    check = 0;
                                }
                            }
                            else
                            {
                                check = plain[i];
                                if (isupper(plain[i]) && check + key[k]>64 && check + key[k]<91)
                                {
                                    cipher[i] = (plain[i] + key[k] - 'A') % 26 + 'A';
                                }

                                else
                                {
                                    check = 91 + (check - 65 + key[k]);
                                    cipher[i] = (check - 'A') % 26 + 'A';
                                    check = 0;

                                }
                            }
                        }
                        else
                            if (isspace(plain[i]))
                            {
                                k--;

                                cipher[i] = plain[i];
                            }
                        k++;
                        if (k>strlen(slowo) - 3)//ostatniznak + \0
                            k = 0;
                    }
                    for (i = 0; i<strlen(plain); i++)
                    {

                        if (isspace(cipher[i]) && cipher[i + 1] == slowo[0] && cipher[i + 2] == slowo[1] && cipher[i + 3] == slowo[2] && cipher[i + 4] == slowo[3] && isspace(cipher[i + 5]))
                        {
                            cipher[strlen(plain) - 1] = '\0';
                            printf("%s", cipher);
                            return 0;

                        }
                    }
                }
            }
        }
    }
    if (strlen(slowo) == 6)
    {
        for (j = n; j != 0; j--)
        {
            key[0] = (j - 25);

            for (jj = n; jj != 0; jj--)
            {
                key[1] = (jj - 25);
                for (jjj = n; jjj != 0; jjj--)
                {
                    key[2] = (jjj - 25);
                    for (jjjj = n; jjjj != 0; jjjj--)
                    {
                        key[3] = (jjjj - 25);
                        for (i = 0; i<strlen(plain); i++)
                        {
                            if (isalpha(plain[i]))
                            {
                                if (islower(plain[i]))
                                {
                                    check = plain[i];

                                    if (islower(plain[i]) && check + key[k]>96 && check + key[k]<123)
                                    {
                                        cipher[i] = (plain[i] + key[k] - 'a') % 26 + 'a';
                                    }
                                    else
                                    {
                                        check = 123 + (check - 97 + key[k]);
                                        cipher[i] = (check - 'a') % 26 + 'a';
                                        check = 0;
                                    }
                                }
                                else
                                {
                                    check = plain[i];
                                    if (isupper(plain[i]) && check + key[k]>64 && check + key[k]<91)
                                    {
                                        cipher[i] = (plain[i] + key[k] - 'A') % 26 + 'A';
                                    }

                                    else
                                    {
                                        check = 91 + (check - 65 + key[k]);
                                        cipher[i] = (check - 'A') % 26 + 'A';
                                        check = 0;

                                    }
                                }
                            }
                            else
                                if (isspace(plain[i]))
                                {
                                    k--;

                                    cipher[i] = plain[i];
                                }
                            k++;
                            if (k>strlen(slowo) - 3)//ostatniznak + \0
                                k = 0;
                        }
                        for (i = 0; i<strlen(plain); i++)
                        {

                            if (isspace(cipher[i]) && cipher[i + 1] == slowo[0] && cipher[i + 2] == slowo[1] && cipher[i + 3] == slowo[2] && cipher[i + 4] == slowo[3] && cipher[i + 5] == slowo[4] && isspace(cipher[i + 6]))
                            {
                                cipher[strlen(plain) - 1] = '\0';
                                printf("%s", cipher);
                                return 0;

                            }
                        }
                    }

                }
            }

        }
    }
    if (strlen(slowo) == 7)
    {
        for (j = n; j != 0; j--)
        {
            key[0] = (j - 25);
            for (jj = n; jj != 0; jj--)
            {
                key[1] = (jj - 25);
                if (isspace(cipher[i]) && cipher[i + 1] == slowo[0] && cipher[i + 2] == slowo[1] && isspace(cipher[i + 7]))
                {
                    jj--;
                }

                for (jjj = n; jjj != 0; jjj--)
                {
                    key[2] = (jjj - 25);

                    for (jjjj = n; jjjj != 0; jjjj--)
                    {
                        key[3] = (jjjj - 25);

                        for (jjjjj = n; jjjjj != 0; jjjjj--)
                        {
                            key[4] = (jjjjj - 25);

                            for (i = 0; i<strlen(plain); i++)
                            {
                                if (isalpha(plain[i]))
                                {
                                    if (islower(plain[i]))
                                    {
                                        check = plain[i];

                                        if (islower(plain[i]) && check + key[k]>96 && check + key[k]<123)
                                        {
                                            cipher[i] = (plain[i] + key[k] - 'a') % 26 + 'a';
                                        }
                                        else
                                        {
                                            check = 123 + (check - 97 + key[k]);
                                            cipher[i] = (check - 'a') % 26 + 'a';
                                            check = 0;
                                        }
                                    }
                                    else
                                    {
                                        check = plain[i];
                                        if (isupper(plain[i]) && check + key[k]>64 && check + key[k]<91)
                                        {
                                            cipher[i] = (plain[i] + key[k] - 'A') % 26 + 'A';
                                        }

                                        else
                                        {
                                            check = 91 + (check - 65 + key[k]);
                                            cipher[i] = (check - 'A') % 26 + 'A';
                                            check = 0;

                                        }
                                    }
                                }
                                else
                                    if (isspace(plain[i]))
                                    {
                                        k--;

                                        cipher[i] = plain[i];
                                    }
                                k++;
                                if (k>strlen(slowo) - 3)//ostatniznak + \0
                                    k = 0;
                            }
                            for (i = 0; i<strlen(plain); i++)
                            {

                                if (isspace(cipher[i]) && cipher[i + 1] == slowo[0] && cipher[i + 2] == slowo[1] && cipher[i + 3] == slowo[2] && cipher[i + 4] == slowo[3] && cipher[i + 5] == slowo[4] && cipher[i + 6] == slowo[5] && isspace(cipher[i + 7]))
                                {
                                    cipher[strlen(plain) - 1] = '\0';
                                    printf("%s", cipher);
                                    return 0;

                                }
                            }
                        }
                    }
                }
            }
        }
    }
    if (strlen(slowo) == 8)
    {
        for (j = n; j != 0; j--)
        {
            key[0] = (j - 25);
            for (jj = n; jj != 0; jj--)
            {
                key[1] = (jj - 25);

                for (jjj = n; jjj != 0; jjj--)
                {
                    key[2] = (jjj - 25);
                    for (jjjj = n; jjjj != 0; jjjj--)
                    {
                        key[3] = (jjjj - 25);

                        for (jjjjj = n; jjjjj != 0; jjjjj--)
                        {

                            key[4] = (jjjjj - 25);

                            for (jjjjjj = 0; jjjjjj != 0; jjjjjj--)
                            {
                                key[5] = (jjjjjj - 25);
                                for (i = 0; i<strlen(plain); i++)
                                {
                                    if (isalpha(plain[i]))
                                    {
                                        if (islower(plain[i]))
                                        {
                                            check = plain[i];

                                            if (islower(plain[i]) && check + key[k]>96 && check + key[k]<123)
                                            {
                                                cipher[i] = (plain[i] + key[k] - 'a') % 26 + 'a';
                                            }
                                            else
                                            {
                                                check = 123 + (check - 97 + key[k]);
                                                cipher[i] = (check - 'a') % 26 + 'a';
                                                check = 0;
                                            }
                                        }
                                        else
                                        {
                                            check = plain[i];
                                            if (isupper(plain[i]) && check + key[k]>64 && check + key[k]<91)
                                            {
                                                cipher[i] = (plain[i] + key[k] - 'A') % 26 + 'A';
                                            }

                                            else
                                            {
                                                check = 91 + (check - 65 + key[k]);
                                                cipher[i] = (check - 'A') % 26 + 'A';
                                                check = 0;

                                            }
                                        }
                                    }
                                    else
                                        if (isspace(plain[i]))
                                        {
                                            k--;

                                            cipher[i] = plain[i];
                                        }
                                    k++;
                                    if (k>strlen(slowo) - 3)//ostatniznak + \0
                                        k = 0;
                                }
                                for (i = 0; i<strlen(plain); i++)
                                {

                                    if (isspace(cipher[i]) && cipher[i + 1] == slowo[0] && cipher[i + 2] == slowo[1] && cipher[i + 3] == slowo[2] && cipher[i + 4] == slowo[3] && cipher[i + 5] == slowo[4] && cipher[i + 6] == slowo[5] && cipher[i + 7] == slowo[6] && isspace(cipher[i + 7]))
                                    {
                                        cipher[strlen(plain) - 1] = '\0';
                                        printf("%s", cipher);
                                        return 0;

                                    }
                                }
                            }
                        }
                    }

                }
            }
        }
    }
    else {
        printf("Error");
        return 1;
    }
}
</code>```

I would like to optimize the code to make it faster, but I have no idea.

答:
There are some possible optimizations - what is called a keyhole optimization - in your code, but I'd rather change the algorithm you're using. Keyhole optimizations are penny wise and pound foolish, and premature optimization is the root of all evil. Decreasing the algorithm complexity is almost always your top priority. Then and only then you do further optimizations.

Here you know that key length is (in the third example) five, because the crib effect is six characters; we'll refer to the key as 12345.

We align the key to the cyphertext since whitespaces are ignored:

```<code>12 345123 4512345 1 23451234 512 345123451 23 451 2345123
Rt kolniz qufkbnx R gjvoczkm zqk kgobzkwin ul cnn suwyckx
</code>```

We could now implement a brute-force Babbage decryption in O(n3) using a linear equation system:

```<code>x1 - 1 = R
x2 - 2 = t
x3 - 3 = k
x4 - 4 = o
x5 - 5 = l
x6 - 1 = n
...
x48 - 3 = x
</code>```

But we can rather observe that we only have one word whose length is equal to that of 'effect' - it is 'kolniz'. Which means that we can recover the key straight away: it is the difference "nikol - efeec". The first symbol, 1, equals to a shift forward from the second e of effect to the n of kolniz, that is, 9 positions. So when we find a letter mapped to the 1 symbol of the worm, such as the first 'R', we go back 9 positions from R, and we find 'I'.

The above algorithm is roughly O(n+m) with n being the length of the ciphertext and m being the length of the key.

Suppose we have two  words whose length is equal to "effect", say they are "abcdef" and "ghijkl". Which one do we use?

Hypothesis 1: abcdef is the cyphertext of effect. If that is true then the shift for the first symbol of 'e' is 'a' and the same shift must get 'f' into 't'.

Hypothesis 2: ghikl is the cyphertext of effect. If that is true then the shift for the first symbol of 'e' is 'g' and the same shift must get 'l' into 't'.

The chances of both hypotheses being true and us not being able which one is correct are those of another word having the same shift difference in its first and last letters as are 'e' and 't' in our crib, for example the first word is 'effect' and the other is "cougar", "dirges", "harlow", or "jalopy". Those chances are very little.

Body:
I need to do a program that decodes Transposition cipher. On start I have one word, which is in encrypted text. the length of the key is equal to the -1 length of the received word. key is random.

Examples:

input text:Uniz isvrh tiesiime ffrmfbi jz tpywjhpf gx ucs zgvey eoj e igpg himua xgxfx qbxo xgw b xihapbx vftx jt xik jpxq pl eo owpygfrit zvjgrhri
input word: mark
output:They could scarcely believe it possible at two yards and a half below water mark was a regular rent in the form of an isosceles triangle

input text:Qr oc cvtmxen ev Rga Asto vlg uwiuxksp acw cx kxu lgmilv
input word:was
output:On my arrival at New York the question was at its height

input text: Rt kolniz qufkbnx R gjvoczkm zqk kgobzkwin ul cnn suwyckx
input word: effect
output:In effect however I admitted the existence of the monster

For examples 1 and 2 the program compiles quite quickly, but for example 3
the program compiles for a very long time because i have too many for loops.

#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>

int main()
{
    unsigned int i = 0;
    int key[10];
    unsigned int k = 0;
    int check;
    unsigned int j, jj, jjj, jjjj, jjjjj, jjjjjj;
    int n = 50;
    char slowo[10];
    char plain[500], cipher[500];

    fflush(stdin);
    printf("Enter text:");
    fgets(plain, 500, stdin);
    printf("Enter word:");
    fgets(slowo, 500, stdin);

    if (strlen(slowo) == 4)
    {
        for (j = n; j != 0; j--)
        {
            key[0] = (j - 25);
            for (jj = n; jj != 0; jj--)
            {
                key[1] = (jj - 25);
                for (i = 0; i<strlen(plain); i++)
                {
                    if (isalpha(plain[i]))
                    {
                        if (islower(plain[i]))
                        {
                            check = plain[i];

                            if (islower(plain[i]) && check + key[k]>96 && check + key[k]<123)
                            {
                                cipher[i] = (plain[i] + key[k] - 'a') % 26 + 'a';
                            }
                            else
                            {
                                check = 123 + (check - 97 + key[k]);
                                cipher[i] = (check - 'a') % 26 + 'a';
                                check = 0;
                            }
                        }
                        else
                        {
                            check = plain[i];
                            if (isupper(plain[i]) && check + key[k]>64 && check + key[k]<91)
                            {
                                cipher[i] = (plain[i] + key[k] - 'A') % 26 + 'A';
                            }

                            else
                            {
                                check = 91 + (check - 65 + key[k]);
                                cipher[i] = (check - 'A') % 26 + 'A';
                                check = 0;

                            }
                        }
                    }
                    else
                        if (isspace(plain[i]))
                        {
                            k--;

                            cipher[i] = plain[i];
                        }
                    k++;
                    if (k>strlen(slowo) - 3)//ostatniznak + \0
                        k = 0;
                }
                for (i = 0; i<strlen(plain); i++)
                {

                    if (isspace(cipher[i]) && cipher[i + 1] == slowo[0] && cipher[i + 2] == slowo[1] && cipher[i + 3] == slowo[2] && isspace(cipher[i + 4]))
                    {

                        cipher[strlen(plain) - 1] = '\0';
                        printf("%s", cipher);
                        return 0;

                    }
                }

            }
        }
    }

    if (strlen(slowo) == 5)
    {
        for (j = n; j != 0; j--)
        {
            key[0] = (j - 25);

            for (jj = n; jj != 0; jj--)
            {
                key[1] = (jj - 25);

                for (jjj = n; jjj != 0; jjj--)
                {
                    key[2] = (jjj - 25);

                    for (i = 0; i<strlen(plain); i++)
                    {
                        if (isalpha(plain[i]))
                        {
                            if (islower(plain[i]))
                            {
                                check = plain[i];

                                if (islower(plain[i]) && check + key[k]>96 && check + key[k]<123)
                                {
                                    cipher[i] = (plain[i] + key[k] - 'a') % 26 + 'a';
                                }
                                else
                                {
                                    check = 123 + (check - 97 + key[k]);
                                    cipher[i] = (check - 'a') % 26 + 'a';
                                    check = 0;
                                }
                            }
                            else
                            {
                                check = plain[i];
                                if (isupper(plain[i]) && check + key[k]>64 && check + key[k]<91)
                                {
                                    cipher[i] = (plain[i] + key[k] - 'A') % 26 + 'A';
                                }

                                else
                                {
                                    check = 91 + (check - 65 + key[k]);
                                    cipher[i] = (check - 'A') % 26 + 'A';
                                    check = 0;

                                }
                            }
                        }
                        else
                            if (isspace(plain[i]))
                            {
                                k--;

                                cipher[i] = plain[i];
                            }
                        k++;
                        if (k>strlen(slowo) - 3)//ostatniznak + \0
                            k = 0;
                    }
                    for (i = 0; i<strlen(plain); i++)
                    {

                        if (isspace(cipher[i]) && cipher[i + 1] == slowo[0] && cipher[i + 2] == slowo[1] && cipher[i + 3] == slowo[2] && cipher[i + 4] == slowo[3] && isspace(cipher[i + 5]))
                        {
                            cipher[strlen(plain) - 1] = '\0';
                            printf("%s", cipher);
                            return 0;

                        }
                    }
                }
            }
        }
    }
    if (strlen(slowo) == 6)
    {
        for (j = n; j != 0; j--)
        {
            key[0] = (j - 25);

            for (jj = n; jj != 0; jj--)
            {
                key[1] = (jj - 25);
                for (jjj = n; jjj != 0; jjj--)
                {
                    key[2] = (jjj - 25);
                    for (jjjj = n; jjjj != 0; jjjj--)
                    {
                        key[3] = (jjjj - 25);
                        for (i = 0; i<strlen(plain); i++)
                        {
                            if (isalpha(plain[i]))
                            {
                                if (islower(plain[i]))
                                {
                                    check = plain[i];

                                    if (islower(plain[i]) && check + key[k]>96 && check + key[k]<123)
                                    {
                                        cipher[i] = (plain[i] + key[k] - 'a') % 26 + 'a';
                                    }
                                    else
                                    {
                                        check = 123 + (check - 97 + key[k]);
                                        cipher[i] = (check - 'a') % 26 + 'a';
                                        check = 0;
                                    }
                                }
                                else
                                {
                                    check = plain[i];
                                    if (isupper(plain[i]) && check + key[k]>64 && check + key[k]<91)
                                    {
                                        cipher[i] = (plain[i] + key[k] - 'A') % 26 + 'A';
                                    }

                                    else
                                    {
                                        check = 91 + (check - 65 + key[k]);
                                        cipher[i] = (check - 'A') % 26 + 'A';
                                        check = 0;

                                    }
                                }
                            }
                            else
                                if (isspace(plain[i]))
                                {
                                    k--;

                                    cipher[i] = plain[i];
                                }
                            k++;
                            if (k>strlen(slowo) - 3)//ostatniznak + \0
                                k = 0;
                        }
                        for (i = 0; i<strlen(plain); i++)
                        {

                            if (isspace(cipher[i]) && cipher[i + 1] == slowo[0] && cipher[i + 2] == slowo[1] && cipher[i + 3] == slowo[2] && cipher[i + 4] == slowo[3] && cipher[i + 5] == slowo[4] && isspace(cipher[i + 6]))
                            {
                                cipher[strlen(plain) - 1] = '\0';
                                printf("%s", cipher);
                                return 0;

                            }
                        }
                    }

                }
            }

        }
    }
    if (strlen(slowo) == 7)
    {
        for (j = n; j != 0; j--)
        {
            key[0] = (j - 25);
            for (jj = n; jj != 0; jj--)
            {
                key[1] = (jj - 25);
                if (isspace(cipher[i]) && cipher[i + 1] == slowo[0] && cipher[i + 2] == slowo[1] && isspace(cipher[i + 7]))
                {
                    jj--;
                }

                for (jjj = n; jjj != 0; jjj--)
                {
                    key[2] = (jjj - 25);

                    for (jjjj = n; jjjj != 0; jjjj--)
                    {
                        key[3] = (jjjj - 25);

                        for (jjjjj = n; jjjjj != 0; jjjjj--)
                        {
                            key[4] = (jjjjj - 25);

                            for (i = 0; i<strlen(plain); i++)
                            {
                                if (isalpha(plain[i]))
                                {
                                    if (islower(plain[i]))
                                    {
                                        check = plain[i];

                                        if (islower(plain[i]) && check + key[k]>96 && check + key[k]<123)
                                        {
                                            cipher[i] = (plain[i] + key[k] - 'a') % 26 + 'a';
                                        }
                                        else
                                        {
                                            check = 123 + (check - 97 + key[k]);
                                            cipher[i] = (check - 'a') % 26 + 'a';
                                            check = 0;
                                        }
                                    }
                                    else
                                    {
                                        check = plain[i];
                                        if (isupper(plain[i]) && check + key[k]>64 && check + key[k]<91)
                                        {
                                            cipher[i] = (plain[i] + key[k] - 'A') % 26 + 'A';
                                        }

                                        else
                                        {
                                            check = 91 + (check - 65 + key[k]);
                                            cipher[i] = (check - 'A') % 26 + 'A';
                                            check = 0;

                                        }
                                    }
                                }
                                else
                                    if (isspace(plain[i]))
                                    {
                                        k--;

                                        cipher[i] = plain[i];
                                    }
                                k++;
                                if (k>strlen(slowo) - 3)//ostatniznak + \0
                                    k = 0;
                            }
                            for (i = 0; i<strlen(plain); i++)
                            {

                                if (isspace(cipher[i]) && cipher[i + 1] == slowo[0] && cipher[i + 2] == slowo[1] && cipher[i + 3] == slowo[2] && cipher[i + 4] == slowo[3] && cipher[i + 5] == slowo[4] && cipher[i + 6] == slowo[5] && isspace(cipher[i + 7]))
                                {
                                    cipher[strlen(plain) - 1] = '\0';
                                    printf("%s", cipher);
                                    return 0;

                                }
                            }
                        }
                    }
                }
            }
        }
    }
    if (strlen(slowo) == 8)
    {
        for (j = n; j != 0; j--)
        {
            key[0] = (j - 25);
            for (jj = n; jj != 0; jj--)
            {
                key[1] = (jj - 25);

                for (jjj = n; jjj != 0; jjj--)
                {
                    key[2] = (jjj - 25);
                    for (jjjj = n; jjjj != 0; jjjj--)
                    {
                        key[3] = (jjjj - 25);

                        for (jjjjj = n; jjjjj != 0; jjjjj--)
                        {

                            key[4] = (jjjjj - 25);

                            for (jjjjjj = 0; jjjjjj != 0; jjjjjj--)
                            {
                                key[5] = (jjjjjj - 25);
                                for (i = 0; i<strlen(plain); i++)
                                {
                                    if (isalpha(plain[i]))
                                    {
                                        if (islower(plain[i]))
                                        {
                                            check = plain[i];

                                            if (islower(plain[i]) && check + key[k]>96 && check + key[k]<123)
                                            {
                                                cipher[i] = (plain[i] + key[k] - 'a') % 26 + 'a';
                                            }
                                            else
                                            {
                                                check = 123 + (check - 97 + key[k]);
                                                cipher[i] = (check - 'a') % 26 + 'a';
                                                check = 0;
                                            }
                                        }
                                        else
                                        {
                                            check = plain[i];
                                            if (isupper(plain[i]) && check + key[k]>64 && check + key[k]<91)
                                            {
                                                cipher[i] = (plain[i] + key[k] - 'A') % 26 + 'A';
                                            }

                                            else
                                            {
                                                check = 91 + (check - 65 + key[k]);
                                                cipher[i] = (check - 'A') % 26 + 'A';
                                                check = 0;

                                            }
                                        }
                                    }
                                    else
                                        if (isspace(plain[i]))
                                        {
                                            k--;

                                            cipher[i] = plain[i];
                                        }
                                    k++;
                                    if (k>strlen(slowo) - 3)//ostatniznak + \0
                                        k = 0;
                                }
                                for (i = 0; i<strlen(plain); i++)
                                {

                                    if (isspace(cipher[i]) && cipher[i + 1] == slowo[0] && cipher[i + 2] == slowo[1] && cipher[i + 3] == slowo[2] && cipher[i + 4] == slowo[3] && cipher[i + 5] == slowo[4] && cipher[i + 6] == slowo[5] && cipher[i + 7] == slowo[6] && isspace(cipher[i + 7]))
                                    {
                                        cipher[strlen(plain) - 1] = '\0';
                                        printf("%s", cipher);
                                        return 0;

                                    }
                                }
                            }
                        }
                    }

                }
            }
        }
    }
    else {
        printf("Error");
        return 1;
    }
}

I would like to optimize the code to make it faster, but I have no idea.

Body:
There are some possible optimizations - what is called a keyhole optimization - in your code, but I'd rather change the algorithm you're using. Keyhole optimizations are penny wise and pound foolish, and premature optimization is the root of all evil. Decreasing the algorithm complexity is almost always your top priority. Then and only then you do further optimizations.

Here you know that key length is (in the third example) five, because the crib effect is six characters; we'll refer to the key as 12345.

We align the key to the cyphertext since whitespaces are ignored:

12 345123 4512345 1 23451234 512 345123451 23 451 2345123
Rt kolniz qufkbnx R gjvoczkm zqk kgobzkwin ul cnn suwyckx

We could now implement a brute-force Babbage decryption in O(n3) using a linear equation system:

x1 - 1 = R
x2 - 2 = t
x3 - 3 = k
x4 - 4 = o
x5 - 5 = l
x6 - 1 = n
...
x48 - 3 = x

But we can rather observe that we only have one word whose length is equal to that of 'effect' - it is 'kolniz'. Which means that we can recover the key straight away: it is the difference "nikol - efeec". The first symbol, 1, equals to a shift forward from the second e of effect to the n of kolniz, that is, 9 positions. So when we find a letter mapped to the 1 symbol of the worm, such as the first 'R', we go back 9 positions from R, and we find 'I'.

The above algorithm is roughly O(n+m) with n being the length of the ciphertext and m being the length of the key.

Suppose we have two  words whose length is equal to "effect", say they are "abcdef" and "ghijkl". Which one do we use?

Hypothesis 1: abcdef is the cyphertext of effect. If that is true then the shift for the first symbol of 'e' is 'a' and the same shift must get 'f' into 't'.

Hypothesis 2: ghikl is the cyphertext of effect. If that is true then the shift for the first symbol of 'e' is 'g' and the same shift must get 'l' into 't'.

The chances of both hypotheses being true and us not being able which one is correct are those of another word having the same shift difference in its first and last letters as are 'e' and 't' in our crib, for example the first word is 'effect' and the other is "cougar", "dirges", "harlow", or "jalopy". Those chances are very little.


问:
protecting adobe air apps
I am about to deliver an Adobe AIR app to a customer.
But it's my first delivery of any sort, I.e. I have
no experience whatsoever with licensing etc.

Users of this app may or may not be online, so
can't count on that. In fact it's 99% sure that
they will be offline.

Nor do I expect them to very tech-savvy, who will
spend enough time scouting for ways to "crack" it.

So, is there an okeish type of way to protect this
app. That is, I don't want people to simply copy
the installation folder, take it to another machine
and run it. It should be slightly harder than this.

Oh, and I am also using PHP and MySql, with which
this AIR app communicates. So anything you guys could
help me with is very very welcome.

答:
If you want to protect your Flex app you can use irrObfuscator. There is a 30 days free demo.

If you wish to obfuscate your PHP code I would suggest ioncube. There is an online obfuscator that you can pay per à-la-carte. Pretty usefull. Tho you need ioncube loaders which is a set of PHP extension that you will find into the products section. Not sure but I think you can install loaders without playing with PHP config so it's shared-hosting friendly.

OwnerDisplayName: dta

Title: protecting adobe air apps

OwnerDisplayName: Erick


问:
Looking for a good practice for dealing with repository in asp.net mvc
Currently I've got repository class for each data model for data access.

In the homepage, I need to display the top 5 records from each repository. So in the HomeController, I would need to have a lot of repository members, which doesn't feel right. Is there any good solution for this?

Thank you very much for your help. Any advice is welcome!

答:
You could use a service layer which will aggregate those five repositories into a single business operation. Example:

```<code>public interface IItemsService
{
    IEnumerable<Item> GetTopItems();
}
</code>```

and the implementation of this service will use as much repositories as required. Now your controller simply becomes:

```<code>public class ItemsController : Controller
{
    private readonly IItemsService _itemsService;
    public ItemsController(IItemsService itemsService)
    {
        _itemsService = itemsService;
    }

    public ActionResult Index()
    {
        var topItems = _itemsService.GetTopItems();
        return View(topItems);
    }
}
</code>```

And in the view:

```<code>@model IEnumerable<AppName.Models.Item>
<h2>Top items</h2>
@Html.DisplayForModel()
</code>```

which uses the item display template (~/Views/Items/DisplayTemplates/Item.cshtml):

```<code>@model AppName.Models.Item
<div>@Model.Title</div>
</code>```

Body:
You could use a service layer which will aggregate those five repositories into a single business operation. Example:

public interface IItemsService
{
    IEnumerable<Item> GetTopItems();
}

and the implementation of this service will use as much repositories as required. Now your controller simply becomes:

public class ItemsController : Controller
{
    private readonly IItemsService _itemsService;
    public ItemsController(IItemsService itemsService)
    {
        _itemsService = itemsService;
    }

    public ActionResult Index()
    {
        var topItems = _itemsService.GetTopItems();
        return View(topItems);
    }
}

And in the view:

@model IEnumerable<AppName.Models.Item>
<h2>Top items</h2>
@Html.DisplayForModel()

which uses the item display template (~/Views/Items/DisplayTemplates/Item.cshtml):

@model AppName.Models.Item
<div>@Model.Title</div>


问:
C: difference between 'struct Table *const' and 'const struct Table *'?
I created a struct like this:

```<code>typedef struct Table {
    #some members
  } Table;

typedef struct Table *TableP; // pointer to Table
</code>```

And I want to use it in the following function (given to me)

```<code>int insert(const TableP table, const void *key, DataP object)
</code>```

but Clion highlights table in the function, and gives the warning: "'table' declared with a const-qualified typedef type; results in the type being 'struct Table * const' instead of 'const struct Table *'"

I am not quite sure what this means. I tried changing my table struct to const but it doesn't change the warning.

答:
Case 1 :

```<code>typedef struct Table *TableP;
</code>```

here Tablep is pointer to structure Table. When you are writing

const TableP table, it will be defined  like this  const struct Table*

so what is meaning of const struct Table* , means address  constant, you can't change the address but you can modify it's members value .

for e.g

```<code> struct Table {
  int x ;
  } v = {10}, v1 ={20};

typedef struct Table  *Tablep;
int main() {
        const Tablep table = &v ;//it becomes const pointer i.e you can't change address
        table = &v1;// it's not possible.. address is contsant
       // table->x = 99;// possible.. can change it's member value

return 0;
}
</code>```

Note : both const Tablep local and Tablep const local are same.

I hope it helps.

Body:
I created a struct like this:

typedef struct Table {
    #some members
  } Table;

typedef struct Table *TableP; // pointer to Table

And I want to use it in the following function (given to me)

int insert(const TableP table, const void *key, DataP object)

but Clion highlights table in the function, and gives the warning: "'table' declared with a const-qualified typedef type; results in the type being 'struct Table * const' instead of 'const struct Table *'"

I am not quite sure what this means. I tried changing my table struct to const but it doesn't change the warning.

Body:
Case 1 :

typedef struct Table *TableP;

here Tablep is pointer to structure Table. When you are writing

const TableP table, it will be defined  like this  const struct Table*

so what is meaning of const struct Table* , means address  constant, you can't change the address but you can modify it's members value .

for e.g

 struct Table {
  int x ;
  } v = {10}, v1 ={20};

typedef struct Table  *Tablep;
int main() {
        const Tablep table = &v ;//it becomes const pointer i.e you can't change address
        table = &v1;// it's not possible.. address is contsant
       // table->x = 99;// possible.. can change it's member value

return 0;
}

Note : both const Tablep local and Tablep const local are same.

I hope it helps.


问:
Can I convert a View to Layout?
In android, one can Inflate a Layout file and will get a View in return.
For Example:

```<code>LayoutInflater layoutInflater = LayoutInflater.from(context);
View myView = layoutInflater.inflate(R.layout.example_layout, null);
</code>```

But I'm trying if I can get a Layout back from that inflated layout which is now a View?
Something by which I can retrieve back the original Layout from the Inflated View.

答:
```<code>LayoutInflater layoutInflater = LayoutInflater.from(context);
LinearLayout myView = (LinearLayout)layoutInflater.inflate(R.layout.example_layout, null);
</code>```

That's it!

Just be sure that the root view in your layout.example_layout is a LinearLayout or whatever layout you desire. Otherwise you'll have a ClassCastException

Every layout or ViewGroup extends View, that's why the inflate method returns a View, it's up to you then performing the right cast.

Title: Can I convert a View to Layout?

Body:
In android, one can Inflate a Layout file and will get a View in return.
For Example:

LayoutInflater layoutInflater = LayoutInflater.from(context);
View myView = layoutInflater.inflate(R.layout.example_layout, null);

But I'm trying if I can get a Layout back from that inflated layout which is now a View?
Something by which I can retrieve back the original Layout from the Inflated View.

Body:
LayoutInflater layoutInflater = LayoutInflater.from(context);
LinearLayout myView = (LinearLayout)layoutInflater.inflate(R.layout.example_layout, null);

That's it!

Just be sure that the root view in your layout.example_layout is a LinearLayout or whatever layout you desire. Otherwise you'll have a ClassCastException

Every layout or ViewGroup extends View, that's why the inflate method returns a View, it's up to you then performing the right cast.


问:
Restricting input text to only numbers and with minimum length to 10 for phone number
How to restrict my text box to only numbers with minimum length to 10 and another version like accept + at the start and after two & three & numbers - should come..like +91-123-456-7890

Here is my code

```<code><input type="text" maxlength="10" onkeyup="if (/\D/g.test(this.value))
this.value = this.value.replace(/\D/g,'')" name="mobile" placeholder="Mobile Number">
</code>```

答:
Use this code</p>

```<code><input type=“number” oninput=“slice(0,10)”>
</code>```

Body:
How to restrict my text box to only numbers with minimum length to 10 and another version like accept + at the start and after two & three & numbers - should come..like +91-123-456-7890

Here is my code

<input type="text" maxlength="10" onkeyup="if (/\D/g.test(this.value))
this.value = this.value.replace(/\D/g,'')" name="mobile" placeholder="Mobile Number">

Body:
Use this code

<input type=“number” oninput=“slice(0,10)”>


答:
I suggest the following:

Divide your functions in different .c files as you already do. For every .c create a .h

In every .h insert its include guard:

Within the include guard, start by including the .h of the libraries you need to declare your functions or to define structs, e.g. #include <stdlib.h> if you use size_t parameters.

Within the include guard, insert the structs, enums, ... you need exported

Within the include guard, insert the function declarations.

In every .c start by including its corresponding .h, then include other libraries needed to implement your functions, then put in the definitions.

Don't make a main.h or common.h, unless you have extremely good reasons for it (I know this will be commented against, but everyone has its style).

In main.c include what you need. You'll be including much less than you think.

Title: How to match .c and .h properly?


问:
Exporting Objects and Promises in NodeJS
I am trying to export a function that will let you put in a parameter (trading pair) and it will return the data for that trading pair. This is the code that creates a function that:

Accepts a parameter (trading pair).

Returns the data for that trading pair in the form of a Promise.

Then calls another function which processes that data.

```<code>// This function is exported and let's you feed in pairs you want data for - feeling proud.
function pullData(coinPair) {
  kc.getTicker({
    pair: coinPair
  }).then(returnData).catch(console.error)
}

// This function is the callback, which I believe means this function is called and fed the results of the Promise returned from 'kc.getTicker'.
// At first it just logs the data, but now I'll need to find a way to return the data as a usable array. Maybe use the 'return()' function?

function returnData(pairData) {
  // Nae Nae
  //return pairData;
  console.log(pairData);
}

//  Finally we export our hard work
exports.pullData = pullData;
</code>```

I now want to simply have the exported function return the data (and for this data to be usable by a callback function.

```<code>// Including important sub modules & config files
const tradeData = require('./example');
var config = require('./config');

// Log the config pairs (Method 1):
function logArrayElements(element, array) {
    console.log(element);
  }

config.pairs.forEach(logArrayElements);

// Was going to cycle through config pairs. However, I will instead have a base strategy that will be replicated for each pair and run side by side.

//console.log(tradeData.pullData('ETH-USDT'));
tradeData.pullData('ETH-USDT', calculations);

function calculations() {
    console.log(pairData);
}
</code>```

The relevant lines here are the including of the file ('./example') and the pitiful attempt at using the function with a callback down lower.

My goal is to be able to pass something like this:

```<code>tradeData.pullData('ETH-USDT', calculations);

function calculations() {
    // Calculations and logic here
}
</code>```

That may involve having '.then' simply return the data. I believe this would allow for a 'calculations' function to use the data after the asynchronous function finishes...

Any answers are greatly appreciated as I haven't been able to find guidance as to what I should do here.

答:
I'm not sure what it is you like pullData to return. you would like it to return only the data? So something like this:

```<code>function pullData(coinPair) {
  return kc.getTicker({
    pair: coinPair
  })
  .catch(console.error)  //.then(returnData)
}
</code>```

And then you'd like it to receive a calculations function that is performed on the data like this:

```<code>function pullData(coinPair,calculations) {
  return kc.getTicker({
    pair: coinPair
  }).then(calculations).catch(console.error)
}
</code>```

Now the caller can do:

```<code>pullData(pair,calculations);
</code>```

But the caller may ass well do:

```<code>pullData(par).then(calculations)
</code>```

I'm not sure what the benefit here is.

Body:
I am trying to export a function that will let you put in a parameter (trading pair) and it will return the data for that trading pair. This is the code that creates a function that:

Accepts a parameter (trading pair).

Returns the data for that trading pair in the form of a Promise.

Then calls another function which processes that data.

// This function is exported and let's you feed in pairs you want data for - feeling proud.
function pullData(coinPair) {
  kc.getTicker({
    pair: coinPair
  }).then(returnData).catch(console.error)
}

// This function is the callback, which I believe means this function is called and fed the results of the Promise returned from 'kc.getTicker'.
// At first it just logs the data, but now I'll need to find a way to return the data as a usable array. Maybe use the 'return()' function?

function returnData(pairData) {
  // Nae Nae
  //return pairData;
  console.log(pairData);
}

//  Finally we export our hard work
exports.pullData = pullData;

I now want to simply have the exported function return the data (and for this data to be usable by a callback function.

// Including important sub modules & config files
const tradeData = require('./example');
var config = require('./config');

// Log the config pairs (Method 1):
function logArrayElements(element, array) {
    console.log(element);
  }

config.pairs.forEach(logArrayElements);

// Was going to cycle through config pairs. However, I will instead have a base strategy that will be replicated for each pair and run side by side.

//console.log(tradeData.pullData('ETH-USDT'));
tradeData.pullData('ETH-USDT', calculations);

function calculations() {
    console.log(pairData);
}

The relevant lines here are the including of the file ('./example') and the pitiful attempt at using the function with a callback down lower.

My goal is to be able to pass something like this:

tradeData.pullData('ETH-USDT', calculations);

function calculations() {
    // Calculations and logic here
}

That may involve having '.then' simply return the data. I believe this would allow for a 'calculations' function to use the data after the asynchronous function finishes...

Any answers are greatly appreciated as I haven't been able to find guidance as to what I should do here.

Body:
I'm not sure what it is you like pullData to return. you would like it to return only the data? So something like this:

function pullData(coinPair) {
  return kc.getTicker({
    pair: coinPair
  })
  .catch(console.error)  //.then(returnData)
}

And then you'd like it to receive a calculations function that is performed on the data like this:

function pullData(coinPair,calculations) {
  return kc.getTicker({
    pair: coinPair
  }).then(calculations).catch(console.error)
}

Now the caller can do:

pullData(pair,calculations);

But the caller may ass well do:

pullData(par).then(calculations)

I'm not sure what the benefit here is.


问:
3 Collection Views on One View Controller
I have 3 collection views on 1 view controller.  I've tried a few of the other suggestions I've found on Stack but nothing seems to work.

All 3 Collection Views are in a separate cell of a HomeTableViewController.  I tried to create the outlet connection to the HomeTableViewController but I get the error Outlets cannot be connected to repeating content.

I've read many people being able to hook up their multiple collectionViews so I am a bit confused as to where I'm going wrong...

答:
You should create outlet in the UITableViewCell. Then you can provide tags to collectionViews in each cell in tableView:cellForRowAtIndexPath Method:

```<code>yourCell.collectionViewOutlet.tag = indexPath.row + 1000
</code>```

you should replace 1000 with Any Constant Integer if the tags conflict with tags of other views.

Then use these tags to differentiate all collectionviews in collectionview:cellForItemForIndexpath method:

```<code>if(collectionView.tag == 1000){
//Code for collection view in first row of the table
}
else if(collectionView.tag == 1001){
//Code for collection view in second row of the table
}
else if(collectionView.tag == 1002){
//Code for collection view in third row of the table
}
</code>```

You should also keep in mind to return number of items in collectionView:numberOfItemsInSection for each collection view just like above.

Tags make the life whole lot easier , don't they?
Happy Coding (Y)

Body:
You should create outlet in the UITableViewCell. Then you can provide tags to collectionViews in each cell in tableView:cellForRowAtIndexPath Method:

yourCell.collectionViewOutlet.tag = indexPath.row + 1000

you should replace 1000 with Any Constant Integer if the tags conflict with tags of other views.

Then use these tags to differentiate all collectionviews in collectionview:cellForItemForIndexpath method:

if(collectionView.tag == 1000){
//Code for collection view in first row of the table
}
else if(collectionView.tag == 1001){
//Code for collection view in second row of the table
}
else if(collectionView.tag == 1002){
//Code for collection view in third row of the table
}

You should also keep in mind to return number of items in collectionView:numberOfItemsInSection for each collection view just like above.

Tags make the life whole lot easier , don't they?
Happy Coding (Y)


问:
Pointer addition and element size
At: http://www.fredosaurus.com/notes-cpp/arrayptr/26arraysaspointers.html

Under: Pointer addition and element size

There is the following code:

```<code>// Assume sizeof(int) is 4.
int b[100];  // b is an array of 100 ints.
int* p;      // p is a a pointer to an int.
p = b;       // Assigns address of first element of b. Ie, &b[0]
p = p + 1;   // Adds 4 to p (4 == 1 * sizeof(int)). Ie, &b[1]
</code>```

How did "p" in the last line become "4"?

Thanks.

答:
(I assume that you mean "1" in the last line, not "p")

Pointer arithmetic in both C and C++ is a logical addition, not a numeric addition.  Adding one to a pointer means "produce a pointer to the object that comes in memory right after this one," which means that the compiler automatically scales up whatever you're incrementing the pointer with by the size of the object being pointed at.  This prevents you from having a pointer into the middle of an object, or a misaligned pointer, or both.

ContentLicense: CC BY-SA 4.0

Title: Pointer addition and element size

Body:
At: http://www.fredosaurus.com/notes-cpp/arrayptr/26arraysaspointers.html

Under: Pointer addition and element size

There is the following code:

// Assume sizeof(int) is 4.
int b[100];  // b is an array of 100 ints.
int* p;      // p is a a pointer to an int.
p = b;       // Assigns address of first element of b. Ie, &b[0]
p = p + 1;   // Adds 4 to p (4 == 1 * sizeof(int)). Ie, &b[1]

How did "p" in the last line become "4"?

Thanks.


问:
How to convert from unicode list to normal list in python/django
How can i convert this list:

```<code>list = [u"[u'book1', u'book2', u'book3']"]into this list:
</code>```

to:

```<code>[u'book1', u'book2', u'book3']
</code>```

I tried this :

```<code>n = ast.literal_eval(list)
</code>```

but i got this error:

ValueError: malformed string

what else can i do to change this list without "u"?

答:
ast.literal_eval takes as parameter a node or a string.
A list is neither. The first value in your example list is a string,
you can pass that:

```<code>alist = [u"[u'book1', u'book2', u'book3']"]
ast.literal_eval(alist[0])
# produces: ['book1', 'book2', 'book3']
</code>```

Body:
How can i convert this list:

list = [u"[u'book1', u'book2', u'book3']"]into this list:

to:

[u'book1', u'book2', u'book3']

I tried this :

n = ast.literal_eval(list)

but i got this error:

ValueError: malformed string

what else can i do to change this list without "u"?

Body:
ast.literal_eval takes as parameter a node or a string.
A list is neither. The first value in your example list is a string,
you can pass that:

alist = [u"[u'book1', u'book2', u'book3']"]
ast.literal_eval(alist[0])
# produces: ['book1', 'book2', 'book3']


问:
Find XML Element by attribute value using dynamic GPath Expression
Following is a sample XML:

```<code><root>
    <persons>
        <person gender="female">X</person>
        <person gender="female">Y</person>
        <person gender="male">Z</person>
    </persons>
</root>
</code>```

I want to get the element count which has gender="male" by using GPath.

I have following code:

```<code>def xml =
'''
    <root>
        <persons>
            <person gender="female">X</person>
            <person gender="female">Y</person>
            <person gender="male">Z</person>
        </persons>
    </root>
'''

def slurper = new XmlSlurper()
def parsedText = slurper.parseText(xml)
def locator = 'persons.person[@gender="male"]'

def elements = Eval.x(parsedText, "x.${locator}")

println elements.size()
</code>```

It is giving me error:

```<code>org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script1.groovy: 1: unexpected token: = @ line 1, column 25.
   x.persons.person[@gender="male"]
                           ^

1 error
</code>```

The code is only for demonstration purpose of the problem. In the actual case, I have a utility method which accepts an XML and a GPath and returns if there is any element can be found by the given GPath.

Update: 1

Following is the actual utility method which takes xml and locator (GPath) as args and check if there is any element whose path matches the provided locator.

```<code>public static void verifyElementExists(String xml, String locator) throws NoElementFoundException {
    def slurper = new XmlSlurper()
    def parsedText = slurper.parseText(xml)
    def elements = Eval.x(parsedText, "x.${locator}")

    if(elements.size() == 0) {
        throw new NoElementFoundException()
    }
}
</code>```

答:
Think you need

```<code>def locator = "persons.person.findAll { it.@gender == 'male' }"
</code>```

I'd avoid this if at all possible, using Eval isn't a safe path to walk

Body:
Following is a sample XML:

<root>
    <persons>
        <person gender="female">X</person>
        <person gender="female">Y</person>
        <person gender="male">Z</person>
    </persons>
</root>

I want to get the element count which has gender="male" by using GPath.

I have following code:

def xml =
'''
    <root>
        <persons>
            <person gender="female">X</person>
            <person gender="female">Y</person>
            <person gender="male">Z</person>
        </persons>
    </root>
'''

def slurper = new XmlSlurper()
def parsedText = slurper.parseText(xml)
def locator = 'persons.person[@gender="male"]'

def elements = Eval.x(parsedText, "x.${locator}")

println elements.size()

It is giving me error:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script1.groovy: 1: unexpected token: = @ line 1, column 25.
   x.persons.person[@gender="male"]
                           ^

1 error

The code is only for demonstration purpose of the problem. In the actual case, I have a utility method which accepts an XML and a GPath and returns if there is any element can be found by the given GPath.

Update: 1

Following is the actual utility method which takes xml and locator (GPath) as args and check if there is any element whose path matches the provided locator.

public static void verifyElementExists(String xml, String locator) throws NoElementFoundException {
    def slurper = new XmlSlurper()
    def parsedText = slurper.parseText(xml)
    def elements = Eval.x(parsedText, "x.${locator}")

    if(elements.size() == 0) {
        throw new NoElementFoundException()
    }
}

Body:
Think you need

def locator = "persons.person.findAll { it.@gender == 'male' }"

I'd avoid this if at all possible, using Eval isn't a safe path to walk


问:
rcpp - R session Aborted

```<code>library(Rcpp)
library(geoR)
elevationd=as.matrix(data.frame(xcoords=elevation$coords[,1],
ycoords=elevation$coords[,2], elev=elevation$data))
elevationd

cppFunction('void a(NumericMatrix data){
  int nr = data.nrow();
  int nc = data.ncol();
  NumericVector tmp;
  for (int i; i<nr; i++){
    tmp[i] = data(i,2);
  }
  NumericMatrix mat(nr, nr);
  for (int i; i<nr; i++){
    for (int j; j<nr; j++){
      mat(i,j) = (tmp[i] - tmp[j])*(tmp[i] - tmp[j]);
    }
  }
}')

a(elevationd)
</code>```

i have a r code like this.

But when i implement this, i got "R Session Aborted. R encountered a fatal error. The session was terminated." message.

but i Can't find any problem with my code.

I wonder if it is the problem of the hardware........ not my code T.T

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

thx to Dirk

This is my edited code.

```<code>cppFunction('NumericMatrix f1(NumericMatrix data){
  int nr = data.nrow();
  int nc = data.ncol();
  NumericMatrix mat(nr, nr);
  for (int i=0; i<nr; i++){
    for(int j=0; j<nr; j++){
      mat(i,j) = (data(i,2)-data(j,2))*(data(i,2)-data(j,2));
    }
  }
  return mat;
}')
</code>```

答:
Roland already gave you a good hint, you also had two types wrong and missed a size on the vector initialization.

Below is a repaired version, as a C++ file you can source with the relevant R code being executed automatically:

```<code>R> Rcpp::sourceCpp("/tmp/jiwon.cpp")

R> library(geoR)
--------------------------------------------------------------
 Analysis of Geostatistical Data
 For an Introduction to geoR go to http://www.leg.ufpr.br/geoR
 geoR version 1.7-5.2 (built on 2016-05-02) is now loaded
--------------------------------------------------------------

R> elevationd <- as.matrix(data.frame(xcoords=elevation$coords[,1],
+                                    ycoords=elevation$coords[,2],
+             .... [TRUNCATED]

R> str(elevationd)
 num [1:52, 1:3] 0.3 1.4 2.4 3.6 5.7 1.6 2.9 3.4 3.4 4.8 ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:52] "1" "2" "3" "4" ...
  ..$ : chr [1:3] "xcoords" "ycoords" "elev"

R> str(a(elevationd))
 num [1:52, 1:52] 0 5929 13225 32400 4900 ...
R>
</code>```

And here is the repaired code addressed a few of your errors:

```<code>#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]
NumericMatrix a(NumericMatrix data){
  int nr = data.nrow();
  int nc = data.ncol();
  NumericVector tmp(nr);
  for (int i=0; i<nr; i++){
    tmp[i] = data(i,2);
  }
  NumericMatrix mat(nr, nr);
  for (int i=0; i<nr; i++){
    for (int j=0; j<nr; j++){
      mat(i,j) = (tmp[i] - tmp[j])*(tmp[i] - tmp[j]);
    }
  }
  return mat;
}

/*** R
library(geoR)
elevationd <- as.matrix(data.frame(xcoords=elevation$coords[,1],
                                   ycoords=elevation$coords[,2],
                                   elev=elevation$data))
str(elevationd)
str(a(elevationd))
*/
</code>```

Title: rcpp - R session Aborted

Body:
library(Rcpp)
library(geoR)
elevationd=as.matrix(data.frame(xcoords=elevation$coords[,1],
ycoords=elevation$coords[,2], elev=elevation$data))
elevationd

cppFunction('void a(NumericMatrix data){
  int nr = data.nrow();
  int nc = data.ncol();
  NumericVector tmp;
  for (int i; i<nr; i++){
    tmp[i] = data(i,2);
  }
  NumericMatrix mat(nr, nr);
  for (int i; i<nr; i++){
    for (int j; j<nr; j++){
      mat(i,j) = (tmp[i] - tmp[j])*(tmp[i] - tmp[j]);
    }
  }
}')

a(elevationd)

i have a r code like this.

But when i implement this, i got "R Session Aborted. R encountered a fatal error. The session was terminated." message.

but i Can't find any problem with my code.

I wonder if it is the problem of the hardware........ not my code T.T

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

thx to Dirk

This is my edited code.

cppFunction('NumericMatrix f1(NumericMatrix data){
  int nr = data.nrow();
  int nc = data.ncol();
  NumericMatrix mat(nr, nr);
  for (int i=0; i<nr; i++){
    for(int j=0; j<nr; j++){
      mat(i,j) = (data(i,2)-data(j,2))*(data(i,2)-data(j,2));
    }
  }
  return mat;
}')

Body:
Roland already gave you a good hint, you also had two types wrong and missed a size on the vector initialization.

Below is a repaired version, as a C++ file you can source with the relevant R code being executed automatically:

R> Rcpp::sourceCpp("/tmp/jiwon.cpp")

R> library(geoR)
--------------------------------------------------------------
 Analysis of Geostatistical Data
 For an Introduction to geoR go to http://www.leg.ufpr.br/geoR
 geoR version 1.7-5.2 (built on 2016-05-02) is now loaded
--------------------------------------------------------------

R> elevationd <- as.matrix(data.frame(xcoords=elevation$coords[,1],
+                                    ycoords=elevation$coords[,2],
+             .... [TRUNCATED]

R> str(elevationd)
 num [1:52, 1:3] 0.3 1.4 2.4 3.6 5.7 1.6 2.9 3.4 3.4 4.8 ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:52] "1" "2" "3" "4" ...
  ..$ : chr [1:3] "xcoords" "ycoords" "elev"

R> str(a(elevationd))
 num [1:52, 1:52] 0 5929 13225 32400 4900 ...
R>

And here is the repaired code addressed a few of your errors:

#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]
NumericMatrix a(NumericMatrix data){
  int nr = data.nrow();
  int nc = data.ncol();
  NumericVector tmp(nr);
  for (int i=0; i<nr; i++){
    tmp[i] = data(i,2);
  }
  NumericMatrix mat(nr, nr);
  for (int i=0; i<nr; i++){
    for (int j=0; j<nr; j++){
      mat(i,j) = (tmp[i] - tmp[j])*(tmp[i] - tmp[j]);
    }
  }
  return mat;
}

/*** R
library(geoR)
elevationd <- as.matrix(data.frame(xcoords=elevation$coords[,1],
                                   ycoords=elevation$coords[,2],
                                   elev=elevation$data))
str(elevationd)
str(a(elevationd))
*/