text:
Q: Hosts file not honoring the dev sites mapping in OSX Yosemite This issue has been affecting my multi-site development since months and on. My Yosemite OSX hosts file (located at /etc/hosts never honors these sites I put in at the top:

192.168.10.10   blackbird.dev
192.168.10.10   saveeo.dev

What might be wrong? To help the answerers understand the situation, I've done the following:

*

*Flushed the DNS cache

*My Homestead.yaml file looks like this below [see A]

*Homestead destroyed and ran again (nope, no difference)

*Computer restarted and ran again (nope, no difference)

*If I go 192.168.10.10, one site opens up, the first one listed in .yaml

*If I do saveeo.dev or blackbird.dev, this shows up [see B]

*If I ping from my local machine, I get this [see C]

*If I ping from within the box (doing homestead ssh) and then I see this. [ see D]

What is happening, help me out. I've used all my knowledge to make this work, but I just don't know what is causing this. I am not able to access my dev sites through the browser like app.dev and app2.dev. Quite frustrating.
Appendix A
---
ip: "192.168.10.10"
memory: 2048
cpus: 1

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:
    - map: /Users/aligajani/Dropbox/Vinkk_Software
      to:  /home/vagrant/Vinkk_Software

    - map: /Users/aligajani/Dropbox/hackathon
      to:  /home/vagrant/hackathon

sites:
    - map: blackbird.dev
      to:  /home/vagrant/Vinkk_Software/blackbird/public

    - map: saveeo.dev
      to:  /home/vagrant/hackathon/saveeo/public

databases:
    - homestead
    - saveeo

variables:
    - key: APP_ENV
      value: local

Appendix B
This webpage is not available
ERR_CONNECTION_TIMED_OUT
Appendix C
PING saveeo.dev (127.0.53.53): 56 data bytes
Request timeout for icmp_seq 0
Request timeout for icmp_seq 1

PING blackbird.dev (127.0.53.53): 56 data bytes
Request timeout for icmp_seq 0
Request timeout for icmp_seq 1

Appendix D
ping saveeo.dev
PING saveeo.dev (127.0.53.53) 56(84) bytes of data.
64 bytes from 127.0.53.53: icmp_seq=1 ttl=64 time=0.027 ms
64 bytes from 127.0.53.53: icmp_seq=2 ttl=64 time=0.055 ms

ping blackbird.dev
PING blackbird.dev (127.0.53.53) 56(84) bytes of data.
64 bytes from 127.0.53.53: icmp_seq=1 ttl=64 time=0.019 ms
64 bytes from 127.0.53.53: icmp_seq=2 ttl=64 time=0.040 ms

A: My hosts file kept on being ignored after I edited in text edit. I tried several ways to fix the line endings, added IPv6 entries to the existing IPv4 entries with no success. The only solution that worked is using this free GUI plugin to edit hosts file.
https://github.com/specialunderwear/Hosts.prefpane/blob/master/README.mdown

A: It sounds like an issue with your mac dns resolution and nothing to do with vagrant.
Check out https://apple.stackexchange.com/questions/158117/os-x-10-10-1-etc-hosts-private-etc-hosts-file-is-being-ignored-and-not-resol


text:
Q: return -1 in C? I was given code and I don't understand why the function returns -1. I feel that it is a typo. The code is given below:
int equilibrium(int array[], int size)
{
    int sum = 0;
    int left_sum = 0;
    int i;
    for (i = 0; i < size; i++) {
        sum += array[i];
    }
    for (i = 0; i < size; i++) {
        if (array[i] == sum - 2 * left_sum) {
            return i;
        }
        left_sum += array[i];
    }
    return -1;
}

A: It looks like it uses -1 to mean "not found", it looks like a search function trying to find an index i where the condition in the innermost if is true.

A: equilibrium returns the equilibrium point of an array as an index in the array. When the array doesn't have an equilibrium point, the function returns -1 instead. It is used as followed:
int equilibrium_idx = equilibrium(somearrayvalue, somesize);

if( equilibrium_idx == -1 )
    printf("It isn't balanced\n");
else
    printf("The equilibrium index is %d\n", equilibrium_idx);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can we build one visual studio project from commandline I have a visual studio c test project (Helloworld project) created from VS 2008 professional edition and it contains VC++ project file.
May I know how can I build the same project from commandline(cmd) so that I wont need to take the VS GUI for building the same.
I am pretty comfused that it may need some make file to be created but I cannot see any option to create the ame in the visual studio said edition.
any suggestions or helps are much appreciated.

A: You can drive the solution or project build using vcbuild or devenv.  An example of the latter:
devenv Solution.sln /build /project Project.vcproj /projectconfig "Debug|Win32"

(You can run vcbuild /? and devenv /? to find their commonly used options.)
Note that in Visual Studio 2010 and later, Visual C++ projects use MSBuild, so projects can be built on the command line using msbuild, just like any other MSBuild projects (C#, VB, etc.).  The older VCBuild, used in previous versions of Visual Studio, is no longer supported.

A: This is typically done via nmake. VS60 allowed to export a makefile and use it with nmake(Microsoft's make utility) . (After than we started writing our own makefile).
http://msdn.microsoft.com/en-us/library/aa233950(v=vs.60).aspx
hopefully newer Visual Studio will have similar or better options.


text:
Q: julia incorrect type when subtyping parametric supertype I have an abstract type
abstract type PointND{N<:Integer, T<:Number} end

When I subtype it, setting N=1
struct Point1D{T} <: PointND{1, T}
    x::T
end

Julia throws error
ERROR: TypeError: in PointND, in N, expected N<:Integer, got Int64

even though (typeof(1)<:Integer) == true.
This happens even when N is of type Number. Why doesn't this work?

A: Your N here is not a subtype of Integer, but an instance of a subtype of Integer. If you actually try 1 <: Integer in the REPL, it will throw an error. So PointND will only accept types that subtype Integer, like Int or UInt, but not instances of subtypes of Integer like 1 or 0xff. The solution here is actually just not to restrict the type of N at all, and document clearly instead that N should always be an integer. There isn't currently any way to restrict the type of instances of bit types in type parameters.


text:
Q: How to solve $x'(t)=\frac{x+t}{2t-x}$? I wish to solve $x'(t)=\frac{x+t}{2t-x}$ with the initial condition
$x(1)=0$. I noted that $x'(t)=f(\frac{x}{t})$ where $f(y)=\frac{y+1}{2-y}$
so I denoted $y(t)=\frac{x(t)}{t}$ and got that $y'(t)=\frac{f(y)-y}{t}$
so I can write something like $\frac{dy}{dt}=\frac{f(y)-y}{t}$ so
$\frac{dy}{f(y)-y}=\frac{dt}{t}$ .
Here I am a bit stuck, I know I should do something like take integrals
on both sides, but I am having trouble with the initial condition.
In this exercise I can leave integrals in the answer so I would like
to know how to get the solution with the integral, I think this requires
to calculate the boundaries of some integral (maybe of $\frac{f(y)-y}{t}$
?)
How can I continue to get the solution with integral that satisfies
the initial condition ?
Help is appriciated!

A: Your differential equation is homogenous of order one. You did it right finding $\frac{dy}{dt}=\frac{f(y)-y}{t}$. So you can integrate of both sides in last equation till your solution is achieved respect to $y(t)$ and $t$. Then you can substitute $x(t)=y(t)t$ in your solution and then apply the initial condition. I hope it help. :)


text:
Q: How to post image instead of URL in microsoft azure analyze image API using javascript ? I am doing the analyzing of image using microsoft azure API using this code https://learn.microsoft.com/en-in/azure/cognitive-services/computer-vision/quickstarts/javascript#AnalyzeImage . But it takes a URL as input.
I want to upload an image from local machine instead of URL.
Help needed.

A:

         $(document).ready(function () {

             //Step 1. Hook into the myFile input file change event

            var subKey = '[your key]';

             function makeblob(b64Data, contentType, sliceSize) {
                 contentType = contentType || '';
                 sliceSize = sliceSize || 512;

                 var byteCharacters = atob(b64Data);
                 var byteArrays = [];

                 for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
                     var slice = byteCharacters.slice(offset, offset + sliceSize);

                     var byteNumbers = new Array(slice.length);
                     for (var i = 0; i < slice.length; i++) {
                         byteNumbers[i] = slice.charCodeAt(i);
                     }

                     var byteArray = new Uint8Array(byteNumbers);

                     byteArrays.push(byteArray);
                 }

                 var blob = new Blob(byteArrays, { type: contentType });
                 return blob;
             }

             $('#myImage').change(function () {

                 //Load everything in
                 var reader = new FileReader();
                 var file = this.files[0];
               //  var mb = $(this).serializeObject();
                 console.log(file);
                 reader.onload=  function() {
                     var resultData = this.result;

                 //     console.log(resultData);

                     resultData = resultData.split(',')[1];

                     processImage(resultData);
                    // processImage(mb);
                 };

                 reader.readAsDataURL(file);

             });

             processImage = function(binaryImage) {

              //   var uriBase = "https://westcentralus.api.cognitive.microsoft.com/vision/v1.0/analyze";
                 var uriBase = "https://eastus.api.cognitive.microsoft.com/vision/v1.0/analyze";

                 //    // Request parameters.
                 var params = {
                     "visualFeatures": "Categories,Description,Color",
                     "details": "",
                     "language": "en",
                 };

                 $.ajax({
                     url: "https://eastus.api.cognitive.microsoft.com/vision/v1.0/analyze?visualFeatures=Categories&language=en",

                    method: "POST",
                    type: "POST",
                     beforeSend: function (xhrObj) {
                         xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", subKey);

                     },
                     contentType: "application/octet-stream",
                     mime: "application/octet-stream",
                     data: makeblob(binaryImage, 'image/jpeg'),
                     cache: false,
                     processData: false

                 }) .done(function(data) {
            // Show formatted JSON on webpage.
            $("#responseTextArea").val(JSON.stringify(data, null, 2));
        })

             }
         });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
    <input type="file" id="myImage" />
    <input type="submit" />
    <textarea  type="text" rows="5" cols="50" id="responseTextArea" />
    </form>

A: Assuming you have an html page like
<input type="file" id="myImage" />

the best option might be to
a)convert myImage to a bases64 string
b) then post a blob as the data attribute in ajax call
There was another post similar to post images by using base64 and a blog here:
How to post an image in base64 encoding via .ajax?


