text:
Q: IE won't clear textarea value Back to my framework again. I have a method which gets the element's value, clears the element's value in dom, and then puts it back in letter by letter. Tested it in Chome, FF and IE (10). Everything is working fine. But there's a small problem with IE. It won't clear the element's value if I refresh the page while the script is executing. Or after it, doesn't really make a difference.
<textarea cols="60" id="textarea">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas suscipit lacus non hendrerit cursus.
</textarea>

<script>
(function(){
    (this[arguments[0]] = function selector(id){
        if(!(this instanceof selector)) {
            return new selector(id);
        }
        this.elm = document.getElementById(id);
    }).prototype = {
        type:       function(delay) {
                        var elm = this.elm;
                        var status;
                        if ('value' in elm) {
                                var text = elm.value;
                                elm.value = "";
                                status = 0;
                            } else if ('innerHTML' in elm)  {
                                var text = elm.innerHTML;
                                elm.innerHTML = "";
                                status = 1;
                            }
                        var letters = text.split("");
                        var counter = 0;
                        function write() {
                            if (counter < letters.length) {
                                switch (status) {
                                    case 0: elm.value += letters[counter];      break;
                                    case 1: elm.innerHTML += letters[counter];  break;
                                }
                            }
                            counter += 1;
                        }
                        setInterval(write, delay);
                    },
   };
})('$');

$('textarea').type("100");

FIDDLE
Is this IE related problem or am I missing something in the code? I feel like it's probably IE >.>

A: I'm pretty sure this is an IE related problem. IE 10 tries to be user-friendly and keeps changed input text in textareas even after a page refresh.
Now here's the problem: Your script already tries to clear the textarea before IE restores the text from the previous page load. Hence your script then adds the new text to the old text.
So a simple workaround would be giving IE a little time to restore the text before starting your typefunction and clearing the textarea. However, you will have to get the textarea's original content before IE overwrites it.
And just something I noticed while looking at your code: Using setInterval for this effect is a bad idea since the function will keep running (and counting) forever even after the complete text has been written to the textarea; you'll have to use clearInterval.
Here's the corrected code (changes are commented). This works for me in FF, IE 10 and Chrome.
(function(){
    (this[arguments[0]] = function selector(id){
        if(!(this instanceof selector)) {
            return new selector(id);
        }
        this.elm = document.getElementById(id);
        this.elm.setAttribute("autocomplete", "off");
    }).prototype = {
        type: function(delay) {
            var elm = this.elm;
            var status;
            // Don't clear textarea here, won't have any effect; but get original textarea content
            if ('value' in elm) {
                var text = elm.value;
                status = 0;
            }
            else if ('innerHTML' in elm)  {
                var text = elm.innerHTML;
                status = 1;
            }
            var letters = text.split("");
            var counter = 0;
            var interval;
            function write() {
                if (counter < letters.length) {
                    switch (status) {
                        case 0: elm.value += letters[counter];      break;
                        case 1: elm.innerHTML += letters[counter];  break;
                    }
                }
                else {
                    // Clear timer
                    clearInterval(interval);
                }
                counter += 1;
            }
            setTimeout(function(){
                // Clear textarea after waiting a little; using 0 as timeout value should be perfect, no need for higher values
                if (status == 0) {
                    elm.value = "";
                }
                else {
                    elm.innerHTML = "";
                }
                interval = setInterval(write, delay);
            }, 0);
        },
    };
})('$');

$('textarea').type("100");


text:
Q: Stationary states of a triangular prism I need to find the wavefunctions of the stationary states of a 3d square potential well with its boundaries defined by a triangular prism - like the one illustrated on the wikipedia page:
https://en.wikipedia.org/wiki/Triangular_prism

The potential well (viewed in 1-d cross section) is a simple square potential well, and can be either finite (0 outside, -V inside) or infinite (0 inside, ∞ outside), both would be reasonable approximations for my purposes.
I.e. the potential is something like this in cross-section, but its full 3-D shape is that of the triangular prism:

[Any solution for a close approximation of this geometry may also be helpful (for example, if the problem is easier to solve for a prism with a Reuleaux triangular cross-section instead of equilateral, or for a potential well described by a continuous function or something, it may be close enough).]
Because of the reduced symmetry compared to the textbook cylindrical or spherical cases, I am not sure how to approach this.
Is anyone able to point me in the direction of a solution? Many thanks!

A: I'm unsure about the case with a finite well depth, but if the walls are infinitely hard this problem can be solved exactly. The solution is detailed in the papers

*

*Particle in an equilateral triangle: Exact solution of a nonseparable problem. Wai-Kee Li and S. M. Blinder. J. Chem. Educ. 64 no. 2, p. 130 (1987)

*Solution of the Schrödinger equation for a particle in an equilateral triangle. Wai‐Kee Li and S. M. Blinder. J. Math. Phys. 26, 2784 (1985)
Other papers with relevant solutions are here, here and here.
The loss of continuous rotational symmetry means that you do need to fully solve a two-dimensional PDE, but the discrete symmetry does help, in that the solutions are required to carry representations of the $D_3$ symmetry group. This means that there are strict relations between the values of the eigenfunctions at the different edges, and those can be exploited to 'stitch' together multiple copies of the domain to make up a translationally-invariant region,

and you therefore expect the solutions to be plane-wave exponentials in that expanded region, which then project back down to sums of exponentials on the inside of the triangle.

I'm not sure to what extent those methods carry over to the finite-depth version of the well, this paper uses numerical diagonalization to solve the problem, and googling for "triangular quantum dot" (probably the most helpful starting point) doesn't immediately yield anything promising, and neither of those bode very well for the existence of closed solutions. (Ditto for their absence in this review.) Since you state that the infinite-walls problem is OK for your purposes, I'd encourage you to just stick to that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to end APScheduler job after set number of seconds? I use APScheduler to schedule a job which calls an API every minute. I now get a massive error which ends with:
  File "/usr/lib/python2.7/httplib.py", line 1045, in getresponse
    response.begin()
  File "/usr/lib/python2.7/httplib.py", line 409, in begin
    version, status, reason = self._read_status()
  File "/usr/lib/python2.7/httplib.py", line 365, in _read_status
    line = self.fp.readline(_MAXLINE + 1)
  File "/usr/lib/python2.7/socket.py", line 476, in readline
    data = self._sock.recv(self._rbufsize)
  File "/usr/lib/python2.7/ssl.py", line 341, in recv
    return self.read(buflen)
  File "/usr/lib/python2.7/ssl.py", line 260, in read
    return self._sslobj.read(len)
SSLError: The read operation timed out
WARNING:apscheduler.scheduler:Execution of job "getAndStoreAPICallResult
(trigger: cron[minute='*'], next run at: 2014-07-08 15:37:00)" skipped: maximum
number of running instances reached (1)

So I guess that the API call somehow doesn't get a response and therefore never finishes. This inhibits running the next job, because the first has never ended. Because of this, it somehow cannot start running a new job.
I could of course increase the number of allowed concurrent running instances, but that wouldn't really solve the problem. I guess I need to make the job end if it hasn't finished after a certain number of seconds (lets say 5).
Because I've got a couple other API-call-jobs that I start with APScheduler it would be awesome if I can somehow solve this using APScheduler. Does anybody know if APScheduler makes it possible to terminate too long running jobs, or do I need to solve this in another way?
All tips are welcome!

A: Since there is no way to terminate a thread from outside, consider setting a shorter SSL timeout.


text:
Q: Read uint8 from []byte without creating a bytes.Buffer How to read a unit8 from []byte without creating a bytes.Buffer. The value has been written to the buffer like this,
buf := new(bytes.Buffer)
binary.Write(buf, binary.BigEndian, uint32(1))
binary.Write(buf, binary.BigEndian, uint8(1))
b := buf.Bytes()

While decoding, it can easily be done for uint32, like the following...
len := binary.BigEndian.Uint32(b[:4])

But for the uint8, the only way to retrieve the value that I could come up with, is to create a buffer and then read the first byte,
buf := new(bytes.Buffer)
_, err := buf.Write(b[4:5])
// error handling ...
id = buf.ReadByte()

It seems like there's no method in the encoding/binary pkg for uint8 value retrieval. And I guess there's probably some good reason behind it.
Question: Is there any other way to read uint8 from that []byte without creating a Buffer??

A: Us an index expression to get an single uint8 from a slice.
len := binary.BigEndian.Uint32(b[:4])
id := b[4]  // <-- index expression

Note that byte is an alias for uint8.

A: Here's an elegant way that I found,
var len uint32
var id uint8
binary.Read(buf, binary.BigEndian, &len)
binary.Read(buf, binary.BigEndian, &id)

// this method doesn't need you to create a buffer for each value read


text:
Q: By returning a pointer that points to a node, is the rest of the list returned as well? c++ I have a project to do where I have to change SLList to LispList and add a few other functions. My only question is that My prof. has asked us not to create new nodes for a function called rest(), where the rest list is returned without the head.
Node* rest(){
      Node* nextToHead = head -> next; //this is a pointer to the next node in the list
      return nextToHead;
    }

by using the pointer nextToHead, will it point to the rest of the list as well?
If not, it'll be great if you guys can give me tips on how to return the list without the head and without using any other nodes.

A: While that technically does return a pointer to the rest of the list, or at least its nodes, the "rest" of a Lisp list is itself a Lisp list – not a different type (like node).
A "Lisp list" doesn't have a head as such; it looks pretty much like this:
struct List
{
    ElementType data;
    List* next;
};

and has the operations
ElementType first(List* l) { return l->data; } /* or "car" */
List* rest(List* l) { return l->next; }        /* or "cdr" */

or, as members:
ElementType List::first() { return data; }
List* List::rest() { return next; }

Note that every node in a Lisp list is the "head" of a sublist of the entire list.

A: When you return a Node pointer, everything the Node exposes can be used and abused. This includes the rest of the list.
The usual solution is to abstract the Node behind an iterator so that the user doesn't even see a Node. All they get is an iterator. The iterator still provides access to the rest of the list, so you have to restrict things even further
SingleNode rest(){
  return SingleNode (head -> next);
}

where SingleNode looks something like
class SingleNode
{
    Node* node;
public:
    MyDataType& operator*()
    {
        return node->data;
    }
};

If you can't do this,

*

*Make the links in Node private to limit access.

*Make SLList a friend of Node so only Node and SLList can see the links.

*Do not have any accessor functions for the links.

Example:
struct Node
{
    friend class SLList;
    MyDataType data;
    // other public stuff
private:
    Node * next;
    // other private stuff
};

Now the holder of a Node pointer can not see the rest of the list. They can still blow up the list by damaging the Node they have access to, but they have to work at it.

