text:
Q: RuntimeException on Google play pre-launch report test Im having a RuntimeException in some espresso test runned on the google play pre-launch console.
The courios thing is only is failing for devices that have Afghanistan/Persiang language (locale = fa_FA)
Notice de persian characters "۱۳" that stands for "13"
devices tha failed image
FATAL EXCEPTION: Thread-4
    Process: com.inmar.android.app.snap, PID: 19516
    java.lang.RuntimeException: java.lang.RuntimeException: Error in evaluationEvaluation: status: ۱۳ value: {message=Invalid or unexpected token} hasMessage: true message: Invalid or unexpected token
        at androidx.test.espresso.web.sugar.Web$WebInteraction$ExceptionPropagator.<init>(Web.java:2)
        at androidx.test.espresso.web.sugar.Web$WebInteraction.doEval(Web.java:10)
        at androidx.test.espresso.web.sugar.Web$WebInteraction.perform(Web.java:1)
        at androidx.test.tools.crawler.platform.hybrid.HybridInteractionController.swipe(HybridInteractionController.java:15)
        at androidx.test.tools.crawler.platform.ActionExecutor.execute(ActionExecutor.java:45)
        at androidx.test.tools.crawler.platform.ActionExecutor.performAction(ActionExecutor.java:4)
        at androidx.test.tools.crawler.platform.RemotePlatform.handlePerformAction(RemotePlatform.java:22)
        at androidx.test.tools.crawler.platform.RemotePlatform.messageLoop(RemotePlatform.java:59)
        at androidx.test.tools.crawler.platform.RemotePlatform.lambda$startCrawlAndWaitUntilFinished$0$androidx-test-tools-crawler-platform-RemotePlatform(RemotePlatform.java:1)
        at androidx.test.tools.crawler.platform.RemotePlatform$$ExternalSyntheticLambda1.run(Unknown Source:6)
        at java.lang.Thread.run(Thread.java:764)
    Caused by: java.lang.RuntimeException: Error in evaluationEvaluation: status: ۱۳ value: {message=Invalid or unexpected token} hasMessage: true message: Invalid or unexpected token
        at androidx.test.espresso.web.model.SimpleAtom.handleBadEvaluation(SimpleAtom.java:1)
        at androidx.test.espresso.web.model.SimpleAtom.transform(SimpleAtom.java:2)
        at androidx.test.espresso.web.model.SimpleAtom.transform(SimpleAtom.java:3)
        at androidx.test.espresso.web.action.AtomAction$3.apply(AtomAction.java:1)
        at androidx.test.espresso.web.action.AtomAction$3.apply(AtomAction.java:2)
        at androidx.test.tools.crawler.obfuscated.bl.f.doTransform(AbstractTransformFuture.java:1)
        at androidx.test.tools.crawler.obfuscated.bl.f.doTransform(AbstractTransformFuture.java:2)
        at androidx.test.tools.crawler.obfuscated.bl.g.run(AbstractTransformFuture.java:9)
        at androidx.test.tools.crawler.obfuscated.bl.i.execute(DirectExecutor.java:1)
        at androidx.test.tools.crawler.obfuscated.bl.a.executeListener(AbstractFuture.java:1)
        at androidx.test.tools.crawler.obfuscated.bl.a.complete(AbstractFuture.java:11)
        at androidx.test.tools.crawler.obfuscated.bl.a.set(AbstractFuture.java:2)
        at androidx.test.tools.crawler.obfuscated.bl.ad.set(SettableFuture.java:1)
        at androidx.test.espresso.web.action.AtomAction$1.setResult(AtomAction.java:1)
        at androidx.test.espresso.web.action.AtomAction$2.run(AtomAction.java:1)
        at androidx.test.tools.crawler.obfuscated.bl.i.execute(DirectExecutor.java:1)
        at androidx.test.tools.crawler.obfuscated.bl.a.executeListener(AbstractFuture.java:1)
        at androidx.test.tools.crawler.obfuscated.bl.a.complete(AbstractFuture.java:11)
        at androidx.test.tools.crawler.obfuscated.bl.a.set(AbstractFuture.java:2)
        at androidx.test.tools.crawler.obfuscated.bl.f.setResult(AbstractTransformFuture.java:1)
        at androidx.test.tools.crawler.obfuscated.bl.g.run(AbstractTransformFuture.java:12)
        at androidx.test.tools.crawler.obfuscated.bl.i.execute(DirectExecutor.java:1)
        at androidx.test.tools.crawler.obfuscated.bl.a.executeListener(AbstractFuture.java:1)
        at androidx.test.tools.crawler.obfuscated.bl.a.complete(AbstractFuture.java:11)
        at androidx.test.tools.crawler.obfuscated.bl.a.set(AbstractFuture.java:2)
        at androidx.test.espresso.web.action.JavascriptEvaluation$ValueCallbackFuture.onReceiveValue(JavascriptEvaluation.java:1)
        at ul.onResult(Unknown Source:2)
        at org.chromium.android_webview.AwContents.a(SourceFile:960)
        at axK.run(Unknown Source:4)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6846)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:883)


text:
Q: Перегрузка операторов сложения, вычитания и умножения для объектов класса Есть класс тестовых вопросов. Объявляются 3 объекта этого класса. В 1 объект записывается первый блок вопросов значения записываются в 1 массив, во 2 - второй блок вопросов записывается во 2 массив, а в 3 объект записывается результат операций над объектами.
Как вообще можно реализовать операцию слияния, вычитания и умножения именно для объектов класса ?
Сравнение идет по названию вопроса.
Должно быть что-то вроде если идет операция сложения, то в 3 объект класса записываются все значения первого массива+ значения 2 массива,которых нет в первом.
Если идет операция вычитания, то в 3 объект записываются все значения первого массива которых нет во 2.
Пытался реализовать перегрузку оператора сложения, но вообще не понял как она реализуется.
Вот код, кто может помочь с этим огромное спасибо.
#include <iostream>
struct card
{
    char quest[512];
    char fst[512];
    char scd[512];
    char thd[512];
    char foh[512];
    char fth[512];
    int num;
    int balls;
};

struct card M[30];
struct card S[30];
struct card tmp;
int i, j, n, k;
using namespace std;

class Test : public card
{
public:
    void otch(card* M, int& N)
    {

        cout << '\n';
        int c = 1;

        for (int i = 0; i < N; i++) {
            cout << c << "-ыйВопрос : " << M[i].quest << endl;
            cout << "1-ый вариант ответа: " << M[i].fst << endl;
            cout << "2-ый вариант ответа: " << M[i].scd << endl;
            cout << "3-ый вариант ответа: " << M[i].thd << endl;
            cout << "4-ый вариант ответа: " << M[i].foh << endl;
            cout << "5-ый вариант ответа: " << M[i].fth << endl;
            cout << "Правильный Ответ: " << M[i].num << endl;
            c++;
        }

        cout << '\n';
        system("pause");

    }

    void add(card* M, int& N)
    {
        system("CLS");
        int c = 1;

        for (int i = 0; i < N; i++)
        {
            cout << "Введите данные о " << c << " вопросе. \n";
            cout << "Вопрос\n";
            while (*M[i].quest == 0) {
                cin.getline(M[i].quest, 512);
            }
            cout << "1 вариант ответа\n";
            cin.getline(M[i].fst, 512);
            cout << "2 вариант ответа\n";
            cin.getline(M[i].scd, 512);
            cout << "3 вариант ответа\n";
            cin.getline(M[i].thd, 512);
            cout << "4 вариант ответа\n";
            cin.getline(M[i].foh, 512);
            cout << "5 вариант ответа\n";
            cin.getline(M[i].fth, 512);
            cout << "Номер правильного ответа\n";
            cin >> M[i].num;
            cin.get();
            cout << endl;
            c++;
        }
        cout << "Введено максимальное кол-во записей.\n";
        system("pause");
        system("CLS");
    }

};

 ```
 Test operator+(Test p1,Test p2) {
        return new Test(p1.value + p2.value);
    };
 ```

