text:
Q: RecursiveIteratorIterator last child I iterate through a multidimensional array with RecursiveIteratorIterator and would like to be able to know if the current element is the last child of it's depth. I thought about this:
$iterator = new RecursiveIteratorIterator($array,
  RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $val) {
  $next = clone $iterator;
  $next->next();
  $lastChild = ($next->getDepth() < $iterator->getDepth());
}

But the RecursiveIteratorIterator says it's not cloneable.

A: The phrase "last child of its depth" is not particularly clear. Could you elaborate on precisely what you mean; the intended use for this?
If you mean, quite simply, that the depth will change after the current element, then the (Recursive)CachingIterator has a handy hasNext method to determine whether the iterator has any further items. To give a watered-down example similar to that in the question:
$array  = array(
    range(1,6),
    range(7,8),
    'foo' => range(1,3),
    'bar' => range(4,5),
);

$rit = new RecursiveArrayIterator($array);
$iterator = new RecursiveIteratorIterator(
    new RecursiveCachingIterator($rit),
    RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($iterator as $val) {
    $lastChild = !$iterator->hasNext();
    if ($lastChild) {
        echo "$val is the last child!\n";
    }
}

Outputs:
6 is the last child!
8 is the last child!
3 is the last child!
5 is the last child!


text:
Q: Is there a way to extend the nuxt/vue template with custom HTML and then execute any scripts inside? this question is related to SPA mode.  I would like to extend template - but before nuxt served it for client. I have some data (text string fetched from API) with user's html output. It could by anything until it is still valid HTML code. It is used for custom client's conversion codes, so the output is mostly bundle of <script> or/and <img> tags to initiate GTM etc (I know there is plenty integration for GTM in nuxt, but I need it like this). This is why I can't use innerHTML in vue-meta Script prop or native HTMLScriptElement with simple iterating <script> tag within data string by regexp (in fetched string could be anything).
I understand how to add external script via nuxt.config.js or page itself (head in vue-meta) or via HTMLScriptElement API (in mounted lifecycle hook), but it is not what I mean. The closest to what I need is app.html overwrite, but I need this custom for multiple routes (while app.html is a global solution). Is there any way to achieve this?
The most of the solutions I've tried can't be used because even if the code is added to the template the javascript won't run. Thanks for help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: .htaccess Directory Index not working in sub-folders I have the following .htaccess file in my root folder:
<Files .htaccess>
    Order allow,deny
    Deny from all
</Files>

DirectoryIndex index.php

ErrorDocument 404 /not-found.php

RewriteEngine On
RewriteBase /
RewriteRule ^@([^/]+)$ /users.php?username=$1
RewriteRule ^@([^/]+)/followers$ /followers.php?username=$1
RewriteRule ^@([^/]+)/highlights$ /highlights.php?username=$1
RewriteRule ^posts/([^/]+)(|/)$ /posts.php?id=$1
RewriteRule ^([^\.]+)$ $1.php

If I write localhost in the address bar, it calls the index file correctly, but if I access the subfolder localhost/support/ it does not detect the index file that is in this folder.
If I delete the last line RewriteRule ^([^\.]+)$ $1.php it works, but I need it for the good functioning of other files.


text:
Q: Why don't my aliases in .bashrc work? I have Lion on my Mac Air. I wrote some aliases in ~/.bashrc file, which looks like:
# Aliases
alias p='pdflatex *.tex;open *.pdf'
alias bromine='ssh administrator@bromine.org'

I then sourced my .bashrc file from .bash_profile, which I believe is sourced upon startup. My .bash_profile file looks like
# Setting PATH for EPD-7.2-2
# The orginal version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/Current/bin:${PATH}"
export PATH

MKL_NUM_THREADS=1
export MKL_NUM_THREADS

# MacPorts Installer addition on 2012-02-27_at_18:19:09: adding an appropriate PATH variable for use with MacPorts.
export PATH=/opt/local/bin:/opt/local/sbin:$PATH
# Finished adapting your PATH environment variable for use with MacPorts.

# source bashrc
. .bashrc

Why is it that my aliases work sometimes upon startup, but not always - (sometimes, I have to manually source .bash_profile)?

A: It seems like your bash shell is looking for .profile instead of .bashrc . What you can do is make a symbolic link:
ln -s ~/.bashrc ~/.profile
and restart your session (close, reopen Terminal). Any future bash setting updates can be made to .profile or .bashrc.


text:
Q: Make edges on graph line round and not "sharp" Swiftui I am currently working on a graph view for a widget and I don't like the way the edges looks on my graph atm. I would like to make the edges on my graph line rounded instead of sharp (Graph).
I've tried with .cornerRadius(5) and .addQuadCurve() but nothing seems to work.
My code looks like this.
import SwiftUI

@available(iOS 14.0.0, *)

struct Graph: View {

    var styling = ViewStyling()
    var stockPrices: [CGFloat]

    var body: some View {
        ZStack {
            LinearGradient(gradient:
                        Gradient(colors: [styling.gradientColor, styling.defaultWhite]), startPoint: .top, endPoint: .bottom)
            .clipShape(LineGraph(dataPoints: stockPrices.normalized, closed: true))

        LineGraph(dataPoints: stockPrices.normalized)
            .stroke(styling.graphLine, lineWidth: 2)
            //.cornerRadius(5)
        }
    }
}

@available(iOS 14.0.0, *)
struct LineGraph: Shape {
    var dataPoints: [CGFloat]
    var closed = false

    func path(in rect: CGRect) -> Path {

        func point(at ix: Int) -> CGPoint {
            let point = dataPoints[ix]
            let x = rect.width * CGFloat(ix) / CGFloat(dataPoints.count - 1)
            let y = (1 - point) * rect.height

            return CGPoint(x: x, y: y)
        }

        return Path { p in

            guard dataPoints.count > 1 else { return }

            let start = dataPoints[0]
            p.move(to: CGPoint(x: 0, y: (1 - start) * rect.height))
            //p.addQuadCurve(to: CGPoint(x: rect.maxX, y: rect.maxY), control: CGPoint(x: rect.maxX, y: rect.maxY))

            for index in dataPoints.indices {
                 p.addLine(to: point(at: index))
            }

            if closed {
                p.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
                p.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
                p.closeSubpath()
            }
        }
    }
}

extension Array where Element == CGFloat {
    // Return the elements of the sequence normalized.
    var normalized: [CGFloat] {
        if let min = self.min(), let max = self.max() {
            return self.map{ ($0 - min) / (max - min) }
        }
        return []
    }
}

A: How the joins between line segments are rendered is controlled by the lineJoin property of StrokeStyle, You're stroking with a color and a line width here:
.stroke(styling.graphLine, lineWidth: 2)

but you want something more like:
.stroke(styling.graphline, StrokeStyle(lineWidth: 2, lineJoin: .round))


text:
Q: How to debug(make page look like in Firefox) CSS in IE?
Possible Duplicate:
Tools Debugging CSS in Internet Explorer

I know there is debugbar plugin, but its not free. How do you debug CSS in IE? I tried firebug lite, but I did not like it. Are there any other free and powerful tools?

A: You can try installing IETester which has it's own debugbar. http://www.my-debugbar.com/wiki/IETester/HomePage

A: You can use the built in debugger if you're on IE8.
If you're on IE7 you can download the IE Developer Toolbar from Microsoft.


text:
Q: How to sync data between a Google Sheet and a Mysql DB? So I have a Google sheet that maintains a lot of data. I also have a MySQL DB with a huge junk of data. There is a vital piece of information in the Sheet that is also present in the DB. Both needs to be in sync. The information always enters the Sheet first. I had a python script with mysql queries to update my database separately.
Now the work flow has changed. Data will enter the sheet and whenever that happens the database has to updated automatically.

*

*After some research, I found that using the onEdit function of Google AppScript (I learned from here.), I could pickup when the file has changed.

*The Next step is to fetch the data from relevant cell, which I can do using this.

*Now I need to connect to the DB and send some queries. This is where I am stuck.

Approach 1:
Have a python web-app running live. Send the data via UrlFetchApp.This I yet have to try.
Approach 2:
Connect to mySQL remotely through appscript. But I am not sure this is possible after 2-3 hours of reading the docs.
So this is my scenario. Any viable solution you can think of or a better approach?

A: Connect directly to mySQL. You likely missed reading this part https://developers.google.com/apps-script/guides/jdbc

A: Using JDBC within Apps Script will work if you have the time to build this yourself.
If you don't want to roll your own solution, check out SeekWell. It allows you to connect to databases and write SQL queries directly in Sheets. You can create a run a "Run Sheet" that will run multiple queries at once and schedule those queries to be run without you even opening the Sheet.
Disclaimer: I made this.


text:
Q: Rotary Cam Switch wiring help I am trying to wire this rotary cam switch to spin a DC motor forward and backwards based on the UP and DOWN setting. I am having a really hard time trying to figure out how to wire it. Can someone please give me some advice?  I have a power supply, DC pos and neg. And a motor. Which terminals should I plug the motor in, and which terminals should I plug the power supply in?
I have been trying to test with a multimeter, but the cam is spring-loaded so it is making things difficult.

A: Terminals 1 and 3 are the common terminals of a DPDT switch. The motor connects there. To form a bridge with the other throws of the switch, you need to connect the positive supply to 6 and the negative supply to 10. Connect a dual-color 2-lead LED with current limiter across 2 and 4 to give a power and direction indicator.


text:
Q: AnimationDrawable crashing app So I've created my animation list and Ive set up my button but when I click the button which calls the animation method the app closes down and says "Unfortunately, Test has stopped working".
I believe the problem is in the animation method but have no idea what it is and have tried several different ways to fix it.
private void homeAnimate() {
    ImageView homeScreenImage = (ImageView) findViewById(R.id.imageView1);
    homeScreenImage.setImageResource(R.drawable.home_animation);
    AnimationDrawable homeAnimation = (AnimationDrawable) homeScreenImage.getDrawable();
    if(homeAnimation.isRunning()){
        homeAnimation.stop();
    }
    homeAnimation.start();
}

Can anyone see the problem in this method?
Also I apologise if it's really simple I haven't done much Android programming. Though I have done an animation before that worked fine.
Thanks
06-22 16:19:53.166: W/dalvikvm(1217): threadid=1: thread exiting with uncaught exception (group=0xb2a20ba8)
06-22 16:19:53.216: E/AndroidRuntime(1217): FATAL EXCEPTION: main
06-22 16:19:53.216: E/AndroidRuntime(1217): Process: com.example.test, PID: 1217
06-22 16:19:53.216: E/AndroidRuntime(1217): java.lang.OutOfMemoryError
06-22 16:19:53.216: E/AndroidRuntime(1217):     at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
06-22 16:19:53.216: E/AndroidRuntime(1217):     at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:587)
06-22 16:19:53.216: E/AndroidRuntime(1217):     at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:422)
06-22 16:19:53.216: E/AndroidRuntime(1217):     at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:840)
06-22 16:19:53.216: E/AndroidRuntime(1217):     at android.content.res.Resources.loadDrawable(Resources.java:2110)
06-22 16:19:53.216: E/AndroidRuntime(1217):     at android.content.res.Resources.getDrawable(Resources.java:700)
06-22 16:19:53.216: E/AndroidRuntime(1217):     at android.graphics.drawable.AnimationDrawable.inflate(AnimationDrawable.java:282)
06-22 16:19:53.216: E/AndroidRuntime(1217):     at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:937)
06-22 16:19:53.216: E/AndroidRuntime(1217):     at android.graphics.drawable.Drawable.createFromXml(Drawable.java:877)
06-22 16:19:53.216: E/AndroidRuntime(1217):     at android.content.res.Resources.loadDrawable(Resources.java:2092)
06-22 16:19:53.216: E/AndroidRuntime(1217):     at android.content.res.Resources.getDrawable(Resources.java:700)
06-22 16:19:53.216: E/AndroidRuntime(1217):     at android.widget.ImageView.resolveUri(ImageView.java:638)
06-22 16:19:53.216: E/AndroidRuntime(1217):     at android.widget.ImageView.setImageResource(ImageView.java:367)
06-22 16:19:53.216: E/AndroidRuntime(1217):     at com.example.test.MainActivity.homeAnimate(MainActivity.java:43)
06-22 16:19:53.216: E/AndroidRuntime(1217):     at com.example.test.MainActivity.access$0(MainActivity.java:41)
06-22 16:19:53.216: E/AndroidRuntime(1217):     at com.example.test.MainActivity$1.onClick(MainActivity.java:31)
06-22 16:19:53.216: E/AndroidRuntime(1217):     at android.view.View.performClick(View.java:4438)
06-22 16:19:53.216: E/AndroidRuntime(1217):     at android.view.View$PerformClick.run(View.java:18422)
06-22 16:19:53.216: E/AndroidRuntime(1217):     at android.os.Handler.handleCallback(Handler.java:733)
06-22 16:19:53.216: E/AndroidRuntime(1217):     at android.os.Handler.dispatchMessage(Handler.java:95)
06-22 16:19:53.216: E/AndroidRuntime(1217):     at android.os.Looper.loop(Looper.java:136)
06-22 16:19:53.216: E/AndroidRuntime(1217):     at android.app.ActivityThread.main(ActivityThread.java:5017)
06-22 16:19:53.216: E/AndroidRuntime(1217):     at java.lang.reflect.Method.invokeNative(Native Method)
06-22 16:19:53.216: E/AndroidRuntime(1217):     at java.lang.reflect.Method.invoke(Method.java:515)
06-22 16:19:53.216: E/AndroidRuntime(1217):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
06-22 16:19:53.216: E/AndroidRuntime(1217):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
06-22 16:19:53.216: E/AndroidRuntime(1217):     at dalvik.system.NativeStart.main(Native Method)