A: Yes, your code is correct for your question "not to create new nodes for a function called rest(), where the rest list is returned without the head."
But you need to delete the head node in case your professor want. But he not mention it so I assume that he just want to return the rest without head.
template<typename T>
struct ListNode{
    T value;
    ListNode<T>* next;
    ListNode(const T &v) : value(v), next(nullptr) {}
};

ListNode<int>* rest(ListNode<int> *head)
{
    if (head) // head is not nullptr
        return nullptr;
    else
        return head->next;
}

You could imagine like below:
In example, we have a list with a few elements and a head pointer which point to the first element:
0x1             0x2                    0x3
-------         --------------
|head |     --> |value1| next|    -->  .....
-------         --------------

so that mean :
&head = 0x1;  // the address of pointer head is 0x1
head  = 0x2;  // head pointer will point to the block memory which have address 0x2, i mean, the first element of list
next  = 0x3;  // next pointer will point to the block memory which have address 0x3, the second element of list
So when we call "return head->next", you can easy see that it will return 0x3, the address of the second element.


text:
Q: Is there any efficient pdf library in react which gets the base64 content from API and displays the output in the form of pdf? I am using a library in React called react-pdf which is having a component Document. Document Component contains a property called file (whose input type is a string).
How can I pass my response(props from redux) which is a base64 content, from the API into file property of Document?. So, Is there any library that accepts my base64 content from API and displays the output in a pdf document?
Here is the sample code :
import React from 'react';
import { connect } from 'react-redux';
import { Document } from 'react-pdf';

import { pdfData } from '../Store/ActionCreators'

class Billing extends React.Component {

  componentDidMount() {
    this.props.pdfData(mobile);
  }

  render() {
    const { base64 } = this.props;
    return (
      <Document file=''>

      </Document>
    )
  }
}

const mapStateToProps = state => ({
  base64: state.login.data
})

export default connect(mapStateToProps, { pdfData })(Billing);

If I pass base64 to file then it is considering it as a string and outputting as base64.
Is there any relevant solution to work it out effectively?

A: Pdf-lib does support base64 by default and attached a sample to show how, and you need to know the pages numbers for your base64 document and to do that I used pdf-lib that I pass the base64 and get the attributes will be used to manipulate base64 document "rotating-scaling-merging-pdf-addImage-etc"
Sandbox Sample
const pdfDocument = await PDFDocument.load(base64);
const numPages = pdfDocument.getPageIndices();

Then pass the props and your data to as follow:
<Document file={`data:application/pdf;base64,${base64}`}>

             {numPages.map((page, ind) => {
              return <div key={ind} id={`viewer-page-${ind+1}`} className=" some-class-names">
                <Page
                  key={`page_${ind + 1}`}
                  pageNumber={ind + 1}
                  scale={1} // you can scale by updating this
                  rotate={0} // you can scale by updating this
                  className={'some-class-names-page'}
                  width={400}
                  renderAnnotationLayer={false} // true by default
                  onRenderSuccess={renderMetricTracker}
                />
              </div>;
            })}
</Document>


text:
Q: Setting data to the elem using jquery.tmpl I have set the data to div element and append it to another div element like this,
var dt = { id: 0 };
$.template("temp", '
${id}
');
$.tmpl("temp", dt).appendTo("#div1");

Its working fine. I am appending it in document ready method.
My requirement is, Its(div2) click event i have to access dt.
Is it possible?
Question 2: i have set this data to a lot of elements. How to get those elements?
Thanks in advance.

A: You can use $.tmplItem:
var dt = { id: 222, text: 'My value id 222' };

$.template("temp", '
${id}
');
$.tmpl("temp", dt).appendTo("#div1");

$(document).on('click', '.innerDiv', function() {
    // gets the data item associated to the rendered template
    var dataItem = $.tmplItem(this);
    // dataItem.data holds the data itself
    alert(dataItem.data.text);
});

DEMO

For the second question, I don't know a way to easily get the list of renderings of a specific template with the API.
What you could do though is to add a data- attribute to your template markup which would allow you to retrieve them easily:
$.template("temp", '
${id}
');

Then you can select all renderings which has an attribute "data-tmpl" with value "temp":
$('[data-tmpl="temp"]')

I have updated the demo in that way.
Maybe there is some other way but I'm that familiar with jQuery template.


text:
Q: Asp Mvc 3 - Restful web service for consuming on multiple platforms I am wanting to expose a restful web service for posting and retrieving data, this may be consumed by mobile devices or a web site.
Now the actual creation of the service isn't a problem, what does seem to be a problem is communicating from a different domain.
I have made a simple example service deployed on the ASP.NET development server, which just exposes a simple POST action to send a request with JSON content. Then I have created a simple web page using jquery ajax to send some dummy data over, yet I believe I am getting stung with the same origin policy.
Is this a common thing, and how do you get around it? Some places have mentioned having a proxy on the domain that you always request a get to, but then you cannot use it in a restful manner...
So is this a common issue with a simple fix? As there seem to be plenty of restful services out there that allow 3rd parties to use their service...

A: How exactly are you "getting stung with the same origin policy"?  From your description, I don't see how it could be relevant.  If yourdomain.com/some-path/defined-request.json returns a certain JSON response, then it will return that response regardless of what is requesting the file, unless you have specifically defined required credentials that are not satisfied.
Here is an example of such a web service.  It will return the same JSON object regardless of from where the request is made: http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true
Unless I am misunderstanding you (in which case you should clarify your actual problem), the same origin policy doesn't really seem to apply here.
Update Re: Comment
"I make a simple HTML page and load it as file://myhtmlfilelocation/myhtmlfile.html and try to make an ajax request"
The cause of your problem is that you are using the file:// URL scheme, instead of the http:// protocol scheme.   You can find information about this scheme in Section 3.10 of RFC 1738.  Here is an excerpt:

The file URL scheme is used to designate files accessible on a particular host computer.  This scheme, unlike most other URL schemes, does not designate a resource that is universally accessible over the Internet.

You should be able to resolve your issue by using the http:// scheme instead of the file:// scheme when you make your asynchronous HTTP request.


text:
Q: Extract subset of postgis data to sqlite using SQL query I have a large vector mapping dataset held in postgis.  This consists of about 20 individual tables in a single schema.  I want to extract a subset of each of these tables into a standalone sqlite database using ogr2ogr.  This code from the postgis website does this and this works ok for transferring the entirety of each table:
    ogr2ogr --config PG_LIST_ALL_TABLES YES --config PG_SKIP_VIEWS YES -f "SQLite" mydb.sqlite -progress PG:"dbname='mydb' \
  active_schema=myschema schemas=myschema host='localhost' port='5432' user='myuser' password='mypass' " -lco LAUNDER=yes \
  -dsco SPATIALITE=yes -lco SPATIAL_INDEX=yes -gt 65536

However, I would like to only export a subset of each table based on an field called 'Tile_Name'.
I assume I can use the keyword '-clipdstwhere' to extract data based on an attribute, for example where the 'Tile_Name' field is NT, NY, or NZ?
In a standard definition query I would use Tile_Name IN (NT, NY, NZ), but this obviously isn't the correct syntax as I get the error "ERROR 1: No field definitions found for 'IN', is it a table?".
There are also options for clipping the data by a boundary or bounding box - might this be an easier way?


text:
Q: How to convert an int[] into an List in Android? It seems like a simple matter; I have an int[] that I prepopulate at initialization, then I want to convert it to a List<Integer>, but this doesn't work:
int[] ACTIVITIES = {0,1,2};
List<Integer> acta = Arrays.asList(ACTIVITIES);

Arrays.asList() wants to make a List<int[]> instead, and I don't understand why.  How do I make a List<Integer> out of an int[]?

A: change from int to Integer
Integer[] ACTIVITIES = {0,1,2};

A: In your case you don't need an array at all:
List<Integer> acta = Arrays.asList(0, 1, 2);

A: List<Integer> acta = new ArrayList();
for(int i=0;i<ACTIVITIES.Length;i++){
      acta.Add(ACTIVITIES[i]);
}

this is sample code,maybe the keywords different from that i wrote but the solution is like this.


text:
Q: 553 Can't open that file: Permission denied so, I work with a IDE (NetBeans) and when I try to upload file on the server, I've got this error :
Failed:
file      web/config.php     553 Can't open that file: Permission denied
Runtime: 5 ms, processed: 0 file(s), 0 KB

But I can download the same file...
Os : CentOs7
A idea ?
Thanks !

A: If you had the same problem -> chown group:user file/folder


text:
Q: Duplicate classes in same jars of different versions - Android I was trying to integrate iText in my Android Studio project when the sync successfully completed.
Then I wrote some code and tried to build and test it when it gave an error (A huge one) that duplicate classes were found in same jars of different versions. (I have removed some because there were a lot)
Duplicate class com.keypoint.PngEncoder found in modules jcommon-1.0.15.jar (jfree:jcommon:1.0.15) and jcommon-1.0.17.jar (org.jfree:jcommon:1.0.17)
Duplicate class org.jfree.JCommon found in modules jcommon-1.0.15.jar (jfree:jcommon:1.0.15) and jcommon-1.0.17.jar (org.jfree:jcommon:1.0.17)
Duplicate class org.jfree.JCommonInfo found in modules jcommon-1.0.15.jar (jfree:jcommon:1.0.15) and jcommon-1.0.17.jar (org.jfree:jcommon:1.0.17)
Duplicate class org.jfree.base.AbstractBoot found in modules jcommon-1.0.15.jar (jfree:jcommon:1.0.15) and jcommon-1.0.17.jar (org.jfree:jcommon:1.0.17)
Duplicate class org.jfree.base.BaseBoot found in modules jcommon-1.0.15.jar (jfree:jcommon:1.0.15) and jcommon-1.0.17.jar (org.jfree:jcommon:1.0.17)
Duplicate class org.jfree.base.BasicProjectInfo found in modules jcommon-1.0.15.jar (jfree:jcommon:1.0.15) and jcommon-1.0.17.jar (org.jfree:jcommon:1.0.17)
...
Duplicate class org.jfree.base.BasicProjectInfo$OptionalLibraryHolder found in modules jcommon-1.0.15.jar (jfree:jcommon:1.0.15) and jcommon-1.0.17.jar (org.jfree:jcommon:1.0.17)
Duplicate class org.jfree.base.BootableProjectInfo found in modules jcommon-1.0.15.jar (jfree:jcommon:1.0.15) and jcommon-1.0.17.jar (org.jfree:jcommon:1.0.17)
jcommon-1.0.17.jar (org.jfree:jcommon:1.0.17)
Duplicate class org.jfree.util.WaitingImageObserver found in modules jcommon-1.0.15.jar (jfree:jcommon:1.0.15) and jcommon-1.0.17.jar (org.jfree:jcommon:1.0.17)

Go to the documentation to learn how to Fix dependency resolution errors.

From this I Understand that the different versions of the same jar caused this issue. So I tried to remove the one with lower version (jcommon-1.0.15 and 1 more ) but when i synced the project with gradle, it again downloaded them and if i ran it offline it said that dependencies couldn't be resolved. Similar is the case with the jars of higher version.
Update:
Here are my build.gradle files as requested:
Project level:
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://jitpack.io' }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

App level:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.nalin.app"
        minSdkVersion 19
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.activity:activity:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.2.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation project(path: ':libraries:OpenCV')
    implementation 'itext:itext:4.2.1'
}

I Also have included OpenCV so here is the gradle file for OpenCV:
apply plugin: 'com.android.library'

buildscript {
    repositories {
        mavenCentral()
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.3'
    }
}

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 29
        versionCode 2480
        versionName "2.4.8"
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            res.srcDirs = ['res']
            aidl.srcDirs = ['src']
        }
    }
}

