text:
Q: Symfony2 JMSDiExtraBundle child service dependency error I'm using JMSDiExtraBundle in my Symfony2 project.
Here is my the problem:
Repository.php
abstract class Repository extends DocumentRepository implements ReadOnlyRepositoryInterface {
    protected $dm;
    protected $repo;
    protected $query;

   /**
    * @InjectParams({
    *       "dm" = @Inject("doctrine.odm.mongodb.document_manager")
    * })
    */
    public function __construct(DocumentManager $dm) {
        $this->dm = $dm;

        parent::__construct($dm, $this->dm->getUnitOfWork(), new ClassMetadata($this->getDocumentName()));

        $this->query = $this->dm->createQueryBuilder($this->getDocumentName());
    }
}

PostRepository.php
/**
 * @Service("post_repository")
 */
class PostRepository extends Repository implements PostRepositoryInterface {
    private $uploader;

    /**
     * @InjectParams({
     *      "dm" = @Inject("doctrine.odm.mongodb.document_manager"),
     *      "uploader" = @Inject("uploader"),
     * })
     */
    public function __construct(DocumentManager $dm, UploaderService $uploader) {
        parent::__construct($dm);

        $this->uploader = $uploader;
    }
}

As can be seen, PostRepository requires 2 dependency : DocumentManager (later injected to Repository as parent) and Uploader.
But it seems that Symfony does something which making it assumed that PostRepository needed 3 dependency : DocumentManager, DocumentManager (again) and Uploader, which off course gives an error since I explicitly stated that the second parameter is required to be an Uploader instance.
Here's from appDevDebugProjectContainer.xml :
<service id="post_repository" class="BusinessLounge\BlogBundle\Repository\PostRepository">
  <argument type="service" id="doctrine_mongodb.odm.default_document_manager"/>
  <argument type="service" id="doctrine_mongodb.odm.default_document_manager"/>
  <argument type="service" id="uploader"/>
</service>

and appDevDebugProjectContainer.php :
/**
 * Gets the 'post_repository' service.
 *
 * This service is shared.
 * This method always returns the same instance of the service.
 *
 * @return BusinessLounge\BlogBundle\Repository\PostRepository A BusinessLounge\BlogBundle\Repository\PostRepository instance.
 */
 protected function getPostRepositoryService()
 {
    $a = $this->get('doctrine_mongodb.odm.default_document_manager');

    return $this->services['post_repository'] = new \BusinessLounge\BlogBundle\Repository\PostRepository($a, $a, $this->get('uploader'));
}

Is this an intended behavior? Or a bug perhaps? Or I did something wrong?
Need advice!

A: You can just remove the @InjectParams on your abstract parent class, since it is never instantiated anyways. Then only the things you need are injected in your real service.


text:
Q: How to convert this to a list comprehension I want to convert this part of the code to a list comprehension, however my knowledge of this method is still very weak and it does not occur to me how, if you could help me, I would appreciate it.
list_1 = ["h",'i',' ', 'w','o','r','l','d']
list_2 = ["h",'i',' ', 'm','o','o','n']

list_3 = []

for word in list_1:
    if word in list_2 and word not in list_3:
        list_3.append(word)

print(list_3)

A: Here you go:
[list_3.append(w) for w in list_1 if (w in list_2) and (w not in list_3)]
list_3

Output:
['h', 'i', ' ', 'o']
Enjoy!

A: In this case, this works:
list_3 = [word for word in list_1 if word in list_2]
print(list_3)  # -> ['h', 'i', ' ', 'o']

If you want to keep excluding duplicates in list_3 then it gets a bit more complicated. Check out Removing duplicates in lists. For example, this will work in Python 3.7+:
dict_3 = {word: None for word in list_1 if word in list_2}
print(list(dict_3))  # -> ['h', 'i', ' ', 'o']

A: The right way to do it is using set data structure.
list_1 = ["h",'i',' ', 'w','o','r','l','d']
list_2 = ["h",'i',' ', 'm','o','o','n']
set_1 = set(list_1)
set_2 = set(list_2)
set_3 = set_1 & set_2
print(set_3)

output
{' ', 'o', 'i', 'h'}

A: This is all you need
next time please do more reaserach
list_1 = ["h",'i',' ', 'w','o','r','l','d']
list_2 = ["h",'i',' ', 'm','o','o','n','']

list_3 = []

for i in range(0, len(list_1)):
    if list_1[i] != list_2[i]
        list_3.append(list_1[i])

print(list_3)

result:
['m','o','n']

redpajama_set_name: RedPajamaStackExchange


text:
Q: Format strings to JSON with jq Might be easy enough for someone who has experience with jq. I am novice. I am learning jq with bash to create json arrays.
I want to generate json array with jq in bash.
I have my file named fileForV:
V    Apple is good for you
A    Broccoli is good for you

Note: The space is a tab.
I have:
jq -R '[inputs |
split("\t") |
{"FruitOrVeg":.[0],"Good?":.[1]}]'<<EOF fileForV EOF

I get:
[
  {
   "FruitOrVeg": "A",
   "Good?": "Apple is good for you"
  },
  {
   "FruitOrVeg": "V",
   "Good?": "Broccoli is good for you\""
  }
]

Why do I get \"" at the end?
Should be:
[
  {
   "FruitOrVeg": "A",
   "Good?": "Apple is good for you"
  },
  {
   "FruitOrVeg": "V",
   "Good?": "Broccoli is good for you"
  }
]

A: There's something fishy here. If you are using inputs and getting anything like the results as shown, then:
a) you would have to be using the -n command-line option;
b) you would almost certainly be using jq version 1.5 or later, but I've verified that these versions (in conjunction with bash) definitely do not produce the extraneous double-quotation mark.
Here is a typical transcript, using the input as shown but with one tab per line:
$ jq-1.5 -n -R '
[inputs | split("\t") | {"FruitOrVeg":.[0],"Good?":.[1]}]' input.tsv
[
  {
    "FruitOrVeg": "V",
    "Good?": "Apple is good for you"
  },
  {
    "FruitOrVeg": "A",
    "Good?": "Broccoli is good for you"
  }
]


text:
Q: Can't expose data as graph in nagios I am monitoring Message Count attribute of JMS Queue using Nagios. For that I am using check_jmx plugin and it gives the output as "JMX OK MessageCount=400". I configured graph for this service, but when click  on graph icon it shows no data available. This service not generating any rrd file. How can I configure graph for my message count monitoring service? In graph i want to show message count/hour. Whether I have to use another plugin?

A: Nagios graphing addons such as PNP4Nagios use the performance data of the plugin output which is everything after the |.  Run the plugin on the command line and see if it's outputting performance data, and try different verbosity options by adding -vvv to check_jmx.
More info on performance data
check_jmx usage

A: As i can't tell from your text, which plugin you are using in order to gernerate the graphs, i myself recommend PNP4Nagios.
Once installed it is working really great.
for your problem:

and it gives the output as "JMX OK MessageCount=400".

if this is the messages / hour, you dont even have to change anything.
if it's not, you might include the code of the plugin in its current version on your nagios to your question or modyfie yourself ( store / grab messagecount and timestamp in order to calculate your messages / hour )


text:
Q: How can I group Client Entities in MS Dynamics We want to implement a simple hierarchy of Clients and Accounts. Accounts will have only one parent Client (usual functionality) but we want to add parent Clients to Clients, to create a hierarchy:
        Client 1----------Act 5
        /      \
 Client 2      Client 3
 /      \      /      \
Act1   Act2   Act3   Act 4

We want the standard screens to show 'rolled up' information, i.e when viewing Client 2, to see the contacts and other associated data from Act 1 and Act 2. When viewing Client 1 we want to see all contacts from all entities in the diagram above.
I think there must a be 'correct' way to do this, using the framework. What is the correct way to implement?
Thank you
Ryan

A: Great question, but so far as I know, there is no "correct" way to do this using the existing API. The group Dynamics CRM Denver recently blogged about this and included a response on this topic from Microsoft:

*

*This is a key understood limitation of subgrids. The way that rollup
  is done makes it difficult implement generically and we were not able
  to get it working for CRM 2011. But fully understand the functional
  gap this leaves.

*We are considering this functionality for a future
  release of CRM.

Because associated (recursive) views only work in supported out-of-box entities, there's no way to make a custom entity that will recursively return all contacts and associated activity under the accounts linked to the custom entity. You'll have to resort to reports and any clever tricks you might come up with (outside the API) to get this to work.

A: There are several options here and it all depends on how "integrated" you want this to be.
If you want this to be totally seamless, then I would suggest a plug-in.  A sub-grid with an advanced find view would be the easiest.  Another option is to incorporate an embedded grid with custom fetch and then using JavaScript modify the left nav options.


text:
Q: how to pass variable in using post method with jquery .load() I want to pass the variables name, email into the .load() event.
var email = $('#reg-email').val();
var name = $('#reg-name').val();
$("#user-detail").load("proc/reg-step2.php",{ "name": "name" , "email": "email" }, function() {
    $("#ajaxLoader2").remove();
});

What should be the syntax for this section so that the variable is passed instead of jst the strings I've written here { "name": "name" , "email": "email" }??

A: You can use a variable instead of a literal:  { "name": name, "email": email }

A: In an object literal you can use quotation marks around the property names, but you shouldn't use them around the variable names that you use in the values:
{ "name": name, "email": email }

You can also write the object literal without quotation marks around the property names:
{ name: name, email: email }

You can also mix quoted and unquoted property names, as you need:
{ "name": name, email: email }

If you would have a property name with special characters, like name+email, you need quotes around it in the object literal:
{ "name+email": name + ', ' + email }


text:
Q: Media codec 4.1 Issue It works fine on most of the devices except nexus5, moto G as per my testing. on these devices app  producing video with only two frames.and also getting the following error log
[OMX.qcom.video.encoder.avc] storeMetaDataInBuffers   (output) failed w/ err -2147483648
Could you please help me out to fix this issue.

A: from http://bigflake.com/mediacodec/#q12
Q12. Why am I seeing storeMetaDataInBuffers failures in the log?
A12. They look like this (example from a Nexus 5):
E OMXNodeInstance: OMX_SetParameter() failed for StoreMetaDataInBuffers: 0x8000101a
E ACodec  : [OMX.qcom.video.encoder.avc] storeMetaDataInBuffers (output) failed w/ err -2147483648

You can ignore them, they're harmless.


text:
Q: Check if a value in hashmap already exists I ve created a hashMap which contains String values. I want every time that I add a new value to map to check if already exists in hashmap. I have defined
final HashMap<String, String> map = new HashMap<String, String>();
 map.put(key, myURL.toString());
How could I loop through the hashmap to check if a duplicate exist?

A: map.containsValue method is what you need. See doc

A: Simple:
return map.containsValue(myURL.toString());

for example. Or, using java8 streams:
return map.values().stream().anyMatch(v -> v.equals(myURL.toString()))

But as you ask for efficient solutions, I suggest you go with the old-school non stream version. Because the second version is most likely using noticeably more CPU cycles.
Only if your map has zillions of entries, and you are looking at response time only, then maybe using parallelStream() could give you the answer more quickly.