06-22 16:07:35.826: E/AndroidRuntime(830): Caused by: java.lang.NullPointerException


text:
Q: Problems connecting to db using Zend db as standalone I am migrating from ZF1 Zend_db to ZF2. I have problems connecting to the db and making a simple query. Appreciate if someone can guide me along. Below is my code.
This is how i connect to db
use Zend\Db\Adapter\Adapter;
$dbo = new Zend\Db\Adapter\Adapter(array(
    'driver'   => 'pdo_mysql',
    'database' => DB_PREFIX.DB_NAME,
    'username' => DB_USER,
    'password' => DB_PW
));
Zend_Registry::set('db', $dbo);

This isan example how i use it.
$this->dbo = Zend_Registry::get('db');

function createData($message,$tags,$userid,$imgsrc){
    $data= array(
                      'message' => $message,
                      'tags' => $tags,
                      'imgsrc' => $imgsrc,
                      'createdtimestamp'=>new Zend_Db_Expr('NOW()'),
                      'userid' => $userid);
    $this->dbo->insert('mydata', $data);
    return $this->dbo->lastInsertId();
}

I have an error. That is $dbo does not have select(),insert() methods etc. I could did it in ZF1 zend db.
Example of error message i received:

Fatal error: Call to undefined method
  Zend\Db\Adapter\Adapter::select() in

A: You seem to think that ZF2 and ZF1 are (and should be) class-compatible. The problem is, they're not - at least in regards to Zend\Db\Adapter. That one in ZF2 is much more concise: while it has query method, its main responsibility is abstracting the DB connection itself.
I suppose what you're looking for is located in Zend\Db\Sql area. Assuming you have your DB connection in $dbo, you can create an Sql object based on it:
use Zend\Db\Sql as Sql;
$sql = new Sql\Sql($dbo);

... then create another object (of Zend\Db\Sql\Insert class):
$insert = $sql->insert('mydata');
$insert->values([
   'message' => $message,
   'tags' => $tags,
   'imgsrc' => $imgsrc,
   'createdtimestamp'=>new Sql\Expression('NOW()'),
   'userid' => $userid
]);

... then use this object in query:
$insertString = $sql->getSqlStringForSqlObject($insert);
$results = $dbo->query($insertString, Adapter::QUERY_MODE_EXECUTE);


text:
Q: Strange Omission of "to be" in The Onion Headlines So I've noticed a pattern lately on the TheOnion.com of omitting 'is' from their headlines.  I get shortening headlines but I can't say this pattern is familiar to me.  It strikes me as obtuse and hard to read.
Here are some links of examples I could drum up.  There are many more:
Report: It A Miracle Nothing Has Punctured Your Eye Yet (9-25-2017)
Hope Hicks Praying She Not Still in Same Shitty Job By Time She Hits 30 (9-15-2017)
Man Must Think It Enough to Wear Blackhawks Jersey at Cubs Game (9-12-2017)
Are they just trolling?  Is this accepted journalistic style?  Is there a name for this?

A: It's standard practice to omit to be from headlines, but what is weird about the Onion is they put a kind of isolated subject in there. normal headlines might be:
*A miracle nothing has punctured your eye yet
*Hope Hicks prays not to be in same job...
*Man thinks wearing Blackhawks jersey to Cuba game acceptable
What that last one shows is that the ugly inclusion of a subject makes for a more flexible sentence structure. Unless there are some terribly written and infamous magazines in the US I think this flexibility rather than parodying bad headline style is the most likely cause.


text:
Q: 9 bits from serialPort c# I've a serialPort communication to a device wich send me a packege of  9 bits data.
I'm using c#. the data are 8 bits and one bit to check if the byte is a data or a command if it's a command then the 9th bit is 1 else is 0.
the problem is that the serialPort implemented in .Net accept only 8 bits.
In some answer i've seen that can man use the parity bit to send and receive the 9 bits data but must restart the port everytime changing the parity value. the restarting is noway because I'll lose the ID of comunication with the device and the dialoge cycle is each 12ms. Can someone give me a clue how to solve this. Thanks!


text:
Q: Javascript Clock - Clock is empty despite full program I have poured over this code and I feel pretty positive about it. That being said, something is obviously missing, as the program itself comes up with an empty clock when run in the browser. I know that the brackets and parentheses all have a matching set, and I am fairly confident in my functions. The chrome developer tools were unhelpful. Anyone with a good eye for Javascript able to see what is missing here?

"use strict";
var $ = function(id) {
  return document.getElementById(id);
};

var displayCurrentTime = function() {
  var today = new Date();
  var hour = today.getHours();
  var min = today.getMinutes();
  var sec today.getSeconds();

  var ap = "AM";

  if (hour > 12) {
    h = h - 12;
    ap = "PM";
  } else {
    switch (hour) {
      case 12:
        ap = "PM";
        break;
      case 0:
        ap = "AM";
        break;
    }
  }

  $("hours").firstChild.nodeValue = padSingleDigit(hours);
  $("minutes").firstChild.nodeValue = padSingleDigit(min);
  $("seconds").firstChild.nodeValue = padSingleDigit(sec);
  $("ap").firstChild.nodeValue = padSingleDigit(ap);
};

var padSingleDigit = function(num) {
  if (num < 10) {
    return "0" + num;
  } else {
    return num;
  }
};

window.onload = function() {
  displayCurrentTime();
  setInterval(displayCurrentTime, 1000);
};

        <meta charset="UTF-8">
        <title>Clock</title>
        <link rel="stylesheet" href="clock.css">

Digital clock

            <fieldset>
                <legend>Clock</legend>
                 :
                 :

            </fieldset>

A: You simply have a lot of (3) typos  ...

"use strict";
var $ = function(id) {
  return document.getElementById(id);
};

var displayCurrentTime = function() {
  var today = new Date();
  var hour = today.getHours();
  var min = today.getMinutes();
  var sec = today.getSeconds();

  var ap = "AM";

  if (hour > 12) {
    hour = hour - 12;
    ap = "PM";
  } else {
    switch (hour) {
      case 12:
        ap = "PM";
        break;
      case 0:
        ap = "AM";
        break;
    }
  }

  $("hours").firstChild.nodeValue = padSingleDigit(hour);
  $("minutes").firstChild.nodeValue = padSingleDigit(min);
  $("seconds").firstChild.nodeValue = padSingleDigit(sec);
  $("ampm").firstChild.nodeValue = padSingleDigit(ap);
};

var padSingleDigit = function(num) {
  if (num < 10) {
    return "0" + num;
  } else {
    return num;
  }
};

window.onload = function() {
  displayCurrentTime();
  setInterval(displayCurrentTime, 1000);
};

Digital clock

  <fieldset>
    <legend>Clock</legend>
     :
     :

  </fieldset>

*there are other (non-functional) problems in this code, but since it is not the Q, I'd not change them to keep this answer on point.


text:
Q: Getting CORS / Origin Error When Calling External API I have a react app without a backend that is using localhost. In a component, there is an onClick handler which calls an external API to get data. The state is amended to have a piece of state be the return value of the API.
The code for that call:
fetch(statsURL)
    .then(function(response) {
        return response.resultSets.rowSet
    })

This generates the following error:

In the Network details, I do get a 200 OK status code, and here is the header info:

Let me know if you have any suggestions. Thanks

A: You can use YQL to request resources that are not served with CORS headers. To get the response from a fetch() call use Response.text(), Response.json(), Response.blob() or Response.arrayBuffer()
fetch(statsURL)
.then(function(response) {
  return response.json()
})
.then(function(data) {
  console.log(data.resultSets.rowSet)
})
.catch(function(err) {
  console.error(err)
})


text:
Q: Sort a list with longest items first I am using a lambda to modify the behaviour of sort.
sorted(list, key=lambda item:(item.lower(),len(item)))

Sorting a list containing the elements A1,A2,A3,A,B1,B2,B3,B, the result is A,A1,A2,A3,B,B1,B2,B3.
My expected sorted list would be A1,A2,A3,A,B1,B2,B3,B.
I've already tried to include the len(item) for sorting, which didn't work. How to modify the lambda so that the sort result is instead?

A: Here is one way to do it:
>>> import functools
>>> def cmp(s, t):
    'Alter lexicographic sort order to make longer keys go *before* any of their prefixes'
    ls, lt = len(s), len(t)
    if ls < lt:   s += t[ls:] + 'x'
    elif lt < ls: t += s[lt:] + 'x'
    if s < t: return -1
    if s > t: return 1
    return 0

>>> sorted(l, key=functools.cmp_to_key(cmp))
['A1', 'A2', 'A3', 'A', 'B1', 'B2', 'B3', 'B']

