text:
Q: Why are my grid-template-areas causing my grid to stretch? two of my grid areas (reset and equals) are pushing the rest of the grid alignment off and I'm not sure what the issue is. Appreciate the guidance.
Here's the code:

.calc-buttons {
  display: grid;
  height: 400px;
  width: 500px;
  padding: 30px 30px;
  border-radius: 5px;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(5, 1fr);
  grid-gap: 30px;
  grid-template-areas:
    'seven eight nine del'
    'four five six plus'
    'one two three sub'
    'dot zero divide times'
    'reset reset equals equals';';
  background: var(--toggle-background);
}

  <button class="seven std">7</button>
  <button class="eight std">8</button>
  <button class="nine std">9</button>
  <button class="del sm-bl">DEL</button>
  <button class="four std">4</button>
  <button class="five std">5</button>
  <button class="six std">6</button>
  <button class="plus std">+</button>
  <button class="one std">1</button>
  <button class="two std">2</button>
  <button class="three std">3</button>
  <button class="sub std">-</button>
  <button class="dot std">.</button>
  <button class="zero std">0</button>
  <button class="divide std">/</button>
  <button class="times std">x</button>
  <button class="reset lg-bl">RESET</button>
  <button class="equals lg-rd">=</button>

reset and equals should span two 1fr each without changing the alignment of the other buttons.
Here's how it looks atm.

A: Q: Why are my grid-template-areas causing my grid to stretch?
A: That is because your defined grid-template area names are not automagically translated to CSS classes (which you seem to assume).
Solution: You never assign the grid template areas you have defined. You need to do that by explicitly assigning grid-area: area-name; to the elements in question.

.calc-buttons {
  display: grid;
  height: 400px;
  width: 500px;
  padding: 30px 30px;
  border-radius: 5px;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(5, 1fr);
  grid-gap: 30px;
  grid-template-areas:
    'seven eight nine del'
    'four five six plus'
    'one two three sub'
    'dot zero divide times'
    'reset reset equals equals';';
  background: var(--toggle-background);
}

.calc-buttons :last-child { grid-area: equals; }
.calc-buttons :nth-last-child(2) { grid-area: reset; }

  <button>7</button>
  <button>8</button>
  <button>9</button>
  <button>DEL</button>
  <button>4</button>
  <button>5</button>
  <button>6</button>
  <button>+</button>
  <button>1</button>
  <button>2</button>
  <button>3</button>
  <button>-</button>
  <button>.</button>
  <button>0</button>
  <button>/</button>
  <button>x</button>
  <button>RESET</button>
  <button>=</button>


text:
Q: How to get the rendered document of a webpage How do I obtain the rendered HTML from an URL?
Let's say I want to have this program that checks for updates on the web in the form of news, schedules and other dynamic content (Content not available in the HTML source)
How do I get the rendered (full) HTML containing the full document as if you were reading it through a browser?
The following example is an example of the dynamic page:

As always when it comes to dynamic sites - the above text is nowhere to be found in the source code - only visible through a browser.
Of course I can download the HTML page using a WebClient and DownloadString ("www.example.com") but that will only give me the source page - the static text.
I want to get the final document, let's say after Javascript added its elements and jQuery is finished its set-up.
    Dim Client As New WebClient
    Dim HTML = WebClient.DownloadString("http://www.example.com")

To access/parse more of the HTML I can also use MSHTML.dll to be able to go through the page, element, by element.
    Dim Client As New WebClient
    Dim Data As Stream = Client.OpenRead(New Uri("http://example.com"))
    Dim Reader As New StreamReader(Data)
    Dim HTML As String = Reader.ReadToEnd

    Dim Document As IHTMLDocument2 = DirectCast(New mshtml.HTMLDocument(), IHTMLDocument2)
    Document.write(HTML)
    Dim Elements As IHTMLElementCollection = Document.all

    For Each Element As IHTMLElement In Elements
    'here I can access things like the elements ids, tag innerHTML and so forth
    Next

But neither of these will give me the actual rendered document.
Although I could create an WebBrowser control, goto the URL and through that access the page's content - but if possible - that's not the way I want to do it.

A: For web pages that load content dynamically, you have to discover the urls that are being called to fetch content by the web page script. Use a tool like fiddler to see the urls. Once you have that information, use WebClient to fetch the content.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Im pulling a file that has different ascci values than I need. Python Basically I have a .txt file that I need to decode. In example the is endcoded as rfc in the file.
This is what I have at the moment.
line = open('encoded_2.txt','r')
for f in line:
    line = chr(ord(line[f])+2)
print(line)

infile.close()

I get this error:

"TypeError: '_io.TextIOWrapper' object is not subscriptable"

A: I'm not exactly sure of the conversion you're attempting.  I tried to preserve that conversion.  This code reads from the entire text file into line all at once.  Then it goes through each ch in the line, making the conversion and appending to new_line.  Hopefully that helps you on your way.
infile = open('encoded_2.txt','r')
line = infile.read()
new_line = ''
for f, ch in enumerate(line):
    new_line += chr(ord(ch) + 2)
print(new_line)
infile.close()


text:
Q: I want to access dynamic value in VirtualService for uri I want to deploy two services with different URLs.
 - match:
      uri:
        prefix: /pune
    route:
    - destination:
        host: wagholi
        port:
          number: 8080
 - match:
      uri:
        prefix: /pune/{location}
    route:
    - destination:
        host: yerwada
        port:
          number: 8080
 - match:
      uri:
        prefix: /pune/{local}/here
    route:
    - destination:
        host: hadapsar
        port:
          number: 8080

In this scenario, When I am hitting API getting 404 Not Found /pune/yerwada when I pass location value as yerwada. Also  I am passing /pune/hadapsar/here getting same error 404 Not Found /pune/hadapsar/here, When I pass hadapsar at the place of local. !!!!!

A: Do the requests pass in a header named location with value of pune? If "no" then remove this from the matching rules - it is the cause for the requests not being matched by uri prefix alone:
    - headers:
        location:
          exact: pune

Just in case, here is a link to the relevant doc.

A: We can go with regex for uri.
 - match:
      uri:
        prefix: /pune
    route:
    - destination:
        host: wagholi
        port:
          number: 8080
 - match:
      uri:
        regex: \/pune/\/(.+)
    route:
    - destination:
        host: yerwada
        port:
          number: 8080
 - match:
      uri:
        prefix: \/pune\/(.+)\/here
    route:
    - destination:
        host: hadapsar
        port:
          number: 8080


text:
Q: Javascript/jQuery attach different function args to .click() method What's wrong with this code? Reading this it seems that for each loop the jquery should attach a function with assigned values for each iteration. Instead it's attaching i = 2 to every object. Why is it doing that and how can I get it to attach the expected values (e.g., 0, 1, ...)?
//data.length is 2.

for (i=0; i<data.length; i++) {
    // Attach the click function
    linkId = 'a#' + pk;
    $(linkId).click(function(e) {
        e.preventDefault();
        console.log(i, pk, data);
    });
};

console.log -- each link has the same parameters
2 "52fef25e391a56206f03be6e" [object Array]

A: console will be displayed only when you click the $(linkId) but at the time is is already equal to data.length (aka 2 in your case) so it will always display 2

A: You're assuming that a block creates a new variable scope. It doesn't in JavaScript. Only a function execution does.
If you use $.each() instead, the callback you give it will be invoked for each iteration, and so you'll have a new scope for every one.
$.each(data, function(i,item) {
                //    ^---^---function parameters are local to this scope

//   v--declare a variable local to this scope
    var linkId = 'a#' + pk;

                //   v--the function made in this scope can access the local vars
    $(linkId).click(function(e) {
        e.preventDefault();
        console.log(i, pk, data, linkId, data[i]);
    });
});

A: Try to isolate the variable's scope. Declare a var j = i; inside the loop context so it enters the click-callback's scope.

A: So in order to create a separate scope for each iteration you can also use ordinary closure-functions, and pass current i into it:
for (var i = 0; i < data.length; i++) {
    (function(j) {
        $('a#' + pk).click(function(e) {
            e.preventDefault();
            console.log(j, pk, data);
        });
    })(i);
};


text:
Q: Purpose of id in PublicKeyCredentialUserEntity When you call navigator.credentials.create to generate a new credential, it is required that you include a [PublicKeyCredentialUserEntity][1] with an id in your PublicKeyCredentialCreationOptions. The spec says this id must be used for authentication and authorization decisions, but when you call navigator.credentials.get you don't pass in this value in the PublicKeyCredentialRequestOptions. You only need the credential IDs for the credentials you will allow to sign the challenge.
If I already have a unique customer identifier on the backend to associate each generated credential with and can use this to fetch the correct credential ID, does it really matter what value I use for the userId of the PublicKeyCredentialUserEntity?

A:
If I already have a unique customer identifier on the backend to associate each generated credential with and can use this to fetch the correct credential ID, does it really matter what value I use for the userId of the PublicKeyCredentialUserEntity?

For 2FA and Passwordless, you probably don't need to worry so much about it. As you said you already have a relationship in your database back to a user record by credential ID, and a user will have necessarily identified themselves via username/email/etc... to get far enough to complete 2FA or Passwordless authentication.
user.id, also known as the userHandle, becomes most important when you require discoverable credentials during registration. These types of credentials get stored internally in an authenticator in a map with a key of (rpID, userHandle). You have to be careful with these because an authenticator will override an existing discoverable credential if you allow a user to register the same authenticator again and specify the same value for user.id.
On the flip side, discoverable credentials allow for "usernameless" authentication. The value of userHandle you get back from navigator.credentials.get() will be how you as an RP know what the user's ID is in lieu of them telling you beforehand via username/email/etc... because it will be the same value as user.id you passed into navigator.credentials.create().