A: map.containsKey(key)
map.containsValue(val)
If you insist on iterating, do:
Iterator<Entry<String, String>>iterator=map.entrySet();
while(iterator.hasNext()){
  final Entry<String, String>next=iterator.next();
  next.getKey(); next.getValue();
}

Specified by:
  http://docs.oracle.com/javase/7/docs/api/java/util/Map.html

A: Check the class javadocs, you'll see that there are two methods contains key and containsvalue
http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html

A: boolean result = selections.values().stream().anyMatch(Boolean::booleanValue);

A: Speaking of efficiency, the existence of this data structure is a proof of inefficiency and bad design. containsValue(V) is the method you're looking for


text:
Q: Wait cursor on thread control I have created three checkbox controls for three threads and each would start by checking a checkbox control. When a user unchecks a checkbox, I want to turn on the Wait Cursor on the other thread controls rather than completely disabling them for an instance of time, letting a particular thread to stop.
How would you set a IDC_WAIT cursor id for a specific control or should i let the user to freely start/stop multiple threads in order?

A: Many people do not understand how "wait" cursors are ... I hesitate to say indended to work.
The history of the message is really telling however: WM_SETCURSOR has existed since Windows 3.1 - a 16 bit co-operatively multitasked operating system. Because there was only a single thread (Being co-operatively multitasked) - it was not possible for non driver level code to run while an application was "busy". Hence, the handling for "busy" cursors was like this:
WM_SETCURSOR would always respond with the appropriate "non busy" cursor.
Any code that was going to be "busy" would look like:
SetCursor(hHourglass);
DoBusyThing();
SetCursor(hRegular);

This would change the hardware cursor to the hourglass - DoBusyThing would occupy the thread, and WM_SETCURSOR messages would not, and could not, be handled until it exited.
Win32 changed the semantics a little - It remembers on each thread the last cursor a window on that thread set - allowing the co-operative logic of Windows 3.1 to work in the casynchronously multitasked Win32 environment: If a thread is busy (i.e. not pumping messages) WM_SETCURSOR messages for windows on that thread will just get "stuck" in the message queue - hence the hourglass cursor remains the default cursor for all windows owned by the blocked thread, until the busy operation completes and the thread returns to the message processing loop.
Of course, none of this logic works really well in the modern world where we no longer block UI threads:- The busy work is now offset to a worker thread, meaning the UI thread is dispatching WM_SETCURSOR messages and resetting the busy cursor back to the class cursor.
This is not really a problem: The wait cursor have always implied that the application is non responsive and a functioning UI thread + busy worker thread is not what this feedback mechanism is really designed or intended to cover.
I think the correct thing to do would be to leave the cursor alone, and reflect on the UI some other way (stop icons next to the buttons?) that further threads can not / should not be launched.

A: Handle WM_SETCURSOR (The parent window usually gets the chance to set the cursor for its children, if the child window has special handling, you would have to subclass it and handle WM_SETCURSOR there)


text:
Q: Office Addin Custom Attributes on Range Text I would like to know if it's possible to add additional attributes to simple Range text or Paragraph text from my Word Add-in.  For simplicity see code below where I can populate the document with text but additionally i would like to store additional but behind the scenes info along with that text. Ultimately I want these read these custom attributes using the Open Xml SDK when these documents go through a processing stage.
private void AddAttributedContent(string documentContent)
        {
            var doc = Globals.Factory.GetVstoObject(Globals.ThisAddIn.Application.ActiveDocument);
            var range = doc.Range();
            range.Font.Size = 12;
            range.Font.Name = "Calibri";
            range.Underline = Word.WdUnderline.wdUnderlineSingle;
            range.Text = documentContent;
            // range.AddOpenXmlProperty("MyProp", "MyValue");

            var para = doc.Paragraphs.Add();
            para.Range.Text = documentContent;
            //para.AddCustomProperty("MyProp", "MyVal");

        }

Edit:
Ideally our property would sit inside of the resulting RunProprties :

A: No, you can't do that. You could probably do it with a content control or a text box though.
For a ContentControl, you could probably use Tag (if this is like sources, it probably has to be unique, though the description seems to imply it's meant for the purpose you need) or Title.
The Tag property is different from the Title property in that a tag is never displayed while a user edits a document. Instead, developers can use it to store a value for programmatic manipulation while the document is opened.

For a text box (a Shape), you could use AlternativeText or Title.
Note that altering Title (in both cases) or AlternativeText will probably affect the way the document is displayed if you save it as HTML.


text:
Q: simulate high cpu usage for certain period of time
Possible Duplicate:
Simulate steady CPU load and spikes

I need to write an application that can simulate high cpu-usage at a pre-set values ( e.g., 30%, 50%, 90% etc) for a certain duration. Meaning it will take two inputs (CPUUsage and duration). Let say i use 50% for CPU-Usage and 2 minutes for Duration). This mean that when I run the application, it should take 50% CPU for 2 minutes. Any ideas how this can be achieved?

A: You will need to write a spin loop to keep the processor busy for the amount of time desired.  Sleep(n) won't work because while it keeps your thread busy it allows the CPU to do something else.
Use a thread-based timer (not a message based timer) to schedule regular execution of your load simulator function, say, every 10 seconds. In that function, run your spin loop (a for loop that increments a local variable) until the desired load time (% of 10 seconds) is reached, then exit the function.  The timer will call you again in (about) 10 seconds to chew up another timeslice.  So, for 30% load, your spin loop should churn for 3 seconds out of each 10 second interval.
You should also consider the number of executable cores that are present in your system.  On a quad core hyperthreaded Intel processor, you should create 8 threads and run your load simulator in each thread.


text:
Q: Chamar chave de um banco de dados para um usuário escolher em um formulário Php <?php
$link = mysqli_connect("localhost", "root", "");
$query = mysqli_query($link, "certificados");
?>
<form name="produto" method="post" action="">
 Selecione um Nome de Autor
 <select>
 <option>Selecione...</option>

 <?php while($prod = mysqli_fetch_array($query)) { ?>
 <option value="<?php echo $prod["aut_nome"] ?>"</option>
 <?php } ?>

Porque este código não funciona não aparece os dados do banco de dados para escolher obrigado!!!

A: Também falta acertar a tag option  <option value="<?php echo $prod["aut_nome"] ?>"><?php echo $prod["aut_nome"] ?></option>

<?php
$link = mysqli_connect("localhost","USUARIO","SENHA","DB");
$query = ("SELECT * FROM certificados");
$resultado_pedido = mysqli_query($link,$query);
?>
<form name="produto" method="post" action="">
Selecione um Nome de Autor
<select>
<option>Selecione...</option>
<?php while($prod = mysqli_fetch_array($resultado_pedido)) { ?>
<option value="<?php echo $prod["aut_nome"] ?>"><?php echo $prod["aut_nome"] ?></option>
<?php } ?>
</select>
</form>


text:
Q: Declare a VisualStateManager Group Collection as a Resource in a Control Template I need to create a several styles that represent different point objects that all do the same thing.  To be more specific, it is a bunch of ESRI MarkerSymbols that can either be a Circle, Square, Star, etc but that is probably not relevant to the specific problem.
Each point will behave exactly the same way when the user hovers or clicks on them - this is done through the Visual State Groups like so (I deleted several of the animations to save space:
<VisualStateManager.VisualStateGroups>
    <VisualStateGroup x:Name="SelectionStates">
        <VisualState x:Name="Unselected" />
        <VisualState x:Name="Selected">
            <Storyboard Storyboard.TargetName="shapeElement">
                <DoubleAnimation BeginTime="0:0:0" Duration="0:0:0.5"
                                 Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleX)"
                                 To="1" />
                <DoubleAnimation BeginTime="0:0:0" Duration="0:0:0.5"
                                 Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleY)"
                                 To="1" />
                ...................................................................
            </Storyboard>

        </VisualState>
    </VisualStateGroup>

    <VisualStateGroup x:Name="CommonStates">
        <VisualState x:Name="Normal">
            <Storyboard Storyboard.TargetName="shapeElement2">
                <DoubleAnimation BeginTime="0:0:0" Duration="0:0:0.1"
                                 Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleX)"
                                 To="1" />
                <DoubleAnimation BeginTime="0:0:0" Duration="0:0:0.1"
                                 Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleY)"
                                 To="1" />

                <ObjectAnimationUsingKeyFrames BeginTime="0:0:0.1" Duration="0:0:0"
                                               Storyboard.TargetProperty="(UIElement.Visibility)">
                    <DiscreteObjectKeyFrame KeyTime="0:0:0">
                        <DiscreteObjectKeyFrame.Value>
                            <Visibility>Collapsed</Visibility>
                        </DiscreteObjectKeyFrame.Value>
                    </DiscreteObjectKeyFrame>
                </ObjectAnimationUsingKeyFrames>

            </Storyboard>
        </VisualState>

        <VisualState x:Name="MouseOver">
            <Storyboard Storyboard.TargetName="shapeElement2">

                <ObjectAnimationUsingKeyFrames BeginTime="00:00:00" Duration="0:0:0.01"
                                               Storyboard.TargetProperty="(UIElement.Visibility)">
                    <DiscreteObjectKeyFrame KeyTime="00:00:00">
                        <DiscreteObjectKeyFrame.Value>
                            <Visibility>Visible</Visibility>
                        </DiscreteObjectKeyFrame.Value>
                    </DiscreteObjectKeyFrame>
                </ObjectAnimationUsingKeyFrames>

                <DoubleAnimation BeginTime="00:00:00" Duration="0:0:0.1"
                                 Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleX)"
                                 To="1.75" />
                <DoubleAnimation BeginTime="00:00:00" Duration="0:0:0.1"
                                 Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleY)"
                                 To="1.75" />
                ...................................................................
            </Storyboard>
        </VisualState>
    </VisualStateGroup>

</VisualStateManager.VisualStateGroups>

Since I want to create several shapes that all will use this collection of Visual State Groups how do I turn it into a resource?  In other words, how would I do this:
<esri:MarkerSymbol x:Key="CircleLocationPointMarker" OffsetX="6" OffsetY="6"  >
    <esri:MarkerSymbol.ControlTemplate>
        <ControlTemplate>
            <Grid >
                <Ellipse x:Name="shapeElement">
                    ..............................................
                </Ellipse>

                <Ellipse x:Name="shapeElement2">
                    ..............................................
                </Ellipse>

                <Border x:Name="LocationLabel">
                    ..............................................
                </Border>

                <VisualStateManager.VisualStateGroups>
                    ---HOW DO I USE A RESOURCE OR SEVERAL RESOURCES??---
                </VisualStateManager.VisualStateGroups>

            </Grid>
        </ControlTemplate>
    </esri:MarkerSymbol.ControlTemplate>
</esri:MarkerSymbol>

and say another one for a Square and a Star, and so on.  Hope that makes sense.

A: Ok, I can think of two possible solutions:
Number 1:
Derive from the MarkerSymbol and add a public Shape property (or maybe better use Path), now you can develop just one ControlTemplate complete with VisualStates that uses the newly added property. Wherever you want to use you special marker you can provide a customized shape/geometry or you can further derive from it to create default shape markers:
<ControlTemplate TargetType="ShapedMarker" x:Key="ShapedMarkerDefaultTemplate">
    <Grid>
        <VisualStateManager.VisualStateGroups>...</...>
        <Path x:Name="shapeElement" Data="{TemplateBinding ShapeGeometry}"/>
        <Path x:Name="shapeElement2" Data="{TemplateBinding ShapeGeometry}"/>
        <Border x:Name="LocationLabel"/>
    </Grid>