Traditionally, lexicographic sort order longer strings after their otherwise identical prefixes (i.e.  'abc' goes before 'abcd').
To meet your sort expectation, we first "fix-up" the shorter string by adding the remaining part of the longer string plus another character to make it the longer of the two:
compare abc to defg     -->  compare abcgx to defg
compare a   to a2       -->  compare a2x to a2

The functools.cmp_to_key() tool then converts the comparison function to a key function.
This may seem like a lot of work, but the sort expectations are very much at odds with the built-in lexicographic sorting rules.
FWIW, here's another way of writing it, that might or might not be considered clearer:
def cmp(s, t):
    'Alter lexicographic sort order to make longer keys go *before* any of their prefixes'
    for p, q in zip(s, t):
        if p < q: return -1
        if q < p: return 1
    if len(s) > len(t): return -1
    elif len(t) > len(s): return 1
    return 0

The logic is:

*

*Compare character by character until a different pair is found

*That differing pair determines the sort order in the traditional way

*If there is no differing pair, then longest input goes first.

*If there is no differing pair and the lengths are equal, the strings are equal.

A: My first answer was: just negate the len criterion to reverse only on that criterion.
sorted(list, key=lambda item:(item.lower(),-len(item)))   # doesn't work!

But that doesn't work, because there's a conflict between alpha sort and length. Alpha sort puts small strings first. So length criterion doesn't work.
You need to merge both criteria. There's no clear priority between each other.
I found a way: first compute the max length of your strings, then return the chr(127) filled (the biggest char provided you're using only ASCII) version of the string as key so smallest strings are filled with big chars in the end: they always come last.
l = ["A","B","A1","A2","A3","B1","B2","B3"]

maxlen = max(len(x) for x in l)
print(sorted(l, key=lambda item:item.lower()+chr(127)*(maxlen-len(item))))

result:
['A1', 'A2', 'A3', 'A', 'B1', 'B2', 'B3', 'B']

BTW don't call your list list for obvious reasons.

A: One could construct the key by taking:

*

*the first letter of every item

*the length

*the item itself

For example:
>>> L = ['A1', 'B2', 'A', 'A2', 'B1', 'A3', 'B3', 'B']
>>> print(sorted(L, key = lambda item: (item[0], -len(item), item)))
['A1', 'A2', 'A3', 'A', 'B1', 'B2', 'B3', 'B']

A: I love Tries, so just for fun, I wrote a Trie-based solution :
class Trie():

    def __init__(self):
        self.data = {}

    def add(self, word):
        ref = self.data
        for char in word:
            ref[char] = char in ref and ref[char] or {}
            ref = ref[char]
        ref[''] = 1

def sorted_print(dct, prefix=''):
    sorted_keys = sorted(filter(bool, dct.keys()), key=str.lower)
    for key in sorted_keys:
        v = dct[key]
        if isinstance(v, dict):
            sorted_print(v, prefix + key)
    if '' in dct:
        print(prefix)

my_list = ["B1", "B3", "B2", "A1", "A2", "A3", "A", "B"]
t = Trie()
for w in my_list:
    t.add(w)

sorted_print(t.data)
# A1
# A2
# A3
# A
# B1
# B2
# B3
# B

This should work for any string of any length.
Note that the result is just printed to screen, not written back in a new list. You didn't write much code, so I'll leave it as an exercise ;)


text:
Q: Laravel Auth::attempt wont work I saw a lot of question relevant to my problem. But none of any solution work in my case.
My Problem:
When I am trying Auth::attempt() to login it shows this message.
exception 'ErrorException' with message 'Argument 1 passed to Illuminate\Auth\EloquentUserProvider::validateCredentials() must be an instance of Illuminate\Auth\UserInterface, instance of User given, called in D:\Workshop\Xampp\htdocs\TP_MAIN\vendor\laravel\framework\src\Illuminate\Auth\Guard.php on line 371 and defined' in D:\Workshop\Xampp\htdocs\TP_MAIN\vendor\laravel\framework\src\Illuminate\Auth\EloquentUserProvider.php:104
Stack trace:
#0 D:\Workshop\Xampp\htdocs\TP_MAIN\vendor\laravel\framework\src\Illuminate\Auth\EloquentUserProvider.php(104): Illuminate\Exception\Handler->handleError(4096, 'Argument 1 pass...', 'D:\Workshop\Xam...', 104, Array)
#1 D:\Workshop\Xampp\htdocs\TP_MAIN\vendor\laravel\framework\src\Illuminate\Auth\Guard.php(371): Illuminate\Auth\EloquentUserProvider->validateCredentials(Object(User), Array)
#2 D:\Workshop\Xampp\htdocs\TP_MAIN\vendor\laravel\framework\src\Illuminate\Auth\Guard.php(352): Illuminate\Auth\Guard->hasValidCredentials(Object(User), Array)
#3 [internal function]: Illuminate\Auth\Guard->attempt(Array)
#4 D:\Workshop\Xampp\htdocs\TP_MAIN\bootstrap\compiled.php(8177): call_user_func_array(Array, Array)
#5 D:\Workshop\Xampp\htdocs\TP_MAIN\bootstrap\compiled.php(3227): Illuminate\Support\Manager->__call('attempt', Array)
#6 D:\Workshop\Xampp\htdocs\TP_MAIN\bootstrap\compiled.php(3227): Illuminate\Auth\AuthManager->attempt(Array)
#7 D:\Workshop\Xampp\htdocs\TP_MAIN\app\controllers\AccountController.php(31): Illuminate\Support\Facades\Facade::__callStatic('attempt', Array)
#8 D:\Workshop\Xampp\htdocs\TP_MAIN\app\controllers\AccountController.php(31): Illuminate\Support\Facades\Auth::attempt(Array)
#9 [internal function]: AccountController->postLogin()
#10 D:\Workshop\Xampp\htdocs\TP_MAIN\vendor\laravel\framework\src\Illuminate\Routing\Controller.php(231): call_user_func_array(Array, Array)
#11 D:\Workshop\Xampp\htdocs\TP_MAIN\bootstrap\compiled.php(5784): Illuminate\Routing\Controller->callAction('postLogin', Array)
#12 D:\Workshop\Xampp\htdocs\TP_MAIN\bootstrap\compiled.php(5772): Illuminate\Routing\ControllerDispatcher->call(Object(AccountController), Object(Illuminate\Routing\Route), 'postLogin')
#13 D:\Workshop\Xampp\htdocs\TP_MAIN\bootstrap\compiled.php(4971): Illuminate\Routing\ControllerDispatcher->dispatch(Object(Illuminate\Routing\Route), Object(Illuminate\Http\Request), 'AccountControll...', 'postLogin')
#14 [internal function]: Illuminate\Routing\Router->Illuminate\Routing\{closure}()
#15 D:\Workshop\Xampp\htdocs\TP_MAIN\bootstrap\compiled.php(5330): call_user_func_array(Object(Closure), Array)
#16 D:\Workshop\Xampp\htdocs\TP_MAIN\bootstrap\compiled.php(4996): Illuminate\Routing\Route->run(Object(Illuminate\Http\Request))
#17 D:\Workshop\Xampp\htdocs\TP_MAIN\bootstrap\compiled.php(4984): Illuminate\Routing\Router->dispatchToRoute(Object(Illuminate\Http\Request))
#18 D:\Workshop\Xampp\htdocs\TP_MAIN\bootstrap\compiled.php(717): Illuminate\Routing\Router->dispatch(Object(Illuminate\Http\Request))
#19 D:\Workshop\Xampp\htdocs\TP_MAIN\bootstrap\compiled.php(698): Illuminate\Foundation\Application->dispatch(Object(Illuminate\Http\Request))
#20 D:\Workshop\Xampp\htdocs\TP_MAIN\bootstrap\compiled.php(7706): Illuminate\Foundation\Application->handle(Object(Illuminate\Http\Request), 1, true)
#21 D:\Workshop\Xampp\htdocs\TP_MAIN\bootstrap\compiled.php(8309): Illuminate\Session\Middleware->handle(Object(Illuminate\Http\Request), 1, true)
#22 D:\Workshop\Xampp\htdocs\TP_MAIN\bootstrap\compiled.php(8256): Illuminate\Cookie\Queue->handle(Object(Illuminate\Http\Request), 1, true)
#23 D:\Workshop\Xampp\htdocs\TP_MAIN\bootstrap\compiled.php(10895): Illuminate\Cookie\Guard->handle(Object(Illuminate\Http\Request), 1, true)
#24 D:\Workshop\Xampp\htdocs\TP_MAIN\bootstrap\compiled.php(659): Stack\StackedHttpKernel->handle(Object(Illuminate\Http\Request))
#25 D:\Workshop\Xampp\htdocs\TP_MAIN\public\index.php(49): Illuminate\Foundation\Application->run()
#26 {main}

Log in Form:
{{-- Form start --}}
<form action="{{ URL::route('log_in') }}" method="post">
<input name="loginemail" placeholder="Email" type="email">
<input name="loginpassword" placeholder="Password" type="password">
{ Form::token() }}

<input type="submit" value="Sign In" />

</form>
{{-- form end --}}

User model:
<?php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

    protected $fillable = array('fullname', 'password', 'email', 'code', 'active', 'account_type', 'team_id', 'image_path', 'token');

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = array('password', 'remember_token');

}

Controller:
public function postLogin(){

        $loginvalidation = Validator::make(
            [
                'loginemail' => Input::get('loginemail'),
                'loginpassword' => Input::get('loginpassword'),
            ],
            [
                'loginemail' => 'required|email',
                'loginpassword' => 'required'
            ]
        );

         if($loginvalidation->fails()) {
            return Redirect::route('home');
        }
        else{
            $loginemail = Input::get('loginemail');
            $loginpassword = Input::get('loginpassword');

            try {

                $auth = Auth::attempt(array(
                        'email' => $loginemail,
                        'password' => $loginpassword,
                        'active' => 1
                    ));

                if($auth){
                    return Redirect::route('home');
                }

            } catch(Exception $e){
                echo "<pre>".$e."</pre>";
            }
        }

    }

I have already checked this issues:

*

*My password is hashed upon creating it to the database.

*My password field in my database is varchar 255.

*The user I'm trying to log in is already created.

Can anybody give me a hint regarding this error?
Thanks in advance.


text:
Q: confusion matrix and test accuracy in multi-label image classification for keras I'm trying to learn multi-label classification using Keras. The dataset is Robotic Instrument (for kidney surgery) classification with 11 classes. I built a model for a multi-label classification problem and able to evaluate model performance. However, I have problem to claculate test accuracy and confusion matrix. Can anyone please share a code snippt that works. Thanks in advance to everyone!
name_label_dictionary = {
1:  "instrument-shaft",
2:  "instrument-clasper",
3:  "instrument-wrist",
4:  "kidney-parenchyma",
5:  "covered-kidney",
6:  "thread",
7:  "clamps",
8:  "suturing-needle",
9:  "suction-instrument",
10:  "small-intestine",
11:  "ultrasound-probe"}
image_dataframe = pd.read_csv('data/train.csv')

encoder = MultiLabelBinarizer()
encoder.fit_transform([(1,),(2,),(3,),(4,),(5,),(6,),(7,),(8,),(9,),(10,),  (11,)])
samples = list(zip(image_dataframe['Id'],image_dataframe['Target']))
train_samples, validation_samples = train_test_split(samples,test_size=0.15)