text:
Q: Regarding understanding differential geometry I am essentially looking for a book that would hold my hand through basic concepts to more complicated ones. I am coming from physics. I am looking to make some connections with Classical mechanics and or quantum field theory. I have been told that QFT is really just geometry and have only seen a few manifest aspects of that. I must say I am not any kind of expert. I want to be one though. I am looking for a short book.  I also want to be able to understand the whole complex cohomology and homology thing. I am guessing most of you know what I am talking about. Are there any books out there? Again, I am wanting to hold back on rigor and proofs to first get the concepts down well. Any video lecture links would be highly appreciated too.
    I am trying to study them for the next couple of months say three or four. Differential geometry and topology are things I would love to be invisible at. . .  So please help me out. Recommend some books and video links. Feel free to throw any Yang- Mills material at me too. Thanks in advance.

A: I think the books "Topology, Geometry, and Gauge Fields: Foundations" and "Topology, Geometry, and Gauge Fields: Interactions" are exactly what you're looking for.  They are not short, but you don't actually want a short book anyway because the only way to write a short differential geometry book is to give few terse examples and leave all the calculations to the reader.  That's good once you have a foothold but frustrating at first.  Mathematically, the books start with basically nothing and get through:
-Basic differential geometry: manifolds, Lie groups, connections on principal bundles, spin geometry
-Basic algebraic topology: de Rham cohomology, Chern-Weil theory, basic homotopy theory, classification of principal bundles
Physically, it covers the rudiments of gauge theory up through the beginnings of Donaldson theory / Yang-Mills theory ("Foundations") and the beginnings of Seiberg-Witten theory ("Interactions").  It gives tons of detailed examples and exercises throughout, including some examples that you don't often see in textbooks (like the quaternionic Hopf fibration).
To decide if the books are for you, I would recommend just finding a copy of "Foundations" and reading Chapter 0 - it is a bird's eye view of the subject which sets the tone for the rest of the series.

A: Maybe the following books will be helpful:
The Geometry of Physics: An Introduction, by Theodore Frankel.
Geometry, Topology and Physics, by Mikio Nakahara.
For a quick introduction into the subject I would recommend (not physics oriented)
Elementary Differential Geometry, by Andrew Pressley.
And finally, as the geometry of physics (both general relativity and gauge theory) is really a Cartan geometry, the following book (alas, also not physics oriented) is worth to mention:
Cartan for Beginners: Differential Geometry Via Moving Frames and Exterior Differential Systems, by  Thomas A. Ivey and J. M. Landsberg.


text:
Q: How can my apple watch receive notifications if bluetooth is disabled on my iphone? I have an iPhone SE and an Apple Watch series 2.  Just a minute ago my watch got a Skype notification, yet Bluetooth was disabled on my phone.
I thought that the watch had to be connected to the phone to be able to get notifications from apps on the phone.  How was my watch able to receive the notification?  Did it come over wifi?

A: Source.
Your Apple Watch can use both bluetooth and wifi to communicate with the paired iPhone.

To enjoy every feature on your Apple Watch, you need to turn on Wi-Fi
  and Bluetooth on your paired iPhone. Swipe up on your iPhone to open
  Control Center. Then make sure Wi-Fi and Bluetooth are on.
Your Apple Watch uses Wi-Fi and Bluetooth to communicate with your
  paired iPhone, switching between connections as needed:

*

*Your Apple Watch uses Bluetooth when your iPhone is near, which
  conserves power.

*If Bluetooth isn't available, your Apple Watch will
  try to use Wi-Fi. For example, if compatible Wi-Fi is available and
  your iPhone isn't in Bluetooth range, your Apple Watch uses Wi-Fi.


text:
Q: Does php always need to connect? Normally SQL in php always need to execute mysql_connect before doing queries while viewer is opening .php file. Is there a way to connect one time and call php file multiple times without new connection? I would use it to reduce accessing time because script is connecting to remote MySQL server.

A: In stock PHP, no, because PHP is tied closely to the stateless CGI model (even when used as an Apache module, FastCGI process, or ISAPI extension). Under this classic CGI model the process that created the page response is terminated immediately so any database connections made would be closed.
In practice this is not a problem as RDBMSs like MySQL are designed so that opening a new connections is a very quick process (as long as the MySQL server is within a short ping distance of the webserver). Other systems like MSSQL (especially under ASP.NET) make use of "connection pooling" where the actual underlying connection is maintained by the OS or the host process.


text:
Q: MRI ruby memory acccess characteristics during multithreading In some hi-level programming environments (java, dotnet), when accessing same memory from multiple threads, you have to explicitly mark it as volatile or synchrnozied, otherwise you could get stale results from some cache or out-of-order values due to out-of-order execution by CPU or other optimizations.
In MRI ruby for some time native OS threads are used. Each of those threads sometime execute ruby code (I assume, but not sure), even if never truly parallel because of VM lock.
I guess MRI solves this stale/ooo values issue somehow, because there is no volatile construct in ruby language and I never heard of stale value issues.
What guarantees Ruby lang or MRI specifically gives regarding memory access from multiple threads? I would be extremely grateful if someone would point me to any documentation regarding this. Thanks!