</ControlTemplate>
<Style TargetType="ShapedMarker">
    <Setter Property="Template"
            Value="{StaticResource ShapedMarkerDefaultTemplate}"/>
</Style>

and code
public class ShapedMarker : MarkerSymbol
{
    public Geometry ShapeGeometry { get {...} set {...} }
    ...DependencyProperty ... "ShapeGeometry" ...

    public ShapedMarker(){ DefaultStyleKey = typeof(ShapedMarker); }
}

public class CircleLocationPointMarker : ShapedMarker
{
  public CircleLocationPointMarker(){this.ShapeGeometry = new EllipseGeometry();}
}

Number 2:
Basically what I described here. You can write your own utility classes to generate VisualStates and all associated Animations programmatically, this saves you from writing the same markup over and over again. It is a tried and trusted approach and does not have a performance impact, the animations are only created once. However, this approach is not common and many developers are reluctant to try anything uncommon (an observation I even made in my own team).
The markup could look like this:
<ControlTemplate ...>
    <Grid>
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
                <VisualState x:Name="Normal"
                    utils:AddAnimations.ScaledAndCollapsed="shapeElement2"/>
                <VisualState x:Name="MouseOver"
                    utils:AddAnimations.ScaledAndVisible="shapeElement2"/>
                <.../>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>

        ...

    </Grid>
</ControlTemplate>

And you can even mix animations that are declared in xaml and animations that are added through your utility methods. The code will respect any existing animations.


text:
Q: Create two threads in Objective-C I am very new to Xcode and Objective-C, so I don't really know what I am doing yet! ;-)
Basically I want to have an IPhone Application that can run possibly two threads, which will later use UDP Sockets to communicate with other Apps.
I have put functions to react when the start-Thread/stop-Thread Button in the UI are pressed, now I want to fill them with code to actually create and start the threads.

*

*What would be the correct procedure here?

*Do I need to subclass    NSThread?

*Where do I implement the code, that the new threads will execute?
I can't see a run method, or something similar. I suppose that has something to do with the selector, which I don't understand.

A: - (void)performBlockInBackground:(void (^)())block {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        block();
    });
}

Then you call it like this:
[self performBlockInBackground:^{
    NSLog(@"Log from background");
}];

A: Use dispatch queues. They're essentially lightweight threads for which you don't need to worry about the threading or queueing directly.
-(void) spawn
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        [self doWorkInBackground];
    });
}

You can use one of the built-in queues or your own.
And you should probably read up on blocks too, in particular the memory management aspect.

A: This is a pretty deep discussion, but Apple's "Concurrency Programming Guide" should get you started.

A: You may also consider using NSOperation. It uses dispatch queues under the hood, but offers higher-level API and possibility to cancel ongoing operation (which might be helpful for you).


text:
Q: Uploading to Amazon S3 from web link I have huge amount of files on my old host... I would like to move all files to Amazon S3 since it seems very cheap. My internet connection at home is very slow, so I can't download them and upload it to amazon.
What I would like to do:
I have file X, located at: http://mydomain.com/file.flv and would like to move it to S3 without having to download it first.

A: Why not spin up a micro instance on Amazon, then use that machine to transfer the files between the current host and S3. When the copy is done kill the VM and you stop paying for it.  This way you don't use any of your bandwidth just the old hosts and Amazon's.

A: If your web host's FTP server supports it, you could try using FXP (File eXchange Protocol.  For transferring data between two FTP servers directly without downloading/uploading to your client).  Look for FTP clients that support FXP and S3 such as:  FlashFXP or Forklift (for OSX).


text:
Q: Inspect template parameter pack in gdb I'm trying to debug the following simple program:
#include <iostream>

template <class... Args>
void printAll(Args&&... args) {
    using swallow = int[];
    swallow{0,
        (std::cout << args, 0)...
    };
}

int main() {
    printAll(1, "23", 4);
}

Compiled with gcc 4.9.2 using:
g++ -std=c++11 -g -O0 foo.cxx

And then debugging with gdb 7.9 using:
gdb a.out

(gdb) break foo.cxx:5
Breakpoint 1 at 0x400884: file foo.cxx, line 5.
(gdb) run
Starting program: /..[snip]../a.out

