text:
Q: Closing a switch in series with a capacitor Suppose we have the following circuit:

Such that for $t<0$ the switch M was open. If we close the switch at $t=0$ what will the voltage on the capacitor, $V_C$, be at $t=0^+$? What about $\dot V_C$ at $t=0^+$? Will there be a current passing through $R$ the moment the switch is closed?
I need to solve an ODE for a more complicated circuit which has this sub-circuit as a part of it, and I need initial conditions to solve for the ZIR case. I'm trying to figure out these initial conditions but I'm not sure. Here are my thoughts:
Before closing the switch, there will be a steady finite current $I$ in the circuit.The moment we close the switch, there can be no current passing through $R$, else there will be some finite voltage on the capacitor $\longrightarrow$ $\dot V_C$ will be infinite $\longrightarrow$ $I_C$=C$\cdot \dot V_C$ will be infinite which cannot be.
Therefore $V_C(t=0^+)=0$ and $\dot V_C(t=0^+)=I/C $. I'm not sure if what I said I correct, I mean we learned that if there is no impulse current (like Dirac's Delta function), the voltage on the capacitor will be continuous.Does this apply in the case too?  I would really appreciate any help.

A: There are some mistakes with your assumptions. When $t<0$ a current $I =V/R$  will be flowing through resistor and no current would be flowing through capacitor. As soon we close the switch the capacitor will get charged instantaneously (yes it could lead to $I = \infty$ at $t=0$ but it can be avoided if even a small resistor is placed between capacitor and voltage source. And we can never get the resistance of those wires down to $0$). After $t=0$ a potential difference will develop across capacitor due to its charge. But a same current $I = V/R$ through the resistor as to satisfy Kirchhoff's loop rule in loop containing resistor and source. And because charge on capacitor will be constant after $t=0$ so will be the potential difference so $\dot{V_c}$ will be zero, not infinite and so will be the current through capacitor.

A: Let me tell you some notable points these should help you solve such problems from the competitive exam point of view:
=>A completely uncharged capacitor is like a wire, it offers 0 resistance
=>A fully charged capacitor is infinite resistance and no current flows through it
=>A battery that you have represented is an ideal battery and ideal batteries do not exist!!! To solve this question what you need to assume is that there is internal resistance of the cell that will be present.
=> The charging and discharging of capacitors is an exponential function which is very important from the physics point of view.
The answer to your question :
If you deliberately wish to take an ideal battery then the time taken to charge a capacitor is 0, the current passing at the instant when the charging might have occurred is infinity, the voltage across the capacitor will be constant throughout because you just used an ideal circuit hence voltage across capacitor is constant.
Ideally in such a situation, the capacitor gets charged at t=0 which is illogical and impractical to occur.

A: You cannot solve the problem presented.
An ideal battery connected to a capacitor will have an initial current equal to infinity, which is obviously not possible. To make the problem solvable, you need to know the internal resistance of the battery.
Once you add the resistor in series with the battery, you will simply need to calculate the voltage across the parallel resistor (the maximum voltage you will across the capacitor).
$V_{t} = V_{max} e^{\frac{-t}{RC}}$
Where R is the resistance of the battery.


text:
Q: Plotting Date with Matplotlib and Pandas I am trying to plot number of sales on Y axis against the dates on the X axis. I can't seem to work out a way to do the dates on the X axis. If i change the dates to a float, it I can plot it but I still cannot figure out a way to plot the date format.
import matplotlib.pyplot as plt
import csv

x = []
y = []

with open('book1.csv','r') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
    for row in plots:
        x.append(float(row[0]))
        y.append(float(row[1]))

plt.plot(x,y, label='Loaded from file!')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Interesting Graph\nCheck it out')
plt.legend()
plt.show()

My csv looks something like:
1/1/2019,7980.185714
2/1/2019,9478.297619
3/1/2019,9282.166667
4/1/2019,6900.833333
5/1/2019,5563.716667

If I change the dates to a float format, I get this graph:

A: You need change the type of x to datetime :
import matplotlib.pyplot as plt
import csv
import datetime as dt

x = []
y = []
with open('book1.csv','r') as csvfile:
  plots = csv.reader(csvfile, delimiter=',')
  for row in plots:
      x.append(dt.datetime.strptime(row[0],'%m/%d/%Y').date())
      y.append(float(row[1]))
plt.plot(x,y, label='Loaded from file!')
plt.xlabel('x')
plt.xticks(x, x, rotation=90)
plt.ylabel('y')
plt.title('Interesting Graph\nCheck it out')
plt.legend()
plt.show()

A: sales are declining.  Set the date as an index then plot the Sales
txt="""1/1/2019,7980.185714
2/1/2019,9478.297619
3/1/2019,9282.166667
4/1/2019,6900.833333
5/1/2019,5563.716667"""

from io import StringIO
f = StringIO(txt)
df = pd.read_table(f,sep =',')
df.columns=['Date','Sales']
df['Date']=pd.to_datetime(df['Date'])
df.set_index('Date',inplace=True)
plt.title("Sales")
plt.plot(df)
plt.xticks(rotation=90)
plt.show()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Open google play store when push notification opened I am setting up firebase push notifications to notify users if there is new update to react native application. The thing is I want to open play store when a push notification opened.
I tried using react native linking. It worked when app is in foreground but when app is in background when push notification opened it will open the app and directed to play store.
this.notificationOpenedListener = firebase.notifications()
   .onNotificationOpened((notificationOpen) => {
        Linking.openURL("https://play.google.com/store/apps/details?id=com.sample.myapp");
    });

const notificationOpen = await firebase.notifications().getInitialNotification();
if (notificationOpen) {
    const { title, body,path } = notificationOpen.notification;
    Linking.openURL('https://play.google.com/store/apps/details?id=com.sample.myapp');
}

So is there away to open play store without opening the app in background when push notification is opened?


text:
Q: How to get xlab and ylab to work in mosaic plots in vcd package For some reason I cannot get xlab and ylab to work in mosaic plots in vcd package.
I tried:
mosaic(~Sex +Survived,
       data=Titanic,
       shade=T,
       legend=T,
       main="myplot",
       labeling_args=list(abbreviate = c( Sex=2, Survived=1)) ,
       ylab="Gender",
       xlab="survival")

this labels the axes "Sex" and "Survived"  respectively.
mosaic(margin.table(Titanic, c(2,4)),
       ylab="Gender",
       xlab="survival",
       shade=T, legend=T,
       main="myplot",
       labeling_args=list(abbreviate = c( Sex=2, Survived=1)))

this also labels the axes "Sex" and "Survived"  respectively.
mosaicplot(margin.table(Titanic, c(2,4)),
           shade=T,
           legend=T,
           main="myplot",
           labeling_args=list(abbreviate = c(Sex=2, Survived=1)),
           ylab="Gender",
           xlab="survival")

this labels the axes correctly, but disregards  'labeling_args'
Does anyone have any suggestions?

A: There is a huge part written on labels in the vcd documentation.
What you were looking for is this:
labeling_args = list(set_varnames = c(Sex="Gender", Survived="survival"))

It's been a while since you asked, but maybe it helps someone else ;)
The mosaic function and the mosaicplot function use very different graphic options. So it's no wonder that what works with one doesn't work with the other.


text:
Q: how to display the thumbnail image How to display the Thumbnail image  for the video before playing. This is Simple question ,I am new in this field can any one help me to solve this problem
NSString *str11 = [NSString stringWithFormat:@"https://www.youtube.com/embed/XGSy3_Czz8k?autoplay=1"];

NSURL *url1 = [NSURL URLWithString:str11];

MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:url1] ;
                [player play];

AVAsset *asset = [AVAsset assetWithURL:url1];

AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc]initWithAsset:asset];

CMTime time = CMTimeMake(1, 1);
CGImageRef imageRef = [imageGenerator copyCGImageAtTime:time actualTime:NULL error:NULL];
UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];
NSLog(@"thumbmail %@",thumbnail);

