text:
Q: Exception at client side when WCF service does callback I have a WCF service
[ServiceContract(CallbackContract = typeof(ICallback))]
public interface IMonitorService
{
  [OperationContract]
  [FaultContract(typeof(MonitorFaultException))]
  void StartMonitoring(MonitorRequest monitorRequest);

}

In the service implementation, I have following service behavior

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant)]

I have two clients for this service

*

*Console application (for testing).

*Web application REST API.

In case of console application client, everything works fine. But when I use Web application client and there is a callback from service side I get following error:

An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%@ Page Async="true" %>.

My web application controller looks like
// I am using same types as WCF for input just for simplicity
public ApiResponse StartMonitor(MonitorRequest request)
{
   IMonitorService monitorService = new MonitorServiceClient(new InstanceContext(callbackEventHandler));
   monitorService.StartMonitoring(request);

   //create ApiResponse and return.
}

Console application also has the same code as shown above. The only difference here is I have a Console.Read() at the end of the main.
Following is the stack trace from windows event viewer

StackTrace:    at
  System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc&
  rpc)    at
  System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc&
  rpc)    at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean
  isOperationContextSet)    at
  System.ServiceModel.Dispatcher.ChannelHandler.DispatchAndReleasePump(RequestContext
  request, Boolean cleanThread, OperationContext
  currentOperationContext)    at
  System.ServiceModel.Dispatcher.ChannelHandler.HandleRequest(RequestContext
  request, OperationContext currentOperationContext)    at
  System.ServiceModel.Dispatcher.ChannelHandler.AsyncMessagePump(IAsyncResult
  result)    at
  System.ServiceModel.Dispatcher.ChannelHandler.OnAsyncReceiveComplete(IAsyncResult
  result)    at
  System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult
  result)    at System.Runtime.AsyncResult.Complete(Boolean
  completedSynchronously)    at
  System.ServiceModel.Channels.TransportDuplexSessionChannel.TryReceiveAsyncResult.OnReceive(IAsyncResult
  result)    at
  System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult
  result)    at System.Runtime.AsyncResult.Complete(Boolean
  completedSynchronously)    at
  System.ServiceModel.Channels.SynchronizedMessageSource.ReceiveAsyncResult.OnReceiveComplete(Object
  state)    at
  System.ServiceModel.Channels.SessionConnectionReader.OnAsyncReadComplete(Object
  state)    at
  System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult
  result)    at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
  at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result,
  IntPtr userToken)    at
  System.Net.Security.NegotiateStream.ProcessFrameBody(Int32 readBytes,
  Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest
  asyncRequest)    at
  System.Net.Security.NegotiateStream.ReadCallback(AsyncProtocolRequest
  asyncRequest)    at
  System.Net.AsyncProtocolRequest.CompleteRequest(Int32 result)    at
  System.Net.FixedSizeReader.CheckCompletionBeforeNextRead(Int32 bytes)
  at System.Net.FixedSizeReader.ReadCallback(IAsyncResult
  transportResult)    at System.Runtime.AsyncResult.Complete(Boolean
  completedSynchronously)    at
  System.ServiceModel.Channels.ConnectionStream.IOAsyncResult.OnAsyncIOComplete(Object
  state)    at
  System.Net.Sockets.SocketAsyncEventArgs.OnCompleted(SocketAsyncEventArgs
  e)    at
  System.Net.Sockets.SocketAsyncEventArgs.FinishOperationSuccess(SocketError
  socketError, Int32 bytesTransferred, SocketFlags flags)    at
  System.Net.Sockets.SocketAsyncEventArgs.CompletionPortCallback(UInt32
  errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)    at
  System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32
  errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
InnerException: System.InvalidOperationException

But When I call the service on a separate thread everything starts working fine:-
Changing
  monitorService.StartMonitoring(request)

to
  Task.Run(() => monitorService.StartMonitoring(request)).Wait();

I also tried calling the async version (by changing the return types of controller accordingly)
 await monitorService.StartMonitoringAsync(request);

but then the error messages changes to:

An asynchronous module or handler completed while an asynchronous operation was still pending.

EDIT The above error is not at the callback but it occurs as ApiResponse.
I have following questions:-
Q-1 Why console client callback is happening and web application callback is not happening? I guess Console.Read() (which I am doing in the console application) is making the thread to wait to receive the callback. Please clarify.
Q-2 Why callback is happening on web application when I shoot the call on a separate thread?
Q-3 Edit: New question In general on which thread callback happens from WCF service? Will it be a new thread at client side to handle callback every time?
Q-4 Why async version of the method is not working?


text:
Q: Partition the list ListNode* partition(ListNode* head, int x) {
    ListNode *p1 = NULL, *p2 = NULL, *cur = head, *cur1, *cur2;
    while (cur != NULL) {
        if (cur->val < x) {
            if (p1 == NULL) {
                p1 = cur;
                cur1 = cur;
            } else {
                cur1->next = cur;
                cur1 = cur1->next;
            }
        }
        else {
            if (p2 == NULL) {
                p2 = cur;
                cur2 = cur;
            } else {
                cur2->next = cur;
                cur2 = cur2->next;
            }
        }
        cur = cur->next;
    }
    if (cur2 != NULL) cur2->next = NULL;
    if (p1 != NULL && cur1 != NULL) {
        cur1->next = p2;
        return p1;
    }
    return p2;
}

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

But I got an error for some test case:

*

*Runtime Error Message:

free(): invalid next size (fast): 0x00000000020f1200 ***

*

*Last executed input:
[-29,-2,-43,-26,-12,58,-55,-44,-75,83,9,46,29,-6,-79,-73,-96,66,66,-100,20,-89,-14,-67,12,96,27,-36,29,-68,29,52,30,38,79,70,-3,-76,-73,-26,60,-12,-80,-11,82,94,16,86,12,-17,39,-68,-54,-75,-82,58,74,-3,74,-45,29,-45,59,-89,94,38,82,-57,15,-91,-31,-25,-3,-58,64,-69,-64,-20,69,0,15,8,32,61,-14,2,-29,-88,-100,97,-81,29,-47,30,-7,99,-31,-73,94,36,88,-37,-89,-63,5]

105

A: Your function is correct. the error exists somewhere else in your code. You should search for the memory error message..
I briefly implemented the following code:
#include <iostream>

using namespace std;

struct ListNode{
    int val;
    ListNode* next;
};

void insert(ListNode *head, int x){
    ListNode *cur = head;
    ListNode *new_node = new ListNode;
    new_node->val = x;
    new_node->next = 0;
    while(cur->next != 0){
        cur = cur->next;
    }
    cur->next = new_node;
}

void print(ListNode *head){
    ListNode *cur = head;
    while (cur != 0){
        cout << cur->val << "-";
        cur = cur->next;
    }
    cout << "NULL" << endl;
}
ListNode* partition(ListNode* head, int x);

int main(){
    ListNode* head = new ListNode;
    head->val= 1;
    head->next = 0;
    insert(head, 4);
    insert(head, 3);
    insert(head, 2);
    insert(head, 5);
    insert(head, 2);
    print(head);
    ListNode * newhead = partition(head, 3);
    cout << endl;
    print(newhead);
    return 0;
}

ListNode* partition(ListNode* head, int x) {
    ListNode *p1 = NULL, *p2 = NULL, *cur = head, *cur1, *cur2;
    while (cur != NULL) {
        if (cur->val < x) {
            if (p1 == NULL) {
                p1 = cur;
                cur1 = cur;
            } else {
                cur1->next = cur;
                cur1 = cur1->next;
            }
        }
        else {
            if (p2 == NULL) {
                p2 = cur;
                cur2 = cur;
            } else {
                cur2->next = cur;
                cur2 = cur2->next;
            }
        }
        cur = cur->next;
    }
    if (cur2 != NULL) cur2->next = NULL;
    if (p1 != NULL && cur1 != NULL) {
        cur1->next = p2;
        return p1;
    }
    return p2;
}

it gives 1-4-3-2-5-2 and the partitioned list 1-2-2-4-3-5

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flutter GridView acting weird (web app), Can someone please explain what is wrong here and how to fix it? I have a List<Map<String,Widget>> and one function to remove items from it, and one function to add to it, and both setState the console is printing that the item removed is actually correct, but on the interface, it's only the last item is removed, and somehow the widget that is to be removed is still there on the interface.
Here are the two functions:
addPage() {
    String i = pageHolder.ins.pages[pageHolder.ins.pages.length - 2].keys.first;
    pageHolder.ins.pages.insert(pageHolder.ins.pages.length - 1, {
      "${int.parse(i) + 1}":
          PageWidget(callback: removePage, index: int.parse(i) + 1)
    });
    setState(() {});
  }

 removePage(String index) {
    print("remove page index recerived: $index");
    var i = (pageHolder.ins.pages)
        .indexWhere((element) => element.keys.first == index);
    print("should be removing at: $i");
    pageHolder.ins.pages.removeAt(i);

    setState(() {});
  }

and here is what i get in the console:
[{0: PageWidget}, {1: PageWidget}, {2: PageWidget}, {7: PageWidget}, {8: PageWidget}, {9: PageWidget}, {: Adder}]
remove page index recerived: 7
should be removing at: 3
[{0: PageWidget}, {1: PageWidget}, {2: PageWidget}, {8: PageWidget}, {9: PageWidget}, {: Adder}]

here is the widget code:
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart';
import 'package:teacher_page/classes/pageHolder.dart';

import 'classes/audiostreamer.dart';