Breakpoint 1, printAll<int, char const (&) [3], int>(int&&, char const (&) [3], int&&) () at foo.cxx:6
6       swallow{0,
(gdb) bt
#0  printAll<int, char const (&) [3], int>(int&&, char const (&) [3], int&&) () at foo.cxx:6
#1  0x0000000000400813 in main () at foo.cxx:12

I'm in the right function, but I have no way to inspect the parameter pack:
(gdb) info args
No arguments.
(gdb) print args
No symbol "args" in current context.
(gdb) inspect args
No symbol "args" in current context.

How do I actually examine the arguments?

A: Related: Showing values of parameters packs in gdb
There are two problems here; the first is that g++ emits parameter pack debugging information in the DWARF format using the tags DW_TAG_GNU_template_parameter_pack and DW_TAG_GNU_formal_parameter_pack, which gdb does not yet support (PR linked).
Even when this is fixed, we run into another problem, which is that the debugging information g++ emits is broken; it's missing the parameter name (DW_AT_name) (PR linked).
TBH gdb support for C++11 is pretty abysmal (unsurprising as it was effectively abandoned for so long); another near-showstopper bug for C++11 is that it didn't support rvalue references (DW_TAG_rvalue_reference_type) until version 8, printing error messages like <unknown type in /tmp/a.out, CU 0x0, DIE 0x7f>.
The workaround (other than using clang, or an ancient version of g++ that doesn't use the DW_TAG_GNU_template_parameter_pack tags, e.g. 4.4.7) is to use the stabs debugging format with GCC extensions:
g++ -std=c++11 -gstabs+ -O0 foo.cxx

</>
(gdb) s
void printAll<int, char const (&) [3], int>(int, int&&, char const (&) [3], int&&) (i=999, args#0=@0x7fffffffe45c: 1, args#1=..., args#2=@0x7fffffffe458: 4)
    at p.cpp:7
7       swallow{0,
(gdb) p 'args#0'
$1 = (int &) @0x7fffffffe45c: 1


text:
Q: Best/Simple hardware security token authentication for ASP.NET websites? I was recently asked to provide a quote on integrating a security solution like most Online Banks use, where there is a security token which key/numbers are randomly changing.
The portal is an ASP.NET website, 2.0...
I haven't implemented this type of security authentication before. Can anyone provide guidance, suggestions, experiences, etc, about the components/hardware they've worked with?
Thanks

A: The most secure way of doing it with a physical token is actually to use a third party product such as RSA SecurId.  They also have a version for sending the token to a mobile device which is part of their "On-demand Authenticators" offering.
Otherwise if you want to manufacture your own system then you need to consider:

*

*The lifetime of the token.

*

*What length of time does the token need to be active for?

*What happens if the client is in a different timezone than the server?

*The randomness of the token?

*

*What method are you using to generate the token?  Last n digits of GUID? Psuedo Random number table? secret + userID + random number, hashed and then take last n digits?

*What are the valid characters for a token?  [0-9]* | [a-zA-Z]* | [0-9A-F]* | etc.

*What is the length of the token?

*Where is the token stored before it is validated?

*How secure is the mechanism used to transport the token?

*

*Over HTTPS?

*Over public SMS network?

*How does the user receive the token?

*

*Rabo bank have a device which you unlock with a pin and then a code is issued.

*Could have a device that you enter the given token and it issues the token you need to respond with?

*What happens if an expired token is presented?

*How many tries to you give them before you lock the device/access?

I was involved with putting a system together for a bank.  It was implemented using a mechanism similiar to that offered by the Microsoft Federation Gateway.  It might not have been for a Login but it was still used for Authentication.


text:
Q: python/mathplotlib plot equivalent of R's symbol plot? Is there a python equivalent of this?

symbols        package:graphics       R Documentation
Draw Symbols (Circles, Squares, Stars, Thermometers, Boxplots)
Description:
This function draws symbols on a plot.  One of six symbols;
    circles, squares, rectangles, stars, thermometers, and
    boxplots, can be plotted at a specified set of x and y
    coordinates.  Specific aspects of the symbols, such as relative
    size, can be customized by additional parameters.

A: You can plot a circle of specific size at a given point using
import matplotlib.pyplot as plt
circle=plt.Circle((0,0),.2,color='r')
plt.add_artist(circle)

The format is Circle(x, y), radius) where x and y are the position of the center in the plot. See this question for more detail and explanation.
A rectangle (or square) of given size with
import matplotlib.pyplot as plt
import matplotlib.patches as patches

rect = patches.Rectangle((50,100),40,30,facecolor='none')
plt.gca().add_patch(rect)

The format is Rectangle((x, y), w, h) where x and y are the coordinates in the plot of the top-left corner, w is the width and h is the height.
You can make an arbitrary polygon (i.e. a star) using
import matplotlib.pyplot as plt
import matplotlib.patches as patches

poly = patches.Polygon(points, facecolor='None')
plt.gca().add_patch(poly)

Where points is an numpy array of shape Nx2 (where N is the number of points) of the vertices of the polygon. More information (including keyword arguments) is available on the matplotlib docs for polygon and rectangle. I you just want those symbols as markers you can simply do
plt.scatter(x, y, marker='*')

Where x and y are arrays or array-like of the coordinates at which you want the markers. The marker used can be specified according to the matplotlib markers docs. You can also draw a custom marker by supplying a path to draw, similar to how the polygon is drawn.


text:
Q: How to convert from recursive function to loop(for while etc) in DOM(Javascript) I got this code while searching, however, I would like it to convert from recursive function to loop using for or while etc.
This code is about selecting all childnodes of Body in DOM(Javascirpt) and print on console.
<script>
function traverse(target, callback){
    if(target.nodeType === 1){
        callback(target);
        var c = target.childNodes;
        for(var i=0; i<c.length; i++){
            /* recursive function here */
            traverse(c[i], callback);
        }
    }
}
traverse(document.querySelector('body'), function(elem){
    console.log(elem);
});
</script>

Could you give me some tips? Thanks in advance:)

A: You can query the target element for all its children and iterate over them
function traverse(target, callback)
{
   var nodes = target.getElementsByTagName('*');
   callback(target);
   for(var i=0;i<nodes.length;i++)
   {
      callback(nodes[i]);
   }

}


text:
Q: Is it possible to use the R function readline without requiring the user to press enter? I am writing a small function that requires user input, which I have coded for using the readline function, but want to eliminate the need for the user to press [enter] after responding to the prompt in the console.
I have searched extensively on SO without finding a solution and the readline documention provides no potential solutions.
timer <- function() {
require(tictoc) #load required package

experiment_no <- readline("Experiment number: ")

while(T){       #open infinite while loop
    tic()       #start timer
    input_state=readline("State input: ")  #allow for entry of state
    if(input_state %in% 1:5){    #check if it's acceptable
        elapsed=toc()            #if it is then end timer and record data
        write.table(cbind(experiment_no,input_state,elapsed$toc-elapsed$tic),'results.txt',col.names=F,row.names=F,quote=F,append=T)
    }else if(input_state=='t'){  #if input is 't'
        break                    #break out of while loop
    }else if(input_state <1 | input_state > 5 & input_state!='t'){#if input is not and accepted state AND is not 't'
     print('thats not an allowed state- please try another')
     }
 }
}

I would like the user to be able to input the experiment number into the console without pushing enter.

A: In contrast to r2evans' response, this solution only works in RStudio. It relies on the rstudioapi package's ability to capture the input currently in the console.
dynamic_readline <- function() {
  while (rstudioapi::isAvailable()) {
    input <- rstudioapi::getConsoleEditorContext()$contents

    if (input != "") {
      rstudioapi::sendToConsole("", execute = FALSE)
      return(input)
    }

    Sys.sleep(0.1)
  }

  readline()
}

The while loop checks the content of the console every 0.1 seconds and returns the input if anything is entered. If something is detected, it sends "" to the console to clear it. If rstudioapi isn't available (i.e. the editor isn't Rstudio), the function falls back to readline().
The sleep time can be adjusted based on the response time you need, although in the R console you're not going to be getting 60 Hz gameplay.
You can also adjust the if statement to test for specific valid inputs rather than any non-empty input by using %in% instead of !=. (Something like if (input %in% c("w", "a", "s", "d", "quit"))). This would make it feasible to use this method with known inputs longer than one character.

A: Edit: up front, this also doesn't work with RStudio. Since I'm confident RStudio is really intercepting and controlling quite a lot of R, while it is possible that C_menu has some other method of control (e.g., options), I think it is more likely that RStudio is intercepting the keypresses (thereby forcing <enter>-use). With that, I suggest that this leans towards a bug/feature-request with RStudio.

If you look at the source for utils::menu, you'll see at the end that it does:
repeat {
        ind <- .Call(C_menu, as.character(choices))
        if (ind <= nc)
            return(ind)
        cat(gettext("Enter an item from the menu, or 0 to exit\n"))
    }

This suggests that the C_menu function (not exported) can be (ab)used to do what you want. I don't know the internal workings of the function, so some empirical takeaways/caveats:

*

*usually (but not always[1]), the first pass in the repeat loop requires an enter for any entry;

*after that first <enter>, it appears to be <enter>-less for single-digit integers, anything else supports some arbitrary length and requires an <enter>
repeat {
  ret <- .Call(utils:::C_menu, letters)
  if (ret == 0L) break
  cat("    you entered ", ret, "\n")
}
# Selection: 345            # I typed "345<enter>"
#     you entered  345
# Selection: 3              # just "3", no enter
#     you entered  3
# Selection: 4
#     you entered  4
# Selection: 5
#     you entered  5
# Selection:                # just enter
#     you entered  27
# Selection: C              # "C<enter>"
#     you entered  27
# Selection: c              # "c<enter>"
#     you entered  3
# Selection: abc            # "abc<enter>"
#     you entered  27
# Selection: 0              # just "0", no enter, it quits

I'm inferring that 27 means I entered something not in the original choices (letters).
Not sure if you can adapt your process to this, as it seems to be restricted to single-digit numbers (once you get past the first entry). I have not found the source for it yet to see if there's a companion function with other arguments.
Notes:

*

*I can infrequently get the code to handle the enter-less entry on the first go, not sure if it's a matter of my code-editing (emacs/ess) or something else. If so, it is likely a bug somewhere.


text:
Q: KO Grid is able to see the array but is not able to show me the Real grid I am trying to use KnockOut Grid to populate some data. It binds to the ObservableArray all fine but it is not populating the grid.
I am not sure what am I missing here.
I am loading jsfiddle for you to take a look:http://jsfiddle.net/sf4p3/6/
Any suggestions?

A: Here you go:
http://jsfiddle.net/jearles/sf4p3/14/
I changed data: myObsArray() to data: myObsArray, added reference to Knockout as a Managed Resource and switched the Framework to jQuery, and added the CSS.

A: You need jquery for the grid to work your fiddle doesnt have jquery


text:
Q: Axios interceptor won't retry original call on React This is my current code:
axios.interceptors.response.use(
    (response) => {
      return response;
    },
    (error) => {
      const originalRequest = error.config;

      if (error.response.status === 401 && !originalRequest._retry) {
        originalRequest._retry = true;

        axios.get("/auth/token").then((res) => {
          if (res.status === 200) {
            console.log("Access token refreshed");
            return axios(originalRequest);
          }
        });

      } else {
        return Promise.reject(error);
      }
    }
  );

It's refreshing the token as expected, but it's not retrying the original request. If the request was to, let's say, display some data, I'm only able to see it if I reload the page or change to some other route and back again to re-render the component.
In my understanding, if the original request hits an error 401, then the interceptor should refresh the token and retry that call - which would trigger the interceptor again, but now would get a successful response - and pass this new response back to the original promise, right?

A: You need to return the axios function:
...

return axios.get("/auth/token").then((res) => {
          if (res.status === 200) {
            console.log("Access token refreshed");
            return axios(originalRequest);
          }
        });


text:
Q: Xcode configuration text fields lose focus I recently upgraded to Xcode 6.2. It seems like there is a weird bug. For example, if I want to change the bundle id, the textfield will lose focus after any character I type.
Is anyone having the same issues? Does anyone know how to fix that?
It's just quite annoying for me, and I guess for anyone else too.

A: I also think so it's weird thing, and you need to try change bundle id in the Info tab not in General tab

A: If you get the problem in "General" tab (same to me), you should modify those infos in "Info" tab if possible. That is my workaround for this bug.


text:
Q: Draw a circle with arcs in CSS 3 I want to draw a circle with arcs in CSS 3 so that I have 5 points and each point can be a link. The reason I want to do it with arcs is because I want to animate an arc when the user hovers over a point. For example if the use hovers over the second point, the line / arc connecting the first and the second point has a fill animation.
Is there a way to do it with CSS or would it be better to use SVGs?

.circle {
  position: relative;
  width: 530px;
}

.dot {
  position: absolute;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: #ccc;
}

.dot1 {
  top: 0;
  left: 50%;
  transform: translate(-50%, -50%);
}

.dot2 {
  top: 34.5%;
  left: 2%;
  transform: translate(-50%, -50%);
}
.dot3 {
  top: 34.5%;
  left: 98%;
  transform: translate(-50%, -50%);
}
.dot4 {
  top: 90%;
  left: 21%;
  transform: translate(-50%, -50%);
}
.dot5 {
  top: 90%;
  left: 79%;
  transform: translate(-50%, -50%);
}

<svg width="530" height="530" viewBox="0 0 530 530" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M265 529C410.803 529 529 410.803 529 265C529 119.197 410.803 1 265 1C119.197 1 1 119.197 1 265C1 410.803 119.197 529 265 529Z" stroke="#DDD7E3" />
<path d="M265 1L13.96 183.4" stroke="#DDD7E3" stroke-miterlimit="10"/>
<path d="M265 1L109.84 478.6" stroke="#DDD7E3" stroke-miterlimit="10"/>
<path d="M265 1L420.16 478.6" stroke="#DDD7E3" stroke-miterlimit="10"/>
<path d="M109.84 478.6L13.96 183.4" stroke="#DDD7E3" stroke-miterlimit="10"/>
<path d="M265 1L516.04 183.4" stroke="#DDD7E3" stroke-miterlimit="10"/>
<path d="M420.16 478.6L516.04 183.4" stroke="#DDD7E3" stroke-miterlimit="10"/>
<path d="M420.16 478.6L13.96 183.4" stroke="#DDD7E3" stroke-miterlimit="10"/>
<path d="M516.04 183.4H13.96" stroke="#DDD7E3" stroke-miterlimit="10"/>
<path d="M516.04 183.4L109.84 478.6" stroke="#DDD7E3" stroke-miterlimit="10"/>
<path d="M420.16 478.6H109.84" stroke="#DDD7E3" stroke-miterlimit="10"/>
</svg>

A: Instead of having divs as points you can use svg elements. Alternatively you can use the divs.
I'm calculating the position of the points on the main circle and using the coords of those points to draw the arcs.
You may try to redraw the lines using the coordinates of the points
Please read the comments in the code.

var SVG_NS = "http://www.w3.org/2000/svg";
var svg = document.querySelector("svg");

let points = [];
let arcs = [];
let c = { x: 265, y: 265 };// the center of the main circle
let r = 263;// the radius of the main circle
let n = 5;//number of points
let step = (2 * Math.PI) / n;// angle between each point

class Point {
  constructor(i) {
    this.p = {};
    this.p.cx = c.x + r * Math.cos(i);
    this.p.cy = c.y + r * Math.sin(i);
    this.p.r = 5;
    this.p.fill = "red";
    this.el = drawSVGelmt(this.p, "circle", circles);
  }
}

//create and push a new point on the points array
for (let i = -Math.PI / 2; i < (3 * Math.PI) / 2; i += step) {
  points.push(new Point(i));
}

for (let i = 0; i < points.length; i++) {
  let _i = i + 1 < points.length ? i + 1 : 0;
  let d = `M${points[i].p.cx},${points[i].p.cy}
           A${r}, ${r}, 0 0 1  ${points[_i].p.cx},${points[_i].p.cy}z`;
  let o = { d: d, fill: "skyBlue" };
  //create a new arc and push it to the arcs array for latter use
  arcs.push(drawSVGelmt(o, "path", arcsgroup));
}

//a function to draw a new svg element and append it to a parent
function drawSVGelmt(o, tag, parent) {
  let elmt = document.createElementNS(SVG_NS, tag);
  for (let name in o) {
    if (o.hasOwnProperty(name)) {
      elmt.setAttributeNS(null, name, o[name]);
    }
  }
  parent.appendChild(elmt);
  return elmt;
}
svg{border:solid}
<svg width="530" height="530" viewBox="-5 -5 540 540" fill="none" xmlns="http://www.w3.org/2000/svg">
<path  d="M265 529C410.803 529 529 410.803 529 265C529 119.197 410.803 1 265 1C119.197 1 1 119.197 1 265C1 410.803 119.197 529 265 529Z" stroke="#f00" />
<path d="M265 1L13.96 183.4" stroke="#DDD7E3" stroke-miterlimit="10"/>
<path d="M265 1L109.84 478.6" stroke="#DDD7E3" stroke-miterlimit="10"/>
<path d="M265 1L420.16 478.6" stroke="#DDD7E3" stroke-miterlimit="10"/>
<path d="M109.84 478.6L13.96 183.4" stroke="#DDD7E3" stroke-miterlimit="10"/>
<path d="M265 1L516.04 183.4" stroke="#DDD7E3" stroke-miterlimit="10"/>
<path d="M420.16 478.6L516.04 183.4" stroke="#DDD7E3" stroke-miterlimit="10"/>
<path d="M420.16 478.6L13.96 183.4" stroke="#DDD7E3" stroke-miterlimit="10"/>
<path d="M516.04 183.4H13.96" stroke="#DDD7E3" stroke-miterlimit="10"/>
<path d="M516.04 183.4L109.84 478.6" stroke="#DDD7E3" stroke-miterlimit="10"/>
<path d="M420.16 478.6H109.84" stroke="#DDD7E3" stroke-miterlimit="10"/>

  <g id="arcsgroup"></g>
  <g id="circles"></g>
</svg>


text:
Q: Implementing unit-of-work for multiple storage types I'm trying to implement the unit-of-work pattern for mutliple storage types like the windows registry, a database or the app.config but I cannot figure out how to do it. All examples I find use Entity Framework which already is a UoW so it doesn't help much. What I'd like to store is a simple Setting object.
From http://martinfowler.com/eaaCatalog/unitOfWork.html I understand that

A Unit of Work keeps track of everything you do during a business transaction that can affect the database. When you're done, it figures out everything that needs to be done to alter the database as a result of your work.

So I probably should start with a class that has two settable properties and one that tells me whether it's dirty and needs an update.
class Setting
{
    private string _value;

    public Setting(string name, string value)
    {
        Name = name;
        _value = value;
    }

    public string Name { get; set; }

    public string Value
    {
        get { return _value; }
        set
        {
            _value = value;
            IsDirty = true;
        }
    }

    public bool IsDirty { get; private set; }
}

then I guess I need a base repository:
abstract class SettingRepository
{
    private readonly List<Setting> _settings = new List<Setting>();

    public abstract IEnumerable<Setting> Get(Setting setting);

    public void Add(IEnumerable<Setting> settings)
    {
        _settings.AddRange(settings);
    }

    public abstract int SaveChanges();
}

and a unit-of-work as SettingContext:
abstract class SettingContext
{
    protected SettingContext(SettingRepository settings)
    {
        Settings = settings;
    }

    public SettingRepository Settings { get; }
}

Now I'm not sure where I should put all the Update/Insert/SaveChanges logic? A database would for example support transaction whereas the windows registry not.
Do I need different repositories for each storage type or do I need different unit-of-work aka contexts for each of them? I'm really confused.

I don't know what exactly I should do next. Maybe I think to much Entity Framework and try to implement it in a too similar way like this:
using(var context = new SettingContext(new RegistryRepository()))
{
    context.Settings.Add(new Setting("Foo", "Bar")); // this should be created
    context.Settings.Add(otherSetting); // this should be updated
    context.SaveChanges();
}

A: Your approach is fine so far. The "Unit-of-Work" class should get the responsibility to keep track of the changes to your "settings entity" for one "transaction" (it could do this, for example, by keeping a list of commands or changed objects, if there would be more than one object involved), and the abstract repository should provide an abstraction for the CRUD operations (so there will be one concrete repository implementation for each type of storage, that is fine). The "Commit" operation of the "UoW" then just loops over the commands or changed objects and uses the CRUD operations of the injected repo to store the data/changes.
However, if all the data you have to manage is contained in just one settings object, and the update operation is just to write that object into the storage in one transaction, using a "Unit-of-Work" approach is probably overkill. UoW makes more sense if you need some kind of parentheses around a complex transaction, involving multiple objects. For your Settings object, a repo with methods like SaveSettings and LoadSettings is probably sufficient.


text:
Q: Prevent Spring Boot from printing logs to console I am using spring boot for my application and I am using default spring boot logging.
In my application.properties, I have added file path for logging.file,
        logging.file= ${logger_path}

and my pom.xml contains
       <logger_path>/tmp/app.log</logger_path>

When I start the application, it prints the logging messages to the file at /tmp/app.log, but the problem is it also prints the log messages on the console. I really don't understand why it is printing on console (though it is printing them to the specified file) when I have specified a log file.
Is there any configuration to prevent spring boot from printing the log messages to console?

A: Include file-appender.xml and not console-appender with following configuration in logback-spring.xml:
<?xml version="1.0" encoding="UTF-8"?>
    <configuration>
        <include resource="org/springframework/boot/logging/logback/defaults.xml" />
        <property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}spring.log}"/>
        <include resource="org/springframework/boot/logging/logback/file-appender.xml" />
        <root level="INFO">
            <appender-ref ref="FILE" />
        </root>
    </configuration>