A: It sounds like your specific question is if Ruby implicitly provides a memory barrier when switching threads, such that all caching/reordering concerns that occur at a processor level are resolved automatically.
I believe MRI does provide this, as otherwise the GVL would be pointless; why restrict one thread to run at a time if even then they can end up reading/writing stale data? It is difficult to find the precise place where this is provided, but I believe the entry point is via RB_VM_LOCK_ENTER which is called throughout the codebase and which ultimately calls vm_lock_enter. This has code which strongly implies that memory barriers are in place:
        // lock
        rb_native_mutex_lock(&vm->ractor.sync.lock);
        VM_ASSERT(vm->ractor.sync.lock_owner == NULL);
        vm->ractor.sync.lock_owner = cr;

        if (!no_barrier) {
            // barrier
            while (vm->ractor.sync.barrier_waiting) {
                unsigned int barrier_cnt = vm->ractor.sync.barrier_cnt;


text:
Q: Posting a link video on facebook using koala I am using the following command to post a video link from youtube into facebook:
client.put_wall_post options[:message].text, {
    :name => "Type O Negative",
    :link => "http://www.youtube.com/watch?v=E67D-ZCuoEw",
    :description => "Type O Negative"} , "me"

It works fine and facebook displays the first thumb for this image which is http://img.youtube.com/vi/E67D-ZCuoEw/1.jpg

But i want the second thumb: http://img.youtube.com/vi/E67D-ZCuoEw/2.jpg

So i pass the :picture argument as follows:
client.put_wall_post options[:message].text, {
    :name => "Type O Negative",
    :link => "http://www.youtube.com/watch?v=E67D-ZCuoEw",
    :picture = > "http://img.youtube.com/vi/E67D-ZCuoEw/2.jpg",
    :description => "Type O Negative"} , "me"

Doing this facebook does not recognizes my link as a embedded video and just shows the thumb with a link to the youtube page.
Any idea what is going on?

A: Have you tried using put_picture from the Koala API?
http://rubydoc.info/github/arsduo/koala/Koala/Facebook/GraphAPIMethods#put_picture-instance_method
Despite its name, it apparently operates just the same for video.
Like you, I have used put_wall_post and it works fine for a basic link, but you might consider using something more specific from the API.

A: Try to use URI like http://www.youtube.com/v/E67D-ZCuoEw instead of http://www.youtube.com/watch?v=E67D-ZCuoEw


text:
Q: Databricks Spark conditional pull from Azure SQL I'm trying to pull data from Azure SQL with Azure Databricks using a sql-spark-connecter. I've installed the Maven library on the cluster and have successfully run this script on Databricks to pull from a sample database:
server_name = "jdbc:sqlserver://(removed).database.windows.net"
database_name = (removed)
url = server_name + ";" + "databaseName=" + database_name + ";"
table_name = "dbo.Test"
username = (removed)
password = (removed)

jdbcDF = spark.read \
        .format("com.microsoft.sqlserver.jdbc.spark") \
        .option("url", url) \
        .option("dbtable", table_name) \
        .option("user", username) \
        .option("password", password) \
        .load()

display(jdbcDF)

However, I want to eventually use this connector to pull from a large table (5 mil+ rows), and want to add a filter to the .read method in order to reduce the amount of rows I need to pull to save processing power and dataframe size. Ideally, I'd also want to pull only specific columns, but rows are the priority.
Looking at the available Pyspark documentation, there doesn't seem to be a generic .filter property, and the sql spark connector documentation doesn't specify an available .option keys that helps in filtering the request either. I am assuming there is not good way to reduce data pulls, but please correct me if there is.
I'll probably drop the unnecessary columns and rows from the dataframe immediately after querying to help with cost and performance. Let me know if there's other ideas to consider!

A: Pass a query that will be executed that contains filter. E.g.
...
...
pushdown_query = "(select * from employees where emp_no < 10008) emp_alias"
df = spark.read.jdbc(url=jdbcUrl, table=pushdown_query,
properties=connectionProperties)
display(df)
...

from https://docs.databricks.com/data/data-sources/sql-databases.html  should help.


text:
Q: Function that counts the occurrences of an element in an array I'm trying to write a function that counts the occurrences of a specific element in an array, specified as a function argument.
Ex: for the array [5,7,12,5,3,3,5], the function countOccurrences(3) would return a value of 2.
Thank you in advance :)

A: You can filter array and return length:

const arr = [5,7,12,5,3,3,5];

const occurences = (array, el) => {
  return array.filter(a => a === el).length
}

const result = occurences(arr, 3);
console.log(result)

A: You could try the following:
const filter = (arr, val) => {
    return arr.filter(item => item === val).length
}


text:
Q: Hide Attribute in product view page if value of attribute = "abc" visit link , search for word " abc" using CTRL + F,
you can see attributes : "Brand" & " charactar"

we gave attribute values as "abc" for lot of attributes.
we want to hide the attribute in product view page if the value ="abc"
we are using following code displaying attributes in product view page :
app/design/frontend/default/em0113/template/catalog/product/view/attributes.phtml
<?php
    $_helper = $this->helper('catalog/output');
    $_product = $this->getProduct()
?>
<?php if($_additional = $this->getAdditionalData()): ?>

<?php $Pro_name =$_product->getName();?>

<?php echo $this->__('Specifications Of '."$Pro_name") ?>

        <col width="25%" />
        <col />

        <?php foreach ($_additional as $_data): ?>

        <?php $_attribute = $_product->getResource()->getAttribute($_data['code']);
       if (!is_null($_product->getData($_attribute->getAttributeCode())) && (trim((string)$_attribute->getFrontend()->getValue($_product)) != '')) { ?>
        <?php if ($_data['code'] == 'gendernew'): ?>

<?php echo $this->__('') ?>

         GENERAL
        <?php elseif ($_data['code'] == 'productweight'): ?>

Product Dimension
<?php echo $this->__('PRODUCT DIMENSION') ?>

        <?php endif; ?>

                <?php echo $this->escapeHtml($this->__($_data['label'])) ?>
                <?php echo $_helper->productAttribute($_product, $_data['value'], $_data['code']) ?>

            <?php } ?>
        <?php endforeach; ?>

<?php endif;?>

<?php

$attribute_value = 'xyz ';
if (strlen($attribute_value) > 0)
{
   // code to display the value
}

?>

A: Just validate it in the first line after foreach:
...

    <?php foreach ($_additional as $_data): ?>
    <?php $_attribute = $_product->getResource()->getAttribute($_data['code']);
    if($_attribute->getFrontend()->getValue($_product) == 'abc') {
        continue;
    }
    ?>
...


text:
Q: OleDb paramater syntax When adding a parameter to an OLEDB command, is there a need to use 'new'. Both of the following work. Is one preferable or are they doing the same thing?
command.Parameters.Add(new OleDbParameter("name", OleDbType.VarChar));
command.Parameters.Add("name", OleDbType.VarChar);

A: Yes, Add(string, OleDbType) overload calls the Add(OleDbParameter) overload. That means they do the same thing under the hood.
public OleDbParameter Add(string parameterName, OleDbType oleDbType)
{
     return Add(new OleDbParameter(parameterName, oleDbType));
}

https://referencesource.microsoft.com/#System.Data/fx/src/data/System/Data/OleDb/OleDbParameterCollection.cs,78
As Steve commented, most common way to use it (as far as I see) like;
command.Parameters.Add("name", OleDbType.VarChar).Value = "YourValue";

or if you know (of specify) your db column size (let's assume it is varchar(10)), you can add an integer as a third parameter like calling the Add(parameterName, oleDbType, size) overload;
command.Parameters.Add("name", OleDbType.VarChar, 10).Value = "YourValue";


text:
Q: Im recieving an Error message and I'm not sure what too do this is what needs to be done
below is a few values from list data.txt
79012400

adfadfaf

54523

29813360

30489059

30350069wqer

30530679

28863496

8787390

ValueError: Invailid literal for int() with base 10: '29933900jhgd'

def FileOpen(studentNumbers):
        count=0
        INFILE=open("data.txt","r")
        for line in INFILE:
            studentNumbers.append(line.rstrip())
            count+=1
        INFILE.close()
        return count

def AnalyseStudents(rawList,ValidNumbers,InvalidNumbers):
    num_sum=0
    for b in range(8,0,-1):
        num_sum += int(rawList[len(rawList)-7])**b

    result = num_sum%11

    if result == 0:
        VailidNumbers.append(rawList)
    else:
        InvalidNumbers.append(rawList)

def Write(outlist):
    OUTFILE=open("output.txt","W")
    for number in outlist:
        OUTFILE.write(number+"\n")
    OUTFILE.close()

inputList = []
outputList=[]
print(FileOpen(inputList),"number of lines read from file")
print("Analysing file")
AnalyseStudents(inputList,outputList,outputList)
print("Writing result to file..")
WriteFile(outputList)
print("Done.Please cheack the output file.")

A: Going by the comments you added, it looks like you only want the first 8 characters:
rawList = ['28698118adfs', 'abcdagsa', '2432142341432134', '30048117']
VailidNumbers = []
InvalidNumbers = []
length = 8
for rawString in rawList:
    if(rawString[0:length].isdigit()):
        num_sum = 0
        for b in range(length,0,-1):
            num_sum += int(rawString[length-b])**b
        print(num_sum)
        result = num_sum%11

        if result == 0:
            VailidNumbers.append(rawString)
        else:
            InvalidNumbers.append(rawString)
    else:
        InvalidNumbers.append(rawString)
print(InvalidNumbers)
print(VailidNumbers)

In your example of 30048117, this expands to (3^8 + 4^5 + 8^4 + 1^3 + 1^2 + 7^1)%11 = 8, which is not equal to zero, so it will be added to InvalidNumbers.
If your code is correct however, this is the fix:
rawList = ['28698118adfs', 'abcdagsa', '2432142341432134', '30048117']
VailidNumbers = []
InvalidNumbers = []
length = 8
for rawString in rawList:
    if(rawString[0:length].isdigit()):
        num_sum = 0
        number = rawString[0:length]
        for b in range(length,0,-1):
            num_sum += int(number[len(number) - 7]) ** b
        print(num_sum)
        result = num_sum%11

        if result == 0:
            VailidNumbers.append(rawString)
        else:
            InvalidNumbers.append(rawString)
    else:
        InvalidNumbers.append(rawString)
print(InvalidNumbers)
print(VailidNumbers)

A: None of your given data samples survive your logic - they are either invalid due to ValueError or due to number % 11 != 0
Write demo data:
with open("studs.txt","w") as f:
    f.write("""79012400
adfadfaf
20570856
54523
29813360
30489059
30350069wqer
30530679
28863496
8787390 """)

Use this to analyze:
def AnalyseStudents(rawList):
    bad = []
    good = []
    for student in rawList:
        try:
            number = int(student[:8])
        except ValueError:  # not 8 numbers
            bad.append(student)
            continue        # next student

        v = 0
        for idx,n in enumerate(str(number)): # enumerate starts at idx 0 to 7
            n = int(n)
            idx = 8-idx
            # detail printing # print(f"v ({v:>10}) += {n}*{idx} => {v+n*idx}")
            v += n*idx

        print(f"v ({v:>10}) % 11 = {v%11}")
        if v%11 == 0:
            good.append(student)
        else:
            # verification mishap
            bad.append(student)
    return good,bad  # return a tuple of 2 lists

Process the file of demo data:
with open("studs.txt") as f:
    students = [line.strip() for line in f if line.strip()]

print(f"{len(students)} lines read from file")
good, bad = AnalyseStudents(students)

with open("output.txt","w") as f:
    f.write( "\n".join(good))

if good:
    with open("output.txt","w") as f:
        f.write( "\n".join(good))
else:
    print("No good ones")

print(good)
print(bad)

Output:
10 lines read from file
v (       144) % 11 = 1
v (       121) % 11 = 0
v (       120) % 11 = 10
v (       165) % 11 = 0
v (       143) % 11 = 0
v (        88) % 11 = 0
v (       110) % 11 = 0
v (       198) % 11 = 0
v (       235) % 11 = 4
# good
['20570856', '29813360', '30489059', '30350069wqer', '30530679', '28863496']
# bad
['79012400', 'adfadfaf', '54523', '8787390']


text:
Q: How to retrieve particular string from a text kotlin? I am getting the scan result in a string like ---
DriverId=60cb1daa20056c0c92ebe457,Amount=10.0
I want to retrive driver id and amount from this string.
How can I retrive?
Please help...

A: It depends on your overall format. Basic operations like substrings as suggested by @iLoveYou3000 can work fine if you really have this fixed format.
If the keys are dynamic, or could be changed in the future, you could also use more general approaches, for instance using split():
val attributeStrings = input.split(",")
val attributesMap = attributeStrings.map { it.split("=") }.associate { it[0] to it[1] }

val driverId = attributesMap["DriverId"]
val amount = attributesMap["Amount"].toDouble() // or .toBigDecimal()

A: This is one of the possible ways that I could think of.
val driverID= str.substringAfter("DriverId=", "").substringBefore(",", "")
val amount = str.substringAfter("Amount=", "")


text:
Q: How do you specify  in the manifest? I'm deeply frustrated and hoping someone can help.
My Word Add-in requires 1.1, and (as a newbie) I've found the MS documentation and submission process ambiguous/confusing. They take 2 days, then reject my Add-in.
To their credit, they include a lot of detail and have found legit issues.
The only item standing in my way is calling out 1.1 in the manifest, so Word 2013 users can't even see it.
The example code they give doesn't work in my Manifest when I submit it. Here's the sample they provide at https://dev.office.com/docs/add-ins/overview/specify-office-hosts-and-api-requirements.
<Requirements>
 <Sets DefaultMinVersion="1.1">
   <Set Name="TableBindings" MinVersion="1.1"/>
   <Set Name="OOXML" MinVersion="1.1"/>
 </Sets>
 <Methods>
    <Method Name="Document.getSelectedDataAsync"/>
 </Methods>
</Requirements>

I submitted the following, which was accepted by their XML checker and ran fine in Word Online and they bounced me. I hadn't checked using an installed Word (my bad) because I've found Word Online to be the gold standard:
<Requirements>
  <Methods>
    <Method Name="Document.insertText"/>
  </Methods>
</Requirements>

They bounced the manifest with these lines (the rest of the manifest is fine and has been checked multiple times)...
All I want to do is block Word 2013. That's it.
I've been trying variations and loading in Word 2016 for Mac and can't get it to work. I know that the manifest is sequencing-sensitive...meaning if you put something in the wrong place it won't work. I've got  right after .
I'm really hoping to avoid waiting another 3 days to get feedback on a typo.
Help deeply appreciated while I continue to experiment.

A: your requirements node should look like this:

 <Requirements>
    <Sets DefaultMinVersion="1.1">
      <Set Name="WordApi" MinVersion="1.1"/>
    </Sets>
  </Requirements>


text:
Q: Ext JS insertAdjacentHTML null when extending Ext.tree.Panel i have a problem when extending Ext.tree.Panel in ext JS 4
I have this code :
Ext.define('Peps.tree', {
    extend: 'Ext.tree.Panel',
    alias: 'widget.pepstree',
});

Ext.create('Peps.tree', {
    renderTo:'selection_indicateur',
    id : 'pepstree',
    width:'500px',
    height:'500px'
});

Ext.create('Peps.tree', {
   renderTo:'selection_arborescence',
   id : 'pepstree2',
   width:'500px',
   height:'500px'
});

And when i execute i can see only one treepanel created and an error :
Uncaught TypeError: Cannot read property 'insertAdjacentHTML' of null

This code is a minimal version of the real one, i hope solving the minimal code will solve everything.
What do i do wrong ? Any ideas ?
Thanks a lot ! :)

A: When I put your code into jsfiddle I dont get the error you are describing
http://jsfiddle.net/dbrin/VbTjx/embedded/result/
however you will notice that when expanding second level children on the second grid you dont get any children - so there is something wrong there, but I amnot sure if thats related to the issue you see.
Looks like the common prototype shares the root - which is not a good thing here.

A: So i've found the problem, i don't know why but ext js needs to have the id of the viewconfig defined when extending a treepanel.
So i added in my initComponent() method this :
initComponent: function() {
    var id = Ext.id();
    Ext.apply(this, {
        viewConfig: {
            id: id + '-view'
        }
    }
}


text:
Q: отправка письма с файлом на почту Не приходят письма на почту, вроде и ошибок нет, как не старался изменять, не работает.
Вот код обработчика может кто подскажет:
<?php

require_once('phpmailer/PHPMailerAutoload.php');
$mail = new PHPMailer;
$mail->CharSet = 'utf-8';

$name = $_POST['name'];
$age = $_POST['age'];
$exp = $_POST['exp'];
$place = $_POST['place'];
$reg = $_POST['reg'];
$phone = $_POST['phone'];
$mail = $_POST['mail'];

//$mail->SMTPDebug = 3;                               // Enable verbose debug output

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp.mail.ru';                                                                                // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'login'; // Ваш логин от почты с которой будут отправляться письма
$mail->Password = 'parol'; // Ваш пароль от почты с которой будут отправляться письма
$mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to / этот порт может отличаться у других провайдеров
$mail->setFrom(''); // от кого будет уходить письмо?
$mail->addAddress('');     // Кому будет уходить письмо

$mail->addAttachment($_FILES['image']['tmp_name'], $_FILES['image']['name']);    // Optional name
$mail->isHTML(true);
                                // Set email format to HTML

$mail->Subject = 'Заявка с тестового сайта';
$mail->Body    = '' .'ФИО:'.$name.'\r\nВозраст: '.$age.'\r\nВозраст: '.$age.'\r\nСтаж вождения: '.$exp.'\r\nРайон проживаният: '.$place.'\r\nРайон регистрации: '.$reg.'\r\nТелефонт: '.$phone.'\r\nEmailт: '.$mail;
$mail->AltBody = '';
$mail->send();

?>

A: Вы создаете класс PHPMailer и записываете его в $mail, потом в $mail вы записываете $_POST['mail']. Естественно дальше у вас все отваливается, что бы избежать таких затруднений, настройте вывод ошибок в php
require_once('phpmailer/PHPMailerAutoload.php');
$mail = new PHPMailer;
$mail->CharSet = 'utf-8';

$name = $_POST['name'];
$age = $_POST['age'];
$exp = $_POST['exp'];
$place = $_POST['place'];
$reg = $_POST['reg'];
$phone = $_POST['phone'];
$email = $_POST['mail'];

//$mail->SMTPDebug = 3;                               // Enable verbose debug output

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp.mail.ru';                                                                                // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'dmitro_bolva@mail.ru'; // Ваш логин от почты с которой будут отправляться письма
$mail->Password = 'ghbdtnlbvjy22081996'; // Ваш пароль от почты с которой будут отправляться письма
$mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to / этот порт может отличаться у других провайдеров
$mail->setFrom('dmitro_bolva@mail.ru'); // от кого будет уходить письмо?
$mail->addAddress($email);     // Кому будет уходить письмо

$mail->addAttachment($_FILES['image']['tmp_name'], $_FILES['image']['name']);    // Optional name
$mail->isHTML(true);
                                // Set email format to HTML

$mail->Subject = 'Заявка с тестового сайта';
$mail->Body    = '' .'ФИО:'.$name.'\r\nВозраст: '.$age.'\r\nВозраст: '.$age.'\r\nСтаж вождения: '.$exp.'\r\nРайон проживаният: '.$place.'\r\nРайон регистрации: '.$reg.'\r\nТелефонт: '.$phone.'\r\nEmailт: '.$mail;
$mail->AltBody = '';
$mail->send();


text:
Q: How to determine the reason why Firefox has poor performance on my web application? I am developing a complex web application, which is working fine on Chrome and IE, but recently has developed huge performance issues on Firefox which lead us to block it's usage completely to avoid a poor UX while the problem isn't solved.
Below is a screenshot of the Firefox profiler:

The file is available here for deeper inspection (2MB JSON)
As I can understand from this, it seems that Firefox is taking a tremendous amount of time recalculating the layout, which seems to happen on each user interaction with the application.
But how do I interpret all this data? How can this help me trace the origin of the problem and remove all of these layout recalculation?


text:
Q: Magic 8 ball in HTML I am thinking of making a "magic 8 ball" kind of website. I would like a version of the following code that looks more like the helix fossil website.

var answers = [
  'Maybe.', 'Certainly not.', 'I hope so.', 'Not in your wildest dreams.',
  'There is a good chance.', 'Quite likely.', 'I think so.', 'I hope not.',
  'I hope so.', 'Never!', 'Fuhgeddaboudit.', 'Ahaha! Really?!?', 'Pfft.',
  'Sorry, bucko.', 'Hell, yes.', 'Hell to the no.', 'The future is bleak.',
  'The future is uncertain.', 'I would rather not say.', 'Who cares?',
  'Possibly.', 'Never, ever, ever.', 'There is a small chance.', 'Yes!'];

document.getElementById('answerButton').onclick = function () {
  var answer = answers[Math.floor(Math.random() * answers.length)];
  document.getElementById('answerContainer').innerHTML = answer;
};
p, input, button {
  font-family: sans-serif;
  font-size: 15px;
}
input {
  width: 200px;
}

 How can I help you today?

<input type="text" placeholder="enter a question"></input>

<button id="answerButton"> Answer me </button>

Also, when I put this into the "insert code" feature in Weebly, it keeps showing the raw code above the elements. Any way I could clean this up or should I just use a different website creator?
I know nothing about CSS.

A: Below is a snippet that adds some styling to the basic code.
If you want to make a web page out of this, you can put the CSS inside style tags, the JavaScript inside script tags, and the HTML inside body tags.
Like this: right-click on my page and select "View Page Source" (or whatever your browser of choice calls it) to see how the page is organized.
Better yet, if the Weebly file manager allows it, put the CSS and JavaScript into external files and link to them in the HTML file.

window.onload = function () {
  var answers = [
    'Maybe.', 'Certainly not.', 'I hope so.', 'Not in your wildest dreams.',
    'There is a good chance.', 'Quite likely.', 'I think so.', 'I hope not.',
    'I would say so.', 'Never!', 'Fuhgeddaboudit.', 'Ahaha! Really?!?', 'Pfft.',
    'Sorry, bucko.', 'Hell, yes.', 'Hell to the no.', 'The future is bleak.',
    'The future is uncertain.', 'I would rather not say.', 'Who cares?',
    'Possibly.', 'Never, ever, ever.', 'There is a small chance.', 'Yes!'];

  var container = document.getElementById('answerContainer'),
      opacityPercent,
      previousAnswer;
  function updateOpacity() {
    opacityPercent += 1;
    container.style.opacity = opacityPercent / 100;
    if (opacityPercent < 100) {
      window.requestAnimationFrame(updateOpacity);
    }
  }
  function makeVisible() {
    container.style.opacity = '0';
    opacityPercent = -1;
    updateOpacity();
  }
  opacityPercent = -1;
  document.getElementById('questionArea').value = '';
  document.getElementById('answerButton').onclick = function () {
    while (true) {
      var answer = answers[Math.floor(Math.random() * answers.length)];
      if (answers.length == 1 || answer != previousAnswer) {
        previousAnswer= answer;
        break;
      }
    }
    container.className = '';
    container.innerHTML = answer;
    makeVisible();
  };
};
body {
  background: #e8e8d6;
  color: #333;
}
#wrapper {
  width: 600px;
  margin: 80px auto;
  text-align: center;
}
p, input, button {
  font-family: 'Source Sans Pro', sans-serif;
  font-size: 24px;
}
#answerContainer {
  opacity: 0;
}
p {
  padding: 20px 0;
}
input {
  width: 500px;
  padding: 5px 15px;
  background: #fff;
  border: 2px solid #ddd;
  outline: none;
}
input:focus {
  border: 2px solid #888;
}
button {
  background: #ffe;
  color: #666;
  border: 2px solid #666;
  border-radius: 8px;
  margin-left: 10px;
  padding: 5px 15px;
  outline: none;
}
button:hover {
  background: #ffc;
  color: #222;
  border: 2px solid #222;
  cursor: pointer;
}
<link rel="stylesheet" type="text/css"
 href="https://fonts.googleapis.com/css?family=Source+Sans+Pro">

 What do you want to know about the future?

  <input id="questionArea" type="text" placeholder="enter a question"></input>

  <button id="answerButton"> Make a prediction </button>