class PageWidget extends StatefulWidget {
  final index;
  final callback;
  const PageWidget({super.key, this.index, this.callback});

  @override
  State<PageWidget> createState() => _PageWidgetState();
}

class _PageWidgetState extends State<PageWidget>
    with AutomaticKeepAliveClientMixin {
  @override
  void initState() {
    print("init state is called again and index is:${widget.index}");
    super.initState();
  }

  bool imageAvailable = false;
  late Uint8List imageBytes;
  late Uint8List AudioBytes;
  final player = AudioPlayer();
  bool audioAvailable = false;

  @override
  Widget build(BuildContext context) {
    return pageContainer();
  }

  placeholder() {
    return Container(
      color: Colors.purple.withOpacity(0.5),
      child: const Center(
          child: Text(
        "Pick your image",
        style: TextStyle(color: Colors.white),
      )),
    );
  }

  pageContainer() {
    return Container(
      margin: const EdgeInsets.only(left: 30, top: 100, right: 30, bottom: 50),
      height: double.infinity,
      width: double.infinity,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: const BorderRadius.only(
            topLeft: Radius.circular(10),
            topRight: Radius.circular(10),
            bottomLeft: Radius.circular(10),
            bottomRight: Radius.circular(10)),
        boxShadow: [
          BoxShadow(
            color: Colors.purple.withOpacity(0.5),
            spreadRadius: 3,
            blurRadius: 7,
            offset: const Offset(0, 3), // changes position of shadow
          ),
        ],
      ),
      child: Column(
        children: [
          Expanded(
            child: InkWell(
              child: imageAvailable ? Image.memory(imageBytes) : placeholder(),
              onTap: () async {
                FilePickerResult? result = await FilePicker.platform.pickFiles(
                  type: FileType.custom,
                  allowedExtensions: ['jpg', 'png'],
                );

                if (result != null) {
                  setState(() {
                    imageBytes = result.files[0].bytes!;
                    imageAvailable = true;
                  });

                  // File file = File(result.files.single.path);
                } else {
                  // User canceled the picker
                }
              },
            ),
          ),
          Row(
            children: [
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: ElevatedButton.icon(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: audioAvailable
                          ? Colors.purple
                          : Colors.grey, // This is what you need!
                    ),
                    onPressed: () async {
                      if (audioAvailable) {
                        await player.setAudioSource(JABytesSource(AudioBytes));
                        player.play();
                      }
                    },
                    icon: const Icon(Icons.play_arrow),
                    label: const Text("Play")),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: ElevatedButton.icon(
                    onPressed: () async {
                      FilePickerResult? result =
                          await FilePicker.platform.pickFiles(
                        type: FileType.custom,
                        allowedExtensions: ['mp3', 'wav'],
                      );

                      if (result != null) {
                        setState(() {
                          AudioBytes = result.files[0].bytes!;
                          audioAvailable = true;
                        });

                        // File file = File(result.files.single.path);
                      } else {
                        // User canceled the picker
                      }
                    },
                    icon: const Icon(Icons.file_upload),
                    label: const Text("Pick an audio file")),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: (widget.index > 2)
                    ? ElevatedButton.icon(
                        onPressed: () async {
                          // print("remove is called: ${widget.index}");

                          widget.callback(widget.index.toString());
                        },
                        icon: const Icon(Icons.delete),
                        label: Text("${widget.index}"))
                    : null,
              ),
            ],
          ),
          TextField(
            onChanged: (text) {
              print("THe text is:$text");
              print(pageHolder.ins.pages);
              // pageHolder.ins.pages;
            },
            style: const TextStyle(color: Colors.purple, fontSize: 24),
            decoration: const InputDecoration(
              fillColor: Colors.white,
              filled: true,
              border: OutlineInputBorder(
                  borderRadius: BorderRadius.all(Radius.circular(8))),
              labelText: 'Word or the sentence for the picture',
              labelStyle: TextStyle(
                  color: Colors.purple, fontSize: 24, fontFamily: "sans-serif"),
              floatingLabelStyle: TextStyle(
                  color: Color.fromARGB(255, 191, 116, 204), fontSize: 24),
            ),
          ),
        ],
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}