You also need to add logging.file to your application.properties
This is in compliance to what is mentioned in spring boot documentation - http://docs.spring.io/spring-boot/docs/current/reference/html/howto-logging.html

A: I tried removing console configuration from logback.xml. But, It was still logging in console. So What I did is, I just removed the appender being added in the logging configuration by springboot. Thereby, we can stop springboot logging in console and separate log file. Add the below lines at the end of your application specific appenders are added. Your custom appender should not match any of these appender names. It worked for me.
// get instance of your log4j instance
Logger logger = LogManager.getRootLogger();
logger.removeAppender("CONSOLE"); // stops console logging
logger.removeAppender("LOGFILE"); // stops file logging

A: Spring boot comes with build-in logback logger, which is configured to print to the console by default.
You need to overwrite the logback configuration (providing your own logback.xml on the classpath).
This is described here -  - section 66.1
How to disable logback logging read here -
as you can see you have to provide the value OFF...something like:
<configuration>
  <include resource="base.xml" />
   .
   .
  <property name="root.level.console" value="OFF" />
</configuration>

Note: Keep in mind that the general idea here is that the logback configuration coming from spring-boot is minimal. The intention is that you provide your own logback configuration and completely overwrite the existing one - e.g. providing your own logback configuration with only log file-appender configured - this should be your general approach.

A: A similar discussion can be found here.
My logback.xml looks like that:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <include resource="org/springframework/boot/logging/logback/defaults.xml" />
  <include resource="org/springframework/boot/logging/logback/file-appender.xml" />

  <root level="INFO">
    <appender-ref ref="FILE" />
  </root>
</configuration>

Just in case you still experience an issue: I have read many discussions about that topic and it was not working at all for me. Unfortunately I have made a really stupid mistake when I have created the file logback.xml for the very first time: A space was added at the beginning of the filename. Therefore the file was never used. So just have another look on the filename, add the file in "src/main/resources" and remove any "logging.config" entries from your property files.

A: Tested with latest 1.3.1 release, with newer releases base.xml has been renamed to defaults.xml
Answer here


text:
Q: How does this LINQ Expression work? I know what this code is doing but I'm not sure on the syntax. It doesn't seem to conform to a "standard" format. Is it mostly LINQ?
return db.Subjects.SingleOrDefault(s => s.ID == ID);

The first part makes sense but it's the part in the brackets I don't understand. How can we use s without declaring it? And how are we putting logic into a method call?

A: It is called a Lambda Expression.  See here for an explanation.
Lambda Expressions (C# Programming Guide)

A: It's the C# 3.0 compiler working some magic for you.
That statement gets compiled into a delegate, and is equivalent to:
return db.Subjects.SingleOrDefault(delegate(s) { return s.ID == ID });

It's called a lambda expression since you don't need to formally declare the parameters, they are inferred by the C# compiler.

A: I think your confusion lies around the expression s => s.ID== ID.  This is a lambda expression.  It simple terms it's a way of definining an inline function.
In this case the text to the left side of the => is the argument list.  So s is declared by virtue of being in it's position.  The right side of the => is the expression executed.  In this particular context the lambda will be run on every element in the collection and the code will assert there is one value which meets the expression executed by the lambda.

A:
The first part makes sense but it's the part in the brackets I don't understand.

What are you seeing here is a lambda expression. It's a very special anonymous delegate.

Is it mostly LINQ?

Enumerable.SingleOrDefault is a LINQ method, but the lambdas are something independent of LINQ; they just make LINQ incredibly more friendly then it otherwise would be.
Now, to get specific IEnumerable<Subject>.SingleOrDefault(s => s.ID == ID) returns the unique instance of Subject in the IEnumerable<Subject> that matches the predicate s => s.ID == ID or it returns null if there is no such instance. It throws an exception if there is more than one such instance. At compile-time s => s.ID == ID is translated into a full-blown delegate the eats objects of type Subject and returns a bool that is true if and only if s.ID is equal to ID.

How can we use s without declaring it?

The => is the lambda operator. It basically separates the left-hand side of the lambda expression from the right-hand side. The left-hand side are the input variables. It's equivalent to the parameter list in an explicitly-defined method. That is s in the lambda expression plays the role of s below:
public bool Predicate(Subject s)

It's just that you don't have to declare the type of s as the compiler will infer it.
The right-hand side the lambda body. It's equivalent to the body below
public bool Predicate(Subject s) {
    return s.ID == ID;
}

What is more, you don't have to declare the return type; the compiler will infer that to.
So, in the end it is as if you did the following:
class MyPredicate {
    public string ID;
    public bool Predicate(Subject s) {
        return s.ID == this.ID;
    }
}

Then:
// elements is IEnumerable<Subject>
// ID is string
MyPredicate predicate = new MyPredicate();
predicate.ID = ID;
elements.SingleOrDefault(predicate.Predicate);

The nice thing is the compiler just automatically spits this out for you when you use a lambda expression.

A: That's a Lambda Expression.

A: s before => declares a variable with type of structure element (type contained in Subjects variable EDIT: Other functions works with more arguments ie. Join) that goes in the right part ( after => ). Logic comes from function. If you call SingleOrDefault (lookup in docs) it will return SINGLE element if satisfy condition or NULL. There are many functions in LINQ that u can use (ie. First(), Where(), ...). Hope that helps.


text:
Q: Replace numbers in string by respective result of a substraction I have a string like this:
"foo 15 bar -2hello 4 asdf+2"

I'd like to get:
"foo 14 bar -3hello 3 asdf+1"

I would like to replace every number (sequence of digits as signed base-10 integers) with the result of a subtraction executed on each of them, one for each number.
I've written a ~50 LOC function that iterates on characters, separating signs, digits and other text, applying the function and recombining the parts. Although it has one issue my intent with the question is not to review it. Instead I'm trying to ask, what is the pythonic way to solve this, is there an easier way?
For reference, here is my function with the known issue, but my intention is not asking for a review but finding the most pythonic way instead.
edit to answer the wise comment of Janne Karila:

*

*preferred: retain sign if given: +2 should become +1

*preferred: zero has no sign: +1 should become 0

*preferred: no spaces: asdf - 4 becomes asdf - 3

*required: only one sign: -+-2 becomes -+-3

edit on popular demand here is my buggy code :)
DISCLAIMER: Please note I'm not interested in fixing this code. I'm asking if there is a better approach than something like mine.
def apply_to_digits(some_str,handler):
    sign = "+"
    started = 0
    number = []
    tmp = []
    result = []
    for idx,char in enumerate(some_str):
        if started:
            if not char.isdigit():
                if number:
                    ss = sign + "".join(number)
                    rewritten = str(handler(int(ss)))
                    result.append(rewritten)
                elif tmp:
                    result.append("".join(tmp))
                number = []
                tmp = []
                sign = "+"
                started = 0
                # char will be dealt later
            else:
                number.append(char)
                continue
        if char in "-+":
            sign = char
            started = 1
            if tmp:
                result.append("".join(tmp))
                tmp = []
            tmp.append(char)
            continue
        elif char.isdigit():
            started = 1
            if tmp:
                result.append("".join(tmp))
                tmp = []
            number.append(char)
        else:
            tmp.append(char)
    if number:
        ss = sign + "".join(number)
        rewritten = str(handler(int(ss)))
        result.append(rewritten)
    if tmp:
        result.append("".join(tmp)), tmp
    return "".join(result)