A: If there is no requirement to use MPMoviewPlayer then you can use UIWebView. There you will have preview thumbnail loaded automatically.
 [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.youtube.com/embed/XGSy3_Czz8k?autoplay=1"]]];


text:
Q: 2x2 MIMO communications, SNR, and data throughput vs link robustness trade off With information about data throughput in a 2x2 MIMO environment and without knowing the channel state information is there a way  one can reliably estimate the receive SNR based on the throughput in a Wi-Fi OFDM link?

A: No. That's mathematically impossible (you'd need to know the magnitude of the singular values of a matrix you explicitly say you don't have), and even if you would know these singular values, you would need knowledge about the actual data demands (which never are uniform), receiver and transmitter characteristics, the interference situation (unlicensed band, collision-detection based multiple access scheme).


text:
Q: Withdrawal of support for TLS 1.0 and 1.1 IBM bluemix team announced that they will be removing TLS1.0,1.1 support.
They have also said if we can access our applications with parameter 'alt' in our url , then we are fine. Does that mean we can keep using the same urls?

A: Yes, you can use the same URLs. Adding alt after your application subdomain just enforces TLS 1.2, and if you can connect you will not be affected by the change.
If, however, you can't connect using your current client, you will need to upgrade/change to a TLS 1.2 supporting one or you will be impacted by the change.


text:
Q: Getting IOException, cant find any reason I tried to read rgb of specific pixels however i was getting IOException.
I couldnt find any reson so yet i tried to run program from this site  link
but im still getting IOException.
So can this be because of JRE or my IDE which is Eclipse?
import java.io.*;
import java.awt.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;

public class GetPixelColor
{
  public static void main(String args[]) throws IOException{
  File file= new File("rockface.jpg");
  BufferedImage image = ImageIO.read(file);
  // Getting pixel color by position x=100 and y=40
  int clr=  image.getRGB(100,40);
  int  red   = (clr & 0x00ff0000) >> 16;
  int  green = (clr & 0x0000ff00) >> 8;
  int  blue  =  clr & 0x000000ff;
  System.out.println("Red Color value = "+ red);
  System.out.println("Green Color value = "+ green);
  System.out.println("Blue Color value = "+ blue);
  }
}

A: That's probably because that program you linked is referencing an image that you haven't in your path.
Add the following line after File constructor to check if the file you are looking for exist:
File file= new File("rockface.jpg");
if (file.exists()){
   //OK
}else{
   //you should have I/O Exception when the code reach ImageIO.read(file);

}

A: According to JavaDoc, this (likely) is the method that is throwing the IOException:
ImageIO#read(File f)
From the documentation:

Throws:
IllegalArgumentException - if input is null.
IOException - if an error occurs during reading.

This is most likely due to not being able to find the File you specified.  Try moving it to the classpath or project root.

A: I can't remember the exact details, but I've heard other people asking about IOExceptions with Eclipse.
It's probably the case that your files are not in the running directory of your project. I can't remember how eclipse is set up, but try moving the files into whatever folder holds the .class files, or just otherwise play around with the file's location.

A: A solution would be to specify the absolute path (assuming you are using windows that would be c:....\etc..) otherwise you will have to use the relative path.

To know in which folder your application is search, you can use :

System.getProperty("user.dir");


text:
Q: Paypal API for checking status of recurring (subscription) payment Does anyone know is there any way to check status of recurring (subscription) payment at PayPal.
I just want to submit transaction ID and to see is payment canceled (suspended) or it is still active.

A: If you're using the Recurring Payments API you can use GetRecurringPaymentsProfileDetails to obtain details including the current status of the profile.
If you're working with Standard Subscriptions, though, then there is no API to obtain the details, unfortunately.
In either case, I'd recommend looking into Instant Payment Notification (IPN).  Using it you could automate the process of sending email notifications, updating your own database, etc. when new profiles are created, suspended, re-activated, etc.


text:
Q: How to teach Intellisense about the existence of  and ? Intellisense has macro for making new table:

Yet when I try to create new row, it forces the <strong> tag:

I actually have to press Esc, otherwise the <strong> is inserted if I type >. I have similar problems with <th>, where <math> is inserted instead.
Is there a way to add HTML element to known elements of intellisense?

A: VS should totally know about these elements.  It sounds like the HTML schema has somehow been corrupted.  You can try to delete the HTML schema cache and see if that fixes the problem.  To do this, go to %AppData%\Microsoft\Visual Studio\15.0_<InstanceID>\ and remove (or rename) the GeneratedSchemas folder.


text:
Q: WordPress - Roaming User Profiles functionality? Our company is currently updating its intranet and is a multi-national company. The update for the intranet is being developed using WordPress. We have been given a requirement with regards to a users profile being able to roam based on what country they are in and to this point we are not sure whether or not WordPress can provide this functionality or if there is a plugin available and would like some help.
Here is an explanation of our requirement/problem:
When a user logs in to the Altranet (intranet) their location code is determined by their Active Directory (AD) Group. This code is required to provide access to country specific documents/messages/items on the altranet eg: the employee handbook for UK staff should only visible to UK based staff as defined in the AD Group.
Many staff travel globally so these specific staff need to have a default location code, plus have the ability to switch to another location if required. The new location will then determine what documents/messages/items they can access. So for example, a member of staff based in UK who can also roam to US should be able to see the UK staff handbook only, but if they switch location they need to be able to see the US handbook only.
To allow this to happen the user will need to be allocated a specific number of location codes and not just a default location. Also, the documents etc will need to be tagged per location also – I believe messages can already be tagged.
We do not want users having more than 1 username but we do need a solution within Wordpress to allow for this functionality.
Summary:
Would anyone be able to offer any advice as to whether this can be achieved in WordPress or know of a particular plugin that would allow a developer to fulfill this requirement?
Can you write code in WordPress to develop this functionality?
Any more information needed let me know!

A: Why not get the AD code and apply it to the User Meta then add a new Meta value for roaming based on the AD code in the 'travelled to' location.
The following should help you with this: https://developer.wordpress.org/reference/functions/add_user_meta/
Then you could add the following into a plugin or the functions.php file
    $location_code = US;
    $roaming_code = GB;
    // Consider an array for other locaitons such as $other_permitted = array("NL", "FR", "SP");
    add_user_meta( $user_id, '_location_code', $location_code);
    add_user_meta( $user_id, '_roaming_code', $roaming_code);

Prior to that you would need to determine the roaming code somehow from the Altranet but that is beyond the scope of this.


text:
Q: converting array into json I have a callback where i am getting the below console output when printing row.
output of row [ 'Name', 'Language' ]
output of row [ 'English', 'Fr' ]
output of row [ 'German', 'Gr' ]
output of row [ 'France', 'London' ]

I want to convert the above array into a valid json excluding the first row alone like this.
{
  "English" : "Fr",
  "German" : "Gr",
  "France" : "London"
}

  .on('record', function(row, index){
      console.log("output of row", row);
      var obj = {};
        row.forEach(function(column, index) {
          obj[row[index].trim()] = row[index].trim();
        })
        record.push(obj);
      }
    })

Additional Code
I am getting csv data which i am pushing it into a row each time. Below is the CSV Data and the array i am getting each time i read the csv data...
Language,Name
Fr,English
Gr,German
London,France