text:
Q: Highcharts with datetime and also additional data (tooltip text) I found info how to add tooltip with additional data.
I found info how to plot a line with date format on x-axis.
Only problem I need a combination of this.
Set Additional Data to highcharts series
data: [ { y : 3, myData : 'firstPoint' },
        { y : 7, myData : 'secondPoint' },

http://api.highcharts.com/highcharts#series
I tried this:
data: [[Date.UTC(2012, 9, 29) , 45, 'my note' ],[Date.UTC(2012, 9, 29) , 54, 'boe' ]

But unfortunately not working.

A: Your custom data needs to be an Object and not array
What you have used is an array
data: [[Date.UTC(2012, 9, 29) , 45, 'my note' ],[Date.UTC(2012, 9, 29) , 54, 'boe' ]]

Use an object instead
data:[{
 x: Date.UTC(2012, 9, 29) ,
 y: 45,
 myData: 'my note'
},
{
 x: Date.UTC(2012, 9, 29) ,
 y: 54,
 myData: 'boe'
}]


text:
Q: How app_scoped_ids will be used on custom audience after May 1st? On custom audience, there is the possibility to upload a Facebook ID list for creating an audience... After the Graph API v2.0 migration, when we won't have access to Facebook ID anymore, how can i upload the user id list? Can i use a app_scoped_id based list?
If someone publishes something on my fanpage, and i get his post using Graph API, will i be able to use his id on custom audience? The official documentation don't make itself clear when explaining about the "expiring process" of a app_scoped_id. As far as i understood, when someone authorizes an application, his app_scoped_id will be "permanent", but if there is no user interaction/authorization with my application, the app_scoped_id CAN expire in 24 hours... is that right? If so, how can i use a list of ids on custom audience if they expires?
Thank you!
UPDATE
From https://developers.facebook.com/docs/apps/upgrading#upgrading_v2_0_user_ids:

For users who have not logged into your app, the user ID may change depending on the version of the API that you call. In v1.0 of the API users who have not logged into your app will be referred to by their original Facebook user ID, whereas in v2.0 they will be referred to by an app-scoped ID.
We've added new API endpoints that allow you to tag and invite friends who don't use your app. These APIs return tokens which may be used to generate custom interfaces for tagging and invitations. Those tokens aren't meant to be cachable and we make no guarantees that they will be stable beyond 24 hours from the time the API response containing them was received. They aren't the same as either the IDs used on data for people not logged into your app nor the same as the app-scoped IDs.

A: You are confusing the app-scoped IDs with temporarily generated IDs.  App-scoped IDs will not change over time.  Temporarily generated IDs are meant to help with inviting and tagging friends who have not authorized an application and as such they will not remain the same over time.


text:
Q: Table won't populate with data I've been new to programming and I been working with phpmyadmin on localhost. I am making a simple table on a webpage to display data. The problem is that everytime I load the page it only displays the table and not table will load up. Here is my code:
<?php
require('../model/database.php');
require('../model/product_db.php');

$products = get_products();

if (isset($_POST['action'])) {
    $action = $_POST['action'];
} else if (isset($_GET['action'])) {
    $action = $_GET['action'];
} else {
    $action = 'under_construction';
}

 // Display the product list
    include('view-productList.php');

?>

This is the view-productList.php:
<?php include '../view/header.php'; ?>

Product List

<?php echo $name; ?>

                Code
                Name
                Version

            <?php foreach ($products as $product) : ?>

                <?php echo $product['productCode']; ?>
                <?php echo $product['name']; ?>
                <?php echo $product['version']; ?>
                <form action="." method="post">
                    <input type="hidden" name="action"
                           value="delete_product" />
                    <input type="hidden" name="product_id"
                           value="<?php echo $product['productID']; ?>" />
                    <input type="hidden" name="category_id"
                           value="<?php echo $product['categoryID']; ?>" />
                    <input type="submit" value="Delete" />
                </form>

            <?php endforeach; ?>

Add Product

<?php include '../view/footer.php'; ?>

Query Page:
<?php
function get_products() {
    global $db;
    $query = 'SELECT * FROM products
              ORDER BY productID';
    $products = $db->query($query);
    return $products;
}

function get_products_by_category($category_id) {
    global $db;
    $query = "SELECT * FROM products
              WHERE products.categoryID = '$category_id'
              ORDER BY productID";
    $products = $db->query($query);
    return $products;
}

function get_product($product_id) {
    global $db;
    $query = "SELECT * FROM products
              WHERE productID = '$product_id'";
    $product = $db->query($query);
    $product = $product->fetch();
    return $product;
}

function delete_product($product_id) {
    global $db;
    $query = "DELETE FROM products
              WHERE productID = '$product_id'";
    $db->exec($query);
}

A: product_db.php should not be commented out for one - assuming that is the file that holds the "Query Page:" contents.
$products = get_products();

should come immediately after the include.
and your for loop needs the fetch result and not just the product resource:
<?php foreach ($products->fetch() as $product) : ?>

assuming fetch() is relevant to this type of resource since we can't see your db class.


text:
Q: Google Tag Manager Container Validation Error I've received the following error from Google Tag Manager when attempting to preview a Custom HTML tag.
Error Type: JavaScript compiler error
Error Description: Error at line 3, character 4: Parse error. '}' expected
Google Tag Manager Validate Container Error
Below is the code included in the tag:

Any help with troubleshooting this would is appreciated. Thanks in advance for your help!

A: It looks like you need to quote your HTML. You may also need to return it from the function as well - I've included this.


text:
Q: Search engine with colored search word I want to search engine with LIKE keyword and i want to colored searched word.
My code is:
$result1=mysql_query("SELECT * FROM archives1 where title like '%$search%' || author like '%$search%'") or die (mysql_error());
     while($row1=mysql_fetch_array($result1))
        {

            extract($row1);
     echo"

Archives

Section:	$section

Title:	$title

Author:	$author

Country:	$country

Page Number:	$pgno
";

If i want to search any word with above code then it gives true answer but i want answer with colored text. Only search word should be colored.
How can it be possible?
I have no idea.

A: use a preg_replace to replace the searched text with a span and add a class to it.
$text = 'sample text';
$query = 'text';
$text = preg_replace('/('.$query.')/','$1',$text);

echo $text;

use the highlight class to style the result.

A: You can use a simple function to highlight arbitrary text:
// Replace string and highlight it
function highlight_words($string, $words, $css_class)
 {
    //convert searched word to array
    $words = array($words);
    //cycle
    foreach ( $words as $word )  {
        $string = str_ireplace($word, ''.$word.'', $string);
    }
    /*** return the highlighted string ***/
    return $string;
 }

Example usage:
$string = 'This text will highlight PHP and SQL and sql but not PHPRO or MySQL or sqlite';
$words = array('php', 'sql');
$string =  highlightWords($string, $words, 'highlight');


text:
Q: Correct work querySelectorAll with forEach into another forEach I have some product list on my page
I need to run all products and get id (article) and name of product
ID need get from data-id into ".eshop_js-add-to-cart"
Name need to get from ".eshop-item-v2-title"
Needed after click on CartButton take data-id from clicked button, not the first and take his name

var CartButton = document.querySelectorAll(".eshop_js-add-to-cart");

CartButton.forEach((item) => {
  item.onclick = function () {
    console.log("addToCart works");

    var NameProductList = document.querySelector(".eshop-item-v2-title").textContent;
    var ProductIdList = document.querySelector('.eshop_js-add-to-cart');
    var ProductIdCountList = ProductIdList.getAttribute('data-id');

    window.dataLayer = window.dataLayer || [];
    dataLayer.push({
      event: 'addToCart',
      ecommerce: {
        add: {
          actionField: { list: 'category' },
          products: [{
            name: NameProductList,
            id: ProductIdCountList,

          }]
        }
      }
    });
    console.log("dataLayer works");
  };
});

        Add to cart

  Product 1

        Add to cart

  Product 2

A: Whats wng with the code?
Your selector quesries document.querySelector(".eshop-item-v2-title") and document.querySelector('.eshop_js-add-to-cart') will always return the first node having class eshop-item-v2-title and eshop_js-add-to-cart regardles of the button that you clicked.
Solution.
You can identify which button you clicked by using e.currentTarget insuide the clicke event listner. You can select the closest element with class eshop-item-v2-wrap which can be called as the container div with e.currentTarget.closest(".eshop-item-v2-wrap"). Your reired nodes can be targetted now by using this node. Simply by using parentNode.querySelector(".eshop-item-v2-title") and parentNode.querySelector('.eshop_js-add-to-cart') where parentNode is the result of selector e.currentTarget.closest(".eshop-item-v2-wrap")

var CartButton = document.querySelectorAll(".eshop_js-add-to-cart");

CartButton.forEach((item) => {
  item.onclick = function (e) {
    console.log("addToCart works", e.currentTarget);
    const parentNode = e.currentTarget.closest(".eshop-item-v2-wrap");

    var NameProductList = parentNode.querySelector(".eshop-item-v2-title").textContent;
    var ProductIdList = parentNode.querySelector('.eshop_js-add-to-cart');
    var ProductIdCountList = ProductIdList.getAttribute('data-id');

    console.log('NameProductList', NameProductList);
    console.log('ProductIdList', NameProductList);
    console.log('ProductIdCountList', NameProductList);

    window.dataLayer = window.dataLayer || [];
    dataLayer.push({
      event: 'addToCart',
      ecommerce: {
        add: {
          actionField: { list: 'category' },
          products: [{
            name: NameProductList,
            id: ProductIdCountList,
          }]
        }
      }
    });
    console.log("dataLayer works");

  };
});

        Add to cart

  Product 1

        Add to cart

  Product 2


text:
Q: CPIO command taking too long to complete I'm trying to install Oracle database 10g on an Ubuntu Server 11.04 VM. I am using Vagrant to run it and access it. I downloaded the install package which has a .cpio.gz file extension. Oracle specifies these commands to unpack it:
gunzip filename
cpio -idmv filename

The gunzip operation worked just fine, but when I run the cpio command it seems to be taking too long. I left it running for over 3 hours and it had not completed. Now, the .cpio file is 764MB. Should it be running this long?

A: Use one of the following
 cpio -idmvI filename      # note the capital I

or
 cpio -idmv < filename     # note the 'lower than'

otherwise cpio tries to read from stdin


text:
Q: Use username to generate Key in the cache I have crosscutting project that can be access anywhere in the aplicattion
Something like this.
//Domain\username
public static string GetLoggedUserName()
        {
            return Thread.CurrentPrincipal.Identity.Name.Split('\\')[1];
        }

And when I need to clean the cache (update, delete, etc) I do this.
private IMethodReturn ApplyCleanCacheHandler(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
    {
        var methodClass = input.MethodBase.DeclaringType.Name;
        var sessionUserName = SomeSessionClass.GetLoggedUserName();

        var cacheKeysToClean = GlobalCachingProvider.GetAllCacheKeys()
                                                    .Where(x => x.Contains(methodClass) &&
                                                               (x.Contains(GlobalCachingProvider.commonCacheUser) ||
                                                                x.Contains(sessionUserName))).ToList();

        cacheKeysToClean.ForEach(key => GlobalCachingProvider.RemoveItem(key));

        // Original target invoking.
        return getNext()(input, getNext);
    }

Its there anyway to do this better, I don't know if its a good practice access to the username anywhere of the aplication.


text:
Q: How to know if Android device is Flat on table I'm using accelometer sensor to detect whether my device is flat on a table or not. The weird thing is even when I put my phone flat or rotate it on it's side the value is always between 90 and 100! This shouldn't be correct! am I missing something? Here is my code:
   float[] values = event.values;
    // Movement
    float x = values[0];
    float y = values[1];
    float z = values[2];
    float norm_Of_g =(float) Math.sqrt(x * x + y * y + z * z);

    // Normalize the accelerometer vector
    x = (x / norm_Of_g);
    y = (y / norm_Of_g);
    z = (z / norm_Of_g);
    int inclination = (int) Math.round(Math.toDegrees(Math.acos(y)));
    Log.i("tag","incline is:"+inclination);

    if (inclination < 25 || inclination > 155)
    {
        // device is flat
        Toast.makeText(this,"device flat - beep!",Toast.LENGTH_SHORT);
    }

Edit: I'm using this code : How to measure the tilt of the phone in XY plane using accelerometer in Android

A: You're using the y-axis instead of the z-axis as used in the answer you linked.
The value of acos will be near-zero when the argument is near one (or near 180 degrees when near negative one), as seen in this picture:

As such, your inclination will be near zero (or 180) degrees only when the y axis is normalized to about one or negative one, eg when it is parallel to gravity, (thus, the device is "standing up").
If there's no other error, simply switching from:
int inclination = (int) Math.round(Math.toDegrees(Math.acos(y)));

to
int inclination = (int) Math.round(Math.toDegrees(Math.acos(z)));

should do it.

A: I used the code on this page Motion Sensors
public void onSensorChanged(SensorEvent event){
  // In this example, alpha is calculated as t / (t + dT),
  // where t is the low-pass filter's time-constant and
  // dT is the event delivery rate.

  final float alpha = 0.8;

  // Isolate the force of gravity with the low-pass filter.
  gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0];
  gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1];
  gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2];

  // Remove the gravity contribution with the high-pass filter.
  linear_acceleration[0] = event.values[0] - gravity[0];
  linear_acceleration[1] = event.values[1] - gravity[1];
  linear_acceleration[2] = event.values[2] - gravity[2];
}

The intention of this is to factor out the force of gravity (over repeated measurements) in the accelerometer values, leaving just the acceleration component in each direction.
The force of gravity is measured along each axis, so once you know which axis represents the device lying flat, you can just check if the majority of the force of gravity lays in just that axis.  That would mean the device is laying flat on the table.
You can also look at the linear acceleration to make sure the device isn't moving.


text:
Q: jQuery code working in FF, Chrome, not in IE I have a small snippet of code, this:
$(document).ready(function () {
                $("#check").blur(function () {
                    var member = check.value;
                    $('#loading-image').show("fast");
                    $.getJSON('/Endpoint/MemberName/' + member, function (result) {
                        //  var data = JSON.parse(result);
                        var json = result;
                        if (json.result.length != 0) {
                            $("div#preload h2").html("Nombre: " + json.result[0].fullName);
                            jQuery('#services').show("fast");
                        }
                        else {
                            $("div#preload h2").html("No encontrado!");
                            jQuery('#services').hide("fast");
                        }
                        $('#loading-image').fadeOut("fast");

                    });
                });
            });

In Firefox and Chrome the snippet is working as intended, yet in IE browsers I get the following error:
SCRIPT5009: 'check' is undefined
Any idea on what could help me solve this issue?
EDIT: Added check textbox field:

                <input type="text" class="form-control input-lg" placeholder="Buscar numero de socio" id="check" name="check" />

                    <button class="btn btn-info btn-lg" type="button">

                    </button>
                    <button class="btn btn-primary btn-lg" type="button" data-toggle="modal" data-target="#myModal">
                         Añadir Cliente sin Cuenta
                    </button>

A: var member = this.value;
var member = $(this).val();


text:
Q: Can't find resource identifiers from AAR in XML I developed a custom Preference for an application.  It has two custom attributes.  I'm trying to move the Preference to a library project to reuse in other projects.  I moved the Java file along with the corresponding layout and attr XML files.  Here's the attr file in the library project:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="NumberPickerPreference" >
        <attr name="minValue" format="integer" />
        <attr name="maxValue" format="integer" />
    </declare-styleable>
</resources>

Here's the manifest:
<manifest package="com.mydomain.androiduilibrary">
</manifest>

An odd-looking manifest for sure.  When I generated the library project the only thing Android Studio put in the manifest was the SDK info, which then generated a warning about it already being specified in the build.gradle file, so I deleted the entry in the manifest.
I generate the AAR file using the bundleRelease task and get a file named androiduilibrary-release.aar.  I then go to the project that needs to use this Preference and select "New Module | Import .JAR or .AAR Package", navigate to the AAR, and it's now in my project as a module entitled androiduilibrary-release.  I make a module dependency in the Project Structure dialog, and can now reference the Preference in Java code.  So far, so good.
However, when I attempt to reference the Preference in XML, I get the following error on my custom attributes:  "Error:(9) No resource identifier found for attribute 'minValue' in package 'com.mydomain.androiduilibrary'".  Here's the XML:
<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:title="@string/location_service_settings_preference_header_title"
    xmlns:custom="http://schemas.android.com/apk/res/com.mydomain.androiduilibrary">

<com.mydomain.androiduilibrary.NumberPickerPreference
    android:title="@string/update_interval_preference_title"
    android:key="@string/update_interval_preference_key"
    android:defaultValue="@integer/update_interval_preference_default"
    android:summary="@string/update_interval_preference_summary"
    custom:minValue="@integer/update_interval_preference_min"
    custom:maxValue="@integer/update_interval_preference_max"
    android:dialogMessage="@string/update_interval_preference_dialog_message"
    android:dialogTitle="@string/update_interval_preference_title" />

I can look inside the AAR and see that the values are populating in R.txt:
int attr maxValue 0x7f010001
int attr minValue 0x7f010000

And that its manifest is being created correctly:
<?xml version="1.0" encoding="UTF-8"?>

<manifest android:versionName="1.0" android:versionCode="1"
    xmlns:android="http://schemas.android.com/apk/res/android" package="com.mydomain.androiduilibrary">

    <uses-sdk android:targetSdkVersion="21" android:minSdkVersion="11"/>

</manifest>

I also get a warning when calling out the custom preference:  "Element com.mydomain.androiduilibrary.NumberPickerPreference is not allowed here" so I'm guessing that will be a problem too.
Is there a step I'm missing that will allow me to reference elements from the AAR in my XML?  I'm using Android Studio 1.0.2.  Thanks in advance.

A: Solved it from this post, down at the bottom where it talks about external libraries.  Essentially, when referencing AAR elements in code you do so using the package specified in the AAR's manifest, but when referencing AAR elements in XML you cite the namespace of the project (not the AAR).


text:
Q: How to stream web cam per ASP.Net Core WebApi I try to create an endpoint which delivers a live stream of my webcam. I´m using AForge to access the camera, but I can´t manage to create and return a stream that actually renders in a video tag in the html client.
Additionally: The MemoryStream I'm using growes every second. And that is definitly not what I want.
What I tried so far:
Cam.cs:
public class Cam
{
    MemoryStream stream = new MemoryStream();

    public Cam()
    {
        FilterInfoCollection videoCaptureDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
        VideoCaptureDevice finalVideo = new VideoCaptureDevice(videoCaptureDevices[0].MonikerString);
        finalVideo.NewFrame += this._streamNewFrame;
        finalVideo.Start();
    }

    private void _streamNewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
    {
        System.Drawing.Image imgforms = (Bitmap)eventArgs.Frame.Clone();

        imgforms.Save(this.stream, ImageFormat.Bmp);

        this.stream.Seek(0, SeekOrigin.Begin);
    }

    public Stream GetStream()
    {
        MemoryStream stream = new MemoryStream();
        this.stream.CopyTo(stream);
        return stream;
    }
}

CamController.cs:
[ApiController]
[Route("[controller]")]
public class CamController : ControllerBase
{
    private readonly Cam cam;

    public CamController(Cam cam)
    {
        this.cam = cam;
    }

    [HttpGet]
    public IActionResult Get()
    {
        var contentType = "multipart/x-mixed-replace;boundary=myboundary";
        Stream stream = this.cam.GetStream();
        var result = new FileStreamResult(stream, contentType)
        {
            EnableRangeProcessing = true,

        };
        return result;
    }
}

Update 1:
I made progress. I managed to create a valid MJPEP stream (it is pretty easy if know how it has to look like). Look at that:
CamController.cs:
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace demo.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class CamController : ControllerBase
    {
        private readonly Cam cam;

        public CamController(Cam cam)
        {
            this.cam = cam;
        }

        [HttpGet]
        [Route("cam/video")]
        public async Task Get()
        {
            Response.ContentType = "video/webm";
            // How to go on here?

        }

        [HttpGet]
        [Route("cam/mjepg")]
        public async Task Get2()
        {
            Response.StatusCode = 206;
            Response.ContentType = "multipart/x-mixed-replace; boundary=frame";
            Response.Headers.Add("Connection", "Keep-Alive");

            StreamingSession session = this.cam.StreamOn(data =>
                {
                    if (Request.HttpContext.RequestAborted.IsCancellationRequested)
                    {
                        throw new Exception();
                    }

                    Response.Body.Write(this.CreateHeader(data.Length));
                    Response.Body.Write(data);
                    Response.Body.Write(this.CreateFooter());
                    Response.Body.Flush();
                });

            await Response.StartAsync();

            await session.WaitAsync();
        }

        /// <summary>
        /// Create an appropriate header.
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        private byte[] CreateHeader(int length)
        {
            string header =
                "--frame" + "\r\n" +
                "Content-Type:image/jpeg\r\n" +
                "Content-Length:" + length + "\r\n\r\n";

            return Encoding.ASCII.GetBytes(header);
        }

        private byte[] CreateFooter()
        {
            return Encoding.ASCII.GetBytes("\r\n");
        }
    }
}

