text:
Q: JSON schema - conditionally apply a $ref to a value based on the other value? I am wanting to conditionally validate against a $ref based on another value in my schema.
items: {
    type: 'object',
    properties: {
      kind: { type: 'string', enum: ['foo', 'bar'] },
      //parameters: { $ref: 'foo.json#' } // This works
      parameters: {
        if: {
          kind: 'foo'
        },
        then: {
          $ref: 'foo.json#'
        }
      }
      // also tried
      if: {
        kind: 'foo'
      },
      then: {
        parameters: { $ref: 'foo.json#' }
      }

I would like parameters to be validated against the foo.json reference whenever the value of kind is equal to foo (same with bar and bar.json). However the above is not working. Uncommenting out the commented section works so they are not equivalent.
How can I format this to conditionally apply a $ref to a value based on the other value?
I actually have about 10 different values for the type enum so if there is a cleaner way do this than if/else I am open.

A: Ah got it....
items: {
  type: 'object',
  properties: {
    kind: { type: 'string', enum: ['foo', 'bar'] }
  },
  required: ['parameters'],
  if: {
    properties: { kind: { const: 'foo' } },
    required: ['kind']
  },
  then: {
    properties: {
      parameters: {
        $ref: 'fpp.json#'
      }
    }
  }

It's helpful for me to think that whatever is in if and else are essentially merged with the main schema.


text:
Q: smbus access in pcie under windows I'm looking for a way to control smbus line in PCIe slot of my PC. There's some device connected via PCIe in that slot. And I wanna access it via the SMBus line under Windows. But cannot find any API to use for that.
Can you suggest me how to do that please?

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to go back to previous activity with closing current activity in android? How can i go back to previous activity(List) with closing current activity(Save) in android
I tried the below code
public  void  cancel() {
   Intent intent = new Intent(Save.this, List.class );
   startActivityForResult(intent, TIME_ENTRY_REQUEST_CODE);
}

but while running unfortunately my app is stopped.. can any one help me?

A: try
public void cancel() {
  finish();
}

A: If you are using startActivityForResult to start a activity , then you can use
   finishActivity() to finish the activity and go back to the previous activity.
   To give you better understanding , i am adding  the following stack overflow link.
Android:Go back to previous activity
Code
public void gobacktoprious()
{
finishActivity();
}

A: Try this it handles when user clicks back key
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if ((keyCode == KeyEvent.KEYCODE_BACK))
    {
        finish();
    }
    return super.onKeyDown(keyCode, event);
}

}


text:
Q: Using ftp_fget using SFTP / phpseclib I'm currently having a horrible time with SFTP.
Is there a way to use ftp_fget using SFTP?
I'm using the phpseclibrary, but it only offers their own implementation of $sftp->get() howver I would like $sftp->fget();

A: In the latest Git version (ie. later than 0.3.7), instead of $sftp->fget(), you can do something like this:
$fp = fopen('filename.ext', 'w');
$sftp->get('file_to_download.ext', $fp);
fclose($fp);

You could also alternatively use Net/SFTP/Stream.php . eg.
$resFile = fopen("sftp://{$resSFTP}/".$filename, 'w');
$srcFile = fopen("/home/myusername/".$filename, 'r');
$writtenBytes = stream_copy_to_stream($srcFile, $resFile);
fclose($resFile);
fclose($srcFile);


text:
Q: How to do turn off vibration in Ionic 2 app I have tried using plugin @ionic-native/vibration and tried three ways
   navigator.vibrate(0);
   (<any>window).vibration.vibrate(0);

And
   import { Vibration } from '@ionic-native/vibration';
     constructor(private vibration: Vibration){
       this.vibration.vibrate(0);
   }

also added to app module
but its not working, Is there any other way to do setting vibration to 0 or turn off vibrations.

A: To my knowledge there's currently no way to completely turn off vibrations that would be sent by some other component than your App.
However, there might be a trick to disable some vibrations given certain circumstances, using vibrate(0) as you did. The documentation on vibrate reads

[...] Pass 0 to stop any vibration immediately.

So you can't completely shut down incoming vibrations, but you can cancel any current vibration. So if for example you want to cancel the vibration of a notification you send, you can call vibrate(0) just as it arrives.
It is a poor workaround as you'll probably need to call it multiple times to cancel the vibration (to be sure you call this after the vibration started), but I think it's the only solution approaching what you're trying to achieve using only Ionic.
Or you could also periodically and very often call vibrate(0) to cancel any incoming vibration but it would not recommand this because to be effective the delay would have to be super short, which is probably a bad idea for performance reasons. I'm merely saying this as an emergency solution.


text:
Q: How to download, use and keep updated PHP, Apache, MySQL on a machine running on Windows 10 Home operating system? I'm a PHP developer by profession. Till now I was working on Ubuntu Linux 14.04 LTS 64-bit operating system and LAMP stack.
Yesterday I bought a new Lenovo laptop pre-installed with Windows 10 Home Single Language operating system.
Then to start development using PHP and MySQL I installed Wampserver (64 bits & PHP 5.6.15 & PHP 7) 3 on my new machine.
After installation I'm facing so many problems in running PHP and PHPMyAdmin without error. Also it's showing me PHP Version 5.6.16 installed which is actually a old one.
Actually, I want to install the latest stable versions of following softwares before starting my PHP development :

*

*PHP Version 7.0.6

*Apache httpd 2.4.20

*MySQL Version 5.7.12

*PHPMyAdmin Version 4.6.1

And also whenever any new stable version for any of the above softwares become available I should be able to upgrade the same software to it like I used to do on my Ubuntu machine by running regular system update.
Can someone please suggest me a way to achieve it without any hassle and trouble? So that I can concentrate more on web development rather than doing configuration settings.
Thanks.

A: There are MANY ADDONS available for WAMPServer 3
They are all on SourceForge
Or they can be downloaded from links on the WAMPServer forum
Or the alternate download site (often a few days ahead of SourceForge)
Remember that with WAMPServer you can switch between any installed version of Apache/PHP/MYSQL with a simple click of a menu item.
The latest version of WAMPServer is currently V3.0.4 and comes with
Apache2.4.18
MYSQL5.7.11
PHP7.6.19 & 7.0.4

ADDON for PHP7.0.6 is also there ready for download and install
ADDON for Apache2.4.20 is also there ready for download and install
ADDON for MYSQL5.7.12 is also there ready for download and install
ADDON for PHPMyAdmin Version 4.6.1 is also there ready for download and install
There have been a few odd hiccups with phpMyAdmin lately so there is also an ADDON for a tool called Adminer4.2.4 available also
MYSQL Workbench is also a great tool for messing with MYSQL, but if you install that be careful to only install the Workbench and not another MYSQL Server as well.

What more could you possibly want

A: Try XAMPP , pick the version you want
https://www.apachefriends.org/download.html
XAMPP is an easy to install Apache distribution containing MariaDB, PHP, and Perl. Just download and start the installer. It's that easy.


text:
Q: Python get arguments from string I wanted to grab a argument from a string in python...
I wanted to grab the city of this string: weather in <city>
How do I get the city? Into a new variable?

A: Use Regular Expressions!
If you haven't heard of them, it's quite simple. Simply import the re module, and away you go!
>>> import re

Ok, maybe that wasn't so exciting. But now you can use pattern matching. Simply define your pattern:
>>> pattern = r"^(?P<thing>.*?) in (?P<city>.*?)$"

and away you go!
>>> re.match(pattern, "weather in my city")
<_sre.SRE_Match object; span=(0, 18), match='weather in my city'>

Don't worry! This is actually something useful. Let's store this in a variable so we can use it:
>>> match = re.match(pattern, "weather in my city")
>>> match.group("city")
'my city'

Hooray!
Now, what was that crazy pattern thing about? It worked, but it just seems like magic. Let me explain:

*

*r"" just makes Python treat (most) \s as literal \s. So, r"\n" will be an actual \ followed by an actual n, as opposed to a new-line character. This is because regular expressions have special meanings for \ characters, and it's awkward to have to write \\ all the time.

*^ means "start of the string".

*(?P<name>...) is a named group. Normal groups are represented by (...), and can be referenced by their number (e.g. match.group(0)). Named groups can also be referenced by number, but they can also be referenced by their name. The P stands for Python, because that's where the syntax originally came from. Neat!

*. means "any character".

** means "repeated 0 or more times".

*? means a few things, but when it's after a * or + it means "match as little as possible". This means that it will make the thing group have as few "any character"s as possible.

*in means exactly what it looks like. A  followed by an i followed by a n followed by a .

*.*? again means "match as few of any character as possible", but... I'm not really sure why I wrote that, considering that

*$ means "end of the string".

And yeah, they never really stop seeming like magic. (Unless you use Perl.) If you want to make your own regular expression or learn some more, have a look at the documentation for the re module.

A: If you have constant spaces in your string and your strings are not going to change, it's relatively easy. Just use split on your string.
x = "weather in <city>"
split_x = x.split(" ")
# will return you
["weather", "in", "<city>"]
city = split_x[2]

Look at split's docs. But suppose your city is something like "New York", then you'll have to look for some alternative because in that case, the list will be -
x = "weather in New York"
# O/P
["weather", "in", "New", "York"]

And then if you do this-
city = split_x[2]

You will have wrong city name

A: With str.lstrip():
s = "weather in Las Vegas"

city_name = s.lstrip('weather in ')
print(city_name)

Prints:
Las Vegas


text:
Q: Atmega328 datasheet recommending against toggling pins in an interrupt I'm making a motor driver that has too many PWM outputs to use hardware PWM, so my intent was to generate waveforms with a "tickless" timer scheme, as follows:
scheduled restack:
   for i in (pwm channels)
      stack in ascending order all pwm channels
   set OCR0A = lowest PWM channel

OC0A ISR:
   toggle GPIO of lowest PWM channel
   pop next PWM channel off stack
   set OCR0A = next lowest PWM channel
   if list is empty
       schedule a restack

This is, at most, 10 or so instructions in the ISR. At 16khz TCNT, this is worst case 16khz interrupts (255 PWM channels each spaced by one count), and usual case, probably around 500Hz, which I think this microcrontroller should have no issues handling. However, from the datasheet:

The output compare unit can be used to generate interrupts at some given time. Using the output compare to generate
waveforms in normal mode is not recommended, since this will occupy too much of the CPU time.

Is the proposed solution bad practice? From a purely CPU usage perspective, it seems totally within limits, despite what the datasheet says.


text:
Q: Oculus Rift Multiplayer We are working on a VR collaboration app where user imports CAD files at run time. Then different users perform operations on it together. We are using Unity.
The challenges:
1. CAD files are very large.
2. Our app has desktop as well as Oculus Rift mode.
Which multiplayer approach should we follow? I heard that OculusPlatform sdk has support for generic networking also. Should we go for it, or rather choose from UNet and Photon?
Any suggestion will be greatly appreciated.


text:
Q: Jmeter script doesn't work with Jenkins I am running my jemeter script with jenkins but it throws below error:-
C:\Program Files (x86)\Jenkins\workspace\Jmeter>H:\D\Jmeter\apache-jmeter-3.0\apache-jmeter-3.0\bin\jmeter.bat
Writing log file to: C:\Program Files (x86)\Jenkins\workspace\Jmeter\jmeter.log

Uncaught Exception java.lang.ExceptionInInitializerError. See log file for details.
Uncaught Exception java.lang.NoClassDefFoundError: Could not initialize class org.apache.jmeter.gui.util.MenuFactory.

My Jenkis configuration:-
H:\D\Jmeter\apache-jmeter-3.0\apache-jmeter-3.0\bin\jmeter.bat
-Jjmeter.save.saveservice.output_format=xml -n -t H:\D\Jmeter\apache-jmeter-3.0\apache-jmeter-3.0\bin\gmail.jmx -l TestResult.jtl

Please help!!


text:
Q: Confusion over bisecting angles of asymptotic curves For E,F,G coefficients of the First Fundamental Form, and L,M,N of the Second, how do i show the following:
For $p \in S$ a regular surface, with Gauss curvature $\kappa(p) > 0$, show that the lines of curvature through $p$ bisect the asymptotic curves through $p$.
So far I have that a line of curvature implies $$(FN-GM)(v')^2 - (GL-EN)(u'v') + (EM-FL)(u')^2 = 0$$ and that for an asymptotic curve (as normal curvature $\kappa_n = 0$) $$\kappa_n = \frac{(u')^2L + 2u'v'M + (v')^2N}{(u')^2E + 2u'v'F + (v')^2G} = 0 \implies(u')^2L + 2u'v'M + (v')^2N = 0$$
Here is where I'm confused. Could you please explain how this could show that lines of curvature bisect asymptotic curves, and your thought process when checking this?


text:
Q: How do I compile for the device without a certificate? I may just be looking in all the wrong places, but is there no way to compile a Cocoa Touch application for ARM without paying for a developer account and certificate?
EDIT: To clarify: I am trying to build for a jailbroken device. I simply want to test code on-device without paying for anything.

A: You're not going to like this answer, but I and everyone else on SO will tell you that developing for a jailbroken device is 10 times worse than developing legitimately with a developer account.  It's not really that expensive, and if you don't have a mac, a low end Mac Mini isn't all that costly either.  If you would just want to get some mobile handset practice in, might I suggest developing with Google's Android.  The SDK is free and you can get a nifty plugin for Eclipse that has a device emulator as well as a GUI builder.  The only downside is that the device support is minimal at the moment.  But hey, you can be on the bleeding edge of a technological revolution.

A: Unless you have jailbroken your iPhone/iPod Touch an Apple iPhone Developer account is required.


text:
Q: How to calculate regression with dates as x axis? Is it good practice for a polynomial regression with dates as x axis to convert the datetime values to numbers, from 1 to the len(dataframe)+1? Are the predicted values considered to be accurate?
data['numbered'] = ''
for i in range(1, len(data) + 1):
    data.loc[i - 1, ['numbered']] = i

X = data[['numbered']].values
y = data[['ozone']].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
``


text:
Q: Calling a method of an Object in a HashMap in Java I have 2 classes: truck and sedan. When some action occurs, I want to add a sedan to the hashMap in Truck class. The map tells what Sedans are currently in the Truck's cargo. I don't want Truck and Sedan to know about each other so I have made a method in CarManager that Sedan can call which passes the id of the sedan and the id of the Truck that Sedan wants to be added to. Then CarManager will inform Truck that a Sedan wants to be added to the list. The issue is I don't know how CarManager will inform the Truck and what I should have in that addSedan method. I do have a HashMap in CarManager that has a collection of CarEntities. The Truck's addCar method cannot be accessed by CarManager since it isnt in the interface and I dont want to add it in the interface because not all CarEntity will use it. Can anyone help?
public interface CarEntity {
    String getId();
    double getSpeed();
    void move();
}

public class CarManager {
    private HashMap<String, CarEntity> hash = new HashMap<String, CarEntity>();
    public void addSedan(String carId, String truckId) {
    ???
    hash.get(truckId).addCarr(carId); //I don't think this will work
    }

}

public class Truck implements CarEntity {
    private HashMap<String, CarEntity> cargo = new HashMap<String, CarEntity>();
    public void addCar(String id, CarEntity ce) {
        cargo.put(id,ce);
}

public class Sedan implements CarEntity {
    CarManager.addSedan("Car 1", "Truck 5");
}

A: If you may not use casts and instanceof and must use polymorphism, then add two methods to your CarEntity interface :
boolean canBeLoadedWithCars();
void addCar(CarEntity c) throws IllegalStateException;

The trucks can be loaded with cars, and thus implement the first methof by returning true. The other ones return false.
The addCar method of Truck adds the car to their map, whereas the other implementations throw an IllegalStateException because they can't be loaded with cars.
So the addCar method of the manager becomes
CarEntity truck = hashMap.get(truckId);
if (truck.canBeLoadedWithCars() {
    truck.addCar(sedan);
}

A: I guess one thing that you can do is
CarEntity t = hash.get(truckId);
if (t instanceof Truck)
   downcast car entity to truck
   call add car method

A: The answer depends on who is doing the action.  If the Sedans add themselves to the truck then you should have an addTruck method which adds all of the trucks into the manager.  The manager would store the Trucks in a Map.
private Map<String, Truck> trucks = new HashMap<String, Truck>();
public void registerTruck(Truck truck) {
    trucks.put(truck.getId(), truck);
}

Then the addCar() method on the manager would do:
public void addCar(String truckId, CarEntity car) {
    Truck truck = trucks.get(truckId);
    // null handling needed here
    truck.addCar(car);
}

If, instead, the trucks take the cars then you could register the cars instead.  If you need to have both be by string id then you'll need to register both cars and trucks and do something like:
private Map<String, Truck> trucks = new HashMap<String, Truck>();
private Map<String, Sedan> sedans = new HashMap<String, Sedan>();

public void registerTruck(Truck truck) {
    trucks.put(truck.getId(), truck);
}
public void registerSedan(Sedan sedan) {
    sedans.put(sedan.getId(), sedan);
}

public void addSedan(String sedanId, String truckId) {
    Sedan sedan = sedans.get(sedanId);
    Truck truck = trucks.get(truckId);
    // null handling needed here
    truck.addCar(sedan);
}

Typically we use Java interfaces to accomplish the decoupling.  The Truck class should be able to add a CarEntity to its load without knowing that it is a Sedan.  In this case an addCar(CarEntity car) method on Truck sounds fine.  The Sedan will never know it is on a Truck and all the truck knows are the methods exposed through the CarEntity interface.  In this case maybe the manager goes away.


text:
Q: How to call a web api from url in mvc4 I have created a web api with two parameters. I want to test it from url that its working or not. I have tried but not able to call. My code is.
API routing...
    public static void Register(HttpConfiguration config)
    {
        config.EnableCors();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

[HttpGet]
    public List<Library> GetLibrary(string DataType, int DataId)
    {
        List<Library> LibraryList = new List<Library>();
        if (DataType == "Course")
        {
            using (ICA.LMS.Service.Models.Entities dbCourse = new Models.Entities())
            {
                LibraryList = (from c in dbCourse.COURSELIBRARies
                               where c.LIBITEMID == DataId
                               select new Library { Id = c.LIBITEMID, Name = c.GROUPNAME, Desc = c.DESCRIPTION }).ToList();
            }
        }
        return LibraryList;
    }

Url which i am putting in browser.
http://localhost:1900/api/librarybyid/?DataType='Course'&DataId=1

Result i am getting...
<Error>
   <Message>
       No HTTP resource was found that matches the request URI     'http://localhost:1900/api/librarybyid/?DataType='Course'&DataId=1'.
   </Message>
   <MessageDetail>
      No type was found that matches the controller named 'librarybyid'.
    </MessageDetail>
</Error>


text:
Q: Deleting node in BST Python this is a possible way to implement add and delete functions for a BST in Python. It somewhat resembles my ideas of BST in C++. As evident by the code for deleting, I want to delete a node, which I cannot do due to lack of pass by reference in Python as it is present in C++. What is a good alternative way to delete a node apart from del currNode(this does not work). I have one more question to clarify my idea about pass by reference in Python, when a node is being using added using add function, it remains "attached" to the root node, when add is being called recursively. However, when a node is being deleted, it is not being "detached" from the root node. Why is this so?
class node(object):
    def __init__(self, data = None):
        self.data = data
        self.left = None
        self.right = None

class bst(object):
    def __init__(self):
        self.root = None

    def add(self, value):

        def _add(self, currNode, value):
            if value < currNode.data:
                if currNode.left == None:
                    currNode.left = node(value)
                else:
                    _add(self, currNode.left, value)

            elif value > currNode.data:
                if currNode.right == None:
                    currNode.right = node(value)
                else:
                    _add(self, currNode.right, value)

            else:
                print("Duplicate found")

        if self.root == None:
            self.root = node(value)
        else:
            _add(self, self.root, value)

    def printBST(self):
        def _printBST(self, currNode):
            if currNode!= None:
                _printBST(self, currNode.left)
                print(currNode.data, end = " ")
                _printBST(self, currNode.right)

        if self.root != None:
            _printBST(self,self.root)

    def minBST(self,currNode):
        def _minBST(self, currNode):
            if currNode.left == None:
                return currNode.data
            else: return _minBST(self, currNode.left)

        if currNode != None:
            return _minBST(self, currNode)
        else:
            return -10000

    def deleteValue(self, val):

        def deleteNode(self, currNode, value):
            if currNode == None:
                return
            elif value > currNode.data:
                return deleteNode(self, currNode.right, value)
            elif value < currNode.data:
                return deleteNode(self, currNode.left, value)
            else:
                if currNode.left == None and currNode.right == None:
                    #del currNode
                    currNode.data = None

                elif currNode.right == None:
                    currNode.data = None
                    #The address of currNode does not change
                    #as it happens in C++
                    #currNode = currNode.left

                elif currNode.left == None:
                    currNode.data = None
                    #The address of currNode does not change
                    #currNode = currNode.right

                else:
                    minV = self.minBST(currNode.right)
                    currNode.data = minV
                    return deleteNode(self, currNode.right, minV)

        deleteNode(self, self.root, val)

if __name__ == '__main__':
    b = bst()
    b.add(50)
    b.add(60)
    b.add(40)
    b.add(30)
    b.add(45)
    b.add(55)
    b.add(100)
    b.printBST()
    b.deleteValue(100)
    print("")
    b.printBST()

A: node structure and insertion
We start with a simple node structure, but notice the left and right properties can be set at the time of construction -
# btree.py

class node:
  def __init__(self, data, left=None, right=None):
    self.data = data
    self.left = left
    self.right = right

Recursion is a functional heritage and so using it with functional style yields the best results. This means avoiding things like mutation, variable reassignment, and other side effects. Notice how add always constructs a new node rather than mutating an old one. This is the reason we designed node to accept all properties at time of construction -
# btree.py (continued)

def add(t, q):
  if not t:
    return node(q)
  elif q < t.data:
    return node(t.data, add(t.left, q), t.right)
  elif q > t.data:
    return node(t.data, t.left, add(t.right, q))
  else:
    return node(q, t.left, t.right)

inorder traversal and string conversion
After we add some nodes, we need a way to visualize the tree. Below we write an inorder traversal and a to_str function -
# btree.py (continued)

def inorder(t):
  if not t: return
  yield from inorder(t.left)
  yield t.data
  yield from inorder(t.right)

def to_str(t):
  return "->".join(map(str,inorder(t)))

btree object interface
Notice we did not over-complicate our plain functions above by entangling them with a class. We can now define a btree object-oriented interface which simply wraps the plain functions -
# btree.py (continued)

class btree:
  def __init__(self, t=None): self.t = t
  def __str__(self): return to_str(self.t)
  def add(self, q): return btree(add(self.t, q))
  def inorder(self): return inorder(self.t)

Notice we also wrote btree.py as its own module. This defines a barrier of abstraction and allows us to expand, modify, and reuse features without tangling them with other areas of your program. Let's see how our tree works so far -
# main.py

from btree import btree

t = btree().add(50).add(60).add(40).add(30).add(45).add(55).add(100)

print(str(t))
# 30->40->45->50->55->60->100

minimum and maximum
We'll continue working like this, defining plain function that work directly on node objects. Next up, minimum and maximum -
# btree.py (continued)

from math import inf

def minimum(t, r=inf):
  if not t:
    return r
  elif t.data < r:
    return min(minimum(t.left, t.data), minimum(t.right, t.data))
  else:
    return min(minimum(t.left, r), minimum(t.right, r))

def maximum(t, r=-inf):
  if not t:
    return r
  elif t.data > r:
    return max(maximum(t.left, t.data), maximum(t.right, t.data))
  else:
    return max(maximum(t.left, r), maximum(t.right, r))

The btree interface provides only a wrapper of our plain functions -
# btree.py (continued)

class btree:
  def __init__():       # ...
  def __str__():        # ...
  def add():            # ...
  def inorder():        # ...
  def maximum(self): return maximum(self.t)
  def minimum(self): return minimum(self.t)

We can test minimum and maximum now -
# main.py

from btree import btree

t = btree().add(50).add(60).add(40).add(30).add(45).add(55).add(100)

print(str(t))
# 30->40->45->50->55->60->100

print(t.minimum(), t.maximum())     # <-
# 30 100

insert from iterable
Chaining .add().add().add() is a bit verbose. Providing an add_iter function allows us to insert any number of values from another iterable. We introduce it now because we're about to reuse it in the upcoming remove function too -
def add_iter(t, it):
  for q in it:
    t = add(t, q)
  return t

#main.py

from btree import btree

t = btree().add_iter([50, 60, 40, 30, 45, 55, 100])   # <-

print(str(t))
# 30->40->45->50->55->60->100

print(t.minimum(), t.maximum())
# 30 100

node removal and preorder traversal
We now move onto the remove function. It works similarly to the add function, performing a t.data comparison with the value to remove, q. You'll notice we use add_iter here to combine the left and right branches of the node to be deleted. We could reuse inorder iterator for our tree here, but preorder will keep the tree a bit more balanced. That's a different topic entirely, so we won't get into that now -
# btree.py (continued)

def remove(t, q):
  if not t:
    return t
  elif q < t.data:
    return node(t.data, remove(t.left, q), t.right)
  elif q > t.data:
    return node(t.data, t.left, remove(t.right, q))
  else:
    return add_iter(t.left, preorder(t.right))

def preorder(t):
  if not t: return
  yield t.data
  yield from preorder(t.left)
  yield from preorder(t.right)

Don't forget to extend the btree interface -
# btree.py (continued)

class btree:
  def __init__():       # ...
  def __str__():        # ...
  def add():            # ...
  def inorder():        # ...
  def maximum():        # ...
  def minimum():        # ...
  def add_iter(self, it): return btree(add_iter(self.t, it))
  def remove(self, q): return btree(remove(self.t, q))
  def preorder(self): return preorder(self.t)

Let's see remove in action now -
# main.py

from btree import btree

t = btree().add_iter([50, 60, 40, 30, 45, 55, 100])

print(str(t))
# 30->40->45->50->55->60->100

print(t.minimum(), t.maximum())
# 30 100

t = t.remove(30).remove(50).remove(100)      # <-

print(str(t))
# 40->45->55->60

print(t.minimum(), t.maximum())
# 40 60

completed btree module
Here's the completed module we built over the course of this answer -
from math import inf

class node:
  def __init__(self, data, left=None, right=None):
    self.data = data
    self.left = left
    self.right = right

def add(t, q):
  if not t:
    return node(q)
  elif q < t.data:
    return node(t.data, add(t.left, q), t.right)
  elif q > t.data:
    return node(t.data, t.left, add(t.right, q))
  else:
    return node(q, t.left, t.right)

def add_iter(t, it):
  for q in it:
    t = add(t, q)
  return t

def maximum(t, r=-inf):
  if not t:
    return r
  elif t.data > r:
    return max(maximum(t.left, t.data), maximum(t.right, t.data))
  else:
    return max(maximum(t.left, r), maximum(t.right, r))

def minimum(t, r=inf):
  if not t:
    return r
  elif t.data < r:
    return min(minimum(t.left, t.data), minimum(t.right, t.data))
  else:
    return min(minimum(t.left, r), minimum(t.right, r))

def inorder(t):
  if not t: return
  yield from inorder(t.left)
  yield t.data
  yield from inorder(t.right)

def preorder(t):
  if not t: return
  yield t.data
  yield from preorder(t.left)
  yield from preorder(t.right)

def remove(t, q):
  if not t:
    return t
  elif q < t.data:
    return node(t.data, remove(t.left, q), t.right)
  elif q > t.data:
    return node(t.data, t.left, remove(t.right, q))
  else:
    return add_iter(t.left, preorder(t.right))

def to_str(t):
  return "->".join(map(str,inorder(t)))

class btree:
  def __init__(self, t=None): self.t = t
  def __str__(self): return to_str(self.t)
  def add(self, q): return btree(add(self.t, q))
  def add_iter(self, it): return btree(add_iter(self.t, it))
  def maximum(self): return maximum(self.t)
  def minimum(self): return minimum(self.t)
  def inorder(self): return inorder(self.t)
  def preorder(self): return preorder(self.t)
  def remove(self, q): return btree(remove(self.t, q))

have your cake and eat it too
One understated advantage of the approach above is that we have a dual interface for our btree module. We can use it in the traditional object-oriented way as demonstrated, or we can use it using a more functional approach -
# main.py

from btree import add_iter, remove, to_str, minimum, maximum

t = add_iter(None, [50, 60, 40, 30, 45, 55, 100])

print(to_str(t))
# 30->40->45->50->55->60->100

print(minimum(t), maximum(t))
# 30 100

t = remove(remove(remove(t, 30), 50), 100)

print(to_str(t))
# 40->45->55->60

print(minimum(t), maximum(t))
# 40 60

additional reading
I've written extensively about the techniques used in this answer. Follow the links to see them used in other contexts with additional explanation provided -

*

*I want to reverse the stack but i dont know how to use recursion for reversing this… How can i reverse the stack without using Recursion

*Finding all maze solutions with Python

*Return middle node of linked list with recursion

*How do i recursively find a size of subtree based on any given node? (BST)

A: Instead of deleting the node using del you can reassign the parent node and let the child node be collected by garbage collector.
In deleteNode return the new child instead of deleting the node. Assign the returned value to the parent.
def deleteNode(self, currNode, value):
    if not currNode:
        return currNode
    elif value < currNode.data:
        return deleteNode(self, currNode.left, value)
    elif value > currNode.data:
        return deleteNode(self, currNode.right, value)

    else:
        if not currNode.right:
            return currNode.left

        if not currNode.left:
            return currNode.right

        temp_val = currNode.right
        mini_val = temp_val.val
        while temp_val.left:
            temp_val = temp_val.left
            mini_val = temp_val.val
        currNode.right = deleteNode(currNode.right,currNode.val)
    return currNode


text:
Q: get Link name from a list of links using javascript I am getting link values using an arraylist before diplaying then onto my Popup jsp. I am supposed to get the text once the link is clicked and pass it to parent page... No matter what I do the value getting passed to the Parent Jsp is only the first value in the array:
My POPUP.Jsp:
<%
    ArrayList all = Locations.getAllLocations();
    int size = all.size();
%>
<%
    for (int i = 0; i < size; i++) {
        ArrayList one = (ArrayList) all.get(i);
%>

<%=(String) one.get(0)%>

<%=(String) one.get(1)%>

<%=(String) one.get(2)%>

<% }%>

The display is working fine but whenever I click on the links I only get the first value in the array. What should I do?
Edit
My JAvascript:

A: You have first value in the array, because all your links have the same id "tname". And when you click on link - javascript fill found all links with id "tname" and get the first.

A: yes, You have to use this keyword to get individual value of link.
Use below code :
<%
ArrayList all = Locations.getAllLocations();
int size = all.size();
%>
<%
for (int i = 0; i < size; i++) {
    ArrayList one = (ArrayList) all.get(i);
%>

           <%=(String) one.get(0)%>

<%=(String) one.get(1)%>

<%=(String) one.get(2)%>

<% }%>

Please Replace this Javascript :

Here i used "ths" to get value for individual link.
I hope it will help you.


text:
Q: Google AppEngine - Uncaught exception 'Google_IO_Exception' Unable to connect Every so often I receive the following errors in my logs. It appears to be happening during the following actions: commit, lookup, runQuery
This is the start of each error:
PHP Fatal error:  Uncaught exception 'Google_IO_Exception' with message 'HTTP Error: Unable to connect: 'fopen(https://www.googleapis.com/datastore/v1beta2/datasets/{APPENGINE_ID}/commit): failed to open stream: Unsupported SSL context options are set. The following options are present, but have been ignored: cafile

PHP Fatal error:  Uncaught exception 'Google_IO_Exception' with message 'HTTP Error: Unable to connect: 'fopen(https://www.googleapis.com/datastore/v1beta2/datasets/{APPENGINE_ID}/lookup): failed to open stream: Unsupported SSL context options are set. The following options are present, but have been ignored: cafile

PHP Fatal error:  Uncaught exception 'Google_IO_Exception' with message 'HTTP Error: Unable to connect: 'fopen(https://www.googleapis.com/datastore/v1beta2/datasets/{APPENGINE_ID}/runQuery): failed to open stream: Unsupported SSL context options are set. The following options are present, but have been ignored: cafile

And this is the exact text below each of the above errors:
Fetch error'' in /base/data/home/apps/{APPENGINE_ID}/{NUMBERS}/vendor/google/apiclient/src/Google/IO/Stream.php:141
Stack trace:
#0 /base/data/home/apps/{APPENGINE_ID}/{NUMBERS}/vendor/google/apiclient/src/Google/IO/Abstract.php(136): Google_IO_Stream->executeRequest(Object(Google_Http_Request))
#1 /base/data/home/apps/{APPENGINE_ID}/{NUMBERS}/vendor/google/apiclient/src/Google/Http/REST.php(60): Google_IO_Abstract->makeRequest(Object(Google_Http_Request))
#2 [internal function]: Google_Http_REST::doExecute(Object(Google_Client), Object(Google_Http_Request))
#3 /base/data/home/apps/{APPENGINE_ID}/{NUMBERS}/vendor/google/apiclient/src/Google/Task/Runne in /base/data/home/apps/{APPENGINE_ID}/{NUMBERS}/vendor/google/apiclient/src/Google/IO/Stream.php on line 141

Does anyone know why this might be occurring? This doesn't happen all the time so I seriously doubt it has anything to do my code.
Bug Report Link


text:
Q: CSS Transition Not Returning To Original Shape & Can't Click Multiple Times Here's the CodePen.
The square changes to a circle as expected when it slides to the right, but when it returns back to the left, it stays a circle instead of changing to a square.
Also, I can only click the  once. If I try to click multiple times, it doesn't work.
Trying to do this with only CSS (if possible).

body {
  margin-top: 30px;
  background: gainsboro;
}
.container {
  margin: auto;
  width: 100%;
}
.path {
  position: relative;
  overflow: hidden;
  width: 100%;
  height: 80px;
  x-background: white;
}
@keyframes ani {
  0% {
    left: 0;
  }
  50% {
    left: 95%;
  }
  100% {
    left: 0;
  }
}
.shape:target {
  border-radius: 50%;
  transition: all .7s ease-in-out;
  animation-name: ani;
  animation-duration: 2s;
  animation-direction: alternate;
  animation-fill-mode: none;
}
.shape {
  position: absolute;
  left: 0;
  background-color: slateblue;
  width: 80px;
  height: 80px;
  display: block;
  border-radius: none;
  transition: border-radius .4s ease-out;
}

A: The closest you can get with just CSS is this, as far as I know:

body {
  margin-top: 30px;
  background: gainsboro;
}
.container {
  margin: auto;
  width: 100%;
}
.path {
  position: relative;
  overflow: hidden;
  width: 100%;
  height: 80px;
  x-background: white;
}
@keyframes ani {
  0% {
    left: 0;
  }
  50% {
    left: 95%;
  }
  100% {
    left: 0;
  }
}
.path a:focus .shape {
  border-radius: 50%;
  transition: all .7s ease-in-out;
  animation-name: ani;
  animation-duration: 2s;
  animation-direction: alternate;
  animation-fill-mode: none;
}
.shape {
  position: absolute;
  left: 0;
  background-color: slateblue;
  width: 80px;
  height: 80px;
  display: block;
  border-radius: none;
  transition: border-radius .4s ease-out;
}

The problem before was triggering the state with :target:.  This is tough to debug with sites like Codepen or other embedded editors, since you can't see the hash change.  Basically, clicking the link would append #elem to the URL, apply the :target styles to .shape, and stay like that until the hash changes.
This solution uses :focus, which gets you closer to your goal, but not all the way.  To repeat the animation, you need to defocus/blur the circle, then click it again.
I'm usually all for CSS-only effects, but I'm pretty sure you'll need Javascript for this.  Something as simple as applying a class on click, waiting 2 seconds, then removing the class would accomplish the same effect more reliably.


text:
Q: Unseen delays in changing div class . . I know a lot of questions must start with "This is odd" , but, ummm, this is odd.
I have some code which takes a while to run. So I've created a 'spinner' in CSS.
It's initiated, within a function, like this
document.getElementById("spinner").className = "spinner";

The I run the main function, which ends like this :
document.getElementById("spinner").className = "spinner_hidden";

It doesn't work, the spinner never shows . . . BUT! If I add an 'alert' after the first line (the class-change to show the spinner), it works!
As a test, I've tried deleting the last line, then the spinner shows, (but doesn't get cleared of course) so I know that the first line is working ok.
I've tried adding a JS delay instead of the alert, but no dice.
Can anyone help me with this oddity? Many Thanks.

A: Ho-hum . . . no response.
This may seem like a trivial question, but I think it's a nice demonstration of the impenetrable peculiarities of JS program-flow.
I've tried everything I can think of to fix this. That includes forcing the functions involved to 'async' (and to 'sync')  -  inserting a whole variety of 'wait' or 'sleep' routines – I've even tried putting the class changes into 'for' loops so that they have to be executed in the correct order.
Nothing works.
JS insists on executing the last line before its due time.
Good luck to all who attempt to use JS to do things in the order that the programmer is requiring . . .


text:
Q: Update the attributes/fields that have been changed PHP I am building the profile section of a php site. It offers a profile edit section. Say, I have the details user_id, user_name, user_firstname, user_lastname,user_email in my $_SESSION variable.
So, if any user edits any of these attributes, by going to localhost/profile/edit,
how should I go on about updating the database columns that have been changed?
ie 1. Should I compare the post data with my session variable and update only the changed fields? But I don't know how to implement this.

*Should I update all fields?

*SOme other standard way of doing things?
If you need more clarification, let me know.

A: Between update all fields and just on field it's up to you. In a REST perspective you should use a PUT to update the whole resource and a PATCH to update just one field of the resource. So i think is really up to you!
In any case the flow should be:

*

*update the tables (one field or many)

*update session


text:
Q: How do I draw an array made bitmap on screen using bitblt? Instead of drawing using Moveto and LineTo, I want to use a hand made bitmap, that I will fill with an array that I will create myself, and use that to fill the screen.
Right now, the array is just filled with red,
But when I draw to the screen I get all black.
This is the code:
void CCGWorkView::OnDraw(CDC* pDC)
{
    CCGWorkDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);
    if (!pDoc)
        return;

    pDCToUse->FillSolidRect(&r, world.bg_color);

    BITMAPINFO bminfo;
    CPaintDC hdc(this);
    CRect rect;
    GetWindowRect(&rect);

    int h = rect.bottom - rect.top,
        w = rect.right - rect.left;
    int *bits = new int[w * h];

    HDC hdcMem = CreateCompatibleDC(hdc);
    HBITMAP bm = CreateCompatibleBitmap(hdc, w, h);

    SelectObject(hdcMem, bm);

    bminfo.bmiHeader.biSize = sizeof(bminfo.bmiHeader);
    bminfo.bmiHeader.biWidth = w;
    bminfo.bmiHeader.biHeight = h;
    bminfo.bmiHeader.biPlanes = 1;
    bminfo.bmiHeader.biBitCount = 32;
    bminfo.bmiHeader.biCompression = BI_RGB;
    bminfo.bmiHeader.biSizeImage = 0;
    bminfo.bmiHeader.biXPelsPerMeter = 1;
    bminfo.bmiHeader.biYPelsPerMeter = 1;
    bminfo.bmiHeader.biClrUsed = 0;
    bminfo.bmiHeader.biClrImportant = 0;

    for (int i = 0; i < w * h; i++) {
        bits[i] = RGB(255, 0, 0);
    }

    SetDIBits(hdcMem, bm, 0, h, bits, &bminfo, 0);

    BitBlt(hdc, rect.left, rect.top, w, h, hdcMem, rect.left, rect.top, SRCCOPY);

    DeleteDC(hdcMem);
    DeleteObject(bm);
    delete bits;
}

A: There are a couple of issues in your code.
First, you don't need CPaintDC, as the pDC is passed into your OnDraw() function.
This may have actually caused your black display, as the newly created DC has a one pixel black-and-white bitmap selected into it, and when you call CreateCompatibleBitmap(), that bitmap is also monochrome.
Second, SetDIBits() expect RGBQUAD colors (https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-rgbquad), NOT RGB.
And, as Constantine Georgiou suggested, you should de-select your bitmap out of DC before deleting it to avoid resource leaks, even if MFC handles it for you.
Here is modified code:
void CMFCApplication1View::OnDraw(CDC* pDC)
{
    CMFCApplication1Doc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);
    if (!pDoc)
        return;

    //pDCToUse->FillSolidRect(&r, world.bg_color);

    BITMAPINFO bminfo;
    CRect rect;
    GetClientRect(&rect);

    int h = rect.bottom - rect.top,
        w = rect.right - rect.left;
    int* bits = new int[w * h];

    HDC hdcMem = CreateCompatibleDC(pDC->m_hDC);
    HBITMAP bm = CreateCompatibleBitmap(pDC->m_hDC, w, h);

    HGDIOBJ hOld = SelectObject(hdcMem, bm);

    bminfo.bmiHeader.biSize = sizeof(bminfo.bmiHeader);
    bminfo.bmiHeader.biWidth = w;
    bminfo.bmiHeader.biHeight = h;
    bminfo.bmiHeader.biPlanes = 1;
    bminfo.bmiHeader.biBitCount = 32;
    bminfo.bmiHeader.biCompression = BI_RGB;
    bminfo.bmiHeader.biSizeImage = 0;
    bminfo.bmiHeader.biXPelsPerMeter = 1;
    bminfo.bmiHeader.biYPelsPerMeter = 1;
    bminfo.bmiHeader.biClrUsed = 0;
    bminfo.bmiHeader.biClrImportant = 0;

    RGBQUAD red = { 0, 0, 255, 0 };
    for (int i = 0; i < w * h; i++) {
        bits[i] = *((int*)&red);
    }

    SetDIBits(hdcMem, bm, 0, h, bits, &bminfo, DIB_RGB_COLORS);

    BitBlt(pDC->m_hDC, rect.left, rect.top, w, h, hdcMem, rect.left, rect.top, SRCCOPY);

    SelectObject(hdcMem, hOld);
    DeleteDC(hdcMem);
    DeleteObject(bm);
    delete[] bits;
}


text:
Q: Filtering a reverse relationship by user, and returning only one object in Django Rest Framework Given these models:
class Product(models.Model):
    name = CharField(max_length=255)

class Order(models.Model):
    product = models.ForeignKey(Product)
    user = models.ForeignKey(User)
    quantity = models.PositiveIntegerField()

A user can only have a single Order object per product. I would like an API call to show a list of products, with the user's order where available. Is there a way to do that?
The default serialisation lists ALL orders under order_set. I did get a bit ahead with this to filter by user:
class FilteredOrderSerializer(serialisers.ListSerializer):
    def to_representation(self, data):
        data = data.filter(user=self.context['request'].user)
        return super(FilteredOrderSerializer, self).to_representation(data)

class OrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = Order
        list_serializer_class = FilteredOrderSerializer

class ProductSerializer(serializers.ModelSerializer):
    order_set = OrderSerializer(many=True, read_only=True)

    class Meta:
        model = Product

So now it only shows the authenticated user's order, but the resulting JSON looks something like
[
    {
        "name": "prod1",
        "order_set": [
            {
                "quantity": 4
            }
        ],
    }
]

i.e. the field is still called order_set and it's a list, while I would like it to be called order and be either an object or null. So I'm not sure where this filtering should take place, nor how to define the field.
Edit: I'm using a simple viewset
class ProductViewSet(view sets.ReadOnlyModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer

A: You need to add related_name field in your orders so you can
product.orders.all()

Then this should do.
class Order(models.Model):
    product = models.ForeignKey(Product, related_name='orders')
    user = models.ForeignKey(User)
    quantity = models.PositiveIntegerField()

class ProductSerializer(serializers.ModelSerializer):
    order = serializers.SerializerMethodField()

    class Meta:
        model = Product
        fields = ('name', 'order')

    def get_order(self, object):
        try:
            order = object.orders.get(user=self.context['request'].user)
            return SceneDetailSerializer(order).data
        except Order.DoesNotExist:
            return None

Update: You can try out serializer method field. Not sure if self contains context and user references in it. You need to remove listfield from your order serializer. Let me know if it works.


text:
Q: How to pass in URI variable values to url Forgive the rookie question--
how do you pass in a the value for a uri variable in a url?
(this is for a spring boot app making a REST call)
for example if I have the url:
"http://example.com/hotels/{hotel}/bookings/{booking}"

And assuming 'hotel' and 'booking' have String values, how do I pass these in?

A: import org.springframework.web.util.UriTemplate;
import java.net.URI;

UriTemplate uritemplate= new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}");
URI uri = tmp.expand(hotel, booking);

Good answers to this question are suprisingly difficult to find.
Spring doc has some useful examples.

A: Easy, let's say a {hotel} is called "Casket" and {booking} has value of "Blue"
So your route: "http://example.com/hotels/{hotel}/bookings/{booking}", should look like:
"http://example.com/hotels/Casket/bookings/Blue"

All you need to do is call that URL and read the response server gives you


text:
Q: Cluster objects by geometric coordinates (Y axis) I've got a pandas DataFrame with records describing rectangles with absolute coordinates of all the 4 points: TL (top-left), TR (top-right), BL (bottom-left) and BR (bottom-right). As it is, the rects seem to follow a row-like pattern, where there are conspicuous clusters forming "rows", like in this picture:

The data look like this:
    tl_x  tl_y  tr_x  tr_y  br_x  br_y  bl_x  bl_y  ht   wd
0   1567   136  1707   136  1707   153  1567   153  17  140
1   1360   154  1548   154  1548   175  1360   175  21  188
2   1567   154  1747   154  1747   174  1567   174  20  180
3   1311   175  1548   175  1548   196  1311   196  21  237
4   1565   174  1741   174  1741   199  1565   199  25  176
5   1566   196  1753   196  1753   220  1566   220  24  187
...

I need to cluster these objects along the bl_y or br_y column (bottom Y coordinate) to produce a 2D list of "rows" like:

As you see, objects in each "row" may have slightly varying Y coordinates (not exactly equivalent in each cluster). What I basically need is some function to add a separate e.g. clustered_y column to the DF and then sort by this column.
What's the simplest way to go?

A: Given the dataframe you provided:
import pandas as pd

df = pd.DataFrame(
    {
        "tl_x": {0: 1567, 1: 1360, 2: 1567, 3: 1311, 4: 1565, 5: 1566},
        "tl_y": {0: 136, 1: 154, 2: 154, 3: 175, 4: 174, 5: 196},
        "tr_x": {0: 1707, 1: 1548, 2: 1747, 3: 1548, 4: 1741, 5: 1753},
        "tr_y": {0: 136, 1: 154, 2: 154, 3: 175, 4: 174, 5: 196},
        "br_x": {0: 1707, 1: 1548, 2: 1747, 3: 1548, 4: 1741, 5: 1753},
        "br_y": {0: 153, 1: 175, 2: 174, 3: 196, 4: 199, 5: 220},
        "bl_x": {0: 1567, 1: 1360, 2: 1567, 3: 1311, 4: 1565, 5: 1566},
        "bl_y": {0: 153, 1: 175, 2: 174, 3: 196, 4: 199, 5: 220},
        "ht": {0: 17, 1: 21, 2: 20, 3: 21, 4: 25, 5: 24},
        "wd": {0: 140, 1: 188, 2: 180, 3: 237, 4: 176, 5: 187},
    }
)

Here is one way to do it:
# Calculate distance between "br_y" values
df = df.sort_values(by="br_y")
df["previous"] = df["br_y"].shift(1).fillna(method="bfill")
df["distance"] = df["br_y"] - df["previous"]

# Group values if distance > 5% of "br_y" values mean (arbitrarily chosen)
clusters = df.copy().loc[df["distance"] > 0.05 * df["br_y"].mean()]
clusters["clustered_br_y"] = [f"row{i}" for i in range(clusters.shape[0])]

# Add clusters back to dataframe and cleanup
df = (
    pd.merge(
        how="left",
        left=df,
        right=clusters["clustered_br_y"],
        left_index=True,
        right_index=True,
    )
    .fillna(method="ffill")
    .fillna(method="bfill")
    .drop(columns=["previous", "distance"])
    .reset_index(drop=True)
)

   tl_x  tl_y  tr_x  tr_y  br_x  br_y  bl_x  bl_y  ht   wd clustered_br_y
0  1567   136  1707   136  1707   153  1567   153  17  140           row0
1  1567   154  1747   154  1747   174  1567   174  20  180           row0
2  1360   154  1548   154  1548   175  1360   175  21  188           row0
3  1311   175  1548   175  1548   196  1311   196  21  237           row1
4  1565   174  1741   174  1741   199  1565   199  25  176           row1
5  1566   196  1753   196  1753   220  1566   220  24  187           row2


text:
Q: Retrofit 2 при добавление cookie в header выходить ошибка public static Retrofit getClient(){
    HashSet<String> cookies = new HashSet<>();
    Gson gson = new GsonBuilder()
            .setExclusionStrategies(new ExclusionStrategy() {
                @Override
                public boolean shouldSkipField(FieldAttributes f) {
                    return f.getDeclaringClass().equals(RealmObject.class);
                }

                @Override
                public boolean shouldSkipClass(Class<?> clazz) {
                    return false;
                }
            })
            .create();

    OkHttpClient client = new OkHttpClient();
    client.interceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());

            if (!response.headers("Set-Cookie").isEmpty()) {
                for (String header : response.headers("Set-Cookie")) {
                    cookies.add(header);
                }
            }

            return response;
        }
    });
    client.interceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request.Builder builder = chain.request().newBuilder();

            String cookiestring = "";
            for (String cookie : cookies) {
                String[] parser = cookie.split(";");
                cookiestring = cookiestring + parser[0] + "; ";
            }
            builder.addHeader("Cookie", cookiestring);
            return chain.proceed(builder.build());
        }
    });

    if(retrofit == null){
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
    }

    return retrofit;
}