#

DISCLAIMER: Please note I'm not interested in fixing this code. I'm asking if there is a better approach than something like mine.

A: You could try using regex, and using re.sub:
>>> pattern = "(-?\d+)|(\+1)"
>>> def sub_one(match):
        return str(int(match.group(0)) - 1)

>>> text = "foo 15 bar -2hello 4 asdf+2"
>>> re.sub(pattern, sub_one, text)
'foo 14 bar -3hello 3 asdf+1'

The regex (-?\d+)|(\+1) will either capture an optional - sign and one or more digits, OR the literal sequence +1. That way, the regex will make sure that all of your requirements when converting digits work properly.
The regex (-?\d+) by itself does the right thing most of the time, but the (\+1) exists to make sure that the string +1 always converts to zero, without a sign. If you change your mind, and want +1 to convert to +0, then you can just use only the first part of the regex: (-?d+).
You could probably compress this all into a one-liner if you wanted:
def replace_digits(text):
    return re.sub("(-?\d+)|(\+1)", lambda m: str(int(m.group(0)) - 1), text)


text:
Q: How to launch a "log(all parameters)" request at the beginning of all methods I'm working on C# project, which all use NLog reference for logging purposes.
As a result, everywhere in the project I can add the line log.Debug("...") and some logging will be shown.
One of my colleagues has written a project, applying lots of classes and methods, but the logging is far too little. What I would like, is for every method to launch the following line at the beginning of its execution:
log.Debug(<list of input parameters>);  // all parameters have a ToString() method

In order to achieve that, I'm thinking of some kind of a base method, like this (pseudo-code):
private <whatever_output_type> base_method(...){
  startup :
    string output = "";
    for each (param) in GetParameters():
      output += ", " + param.ToString();
    log.Debug(<this_method_name>, output);
}

Then I do the following for every existing method:
Replace:
private void Method1 (int i1, int i2, string S1, SomeClass obj1)
{ ... }
public void Method2 ()
{ ... }

By:
private void Method1 (int i1, int i2, string S1, SomeClass obj1) : base_method
{ ... }
public void Method2 () : base_method
{ ... }

In order to get a more readable logging, I would use indentation, based on callstack framecount, as explained in this URL, but let's first start making this work.
For that, I need the following:

*

*How can I retrieve the full list of input parameters of a random method?

*How can I mention that something must be done at the start of a method and how to I inherit one method from a basic function?

Thanks in advance

A: Maybe combine this:
public static void InfoParams(this ILoggger logger, params object[] list)
{
    logger.Info("{@params}", (object)list);
}

See also: https://github.com/NLog/NLog/wiki/How-to-use-structured-logging
You could also consider using one of these:

*

*https://www.nuget.org/packages/Tracer.4NLog.Fody/

*https://www.nuget.org/packages/Anotar.NLog.Fody/


text:
Q: Use case for multiple login option I have a use case where user may log in via normal login, as well as social login such as Twitter, Google, Facebook. I draw the use case as below but not sure if it is correct.
Login account ---extends---> normal login
              ---extends---> Twitter login
              ---extends---> Google login
              ---extends---> Facebook login

A: The <<extends>> works vice versa.
I'm quite tired telling this all the time, but Login account is not a use case. It does not deliver any value to an actor. It is a simple constraint which applies to other real use cases.
Further: avoid the use of <<extends>>/<<include>>. They are a sign of functional analysis you are trying to do with your use cases. Instead use cases are synthesized which makes a big difference. If your use case diagrams start resembling a spider's web your design is broken.
Recommended read: Bittner/Spence.

A: In general I tend to agree with Thomas Kilian to be careful with use cases for loggin in as they generally do not pass the boss test.

Will my boss be happy if I do [--insert use case--] 100 times?

But use cases are used in many different ways, and for many different systems. If your system is authentication service then I guess Log In might be an important use case.
Anyhow, the extend relations are pretty much wrong.
There is also a heated debate in the community on what extends really means, and how to use it. I usually advice not to use extend at all.
But if you want to keep them then you probably need to do it the other way around.
The extending use case inserts some specific functionality to the extended use case at a specific point in the execution of the extended use case (the extension point). The extended use case has no knowledge of the extending use case(s).
Extends is probably not what you need here.
I would probably not go into that much detail, and stick to the single Log in use case (if any). You could make alternate scenario's for facebook, twitter, google, etc...
But if you really need this much detail in your use case model then I would use generalization

As you can see there is one abstract use case Log in. The three other concrete use cases inherit from this use case.
In analyses there are no right or wrong answers. There are only better or worse answers, and it all depends heavily on the purpose of your model.

A: I think your use cases are a little too technical. When you're identifying use cases, you need to go back over them a few times to make sure the complete set of uses cases is meaningful. This often means some use cases are merged into a single one, others are split, etc.
The key question to ask when differentiating use cases is "is the difference between these two use cases meaningful to the actor?" You should not be asking "are there different ways to achieve this functionality?" or "will the implementation need to support several different protocols?" These are design issues, which should be documented not in the use cases but in the collaborations which realize them. Realizing one use case with several different alternative collaborations is perfectly valid and normal use of UML.
In this case, does it matter to the user how they log in or is it only important that they log in? I suspect the latter, in which case there should only be one use case.


text:
Q: Querying XML doc with Excel VBA I'm building a list of nodes I need to load from XML document using SelectNodes(xpath):
Set oNodeList = xmldoc.selectNodes("//Object/Property[@Name='Group' and Value='True']")

and looping thru the nodes:
For Each curNode In oNodeList
  Set nAttr = curNode.parentNode.Attributes
  If (nAttr.getNamedItem("Seq").nodeValue = "abc") Then
'  additional processing
  End If
Next

Additional processing involves looping thru child nodes of curNode. I was wondering if it's possible in build yet another nodeList using selectNodes which would select child nodes of curNode that meet particular criteria. The key point that xpath should start looking from the current node.
How can I do that?

A: Alejandro, thank you! It seems like
curNode.Selectnodes("child::*")

does the trick!


text:
Q: Confirmation box is not working when trying to run a python script from an HTML button I'm new to PHP and HTML so I was looking for some help. I need to get the confirmation box working on this script. Any help will be greatly appreciated. Thanks.
The python script "disconnect.py" runs fine when the "Disconnect Service" button is clicked but I do not get a confirmation box.
<?php

  $output = exec("/usr/bin/python /var/www/html/disconnect.py");

?>

<html>
<body>
  <form action="/button1.php" method="get">
    <button onclick="$output()">Disconnect Service</button>
    <script>
      function output() {
        confirm("Are you sure?");
      }
    </script>

    </form>

  </body>

</html>

A: Your button is not calling the JavaScript function. The diconnect.py script is not being called when the button is clicked. That being said, to get the confirmation to display, try the following below.
<button onclick="output()">Disconnect Service</button>


text:
Q: Android 2.1-update1 AVD cannot make a successful connection to Charles Web Proxy 3.6 From the Administrator Command Prompt on Windows 7, I type in:
C:\Program Files (x86)\Android\android-sdk\tools>emulator -avd Nexus -http-proxy localhost.:8888 -port 5554 -debug-proxy

I return the following:
C:\Program Files (x86)\Android\android-sdk\tools>server name 'localhost.' resolved to 127.0.0.1:8888
proxy_http_setup: creating http proxy service connecting to: localhost.:8888
server name 'localhost.' resolved to 127.0.0.1:8888
proxy_http_setup: creating HTTP Proxy Service Footer is (len=2):
'
'
http_service_connect: trying to connect to (null)
http_service_connect: using HTTP rewriter
tcp:(null)(252): connecting
tcp:(null)(252): connected to http proxy, sending header
tcp:(null)(252): sending 27 bytes:
>> 43 4f 4e 4e 45 43 54 20 28 6e 75 6c 6c 29 20 48    CONNECT (null) H
>> 54 54 50 2f 31 2e 31 0d 0a 0d 0a                   TTP/1.1....

tcp:(null)(252): header sent, receiving first answer line
tcp:(null)(252): received 'HTTP/1.0 503'
tcp:(null)(252): connection refused, error=503
http_service_connect: trying to connect to (null)
http_service_connect: using HTTP rewriter
tcp:(null)(332): connecting
http_service_free

When I open the browser in the emulator, I have the following entry in Charles:
null:0
Failed
CONNECT request didn't include a port: (null)
HTTP/1.1
CONNECT
/127.0.0.1

If I try to use my IP Address, I receive the following:
C:\Program Files (x86)\Android\android-sdk\tools>emulator -avd Nexus -http-proxy 192.234.2.90:8888 -debug-proxy

C:\Program Files (x86)\Android\android-sdk\tools>server name '192.xxx.2.xx' resolved to 192.xxx.2.xx:8888
emulator: Could not connect to proxy at 192.xxx.2.xx:8888: resource temporarily unavailable !
emulator: Proxy will be ignored !

How do I properly run Charles against the Android emulator?
I've read the other posts about setting the proxy and port in Settings while the emulator is running, but I receive the similar errors with -debug-proxy turned on.
Thanks.

A: This seems to be a problem with the latest version of the Android development tools, r12.
This bug report indicates that downgrading to the emulator binary from r11 will fix the problem. Go to the Android SDK download page and change the '12' in the URL for your OS to '11'. Install that SDK to a separate directory from your existing SDK, and use that emulator version until Google fixes the problem.

A: Just as an update for anyone else looking at this, this problem has been addressed in r13

A: It's a bug that had been fixed at VERSION 3.9.
http://www.charlesproxy.com/documentation/version-history/


text:
Q: What is the most efficient and least laggy method for creating geofence? I am trying to create a geofence that the user can click a button and it will alert whether or not the user is within the zone. I have a way to make this work but since I am new to iOS programming and swift, I am not sure if this is the most efficient way. Also, the user location dot sometimes lag on my app (it says the user is somewhere else instead of displaying the correct position). Is my implementation of the geofence correct? Or am I missing something?
The code that I am using is:
To display user location:
func checkLocationAuthorizationStatus() {
    if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
        Map.showsUserLocation = true
    } else {
        locationManager.requestWhenInUseAuthorization()
    }
}

To set up the location manager
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    checkLocationAuthorizationStatus()

    if (CLLocationManager.locationServicesEnabled()) {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()
    }
}

And for creating the geofence
@IBAction func checkLocation(sender: UIButton) {
    let geoFence = CLCircularRegion(center: defaultLocation, radius: 15, identifier: "fence")
    if geoFence.containsCoordinate(userLocation.coordinate) {
        let title = "You are in the zone"
        let okText = "OK"

        let alert = UIAlertController(title: title, message: nil, preferredStyle: UIAlertControllerStyle.Alert)
        let okayButton = UIAlertAction(title: okText, style: UIAlertActionStyle.Cancel, handler: nil)
        alert.addAction(okayButton)

        presentViewController(alert, animated: true, completion: nil)
    } else {
        print("no")
    }
}