Cam.cs:
using AForge.Video.DirectShow;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace demo
{
    public class Cam
    {
        object locker = new object();
        bool signaledToStop = false;
        List<StreamingSession> sessions = new List<StreamingSession>();
        VideoCaptureDevice finalVideo;

        public Cam()
        {
            FilterInfoCollection videoCaptureDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            finalVideo = new VideoCaptureDevice(videoCaptureDevices[0].MonikerString);

            finalVideo.VideoResolution = finalVideo.VideoCapabilities
                .OrderByDescending(x => x.MaximumFrameRate)
                .ThenByDescending(x=>x.FrameSize.Width)
                .FirstOrDefault();

            finalVideo.NewFrame += this._streamNewFrame;
        }

        private void _streamNewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
        {
            System.Drawing.Image imgforms = (Bitmap)eventArgs.Frame.Clone();
            byte[] data = new byte[0];

            using (MemoryStream stream = new MemoryStream())
            {
                imgforms.Save(stream, ImageFormat.Jpeg);
                data = stream.ToArray();
            }

            lock (this.locker)
            {
                foreach (var session in sessions.ToList())
                {
                    session.ProvideData(data);
                }
            }
        }

        public StreamingSession StreamOn(Action<byte[]> callback)
        {
            StreamingSession session = new StreamingSession(callback);
            lock (this.locker)
            {
                this.sessions.Add(session);

                if (this.signaledToStop)
                {
                    this.finalVideo.WaitForStop();
                }

                if (!this.finalVideo.IsRunning)
                {
                    this.finalVideo.Start();
                    this.signaledToStop = false;
                }
            }

            session.OnSessionEnded += Session_OnSessionEnded;

            return session;
        }

        private void Session_OnSessionEnded(object sender, EventArgs e)
        {
            lock(this.locker)
            {
                this.sessions.Remove(sender as StreamingSession);

                if (!this.sessions.Any())
                {
                    this.finalVideo.SignalToStop();
                    this.signaledToStop = true;
                }
            }
        }
    }

    public class StreamingSession
    {
        public StreamingSession(Action<byte[]> Callback)
        {
            this.Callback = Callback;
        }

        private Action<byte[]> Callback;
        private TaskCompletionSource Completion = new TaskCompletionSource();

        public event EventHandler OnSessionEnded;

        public Task WaitAsync(int? timeout = null)
        {
            if (timeout.HasValue)
            {
                return Task.WhenAny(Task.Delay(timeout.Value), this.Completion.Task);
            }

            return this.Completion.Task;
        }

        public void ProvideData(byte[] data)
        {
            try
            {
                this.Callback(data);
            }
            catch(Exception)
            {
                this.EndSession();
            }
        }

        public void EndSession()
        {
            this.Completion.SetResult();
            if (this.OnSessionEnded != null)
            {
                this.OnSessionEnded(this, null);
            }
        }
    }
}