text:
Q: How do I disable a button using data bindings in Dart? In a response to a similar question, that is more than a year old, I read about an easy way to disable a button using data binding in Dart (and polymer-dart).
My current code looks like this:
html:
...
<button id="btnPointDown" on-click="{{decrement}}" disabled="{{points == 0}}">\/</button>
...

.dart:
...
@published int points = 0;

void increment() {
  points++;
}

void decrement() {
  points--;
}
...

However Dart does not seem 'to be clever' about the disabled element anymore.
How do I use up-to-date Dart and Polymer to disable a button using data bindings (or if not possible programmatically)?

A: for polymer 1.0 I found the answer here.
It should be: <button ... disabled$="{{myTestFunction()}}">Content</button>
FYI: I have not been able to use simple statements like points == 0, but instead I had to use a function, which returns a boolean.

A: Binding to the disabled attribute can be done like this:
<button ... disabled?="{{ points == 0 }}">Content</button>

This ? is special syntax introduced by Polymer to support binding to this kind of boolean attributes.
This does not work:
<button ... disabled="{{ points == 0 }}">Content</button>

Because it would result in
<button ... disabled="false">Content</button>

which would still disable the button.
For Polymer >= 1.0 the new syntax to use is:
<button ... disabled$="{{value}}">Content</button>