output of row [ 'Name', 'Language' ]
output of row [ 'English', 'Fr' ]
output of row [ 'German', 'Gr' ]
output of row [ 'France', 'London' ]

  cvcsv()
    .from.string(csv)
    .transform( function(row){
      row.unshift(row.pop());
      return row;
    })
    .on('record', function(row, index){
      console.log("output of row",row)

A: Assuming that you're getting array on consecutive calls of the callback() which is generating rows each time, you can collect the rows you need, parsing each one of them into a "key": "value" pair, adding it to an object. Then, you can use the JSON.stringify() method to turn your object into a valid JSON string.
Here's a working solution according to the code you provided:
var rows = {};

cvcsv().from.string(csv).transform(function(row){
    row.unshift(row.pop());
    return row;
}).on('record', function(row, index){
    if (index > 0) rows[row[0]] = row[1];
});

jsonRows = JSON.stringify(rows);

// Log to the console to check
console.log(jsonRows);

The result will be something like this:
{"English" : "Fr", "German" : "Gr", "France" : "London"}

A: Can you use JSON.stringify(yourArray)?
You can remove the first element from the array using shift:
yourArray.shift();

A: Here's a simplified method to help translate an array of array(size 2)
function addToObject(object, row, keyIndex, valueIndex) {
    object[row[keyIndex]] = row[valueIndex];
}

function test() {
    var data = [[ 'Name', 'Language' ],
                [ 'English', 'Fr' ],
                [ 'German', 'Gr' ],
                [ 'France', 'London' ]];
    var obj = {};

    for(var i = 1; i < data.length; i++)
        // NOTE data[i] can come from any place
        addToObject(obj, data[i], 0, 1);

    return obj;
}


text:
Q: sw-toolbox not working on gh-pages I made a simple AngularJS to-do app and used sw-toolbox. It is working fine on my localhost but when I am using it on gh-pages, few 404 errors are thrown on console and service worker is also showing 404 error while fetching scripts.
DEMO
CODE

A: The thrown error, TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script., tells us that the SW script itself was never found. The browser tried to fetch the script but was not able to since 404 was returned.
Very simple mistake. Your app tries to register the sw.js file from https://viveksharma619.github.io/sw.js while it's actually located in https://viveksharma619.github.io/PWA_simple_to_do/sw.js
The evil here is /sw.js - on your computer you were probably running the site in localhost:8080 when /sw.js was the real location but now the app lives inside PWA_simple_to_do folder and the sw.js script should be pointed to by either "sw.js" (current folder) or /PWA_simple_to_do/sw.js

A: Since gh pages are hosted using jekyll, jekyll version 3.3 by default ignores node_modules and vendor files. Hence, you won't be getting them when fetched from gh-pages. It will instead log "Failed to load resource" for sw-toolbox.js.
Your can bypass this by adding a simple .nojekyll file to the root of your github repository and your code will work just fine.


text:
Q: TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType I need the edges of the object to be painted in color. I know python very poorly, but my teacher gave this code and this is what happened with it.
def triangleArea(half_edge):

    a = len (half_edge)
    b = len (half_edge.edge_next)
    c = len (half_edge.edge_next.edge_next)

    s = (a + b + c) / 2
    area = math.sqrt(s * (s - a)*(s - b)*(s - c))
    return area

def angle(half_edge):

   v1 = half_edge.vertex
   v2 = prev(half_edge).vertex
   v3 = half_edge.edge_next.vertex

   angle = math.acos(((v2.co.x - v1.co.x)*(v3.co.x - v1.co.x)+(v2.co.y - v1.co.y)*(v3.co.y - v1.co.y)+(v2.co.z - v1.co.z)*(v3.co.z -v1.co.z))/(len(prev(half_edge))*len(half_edge)))

   if (angle > math.pi / 2):
       print (">90")
       return angle

def curvature(v):
    anglesSum = 0
    completeArea = 0
    for e in h_edge_list:
        if (v == e.vertex):
            start_edge = e
            anglesSum += angle(start_edge)
            completeArea += triangleArea(start_edge)

    half_edge = start_edge.edge_next
    cur = (2*math.pi - anglesSum)/completeArea
    color (half_edge, cur, 0.13, 0.29)#farbime z intervalu 0 az 2/3
    return cur

for e in h_edge_list:
    print (curvature(e.vertex))

bmesh.free()  # free and prevent further access

error in the last lines of code with the S operator
enter image description here

A: Your angle function returns None when this condition is False
if (angle > math.pi / 2):
   print (">90")
   return angle

This is how return in your current angle function looks like
def angle(half_edge):

   v1 = half_edge.vertex
   v2 = prev(half_edge).vertex
   v3 = half_edge.edge_next.vertex

   angle = math.acos(((v2.co.x - v1.co.x)*(v3.co.x - v1.co.x)+(v2.co.y - v1.co.y)*(v3.co.y - v1.co.y)+(v2.co.z - v1.co.z)*(v3.co.z -v1.co.z))/(len(prev(half_edge))*len(half_edge)))

   if (angle > math.pi / 2):
       print (">90")
       return angle
   return None

It returns None if the (angle > math.pi / 2) condition is False
Maybe you want to return the angle value, whatever the condition is (this makes the if statement unnecessary),
by reducing its indentation tab
def angle(half_edge):

   v1 = half_edge.vertex
   v2 = prev(half_edge).vertex
   v3 = half_edge.edge_next.vertex

   angle = math.acos(((v2.co.x - v1.co.x)*(v3.co.x - v1.co.x)+(v2.co.y - v1.co.y)*(v3.co.y - v1.co.y)+(v2.co.z - v1.co.z)*(v3.co.z -v1.co.z))/(len(prev(half_edge))*len(half_edge)))

   if (angle > math.pi / 2):
       print (">90")
   return angle

A: This if statement will return None if this condition is False
if (angle > math.pi / 2):
   print (">90")
   return angle

You'll want to add at least an else statement to your angle function.

A: The angle function is returning NoneType if the condition inside is not satisfied, and the += operator can't be used with NoneType values. Try returning 0 instead.
if (angle > math.pi / 2):
    print (">90")
    return angle
else:
    return 0


text:
Q: Copy phone's photo to app's directory I am developing an iPhone app that uses the user's photos to create a new special photo. I want to store the special photo within my app, but give the user the ability to change it by using the original photo.
What happens when the user deletes the original photo from their photo albums on the phone?
Should I save a copy of the original photo into my app, just in case? Or is there a better way?
My question is similiar to iOS save photo in an app specific album, but I want to know if this is the best way.

A: You can save a copy of photo/image in your application's document directory and access it from there when you want to use.
so if a person deletes it from original location, you will have a copy.


text:
Q: Django get_form_kwargs() not being called I have a view that has 3 sections. The top section is a search area. The bottom left section shows a list of objects and the right section shows the details of the selected object.
My view inherits from ListView and FormView.
class SearchViewMixin(FormView):
    template = 'template here'
    form_class = forms.SearchForm

    def get_form_kwargs(self):
        print 'This is not being called'
        kwargs = super(SearchViewMixin, self).get_form_kwargs()
        kwargs['search-units'] = self.request.search.unit_set.all()
        return kwargs

class ListView(ListView, SearchViewMixin):

    def get_queryset()...
    def get_context_data()....

The form view is this:-
class ReceiptSearchForm(BaseForm):

    obj_id = forms.IntegerField(required=False)

    unit = forms.ModelChoiceField(queryset=None, required=False, empty_label='Select a unit',
                                  widget=core.SelectPickerSearch)

    def __init__(self, *args, **kwargs):
        self.units = kwargs.pop('search-units', None)
        super(ReceiptSearchForm, self).__init__()
        self.fields['unit'].queryset = self.units

The problem is the get_form_kwargs method is not being called. The print statement is not getting executed
Since I am not writing or updating any data, I am just using a get method for the form.


text:
Q: right continuous representant of L^1 function Would someone know if a function in $L^1(\Omega)$ or more generally in $L^p(\Omega)$ must have a right continuous representant. $\Omega$ being a open set of $\mathbb{R}$.
Thankfully,

A: The answer is No. The following counter example will work.
Consider $f(x) = \frac{1}{\sqrt{x}}$ on $\Omega = (0,1)$ and $0$ otherwise. Let $\{r_n \}$ be any enumeration of rationals in the interval $(0, 1)$ and let $g(x) = \sum_1^{\infty} \frac{f(x-r_n)}{2^n}$. Its easy to prove that $g$ is integrable. However, $g$ is discontinuous at every point and unbounded in any interval and it remains so even after modification on any Lebesgue zero set!


text:
Q: How to download & install "COMODO" antivirus for Ubuntu 14.04 Lts Downloading and installing is not like windows in ubuntu. If we want to install something then we can only install from Ubuntu Software center or Terminal. But, I have been fed up, I tried but i am not getting command to download and install "comodo" antivirus by terminal and Comodo is not available in "ubuntu software center. If I am downloading Comodo from Comodo website, then I will not be able to install it further. But in window we can install anything by clicking right button and that file will install.
Please help and make me download and install COMODO antivirus for Ubuntu 14.04 LTS
I am looking best help from Gentle persons. I will really appreciate any help regarding the same.

A: First, you really don't need an antivirus for Ubuntu unless you're planning on dealing with windows files and/or systems.
You can download Comodo Antivirus from their website, and choose your architecture 32bit or 64bit. Once downloaded, just press Ctrl+Alt+T on your keyboard to open Terminal. When it opens, navigate to where the file was downloaded (probably the Downloads folder), and run the command(s) below:

sudo dpkg -i file_name.deb

I would recommend ClamAV. To install run in terminal

sudo apt-get install clamav
sudo freshclam
sudo clamscan

or you can use https://apps.ubuntu.com/cat/applications/clamav/


text:
Q: Trying to convert if else statement into ternary in javascript if (props.name == "Computer"){
        if (result == "Won"){
            result = "Lost";
        }
        else if (result == "Lost"){
            result = "Won";
        }
    }

Tried converting to ternary, but failed to do so. (Have no idea how to mix up the first and second line).
Also, not sure about "HAVE NO IDEA WHAT TO PUT" this spot.
result =="Won" ? result="Lost": result=="Lost" ? result="Won" : <HAVE NO IDEA WHAT TO PUT>;

A: result = (props.name == "Computer" ? (result == "Won" ? "Lost" : "Won") : "What you want when props.name is not Computer");

A: There are several different cases in your logic. Perhaps it's unclear to you. But this is what your attempts with the ternary operator have revealed:

*

*props.name could be something other than "Computer". What should be printed then?

*result could be something other than just "Won" or "Lost"
Anyway, let's build this ternary operator up:
result = props.name == "Computer" ? <YOUR CURRENT LOGIC> : <WHATEVER HAPPENS WHEN PROPS IS NOT COMPUTER>;

I am simply going to have the code return "result" as-is whenever we hit a case that was not defined by your if-else:
result = (props.name == "Computer" ? (result == "Won" ? "Lost" : "Won" ) : result);


text:
Q: Prevent tooltip from hiding when clicked, by tweaking events I have a content script running on Twitter, and I created tooltips by replicating the behaviour of them. I mean, a basic tooltip in Twitter needs a class js-tooltip and a data-original-title attribute. When the mouse is over the element, the class in is added to the element.
This is my injected element,

And this is my content script,
$('body').on('click', '.custom', function(e) {
    e.preventDefault();

    var elem = $(e.target);
    var a = elem.parent();

    a.attr('data-original-title', 'clicked');
    // forcing mouseenter did nothing
    elem.trigger('mouseenter')
}

Is there any way to prevent tooltip from hiding when clicked?


text:
Q: Some icons display differently VB6 I have a VB6 application which is running under Windows 10 with admin rights.  The application is made up of various things but the main form (frmMain) has several buttons with icons on it.  Each of the icon files used is a 32x32 ico file and the majority display as they have always done.  I am finding though that about 40% are showing differently - mainly quite big and blocky.  I can't figure out any difference in the properties of the buttons they are associated or the files so why do some change and some don't?

A: Maybe your icons use a different color depth or if they are loaded at runtime they are stored in different ImageLists?


text:
Q: GNU make builtin functions not working Tried to get GNU make 3.81 Built-in Function to work
but kept getting an error message.
I built a simple makefile:
FOO=bar

$(info $(FOO) $(origin FOO))

$(firstword $(origin FOO))

and ran it.
The first function works but second will not.
Error message is:
...
$ make -d
GNU Make 3.81
Copyright (C) 2006  Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.
This program built for i686-pc-linux-gnu
Reading makefiles...
Reading makefile `makefile'...
bar file
makefile:6: *** missing separator.  Stop.
...
First two functions work correctly so why is this happening? Am I not seeing something obvious or is this $(firstword) function not supported in this version of make?
Thanks for any help.

A: For the most part, a make file looks like one or more of these blocks:
target: [depends-on]...
        command to build
        another command

Where the command lines start with a tab.  Your error is complaining about finding 2 consecutive lines that look like target lines.
I've never seen the book you speak of, but either it is wrong or you are reading it wrong.  Try this:
FOO=bar

all:
        $(info $(FOO) $(origin FOO))
        echo '<' $(firstword $(origin FOO)) '>'

You need the echo on the last line because firstword is an ordinary substitution function, while info works more like a command.
I put the angle brackets on the firstword line just to show what was going on where.
Again, note that indented lines on Makefiles use tabs not spaces.

A: The firstword function is a text manipulation function. It takes text as its input, and returns text as its output. It does not write any messages or error output.
As such, when you call it, you are using it to build a makefile. Makefiles have a special syntax, just like any other programming language. When you put text into a makefile, it has to be structured in a particular way - you have to make a statement, or define a variable, or something.
For example, this is what a 'build rule' looks like:
output: input
    rule to produce output from input

You put a word into the makefile (the result of $(firstword)), so make assumes you are doing something - defining a variable or specifying a build rule. But you didn't follow up with any other words. Basically, your make program has a syntax error. :(


text:
Q: How to render bundle item product name with From/To: bundle product prices in price.phtml I have many bundle products that are made up of bundle items.
For example if I have a bundle product called "Farm Animals" made up of four bundle items:
duck - $1
chicken - $2
cow - $3
zebra - $4
I would like to display the following pricing information:
Farm Animals
From: 1$ duck To: $4 zebra

At the moment I've implemented:
            $selectionCollection = $_product->getTypeInstance(true)->getSelectionsCollection(
                $_product->getTypeInstance(true)->getOptionsIds($_product), $_product
            );

            $max_prod_name = '';
            $min_prod_name ='';
            $max_price = 0;
            $min_price = 999999;

            foreach($selectionCollection as $option) {
                $pr = Mage::getModel('catalog/product')->load($option->product_id);
                if ($pr->getPrice() > $max_prod_name) {
                    $max_price = $pr->getPrice();
                    $max_prod_name = $pr->name;
                } else if ($pr->getPrice() < $min_price) {
                    $min_price = $pr->getPrice();
                    $min_prod_name = $pr->name;
                }
            }

This is very resource intensive when rendering category list pages with the foreach loop executing multiple times per product.
Is there a more efficient way to do this?

A: You just need to avoid the extra load() within the loop.
$_product = $this->getProduct();

$selectionCollection = $_product->getTypeInstance(true)->getSelectionsCollection(
    $_product->getTypeInstance(true)->getOptionsIds($_product), $_product
);

$max_prod_name = '';
$min_prod_name ='';
$max_price = 0;
$min_price = 999999;

foreach ($selectionCollection as $option) {
    $price = $option->getPrice();
    if ($price > $max_price) {
        $max_price = $price;
        $max_prod_name = $option->getName();
    } else if ($price < $min_price) {
        $min_price = $price;
        $min_prod_name = $option->getName();
    }
}

A: All this data is already present in the tables catalog_product_bundle_selection and the catalog_product_flat. I guess the easiest way to go about is getting a collection via Mage::getModel('catalog/product->getCollection() and joining that with the catalog_product_bundle_selection table.
So where catalog_product_bundle_selection fields parent_product_id is your bundled product and the product_id equals the entity_id in the catalog_product_flat table. Then retrieve the name, price, special_price and special_price_from and special_price_to fields to determine the products current price. Once you have all of this you can determine what is the minimum and maximum prices.
Now I've never done this so I don't have any ready to go code lying around for you but if you manage to get this to work please let me know and maybe post some code. If you need any more help let me know.


text:
Q: Using Template in friend class First of all, my teacher asked mу to do something like that.
I have a class of two-dimensional array:
    #pragma once
    #include <iostream>
    #include "MyMaskedMassiv.h"

    template<typename T>
    class MyMaskedMassiv;

    template <typename T>
    class My2dMassiv{
    private:
        T* mas;
        int col;
        int str;
    public:
    ........
        friend class MyMaskedMassiv<T>;

        MyMaskedMassiv<T>& operator()(My2dMassiv<bool>& mask){
            MyMaskedMassiv<T> *maskMas = new MyMaskedMassiv<T>();
            maskMas->masiv = this;
            maskMas->mask = &mask;
            return *maskMas;
        }
    }

And as you can see another class "MyMaskedMassiv" that have links to the first one:
    #pragma once
    #include "My2dMassiv.h"

    template <typename U>
    class My2dMassiv;

    template <typename T>
    class MyMaskedMassiv{
    private:
        My2dMassiv<T> *masiv;
        My2dMassiv<bool> *mask;
    public:
        friend class My2dMassiv<T>;
        friend class My2dMassiv<bool>;

        MyMaskedMassiv(){
            masiv = nullptr;
            mask = nullptr;
        }

        MyMaskedMassiv& operator=(const T& el){
            int s = masiv->str;
            int c = masiv->col;

            for(int i=0; i<c; i++)
                for( int j=0; j<s; j++)
                    if( this->mask->mas[i*s + j] == true)
                        this->masiv->mas[i*s + j] = el;

        return *this;
        }
    }

So then I try to build I got an error:
    My2dMassiv.h:11:8: error: 'bool* My2dMassiv<bool>::mas' is private

    ../src/myproject/MyMaskedMassiv.h:27:36: error: within this context
             if( this->mask->mas[i*s + j] == true)

So.. what am I doing wrong?
If you want to see full code, check here: GIT

A: With
template <typename T>
class My2dMassiv{
    friend class MyMaskedMassiv<T>;
    // ...
};

Friendship is done only for matching T, I mean MyMaskedMassiv<int> can use private members of My2dMassiv<int> but not those from My2dMassiv<char>.
You want
template <typename T>
class My2dMassiv{
    template <typename U>
    friend class MyMaskedMassiv;
    // ...
};


text:
Q: laravel 5.6 random error "The page has expired due to inactivity" My Laravel 5.6 project was working well.
But suddenly when I try to login sometimes it says

The page has expired due to inactivity.

and sometimes it login properly with out any error. For example

*

*I go to page 127.0.0.1:8000/login...submit login form and get that error.

*I refresh the 127.0.0.1:8000/login page...submit...again error.

*I refresh the 127.0.0.1:8000/login page...submit and it works properly :|
Anybody know whats wrong with my project?!
this project works on my host without any problem and I have {{ csrf_field }} in my form.
I've tried to clear cache, view, route, config and deleting browser cache/cookie
and change SESSION_DRIVER=array but still got error.
UPDATE :
another thing that i should say is when it work properly and i login to the panel...when i submit any forms i got out of the panel and i should login again.

A: for localhost development open kernel.php inside Http folder and just comment this line :
\App\Http\Middleware\VerifyCsrfToken::class,

the csrf protection of laravel doesn't work properly on localhost. I already tried everything. just comment that, it's very annoying problem.

A: finaly...after 3 bad days focus on this issue...i find the answer and i hope it help someone else :

check your browser setting -> cookies and see how many cookies create
  when a user login.

by default laravel create 2 cookies when user login with names :

*

*"XSRF-TOKEN"

*"laravel_session"

these are ok but other cookies which you create manually or other installed packages creates cause this problem.
i was using eloquent-viewable package and it creates a cookie everytime i logged in.
i remove this package and then everything works properly :)


text:
Q: Angular 2: Local workspace file ('angular.json') could not be found After updating node, npm and angular/cli (from angular-cli), I am not able to run an existing project (which is based on angular2). I get the error:

Local workspace file ('angular.json') could not be found.

How I can fix this issue?
Simply renaming angular-cli.json to angular.json did fix the issue but resulted in another error:

Schema validation failed with the following errors:   Data path ""
  should NOT have additional properties(project).

angular-cli.json
{
 "project": {
   "version": "1.0.0-beta.18",
   "name": "client"
 },
 "apps": [
   {
     "root": "src",
     "outDir": "dist",
     "assets": [
       "assets",
       "favicon.ico"
     ],
     "index": "index.html",
     "main": "main-polymer.ts",
     "test": "test.ts",
     "tsconfig": "tsconfig.json",
     "prefix": "app",
     "mobile": false,
     "styles": [
       "main.scss"
     ],
     "scripts": [
       "../node_modules/jquery/dist/jquery.js",
       "../node_modules/signalr/jquery.signalR.js",
       "../node_modules/tether/dist/js/tether.js",
       "../node_modules/chart.js/dist/Chart.bundle.min.js"
     ],
     "environments": {
       "source": "environments/environment.ts",
       "dev": "environments/environment.ts",
       "prod": "environments/environment.prod.ts",
       "tristan": "environments/environment.tristan.ts",
       "azure": "environments/environment.azure.ts",
       "marius": "environments/environment.marius.ts"
     }
   }
 ],
 "addons": [],
 "packages": [],
 "e2e": {
   "protractor": {
     "config": "./protractor.conf.js"
   }
 },
 "test": {
   "karma": {
     "config": "./karma.conf.js"
   }
 },
 "defaults": {
   "styleExt": "scss",
   "prefixInterfaces": false,
   "inline": {
     "style": false,
     "template": false
   },
   "spec": {
     "class": false,
     "component": true,
     "directive": true,
     "module": false,
     "pipe": true,
     "service": true
   }
 }

}
package.json:
{
   "name": "client",
   "version": "0.0.0",
   "license": "MIT",
   "angular-cli": {},
   "scripts": {
      "start": "ng serve",
      "build": "ng build --env=prod",
      "lint": "tslint \"src/**/*.ts\"",
      "test": "ng test",
      "pree2e": "webdriver-manager update",
      "e2e": "protractor"
   },
   "private": true,
   "dependencies": {
   "@angular/common": "~2.1.0",
   "@angular/compiler": "~2.1.0",
   "@angular/core": "~2.1.0",
   "@angular/forms": "~2.1.0",
   "@angular/http": "~2.1.0",
   "@angular/material": "^2.0.0-alpha.10",
   "@angular/platform-browser": "~2.1.0",
   "@angular/platform-browser-dynamic": "~2.1.0",
   "@angular/router": "~3.1.0",
   "@types/hammerjs": "^2.0.33",
   "@types/moment": "^2.13.0",
   "@vaadin/angular2-polymer": "^1.0.0-beta5",
   "angular2-datatable": "^0.5.1",
   "angular2-moment": "^1.0.0-beta.rc.1",
   "bootstrap": "4.0.0-alpha.4",
   "chart.js": "^2.4.0",
   "core-js": "^2.4.1",
   "font-awesome": "^4.7.0",
   "glyphicons-halflings": "1.9.0",
   "hammerjs": "^2.0.8",
   "jquery": "^2.2.4",
   "jwt-decode": "^2.1.0",
   "lodash": "^4.16.6",
   "moment": "^2.15.2",
   "ng2-charts": "^1.4.1",
   "ng2-toastr": "^1.3.0",
   "rxjs": "5.0.0-beta.12",
   "signalr": "^2.2.1",
   "tether": "^1.3.7",
   "ts-helpers": "^1.1.1",
   "zone.js": "^0.6.23"
 },
 "devDependencies": {
   "@angular/cli": "^6.0.3",
   "@types/jasmine": "^2.2.30",
   "@types/lodash": "^4.14.50",
   "@types/moment": "^2.13.0",
   "@types/node": "^6.0.42",
   "@types/selenium-webdriver": "2.53.34",
   "angular-cli": "1.0.0-beta.18",
   "codelyzer": "1.0.0-beta.1",
   "jasmine-core": "2.4.1",
   "jasmine-spec-reporter": "2.5.0",
   "karma": "1.2.0",
   "karma-chrome-launcher": "^2.0.0",
   "karma-cli": "^1.0.1",
   "karma-jasmine": "^1.0.2",
   "karma-remap-istanbul": "^0.2.1",
   "protractor": "4.0.9",
   "ts-node": "1.2.1",
   "tslint": "3.13.0",
   "typescript": "~2.0.3"
 }
}


text:
Q: Different ways of using dplyr :: filter() to get the same output I am currently learning about the tidyverse package using Grolemund and Wickham's brilliant book, R4DS. While playing with the code, I realised that I was getting the same output using slight variations in how I wrote the arguments within the filter() verb. I would like to get confirmation on one of the following (a) if the output I am getting is the exact same for the variations (b) if the output is somehow different but I have not realised that (c) if the output is same but the way to get at it is different
The two variations are as follows:
library(nycflights13)
library(tidyverse)

#Variation 1
flights %>%
  filter(arr_delay >= 120) %>%
  filter(dest == "IAH" | dest == "HOU") %>%
  filter(carrier == "UA" | carrier == "AA" | carrier == "DL") %>%
  filter(month >= 7 & month <= 9)

#Variation 2
flights %>%
  filter(arr_delay >= 120,
         dest == "IAH" | dest == "HOU",
         carrier == "UA" | carrier == "AA" | carrier == "DL",
         month >= 7 & month <= 9)

For both, I get the same tibble output
# A tibble: 47 x 19
    year month   day dep_time sched_dep_time dep_delay arr_time sched_arr_time arr_delay carrier
   <int> <int> <int>    <int>          <int>     <dbl>    <int>          <int>     <dbl> <chr>
 1  2013     7     1     1310           1057       133     1551           1338       133 UA
 2  2013     7     1     1707           1448       139     1943           1742       121 UA
 3  2013     7     1     2058           1735       203     2355           2030       205 AA
 4  2013     7     2     2001           1735       146     2335           2030       185 AA
 5  2013     7     3     2215           1909       186       45           2200       165 UA
 6  2013     7     9     1937           1735       122     2240           2030       130 AA
 7  2013     7    10       40           1909       331      301           2200       301 UA
 8  2013     7    10     1629           1520        69     2048           1754       174 UA
 9  2013     7    10     1913           1721       112     2214           2001       133 UA
10  2013     7    17     1657           1446       131     2007           1745       142 UA
# ... with 37 more rows, and 9 more variables: flight <int>, tailnum <chr>, origin <chr>,
#   dest <chr>, air_time <dbl>, distance <dbl>, hour <dbl>, minute <dbl>, time_hour <dttm>

Apologies if there is some mistake in the question format. This is my first time posting here.

A: The two versions give exactly the same results. We can test this by storing the results of each and using the identical function:
test1 <- flights %>%
  filter(arr_delay >= 120) %>%
  filter(dest == "IAH" | dest == "HOU") %>%
  filter(carrier == "UA" | carrier == "AA" | carrier == "DL") %>%
  filter(month >= 7 & month <= 9)

test2 <- flights %>%
  filter(arr_delay >= 120,
         dest == "IAH" | dest == "HOU",
         carrier == "UA" | carrier == "AA" | carrier == "DL",
         month >= 7 & month <= 9)

identical(test1, test2)
#> [1] TRUE

They both benchmark similarly too:
library(microbenchmark)

microbenchmark(
  multi_filter = {
  flights %>%
    filter(arr_delay >= 120) %>%
    filter(dest == "IAH" | dest == "HOU") %>%
    filter(carrier == "UA" | carrier == "AA" | carrier == "DL") %>%
    filter(month >= 7 & month <= 9)
},

  single_filter = {
  flights %>%
    filter(arr_delay >= 120,
           dest == "IAH" | dest == "HOU",
           carrier == "UA" | carrier == "AA" | carrier == "DL",
           month >= 7 & month <= 9)
})

#> Unit: milliseconds
#>          expr     min       lq     mean   median       uq     max neval cld
#>  multi_filter 26.7920 27.33855 29.40675 27.70585 28.74525 40.6825   100  a
#> single_filter 32.0836 32.77430 34.41295 33.26740 33.67100 55.9700   100   b

Calling filter several times actually seems a little faster in this benchmark. However, the difference isn't massive. The flights data frame is large, with over 300,000 rows, so a few milliseconds in a data frame this big is unlikely to translate into a difference in most real-life applications.
In this case, I think it largely comes down to individual preference.


text:
Q: Parsing error: '=' expected in `import type` I am using create-react-app with TS and do import type but eslint complains in VS Code saying that Parsing error: '=' expected when hovering type in import type.  I'm using eslint, 6.7.2

A: Prettier
If you're using prettier rather than ESLint then the solutions is:
npm update prettier@latest
# Or yarn
yarn upgrade prettier@latest

Which installed prettier version "2.6.2". Which worked for me with import type { } from './types' syntax

A: UPDATE: The syntax is now supported by the latest versions of @typescript-eslint/parser and @typescript-eslint/eslint-plugin.

ESLint support for TS import type syntax is working in progress.
Issue: https://github.com/typescript-eslint/typescript-eslint/issues/1436
Pull request: https://github.com/typescript-eslint/typescript-eslint/pull/1465


text:
Q: XSLT Delete and Append Tags In my XML below, <Subject> is a sub-tag of <Subjects>. Additionally, <Subject> has a few sub-tags. What I need to do is A) remove all the sub-tags of <Subject> (they're duplicates of other fields we're merging this doc with later) and B) make the xref number the value of <Subject> so that it becomes <Subject_xref></Subject_xref>.
I attempted this using
<xsl:template match="Subject">
   <xsl:apply-templates select="*" mode="extra" />
</xsl:template>

but it did not change <Subject> and instead changed <SubjectPhone> to <SubjectPhone_Mobile>. What am I doing wrong, and how can I fix it?
XML
<?xml version="1.0" encoding="UTF-8"?>
<NORMDOC>
   <DOC>
      <DOCID>123456789</DOCID>
      <Subjects>
         <Subject stype="PER" xref="54815594140">
            <SubjectPhone type="Mobile">JANE</SubjectPhone>
         </Subject>
      </Subjects>
      <TXT>
         <S sid="123456789-SENT-075">For assistance contact <ENAMEX type="BANK" id="BAN-123456789-323">BANK OF FURY</ENAMEX> Law Enforcement Liaison at <IDEX type="PHONE" id="PHO-123456789-324">000-000-0000</IDEX> or <CYBEX type="EMAIL" id="EMA-123456789-325">email@bankoffury.com</CYBEX>.</S>
      </TXT>
   </DOC>
   <ENTINFO ID="ACC-123456789-013"
            TYPE="ACCOUNT"
            MENTION="MI checking account # 333222111000"/>
</NORMDOC>

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

<xsl:template match="/NORMDOC">
    <xsl:apply-templates select="DOC"/>
    <ENTINFOS>
        <xsl:apply-templates select="ENTINFO"/>
    </ENTINFOS>
</xsl:template>

<xsl:template match="TXT">
    <RAW_TXT>
        <xsl:value-of select="."/>
    </RAW_TXT>
    <xsl:copy>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

<xsl:template match="S">
    <xsl:copy>
        <xsl:apply-templates select="*" mode="extra"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="*" mode="extra">
    <xsl:element name="{name()}_{@type}">
        <xsl:apply-templates/>
    </xsl:element>
</xsl:template>

<xsl:template match="ENTINFO">
    <xsl:copy>
        <xsl:for-each select="@*">
            <xsl:element name="ENTINFO_{translate(name(), '-', '_')}">
                <xsl:value-of select="." />
             </xsl:element>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

<xsl:template match="/">
  <NORMDOC>
    <xsl:apply-templates/>
  </NORMDOC>
</xsl:template>

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

</xsl:stylesheet>

Actual Output
<NORMDOC>
   <DOC>
      <DOCID>123456789</DOCID>
      <Subjects>
         <Subject>
            <SubjectPhone>JANE</SubjectPhone>
         </Subject>
      </Subjects>
      <RAW_TXT>For assistance contact BANK OF FURY Law Enforcement Liaison at 000-000-0000 or email@bankoffury.com.</RAW_TXT>
      <TXT>
         <S>
            <ENAMEX_BANK>BANK OF FURY</ENAMEX_BANK>
            <IDEX_PHONE>000-000-0000</IDEX_PHONE>
            <CYBEX_EMAIL>email@bankoffury.com</CYBEX_EMAIL>
         </S>
      </TXT>
   </DOC>
   <ENTINFOS>
      <ENTINFO>
         <ENTINFO_ID>ACC-123456789-013</ENTINFO_ID>
         <ENTINFO_TYPE>ACCOUNT</ENTINFO_TYPE>
         <ENTINFO_MENTION>MI checking account # 333222111000</ENTINFO_MENTION>
      </ENTINFO>
   </ENTINFOS>
</NORMDOC>

Goal
<NORMDOC>
   <DOC>
      <DOCID>123456789</DOCID>
      <Subjects>
         <Subject_xref>54815594140</Subject_xref>
      </Subjects>
      <RAW_TXT>For assistance contact BANK OF FURY Law Enforcement Liaison at 000-000-0000 or email@bankoffury.com.</RAW_TXT>
      <TXT>
         <S>
            ...
         </S>
      </TXT>
   </DOC>
   <ENTINFOS>
      <ENTINFO>
         ...
      </ENTINFO>
   </ENTINFOS>
</NORMDOC>

A: Just add the following template to the set:
<xsl:template match="Subject">
  <Subject_xref><xsl:value-of select="@xref"/></Subject_xref>
</xsl:template>

This does also remove all children of <Subject> elements.


text:
Q: how to Save the Child Form textbox Values in MdiParent form Button Click Event? I inserted mdiparent form in my project.It contains one child form(Customer Data Entry) with textboxes.In parent form one toolstrip button(Save Record).At the time of pressing the Save Record Button I want to Save the Customer Data Entry form Values(Child form Text Box values) in to Database.

A: You can create public getter properties in you child form, accessing the respective text-box.
So you can access the property values from text-boxes, when you have the form's object initialized & not disposed.


text:
Q: Run console Asynchronously to result a more efficient output class CommandLine2
{
static void Main(string[] args)
{
    System.Console.WriteLine("Number of command line parameters = {0}", args.Length);

    foreach (string s in args)
    {
        System.Console.WriteLine(s);
    }
}
}

This is an example of the console app that will fire the task from a WCF.
I got a project that fires a set of check on csv files line by line and I am creating a console app that will do the task. What I need is to run this async so it will hit each row and after say around few seconds end the task. I want it to be efficient that's why. I will be using a WCF so if you know a way to run the command async please guide me.

A: If you're using WCF, you should be able to make the client server reference include Task-based asynchronous client calls.
You'd then just need to call the operation(s) asynchronously.
Given that you're working in a console application, however, you may not want to use async/await, and instead just fire off the operations, and use Task.WaitAll or similar.  The problem with  async operations in a console app is that there is no current synchronization context, so you need to be careful not to let the application shut down until your async work is completed.


text:
Q: How can I extract those bits from 16bit LE data? I've got 16 bit data in the following LE bit format:
B4 | B5 | C1 | C2 | C3 | D1 | D2 | D3
A1 | A2 | A3 | A4 | A5 | B1 | B2 | B3
Each letter represents one data category that I want to extract and make a seperate image from.
Using this python code, I managed to create an image from the A layer, but I did not succeed in extracting B, C and D.
# using numpy and PIL
data = np.fromfile(i, dtype=np.dtype('<u2')).reshape(size, size)
A = ((data & 31) - 1).astype('uint8')
image_A = Image.fromarray(A)

Does anyone know how that would work?
Sample data (512x512), Output A

A: Using a dictionary of bitmasks and some bit twiddling to compute the requisite shifts:
import numpy as np
from PIL import Image

def extract_mask(arr, mask):
    # bit twiddling magic (count trailing zeros)
    shift = int(np.log2(mask & -mask))
    return (arr & mask) >> shift

masks = {
    "A": 0b000_000_00000_11111,
    "B": 0b000_000_11111_00000,
    "C": 0b000_111_00000_00000,
    "D": 0b111_000_00000_00000,
}

filename = "512x512.buffer"
size = 512
data = np.fromfile(filename, dtype="<u2").reshape(size, size)
images = {
    k: Image.fromarray(extract_mask(data, mask).astype(np.uint8))
    for k, mask in masks.items()
}

A: This seems an easy way to do it:
import numpy as np
from PIL import Image

# Load image as 16-bit LE and reshape
size = 512
data = np.fromfile('512x512.buffer', dtype='<u2').reshape(size, size)

A = Image.fromarray(((data      ) & 31).astype(np.uint8))
B = Image.fromarray(((data >>  5) & 31).astype(np.uint8))
C = Image.fromarray(((data >> 10) &  7).astype(np.uint8))
D = Image.fromarray(((data >> 13) &  7).astype(np.uint8))


text:
Q: initializing View from a different ViewModel in MVVM I am working on a WPF map application and I a View and a ViewModel in my MVVM WPF App. The user clicks on the button in the View (lets call it View#1) and then the ViewModel adds the map to the window. However there is another View (lets call that View#2) in my App which is responsible for the map manipulation. I cannot add the controls used in View#2 to View#1 because View#1 is just a listbox with different map names.

I want View#2 to get initialized and shown on the screen from the ViewModel#1.

Is this approach against good MVVM programming practice to initialize a View from a different ViewModel? If yes then what is the correct way of dealing with these situations.
Thanks

A: Normally you inject you viewmodel into your view, so you can only have one view on one view model.
But you could have a View#0 that contains both View#1 and View#2.
The ViewModel#0 would have 2 properties containing ViewModel#1 and ViewModel#2


text:
Q: C# Action parameters in extension methods I'm using DevExpress to build up grids, but I'm trying to build helper methods to simplify the amount of code to generate.  For instance, the following simple example produces a grid column:
settings.Columns.Add(column =>
{
    column.FieldName = "StatusId";
    column.Caption = "Status";
    column.Width = Unit.Percentage(20);
});

I want to use extension methods to get the following, which allows the developer to simplify the basic work but still get access to the advanced settings:
settings.AddColumn("StatusId", "Status", column =>
{
    column.Width = Unit.Percentage(20);
});

I could just return a column variable, but that means having to create a new variable name for each column, which is why I wanted to maintain the Action approach.
What would my extension method look like to support this format?  It would need to create the column with the default settings applied, and add it to the columns collection.  This is as far as I get:
public static void AddColumn(this GridViewSettings settings, string fieldName, string caption, Action<MVCxGridViewColumn> column)
{
    //...?
}

A: public static void AddColumn(
    this GridViewSettings settings,
    string fieldName,
    string caption,
    Action<MVCxGridViewColumn> action
)
{
    settings.Columns.Add(column =>
    {
        column.FieldName = fieldName;
        column.Caption = caption;
        action(column);
    });
}

A: You are very close.  I would make the action parameter optional, so that the developer could leave it out unless they needed it.
public static void AddColumn(this GridViewSettings settings, string fieldName, string caption, Action<MVCxGridViewColumn> additionalConfig = null)
{
    var column = new MVCxGridViewColumn
    {
        FieldName = fieldName,
        Caption = caption
    };

    if (additionalConfig != null)
    {
        additionalConfig(column);
    }

    settings.Columns.Add(column);
}

Call it with
settings.AddColumn("StatusId", "Status", column =>
{
    column.Width = 20;
});

or
settings.AddColumn("StatusId", "Status");


text:
Q: Jump if touching the ground I have a sphere which jumps after I touch the screen. In my previous code, it was jumping infinite time, but in the current code, it is jumping only once. I want the sphere to jump every time I touch the screen, but the main issue is, I want it to jump only when it is on the ground. I tried this...
public float speed;
public Rigidbody rb;
private bool thrown ;

void Start()
{
    rb = GetComponent<Rigidbody>();
}

void Update()
{
    if (
        !thrown && (
            (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended ) ||
            Input.GetMouseButtonDown(0) )
    )
    {
        rb.isKinematic = false;
        rb.AddForce (new Vector3(0.0f, 0.5f, 0.2f));
        thrown = true ;

    }
}
void OnTriggerEnter(Collider other)
{
    if (other.gameObject.CompareTag ("player"))
    {
        thrown = true;
    }
}

I think I am doing something wrong in ontriggerEnter or may be somewhere else. Please help me with it.


text:
Q: AVRO schema evolution adding optional column with default fails deserialization When reading through avro documentation, for example [1], I understood, that schema evolution is supported, and if I added column with specified default, it should be backwards compatible (and even forward when I remove it again). Sounds great, so I added column defined as:
        {
          "name": "newColumn",
          "type": ["null","string"],
          "default": null,
          "doc": "something wrong"
        }

and try to consumer some topic having this schema from beginning, it fails with message:
Caused by: java.lang.ArrayIndexOutOfBoundsException: 5
    at org.apache.avro.io.parsing.Symbol$Alternative.getSymbol(Symbol.java:424)
    at org.apache.avro.io.ResolvingDecoder.doAction(ResolvingDecoder.java:290)
    at org.apache.avro.io.parsing.Parser.advance(Parser.java:88)
    at org.apache.avro.io.ResolvingDecoder.readIndex(ResolvingDecoder.java:267)
    at org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:179)
    at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:153)
    at org.apache.avro.generic.GenericDatumReader.readField(GenericDatumReader.java:232)
    at org.apache.avro.generic.GenericDatumReader.readRecord(GenericDatumReader.java:222)
    at org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:175)
    at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:153)
    at org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:179)
    at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:153)
    at org.apache.avro.generic.GenericDatumReader.readField(GenericDatumReader.java:232)
    at org.apache.avro.generic.GenericDatumReader.readRecord(GenericDatumReader.java:222)
    at org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:175)
    at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:153)
    at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:145)
    at tech.allegro.schema.json2avro.converter.JsonAvroConverter.convertToJson(JsonAvroConverter.java:83)

to give a little bit more information. Avro schema defines one top level type, having 2 fields. String describing type of message, and union of N types. All N-1, non-modified types can be read, but one updated with optional, default-having column cannot be read. I'm not sure if this design is strictly speaking correct, but that's not the point (feel free to criticise and recommend better approach!). I'm after schema evolution, which seems not to be working.
Am I doing something wrong?
[1] https://docs.oracle.com/database/nosql-12.1.3.4/GettingStartedGuide/schemaevolution.html#changeschema-rules
EDIT:
and if we alter type definition to:
"type": "string",
"default": ""

it still does not work and generated error is:
Caused by: org.apache.avro.AvroRuntimeException: Malformed data. Length is negative: -1
    at org.apache.avro.io.BinaryDecoder.doReadBytes(BinaryDecoder.java:336)
    at org.apache.avro.io.BinaryDecoder.readString(BinaryDecoder.java:263)
    at org.apache.avro.io.ResolvingDecoder.readString(ResolvingDecoder.java:201)
    at org.apache.avro.generic.GenericDatumReader.readString(GenericDatumReader.java:422)
    at org.apache.avro.generic.GenericDatumReader.readString(GenericDatumReader.java:414)
    at org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:181)
    at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:153)
    at org.apache.avro.generic.GenericDatumReader.readField(GenericDatumReader.java:232)
    at org.apache.avro.generic.GenericDatumReader.readRecord(GenericDatumReader.java:222)
    at org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:175)
    at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:153)
    at org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:179)
    at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:153)
    at org.apache.avro.generic.GenericDatumReader.readField(GenericDatumReader.java:232)
    at org.apache.avro.generic.GenericDatumReader.readRecord(GenericDatumReader.java:222)
    at org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:175)
    at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:153)
    at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:145)
    at tech.allegro.schema.json2avro.converter.JsonAvroConverter.convertToJson(JsonAvroConverter.java:83)

what code does lead to given failures:
BinaryDecoder binaryDecoder = DecoderFactory.get().binaryDecoder(avro, (BinaryDecoder)null);
GenericRecord record = (GenericRecord)(new GenericDatumReader(schema)).read((Object)null, binaryDecoder);

A: There is usually some miss-understanding regarding to schema evolution and how it works.   When you evolution a schema it does not mean that you don't need the "writer" schema to read the avro data. For this  purposes you should be using the following constructor GenericDatumReader
public GenericDatumReader(Schema writer,
                  Schema reader)

As you can see, writer schema (schema used to serialize the avro data) and reader schema ( your "evolution" schema) must be present. There are several libraries/tools (Hive, Spark) that abstract this but it is only possible because the file itself contains the schema (non schema-less)


text:
Q: Turning off iPad & taking screen shots Since doing the last upgrade/update on my iPad, I can no longer lock it or take screens shots. Now because I can't lock it, I can't back it up. Why is this happening & what need to be done so I can go back to redoing both?

A: I had a similar issue with my iPad. What version of iOS or iPadOS is it running? A fix for me was going to Recovery Mode, and using connecting the device to your Mac or Windows PC and then using iTunes. When the dialog appears saying that there is a problem with your device, select Update. You can also restore a back up. Here is an article: https://support.apple.com/en-us/HT211078. This covers recovering the passcode but the steps mentioned can help solve this.


text:
Q: Getting multiple types from same Morphia Query I have a Mongo Collection with multiple different kinds of objects in it.  All of these classes form a tree that inherits from a common abstract base called "Event".  There are many different kinds of Events, and I put them all into the same collection.
I want to write a Morphia query to get all the Events, and I want them deserialized back into their original Java classes.
I was hoping that I could do this query, but it does not seem to work.  I get 0 objects.
Query query = mongo.createQuery(Event.class);
List<Event> events = query.asList();

What is the correct way to do this?
Thank you
Peter

A: Is Event abstract?  The generated query is going to include the classname which will never match the subclasses.  You seem to be running in to this open issue.


text:
Q: Android Firebase - setPersistenceEnabled(true) crashing the app So I was just trying out Firebase to update Toolbar label of activities from realtime database. I am getting the following error:
12-21 00:25:19.890 10295-10295/com.xlr8labs.FirebaseAuth E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.xlr8labs.FirebaseAuth, PID: 10295
                                                                       java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xlr8labs.FirebaseAuth/com.xlr8labs.FirebaseAuth.RegisterActivity}: com.google.firebase.database.DatabaseException: Calls to setPersistenceEnabled() must be made before any other usage of FirebaseDatabase instance.
                                                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2341)
                                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2393)
                                                                           at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1324)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:110)
                                                                           at android.os.Looper.loop(Looper.java:193)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:5295)
                                                                           at java.lang.reflect.Method.invokeNative(Native Method)
                                                                           at java.lang.reflect.Method.invoke(Method.java:515)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
                                                                           at dalvik.system.NativeStart.main(Native Method)
                                                                        Caused by: com.google.firebase.database.DatabaseException: Calls to setPersistenceEnabled() must be made before any other usage of FirebaseDatabase instance.
                                                                           at com.google.firebase.database.FirebaseDatabase.zzhM(Unknown Source)
                                                                           at com.google.firebase.database.FirebaseDatabase.setPersistenceEnabled(Unknown Source)
                                                                           at com.xlr8labs.FirebaseAuth.RegisterActivity.onCreate(RegisterActivity.java:35)
                                                                           at android.app.Activity.performCreate(Activity.java:5264)
                                                                           at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
                                                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
                                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2393)
                                                                           at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1324)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:110)
                                                                           at android.os.Looper.loop(Looper.java:193)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:5295)
                                                                           at java.lang.reflect.Method.invokeNative(Native Method)
                                                                           at java.lang.reflect.Method.invoke(Method.java:515)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
                                                                           at dalvik.system.NativeStart.main(Native Method)

Even though I'm using setPersistenceEnabled() before calling any other methods on my database instance, I'm still getting this error. Here is my Activity.java code:
public class RegisterActivity extends AppCompatActivity {
 private FirebaseDatabase mFirebaseInstance;
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        // ------------------ Update activity label from database in realtime ------
        mFirebaseInstance = FirebaseDatabase.getInstance();
        mFirebaseInstance.setPersistenceEnabled(true);
        mFirebaseInstance.getReference("RegisterLabel").keepSynced(true);
        mFirebaseInstance.getReference("RegisterLabel").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Log.e(LOG_TAG,"Register label changed");
                String appTitle = dataSnapshot.getValue().toString();
                getSupportActionBar().setTitle(appTitle);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        // ---------------------------------------------------------------------------

What is causing the crash. I'm using the exact same snippet on two other activities...

A: This part mFirebaseInstance.setPersistenceEnabled(true); should be just in first Activity. It's shouldn't be called more than once.
Better solution would be to put that line in onCreate method of your Application class. You can read more about it here.

A: Remove the line mFirebaseInstance.setPersistenceEnabled(true); from your RegisterActivity class.
Make a custom class which should extend Application and write it there.
Example :
public class JustExample extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        if (!FirebaseApp.getApps(this).isEmpty())
        {
            FirebaseDatabase.getInstance().setPersistenceEnabled(true);
        }
    }
}

A: boolean flag = true; //before onCreate() method

//inside onStart() Method
if(flag)
{
  firebaseDatabase.setPersistenceEnabled(true);
  flag = false;
}

A: You can use a Model class and use Method inside it such as the one mentioned below.
public class DatabaseUtility {

    private static FirebaseDatabase database;

    public static FirebaseDatabase getDatabase(){
        if(database==null){
            database=FirebaseDatabase.getInstance();
            database.setPersistenceEnabled(true);
        }
        return database;
    }
}

This will return database instance and you can use database.getReference(); method to get Root reference. This will also save some time if the database object is already present.

A: You just simply uninstall the previously installed app. And let it install the fresh app. It will resolve the problem.


text:
Q: Eclipse eRCP command framework - Unable to update command label dynamically I've scoured the web for the entire day trying to find an example on how to implement what I read concerning changing a command label dynamically here:
http:// wiki.eclipse.org/Platform_UI_Command_Design#Issue_102_-_Comm ands_implementation_of_label_changing
I have the a command defined in my plugin.xml that uses the suggested schema:
<command
     description="Hoping to change my state"
     id="my.commandWithState"
     name="Command Wtih State">
  <state
        class="org.eclipse.jface.menus.TextState"
        id="NAME"/>
</command>

In my handler, I have tried a lot of variations (including calling "getValue" before trying to set it in hopes of forcing a load to be called), but basically the gist is:
public Object execute(final ExecutionEvent pEvent) throws ExecutionException {
        pEvent.getCommand().getState("my.commandWithState").setValue("UPDATED!");
        return null;
    }

The state value itself is updated, but not persisted. I specified a style of "push" in the menuContribution area of my plugin.xml and the text on the command is always "Command With State" since I did not specify a label (though i expected it to change...)
I'm using Eclipse 3.6 so I assume I have the updates that supposedly allow this from 3.3.
The only way I have been able to set the text on the command ui object is to have my handler implement IElementUpdater like I'm working with a ToggleState. This allows me to change the text a total of 1 time, when I first start the product.
I'm about to tear my hair out.
1) The command "label" is not updated and
2) the state value is not persisted even though TextState extends PersistedState.
What d>_


text:
Q: Dry run for analyzing wake-on-lan problems Note I had wake-on-lan working on an older kernel but after an upgrade, it now fails to wake up the machine.
I read in a forum to open a terminal and enter journalctl -f on the machine to wake up and enter wakeonlan <mac_address> on a different machine. (If I listen with nc -ul -p 9 I do receive the magic packet.)
Q1 Should there be any observable output from wakeonlan in the journal?
Q2 Is there some kind of dry run to troubleshoot wake-on-lan problems?


text:
Q: Subscript out of range while setting the range By the line
Set srchrange = Workbooks(wipreport).Worksheets("1. WIP report").Range("B15:B")
I got the error Subscript out of range. wipreport is chosen above from the file. The workbook for sure has the Sheet "1. WIP report". I copied it. Workbooks BPM-Tool is already opened but I have no error by this line of code.
I can not even try if vlookup works.
With Application.FileDialog(msoFileDialogFilePicker)
        'Makes sure the user can select only one file
        .AllowMultiSelect = False
        .Title = "Select WIP Report"
        .ButtonName = "OK"
        'Filter to just the following types of files to narrow down selection options
        .Filters.Add "Excel Files", "*.xlsx; *.xlsm; *.xls; *.xlsb", 1
        'Show the dialog box
        .Show

        'Store in fullpath variable
        wipreport = .SelectedItems.Item(1)
    End With

Workbooks.Open wipreport

Dim lookFor As Range
Dim srchrange As Range

Set lookFor = Workbooks("BPM-Tool.xlsm").Worksheets("BPM-Report").Cells(10, 2)

Set srchrange = Workbooks(wipreport).Worksheets("1. WIP report").Range("B15:B")

    lookFor.Offset(0, 317).Value = Application.VLookup(lookFor, srchrange, 18, False)

A: Try this:
With Application.FileDialog(msoFileDialogFilePicker)
        'Makes sure the user can select only one file
        .AllowMultiSelect = False
        .Title = "Select WIP Report"
        .ButtonName = "OK"
        'Filter to just the following types of files to narrow down selection options
        .Filters.Add "Excel Files", "*.xlsx; *.xlsm; *.xls; *.xlsb", 1
        'Show the dialog box
        .Show

        'Store in fullpath variable
        wipreport = .SelectedItems.Item(1)
    End With

Dim wb As Workbook
Set wb = Workbooks.Open(wipreport)

Dim lookFor As Range
Dim srchrange As Range

Set lookFor = Workbooks("BPM-Tool.xlsm").Worksheets("BPM-Report").Cells(10, 2)

Set srchrange = wb.Worksheets("1. WIP report").Range("B15:B1000")

    lookFor.Offset(0, 317).Value = Application.VLookup(lookFor, srchrange, 18, False)

wipreport is a String not a Workbook object, that's why you are getting an error.

A: Workbooks.Open takes the full file name e.g. C:\temp\myfile.xlsx
Workbooks() takes file name only e.g. myfile.xlsx
You can use this code to get the workbook object and then use it:
' Get the workbook object
Dim wk As Workbook
Set wk = Workbooks.Open(wipreport)

' Use the workbook object
wk.Worksheets("1. WIP report").Range ("B15:B")


text:
Q: Common legend for subplot matplotlib I'm creating a plot using matplotlib and it seems that I stucked with one problem.
I draw 3 subplots and I want to get common legend for all of them
fig, (ax, ax2, ax3) = plt.subplots(3, 1, sharex=True)
ax.plot(FRAME1['T1'],FRAME1['Num'], marker = 'o', label='1')
ax2.plot(FRAME3['T1'],FRAME3['Num'], marker = 'o', label='2',color='r')
ax2.plot(FRAME4['T1'],FRAME4['Num'], marker = 'o', label='3',color='turquoise')
ax3.plot(FRAME2['T1'],FRAME2['Num'], marker = 'o', label='4',color='g')

ax.set_ylim(-118, -116.5)
ax3.set_ylim(-136, -135)

plt.legend( (ax,ax2,ax3),loc="upper left", bbox_to_anchor=[0, 1],
           ncol=2, shadow=True, title="Legend", fancybox=True)

I have used the legend instance but it shows legen only on the last subplot.

A: Of course you need to show the legend on one of the subplots. It's your decision which one you chose.
In order to show all four lines in the legend, you need to provide a reference to the lines to the legend
plt.legend(handles = [line1, line2, ...])

See also the Matplotlib legend guide.
So here is a working example
import numpy as np
import matplotlib.pyplot as plt

x = np.random.randint(0,12,size=(12,4))
y = np.random.randint(0,8,size=(12,4))

fig, (ax, ax2, ax3) = plt.subplots(3, 1, sharex=True, figsize=(5,5))

l, = ax.plot(x[:,0],y[:,0], marker = 'o', label='1')
l2, =ax2.plot(x[:,1],y[:,1], marker = 'o', label='2',color='r')
l3, =ax2.plot(x[:,2],y[:,2], marker = 'o', label='3',color='turquoise')
l4, =ax3.plot(x[:,3],y[:,3], marker = 'o', label='4',color='g')

plt.legend( handles=[l, l2, l3, l4],loc="upper left", bbox_to_anchor=[0, 1],
           ncol=2, shadow=True, title="Legend", fancybox=True)

plt.show()


text:
Q: CMD window is too big for the output I have a build operation running in cmd and it outputs information about processes and stack traces if there are any errors.
But the CMD window is way bigger than the output so normal scrolling (like with a scroll wheel) moves too slowly. And if you grip the scrollbar handle it becomes overly sensitive, moving too many lines at once making it difficult to find the beginning of the stack trace.
How can I force the window to vertically adjust to the output?
For example, you can open a new cmd window and see what I'm talking about:

The handle is tiny, so if you grab it and move it, it goes too fast and skips all the important output. In simpler terms, I'd like to force the window to adjust to the size of the output so the handle is bigger.

A: You can do this running your command 2 times:
1. Count lines in the output command:
>your command |find/v /c ""
2. Increase +10 using for /f loop and set /a
for /f %i in (`your command^|find/v /c ""`)do set /a "_lines+=%~i+10"
3. Define your mode con: accordingly with mode con: cols=135 lines=%_lines%
...)do set /a ...  & call mode con: cols=135 lines=%_lines% ...
4. Run your command again
for /f %i in ('run your command ^|find/c /v ""')do set /a "_lines+=%~i+10" & call mode con: cols=135 lines=%_lines% && run your command again

*

*Example:

for /f %i in ('robocopy /?^|find/v /c ""')do set /a "_lines+=10+%i" & call mode con: cols=135 lines=%_lines% && robocopy /?

*

*Alternative command: your command |more /E
robocopy /? | more /e

*

*If extended features are enabled, (/E) the following
keystrokes can be used at the: -- More -- prompt:
      <space>   Display next page
      <return>  Display next line
      Q         Quit
      P n       Display next n lines
      S n       Skip next n lines
      F         Display next file
      =         Show line number
      ?         Show help line

*

*Some further reading:

[√] |Mode /?
[√] |More /?
[√] |find /?
[√] For Loop
[√] For /F Loop
[√] Escape Characters


text:
Q: React material-table is not displaying table icons I have a project where I have to use a table. I am using material-table. But I can't seem to get it to look right. The icons that are needed for the table are not showing and instead I get some placeholder texts.
Here is the code I am using to show the table. I have material-table and material-icons installed in the project.
class RegistrationList extends Component {
  state = {
    registrations: [],
  };

  infoButtonHandler(id) {}

  componentDidMount() {
    axios.get("http://localhost:3030/api/items").then((res) => {
      let registrations = [];
      res.data.forEach((registration) => {
        let childeren = "";
        for (let i = 0; i < registration.childeren.length; i++) {
          childeren += registration.childeren[i].name;
          if (i + 1 !== registration.childeren.length) {
            childeren += ", ";
          }
        }
        registrations.push({
          _id: registration._id,
          name: registration.name,
          childeren: childeren,
          street: registration.street,
          houseNumber: registration.houseNumber,
          city: registration.city,
          postalCode: registration.postalCode,
        });
      });
      this.setState({ registrations: registrations });
    });
  }

  rowClickedHandler(rowData) {
    this.props.history.push("/RegistrationDetail/" + rowData._id);
  }

  render() {
    let table = (
      <MaterialTable
        title="Overzicht"
        columns={[
          { title: "familienaam", field: "name" },
          { title: "kinderen", field: "childeren" },
          { title: "dorp", field: "city" },
          { title: "postcode", field: "postalCode" },
          { title: "straat", field: "street" },
          { title: "nr.", field: "houseNumber" },
        ]}
        data={this.state.registrations}
        options={{
          search: true,
        }}
        onRowClick={(event, rowData) => this.rowClickedHandler(rowData)}
      />
    );
    return <div>{table}</div>;
  }
}

A: this approach is working for me
 import DeleteIcon from '@material-ui/icons/Delete';

actions={[

        rowData => ({
          icon: DeleteIcon,
          tooltip: 'Delete User',
          onClick: (event, rowData) => confirm("You want to delete " + rowData.name),
          disabled: rowData.birthYear < 2000
        })
      ]}

A: It says right on the site what to do material-table
Add material icons
There are two ways to use icons in material-table either import the material icons font via html OR import material icons and use the material-table icons prop.
HTML
<link
  rel="stylesheet"
  href="https://fonts.googleapis.com/icon?family=Material+Icons"
/>

OR
Import Material icons
Icons can be imported to be used in material-table offering more flexibility for customising the look and feel of material table over using a font library.
To install @material-ui/icons with npm:
npm install @material-ui/icons --save

To install @material-ui/icons with yarn:
yarn add @material-ui/icons

If your environment doesn't support tree-shaking, the recommended way to import the icons is the following:
import AddBox from "@material-ui/icons/AddBox";
import ArrowDownward from "@material-ui/icons/ArrowDownward";

If your environment support tree-shaking you can also import the icons this way:
import { AddBox, ArrowDownward } from "@material-ui/icons";

Note: Importing named exports in this way will result in the code for every icon being included in your project, so is not recommended unless you configure tree-shaking. It may also impact Hot Module Reload performance. Source: @material-ui/icons
Example
import { forwardRef } from 'react';

import AddBox from '@material-ui/icons/AddBox';
import ArrowDownward from '@material-ui/icons/ArrowDownward';
import Check from '@material-ui/icons/Check';
import ChevronLeft from '@material-ui/icons/ChevronLeft';
import ChevronRight from '@material-ui/icons/ChevronRight';
import Clear from '@material-ui/icons/Clear';
import DeleteOutline from '@material-ui/icons/DeleteOutline';
import Edit from '@material-ui/icons/Edit';
import FilterList from '@material-ui/icons/FilterList';
import FirstPage from '@material-ui/icons/FirstPage';
import LastPage from '@material-ui/icons/LastPage';
import Remove from '@material-ui/icons/Remove';
import SaveAlt from '@material-ui/icons/SaveAlt';
import Search from '@material-ui/icons/Search';
import ViewColumn from '@material-ui/icons/ViewColumn';

const tableIcons = {
    Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />),
    Check: forwardRef((props, ref) => <Check {...props} ref={ref} />),
    Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
    Delete: forwardRef((props, ref) => <DeleteOutline {...props} ref={ref} />),
    DetailPanel: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
    Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />),
    Export: forwardRef((props, ref) => <SaveAlt {...props} ref={ref} />),
    Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />),
    FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />),
    LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />),
    NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
    PreviousPage: forwardRef((props, ref) => <ChevronLeft {...props} ref={ref} />),
    ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
    Search: forwardRef((props, ref) => <Search {...props} ref={ref} />),
    SortArrow: forwardRef((props, ref) => <ArrowDownward {...props} ref={ref} />),
    ThirdStateCheck: forwardRef((props, ref) => <Remove {...props} ref={ref} />),
    ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />)
  };

<MaterialTable
  icons={tableIcons}
  ...
/>

A: Upgrade material UI to @material-ui/core@4.2.1 by yarn add @material-ui/core@4.2.1 and hopefully, it will work

A: To get them working, I added them manually.

A: import and add icon to tableIcons.js file
import AddIcon from '@mui/icons-material/Add';

AddNew: forwardRef((props, ref) => <AddIcon {...props} ref={ref} />),

import into the file where you need the icon
import tableIcons from "components/Table/tableIcons";

use with bellow code where needed
 icon: tableIcons.AddNew,


text:
Q: Add column value in the spark dataset on the basis of a condition public class EmployeeBean implements Serializable {

    private Long id;

    private String name;

    private Long salary;

    private Integer age;

    // getters and setters

}

Relevant spark code:
SparkSession spark = SparkSession.builder().master("local[2]").appName("play-with-spark").getOrCreate();
List<EmployeeBean> employees1 = populateEmployees(1, 10);

Dataset<EmployeeBean> ds1 = spark.createDataset(employees1, Encoders.bean(EmployeeBean.class));
ds1.show();
ds1.printSchema();

Dataset<Row> ds2 = ds1.where("age is null").withColumn("is_age_null", lit(true));
Dataset<Row> ds3 = ds1.where("age is not null").withColumn("is_age_null", lit(false));

Dataset<Row> ds4 = ds2.union(ds3);
ds4.show();

Relevant Output:
ds1
+----+---+----+------+
| age| id|name|salary|
+----+---+----+------+
|null|  1|dev1| 11000|
|   2|  2|dev2| 12000|
|null|  3|dev3| 13000|
|   4|  4|dev4| 14000|
|null|  5|dev5| 15000|
+----+---+----+------+

ds4
+----+---+----+------+-----------+
| age| id|name|salary|is_age_null|
+----+---+----+------+-----------+
|null|  1|dev1| 11000|       true|
|null|  3|dev3| 13000|       true|
|null|  5|dev5| 15000|       true|
|   2|  2|dev2| 12000|      false|
|   4|  4|dev4| 14000|      false|
+----+---+----+------+-----------+

Is there any better solution to add this column in the dataset rather than creating two datasets and performing union?

A: Same can be done using when otherwise and withColumn.
ds1.withColumn("is_age_null" , when(col("age") === "null", lit(true)).otherWise(lit(false))).show()

This will give the same result as the ds4.


text:
Q: Django Allow Users to insert dynamic content into email I want to allow my end users to create email templates and in the template allow them to specify dynamic info like in mail chimp.
Example:
"Hello Mr.{{last_name}} I am calling regarding an issue."

A: You can use Django's built in templating engine to allow your users to create custom email templates, this seems to be a very common approach.
https://docs.djangoproject.com/en/1.11/topics/email/#send-mail
https://docs.djangoproject.com/en/1.11/ref/templates/api/#rendering-a-context
You may also want to consider using a less featureful templating engine with your users though because Django templates allow your users to put some really wacky logic or Python expressions in your templates, it may be too permissive for the average user.  I enjoy using Mustache for logic-less templates, it may be a simpler syntax and solution for your users, there is a Mustache implementation in python at Pystache.


text:
Q: Unity. Не работает Raycast Работал над проектом, понадобилось переработать метод определения того, находится ли обьект на земле или нет.
Получилось вот это:
Ray ray = new Ray(_rigidbody.position - Vector3.up * (_controller.height / 2 - 0.1f), Vector3.down);
_onGround = Physics.Raycast(ray, CHECK_GROUND_RAY_MAX_DISTANCE, GlobalLayerMasks.Enviroment);

Через гизмо дебажил, рисовал луч по точно такому-же лучу как и в рейкасте. Гизмо луч чётко проходит через box collider на кубе, но рейкаст не возвращает true. Насчёт слоёв: пробывал убрать слой из рк, результата - 0. Знаю, что рейкаст реагирует только на границы колайдеров, поэтому пробывал поменять константу длины луча на огромные значения, итог - 0. Время позднее, нервный срыв на подходе.


text:
Q: Android Studio Tabhost in scrollview always at top I have a tabhost in android studio that is inside a scroll view. The tabhost itself lies underneath some text.
Here is an image of the xml file
However, whenever i open the app on a device, the scroll view has the tabhost set at the top so i have to scroll up to see the text that is above it.
Why is this and is there a fix?
Thanks in advance.

A: The TabHost is the first view that can request focus. So the work-around is to have another focusable view at the top of the LinearLayout within the ScrollView.
I used the following View for this purpose
    <View android:focusableInTouchMode="true" android:layout_width="0px" android:layout_height="0px"/>

Note: I was heavily inspired by TabHost inside a ScrollView forces it it to scroll to the bottom and Stop EditText from gaining focus at Activity startup.


text:
Q: Reading Xml file in eclipse plugin view I would like to know how to read and modify an XML file in Eclipse plugin with view template.
I have written the following code inside createPartControl method of view class. Upon button click this method shall read xml file but it does not. It throws file not exist error.
Code:
        IWorkspace workspace = ResourcesPlugin.getWorkspace();
        IWorkspaceRoot iroot = workspace.getRoot();
        IProject project  = iroot.getProject("samplePlugin");
        IFolder folder = project.getFolder("resources");
        IFile file=folder.getFile("repository.xml");

        if(file.exists())
        {
            System.out.println("File Exists");
            try {
                doc = docBuilder.parse(file.getContents());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        else {
            System.out.println("File not exists");
             }

Anyone please correct my code and let me know where did I make the mistake.


text:
Q: Using Rigidbody.AddForce with a NavmeshAgent Can't seem to get any of the suggestions I find to this question to work. I have an agent that follows my player, I want to push back that agent when it hits my player, and that works, but the agents position does not seem to update correctly, since after the collision it does not properly try to get to the Player again, like it thinks it's reached its position.
It also says in Unity docs that I need to set the RigidBody to Kinematic, but then I can't add force to it?
private void Update()
{
    if (!playerHit && followPlayer)
    {
        _agent.SetDestination(GameManager.instance.ActivePlayer.transform.position);
    }
}

private void FixedUpdate()
{
    if (playerHit)
    {
        _rb.AddForce(-transform.forward * 10, ForceMode.Impulse);
    }
}

A: You can do this by disabling the navmesh agent for a certain amount of time and then re-enabling it when the velocity is near to zero.
private void Update()
{
    if (!playerHit && followPlayer)
    {
        _agent.SetDestination(GameManager.instance.ActivePlayer.transform.position);
    }
}

private void FixedUpdate()
{
    if (playerHit)
    {
        agent.enabled = false; // disabling the navmesh agent.
        _rb.AddForce(-transform.forward * 10, ForceMode.Impulse);
    }
}

Implementation can be improved, let me know if it helps.


text:
Q: Pressing Esc when editing a comment should cancel editing When editing a post, pressing Esc does the same thing as clicking the "cancel" link: it cancels the edit. However, when editing a comment, pressing Esc does nothing.
Could pressing Esc when editing a comment cancel that edit as well?

A: A keyboard shortcut to cancel a comment does not make sense.
When you edit a post, canceling will ask for confirmation before you lose any changes. If you didn't make any changes, this convenient shortcut will quickly bring you back to the original screen.
But comments are created inline. If you didn't enter any text, there's nothing to jump back to. But if you did enter a comment, one slip of the finger will send your text to the great  *poof* in the sky. So we would have to add an "are you sure" confirmation. That doesn't make it much of a shortcut. Where's the upside?


text:
Q: Cauchy Determinant with Absolute Values This is perhaps a straightforward question but I'm a little confused. An $n\times n$ Cauchy matrix $A$ is a matrix with entries $$a_{i,j}=\frac{1}{x_i-y_j}$$ for $1\le i,j\le n$, where $x_i$ and $y_j$ are elements of a field $\mathcal{F}$, and $(x_i)$ and $(y_j)$ are injective sequences (they do not contain repeated elements; elements are distinct).
The determinant of $A$ is given explicitly as
$$\frac{\prod_{i=2}^n\prod_{j=1}^{i-1}(x_i-x_j)(y_j-y_i)}{\prod_{i=1}^n\prod_{j=1}^n(x_i-y_j)}.$$
My question is this: what happens if one replaces the denominator of $a_{i,j}$ with its absolute value, in other words, does the determinant of the matrix $A'$ where $$a'_{i,j}=\frac{1}{|x_i-y_j|}$$ have a similar explicit evaluation?