But there is a problem left: The "video" (more like moving images) only renders in an img tag. But it shall render in a video tag. I read that video tag doesn´t support mjpeg - but how can I encode the stream in a format the video tag understands?
I uploaded the complete code here: https://github.com/ChristophWieske/asp-net-core-live-stream-source

A: You may want to consider WebRTC.
WebRTC is a relatively new browser based technology that allows a server to send streams to a JavaScript client.
See the WebRTC Samples for client side code:  https://github.com/webrtc/samples
Server side code is a bit more complex.  Here's an overly complicated example that uses "Mixed Reality."  It's a bit overboard, but should point you in the right direction.
https://microsoft.github.io/MixedReality-WebRTC/manual/cs/helloworld-cs-connection-core3.html


text:
Q: TitleState.hx:531: characters 6-28 : Bool cannot be called im having a problem executing a OnClickFuntion in Haxeflixel
if(FlxG.mouse.justPressed(logo2))
    {
        MusicBeatState.switchState(new StoryMenuState());
    }

i would love help in need of confusion!..
and yes the Mouse variable is set to true!

A: You can't do that.
FlxG.mouse.justPressed  just checks if you... well.. just pressed to mouse.
To do what you are trying to achieve, you can check if the mouse overlaps the sprite.
Something like this:
if(FlxG.mouse.justPressed && FlxG.mouse.overlaps(logo2))
{
        MusicBeatState.switchState(new StoryMenuState());
}

A: justPressed is Bool variable, so should be like below
if(FlxG.mouse.justPressed)


text:
Q: simpleHtmlDom со своей строкой Кусок html-кода отправляю с другой страницы
$parse = $_POST['all_page'];
$parse ->find('input')

Пытаюсь получить значения, но получаю ошибку:
Fatal error: Call to a member function find() on a non-object in /home/ххх.ru/public_html/subb/auto.php on line 111

A: Так, в порядке бреда поинтересуюсь: Не приходило в голову глянуть маны или, хотя бы, перевести сообщение?
Риторический вопрос, наверное.
Проблема в том, что до того, как работать с парсером, нужно его сначала проинициализировать и работать с объектом, который он вернёт.
Например так:
$parse = str_get_html($_POST['all_page']); // Parse the DOM from the string
$parse ->find('input'); // Get all 'input' elements


text:
Q: htaccess redirect in wordpress By using WordPress with Divi and custom php pages/scripts I ended with urls looking like this:
https://example.com/?day=today
https://example.com/?sport=1&league=123 (1=football and 123=premier_league)

I want to make them more user and SEO friendly and rewrite them in htaccess to:
https://example.com/?day=today ==> https://example.com/today
https://example.com/?sport=1&league=123 ==> https://example.com/football/premier_league

For the "day" link I tried this code, but it doesn't work
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([0-9a-z\-\_]+)?$ /?day=$1 [L,QSA,NC]
</IfModule>

For the other example with sport and league I wanted to find a solution in which I will manually add old link and new link, tried redirect 301, but I think it can't work, right?
Redirect 301 https://example.com/?sport=1&league=123 https://example.com/football/premier_league

I also tried Redirection plugin in WP, but it created Rule which destroys page and makes error 500:
RewriteRule ?sport=1&liga=123 https://example.com/football/premier_league [R=301,L]

or
RewriteCond %{QUERY_STRING} ^sport=1&league=123$
RewriteRule ^$ https://example.com/football/premier_league [R=301,L]

which gaved address: https://example.com/premier_league/?sport=1&league=123
I was also wondering if I can make it with pure php, since in PHP I can easilly get proper strings for id's of the sports and leagues. Unfortunantelly changing "?sport=1&league=32758" into "?sport=football&league=premier_league" and then clean it with rewrite in htacces is not possible right now.
I'm not expecting whole code for both problems, I believe that some directions would be enough. I browse stack and google and coudn't find any examples with links that looks like mine, so example.com/?sport=1 not example.com/page?sport=1
After further investigation I believe the problem is in the way I'm opening my custom pages. I'm using shortcodes to initiate a script and inside the script my php code is included with parameters. I think that because of that I got to this page https://example.com/premier_league/?sport=1&league=123 which was pretty close, but not working.
Now my question is how to send those parameters to proper script but not into url.


text:
Q: Removing b' in python django I have a string showing as b'value' i want to remove the b' part.
AFTER Searching thru stackoverflow, i tried below but didnt work

{% for item in row %}
35                                                  <td>{{ item.decode('UTF-8') }}</td>
36                                              {% endfor %}

I get error Could not parse the remainder: '('UTF-8')' from 'item.decode('UTF-8')'

A: You can try
>>> b'value'.decode('UTF-8')

A: You cannot remove the b' part because it is a byte string. The b' isn't part of the string. You have to decode it using .decode method available to strings.
>>> x = b'hello'
>>> x
b'hello'
>>>x.decode("utf8")
'hello'


text:
Q: Building image masonry like Facebook photos (architecture) I've gone through lots of masonry libraries before posting this question, but I could not find anything similar. So, I would greatly appreciate your advice.
What I'm trying to achieve is a perfect square masonry with just several (1-5) images - similar to Facebook images layout. E.g:

Also, I've been trying to build it myself from scratch, but there are some difficulties: As I understand, one can never know image height and width before it is partly or fully loaded. Even though, at first I need dimensions of only the first image to decide on a grid style, this waiting does not seem a good solution. On fb, the grid seems(?) to be determined from the beginning.
I have doubts that in case of FB the positions and sizes of these images are calculated in back-end and css is used only for masking, because server returns already resized images and maybe it even stores these alignment data to avoid repeated calculations.
Could you share your experience on this or redirect me to some library that solves this task? Actually, this algorithm should be easier than perfect masonry algorithms with many images, because only 1-5 images needs be shown here and all cases are determined based on whether first image is a portrait, landscape or square and whether it fills container width.
Thanks!


text:
Q: Complex array in Ruby I need to create this structure in ruby
   {
    "list": {
       "ownerList" : [ {
                "owner" : "Nacho",
                "list" : "MyList"
            },
            {
                "owner" : "Nacho2",
                "list" : "MyList2"
            }
         ]
      }
   }

but I'm not sure how to create a multientry array in ruby. Any ideas?

A: my_hash = {
  owner_list: [
    {
      owner: "Nacho",
      list: "MyList"
    },
    {
      owner: "Nacho",
      list: "MyList"
    },
  ]
}

This creates a hash with the data you want. You can then very easily transform it to a json if you like and make operations over it.


text:
Q: Rendering from GL_TEXTURE_EXTERNAL_OES to GL_TEXTURE_2D but only one color flashes I'm pretty new to opengl-es and currently have a problem rendering my video output on a screen in Unity.
I was developing a video player project with Unity. I bought the EasyMovieTexture plugin and replaced the video player module with another open-source video player (Ijkplayer) years ago which worked fine all the time.
Now I want to replace it with newer VLC using libvlcjni. I compiled and just replaced the old Ijkplayer but it didn't work as I expected. The screen just started flashing one color from every video frame but the video was going and the audio track was normally playing too.
Screenshot - A test scene with a screen, sorry there's mistake with texcoord but only color flashing
I'd like to provide some further information hope that I can find some help (Sorry if I have some mistakes or misunderstandings):

*

*As far as I know, these video player modules need a Surface (Or SurfaceTexture) in the Android layer and the video decoder will work as a data producer. The SurfaceTexture consumes data from the producer and converts it to the texture with the type of GL_TEXTURE_EXTERNAL_OES which can be directly consumed and displayed with components like TextureView. But this texture data cannot be consumed in the Unity layer unless I use a GLSL shader directly sampling my OES texture data, like this:
// Unity shader with GLSL
GLSLPROGRAM
    #pragma only_renderers gles3
    #include "UnityCG.glslinc"
// ...
// Ignoring vertex shader
// ...
    in vec2 textureCoord;
    layout(binding = 0) uniform samplerExternalOES _MainTex;
    out vec4 fragColor;
    void main()
    {
        fragColor  = texture(_MainTex, textureCoord);
    }
ENDGLSL

*My approach was to convert the texture to GL_TEXTURE_2D with the native library which came along with the EasyMovieTexture plugin. Here I cannot provide the source code of this .so library but I've decompiled it in IDAPro and I know it can work along with GLES and render the external texture data to another 2d texture using FrameBuffer Object and external shader program.

*

*Here is a random example to explain the procedure, it is NOT the accurate code from the binary: FilterFBOTexture.java

*Though I cannot edit the .so file, luckily it was reading two external files as the shader program:

// vertex shader
attribute highp   vec3  inVertex;
attribute mediump vec3  inNormal;
attribute mediump vec2  inTexCoord;
uniform highp   mat4  MVPMatrix;
uniform mediump vec2 TexCoordMove;
varying mediump vec2   TexCoord;

void main()
{
    highp vec4 vPos = vec4(0,0,0,1);

    vPos.x = ( inTexCoord.x * 2.0 - 1.0 );
    vPos.y = ( inTexCoord.y * 2.0 - 1.0 );

    gl_Position = vPos;

    mediump vec4 vec4Temp  = vec4(inTexCoord.x - TexCoordMove.x,inTexCoord.y - TexCoordMove.y,0,1.0);
    vec4Temp  = MVPMatrix * vec4Temp;
    vec4Temp.xyz = vec4Temp.xyz / vec4Temp.w;
    TexCoord = vec4Temp.xy;
}