int main()
{
    setlocale(LC_ALL, "");

    Test p1;
    Test p2;
    Test p3;

    int N, K,v;
    cout << "Введите размер Теста 1 :\n";
    cin >> N;
    cout << "Введите размер Теста 2 :\n";
    cin >> K;
    system("CLS");

    p1.add(M, N);
    p2.add(S, K);
    system("CLS");

    cout << "Первый Тест: \n";
    p1.otch(M, N);
    system("CLS");
    cout << "Второй Тест: \n";
    p1.otch(S, K);
    system("CLS");

    for (;;)
    {

        printf("\n[1 - слияние двух тестовых наборов]");
        printf("\n[2 - разность двух тестовых наборов]");
        printf("\n[3 - пересечение двух тестовых наборов]");
        printf("\n[0 - Exit]");
        printf("\n Выберите номер в меню:");
        std::cin >> v;
        switch (v)
        {
        case 1:
            `c=p1+p2;`

            break;
        case 2:
            break;
        case 3:
            break;
        case 0:exit(1);
        default:
            cout << "Выберите существующий пункт меню." << endl;
            system("pause");
            break;
        }
    }
    system("pause");

    system("PAUSE");
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to solve this equation with three variables arithmetically? How can we find the sum of $x$, $y$, and $z$ arithmetically?
$$x+y=6$$
$$z+y=10$$
$$x+y+z=?$$
Some things I have tried:
$$y=6-x$$
$$y=10-z$$
$$6-x=10-z$$
$$z-x=4$$
or
$$x+2y+z=16$$
or
$$x=6-y$$
$$z=10-y$$
$$x+z=6-y+10-y$$
$$x+z=16-2y$$
Will these lead me anywhere?

A: Just having $x+y=6$ and $y+z=10$ is not enough information to determine $x+y+z$.
For example, we could have $(x,y,z)=(6,0,10)$ with sum $16$, or $(x,y,z)=(-10,16,-6)$ with sum $0$.
In general you can get any sum you want by setting $(x,y,z)=(t-10,16-t,t-6)$, giving a sum of $t$.
Even if, for example, you want $x$, $y$ and $z$ all to be positive, you can still get any $t$ strictly between $10$ and $16$.

A: Another way you can solve this is using matrix row operations.
Place the systems of equations in to a 3x4 matrix and solve.
$$ \left[
    \begin{array}{ccc|c}
      1&2&0&6\\
      0&1&1&10\\
      1&1&1&a
      \end{array}
\right] $$
Where $a = ?$
And the columns represent $x,y, z$ respectively.


text:
Q: Failed to create Java Virtual Machine after updating. :( I've got this message (Failed to create the Java Virtual Machine) after updating some installed plugins.
I have no idea that how can i fix it ?
Please help me guys :(
I'm using eclipse Oxygen.(upgraded few weeks ago)
beneath lines are my eclipse.ini

1-startup
  2 ../Eclipse/plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar
  3 --launcher.library
  4 ../Eclipse/plugins/org.eclipse.equinox.launcher.cocoa.macosx.x86_64_1.1.550.    v20170928-1359
  5 -product
  6 org.eclipse.epp.package.jee.product
  7 -showsplash
  8 org.eclipse.epp.package.common
  9 --launcher.defaultAction
 10 openFile
 11 --launcher.defaultAction
 12 openFile
 13 --launcher.appendVmargs
 14 -vmargs
 15 -javaagent:../Eclipse/lombok.jar
 16 -javaagent:/Applications/Eclipse.app/Contents/Eclipse/plugins/com.zeroturnar    ound.eclipse.optimizer.plugin_1.0.11/agent/eclipse-optimizer-agent.jar
 17 -server
 18 -XX:PermSize=256m
 19 -XX:MaxPermSize=256m
 20 -XX:+UseParallelGC
 21 -Xverify:none
 22 -Dosgi.requiredJavaVersion=1.8
 23 -Dosgi.instance.area.default=@user.home/eclipse-workspace
 24 -XX:+UseG1GC
 25 -XX:+UseStringDeduplication
 26 --add-modules=ALL-SYSTEM
 27 -XstartOnFirstThread
 28 -Dorg.eclipse.swt.internal.carbon.smallFonts
 29 -Dosgi.requiredJavaVersion=1.8
 30 -Xms512m
 31 -Xmx3072m
 32 --add-modules=ALL-SYSTEM
 33 -Xdock:icon=../Resources/Eclipse.icns
 34 -XstartOnFirstThread
 35 -Dorg.eclipse.swt.internal.carbon.smallFonts

A: This might come when the java upgrade happens in the machine. verify eclipse.ini file and set -vmargs
-Dosgi.requiredJavaVersion=1.8 (which is the latest version)

A: Follow the following steps, It may help you.

i.stack.imgur.com/PtDpw.png
Also visit: Setting the correct PATH for Eclipse to update eclipse.ini

A: first, i commented -vmargs line of eclipse.ini
then i faced problem that lombok doesn't work for eclipse Oxygen.1A
you will need to launch eclipse on the command line on Terminal..ETC.

./eclipse -vmargs -javaagent:../Eclipse/lombok.jar

Then you can check installed lombok from 'About Eclipse'
but i don't know how can i activate lombok as eclipse icon launching.


text:
Q: how to add images for pivot item header Am developing a simple app for learning pivot control in wp7.
can we add images for pivot item instead of text in header(red mark area in bellow image ).
is it possible to  add images, please suggest me
my xaml code is:
 <Grid x:Name="LayoutRoot" Background="Transparent">
    <!--Pivot Control-->
    <controls:Pivot Title="MY APPLICATION" Name="mainPivot">
        <!--Pivot item one-->
        <controls:PivotItem Header="item1">
            <Grid>
                <Image Source="/SchoolList;component/Gallery/child.jpg"/>
            </Grid>
        </controls:PivotItem>

        <!--Pivot item two-->
        <controls:PivotItem Header="item2">
            <Grid>
                <Image Source="/SchoolList;component/Gallery/class.jpg"/>
            </Grid>
        </controls:PivotItem>
    </controls:Pivot>
</Grid>

thanks in advance

A: use this tip :
<phone:Pivot>
        <phone:Pivot.HeaderTemplate>
            <DataTemplate>
                <Image Source="{Binding}" /> // important
            </DataTemplate>
        </phone:Pivot.HeaderTemplate>
</phone:Pivot>

and then set your Pivot Item header as
<phone:PivotItem Header="path-to-image" >

A: Yes it is. Simply use HeaderTemplate
<Pivot>
    <Pivot.HeaderTemplate>
        <DataTemplate>
            <Image ... />
        </DataTemplate>
    </Pivot.HeaderTemplate>
</Pivot>

May I also add that while this is generally possible, it is not recommended for the general use. Unless you need pivot functionality for something completely different. It is somewhat non intuitive.

A: with the Idea of @toni petrina i added images to the HeaderTemplate to the pivot control using data binding. am implemented image gallery in my app using pivot with images in header template gives great look and feel
Xaml code is :
<controls:Pivot Title="Photo Gallery" Name="mainPivot" ItemsSource="{Binding PivotImages}">
        <controls:Pivot.HeaderTemplate>
            <DataTemplate>
                <Image Name="play" Source="{Binding imgSrc}" Height="80" Width="120" Margin="0,10,0,0"/>
            </DataTemplate>
        </controls:Pivot.HeaderTemplate>
        <controls:Pivot.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Image Name="mainImage" Source="{Binding imgSrc}" />
                </Grid>
            </DataTemplate>
        </controls:Pivot.ItemTemplate>
</controls:Pivot>

and i have created a simple class with one string property to save the images source and prepared a List and assigned to the pivot ItemsSource on page loaded event
mainPivot.ItemsSource = items; // items is the list with image sources


text:
Q: How do you fix: "UnboundLocalError: local variable 'events' referenced before assignment" in pygame? I am making a button on my credits screen to go back to the start screen when pressed. I have a button function with 'events' as a parameter, but when I use it on my credits scene. However, this error occurs: "UnboundLocalError: local variable 'events' referenced before assignment". I don't understand, 'events' isn't even a variable. Does anyone know how to fix this?
  File "/Users/qingduliu/PycharmProjects/Pygame3/Shoot 'em Up.py", line 355, in credits
button(events, 10, 10, 120, 60, WHITE, GRAY, 'back')
UnboundLocalError: local variable 'events' referenced before assignment

Code
def button(events, x, y, width, height, ic, ac, action=None):

    mouse = pygame.mouse.get_pos()
    # print(mouse)

    if x + width > mouse[0] > x and y + height > mouse[1] > y:
        pygame.draw.rect(screen, ac, (x, y, width, height), 0)
        if events.type == pygame.MOUSEBUTTONDOWN and action is not None:
            if action == 'play':
                game_loop()
            elif action == 'credits':
                credits()
            elif action == 'instructions':
                instructions()
            elif action == 'back':
                start_screen()
            elif action == 'quit':
                pygame.quit()
                quit()
    else:
        pygame.draw.rect(screen, ic, (x, y, width, height), 0)

def start_screen():

    start = True

    while start:

        clock.tick(FPS)
        for events in pygame.event.get():
            if events.type == pygame.QUIT:
                pygame.quit()
                quit()

        screen.blit(background, background_rect)
        pygame.transform.scale(player_img, (50, 38))
        player_img.set_colorkey(BLACK)
        screen.blit(player_img, (10, HEIGHT - 120))
        screen.blit(player_img, (WIDTH - 110, HEIGHT - 120))
        bullet_img.set_colorkey(BLACK)
        screen.blit(bullet_img, (55, 400))
        screen.blit(bullet_img, (415, 400))
        screen_meteor.set_colorkey(BLACK)
        screen.blit(screen_meteor, (5, 220))
        screen.blit(screen_meteor, (WIDTH - 105, 220))
        boss_img.set_colorkey(BLACK)
        pygame.transform.scale(boss_img, (50, 38))
        screen.blit(boss_img, (190, 25))

        button(events, 180, 285, 120, 60, BLUE, LIGHT_BLUE, 'play')
        button(events, 202, HEIGHT - 150, 80, 40, WHITE, GRAY, 'quit')
        button(events, 310, 45, 140, 30, WHITE, GRAY, 'credits')
        button(events, 20, 45, 140, 30, WHITE, GRAY, 'instructions')

        draw_text(screen, "Shoot 'Em Up", 80, WIDTH / 2, HEIGHT / 4, WHITE)
        draw_text(screen, "Instructions", 30, 90, 53, BLACK)
        draw_text(screen, "Credits", 35, 378, 50, BLACK)
        draw_text(screen, "Play", 55, WIDTH / 2, HEIGHT / 2, WHITE)
        draw_text(screen, "Quit", 30, WIDTH / 2, HEIGHT - 137, BLUE)

        pygame.display.flip()

def credits():

    credits = True

    while credits:

        clock.tick(FPS)
        for events in pygame.event.get():
            if events.type == pygame.QUIT:
                pygame.quit()
                quit()

        screen.blit(background, background_rect)
        draw_text(screen, "Credits", 100, WIDTH / 2, 15, WHITE)
        draw_text(screen, "Game Template:", 60, WIDTH / 2, 95, WHITE)
        draw_text(screen, "Kids Can Code, Shmup, Chris Bradfield", 35, WIDTH / 2, 155, WHITE)
        draw_text(screen, "Youtube Channel", 30, WIDTH / 2, 195, WHITE)
        draw_text(screen, "https://www.youtube.com/channel/UCNaPQ5uLX5iIEHUCLmfAgKg", 20, WIDTH / 2, 220, WHITE)
        draw_text(screen, "Blog", 30, WIDTH / 2, 245, WHITE)
        draw_text(screen, "http://kidscancode.org/blog/tags/pygame/", 20, WIDTH / 2, 270, WHITE)
        draw_text(screen, "Music:", 60, WIDTH / 2, 300, WHITE)
        draw_text(screen, "Frozen Jam by tgfcoder", 45, WIDTH / 2, 345, WHITE)
        draw_text(screen, "Twitter", 30, WIDTH / 2, 380, WHITE)
        draw_text(screen, "<https://twitter.com/tgfcoder>", 20, WIDTH / 2, 403, WHITE)
        draw_text(screen, "licensed under CC-BY-3 <http://creativecommons.org/licenses/by/3.0/>", 15, WIDTH / 2, 425, WHITE)
        draw_text(screen, "Art:", 60, WIDTH / 2, 450, WHITE)
        draw_text(screen, "Kenney.nl", 35, WIDTH / 2, 490, WHITE)
        draw_text(screen, "https://opengameart.org/", 20, WIDTH / 2, 520, WHITE)
        draw_text(screen, "Background https://imgur.com/bHiPMju by Chris Bradfield", 20, WIDTH / 2, 540, WHITE)
        draw_text(screen, "Thank You for all your help and hard work!", 32, WIDTH / 2, 560, RED)

        button(events, 10, 10, 120, 60, WHITE, GRAY, 'back')
        draw_text(screen, "Back", 25, 13, 13, WHITE)

        pygame.display.flip()

A:  button(events, 180, 285, 120, 60, BLUE, LIGHT_BLUE, 'play')

In your first code block you reference events outside of the for loop which defines the events variable

A: You have to move buttons to events loop because buttons have to check every event.
Because you use function which check collision with mouse and draw button in one code so you have to move event loop to buttons.
    clock.tick(FPS)

    # - draw background, etc. -

    screen.blit(background, background_rect)
    pygame.transform.scale(player_img, (50, 38))
    player_img.set_colorkey(BLACK)
    screen.blit(player_img, (10, HEIGHT - 120))
    screen.blit(player_img, (WIDTH - 110, HEIGHT - 120))
    bullet_img.set_colorkey(BLACK)
    screen.blit(bullet_img, (55, 400))
    screen.blit(bullet_img, (415, 400))
    screen_meteor.set_colorkey(BLACK)
    screen.blit(screen_meteor, (5, 220))
    screen.blit(screen_meteor, (WIDTH - 105, 220))
    boss_img.set_colorkey(BLACK)
    pygame.transform.scale(boss_img, (50, 38))
    screen.blit(boss_img, (190, 25))

    # - buttons - events + draw  -

    for events in pygame.event.get():
        if events.type == pygame.QUIT:
            pygame.quit()
            quit()

        button(events, 180, 285, 120, 60, BLUE, LIGHT_BLUE, 'play')
        button(events, 202, HEIGHT - 150, 80, 40, WHITE, GRAY, 'quit')
        button(events, 310, 45, 140, 30, WHITE, GRAY, 'credits')
        button(events, 20, 45, 140, 30, WHITE, GRAY, 'instructions')

    # - draw text on buttons -

    draw_text(screen, "Shoot 'Em Up", 80, WIDTH / 2, HEIGHT / 4, WHITE)
    draw_text(screen, "Instructions", 30, 90, 53, BLACK)
    draw_text(screen, "Credits", 35, 378, 50, BLACK)
    draw_text(screen, "Play", 55, WIDTH / 2, HEIGHT / 2, WHITE)
    draw_text(screen, "Quit", 30, WIDTH / 2, HEIGHT - 137, BLUE)

    # - send all on screen -

    pygame.display.flip()

Code is weird because now it draws buttons many times - for every event. But to change it you would have to split button into two functions or create class Button with two functions - draw() and handle_event()

EDIT: you could try click = pygame.mouse.get_pressed() and lick[0] == 1 instead of events so it doesn't have to be in for events loop but it can make problem when you remove button and put new one in the same place. Python will do it so fast that you will still keep button pressed and python will think that you pressed new button.
def button(x, y, width, height, ic, ac, action=None):

    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    # print(mouse)

    if x + width > mouse[0] > x and y + height > mouse[1] > y:
        pygame.draw.rect(screen, ac, (x, y, width, height), 0)
        if click[0] == 1 and action is not None:
            if action == 'play':
                game_loop()
            elif action == 'credits':
                credits()
            elif action == 'instructions':
                instructions()
            elif action == 'back':
                start_screen()
            elif action == 'quit':
                pygame.quit()
                quit()
    else:
        pygame.draw.rect(screen, ic, (x, y, width, height), 0)

You can assign to action function's name instead of text '"credits","instruction"ect. and then you can run it asaction()`
def button(x, y, width, height, ic, ac, action=None):

    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    # print(mouse)

    if x + width > mouse[0] > x and y + height > mouse[1] > y:
        pygame.draw.rect(screen, ac, (x, y, width, height), 0)
        if click[0] == 1 and action is not None:
            action()
    else:
        pygame.draw.rect(screen, ic, (x, y, width, height), 0)

button(180, 285, 120, 60, BLUE, LIGHT_BLUE, game_loop)
button(310, 45, 140, 30, WHITE, GRAY, credits)
button(20, 45, 140, 30, WHITE, GRAY, instructions)

button(202, HEIGHT - 150, 80, 40, WHITE, GRAY, game_quit)

def game_quit():
    pygame.quit()
    quit()

button(..., start_screen)


text:
Q: Convert array of links into links - React Im new to React. Im trying to convert an array contains links into something that will show the links in order in the website.
something like this:
external_references = ["https://google.com", "https://en.wikipedia.org/wiki/Wiki"]

into something to show up in the server like this:
external_references:
https://google.com(link)
https://en.wikipedia.org/wiki/Wiki(link)

I tried to do the following code I found but it failed to work:
External_references:

 {external_references.forEach(link => {
                                return new DOMParser().parseFromString(link, "text/xml");
                            })}

A: just
{external_references.map((reference, i) => {
  return(

   {reference}

);
})}

A: you can try the map function:

external_references:

{external_references.map(link=>{
     return

               {link}

     }
}

I recomend you as a good practice using the link as a key, since each of them should be different.

A: You can use the Array.map function.
 External_references:

  {
   external_references.map(link, i) => {

     {link}

   }
  }


text:
Q: Session affinity cookie not working anymore (Kubernetes with Nginx ingress) An upgrade of our Azure AKS - Kubernetes environment to Kubernetes version 1.19.3 forced me to also upgrade my Nginx helm.sh/chart to nginx-ingress-0.7.1. As a result I was forced to change the API version definition to networking.k8s.io/v1 since my DevOps pipeline failed accordingly (a warning for old API resulting in an error). However, now I have the problem that my session affinity annotation is ignored and no session cookies are set in the response.
I am desperately changing names, trying different unrelated blog posts to somehow fix the issue.
Any help would be really appreciated.
My current nginx yaml (I have removed status/managed fields tags to enhance readability):
kind: Deployment
apiVersion: apps/v1
metadata:
  name: nginx-ingress-infra-nginx-ingress
  namespace: ingress-infra
  labels:
    app.kubernetes.io/instance: nginx-ingress-infra
    app.kubernetes.io/managed-by: Helm
    app.kubernetes.io/name: nginx-ingress-infra-nginx-ingress
    helm.sh/chart: nginx-ingress-0.7.1
  annotations:
    deployment.kubernetes.io/revision: '1'
    meta.helm.sh/release-name: nginx-ingress-infra
    meta.helm.sh/release-namespace: ingress-infra
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx-ingress-infra-nginx-ingress
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: nginx-ingress-infra-nginx-ingress
      annotations:
        prometheus.io/port: '9113'
        prometheus.io/scrape: 'true'
    spec:
      containers:
        - name: nginx-ingress-infra-nginx-ingress
          image: 'nginx/nginx-ingress:1.9.1'
          args:
            - '-nginx-plus=false'
            - '-nginx-reload-timeout=0'
            - '-enable-app-protect=false'
            - >-
              -nginx-configmaps=$(POD_NAMESPACE)/nginx-ingress-infra-nginx-ingress
            - >-
              -default-server-tls-secret=$(POD_NAMESPACE)/nginx-ingress-infra-nginx-ingress-default-server-secret
            - '-ingress-class=infra'
            - '-health-status=false'
            - '-health-status-uri=/nginx-health'
            - '-nginx-debug=false'
            - '-v=1'
            - '-nginx-status=true'
            - '-nginx-status-port=8080'
            - '-nginx-status-allow-cidrs=127.0.0.1'
            - '-report-ingress-status'
            - '-external-service=nginx-ingress-infra-nginx-ingress'
            - '-enable-leader-election=true'
            - >-
              -leader-election-lock-name=nginx-ingress-infra-nginx-ingress-leader-election
            - '-enable-prometheus-metrics=true'
            - '-prometheus-metrics-listen-port=9113'
            - '-enable-custom-resources=true'
            - '-enable-tls-passthrough=false'
            - '-enable-snippets=false'
            - '-ready-status=true'
            - '-ready-status-port=8081'
            - '-enable-latency-metrics=false'

My ingress configuration of the service name "account":
kind: Ingress
apiVersion: networking.k8s.io/v1beta1
metadata:
  name: account
  namespace: infra
  resourceVersion: '194790'
  labels:
    app.kubernetes.io/managed-by: Helm
  annotations:
    kubernetes.io/ingress.class: infra
    meta.helm.sh/release-name: infra
    meta.helm.sh/release-namespace: infra
    nginx.ingress.kubernetes.io/affinity: cookie
    nginx.ingress.kubernetes.io/proxy-buffer-size: 128k
    nginx.ingress.kubernetes.io/proxy-buffering: 'on'
    nginx.ingress.kubernetes.io/proxy-buffers-number: '4'
spec:
  tls:
    - hosts:
        - account.infra.mydomain.com
      secretName: my-default-cert **this is a self-signed certificate with cn=account.infra.mydomain.com
  rules:
    - host: account.infra.mydomain.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              serviceName: account
              servicePort: 80
status:
  loadBalancer:
    ingress:
      - ip: 123.123.123.123 **redacted**

My account service yaml
kind: Service
apiVersion: v1
metadata:
  name: account
  namespace: infra
  labels:
    app.kubernetes.io/instance: infra
    app.kubernetes.io/managed-by: Helm
    app.kubernetes.io/name: account
    app.kubernetes.io/version: latest
    helm.sh/chart: account-0.1.0
  annotations:
    meta.helm.sh/release-name: infra
    meta.helm.sh/release-namespace: infra
spec:
  ports:
    - name: http
      protocol: TCP
      port: 80
      targetPort: 80
  selector:
    app.kubernetes.io/instance: infra
    app.kubernetes.io/name: account
  clusterIP: 10.0.242.212
  type: ClusterIP
  sessionAffinity: ClientIP **just tried to add this setting to the service, but does not work either**
  sessionAffinityConfig:
    clientIP:
      timeoutSeconds: 10800
status:
  loadBalancer: {}

A: Ok, the issue was not related to any configuration shown above. The debug logs of the nginx pods were full of error messages in regards to the kube-control namespaces. I was removing the Nginx helm chart completely and used the repositories suggested by Microsoft:
https://learn.microsoft.com/en-us/azure/aks/ingress-own-tls
# Create a namespace for your ingress resources
kubectl create namespace ingress-basic

# Add the ingress-nginx repository
helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx

# Use Helm to deploy an NGINX ingress controller
helm install nginx-ingress ingress-nginx/ingress-nginx \
    --namespace ingress-basic \
    --set controller.replicaCount=2 \
    --set controller.nodeSelector."beta\.kubernetes\.io/os"=linux \
    --set defaultBackend.nodeSelector."beta\.kubernetes\.io/os"=linux


text:
Q: How will self-hosted WordPress work with Google Page Speed Service? Google announced Page Speed Service, jumping on bandwagon of all-in-one site optimization and CDN.

*

*What are the potential issues, when configuring self-hosted WordPress for it?

*How will setting up reference domain work with WP? Considering that is required for Google to pull content, but public site URL will be different.

*Will it be possible to set it up with multisite?

*Should static caching plugins be left enabled or disabled for better compatibility?

*How will it work with wp-admin and Ajax? Should those be blacklisted in service settings?
PS this is intended to be large reference question, so feel free to edit in your own questions on subject

A: Potential Issues
Google's Page Speed service does not work with "naked domains". That is, it will not work with just "example.com". The domain name must have a subdomain in front of it, such as "www.example.com".
This is due to a limitation on Google's implementation of the Page Speed service, which requires you to set up a CNAME record in your DNS. This is not a generic limitation of the Page Speed system itself, and you can use the open-source mod_pagespeed to achieve the same ends, if you have that level of access to your webhost.
So if you do attempt to use the Page Speed service, migrate your entire site to a subdomain setup first. Note that this will affect subdomain installations of multisite setups.
Reference Domains
The reference domain is only used for DNS lookups.
For example, say I'm moving a site at example.com onto their service. The domain example.com lives on the IP address 1.2.3.4.
Now, Google Page Speed service needs to know where your actual site is. To do this, they want you to set up a reference domain at ref.example.com pointing to 1.2.3.4.
But, they're only using this to get the IP address. When their system actually contacts your domain, it's talking to 1.2.3.4 but setting the Host: header to example.com, not to ref.example.com.
So basically, WordPress sees no difference here. It will behave normally. It need know zero about the reference domain.
MultiSite Considerations
Multisite will work fine with Google's Page Speed service, however only on a subdirectory setup. Subdomain-based setups will not work at all.
Google's Page speed service provides proxy services for one domain/site only. However, a multisite in subdirectory configuration essentially is one domain/site as far as Google cares.
If you're using multisite with different subdomain names, Google Page Speed service will not work due to their methodology. The requirement for a CNAME record in the DNS eliminates this. You can, however, use the open-source mod_pagespeed instead, which does the same thing but on your own servers instead of through Google's proxy.
If you're using multiple domain names with domain mapping, Google is going to consider that to be completely separate sites and will charge or require setup for them accordingly.
Static Caching
Static Caching plugins can be used with Google Page Speed service, as in this case Google is really acting as a proxy, not as a full caching service.
Google Page Speed service will cache several resources such as images, JavaScript and CSS files. However the actual HTML generated by your page will not be cached. Google will retrieve the normal page generated by your server and re-serve it to your users normally, after running it through their Page Speed tools.
The wp-admin and AJAX requests
If you do nothing special, the wp-admin section will be run through the Google Page Speed proxy too.
Since the normal mod_pagespeed seems to have no effect on the wp-admin code, it is unlikely that Google's service will have any effect at all.
The same applies to all AJAX type behavior, mod_pagespeed has had no effect on these in tests.


text:
Q: Array not being randomized as it should and values coming in negative I'm trying to store random numbers using the srand function to store values in a 2D Array using a loop. When I print out the array it has the same values everytime and the numbers are often in negative values which is strange and also they remain the same even if srand function is there.
#include <stdio.h>
#include <math.h>
#include <time.h>

#define NROW 13
#define NCOL 11

int main()
{
    void disp_array(int a[NROW][NCOL]);

    int ar[NROW][NCOL];
    int i, j;

    for (i = 0; i < NROW; i++) {
        for (j = 0; j < NCOL; j++) {
            ar[NROW][NCOL] = (rand() % 101);
        }
    }
    disp_array(ar);

    return 0;
}

void disp_array(int a[NROW][NCOL])
{
    int i;
    int j;

    for (i = 0; i < 7; i++) {
        for (j = 0; j < 5; j++) {
            printf("Value at row %d column %d is %d \n", i, j, a[i][j]);
        }
    }
}

A: Firstly, the statement ar[NROW][NCOL]= (rand()%101); is not correct as  every time  you are assigning data into same ar[NROW][NCOL] and NROW & NCOL is not varying.
So Replace it like ar[i][j]= (rand()%101);
Secondly, to print array elements, print like this
for (i=0;i<NROW;i++){  /* don't use < 5 or < 7 if you have NROW & NCOL*/
        for(j=0;j<NCOL;j++){
               ar[i][j]= (rand()%101);
        }
}

Finally, In statement ar[i][j]= (rand()%101); rand() generates same random number if you don't change the seed value. Read the manual page of rand() and srand(). for e.g use srand(getpid()) before calling rand().
srand(getpid());/*getpid() returns process id and
              every time process manager generates different process id*/

See this http://man7.org/linux/man-pages/man3/rand.3.html and https://linux.die.net/man/3/srand


text:
Q: Vue.js "npm run build" but Vue.js not bound to DOM / working Newbie to Vue.js here. On Mac OS using versions:
$ npm --version
4.6.1
$ vue --version
2.8.1

I'm using the webpack-simple init with the vue-cli for vue 2.0. I've created a folder within my Django project folder for vue stuff called frontend. Directory structure:
$ tree
├── README.md
├── asnew
│   ├── __init__.py
│   ├── migrations
│   ├── models.py
│   ├── settings.py
│   ├── templates
│       └── index.html
│   ├── urls.py
│   ├── views.py
│   ├── wsgi.py
├── frontend
│   ├── node_modules
│   ├── package.json
│   ├── src
│       ├── App.vue
│       ├── assets
│       ├── components
│       │   └── SearchPageResult.vue
│       ├── main.js
│       └── webpack.config.js
├── manage.py
├── media
├── requirements.txt
├── static
└── staticfiles

Then basically in my index.html Django template I have the following code:

Once rendered this turns into the full path:

which I create with npm run build and I verified does actually get loaded/imported by the browser. I run the heroku CLI as the devserver.
I build like this:
$ cd frontend
$ npm run build

> vue-asnew@1.0.0 build /Users/me/MyProject/frontend
> cross-env NODE_ENV=production webpack --progress --hide-modules

Hash: d5e16854b8f88beea3e9
Version: webpack 2.4.1
Time: 4503ms
       Asset     Size  Chunks             Chunk Names
    build.js  87.4 kB       0  [emitted]  main
build.js.map   718 kB       0  [emitted]  main

I don't know what to do with build.js.map, I don't use it.
HOWEVER, Vue doesn't work. While I get no errors with npm run build, I see no warnings in my console, none of my directives like v-bind work, nor can I access my object vm from main.js:
import Vue from 'vue'
import App from './App.vue'

# adding "export" in front here doesn't help either -
# in browser console it doesn't see `vm` object
const vm = new Vue({
    el: '#app',
    render: h => h(App)
});

as vm (or just Vue!) in the console.
> vm
VM1256:1 Uncaught ReferenceError: vm is not defined
> Vue
VM1256:1 Uncaught ReferenceError: Vue is not defined

My webpack.config.js looks like this:
var path = require('path')
var webpack = require('webpack')

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, '../static/js/vue/'),
    publicPath: '/js/vue/',
    filename: 'build.js'
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
          }
          // other vue-loader options go here
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]?[hash]'
        }
      }
    ]
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    }
  },
  devServer: {
    historyApiFallback: true,
    noInfo: true
  },
  performance: {
    hints: false
  },
  devtool: '#eval-source-map'
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}

and npm run build runs without error, so I'm not sure what's going on.
Any ideas?

A: npm run build usually also creates the index.html file, or in your case 'webpack-simple' its already present, in which it includes the app.js or build.js just before closing the body tag. If you are including build.js in your own html, try placing it after

 and before closing the .
Including scripts at the bottom ensures that the actual page content is loaded first; when the scripts are finally downloaded the content (DOM) will be ready for your scripts to manipulate.
Also if you:
const vm = new Vue({
    el: '#app',
    render: h => h(App)
});

you cannot access 'vm' in the console. Any variable created inside main.js won't be globally available. If you need it for debugging purposes you can do it in the following way:
window.vm = new Vue({
  el: '#app',
  render: h => h(App)
});

And then you can access 'vm' in the console.

A: As you can see in the index.html file of the webpack-simple template, you should include the scriptafter the
 element:
https://github.com/vuejs-templates/webpack-simple/blob/master/template/index.html#L8-L9
The fact that there's no global Vueobject is to be expected since your bundles app doesn'T expose it (and shouldn't)


text:
Q: Kotlin - Firestore toObject method not working as intended I am using Firestore for my Android project and I am using the following code to convert the fetched document to a custom data class
val userData = user.toObject(UserData::class.java)!!

Now this line works perfectly when no code obfuscation is happening, however, with obfuscation, this line does not fail but rather does not copy the user document data to the userData. so I think the issue might be with Firestore and code obfuscation.
Does anyone else have had this issue before?

A: toObject() method uses reflection to fill up your UserData model from the user document. Now that your UserData class is getting obfuscated, Firestore is not able to map the values in document to the model class.
To fix this, you need to disable code obfuscation for all the data models that you are using in Firebase.
The easiest fix is to add a @Keep annotation to your data class.
@Keep
data class UserData(...)

If you have a lot of such models, you can disable obuscation for an entire file or package by adding more rules to your proguard-rules.pro.
For example, this statement will keep all the classes intact inside model package while code shrinking and obfuscation:
-keep class com.example.app.data.models.** { *; }

Check out the documentation for more such rules.


text:
Q: Local object memory management I'm implementing an application in Objective-C, and just start to analyze it. It looks like I've got some problems with some images. For example, I've wrote:
Example = [[UIImageView alloc] initWithFrame:CGRectMake(15, 70, 290, 98.5)];
UIImage * ImageExample = [UIImage imageNamed:@"Test.png"];
Example.image = ImageExample;
[ImageExample release];
[Menu addSubview:Example];
[Example release];

It gives me:

Incorrect decrement of the reference count of an object that is not owned at this point by the caller

I've found some example, with NSString that made it local, and release after using.
So what's the matter with this sort of code please?

A:  UIImage * ImageExample = [UIImage imageNamed:@"Test.png"];

gives autorelease object, You can not release it as you are not allocating(owned) it .

A: You don't own ImageExample. So you shouldn't release it. Take a look at this guide:
iOS Memory Management Programming Guide
Especially on the article "Basic Memory Management Rules".

A: Remove the below statement, It should work fine.
[ImageExample release];

A: EDIT:
You should only release objects you OWN.
 You only release objects that you have allocated memory for. So, the thumb rule is - use release only if you have used init.
Also, starting with iOS5? Apple gave us something called as ARC (Automatic reference Counting). Just make sure the checkbox is ticked when creating the project. With ARC you don't have to use release statements at all. The complier will do the job for you.
While ARC simplifies a lot of things, you can also make mistakes with it. I would recommend you to have a read about ARC whenever you are comfortable with coding in Objective C. Have a look at the WWDC session videos related to ARC too.


text:
Q: access jhipster application from web I am not familiar with web servers, but I know jhipster ships applications without the need of one. I created a very simple microservice application composed of a gateway, a microservice, the two corresponding databases and the registry. I built it with the production profile and deployed it with docker-compose on ubuntu. Now, locally everything works great, but if I try and access the application over the web with the ip of the server where it is deployed I see nothing (site can't be reached). I tried to open port 8080 (the one on which the application serves requests) but nothing happens. Is it a problem of ip binding? Where can I configure it?
result of sudo netstat -ntlp with the application running:


text:
Q: To show that the problem is NP complete A decision problem: For a given graph G and numbers 'a','b' it is required to be answered whether there is a set of 'a' vertices which have a cumulative neighborhood of size at least 'b'. How do we show that this problem is NPC?

A: I assume that you're looking for a set $S$ with size $a = |S|$ and you're taking the union of the neighbors, so $b = \cup_{v\in S} n(v)$ (where $n(v)$ is the set of all vertices that share a neighbor with $b$).*
Then we can reduce from set cover with $b \gets m + k(n+1)$ and $a \gets k$.  We create a vertex for each of the $m$ sets in the Set Cover instance, and we also create a vertex for each of the $n$ items which may be contained in a set.  We create an edge between a set and an item iff the set contains that item.
For each of the $n$ "item vertices" created above, we create $n+1$ more vertices, and add edges between them.  (This means it's never good to select one of the "set" vertices.)
Then there is a set cover of size $k$ if and only if there are $k$ vertices with total neighborhood size $m + k(n+1)$.
*A note on problem variants:  if you are adding the neighborhood sizes (rather than taking the union as I assumed), just take the vertices with largest neighborhood greedily and the problem is trivial.  Whether or not "selected" vertices count towards neighborhood size is irrelevant because the reduction above has no edges between selected vertices.


text:
Q: make java plugin use the browser certificates We have a java applet that communicates with a spring application running on tomcat and using spring's http invoker.
We want to secure the applet using ssl with client authentication, we have a jsp page for login, after successful login the applet loads.
The jsp page is secured with ssl, when the applet loads the http invoker inside the applet is doing a second handshake apparently not related to the browser handshake, OK, I don't mind that, but I want the java plugin to use browser certificates and client certificates but its not, I have to load the client certificate to the java plugin also using the java ControlPanel, and if my server's certificate is self signed then I have to load the server certificate also to the java ControlPanel and to the nrowser.
Another thing is when the applet starts loading the java plugin pops a dialog asking for the client keystore password, I would like to avoid that.
So to conclude: I would like the java plugin to use the browser's trusted certificates and client certificates, and to avoid the keystore password dialog that pops up.
I have googled for it for two days and can't find any clue of how to accomplish that.
I will appreciate any help.
I'm using jdk 1.6.0 u23 and firefox 3.6.13.

A: Java has its own keystore database which holds these client certificates, this is controlled by 3 variables;
-Djavax.net.ssl.keyStore=<client_keystore_file_path>
-Djavax.net.ssl.keyStorePassword=<password to access the client keystore file>
-Djavax.net.ssl.keyStoreType=<keystore_type>

for example;
-Djavax.net.ssl.keyStore=c:\certs\client.pfx
-Djavax.net.ssl.keyStorePassword=test
-Djavax.net.ssl.keyStoreType=pkcs12

To be able to use this, you have to use keytool program (that comes with JRE/JDK) to convert & add client certificates into the keystore, here is an example on how to do this.

A: Java plugin documentation says its possible to applets access the browser keystore:
http://www.java.net/external?url=http://java.sun.com/javase/6/docs/technotes/guides/deployment/deployment-guide/keystores.html
But unfortunaly, the docs are sparse and I never tried to do that.
Good luck and post your solution here if you find it!


text:
Q: Mixing C# with Objective-C I would like to use larger body of C# code as a library for Objective-C (Cocoa) application.
I discovered MonoMac project which wraps Cocoa code, but I would rather have standard Cocoa application written in Objective-C, which can call wrapped C# code (other way around).
On Windows I am used to make C++/CLI project which wraps .NET code and exports plain old C interface for C/C++ based apps.
Is there some simple way to achieve this?

A: If you're doing this on Mac, then yes, it's possible.  On iOS not so much.
On the Mac, if you can create a CLI app in MonoMac, then you can call your CLI app from within your Objective-C app using NSTask.  NSTask allows you to easily launch a commandline tool and then capture it's output and interact with it.  To do this, you'd do something like:
NSArray *args = [NSArray arrayWithObjects:@"-arg1", @"-arg2", nil];
NSTask *foo = [[NSTask alloc] init];
[foo setLaunchPath:@"/usr/bin/foo"];
[foo setArguments:args];

NSPipe *pipe = [NSPipe pipe];
[foo setStandardOutput:pipe];

NSFileHandle *output = [pipe fileHandleForReading];

[foo launch];

NSData *data = [output readDataToEndOfFile];

NSString *outputStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

NSLog(@"Got stuff: %@", outputStr);

Typically, the way you want to do this, is you include the CLI app inside your app bundle. You can then get the path to the CLI app using NSBundles -pathForResource:ofType: method.
iOS doesn't include the NSTask API, so this isn't possible there.  I've heard of some folks using MonoTouch to make iOS apps using C#, but as you suggested, I think you're best off sticking with Objective-C for the bulk of your app if possible.  Using a CLI app like you describe is definitely an option on the Mac and can be particularly useful when you have a body of code that's already written and tested and works that you just want to "Wrap" with a Cocoa GUI.
So, NSTask is one way to do this using an external CLI executable wrapped in your app bundle.  On the other hand, you might be wondering, can you link your C# code directly into Objective-C?
Well, Objective-C is a superset of C, and as such, it has all the capabilities of C.  Additionally, if you use Objective-C++ it has all the capabilities of C++ as well.  So, IF you can get MonoMac to generate either a C or C++ static library, then yes, you could even just link your static library with your Objective-C cocoa code, and it'll just work.  I can't tell you how to make the library from MonoMac, but linking it in is just a matter of adding it to your linked libraries in your build settings in Xcode.
EDIT: I'm not familiar with C++/CLI as a language, and I misinterpreted the meaning of C++/CLI to mean "C++ Command Line Interface app".  That said... the techniques I described still apply as possible methods to do what you want to do, but it is NOT using the C++/CLI interface like you can on Windows.

A: There is, obviously, no such language as C++/CLI on Mac OS. On Windows, C++/CLI actually compiles as managed code ran by the CLR, that runs native code; since on Mac OS Mono isn't integrated to the system, it's rather the other way around. Your app is native, and it can host managed code.
Mono exposes functions to host a CLR virtual machine inside a process. Since CLR classes aren't directly exposed to your C code, you'll be able to call methods of objects through reflection-like calls.
There is documentation on how to embed Mono into an application on the official site. Since you're not interested in running .NET programs directly, you should rather read the "Invoking Methods in the CIL Universe" section. On Mac OS, you'll want to link against the Mono framework from your /Library/Frameworks folder, instead of using pkg-config.
This really shouldn't replace an actual reading of the above document, but the following can be seen as a guide as to what to expect:
#include <glib/glib.h>
#include <mono/jit/jit.h>
#include <mono-metadata/assembly.h>
#include <mono/metadata/debug-helpers.h>

// create an app domain
// http://en.wikipedia.org/wiki/Application_Domain
MonoDomain* domain = mono_jit_init("Domain");

// mandatory Cocoa call to show that Mono and ObjC work together
NSBundle* mainBundle = [NSBundle mainBundle];
NSString* dll = [mainBundle pathForResource:@"your-dll" ofType:@"dll"];

// load the referenced assembly in our domain
MonoAssembly* assembly = mono_domain_assembly_open(domain, [dll UTF8String]);
MonoImage* image = mono_assembly_get_image(assembly);

// find the class we want to wrap and create an uninitialized instance
MonoClass* classHandle = mono_class_from_name(image, "Name.Space", "YourClass");
MonoObject* object = mono_object_new(domain, classHandle);

// this calls the default, argument-less ctor
// for more complex constructors, you need to find the method handle and call it
// (helpful hint: constructors are internally called ".ctor", so the description
// string will look like "Name.Space.Class:.ctor()")
mono_runtime_object_init(object);

// get a method handle to whatever you like
const char* descAsString = "Name.Space.YourClass:YourMethod()";
MonoMethodDesc* description = mono_method_desc_new(descAsString);
MonoMethod* method = mono_method_desc_search_in_class(description, classHandle);

// call it
void* args[0];
mono_runtime_invoke(method, object, args, NULL);

// when you're done, shutdown the runtime by destroying the app domain
mono_jit_cleanup(domain);

If you don't find this very appealing, you may want to go the other way around, as you mentioned, and look into MonoMac, which provides .NET bindings to a large portion of the APIs you may want to use in a Mac application (Cocoa, CoreImage, CoreAnimation, etc) and means to create your own bindings.


text:
Q: How can i sum two property values iterating through the properties of an object? js I have this object in which every property it has an array as a value and inside another object:
  products: {
        product1Options: [{ itemName: "", itemRate: 0, itemAmount: 0 }],
        product2Options: [{ itemName: "", itemRate: 0, itemAmount: 0 }],
        product3Options: [{ itemName: "", itemRate: 0, itemAmount: 0 }],
        },

In some inputs i change the value of the 0's and I need to multiply the itemRate and itemAmount in each object inside each array. So I made this:
 if (this.products.product1Options.length ||
            this.products.product2Options.length ||
            this.products.product3Options.length) {

            for(let prop in this.products) {
                prop.map((obj) => {

                if(obj.itemRate > 0 && obj.itemAmount > 0 ) {
                    let sum = 0;
                    return sum += prop.itemRate * prop.itemAmount;
                }
                })
            }; }

But i get prop.map is not a function, i realized that's because prop is actually an object prop. So how could i do to achieve what im needing here. If anyone could help me i will be very thankful.

A: Your for..in loop iterates over the properties of an object not its values. So inside your loop, prop is just a string. You can either do
for(let prop in this.products) {
  this.products[prop].map((obj) => {
    if(obj.itemRate > 0 && obj.itemAmount > 0 ) {
      let sum = 0;
      return sum += prop.itemRate * prop.itemAmount;
    }
  })
 };

or
for(let prop in Object.values(this.products)) {
  // .map returns an array but you are not doing anything with it
  prop.map((obj) => {
    if(obj.itemRate > 0 && obj.itemAmount > 0 ) {
      let sum = 0; // This var is not helping since it gets reset to 0 every time
      return sum += prop.itemRate * prop.itemAmount;
    }
    // when you get here you don't return anything
  })
 };

But also it doesn't seem like you are using the map function properly, at times you are returning undefined when the if condition is not met. And you are not really doing anything with the array returned by the mapping. If what you care about is the sum of each product either you declare sum outside of the loop or you use reduce
for (let prop in this.products) {
  const sum = this.products[prop].reduce((acc, item) => {
    if (item.itemRate > 0 && item.itemAmount > 0) {
      return acc + item.itemRate * item.itemAmount;
    }
    return acc;
  }, 0);
  // do something with sum
}

To be honest though that if check doesn't seem to be that useful since if they are both 0 you only add 0 to a sum. So you can simplify like this:
for (let prop in this.products) {
  // If you are not familiar with reduce go check it out! What we do here
  // is reducing an array to a single value. We initialize it with 0 and for
  // each item in the array we add the rate * amount to the previous sum
  const sum = this.products[prop].reduce((prevSum, item) => prevSum + item.itemRate * item.itemAmount, 0);
}

I then assume you do something with that sum. If you want the final total you would have something like this:
let totalSum = 0;
for (let prop in this.products) {
  totalSum += this.products[prop].reduce((prevSum, item) => prevSum + item.itemRate * item.itemAmount, 0);
}

Technically you can go one step further and do all of it with one reduce only but I will let you figure that out. Keep in mind that readability is important! Don't feel like you HAVE to use reduce if you are not comfortable with it, I just wanted to show you what was possible but you can achieve the same in many other ways in JS.


text:
Q: How to re-enable function keys in byobu? I was using byobu on Ubuntu 11.10 Server and I needed to hit a function key in an app, so I hit F9 to bring up the config menu and switched the keybinding set from "f-keys" to "screen-escape-keys".  That worked, but now I can't re-enable all the f-keys.
I found a program byobu-config that brings up the menu again, and I can switch back to screen keys from there.  This fixes things for new screen processes, but the effect on the current screen session is weird: it disables the CTRL-A (screen) keys and restores F2-F8, but F9-F12 still don't do anything (they're just passed on to the foreground process).
What's up with this?  Any ideas?

A: Since byobu-config fixes things for new screen processes but not the current session it may be a bug worth reporting.
Visit https://bugs.launchpad.net/byobu to report the bug or to see if someone else already has.
Optionally you could contact the project maintainer, Dustin Kirkland:
https://launchpad.net/~kirkland
This is not a direct solution to your problem, but should be a step in the right direction!

A: We can try to debug your particular situation, but the easiest solution would be to just clear your current Byobu configuration with:
rm -rf ~/.byobu

And then restart byobu.


text:
Q: Get youtube video tags without any API in Java I have been trying to get youtube video tags from youtube video ID, searched everywhere but got answer in PHP, I did not try anything because I am a newbie java developer.

A: This is a long and complicated process but I will try to explain how to do this.

*

*create a url object to the video URL url = new URL(video url goes here!);

*open a urlconnection URLConnection urlCon = url.openConnection();

*read from the connection

InputStream inputStream = urlCon.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
BufferedReader br = new BufferedReader(reader);
String line = "";
while((line = br.readLine())!=null){
        //now we parse the information here!
}

*this is the hardest part... We need to parse the information from the reader...
I can not do this part for you because it takes a lot of time and code, but this is the fatest way to do it:  go to that url and open the page's source (ctr + u),  look through the source until you find the area with the tags. Now you have to parse strings over and over until you get the desired output.

A: After going through the source code of a youtube page, I noticed youtube tags are stored as keywords.
here how it looks like "keywords":["James","Gosling","Sun","Microsystems","Students"]
We just need to extract a string that starts with keywords and ends with ] which is followed by cleaning data
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class YoutubeTags
{
    public static void main(String[] args) {
        final String baseUrl = "https://www.youtube.com/watch?v=";
        String videoId = "r19P3y1VBiw";

        String tags[] = null;
        try {
            URL url = new URL(baseUrl + videoId);
            BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));

            Pattern pattern = Pattern.compile("\"keywords([^\\]])*");
            String line;
            while ((line = br.readLine()) != null) {
                Matcher matcher = pattern.matcher(line);
                if (matcher.find()) {
                    tags = matcher.group().split(",");
                    break;
                }
            }
        } catch (Exception e) {
            // do something
        }

        // cleaning data
        for(int i = 0; i < tags.length; i++) {
            tags[i] = tags[i].substring(2, tags[i].length() - 2);
            if(i == 0) {
                tags[0] = tags[0].substring(tags[0].lastIndexOf("\"") + 1);
            }
        }

        System.out.println(Arrays.toString(tags));
    }
}

output
[James, Gosling, Sun, Microsystems, Students]
Note: I used this post as the base for my answer. I have removed some code for easy understanding.


text:
Q: Which local database fits my situation? I will be building a set of applications.  One of these apps is unattended application (written in VB6) which will write data it receives from various sources to a local database.  All the other applications (will be written in VS 2008/c# 3.0) will read this data for mostly reporting reasons.
I don't want SQL Server/MySql/Sybase or even its express editions, because distributing it is a problem (e.g. requires separate install, etc...).  I am looking for a local database that has drivers for both VB6 (so probably OLEDB, or ODBC if I have to settle for it) and ADO.NET.  It would also be nice, if the database had support for ORMs, like NHibernate or at least 1-to-1 mappers, like Subsonic, but that's not a deal breaker.  But my main requirement is that the database should be massively solid, so that I don't have to waste time fiddling with it, recovering lost data, etc...
I have experience with MS Access from back in the day and don't have too many good recollections (nor was it bad either).  I've heard of SQLite, SQL Server Compact Edition, VistaDB, etc... but have zero experience with them and I don't know anyone who has actually used it.
What's out there that best fits my situation?

A: SQLite might just fit the bill.  Make sure you check out all the available wrappers as well.

A: Have you thought of FireBird SQL?

A: I'd recommend SQLite unless the database. I have experience using it and I was in the same shoes you were. The System.Data.Sqlite project is really nice and they support ADO.net 2.0 and all that fanciness. They are currently working on getting full Linq support on the wrapper as well. I recommend it for the following reasons.

*

*Low Footprint - The engine is only 700 KB or less.

*Scalable - It can handle fairly large databases. Order of GBs. Anything larger than this probably will require a server based database engine with LOTS of RAM.

*Durable - Their testing suite overs most of the code and has been proven to work on many commercial applications such as the iPhone

*Fast - There's very little overhead with this engine.

*Current - The .NET project is very up to date with the latest .NET 3.5 technology microsoft is bringing up.

*Portable - Can use it on embedded systems or desktop.

Check the System.Data.Sqlite project here http://sqlite.phxsoftware.com/

A: Check out Advantage Database Server. It has a silent install option, has a very small footprint and is easy to maintain. It has a lot of client support: ODBC, OLE DB, .net data provider, jdbc, dbi, php, etc. Royalty free local engine (just a dll that runs in-process with your application), inexpensive client/server, SQL and direct navigational table access.
The DevZone

A: SQL Server Compact Edition is in-proc, so there is nothing separate to install.

A: I don't have a lot of experience with SQLite either but I have used it a little. It is used in a LOT of situations and applications. There really are 100s of little DBs out there but I'd recommend SQLite as a starting point at least.

A: I can vouch for VistaDB. Another database you might want to look at is Blackfish

A: It is possible to use SQL Server as a local database connecting directly to a database file. But this requires that you have sql server express installed.
Look at the default setup of ASP.Net with a Membership Provider. It will create a local file based database for the website.
Using this approach you might be ok since you can use all your familiar tools when developing.
EDIT:
I just noticed the embedded tag. If you want to run the app on Windows CE devices you could opt for SQL Server Compact. It doesn't support stored procedures AFAIK but it does support most other features of SQL Server.

A: SQLite is very low impact and VERY well written. It is perfect for a local client database

A: SQLite as others have mentioned with the SQLite.net ADO.net provider, for easy .NET access to it.

A: I have used ScimoreDB, and wrote my appender for log4net, for my application. Have had mixed results and spent a lot of time trying to get through the documentation to get things to work as per needs.
I am moving towards SqlLite and there was a link floating around about using SubSonic with SqlLite.


text:
Q: Existence of surjective map / homomorphism from an infinite group onto its symmetric group From Cayley's theorem , we know that any group $G$ can be embedded in its permutation  group $S(G)$ ; I would like to ask , If $G$ be an infinite group , then does there exist a surjection from $G$ onto the permuttaion group of $G$ ?  And even if a surjection exists for some $G$ , can there ever exist a surjective homomorphism of $G$ onto $S(G)$ when $G$ is infinite ?
Please help . Thanks in advance

A: No: For any infinite set $X$, the cardinality of $S(X)$ is the same as that of its power set $\mathcal P(X)$ and therefore (by Cantor's theorem) different from the cardinality of $X$ itself.
We need to know that there is a bijection $f: X\times X\to X$. That this exists for every infinite $X$ is a well-known consequence (and, indeed, equivalent) of the axiom of choice.
Now in one direction, every permutation $\sigma\in S(X)$ can be encoded as a subset of $X$, namely $\{ f(x,\sigma(x)) \mid x\in X \}$, so there are at least as many subsets as there are permutations.
In the other direction: Choose two different $x,y\in X$. Then we can encode any subset $A\subseteq X$ as a permutation of $X$, namely the one that swaps $f(x,a)$ and $f(y,a)$ for all $a\in A$, and leaves all other elements of $X$ unchanged. This shows there are at least as many permutations as there are subsets.
The Cantor-Bernstein theorem now tells us that $S(X)$ and $\mathcal P(X)$ are equinumerous.


text:
Q: android - Работа с базой данных настроек Необходимо...
1) Взять базу данных из data/data/com.android.provider.settings/databases/settings.db
2) Далее нужно добавить в нее новую строчку
3) Поставить измененную базу данных на место.
Как выполнить первый пункт?  Сначала я запрашиваю root доступ
try  {
java.lang.Process p = Runtime.getRuntime().exec("su");
}
catch (IOException e){}

Появляется окошко подтверждения выдачи root, нажимаю "Access". Далее по идее должен выполниться этот код
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();

if (sd.canWrite()) {
String currentDBPath = "/data/data/" + "com.android.providers.settings" + "/databases/settings.db";
String backupDBPath = "data.db";
File currentDB = new File(currentDBPath);
File backupDB = new File(sd, backupDBPath);

if (currentDB.exists()) {
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}}} catch (Exception e) {
Toast.makeText(MainActivity.this, e.toString(), 1).show();
}

Но, в Toast пишет:
.....EACCESS: Permission denied

Добавил в AndroidManifest.xml разрешения:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ru.albatros.testroot"
>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_SUPERUSER"/>
...

И это ничего не дает. Как? Приложение получило root, но всё равно нет какого-то разрешения. Тестирую на Android 5.1.1 (CyanogenMod 12.1, кастомная прошивка). Помогите, оказывается, все сложнее, чем я думал.


text:
Q: How can I filter packets from a port monitor? I have some data going from Point A to Point B.  I have a SPAN monitor set up to a monitoring device C.
To recreate some real world scenarios, I want to filter out all traffic which is a certain type (H.323 VoIP Signaling Packets) so that C sees a subset of the information that is flowing from A to B.
What would the easiest way to do this be?  I assume I would need a computer with 2 NIC cards and some software to examine each packet and chuck out the H.323 VoIP packets?

A: You can do it with almost any hardware and software you want. You do need a PC with 2 NIC cards. Personally, I'd use Linux's software bridging and ebtables to enforce the filtering.

A: you could just use a capture filter in wireshark...


text:
Q: MongoDB : find query with an OR condition with additional column to tag which conidtion the record correspond to I need to fetch certain records from a table using the following OR query
db.book.find({
    "$or" : [
        { "_id': ObjectId("53e49ab8fdc5c42d13965e85")},
        { "topics": { "$in" : ["mysql","MongoDB"] }}
    ]
})

I need to tag the results in my final output to show where the record came from, i.e. did the record match first condition or the second one. How to do that ?
EDIT:
Posted solution (with help from Phillip)

A: The aggregation framework with the $cond operator could help you here.
The first step of the aggregation would be a $match with the same object you have in your find above. The second step would then be a $project which uses the $cond operator to generate a new field foundBy which gets a different value depending on whether or not the _id of the document matches the one in the query.
$project: {
    // fields from original document you want to retain unchanged:
    any: 1,
    field: 1,
    you: 1,
    need: 1,
    // a new, computed field:
    foundBy: {
        $cond: {
           if: {$eq: [ "$_id", ObjectId("53e49ab8fdc5c42d13965e85") ] },
           then: "id match",
           else: "topic match"
        }
    }
}

A: db.tbook.aggregate(
{
   "$match": {
      "$or": [
        { "_id": ObjectId("53e49ab8fdc5c42d13965e85") },
        {"topics": { "$in" : ["mysql","MongoDB"]}}
      ]
   }
},
{
   "$project": {
    "intersect": {
        $setIntersection: [ "$topics", ["mysql","MongoDB"] ]
     }
   }
},
{
   "$project": {
     foundBy: {
        $cond: {
           if: { $eq : [ "$intersect", [] ] },
           then: "id match",
           else: "topic match"
        }
     }
   }
}
)


text:
Q: SwiftChart Library not working with Swift 3.0 I have used SwiftChart to implement Line and area chart like below image .
It works fine with Xcode 7.3. Now am porting my code to iOS 10 so converting the code to Swift 3.0. I'm getting following error:
U
CGPathMoveToPoint(area, nil, CGFloat(xValues[0]), zero)

for i in 0..<xValues.count {
    CGPathAddLineToPoint(area, nil, CGFloat(xValues[i]), CGFloat(yValues[i]))
}

CGPathAddLineToPoint(area, nil, CGFloat(xValues.last!), zero)

and
if labels[i] != 0 {
    // Horizontal grid for 0 is not dashed\
    CGContextSetLineDash(context,phase:0,lengths:[5],count:1)
   // CGContextSetLineDash(context, 0, [5], 1)
} else {
    CGContextSetLineDash(context, 0, nil, 0)
}

Please help me in fixing this issue

A: Latest update of SwiftChart fixes the issue mentioned above . please update your swift chart lib code to latest


text:
Q: jQuery script not working in HTML page I am trying to use a jQuery script, yet it is not displaying as it should. I have it working within JSFiddle. Yet it does not work within my page: when an option is chosen it does not show anything at all. What am I doing wrong?

    <meta charset="UTF-8">
    <title>title</title>

    <link href="css/faqtest.css" rel="stylesheet">

    <select>
      <option disabled selected>choose</option>
      <option value="answer1">answer1</option>
      <option value="answer2">answer2</option>
      <option value="answer3">answer3</option>
    </select>

answer1

answer2

answer3

A: Execute the code on document ready.
$(function(){
  $('select').on('change',function() {
    var answer = $(this).val();
    $('.answers').hide();
    $('#'+answer).show();
  });
});


text:
Q: Class of laravel package not found I made a laravel package with this composer.json:
{
    "name": "calcanotica/file-storage",
    "type": "library",
    "description": "A file storage module for laravel.",
    "homepage": "<<gitlab url>>",
    "authors": [
        {
            <<authors>>
        }
    ],
    "autoload": {
        "psr-4": { "Calcanotica": "src" }
    },
    "require": {
        "php": "^5.5.9 || ^7.0",
        "illuminate/contracts": "5.1.* || 5.2.* || 5.3.* || 5.4.*",
        "illuminate/support": "5.1.* || 5.2.* || 5.3.* || 5.4.*",
        "league/flysystem-aws-s3-v3": "~1.0",
        "nesbot/carbon": "^1.0"
    }
}

The structure of the package is:
-src
   -Storage
      -S3FileStorage.php

In the S3FileStorage.php file I have the following class:
namespace Calcanotica\Storage;

class S3FileStorage { ... }

But, when I try to use the class inside another application as \Calcanotica\Storage\S3FileStorage, I get a Class \Calcanotica\Storage\S3FileStorage not found error.
I already execute composer dump-autoload.
What's the problem?

A: Your autoload section is incorrect. Namespace must end with \\ (docs) so it should be:
"autoload": {
    "psr-4": { "Calcanotica\\": "src" }
},

however I'd replace the whole
"autoload": {
    "psr-4": { "Calcanotica": "src" }
},

with
"autoload": {
    "classmap": [ "src/" ]
},

and let composer figure out what is where (docs), which in general use is better, less error prone than setting up namespace mapping by hand and won't require any future attention if you add new namespace to your package.

A: In your composer.json file add following lines :
"autoload": {
    "psr-4": {
        "Calcanotica\\": "src/"
    },

},

You need to add \\ after your namespace and / after your src. For more check here : https://getcomposer.org/doc/04-schema.md#psr-4


text:
Q: Spring cloud stream with kafka Need some help in integrating kafka with spring cloud stream. The application is very simple, with 2 parts(run as separate java processes)

*

*A consumer- puts request into RequestTopic and gets response from ResponseTopic

*A producer- gets the request from the RequestTopic and puts the response back in ResponseTopic.

I have created RequestSenderChannel and ResponseReceiverChannel interfaces for consumer and  RequestReceiverChannel and  ResponseSenderChannel
for the producer application. both of them share the same yaml file.
As per the documentation spring.cloud.stream.bindings..destination should specify the topic to which the message is sent or received.
But when i run the application, the application creates topics as 'RequestSender', 'RequestReceiver', 'ResponseSender' and 'ResponseReceiver' in the kafka
My assumption was: since destination in the YAML file specifies only two topics 'RequestTopic' and 'ResponseTopic', it should have created those topics.
but it creates Kafka topics for attributes specified at 'spring.cloud.stream.bindings' in the YAML file.
can someone please point out the issue in the configruation/code?
public interface RequestReceiverChannel
{
    String requestReceiver ="RequestReceiver";
    @Input(requestReceiver)
    SubscribableChannel pathQueryRequest();
}

public interface RequestSenderChannel
{
    String RequestSender ="RequestSender";
    @Output(RequestSender)
    MessageChannel pathQueryRequestSender();
}

public interface ResponseReceiverChannel
{
    String ResponseReceiver = "ResponseReceiver";
    @Input(ResponseReceiver)
    SubscribableChannel pceResponseServiceReceiver();
}
public interface ResponseSenderChannel
{
    String ResponseSender = "ResponseSender";
    @Output(ResponseSender)
    MessageChannel pceResponseService();
}
'''

The YAML configuration file
spring:
  cloud:
    stream:
      defaultBinder: kafka
      bindings:
        RequestSender:
          binder: kafka
          destination: RequestTopic
          content-type: application/protobuf
          group: consumergroup
        ResponseSender:
          binder: kafka
          destination: ResponseTopic
          content-type: application/protobuf
          group: consumergroup
        RequestReceiver:
          binder: kafka
          destination: RequestTopic
          content-type: application/protobuf
          group: consumergroup
        ResponseReceiver:
          binder: kafka
          destination: ResponseTopic
          content-type: application/protobuf
          group: consumergroup
      kafka:
        bindings:
          RequestTopic:
            consumer:
              autoCommitOffset: false
          ResponseTopic:
            consumer:
              autoCommitOffset: false
        binder:
          brokers: ${SERVICE_KAFKA_HOST:localhost}
          zkNodes: ${SERVICE_ZOOKEEPER_HOST:127.0.0.1}
          defaultZkPort: ${SERVICE_ZOOKEEPER_PORT:2181}
          defaultBrokerPort: ${SERVICE_KAFKA_PORT:9092}

A: By doing spring.cloud.stream.bindings.<binding-name>.destination=foo you are expressing desire to map binding specified by <binding-name> (e.g., RequestSender) to a broker destination named foo. If such destination does not exist it will be auto-provisioned.
So there are no issues.
That said, we've just released Horsham.RELEASE (part of cloud Hoxton.RELEASE) and we are moving away from annotation-based model you are currently using in favor of a significantly simpler functional model. You can read more about it in our release blog which also provides links to 4 posts where we elaborate and provide more examples on functional programming paradigm.


text:
Q: Oracle SQL Join columns on 2 conditions I tried to search forums for my scenario but could not find anything remotely similar. So here goes my long winded explanation : I have 3 tables - order_fact , session_fact and orderline.
create table order_fact (order_no varchar2(20), order_timestamp date, cookie_id number, session_id number);

insert into order_fact values ('69857-20210329', to_date('29-MAR-2021 10:11:58', 'DD-MON-YYYY HH24:MI:SS'), 827678, 79853421);
insert into order_fact values ('78345-20210411', to_date('11-APR-2021 18:37:07', 'DD-MON-YYYY HH24:MI:SS'), 569834, 84886798);
insert into order_fact values ('79678-20210519', to_date('19-MAY-2021 20:51:34', 'DD-MON-YYYY HH24:MI:SS'), 589623, 89556782);
insert into order_fact values ('78759-20210411', to_date('11-APR-2021 09:46:52', 'DD-MON-YYYY HH24:MI:SS'), 685213, 77549823);

create table session_fact (cookie_id number, session_id number, session_timestamp date, marketing_vendor varchar2(30) , referral_type VARCHAR2(2) );

insert into session_fact values (827678, 79853421, to_date('29-MAR-2021 09:47:36', 'DD-MON-YYYY HH24:MI:SS'), '-1', 'D');
insert into session_fact values (827678, 79853378, to_date('28-MAR-2021 12:47:36', 'DD-MON-YYYY HH24:MI:SS'), '-1', 'D');
insert into session_fact values (827678, 79853313, to_date('24-MAR-2021 13:23:36', 'DD-MON-YYYY HH24:MI:SS'), 'Naaptol', 'S');
insert into session_fact values (827678, 79853254, to_date('23-MAR-2021 14:39:56', 'DD-MON-YYYY HH24:MI:SS'), '-1', 'D');
insert into session_fact values (569834, 84886798, to_date('11-APR-2021 14:41:44', 'DD-MON-YYYY HH24:MI:SS'), '-1', 'D');
insert into session_fact values (569834, 84886735, to_date('10-APR-2021 11:03:44', 'DD-MON-YYYY HH24:MI:SS'), '-1', 'D');
insert into session_fact values (569834, 84886687, to_date('08-APR-2021 17:26:49', 'DD-MON-YYYY HH24:MI:SS'), '-1', 'D');
insert into session_fact values (569834, 84886659, to_date('03-APR-2021 11:03:44', 'DD-MON-YYYY HH24:MI:SS'), '-1', 'D');
insert into session_fact values (569834, 84886497, to_date('01-APR-2021 07:59:08', 'DD-MON-YYYY HH24:MI:SS'), 'Google', 'R');
insert into session_fact values (685213, 77549823, to_date('11-APR-2021 09:07:34', 'DD-MON-YYYY HH24:MI:SS'), '-1', 'D');
insert into session_fact values (685213, 77549786, to_date('09-APR-2021 20:51:34', 'DD-MON-YYYY HH24:MI:SS'), '-1', 'D');
insert into session_fact values (685213, 77549589, to_date('07-APR-2021 14:11:57', 'DD-MON-YYYY HH24:MI:SS'), 'FabShopping', 'D');
insert into session_fact values (685213, 77548356, to_date('03-APR-2021 15:38:42', 'DD-MON-YYYY HH24:MI:SS'), '-1', 'D');
insert into session_fact values (589623, 89556782, to_date('19-MAY-2021 16:46:52', 'DD-MON-YYYY HH24:MI:SS'), '-1', 'D');
insert into session_fact values (589623, 89556512, to_date('18-MAY-2021 09:46:52', 'DD-MON-YYYY HH24:MI:SS'), '-1', 'D');
insert into session_fact values (589623, 89556477, to_date('13-MAY-2021 18:34:29', 'DD-MON-YYYY HH24:MI:SS'), '-1', 'D');
insert into session_fact values (589623, 89556348, to_date('10-MAY-2021 16:13:49', 'DD-MON-YYYY HH24:MI:SS'), '-1', 'D');

create table orderline (order_no varchar2(20), ol_nbr number, ol_ref varchar2(5));

insert into orderline values ('78345-20210411', 0, '-2');
insert into orderline values ('78345-20210411', 1, 'HV3');
insert into orderline values ('78345-20210411', 2, 'HV3');
insert into orderline values ('78759-20210411', 0, '-2');
insert into orderline values ('78759-20210411', 1, 'PS5');
insert into orderline values ('78759-20210411', 2, 'PS5');
insert into orderline values ('78759-20210411', 3, 'PS5');
insert into orderline values ('79678-20210519', 0, '-2');
insert into orderline values ('79678-20210519', 1, 'NPT');
insert into orderline values ('79678-20210519', 2, 'NPT');
insert into orderline values ('69857-20210329', 0, '-2');
insert into orderline values ('69857-20210329', 1, 'HV3');
insert into orderline values ('69857-20210329', 2, 'HV3');
insert into orderline values ('69857-20210329', 3, 'HV3');

As can be seen from above order_fact and session_fact tables are connected by cookie and session id. The request is to get these columns : ORDER_NO, MARKETING_VENDOR, REFERRAL_TYPE, OL_REF from the above 3 tables.
I have written the JOIN query :
select a.ORDER_NO, b.MARKETING_VENDOR,
b.REFERRAL_TYPE, c.OL_REF
FROM order_fact a
INNER JOIN session_fact b
ON (a.cookie_id = b.COOKIE_ID AND
b.session_timestamp < a.order_timestamp AND
b.session_timestamp > a.order_timestamp-7)
INNER JOIN orderline c ON
(a.ORDER_NO = c.ORDER_NO AND c.OL_NBR = 1);

Here is the sticky situation for me :

*

*Get the data in session_fact table for a cookie_id in order_fact for timestamp of not more than 7 days before the order_timestamp. For example - order_no 78345-20210411 was placed on 11-APR-2021 18:37:07. Using the cookie id of that order I get all rows in session_fact till 11-APR - 7 days = 4-APR. So 3rd and 1st Apr data cannot be considered. This has been taken care in my query. But I wanted to mention why I had the additional AND clauses in the 1st JOIN ON condition.

*From the data got in point 1 above do not consider those records where REFERRAL_TYPE = 'D' and MARKETING_VENDOR = '-1'. 'S' and '-1' can be considered and so is 'R' and '-1'. Basically any values can be considered as long as its NOT 'D' and '-1'. And select the record whose timestamp is closest to the order_timestamp in table order_fact. Now this is where it gets tricky - if there are no records of past 7 days where combo of REFERRAL_TYPE and MARKETING_VENDOR is NOT 'D' and '-1' then join the tables order_fact and session_fact on both cookie_id and session_id and fetch the values.

*Join tables order_fact and orderline ON ORDER_NO and OL_NBR = 1. This also has been taken care in my join query.
So my only problem is getting the JOIN between session_fact and order_fact on the 2 different conditions mentioned in point 2. Can this be done by SQL? The Tech Lead of my team asked me to write a PL/SQL block. I did that because the original request was to add MARKETING_VENDOR, REFERRAL_TYPE, OL_REF columns in order_fact table and get the values from their respective tables. I cannot help but feel this can be done by SQL using CASE. Or am I wrong? If anyone could please help me with this query I will be grateful.
Edit : Adding the result data set

Edit : Any kind soul to help me out?  I take it it's not possible in a SQL statement.

A:
And select the record whose timestamp is closest to the order_timestamp in table order_fact

From your description looks like you just need Top 1 record by session_timestamp:
with
 step1 as (
   SELECT
       a.ORDER_NO
      ,a.order_timestamp
      ,c.MARKETING_VENDOR
      ,c.REFERRAL_TYPE
      ,c.session_timestamp
   FROM order_fact a
   cross apply (
       select *
       from session_fact b
       where a.cookie_id = b.COOKIE_ID
         and (REFERRAL_TYPE,MARKETING_VENDOR) not in (('D','-1'))
         AND b.session_timestamp < a.order_timestamp
         --AND b.session_timestamp > a.order_timestamp-7
       order by b.session_timestamp desc
       fetch first 1 rows only
   ) c
)
select
   s.*
  ,o.OL_REF
FROM
   step1 s
   JOIN orderline o
        ON (s.ORDER_NO = o.ORDER_NO AND o.OL_NBR = 1)
;

Result:
ORDER_NO       ORDER_TIMESTAMP     MARKETING_VENDOR REFERRAL_TYPE SESSION_TIMESTAMP   OL_REF
-------------- ------------------- ---------------- ------------- ------------------- ------
78345-20210411 2021-04-11 18:37:07 Google           R             2021-04-01 07:59:08 HV3
78759-20210411 2021-04-11 09:46:52 FabShopping      D             2021-04-07 14:11:57 PS5
69857-20210329 2021-03-29 10:11:58 Naaptol          S             2021-03-24 13:23:36 HV3


text:
Q: Allocation of Return Values of User Defined Functions: Performance? In considering a scenario where we may not wish to always store the return value of a function in multiple calls, take this code:
  int foo()
     {
        return 1;
     }

which is called from the following procedure.
  void main()
  {
    foo();
  }

What happens to the return value of foo? In not finding a variable address does the compiler put it on a spare register- or does it get wiped when the next statement is executed?
If now instead the return value is stored somewhere:
  void main()
  {
    int retval;
    retval = foo();
  }

What's the performance difference between the two scenarios? Is not storing  retval somewhere going to cause any issues with the stack management somewhere down the track?
Edit: Own config: Toolset: V100, __cdecl (/Gd): Running Win32 in VS10 compiling as C++ - would inlining come into play?
Can we but guess as to how many many specific configurations apply to a given set of answers. Might be enough for a small book!

As to performance, int was a poor choice, perhaps float or double makes for more impact?
This question differs from the proposed duplicate like this:
Given the return address of foo is added to a call frame, one scenario is that the address of retval is placed below it, but if retval is NULL there is an extra overhead?

A: So, this is very dependent on exactly what's being returned. For a datatype like int most implementations will stuff the return value into a register, and the optimizer in the calling function will treat the register as 'dirty' and otherwise ignore it unless it needs to repurpose it for something else. Basically, there's no performance difference at all.
If you are returning a more complex value that has constructors and destructors and such, the compiler will have to call them unless the function being called is inline and the optimizer can determine that the constructor and destructor have no effect. Even when they do have an effect, there are specific cases in which it's permissible for the compiler to elide constructor and destructor calls for return values. C++11 with it's support of the move constructor has removed some of the need for this. Anyway, this is addressed here: What are copy elision and return value optimization?
For complex return values that are too big to fit into registers the implementations I've seen have the caller make some space for the return value on the stack and pass in a pointer to that return value into the called function. This means that if the caller can determine that the destructor has no effect it will simply omit a call to it and treat that section of memory as 'dirty' for optimization purposes.

A: If you don't assign it, it is lost.
It depends on the calling convention but typically the return value is passed in a register (%rax, e.g. in SysV x86_64) and if you don't assign it, the register is simply reused which will obviously overwrite the value.
In the 2nd case it will put it on the stack, but the optimizer will most probably remove the code since it is useless. But this depends on the compiler and the optimizer.


text:
Q: How to compare string with specific part of array item? I have an array arr[] of string type with array-items as follows:
arr[0]= "2/13/2019|202"
arr[1]= "2/14/2019|197"
arr[2]= "2/15/2019|101"
arr[4]= "2/16/2019|271"
arr[5]= "2/17/2019|199"

I want to get an array-item that matches my string "2/15/2019" so I can get "2/15/2019|101".
in short, I just want to compare my string with the array-item string till "|" and rest strong will not be considered for comparison.
how can I get it?

A: You can use Linq to get the data you are looking for.

*

*use Contains(string) to check if there is one or more elements that match your criteria

*if it does, get the first one from the list (or you can assign that list to a variable and iterate through each of it)

*Split the value and get the value after |

*Use ?. after FirstOrDefault() method to ensure you dont get NullReferenceException when you run Split().

*Use validation to ensure result is not null.

var result = arr.FirstOrDefault(x => x.Contains("2/15/2019"))?.Split('|')[1];
// result contains 101

Enumerable.FirstOrDefault: Returns the first element of a sequence, or a default value if no element is found

A: You could use Where and StartWith
var results = arr.Where(x => x.StartsWith("2/15/2019"));

Additional Resources
Enumerable.Where Method

Filters a sequence of values based on a predicate.

String.StartsWith Method

Determines whether the beginning of this string instance matches a
  specified string.

A: Use where and contains
           string getdata = "2/15/2019";
            string[] arr = new string[5];
            arr[0] = "2/13/2019|202";
            arr[1] = "2/14/2019|197";
            arr[2] = "2/15/2019|101";
            arr[3] = "2/16/2019|271";
            arr[4] = "2/17/2019|199";

            var op = arr.Where(a => a.Contains(getdata)).FirstOrDefault();


text:
Q: Count the numbers satisfying division criteria in discrete maths I have a problem in Discrete Math to ask: How many least non-negative numbers are there that we can always take randomly 23 numbers from that set which having sum divisible to 23?
I'm thinking about a set containing all possible remainders when dividing to 23, so the set has 22*23 = 506 numbers.
I dont think it is correct, so can you guys help me. Many thanks


text:
Q: Why Whole Table Scan (Clustered Index) I have a big table with 315M rows. with these columns & Index :

[key_] (int & IDENTITY(1,1)), [time_] (datetime), [value_] (float), [quality_] (int)

PK & Clustered-Index: key_ , Non-Clustered-Index on: time_ + quality_

Actually the main select that we use here is as bellow. This select gives good result, in 2Secs, but when I change the range & make it wider (like 36 hours), it responds in 6Minutes!
SELECT TOP (1000)
     ,[time_]
     ,[value_]
     ,[quality_]
    FROM [DataHubRev2].[dbo].[tb_HPGR_120MI01ME01_Power]
    WHERE quality_=192 AND time_ >' 2020-03-27 19:00:01'AND time_ <' 2020-03-28 07:00:00'
                           --- 12 hours: Good Result
--- WHERE quality_=192 AND time_ >' 2020-03-27 07:00:01'AND time_ <' 2020-03-28 19:00:00'
--- 36 hours: Bad Result

It is clear that by using this select & where, SQL-Engine should go for NonClusteredIndex (at least I think so). When I look at the 'Actual Execution Plan' the first one goes directly to the NonClustIndex Seek, but the second one goes for ClusteredIndex Scan & the readed rows tells 315M (the entire table)!!
Interesting part is that when I remove  ',[value_]' from the select or add the Hint to force NonClustIndex use (With (INDEX = [IX_TimeQuality_Index])) response time & exec-plan is solved. But I need a more deep solution & actually why this is happening.
Also tell me that: making my table as Heap & not having any Clustered Index on ID which I don't use on my selects is a good practice or not?
Edit:
These are the Actual Execution Plans, you could see that the second one scans all the table (Number of rows read).

*

*Good Response Time : https://ibb.co/JFjXXwJ

*Bad Response Time:    https://ibb.co/WGgrDh2

A: Wild Guess only: Use quality_ + time_ instead time_ + quality_ and include (value_) ?

A: Without seeing the execution plan to see the row estimates, it's going to be difficult to give you a precise answer.
Probably, the expanded range results in a broad enough set of rows that the optimizer, based on the statistics on your indexes, has determined that a seek is no longer efficient, so it's doing a scan instead. One of the reasons for this is outlined in the comments. Since your non-clustered index doesn't cover the query (cover = have all columns needed either in the key or as part of an INCLUDE), it will have to do a key lookup operation in the clustered index. In general terms, this is a 3:1 read addition to a query. So, as you expand the set of rows, the optimizer figures, it's faster to scan the index and retrieve stuff than to go through the key lookup process.
As to heaps vs. clustered indexes, I have a very simple default. Every table gets a clustered index. Yes, there are exceptions, but the exceptions are just that, exceptional, and well documented why, exactly, they should be heaps. SQL Server is, by and large, engineered around the clustered index. So, best to use them. There are a gajillion details around this that are just too much to cover here. TLDR: Prove you need a heap.


text:
Q: Bizarre NoClassDefFoundError when running in Android I've tried looking at all the other NoClassDefFoundError threads on here and elsewhere, but they all seem to be a different problem.
My activity refers to a custom FragmentPagerAdapter - let's call it MyFragmentPagerAdapter.
The Activity refers to it with:
MyFragmentPagerAdapter pagerAdapter = new MyFragmentPagerAdapter(getFragmentManager());
ViewPager viewPager = (ViewPager) findViewById(R.id.form_pager);
viewPager.setAdapter(pagerAdapter);

This all seems to compile and build perfectly well in Eclipse.  Eclipse can certainly find all the classes - it auto filled the import statement for me.
However, when I try and run the class in Android (emulator or device) I get a NoClassDefFoundError for MyFragmentPagerAdapter and (of course) the app crashes.
I've tried deleting the APK on the device and re-installing in case it was a deployment issue, but it didn't help.
This isn't to do with some 3rd party library - it's my own class that it fails to find!
I have also tried "cleaning" the Project.
I have extracted the apk and inspected the output of
dexdump classes.dex | grep PagerAdapter

and there are references to my class in there, so I can only assume the compiled class is getting itnot the apk - which makes me even more bemused.

A: NoClassDef refers to classes that are referred by your class (in this case "MyFragmentPagerAdapter") not to the class itself (that's the ClassNotFoundException).
Check the import you have in the class "MyFragmentPagerAdapter" and be sure that they are all in the classpath of your android application i.e. by checking the libs folder and (eventually) other android libraries you are referring to in your project.
Hope this helps.


text:
Q: Cypher: How to create a recursive cost query with alternates? I have the following structure:
(:pattern)-[:contains]->(:pattern)
...basically a hierarchy of patterns that use other patterns as content. These constitute trees.
Certain patterns are generated by certain generators:
(:generator)-[:canProduce]->(:pattern)

The canProduce relationship has a cost value associated with it as a property. Multiple generators can create the same pattern.
I would like to figure out, with a query, what patterns I need to generate to produce a particular output - and which generators to choose to have the lowest cost. I started like this:
MATCH (p:pattern {name: 'preciousPattern'})-[:contains *]->(ps:pattern) RETURN ps

so far so good. The results don't contain the starting pattern, so I made this:
MATCH (p:pattern {name: 'preciousPattern'})-[:contains *]->(ps:pattern)
WITH p+collect(ps) as list
UNWIND list as patterns
RETURN patterns

That does not feel elegant, but it also does not provide the hierarchy
I can of course do a path query (MATCH path = MATCH...) but the results don't seem very useful.
Also, now I need to connect the cost from the generator relationship.
I tried this:
MATCH (p:pattern {name: 'awesome'})-[:contains *]->(ps:pattern)
WITH p+collect(ps) as list
UNWIND list as rec
CALL {
WITH rec
MATCH (rec)-[r:canGenerate]-(g:generator)
return r.GenCost as GenCost, g.name AS GenName
}
return rec.name, GenCost , GenName

The problem I have now is that if any of the patterns that are part of another pattern can be generated by multiple generators, I just get double entries in the list, but what I want is separate lists for each alternative possibility, so that I can generate the cost.
This is my pattern tree:

*

*Awesome

*

*input1

*input2

*

*input 3

Input 3 can be generated by 2 different generators. I now get:
Awesome   |  2    | MainGen
input1    |  3    | TestGen1
input2    |  2.5  | TestGen2
input3    |  1.25 | TestGen3
input4    |  1.4  | TestGen4

What I want is this: Two lists (or n, in the general case, where I might have n possible paths), one
Awesome   |  2    | MainGen
input1    |  3    | TestGen1
input2    |  2.5  | TestGen2
input3    |  1.25 | TestGen3

and one:
Awesome   |  2    | MainGen
input1    |  3    | TestGen1
input2    |  2.5  | TestGen2
input4    |  1.4  | TestGen4

each set representing one alternative set, so that I can calculate the costs and compare.
I have no idea how to do something like that. Any suggestions?