response.header не пустой
String number =  eTxtUsername.getText().toString();
            String password = eTxtPassword.getText().toString();
            ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
            Call<AuthResponse> call =  apiInterface.auth(number,password);
            call.enqueue(new Callback<AuthResponse>() {
                @Override
                public void onResponse(Call<AuthResponse> call, Response<AuthResponse> response) {
                    AuthResponse authorization = response.body();
                    Headers header = response.headers();
                    Log.i("ssss","head"+ header);
                    DataAuth dataAuth = authorization.getData().get(0);
                    boolean success = dataAuth.isSuccess();

Вот такой ошибка выходить
FATAL EXCEPTION: main                                                                        java.lang.UnsupportedOperationException
                                                                                at java.util.Collections$UnmodifiableCollection.add(Collections.java:928)
                                                                                at marketmobile.project.kz.marketmobile.rest.ApiClient.getClient(ApiClient.java:78)
                                                                                at marketmobile.project.kz.marketmobile.fragment.LoginFragment$2.onClick(LoginFragment.java:92)

A: Вы не правильно добавляете Interceptor
OkHttpClient client = new OkHttpClient.Builder()
    .addInterceptor(new YourInterceptor())
    .build();

А client.interceptors().add() будет кидать исключение.
И еще лучше не создавать каждый раз новый OkHttpClient, а сохранить его в статическое поле и использовать повторно. Возможно без этого кукисы и не заведутся.
А еще лучше использовать готовую библиотеку, вместо изобретения велосипедов.


text:
Q: How to check if clangd is running in VS code? I installed clangd, but I'm not sure if it's running. I don't seem to be getting some of the features that were advertised, so I feel like it's not running or only partially working.
I'm looking at the "Visual Studio Code" section of https://releases.llvm.org/8.0.0/tools/clang/tools/extra/docs/clangd/Installation.html.
Here it says:

Debug logs: when clangd is running, you should see "Clang Language Server" in the dropdown of the Output panel (View -> Output).

In my drop down (see image below), I only see clangd but there is no Clang language server. Are these 2 equivalent? If not, then it appears that clangd isn't running properly?

A: It is running. The output panel was renamed to "clangd" at some point in the VSCode extension.


text:
Q: RStudio on Windows doesn't detect Git installation I have followed the instructions as per "Version Control with Git and SNV" but I do not get any possibility to select git for version control for my project in the Project settings.
I am on:

*

*Microsoft Windows 7 Enterprise 6.1.7601 Service Pack 1 Build 7601

*RStudio: Version 0.99.902

*R: version 3.3.1 (2016-06-21) -- "Bug in Your Hair"

I have installed git 2.9.0 for Windows from https://git-scm.com/downloads.
It installs under C:\Users\spi\AppData\Local\Programs\Git (let's call it gitroot)
In RStudio and in PATH I tried (one at the time and closing/reopening RStudio every time) to specify all possible combinations of
PATH - RStudio global settings
as follows:

*

*gitroot\cmd   -  gitroot\cmd\git.exe

*gitroot - gitroot\git-bash.exe

*gitroot - gitroot\git-cmd.exe

*gitroot - gitroot\mingw64\bin\git.exe
Any hints is welcome.
Thanks in advance!

A: The solution was to install Git for Windows in C:\opt\Git which looks like not to be a special folder.
I was able to choose where to insall only after aborting a reinstallation.

A: What worked for me was changing the path file from git-bash to gitcmd:
Correct Path file:
C:\Program Files\Git\cmd


text:
Q: Virtual keyboard and tablet mode for KDE I've just installed the last Ubuntu version with KDE.
I would love to use my convertible computer also in tablet mode but it seems not working at the moment. Is there any additional package you suggest to make it work, like for instance virtual keyboards, or something else that automatically detect tabled mode and starts the virtual keyboard?
Thanks

A: This stuff is implemented, with a few caveats:

*

*It only works when using Wayland. On X11 there seem to be some ways to work around that though.

*The virtual keyboard only works for Qt apps, although there is ongoing work to improve this

*The tablet mode detection requires support for the hardware in the kernel, which sadly is missing sometimes

A: Onboard can do this. Add it to your tray or start it automatically. Now whenever input is requested by any application, onboard will open automatically.

A: Not sure if u are still searching for a way but one simple solution is adding the following as the last line in your .bashrc (~/.bashrc):
onboard &

For convertibles one can use xinput test-xi2 --root to detect if the display rotates "for me device 3 will returns some key presses" and start onboard / kill it giving a simple way of making tablet mode if the in build one is not working!
But its helpful to have the icon somewhere so you can press it in some cases when the app doesn't support qt. ;)


text:
Q: Вывод в jEditorPane содержимого xml файла без тег Здравствуйте, я недавно начала изучать java и столкнулась с проблемой. Мне необходимо вывести в jEditorPane содержимое книги, книга является файлом xml. Я использую:
jEditorPane1.setEditorKit(new XMLEditorKit());
try{
            jEditorPane1.read(new FileInputStream(library.Fil.filename.get_value()), new FileInputStream(library.Fil.filename.get_value()));

}catch (IOException e) {};

Выводится отформатированный раскрашенный текст с тегами, но мне нужно только текстовое содержание книги. Подскажите, пожалуйста, каким способом это можно реализовать
A: Предлагаю использовать XML-парсеры, лучше всего (имхо) подойдёт SAX


text:
Q: had not vs did not - past perfect I recently watched a YouTube tutorial which talks about right usage of past perfect tense. For negative sentences in past perfect, a simple rule to frame sentences is -
Subject + hadn't + main verb in past participle.
Example - He had not learnt music before he became famous.
My question -
Is the rule restricted to "hadn't" coming after the subject? Can we not say something like this -
He did not study music before he became famous.
Is this sentence correct? If it is not, what is the mistake?

A: The sentence He did not study music before he became famous is correct, but it is not written in the past perfect. You used the past simple. You used 'did' because the sentence is a negation.
Small guide on the difference between the past simple, present perfect and past perfect:

*

*The past simple is used when something is over and done with, i.e. it has no relevant influence on the present. It is usually used if the sentence contains yesterday, a week ago, last year, etc.

*The present perfect is used when something started in the past and is still going on, or when it has relevant influence on the present.

*The past perfect is almost always used in combination with other verbs, to indicaste that something in the past happened and had influence on the actions described by the other verbs. This is a bit difficult, so I will explain it with your example sentence:
He had not learnt music before he became famous. In this case, the fact that he had not learnt music was relevant at the time when he became famous.

The difference between He had not learnt music before he became famous and He did not study music before he became famous is that in the first sequence you indicate that the fact that he had not learnt music had influence for some reason you explain later.


text:
Q: Does Java have heap and stack? http://courses.washington.edu/css342/zander/css332/arch.html
bottom of the page:

The C++ memory model differs from the Java memory model. In C++,
  memory comes from two places, the run time stack and the memory heap.

This reads as if Java doesnt have a heap (or stack)?
I am trying to learn all the "under the bonnet" details for Java and C++

A: Java has a heap and a (per-thread) stack as well. The difference is that in Java, you cannot choose where to allocate a variable or object.
Basically, all objects and their instance variables are allocated on the heap, and all method parameters and local variables (just the references in the case of objects) are allocated on the stack.
However, some modern JVMs will allocate some objects on the stack as a performance optimization when they detect that the object is only used locally.

A: Java uses a heap memory model.  All objects are created on the heap; references are used to refer to them.
It also puts method frames onto a stack when processing them.
I would say it has both.

A: Yes, Java have both heap (common to the entire JVM) and stack (one stack per thread).
And having stack & heap is more a property of implementations than of languages.
I would even say that most Linux programs have heap (obtained thru mmap & sbrk system calls) and stack (at the level of the operating system, this is not dependent of the language).
What Java have, but C++ usually not, is a garbage collector. You don't need to release unused memory in Java. But in C++ you need to release it, by calling delete, for every C++ object allocated in the heap with new.
See however Boehm's garbage collector for a GC usable in C & C++. It works very well in practice (even if it can leak in theory, being a conservative, not a precise, GC).
Some restricted C++ or C environments (in particular free standing implementations for embedded systems without operating system kernel) don't have any heap.


text:
Q: Why are the top-most if conditions ignored? I will admit that I'm still new to Ruby so I'm not yet familiar with the gotcha's and am still learning.
I've googled the issue many times but haven't been able to find an exact answer. Most results talk about "nested" if/else statements. Which isn't what I'm attempting.  I found another answer from SO that talked about mapping the arrays based on conditions, but feel like that would bring me back to the same issues I'm already having.
Link to SO article regarding merging nested arrays if anyone is interested:
Ruby: Merging nested array between each other depending on a condition
My Question:
While designing a simple CLI script in ruby using optparse to control the output based on conditionals. I came across an issue where I am unable to do multiple sequential if statements and concat/merge multiple arrays into one to be passed to another function.
For some reason only the last if block is being honoured. All if blocks before the last one return nil.
Can anyone tell me what I'm doing wrong and provide me with some relevant documentation regarding my issue. Such as why such an issue occurs?
Would love a working solution to learn from, but reference material would work as well since my goal is to learn from this issue.
Results of my tests:
$ ruby servers.rb
#=> ["server1", "server2", "server3"]
$ ruby servers.rb -m
#=> nil
$ ruby servers.rb -h
#=> nil
$ ruby servers.rb -s server6
#=> ["server6"]
$ ruby servers.rb -m -h
#=> nil

Below is my script:
#!/usr/bin/env ruby
require 'optparse'

@servers = {
  'primary' => %w[server1 server2 server3],
  'inhouse' => %w[server4 server5],
  'mlm' => %w[server6]
}

@options = {
  inhouse: false,
  server: [],
  mlm: false
}

# Parse options passed to medusabackup.rb
optparse = OptionParser.new do |opts|
  opts.on('-h', '--inhouse', 'Limit results to inhouse results') do
    @options[:inhouse] = true
  end
  opts.on('-m', '--mlm', 'Include mlm results') do
    @options[:mlm] = true
  end
  opts.on('-s', '--server=SERVER', 'Limit results to SERVER') do |f|
    @options[:server] << f
  end
  opts.on_tail('--help', 'Display this screen') { puts opts, exit }
end

begin
  optparse.parse!
rescue OptionParser::InvalidOption, OptionParser::MissingArgument
  puts $ERROR_INFO.to_s
  puts optparse
  exit
end

def selected_servers
  # Setup Selected variable as an array
  selected = []
  # If @options[:server]  array is not empty and @options[:server]
  # add @options[:server] servers to [selected] array
  if @options[:server].empty?
    # If @options[:mlm] is true add @server['mlm'] servers to [selected] array
    selected.concat @servers['mlm'] if @options[:mlm]
    # If @options[:inhouse] is true add @server['inhouse'] servers to [selected] array
    selected.concat @servers['inhouse'] if @options[:inhouse]
    # If @options[:mlm], @options[:inhouse] is true add @server['mlm'] servers to [selected] array
    selected.concat @servers['primary'] unless @options[:mlm] || @options[:inhouse]
  else
    selected.concat @options[:server]
  end
end
puts selected_servers.inspect

Thanks to Max and everyone for showing me my blunder.  Forgot to return selected at the bottom of the function.

A: There's no explicit return in selected_servers, so it's returning the value of the last expression it runs, which is usually a failing unless. A failing if/unless returns nil.


text:
Q: Request failed with status code 404 (REDUX) Can't seem to pull data from database but according Redux DevTools the actions PASSWORD_LIST_REQUEST seems to be firing. What is going wrong here? I checked my original route, it should be going towards "api/passwords" in the server, is this a backend problem or Redux problem?
I checked the backend url routes with postman, so thats all good.
ACTIONS
export const listPasswords = () => async (dispatch) => {
  try {
    dispatch({ type: PASSWORD_LIST_REQUEST });

    const { data } = await axios.get("/api/passwords");

    dispatch({
      type: PASSWORD_LIST_SUCCESS,
      payload: data,
    });
  } catch (error) {
    dispatch({
      type: PASSWORD_LIST_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
};

REDUCERS
  export const passwordListReducer = (state = { passwords: [] }, action) => {
      switch (action.type) {
        case PASSWORD_LIST_REQUEST:
          return {
            loading: true,
            passwords: [],
          };
        case PASSWORD_LIST_SUCCESS:
          return { passwords: action.payload, loading: false };
        case PASSWORD_LIST_FAIL:
          return { loading: false, error: action.payload };
        default:
          return state;
      }
    };

STORE
import { createStore, combineReducers, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import { composeWithDevTools } from "redux-devtools-extension";
import { passwordListReducer } from "./reducers/passwordReducers";

const reducer = combineReducers({ passwordList: passwordListReducer });

const initialState = {};

const middleware = [thunk];

const store = createStore(
  reducer,
  initialState,
  composeWithDevTools(applyMiddleware(...middleware))
);

export default store;

Server
import passwordRoutes from "./routes/passwordRoutes.js";

dotenv.config();

connectDB();

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.get("/", (req, res) => {
  res.send("API is running");
});

app.use("/api/passwords", passwordRoutes);

app.use(notFound);

app.use(errorHandler);

const PORT = process.env.PORT || 5000;

app.listen(
  PORT,
  console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`)
);

A: Seems like your call to endpoint might be going to the wrong url here
const { data } = await axios.get("/api/passwords");

The above axios call would point to your app url, say you app is running on localhost:3000, an API call would be made to http://localhost:3000/api/password by default.
If your app and back end run on different ports on your localhost, you have to set the domain on the axios call. From you code sample, I see you set you APIs to run from port 5000.
const { data } = await axios.get("http://localhost:5000/api/passwords");

Tip
If you don't want to keep repeating the base url, you can create an axios instance
export const request = axios.create({baseUrl: "http://localhost:5000"});

Then make your requests this way
import { request } from "path to request module";

...
const { data } = await request.get("/api/passwords");
...

A: I needed a proxy in package.json.
 "proxy": "http://localhost:5000",


text:
Q: Chrome page crash when running selenium and capybara under tmux I'm using cucumber + selenium + capybara to do test on OSX 10.9.
chromedriver is installed via brew with latest version 2.10.
When I run the test, the page in chrome which is lunched by selenium is just crashed.  Below are the output in the console :
unknown error: session deleted because of page crash
      from tab crashed
        (Session info: chrome=37.0.2062.120)
        (Driver info: chromedriver=2.10.267517,platform=Mac OS X 10.9.4 x86_64) (Selenium::WebDriver::Error::UnknownError)

If I tried to use the selenium launched chrome, every tab will be crashed.
I googled the problem, the chrome crash issue happened before and fixed after chromedriver 2.6.  As you can see all my chromedriver (2.10) and chrome are the latest ones.
If I switch my selenium driver browser to firefox, it works well.
Thanks in advance for your attention.

A: I had the same issue.This puzzled me for a long time.
By a happy chance,I run testing in terminal,everything is ok.
The problem only happens when I run testing with tmux session!
Fix problem for me .


text:
Q: USDC smart contract on polygon revoked all my approve request Simple. I'm trying to interact with USDC in my Dapp.
async function approveUSDC() {
try {
    const USDCContractAdress = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174";
    const USDCContractAbi = [
        "function approve(address spender, uint256 amount) public",
    ];
    const address = "0x644F303448a1d14Fa24Bf18200Dd41790f6B9920"; //BGGExchange Contract
    const amount = 50000000000000000000n ;
    const USDCContract = new ethers.Contract(USDCContractAdress, USDCContractAbi, provider);
    const result = await USDCContract.connect(signer).approve(address, amount);
    console.log(result);
} catch (error) {
    console.log(error);
}

}
Everytime I call the approve function on the USDC smart contract of polygon, the transaction return as revoked. I'm baffled please help.