// fragment shader
#extension GL_OES_EGL_image_external : require
uniform samplerExternalOES sTexture;
uniform lowp float AlphaValue;
varying mediump vec2  TexCoord;
void main()
{
    lowp vec4 color = texture2D(sTexture, TexCoord) ;
    color = vec4(color.rgb, color.a * AlphaValue);
    gl_FragColor = color;
}

I don't know whether I have to check the vertex shader or just dive into the source code of libvlcjni so that I can correctly render my video output. Any idea will be grateful, thanks.
Update 2022-11-4:
I turned around and began to use VLC for Android.
Big appreciation to @mfkl, I created an issue days ago on the VLC repo.
https://code.videolan.org/videolan/vlc-unity/-/issues/164
The problem still remains but at least I can work for something now.


text:
Q: SetDate in textBox? I create widgets for date for my project.
n using the same widget for setProperty and getProperty of a object.
public TextBox getTimeTxtbx() {
        // TODO Auto-generated method stub

        timebx =new TextBox();

        timebx.setReadOnly(true);
        final PopupPanel popupPanel=new PopupPanel(true);
        final DatePicker datePicker=new DatePicker();

        datePicker.addValueChangeHandler(new ValueChangeHandler<Date>() {

            public void onValueChange(ValueChangeEvent<Date> event) {
                // TODO Auto-generated method stub

                Date date=event.getValue();
                timebx.setText(DateTimeFormat.getFormat("EEE MMM dd HH:mm:ss z yyyy").format(date));
                popupPanel.hide();
            }

        });
        popupPanel.setWidget(datePicker);
        timebx.addClickHandler(new ClickHandler() {

            public void onClick(ClickEvent event) {
                // TODO Auto-generated method stub
                String strDate = timebx.getText();
                System.out.println(" strDate " +strDate);
                DateTimeFormat format = DateTimeFormat.getFormat("[EEE MMM dd HH:mm:ss z yyyy]");
                try {
                      Date selDate = (Date)format.parse(strDate);
                      datePicker.setValue(selDate, true);
                    } catch(Exception pe){
                     // setting current date
                        System.out.println("error" +pe);
                     datePicker.setValue(new Date(), true);
                    }
                int x=timebx.getAbsoluteLeft();
                int y=timebx.getAbsoluteTop();
                popupPanel.setPopupPosition(x, y+20);
                popupPanel.show();
            }
        });
        return timebx;
    }
    public void setTimebx(String string) {
        // TODO Auto-generated method stub
        timebx.setText(string);
    }

I am adding this widgets in flexTable in different gui class
flexTable.setWidget(i, j,textBoxDisplay.getTimeTxtbx());
textBoxDisplay.setTimebx(customProperty.getValues().toString());

In a flexTable , this above code is inside a iterator and called Twice.

Like in Image : testDate an received on.
When i click on testDate the value of Received On is Changed

Edited
public ListBox getBooleanBox() {
        // TODO Auto-generated method stub
        selectBoolean = new ListBox(false);
        //selectBoolean.setName(title);
        selectBoolean.setStyleName("cmis-Customproperties-TextBox");
        selectBoolean.setSize("150px", "20px");
        selectBoolean.addItem("True","True");
        selectBoolean.addItem("False", "False");
        return selectBoolean;
    }
    public void setBooleanBox(String value){
         int itemCount = selectBoolean.getItemCount();
         for(int i = 0 ;i < itemCount;i++){
             if(selectBoolean.getItemText(i).equalsIgnoreCase(value)){
                 selectBoolean.setSelectedIndex(i);
             }
         }
    }

adding in flexTable
customPropertyTabel.setWidget(i, j,textBoxDisplay.getBooleanBox());
textBoxDisplay.setBooleanBox(removeSymbol(customProperty.getValues().toString()));

and this is working perfectly fine.
I got the correct values.

A: It looks to me textBoxDisplay is the same widget instance for both testingDate and receivedOn. Meaning if the receivedOn is added it overrides the testingDate, hence you get the popup when you click on the icon of testingDate. So you need a textBoxDisplay for both testingDate and receivedOn, like: textBoxDisplayTestingDate and textBoxDisplayReceivedOn

A: This is a referencing issue in the implementation.
On your second iteration of getTimeTxtbx (when you create Received On textbox) you have set the local variable timebx in textBoxDisplay instance to a new reference which is the Received On textbox. Your datePicker's onValueChange implementation set the text on timebx, hence the Received On textbox gets set instead of the testingDate textbox on your second iteration.
Try use a new instance of TextBoxDisplay instead during the iteration.
TextBoxDisplay textBoxDisplay = new TextBoxDisplay();
flexTable.setWidget(i, j,textBoxDisplay.getTimeTxtbx());
textBoxDisplay.setTimebx(customProperty.getValues().toString());


text:
Q: Meteor: How do you preserve dom manipulations when page refreshes or another page location? I have an infinite scroll that adds new elements (links), when I navigate to the link and go back in my browser, I am back to the first page of results and not the expansive elements that were added as a result of my previous scrolling action.

A: You are doing it all wrong! Need to do it the meteor way.
You simply grow the number of documents on the client side by using Deps.autorun() and changing the page number Session.set('currentPage');
main.js
//when scrollbar reaches end of page, just change the 'currentPage' session variable to 'grow' the list template
    if ($(window).scrollTop() + $(window).height() == $(document).height()) {
var nowPage = Session.get('pageNumber');
Session.set('pageNumber', parseInt(nowPage) + 1);
e.stopImmediatePropagation();
}

client/subscription.js
Deps.autorun(function(){
  Meteor.subscribe('huge-list', Session.get('currentPage'); //whenever currentPage changes, so will your subscription if you set up your publish() on the server side;
});

server/publication.js
Meteor.publish('huge-list', function(page){ //when session changes on client, this changes
return Requests.find({}, {limit:page});
});

A: The only way would be to save the state of your scroll, then re-apply your DOM manipulations after Meteor has rendered your templates.
For example, something like this:
Template.my_template.rendered = function() {
    $('#my-scrolling-element').scroll(function(e) {scrollPosition = e.target.scrollTop()})

    if(scrollPosition) {
        $('#my-scrolling-element').scrollTo(scrollPosition);
    }
}


text:
Q: Updating part / range of UITextView AttributedText I've created a small text editor that works with RTF files.
The file is read into a UITextView the user can edit. The UITextView works with a
Currently, when a range of text is selected and the Bold button is pressed, I do the following:
NSRange selectedTextRange = _textView.selectedRange;
BOOL isBold = [self isBold:selectedTextRange];

if(selectedTextRange.length > 0) {
    NSMutableAttributedString *str = [_textView.attributedText mutableCopy];
    [str enumerateAttribute:NSFontAttributeName inRange:selectedTextRange options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {
        if (value) {
            UIFont *newFont = [self boldOptionWithFont:(UIFont *)value setBold:!isBold];
            if(newFont) {
                [str removeAttribute:NSFontAttributeName range:range];
                [str addAttribute:NSFontAttributeName value:newFont range:range];
            }
        }
    }];
    _textView.attributedText = str;
    _textView.selectedRange = selectedTextRange;
}

At the end the attributed text is set on the UITextView. However, this is slow on large files (a 200+ page took over 4 seconds).
Question: is there a way to update just a part of the attributed text of a UITextView?
Note: the question is somewhat similar to this unanswered one: Delete a word of attributedtext on textview

A: Try calling [_textview.textStorage replaceCharactersInRange:withAttributedString:].


text:
Q: Error: New app path did not have extension .apk Trying to learn Appium and run in some issues that I can't really figure out when running Maven Project and wanted to see if I could execute the java application.
When executing the Java application it complains about the apk file. The apk file is in the "src" folder (see attached image) and I have entered correct path.
Original error: New app path 'C:\Users\Elvedin\eclipse-workspace\AppiumFramework\src' did not have extensions: .apk,.apks
    ******MY CODE:******

public class main {

public static AndroidDriver<AndroidElement> Capabilities(String appName) throws IOException {

//      System.getProperty("user.dir");
        FileInputStream fis = new FileInputStream(System.getProperty("user.dir") + "\\src\\main\\java\\practise\\AppiumFramework\\global.properties");
        Properties prop = new Properties();
        prop.load(fis);

        AndroidDriver<AndroidElement>  driver;
        File appDir = new File("src");
        File app = new File(appDir, (String) prop.get(appName));

        DesiredCapabilities cap = new DesiredCapabilities();

        String device = (String) prop.get("device");
        cap.setCapability(MobileCapabilityType.DEVICE_NAME,"device");
        cap.setCapability(MobileCapabilityType.AUTOMATION_NAME,"uiautomator2");
        cap.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 14);
        cap.setCapability(MobileCapabilityType.APP, appDir.getAbsolutePath());
        driver = new AndroidDriver<AndroidElement>(new URL("http://127.0.0.1:4723/wd/hub"), cap);
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        return driver;

    }

}

**CONSOLE OUTPUT**:
Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: Unable to create a new remote session. Please check the server log for more details. Original error: An unknown server-side error occurred while processing the command. Original error: New app path 'C:\Users\Elvedin\eclipse-workspace\AppiumFramework\src' did not have extensions: .apk,.apks
    Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
    System info: host: 'LAPTOP-PDE95IER', ip: '192.168.1.24', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '15.0.2'
    Driver info: driver.version: AndroidDriver
    remote stacktrace: UnknownError: An unknown server-side error occurred while processing the command. Original error: New app path 'C:\Users\Elvedin\eclipse-workspace\AppiumFramework\src' did not have extensions: .apk,.apks
        at getResponseForW3CError (C:\Users\Elvedin\AppData\Roaming\npm\node_modules\appium\node_modules\appium-base-driver\lib\protocol\errors.js:804:9)
        at asyncHandler (C:\Users\Elvedin\AppData\Roaming\npm\node_modules\appium\node_modules\appium-base-driver\lib\protocol\protocol.js:380:37)
    Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
    System info: host: 'LAPTOP-PDE95IER', ip: '192.168.1.24', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '15.0.2'
    Driver info: driver.version: AndroidDriver
        at io.appium.java_client.remote.AppiumCommandExecutor$1.createSession(AppiumCommandExecutor.java:208)
        at io.appium.java_client.remote.AppiumCommandExecutor.createSession(AppiumCommandExecutor.java:217)
        at io.appium.java_client.remote.AppiumCommandExecutor.execute(AppiumCommandExecutor.java:239)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
        at io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:42)
        at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:1)
        at io.appium.java_client.android.AndroidDriver.execute(AndroidDriver.java:1)
        at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:213)
        at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:131)
        at io.appium.java_client.DefaultGenericMobileDriver.<init>(DefaultGenericMobileDriver.java:38)
        at io.appium.java_client.AppiumDriver.<init>(AppiumDriver.java:84)
        at io.appium.java_client.AppiumDriver.<init>(AppiumDriver.java:94)
        at io.appium.java_client.android.AndroidDriver.<init>(AndroidDriver.java:95)
        at practise.AppiumFramework.main.Capabilities(main.java:37)
        at practise.AppiumFramework.ecommerc_tc_4.main(ecommerc_tc_4.java:18)
    Caused by: java.lang.reflect.InvocationTargetException
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:564)
        at io.appium.java_client.remote.AppiumCommandExecutor$1.createSession(AppiumCommandExecutor.java:186)
        ... 14 more
    Caused by: org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command. Original error: New app path 'C:\Users\Elvedin\eclipse-workspace\AppiumFramework\src' did not have extensions: .apk,.apks
    Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
    System info: host: 'LAPTOP-PDE95IER', ip: '192.168.1.24', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '15.0.2'
    Driver info: driver.version: AndroidDriver
    remote stacktrace: UnknownError: An unknown server-side error occurred while processing the command. Original error: New app path 'C:\Users\Elvedin\eclipse-workspace\AppiumFramework\src' did not have extensions: .apk,.apks
        at getResponseForW3CError (C:\Users\Elvedin\AppData\Roaming\npm\node_modules\appium\node_modules\appium-base-driver\lib\protocol\errors.js:804:9)
        at asyncHandler (C:\Users\Elvedin\AppData\Roaming\npm\node_modules\appium\node_modules\appium-base-driver\lib\protocol\protocol.js:380:37)
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:64)
        at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
        at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)