Note: value already has to be a boolean as Marco pointed out below. Otherwise you have to create a function that would return points == 0. See Data Binding Documentation here and Migration Guide here for reference.
Regards,
Robert


text:
Q: Encoding strange persian csv file I want to read a CSV file that has some Persian(Farsi) text in it
what is the right encoder for it?
one of csv line is there:
9004090036,98,02,01,34028036 ,üَن,¤ّîھ,¢م¨,0520275950 ,يگ¤گ, 0 ,¢¤ُ ,ü÷گ¤گ ,ù¢'¨ ¤ً¤'î ,98/02/01

A: I convert the text file to hex and find out in is encode with 'iransystem' encoding scheme
wiki

A: You can use google doc spreadsheet. Copy or import your table in google doc new spreadsheet and then download in CSV format. Open your CSV file with Notepad and save as with UTF-8 format. Now your CSV file is ok.


text:
Q: Create IKernel with Ninject in MVC 4 project This is my first time using Ninject and I'm facing some problems with my MVC 4 application.
I created a class called IocConfig at App_Start folder in my Presentation Layer.
IocConfig class
public class IocConfig
{
    public static void ConfigurarDependencias()
    {
        IKernel kernel = new StandardKernel();
        ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory(kernel));

        kernel.Bind<IReceitaRepository>().To<SqlReceitaRepository>();

        DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
    }
}

public class NinjectControllerFactory : DefaultControllerFactory
{
    private IKernel ninjectKernel;

    public NinjectControllerFactory(IKernel kernel)
    {
        ninjectKernel = kernel;
    }

    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        return (controllerType == null) ? null : (IController)ninjectKernel.Get(controllerType);
    }
}

public class NinjectDependencyResolver : IDependencyResolver
{
    private readonly IResolutionRoot _resolutionRoot;

    public NinjectDependencyResolver(IResolutionRoot kernel)
    {
        _resolutionRoot = kernel;
    }

    public object GetService(Type serviceType)
    {
        return _resolutionRoot.TryGet(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return _resolutionRoot.GetAll(serviceType);
    }
}

And after read the thread ASP.NET MVC 4 + Nunject MVC 3, I'm trying to implement the same solution proposed by @JereJones, but I got the following error at the line below
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
    return (controllerType == null) ? null : (IController)ninjectKernel.Get(controllerType);
}

Error
Error activating ISession
No matching bindings are available, and the type is not self-bindable.
Activation path:
 3) Injection of dependency ISession into parameter session of constructor of type SqlReceitaRepository
 2) Injection of dependency IReceitaRepository into parameter repositorio of constructor of type HomeController
 1) Request for HomeController

Suggestions:
 1) Ensure that you have defined a binding for ISession.
 2) If the binding was defined in a module, ensure that the module has been loaded into the kernel.
 3) Ensure you have not accidentally created more than one kernel.
 4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name.
 5) If you are using automatic module loading, ensure the search path and filters are correct.

A: You should simply install ´Ninject.MVC4´ from NuGet. Then you get a class NinjectWebCommon.cs in App_Start. In the method RegisterServices you can place your binding configurations.
A short and nice introduction on how to use Ninject with ASP.NET MVC can be found here.


text:
Q: Julia 1.4.2 - Smooth Arrays Is there a function in Julia that is analogous to MATLAB's smooth() function.
MATLAB smooth function:
z = smooth(y, span, method) where

*

*y -> input array;

*span -> span of moving average;

*method -> option between default moving average, lowess, loess etc.

THe result of this operation  z is a vector of the same dimension as y which is basically a smoothening of the original array y.
I can't find a simple function in Julia to do that. TimeSeries.jl has function called moving(), but the issue is that we need to transform the input variable first into a TimeArray instead of a normal Array. The output from the function is a TimeArray as well. This is fine, but TimeArray becomes a bit of a problem for some other functions (e.g. those that only allow Array, and not TimeArray).


text:
Q: Regexps in Elisp to include newlines I'm trying to add a special markup to Python documentation strings in emacs (python-mode).
Currently I'm able to extract a single line with:
(font-lock-add-keywords
 'python-mode
 '(("\\(\"\\{3\\}\\.+\"\\{3\\}\\)"
    1 font-lock-doc-face prepend)))

This works now:
"""Foo"""

But as soon there is a newline like:
"""
Foo

"""

It doesn't work anymore. This is logical, since . doesn't include newlines (\n).
Should I use a character class?
How can I correct this regular expression to include everything between """ """?
Thanks in advance!

A: "\\(\"\\{3\\}\\(.*\n?\\)*?\"\\{3\\}\\)"

The "*?" construct is the non-greedy version of "*".

A: A newline in emacs regexps is entered by C-q C-j so just stick a group containing . and C-q C-j into your regexp. As I use regexp-tool to build them, mine isn't fully quoted as yours, but I hope the changes are obvious.
\("\{3\}\(.\|C-qC-j\)+"\{3\}\)
Sorry I can't format it better, stackoverflow doesn't agree with me.
Also it will probably display as a newline in emacs.

A: This works half:
(font-lock-add-keywords
     'python-mode
      '(("\\(\"\\{3\\}\\(.\\|\n\\)*?\"\\{3\\}\\)"
         1 font-lock-warning-face prepend)))

But when adding RET's the markup is gone.
The suggested regexp "\\(\"\\{3\\}\\(.*\n?\\)*?\"\\{3\\}\\)" makes my emacs hang when opening a .py file.
Maybe it's time to visit the emacs mailinglist..

A: The best and easiest way is this one:
font-lock-add-keywords
 'python-mode
 '(("\\(\"\\{3\\}\\[^|]*?\"\\{3\\}\\)"
    1 font-lock-doc-face prepend)))

You can use any character that is definitly not between """ and """ instead of |.


text:
Q: UIView detecting touches in only one half of the screen I am currently working on a 3D OpenGLES-based iPhone Game project and I want to have a view that detect touches so I can then rotate my camera according to the touch gestures.
So here I created a TouchPad class that derives from UIView to record the touch gestures.
Once done I have figured out that only half of the screen is effective. The whole left side.
Whenever i touch the right part of the screen it does not call the -[touchesBegan] method
Here is my class  definition
@interface TouchPad : UIView
{
CGPoint fingerMove, originalPosition;
}
@property (nonatomic, assign) CGPoint fingerMove;
@end