def generator(data,batch_size=8):
images_path_length = len(data)
while 1:
    for off in range(0,images_path_length,batch_size):
        images_list = data[off:off+batch_size]
        rgb_arr=[]
        label=[]
        for j in images_list:
            img=[]
            img = np.array(Image.open("data/train/"+j[0]+"_resized.png"))/255
            rgb_arr.append(img)
            label.append(encoder.transform([tuple(map(int,j[1].split()))]))

        yield np.array(rgb_arr),np.array(label).reshape(len(label),11)

train_images_gen = generator(train_samples)
val_images_gen = generator(validation_samples)

Here is the Keras code to train the data.
   model = InceptionV3(include_top = True, weights = None, classes=11)
   model.layers.pop()
   x = model.layers[-1].output
   x = Dense(11, activation='sigmoid', name='predictions')(x)
   train_model = Model(input=model.input,output=x)
   train_model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

   train_model.fit_generator(train_images_gen,
                      epochs=10,
                      verbose=1,
                      steps_per_epoch=len(train_samples)/8,
                      validation_data=val_images_gen,
                      validation_steps=len(validation_samples)/8)

 score = train_model.evaluate_generator(val_images_gen, steps=50)
 print ('Validation Score: ', score[0])
 print ('Validation Accuracy: ',score[1])

At the next part, I generate the test set and its corresponding labels similar to train and validation set.
test_image_dataframe = pd.read_csv('data/test.csv')
test_samples = list(zip(test_image_dataframe['Id'], test_image_dataframe['Target']))

def test_generator(data,batch_size=8):
images_path_length = len(data)
while 1:
    for off in range(0,images_path_length,batch_size):
        images_list = data[off:off+batch_size]
        rgb_arr=[]
        label=[]
        for j in images_list:
            img=[]
            img = np.array(Image.open("data/test/"+j[0]+"_resized.png"))/255
            rgb_arr.append(img)
            label.append(encoder.transform([tuple(map(int,j[1].split()))]))

        yield np.array(rgb_arr),np.array(label).reshape(len(label),11)

and at the end predict the labels:
results = train_model.predict_generator(test_images_gen,steps=len(test_samples)/8,verbose=1)

predictions=[]
for i in results:
    label_predict=np.arange(11)[i >=0.2]
    predictions.append(' '.join(str(l) for l in label_predict))
print(predictions)