**APPIUM LOG:**
[HTTP] --> POST /wd/hub/session
[HTTP] {"desiredCapabilities":{"app":"C:\\Users\\Elvedin\\eclipse-workspace\\AppiumFramework\\src","automationName":"uiautomator2","platformName":"Android","deviceName":"device","newCommandTimeout":14},"capabilities":{"firstMatch":[{"appium:app":"C:\\Users\\Elvedin\\eclipse-workspace\\AppiumFramework\\src","appium:automationName":"uiautomator2","appium:deviceName":"device","appium:newCommandTimeout":14,"platformName":"android"}]}}
[debug] [W3C] Calling AppiumDriver.createSession() with args: [{"app":"C:\\Users\\Elvedin\\eclipse-workspace\\AppiumFramework\\src","automationName":"uiautomator2","platformName":"Android","deviceName":"device","newCommandTimeout":14},null,{"firstMatch":[{"appium:app":"C:\\Users\\Elvedin\\eclipse-workspace\\AppiumFramework\\src","appium:automationName":"uiautomator2","appium:deviceName":"device","appium:newCommandTimeout":14,"platformName":"android"}]}]
[debug] [BaseDriver] Event 'newSessionRequested' logged at 1614346210971 (14:30:10 GMT+0100 (centraleuropeisk normaltid))
[Appium] Appium v1.20.2 creating new AndroidUiautomator2Driver (v1.61.2) session
[debug] [BaseDriver] W3C capabilities and MJSONWP desired capabilities were provided
[debug] [BaseDriver] Creating session with W3C capabilities: {
[debug] [BaseDriver]   "alwaysMatch": {
[debug] [BaseDriver]     "platformName": "android",
[debug] [BaseDriver]     "appium:app": "C:\\Users\\Elvedin\\eclipse-workspace\\AppiumFramework\\src",
[debug] [BaseDriver]     "appium:automationName": "uiautomator2",
[debug] [BaseDriver]     "appium:deviceName": "device",
[debug] [BaseDriver]     "appium:newCommandTimeout": 14
[debug] [BaseDriver]   },
[debug] [BaseDriver]   "firstMatch": [
[debug] [BaseDriver]     {}
[debug] [BaseDriver]   ]
[debug] [BaseDriver] }
[BaseDriver] Session created with session id: 210de100-ae52-494e-9efd-b449c93d0142
[BaseDriver] Using local app 'C:\Users\Elvedin\eclipse-workspace\AppiumFramework\src'
[debug] [UiAutomator2] Deleting UiAutomator2 session
[debug] [BaseDriver] Event 'newSessionStarted' logged at 1614346210995 (14:30:10 GMT+0100 (centraleuropeisk normaltid))
[debug] [W3C] Encountered internal error running command: Error: New app path 'C:\Users\Elvedin\eclipse-workspace\AppiumFramework\src' did not have extensions: .apk,.apks
[debug] [W3C]     at verifyAppExtension (C:\Users\Elvedin\AppData\Roaming\npm\node_modules\appium\node_modules\appium-base-driver\lib\basedriver\helpers.js:120:9)
[debug] [W3C]     at C:\Users\Elvedin\AppData\Roaming\npm\node_modules\appium\node_modules\appium-base-driver\lib\basedriver\helpers.js:269:5
[HTTP] <-- POST /wd/hub/session 500 30 ms - 785
[HTTP]
[Appium] Received SIGINT - shutting down
[debug] [Appium] There are no active sessions for cleanup
[HTTP] Waiting until the server is closed
[HTTP] Received server close event

src path folder
main class
ecommerce_tc_4 class
global.properties file

A: check capabilities in documentation. Specify with app - absolute path to .apk file: /abs/path/to/my.apk. There are no specified .apk file in your code: C:\\Users\\Elvedin\\eclipse-workspace\\AppiumFramework\\src


text:
Q: How to perform a map operator inside a ngrx's affect? I would like to perform a mapping operator on a given string property in order to make it a Date object, because the FooModel is being sent with the format of { "id": 1, "start": "2020-12-15T16:00:00.000Z" }
export interface FooModel {
  id: number;
  start: string;
}

export class FoosService {
  constructor(private http: HttpClient) {}

  all() {
    return this.http.get<FooModel[]>(BASE_URL);
  }
}

@Injectable()
export class FoosApiEffects {
  constructor(private foosService: FoosService, private actions$: Actions) {}

  loadFoos$ = createEffect(() =>
    this.actions$.pipe(
      ofType(FoosPageActions.enter),
      exhaustMap(() =>
        this.foosService
          .all()
          .pipe(map(foos => FoosApiActions.foosLoaded({ foos })))
      )
    )
  );
}