text:
Q: NGRX Store fires multiple events on dispatch I have an app, which has a firestore in background and an ngrx store for the application data.
I want the store to handle my application data and I want the firestore to provide me observables from my database. In my case a user makes a selection, so it is applicationData for me and is dispatched to the store.
According to the selection that is now in my ngrx store, I want to get an Observable from my firestore. when the selection changes, I want to ask the firestore again for a new Observable. My approach is the following:
my ngOnInit()
ngOnInit(): void {
    this.selectedGroupUid$ = this.store.select(fromApp.advGetSelectedGroupId);

    this.selectedGroup$ = this.selectedGroupUid$.pipe(
      switchMap(gUid => this.groupService.readGroup(gUid))
    );

The Event is fired as the result of a Modal dialog
  onSelectionModal() {
    this.modalRef = this.modalService.open(StartAdventureModalComponent);
    this.modalRef.result.then((data) => {
      this.store.dispatch(GroupActions.selectStartWithGroup(data))
    });
  }

My Problem is, that I dispatch the value once, the store is called once, but the Observable selectedGroupUid$ is fired ~35 times. Meaning I read ~35 times from my database but I only need to read it exactly once on change.
I tried it by debouncing, but this only waits some time and then it executes all ~35 calls to my database.
I do not want to handle this with a subscription, if I can prevent it. When I am searching in the internet I do get a load of answers, but all are not related to my problem of reducing multiple fired results to the last one without subcsribing.

A: Does the selector also get fired that many times?
I think you could use distinctUntilChanged operator to reduce the amount of db calls.
   this.selectedGroup$ = this.selectedGroupUid$.pipe(
      distinctUntilChanged(),
      switchMap(gUid => this.groupService.readGroup(gUid))
    );


text:
Q: CSS: Create looking down *D Shaped* div I have tried my best to use clipPath editors but not able to achieve a shape like this one.
Any help ?

A:

.dshape {
  /* to ensure the starting shape is a square,
     with the inline and block sizing in a
     ratio of 1 to 1: */
  aspect-ratio: 1;
  /* in Latin (left-to-right) languages this
     is equivalent to 'width' ('block-size'
     would be the equivalent of 'height'): */
  inline-size: 10em;
  background-color: red;
  /* using a circular clip path of 80% of
     the element's size, with the clipping
     circle centred at 50% on the inline
     axis, and zero on the block-axis: */
  clip-path: circle(80% at 50% 0);
}

A: is this what you want?
creating a div with 200px/200px Adding border-radius bottom right and bottom left border-radius: 0 0 100% 100%;

.dshape {
  width: 200px;
  height: 200px;
  background-color: red;
  border-radius: 0 0 100% 100%;
}


text:
Q: Visual C++ Runtime Distributable 2010 in Visual Studio 2012 I need to be able to distribute Visual C++ Runtime Distributables 2010 in Visual Studio 2012 using ClickOnce.  How do I get the 2010 C++ bootstrapper to appear in the VS 2012 Prerequisites? The 2012 bootstrapper is already there.  Can I have both?

A: You can accomplish this by hacking your project file and copying some files. The example below is for using the Visual C++ 2012 Runtime libraries in Visual Studio 2013. You will have to change some version numbers if you are using a different version of Visual Studio or want a different version of the Visual C++ Runtime libraries.
First add the following to your project file:
<ItemGroup>
  <BootstrapperPackage Include="Microsoft.Visual.C++.11.0.x64">
    <Visible>False</Visible>
    <ProductName>Visual C++ 2012 Runtime Libraries %28x64%29</ProductName>
    <Install>true</Install>
  </BootstrapperPackage>
</ItemGroup>

The example above is for the 64-bit version of the Visual C++ 2012 Runtime Libraries. If you want to use the 32-bit version you should replace x64 with x86. And if you want to use a different version of the C++ library you will have to change the 11.0 version number. If you open your project at this point and go to the prerequisites you will notice a warning that Visual Studio 2013 cannot find the Visual C++ Runtime Libraries. To fix this you will need to copy some files.

*

*Go to the following folder: C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\Bootstrapper\Packages. If you want a different version of the C++ Runtime Libraries you should change the v8.0a version number.

*Copy the folder vcredist_x86 to the folder that Visual Studio 2013 uses: C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\Bootstrapper\Packages. Make sure you use a different name to avoid overwriting the 2013 libraries. I used vcredist_x64.2012.

At this point you can open your solution and publish your solution. When users install your application they will be asked to also install the C++ Runtime libraries. If your users already installed the application they will need to reinstall otherwise they won't get the question to install the C++ Runtime libraries.
It might be possible that you don't have the C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\Bootstrapper\Packages folder on your system. I think you only get this folder when you install Visual Studio 2012 besides Visual Studio 2013. Feel free to edit this question if you know where you can just download the files without having to install Visual Studio 2012.


text:
Q: how to get return value of promise Here is a function to find mx records of a service and i need to save the one value(with the lowest priority) to make a request to it. How can I save and return this value?
const dns = require('dns');
const email = '...@gmail.com'
let res = email.split('@').pop();

function getMxRecords(domain) {
  return new Promise(function(resolve, reject) {
    dns.resolveMx(domain, function(err, addresses) {
      if (err) {
        //console.log(err, err.stack)
        resolve(null);
      } else {
        //console.log(addresses);
        let copy = [...addresses];
        //console.log(copy);
        let theone = copy.reduce((previous, current) => {
          if (previous.priority < current.priority) {
            return current;
          }
          return previous;
        });
        resolve(theone);
      }
    });
  });
}

let a = getMxRecords(res);
console.log(a);

Yeah, so i need to export this module to make a request to it like below;
let socket = net.createConnection(25, request(email), () => {})

so for this my function should request me or array or object with only one value, when i'm trying it doesn't work, i always get this:
Promise {  } //HERE IS RETURN FROM MY FUNCTION (WITH .THEN)
Error in socket connect ECONNREFUSED 127.0.0.1:25

A: A Promise is mostly an asynchronous call. It returns an Promise-Object that will resolve or reject the Promise. To access the result, you will call some functions:
function getMxRecords(domain) {
  return new Promise(function(resolve, reject) {
    dns.resolveMx(domain, function(err, addresses) {
      if (err) {
        //console.log(err, err.stack)
        resolve(null);
      } else {
        //console.log(addresses);
        let copy = [...addresses];
        //console.log(copy);
        let theone = copy.reduce((previous, current) => {
          if (previous.priority < current.priority) {
            return current;
          }
          return previous;
        });
        resolve(theone);
      }
    });
  });
}

getMxRecords(res)
  .then(yourResolveValueProvided => {
    // Your code if the promise succeeded
  })
  .catch(error => {
    // Your code if the promises reject() were called. error would be the provided parameter.
  })


text:
Q: How do I make one event listener to multiple text fields in Java Swing? I have a shell with several Text Widgets.
Each one corresponds to a different String object which saves its input for later processing (after the widget itself is disposed).
I'm using a ModifyListener to update the string each time the text changes, as seen in this simple example:
    String clientNametext = "";
    Text clientName = new Text(composite, SWT.BORDER);
    clientName.addModifyListener(new ModifyListener() {

        @Override
        public void modifyText(ModifyEvent paramModifyEvent)
        {
            clientNametext = clientName.getText();

        }
    });

However, I have many such Text fields and I would like to clean up the code, and - instead of attaching a new inner class listener per field - create a single ModifyListener, which will then be attached to all of them, and modify the correct variable according to which field change triggered the event.
The issue is, the ModifyEvent itself doesn't seem to hold such information, or any way to uniquely identify which text field changed.
EDIT: It is very important for me to have only one Listener which handles all cases, if possible.
Answers with "use other types of fields and listening objects" are welcome, in case ModifyEvent cannot uniquely identify the exact widget where it occurred, without using some crazy logic with mapping Object IDs or whatnot.

A: Wrap the entire behavior in a single class.
Right now you have a bunch of pairs of String and Text objects. Roll them all into one class:
public class ListeningText {
  private String clientNametext = "";
  private final Text clientName = new Text(composite, SWT.BORDER);

  public ListeningText() {
    clientName.addModifyListener(new ModifyListener() {
      @Override
      public void modifyText(ModifyEvent paramModifyEvent)
      {
        clientNametext = clientName.getText();
      }
    });
  }

  public Text getText() {
    return Text;
  }

  public String getValue() {
    return value;
  }
}

Then, use it like this. You only create one field item, a ListeningText, instead of two, a String and a Text. You would use it like this:
public class YourComponent {
  ListeningText text;
  ListeningText anotherText;
  // etc.

  public void initComponents() {
    // add them like this:
    text = new ListeningText();
    container.add(text.getComponent());
  }

  public void doSomething() {
    // get the value like this:
    System.out.println(text.getValue()); // or whatever
  }
}

Note that this solution doesn't create a "single" ModifyListener, but I think what you wanted was to prevent code duplication, you don't care that there are still many such objects. It would be much harder to only have one object, and then write it to update the corresponding field; this way should accomplish the clean code goal without really complicated code.


text:
Q: How can I get the a tag inside a li using selenium im coding a program to pull data from sites to ease my job at my company I need to get the contents of all "a" tags inside "li" tags ive tried it by finding all elements by their xpath but it yielded no result here's my code and output:
def getLinks(link):
    driver.get(link)
    for i in range(0,10):
        result = driver.find_elements_by_xpath(f"/html/body/div[3]/div/div[1]/div[2]/div[3]/ul/li[{i}]/a")
        for r in result:
            print(r.text)
    # for result in results:
    # print(r)

    driver.close()

output should look like:
http://turkosb.com/presmetal-otomotiv.html
    for all li elements

but what I get is:
   Presmetal Otomotiv Yan San. A.Ş.
    Belirtilmemiş
    +90 224 484 30 30

ps: driver.find_elements_by_xpath(f"/html/body/div[3]/div/div[1]/div[2]/div[3]/ul/li[{i}]/a") this code refers to variable xpath's of all a elements inside li elements

A: You want href attribute but trying r.text which return the Text of the Element.
Use get_attribute() to get the href of all a tags.
And try Relative xpath like below. (As per the screen shot)
//ul[@class='box-listing']/li/a

options = driver.find_elements_by_xpath("//ul[@class='box-listing']/li/a") # Xpath to find all the `a` tags.
for option in options:
    print(option.get_attribute("href"))


text:
Q: SharePoint Designer workflow email - multiple line of text field showing blank I have a designer workflow that triggers an email on item creation. However, body of the email should contain one of the field value. This field is of type multiple lines of text, plain text and appends changes checked.
I am receiving an email but it shows blank for multiple lines of text. Can't, we show Multiple lines of text field value in designer email, is it unsupported?
Update : When I disable append changes, it works fine for me. But we need append changes also if I run it manually it works fine. Just not working on Item Added event.
Update 2 Adding pause of 5 min didn't help as well.

A: The reason it doesn't work with 'append changes' is because each comment change is saved as a version of the item - the actual field in the current version is always blank. I supposed there's some way in a 2013 workflow to use the http calls to grab all versions and rebuild the comment, but that would be a lot of work for little gain. Your workaround is the best.

A: It is well supported you can send email that contain richtext field value in body of email.
I have recently done the same thing with the combination you mention above and its working.

A: Try assigning the multiple lines of text field to a string variable in the workflow and use that in the email body instead of the original field.

A: i was able to use this workaround, since my users enter comments via tasks assigned to them:
-disabled 'append changes' in the item comment field
-implemented the append in the workflow (append task comments to
   current item comments)
-i can now include the comments in logs, mails, ... in the workflow

A: I found what Microsoft says about it: Workflow that uses the SharePoint 2013 Workflow Platform Type contains blank values in output from the "Multiple lines of text" column
WORKAROUND
To work around this issue, disable automatic updating of the workflow status to the current stage name. To do this, follow these steps:

*

*Open the affected workflow in Microsoft SharePoint Designer 2013.

*On the Workflow Settings page for the workflow, clear the Automatically update the workflow status to the current stage name check box.

*Save the workflow, and then and publish it to the SharePoint website.

*Run the workflow again.

Notes

*

*When you clear this setting, you may want to use the Set Workflow Status action as part of the workflow to update the Workflow Status field if that appears to be necessary. Otherwise, the status won't be listed.

*You may also want to consider saving the value of the Multiple lines of text column in a workflow variable if you plan to update the list item within the workflow logic.

*In this scenario, the value from the Multiple Lines of text column will be blank if you edit the list item but don't change the Multiple Lines of Text column.


text:
Q: Unclear how to connect Plivo to OpenTok Java SDK SIP I'm trying to use Plivo with the OpenTok Java SDK to dial out. There is an example for javascript where Plivo is used.
I'm able to invoke the method Openok.dial() and get a positive response that I then send to my react client.
There are no errors but I'm not calling the targeted number.
I'm not understanding how to use the uris or if they are still necessary.
So is it still necessary to create the uri's as stated in the JS example (https://github.com/opentok/opentok-sip-samples/tree/master/Plivo-SIP-Dial-Out)? And how do i then use those uri's?
Or is there an example i can peek to get a rough idea?

A: TokBox Developer Evangelist here.
The OpenTok SIP Interconnect feature allows you dial out to a SIP address (uri). With the Plivo sample, you would have to create an application on their website and configure the Plivo application with the appropriate webhooks so when that when you dial out to the Plivo SIP uri from OpenTok, you will get events on the webhook which will allow you to connect the OpenTok session with the PSTN user.
You can also leverage Nexmo or other SIP providers to dial out and connect an OpenTok session with a PSTN user. For example, if you use Nexmo, you can dial directly to a phone number by constructing the SIP properties in the OpenTok Java SDK like so:
String nexmoApiKey = "";
String nexmoApiSecret = "";
String sessionId = "";
String token = "";
SipProperties properties = new SipProperties.Builder()
     .sipUri("sip:15555555555@sip.nexmo.com")
     .from("from@example.com")
     .headersJsonStartingWithXDash(headerJson)
     .userName(nexmoApiKey)
     .password(nexmoApiSecret)
     .secure(false)
     .build();
 Sip sip = opentok.dial(sessionId, token, properties);

Please note that you would have to configure the phoneNumber, sessionId, token, and credentials - I've just added a sample number along with empty strings as the credentials.


text:
Q: c# how to validate windows credentials in a different domain Is there a way to validate windows credentials in a certain domain? I only have the users windows credentials I got with;
CredentialCache.DefaultNetworkCredentials

When I had a password and such I used the below code;
using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "SOME DOMAIN"))
{
   // validate the credentials
   bool isValid = pc.ValidateCredentials("myuser", "mypassword");
}


text:
Q: Cómo adaptar evenBetterBuildUrls() de Mogsdad para importar respuestas a un formulario En https://stackoverflow.com/a/26395487/1595451 por Mogsdad del 2014-11-26 01:27:15Z comparte el código de evenBetterBuildUrls(). Este tiene la finalidad de generar los URLs de prellenado de formularios de Google. Algunas cosas las he podido realizar pero en otras estoy atorado.
La adaptación a realizar es la siguiente:

*

*Obtener las respuestas de una hoja específica en lugar de la hoja predeterminada.

*Incluir respuestas del tipo TIME, DURATION y GRID

*Traducción de los comentarios para facilitar la adopción del mismo por quienes sólo hablan español.

*Agregar instrucciones para usuarios que recien empiezan con Google Apps Script.

Sé que varían los parámetros de cada clase de tipo elemento de respuesta para el método createResponse() correspondiente a cada una y que el nombre de las preguntas del tipo GRID no coincide con el título de la pregunta del formulario.
/**
 * Use Form API to generate pre-filled form URLs
 *
 * https://stackoverflow.com/a/26395487/1677912
 */
function evenBetterBuildUrls() {
  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName("Form Responses 1");
  var data = ss.getDataRange().getValues();  // Data for pre-fill
  var headers = data[0];                     // Sheet headers == form titles (questions)

  var formUrl = ss.getFormUrl();             // Use form attached to sheet
  var form = FormApp.openByUrl(formUrl);
  var items = form.getItems();
  var urlCol = headers.indexOf("Prefilled URL");   // If there is a column labeled this way, we'll update it

  // Skip headers, then build URLs for each row in Sheet1.
  for (var row = 1; row < data.length; row++ ) {
    Logger.log("Generating pre-filled URL from spreadsheet for row="+row);
    // build a response from spreadsheet info.
    var response = form.createResponse();
    for (var i=0; i<items.length; i++) {
      var ques = items[i].getTitle();           // Get text of question for item
      var quesCol = headers.indexOf(ques);      // Get col index that contains this question
      var resp = ques ? data[row][quesCol] : "";
      var type = items[i].getType().toString();
      Logger.log("Question='"+ques+"', resp='"+resp+"' type:"+type);
      // Need to treat every type of answer as its specific type.
      switch (items[i].getType()) {
        case FormApp.ItemType.TEXT:
          var item = items[i].asTextItem();
          break;
        case FormApp.ItemType.PARAGRAPH_TEXT:
          item = items[i].asParagraphTextItem();
          break;
        case FormApp.ItemType.LIST:
          item = items[i].asListItem();
          break;
        case FormApp.ItemType.MULTIPLE_CHOICE:
          item = items[i].asMultipleChoiceItem();
          break;
        case FormApp.ItemType.CHECKBOX:
          item = items[i].asCheckboxItem();
          // In a form submission event, resp is an array, containing CSV strings. Join into 1 string.
          // In spreadsheet, just CSV string. Convert to array of separate choices, ready for createResponse().
          if (typeof resp !== 'string')
            resp = resp.join(',');      // Convert array to CSV
          resp = resp.split(/ *, */);   // Convert CSV to array
          break;
        case FormApp.ItemType.DATE:
          item = items[i].asDateItem();
          resp = new Date( resp );
          break;
        case FormApp.ItemType.DATETIME:
          item = items[i].asDateTimeItem();
          resp = new Date( resp );
          break;
        default:
          item = null;  // Not handling DURATION, GRID, IMAGE, PAGE_BREAK, SCALE, SECTION_HEADER, TIME
          break;
      }
      // Add this answer to our pre-filled URL
      if (item) {
        var respItem = item.createResponse(resp);
        response.withItemResponse(respItem);
      }
      // else if we have any other type of response, we'll skip it
      else Logger.log("Skipping i="+i+", question="+ques+" type:"+type);
    }
    // Generate the pre-filled URL for this row
    var editResponseUrl = response.toPrefilledUrl();
    // If there is a "Prefilled URL" column, update it
    if (urlCol >= 0) {
      var urlRange = sheet.getRange(row+1,urlCol+1).setValue(editResponseUrl);
    }
  }
};

Referencias
Ejemplos de preguntas que podrían beneficiarse de esta adaptación
Como asociar resultados de una hoja a un formulario de google - Foro de Ayuda de Google Drive

A: Respuesta parcial

*

*Obtener las respuestas de una hoja específica en lugar de la hoja predeterminada.

Dado que en la línea 8 se especifica la el nombre de la hoja con las repuestas, cambiar la línea 9
var data = ss.getDataRange().getValues();  // Data for pre-fill

por
var data = sheet.getDataRange().getValues();  // Data for pre-fill

donde sheet es la hoja de la que deseamos obtener los datos.

*Incluir respuestas del tipo TIME, DURATION y GRID

En relación a TIME y Duration véase Cómo leer valores de hora correctamente en una hoja de cálculo de Google


text:
Q: How to download a github release by code, not by a CLI I am making a bot that can grab a source.zip / source.targz from Github, then implement it into my app and new changes are applied, but I have not found a way to download a release because the @Octokit/Rest module I'm using only gets the release. Not download. Other npm packages don't work for me and if so, the node_modules folder can get really big, around 19mb. When I do a https GET request, Github requires me to use a USERAGENT, but I don't know how to tie in Octokit with plain HTTPS requests.
I want to be able to download releases by code, but what I get is the following in the zipfile I tie it to:

Request forbidden by administrative rules. Please make sure your request has a User-Agent header (http://developer.github.com/v3/#user-agent-required). Check https://developer.github.com for other possible causes.

    var file = fs.createWriteStream('bot.zip')
    var request = await https.get(releases[num].zipball_url, function(response) {
        response.pipe(file)
    })

//https://stackoverflow.com/questions/11944932/how-to-download-a-file-with-node-js-without-using-third-party-libraries

var octokit = new Octokit.Octokit({
        userAgent: 'Github Bot Updater',
        previews: ['jean-grey', 'symmetra'],
        baseUrl: 'https://api.github.com',
        log: {
            debug: () => {},
            info: () => {},
            warn: console.warn,
            error: console.error
          },
          request: {
            agent: undefined,
            fetch: undefined,
            timeout: 0
          }
    })
    var releases = await octokit.paginate("GET /repos/:owner/:repo/releases", {  owner: username,  repo: reponame})
//octokit has no method for downloading a release

A: What I did was instead of getting the zipball from the release, you can also get the same thing from going to the main repo page, then going to the branches button in the corner, going to tags and the desired release tag. Then after you click on that you can download that release. When I looked into that, instead of doing
releases[num].zipball_url in
    var request = await https.get(releases[num].zipball_url, function(response) {
        response.pipe(file)
    })

You can do
https://codeload.github.com/${username}/${reponame}/zip/${releases[num].tag_name}
And that works.


text:
Q: I used this as a code to play a video in android studio but it says "Can't play this video" I used this as a code to play a video in android studio but it says "Can't play this video". What should i do ?
    VideoView videoView = (VideoView) findViewById(R.id.videoView);
    videoView.setVideoPath("android.resourse://"+ getPackageName()+ "/" +R.raw.video);
    videoView.start();
    MediaController mediaController = new MediaController(this);
    mediaController.setAnchorView(videoView);
    videoView.setMediaController((mediaController));
    videoView.start();


text:
Q: How to implement collecting nodes according the logic I am struggeling with xslt the last couple of weeks with a task I should implement since I have a lack an experience in xslt programming I appreciate every help I could get in solving my task, I have alredy asked a couple of questions about this task but still I have not it solved completely.
My task is to implement such code with style sheet on the basis of html data structure.

Furthermore I add mine html file:

example_2

            global_structure in a code_1

            global_structure in a code_2

            name of the file

            skip
            text_var
            text
            funktion
            A1

            skip

            funktion
            A2

            skip

            var
            A2_var

            skip

            funktion
            A3

            skip

            var
            A3_var1

            skip

            var
            A3_var2

            name of the file_2

            skip
            text_var
            text
            funktion
            A1

            skip

            funktion
            A2

            skip

            var
            A2_var

            skip

            funktion
            A3

            skip

            var
            A3_var1

            skip

            var
            A3_var2

            end

For example file with file name: "name of the file" should have the following code
global_structure in a code_1(){
text;
};

global_structure in a code_2(){
A1();
A2(A2_var);
A3(A3_var1,A3_var2);
};

The idea is that if  the parser face any "var" it should insert it into "function". If after funktion no vars are showed funktion should be inserted without any variables.
I have problems with that I have already asked I question how to calculate the number of rows which are between the files (skip-sequences). But I cannot undertand how can I use this function for any recursive function because it gives me two numbers as they are. Now for each iteration of my structure. Please give me any advices how to implement it. I am very new at xslt:)
Here is my link to code:
https://xsltfiddle.liberty-development.net/bwe3c5/54
 <xsl:template match="/html/body/table">

   <xsl:param name ="counter_var" select="mf:skip-sequences(.)" />

   <xsl:for-each select="./tr">
       <xsl:if test = "not(child::td[1] ='skip') or not(string(child::td[1]))">
           <xsl:variable name ="new_file_name" select="child::td[1]" />

             <xsl:value-of select="child::td[1]"/>
             <xsl:text>
</xsl:text>
       </xsl:if>
   </xsl:for-each>

   <xsl:for-each select="./tr[1]/td">

       <xsl:choose>
       <xsl:when test="position() mod 2=0">
           <xsl:call-template name="filtering_a_position">
           <xsl:with-param name="position" select="position()">
           </xsl:with-param>
           </xsl:call-template>
       </xsl:when>
     </xsl:choose>
     </xsl:for-each>
   </xsl:template>

    <xsl:template name="filtering_a_position">

    <xsl:param name="position"/>
    <xsl:text>
