text:
Q: Having an issue using TextFeild in flutter, Text box not showing up I'm creating a flutter app that requires a user to complete certain tasks in order to stop an alarm clock. It's a more immersive alarm clock app that could help stimulate the brain in order to aid in the process of waking up.
The tasks are simple questions the user has to answer. I'm utilizing TextFeild() to allow the user to input their answer. However, when I go to debug my code is redirected to a file called box.dart this is where the error is stated.
Here is the box.dart file error:
throw FlutterError.fromParts(<DiagnosticsNode>[
          ErrorSummary('Cannot hit test a render box with no size.'),
          describeForError('The hitTest() method was called on this RenderBox'),
          ErrorDescription(
            'Although this node is not marked as needing layout, '
            'its size is not set.',
          ),
          ErrorHint(
            'A RenderBox object must have an '
            'explicit size before it can be hit-tested. Make sure '
            'that the RenderBox in question sets its size during layout.',
          ),
        ]);
      }

Here is my full code:
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
//import 'package:audioplayers/audio_cache.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Time Attack',
      theme: ThemeData(
        primarySwatch: Colors.red,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.black,
        appBar: AppBar(
          backgroundColor: Colors.red,
          title: const Text('Time Attack'),
          centerTitle: true,
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () async {
            // ignore: avoid_print
            print("alarm is playing");
            final player = AudioCache();
            //bool isPLaying = false;
            await player.load('musicForapp.mp3');
            AudioPlayer p = AudioPlayer();
            p.audioCache = player;
            await p.play(AssetSource('musicForapp.mp3'));
          },
          backgroundColor: Colors.red,
          child: const Icon(Icons.punch_clock),
        ),
        body: Padding(
          padding: const EdgeInsets.all(170),
          child: Column(
            children: [
              const Text(
                "Click the Icon in the bottem right to simulate alarm",
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 30.0,
                ),
              ),
              ElevatedButton(
                style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (_) => const TasksPage(),
                    ),
                  );
                }, //on pressed
                child: const Text(
                  "Tasks page",
                  style: TextStyle(color: Colors.white),
                ),
              )
            ],
          ),
        ),
      ),
    );
  } //widget build
}

class TasksPage extends StatefulWidget {
  const TasksPage({super.key});

  @override
  State<TasksPage> createState() => _TasksPageState();
}