This is works as expected but when I'm trying to map the foos in odrer to get the start property as Date object like:
foos.map((foo) => foo.start = new Date(foo.start)

inside the affects:
  loadFoos$ = createEffect(() =>
    this.actions$.pipe(
      ofType(FoosPageActions.enter),
      exhaustMap(() =>
        this.foosService
          .all()
          .pipe(map(foos => {
            return FoosApiActions.foosLoaded({ foos.map((foo) => foo.start = new Date(foo.start) }
          )
        }))
      )
    )
  );

I'm getting an error of:

Argument of type '{ foos: FooModel[]; "": any; }' is not assignable to
parameter of type '{ foos: FooModel[]; }'.   Object literal may only
specify known properties, and '(Missing)' does not exist in type '{
foos: FooModel[]; }'.

What is the correct way to use the property mapper inside the affect?


text:
Q: Data from other controller to home controller MVC5 So, I have the Home view and the Homecontroller. Now I want to populate data from a other view called Calendar (which also has a controller: CalendarController) in the Homecontroller view.
I've tried this already:
@model IEnumerable<GJL.Models.Calendar>
                @foreach (var item in Model)
                {

                                @Html.DisplayFor(modelItem => item.Dag)
                                @Html.DisplayFor(modelItem => item.Maand)

                                @Html.DisplayFor(modelItem => item.Tijd)

@Html.DisplayFor(modelItem => item.Titel)

                 }

But it gives me a NullReferenceException. System.Web.Mvc.WebViewPage.Model.get returned null.
Why is this? I hope someone can help me. Thanks in advance.

A: If I understand what you need exactly.But I think this info will help you. As I understood you need to pass data one controller to another controller and there's various way to do so...
You can use session like this way
Session["your_variable_name"] = your_value;

Or you can redirect controller with the value
return RedirectToAction("Index", "Nome", new{ your_variable_name: your_value})

or you can use tempdata also
TempData["your_variable_name"] = "your_value";


text:
Q: Count comments to each recension? I need someone to help me with this problem. My head doesn't want to think straight today.
So, i have a table named "recensions", and another named "comments". In each table, i have a column named "amne_id". This would make so i could connect the comments to the correct recension.
Now, on my first page, i simply get all the recensions with the code:
$rec = $this->db->get('recensions');

What i want is to count how many comments each recension has. But i have no idea how. I guess i maybe should use JOIN and num_rows()?
Please ask if you dont understand, so i can explain better.
Have a nice day!

A: $this->db->select('COUNT(*) as count, recensions.anme_id as recension_id')
->from('recensions')
->join('comments','recensions.anme_id = comments.anme_id','left')
->group_by('anme_id');
$result = $this->db->get();

Should give you the recensions id and the comment count for that id.
then loop:
foreach($result->result() as $row){
    echo "Recension id $row->recension_id has $row->count comments<br />";
}

A: I don't know about the database connector you are using, but in pure SQL (assuming the connection recensions.id=comments.anme_id connection), try this:
SELECT COUNT(comments.id), anme_id
FROM recensions
LEFT JOIN comments on comments.anme_id=recensions.id
GROUP BY anme_id

A: Like this??
$sql = mysql_query("SELECT * FROM recensions");
while($row = mysql_fetch_array($sql)){
$amne_id = $row{"amne_id"};
$sql2 = mysql_query("SELECT * FROM comments WHERE amne_id='$amne_id'");
$total_comments = mysql_num_rows($sql2);
echo $total_comments;
}


text:
Q: Setting up a real time dashboard/visualization of an existing Kafka ETL pipeline using Docker containers I after advice, recommendations or suggestions for setting up a real time dashboard/visualization of an existing Dockerized ETL pipeline using Kafka. The ETL consists of the following:
Extraction Service - Producer/Subscriber
Transformation Service - Producer/Subscriber
Load Service - Producer/Subscriber
Orchestration Service - Producer/Subscriber
Reporting Service - Subscriber
confluentinc/cp-enterprise-kafka
confluentinc/cp-zookeeper
provectuslabs/kafka-ui
All of these are Docker containers and are spun up together. I now need to be able to visualize the workflow of data through this process and I am not entirely sure where I should start of what would be the best approach.
So requirements are:

*

*Visualization must be in real time

*Visualization must be read only

*No user interaction required to update the page data

*Must be open source software
So I need to be able to query Topics and Topic Messages to get the data to display and also need someway of storing/tracking progress so I am guessing that I will some persistence mechanism or database to write to?
I have tried searching here and Googling elsewhere but it just adds to my confusion as I dont know where to start or what the most appropriate stack I should be looking at using.
I have heard mention that Kafka has a Stream-API would be something that that would be helpful to me?
For the realtime updates I need to use some sort of push notification, either Websockets or SignalR?
Does anyone know of any GIT repo's or tutorial sites they could point me to give me a foot up?
I am not looking for anybody to give me a ready made solution as I want to do the work myself but I could really just do with a shove in the right direction or a kick-start project if such a thing exists?


text:
Q: Getting "Could not find a version of package .." in composer inspite of having tags in Github branch of package I am learning on how to upload a package on packagist.org. I created a github repository for testing with composer.json file -
https://github.com/perials/check
 and a composer package using this github repository - https://packagist.org/packages/perials/check
When I try to install this package using composer require perials/check I get below error
[InvalidArgumentException]
Could not find a version of package perials/check matching your minimum-stability (stable). Require it with an explicit version constraint allowing its desired stability.

From what I read in other related questions on SO this error occurs if there are no stable releases of github branch. But thing is that I already have some releases.
I also tried composer require perials/check:dev-master and composer require perials/check:7.1.0 but then I get below error
[InvalidArgumentException]
Could not find package perials/check.

Did you mean this?
perials/check

A: It was an issue with Singapore mirror for the packagist metadata. Now it should be resolved. https://github.com/composer/composer/issues/8347#issuecomment-537176755
If still not solve your issue please add "minimum-stability": "dev" in your composer.json
{
    "name": "perials/check",
    "description": "Package for testing packagist",
    "license": "MIT",
    "authors": [
        {
            "name": "Perials",
            "email": "info@perials.com"
        }
    ],
    "autoload": {
        "psr-4": {"Abc\\": "src/xyz"}
    },
    "require": {},
    "minimum-stability": "dev"
}

A: I am also learning how to create packages and have the same problem, but in my case I created a v1.0.0 tag for my package and that solves the problem.

A: You can accept no stable version packages. See composer in docs (https://getcomposer.org/doc/04-schema.md#package-links).
Paste piece here for convinience:

You can apply them to a constraint, or apply them to an empty constraint if you want to allow unstable packages of a dependency for example.

composer.json:
{
    "require": {
        "monolog/monolog": "1.0.*@beta",
        "acme/foo": "@dev"
    }
}

In your case you would do:
{
    "require": {
        "perials/check": "7.1.0@dev"
    }
}

and then run rm composer.lock; composer install.


text:
Q: The above query will not pull the information from the database $read = "SELECT * FROM elmtree
WHERE id ='$getid' AND
INNER JOIN elmtree_users ON elmtree.userid = elmtree_users.id";

The above query will not pull the information from the database to publish to the website.
Im trying to pull the item from the database with the $getid but also join the item id with the userid who uploaded it. Then using a while loop to print out the item to screen.
Any help would be greatly appreciated.

A: The SQL syntax you show isn't correct. A join clause describes which tables will be available for the rest of the query; all tables you mention need to be part of the 'FROM' clause, so that is where the 'JOIN' also belongs.
SELECT *
FROM elmtree
    INNER JOIN elmtree_users ON elmtree.userid = elmtree_users.id
WHERE id ='$getid'

A: Your SQL query was not correctly written. The AND is not used in joining tables and the WHERE statement should be after the JOIN.
Try the following:
$read = "SELECT * FROM elmtree INNER JOIN elmtree_users ON(elmtree.userid = elmtree_users.id) WHERE elmtree.id ='$getid'";

UPDATE
Could you try the following in your code (replacing $this->database with your database variable) and post the result:
if ($result = $conn->query($read)) {
    while ($row = $result->fetch_assoc()) {
        ...
    }
} else {
    throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}

A: $read = "SELECT * FROM elmtree INNER JOIN elmtree_users ON(elmtree.userid = elmtree_users.id) WHERE elmtree.itemid ='$getid'
Big thanks to Omari Celestine to finding the answer to the problem!


text:
Q: simulate x percentage of missing and error in data in r I would like to perform two things to my fairly large data set about 10 K x 50 K . The following is smaller set of 200 x 10000.
First I want to generate 5% missing values, which perhaps simple and can be done with simple trick:
# dummy data
set.seed(123)
# matrix of X variable
xmat <- matrix(sample(0:4, 2000000, replace = TRUE), ncol = 10000)
colnames(xmat) <- paste ("M", 1:10000, sep ="")
rownames(xmat) <- paste("sample", 1:200, sep = "")

Generate missing values at 5% random places in the data.
N <- 2000000*0.05 # 5% random missing values
inds_miss <- round ( runif(N, 1, length(xmat)) )
xmat[inds_miss] <- NA

Now I would like to generate error (means that different value than what I have in above matrix. The above matrix have values of 0 to 4. So what I would like to do:
(1)  I would like to replace x value with another value that is not x (for example 0 can be replaced by a random sample of that is not 0 (i.e. 1 or 2 or 3 or 4), similarly 1 can be replaced by that is not 1 (i.e. 0 or 2 or 3 or 4). Indicies where random value can be replaced can be simply done with:
  inds_err <- round ( runif(N, 1, length(xmat)) )

If I randomly sample 0:4 values and replace with the indices, this will sometime replace same value with same value ( 0 with 0, 1 with 1 and so on)  without creating error.
errorg <- sample(0:4, length(inds_err), replace = TRUE)
xmat[inds_err] <- errorg

(2) So what I would like to do is introduce error in xmat with missing values, However I do not want NA generated in above step be replaced with a value (0 to 4). So ind_err should not be member of vector inds_miss.
So summary rules :
(1) The missing values should not be replaced with error values
(2) The existing value must be replaced with different value (which is definition of error here)- in random sampling this 1/5 probability of doing this.
How can it be done ? I need faster solution that can be used in my large dataset.

A: You can try this:
    inds_err <- setdiff(round ( runif(2*N, 1, length(xmat)) ),inds_miss)[1:N]
    xmat[inds_err]<-(xmat[inds_err]+sample(4,N,replace=TRUE))%%5

With the first line you generate 2*N possible error indices, than you subtract the ones belonging to inds_miss and then take the first N. With the second line you add to the values you want to change a random number between 1 and 4 and than take the mod 5. In this way you are sure that the new value will be different from the original and stil in the 0-4 range.

A: Here's an if/else solution that could work for you.  It is a for loop so not sure if that will be okay for you.  Possibly vectorize it is some way to make it faster.
# vector of options
vec <- 0:4

# simple logic based solution if just don't want NA changed
for(i in 1:length(inds_err){
  if(is.na(xmat[i])){
    next
  }else{
    xmat[i] <- sample(vec[-xmat[i]], 1)
  }
}


text:
Q: Access results from google places api ios for auto completion I am using this method to get suggestions and i need to show them in tableview:
- (void)placeAutocomplete:(NSString *)autoCompleteString {
    [self.autoCompleteSuggestionsList removeAllObjects];
    GMSAutocompleteFilter *filter = [[GMSAutocompleteFilter alloc] init];
    filter.type = kGMSPlacesAutocompleteTypeFilterCity;

    [_placesClient autocompleteQuery:(NSString *)autoCompleteString
                              bounds:nil
                              filter:filter
                            callback:^(NSArray *results, NSError *error) {
                                if (error != nil) {
                                    NSLog(@"Autocomplete error %@", [error localizedDescription]);
                                    return;
                                }

                                for (GMSAutocompletePrediction* result in results) {
                                    //NSLog(@"Result '%@' with placeID %@", result.attributedFullText.string, result.placeID);
                                    //NSRange autoCompleteRange = [result.attributedFullText.string rangeOfString:autoCompleteString];
                                    //if (autoCompleteRange.location == 0) {
                                    //NSString *stringNow = [NSString stringWithFormat:@"%@",result.attributedFullText.string];
                                    [self.autoCompleteSuggestionsList addObject:result.attributedFullText.string];
                                        //NSLog(@"test : %@",stringNow);
                                    //NSLog(@"%@",self.autoCompleteSuggestionsList);
                                    //}
                                }
                            }];
    [self.autocompleteTableView reloadData];
    NSLog(@"%@",self.autoCompleteSuggestionsList);
}

but I cannot access the results outside of the autocompleteQuery method
when logged it shows correctly inside the method but not outside ,
I am using mutable array to access it but i shows correctly inside but not outside.
I don't need suggestions for using any third party autocomplete pod .
I am getting the result i just need them to be accessed from the method so that it could be accessible to show the tableview as well

A: You have to reload the data inside the block.

Reason for doing this is simple because block is run in different thread so when it complete the execution it come in callback block with main thread thats why we need to reload table in block.

- (void)placeAutocomplete:(NSString *)autoCompleteString {
    [self.autoCompleteSuggestionsList removeAllObjects];
    GMSAutocompleteFilter *filter = [[GMSAutocompleteFilter alloc] init];
    filter.type = kGMSPlacesAutocompleteTypeFilterCity;

    [_placesClient autocompleteQuery:(NSString *)autoCompleteString
                              bounds:nil
                              filter:filter
                            callback:^(NSArray *results, NSError *error) {
                                if (error != nil) {
                                    NSLog(@"Autocomplete error %@", [error localizedDescription]);
                                    return;
                                }

                                for (GMSAutocompletePrediction* result in results) {

                                    [self.autoCompleteSuggestionsList addObject:result.attributedFullText.string];

                                }
                                [self.autocompleteTableView reloadData];
                            }];
    NSLog(@"%@",self.autoCompleteSuggestionsList);
}


text:
Q: How to fetch meta_value and meta_key in matrix after ajax request by post_id Well, I have 2 custom post types:
A = Properties
B = Property Owners
Inside CPT Properties, I was created a Meta Box to:

*

*Search a registred Owner (CPT) by VAT number (CPF in Brazil)

*Relate Owner with de Property

I have the CPTs and Meta Boxes. The Meta Boxe "Search Onwer" it is making the ajax request to the server, using this query
function getOwner($post){

    global $wpdb;
    $cpfcode = $wpdb->escape($post['cpfCode']);

    $query =    'SELECT
                    post_id,
                    meta_key,
                    meta_value
                FROM
                    wp_postmeta
                WHERE
                    post_id = (SELECT post_id FROM wp_postmeta WHERE meta_value = "'.$cpfcode.'");';

    $keys = $wpdb->get_results($query, OBJECT);

    if ($keys) { return $keys; } else { echo "error"; };
    exit();
}

and returning an json object with the meta_values and meta_keys like this:
[
    {
        "post_id"   :"112",
        "meta_key"  :"owner_vat",
        "meta_value":"123.456.789-10"
    },

    {
        "post_id"   :"112",
        "meta_key"  :"owner_name",
        "meta_value":"Jonh Doe"
    },

    {
        "post_id"   :"112",
        "meta_key"  :"owner_city",
        "meta_value":"Rio de Janeiro"
    },
]

Now, I need, using jQuery, insert this values in some fields. The problem is do the each or the for, I don't know.

A: I'm not 100% what you are asking for but here is the code for navigating through a JSON request. The code below assumes you have input fields with the same name as your meta_fields.
<input id="owner_vat" type="text">
<input id="owner_name" type="text">
<input id="owner_city" type="text">

success: function(response){
    $.each(response, function(index, value) {
        $('#'+value['meta_key']).val(value['meta_value']);
    });
}

Hope that helps

A: Solved with collaboration of Thiago Lewin:
function ajx_cpf(cpfCode){

    var cpf_data = {
                    'action': 'Load_owner',
                    'cpfCode': cpfCode
                    };

    jQuery.ajax({
                type: 'POST',
                url: '<?php echo get_settings('home')?>/wp-admin/admin-ajax.php',
                data: cpf_data,

                success: function(data, textStatus, XMLHttpRequest){
                    loadOwner_sel(data);
                },

                error: function(MLHttpRequest, textStatus, errorThrown){
                    alert(errorThrown);
                }
    });
}

function loadOwner_sel(dta) {
    var
        array = JSON.parse(dta),
        obj = {};

        jQuery.each(array, function(index, item) {
            obj[item.meta_key] = item.meta_value;
        });

    document.getElementById('owner_vat').value = post_id;
    document.getElementById('owner_name').value = obj.owner_name;
    document.getElementById('owner_city').value = post_id;
}


text:
Q: Sample use case to test Async Storage with Jest-expo? I have replicated an example to understand the testing of Mock-async-storage for reactjs. Any suggestions for a different approach of testing are welcome. I tried to replicate the use case from this stack overflow page : How to test Async Storage with Jest? but I couldn't figure out how that would fit for my sample case. So I tried the below npm module https://github.com/devmetal/mock-async-storage, but that didn't help either.
Code written in Example.test.js
import  AsyncStorage  from '@react-native-community/async-storage';

beforeEach(() => {
    AsyncStorage.clear();
    // console.log(`After the data is being reset :`)
    // console.log(AsyncStorage)
});

it('can read asyncstorage', async () => {

    await AsyncStorage.setItem('username', 'testUser')
    let username = await AsyncStorage.getItem('username')
    // console.log(`After the data is being set :`)
    // console.log(AsyncStorage)
    expect(username).toBe('testUser')
});

Code in jest.config.js file :
module.exports = {
    setupFilesAfterEnv: [
      './setup-tests.js',
    ],
  };

Code in setup-tests.js
import MockAsyncStorage from 'mock-async-storage';

const mockImpl = new MockAsyncStorage();
jest.mock('@react-native-community/async-storage', () => mockImpl);

Created the mocks folder in root directory and then created @react-native-community folder in it. Then created at async-storage.js file with the following code :
export default from '@react-native-community/async-storage/jest/async-storage-mock'

I am using jest-expo for testing.
The output of the above test case is :

A: Detailed Solution for the above:
Install the module using the command :
Run this command from the root directory of the project.
npm install --save mock-async-storage

In the project root directory create __mocks__\@react-native-community folder. Inside that create a file async-storage.js.
Code in async-storage.js
export default from '@react-native-community/async-storage/jest/async-storage-mock'

Inside package.json configure the jest as follows:
"jest": {
    "preset": "jest-expo",
    "transformIgnorePatterns" : ["/node_modules/@react-native-community/async-storage/(?!(lib))"]
  },

Here I am using jest-expo for testing. If you are using jest then the preset value will be jest not jest-expo.
In the project root directory create a file called jest.config.js
Configuration inside the  jest.config.js file:
module.exports = {
    setupFilesAfterEnv: [
      './setup-tests.js',
    ],
  };

In the project root directory create a file called setup-tests.js. Code in this file is :
import MockAsyncStorage from 'mock-async-storage';

const mockImpl = new MockAsyncStorage();
jest.mock('@react-native-community/async-storage', () => mockImpl);

In the project root directory create the test file. Here I am calling it Example.test.js.
import  AsyncStorage  from '@react-native-community/async-storage';

beforeEach(() => {
    AsyncStorage.clear();
    // console.log(`After the data is being reset :`)
    // console.log(AsyncStorage)
});

it('can read asyncstorage', async () => {

    await AsyncStorage.setItem('username', 'testUser')
    let usernameValue = await AsyncStorage.getItem('username')
    // console.log(`After the data is being set :`)
    // console.log(AsyncStorage)
    expect(usernameValue).toBe('testUser')
});

Here setting the value of username to testUser using AsyncStorage.setItem. Then fetching the value using getItem function.
The test case is to compare whether the usernameValue is equal to testUser.
If yes then the test case passes else the test case will fail.
Using beforeEach so that every time a test case is being run Asyncstorage is being cleared and is empty.
If needed one can check what is present in Asyncstorage using console.log
Run the command yarn test to run the tests. The output is:


text:
Q: Compile Swift script with static Swift core library I would like to execute a compiled Swift script on a computer which doesn't have Swift installed. But it seems by default the Swift Compiler uses dynamically linked libraries.
Is it possible to include these libraries statically?
Steps to reproduce using Docker:
user@host:~# docker run -it swiftdocker/swift
root@16974ad4edb1:/# swift --version
Swift version 3.0-dev (LLVM dffa09ffd8, Clang 9f0d189820, Swift 1c720b8f84)
Target: x86_64-unknown-linux-gnu
root@16974ad4edb1:/# echo 'print("Hello, world")' > helloworld.swift
root@16974ad4edb1:/# swiftc helloworld.swift
root@16974ad4edb1:/# ./helloworld
Hello, world
root@16974ad4edb1:/# exit
exit
user@host:~# docker cp 16974ad4edb1:/helloworld .
user@host:~# file helloworld
helloworld: ELF 64-bit LSB  executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=c4d42f6185b3d53ecf2dfb0c386263c17cb34675, not stripped
user@host:~# ./helloworld
./helloworld: error while loading shared libraries: libswiftCore.so: cannot open shared object file: No such file or directory

A: The argument -static-stdlib must be used:
swiftc -static-stdlib helloworld.swift

For swift build, pass it to -Xswiftc:
swift build -Xswiftc -static-stdlib

If you get an ICU dependency error, install it:
apt-get install libicu-dev


text:
Q: How to export image filenames from Wordpress database? I have a Wordpress install that's using about 10,000 images. I'd like to export all filenames used in Wordpress to a file, filenames.log
filenames.log would look like this:
car.jpg
boat.jpg
milf.jpg
car2.jpg
other.jpg
etc...
The reason I'm doing this is that I have orphaned images in /uploads, and I want to run a delete operation and exclude these filenames that are actually in use.
What command could I run to generate such a file?
Thanks!

A: Pure MySQL, be sure to correct it for your desired filepath /tmp/filenames.log: (Thanks Phil for the select query)
"SELECT meta_value AS filename
FROM wp_posts p, wp_postmeta pm
WHERE p.id = pm.post_id
AND p.post_type = 'attachment'
AND meta_key = '_wp_attached_file'
INTO OUTFILE '/tmp/filenames.log'
LINES TERMINATED BY '\n';"

A: Looking at the Wordpress ERD and googling a little, attachments are in the wp_posts table, as follows:
select *
from wp_posts
where post_type = 'attachment';

Join with wp_postmeta, which is a key=>value store, on meta_key = '_wp_attached_file' to get the filename (meta_value).
So we end up with:
select meta_value as filename
from wp_posts p, wp_postmeta pm
where  p.id = pm.post_id
and    p.post_type = 'attachment';

Obviously you can filter meta_value in the WHERE clause to just return .jpgs, or whatever.


text:
Q: How to ensure CoordinatorLayout children do not overlap I am using bottom app bar inside the coordinator layout. the rest of the content is coming from a fragment. the fragment content is being covered by the bottom app bar
Because I am using bottomAppBar it has to be inside a CoordintorLayout and all the children have to be inside of it as well. All layout above the BottomAppBar should fill the space reminding, but if I do so the views at the bottoms get covered. how do I ensure the view do not overlap with BottomAppBar
<androidx.drawerlayout.widget.DrawerLayout
android:id="@+id/drawerLayout_main"
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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".main.MainActivity">

<androidx.coordinatorlayout.widget.CoordinatorLayout
    android:id="@+id/coordinatorLayout"
    android:layout_width="0dp"
    android:layout_height="wrap_content">

    </androidx.constraintlayout.widget.ConstraintLayout>

    <fragment
        android:id="@+id/fragment_main_navHost"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        android:layout_gravity="top"
        app:navGraph="@navigation/nav_graph"/>

    <com.google.android.material.bottomappbar.BottomAppBar
        android:id="@+id/bottomAppBar_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        app:fabAlignmentMode="end"
        app:fabCradleMargin="4dp"
        app:hideOnScroll="true"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

<com.google.android.material.navigation.NavigationView
    android:id="@+id/navView_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:headerLayout="@layout/nav_header_layout"
    app:menu="@menu/main_navigation"/>

What I need is to ensure whatever content is replacing the fragment should not be covered by the bottom app bar and it should use all the white space not being used the bottom app bar. I another world the content should be above it while using rest the white space and still be inside the coordinator layout.

A: Just add margin to your fragment container :
  <fragment
    android:id="@+id/fragment_main_navHost"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="{bottom_navigation_height}"
    android:layout_marginTop="{tool_bar_height}"
    app:defaultNavHost="true"
    android:layout_gravity="top"
    app:navGraph="@navigation/nav_graph"/>

A: According to the CoordinatorLayout Documentation, edges where a View in CoordinatorLayout expects to overlap with another View can be specified with layout_dodgeInsetEdges="bottom". So if your fragment is being overlapped by your BottomAppBar, you add this attribute to the fragment. You must also specify that you wish to dodge the BottomAppBar. This is done by adding layout_insetEdge="bottom" to it.
To be more specific for your case, do the following:
Add app:layout_dodgeInsetEdges="bottom" to the <fragment> like so:
<fragment
    app:layout_dodgeInsetEdges="bottom" <--- THIS
    android:id="@+id/fragment_main_navHost"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:defaultNavHost="true"
    android:layout_gravity="top"
    app:navGraph="@navigation/nav_graph"/>

Add app:layout_insetEdge="bottom" to BottomAppBar. (Note that this step my be unnecessary if BottomAppBar applies this inset by default so try also without it):
<com.google.android.material.bottomappbar.BottomAppBar
    app:layout_insetEdge="bottom" <---- THIS
    android:id="@+id/bottomAppBar_main"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    app:fabAlignmentMode="end"
    app:fabCradleMargin="4dp"
    app:hideOnScroll="true"/>

There's a really good article that shows examples with animated giffs that I highly recommend you to check out.

A: Try adding app:layout_behavior="@string/appbar_scrolling_view_behavior" to the fragment.