xsl:value-of select="../td[$position]"
</xsl:text>
    <xsl:value-of select="../td[$position]"/>
    <xsl:text>
</xsl:text>
    <xsl:for-each select="/html/body/table/tr/td[$position+1]">
    <xsl:value-of select="current()"/> <xsl:text>
</xsl:text>
    </xsl:for-each>

    </xsl:template>

<xsl:function name="mf:skip-sequences" as="xs:integer*">
     <xsl:param name="table" as="element(table)"/>
     <xsl:for-each-group select="$table/tr" group-adjacent="boolean(self::tr[td[1] = 'skip'])">
         <xsl:sequence select="count(current-group())[current-grouping-key()]"/>
     </xsl:for-each-group>
 </xsl:function>

 <xsl:template match="table">
     <xsl:sequence select="mf:skip-sequences(.)"/>
 </xsl:template>

</xsl:stylesheet>

A: This is quite a complex problem, and certainly will take more than the five minutes I usually allow myself for a StackOverflow answer. But it feels very much to me like the kind of problem that will benefit from a multi-phase approach: that is, divide it up into a series of transformations, each of which is relatively simple.
I would start by defining an intermediate representation of the data that reflects its logical structure. This might look something like this:
<files>
  <file name="file1">
    <structure in="code1">
      <entry type="text_var" name="text"/>
    </structure>
    <structure in="code2">
      <entry type="funktion" name="A1"/>
      <entry type="funktion" name="A2"/>
      <entry type="var" name="A2_var"/>
      ... etc ...

(I might have got this wrong; I don't claim to understand your data or its true structure).
The first stage of the transformation (to get to this structure from your initial input) can be done using <xsl:for-each-group select="tr" group-starting-with="tr[td[1] ne 'skip']">.
The second stage also involves positional grouping, this time something like <xsl:for-each-group select="entry" group-starting-with="entry[@type='funktion'">.
I know this is only a sketch of an approach to a solution, but I hope it takes you forward.


text:
Q: Convert \x3c/div\x3e to  using perl I have a string which has characters like \x3c/div\x3e , i am trying to convert this to <div> is there any module which helps to solve this issue. I have checked use HTML::Entities but couldn't solve the issue, i am in need of some suggestion.

A: One method:
my $str = '\x3c/div\x3e';

$str =~ s{\\x([[:xdigit:]]{2})}{chr hex $1}eg;

print $str;

Outputs
<div>


text:
Q: Wildcards on query for AWS cli for elbv2 I'm trying to get the ARN of some LoadBalancer which I only know the prefix of the DNS name.
As an example, aws elbv2 describe-load-balancers --query 'LoadBalancers[].DNSName[]' will print me:
[
    "services-green-********.elb.eu-central-1.amazonaws.com",
    "services-blue-********.elb.eu-central-1.amazonaws.com"
]

Something like
aws elbv2 describe-load-balancers --query "LoadBalancers[?DNSName=='services-green-*']"

is not working because wildcards are not accepted and using filters like at ec2 commands is not possible.
How can I get the ARN without falling back to using jq?

A: You may try this;
aws elbv2 describe-load-balancers --query 'LoadBalancers[?contains(DNSName, `services-green-*`) == `true`][DNSName]'

You may remove the last [DNSName] if you want the full response. Or replace with DNSName with LoadBalancerArn;
aws elbv2 describe-load-balancers --query 'LoadBalancers[?contains(DNSName, `services-green-*`) == `true`][LoadBalancerArn]'

Just like contains, you can try starts_with if you don't want full wildcard but know how it starts.


text:
Q: Editing element in wordpress causes multiple elements to change also? Sorry if this makes no sense as am only just getting to grips with WordPress and editing CSS.
I have a calendar plugin which for the most part is pretty standard.
However, I wish to make a minimum height for the elements so if there isn't much text, the format still looks better.
Following tutorials, I am able to inspect the source, make the change, and have the desired effect. My issue is, that if I find the element, it seems the custom CSS makes changes to multiple elements on the screen, I can work round most of this but it effectively breaks a clickable link (Makes it not cover the whole button).
The element part I edit is quite large but here is a chunk of it:
.tribe-common abbr, .tribe-common acronym, .tribe-common address, .tribe-common applet, .tribe-common article,
There's about 50, so I'm guessing my edit is covering too much or that I'm editing an attribute that more than one element inherits?
The only attribute I am setting is min-height, so unsure why this seems to make the clickable button area smaller? The button itself stays the same, but I can only click it right at the top.
The plugin I am using is a free one called events calendar. And for the most part I am able to edit the way I've described, I am just struggling to get this one to work and thought it might be the giant list that's causing it. Or should I say my lack of knowledge
Thanks

A: I am not sure if i get the issue you are describing correctly, but if your changes in css apply to some elements that you don't want them to apply, then you are not precise enough with your selector.
For example, the element you mentioned in your text contains many commas (","), which select all elements separated with comma. This makes your selection wider, not narrowing it down.
If you are not familiar with syntax of CSS selectors, i recommend checking out this resource:
https://www.w3schools.com/cssref/css_selectors.asp


text:
Q: How to sequence a recursive callback in Javascript? I need to execute 3 ajax requests. I know that they happen to be asynchronous by default (And making them synchronous messes up the VM, so I don't want to go that way.) The way I do it is by calling a function three times passing variables.
result = '';
parse(var1);
parse(var2);
parse(var3);
view();

function parse(variable) {
    //ajax request here
    $.ajax({
        type: 'POST',
        url: 'script.php',
        data: {variable: variable},
        success: function (data) {
            //result stored in a global variable
            result += data;
        }
    });
}
function view() {
    //do something with result
}

But right now, the view() is triggered right away when the result isn't done cooking. How do I set them up to happen one after the other? I read about callbacks but they are very confusing since I don't have 3 distinct functions but just one taking different variables.

A: You could store your variables in an array and use a function to make your ajax call:
var variables = [var1, var2, var3];

function callParse() {
  if(variables.length) {
    var currentVar = variables.shift();
    parse(currentVar);
  }
  else {
    view();
  }
}

function parse(variable){
  //ajax request here
  $.ajax({
    type:"POST",
    url:'script.php',
    data:{variable:variable},
    success:function(data)
    {
      result+=data;
      callParse();
    }
  });
}

function view(){
//do something with result
}

A: Try chained promises - from: https://css-tricks.com/multiple-simultaneous-ajax-requests-one-callback-jquery/
$.when(
  // Get the HTML
  $.get("/feature/", function(html) {
    globalStore.html = html;
  }),

  // Get the CSS
  $.get("/assets/feature.css", function(css) {
    globalStore.css = css;
  }),

  // Get the JS
  $.getScript("/assets/feature.js")

).then(function() {

  // All is ready now, so...

  // Add CSS to page
  $("<style />").html(globalStore.css).appendTo("head");

  // Add HTML to page
  $("body").append(globalStore.html);

});

A: You could try doing it this way:
parseAndView([var1, var2, var3]);

function parseAndView(vars, index) {
    index = index || 0; //initialize index if not passed

    //execute the AJAX call only if there are more variables to parse
    if (index < vars.length)
        //ajax request here
        $.ajax({
            type: "POST",
            url: 'script.php',
            data: {variable: vars[index]},
            success: function (data) {
                // result stored in a global variable
                result += data;
                // recursive call to parse another variable
                parseAndView(vars, index++);
            }
        });
    else
        view();
}

function view() {
  //do something with result
}


text:
Q: Use of image multiple image button I am new to android i am creating an application in which i have a layout which has three image button i want that when ever each button is clicked it play its own sound not the same sound is repeated for every image.
Another thing when i click an image button it produce sound if i want to pause it so it pause and on clicking again it start from where i pause.
Another thing when i click an image button it produce sound if i want to pause it so it pause and when i click another image button the new sound start which is set on that image.
XML CODE
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/ScrollView01"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true"
        android:scrollbars="horizontal|none"
        tools:ignore="HardcodedText,ContentDescription" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="640dp"
        android:background="@drawable/main"
        tools:context=".Tanween" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:text="It means"
            android:textAppearance="?android:attr/textAppearanceLarge"
            tools:ignore="RtlHardcoded" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/textView1"
            android:layout_below="@+id/textView1"
            android:text="1. Tanween-Fathatain"
            android:textAppearance="?android:attr/textAppearanceLarge"
            tools:ignore="RtlHardcoded" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/textView2"
            android:layout_below="@+id/textView2"
            android:text="The sound"
            android:textAppearance="?android:attr/textAppearanceLarge"
            tools:ignore="RtlHardcoded" />

        <ImageButton
            android:id="@+id/imageButton24"
            android:layout_width="120sp"
            android:layout_height="60sp"
            android:src="@drawable/ta1"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/textView3"
            android:layout_marginLeft="162dp"
            android:layout_marginStart="162dp"
            android:layout_marginTop="8dp"
             />

        <TextView
            android:id="@+id/textView38"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/imageButton24"
            android:layout_marginTop="10dp"
            android:text="2.Tanween-Kasratain"
            android:textSize="22sp"/>

        <TextView
            android:id="@+id/textView39"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/textView38"
            android:textSize="22sp"
            android:text="The sound" />

        <ImageButton
            android:id="@+id/imageButton28"
            android:layout_width="110sp"
            android:layout_height="65sp"
            android:layout_alignLeft="@+id/imageButton24"
            android:layout_alignStart="@+id/imageButton24"
            android:layout_below="@+id/textView39"
            android:layout_marginLeft="6dp"
            android:layout_marginStart="6dp"
            android:layout_marginTop="6dp"
            android:src="@drawable/ta2" />

        <TextView
            android:id="@+id/textView40"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/imageButton28"
            android:layout_marginTop="8dp"
            android:text="3.Tanween-Dammatain"
            android:textSize="22sp"/>

        <TextView
            android:id="@+id/textView41"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/textView40"
            android:text="The sound"
            android:textSize="22sp"/>

        <ImageButton
            android:id="@+id/imageButton29"
            android:layout_width="180sp"
            android:layout_height="60sp"
            android:src="@drawable/ta3"
            android:layout_below="@+id/textView41"
            android:layout_alignLeft="@+id/imageButton28"
            android:layout_alignStart="@+id/imageButton28" />
    </RelativeLayout>
 </ScrollView>

JAVA Code
package com.example.tajweedapp;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;

public class Tanween extends Activity {

    MediaPlayer mp = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tanween);

        mp= MediaPlayer.create(Tanween.this,R.raw.sound1);
        ImageButton b=(ImageButton) findViewById(R.id.imageButton24);

        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View V) {

                if(mp.isPlaying()){
                    mp.pause();
                }else
                {
                    mp.start();
                }
            }
        });

        mp= MediaPlayer.create(Tanween.this,R.raw.sound2);
        ImageButton a=(ImageButton) findViewById(R.id.imageButton28);

        a.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View V) {

                if(mp.isPlaying()){
                    mp.pause();
                }else
                {
                    mp.start();

                }
            }
        });

        mp= MediaPlayer.create(Tanween.this,R.raw.sound);
        ImageButton c=(ImageButton) findViewById(R.id.imageButton29);

        c.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View V) {

                if(mp.isPlaying()){
                mp.pause();
                }else
                {
                    mp.start();
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.tanween, menu);
        return true;
    }
    public void onPause(){
        super.onPause();
        mp.stop();
        mp.release();

    }

}