A: Thanks to the guys in the comments, I could solve the problem quite easily.
What i did was ran gradlew app:dependencies and it gave me a dependency tree.
From that tree i could make out which parts of the library required which transitive dependencies and i excluded the jcommon library of the lower version which did not have any other dependencies using:
exclude group: 'jfree', module: 'jcommon'


text:
Q: How to use cgitb for enhanced traceback logging in a flask app? When exceptions occur in my Flask app I want to be able to use cgitb for enhanced traceback logging when exceptions occur.
Simply doing
import cgitb
cgitb.enable(format="text")

at the top of the file where the app is initialized is not doing the trick. I am still getting the standard python traceback when an exception occurs.
There could be an issue caused by how I currently have logging set up in my application, but I haven't been able to figure it out.
app = Flask(__name__)
streamHandler = logging.StreamHandler(sys.stdout)
streamHandler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s:% (message)s'))
app.logger.addHandler(streamHandler)
app.logger.setLevel(logging.DEBUG)

@app.route('/')
def main_route():
    a = 0
    b = 2
    c = b / 2

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

I'd expect the traceback results to be like:
$ python3 cgitb_local_vars.py

ZeroDivisionError
Python 3.7.1: .../bin/python3
Sun Dec  9 10:46:17 2018

A problem occurred in a Python script.  Here is the sequence of
function calls leading up to the error, in the order they
occurred.

 .../cgitb_local_vars.py in <module>()
   18 def func1(a, b):
   19     c = b - 5
   20     return func2(a, c)
   21
   22 func1(1, 5)
func1 = <function func1>

 .../cgitb_local_vars.py in func1(a=1, b=5)
   18 def func1(a, b):
   19     c = b - 5
   20     return func2(a, c)
   21
   22 func1(1, 5)
global func2 = <function func2>
a = 1
c = 0

 .../cgitb_local_vars.py in func2(a=1, divisor=0)
   13
   14 def func2(a, divisor):
   15     return a / divisor
   16
   17
a = 1
divisor = 0
ZeroDivisionError: division by zero
    __cause__ = None
    __class__ = <class 'ZeroDivisionError'>
    __context__ = None
    __delattr__ = <method-wrapper '__delattr__' of
    ZeroDivisionError object>
    __dict__ = {}
    __dir__ = <built-in method __dir__ of ZeroDivisionError
    object>
    __doc__ = 'Second argument to a division or modulo operation
    was zero.'
    __eq__ = <method-wrapper '__eq__' of ZeroDivisionError
    object>
    __format__ = <built-in method __format__ of
    ZeroDivisionError object>
    __ge__ = <method-wrapper '__ge__' of ZeroDivisionError
    object>
    __getattribute__ = <method-wrapper '__getattribute__' of
    ZeroDivisionError object>
    __gt__ = <method-wrapper '__gt__' of ZeroDivisionError
    object>
    __hash__ = <method-wrapper '__hash__' of ZeroDivisionError
    object>
    __init__ = <method-wrapper '__init__' of ZeroDivisionError
    object>
    __init_subclass__ = <built-in method __init_subclass__ of
    type object>
    __le__ = <method-wrapper '__le__' of ZeroDivisionError
    object>
    __lt__ = <method-wrapper '__lt__' of ZeroDivisionError
    object>
    __ne__ = <method-wrapper '__ne__' of ZeroDivisionError
    object>
    __new__ = <built-in method __new__ of type object>
    __reduce__ = <built-in method __reduce__ of
    ZeroDivisionError object>
    __reduce_ex__ = <built-in method __reduce_ex__ of
    ZeroDivisionError object>
    __repr__ = <method-wrapper '__repr__' of ZeroDivisionError
    object>
    __setattr__ = <method-wrapper '__setattr__' of
    ZeroDivisionError object>
    __setstate__ = <built-in method __setstate__ of
    ZeroDivisionError object>
    __sizeof__ = <built-in method __sizeof__ of
    ZeroDivisionError object>
    __str__ = <method-wrapper '__str__' of ZeroDivisionError
    object>
    __subclasshook__ = <built-in method __subclasshook__ of type
    object>
    __suppress_context__ = False
    __traceback__ = <traceback object>
    args = ('division by zero',)
    with_traceback = <built-in method with_traceback of
    ZeroDivisionError object>

The above is a description of an error in a Python program.
Here is
the original traceback:

Traceback (most recent call last):
  File "cgitb_local_vars.py", line 22, in <module>
    func1(1, 5)
  File "cgitb_local_vars.py", line 20, in func1
    return func2(a, c)
  File "cgitb_local_vars.py", line 15, in func2
    return a / divisor
ZeroDivisionError: division by zero

 Demo Code
from flask import Flask
import cgitb
import logging
import sys
cgitb.enable(format="text")

app = Flask(__name__)
streamHandler = logging.StreamHandler(sys.stdout)
streamHandler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s:% (message)s'))
app.logger.addHandler(streamHandler)
app.logger.setLevel(logging.DEBUG)

@app.before_request
def before_request():
    a = 0
    b = 2
    c = b / a

@app.route('/')
def main_page():
    a = 0
    b = 2
    c = b / a
    return 'Success'

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5005, debug=True)

 Result
Connected to pydev debugger (build 182.4505.18)
 * Serving Flask app "flask_app_demo" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://0.0.0.0:5005/ (Press CTRL+C to quit)
 * Restarting with stat
pydev debugger: process 36941 is connecting

 * Debugger is active!
 * Debugger PIN: 334-725-940
10.81.19.181 - - [30/Jan/2019 17:46:47] "GET / HTTP/1.1" 500 -
Traceback (most recent call last):
  File "/python/site-packages/flask/app.py", line 2309, in __call__
    return self.wsgi_app(environ, start_response)
  File "/python/site-packages/flask/app.py", line 2295, in wsgi_app
    response = self.handle_exception(e)
  File "/python/site-packages/flask/app.py", line 1741, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/python/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/python/site-packages/flask/app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "/python/site-packages/flask/app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/python/site-packages/flask/app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/python/site-packages/flask/_compat.py", line 35, in reraise
    raise value
  File "/python/site-packages/flask/app.py", line 1811, in full_dispatch_request
    rv = self.preprocess_request()
  File "/python/site-packages/flask/app.py", line 2087, in preprocess_request
    rv = func()
  File "/flask_app_demo.py", line 18, in before_request
    from _pydev_bundle import fix_getpass
ZeroDivisionError: division by zero


text:
Q: Names and terms Are there any packages that would help to handle titles and names in the text?

*

*formatting: italics, quotation marks

*index generation: removing articles, rearranging names to Last, First in the index