output of predictions is :
['0 1 2 4 5',
 '0 1 2 4',
 '0 1 2 4',
 '0 1 2 3 4',
 '0 1 2 3 4',
 '0 1 2 3 4',
 '0 1 2 3 4',
 '0 1 2 3 4',
 '0 1 2 3 4',
 '1 2 3 4',
 '0 1 2 3 4',
 '0 1 2 3 4',
 '0 1 2 3 4',

output of results is:
array([[9.96413887e-01, 1.00000000e+00, 9.80881095e-01, ...,
    8.43488611e-04, 9.98612493e-03, 1.06460014e-07],
   [9.88547325e-01, 9.99999881e-01, 9.43120480e-01, ...,
    4.49081184e-03, 7.23437071e-02, 1.84218152e-05],
   [9.99697685e-01, 1.00000000e+00, 9.99999642e-01, ...,
    1.14535843e-03, 1.99837261e-03, 6.23652944e-03],
   ...,
   [9.99984503e-01, 1.00000000e+00, 9.99968529e-01, ...,
    4.65406990e-03, 5.77826202e-01, 3.62675011e-01],


text:
Q: find colour property in array of objects Trying to find matching property in an array of objects. I cant get my find to pick out the colour. Any ideas? I can't get anything to console.log
const tag = 'lecture';

const eventColour = [
        {
            type: "lecture",
            colour: "red"
        },
        {
            type: "social",
            colour: "blue"
        },
        {
            type: "break",
            colour: "green"
        }
    ]

eventColour.filter(obj => Object.keys(obj).find(e => obj[e].type == tag))

A: If your goal is to get the colour of the object with the matching type, that would be find combined with a property accessor:
const obj = eventColour.find(obj => obj.type === tag);
const colour = obj && obj.colour;

We need that && guard in case there's no match.
Live Example:

const tag = 'lecture';

const eventColour = [
        {
            type: "lecture",
            colour: "red"
        },
        {
            type: "social",
            colour: "blue"
        },
        {
            type: "break",
            colour: "green"
        }
    ];

const obj = eventColour.find(obj => obj.type === tag);
const colour = obj && obj.colour;
console.log(tag + " => " + colour);

// Example of not finding it:
const tag2 = "not found";
const obj2 = eventColour.find(obj => obj.type === tag2);
const colour2 = obj2 && obj2.colour;
console.log(tag2 + " => " + colour2);

A: Try this

const tag = 'lecture';

const eventColour = [{
    type: "lecture",
    colour: "red"
  },
  {
    type: "social",
    colour: "blue"
  },
  {
    type: "break",
    colour: "green"
  }
]

eventColour.forEach(function(obj) {
  if (obj['type'] == tag) {
    console.log(obj['colour'])
  }
});

A: What't the problem with using a good old loop ?

const tag = 'social';
const eventColour = [
        {
            type: "lecture",
            colour: "red"
        },
        {
            type: "social",
            colour: "blue"
        },
        {
            type: "break",
            colour: "green"
        }
    ]

for(var i = 0; i < eventColour.length;i++)
{
 var obj = eventColour[i];
 if (obj['type'] == tag)
 {
  console.log(obj['colour']);
  break;
 }
}


text:
Q: How to output a string in a variable removing the first character that is found using a substr function Hi I have a string named $sql which is:
* FROM users WHERE users.id = '390' (just and example, can be anything)
In my function I have a $sql variable which is the string above. I wish to get rid of the * before the FROM. My variable $star does output the *, but how do I code the $sql variable to exclude the * character in front of it?
$sql = $this->pdoquery($a, $v);
$star = substr($sql, 1, 2);
$query = "DELETE " . $sql;

I cannot alter the $sql variable to omit it in the pdoquery function, because I use it for SELECT etc.

A: To remove any leading character, you can use the php function ltrim.
$sql = ltrim($sql, "*");

var_dump($sql); // Output: string(34) " FROM users WHERE users.id = '390'"

Edit according to your update:
Since you cannot modify the original variable, you can simply do it like this:
$without_star = ltrim($sql, "*");

var_dump($sql); // Output: string(35) "* FROM users WHERE users.id = '390'"
var_dump($without_star); // Output: string(34) " FROM users WHERE users.id = '390'"

A: If you only want to remove the asterisk '*'
you can replace in your code this line:
$star = substr($sql, 1, 2);

with:
$star = str_replace('*',"",$sql);
//this will remove all asterisk

If you only need to replace the first occurrence of '*' use:
$star = preg_replace('/\*/', '', $sql, 1);


text:
Q: Building intranet search At work, we have lots of information squirreled away in many different sites -- wikis, product docs, ticketing system, etc -- many of which require authentication.
I'm very interested in having a single way to search all our various silos, and in my spare time have looked at Nutch, Grub, Django + Haystack, etc.  None of these is a complete solution a la Google Mini or Google Search Appliance.
Has anybody built a basic intranet search engine out of a mixture of these tools?  Would you have recommendations about how to go about it?  I like Django, and Haystack seems to be a mildly popular search solution for it, but I'd need to wire up a crawler that can support crawling authenticated sites to it.

A: Velocity by Vivisimo is a great product, but expensive.

A: Take a look at Lucene from the Apache Foundation. Also take a look on their PoweredBy wiki page, maybe you even find a project already using lucene.


text:
Q: MySql error code: 1290 secure_file_priv This question has been asked before and I researched most of the answers, but still no fix.
In MySQL workbench 6.3 CE, I type: load data infile 'C:\Users\User1\Desktop\cm07JAN2014bhav.csv'
into table stockmovements fields terminated by ',' ignore 1 lines;
I then get the secure-file-priv error.
One of the previous answers here in stackoverflow says to find the directory where I can store the file by typing: SHOW VARIABLES LIKE "secure_file_priv";
I did and get: 'C:\ProgramData\MySQL\MySQL Server 5.7\Uploads\'
However, after I go into my C Drive there is no "Program Data" folder. Just a "Program Files" folder.
So I cannot find the correct folder path in which to place the csv file so the error message stops.
Please help.

A: try to create the folder 'C:\ProgramData\MySQL\MySQL Server 5.7\Uploads\' or change the setting of secure_file_priv and restart MySQL

A: You need to enable Hidden Items to show ProgramData folder. Have a read: https://support.microsoft.com/en-gb/help/14201/windows-show-hidden-files


text:
Q: How to represent Log-Normal Distribution I am having trouble getting the following distribution represented in the picture below to give me correct values in excel. Can anyone give me any assistance?
Log Normal Distribution

Here is the formula I am using in excel.
=LOGNORM.INV(RAND(),2000,800)

A solution in R or excel would be nice.

A: Finally figured it out. You have to use the conversion formulas (See https://en.wikipedia.org/wiki/Log-normal_distribution under Notation):
mean <- 2000
sd <- 800
meanlog <- log(mean/sqrt(1+sd^2/mean^2))
sdlog <- sqrt(log(1+sd^2/mean^2))
plot(density(rlnorm(100000, meanlog=meanlog, sdlog=sdlog)), xlim=c(0,5000))


text:
Q: How can i write inner query in spring boot jpa My query is this :

SELECT * FROM property_data p JOIN (SELECT property_id, MAX(date) AS
  MaxDateTime FROM property_data WHERE property_id IN (18255, 80604,
  35983, 41220)GROUP BY property_id) groupedtt ON p.property_id =
  groupedtt.property_id AND p.date = groupedtt.MaxDateTime AND
  p.property_id IN (18255, 80604, 35983, 41220);

I have written in this form:
@Query("SELECT p FROM DateWisePropertyInfo p JOIN (SELECT h.property_id, MAX(h.date) AS MaxDateTime FROM DateWisePropertyInfo h WHERE h.property_id IN :hIds GROUP BY h.property_id) p.groupedtt ON p.property_id = groupedtt.property_id AND p.date = groupedtt.MaxDateTime AND p.property_id IN :hIds")
List<DateWisePropertyInfo> findByLatestDateAndPropertyIdIn(@Param("hIds") List<Long> propertyIds);

Detailed Error :
Caused by: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 81 [SELECT p FROM com.oyorooms.retention.entity.primary.DateWisePropertyInfo p JOIN (SELECT h.property_id, MAX(h.date) AS MaxDateTime FROM com.oyorooms.retention.entity.primary.DateWisePropertyInfo h WHERE h.property_id IN :hIds GROUP BY h.property_id) p.groupedtt ON p.property_id = groupedtt.property_id AND p.date = groupedtt.MaxDateTime AND p.property_id IN :hIds]

But this is not working, throwing InvocationTargetException.


text:
Q: how can I solve the problem with accents even if I already used a charset = UTF-8? <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>

<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Library Management</title>
  <meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/css/materialize.min.css">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link href="assets/css/custom.css" rel="stylesheet" type="text/css" />

  <jsp:include page='menu.jsp'></jsp:include>

        menu

Fiche livre

Crèation d'un nouveau livre

          <form action="livre_add" method="post" class="col s12">

                <input id="titre" type="text" name="titre">
                Titre

                <input id="auteur" type="text" name="auteur">
                Auteur

                <input id="isbn" type="text" name="isbn">
                ISBN 13

              <button class="btn waves-effect waves-light" type="submit">Enregistrer</button>
              <button class="btn waves-effect waves-light orange" type="reset">Annuler</button>

          </form>

  <jsp:include page='footer.jsp'></jsp:include>

That's a file in .jsp that is a class to visualize one function of the program .
I have a problem when I open the browser, the accents are decoded as not found even if I have used a UTF-8 charset and  statement to print Crèation d'un nouveau livre .


text:
Q: Entity Framework - Update entity with child properties I have an entity that has one child and I need to update it, but, in the TryUpdateModel  method, it does not accept an strong typed object (accepts only a FormCollection), and when I try to update it, I get the following error.
{"A relationship is being added or deleted from an AssociationSet 'FK__SG_Usuari__ID_Si__534D60F1'. With cardinality constraints, a corresponding 'SG_Usuario' must also be added or deleted."}
The problem is that I can't load in the formcollection the child property, only an id, but not the entire object.

A: You can directly click update from model in entity framework and it will automatically update the enitty with all the relationship

A: the "create" statement is like this:
    public ActionResult Edit(FormCollection  form)
    {

      Usuario usuario = new Usuario
             {
                 NomeUsuario = form["Usuario.NomeUsuario"],
                 IdeUsuario = form["Usuario.IdeUsuario"],
                 NumRegistroRM = form["Usuario.NumRegistroRM"],
                 SenUsuario = form["Usuario.SenUsuario"],
                 SituacaoUsuario = this.SituacaoUsuarioService.GetSituacaoUsuario(x => x.ID_SituacaoUsuario == Convert.ToInt32(form["Usuario.SituacaoUsuario"]// note that i have to retrieive the entire object... the "child"

             };

      this.UsuarioService.AddUsuario(usuario);
     }

the edit statement should be like this:
 TryUpdateModel(a, "Usuario", this.GetUsuarioWhiteList(), form.ToValueProvider()); // but the form contains only the id and I can't load the child in it nor pass the object.

A: I had the same issue recently and I managed to solve it when I changed the cardinality ratios for my foreign keys in the child table from 1:many to 0..1:many in the Entity Designer and it worked fine.


text:
Q: How to implement threaded socket.recv() in python? I have a number of devices from which i need to get status updates. A socket object is all I have, and socket.recv() is all I need to get the status. Put into a single threaded application, no problems occur:
class Device:
    def receive(self):
        log.debug("receive waiting: %r", self.device_id)
        try:
            packet = self.socket.recv(255)
        except Exception as e:
            self.report_socket_error(e)
            self.reconnect()
        log.debug("received response: %r", self.device_id)
d = Device()
d.connect()
while True:
    d.receive()

However, the same code wrapped in a threading.Thread class causes deadlocks and funny behaviour. Wrapping it with locks didn't change anything. I traced the problem down to be the socket.recv() call...So, how to implement multiple threads where each thread owns one socket (1 thread owns exclusively 1 socket), which are able to wait for data simultaneously?
Thanks in advance

A: How many different sockets do you have to read from?

*

*If the answer is "just one", then use just one thread. Adding another helps you in no way and only complicates your life, as you found out.

*If the answer is "several", than one way to organize this is indeed to have a thread per socket. recv is a blocking operation, which makes a thread an attractive option to organize code. Each thread owns a separate socket and reads from it at its leisure. You should have no problems and deadlocks with this.
Locks are unnecessary as long as no resources are shared. Even if you do share resources (logging, some data store, etc.) don't just use simple locks - Python has higher-level utilities for that like the Queue module.

A: I know this does not answer your question on how to fix your deadlock problem, however it appears as your use of threads is overhead in your case:
You can just use one thread in which you use select() to find out which socket has available data and then handle the reported data. Unless the handling takes long or your protocol is more complicated select should be just fine and avoid all threading issues.
Have a look at http://docs.python.org/howto/sockets.html#non-blocking-sockets for more details.


text:
Q: Problems extracting property names from an object (JAVASCRIPT) I have an array of objects (I think!) and I need to extract the property name (for example "nickname") from a given object.
With
var VarObjAndValue = newArr[0];

I get the individual arrays (for example Object { nickname: "jhonny" }).
How can I now extract the property name "nickname" from the object above?
Listing the keys with
var listPropertyNames = Object.keys(newArr);

only provides sequential numbers from 0 to 6 rather than the desired keys names..
var StrToInclude = ["nickname", "name", "surname", "sex", "dob", "email", "phone"];
var newArr=[]; //Key name + its value

for (var i=0; i<StrToInclude.length; i++) {
  temp_obj = {};
  temp_obj[StrToInclude[i]] = document.getElementById(StrToInclude[i]).value;
  newArr.push(temp_obj);
}

console.log('newArr --> = ',newArr);
/**
 * newArr = [
 * { "nickname": "jhonny" },
 * { "name": "jonathan" },
 * { "surname": "ross" },
 * { "sex": "male" },
 * { "dob": "22/02/1984" },
 * { "email": "j@yahoo.com" },
 * { "phone": "123" }
 * ]
 */

var VarObjAndValue = newArr[0];
console.log('VarObjAndValue --> = ',VarObjAndValue); //if i=0 ----> Object { nickname: "jhonny" }

var VarObjAndValue = newArr[1];
console.log('VarObjAndValue --> = ',VarObjAndValue); //if i=1 ----> Object { name: "jonathan" }

var listPropertyNames = Object.keys(newArr);
console.log('listPropertyNames --> = ',listPropertyNames); //Array(7) [ "0", "1", "2", "3", "4", "5", "6" ] (not useful for this...)

A: newArr.map(obj => Object.keys(obj)).flat()

or newArr.map(obj => Object.keys(obj)[0])
or from dave's comment
newArr.reduce((keys, o) => [...keys, ...Object.keys(o)], [])

gives you all property names as an array
Not sure if this is what you want, but you have already gotten those property names in StrToInclude

const newArr =
                [
                  {
                    "nickname": "jhonny"
                  },
                  {
                    "name": "jonathan"
                  },
                  {
                    "surname": "ross"
                  },
                  {
                    "sex": "male"
                  },
                  {
                    "dob": "22/02/1984"
                  },
                  {
                    "email": "j@yahoo.com"
                  },
                  {
                    "phone": "123"
                  }
                ]

console.log(newArr.map(obj => Object.keys(obj)[0]))

A: You are very close to getting the right answer. Since newArr is an Array, the keys are numeric keys. All you have to do is go through each element is the Array of Objects to extract the keys. Something like this should do nicely:
for(let i = 0;i<newArr.length;i++){
    console.log(Object.keys(newArr[i])); //Will go through the whole array and give you the keys of every object in it
}

A: You can simply do by looping over the array and using destructuring operator with the desired property name.
const arr = [
  {
    nickname: "abdullah"
  },
  {
    age: 27
  }
];

arr.forEach(({nickname}) => {
    if (nickname) {
    console.log(`Thats the property we want to extract: ${nickname}`);
    break; // if you are not expecting this property name in other objects, otherwise no need to break
  }
});


text:
Q: Unknown internal error in nodejs runMicrotasks() When i try to run a nodejs program, i get the following error:
node:internal/process/task_queues:96
    runMicrotasks();
    ^

TypeError: Cannot convert undefined or null to object
    at push (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

REPL Node works just fine. When i try to run a js file i get the error.

A: Because This error is caused when you call a function that expects an Object as its argument, but pass undefined or null instead
U can try

If(obj == null)
{
console.log(null)//or return null
}

A: Fixed by updating windows 10 and installing a newer version of node.


text:
Q: Why do i not get through to my Meteor.method on the server? I'm trying to add a url to the logged in users collection. My final goal at least is to be able to add a field e.g {profilePicture: 'http://randompic.com/123.png'}
What i've tried so far is:
<template name="profile">

My Profile

  <form class="form-inline"action="">

    <input class="input input-large" type="url" name="url" placeholder="URL for you image..." id="url">
    <button class="btn btn-success submit">Update profile picture</button>
  </form>
</template>

When the user will press the Update profile picture -button i send it to this helper function:
Template.profile.events({
  'click .submit': function (evt, tmpl) {
    var userid = Meteor.userId();
    var url = tmpl.find('#url').value;
    var options = {_id: userid, profilePicture: url};
    Meteor.call('addToProfile', options);
  }
});

I have tried to alert out option._id and options.profilePicture and i have that data availble.
Now when i pass it along to my server.js file i get no output of my alert:
Meteor.methods({
  'addToProfile': function(options) {

  //Not even this alert will show..

    alert(options._id);    Edit: console.log() works on the server thought.
  }
})

So that is my first issue.
The second problem (to come) is that i don't know how to update/add to the users collection with this profilePicture data. Would really appreciate if someone could contribute with a small example of that part.

A: Based on the comments everything seems to be functioning as expected. It appears that you are just trying to update some user data on the client. Since you have the insecure package removed you need to validate the updates on the server (that the client requests), this is how you would do that:
// only applies to client requests
Meteor.users.allow({
    // validation for user inserts
    insert: function ( userId, doc ) {

        // perform any checks on data that you want to perform, like checking to see if the current user is an admin.

        // this check just requests that a user be logged in
        return userId;
    }
    ,
    // is your validation for user updates
    update: function ( userId, doc, fields, modifier ) {

        // again, perform any validation you want. A typical check is to make sure they didn't add any extra fields.

        // this makes sure a user is logged in and that they are only attempting to update themself
        return userId === doc._id;
    }
});

There are some more thorough examples in the docs. Now you can just call update like you normally would and rely on the server to perform any validation!


text:
Q: Recovering a SQL Server database In a series of unfortunate mistakes, I lost 4 months of data and all the rapid database modifications. I'm not a database administrator, I'm a programmer who also designs and happens to maintain a database.
Initially I just wanted to only compare some database objects to another database. I did that using OpenDBDiff tool. I selected the objects that I wanted to update and hit 'Update selected'. It failed for some reason, but I didn't pay any attention to it. So I generated a script to execute directly into SSMS. I again failed to notice that the script included all objects, and not just the selected ones. I realized too late, by then, some of the destination's database objects i.e. tables, views, functions, etc. were already dropped.
And then it got worse,  I know we have daily backup and decided to restore from there. It turns out that for some reason, this database, on that server has its last backup 4 months ago and didn't run afterwards successfully. I decided that I'd restore from its transaction log to the current date. I still don't know if that's even possible, but I decided to do it on a live database. I did not take a new backup even at this point, I was afraid that this will destroy the transaction log. So I ran a command like this:
USE [master]
BACKUP LOG [mydb] TO  DISK = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\mydb_LogBackup_2019-01-17_13-49-00.bak' WITH NOFORMAT, NOINIT,  NAME = N'mydb_LogBackup_2019-01-17_13-49-00', NOSKIP, NOREWIND, NOUNLOAD,  NORECOVERY ,  STATS = 5
RESTORE DATABASE [mydb] FROM  DISK = N'D:\Backups\mydb_2018_08_30_19_01_01\mydb.bak' WITH  FILE = 1,  MOVE N'exact_Data' TO N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\mydb.mdf',  MOVE N'exact_Log' TO N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\mydb.ldf',  NORECOVERY,  NOUNLOAD,  STATS = 5
RESTORE LOG [mydb] FROM  DISK = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\mydb_LogBackup_2019-01-17_13-49-00.bak' WITH  NOUNLOAD,  STATS = 5,  STOPAT = N'2019-01-17T13:00:00'
GO

The log backup failed. The database is now in restoring state. Before all this, mydb.mdf and mydb.ldf files where located in the D:\db folder, now they are not there. Instead they are in C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\. I tried to attach them to my local server, it fails because they are in restoring state too. I download and managed to open the with a SQL Server database repair tool, but the only hold the data from 4 months ago.
I'm currently scanning the computer for deleted files to search for the original .mdf and .ldf files, but I don't have much hope on this because the quick scan didn't show anything and I'm running a deep scan now.
Questions

*

*How can I take the database out of that (restoring…) state and what will happen if I do so? This is why I decided to ask before I do anything else that might be destructive.

*My goal now is to restore the database in the most recent possible state, so how can I achieve that?

A: The last successful restore was the RESTORE DATABASE. Since you specified NORECOVERY, the database is, as expected, in restoring state. If you don't have any more backups to restore and just want to get out of the restoring state, you just do:
RESTORE DATABASE mydb WITH RECOVERY

That's it.  You find the database as it were when that full backup you restored was produced.
As for log backups, you need an unbroken chain of log backups. You can't skip a log backup, like you most probably tried to do. You likely got an error message saying that the log backup was too recent to restore, citing LSN numbers and that it requires some earlier log backup with some earlier LSN number. There's no way around the "unbroken chain of log backups" requirement. If you can't find those log backups, or a more recent full backup, then you are probably stuck with a 4 month old database.


text:
Q: How to automatically run a script in chrome console I am trying to run a chrome console command whenever I land on a webpage. What recourses should I look at to go about doing that? This is all I want to run on loop:
document.querySelector("#currentKey").innerText
Result should be something like this:
V&2Y/9);fQpeP"X,
W{8Q]^DdQB>+>A5z
_Am[{.`>j^8b/DD5

A: Please refer to official google documentation
https://developer.chrome.com/docs/devtools/javascript/snippets/


text:
Q: Is there any built-in functionality in c++ to run task at scheduled time Is there any built-in functionality in c++ to run task at scheduled time? (Some thing like cron?) Or have I to implement it myself?

A: The closest you can do is to wait on a mutex or other synchonization primitive for a specified period of time.
"Release" the mutex (or fire a condition variable, etc) if the app is told to shut down (always a good plan), and if it times out, otherwise run the task.
Note that there are no realtime guarantees -- wait in C++ waits "at least that long".  Basically, if the system is busy, tough.
This can be done in a thread, naturally, so whatever main functionality (message pump or whatever) isn't bothered by it.
You can also sleep for a specified period of time, but programs should always have an abort possibility, and sleeping doesn't provide it.


text:
Q: IOS/Objective-C: String length Syntax for HTTP Post to Server For a JSON request to a server, I am using some code that includes a value for the length of a string as follows:
[request addValue:[NSString stringWithFormat:@"%d", [body length]] forHTTPHeaderField:@"Content-Length"];

This code, however, is throwing a warning that %d should not be used for the length and the code be changed to %lu(unsigned long).
I am following the accepted answer here and numerous other places that says:
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];

Should I follow Xcode's suggestion?  I am a bit reluctant to change working code as I have found XCode's suggestions to occasionally cause unintended problems.
Thanks in advance for any suggestions


text:
Q: Django form wont validate? I am having trouble having my form validate in Django and I really dont know what the problem is.  It is a messaging application and I am trying to have the user sending the message be automatically populated with the user that is logged in.  I have tried a lot of things but none of them have worked. Any help would be appreciated.  Here is my models.py: (anything commented out is previous attempts at a solution)
class Message(models.Model):
#readonly_fields = 'sender'
sender = models.ForeignKey(User, related_name="send", default=User)
recipient = models.ForeignKey(User, related_name="receive", default=None)
message_subject = models.CharField("Subject", max_length=25)
message_text = models.TextField("Message")
message_time_created = models.DateTimeField(auto_now_add=True)
urgent = models.CharField(max_length=3, choices=URGENCY)
#field to make message urgent or not

def __str__(self):
    return self.message_subject

here is the views.py for creating a new message: (anything commented out is previous attempts at a solution)(also includes@login_required tag that wouldnt show up when pasting)
def newMessage(request, user):
user = get_object_or_404(User, pk=user)
#form = MessageForm(request.POST or None, initial={'sender':request.POST.get('username')})
if request.method == 'POST':
    #instance = Message(sender=request.user)
    #form = MessageForm(instance=instance)
    #form = MessageForm(initial={'sender':request.user})
    form = MessageForm(request.POST)
    if form.is_valid():
        new_instance = form.save()
        temp = Event(activity='\n' + new_instance.sender.get_full_name() + " sent a message to " +  new_instance.recipient.get_full_name())
        temp.save()

        try:
            target = Patient.objects.get(user=user)
            return HttpResponseRedirect('/patients/%s/' % target.id)
        except Exception as e:
            try:
                target = Nurse.objects.get(user=user)
                return HttpResponseRedirect('/nurses/%s/' % target.id)
            except Exception as e:
                try:
                    target = Doctor.objects.get(user=user)
                    return HttpResponseRedirect('/doctors/%s/' % target.id)
                except Exception as e:
                    try:
                        target = HospitalAdmin.objects.get(user=user)
                        return HttpResponseRedirect('/hospitalAdmins/%s/' % target.id)
                    except Exception as e:
                        return render(request, "main_site/newMessagePrompt.html",
                                        { "form" : form, })
elif request.method == 'GET':
    form = MessageForm()
return render(request, "main_site/newMessagePrompt.html",
              { "form" : form, })

Here is the form:(anything commented out is previous attempts at a solution)
class MessageForm(ModelForm):
#readonly_fields = 'sender'
urgent = forms.ChoiceField(choices=URGENCY, required=True)
class Meta:
    model = Message
    #widgets = {'sender': forms.HiddenInput()}
    exclude =['message_time_created']

Currently, with giving the sender a default=User in the model, which does auto-populate with the user who is logged in, and if you try to send the message it will work.  However the field can still be edited, which is not intentional.  If i try to make the field editable=False in the model.py, and then try to send the message, it will give an error.  If i try other ways to hide this, such as HiddenInput in the form, the form will not validate.  Similar results have occurred when trying to use an instance variable.  I have also tried to make the sender field be a read only field but have not succesffully been able to implement it to see if it would work.  I really cannot figure out how to fix this problem.  Can anyone help me out with this?


text:
Q: How can i execute two javascript functions I am new in HTML, PHP. I have build a page with following coding -
<script src="js/jquery.min.js"></script>
<script src="js/timepicki.js"></script>
<link rel="stylesheet" type="text/css" href="css/timepicki.css">
<script>
$(document).ready(function (){
$(".time_element").timepicki();
});
</script>
<script src="jquery-1.6.2.min.js"></script>
<script src="jquery-ui-1.8.15.custom.min.js"></script>
<link rel="stylesheet" type="text/css" href="jqueryCalendar.css">
<script>

   jQuery(function () {
      jQuery( "#datepicker" ).datepicker();
      jQuery( "#datepicker1" ).datepicker();
});
 </script>

problem is only second one is working. If I put the first portion in the place of second it also work but both together does not. How can I combine those. I tried "body onload" method and also tried "addloadevent" but probably I am not writing the code properly. Any help will be greatly appreciated.

A: You're including jQuery more than once. Don't do that. Just include it once, then include your plugins. You can leave your ready blocks separate, or combine them, it's up to you.
Here's how I would change that:
In the head:
<link rel="stylesheet" type="text/css" href="css/timepicki.css">
<link rel="stylesheet" type="text/css" href="jqueryCalendar.css">

In the body at the very end prior to the closing </body> tag:
<script src="js/jquery.min.js"></script>
<script src="js/timepicki.js"></script>
<script src="jquery-ui-1.8.15.custom.min.js"></script>
<script>
$(".time_element").timepicki();
$("#datepicker, #datepicker1" ).datepicker();
</script>

...where jquery.min.js is a recent version of jQuery, such as v1.11.2.
Or if you want all the scripts in the head (although that's usually not best practice):
<link rel="stylesheet" type="text/css" href="css/timepicki.css">
<link rel="stylesheet" type="text/css" href="jqueryCalendar.css">
<script src="js/jquery.min.js"></script>
<script src="js/timepicki.js"></script>
<script src="jquery-ui-1.8.15.custom.min.js"></script>
<script>
jQuery(function($) {
  $(".time_element").timepicki();
  $("#datepicker, #datepicker1" ).datepicker();
});
</script>

Other changes I'd probably make:

*

*Give #datepicker and #datepicker1 a common class rather than ids (as with your .time_element).

*Combine the CSS into a single, minified file.

*Combine the JS into a single, minified file (or possibly all the JS except for jQuery, and load jQuery from a CDN).


text:
Q: Is there an operator like && that ignores return status? I've discovered the following useful trick for long-running tasks on the command line:
do_some_task && make_a_noise

For instance, on OSX:
do_some_task && say 'done'

However, && means "run the next command if the previous one returned 0 for success". If the first command fails, the second doesn't execute.
Is there a similar operator that means "do this regardless of the previous command's return status"?

A: Yes, the ;:
do_some_task ; say 'done'


text:
Q: Powershell: Fetching data from text file
Hi Everyone,
I am trying to get the list of approver for each group. Below code is an example of some coding I am trying to do.
Expected Output

Any clues how to do it?
Thank you
$file = 'textfile.txt'
$groups

foreach($line in Get-Content $file){

$Lines = Get-Content $file
$Output =

For( $i = 0; $i -lt $Lines.Length; ++$i)
{
    If($Line.StartsWith("# APPROVER:"))
    {
        $Lines[$i]
        # Need to ignore lines in between
        :LookForGroup Do
        {
            ++$i
            If( $Lines[$i].StartsWith($groups))
            {
                $Lines[$i]
                ""
                Break LookForGroup
            }
        } While($true)
    }
}
}
$Output

A: It looks like you're splitting and replacing it to get the file content into individual lines.  However, Get-Content does that by default.  Moreover, in your code $line & $content would have the same values.
I'm giving this a shot but I think what you are trying to do is look forward through an array of lines to find the group name that may come at some arbitrary point after you spot the "approver".
I manually typed out a file as a pretty good match to what you demonstrated in the revised question.  Came up with the below.  Again this is off the top of my head, but it seems to work as you dictated above.
Note: I added the $Groups array just to simulate what you said in your last comment.
$File = 'C:\Temp\InputTest.txt'
$Groups = @( 'Group1','Group2','Group3','Group4','Group5' )

$Lines = Get-Content $File
$Output =
For( $i = 0; $i -lt $Lines.Length; ++$i )
{
    If( $Lines[$i] -match '^# approver' )
    {
        $Approver = $Lines[$i].split(':').Trim()[1]
        # Need to ignore lines in between
        :LookForGroup Do
        {
            ++$i
            ForEach ( $Group in $Groups )
            {
                If( $Lines[$i] -match "^$Group" )
                {
                    $Approver + ' ' + $Lines[$i]
                    ++$i
                }
                ElseIf( $Lines[$i]  -match "(^$|\r\n|^######)")
                {# Looking for a signal to move on...
                    Remove-Variable Approver #Maybe don't need this???
                    Break LookForGroup
                }
            }
        } While($true)
    }
}
#This will display the output, you can do something else with it...
$Output

What I'm doing is using $i kind of like a cursor.  Once an approver line is spotted I go through each group to see if the line matches the group name.If yes I output the approver and the group name as you specified.  I then increment $i thus moving one line forward in the file.  If the line doesn't match the group I check for some characteristics to see if we've reached the end of a section (as defined by your example).  If yes I'll break the Do loop which will cause the For loop to continue, note: that $i will remain as we set it...
I admit this is a little kludge let me know...


text:
Q: applicability of mutli threading to a specific scenario in a java program I am confused about the applicability of multi threading in general...
I am creating an application which executes some code which has been saved in xml format. The work is to use apache http client and retrieve some data from websites...More than 1 website can be visited by one block of code in xml...
Now I want that if 2 users have created their own respective codes and saved them in XML, then each user's 'job' (ie block of code in xml format) runs in a separate thread.
I have with me code to execute one user's code...Now I want that multiple persons' code can be run in parallel. But I have some doubts--
(1) The Apache HTTP client provides a way of multithreaded communication, currently I am simply using the default HTTP client- this same client can be made to visit multiple websites, one after the other- as per code block in xml. Am I correct in thinking that I do not need to change my code so that it uses the recommended multithreaded communication?
(2) I am thinking of creating a servlet that when invoked, executes one block of xml code. So to execute 2 blocks of code as given by 2 different users, I will have to invoke this servlet twice. I am going to deploy this application using Amazon Elastic Beanstalk, so what I am confused about is, do I need to use multi threading at all in my program? Can I not simply invoke the existing code (which is used to execute one block of code at a time) from the servlet? And I do want to keep processing of the different blocks of XML code separate from each other, so I dont think I should use multi threading here.. Am I correct in my assumption?

A: Since you are going to use a servlet container then it's going to manage multithreading for you. Every servlet request will be executed in a different thread. In that scenario one servlet call would execute on block of code from provided XML in a single threaded manner. If there are several sites declared per block of code they would be visited serially. Other user in the same time may call the same server with other block of code running in parallel with the first one.

A: Running it one after the other as per your 1st option will not be considered 'concurrent' .
Coming to the servlet method , the way you describe it will work concurrently , but you also need to think about how many users concurrently ? Since for each user , there would be a separate request , there would be some network latency involved for multiple calls. You need to think about all these factors before going ahead with this option
Since you have the code for one user's job , you can define a thread class which has userid as an attribute. In the run() method call the code for a particular user's job.
Now create two threads and set the appropriate userid for each thread and spawn them off.
If the number of users are more , you can look at using Java's Thread Pool Executor .


text:
Q: How to test if a class attribute is an instance method In Python I need to efficiently and generically test whether an attribute of a class is an instance method. The inputs to the call would be the name of the attribute being checked (a string) and an object.
hasattr returns true regardless of whether the attribute is an instance method or not.
Any suggestions?

For example:
class Test(object):
    testdata = 123

    def testmethod(self):
        pass

test = Test()
print ismethod(test, 'testdata') # Should return false
print ismethod(test, 'testmethod') # Should return true

A: You can use the inspect module:
class A(object):
    def method_name(self):
        pass

import inspect

print inspect.ismethod(getattr(A, 'method_name')) # prints True
a = A()
print inspect.ismethod(getattr(a, 'method_name')) # prints True

A: import types

print isinstance(getattr(your_object, "your_attribute"), types.MethodType)

A: This function checks if the attribute exists and then checks if the attribute is a method using the inspect module.
import inspect

def ismethod(obj, name):
    if hasattr(obj, name):
        if inspect.ismethod(getattr(obj, name)):
            return True
    return False

class Foo:
    x = 0
    def bar(self):
        pass

foo = Foo()
print ismethod(foo, "spam")
print ismethod(foo, "x")
print ismethod(foo, "bar")

A: def hasmethod(obj, name):
    return hasattr(obj, name) and type(getattr(obj, name)) == types.MethodType

A: Be aware that @classmethod-decorated functions will pass all the tests in other answers. Do you want these to be considered 'instance methods'? Maybe it's just semantics, but they by definition operate on the class, not the spawned instance. I am not sure about the cases where hasmethod2 (my proposed solution) fails, but at least it can be wary of class methods:

import inspect
import types

def hasmethod(obj, name):
    return hasattr(obj, name) and type(getattr(obj, name)) == types.MethodType

def hasmethod2(obj, name):
    try:
        attr = getattr(obj, name)
        return not inspect.isclass(attr.__self__)
    except AttributeError:
        return False

class Test(object):
    testdata = 123

    def testmethod(self):
        pass

    @classmethod
    def testmethod2(cls):
        pass

# Returns True. This may be undesired depending on your definition of 'instance method'
hasmethod(Test(), 'testmethod2')

# Returns False
hasmethod2(Test(), 'testmethod2')

It works because __self__ is bound to the primary calling argument (class instance for classmethod, object instance for normal attributes, module or nothing for various built-ins). Thus, checking for the existence of __self__ and that __self__ is not a class rules out non-function attributes and classmethods, respectively.


text:
Q: Long Press button in react this is probably really simple but anyone know how to make a long press button in react. Like a button where if you press and hold for 2 seconds it is "clicked", otherwise it is not. Is there a react mouse event for this? Maybe I use onMouseDown event in some clever way?

A: One of the hack you can try is that you note the time when 'onMouseDown' event is fired and also note the time when 'onMouseUp' is fired.
If the difference between these times is greater than equal to 2 seconds, you can perform the action you want.
You must write logic to check the time difference and the code you want to execute, in method which will get executed when 'onMouseUp' event is fired.
delay = 2000;
startPress = null;

function mouseDown() {
    startPress = Date.now();
}

function mouseUp() {
    if(Date.now() - startPress > delay)
    {
        // your code
    }
}

A: I used the following to create a button that dynamically changes class while you hold down the button. The use of setInterval instead of setTimeout simplifies the operation, since we manage the end-count ourselves. We don't do any type of DateTime calculations, and we can actively monitor the current delay milliseconds by watching currentCount.
I'm using DaisyUI as my component framework, but any CSS classes could be used.
import { useCallback, useEffect, useRef, useState } from 'react';

export type LongPressButtonProps = {
  /** Text that will appear within the button */
  buttonText: string;
  /** Function to run once delay has been exceeded */
  onExecute: () => void;
  /** How long should be button be held before firing onExecute */
  delayMs: number;
  /** How frequently should the count be updated */
  refreshMs: number;
};

const LongPressButton = ({
  delayMs,
  onExecute,
  buttonText,
  refreshMs = 100,
}: LongPressButtonProps) => {
  const [mouseDown, setMouseDown] = useState(false);
  const [currentCount, setCurrentCount] = useState(0);
  const intervalRef = useRef<NodeJS.Timer>();
  const [buttonClass, setButtonClass] = useState('btn-primary');

  const onInterval = useCallback(() => {
    setCurrentCount((c) => c + refreshMs);
  }, [setCurrentCount, refreshMs]);

  useEffect(() => {
    if (mouseDown) intervalRef.current = setInterval(onInterval, refreshMs);

    if (!mouseDown && intervalRef.current) {
      clearInterval(intervalRef.current);
      setCurrentCount(0);
      setButtonClass(`btn-primary`);
    }
  }, [onInterval, delayMs, mouseDown, refreshMs]);

  useEffect(() => {
    if (currentCount > 0) setButtonClass(`btn-error`);
    if (currentCount > delayMs) {
      onExecute();
      setCurrentCount(0);
    }
  }, [currentCount, delayMs, onExecute]);

  return (
    <button
      className={`btn ${buttonClass}`}
      onMouseDown={() => setMouseDown(true)}
      onMouseUp={() => setMouseDown(false)}
      onMouseLeave={() => setMouseDown(false)}
      onTouchStart={() => setMouseDown(true)}
      onTouchEnd={() => setMouseDown(false)}
      style={{ transition: `${delayMs}ms` }}
    >
      {buttonText}
    </button>
  );
};

export default LongPressButton;


text:
Q: Apple devices browser no scrolling after using back-button I have some weird behaviour on the iPad 2 and iPhone 6 running iOS 9.3.1.
On my site there is a <div>, positioned relative with a fixed height, calculated by javascript on window.load() (jQuery).
In this div there's my scrollable content.
The site is running on Joomla 3.5 and I used a category to display some images as thumbnails for galleries.
On a normal site load there's no problem, clicking through works just fine an scrolling is working.
But after entering a gallery and pushing the browsers back-button (safari / chrome is behaving the same) the content in not scrollable anymore.
After changing the device orientation, selecting another site from the menu or reloading the scrolling works fine again.
On all other devices (Windows / Android) I have no problems at all.
JS code (shortened - it's all of my code that effects the specific div):
$(window).on('load', function () {
    wheight = $(window).outerHeight();
    innerWrap.css(
      'max-height',
      wheight - $('#wrapper').height() - $('footer').height() - 67 + "px"
    );
});

I already searched the web for iOS scrolling bugs but none of the fixes seemed to work for me.
Any suggestions?

A: I found a solution.
After finding that my javascript was not executed on .load when going back I searched specifically for this execution problem.
The problem was the internal cache of the system that is used to quickly display websites when going 'back' with the browser.
A little javascript snippet saved me:
jQuery(window).bind("pageshow", function(event) {
    if (event.originalEvent.persisted) {
       window.location.reload();
    }
});

After adding this the page does a true reload and renders normally, with working scrolling!


text:
Q: How do I calculate the standard deviation of an arbitrary distribution in r? x    Px
134  .5
565  .25
65   .125
563  .125

Suppose the above is the data.frame.
Is there a function that I can input it into to compute the standard deviation?

A: You could calculate the SD analytically (more info):

Or numerically:
samp = sample(x = x, n = 1e6, replace = TRUE, prob = Px)
sd(samp)

A: You could use sd function from the stats package (https://www.rdocumentation.org/packages/stats/versions/3.6.2/topics/sd).
Something like this:
result = sd(your_data_frame$Px)

A: 1) lm Assuming input P shown in the Note at the end, we can use lm
fm <- lm(x ~ 1, P, weight = Px)
sqrt(deviance(fm))
## [1] 216.1202

or we can replace the last line with:
sqrt(nobs(fm) - 1) * sigma(fm)
## [1] 216.1202

2) direct or do it directly:
m <- with(P, sum(x * Px))
with(P, sqrt(sum((x - m)^2 * Px)))
## [1] 216.1202

or
with(P, sqrt(sum(x^2*Px)-sum(x*Px)^2))
## [1] 216.1202

3) In the particular example in the question, if we multiply the probabilities by 8 the results are all integer so if we repeat each item that number of times we can simply take the standard deviation of those numbers using sd except that sd gives the sample standard deviation so we need to correct that to give the population standard deviation.
xx <- with(P, rep(x, 8 * Px))
n <- length(xx)
with(P, sqrt((n-1)/n) * sd(xx))
## [1] 216.1202

Note
The input data frame in reproducible form is assumed to be:
Lines <- "x    Px
134  .5
565  .25
65   .125
563  .125"
P <- read.table(text = Lines, header = TRUE)


text:
Q: Can't find sdk\lib\library.lib This particular issue is caused by specifying a dependency to a lib file that had spaces in its path. The path needs to be surrounded by quotes for the project to compile correctly.
On the Configuration Properties -> Linker -> Input tab of the project's properties, there is an Additional Dependencies property. This issue was fixed by changing this property from:
C:\Program Files\sofware sdk\lib\library.lib

to:
" C:\Program Files\sofware sdk\lib\library.lib"

but after compiling, it says:

Error  1   fatal error LNK1104: cannot open file 'sdk\lib\library.lib'

How can I resolve this?

A: Try adding the path to your linker path and just the 'library.lib' name to your libs.


text:
Q: WSO2 API Manager 2.0.0: Enabling XACML mediator I am trying to follow the documentation Enabling Role-Based Access Control Using XACML for WSO2 API Manager 2.0.0.
But adding the features described failed,
complaining: the XACML feature 5.0.7 cannot be installed since 5.2.0 is already installed (although not visible under "installed features"). Adding XACML Mediation fails due to missing dependencies.
Anyone got this working and can share some insight?

A: Looks like the features in the new p2 repository has conflicts with existing ones. Basically, it's a bug. I reported this here in WSO2 APIM JIRA.
As a workaround, if you only need role based authorization, you can use oAuth2 scope based authorization.


text:
Q: increasing sample size while keeping sample features I am trying to generate a collection of 173056 samples following the distribution in the picture,
but the following image was obtained plotting 6120 samples.
Is there a way to keep this distribution while increasing the sample size?

A: Taking the problem reverse way, 173056 is about the number of temperature measures you make in a year if you do a mesure each 3 minutes.
And what you have is 6120 points, that is a point each 90 minutes. The best thing you can do is probably a linear  interpolation.
A (very simplified) model of temperature:
Ta=6120
Tj=Ta/365
Tp=20-10*cos(2*pi/Ta*tp)-10*cos(2*pi/Tj*tp)

tp=arange(6120)
Tp=20-10*cos(2*pi/Ta*tp)-10*cos(2*pi/Tj*tp)

and the interpolation:
t=numpy.linspace(0,6120-1,173056)
T=numpy.interp(t,tp,Tp)

Zoom :
plot(tp[:4],Tp[:4],'ro',t[:90],T[:90],'b+')


text:
Q: Why can't I modify the response of this post request via jQuery? So I have a login form, that when submitted will redirect to the homepage /.
I would like the form to have the same behaviour except that when I receive the response back from the server, which comes in the form of HTML data, I can modify that HTML data so that after the redirect occurs, the homepage will show the modified HTML:
$(#login-form).submit(function(event) {
  event.preventDefault();
  var $form = $(this);
  var user = $("#username").val();
  var passwd = $("#password").val();
  var url = $form.attr("action");
  var posting = $.post(url, { username: user, password: passwd });
  posting.done(function(data) {
    $(data).find("#logged-user").text("user777");
    $('html').html(data);
  });
});

In the above snippet of code, when say user111 logs in, then there's a span tag  that displays the name of the logged in user.
However, when I try to manipulate this span tag so it shows the name of a different user via $(data).find("#logged-user").text("user777"); it doesn't work. Why?

A: Try this:
posting.done(function(data) {
  var tmp = $('
' + data + '
');   // Create a temporary DOM
  tmp.find("#logged-user").text("user777"); // Modify it
  $('html').html( tmp.html() );             // Get its HTML, and use it
});

or simply:
posting.done(function(data) {
  $('html').html(data);
  $("#logged-user").text("user777");
});


text:
Q: Projection out of orthogonal matrices
Let A,B be orthogonal matrices of order $n \geq 2 $. $\det A = 1, \det
 B = -1$.
There exist $a \in [0,1]$ such that  $aA + (1-a)B$ is projection.

I know that the claim above is false. I fail to come up with a counterexample, so I decided to use $PP = P$ property of projection with hope to run into some contradiction.
$$a^2A^2 + a(1-a)(AB + BA) + (1-a)^2B^2 = aA + (1-a)B$$
And here I stuck. Could you help me: how can I utilize the fact that A,B are orthogonal.

A: The claim is not necessarily false if $P$ was allowed to be an orthogonal projection. For a trivial example, take $A=I$  and $a=1$. The identity matrix is certainly a projection.
The claim is, however, false if $P$ is assumed to be a "strictly" nonorthogonal projection. We know that a projection $P$ is nonorthogonal if and only if $\|P\|_2>1$, see, e.g., here. However, for any $x$,
$$
\|[aA+(1-a)]x\|_2\leq a\|Ax\|_2+(1-a)\|Bx\|_2=a\|x\|_2+(1-a)\|x\|_2=\|x\|_2,
$$
which implies that $\|aA+(1-a)B\|_2\leq 1$.


text:
Q: How to change dependency versions accepted in package I have an expo project using rn-pdf-reader-js with what is below (in package-lock.json)
"node_modules/rn-pdf-reader-js": {
  "version": "4.1.1",
  "resolved": "https://registry.npmjs.org/rn-pdf-reader-js/-/rn-pdf-reader-js-4.1.1.tgz",
  "integrity": "sha512-KnBzB1wfHPdE/Qb6oMmX0/iAD60tp+kf0TZaHw6tb0ULrdSvaG5rspTJArUEA724qYFwuVG1U2B0WTK8inpe1Q==",
  "dependencies": {
    "buffer": "5.1.0",
    "csstype": "2.6.8",
    "js-base64": "2.4.5"
  },
  "peerDependencies": {
    "expo": ">= 33.0.x < 37.0.x",
    "expo-constants": ">= 5.0.0 < 9.x",
    "expo-file-system": ">= 5.0.0 < 9.x",
    "react": "16.x",
    "react-native": "*",
    "react-native-webview": ">= 7.0.5 < 8.x"
  }
},

However I am using expo version 47.0.9
So, I was wondering if I can just edit the peerDependencies for rn-pdf-reader-js to be "expo": ">= 33.0.x < 50.0.x" instead of "expo": ">= 33.0.x < 37.0.x"
I ask because everytime I would install any other dependency I would get an error saying rn-pdf-reader-js is not compatible and then I would have to install with --legacy-peer-deps. This works fine in the expo-go app (the app runs normally) and although the package rn-pdf-reader-js is supposedly outdated I don't see any issues.
However now I cannot build my project because that runs npm install which throws the error
Cannot read properties of null (reading 'children')

Is this the correct approach to fixing the issue and not having to use --legacy-peer-deps for everything?


text:
Q: Laravel - Validator::make fails my unique rule I'm trying to use a validation on 'name' as unique, but to be ignored if the objected that has that same name is the same object being updated.
The Validation keeps failing, can you help me figuring out why?
Validator Function - I'm using same validator function to both create and update and only need to apply the rule on the update.
protected function validator(array $data, Wharehouse $wharehouse = null)
    {
        //different validations for create and edit
        if($wharehouse != null){
            return Validator::make($data, [
                'name' => ['required', 'string', 'max:255', Rule::unique('wharehouses')->ignore($wharehouse)],
                'espacoTotal' => ['required', 'numeric', 'max:60000']
            ]);
        }else{
            return Validator::make($data, [
                'name' => ['required', 'string', 'max:255', Rule::unique('wharehouses')],
                'espacoTotal' => ['required', 'numeric', 'max:60000']
            ]);
        }
    }

Validation Call
protected function editById(Request $request)
    {

        $wharehouse = Wharehouse::find($request->wharehouse_id);

        $validation = $this->validator($request->all(),$wharehouse);

        if ($validation->fails()) {
            return Redirect::to('/wharehouses')->withInput()->withErrors($validation);
        } else {
            $wharehouse->name = $request->input('name');
            $wharehouse->espacoTotal = $request->input('espaco');
            $wharehouse->save();
            return back()->with('create.success','Armazem actualizado com sucesso.');
        }
    }

A: Append the id of the instance currently being updated to the validator.

*

*Pass the id of your instance to ignore the unique validator.

*In the validator, use a parameter to detect if you are updating or
creating the resource.

If updating, force the unique rule to ignore a given id: unique:table,column,except,idColumn
//rules
'name' => ['required', 'string', 'max:255', 'unique:users,name,' . $userId],


text:
Q: Automated Export Failed As admin for an Azure subscription I am getting emails reporting:

Automated SQL Export failed for {server:database} at 9/5/2013 12:00:11
  AM. The temporary database copy to export from could not be made.

I deleted this server, without explicitly removing the automated export configuration.
First question: how do I tell Azure to stop trying to do the export?
Second question: newbie mistake (if so please let me know what I failed to do) or bug?
Thanks!

A: I believe that this might be because the schema of the database has changed, which has resulted in an object (stored procedure, view, function) becoming invalid.
This problem / solution is elaborated on in another question:
Automated azure sql export fails


text:
Q: Hide menu by clicking outside a div or a on mouseout after a certain amount of time? On a web page there are menus and on hovering it sub menus open.All menu and sub menus are made using div and sub menus are hiding using style.display = none;
The problem is once subMenu is opened it does not hide even on mouse-out. It remains open no matter user has clicked somewhere else on the page.
I want to know how can I implement some functionality so that after some time it automatically get disappear or on clicking on rest of the area on page it disappears?
Note: mouseout is not working properly.

A: For how can I implement some functionality so that after some time it automatically get disappear use setTimeout.
var canceled;

$("mymenu").on("focusout", function() {
    canceled = false;
    setTimeout(function() {
        if (!canceled) {
            // Hide menu
        }
    }, 2000);
});

$("mymenu").on("focusout", function() {
    canceled = true;
});

For or on clicking on rest of the area on page it disappears. you should bind a click event directly on the document root:
$(document).on("click", function() {
    // hide menu if visible
});


text:
Q: Un mismo sitio web con diferentes detalles Tengo la siguiente situacion y me gustaria pedirles sus consejos y ver de que manera puedo solicionar esto.
Ya tengo un sitio web creado, en el ingresan los usuarios sin problema, la consulta es como puedo hacer para que cada usuarios tenga partes o diseños diferentes en el mismo sitio, por ejemplo si Juan y Luis son usuarios, como hago para que Juan tenga una opción mas en el menú o que Luis tenga diferentes colores en la página,
Como se podria hacer algo asi ?
Gracias por la ayuda
ACTUALIZACION
Muchas gracias a todos por sus respuestas y comentarios, me parece que la opción de roles puede ser que no se acople muy bien aca, hice este imagen para aclarar mas la consulta, el punto es que todo usuario ve el sitio web completo de igual forma (digamos 10 paginas), ahora, cada usuario por separado puede ver o tener acceso a paginas que haya soliciatod crear para el, en la siguiente imagen LUIS va a ver todo el sitio web mas las páginas de Mapa, Video y Tablas que el solicitó crear para el, en su caso JUAN va a poder ver todo el sitio web mas la página de Galeria y la de Graficos que el pidio crear para el, ese es el punto de la consulta, espero que con esto se aclare mas la consulta, gracias