A: I didn't try the code myself but I think you can fix this by just using moving this mp= MediaPlayer.create(Tanween.this,R.raw.sound); code inside its corresponding button onClick listener.
b.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View V) {

                mp= MediaPlayer.create(Tanween.this,R.raw.sound1);

                    if(mp.isPlaying()){
                        mp.pause();
                    }else
                    {
                        mp.start();
                    }
                }
            });

            ImageButton a=(ImageButton) findViewById(R.id.imageButton28);

            a.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View V) {
            mp= MediaPlayer.create(Tanween.this,R.raw.sound2);

                    if(mp.isPlaying()){
                        mp.pause();
                    }else
                    {
                        mp.start();

                    }
                }
            });

            ImageButton c=(ImageButton) findViewById(R.id.imageButton29);

            c.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View V) {

            mp= MediaPlayer.create(Tanween.this,R.raw.sound);

                    if(mp.isPlaying()){
                    mp.pause();
                    }else
                    {
                        mp.start();
                    }
                }
            });


text:
Q: SmtpClient.SendMailAsync causes deadlock when throwing a specific exception I'm trying to set up email confirmation for an ASP.NET MVC5 website, based on the example AccountController from the VS2013 project template. I've implemented the IIdentityMessageService using SmtpClient, trying to keep it as simple as possible:
public class EmailService : IIdentityMessageService
{
    public async Task SendAsync(IdentityMessage message)
    {
        using(var client = new SmtpClient())
        {
            var mailMessage = new MailMessage("some.guy@company.com", message.Destination, message.Subject, message.Body);
            await client.SendMailAsync(mailMessage);
        }
    }
}

The controller code that is calling it is straight from the template (extracted into a separate action since I wanted to exclude other possible causes):
public async Task<ActionResult> TestAsyncEmail()
{
    Guid userId = User.Identity.GetUserId();

    string code = await UserManager.GenerateEmailConfirmationTokenAsync(userId);
    var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = userId, code = code }, protocol: Request.Url.Scheme);
    await UserManager.SendEmailAsync(userId, "Confirm your account", "Please confirm your account by clicking here");

    return View();
}

However I'm getting odd behavior when the mail fails to send, but only in one specific instance, when the host is somehow unreachable. Example config:
<system.net>
    <mailSettings>
        <smtp deliveryMethod="Network">
            <network host="unreachablehost" defaultCredentials="true" port="25" />
        </smtp>
    </mailSettings>
</system.net>

In that case, the request appears to deadlock, never returning anything to the client. If the mail fails to send for any other reason (e.g. host actively refuses connection) the exception is handled normally and I get a YSOD.
Looking at the Windows event logs, it seems that an InvalidOperationException is thrown around the same timeframe, with the message "An asynchronous module or handler completed while an asynchronous operation was still pending."; I get that same message in a YSOD if I try to catch the SmtpException in the controller and return a ViewResult in the catch block. So I figure the await-ed operation fails to complete in either case.
As far as I can tell, I am following all the async/await best practices as outlined in other posts on SO (e.g. HttpClient.GetAsync(...) never returns when using await/async), mainly "using async/await all the way up". I've also tried using ConfigureAwait(false), with no change. Since the code deadlocks only if a specific exception is thrown, I figure the general pattern is correct for most cases, but something is happening internally that makes it incorrect in that case; but since I'm pretty new to concurrent programming, I've a feeling I could be wrong.
Is there something I'm doing wrong ? I can always use a synchronous call (ie. SmtpClient.Send()) in the SendAsync method, but it feels like this should work as is.

A: Try this implementation, just use client.SendMailExAsync instead of client.SendMailAsync. Let us know if it makes any difference:
public static class SendMailEx
{
    public static Task SendMailExAsync(
        this System.Net.Mail.SmtpClient @this,
        System.Net.Mail.MailMessage message,
        CancellationToken token = default(CancellationToken))
    {
        // use Task.Run to negate SynchronizationContext
        return Task.Run(() => SendMailExImplAsync(@this, message, token));
    }

    private static async Task SendMailExImplAsync(
        System.Net.Mail.SmtpClient client,
        System.Net.Mail.MailMessage message,
        CancellationToken token)
    {
        token.ThrowIfCancellationRequested();

        var tcs = new TaskCompletionSource<bool>();
        System.Net.Mail.SendCompletedEventHandler handler = null;
        Action unsubscribe = () => client.SendCompleted -= handler;

        handler = async (s, e) =>
        {
            unsubscribe();

            // a hack to complete the handler asynchronously
            await Task.Yield();

            if (e.UserState != tcs)
                tcs.TrySetException(new InvalidOperationException("Unexpected UserState"));
            else if (e.Cancelled)
                tcs.TrySetCanceled();
            else if (e.Error != null)
                tcs.TrySetException(e.Error);
            else
                tcs.TrySetResult(true);
        };

        client.SendCompleted += handler;
        try
        {
            client.SendAsync(message, tcs);
            using (token.Register(() => client.SendAsyncCancel(), useSynchronizationContext: false))
            {
                await tcs.Task;
            }
        }
        finally
        {
            unsubscribe();
        }
    }
}