And here is my class implementation
#import "TouchPad.h"

@implementation TouchPad

@synthesize fingerMove;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
        fingerMove = CGPointMake(0, 0);
    return self;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    std::cout << "called";
    UITouch *touch = [touches anyObject];
    originalPosition = [touch locationInView:self];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint currentPosition = [touch locationInView:self];
    fingerMove = CGPointMake(currentPosition.x - originalPosition.x,
                             currentPosition.y - originalPosition.y);
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
{
    UITouch *touch = [touches anyObject];
    originalPosition = [touch locationInView:self];
    fingerMove = CGPointMake(0, 0);
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    fingerMove = CGPointMake(0, 0);
}

@end

And here is how i use it inside my ViewController
- (void)prepareGame
{
    game = [[MainGame alloc] init];
    [self.view addSubview:game.IrrView];
    [game.IrrView release];

    rotationPad = [[TouchPad alloc] initWithFrame:CGRectMake(0.0, 0.0,
                                [[UIScreen mainScreen] bounds].size.width,
                                [[UIScreen mainScreen] bounds].size.height)];
    [self.view addSubview:rotationPad];
    [rotationPad release];

}

- (void)runGame
{
    [game updateMapPattern];
    [game updateCamera :rotationPad.fingerMove];
    [game draw];
}

I really want to know how to make the touchPad work in the whole screen and not only the left part of the screen. Maybe there is a conflict with my game view


text:
Q: ios table with data that is grouped by I have a conceptual sql query that uses group by on a core data table t as follows:
select a, b, sum(c) c_sum from t group by a, b;
Using core data I can run the query (as described in thread GROUP BY with SUM() using Core Data). I would like to use NSFetchedResultsController. I tried the following:

*

*In my "refresh" operation, I tried to use the fetch request corresponding to the above group by query directly but ran into the problem  "NSFetchedResultsController does not support both change tracking and fetch request's with NSDictionaryResultType".

*Then I thought of the following. Save the records in the table t. Then run the above query and save the result in another table t1. Tie the nsfetchedresultscontroller to a regular fetch from t1. Unfortunately, in this case, I run into the issue that the group by query does not see anything in the db since the document save operation is asynchronous.

*To counter the above issue, I tried to save the document right after I did the insert into table t - but then I got the error "This NSPersistentStoreCoordinator has no persistent stores.  It cannot perform a save operation."
The obvious alternative is for me to do the group by and sum programmatically and then insert data into t1 but I thought I would ask around here to see if others have any thoughts. Second one that I have not tried yet is to listen to document save notification and then do the insert into t1. Another alternative is to not use nsfetchedresultscontroller - which I would like to avoid.
Thoughts?
Thanks!
UPDATE:
OK detecting save notification and then populating t1 from t using the grouped by query works but is not a good solution because:
1. I am the mercy of when the save operation happens
2. Each time the save happens, the table is repopulated which is not a good idea obviously.

A: OK. I finally figured out how to save the context, i.e. how to successfully do the option 3 without running into the error mentioned. The option 3 involves using UIDocument saveToURL:forSaveOperation:completionHandler: operation. That is what I had tried. But the error I made was that I was creating a new UIManaged Document instance from the same url as the original document instance (whose managed context I had been using).
So, now in my viewWillAppear, I save the document also as a property at the same time I save the managed context property. Then when I run the saveToUrl, I use the property document instance - in this case, I do not get the error "This NSPersistentStoreCoordinator has no persistent stores. It cannot perform a save operation."


text:
Q: Syntax for comparison expression in Simple case expression in Oracle DB SQL I am trying to make a parser for Oracle SQL select statement which include CASE statement
http://docs.oracle.com/cd/B19306_01/server.102/b14200/img/case_expression.gif
And the oracle reference listed that the simple case expression can be expressed in
http://docs.oracle.com/cd/B19306_01/server.102/b14200/img/simple_case_expression.gif
But i cannot find the comparison expression everywhere in the reference, does anyone have a clue where is it and how it looks like?

A: I believe it's the same as the condition defined here:
http://docs.oracle.com/cd/E11882_01/server.112/e26088/conditions001.htm#SQLRF52101

which means it can be several kinds of things, requiring all of chapter 7 of the manual to explain them. And most of them in turn can include arbitrary expressions (that's all of chapter 6, plus chapter 5 for function calls) and even subqueries (so all of chapter 9 too). For eaxmple this is a "simple case statement" in action:
SELECT
  CASE
    WHEN (SELECT /* anything that can go in a select statement might be here */) > 0
    THEN 'Y'
    ELSE 'N'
  END
FROM DUAL

And in the nested query you can have all kinds of hard-to-parse things. Basically if you want to parse a CASE expression the way Oracle would parse it, you're in trouble. There's no way to avoid the need to parse the rest of Oracle SQL.
If you limit yourself to standard SQL (and maybe ban subqueries) you have a better chance of finishing the project.
OK, first answer was exactly the opposite of the truth. comparison_expr is an expr that will be compared to the expr that comes right after the CASE.


text:
Q: html format assign to java string

        <form role="form">

            </form>

Hi is there any tool or shortcut which can be used for storing the above to a Java String. Manually doing is totally tiredness.
This is a small code. There are chances to have more lines to be there. I thought doing through message.properties. But
the format is not coming properly. so again i have to format and make it into single line.Again tiredness. And I cannot use java file reading due to some problem.

A: Googling html to java constant online comes up with this online tool pretty quickly: http://www.htmlescape.net/javaescape_tool.html, which in turn generates this for you:
String s="
\n
\n <form role=\"form\">\n
\n
\n </form>\n
\n
";


text:
Q: ASP.NET not showing any error, but unable to insert data into database Under this I am trying to save the cart items chosen by the user into the database, for that I have initially selected the chosen items through Request.Query method now after that I have called those values and formed an SaveCartDetail function in which I have performed insert command into the database,the asp.net shows no error but there is no change in my table the name of my table is cart.
if (!IsPostBack)
{
    DataTable dt = new DataTable();
    DataRow dr;

    dt.Columns.Add("sno");
    dt.Columns.Add("itemname");
    dt.Columns.Add("quantity");
    dt.Columns.Add("price");
    dt.Columns.Add("totalprice");
    dt.Columns.Add("image");

    if (Request.QueryString["itemname"] != null)
    {
        if (Session["Buyitems"] == null)
        {
            dr = dt.NewRow();

            SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["online food orderingConnectionString"].ConnectionString);
            scon.Open();

            String myquery = "select * from food_items where item_name=@items_name";

            SqlCommand cmd = new SqlCommand(myquery, scon);

            cmd.Parameters.AddWithValue("items_name", Request.QueryString["itemname"].ToString());

            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);

            dr["sno"] = 1;

            if (ds.Tables[0].Rows.Count > 0)
            {
                dr["itemname"] = ds.Tables[0].Rows[0]["item_name"].ToString();
                dr["image"] = ds.Tables[0].Rows[0]["image"].ToString();
                dr["price"] = ds.Tables[0].Rows[0]["price"].ToString();
                int price = Convert.ToInt16(ds.Tables[0].Rows[0]["price"].ToString());
                int quantity = Convert.ToInt16(Request.QueryString["quantity"].ToString());
                int totalprice = price * quantity;
                dr["quantity"] = Request.QueryString["quantity"];

                dr["totalprice"] = totalprice;

                SaveCartDetail(ds.Tables[0].Rows[0]["item_name"].ToString(), Request.QueryString["quantity"], ds.Tables[0].Rows[0]["price"].ToString(), totalprice.ToString());
                dt.Rows.Add(dr);

                GridView1.DataSource = dt;
                GridView1.DataBind();

                Session["buyitems"] = dt;

                GridView1.FooterRow.Cells[4].Text = "Total Amount";
                GridView1.FooterRow.Cells[5].Text = grandtotal().ToString();
            }
        }
    }
}

private void SaveCartDetail(String itemname, String quantity, String price, String totalprice)
{
    String query = "insert into cart(item_name, quantity, price, totalprice, username) values ('" + itemname + "','" + quantity + "','" + price + "','" + totalprice + "','" + Session["username"].ToString() + "')";

    SqlConnection scon1 = new SqlConnection(ConfigurationManager.ConnectionStrings["online food orderingConnectionString"].ConnectionString);

    scon1.Open();

    SqlCommand cmd1 = new SqlCommand(query, scon1);
    cmd1.ExecuteNonQuery();
    scon1.Close();

    Response.Write("Items saved in cart");
}


text:
Q: What happens when I close a gate? I've gained access to the Historia Crux, and for some gates, there's a "Close Gate" option. If I select it, a fancy animation occurs, but it's not clear what, exactly, it does.
What's the difference between a closed gate and an open gate?

A: An open gate is one that you've found in-game and used a fragment to activate. Open gates save your progress as you roam about, and as you leave them to return to the Hisoria Crux.
Some portals have the close gate option. When you close a gate it resets all of the events and content there (other than collecting fragments and key items). This is so that you can re-play the area to make different story-altering live event choices. Those portals that do not have a close gate option don't have multiple story lines to choose from. You can still go back to collect missed items, but there's only one outcome from completing that time period.
This is what you're expected to do in order to experience each of the anomalies for a gate that has many of them. It is also how you earn the Anomalous trophy / achievement.