class _TasksPageState extends State<TasksPage> {
  final _textcontroller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.black,
        appBar: AppBar(
          backgroundColor: Colors.red,
          title: const Text('Tasks'),
          centerTitle: true,
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (_) => const SecondTask(),
              ),
            );
          },
          backgroundColor: Colors.red,
          child: const Text("Next"),
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Center(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                const Text(
                  "How many states are there in the United States of America?",
                  style: TextStyle(
                    backgroundColor: Colors.white,
                    color: Colors.black,
                    fontSize: 30.0,
                  ),
                ),
                Expanded(
                  child: TextField(
                    controller: _textcontroller,
                    decoration: InputDecoration(
                      hintText: "Type your answer here!",
                      border: const OutlineInputBorder(),
                      suffixIcon: IconButton(
                        onPressed: () {
                          _textcontroller.clear();
                        },
                        icon: const Icon(Icons.clear),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  } //widget build
}

class SecondTask extends StatefulWidget {
  const SecondTask({super.key});

  @override
  State<SecondTask> createState() => _SecondTask();
}

class _SecondTask extends State<SecondTask> {
  final _textcontroller2 = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.black,
        appBar: AppBar(
          backgroundColor: Colors.red,
          title: const Text('Tasks'),
          centerTitle: true,
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (_) => const Thirdtask(),
              ),
            );
          },
          backgroundColor: Colors.red,
          child: const Text("Next"),
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Center(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                const Text(
                  "how many oceans are there?",
                  style: TextStyle(
                    backgroundColor: Colors.white,
                    color: Colors.black,
                    fontSize: 30.0,
                  ),
                ),
                Expanded(
                  child: TextField(
                    controller: _textcontroller2,
                    decoration: InputDecoration(
                      hintText: "Type your answer here!",
                      border: const OutlineInputBorder(),
                      suffixIcon: IconButton(
                        onPressed: () {
                          _textcontroller2.clear();
                        },
                        icon: const Icon(Icons.clear),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  } //widget build
}

class Thirdtask extends StatefulWidget {
  const Thirdtask({super.key});

  @override
  State<Thirdtask> createState() => _Thirdtask();
}

class _Thirdtask extends State<Thirdtask> {
  final _textcontroller3 = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.black,
        appBar: AppBar(
          backgroundColor: Colors.red,
          title: const Text('Tasks'),
          centerTitle: true,
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (_) => const Finaltask(),
              ),
            );
          },
          backgroundColor: Colors.red,
          child: const Text("Next"),
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Center(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                const Text(
                  "What is 8 x 7?",
                  style: TextStyle(
                    backgroundColor: Colors.white,
                    color: Colors.black,
                    fontSize: 30.0,
                  ),
                ),
                Expanded(
                  child: TextField(
                    controller: _textcontroller3,
                    decoration: InputDecoration(
                      hintText: "Type your answer here!",
                      border: const OutlineInputBorder(),
                      suffixIcon: IconButton(
                        onPressed: () {
                          _textcontroller3.clear();
                        },
                        icon: const Icon(Icons.clear),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  } //widget build
}

class Finaltask extends StatefulWidget {
  const Finaltask({super.key});

  @override
  State<Finaltask> createState() => _Finaltask();
}

class _Finaltask extends State<Finaltask> {
  final _textcontroller4 = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.black,
        appBar: AppBar(
          backgroundColor: Colors.red,
          title: const Text('Tasks'),
          centerTitle: true,
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (_) => const Congrats(),
              ),
            );
          },
          backgroundColor: Colors.red,
          child: const Text("Submit"),
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Center(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                const Text(
                  "Riddle: What goes up but never comes back down?",
                  style: TextStyle(
                    backgroundColor: Colors.white,
                    color: Colors.black,
                    fontSize: 30.0,
                  ),
                ),
                Expanded(
                  child: TextField(
                    controller: _textcontroller4,
                    decoration: InputDecoration(
                      hintText: "Type your answer here!",
                      border: const OutlineInputBorder(),
                      suffixIcon: IconButton(
                        onPressed: () {
                          _textcontroller4.clear();
                        },
                        icon: const Icon(Icons.clear),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  } //widget build
}

class Congrats extends StatefulWidget {
  const Congrats({super.key});

  @override
  State<Congrats> createState() => _Congrats();
}

class _Congrats extends State<Congrats> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.black,
        appBar: AppBar(
          backgroundColor: Colors.red,
          title: const Text('Good Job!'),
          centerTitle: true,
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (_) => const MyHomePage(),
              ),
            );
            //player.clear('explosion.mp3');  (to stop alarm)
            // ignore: avoid_print
            print("Alarm has stoped");
          },
          backgroundColor: Colors.red,
          child: const Text("Home"),
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Center(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: const [
                Expanded(
                  child: Text(
                    "Congratulations you completed your tasks, Click the home button to return home and stop the timer!",
                    style: TextStyle(
                      backgroundColor: Colors.white,
                      color: Colors.black,
                      fontSize: 30.0,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  } //widget build
}

A: Firstly, please delete all MaterialApp (except the first on the top). Because in Flutter app there must be only one MaterialApp throughout the code.
Secondly, juste change your padding 170 to 17 for exemple. 170 is extremely big.

A: Use single MaterialApp on top widget as @Antonin Liehn said. Now for the TextFormField border. You need to use enabledBorder, also try others border property , Find more about OutlineInputBorder.
decoration: InputDecoration(
  hintText: "Type your answer here!",
  enabledBorder: OutlineInputBorder(
    borderSide: BorderSide(
      color: Colors.white,
      width: 22,
    ),
  ),
  errorBorder: ,
  focusedBorder: ,
  disabledBorder: ,
  focusedErrorBorder: ,
  border: OutlineInputBorder(
    borderSide: BorderSide(
      color: Colors.white,
      width: 22,
    ),
  ),

Also wrap text with Flexible/Expanded widget. You cal follow this widget
class TasksPage extends StatefulWidget {
  const TasksPage({super.key});

  @override
  State<TasksPage> createState() => _TasksPageState();
}

class _TasksPageState extends State<TasksPage> {
  final _textcontroller = TextEditingController();
  final border = const OutlineInputBorder(
      borderSide: BorderSide(
    color: Colors.white,
    width: 22,
  ));
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.red,
        title: const Text('Taskssssssss'),
        centerTitle: true,
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (_) => const SecondTask(),
            ),
          );
        },
        backgroundColor: Colors.red,
        child: const Text("Next"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Center(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Flexible(
                child: const Text(
                  "How many states are there in the United States of America?",
                  style: TextStyle(
                    backgroundColor: Colors.white,
                    color: Colors.black,
                    fontSize: 30.0,
                  ),
                ),
              ),
              Expanded(
                child: TextFormField(
                  controller: _textcontroller,
                  decoration: InputDecoration(
                    hintText: "Type your answer here!",
                    enabledBorder: OutlineInputBorder(
                      borderSide: BorderSide(
                        color: Colors.white,
                      ),
                    ),
                    errorBorder: border,
                    focusedBorder: border,
                    disabledBorder: border,
                    focusedErrorBorder: border,
                    border: border,
                    suffixIcon: IconButton(
                      onPressed: () {
                        _textcontroller.clear();
                      },
                      icon: const Icon(Icons.clear),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  } //widget build
}


text:
Q: Stylecop doesn't understand  I'm trying to use Stylecop 4.7.31
I have a project, where an interface is declared:
public interface IRmlManager
{
    /// <summary>
    /// Adds the notification.
    /// </summary>
    /// <param name="notificationData">The notification data.</param>
    void AddNotification(RmlNotificationData notificationData);
}

and another project, where an implementation of the interface:
public class RmlManager : IRmlManager
{
........
    /// ???
    void AddNotification(RmlNotificationData notificationData);
........
}

if I use <inheritdoc /> instead of ???, Stylecop ignores it and produces errors:
BusinessLogic\RmlManager.cs(39,1): error : SA1604: The documentation header must have a summary tag.
BusinessLogic\RmlManager.cs(39,1): error : SA1611: The documentation header must contain param tags matching the element's parameter list.

have any ideas what I'm doing wrong?
According to google, Stylecop supports this tag starting approximately from 4.1 version

A: I hate to tell you, but Inheritdoc IS supported by StyleCop, as per http://stylecop.codeplex.com/workitem/6637.
So, this can only be assumed to be a - well - specific instance (i.e. it does undrestand inheritdoc, just this particular example is a bug behavior).
Given that inheritdoc is generally accepted, I Would suggest you ask on a stylecop specific list (open a discussion on their site on codeplax at http://stylecop.codeplex.com/discussions) and possibly make a repro case and open a bug.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ADT not detecting HTC One in debug mode I have recently installed the official update to Android 4.3/Sense 5.5 for my HTC One, and now when I try to run my Android applications via ADT it doesn't recognize my device anymore. One thing I noted to be different than the previous version is that it now starts with the debug mode right away, and the option to enable/disable it to use HTC Sync is gone. So I have tried enabling the Developer options to disable debugging and enable it again, nothing happened - the phone says "USB debugging connected" but ADT won't detect it.
My projects' Target SDK are all set to 18 and min SDK 11 and they were running before when my phone had Android 4.2.2/HTC Sense 5.
Has anyone experienced the same problem lately? I tried to find similar issues but since this upgrade is recent for HTC One then maybe not many people had this issue yet...
Thanks for your help!

A: I guess the version problem causing the damage for you..
 see the answer below it would help you...
Android: ADB Driver for HTC One X


text:
Q: Where can I find the list of allowed colors for android notification icons? It seems as if android doesn't except all colors.
When I set it to a certain green, the icon is green but different. Same goes if I try a certain red for example. It's like android sets it to the closest color out of a list of allowed colors.
Is there a list somewhere I can choose from?
I'm talking about the color of the icon on the top left.

A: for the notification icon color , first the icon should be in white color , all of it and then you can customize the color you want within your builder :
mBuilder.setColor(ContextCompat.getColor(context, R.color.colorPrimary));


text:
Q: If my app is open or in background i got the notifications. But if i force closed to my app i don't get the notification How to show the notification to user even app is not running or force closed by user.
If my app is open or in background i got the notifications. But if i force closed to my app i don't get the notification in xcode 8.3 and swift 3 iOS
if #available(iOS 10.0, *) {
            let center  = UNUserNotificationCenter.current()
            //center.delegate = self
            center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
                if error == nil{
                    UIApplication.shared.registerForRemoteNotifications()
                }
            }
        }
        else {
            UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil))
            UIApplication.shared.registerForRemoteNotifications()
        }

In this way i am registering for notifications


text:
Q: Equivalence of Kahler structures of based loop group and its Grassmannian model In Pressley-Segal's Loop Groups, we have the following spaces equipped with Kahler structures. Let $G$ be a compact, connected, (simply connected) group with Lie algebra $\mathfrak g$.

*

*Let $\mathcal H^{\mathfrak g} = L^2(S^1,\mathfrak g)$ equipped with a polarization $\mathcal H^{\mathfrak g} = \mathcal H_+ \oplus \mathcal H_-$. Consider the corresponding Grassmannian $\text{Gr}^{\mathfrak g}$ consisting of linear subspaces $W \subseteq \mathcal H^{\mathfrak g}$ such that

*

*Projection onto $\mathcal H_+$ is Fredholm and projection onto $\mathcal H_-$ is Hilbert-Schmidt.

*$zW \subseteq W$ (where $z$ is the $S^1$ coordinate, thinking of elements of $\mathcal H^{\mathfrak g}$ in their Fourier basis $\{ z^k \}$. )

Then $\text{Gr}^{\mathfrak g}$ has a Kahler structure whose Kahler form is induced by
$$ \omega(X,Y) = -i \text{Trace}(X^*Y-Y^*X)$$
where $\omega$ is defined at $T_{\mathcal H_+} \text{Gr}^{\mathfrak g}$ as identified with the collection of Hilbert-Schmidt operators from $\mathcal H_+ \to \mathcal H_-$.

*Let $\Omega G$ be the collection of identity preserving smooth maps $S^1 \to G$. Give this the Kahler form by specifying that at $\Omega \mathfrak g$ we have
$$\omega(\gamma,\eta) = \frac1{2\pi} \int_{S^1} \langle \eta,\gamma' \rangle $$
where $\langle,\rangle$ is some $\text{Ad}$-invariant inner product on $\mathfrak g$.

It is known that $\Omega G$ is biholomorphic to $\text{Gr}^{\mathfrak g}$ under the map $ \gamma \mapsto \gamma \mathcal H_+$ where
$$ \gamma \mathcal H_+ = \{ \text{Ad}_{\gamma(z)} X(z): X \in \mathcal H_+\}.$$
I wonder if the Kahler structures are similarly equivalent. I have tried to pullback the Kahler form under the above biholomorphism, but to no avail.


text:
Q: Does deleting an argo cron workflow delete all argo workflows started by it as well It looks like the case that when I delete an Argo cron workflow with argo cron delete, all the previous workflows (completed as well as still running ones) will also be deleted based on my observation. I'm not totally sure though and I haven't found a more detailed doc than https://argoproj.github.io/argo/cli/argo_cron_delete/.
What if I'd like to keep all the history workflows when e.g. updating the frequency of a cron workflow, e.g. to run every Monday instead of every day? What would be the recommended way to do such an update?

A: To add to Michael's answer:
CronWorkflows are owners of all the Workflows they spawn, so how their respective Workflows are deleted when the parent CronWorkflow is deleted is governed by Kubernetes' Garbage Collection policies. Argo does not delete the child Workflows of a CronWorkflow when the latter is deleted, Kuebrnetes does. You can see the Kubernetes doc for more options on how to manage this.
(Edit: adding more info)
For example, to delete a CronWorkflow while leaving its children Workflows intact, you can run:
kubectl delete cwf my-cwf --cascade=false

Source: I developed the CronWorkflow feature.

A: If you want to keep workflow data around for a while, you should persist them to a database using Argo's workflow archive tool.
Just to confirm your issue, I did a quick test using their "hello-world" cron workflow:
apiVersion: argoproj.io/v1alpha1
kind: CronWorkflow
metadata:
  name: hello-world
spec:
  schedule: "* * * * *"
  timezone: "America/Los_Angeles"   # Default to local machine timezone
  startingDeadlineSeconds: 0
  concurrencyPolicy: "Replace"      # Default to "Allow"
  successfulJobsHistoryLimit: 4     # Default 3
  failedJobsHistoryLimit: 4         # Default 1
  suspend: false                    # Set to "true" to suspend scheduling
  workflowSpec:
    entrypoint: whalesay
    templates:
      - name: whalesay
        container:
          image: docker/whalesay:latest

Deleting the cron workflow does indeed delete the hello-world workflow kicked off by it. I'm especially confident because I have other workflows that have been sitting on my Minikube cluster for days without being deleted.
If you don't want to use the workflow archive, you can use kubectl edit cronworkflow <workflow name>. I just tested, and the update will not delete the child workflows.
If you're using something like Kustomize or Helm, it's possible your changes might delete/recreate the cron workflows rather than simply patching them. You'd have to check the docs of those projects.
I agree, the docs should be more clear. I'd recommend opening a PR against their argo cron delete page.


text:
Q: Best way of structuring Javascript If statements to be synchronous in a function I'm asking this question so I can learn the 'best practice' way of doing something in javascript. Say I have this code here:
var someFunc = function () {
  if (something) {
    // do something
  }
  if (somethingElse) {
    // do somethingElse
  }
};

The question is what would be the best way to ensure that the 'something' is always ran BEFORE the 'somethingElse'. Since javascript is asynchronous, I understand that I would need some sort of callback system to ensure this. However, is there an easier way to refactor this? What if there are many if statements? What are the best libraries to do something like this cleanly? Thanks in advance.

A: Not all lines of code run asynchronously in Javascript. It depends on your code. For example:
var someFunc = function () {
  if (something) {
    console.log('something');
  }
  if (somethingElse) {
    console.log('something else');
  }
};

Will always write the following output:
something
something else

However if instead of printing the values you are calling a function that will be run later (like an Ajax request or a setTimeout callback), there is no guarantee that your code is run in the exact order. This behaviour depends on the function you are calling. For example the JQuery $.get() function is asynchronous (which means it will call your function at a later time that is not in your control) like this:
var someFunc = function () {
  if (something) {
    $.get('some-file.txt').done(function (result) {
      console.log(result);
    });
  }
  if (somethingElse) {
    $.get('some-other-file.txt').done(function (result) {
      console.log(result);
    });
  }
};

The resulting output can be the contents of 'some-file.txt' and 'some-other-file.txt' in any other.
As a rule of thumb whenever you are passing a function to another function (callbacks) you may be using the asynchronous feature of Javascript.

Nested callbacks
One way to solve this issue is to call the second asynchronous call in the first function:
var someFunc = function () {
  if (something) {
    $.get('some-file.txt').done(function (result1) {
      console.log(result1);
      if (somethingElse) {
        $.get('some-other-file.txt').done(function (result2) {
          console.log(result2);
        });
      }
    });
  }
};

But as you might have guessed this code will be hard to read.

Promises to the rescue
With Promises you can have a code that is easier to read.
Let's write the above ugly code with promises:
var someFunc = function () {
  if (something) {
    $.get('some-file.txt').then(function (result1) {
      console.log(result1);
      if (somethingElse) {
        return $.get('some-other-file.txt');
      }
    }).then(function (result2) {
        console.log(result2);
    });
};

In general, promises make the code more readable and avoid too many nested callbacks. You can chain promises and it will read like synchronous code but it actually runs asynchronously.
See these questions to get more information:

*

*How do I chain three asynchronous calls using jQuery promises?

*Chain of Jquery Promises
What's the catch with promises?

*

*They are not supported in old browsers (but you can add them with a 3rd party library like ES6 Promise Polyfill.

*Before the promises were officially standardized every library had their own implementation which are slightly incompatible (jQuery, Angular, Ember)

*They are a new concept to learn so the learning curve will be a little steep for newcomers.

A: Javascript is not asynchronous.
Provided both the if conditions are satisfied, what is inside the first if will get executed first and then the contents of the second if will be executed.


text:
Q: Passing a void* pointer and then cast in C I'm passing a pointer to my function, but the type of this pointer may change. I don't want to write several versions of this function such as func_float() and func_int(). So I'm passing a pointer of void* to my function and then type casting to int* or float* which depends on an argument type. Here's my code:
void func(void* pSrc, float* pDst, int len, int type)
{
    if (type == 0)
        float* pIn = (float*)pSrc;
    else
        int* pIn = (int*)pSrc;
    float* pOut = pDst;
    while (len--)
        *pOut++ = (float)*pIn++ * 2.0;  // cast to float and then do some math
}

int main()
{
    int input[3] = { 1,2,3 };
    float output[3] = { 0 };
    func(input, output, 3, 1);
    return 0;
}

But this seems not work. VS told me that a dependent statement may not be a declaration. I tried to declare pIn as void* before if, but I got another error expression must be a pointer to a complete object type when I dereference the pointer pIn.
Any help would be appreciated.

A: There's lots of problems here. Wrong number of parameters, wrong types used, wrong scope for variables - very fundamental stuff.
In addition, you cannot do arithmetic on void pointers. gcc provides that as a non-standard extension, but then my_void_pointer++ doesn't mean "increase 1 item" but "increase 1 byte", similar to character type pointers.
Since the void pointer doesn't contain any type information, the compiler can't know many bytes the pointed at item contains. I'd advise to simply forget about void pointer arithmetic and gcc extensions in general.
To answer the question of how to do this in C, there are 3 different ways I can think of:

The KISS principle/common sense solution is to simply avoid type-generic programming in C - its usefulness is overall overrated - and write two separate functions:
#include <stdio.h>

void func_int (int* dst, const int* src, size_t size)
{
  for(size_t i=0; i<size; i++)
  {
    dst[i] = src[i] * 2;
  }
}

void func_float (float* dst, const float* src, size_t size)
{
  for(size_t i=0; i<size; i++)
  {
    dst[i] = src[i] * 2;
  }
}

int main (void)
{
    int input_i[3] = { 1,2,3 };
    int output_i[3];
    func_int(output_i, input_i, 3);
    for(size_t i=0; i<3; i++)
    {
      printf("%d ", output_i[i]);
    }

    puts("");

    float input_f[3] = { 1.0f, 2.0f, 3.0f };
    float output_f[3];
    func_float(output_f, input_f, 3);
    for(size_t i=0; i<3; i++)
    {
      printf("%f ", output_f[i]);
    }
}

If you still insist on type-generic programming ("Keep it complicated for the sake of complexity"), then you can use standard C _Generic:
#define func(dst,src,size) _Generic((dst), int*: func_int, float*: func_float) (dst,src,size)

func(output_i, input_i, 3);
func(output_f, input_f, 3);

And finally you can do "template meta programming" in the same manner, by using a combination of _Generic and X-macros to generate the function itself ("Keep it stupidly complicated")
#include <stdio.h>

#define SUPPORTED_TYPES(X) \
  X(int)                   \
  X(float)                 \

#define FUNC_DEFINITIONS(type)                              \
void func_##type (type* dst, const type* src, size_t size)  \
{                                                           \
  for(size_t i=0; i<size; i++)                              \
  {                                                         \
    dst[i] = src[i] * 2;                                    \
  }                                                         \
}
SUPPORTED_TYPES(FUNC_DEFINITIONS)

#define GENERIC_LIST(type) ,type*: func_##type
#define func(dst,src,size) _Generic((dst) SUPPORTED_TYPES(GENERIC_LIST)) (dst,src,size)

int main (void)
{
    int input_i[3] = { 1,2,3 };
    int output_i[3];
    func(output_i, input_i, 3);
    for(size_t i=0; i<3; i++)
    {
      printf("%d ", output_i[i]);
    }

    puts("");

    float input_f[3] = { 1.0f, 2.0f, 3.0f };
    float output_f[3];
    func(output_f, input_f, 3);
    for(size_t i=0; i<3; i++)
    {
      printf("%f ", output_f[i]);
    }
}

Overall, good programmers keep their code simple and bad programmers try to write it as complex as possible. That's why you should think twice before deciding which of these 3 versions to use.

A: The variables cease to exist at the end of their scope. You would have to do something like this:
void func(void* pSrc, float* pDst, int len, int type)
{
    if (type == 0)
        func_float(pSrc, pDst, len);
    else
        func_int(pSrc, pDst, len);
}

and then implement func_float and func_int
If you want to support many types, this could be good:
void foo(void* pSrc, float* pDst, int len, int type)
{
    switch(type) {
        case 0: func_float(pSrc, pDst, len); break;
        case 1: func_int(pSrc, pDst, len); break;
        // More cases:
        default: perror("Invalid type"); exit(EXIT_FAILURE);
    }
}

A: You are, in effect, trying to make the type of your pIn variable differ, depending on the value of the passed-in type flag.  But there's no way to do that.  Each variable must have exactly one type, known at compile time.
The closest you could achieve to what you're trying to do would probably be something like this:
void func(void *pSrc, float *pDst, int len, int type)
{
    char *pIn = pSrc;        /* char * so can do pointer arithmetic */
    float *pOut = pDst;
    while (len--) {
        *pOut++ = (type == 0 ? *(float *)pIn : *(int *)pIn) * 2.0;

        if (type == 0)
             pIn += sizeof(float);
        else pIn += sizeof(int);
    }
}

This is kind of an ugly kludge, however.  If your actual func is more complicated, it might be worth it.  But if all you're doing is multiplying by 2, it would probably cleaner to just bite the bullet and use two separate functions.  (Sorry, I know you said that's not what you wanted to do.)
The subexpression (type == 0 ? *(float *)pIn : *(int *)pIn) is somewhat of a jawbreaker as I've written for.  (C is both celebrated, and notorious, for allowing this kind of pithiness.)  You might prefer to write things out in a more "longhand" way:
void func(void *pSrc, float *pDst, int len, int type)
{
    char *pIn = pSrc;        /* char * so can do pointer arithmetic */
    float *pOut = pDst;
    while (len--) {
        double inVal;

        if (type == 0) {
            inVal = *(float *)pIn;
            pIn += sizeof(float);
        } else {
            inVal = *(int *)pIn;
            pIn += sizeof(int);
        }

        *pOut++ = inVal * 2.0;
    }
}

This second formulation would also make things easier and cleaner if you have more different values for type, or if you're doing more involved things with inVal.

Addendum: Here's a completely different approach.  In your original problem statement, you had either an array of int, or an array of float, and you wanted to multiply every element by 2, without repeating too much code.  I assume that in your actual situation, you have functions to apply that are more involved than just "multiply by 2".
If you're comfortable using function pointers, you could literally write a pair of "apply function to int" and "apply function to float" functions, with the actual do-the-work function specified separately, and exactly once.  Here are the two "apply function" functions:
void apply_func_to_int(double (*func)(double), int *pSrc, float *pDst, int len)
{
    for(int i = 0; i < len; i++)
        pDst[i] = func(pSrc[i]);
}

void apply_func_to_float(double (*func)(double), float *pSrc, float *pDst, int len)
{
    for(int i = 0; i < len; i++)
        pDst[i] = func(pSrc[i]);
}

As you can see, they are very, very similar to each other — basically a copy-and-paste job — but they're both so short, the repetition isn't too objectionable.
Here is the function to apply:
double func(double x)
{
    return x * 2;
}

Notice that you only have to write this function once.  It accepts and returns a double, for reasonably full generality.
Putting it all together:
int main()
{
    int i;
    int input[3] = { 1, 2, 3 };
    float output[3] = { 0 };
    apply_func_to_int(func, input, output, 3);
    for(i = 0; i < 3; i++) printf("%f ", output[i]); printf("\n");

    float input2[3] = { 1.1, 2.2, 3.3 };
    apply_func_to_float(func, input2, output, 3);
    for(i = 0; i < 3; i++) printf("%f ", output[i]); printf("\n");
}

And of course you can apply other functions:
#include <math.h>

/* ... */

    float input3[4] = { 2, 10, 25, 1.44 };
    apply_func_to_float(sqrt, input3, output, 4);
    for(i = 0; i < 4; i++) printf("%f ", output[i]); printf("\n");


text:
Q: HttpUrlConnection headers response code is 403 The response http code of the given snippet at the end of this post is 403. 403 means forbidded. But i am accessing and posting into it through google chrome POSTman app. I am unable to resolve the problem in this case. I have tried many other solutions like:
httpURLConnection.setRequestProperty("Authorization","Basic "+Header);
httpURLConnection.setRequestProperty("ApiKey","abcd1234");
  HttpURLConnection httpURLConnection = (HttpURLConnection) (new URL ("http:abc.com")).openConnection();
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Authorization",Header);
          //  Header = "ApiKey:abcd1234" ;
            httpURLConnection.setRequestProperty("Content-Type","application/json");

A: BASIC authentication data needs to be baase64 encoded, something like
String encoded = Base64.encode(username+":"+password); connection.setRequestProperty("Authorization", "Basic "+encoded);


text:
Q: Retrieving ajax data synchronously back to calling function I have a form featuring the google captcha code: http://code.google.com/p/cool-php-captcha.
As this captcha uses a session to store the captcha I am having difficulty retrieving the upto date variable of the session into javascript through ajax. It was working well when my ajax command was using the async: false flag but as this is being depreciated I would rather not use it.
My problem at the moment is that I am trying to use a callback function to retrieve the value but by trying to send the value back to the original function I am creating a loop between my 2 functions and can't quite figure out the best way to get what I want.
thanks for any help cheers Callum

My form is as follows:
<form id="ContactForm" name="ContactForm" action="javascript:loadDoc();" onsubmit="return(validate());">
 Name *
 <input id="ContactFormInput" name="Fullname" class="text" id="Fullname">
 Email *
 <input id="ContactFormInput" name="Emailadd" class="text" id="Emailadd">
 Subject *
 <input id="ContactFormInput" name="Subject" class="text" id="Subject">
 Message *
 <textarea id="Message" name="Message" rows="6" cols="30"></textarea>
Captcha *

<input name="CaptchaText" id="CaptchaText" maxlength="8" class="text">

<input id="Submit" class="ContactButton" type="submit" name="submit" class="button" value="Send Now"/>

</form>

My php session page has
<?php
session_start();

echo $_SESSION['captcha'];
?>


text:
Q: left join error of non-existing column I have got 2 tables ( pseudo code below )
prod_categories->   id  name  hex_name
prod_categories_translate ->    id  id_cat translate
where id.prod_categories == id_cat.prod_categories_translate

So id's in both tables are the same.
SQL gives me an error -> Unknown column 'hex_name.prod_categories' in 'field list'.  I'm not sure why, because that column exists. Here is my query
SELECT hex_name.prod_categories, name.prod_categories, id.prod_categories, translate.prod_categories_translate FROM prod_categories LEFT JOIN prod_categories_translate ON id.prod_categories=id_cat.prod_categories_translate

How can I remove this error?

A: I think there is an sql syntax error.
Try this:
SELECT prod_categories.hex_name,
prod_categories.name,
prod_categories.id,
prod_categories_translate.translate
FROM prod_categories
LEFT JOIN prod_categories_translate ON prod_categories_translate.id_cat=prod_categories.id


text:
Q: Removing duplicate rows from hashtable Hi there I have a grid which is being populated with user results on educational courses they have taken part in. For each user they have their own grid showing them each course they have done and their status of each time they have tried the course. For example:
CourseTitle   | Status
Excel,                                     incomplete
Body Language,                             complete
Body Language,                             abandoned
Body Language,                             incomplete
Body Language,                             completed
Body Language,                             completed
After removing duplicates the table should look like this:
CourseTitle   | Status
Excel,                                     incomplete
Body Language,                             complete
Body Language,                             abandoned
Body Language,                             incomplete
I was trying to do it like this:
public static DataTable RemoveDuplicateRows(DataTable dTable, string colName, string colTitle)
    {
        Hashtable hTable = new Hashtable();
        ArrayList duplicateList = new ArrayList();
    foreach (DataRow drow in dTable.Rows)
    {

        if (hTable.Contains(drow[colName]) && hTable.Contains(drow[colTitle]))
        {
            duplicateList.Add(drow);
        }
        else
            hTable.Add(drow[colName], drow[colTitle]);
    }

    foreach (DataRow dRow in duplicateList)
        dTable.Rows.Remove(dRow);

    return dTable;
}

But this way gives me an error:
Item has already been added. Key in dictionary: 'incomplete' c#
I now know that you cannot have duplicated keys in key,value pairs. Does anyone know a way around this or a different method I could use to solve this problem. Sorry forgot to add that this needs to be added to a datatable.
Cheers, James

A: Try to use Dictionnary or Dictionnary instead of a Hashtable.
If you want to keep all statuses use Dictionary>. The key is the course and you will have the list of statuses in the value part (list).
If i take your code it will be like this:
Dictionary<string, List<string>> values = new Dictionary<string, List<string>>();
        foreach (DataRow drow in dTable.Rows)
        {

            if (values.ContainsKey(drow[colName]))
            {
                if(values[row[colName]] == null)
                    values[row[colName]] = new List<string>();

                if (!values[row[colName]].Contains(drow[colTitle]))
                    values[row[colName]].Add(drow[colTitle]);
            }
        }

        return values;

Hope this helps.


text:
Q: How do I test the Sync feature of the chrome extension during development I am building a chrome extension which requires you to sign in to chrome before using it, post which you could save some values (which I store it in the Sync storage)  and the same is expected to get Synced whenever I Sign into chrome from some other machine using the same Sign in info.
I tested the extension and the info is being stored successfully on the machine where i am saving it. But the same info is not synced to the other machine. Just to make it clear,I have also installed the extension in the other machine's chrome as well.
I have used the following code in the background js for syncing purpose-
chrome.storage.onChanged.addListener(function(changes, areaname) {
          if(areaname=="sync")
          {alert('Storage Changed' + changes);}}

so that I get an alert indicating that the event is getting fired.
I don't get this alert in the other machine; indicating the sync didnt happen.
I looked up  Sync settings,it shows that the sync just happened. But there was no alert.
Is it so, that we can test syncing during development of the extension ?
I have been through Does-chrome-app-id-for-extensions-affect-sync-storage
Does the App Id has to do anything with it ??
UPDATE -  I found the answer. Let me elaborate how I did it. -
This page developer.chrome.com/extensions/packaging explains how to package and extension manually. Please go through that before proceeding.
Step 1 - I deleted the extension that I had installed in both the machines.( I had installed it using the Load unpacked extension option before)
Step 2 - I followed the link above and made a manual package file with .crx and .pem file
Step 3 - While I was signed in into the two machines using the same gmail account, I shared and installed this .crx file by drag-dropping the file into the browser. (It asks for confirmation and proceeds to install)
Step 4 - After following Step-3 on both the machines, I now have my extensions installed in both browsers.
Step 5- I saved values using my extension in one browser and voila, after a while, it appeared in the other machine.
Step 6- But One important thing though, the data was synced automatically without the alert that I wanted to display-
if(areaname=="sync") {alert('Storage Changed' + changes);}}

So I assume that this listener code was not important in my case anyways. Hope this helps other guys looking for the solution.


text:
Q: how to replace [ symbol from string? Have this symbol from my list which coming from server Begin: [[ End: ]]
This is must be just one not two. How I can remove other one?
Thanks.

A: String s = "Begin: [[ End: ]]";

// will replace two square brackets with one
s = s.replace("[[", "[").replace("]]", "]");

with regular expression
String s = "Begin: [[ End: ]]";

// will replace two or more square brackets with one
s = s.replaceAll("\\[\\[+", "[").replaceAll("\\]\\]+", "]");

A: try using the String .replace method.
You should be able to do something like this:
yourString.replace("[[", "[");
If this is not enough to you, please give me more details about your problem.

A: Simply remove first and last character
String message = "[[message]]";
message = message.substring(1, message.length()-1);


text:
Q: Libreoffice Base - Triggering stock table deductions from orders table I'm working on a DB that consists mostly of two tables. One with our stock of memorial markers, and the other where I keep a running list of ongoing and completed orders.
When I change an ongoing order in the Orders table to completed I would like to have one of the corresponding memorial markers deducted from that size category in the stock table.
I've mostly been building this using the form designer and wizards but I am comfortable with coding, though I'm not super familiar with SQL. Some pointers in the right direction should to get me going should help. I've been searching around but keep getting results for other things.
Thanks for your time


text:
Q: I can't verify if there is a duplicate email in my local db. When I register for the first time it's working and the second time I got an error And I know my error is due to email adress because when I submit a new user to the form, it's working well but when I change all the informations except the email adress I got the error 500 Internal Server Error
My code for register
<?php

include 'DbConnect.php';
$objDb = new DbConnect;
$conn = $objDb->connect();

$data = json_decode(file_get_contents('php://input')) ;

$first_name = $data->first_name;
$name = $data->name;
$email = $data->email;
$password = $data->password;
$password_confirm = $data->password_confirm;

$password_hash = password_hash($password, PASSWORD_DEFAULT);

$method = $_SERVER['REQUEST_METHOD'];

switch($method){
    case "POST":

        $sql = "INSERT INTO register(name, first_name, email, password_hash) VALUES ('$name', '$first_name', '$email', '$password_hash')";
        $stmt = $conn->prepare($sql);

        if($stmt->execute()){
            $response = ['status' => 1, 'message' => 'Record created succesfully. '];
        }else{
            $response = ['status' => 0 , 'message' => 'Failed to create record. '];
        }

        echo json_encode($response);
        break;
}
?>

A: if you want to have duplicate email, you should change your SQL code and remove unique index on the email field.
and if you don't want, you can use below code to prevent duplicate emails to your database:
<?php

include 'DbConnect.php';
$objDb = new DbConnect;
$conn = $objDb->connect();

$data = json_decode(file_get_contents('php://input')) ;

$first_name = $data->first_name;
$name = $data->name;
$email = $data->email;
$password = $data->password;
$password_confirm = $data->password_confirm;

$email_duplicate = "SELECT EXISTS(SELECT * FROM register WHERE email = '$email')";
if($email_duplicate) {
    exit("the $email already used, please enter another email.");
}

$password_hash = password_hash($password, PASSWORD_DEFAULT);

$method = $_SERVER['REQUEST_METHOD'];

switch($method){
    case "POST":

        $sql = "INSERT INTO register(name, first_name, email, password_hash) VALUES ('$name', '$first_name', '$email', '$password_hash')";
        $stmt = $conn->prepare($sql);

        if($stmt->execute()){
            $response = ['status' => 1, 'message' => 'Record created succesfully. '];
        }else{
            $response = ['status' => 0 , 'message' => 'Failed to create record. '];
        }

        echo json_encode($response);
        break;
}
?>


text:
Q: google plugin services gives me an error In gradle, at the end, I'm trying to insert this line
apply plugin: 'com.google.gms.google-services'
but whenever I sync the file I get this error:
Error:FAILURE: Build failed with an exception.

*

*What went wrong:
Execution failed for task ':app:processDebugGoogleServices'.

File google-services.json is missing. The Google Services Plugin cannot function without it.
  Searched Location:
  C:\Users\USER\AndroidStudioProjects\MyListViewApp\app\src\nullnull\debug\google-services.json
  C:\Users\USER\AndroidStudioProjects\MyListViewApp\app\src\debug\nullnull\google-services.json
  C:\Users\USER\AndroidStudioProjects\MyListViewApp\app\src\nullnull\google-services.json
  C:\Users\USER\AndroidStudioProjects\MyListViewApp\app\src\debug\google-services.json
  C:\Users\USER\AndroidStudioProjects\MyListViewApp\app\src\nullnullDebug\google-services.json
  C:\Users\USER\AndroidStudioProjects\MyListViewApp\app\google-services.json

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

*Get more help at https://help.gradle.org
BUILD FAILED in 1s
Can anyone help?

A: As error says File google-services.json is missing, you have not included google-service json file in your project. Which is configuration file needed if you use any google api.
To include google-service.json in your project
Please go to this URL :
https://developers.google.com/mobile/add
Choose your Options and  finally you will be able to download
google-service.json file
copy that file and paste it Into
YourProjectName/app  Directory and build project.


text:
Q: Error in WCF client running under IIS 5.0 with server on Windows 2008 I have a .Net 3.5 SP1 WCF service running under IIS 7 on a Windows 2008 machine.  When I try to connect to this service from an IIS hosted WCF service running under IIS 5.0 (Windows XP) .Net 3.5 SP1, I get the following error:
The token provider cannot get tokens for target: http://(URL for WCF service)
I've built a simple console application that can successfully connect to the WCF service using the exact same configuration.  I've also built a simple web application hosted under the WebDev server (ASP.Net server that comes with Visual Studio 2008) and it is able to successfully connect to the WCF service.  When I configured a virtual directory within IIS (Windows XP) to point at the same directory as the WebDev server, I get the following error:
No credentials are available in the security package
But, if I set the web.config to turn impersonation on using my logon credentials, it works fine.  This is not a good long term solution for obvious reasons.  The one difference that I've noted between IIS and the WebDev servers are the user that each process is running under.  IIS runs under the ASPNet account and WebDev runs under my account.
Here's the config for the WCF section on the client:
<system.serviceModel>
<behaviors>
  <serviceBehaviors>
    <behavior name="mexBehavior">
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />
      <serviceThrottling maxConcurrentCalls="200" maxConcurrentSessions="200" />
    </behavior>
  </serviceBehaviors>
</behaviors>
<bindings>
  <wsHttpBinding>
    <binding name="FABindings" maxReceivedMessageSize="2147483647">
      <readerQuotas maxStringContentLength="300000"/>
      <security mode="Message">
        <message clientCredentialType="Windows" negotiateServiceCredential="false" establishSecurityContext="false" />
      </security>
    </binding>
  </wsHttpBinding>
</bindings>
<client>
  <endpoint address="http://<server url>/FinancialAggregator/v3/Services/FAService.svc"
      binding="wsHttpBinding" bindingConfiguration="FABindings"
      contract="ServiceReference1.IFilteredService" name="FAServiceEndpoint">
    <identity>
      <servicePrincipalName value="<UsernameRunningTheAppPoolOnW2k8>" />
    </identity>
  </endpoint>
</client>

Here's the server config (as requested):
  <system.serviceModel>
<bindings>
  <wsHttpBinding>
    <binding name="wsHttpBinding" maxReceivedMessageSize="2147483647">
      <security mode="Message">
        <message establishSecurityContext="false" negotiateServiceCredential="false" />
      </security>
    </binding>
  </wsHttpBinding>
</bindings>
<behaviors>
  <serviceBehaviors>
    <behavior name="mexBehavior">
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="false" />
      <serviceDebug includeExceptionDetailInFaults="true" />
      <serviceThrottling maxConcurrentCalls="200" maxConcurrentSessions="200" />
    </behavior>
  </serviceBehaviors>
</behaviors>
<services>
  <service behaviorConfiguration="mexBehavior" name="FCSAmerica.Financial.Aggregator.Service.FilteredService">
    <endpoint name="FAServiceEndpoint" address="" binding="wsHttpBinding" bindingConfiguration="wsHttpBinding" contract="FCSAmerica.Financial.Aggregator.Service.IFilteredService">
    </endpoint>
  </service>
</services>

Any thoughts on the cause of this error?
Thanks!

A: When you access the services via IIS, with impersonate = false, then it is the ASPnet account which is used to access the service on the Windows 2008 machine.
The ASPnet account is a local account and therefore does not have rights on the 2008 machine.
There are 3 ways you could solve this:

*

*Allow annonymous access to the service on the Windows 2008 machine

*Use impersonate = true (as you have)

*Change the identity of the application pool from aspnet to a domain account with the required access.

A: I guess the ultimate answer to this question is to simply upgrade to an OS that allows you to set the identity of an application pool, which I have done ages ago.
Thanks for the consideration.
Matt


text:
Q: How to add a in-app browser in React Native (Expo) How to open a web browser in expo rather than using the expo browser.I want open the browser in inside the app.

A: you can use the following library react-native-inappbrowser
follow the installation from the github page
import { Linking } from 'react-native'
import InAppBrowser from 'react-native-inappbrowser-reborn'

...
  async openLink() {
    try {
      const url = 'https://www.google.com'
      if (await InAppBrowser.isAvailable()) {
        const result = await InAppBrowser.open(url, {
          // iOS Properties
          dismissButtonStyle: 'cancel',
          preferredBarTintColor: '#453AA4',
          preferredControlTintColor: 'white',
          readerMode: false,
          animated: true,
          modalPresentationStyle: 'overFullScreen',
          modalTransitionStyle: 'partialCurl',
          modalEnabled: true,
          // Android Properties
          showTitle: true,
          toolbarColor: '#6200EE',
          secondaryToolbarColor: 'black',
          enableUrlBarHiding: true,
          enableDefaultShare: true,
          forceCloseOnRedirection: false,
          // Specify full animation resource identifier(package:anim/name)
          // or only resource name(in case of animation bundled with app).
          animations: {
            startEnter: 'slide_in_right',
            startExit: 'slide_out_left',
            endEnter: 'slide_in_left',
            endExit: 'slide_out_right'
          },
          headers: {
            'my-custom-header': 'my custom header value'
          },
          waitForRedirectDelay: 0
        })
        Alert.alert(JSON.stringify(result))
      }
      else Linking.openURL(url)
    } catch (error) {
      Alert.alert(error.message)
    }
  }
...

you can check the example app here
for expo it becomes little bit complicated please check the related tutorial by Medium
if you want reading mode in ios please refer this link
reader-mode-webview-component-for-react-native

A: The expo-web-browser package opens an in app browser.
This worked for me with expo. I tried react-native-inappbrowser-reborn first, but isAvailable() was throwing an error.
import * as WebBrowser from 'expo-web-browser'

...
WebBrowser.openBrowserAsync(url, {showTitle: true})


text:
Q: Is there anything that blocks reaction in Svelte? Does Svelte have anything that blocks reaction to prevent loops? I have a child component that is calling a function passed down from a parent, which in turn sets a value that gets passed down to the child as a prop. The potential exists for an infinite loop. I don't have an infinite loop, but I'm seeing Svelte refuse to react a change to that prop the component that initiated the change. Any thoughts?

A: Figured it out... Svelte only dirties each component once per update cycle... my circular component dependency resulted in two conceptual dirties but Svelte only reacted on the first one... the fix was to add await tick() between these to ensure that the second change is in a new update cycle. Bingo, it reacts properly now.


text:
Q: Is there a way to get data together with aggregations using graphql subscribtions?
I have a social network kind of web app which includes graphql by react-apollo-client (my graphql server is a Hasura instance).
I have notifications feature in my app and I query the notifications details together with count aggregation to show the user how many notifications he has before displaying it.
Recently I added web sockets to my app and refactor my notifications query to be a subscribtion. It works just fine - when new notification was inserted to the DB the subscription gets called instantly.
My problem is the count aggregation.
When I run the following subscription:

const GET_NOTIFICATIONS = gql`
subscription($userId: Number!) {
  notifications(where: { user_id: { _eq: $userId } }) {
    creation_time
    description
  }
  notifications_aggregations (where: { user_id: { _eq: $userId } }) {
    aggregate {
      count
    }
}
`

I am getting the following error - {"type":"subscription_data","id":4,"payload":{"errors":[{"message":"Subscription \"A\" must select only one top level field.","locations":[{"line":7,"column":3}]}]}}
After quick research I still could not find any solution to my problem.
Is there a way for my to keep the count aggregation in my subscribtion? Or do I need to count the notifications number myself after the subscription called?

Thanks for every response.

A: As the error states, a subscription is only allowed to have a single top level selection. To work around this, you can just split it into two separate subscriptions.
It probably makes more sense to hoist the notification count higher up in the application context anyways so that you can display the total count of notifications in the app header for example. If you do this I'd suggest that you can convert the part of the operation that actually retrieves the notifications back into a query instead and only call it when the user actually attempts to view the notifications to save on the overhead.


text:
Q: How to zoom and change color in leaflet I am using leaflet and leaflet-fusesearch. This is my code for pop up a box when searching for a line plotted in leaflet:
var map = L.map('map').setView([1.3096622448984000, 103.7689017333800], 12);

    L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=token', {
        maxZoom: 18,
        attribution: 'Map data © OpenStreetMap contributors, ' +
            'CC-BY-SA, ' +
            'Imagery © Mapbox',
        id: 'mapbox.streets'
    }).addTo(map);
    map.doubleClickZoom.disable();
    var info = L.control();

    var options = {
            position: 'topleft',
            title: 'Search',
            placeholder: 'enter link id ',
            maxResultLength: 15,
            threshold: 0.5,
            showInvisibleFeatures: true,
            showResultFct: function(feature, container) {
                props = feature.properties;
                var name = L.DomUtil.create('b', null, container);
                name.innerHTML = props.id;

                container.appendChild(L.DomUtil.create('br', null, container));

                var cat = props.id
                    info = '' + cat + ', ' + 'th link';
                container.appendChild(document.createTextNode(info));
            }
        };

    var searchCtrl = L.control.fuseSearch(options);

    searchCtrl.addTo(map);

    var geojson;

    function getColor(d) {
        return  d > 2000 ? '#006400' :
            d > 1500  ? '#6fdc6f' :
            d > 1000  ? '#6fdc6f' :
            d > 500  ? '#6fdc6f' :
            d > 50   ? '#FF0000' :
            d > 20   ? '#c8ff58' :
            d > 10   ? '#6fdc6f' :
                       '#fafafa';

    }

    function style(feature) {
        return {
            weight: 2,
            opacity: 1,
            color: '#ff0000',
            fillOpacity: 0.7,

        };
    }

    function highlightFeature(e) {
    var layer = e.target;

    layer.setStyle({
        weight: 5,
        color: '#0000FF',
        dashArray: '',
        fillOpacity: 0.7
    });

    if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
        layer.bringToFront();
    }

    info.update(layer.feature.properties);

    }
function resetHighlight(e) {
    geojson.resetStyle(e.target);
     info.update();
}
function zoomToFeature(e) {
    map.fitBounds(e.target.getBounds());
    map.doubleClickZoom.disable();
}

info.update = function (props) {
    this._div.innerHTML = '
August 2016:
' +  (props ?
        'Link ' + props.id + '
'
        : 'Hover over a link');

};

function onEachFeature(feature, layer) {
     feature.layer = layer;

    layer.on({
        mouseover: highlightFeature,
        mouseout: resetHighlight,

    });
    var popupContent =
      'Link ' + feature.properties.id + '';

    layer.bindPopup(popupContent);
    feature.layer = layer;

}

geojson = L.geoJson(zones, {
    style: style,
    onEachFeature: onEachFeature
}).addTo(map);

info.onAdd = function (map) {
    this._div = L.DomUtil.create('div', 'info'); // create a div with a class "info"
    this.update();
    return this._div;
};

searchCtrl.indexFeatures(zones.features, ['id']);
info.addTo(map);

But when I load the page the highlight feature works fine and when I search for a line the pop up also works fine.But after the search the highlight feature does not work and I also want to zoom in and change the color of the line in the map.Any help is appreciated.

A: Having the same problem and digging into the leaflet-fusesearch code I guess we have to modify the createResultItem function :
https://github.com/naomap/leaflet-fusesearch/blob/master/src/leaflet.fusesearch.js#L286
It seems the function allows only openPoup / panAndpopup as event, it would be usefull to add other events or pass personnal function at this step


text:
Q: Control OS mouse clicks I can't seem to find what I am looking for which is a way to alter the OS's mouse clicks. To specify this would be on Windows.
The goal is to limit the number of mouse clicks a user can register within a period of time.

A: I think the function that you are looking for is SetWindowsHookEx. Here is a quick example.
#include <windows.h>

const DWORD desireddelay = 10;

LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    static DWORD previoustimestamp = 0;
    if ((nCode == 0) && (wParam == WM_RBUTTONDOWN))
    {
        if ((((MSLLHOOKSTRUCT*)lParam)->time - previoustimestamp) < desireddelay)
        {
            return 1; //Non-Zero Swallows the keystroke. 0 Allows it. Always CallNextHookEx if you are not swallowing it.
        }
        else
        {
            previoustimestamp = ((MSLLHOOKSTRUCT*)lParam)->time;
        }
    }
    return CallNextHookEx(NULL, nCode, wParam, lParam);
}

int main()
{
    HHOOK hook = SetWindowsHookEx(WH_MOUSE_LL, MouseProc, GetModuleHandle(NULL), NULL);
    MSG msg;
    bool done = false;
    while (GetMessage(&msg, NULL, NULL, NULL)) {}
    UnhookWindowsHookEx(hook);
    return 0;
}


text: Q: How to add style to a tag as it is done in this website when we add tag I have a text box with a auto complete list and the values are seperated by a ;  How i can I add the css property just like in this website if we add tags, the tag come with a (x) for removing the tag, How can I implement that in my website. All i want is a (x) same as the tags that we add in Stackoverflow website.


text:
Q: Indicate variable values from side-effects with Python type hinting With type-hinting in Python 3.9, once an isinstance call is made in an if-statement, the typing interpreter knows the variable type. For example:
if isinstance(value, int):
    value += 1  # <-- known to be an int

However if you wanted to do some sort of additional validation, then the typing interpreter can easily get confused. For example:
def is_positive_int(value:Any)->bool:
    return isinstance(value, int) and value>=0

if is_positive_int(value):
    value += 1  # <-- NOT known to be an int

Is it possible to mimic the behavior of, in this case, isinstance and instruct the type-interpreter to treat a variable as a specific type depending on the return of is_positive_int?

A: Since the implementation of PEP 647 in Python 3.10, you can use typing.TypeGuard for this:

Using -> TypeGuard tells the static type checker that for a given
function:

*

*The return value is a boolean.

*If the return value is True, the type of its argument is the type inside TypeGuard.

In your case that would be:
def is_positive_int(value: Any) -> TypeGuard[int]:
    return isinstance(value, int) and value >= 0

This has been backported to Python 3.6-3.9 via typing_extensions.


text:
Q: Find out the unit quaternion (or i,j,k) value From the definition, we understand $i,j,k$ are quaternion units.

Quaternions are generally represented in the form:
$a + bi + cj + dk$ where a, b, c, and d are real numbers, and i, j, and
k are the fundamental Quaternion Units.

https://en.wikipedia.org/wiki/Quaternion
We also know that
$i^2 = j^2 = k^2 = ijk = -1$
So, when we apply rotation with Q quaternion(as a unit quaternion like i, j or k) to vector we expect to get reverse of it.
$$Q = (w:0.707,x:0.707,y:0,z:0) (or Axis: [ x:1, y:0, z:0 ], angle:90)$$
$$v = (w:0,x:0,y:1,z:0) $$
then from the rotation formula  $$ q V q^-1 $$ we get result $$r=(w:0,x:0,y:0,z:1)$$
And when we rotate it again with same $Q$ we get result $$(w:0,x:0,y:-1,z:1)$$ which is $-v$.
Thus, could we say that Quaternion units $i,j,k$ are always 90 degree rotations!?
Which seems intiutively correct to me, rotating 90 degrees twice you would get the reverse by 180 degrees.
Also, while asking this question, i re-checked the definition of unit quaternion(versor) and determine the unit quaternion as
$$ Unit Quaternion: ( w:0, x:0.577, y:0.577, z:0.577 )  (or Axis:[ 0.577, 0.577, 0.577 ], angle:180)$$
And applied the rotation formula twice and find out that it works, it reverses the vector.
Edit1: I checked it again but applying rotation by the "Unit Quaternion" twice gets the same vector, not reverse!
So, are those i,j and k unit quaternions have this value : $$ ( w:0, x:0.577, y:0.577, z:0.577 ) $$
Or what is the value of unit quaternions(or i,j,k) actually?
Edit2: My false assumption is that multiplying vector with $i^2=-1$ is identical to applying $i$ quaternion twice to vector with the rotation formula but multiplication is non-commutative and it will not work i think.
Edit3: Finally i tested to directly multiply vector by $i^2$(without rotation formula) and i get the reverse of vector as expected from $i^2=-1$. So,  $$ ( 0, 0.577, 0.577, 0.577 ) $$ is the unit quaternion i think but i am not sure which one is this i,j or k and how i,j and k differs in this case?


text:
Q: Prohibitory sign after using SuperDuper!; MacBook Pro can no longer boot from MacOS X partition This is going to be a long story, but please bear with me...
I'm trying to recover a MacOS X partition that got lost on my Seagate HD.  This HD was dual booted using BootCamp with Windows 10.  I originally had Linux on this HD too, but eventually deleted it and used BootCamp to put on a Windows 10 install. (This is all on a late 2011 MacBook Pro).  I was actually trying to migrate everything over to a solid state drive by using SuperDuper! and Winclone, but something went wrong in the whole process, and all of a sudden I couldn't boot into the MacOS operating system any longer (gave the prohibitory sign).  To make things worse, the system couldn't actually find the MacOS partition either.
So I used Apple's internet recovery to at least get a bootable MacOS X going and put the SSD into the MacBook Pro.  I then put the Seagate HD into a Sabrent external USB adaptor so I could see what was going on.  After booting into MacOS and running terminal, I see this:
/dev/disk0 (internal, physical):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:      GUID_partition_scheme                        *500.1 GB   disk0
   1:                        EFI EFI                     209.7 MB   disk0s1
   2:                  Apple_HFS Macintosh SSD           499.2 GB   disk0s2
   3:                 Apple_Boot Recovery HD             650.0 MB   disk0s3

/dev/disk1 (external, physical):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:      GUID_partition_scheme                        *500.1 GB   disk1
   1:                        EFI EFI                     209.7 MB   disk1s1
   2:          Apple_CoreStorage Macintosh HD            336.8 GB   disk1s2
   3:                 Apple_Boot Recovery HD             650.0 MB   disk1s3
   4:       Microsoft Basic Data BOOTCAMP                110.0 GB   disk1s4

/dev/disk2 (external, virtual):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                  Apple_HFS                        +336.5 GB   disk2
                                 Logical Volume on disk1s2
                                 0F8A5999-AA3A-42E3-AB53-260295D99FA1
                                 Unencrypted

So you can see that it knows the MacOS partition is there (disk1s2), but it won't mount, DiskUtility has no idea what is on the disk (it's greyed out), and I obviously can't browse into it to get any files.  I don't know why it lists an external virtual volume as well...this seems to be the MacOS partition as well - i.e. it looks like disk2 is the same as disk1s2.  I ran First Aid on it through DiskUtility, but got:
File system check exit code is 8.
Restoring the original state found as unmounted.
File system verify or repair failed.

If you try and run DiskUtility through Recovery on the entire drive, it says something's wrong and that it may be corrupt.
Using the command fdisk /dev/disk1 gives:
Disk: /dev/disk1    geometry: 60801/255/63 [976773168 sectors]
Signature: 0xAA55
         Starting       Ending
 #: id  cyl  hd sec -  cyl  hd sec [     start -       size]
------------------------------------------------------------------------
 1: EE 1023 254  63 - 1023 254  63 [         1 -     409639] <Unknown ID>
 2: AC 1023 254  63 - 1023 254  63 [    409640 -  657891312] <Unknown ID>
 3: AB 1023 254  63 - 1023 254  63 [ 658300952 -    1269536] Darwin Boot
*4: 0C 1023 254  63 - 1023 254  63 [ 659570688 -  214843392] Win95 FAT32L

Using the command gpt -r show disk1 gives:
gpt show: disk1: Suspicious MBR at sector 0
      start       size  index  contents
          0          1         MBR
          1          1         Pri GPT header
          2         32         Pri GPT table
         34          6
         40     409600      1  GPT part - C12A7328-F81F-11D2-BA4B-00A0C93EC93B
     409640  657891312      2  GPT part - 53746F72-6167-11AA-AA11-00306543ECAC
  658300952    1269536      3  GPT part - 426F6F74-0000-11AA-AA11-00306543ECAC
  659570488        200
  659570688  214843392      4  GPT part - EBD0A0A2-B9E5-4433-87C0-68B6B72699C7
  874414080  102359055
  976773135         32         Sec GPT table
  976773167          1         Sec GPT header

I think this might be similar to an issue someone was having here:
Prohibitory sign on boot after Sierra update, can't mount disk anymore
but I'm not sure, so I thought I'd post this.
Any help that anyone can provide is greatly appreciated!


text:
Q: Sorting std::map based on the data (map->vector->sort) I want to sort a std::map based on the data (second field). However the second field itself is a structure and I want to sort based on one of its elements. Based on what is suggested here and its reference, decided to copy the map to a vector and then use std::sort. Here is the class implementtion
#include <iostream>
#include <vector>
#include <map>
#include <utility>

class foo() {
    foo() {}
    void bar()
    {
      aDeltaMap theDeltaMap;
      // insert some elements to theDeltaMap
      aDeltaVector theDeltaVec( theDeltaMap.begin(), theDeltaMap.end() );
      std::sort(theDeltaVec.begin(), theDeltaVec.end(), descend_rep<deltaPair>() );   //ERROR
    }
private:
    typedef struct entry {
      entry( int r, int mc ) : rep(r), missCounter(mc) {}
      int rep;
      int missCounter;
    } aDeltaEntry;

    typedef std::map< int, aDeltaEntry > aDeltaMap;
    typedef std::pair< int, aDeltaEntry > deltaPair;
    typedef std::vector< deltaPair > aDeltaVector;
    struct descend_rep
      : std::binary_function<deltaPair,deltaPair,bool>
      {
         inline bool operator()(const deltaPair& lhs, const deltaPair& rhs) { return lhs.second.rep > rhs.second.rep; };
      };
 };

At the line of sort function, I get this error
 error C2275: illegal use of this type as an expression
 error C2059: syntax error : ')'

What did I missed?

A: One error is that descent_rep is not a class template, so you need to replace
descend_rep<deltaPair>()

by
descend_rep()

You should make descend_rep's bool operator() const too, since comparing its operands does not change its state.


text:
Q: I don't want field for a specific row to not be updated atall I have a table named users in which there is accountlocked field ... the possible values of that field are Y and N ... if the user from frontend logs in with 3attempts of wrong password then accountlocked will be Y which means account is locked... but I have a specific user that I don't want the accountlocked to be updated to Y... I created a trigger which can update it to N once it is Y... but I just don't want the field to be updated to Y atall in the first for that specific user
CREATE OR REPLACE TRIGGER traccountunlock AFTER
   UPDATE OF accountlocked ON users
   FOR EACH ROW
   WHEN (new.username='Testuser ')
BEGIN
    IF :new.accountlocked = 'Y' THEN
        UPDATE users
        SET
            accountlocked = 'N'
        WHERE
            username IN (
                'Testuser'
            );

    END IF;
END;

This works but it does it after the field is updated to Y,but I don't want it to update to Y at the first place something like instead of ... but instead of works only for views not tables in oracle
Note: I can do it through java code but, I'm not looking for that solution as it needs deploy and future issues

A: It would be this one. However, I think you should solve it better on application level.
CREATE OR REPLACE TRIGGER traccountunlock
   BEFORE UPDATE OF accountlocked ON users
   FOR EACH ROW
   WHEN (new.username = 'Testuser')
BEGIN
    IF :new.accountlocked = 'Y' THEN
        :new.accountlocked := 'N';
    END IF;
END;

--Just Updated with the working version

A: What are constraints for?
create table t (
  username varchar2(30),
  accountlocked varchar2(1) check( accountlocked in ('Y','N') ),
  constraint not_lock_testuser check( (username,accountlocked) != (('Testuser', 'Y')) )
);

Done!
Best regards,
Stew Ashton


text:
Q: How to sleep in a firefox extension without using setTimeout? I am trying to open a pop-up window, wait X seconds and then close the popup window.
(The use case is sending a notification to a webapp  - but we can't just do a GET request as it needs to be in the same session so we can use the login session)
I can't use setTimeout as we can't use it in add-ons/extensions
How can I get similar functionality without resorting to chewing up CPU cycles, which obviously causes a noticeable lag?

A: You can use nsITimer.
A basic example is below but you can find more information (including the use of Components.interfaces.nsITimer.TYPE_REPEATING_SLACK as an alternative to setInterval) on the relevant documentation page at https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsITimer
// we need an nsITimerCallback compatible interface for the callbacks.
var event = {
  notify: function(timer) {
    alert("Fire!");
  }
}

// Create the timer...
var timer = Components.classes["@mozilla.org/timer;1"]
    .createInstance(Components.interfaces.nsITimer);

// initialize it to call event.notify() once after exactly ten seconds.
timer.initWithCallback(event,10000, Components.interfaces.nsITimer.TYPE_ONE_SHOT);

A: You can use the timers module provided by the SDK instead of nsITimer for the same kind of setTimeout/setInterval functionality provided in browsers
let { setTimeout } = require('sdk/timers');

function openPopup () {}

setTimeout(openPopup, 3000);


text:
Q: Add text and attribute to div depending on url with jquery On page load, I'm trying to add the text (capitalized) of the last part of the url to a li and its attribute data-filter (with a dot behind).
For example, if the page has this url:
www.myexample.com/#commisions
the li would look like this:

Commisions

I have tried with this method but it doesn't remove the # from the text:
var url = document.URL
var cuturl = url.substr(url.lastIndexOf('/') + 1);
$( ".navbar-brand" ).html( cuturl );

Any idea how can achieve it?

A: Try this
var url = document.URL;
var cuturl = url.split("#")[1];
$("li a").html(cuturl);
$("li a").attr('data-filter','.'+cuturl);

A: Simply replace "\" with "#"
var cuturl = url.substring(url.lastIndexOf('#') + 1);

or
var cuturl = url.split("#")[1];


text:
Q: How to setup Netdata to monitor my website performance? So I have installed netdata on my machine using this tutorial https://www.how2shout.com/how-to/how-to-install-netdata-on-windows-10-wsl.html
I started it in my browser via the provided command 127.0.0.1:19999 and it only monitors and sends performance of my local machine (the laptop I'm using)
I own a website so I tried to enter my website IP + 19999 at the end but of course that did not work.
I'd like to set it up so I can measure live performance from my website.
Any idea how I can do that?

A: Your website runs on a server that your hosting provider owns. To use Netdata, Netdata would have to already be installed on your provider's hosting infrastructure, or you would require sufficient (effectively administrator) access to your hosting server (or servers) to install it yourself, which many hosting services would be unlikely to provide. If you are using a hosting provider that manages your website hosting you likely don't need Netdata to monitor your website performance - monitoring then is considered to be part of what you pay for.
On the other hand, if you are managing your own cloud infrastructure, it should be easy (and a good idea) to install Netdata to monitor any website servers that run on top of it.


text:
Q: When to return vector iterator instead of vector? Let's say we have a function 1 :
vector<T>::iterator GetSomething()
{
 vector<T> vec;

 // Update vec with something...

 return vec.begin();
}

And another function 2:
vector<T> GetSomething()
{
 vector<T> vec;

 // Update vec with something...

 return vec;
}

In what situations would we prefer function 1 ?
Also, what would be the lifetime of that vector object ?
How would we know if the iterator is pointing to empty vector ? Probably need to pass pair of iterators to determine begin / end.

A: You shouldn't return iterator to locally allocated vector. It is an undefined behavior.
The explanation is pretty simple: vector<T> vec; is destroyed once you leave the function.
The second option is better and most probably will have Return Value Optimization that will construct vector exactly where it should be returned.

A: A vector iterator is only valid for the vector it comes from so returning an iterator to a local vector is no use.
Only return a vector iterator when you passed the vector it belongs to in as a parameter reference:
std::vector<int>::iterator find(std::vector<int>& v, int i)
{
    // do findie stuff
    return std::find(std::begin(v), std::end(v), i);
}

You would never want to do this:
vector<T>::iterator GetSomething()
{
    vector<T> vec;

    // Update vec with something...

    return vec.begin(); // this iterator will be bad when it arrives
}

Once the vector is destroyed at the end of the function its iterators are invalidated.

A: The lifetime of vector, just like all other automatic variables ends with the scope of the block it was declared in.
As such, if you return the iterator, it will point to freed memory and do all kinds of funny things like crash your program.
If you return the vector itself, it is copied with all of its content, but the original vector still 'dies' at the end of the block.

A: Apart from the general remark about returning a pointer-like to something disapparead on the stack, option 1 asks for a pair of methods (functions disqualify option 1) : begin & end. Iterators in C++ do not work as in java, python and many others.

A: There is no circumstance in which your first function would be preferred.  The vector vec ceases to exist when the function returns.  Any iterators supplied by that vector will be invalid for the caller.   And most usages of those iterators (particularly dereferencing) will cause the caller to exhibit undefined behaviour.
The only time an iterator should be returned by a function will be if the vector which provides those iterators is guaranteed to exist after the function returns.   Practically, there are only three circumstances in which one MIGHT do that.  The first is if the vector is passed as an argument to the function, such as
 std::vector<int>::iterator func(std::vector<int> &vec)
 {
     return vec.begin();
 }

Since the caller passes the vector, the vector will exist when the function returns.
The second case is if the vector is a static, or otherwise continues to exist when the function returns.
 std::vector<int>::iterator func(std::vector<int> &vec)
 {
     static std::vector<int> vec;
     return vec.begin();
 }

Of course, using a function like this has all the complications associated with statics (e.g. problems with reentrancy, need to synchronise usage across threads, etc etc).
The third case in which an iterator may be returned is if an iterator is passed to the function.  Such as
 std::vector<int>::iterator func(std::vector<int>::iterator it)
 {
     return it + 1;
 }

In this case, it is up to the caller to pass a valid iterator (e.g. obtained from a container it controls) that can be incremented (or advanced by 1).
Also, if a function returns an iterator, the caller might need to check if the iterator is valid before using it.   If so, that should be docuumented.  For example, if the function might return an end iterator, the caller should check BEFORE trying to dereference it, not after.


text:
Q: Why was my question on algorithms closed? My question on algorithms was closed as "not a real question," though I don't understand why.
I believe I stated the problem clearly even though I am not a native English speaker.
Could someone clarify this for me? And help me identify what a "real question" is?

A: The problem with a question like this is that it's not an actual problem you face. "Now hold on" I hear you say, "This is a problem I'm facing, because I don't know how to solve it". Well, the way I see it, that's not exactly what that line means.
In your question, you posted (ad verbatim) the full problem. You did not attempt to solve it. Or at least you did not tell us about it. The problem is stated and you ask others to solve it.
What we ideally would have liked to see is:

*

*This is the problem I'm trying to solve

*This is how I am trying to solve it

*I'm stuck here. This doesn't work because...  <--- That is the actual problem you face

Looking through your question history, I see why you might be somewhat confused. You have after all successfully asked this type of question before. And you've gotten answers and upvotes. I personally think that has sent the wrong message from the start.
That is not your fault and I don't think you can be blamed for it. I'm surprised to see that the community has not picked this up and informed you that such questions are problematic, if not off-topic for SO.
Anyway, that is my view on the closure and the history of your questions. I hope this explains my reasoning behind the closure. Thank you for bringing it up here in a constructive manner.

A: From the FAQ:

You should only ask practical, answerable questions based on actual problems that you face.

Your question would probably fit better on https://codegolf.stackexchange.com/
And if you post something on Stackoverflow you should always provide your efforts so far.


text:
Q: Load a html page in a div by clicking an image I have an image and i want, once i click it, that a particular html page is displayed into a specific div. I found several answer yet, but none of them seems to work.
I'm thinking something simple with jquery, like the answer given here: display html file in a div
What's your solution ?
Thanks in advance.
EDIT1
I want to load an internal html page ( not an external page from another webiste ) by clicking an image.
This is the code i used taking example from the answer on the link above.

"mainscreen" is the final div when i want to display the html page.
Inside the function .load() there is the path of the html page.
But no html page is displayed into the div.
EDIT2: I found the silly mistake. I use this structure:  when the correct position of the elements is . I could remove also the  element but i'm using CSS and i'm more comfortable to place elements than using  tag options instead. Thanks for all your replies. Tomorrow i'll see if the code with jquery works.

A: I think your Problem is, that when you load another website using .load().
All the other websites CSS/JavaScript gets loaded and yours gets overwritten.
Could you tell us, what you are trying to accomplish?
Are you loading a html-page from your own website or an external url?
If you dont care for the styles that other website uses, you could do something like this:
.load("example.com/some.html #content");

This loads the url you specifies and just copys the content of the HTML-Element that corresponds to this selector into your target element. (ONLY INLINE-CSS will be applyed that way, you would need to do that styling manually)
EDIT: Thank you for updateing your question.
You are trying to load a file from your filesystem.
Add file:// in front of the path to your .html file.
NOTE: Especially when you are trying to use AJAX you should use a local website and work with relative paths! This makes it much easier to deploy the website afterwards as you do not have to rewrite all your URLs.

A: Here is jsFiddle
Your html code

Your javascript
$(document).ready(function(){
    $(".img").click(function(){ //capture the event and ignite your work
        loadPage("http://fiddle.jshell.net/"); //call our function
    });
});

function loadPage(link){
    $.get(link,function(data){ //dont forget cross-browser rules.
          $(".targetDiv").append(data) //appended in to your div
    })
};

Or you can use .load function with link parametre.

A: Lets say you have the following HTML code.

click on the image to load html …

And some JavaScript code (with jQuery).
var image = document.getElementById('js-image'),
    mainscreen = document.getElementById('mainscreen');

$(image).on('click', function() {
    $(mainscreen).load("http://fiddle.jshell.net/florianpircher/tmRy9/show/");
});

Demo: http://jsfiddle.net/florianpircher/6wXBu/1/
You can not use $("mainscreen") because that would select <mainscreen> and not #mainscreen. In jQuery, you need a CSS-selector (like $("#mainscreen")).


text:
Q: Align a text frame when creating a ppt from access vba I'm trying to align a text frame when creating a ppt from access. Alignment control is available from excel vba but I'm struggling to find this in access.
Here is an example of the creation of a textbox in powerpoint from access vba. I have control of the font size and such but I cannot locate the alignment for the textbox.
' Program data
Dim tb_ProgramData As Shape
Set tb_ProgramData = pptCurrentSlide.Shapes.AddTextbox(msoTextOrientationHorizontal, Left:=68.399, Top:=51.12, Width:=187.2, Height:=18.72)
tb_ProgramData.TextFrame.TextRange.Text = rs.Fields(27) + " Program: " + rs.Fields(29)
tb_ProgramData.TextFrame.TextRange.Font.Size = 9
tb_ProgramData.TextFrame.TextRange.Font.Bold = msoTrue

The only thing close is a paragraph alignment but it has no effect...
tb_Title.TextFrame.TextRange.ParagraphFormat.Alignment = ppAlignCenter

Any help would be appreciated... regards,

A: Good grief.. I found it under the text effects.
tb_SystemClass.TextEffect.Alignment = msoTextEffectAlignmentRight

and if you wish to select the textbox from the list of shapes then...
pptCurrentSlide.Shapes.Range("tb_SystemClass").TextEffect.Alignment = msoTextEffectAlignmentRight


text:
Q: Manipulating oledb tables in conjunction with foxpro (or other) tables I'm converting a lot of FOXPRO/FOXWEB files to ASP.NET with VB.NET. The underlying database will remain FOXPRO (for now).
Given two tables in two different databases that share a common field.
Say the first table is "table1" and the second is "table2" and the name of the common field is "cid"
Say I have used oledb to extract an oledb table from table1 called "interestingrows" using a line of code something like:
adapter.Fill(MyDataSet, "interestingrows")

I would like to say something like
sql = "DELETE FROM interestingrows WHERE cid in (SELECT cid FROM TABLE2)"

... except the sql cmd is being sent to my adapter which is connect to a foxpro db and "interestingrows" is an oledb table.
It would be very nice, though not absolutely necessary, if the solution will work when we eventually decide to switch underlying database to MS SQL (or whatever customer decides on).

A: Based on your comment feedback, you might want to create a SECONDARY "Connection" that points to the common root folder to both tables... Otherwise I expect your query would fail by trying to gain access one level UP from where the current connection is... It might fail you on that.  So, with a new rooted connection path, your query can reference the paths and tables in one query... something like...
C:\Somewhere\CommonPath\
C:\Somewhere\CommonPath\PrimaryData\
C:\Somewhere\CommonPaht\AlternateData\

and your current connection is going to
C:\Somewhere\CommonPath\PrimaryData\

create a SECONDARY connection pointing to
C:\Somewhere\CommonPath\

Then your query can be something like
delete from PrimaryData\Table1
   where cid in ( select cid from AlternateData\Table2 );

A: How about issuing the SQL command directly to the underlying tables?
DELETE FROM Table1 WHERE cid in (SELECT cid FROM Table2)


text:
Q: How to anticipate a changing multidimensional array and correlate all the data to the proper places Okay I am pulling data from an api and it returns json objects. In this data there are 4 fields, lack of a better word, level , xp, rank, id. Level pertains to the level of a certain skill, rank pertains to the total rank in the skill compared to other players, xp pertains to total xp in the skill, and id pertains to the a certain skill. The way the api sorts data is highest xp to lowest xp and there are 27 skills total.  Okay now that I got that outta the way I am trying to connect the dots so to speak. Ex id 6, in the below array, is the skill magic and id 17 is the skill thieving. So, because the api sorts from highest xp to lowest, $array[skillvalues][0][id] will not always equal 6(magic). Then I wouldn't know how to connect the dots that all the values in $array[skillvalues][0], in this example, belongs to the magic skill. Meaning my level in magic is 99, my xp in magic is 32mil, my rank compared to other players is 56,731
This api pops out more data than the skills data... I was able to get it down to the data that I am interested in and that is about it. I got variables ready to go to store the values in the right place, I just need the parts that connect the dots. I have tried searching here an google for the answer and everything I come across doesn't solve the two issues I stated above. I was able to use foreach loops to target that id field, but I don't think that is what I need. I would appreciate any feedback.
Array
(
  [skillvalues] => Array
      (
         [0] => Array
             (
                [level] => 99
                [xp] => 322039589
                [rank] => 56731
                [id] => 6
             )

         .
         .
         .

         [26] => Array
             (
                [level] => 73
                [xp] => 10590542
                [rank] => 251597
                [id] => 17
             )

     )
     //skill ids if it matters
     AttacK: 0
     Defence: 1
     Strength: 2
     Hitpoints: 3
     Ranged: 4
     Prayer: 5
     Magic: 6
     Cooking: 7
     Woodcutting: 8
     Fletching: 9
     Fishing: 10
     Firemaking: 11
     Crafting: 12
     Smithing: 13
     Mining: 14
     Herblore: 15
     Agility: 16
     Thieving: 17
     Slayer: 18
     Farming: 19
     Runecrafting: 20
     Hunter: 21
     Construction: 22
     Summoning: 23
     Dungeoneering: 24
     Divination: 25
     Invention: 26

A: You can place all the skills in an array using the skill ID as the Key. If you called the array like echo $skills_arr[1] Defense would be echoed. You could also place these in a Database and call them depending on your preferences, how many skills there actually were etc.
$skills_arr = array(
    '1' => 'Defence',
    '2' => 'Strength',
    '3' => 'Hitpoints',
    '4' => 'Ranged',
    '5' => 'Prayer',
    '6' => 'Magic',
    '7' => 'Cooking'
);
//etc

foreach($array[skillvalues] as $skills){
    echo 'Skill Type:'.$skills_arr[$skills['id']];
    echo 'Skill XP:'.$skills['xp'];
    echo 'Skill Rank:'.$skills['rank'];
    echo 'Skill Level:'.$skills['level'];
}

A: TO any future readers please disregard my questions about the database because Second2None's code seperates everything!! I thank you sooooo much second you are a lifesaver!!!!
all you need to do is.....
$skills_arr = array(
 '0'  => "Attack",
 '1'  => "Defence",
 '2'  => "Strength",
 '3'  => "Hitpoints",
 '4'  => "Ranged",
 '5'  => "Prayer",
 '6'  => "Magic",
 '7'  => "Cooking",
 '8'  => "Woodcutting",
 '9'  => "Fletching",
 '10' => "Fishing",
 '11' => "Firemaking",
 '12' => "Crafting",
 '13' => "Smithing",
 '14' => "Mining",
 '15' => "Herblore",
 '16' => "Agility",
 '17' => "Thieving",
 '18' => "Slayer",
 '19' => "Farming",
 '20' => "Runecrafting",
 '21' => "Hunter",
 '22' => "Construction",
 '23' => "Summoning",
 '24' => "Dungeoneering",
 '25' => "Divination",
 '26' => "Invention"
);
foreach($highscores[skillvalues] as $skills){
  $skill = $skills_arr[$skills['id']];
  $xp = $skills['xp'];
  $rank = $skills['rank'];
  $level = $skills['level'];
  if($skill == "Slayer"){
   echo "My level in " . $skill . " is " . $level . " and I
   have a total of " . $xp . " xp";//this is outputing all the info for slayer skill
  }

}