text:
Q: call the same jQuery function in multiple buttons I am not really familiar with jQuery. I have this code that I downloaded to create a fade in/fade out popup form. Here's the code:
<script type='text/javascript'>
    $(document).ready(function() {
        $('#button').click(function(e) {
            $('#modal').reveal({
                animation: 'fade',
                animationspeed: 150,
                closeonbackgroundclick: true,
                dismissmodalclass: 'close'
            });
            return false;
        });
    });
</script>

The code above executes when a button with an id='button' is clicked. Now I have multiple buttons, how can I call this function in all buttons? I tried setting the id of all buttons to button but only the first button works. Any help would be very much appreciated.
By the way I forgot to mention, in my .php file i have this codes:
for ($c=1;$c<=5;$c++){
echo "<input type='button' id='button'">
};

This php code will display 5 buttons with the same id which is 'button'. What I want to happen is when I click any of the 5 buttons the jQuery function will execute which is popping up a fade in/fade out form.

A: First solution :
function doClick(e) {
   $('#modal').reveal({
     animation: 'fade',
     animationspeed: 150,
     closeonbackgroundclick: true,
     dismissmodalclass: 'close'
   });
   return false;
}
$('#button1').click(doClick);
$('#button2').click(doClick);

Second solution :
Give a class "someClass" to all the involved buttons
<input type=button class=someClass ...

and do
$('.someClass').click(function(e) {
...
});

Third solution :
Use the comma to separate ids :
$('#button1, #button2').click(function(e) {
...
});

Generally, the best solution is the second one : it allows you to add buttons in your code without modifying the javascript part. If you add some of those buttons dynamically, you may even do
$(document).on('click', '.someClass', function(e) {
...
});

A: Use different ids for buttons and change your function as below.