text:
Q: std::string resize is ruining compare operator (==) std::string resize causes strings that appear to be equal to no longer be equal. It can appear to be misleading when I hover over the variable in my debugger and they appear to hold the same value.
I think it comes down to the fact that I expected the == operator to stop at the first null character but it keeps going till the end of the size. I'm sure this is working as intended but I was stuck on an issue caused by this for a while so I wanted to see why you would keep comparing characters even after the first null character. thanks!
int main(void)
{
    std::string test1;
    test1.resize(10);
    test1[0] = 'a';

    std::string test2 = "a";

    //they are not equal
    bool same = (test1 == test2);

    return 0;
}

A: test1 is the string "a\0\0\0\0\0\0\0\0\0".  test2 is the string "a".  They are not equal.
std::string can contain null characters.  Its length is not the distance to the first null character.  It does also guarantee that the memory buffer containing the characters of the string ends with an additional null character 1 beyond its length.
If you don't intend for the string to be longer but just want the memory, use std::string::reserve.  Note that you cannot access elements beyond the end with [] legally, but pushing back or whatever won't cause any new memory allocations until you pass the reserve limit.

A: This is the intended behavior of std::string.  Unlike a c-string a std::string can have as many null characters as you want.  For instance "this\0 is\0 a\0 legal\0 std::string\0" would be legal to have as the contents for a std::string.  You have to build it like
std::string nulls_inside("this\0 is\0 a\0 legal\0 std::string\0", sizeof("this\0 is\0 a\0 legal\0 std::string\0");

but you can also insert null characters into an existing std::string.  In your case you're comparing
"a\0\0\0\0\0\0\0\0\0\0"

against
"a\0"

so it fails.


text:
Q: How do I force an html file to open in the browser instead of downloading? (Classic Google Sites) I'm using classic google sites and uploaded an html file. However, when I click on the link instead of opening directly on a new tab it tries to download it. So, how can I force that by clicking the link it opens directly in the browser?
Link location:
http://www.rodriguesloures.com/econometrics.html?attredirects=0&d=1
Code:

 Applied Econometrics using Julia

Thanks for you feedback!
Alexandre

A: You probably generated your html file with PANDOC and uploaded it to your site as page attachment (using Add file link). Google treats all attachments as files for download only.
What you can try to do is:

*

*create a new page called econometrics for example

*at the new page's EDIT pane click  button, Edit HTML popup window should be open now

*Paste your entire HTML content into text area and hit update button

Now, all links to this page will open your HTML and not download it


text:
Q: Qt system tray application can't receive the WM_QUERYENDSESSION or WM_ENDSESSION message I'm new and have coded something like this:
class MyXcbEventFilter : public QAbstractNativeEventFilter
{
public:
MyXcbEventFilter():myWindow(Q_NULLPTR)
{}
void setMainWindow(QMainWindow* _mainWindow){
    myWindow=_mainWindow;
}

virtual bool nativeEventFilter(const QByteArray &eventType, void *message, long *) Q_DECL_OVERRIDE
{
        MSG * pMsg = static_cast<MSG *>(message);
        if (WM_ENDSESSION==pMsg->message||WM_QUERYENDSESSION==pMsg->message)
        {
            QSound::play(":/Sound/start.wav");
            if(myWindow!=Q_NULLPTR){
                myWindow->close();
            }
        }
    return false;
}
private:
QMainWindow* myWindow;
};

What I want to do is detect system shutdown and do some cleanup.
The code works normally when the app windows is maximized but not work when the app window is minimized to system tray.
What's wrong?
The platform is: windows 10 64,Qt 5.7.1,MSVC2015


text:
Q: asp.net MVC EF 6 Identity only allowed to select 'lower' roles I have these roles setup within identity and one role is assigned per user
00 - Super Admin
10 - Admin
20 - Staff Manager
30 - Staff
40 - User Manager
50 - User

The aim is to allow a user to change the role of other users below (not equal to) their own user role
so if I could get the first two chars from the Name of the role added to the current user e.g. 30 then the choice of roles that could be applied to other users would be > 30
to get the user state of the current user
var currentUser = await _userManager.GetUserAsync(HttpContext.User);
var currentUserRole = await _userManager.GetRolesAsync(currentUser);

Then something like below that get all the roles, with 'WHERE' clause, or following if statement, first two chars > current users first two chars
var allRoles = _roleManager.Roles.ToList();

Does anyone know of a way that this could be done, or if there is a better idea?
Many Thanks
EDIT:
Ok, I now have this hardcoded to a SelectList in the view, select roles > 30 which is working
ViewBag.allRoles = _roleManager.Roles.Where(a => Convert.ToInt32(a.Name.Remove(2)) > 30).Select(a => new SelectListItem()
{
    Value = a.Id.ToString(),
    Text = a.Name.Remove(0, 5).ToString(),
}).ToList();

just need to get the current user role name to a string?

A: I have managed to sort it
var currentUser = await _userManager.GetUserAsync(HttpContext.User);

var currentUserRole = await _userManager.GetRolesAsync(currentUser);

int currentUserRoleLevel = int.Parse(currentUserRole[0].Remove(2));

ViewBag.allRoles = _roleManager.Roles.Where(a => Convert.ToInt32(a.Name.Remove(2)) > currentUserRoleLevel).Select(a => new SelectListItem()
{
    Value = a.Id.ToString(),
    Text = a.Name.Remove(0, 5).ToString(),
}).ToList();

The question still stands, is there a better way?


text:
Q: How should I use functions and / or combine some code here? I extended some tables with pagination and the possibility to sort columns. Everything is working fine so far, but I could use the very same code on up to 10 pages, so I thought about using functions, but I'm not sure if it's reasonable (performance etc.) to use a function for every part or if I should combine several things, so I need some advice..
Currently the code for one page looks like this (every number could be a function):
$limit = 30;

1.
$sql = 'SELECT
            COUNT(`news_id`)
        FROM
            `news`';

$stmt = $db->prepare($sql);
$stmt->execute();
$stmt->bind_result($count);
$stmt->fetch();
$stmt->free_result();
$stmt->close()

2.
if ($count === 0)
{
    $max_pages = 1;
}
else
{
    $max_pages = (int)ceil($count/$limit);
}

3.
if (isset($_GET['page']))
{
    if (preg_match('/^[0-9]{1,}$/', $_GET['page'])
    && ($_GET['page'] > 1
    && $_GET['page'] <= $max_pages))
    {
        $current_page = (int)$_GET['page'];
        $offset = ($current_page - 1) * $limit;
    }
    else
    {
        header('location: http://' .SERVERNAME. '/admin/news/');
        exit;
    }
}
else
{
    $current_page = 1;
    $offset = 0;
}

4.
$valid_sort = array('id', 'date', 'title');

if (isset($_GET['sort']))
{
    if(in_array($_GET['sort'], $valid_sort))
    {
        $sort = $_GET['sort'];
    }
    else
    {
        header('location: http://' .SERVERNAME. '/admin/news/');
        exit;
    }
}
else
{
    $sort = 'id';
}

5.
$valid_order = array('asc', 'desc');

if (isset($_GET['order']))
{
    if(in_array($_GET['order'], $valid_order))
    {
        $current_order = $_GET['order'];
    }
    else
    {
        header('location: http://' .SERVERNAME. '/admin/news/');
        exit;
    }
}
else
{
    $current_order = 'desc';
}

Since 4 and 5 are almost identical I could call the same function with different parameters here, but still I'm not sure if it really makes sense to call up to 5 functions..
Finally I need the following variables: $limit, $count, $max_pages, $current_page, $offset, $sort, $current_order
EDIT : Just to make it clear, the question is not how functions would work or if it's possible to use them here.. the question is, how complex should a function be relating to what I want to do with it? For example I could write one function with 120 lines and 8 parameters but I would only need to call 1 function / page... or I could keep it short and simple (1 function for 1 purpose / variable) but then I would need to call more functions / page..

A: Long story short. Yes.
It's fairly simple. If it's possible to put something in a function and make it re-usable, do so! It will organise your code and you can re-use it more easily. Otherwise you will have to rewrite your code afterwards to put it in a function anyway. So yes, do so and make it accessible for every single file if necessarily.
Also, if it's possible for you, try to start with functions to understand them completely, if you do, start with OOP! It will make your life so much easier. I hope this helps.
I am not going to rewrite your code, I think it's good practice for yourself if you do it on your own. If it's hard and you can't finish it yourself, feel free to ask on SO :)

*

*edit:
About the performance you are talking about, don't worry. A function is maybe 0.00000000001 nanoseconds slower than copy pasting. But if you consider readability and programming into a count, use functions. If you don't care how your code looks like, and for a simple tweak you'd like to spend 5 days, don't use functions ;)


text:
Q: How to prove a limit exists using delta and epsilon? I am having issues writing a proof using deltas and epsilons for this limit:
I basically do not  how to construct a proof after finding a limit. My main problem with problems like that arise from the proof. I took the the path of y=x and y =-x
to come up with L= 0.
$$\lim_{(x,y) \to (0,0)} \frac{xy}{\sqrt{x^2+y^2}}$$
Thanks,
Mo.

A: Related techniques: (I). Here is a how.
$$ \Bigg| \frac{xy}{\sqrt{x^2+y^2}}-0 \Bigg| = \frac{|x|\,|y|}{\sqrt{x^2+y^2}} \leq \frac{\sqrt{x^2+y^2}\,\sqrt{x^2+y^2}}{\sqrt{x^2+y^2}} = \sqrt{x^2+y^2} < \epsilon = \delta. $$
Note:

$$ |x| = \sqrt{x^2} \leq \sqrt{x^2+y^2}. $$