Or that is what you have to do yourself? Like these:
\newcommand{\ftfilm}[1]{\index{\textit{#1}}}
\newcommand{\ftarticle}[1]{``\index{#1}''}
\newcommand{\ftname}[1]{\index{#1}}

A: If I understand you right, you want

*

*films in italic

*articles in "quotation marks"

*names just rearranged

You state that you want to remove articles from the index, yet \ftarticle writes them to the index? Or do you want to remove articles at the beginning of titles, e.g. put "The Fog" as "Fog, The"?
Anyways, you could do it like this
\newcommand{\ftfilm}[1]{\textit{#1}\index{\textit{#1}}} % write the movie to text and index
\newcommand{\ftfilmra}[2]% article, title
  {\textit{#1 #2}\index{\textit{#2, #1}} % write "The Fog" in text and "Fog, The" in index

The same you can do with names:
\newcommand{\ftname}[2]% FName, LName
  {#1 #2\index{#2, #1}}% "John Smith" in Text, "Smith, John" in index


text:
Q: Android: Custom dialog view, change button color before showing for first time I'm making something like a social app.
I would like that if someone has already viewed something before, that the button in the view will change colors.
I have a method to check if someone has viewed this list before. It works in the clickListener, and will say "Already pressed."
I'm having a hard time figuring out how to change the color of the button, maybe on the onCreate method. I've tried passing it as an argument, but the color will change on the second time the list is pulled up...
This is how I call up my dialog and pass it the list ID.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View r = inflater.inflate(R.layout.list_view_dialog_layout, container, false);

    checklistView = (UserlistView) r.findViewById(R.id.user_list);
    checklistview.getList(getArguments().getString("list_id")); // Can be modified

    return r;
}

in that function getList, I make my call to my database to get the info of the list.
public void getList(final String listID) {
    // TODO fetch list information from params and fill fields
    Event.requestEvent(listID, "AuthToken", new List.ListReceivedListener() {
        @Override
        public void onListReceived(lissts... lissteses) {
            List lst = lissteses[0];
            setInfo(lst);
            LISTID = listID;

        }
    });
}

public void setInfo(List lst){

    listTitleView.setText(lst.listName);
    viewsCount.setText(Integer.toString(lst.views));

}

I have a checker function to see if the user has already clicked the "have viewed"
public static boolean viewed(String id, final String user){
        DatabaseReference rootref = FirebaseDatabase.getInstance().getReference("views").child(id);
    rootref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if(dataSnapshot.hasChild(user)){
                result = true;
            }
            else{
                result = false;
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
    return result;
}

then, I wanted to call it in the getList() as such
if(viewed(lstID, curuser){
     viewButton.setColorFilter(R.color.blue);
 }

this doesn't work for the first time the view is created, and so, if the user has already clicked view, logs out and logs back in, and click view again, messing up the view count.

A: int flag=0;
    button.setOnClickLitener(new OnClickListener()){

        @Override
        public void onClick(View arg0) {
            flag++;

        }
    });
if(flag>0){
 button.setBackgroundColor(getResources().getColor(R.color.yourColor));
}

A: Another solution is this.
button.setBackgroundColor(getResources().getColor(R.color.youCustomColor));


text:
Q: Using Discord user ID to store data in .JSON file I feel like the title of this problem just made this whole thing even more confusing. But here is the long of it:
I have a bot that uses .JSON files to store information a user puts into it upon creation. However, to ensure that they are creating one, and only one, file, I have tied it to their unique ID. This ensures that even if a user changes nicknames, he can only create one file for himself. Of course, the .JSON file in the background, will be named '123456789.txt'.
This has been done successfully, but I want to add in bot commands that will allow OTHER users to obtain information stored in that user's file. So, for example: If Joe wants to see what Ned's favorite color is, he could use a simple command like:
!favcolor Ned

And the bot will fine Ned's .JSON file (123456789.txt), look for what value is stored under the key "color", and print out the results.
The problem isn't that I can't find people's user ID (ctx.message.author.id). The problem is that I don't know how to let someone else do such, as, as far as I can find out, there is no way to ensure that when someone precedes '!favcolor' with 'Ned', the bot will find 123456789.txt.
The only solution I can think of at the moment is to maintain a .JSON file at the moment of creation of a file that grabs the user's unique ID, and then pairs it with the name of the user. Something like:
{
"Ned": "123456789"
"Joe": "234567891"
"Sam": "345678912"
}

And so on. Then it just looks at that JSON, and grabs the correct ID. Is this a good approach? Or am I missing something much easier that is already built into discord.py?

A: Discord users are only uniquely identifiable by ID or username#discriminator.
You can easily get the ID from a User object, given that you're able to identify it from the user input in question.
A .JSON file with a .txt extension is contradictory, and you should be storing JSON data in JSON files rather than text files.
Also, I'd recommend using a database rather than JSON files, as there are lot of advantages to doing so and a lot of disadvantages to continuing to use JSON files.


text:
Q: web api - disable origins not working i wont to enable access to my web api for only one origin.
I tried the next steps:
1.add this lines to WebApiConfig:
 var cors = new EnableCorsAttribute("https://allow-access.com", "*", "*");
 config.EnableCors(cors);

2.add this attribute above the ApiController:
[EnableCors(origins: "https://allow-access.com", headers: "*", methods: "*")]

but still the api allow access to all origin.
Someone has an idea why?

A: Technically, below statement will enable CORS only for one origin "https://allow-access.com"
var cors = new EnableCorsAttribute("https://allow-access.com", "*", "*");
 config.EnableCors(cors);

I'm not sure how you are testing your API for all origins but as per the official documentation, only this will enable all origins in Web API:
// Allow CORS for all origins. (Caution!)
[EnableCors(origins: "*", headers: "*", methods: "*")]


text:
Q: nginx serve static files and run server on same host Almost have this working how I want - basically I'm trying to serve static files on host/static (including directory listings), and serve to another backend for any non-file request (including the default site).  The config below seems to do this, but the ONE problem remaining is that I can't get to the root static dir with host/static - a trailing slash is required!  Any ideas?
My config:
location / {
  try_files /static/$uri /static/$uri/ @myserver;
}

location /static/ {
  alias /var/www/static_files/;
  autoindex on;
  disable_symlinks off;
}

location @myserver {
  proxy_pass              http://localhost:8081;
  proxy_set_header        Host $host;
  proxy_set_header        X-Real-IP $remote_addr;
  proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_connect_timeout   150;
  proxy_send_timeout      100;
  proxy_read_timeout      100;
  proxy_buffers           4 32k;
  client_max_body_size    8m;
  client_body_buffer_size 128k;
}

A: As @RichardSmith said - to get this behavior, just remove the trailing slash from the location and alias statements.


text:
Q: Using more than 2 IF conditions to identify different data types in a mixed column - Power Query I am trying to Add a new Column that uses multiple If conditions to check if a particular column contains a specific text, numbers formatted as text or textual values.
The below If conditon works only for the first 2 criteria but adding a 3rd checking criteria does not yield the desired NULL results for numeric values that are formatted as text.
===============================
ColumnToCheck       | NewColumn
===============================
R0                  |  Questions
Is this my life?    |  Is this my life?
0.5445              |  null
0.23                |  null
0.23335             |  null
===============================

The formula is:
= Table.AddColumn(PreviousStep, "NewColumn",
    each
if
       Value.Is([ColumnToCheck],Text.Type) and not Text.Contains([ColumnToCheck],"R0") then
     [ColumnToCheck]
else if
  Text.Contains([ColumnToCheck],"R0", Comparer.OrdinalIgnoreCase) then
     "Questions"
else if
Value.Is(Number.FromText([ColumnToCheck]),type number) then
     null
else
     null)

A: Maybe you need something like that
 if
    try Value.Is(Number.FromText([ColumnToCheck]), type number) otherwise Value.Is([ColumnToCheck],type number)
then
    null
else
    if
       Value.Is([ColumnToCheck],Text.Type) and not Text.Contains([ColumnToCheck],"R0")
    then
        [ColumnToCheck]
    else
        if
            Value.Is([ColumnToCheck],Text.Type) and  Text.Contains([ColumnToCheck],"R0", Comparer.OrdinalIgnoreCase)
        then
            "Questions"
        else
            null

Result in PQ looks like


text:
Q: setting text view according its position of the row a listview filled by SimpleCursorAdapter database with click on the row setting the text view according its position in of the row a list view filled from SimpleCursorAdapter from database on the click of the onlistitemclicked
my custom list view has an image& textview for a name and another invisible text view which will be visible and be setting with a different number on the row clicked only but the problem is that when i clicked any row the text appeared on the view at the first row only whatever the row i clicked
and I tried to use the set and get methods but i found its used for the Base Adapter.
and the textview which will visible is not from data base
can some one tell me how to do it please
here is a part of the code
public class Select_players_two extends ListActivity
{

    protected static class RowViewHolder
    {
        public TextView tvOne;
        public TextView tvTwo;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(android.view.Menu menu)
    {
        // TODO Auto-generated method stub
        return super.onCreateOptionsMenu(menu);
    }

    public class CustConAdpterSelect extends SimpleCursorAdapter
    {

          int i = 0;
          int count;
          private int layout;
          LayoutInflater inflator;
          final SQLiteConnector sqlCon = new SQLiteConnector(mContext);
          private ImageButton editBtn;
          private ImageButton delBtn;
          int id ;
          TextView txt_select;
          CharSequence txt_char;
          static final String KEY_No = "playerNo";
        public CustConAdpterSelect(Context context, int layout, Cursor c,
                String[] from, int[] to, int flags)
        {
            super(context, layout, c, from, to,0);
            this.layout = layout;
            inflator= LayoutInflater.from(context);
        }

         public View newView(Context context, Cursor cursor, ViewGroup parent)
            {
                LayoutInflater inflater = LayoutInflater.from(parent.getContext());
                View retView = inflater.inflate(R.layout.lv_name_photo, parent, false);

                RowViewHolder holder = new RowViewHolder();
                holder.tvOne = (TextView) retView.findViewById(R.id.name);
                holder.tvTwo = (TextView) retView.findViewById(R.id.txt_number);
         //       holder.tvOne.setOnClickListener(tvOneLapOnClickListener);
                retView.setTag(holder);

                return retView;
            }
        @Override
        public void bindView(View v, final Context context, Cursor c)
        {
            editBtn=(ImageButton) v.findViewById(R.id.edit_btn);
             if( editBtn.getVisibility() == View.VISIBLE )
                 editBtn.setVisibility(View.INVISIBLE);
                else
                    editBtn.setVisibility(View.INVISIBLE);

             //set delete button invisble
             delBtn=(ImageButton) v.findViewById(R.id.del_btn);
             if( delBtn.getVisibility() == View.VISIBLE )
                 delBtn.setVisibility(View.INVISIBLE);
                else
                    delBtn.setVisibility(View.INVISIBLE);

            //final int
             id = c.getInt(c.getColumnIndex(Contacts.ID));
            final String name = c.getString(c.getColumnIndex(Contacts.NAME));
            final String phone = c.getString(c.getColumnIndex(Contacts.PHONE));
            final String email = c.getString(c.getColumnIndex(Contacts.MAIL));
            final String fb = c.getString(c.getColumnIndex(Contacts.FB));
            final byte[] image = c.getBlob(c.getColumnIndex(Contacts.IMAGE));

            ImageView iv = (ImageView) v.findViewById(R.id.photo);

            if (image != null)
            {
                if (image.length > 3)
                {
                    iv.setImageBitmap(BitmapFactory.decodeByteArray(image, 0,image.length));
                }
            }

            TextView tname = (TextView) v.findViewById(R.id.name);
            tname.setText(name);
            TextView tphone = (TextView) v.findViewById(R.id.phone);
            tphone.setText(phone);
            TextView temail = (TextView) v.findViewById(R.id.email);
            temail.setText(email);
            txt_select=(TextView)v.findViewById(R.id.txt_number);

        //  final SQLiteConnector sqlCon = new SQLiteConnector(context);

            //for( i = 0; i <=4; i++)
        /*
            v.setOnClickListener(new View.OnClickListener()
            {

                @Override
                public void onClick(View v)
                {
                    //onitem clicked

         txt_char = txt_select.getText();
        {
            if (txt_char != null)
                {
                    int txt_int = Integer.parseInt(txt_char.toString());
                    int count = txt_int;
                    Log.d("count1",String.valueOf(count));
                    count++;
                     txt_select.setText(String.valueOf(count));
                     Log.d("count",String.valueOf(count));
                     if( txt_select.getVisibility() == View.INVISIBLE )
                         txt_select.setVisibility(View.VISIBLE);
                        else
                            txt_select.setVisibility(View.INVISIBLE);
                     Log.d("number", String.valueOf(i));

                }

                /*   if( txt_select.getVisibility() == View.INVISIBLE )
                         txt_select.setVisibility(View.VISIBLE);
                        else
                            txt_select.setVisibility(View.INVISIBLE);
                     i++;
                     Log.d("number", String.valueOf(i));*/
            /*  }
                }
              });
            */
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent)
        {
              final View view = super.getView(position, convertView, parent);
                final TextView textView = (TextView)view.findViewById(R.id.txt_number);

    /*          textView.setOnClickListener(new OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {

                        Log.i("Click", "TextView clicked on row " + position);
                        //  textView.setTag(position);
                        txt_char = txt_select.getText();
                           Log.d("txt", txt_char.toString());
                        if (txt_char != null)
                        {
                            int txt_int = Integer.parseInt(txt_char.toString());
                            Log.d("txt2", txt_char.toString());
                            int count = txt_int;
                            Log.d("count1",String.valueOf(count));
                            count++;
                            txt_select.setText(String.valueOf(count));

                             CharSequence txt_char2 = txt_select.getText();
                             Log.d("ttxt", txt_char2.toString());
                             Log.d("count",String.valueOf(count));
                             if( txt_select.getVisibility() == View.INVISIBLE )
                                 txt_select.setVisibility(View.VISIBLE);
                                else
                                    txt_select.setVisibility(View.INVISIBLE);
                             Log.d("number", String.valueOf(i));
                             i++;
                        }

        }*/
               // });   // TODO Auto-generated method stub
        return view;

        }

         private OnClickListener  tvOneLapOnClickListener = new OnClickListener()
         {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                 // get the RowViewHolder
                RowViewHolder holder = new RowViewHolder();
                // Get the holder for the row
                holder = (RowViewHolder) ((View) v.getParent()).getTag();
                if (holder.tvOne.getVisibility() == View.INVISIBLE)
                    holder.tvOne.setVisibility(View.VISIBLE);
                else
                    holder.tvOne.setVisibility(View.INVISIBLE);
            }

        };

    }

}

that is the database class "SQLiteConnector"
    public class SQLiteConnector
{
    private SQLiteDatabase db;
    private SQLiteHelper sqlHp,sqlhpc;
    private Cursor cur,curc;

    public SQLiteConnector(Context context)
    {
        sqlHp = new SQLiteHelper(context, Contacts.DB_NAME, null, 1);
        sqlhpc = new SQLiteHelper(context, Contacts.DB_NAME, null, 1);

    }
    // insert new player in the list//
    public void insertContact(String name, String phone, String mail,String fb,byte[] blob) {
        ContentValues cv = new ContentValues();
        cv.put(Contacts.NAME, name);
        cv.put(Contacts.PHONE, phone);
        cv.put(Contacts.MAIL, mail);
        cv.put(Contacts.FB, fb);
        cv.put(Contacts.IMAGE,blob);
        db = sqlHp.getWritableDatabase();
        db.insert(Contacts.TABLE, null, cv);
        db.close();
    }
    // insert the score sheet //
    public void insertContact_score(String score,  String  num_call, String  num_collection ,String shape_type,
                            String score_sec,  String  num_call_sec, String  num_collection_sec ,String shape_type_sec,
                            String score_third,  String  num_call_third, String  num_collection_third ,String shape_type_third,
                  String score_forth,  String  num_call_forth, String  num_collection_forth ,String shape_type_forth)
    {
        ContentValues cvscore = new ContentValues();
        cvscore.put(Contacts.SCORE_st, score);
        cvscore.put(Contacts.NUM_CALL_st, num_call);
        cvscore.put(Contacts.NUM_COLLECTION_st, num_collection);
        cvscore.put(Contacts.SHAPE_CALL_st, shape_type);

        cvscore.put(Contacts.SCORE_sec, score_sec);
        cvscore.put(Contacts.NUM_CALL_sec, num_call_sec);
        cvscore.put(Contacts.NUM_COLLECTION_sec, num_collection_sec);
        cvscore.put(Contacts.SHAPE_CALL_sec, shape_type_sec);

        cvscore.put(Contacts.SCORE_third, score_third);
        cvscore.put(Contacts.NUM_CALL_third, num_call_third);
        cvscore.put(Contacts.NUM_COLLECTION_third, num_collection_third);
        cvscore.put(Contacts.SHAPE_CALL_third,shape_type_third);

        cvscore.put(Contacts.SCORE_forth, score_forth);
        cvscore.put(Contacts.NUM_CALL_forth, num_call_forth);
        cvscore.put(Contacts.NUM_COLLECTION_forth, num_collection_forth);
        cvscore.put(Contacts.SHAPE_CALL_forth,shape_type_forth);

        //cvscore.put(Contacts.IMAGE,blob);
        db = sqlhpc.getWritableDatabase();
        db.insert(Contacts.TABLESCORE, null, cvscore);
        db.close();
    }

    public void updateContact_score(long id,String score,  String  num_call, String  num_collection ,String shape_type,
            String score_sec,  String  num_call_sec, String  num_collection_sec ,String shape_type_sec,
            String score_third,  String  num_call_third, String  num_collection_third ,String shape_type_third,
              String score_forth,  String  num_call_forth, String  num_collection_forth ,String shape_type_forth)
    {
        ContentValues cvscore = new ContentValues();
        cvscore.put(Contacts.SCORE_st, score);
        cvscore.put(Contacts.NUM_CALL_st, num_call);
        cvscore.put(Contacts.NUM_COLLECTION_st, num_collection);
        cvscore.put(Contacts.SHAPE_CALL_st, shape_type);

        cvscore.put(Contacts.SCORE_sec, score_sec);
        cvscore.put(Contacts.NUM_CALL_sec, num_call_sec);
        cvscore.put(Contacts.NUM_COLLECTION_sec, num_collection_sec);
        cvscore.put(Contacts.SHAPE_CALL_sec, shape_type_sec);

        cvscore.put(Contacts.SCORE_third, score_third);
        cvscore.put(Contacts.NUM_CALL_third, num_call_third);
        cvscore.put(Contacts.NUM_COLLECTION_third, num_collection_third);
        cvscore.put(Contacts.SHAPE_CALL_third,shape_type_third);

        cvscore.put(Contacts.SCORE_forth, score_forth);
        cvscore.put(Contacts.NUM_CALL_forth, num_call_forth);
        cvscore.put(Contacts.NUM_COLLECTION_forth, num_collection_forth);
        cvscore.put(Contacts.SHAPE_CALL_forth,shape_type_forth);

        //cvscore.put(Contacts.IMAGE,blob);
        db = sqlhpc.getWritableDatabase();
        db.update(Contacts.TABLESCORE, cvscore, Contacts.ID+"="+ id, null);
        db.close();
    }

    public void updateContact(long id,String name, String phone, String mail,String fb,byte[] blob) {
        ContentValues cv = new ContentValues();
        cv.put(Contacts.NAME, name);
        cv.put(Contacts.PHONE, phone);
        cv.put(Contacts.MAIL, mail);
        cv.put(Contacts.FB, fb);
        cv.put(Contacts.IMAGE,blob);

        db = sqlHp.getWritableDatabase();
        db.update(Contacts.TABLE, cv, Contacts.ID+"="+ id, null);
        db.close();
    }

    public Cursor getAllContacts() {
        db = sqlHp.getReadableDatabase();
        cur=db.query(Contacts.TABLE,null, null,null, null, null, "name");
        return cur;
    }

    public Cursor getAllScores() {
        db = sqlhpc.getReadableDatabase();
        curc=db.query(Contacts.TABLESCORE,null, null,null, null, null, "score_st");
        return curc;
    }
    public void deletescore(long id) {
        System.out.println("DELETE ");
        db = sqlhpc.getWritableDatabase();
        db.delete(Contacts.TABLESCORE, "_id="+id , null);
        db.close();
    }

    public Cursor getOneContact(long id) {
        db = sqlHp.getReadableDatabase();
        cur=db.query(Contacts.TABLE, null, "_id="+ id, null, null, null,null);
        return cur;
    }

    public void deleteContact(long id) {
        System.out.println("DELETE ");
        db = sqlHp.getWritableDatabase();
        db.delete(Contacts.TABLE, "_id="+id , null);
        db.close();
    }
}

A: I believe what you need to do is use the Tag facility of the row view container to identify the textview it contains and then retrieve it in the listener to identify the correct textview. The way I've done it is to use a holder for the row contained views, so you can access any that you need. For example:
protected static class RowViewHolder {
    public TextView tvOne;
    public TextView tvTwo;
}

Then in your newView method, populate the holder and set the Tag to it:
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View retView = inflater.inflate(R.layout.single_row_item, parent, false);

    RowViewHolder holder = new RowViewHolder();
    holder.tvOne = (TextView) retView.findViewById(R.id.name);
    holder.tvTwo = (TextView) retView.findViewById(R.id.txt_number);
    retView.setTag(holder);

    return retView;
}

In your listener then you can access the correct textview:
    public void onClick(View v) {
            ListView lv = (ListView) v.getParent();
            final int position = lv.getPositionForView((View) v.getParent());

            // get the RowViewHolder
            RowViewHolder holder = new RowViewHolder();
            holder = (RowViewHolder) ((View) v.getParent()).getTag();
            if(holder.tvOne.getVisibility() == View.INVISIBLE ) {
                holder.tvOne.setVisibility(View.VISIBLE);
            }
            else
            {
                holder.tvOne.setVisibility(View.INVISIBLE);
            }
    }

Apologies, but I've not been able to test this code but I hope it gives you a pointer to the process. You shouldn't need the RowViewHolder but I've included it so you or others can see how to access multiple views within the row.
You may find the this video helpful The World of ListView I think you'll find the relevant discussion at about 4:10 in which describes how the views are res-used and how index, position etc. relate.
I also found one of the answers to this question helpful Android: ListView elements with multiple clickable buttons

A: There are multiple ways of doing this. The way I was suggesting assumes you have a single code module for the activity containing the CustConAdpterSelect class. So the structure looks something like this.
package com.example.totastest;

// imports

public class Copy_2_of_MainActivity extends Activity {

protected static class RowViewHolder
{
    public TextView tvOne;
    public TextView tvTwo;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

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

public class CustConAdpterSelect extends SimpleCursorAdapter
{
    // ...

    public CustConAdpterSelect(Context context, int layout, Cursor c, String[] from, int[] to)
    {
        super(context, layout, c, from, to, 0);
        // ...
    }

    public View newView(Context context, Cursor cursor, ViewGroup parent)
    {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View retView = inflater.inflate(R.layout.lv_name_photo, parent, false);

        RowViewHolder holder = new RowViewHolder();
        holder.tvOne = (TextView) retView.findViewById(R.id.name);
        holder.tvTwo = (TextView) retView.findViewById(R.id.txt_number);
        holder.tvOne.setOnClickListener(tvOneLapOnClickListener);
        retView.setTag(holder);

        return retView;
    }

    @Override
    public void bindView(View v, final Context context, Cursor c)
    {
        // ...
    }

    @SuppressWarnings("unchecked")
    @Override
    public View getView(final int position, View convertView, ViewGroup parent)
    {
        // ...
    }

    private OnClickListener tvOneLapOnClickListener = new OnClickListener() {
        @Override
        // When the tvOne button is clicked, execute this code
        public void onClick(View v) {
                // get the RowViewHolder
                RowViewHolder holder = new RowViewHolder();
                // Get the holder for the row
                holder = (RowViewHolder) ((View) v.getParent()).getTag();
                if (holder.tvOne.getVisibility() == View.INVISIBLE)
                    holder.tvOne.setVisibility(View.VISIBLE);
                else
                    holder.tvOne.setVisibility(View.INVISIBLE);
        }
    };

}

protected void onListItemClick(ListView l, View v, int position, long id)
{
    // ...
}

}


text:
Q: Turn a repeated foreach loop to a method so that it's only repeated once So, my issue here may turn out to be simple. I know how to create a method to callback from the application, but my issue is trying to figure out how to do it properly in this manner. I need to take the foreach loop that is repeated :(foreach (Ticket t in events)
            {
                if (t.getName().Equals(cbEvents.SelectedItem.ToString()))
                {
)
 and change it to a method to be called on twice in the code. Please help. Code below.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TicketPurchasing
{
public partial class Form1 : Form
{
    private ArrayList events;

    public Form1()
    {
        InitializeComponent();
        events = new ArrayList();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        //Create events
        events.Add(new Game(12.00, "KSU vs UGA", "Convocation Building",   "bball", "Basketball"));
        events.Add(new Game(15.00, "KSU vs GSU", "Stadium", "fball", "Football"));
        events.Add(new Concert(8.00, "Country Music", "Campus Green", "hayes", "Hunter Hayes"));
        events.Add(new Concert(12.00, "Rock/Pop", "Campus Green", "m5", "Maroon5"));

        //Load combobox
        foreach (Ticket t in events)
        {
            cbEvents.Items.Add(t.getName());
        }
    }

    private void btnDetails_Click(object sender, EventArgs e)
    {
        //Get name of selected item from combobox
        string eventName;

        //Traverse array to determine the match
        foreach (Ticket t in events)
        {
            if (t.getName().Equals(cbEvents.SelectedItem.ToString()))
            {
                //Display details
                lblDetails.Text = t.getDetails();

                //Display image
                displayImage(t.getFileName());
            }
        }
    }

    private void displayImage(string file)
    {
        Size size = new Size(173, 180);
        Image img = (Image)Properties.Resources.ResourceManager.GetObject(file);
        img = (Image)(new Bitmap(img, size));
        pbImage.Image = img;
        pbImage.Refresh();
        pbImage.Visible = true;
    }

    private void txtTickets_TextChanged(object sender, EventArgs e)
    {
        //Get number of tickets

        int num = int.Parse(txtTickets.Text);

        double ticketCost = 0;

        //Get cost of ticket
        foreach (Ticket t in events)
        {
            if (t.getName().Equals(cbEvents.SelectedItem.ToString()))
            {
                ticketCost = t.getCost();
            }
        }

        //Calculate cost
        double total = num * ticketCost;

        //Display cost
        txtCost.Text = total.ToString("c");
    }

    private void btnExit_Click(object sender, EventArgs e)
    {
        //Exit the application
        this.Close();
    }

    private void btnClear_Click(object sender, EventArgs e)
    {
        //Clear all information
        lblDetails.Text = "";
        pbImage.Image = null;
        txtTickets.Text = "0";
        txtCost.Text = "";
    }

}
}

A: Are you trying to achieve something like this?
    private void btnDetails_Click(object sender, EventArgs e)
    {
        //Get name of selected item from combobox
        string eventName;

        //Traverse array to determine the match
        MethodAfterRefactor(() =>
        {
            //Display details
            lblDetails.Text = t.getDetails();

            //Display image
            displayImage(t.getFileName());
        });
    }

    private void MethodAfterRefactor(Func<object> p)
    {
        foreach (Ticket t in events)
        {
            if (t.getName().Equals(cbEvents.SelectedItem.ToString()))
            {
                p.Invoke();
            }
        }
    }

A: Try thinking about this slightly differently, let's start by working out what you really want to do.
You have two lists, one represents the View artefacts cbEvents, the other the data behind that (sometimes known as the ViewModel) events.
What you are trying to do is match your ViewModel from your View because you only put the name into the view.
If you instead put your ViewModel into your View so that it can be rendered as just the name, then this code goes away. Something like
public class Ticket
{
    ...

   public string override ToString() { return getName(); }
}

private void Form1_Load(object sender, EventArgs e)
{
     ...
     //Load combobox
    foreach (Ticket t in events)
    {
        cbEvents.Items.Add(t);
    }
}

Then you can do stuff like
private void btnDetails_Click(object sender, EventArgs e)
{
    Ticket t = cbEvents.SelectedItem as Ticket;
    if (t !=null)
    {
            //Display details
            lblDetails.Text = t.getDetails();

            //Display image
            displayImage(t.getFileName());
    }
}

This is obviously a totally different way of thinking about this but is much easier.  You may also find that some controls don't support binding to the object so well, in which case (at least in WinForms) you can use the Tag field
 lblText.Text = t.getName();
 lblText.Tag = t;

or in WPF the DataContext so you then bind to the fields e.g.
<TextBlock Text="{Binding Name}"/>


text:
Q: Android/PHP: how to POST/GET JSON data from Android to php Android/PHP: how to POST/GET JSON data from Android to php?
Currently I am stuck at a point where I am sending JSONObject data to php but
getting NULL values always in response.
What I want:
I am sending 'username' and 'password' from Android in the form of JSONObject and want to retrieve same data in JSONObject in PHP response.
Here is my code snippet
Android_file.java
DefaultHttpClient httpClient=new DefaultHttpClient();
        HttpPost httpPost=new HttpPost(register_user);
        JSONObject jsonObject=new JSONObject();
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        try {

            jsonObject.put("username",username.getText().toString());
            jsonObject.put("password",password.getText().toString());
            StringEntity se=new StringEntity("json="+jsonObject.toString());
            //httpPost.addHeader("content-type", "application/x-www-form-urlencoded");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
            httpPost.setEntity(se);
           String req=se.toString();

            HttpResponse response=httpClient.execute(httpPost);

            if(response!=null){
                InputStream is=response.getEntity().getContent();
                BufferedReader bufferedReader=new BufferedReader(new     InputStreamReader(is));
                StringBuilder sb=new StringBuilder();
                String line=null;
                while((line=bufferedReader.readLine())!=null){
                    sb.append(line+"\n");
                }
                this.message=sb.toString();
                //Toast.makeText(getBaseContext(), message, Toast.LENGTH_LONG).show();
            }

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

Login_check.php
<?php
include('../core/init.php');

 // $contents = file_get_contents('php://input');
  // $contents = utf8_encode($contents);
  if($_POST['json'])
  {
  $data=json_decode(stripslashes($_POST['json']));
  $username=$data['username'];
  $password=$data['password'];
$response=array('username'=>$username,'password'=>$password);
echo json_encode($response);

  }
   else{
   $no_data=array('none'=>'no data received');
echo json_encode($no_data);
   }

    ?>

Please let me know if I am doing something wrong or missing some point? thanks in advance!

A: I dont know what exactly is wrong with your code but I compared your code to mine which is working fine on diffrent apps and I made some changes to your code and hope that it works:
replace the part:
        jsonObject.put("username",username.getText().toString());
        jsonObject.put("password",password.getText().toString());
        StringEntity se=new StringEntity("json="+jsonObject.toString());
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
        httpPost.setEntity(se);

With:
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username", username.getText().toString()));
        params.add(new BasicNameValuePair("password",password.getText().toString()));
        httpPost.setEntity(new UrlEncodedFormEntity(params));

and this will be your web service (I think the problem is here):
<?php
include('../core/init.php');

 // $contents = file_get_contents('php://input');
  // $contents = utf8_encode($contents);
  if(isset($_POST['username']) && isset($_POST['password']))
  {
      $username=$_POST['username'];
      $password=$_POST['password'];
      $response = array();
      $response['username'] = $username;
      $response['password'] = $password;
      echo json_encode($response);
  }
  else{
       $no_data=array();
       $no_data['none']= 'no data received';
       echo json_encode($no_data);
  }
 ?>

Please let me know if it fixes your problem.


text:
Q: How to automatically take the data from MDTextfield without a button press in kivymd Like I don't want the user to be pressing any button as placing the button will make the UI really ugly. And any other better alternatives will do the trick too.
so here there is no button when typing the stock/company name I want it to automatically alter results/by taking the string(from MDtextfield)
without the user having to press a ok/search button
there is another thing I am having a problem with ;
I want to further add google like auto-complete but from a pre-specified .txt file of strings of stock/company name/
This is something I am still working on there is not much i was able to find about this/


text:
Q: How can I run an application with arguments from Windows Explorer? Is there an easy way to launch an application from Windows Explorer with arguments?  Or do I have to actually run them from the command line?

A: It sounds like you want a brief script that you can just double-click to run a command with certain arguments - is that right? If it is, here's one way:
Open a simple text editor, like Notepad, and type in the commands with the arguments you want it to take, like so:
cd %USERPROFILE%\useful-files\executables
putty.exe 192.168.2.10

(In this example, putty.exe is a program that can take IP addresses as arguments, and it's saved in C:\Users\\useful-files\executables.) When you're done, save it with the .bat extension (if you're using Notepad, just make sure you replace the .txt it starts you off with; in our example, we could save it as something like run-putty-with-IP.bat).
If you've done this correctly, in File Explorer it will show the file type as "Windows Batch File" and double-clicking it will run its contents.
Note that certain programs, without configuring system or environment variables, will require you to change to their directory to be able to execute them, hence the cd command included here.

A: If you open any folder, then the shortest way to run any application with arguments is just typing program name and arguments in the upper textbox.

Otherwise, if your program is on Desktop, you can use various ways such as:

*

*Click on any folder on your desktop, up one level, and do the same as is in picture.

*Press Win+R, write cmd.exe /k cd desktop, hit enter, write
program name and arguments.

*Create a shortcut or a batch file with this command:
cmd.exe /k cd %systemdrive%\%username%\desktop
run it and write program name and arguments.

A: Foggy memory here, but I believe there was a TweakUI addition to the Windows XP context menu for CMD and BAT files that allowed you to add your arguments and run the script. I believe this is what OP is looking for, and I would also find that very useful.
--tim


text:
Q: Sort dataframe based on column criteria I need to sort the below dataframe1 based on another dataframe2 columns:
Dataframe1:
LC       Item     Rolledfcst
MW92    1358576     2125
RM11    1358576     3955
WK14    1358576     307
SW92    1358576     190
MW92    1267890     200
SW92    1267890     670
RM11    1267890     890
WK14    1267890     245

Dataframe 2:
      Item   LC1    LC2     LC3
    1358576 RM11    MW92    SW92
    1358576 RM11    WK14    NA
    1267890 MW92    SW92    NA
    1267890 RM11    WK14    NA

Now for each Item in Dataframe1 it should sort the LC based on Dataframe2 columns in the order such that first column LC1 elements then LC2 and after that LC3.
Note: For each Item, in LC1 or LC2 or LC3 there are 2 LCs in any column then there order doesn't matter
Output Dataframe:
LC       Item     Rolledfcst
RM11    1358576     3955
MW92    1358576     2125
WK14    1358576     307
SW92    1358576     190
MW92    1267890     200
RM11    1267890     890
SW92    1267890     670
WK14    1267890     245

A: A tidyverse solution:
df1 <- structure(list(LC         = c("MW92", "RM11", "WK14", "SW92", "MW92",
                                     "SW92","RM11", "WK14"),
                      Item       = c(1358576L, 1358576L, 1358576L, 1358576L,
                                     1267890L, 1267890L, 1267890L, 1267890L),
                      Rolledfcst = c(2125L, 3955L, 307L, 190L, 200L, 670L,
                                     890L, 245L)),
                      class      = "data.frame",
                      row.names  = c(NA, -8L))

df2 <- structure(list(Item      = c(1358576L, 1358576L, 1267890L, 1267890L),
                      LC1       = c("RM11", "RM11", "MW92", "RM11"),
                      LC2       = c("MW92", "WK14", "SW92", "WK14"),
                      LC3       = c("SW92", NA, NA, NA)),
                      class     = "data.frame",
                      row.names = c(NA, -4L))

First determine an order via df2 in long format:
library(tidyverse)
(ord <- df2 %>%
    gather(LC, value, -Item) %>%
    arrange(Item, LC) %>%
    group_by(Item) %>%
    mutate(order = as.numeric(factor(value, unique(value)))) %>%
    filter(!is.na(order)) %>% unique())

# # A tibble: 8 x 4
# # Groups:   Item [2]
#      Item LC    value order
#     <int> <chr> <chr> <dbl>
# 1 1267890 LC1   MW92      1
# 2 1267890 LC1   RM11      2
# 3 1267890 LC2   SW92      3
# 4 1267890 LC2   WK14      4
# 5 1358576 LC1   RM11      1
# 6 1358576 LC2   MW92      2
# 7 1358576 LC2   WK14      3
# 8 1358576 LC3   SW92      4

Now, join df1 and ord and sort to item and order:
left_join(df1,
          ord %>% select(-LC),
          by = c("Item", LC = "value")) %>%
   arrange(desc(Item), order) %>% select(-order)

#     LC    Item Rolledfcst
# 1 RM11 1358576       3955
# 2 MW92 1358576       2125
# 3 WK14 1358576        307
# 4 SW92 1358576        190
# 5 MW92 1267890        200
# 6 RM11 1267890        890
# 7 SW92 1267890        670
# 8 WK14 1267890        245

As per the comments here a pure base R solution:
## transform data to long format
ord <- reshape(df2, varying=names(df2)[-1], direction = "long", v.names = "LC")
## sort according to item and time
ord <- ord[order(-ord$Item, ord$time), ]
## remove NAs
ord <- ord[!is.na(ord$LC),]
## remove duplicates
ord <- ord[!duplicated(ord[, c(1, 3)]), ]
## add the order
split(ord$id, ord$Item) <- lapply(split(ord$id, ord$Item), seq_along)
## merge the data
df.res <- merge(df1, ord[, -2], by = c("Item", "LC"))
## sort according to order
df.res[order(-df.res$Item, df.res$id), -4]
#      Item   LC Rolledfcst
# 6 1358576 RM11       3955
# 5 1358576 MW92       2125
# 8 1358576 WK14        307
# 7 1358576 SW92        190
# 1 1267890 MW92        200
# 2 1267890 RM11        890
# 3 1267890 SW92        670
# 4 1267890 WK14        245

A: A base R approach using split and mapply. We convert Item to factor based on it's occurrence in df1 then split row numbers of df1 based on Item column and match those LC values with unlisted values of df2 to get original row numbers in sorted manner to subset.
df1$Item <- factor(df1$Item, levels = unique(df1$Item))
df2$Item <- factor(df2$Item, levels = unique(df1$Item))

df1[c(mapply(function(x, y) y[match(df1$LC[y], unique(unlist(x)))],
           split(df2[-1], df2$Item), split(seq_along(df1$LC), df1$Item))), ]

#    LC    Item Rolledfcst
#2 RM11 1358576       3955
#1 MW92 1358576       2125
#3 WK14 1358576        307
#4 SW92 1358576        190
#5 MW92 1267890        200
#7 RM11 1267890        890
#6 SW92 1267890        670
#8 WK14 1267890        245

A: Read in Data:
df1 <- read.table(text = 'LC       Item     Rolledfcst
MW92    1358576     2125
RM11    1358576     3955
WK14    1358576     307
SW92    1358576     190
MW92    1267890     200
SW92    1267890     670
RM11    1267890     890
WK14    1267890     245', header = T)

df2 <- read.table(text = ' Item   LC1    LC2     LC3
    1358576 RM11    MW92    SW92
    1358576 RM11    WK14    NA
    1267890 MW92    SW92    NA
    1267890 RM11    WK14    NA', header = T)

Gather LC columns into single column and create an ID column containing the sort order
library(tidyr)
library(dplyr)

df2 <- df2 %>%
  gather(LC, value,2:4) %>%
  mutate(sort_id = paste0(Item,value))

#     Item  LC value     sort_id
#1  1358576 LC1  RM11 1358576RM11
#2  1358576 LC1  RM11 1358576RM11
#3  1267890 LC1  MW92 1267890MW92
#4  1267890 LC1  RM11 1267890RM11
#5  1358576 LC2  MW92 1358576MW92
#6  1358576 LC2  WK14 1358576WK14
#7  1267890 LC2  SW92 1267890SW92
#8  1267890 LC2  WK14 1267890WK14
#9  1358576 LC3  SW92 1358576SW92
#10 1358576 LC3  <NA>   1358576NA
#11 1267890 LC3  <NA>   1267890NA
#12 1267890 LC3  <NA>   1267890NA

Create a sort_id column in the same way for df1 and apply the factor levels from df2. The factor levels will govern the sort order when using arrange.
df1 %>%
  mutate(sort_id = factor(paste0(Item,LC), levels = unique(df2$sort_id)),
         Item = factor(Item, levels = unique(df2$Item))) %>%
  group_by(Item) %>%
  arrange(sort_id, .by_group = T) %>%
  select(-sort_id)

#LC    Item    Rolledfcst
#  <fct> <fct>        <int>
#1 RM11  1358576       3955
#2 MW92  1358576       2125
#3 WK14  1358576        307
#4 SW92  1358576        190
#5 MW92  1267890        200
#6 RM11  1267890        890
#7 SW92  1267890        670
#8 WK14  1267890        245


text:
Q: group values of (ordered) dictionary based on condition within values I have a sorted dictionary (orderedDict to be exact) and I want to make a new dictionary (or edit the old one) that group specific values based on a condition. The main problem is that I need to check each key in the dictionary with the previous ones and group (multiple) entries together until the condition is not true anymore. I know this i quite vague so here is an example
{
'5': ['a', 300, 350, 'name1'],
'98': ['a', 370, 450, 'name2'],
'115': ['a', 540, 600, 'name3'],
'7': ['a', 900, 960, 'name4'],
'12': ['a', 980, 1200, 'name5'],
'24': ['a', 2000, 2200, 'name6'],
'25': ['b', 100, 150, 'name7'],
'100': ['b', 190, 270, 'name8'],
'200': ['b', 280, 350, 'name9'],
'99': ['b', 370, 500, 'name10'],
'4': ['b', 980, 1200, 'name11']
}

here I want to compare the "end" value (the third value, here "350") with the "start" value of the next key (the second value, here "370") and additionally within either group a or b (i can also make 2 different dictionaries if that complicates it too much, there are only 2 groups anyway). If the difference between the end and start are for example <100 in difference, then add them together in a group. Keep adding, until the condition is not true anymore. I don't need all the values afterwards in my new dictionary. So a possible outcome might be.
{
'Group_1': ['a', 'name1; name2; name3'],
'Group_2': ['a', 'name4; name5'],
'Group_3': ['a', 'name6'],
'Group_4': ['b', 'name7; name8; name9; name10'],
'Group_5': ['b', 'name11']
}

I am really thinking about a solution, But the only thing I could come up with is looping with
for key[i], value[i] in sorted_dict.iteritems():
    check key[i] with key[i-1]
    if <100
        new_dict[counter] = [list of combined values]

but that seems very unlogical, because then you can only have a group of max 2 in length and I think would be very hard to program for different lengths. I also think that I should not do this in dictionaries at all, but my python knowledge is a bit short in how to solve this, quite simple in theory, but difficult to handle in datastructure problem.
I looked at this post, which is the most similar I could find on the web, but I think not really applicable to my case?
Any help would be appreciated. The ordereddict that i have is sorted first on the group(a or b) and then based on Start value.

A: The following code will produce an outcome similar to what you described, though I changed the datastructure to be more compact:
sorted_dict = {
    '5': ['a', 300, 350, 'name1'],
    '98': ['a', 370, 450, 'name2'],
    '115': ['a', 540, 600, 'name3'],
    '7': ['a', 900, 960, 'name4'],
    '12': ['a', 980, 1200, 'name5'],
    '24': ['a', 2000, 2200, 'name6'],
    '25': ['b', 100, 150, 'name7'],
    '100': ['b', 190, 270, 'name8'],
    '200': ['b', 280, 350, 'name9'],
    '99': ['b', 370, 500, 'name10'],
    '4': ['b', 980, 1200, 'name11']
}

values = sorted(sorted_dict.values())
result = {values[0][0] : [[values[0][3]]]}

for list_1, list_2 in zip(values[:-1], values[1:]):
    if list_1[0] == list_2[0]:
        # assuming list_1[2] >= list_1[2], otherwise use abs(list_1[2] - list_1[2])
        if list_2[1] - list_1[2] < 100:
            result[list_1[0]][-1] += [list_2[3]]
        else:
            result[list_1[0]] += [[list_2[3]]]
    else:
        result[list_2[0]] = [[list_2[3]]]

print(result)

Result:
> {'a': [['name1', 'name2', 'name3'], ['name4', 'name5'], ['name6']], 'b': [['name7', 'name8', 'name9', 'name10'], ['name11']]}


text:
Q: How to know about the event listeners attached to a UI element in Angular 6? Let's say I have this simple rendered div element in browser:
<div class="contact">
   <!-- info here -->
</div>

And I don't have access to the source code of Angular. Is there a way to find out what event listeners are attached to div.contact element?


text:
Q: How to find average time to load data from S3 into Redshift I have more than 8 schemas and 200+ tables and data is loaded by CSV files in different schema.
I want to to know the SQL script for how to find average time to load the data from S3 into Redshift for all 200 tables.

A: You can examine the STL System Tables for Logging to discover how long queries took to run.
You'd probably need to parse the Query text to discover which tables were loaded, but you could use the historical load times to calculate a typical load time for each table.
Some particularly useful tables are:

*

*STL_QUERY_METRICS: Contains metrics information, such as the number of rows processed, CPU usage, input/output, and disk use, for queries that have completed running in user-defined query queues (service classes).

*STL_QUERY: Returns execution information about a database query.

*STL_LOAD_COMMITS: This table records the progress of each data file as it is loaded into a database table.

A: Run this query to find out how fast your COPY queries are working.
select q.starttime,  s.query, substring(q.querytxt,1,120) as querytxt,
       s.n_files, size_mb, s.time_seconds,
       s.size_mb/decode(s.time_seconds,0,1,s.time_seconds)  as mb_per_s
from (select query, count(*) as n_files,
     sum(transfer_size/(1024*1024)) as size_MB, (max(end_Time) -
         min(start_Time))/(1000000) as time_seconds , max(end_time) as end_time
      from stl_s3client where http_method = 'GET' and query > 0
       and transfer_time > 0 group by query ) as s
LEFT JOIN stl_Query as q on q.query = s.query
where s.end_Time >=  dateadd(day, -7, current_Date)
order by s.time_Seconds desc, size_mb desc, s.end_time desc
limit 50;

Once you find out how many mb/s you're pushing through from S3 you can roughly determine how long it will take each file based on the size.

A: There's a smart way to do it. You ought to have an ETL script that migrates data from S3 to Redshift.
Assuming that you have a shell script, just capture the time stamp before the ETL logic starts for that table (let's call that start), capture another timestamp after the ETL logic ends for that table (let's call that end) and take the difference towards the end of the script:
#!bin/sh
    .
    .
    .

start=$(date +%s) #capture start time

#ETL Logic
        [find the right csv on S3]
        [check for duplicates, whether the file has already been loaded etc]
        [run your ETL logic, logging to make sure that file has been processes on s3]
        [copy that table to Redshift, log again to make sure that table has been copied]
        [error logging, trigger emails, SMS, slack alerts etc]
        [ ... ]

end=$(date +%s) #Capture end time

duration=$((end-start)) #Difference (time taken by the script to execute)

echo "duration is $duration"

PS: The duration will be in seconds and you can maintain a log file, entry to a DB table etc. The timestamp will be in epoc and you can use functions (depending upon where you're logging) like:
sec_to_time($duration) --for MySQL
SELECT (TIMESTAMP 'epoch' + 1511680982 * INTERVAL '1 Second ')AS mytimestamp -- for Amazon Redshift (and then take the difference of the two instances in epoch).


text:
Q: Проверка сетевого интерфейса в Windows Есть список сетевых интерфейсов, необходимо проверить каждый из них на то, является ли он активным. Пробовал проверять, установлен ли у интерфейса IP адрес, но как выяснил через гугление, установленный IP не гарантирует мне того, что интерфейс будет активен. Каким образом можно проверить на это на 100% ?

A: Попробуйте так:
In [102]: import wmi

In [103]: c = wmi.WMI()

In [104]: qry = "select Name from Win32_NetworkAdapter where NetEnabled=True and NetConnectionStatus=2"

In [105]: [o.Name for o in c.query(qry)]
Out[105]:
['Realtek PCIe GBE Family Controller',
 'VMware Virtual Ethernet Adapter for VMnet1',
 'VMware Virtual Ethernet Adapter for VMnet8',
 'VirtualBox Host-Only Ethernet Adapter']


text:
Q: Login and password script with each user having a custom page after login so i have a simple script i'm trying to utilize for a side project with multiple users. no real security required just a custom page for each user.
the problem i'm having is getting this script to allow each user/password combo to be redirected to that users custom login page.
ex. Username- Jeff Password- lucky -- if correct go to ...com/users/jeff.htm
    Username- Sally Password- home -- if correct go to ...com/users/sally.htm

if anyone can help or has any ideas let me hear em. here is the script i'm trying to use in native form.
<script type = "text/javascript">

var count = 2;
function validate() {
var un = document.myform.username.value;
var pw = document.myform.pword.value;
var valid = false;

var unArray = ["Philip", "George", "Sarah", "Michael"];  // as many as you like - no     comma after final entry
var pwArray = ["Password1", "Password2", "Password3", "Password4"];  // the corresponding passwords;

for (var i=0; i <unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = true;
break;
}
}

if (valid) {
alert ("Login was successful");
window.location = "http://www.google.com";
return false;
}

var t = " tries";
if (count == 1) {t = " try"}

if (count >= 1) {
alert ("Invalid username and/or password.  You have " + count + t + " left.");
document.myform.username.value = "";
document.myform.pword.value = "";
setTimeout("document.myform.username.focus()", 25);
setTimeout("document.myform.username.select()", 25);
count --;
}

else {
alert ("Still incorrect! You have no more tries left!");
document.myform.username.value = "No more tries allowed!";
document.myform.pword.value = "";
document.myform.username.disabled = true;
document.myform.pword.disabled = true;
return false;
}

}

</script>

A: Hope it will work
if(valid)
 {
     window.location=".....com/users/"+ unArray[i] +".html"
 }

if the page where you want the user to go is different then you may use another array for users.


text:
Q: Creating a counter that returns an incremental value for unique child elements XSLT I am attempting to do an XSLT Transformation. I want to create a counter that returns the an incremental value for each unique "col1". So for example for all rows that have col1 "Alpha", I want a value of 1. All rows that have col1 "Bravo" I want a value of 2. And for col1 "Charlie" all rows have a value of 3, and other unique col1's would keep incrementing and so on. Do I need to create a variable or some kind of thing that compares one string to another string and increments it? I'm not really sure how to approach this...
 <root>
  <row>
    <col1>Alpha</col1>
    <col2>123</col2>
    <col3>ABC</col3>
  </row>
  <row>
    <col1>Alpha</col1>
    <col2>234</col2>
    <col3>BCD</col3>
  </row>
   <row>
    <col1>Bravo</col1>
    <col2>123</col2>
    <col3>ABC</col3>
  <row>
    <col1>Bravo</col1>
    <col2>234</col2>
    <col3>BCD</col3>
  </row>
  <row>
    <col1>Bravo</col1>
    <col2>345</col2>
    <col3>CDE</col3>
  </row>
  <row>
    <col1>Charlie</col1>
    <col2>123</col2>
    <col3>ABC</col3>
  </row>

A: If - as in your previous question - your data is already sorted, you can use a very similar:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/root">
    <output>
        <xsl:for-each select="row">
            <xsl:copy>
                <col0>
                    <xsl:value-of select="count((. | preceding-sibling::row)[col1!=preceding-sibling::row[1]/col1])+1"/>
                </col0>
                <xsl:copy-of select="*"/>
            </xsl:copy>
        </xsl:for-each>
    </output>
</xsl:template>

</xsl:stylesheet>

This increases the count on each "break" in col1, not necessarily by unique values.

A: If you can use XSLT 2.0, you can use a combination of distinct-values() and index-of().
If your data is not sorted, it will give the index of the first occurrence.
XML Input
<root>
    <row>
        <col1>Alpha</col1>
        <col2>123</col2>
        <col3>ABC</col3>
    </row>
    <row>
        <col1>Alpha</col1>
        <col2>234</col2>
        <col3>BCD</col3>
    </row>
    <row>
        <col1>Bravo</col1>
        <col2>123</col2>
        <col3>ABC</col3>
    </row>
    <row>
        <col1>Bravo</col1>
        <col2>234</col2>
        <col3>BCD</col3>
    </row>
    <row>
        <col1>Bravo</col1>
        <col2>345</col2>
        <col3>CDE</col3>
    </row>
    <row>
        <col1>Charlie</col1>
        <col2>123</col2>
        <col3>ABC</col3>
    </row>
</root>

XSLT 2.0
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:variable name="col1s" select="distinct-values(/*/row/col1)"/>

    <xsl:template match="col1">
        <col0><xsl:value-of select="index-of($col1s,.)"/></col0>
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

Output
<root>
   <row>
      <col0>1</col0>
      <col1>Alpha</col1>
      <col2>123</col2>
      <col3>ABC</col3>
   </row>
   <row>
      <col0>1</col0>
      <col1>Alpha</col1>
      <col2>234</col2>
      <col3>BCD</col3>
   </row>
   <row>
      <col0>2</col0>
      <col1>Bravo</col1>
      <col2>123</col2>
      <col3>ABC</col3>
   </row>
   <row>
      <col0>2</col0>
      <col1>Bravo</col1>
      <col2>234</col2>
      <col3>BCD</col3>
   </row>
   <row>
      <col0>2</col0>
      <col1>Bravo</col1>
      <col2>345</col2>
      <col3>CDE</col3>
   </row>
   <row>
      <col0>3</col0>
      <col1>Charlie</col1>
      <col2>123</col2>
      <col3>ABC</col3>
   </row>
</root>


text:
Q: Determinant of Gram matrix is non-zero, but vectors are not linearly independent From Wikipedia:

a set of vectors is linearly independent if and only if the Gram determinant (the determinant of the Gram matrix) is non-zero.

But consider the matrix M:
  5   4   2   1
  0   1  -1  -1
 -1  -1   3   0
  1   1  -1   2

The Gram matrix G is:
 27  22   6  7
 22  19   3  5
  6   3  15  1
  7   5   1  6

And the determinant of G is 1024.  The eigenvalues of M are:
4, 4, 1, 2

The eigenvectors of M are:
 -0.58   0.58  -0.71  -0.58
  0.0   -0.0    0.71   0.58
  0.58  -0.58   0.0    0.0
 -0.58   0.58   0.0   -0.58

And the rank of this eigenvector matrix is 3, not 4, so... the vectors are not linearly independent.  Am I missing something obvious here?  Thanks.

A: Consider the matrix
1  1
0  1

It's got one eigenvector,
0
1

so its eigenvector matrix, as reported by matlab, will be
0  0
1  1

Its eigenvalues are 1 and 1. But it's got rank 2, even though the eignevector matrix has rank 1. So what you're missing is a clear understanding of what matlab returns when it computes an eigenvector matrix.