$('#button1, #button2, #button3').click(function(e) {
  .....

A: IDs should be unique. Try using something like
$('input[type="button"]')

A: you class can call them by class you using , seperated id
$(document).ready(function() {
$('#button, #button1, #button2').click(function(e) {
$('#modal').reveal({
animation: 'fade',
animationspeed: 150,
closeonbackgroundclick: true,
dismissmodalclass: 'close'
});
return false;
});
});

A: <script type='text/javascript'>
$(document).ready(function() {
$('#button1,#button2,#button3').click(function(e) {
$('#modal').reveal({
animation: 'fade',
animationspeed: 150,
closeonbackgroundclick: true,
dismissmodalclass: 'close'
});
return false;
});
});
</script>

or else use class as mentioned bt dystroy

A: You can use css class name instead of id to achieve it like below
<script type='text/javascript'>
$(document).ready(function() {
    $('.fade').click(function(e) {
        $('#modal').reveal({
            animation: 'fade',
            animationspeed: 150,
            closeonbackgroundclick: true,
            dismissmodalclass: 'close'
        });
        return false;
    });
});
</script>

and your html of the buttons
<button class="fade">Button1</button>
<button class="fade">Button2</button>
<button class="fade">Button3</button>

A: If you use same  buttonid  for  all button then there is no  need to call all buttons..just simply use this code..It seems that you are using animation in this code....well use togglefade instead of reveal

<script type=text/javascript>
       $(document).ready(function(){
          $("button").click(function(){
             $("#buttonid").fadein();
             $("#buttonid").fadeout();
     });
    });
  </script>

A: Create an array for unique buttonid dynamically in the loop like
$button[] = '#'.$buttonid;

Outside the loop use implode to convert this array to comma separated string
$jsstring = implode(",",$button);

Now use php to pass above string as selector in your js code like:
$(document).ready(function() {
    $('< php echo $jsstring ; ?>').click(function(){ });
});

A: To use the easier simple ways as following code :
Method 1:

<script>
    $(document).ready(function () {
        $('input:button[name="button1"],[name="button2"]').click(
            function () {
                alert('test')
            });
    });
</script>
<input type="button" id="button1" name="button1" value="Filter" />
<input type="button" id="button2" name="button2" value="Filter" />

Method 2:

<script>
    $(document).ready(function () {
        $('button[id="button1"],[id="button2"]').click(
            function () {
                alert('te2222st')
            });
    });
</script>
<button id="button1" >bbbbb</button>
<button id="button2" >bbbbb</button>

A: I have solution for this problem
      $(document).ready(function () {
                    $("#btnSubmit,#btnSubmitbuttom").click(function () {
                        var rfp = true;
                        var count = 0;
                        var lbxBD_Role = $("#lbxBD_Role option:selected").val();
                        if (lbxBD_Role == "" || lbxBD_Role == undefined) {
                            $("#lblBD_Role").attr("style", "visibility: visible");
                            $("#lblBD_Role").attr("style", "color: red");
                            $("#lblBD_Role").html('* Required');
                            count++;
                        }
                      });
                   });
            </script>


text:
Q: Paramaterized batch insert into spring JDBC I'm trying to create a function to batch insert data into different tables using Spring JDBC. I am looking at section 13.4 of http://static.springsource.org/spring/docs/current/spring-framework-reference/html/jdbc.html to see how I can do it, but it doesn't show any examples when list of columns and values are dynamically generated.
In Python and cx_Oracle all I did was to do that using insertmany by passing a sql statement and a dictionary consists of (column: values) to it.
Is there any ways to achieve the same thing on Java using Spring JDBC?

A: Something like this:
public final SimpleJdbcInsert create(String tableName, String columnNames)
{
    return new SimpleJdbcInsert(jdbcTemplate).withTableName(tableName)
            .usingColumns(getTokens(columnNames));
}

final Map<String, Object> parameters = new HashMap<String, Object>();
/*
* columnName1 is in columnNames
*/
parameters.put("columnName1", value1);

final SimpleJdbcInsert insert = create(table, columnNames);
insert.execute(parameters);


text:
Q: Swagger constructor based mandatory fields When I use Swagger-codegen, The only constructor generated is the default constructor.
I want a constructor with all my fields, for example:
public Person(String name, int age) { };

Do you know what I should change in the yaml file to make it work? Is it possible? How?
Update - Example:
---
swagger: "2.0"
info:
  version: 1.0.0

paths: {}

definitions:
  Person:
    type: object
    required:
      - name
      - state
    properties:
      name:
         type: string
      state:
         type: string


text:
Q: jquery load event sometimes dont work, why? i use something like this
$(img).bind('load',function(){
       console.log('loaded');
});

and obviously it works, but when the page is loading images from cache
the event isn't triggered.
how can i fix this situation?

A: This event isn't triggered in some browsers if the image is cached, to get around that you need to check the .complete property, like this:
$("img").one('load',function(){
       console.log('loaded');
}).each(function() {
  if(this.complete) $(this).load();
});

The .one() ensures it doesn't fire twice, the .each() part is manually firing the event for cached images that aren't doing a load event themselves.

A: Fount it!
each image has a .complete property(boolean) so i just need to check that before i bind a load event.


text:
Q: What did you there? What do you then? Why are they grammatically correct? In literature I meet such questions: What did you there? What do you then? Why are they grammatically correct?

Pussycat pussycat, where have you been? I've been up to London to
  visit the Queen. Pussycat pussycat, what did you there? I frightened a
  little mouse under her chair

In another source of this poem I saw 'what you did there?'

"We will need men," Zouga said. "What will you do when you have them?"
  Jan Cheroot asked. "Dig the stuff out." "And then?" the little
  Hottentot demanded with a malicious gleam in his dark eyes, his
  features wrinkled as a sour windfallen apple. "What do you then?"
  he insisted.

A: They were grammatical several hundred years ago, but are not used in contemporary English.
Today we would ask:
What did you do there?
using did as an auxiliary to form the past tense in combination with bare infinitive do.
What saw you there? would become today What did you see there?


text:
Q: Fastled not enough CPU power? I was wondering if someone could help me out?
I have a 5M ledstrip (300 leds) and running the following code on my ESP32.
The code will make a led light spinning around!
void spinningwheel(){
int random_number;
int spin_speed;
for(int i =0; i < 1; i++){
random_number = random(NUM_LEDS);
}

Serial.println(random_number);
for (int i = 0; i <= random(6,15); i++){
spin_speed = i+1;
for (int i = 0; i <= NUM_LEDS; i++){
leds[i] = CRGB ( 0, 0, 255);
leds[i-10] = CRGB ( 0, 0, 0);
FastLED.show();
delay(spin_speed);
}
FastLED.clear();

}
for (int i = 0; i <= random_number; i++){
leds[i] = CRGB ( 0, 0, 255);
leds[i-10] = CRGB ( 0, 0, 0);
FastLED.show();
delay(spin_speed);
}
FastLED.clear();
delay(1000);
}

The code is working fine if i use leds[i-3] = CRGB ( 0, 0, 0);
But when i change the number i-3 to something
like i-10 ill get a error in my Serial port
15:51:36.233 -> 258
15:51:36.267 -> Guru Meditation Error: Core  1 panic'ed (StoreProhibited).
Exception was unhandled.
15:51:36.335 -> Core 1 register dump:
15:51:36.368 -> PC      : 0x400d12ae  PS      : 0x00060930  A0      :
0x800d1658  A1      : 0x3ffb1e80
15:51:36.469 -> A2      : 0x3ffc0124  A3      : 0x3ffb1ea4  A4      :
0x3ffc04bc  A5      : 0x3ffb1eb0
15:51:36.571 -> A6      : 0x00000000  A7      : 0x3ffb0060  A8      :
0x00000000  A9      : 0x3ffb1e40
15:51:36.639 -> A10     : 0x00000001  A11     : 0x00000000  A12     :
0x3ffb8570  A13     : 0x00000000
15:51:36.742 -> A14     : 0x3ffb8528  A15     : 0x00000000  SAR     :
0x00000020  EXCCAUSE: 0x0000001d
15:51:36.843 -> EXCVADDR: 0x00000000  LBEG    : 0x400d0dfd  LEND    :
0x400d0e0c  LCOUNT  : 0x00000000
15:51:36.944 ->
15:51:36.944 -> Backtrace: 0x400d12ae:0x3ffb1e80 0x400d1655:0x3ffb1ea0
0x400d1741:0x3ffb1ee0 0x400d0ee0:0x3ffb1f20 0x400d0fe1:0x3ffb1f40
0x400d115e:0x3ffb1f70 0x400d118f:0x3ffb1f90 0x400d216d:0x3ffb1fb0
0x40088215:0x3ffb1fd0
15:51:37.147 ->
15:51:37.147 -> Rebooting...
15:51:37.180 -> :⸮⸮⸮⸮L⸮⸮1⸮m֊⸮1
HL⸮⸮b⸮⸮⸮

DECODE OF THE ERROR
PC: 0x400d12ae: ClocklessController14, 60, 150, 90, (EOrder)66, 0, false,
5>::showPixels(PixelController(EOrder)66, 1, 4294967295u>&) at
D:\Documenten\Arduino\libraries\FastLED/controller.h line 178
EXCVADDR: 0x00000000

Decoding stack results
0x400d12ae: ClocklessController14, 60, 150, 90, (EOrder)66, 0, false,
5>::showPixels(PixelController(EOrder)66, 1, 4294967295u>&) at
D:\Documenten\Arduino\libraries\FastLED/controller.h line 178
0x400d1655: CPixelLEDController(EOrder)66, 1, 4294967295u>::show(CRGB const*,
int, CRGB) at D:\Documenten\Arduino\libraries\FastLED/controller.h line 408
0x400d1741: CFastLED::show(unsigned char) at
D:\Documenten\Arduino\libraries\FastLED/controller.h line 90
0x400d0ee0: CFastLED::show() at
D:\Documenten\Arduino\libraries\FastLED/FastLED.h line 500
0x400d0fe1: spinningwheel() at
D:\Documenten\Arduino\Ledstrip_wave/Ledstrip_wave.ino line 48
0x400d115e: Binair_buttons() at
D:\Documenten\Arduino\Ledstrip_wave/Ledstrip_wave.ino line 125
0x400d118f: loop() at D:\Documenten\Arduino\Ledstrip_wave/Ledstrip_wave.ino
line 141
0x400d216d: loopTask(void*) at
C:\Users\....\AppData\Local\Arduino15\packages\esp32\
hardware\esp32\1.0.4\cores\esp32\main.cpp line 19
0x40088215: vPortTaskWrapper at /home/runner/work/esp32-arduino-lib-
builder/esp32-arduino-lib-builder/esp-idf/components/freertos/port.c line 143

Can someone please explain me what i am doing wrong? Or did i passed the max RAM or CPU usage.

A: You have array of colors indexed from  0 up to NUM_LEDS-1, if you use indexes before or after that space, you are destroying something you shouldn't.
And now:
for (int i = 0; i <= NUM_LEDS; i++){  // values of i  0 .. NUM_LEDS (including! -buffer overflow)
  leds[i] = CRGB ( 0, 0, 255);
  leds[i-10] = CRGB ( 0, 0, 0);  // for all i less than 0, you are BEFORE the actual array

So you've achieved to go outside the array on both sides. Going three elements before the first element obviously didn't do so much damage to crash the program, but 10 elements before must've destroyed something really important. And also going after the array boundaries destroys something stored just after it..


text:
Q: c++ unable to get trie to give correct search words I'm creating a word suggestion auto-complete interface. I'm using a trie in c++ to do this. I'd like to enter part of a word into my code and have the trie suggest possible words to complete the end of my word.
#include<bits/stdc++.h>
using namespace std;

#define alphabet (26)

#define CHAR_TO_INDEX(c) ((int)c - (int)'a')

struct TrieNode
{
    struct TrieNode *children[alphabet];

    // isWordEnd is true if the node represents
    // end of a word
    bool isWordEnd;
};

struct TrieNode *getNode(void)
{
    struct TrieNode *Node = new TrieNode;
    Node->isWordEnd = false;
    for (int i = 0; i < alphabet; i++)
        Node->children[i] = NULL;

    return Node;
}

void insert(struct TrieNode *root,  const string key)
{
    struct TrieNode *Crawl = root;

    for (int level = 0; level < key.length(); level++)
    {
        int index = CHAR_TO_INDEX(key[level]);
        if (!Crawl->children[index])
        {
            Crawl->children[index] = getNode();
            //Crawl = Crawl->children[index];
        }
        Crawl = Crawl->children[index];
    }
    // mark last node as leaf
    Crawl->isWordEnd = true;
}

//returns 0 if current node has a child
// If all children are NULL, return 1.
bool isLastNode(struct TrieNode* root)
{
    for (int i = 0; i < alphabet; i++)
        if (root->children[i])
            return 0;
    return 1;
}

void suggestionsRec(struct TrieNode* root, string currPrefix)
{
    // found a string in Trie with the given prefix
    if (root->isWordEnd)
    {
        cout << currPrefix;
        cout << endl;
    }

    // All children struct node pointers are NULL
    if (isLastNode(root))
    {
        //currPrefix = "help";
        //deleteNode(root);
        //delete root;
        //root = NULL;
        //currPrefix.pop_back();
        return;

    }

    for (int i = 0; i < alphabet; i++)
    {
        if (root->children[i])
        {
            currPrefix.push_back(97 + i);
            //currPrefix.push_back(i);
            //currPrefix.pop_back(97 + i);
             /*if (isLastNode(root))
             {
                currPrefix.erase(3);
             }*/

            // recur over the rest
            suggestionsRec(root->children[i], currPrefix);
            //printAutoSuggestions(root->children[i], currPrefix);
        }
    }
}

// print suggestions for given query prefix.
int printAutoSuggestions(TrieNode* root, const string query)
{
    struct TrieNode* Crawl = root;

    // Check if prefix is present and find the
    // the node (of last level) with last character
    // of given string.
    int level;
    int n = query.length();
    for (level = 0; level < n; level++)
    {
        int index = CHAR_TO_INDEX(query[level]);

        // no string in the Trie has this prefix
        if (!Crawl->children[index])
            return 0;

        Crawl = Crawl->children[index];
    }
    // If prefix is present as a word.
    bool isWord = (Crawl->isWordEnd == true);

    // If prefix is last node of tree (has no
    // children)
    bool isLast = isLastNode(Crawl);

    // If prefix is present as a word, but
    // there is no subtree below the last
    // matching node.
    if (isWord && isLast)
    {
        cout << query << endl;
        return -1;
    }

    // If there are are nodes below last
    // matching character.
    if (!isLast)
    {
        string prefix = query;
        suggestionsRec(Crawl, prefix);
        return 1;
    }
}

// Driver Code
int main()
{
    struct TrieNode* root = getNode();

    insert(root, "hello");
    insert(root, "dog");
    insert(root, "hell");
    insert(root, "cat");
    insert(root, "a");
    insert(root, "hel");
    insert(root, "help");
    insert(root, "helps");
    insert(root, "helping");

    int comp = printAutoSuggestions(root, "hel");

    if (comp == -1)
        cout << "No other strings found with this prefix\n";

    else if (comp == 0)
        cout << "No string found with this prefix\n";

    return 0;
}

When I enter the prefix "hel" I'd like to see
hel
hell
hello
help
helping
helps
But instead, I just see
hel
hell
hello
hellp
hellping
hellpis

A: In suggestionsRec(...) you have:
for (int i = 0; i < alphabet; i++)
  {
    currPrefix.push_back(97 + i);
    ...
    suggestionsRec(root->children[i], currPrefix);
  }
}

You are adding characters to currPrefix and keeping them. So you call suggestionsRec on later children, with characters in currPrefix that don't belong there.


text:
Q: Android: Exception when calling a static java method from cpp thread When my java class loads, I call this jni method to set "listener" from cpp to java (I record audio using cpp and want to pass its bytes to java) :
MyJava.class
setListener(JNIEnv *env, jclass thiz);

myCpp.cpp
setListener(JNIEnv *env, jclass thiz) {
    envMyClass = env;
    classMyClass = thiz;
    // I read that I need these 2 lines in order to connect the java thread to the cpp thread
    env->GetJavaVM(&javavm);
    GetJniEnv(javavm, &envCamera);
    return 0;
}

bool GetJniEnv(JavaVM *vm, JNIEnv **env) {
    bool did_attach_thread = false;

    *env = nullptr;
    // Check if the current thread is attached to the VM
    auto get_env_result = vm->GetEnv((void**)env, JNI_VERSION_1_6);
    if (get_env_result == JNI_EDETACHED) {
        if (vm->AttachCurrentThread(env, NULL) == JNI_OK) {
            did_attach_thread = true;
        } else {
            // Failed to attach thread. Throw an exception if you want to.
        }
    } else if (get_env_result == JNI_EVERSION) {
        // Unsupported JNI version. Throw an exception if you want to.
    }
    return did_attach_thread;
}

and the in myCpp.cpp thread I'm trying to call:
if (envMyClass != nullptr && classMyClass != nullptr && javavm != nullptr) {
    LOGD("000");
    jmethodID javaMethod = envMyClass->GetStaticMethodID(classMyClass, "myJavaFunction", "()V");
    LOGD("001");
    envMyClass->CallStaticVoidMethod(classMyClass, javaMethod);

}

and it crashes on the line of "jmethodId javaMethod.."
myJavaFunction is a method in MyJava class:
public static void myJavaFunction() {
    Log.d("my_log", "jni callback");
}

the crash:
   Abort message: 'JNI DETECTED ERROR IN APPLICATION: a thread (tid 12346 is making JNI calls without being attached
    in call to GetStaticMethodID'

Any idea how to fix it?

A: I've noticed a few things:

*

*In setListener, I assume you are assigning jclass thiz to a global variable classMyClass. To do so, you should use classMyClass = env->NewGlobalRef(thiz), otherwise the class reference will not be valid (reference).

*You are calling GetJniEnv but you do not check its result and therefore you do not actually know whether the current thread has attached successfully.

*I assume you are attaching the current thread in setListener, save the env to a global variable, and then use that variable at another point in your code. Could it be that you are switching thread context somewhere in between? You could do the following to make sure the current thread is really attached:

    JNIEnv *thisEnv;
    int getEnvStat = jvm->GetEnv((void **)&thisEnv, JNI_VERSION_1_6 /* or whatever your JNI version is*/);
    if (getEnvStat == JNI_EDETACHED)
    {
        if (jvm->AttachCurrentThread(&thisEnv, NULL) != 0)
        {
           // throw error
        }
        else
        {
           jmethodID javaMethod = thisEnv->GetStaticMethodID(classMyClass, "myJavaFunction", "()V");
           thisEnv->CallStaticVoidMethod(classMyClass, javaMethod);
        }
    }
    else if (getEnvStat == JNI_OK)
    {
       jmethodID javaMethod = thisEnv->GetStaticMethodID(classMyClass, "myJavaFunction", "()V");
       thisEnv->CallStaticVoidMethod(classMyClass, javaMethod);
    }
    else if (getEnvStat == JNI_EVERSION)
    {
       // throw error
    }
}

*You can make this more efficient if you call jmethodID javaMethod = thisEnv->GetStaticMethodID(classMyClass, "myJavaFunction", "()V"); only once initially and store the jmethodID in a global variable. jmethodIDs are valid across envs.


text:
Q: java.lang.ClassCastException: java.util.HashMap cannot be cast to java.util.TreeMap I stuff a TreeMap into an intent:
private TreeMap<Long, Long> mSelectedItems;

...

mSelectedItems = new TreeMap<Long, Long>();

...

Intent intent = new Intent();
intent.putExtra("results", mSelectedItems);

setResult(RESULT_OK, intent);

and then attempt to read it back out in the calling activity:
TreeMap<Long, Long> results = (TreeMap<Long, Long>)
    data.getSerializableExtra("results");

which causes:
E/AndroidRuntime(26868): Caused by: java.lang.ClassCastException: java.util.HashMap cannot be cast to java.util.TreeMap

Well, sure, but since I'm not using HashMap anywhere in the code, and since TreeMap implements Serializable, this should work without error, no? Why is android trying to force a class on me that I'm not using?

A: The first link that Emmanuel provided is the exact same issue you are having. It doesn't specifically mention that exact error but it is implied.
The issue is that when your TreeMap is serialized it will come back as a HashMap. Completely explained by this answer which Emmanuel also provided.
So simply doing the follow shall resolve your issue:
TreeMap<Long, Long> results = new TreeMap<Long, Long>((HashMap<Long, Long>) getIntent().getSerializableExtra("results"));

Basically populates your results TreeMap with the HashMap returned from the bundle.
Also upvote those answers in the links provided if this resolves your issue.