A: What do you think the limit is?  If I give you an $\epsilon$ that is positive, you need to find a $\delta$ so that over the whole square $-\delta \lt x,y \lt \delta$ the expression is within $\epsilon$ of the limit.  It seems that $x=\pm y$ will yield the extreme values.  What are your issues?


text:
Q: Vim - error messages timeout I want Vim to timeout error messages in the command line after 5 seconds or so. What's the way to do it?
Currently an error message (e.g. E486: Pattern not found...) hangs there until it's cleared by some other action.

A: You can clear the message in the command-line via :echo. The CursorHold event can be used for triggering when you're idle for some time (default 4 seconds). You can also add more events (e.g. CursorMoved, FocusLost, etc.) according to your preferences. (But having an exact timeout N seconds after an error occurs would be very hard to implement, as there's no hook for that.) Taken together, you can define the following (e.g. in your ~/.vimrc):
:autocmd CursorHold * echo


text:
Q: All pages are giving 404 Error in Postman for Spring Boot application using Maven https://github.com/SREEJA-PALLA/SpringBootCoursesAPI/tree/master
I'm getting a 404 error in postman this is my project.
{
"timestamp": "2021-05-18T17:46:24.979+00:00",
"status": 404,
"error": "Not Found",
"message": "",
"path": "/topics"
}
I checked the dependencies and also tried many ways but nothing seemed to work.
Can someone please help?
Thank you in advance.

A: You have annotated your main application class with
@ComponentScan({"com.delivery.request"})

But this package does not exist in your codebase. So Spring does not find the Controller that you want it to find. This is in the package com.example.courseData.topic.


text:
Q: How to integrate $y' = x(1+y)(2-y)$? $$y' = x(1+y)(2-y)$$
I have been stuck on this problem for a little while and do not know what I should set as v (some random variable for substitution) if I were to approach this problem as a separable equation.
I had tried setting v equal to all three terms, $x, 1+y,$ and $2-y$, with no luck and then v equal to $((1+y)(2-y))$ but did not succeed with that either.

Edit1:
Here is my solution :
$$ \frac 1 3(\ln|y+1|-\ln|y-2|)= \frac {x^2}2+C_1 $$
$$ \ln \left | \frac {y+1}{y-2} \right |= \frac {3}2x^2+C $$

A: $$\frac {dy}{dx} = x(1+y)(2-y)$$
Separate and integrate :
$$\int \frac {dy}{(y+1)(y-2)}=-\int xdx$$
Then use fraction decomposition method for the left integral:
$$-\frac 13\int \frac {dy}{y+1}+\frac 1 3\int \frac {dy}{y-2}=-\int xdx$$
Can you take it from here ?


text:
Q: Can I make table from other table elements? Am I able to make a separated table filled with elements from other tables in Lua? Like this:
TableA = { a=1, b=2, c=3 }
TableB = { John=4, Jane =5 }
TableC = { x = "asd", y = "dsa", z = "sda" }

TableAll = { TableA.a, TableB.John, TableC.x}

It's a general example, but may work. I'm not sure in it.

A: Is there some reason why that wouldn't work?
All that tablename.key does is access an element of a table. This is a value; the fact that it came from a table is completely irrelevant. The value returned by tablename.key is no different than the value 5, nil, true, "some string", or any other value in Lua.
You can initialize a table with values; it doesn't matter where those values come from.


text:
Q: I'm getting this error when trying to run the mlagents-learn command. All the correct versions of the correct packages are installed in a venv I'm trying to use this toolkit to get the hang of creating machine learning agents in simulations. It seemed like the easiest one out there, so I followed a tutorial from a channel called CodeMonkey. Does anyone know what is going wrong here?
(https://www.youtube.com/watchv=zPFU30tbyKs&ab_channel=CodeMonkey).
'''
Traceback (most recent call last):
  File "/usr/local/bin/mlagents-learn", line 5, in <module>
    from mlagents.trainers.learn import main
  File "/usr/local/lib/python3.9/site-packages/mlagents/trainers/learn.py", line 2, in <module>
    from mlagents import torch_utils
  File "/usr/local/lib/python3.9/site-packages/mlagents/torch_utils/__init__.py", line 1, in <module>
    from mlagents.torch_utils.torch import torch as torch  # noqa
  File "/usr/local/lib/python3.9/site-packages/mlagents/torch_utils/torch.py", line 6, in <module>
    from mlagents.trainers.settings import TorchSettings
  File "/usr/local/lib/python3.9/site-packages/mlagents/trainers/settings.py", line 644, in <module>
    class TrainerSettings(ExportableSettings):
  File "/usr/local/lib/python3.9/site-packages/mlagents/trainers/settings.py", line 667, in TrainerSettings
    cattr.register_structure_hook(
  File "/usr/local/lib/python3.9/site-packages/cattr/converters.py", line 207, in register_structure_hook
    self._structure_func.register_cls_list([(cl, func)])
  File "/usr/local/lib/python3.9/site-packages/cattr/dispatch.py", line 55, in register_cls_list
    self._single_dispatch.register(cls, handler)
  File "/usr/local/Cellar/python@3.9/3.9.12/Frameworks/Python.framework/Versions/3.9/lib/python3.9/functools.py", line 855, in register
    raise TypeError(
TypeError: Invalid first argument to `register()`. typing.Dict[mlagents.trainers.settings.RewardSignalType, mlagents.trainers.settings.RewardSignalSettings] is not a class.

'''

A: As user19218911 mentions, Python 3.9 is not compatible. Neither is Python 3.10.
Install Python 3.8, create the virtual environment, and download the packages using that version of python.
py -3.8 -m venv venv

venv/Scripts/activate

python install torch

python install mlagents

mlagents-learn --help

A: Python 3.9 is not compatible. No idea why.


text:
Q: Obter um html e guardar em variável Tenho um html simples em arquivo e quero guetarda-lo em uma variavel para usar, eu fiz o get assim:
 let popup = '';
 $.get( "popup.html", function( data ) {
     // the contents is now in the variable data
     console.log("data"+data);
     popup =  data;
 });
 console.log("popup"+popup);

Porem não esta salvando em popup, o log é:
    popup
(index):247 data
a

c

dc

ca

data possui meu html, porem o popup não, estou fazendo algo errado?

A: Você está chamando uma função assíncrona ($.get) e querendo atribuir o retorno à variável popup antes dela retornar algum valor. Você poderia usar o método $.ajax com o parâmetro async: false, mas não é recomendado devido ao aviso:

Synchronous XMLHttpRequest on the main thread is deprecated because of
  its detrimental effects to the end user's experience
Saiba mais neste tópico...

O que você pode fazer é chamar uma função que retorna o valor de data do $.get após ele ser processado, usando .then():
function htmlPopup(){
   return $.get( "popup.html").then(function(data){
      return data;
   });
}

htmlPopup().then(function(popup){
   console.log(popup);

   // resto do código que irá usar a variável popup

});

A: popup = $.get( "popup.html", function( data ) { return(data)});

Já pega o retorno na variavel


text:
Q: Issue regarding logging the pose object in posenet of tensorflow.js When I run the above code only the pose object of the last image is logged 5 times.
I want to log the pose object of each image.
I am using the http-server of node.js
There is no error in the following code, Any help would be appreciated and thanks in advance.
<html>

<head>
    <meta charset="UTF-8">
    <!-- Load TensorFlow.js -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
    <!-- Load Posenet -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/posenet"></script>
</head>

<body>
    <img id='cat' crossorigin="anonymous" />
    <button onclick="myfun()">button</button>
    <script>
        function myfun() {
            arr = ["http://127.0.0.1:8080/pic1.jpeg", "http://127.0.0.1:8080/pic2.jpeg", "http:  //127.0.0.1:8080/pic3.jpeg", "http://127.0.0.1:8080/pic4.jpeg", "http://127.0.0.1:8080/pic5.jpeg"]
            var x;
            for (x of arr) {
                document.getElementById("cat").src = x;
                var flipHorizontal = false;
                var imageElement = document.getElementById('cat');
                imageElement.crossOrigin = "Anonymous";
                posenet.load({
                    architecture: 'MobileNetV1',
                    outputStride: 16
                }).then(function(net) {
                    const pose = net.estimateSinglePose(imageElement, {
                        flipHorizontal: true
                    });
                    return pose;
                }).then(function(pose) {
                    console.log(pose);
                })
            }
        }
    </script>
</body>

</html>

A: the for loop is running async operation. By the time both posenet calls have resolved, the image has been set to the last item of the for loop.
Using async ... await will prevent to have the posenet estimation only for the last item of the loop.
async function myfun() {
        arr = ["http://127.0.0.1:8080/pic1.jpeg", "http://127.0.0.1:8080/pic2.jpeg", "http:  //127.0.0.1:8080/pic3.jpeg", "http://127.0.0.1:8080/pic4.jpeg", "http://127.0.0.1:8080/pic5.jpeg"]
        var x;
        for (x of arr) {
            document.getElementById("cat").src = x;
            var flipHorizontal = false;
            var imageElement = document.getElementById('cat');
            imageElement.crossOrigin = "Anonymous";
            const p = new Promise((resolve, reject) => {
                imageElement.onload = _ => {
                    resolve(imageElement)
                }
            })
            const net = await posenet.load({
                architecture: 'MobileNetV1',
                outputStride: 16
            })

            const pose = await net.estimateSinglePose(await p, {
                flipHorizontal: true
            });

            console.log(pose);
        }

Additionnaly, the model could be loaded before running the loop. A single instance of the model can be used for all estimations.

A: Change the loop from for (x of arr) { to for (var x = 0; x < arr.length; x++) {
x = arr[x];
...
...
}
And it will work as it should.