text:
Q: Sequence empty right after setting \documentclass{article}
\usepackage{expl3,xparse}
\ExplSyntaxOn
\ProvideDocumentCommand \Union { O{\cup} O{,} m }
{
  \typeout{#3}
  \seq_set_split:Nnn \l_lmpa_seq { #2 } { #3 }
  \seq_show:N \l_tmpa_seq
  \seq_use:Nn \l_tmpa_seq { #1 }
}

\begin{document}
$\Union{a,b,c}$
\end{document}

gives in the console
a,b,c
The sequence \l_tmpa_seq is empty
> .
<recently read> }

l.13 $\Union{a,b,c}
                   $

with no (visible) printed output.  I can't for the life of me figure out what is going awry.  I've also tried the analogous clist implementation to no avail…


text:
Q: Exchange mail flow rules for signatures I've recently implemented an html signature using transport rules in exchange 2013, that appends given signature as a disclaimer to all emails from a given sender domain.
The problem is that the signature gets appended at the bottom of the entire email, including emails being replied to. Instead I would like the signature to appear only under each message sent.
The situation now:
email reply i sent
original email i received and am replying to
my signature
instead i want it to be:
email reply i sent
my signature
original email i received and am replying to
How do i do this, or are there any other better ways to do this?

A: This is not possible using Exchange transport rules. You will need a third party product.
I use Exclaimer Signature Manager (manages Outlook signatures) and Exclaimer Mail Disclaimers (adds signatures at the transport level). I highly recommend them both.


text:
Q: How can I load a sound by input value using javascript? In the first, I use Firefox. I have code for a HTML spectrum, but I can't load sound from a textbox using input's id and javascript.
This is input:
<input type="text" id="song" value="first.mp3"></input>
And this is a part of javascript's code, the other part is for making spectrum:
var song = document.getElementById('song').value;
loadSound(song.value);

If I use directly values without input, for example loadSound("first.mp3");, code work, sound is loaded and it starts to play.
This is my full code, but doesn't run on jsfiddle.net because there is no sound for import: https://jsfiddle.net/77js54b4/.
But how can I make a load sound from input textbox?

A: It looks like you're using value twice in your example...
var song = document.getElementById('song').value;
loadSound(song.value);
If document.getElementById('song').value = "song.mp3", then loadSound(song); should work according to what you mentioned.


text:
Q: Is it possible to stream Cloud Build logs with the Node.js library? Some context: Our Cloud Build process relies on manual triggers and about 8 substitutions to customize deploys to various firebase projects, hosting sites, and preview channels. Previously we used a bash script and gcloud to automate the selection of these substitution options, the "updating" of the trigger (via gcloud beta builds triggers import: our needs require us to use a single trigger, it's a long story), and the "running" of the trigger.
This bash script was hard to work with and improve, and through the import-run shenanigans actually led to some faulty deploys that caused all kinds of chaos: not great.
However, recently I found a way to pass substitution variables as part of a manual trigger operation using the Node.js library for Cloud Build (runTrigger with subs passed as part of the request)!
Problem: So I'm converting our build utility to Node, which is great, but as far as I can tell there isn't a native way to steam build logs from a running build in the console (except maybe with exec, but that feels hacky).
Am I missing something? Or should I be looking at one of the logging libraries?
I've tried my best scanning Google's docs and APIs (Cloud Build REST, the Node client library, etc.) but to no avail.


text:
Q: What is the actual ASCII value of the FNC1 character in GS1 barcodes? I have searched many a page on wikipedia, the official GS1 specifications, but have yet to find a definite answer to the question
What is the actual HEX / binary value of the GS1 FNC1 character?
There is much information about how to use the GS1 identifiers, how to print the barcodes with ZPL and how to encode the FNC1, but I want to know the actual HEX value of that character.

A: The special function characters such as FNC1 through FNC4 belong to the class of "non-data characters" that can be encoded within various barcode symbologies but with do not have any direct ASCII representation in the decoded data stream. Each symbology that supports such characters has a different scheme for encoding them in its internal representation quite distinct from any byte-orientated character data.
The FNC characters serve both as flag characters (indicating something special to the reader) and as formatting characters (modifying the meaning of the encoded data). As such they are not intended to be transmitted directly in the data received by the host system from a basic barcode reader, although in both cases they may have an "effect" on the transmitted message.
The usual purpose of each of the FNC characters are as follows:

*

*FNC1 - Structured Data flag character indicating GS1 and AIM formatting AND group separator formatting character, amongst other uses.

*FNC2 - Message Append flag character for buffering the data in groups of symbols for a single read.

*FNC3 - Reader Programming flag character for device configuration purposes.

*FNC4 - Extended ASCII formatting character for encoding characters with ordinals 128-255.

Be aware that they may not all be available in certain barcode symbologies and may even be specified in different, non-typical or overloaded ways.
Encoding an FNC character in a symbol's internal data is accomplished via an "escape mechanism" that is specific to the encoding software. Each library has a different way of accepting these non-data characters within their input. For example, to use FNC1 in its typical GS1 structured data role for the data "(01)00312345678906(21)123456789012(30)0144" you might see the FNC1 characters escaped as {FNC1} so that the input looks like {FNC1}010031234567890621123456789012{FNC1}300144.
Some libraries will even use a set of regular or extended ASCII characters as placeholders for the FNC characters, but these are arbitrary representations and it is a mistake to consider them to be actual ASCII values for these non-data characters.
Upon scanning a barcode the symbol's internal data is typically decoded then transmitted to the host over a basic channel (e.g. keyboard wedge) as a sequence of bytes to be interpreted according to the Latin-1 character encoding. The FNC characters cannot be represented in such a manner and are excluded from the data stream, however their formatting effect on the data remains.
For instance, the standards for most symbologies specify that when an FNC1 character is being used in its role as a field separator in data conforming to GS1 Application Identifier Standard Format it should be decoded and transmitted as GS (ASCII 29). Explicitly stated, the formatting effect of a FNC1 character used as a GS1 Application Identifier separator is to place a GS character at the end of the variable-length field. But in other roles (such as when FNC1 is used in "first/second position" as a flag character and with non-GS1 formatted data) there is no formatting effect on the carried data and therefore no ASCII representation during decoding.
Another instance of the special function characters having a formatting effect on the data is with symbologies that use FNC4 to extend their reach from 7-bit ASCII into extended ASCII as described in this answer.
A subtle technical point is that the data transferred to the host is often prefixed with a short symbol indicator header known as a "symbology identifier" which denotes the type and usage of the symbol from which the data is being read. This is often modified by the presence of otherwise invisible flag characters within the symbol data, for example to indicate the presence of GS1 formatted data with "FNC1 in first" or to indicate reader programming mode when FNC3 appears anywhere in the symbol. The details are symbology specific.
Aside: In addition to FNC non-data characters, there are other non-data characters commonly supported by barcode symbologies that have no direct ASCII representation but affect the overall message. These include macro characters (that wrap the message data in an "envelope"), and ECI indicators that require the use of a transmission protocol beyond the typical "basic channel" mode but which enable the use of extended character sets amongst other enhancements.

A: Important is to know (and to setup a scanner properly) that the FNC1 character at the first position is translated to a symbology identifier according ISO/IEC 15424. The modifier m of the symbology identifier shows if there was a FNC1 or not. If this is not done the application cannot see anymore if a GS1 Structure was intended or not. Other structures are identified by e.g. Macro 06 in a data matrix code (ISO/IEC 16022, ISO/IEC 15434). Its required to figure our the difference to take the correct action to process the data.


text:
Q: Google Earth Engine: different stretch options I'm working on a map view that detects new ice using Sentinel-1 together with Google Earth Engine.
When adding images to Google Earth Engine I can set the min and max values for my layer in numbers but then in the map view I have the possibility to change change these values and also select different stretch options.

Is it possible to choose one of these options instead of entering a max and min view in the code? Right now my code end looks like this:
Map.addLayer(hh2017, {

bands: ["HH"],
max: -5,
min: -19,
opacity: 1,
palette: ['002bff','a4d5ff','979797','080358','000029' ]

}, 'sentinel-1');

I want it to be Stretch: 90% The reason I need to stretch the image each time is that they all look a bit different.

A: As described here, you may want to try a Styled Layer Descriptor.  The previous answer also works, but requires you to use getInfo(), which can cause your browser to lock (see Client-Server doc for details).  Here's another approach:
var i = ee.Image(ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA')
    .filterBounds(Map.getCenter())
    .sort('CLOUD_COVER')
    .first());
Map.centerObject(i);
Map.addLayer(i);

function setDisplay(dictionary) {
  var visParams = {
    bands: ['B4', 'B3', 'B2'],
    min: [
      dictionary['B4_p5'], dictionary['B3_p5'], dictionary['B2_p5']
    ],
    max: [
      dictionary['B4_p95'], dictionary['B3_p95'], dictionary['B2_p95']
    ]
  };
  Map.layers().set(0, ui.Map.Layer(i, visParams));
}

Map.onChangeBounds(function() {
  var params = i.reduceRegion({
    reducer: ee.Reducer.percentile([5, 95]),
    geometry: Map.getBounds(true),
    scale: Map.getScale(),
  });
  params.evaluate(setDisplay);
});

A: If you want to stretch based on statistics for a fixed region, you can use the following approach, which demonstrates both percentage and standard deviation based stretches.
// Function for displaying stretched image based on standard devitations from the mean.
var AddLayerStdDevStretch = function(img, sampling_geom, num_stddev) {
  var stats = img.select(['elevation'],['value']).reduceRegion({
    reducer: ee.Reducer.mean().combine({reducer2:ee.Reducer.stdDev(), sharedInputs:true})
                              .setOutputs(['mean', 'stddev']),
    geometry: sampling_geom,
    scale: 30,
    bestEffort: true
  });
  var vis_params = ee.Dictionary({
      'min': ee.Number(stats.get('value_mean'))
               .subtract(ee.Number(num_stddev).multiply(ee.Number(stats.get('value_stddev')))),
      'max': ee.Number(stats.get('value_mean'))
               .add(ee.Number(num_stddev).multiply(ee.Number(stats.get('value_stddev')))),
    });
  Map.addLayer({
    eeObject: img,
    visParams: vis_params.getInfo(),
    name: num_stddev + ' sigma'
  });
};

// Function for displaying stretched image based on percentile values.
var AddLayerPercentStretch = function(img, sampling_geom, percent) {
  var lower_percentile = ee.Number(100).subtract(percent).divide(2);
  var upper_percentile = ee.Number(100).subtract(lower_percentile);
  var stats = img.select(['elevation'],['value']).reduceRegion({
    reducer: ee.Reducer.percentile({percentiles: [lower_percentile, upper_percentile]}).setOutputs(['lower', 'upper']),
    geometry: sampling_geom,
    scale: 30,
    bestEffort: true
  });
  var vis_params = ee.Dictionary({
      'min': ee.Number(stats.get('value_lower')),
      'max': ee.Number(stats.get('value_upper'))
    });
  Map.addLayer({
    eeObject: img,
    visParams: vis_params.getInfo(),
    name: percent + '%'
  });
};

// Sample use - add layers with various stretches to the map.
var image = ee.Image("USGS/SRTMGL1_003");
var geometry = ee.Geometry.Polygon(
        [[[-112.6, 36.3],
          [-112.6, 35.9],
          [-111.9, 35.9],
          [-111.9, 36.3]]]);
Map.centerObject(geometry);
AddLayerStdDevStretch(image, geometry, 1);
AddLayerStdDevStretch(image, geometry, 2);
AddLayerStdDevStretch(image, geometry, 3);
AddLayerPercentStretch(image, geometry, 90);
AddLayerPercentStretch(image, geometry, 98);
AddLayerPercentStretch(image, geometry, 100);
Map.addLayer(geometry, {}, 'geometry used for stretch statistics');

Note that the percentage based stretches are based on a histogram (see ee.Reducer.percentile), so the 100% stretch may not exactly match the extreme values within the sampling region.

A: For stretching using the mean and standard deviation I wrote a function available in https://github.com/gee-community/gee_tools. I do not know how GEE does it when you do it as you mention (developers like as Noel Gorelick may know), but somehow it has slightly different values, see the test.
var stretch_std = function(n_std) {
  var mean = i.reduceRegion({
    reducer: ee.Reducer.mean(),
    geometry: i.geometry(),
    bestEffort: true})
  var std = i.reduceRegion({
    reducer: ee.Reducer.stdDev(),
    geometry: i.geometry(),
    bestEffort: true})
  var min = mean.map(function(key, val){
      return ee.Number(val).subtract(ee.Number(std.get(key)).multiply(n_std))
    }).getInfo()
  var max = mean.map(function(key, val){
      return ee.Number(val).add(ee.Number(std.get(key)).multiply(n_std))
    }).getInfo()

  return {vmin: min, vmax: max}
}

// TEST
var i = ee.Image("LANDSAT/LC8_L1T_TOA_FMASK/LC82310902013296LGN00")
var s = stretch_std(3)
var min = ee.Number(ee.List([s.vmin.B5, s.vmin.B6, s.vmin.B4]).reduce(ee.Reducer.mean()))
var max = ee.Number(ee.List([s.vmax.B5, s.vmax.B6, s.vmax.B4]).reduce(ee.Reducer.mean()))
var viz = {bands:["B5", "B6", "B4"],
           min: min.getInfo(),
           max: max.getInfo()}
var vizEE = {bands:["B5", "B6", "B4"],
           min: -0.06102305441591904,
           max: 0.41922686174360246}
print(viz)
Map.centerObject(i)
Map.addLayer(i, {bands:["B5", "B6", "B4"],
                 min:0, max:1}, "not streched")
Map.addLayer(i, vizEE, "streched by EE")
Map.addLayer(i, viz, "streched by gee_tools")


text:
Q: __block variable returns null. How can I access the NSString inside the __block variable? I am using this findAllMessages() function to return a NSString with information about each message.
Everything goes well until I go outside of the block and the concatenatedMessage string is null.
The last three lines concatenatedMessage return null:
 NSLog(@"%@",concatenatedMessage);
 NSString *newString = concatenatedMessage;
 return newString;

How can I access the value of concatenatedMessage outside of the block so that concatenatedMessage is not null?
+(NSString *) findAllMessages{

    __block NSMutableArray *totalMessages = [[NSMutableArray alloc] init];
    __block NSDictionary *values;
    __block NSString *concatenatedMessage;

    FIRUser *current_user = [[FIRAuth auth] currentUser];
    FIRDatabaseReference *dbReference = [[[[FIRDatabase database] reference] child:@"Messages"] child:current_user.uid];
    FIRDatabaseQuery *allMessages = [dbReference queryOrderedByChild:current_user.uid];

    [allMessages observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot *snapshot) {
        NSMutableDictionary *eachMessage = snapshot.value;
        concatenatedMessage = @"";
        for(id key in eachMessage){
            [totalMessages addObject:key];
            values = [eachMessage objectForKey:key];
            for(id key2 in values){
                concatenatedMessage = [concatenatedMessage stringByAppendingString:[values objectForKey:key2]];
                concatenatedMessage = [concatenatedMessage stringByAppendingString:@"^^"];
            }
            concatenatedMessage = [concatenatedMessage stringByAppendingString:@"%%"];
        }
    }];

    NSLog(@"%@",concatenatedMessage);
    NSString *newString = concatenatedMessage;
    return newString;
}

THANKS!!

A: You're trying to wrap an async function (observeEventType:withBlock:) with a synchronous function (findAllMessages).
This just doesn't work. It seems to be an issue in every modern language.
You can either:

*

*Find a synchronous method on FIRDatabaseQuery and call that (DON'T do this from the main thread or you will block the UI)

*Change findAllMessages to be asynchronous (findAllMessagesWithBlock:) and return to the caller via block. You may need to modify the caller to be async too. Async has a way of taking over big portions of codebases that use it.

A: I think you're misunderstanding how the block works. Let me elaborate:
Your definition of concatenatedMessage above the block is correct. Doing something like what you did will allow you to access it within and outside of the block:
__block NSString *concatenatedMessage;

The key here is to understand that your block passed into ...withBlock:^(FIRDataSnapshot *snapshot) { will most likely not be executed immediately as blocks are asynchronous.
That being said, when you log concatenatedMessage in your code after the block, the block has not yet been executed, thus the string isn't changed.
Instead, what you should be doing is either:

*

*Not be using a block (use something synchronous like a normal function instead)

*Do whatever you need to do with concatenatedMessage inside the block at the end of it so that when the block is eventually executed, you code executes after the variable is set


text:
Q: Update Mongoengine document without actively keeping track of the fields that changed I read a lot of the questions & answers on SO regarding how to update a document in Mongoengine (and MongoDB), but my problem is that all of them recommend "manually" giving as parameter all the fields that one wants to update as a dict - e.g.
p.update(**{
    "set__name": "Hank",
    "set__address": "Far away"

})
My problems with this are the following:

*

*I need to keep track of all the fields that modified

*I need to specify as strings in a dict all the names of the fields that I want to update

*I need to specify a modifier specific to the type of field I am modifying and the operation I do on that field.

Is there any way to update documents in Mongoengine/MongoDB using Python in a higher-level way? (To be more specific, I wish to update a document in MongoDB if it hasn't changed since I last read it from the DB.)
So my application is quite complex. I am often pass around an object p which corresponds to a document in the database, so that different methods modify fields of it, and then at the end of all the updates I want to save the modified document without having to worry which field has change and what modifier I need to use for it.
Any suggestion how I could do this or implement something to do this?
Thanks!

A: I have just found the answer to my question: it seems that starting from mongoengine 0.8.5 they've added a new parameter to the save() function - called save_condition - which does exactly what I was asking about:
save_condition – only perform save if matching record in db
                 satisfies condition(s) (e.g., version number)

(according to the documentation:
http://docs.mongoengine.org/apireference.html)


text:
Q: Meteor - accessing parent template vars from child helpers I cannot get and set the parent template variable from within the child helper.
I have read plenty of pages on the issue but I'm stuck ...
Template.parent.onCreated(function() {
    this.myVar = new ReactiveVar('xyz');
});

is expected to be accessible in child like this:
Template.child.helpers({
setAndGetIt : function() {
    Template.parentData(1).myVar = 'testString';
    return Template.parentData(1).myVar;

}});

where
<template name="parent>
    {{>child}}
</template>

Do I miss something? (Sessions solution is not a case here...)

A: There's a smarter way to accomplish this task. But you need to explicitly declare which variables you want to be accessible in the child template. and most probably you want that var to be reactive.
Template.parentTemplate.onCreated(function(){
    this.myVar = new ReactiveVar('hello');
});

in Blaze, you need to pass this variable when calling the child template like this.
{{>child myVar=myVar }}

Template.child.onRendered(function(){
    console.log(this.myVar.get());
});


text:
Q: Referencing two collections documents to each other in MongoDB Is it possible to reference 2 documents to each other using ref and if it is possible, is it recommended and is it good practice ? Like this :
FirstDocumentId Collection's Model :
const FirstDocumentId = mongoose.model(
    'FirstDocumentId',
    new mongoose.Schema({
        coolField: String,
        secondDocumentId: {type: Mongoose.Schema.Types.ObjectId, ref: 'secondDocumentId'}
    })
);

SecondDocumentId Collection's Model :
const SecondDocumentId = mongoose.model(
    'SecondDocumentId',
    new mongoose.Schema({
        someField: String,
        firstDocumentId: {type: Mongoose.Schema.Types.ObjectId, ref: 'firstDocumentId'}
    })
);

The point of this is to create a 1 to 1 relationship and being able to access both documents easily.
I know I can just reference 1, without referencing the second to the first, but I thought it would be simpler to modify them both.

A: Yes you can reference a collection to another collection like the way you're doing, ideally that's how relationships between two collections are maintained in MongoDB, but you need to understand as MongoDB is schema free, there is no direct way to create/update/delete documents in second collection by creating/updating/deleting relative documents in first collection(Collections & their docs are independent - operations are atomic at document level). As there is no direct way - You've to write application logic or some kind of batch job or MongoDB-stitch to achieve reference maintainance.

*

*But then if you ask why to maintain ?  - As you might be familiar with JOINS in SQL, this is the way, we can do reads very well using references.

*So how ? - MongoDB has aggregation framework which is way powerful to query database, In aggregation there is an operator called $lookup which is helpful to do JOINS. For that you've maintain references. You can also check $graphLookup.

*Do I've to use ref's ? - So as I've already talked about $lookup is a helpful operator - So by using that you doesn't need to mention ref for those fields. If you're using mongo shell or any client like robo3T or mongo compass or any native driver like mongodb driver for node.js you can use native $lookup. Even you can use lookup while using mongoose but mongoose claims they've .populate() which is very powerful compared to native $lookup, to use that you'll use ref. Apart from that there is no use of it, Even having the same models you can use $lookup with mongoose instead of using populate.

*Reference fields - So you're not restricted to _id fields, you can actually reference any field but the values & types should match in both of the collections, that way it could be easy while querying else you need to convert one to another while querying every time, So be careful on writes.

*Do I need to maintain reference in both collections - Not necessarily needed, it seems to easy or ok at first but when your collection does grow eventually it would be a hefty task to maintain references - You might need to write/delete/update in two collections every time, where indexes needs to build, document size/collection size can grow, So it would be better to maintain reference based on your query needs. Check this document on data design : data-modeling.