text:
Q: Medieval term for sister and brother in-law Is there a medieval term for sister/brother-in-law? The only example I could find was in GRR Martin's A Song of Ice and Fire series where he uses the terms goodsister and goodbrother. Are those rooted in actual medieval terms for in-laws? Were the in-laws even addressed as members of family with specific words? (I've read somewhere that before 19th century the in-laws were used instead of step-mother/father/etc., so they could not be used for the other relation or would be very confusing).

A: According to the Oxford English Dictionary, they have been called in laws for a while. Here are its earliest examples of each:

*

*
[We] schul be samen hole frendes, lelli breþeren in lawe.
The romance of William of Palerne, a1375

*
Syster yn lawe, as howsolde syster [?a1475 Winch. husbandis syster], or wyfys syster, glos.
  [...]
  Syster yn lawe, broders wyyf, fratrissa.
Promptorium parvulorum sive clericorum, 1440

Later, in the 1530 Tyndale Bible (a little too late for it to be considered medieval) shortened versions of these terms, sister law and brother law, were used (again, the earliest examples I could find in the OED):

Yf the man will not take his systerlawe, then let her goo to the gate vnto the elders and saye: My brotherlawe..will not marie me.

Confusingly enough, sometimes they are simply referred to as brother and sister according to the OED:

*

*
No man..miȝt telle þe ioye þat þe bold breþeren..made, william & alphouns.
The romance of William of Palerne, a1375

*
Suster..With al thauys, heer of my perlement.
Canterbury Tales, c1405

In addition, good brother and good sister were used, but mainly in Scottish English. The OED's earliest respective citations are:

*

*
Iames steward, that ledar was Eftir his gud brother disses.
The Bruce, 1375

*
That his gud systyr the Quenys grace be nocht therby mynyst in hyr autorite.
 Douglas Book, 1515


text:
Q: Display an image that is stored outside the project with primefaces I upload an image in my local disk  (image.path=C:/images/) like this :
InputStream input = file.getInputstream();

InputStream appProperties = MyBean.class.getClassLoader().getResourceAsStream("application.properties");
                Properties prop = new Properties();
                prop.load(appProperties);

                String path = prop.getProperty("image.path");
                Path newPath = new File(path+"", agence.getId()+".png" ).toPath();

and now I want to display it in my view on datalist with graphicImage?
Thank you ALL,

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to explain the strange results for while loop with floating point in swift I have tested while loop below and don't understand the result.
var x: Float = 0.0
var counter = 0

 while x < 1.41
 {
     x += 0.1
     counter += 1

 }

 print (counter) // 15
 print (x) // 1.5

How is it possible to have the result x = 1.5 for the used while condition where x < 14.1 ? How to explain this result?
Update:
and one more. Why the results are  different for Double and Float ?
var x: Double = -0.5
var counter = 0

while x < 1.0
{
    x += 0.1
    counter += 1
}

print (counter) // 16
print (x)//1.1

var x: Float = -0.5
var counter = 0

while x < 1.0
{
    x += 0.1
    counter += 1
}

print (counter) // 15
print (x)//1.0

Update 2
and another one. Why there is no difference for < and <= conditions. Does it mean that usage of <= has no sense for floating point ?
var x: Double = 0.0
var counter = 0

while x < 1.5
{
    x += 0.1
    counter += 1
}

print (counter) // 15
print (x) //1.5

var x: Double = 0.0
var counter = 0

while x <= 1.5
{
    x += 0.1
   counter += 1
}

print (counter) // 15
print (x) //1.5

A: What else would you expect? The loop is executed 15 times. On the 14th time, x is 1.4 and so you add another 0.1, making it 1.5.
If you expect the loop to terminate at 1.4, you should increment x before checking the while condition, not after that.
If you expect the loop to terminate on 1.41, your increment is wrong and you should do
x += 0.01

instead, making it 141 iterations.
As for the second question, I am aware that Float should not be used for monetary calculations and such due to its lack of precision. However, I trusted Double so far, and the while loop in run 15 actually claims the Double value to be less than 1.0 while it is reported to be 1.0. We have got a precision problem here, as we can see if we substract x from 1.0:
print(1.0-x)

which returns: 1.11022302462516e-16
At the same time, Float seems to be unprecise in the other direction. In the last run, it is a little bigger than 0.9 (0.9 + 5.96046e-08), making it bigger than 10 in the following run.
The reason why Double and Float are wrong in different directions is just a matter of how the values are stored, and the result will be different depending on the number. For example, with 2.0 both actual values are bigger: Double by 4.440892..e-16 and Float by 2.38419e-07. For 3.0 Double is bigger by 1.33226e-15 and Float smaller by 7.1525e-07.
The same problems occur using x.isLess(than: 1.0), but this method is the basis for the < operator as of https://developer.apple.com/reference/swift/floatingpoint/1849403-isless
isLessThanOrEqualTo(1.0), on the other hand, seems to work reliably as expected.
This answer is pretty much a question itself by now, so I'm curious if anyone has an in-depth explanation of this...
Update
The more I think about it, the less of a Swift problem it is. Basically, you have that problem in all floating point calculations, because they are never precise. Both Float and Double are not precise, Double is just twice as accurate. However, this means that comparisons like == are useless with floating point values unless they are both rounded. Therefore, good advice in loops like those of yours with a known precision (in your case one decimal) would be to round to that precision before doing any kind of comparison. For example, this would fix the loop:
var x: Double = -0.5
var counter = 0

while (round(x * 1000) / 1000) < 1.0
{
    x += 0.1
    counter += 1
}

print (counter) // 15
print (x)//1.0

var x: Float = -0.5
var counter = 0

while (round(x * 1000) / 1000) < 1.0
{
    x += 0.1
    counter += 1
}

print (counter) // 15
print (x)//1.0


text:
Q: How to load image into bootstrap modal with javascript My setup is 4 links (below).  I want each link to open myModal, but depending on which link gets clicked, a different image file should load in the modal.  I got it working for one of the links.

6 Teams

5 Teams

4 Teams

3 Teams

<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>

How do I get this to work for each link without building a separate modal for each one?

A: By using jquery .click you can easily achieve this (with html5 data attribute too).

6 Teams

5 Teams

4 Teams

3 Teams

Script:
$('li a').click(function (e) {
    $('#myModal img').attr('src', $(this).attr('data-img-url'));
});

Fiddle: http://jsfiddle.net/vLSWH/292/
Note: Though you did not specify using jQuery, twitter-bootstrap modal require you to use jQuery anyway, so might as well use it.


text:
Q: Effect of KStreams map() on output topic partitioning if the key is altered I'm a noob to KStreams and have a question about repartitioning in a KStreams application.
I'm having a hard time finding a definitive answer in online documentation and was wondering if any of you could shed some light.
The goal is to repartition a topic on a new key in an efficient way.
In KStreams we can call map() and change the key and write it to the output topic.
How would this work for kstream app instances running in different JVMs running their own consumers in the same consumer group consuming from the original topic?
For example -
Let's say I have an input topic with 3 partitions that supplies employee data that has sick leave  details for a month + year.
The key to this input topic is let's say is null.
We want to flag if any Employee took more than 10 days of sick leave in a month. So we map the stream to have (EmployeeId, Month, Year) in the key and sick leave amount in the value. Then we aggregate this KStream into a KTable(persisted with an in-memory store) and convert that KTable back into a stream to get changing cumulations as a stream instead.
Finally we filter on the cumulations to flag if they become greater than 10.
Now the original input topic could have had sick leave details for the same employee on different partitions.
Does that mean that the aggregation for a single (EmployeeId, Month, Year)  could get fractured across the different application instances and thus fail to fire the 10 day filter? (edited)

A: KafkaStreams does not create output topics for you, but you should create the output topic before you start your application. Cf. https://docs.confluent.io/platform/current/streams/developer-guide/manage-topics.html#user-topics
If you don't create the output topic, KafkaStreams would fail eventually (as it cannot write to a non-existing topic), or if you have broker side auto-topic creation enable, the broker would create the topic for you (however, it's not recommended to use auto-topic creation).
Thus, you can create your output topic with any number of partitions, as suitable for your application.
If you run multiple instances of the same KafkaStreams application, all of them will write to the partitions of the output topic, ie, each instance can write to any partition, and every partitions might receive data from any instance.
If you call repartition() Kafka Streams will create a repartition topic on your behalf. In general, you don't need to call this method, because if you do a downstream aggregation or join, repartitioning happens automatically anyway. The purpose of repartition() is for case in which you need to repartition but Kafka Streams does not do it automatically, for example before a transform(). Another use case is, if you want to change the number of partitions for the repartition topic: by default it's create with the same number of partitions as the input topic.
If an internal repartition topic is created, your topology will look like this:
inputTopic -> map() -> repartitionTopic -> agg()/join() -> outputTopic


text:
Q: Belonging to an $ L^p$ space... so I'm currently tussling with this particular problem. I have $$f(x)={e^{-|x|}-1 \over x} $$ $$f_\varepsilon(x)={e^{-|x|}-{\sin(\varepsilon x) \over \varepsilon x} \over x},\quad x \in \mathbb R, \ \varepsilon > 0$$
I need to determine whether they belong to $L^1(\mathbb R), L^2(\mathbb R)$. The question is, must I necessarily brute-force it via the $\int_\mathbb R|f|^pdx<\infty$ condition or is there a smarter way to go about this? Can I determine the answer by looking for something in the functions?

A: Hints:
$1).\ $ If $0\leqslant   t \leqslant  |x|,\ \left|{e^{-|t|}-1 \over t}\right |={1-e^{-|t|} \over t}=-\sum^{\infty}_{k=1}\frac{(-1)^kt^k}{k!}$ and this series converges uniformly on $[1,x]$ so it may be integrated termwise:
$\displaystyle\int^x_0 {e^{-t}-1 \over t}dt=-\sum^{\infty}_{k=1}\frac{(-1)^kx^{k+1}}{(k+1)!}=-\sum^{\infty}_{k=2}\frac{(-1)^kx^{k}}{k!}=-e^{-x}+1+x$ so the integral diverges.
This shows that  $\displaystyle\int^0_{-\infty} {e^{-|t|}-1 \over t}dt$ diverges as well.
Since $\displaystyle\int^1_{-1} {e^{-|t|}-1 \over t}dt$ converges, putting the pieces together, we get that the integral diverges.
$2).\ $ Now,  $\displaystyle \int^{\infty}_1\left|{e^{-|t|}-1 \over x}\right|^2dx$ and $\displaystyle \int_{-\infty}^{-1}\left|{e^{-|t|}-1 \over x}\right|^2dx$ clearly converge so all you need consider is $\left|{e^{-|t|}-1 \over x}\right|^2$ on $[-1,1]$.
$3).\ $ Finally, split up $\mathbb R$ and analyze as above to consider the three integrals whose integrand is $f_{\epsilon.}$


text:
Q: Add action to the button in MKPinAnnotationView tldr: I try to add actions with alerts to a button in pinView and store this data (names of pins with describtion and pin icon) in UserDefaults. I have pins with MKPinAnnotationView and a button in it. I would like this button to check if user is more or less than 100 meters form the CLLocation of the pin. After clicking the button (when the user IS INSIDE 100m radius od pin location) it should show UIAlertController (otherwise it should display similar alert as below with the info that user is outside radius for example with just cancel action):
let alertController = UIAlertController(title: "Check-in!", message: "Click below to check-in", preferredStyle: UIAlertController.Style.alert)

alertController.addAction(UIAlertAction(title: "Check-In", style: UIAlertAction.Style.default, handler: { action in  //HERE I WOULD LIKE TO SAVE THE NAME OF THE PIN SOMEWHERE IN UserDefaults to display it later in table view in another ViewController))

alertController.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.default, handler: { action in  //close alert and do nothing))

Here is my code:
import UIKit
import MapKit

class ViewController: UIViewController, MKMapViewDelegate{

    let locationManager = CLLocationManager()

    struct Szczyt {
      let name: String
      let opis: String
      let lattitude: CLLocationDegrees
      let longtitude: CLLocationDegrees
        var coordinate: CLLocationCoordinate2D {
            .init(latitude: lattitude, longitude: longtitude)
        }
    }

    @IBOutlet weak var mapView: MKMapView!
    @IBAction func mapTypeSegmentSelected(_ sender: UISegmentedControl) {
            switch sender.selectedSegmentIndex {
            case 0:
                mapView.mapType = .standard
            case 1:
                mapView.mapType = .satellite
            default:
                mapView.mapType = .hybrid
            }
        }
    private(set) var circles: [MKCircle]!

    let szczyty = [Szczyt(name: "one", opis: "describtion", lattitude: 53.865061725039226, longtitude:   17.708595782487315),
                   Szczyt(name: "two", opis: "describtion2", lattitude: 55.893874478583854, longtitude: 24.896341184611302),
                   Szczyt(name: "Skrzyczne", opis: "describtion3", lattitude: 49.685059170137386, longtitude: 19.030076144463138)]

    override func viewDidLoad() {
        super.viewDidLoad()
        mapView.register(MKMarkerAnnotationView.self, forAnnotationViewWithReuseIdentifier: "identifier")
        checkLocationServices()
        znajdzSzczytyNaMapie(szczyty)
        circles = szczyty.map {
                    MKCircle(center: $0.coordinate, radius: 100)
                }
        mapView.addOverlays(circles!)
        mapView.delegate = self
        }

        func checkLocationServices() {
          if CLLocationManager.locationServicesEnabled() {
            checkLocationAuthorization()
          } else {
            // Show alert letting the user know they have to turn this on.
          }
        }
        func checkLocationAuthorization() {
          switch CLLocationManager.authorizationStatus() {
          case .authorizedWhenInUse:
            mapView.showsUserLocation = true
           case .denied:
           break
          case .notDetermined:
            locationManager.requestWhenInUseAuthorization()
            mapView.showsUserLocation = true
          case .restricted:
           break
          case .authorizedAlways:
           break

          }
    }
    func znajdzSzczytyNaMapie(_ szczyty: [Szczyt]) {
      for szczyt in szczyty {
        let annotations = MKPointAnnotation()
        annotations.title = szczyt.name
        annotations.subtitle = szczyt.opis
        annotations.coordinate = CLLocationCoordinate2D(latitude:
          szczyt.lattitude, longitude: szczyt.longtitude)
        mapView.addAnnotation(annotations)
      }
    }
let location = CLLocation()
let circleCenter = CLLocation()
//This I think is necessary for detecting if user is in 100m distance from the location - Is it good?:if location.distance(from: circleCenter) < circleRadius {
    // User is inside radius 100m.
//}

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        guard !(annotation is MKUserLocation) else { return nil }
        mapView.delegate = self
        let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: String(annotation.hash))
        let identifier = "identifier"
        annotationView.canShowCallout = true
        guard let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier, for: annotation) as? MKMarkerAnnotationView else { return nil }
        let rightButton = UIButton(type: .contactAdd)
        rightButton.tag = annotation.hash
        annotationView.canShowCallout = true
        annotationView.rightCalloutAccessoryView = rightButton

//HERE IS THIS BUTTON called rightButton that I need action with alerts.

switch annotation.title!! {
            case "one":
                annotationView.markerTintColor = UIColor(red: 0.86, green: 0.99, blue: 0.79, alpha: 1.00)
                annotationView.glyphImage = UIImage(named: "one_pic")
            case "two":
                annotationView.markerTintColor = UIColor(red: 0.80, green: 0.98, blue: 0.73, alpha: 1.00)
                annotationView.glyphImage = UIImage(named: "two_pic"")
            case "Skrzyczne":
                annotationView.markerTintColor = UIColor(red: 0.02, green: 0.61, blue: 0.69, alpha: 1.00)
                annotationView.glyphImage = UIImage(named: "three_pic"")
            default:
                annotationView.markerTintColor = UIColor.green
                annotationView.glyphImage = UIImage(named: "default")
        }
        return annotationView
    }
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let circleRenderer = MKCircleRenderer(overlay: overlay)
        circleRenderer.strokeColor = UIColor.green
        circleRenderer.fillColor = UIColor.green
        circleRenderer.alpha = 0.3
        circleRenderer.lineWidth = 1.0
        return circleRenderer
    }

}

For these stored thata with names I've created second ViewController to store it with Table View.
If something is not understandable, please ask :) Thank you in advance.


text:
Q: Windows Users Management run command What is the "run" command for Windows Users Management?
the MMC console you change the local users password and create new users?

A: Open run prompt, type in "lusrmgr.msc"


text:
Q: angular2 router interpreting route as parameter? I am trying to route to a child module with route params, my app.routes looks like
import { Routes, RouterModule } from '@angular/router';

const appRoutes: Routes = [
  { path: 'cell', loadChildren: './cell/cell.module#CellModule', pathMatch: 'prefix'}
];

export const appRoutingProviders: any[] = [];
export const routing = RouterModule.forRoot(appRoutes);

my child component (cell) has these routes:
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { CellComponent } from './cell.component';

const cellRoutes: Routes = [
    { path: ':id', component: CellComponent, pathMatch: 'full' }
];

export const cellRouting: ModuleWithProviders = RouterModule.forChild(cellRoutes);

and CellComponent looks like this:
export class CellComponent implements OnInit {
  @Input()
  dep: string;

  constructor(
    private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.params.forEach((params: Params) => {
      this.dep = params['id'];
      console.log(this.dep);
    });

  }
}

I expect to be able to call the /cell/2 route and get 2 in my console, however, if I make that call, I get an error:

TypeError: Cannot read property 'length' of undefined

which seems to be because of using an undefined route, and if I just call /cell then my component loads fine and prints cell to the console. Why is the router interpreting the route as a parameter?

A: Use below code to get the id:
import { ActivatedRoute, Router } from '@angular/router';
constructor(public route: ActivatedRoute, ...) {
}
ngOnInit() {
    this.route
        .params
        .subscribe(params => {
            this.id= params['id'];
    });
}


text:
Q: An elegant way to unpool matrix with numpy I will describe the problem with an example. There is a matrix
[[1 2]
 [3 4]]

I need to resize/unpool it to the next one
[[1 1 2 2]
 [1 1 2 2]
 [3 3 4 4]
 [3 3 4 4]]

The operation is kind of opposite to max pooling in convnets. I have a brute solution with cycles. I would be very happy to see if there is a sophisticated solution with numpy.
My brute force solution is below.
matrix = np.arange(1, 5).reshape(2, 2)
matrix_m, matrix_n = matrix.shape
kernel = np.ones((2, 2), dtype=np.int)
kernel_m, kernel_n = kernel.shape
unpooled_matrix = np.zeros((matrix_m * kernel_m, matrix_n * kernel_n), dtype=np.int)
for i in range(matrix_m):
    pos_i = i * kernel_m
    for j in range(matrix_n):
        pos_j = j * kernel_n
        unpooled_matrix[pos_i: pos_i + kernel_m, pos_j: pos_j + kernel_n] = kernel * matrix[i][j]

print(matrix)
print(kernel)
print(unpooled_matrix)


text:
Q: select onchange add get variable to url I am using multiple select elements on a page. This page's url is something like this: "index.php?s=foo".
Now I want that changing my select boxes will alter my URL and refresh page, this just works partly :(
Here is the example:
<form action="'.$_SERVER['REQUEST_URI'].'" method="GET">
    <select name="this" onchange="this.form.submit()">
        <option value="1">Value 1</option>
        <option value="2">Value 2</option>
        <option value="3">Value 3</option>
    </select>
</form>

So if I change my selection the url will swap to "index.php?this=1", but I would like to hold the previous _GET Parameters, so change would occur to "index.php?s=foo&this=1".
Any chance I would get that?
Thanks very much for your help.
Best Regards

A: You could add each query string item as a hidden field which will be added to the query string when the form is submitted. Be sure to do some sanitizing on these things to make them safe.
if(!empty($_GET))
{
    foreach($_GET AS $k => $v)
    {
        echo '<input type="hidden" name="'.$k.'" value="'.$v.'">';
    }
}

The form action can then be hard coded to something like the file name or  $_SERVER['SCRIPT_NAME']. Not $_SERVER['PHP_SELF'] - as pointed out by comment below.
edit : posted answer before I was finished. :(

A: Using REQUEST_URI does not include your current GET parameters. You will need the function in this gist to transform all parameters into input fields: https://gist.github.com/eric1234/5802030 .
<form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method="get">
    <?php array_to_input($_GET); ?>
    <select name="this" onchange="this.form.submit()">
        <option value="1">Value 1</option>
        <option value="2">Value 2</option>
        <option value="3">Value 3</option>
    </select>
</form>

CAUTION: array_to_input can introduce XSS vulnerabilities. Please escape contents of the $_GET variable so this cannot happen.

A: The simple answer is instead of this:
<form action="'.$_SERVER['REQUEST_URI'].'" method="GET">

Do the action like this:
<form action="<?php echo $_SERVER['REQUEST_URI'].'?'.$_SERVER['QUERY_STRING']; ?>" method="GET">

Which will include the current $_GET values in your form's action/url and by extension be present when the form is submitted.  Basically that is the way forms are designed in general to handle submission to a page with query parameters, ie. the default way it works.
Just a note but I think the way you have it now you might get this for your action/url
 "http://'.$_SERVER['REQUEST_URI'].'"

It's just a guess, but it looks like the form is html, and the php will just print and not be executed as code ( without php tags ). Probably just an over-site in the example code. But, I would expect this with the format you have:
 echo '<form action="'.$_SERVER['REQUEST_URI'].'" method="GET">';

Cheers!


text:
Q: App-Store-Review-Scraping: AppStoreScraper does not recognise app-id I am very new in coding, just started this summer. I am trying to scrape reviews from App Store for 9 live-shopping-apps: https://www.apple.com/us/search/live-shopping?src=globalnav
I have created an xlsx-file with information about the apps and downloaded that as csv to the code, hoping that appstorescraper will identify apps through their id but it does not seem to work. Here is the code, originally retrieved from https://python.plainenglish.io/scraping-app-store-reviews-with-python-90e4117ccdfb:
import pandas as pd

# for scraping app info from App Store
from itunes_app_scraper.scraper import AppStoreScraper

# for scraping app reviews from App Store
from app_store_scraper import AppStore

# for pretty printing data structures
from pprint import pprint

# for keeping track of timing
import datetime as dt
from tzlocal import get_localzone

# for building in wait times
import random
import time

## Read in file containing app names and IDs
app_df = pd.read_csv('Data/app_.....ids.csv')
app_df.head()

app_name    iOS_app_name    iOS_app_id  url
4   Flip - Beauty and Shopping  flip-beauty-shopping    1470077137  https://apps.apple.com/us/app/flip-beauty-shop...
7   Spin Live   spin-live   1519146498  https://apps.apple.com/us/app/spin-live/id1519...
1   Popshop - Live Shopping popshop-live-shopping   1009480270  https://apps.apple.com/us/app/popshop-live-sho...
5   Lalabox - Live Stream Shopping  lalabox-live-stream-shopping    1496718575  https://apps.apple.com/us/app/lalabox-live-str...
6   Supergreat Beauty   supergreat-beauty   1360338670  https://apps.apple.com/us/app/supergreat-beaut...
8   HERO®   hero-live-shopping  1178589357  https://apps.apple.com/us/app/hero-live-shoppi...
2   Whatnot: Buy, Sell, Gov Live    whatnot-buy-sell-go-live    1488269261  https://apps.apple.com/us/app/whatnot-buy-sell...
3   NTWRK - Live Video Shopping ntwrk-live-video-shopping   1425910407  https://apps.apple.com/us/app/ntwrk-live-video...
0   LIT Live - Live Shopping    lit-live-live-shopping  1507315272  https://apps.apple.com/us/app/lit-live-live-sh...

## Get list of app names and app IDs
app_names = list(app_df['iOS_app_name'])
app_ids = list(app_df['iOS_app_id'])```

## Set up App Store Scraper
scraper = AppStoreScraper()
app_store_list = list(scraper.get_multiple_app_details(app_ids))

## Pretty print the data for the first app
pprint(app_store_list[0])

https://itunes.apple.com/lookup?id=1507315272&country=nl&entity=software
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
/opt/anaconda3/lib/python3.8/site-packages/itunes_app_scraper/scraper.py in get_app_details(self, app_id, country, lang, flatten)
    179                         result = json.loads(result)
--> 180                 except json.JSONDecodeError:
    181                         raise AppStoreException("Could not parse app store response")

IndexError: list index out of range

During handling of the above exception, another exception occurred:

AppStoreException                         Traceback (most recent call last)
<ipython-input-73-624146f96e92> in <module>
      1 ## Set up App Store Scraper
      2 scraper = AppStoreScraper()
----> 3 app_store_list = list(scraper.get_multiple_app_details(app_ids))
      4
      5 app = result["results"][0]

/opt/anaconda3/lib/python3.8/site-packages/itunes_app_scraper/scraper.py in get_multiple_app_details(self, app_ids, country, lang)
    205                 :param str lang: Dummy argument for compatibility. Unused.
    206
--> 207                 :return generator:  A list (via a generator) of app details
    208         """
    209                 for app_id in app_ids:

/opt/anaconda3/lib/python3.8/site-packages/itunes_app_scraper/scraper.py in get_app_details(self, app_id, country, lang, flatten)
    180                 except json.JSONDecodeError:
    181                         raise AppStoreException("Could not parse app store response")
--> 182
    183                 try:
    184                         app = result["results"][0]

AppStoreException: No app found with ID 1507315272```

This is where I am stuck. It seems to be a simple problem but my experience is very limited. The url that App Store scraper use is not the same I used to retrieve app-ids from. Could this be the concern? Please help me to solve it. Thank you in advance!


text:
Q: Problema na utilização do QPixmap.scaled Recentemente estou aprendendo a utilizar o PyQt4, porém surgiu uma dúvida na utilização da linha de código para modificar a escala de uma imagem:
class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName(_fromUtf8("Form"))
        Form.resize(743, 510)
        self.pushButton = QtGui.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(20, 430, 85, 27))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.foto = QtGui.QLineEdit(Form)
        self.foto.setGeometry(QtCore.QRect(20, 390, 700, 27))
        self.foto.setObjectName(_fromUtf8("Diretorio"))
        self.label = QtGui.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(30, 26, 671, 341))
        self.label.setText(_fromUtf8(""))
        self.label.setObjectName(_fromUtf8("label"))
        self.horizontalSlider = QtGui.QSlider(Form)
        self.horizontalSlider.setGeometry(QtCore.QRect(120, 430, 601, 18))
        self.horizontalSlider.setMaximum(255)
        self.horizontalSlider.setOrientation(QtCore.Qt.Horizontal)
        self.horizontalSlider.setObjectName(_fromUtf8("horizontalSlider"))
        self.label_2 = QtGui.QLabel(Form)
        self.label_2.setGeometry(QtCore.QRect(380, 450, 71, 17))
        self.label_2.setObjectName(_fromUtf8("label_2"))

        self.retranslateUi(Form)
        QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), self.abrirfoto)
        #self.horizontalSlider.valueChanged.connect(self.threshold)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        Form.setWindowTitle(_translate("Form", "Testando", None))
        self.pushButton.setText(_translate("Form", "Abrir", None))
        self.label_2.setText(_translate("Form", "Threshold", None))

    def abrirfoto(self):

        img = self.foto.text()
        self.label.setPixmap(QtGui.QPixmap(img))
        QtGui.QPixmap.scaled(671,341,0,0)

E retorna o erro:

TypeError: arguments did not match any overloaded call:
    QPixmap.scaled(int, int, Qt.AspectRatioMode aspectRatioMode=Qt.IgnoreAspectRatio, Qt.TransformationMode transformMode=Qt.FastTransformation): first argument of unbound method must have type 'QPixmap'
    QPixmap.scaled(QSize, Qt.AspectRatioMode aspectRatioMode=Qt.IgnoreAspectRatio, Qt.TransformationMode transformMode=Qt.FastTransformation): first argument of unbound method must have type 'QPixmap'

A: Eu adicionei uma variável na função abrirfoto, que estava associada a função .scaled, ficando dessa forma:
def abrirfoto(self):
    img = self.foto.text()
    imagem = QtGui.QPixmap(img)
    imagem1 = imagem.scaled(671,341,QtCore.Qt.IgnoreAspectRatio,QtCore.Qt.FastTransformation)
    self.label.setPixmap(QtGui.QPixmap(imagem1))


text:
Q: ASP.NET Membership Provider failing on different SQL instance I am using the ASP.NET Membership Schema using aspnet_regsql.exe on SQL1 (hosted via windows server), I had a backup of that sql database restored on SQL2 (local instance).
However, when I have my connection string pointed to SQL2, authentication is failing @

Membership.ValidateUser

It is returning a false, but when I change my connection string back to SQL1, it returns true, this is happening on same codebase. I am not sure what is causing this, I have tried the following

*

*Checked SQL1 and SQL2 passwords and salts, they match exactly

*Tried using SQL Compare to see if there was something different, the schema
matches exactly

*Checked SQL login permissions, they both match

Any ideas?

A: The encrypted password is created from a hash of the machine key (which is in web.config so could be a red herring if this is the same web server?) + actual pwd + randomly generated password salt.
Try running a sql trace to capture the issued commands and try running those in QA. This would show up a hash mismatch or simple auth fail.
Maybe you should force the machine key, look for machine.config and copy it from there into your local web.config.
My past pain-history says if ur still scratching your head - go find a decent decompiler (ILSpy) and attach your debugger to the dll and step through as you would if it were your own code.
Machine key in Forms-Auth

A: If password is stored as hashed, it doesn't use machine key.
However, password is stored as encrypted, it uses machine key.
If they are mixed and machine key is not explicitly set in web.config, only thing you can do is to retrieve the machine key from old server using this method -
How to read Auto Generated machine key?
Rule of thumb is you want to include machine key in web.config. We learn the hard way that Azure creates machine key automatically if you do not set one in web.config.


text:
Q: Sqlite3 Operational Error: near "REFERENCES" Syntax Error I have the following code:
with sqlite3.connect('notDataBase1.db') as db:
    cursor = db.cursor()

sql = """CREATE TABLE OrderDetails
                (OrderDetailsID INTEGER,
                 OrderID INTEGER,
                 ProductID INTEGER,
                 PRIMARY KEY(OrderDetailsID),
                 FOREIGN KEY(OrderID REFERENCES
                             Orders(OrderID)),
                 FOREIGN KEY(ProductID REFERENCES
                             Products(ProductID)))"""
cursor.execute(sql)

Which gives me the error:
sqlite3.OperationalError: near "REFERENCES": syntax error
I'm not sure what has happened as this code worked for me yesterday, but has since stopped working.
Any ideas?
Thanks in advance.

A: does you DB have Orders and Products table?
CREATE TABLE `OrderDetails` (
    `OrderDetailsID `   INTEGER,
    `OrderID `  INTEGER,
    `ProductID `    INTEGER,
    FOREIGN KEY(`ProductID `) REFERENCES `Products`(`ProductsID`),
    FOREIGN KEY(`OrderID `) REFERENCES `Orders`(`OrdersID`),
    PRIMARY KEY(`OrderDetailsID `)
);

The sql above works, I think your mistake comes from the Foreign Key part, bad english sorry. As you can see, the References part must be out of the Foreign key attribute. Give it a try and tell me.
Have a nice day


text:
Q: How SMS numbers for services work? Not sure if this is the place for the question, but...
I did receive spam sms from a number, about a promotion here in Brazil. And, from this same number (27900), I did receive my Evernote verification code.
Now I wonder, is there some 'free for use', or rentable, sms numbers for anyone to send anything?

A: Not quite "free for use". But, there are companies such as Twilio which specialize in providing APIs for sending SMS messages, so that individual web apps won't need to make agreements with dozens of telephone operators anymore.
Such services will usually route all messages (even from different customers) sent towards the same regio through the same phone number. For example, I live in Central Europe and various services – Tumblr, Blizzard, eBay, Namecheap – send me security codes via +44.7781470659. (According to the web, even Google and Microsoft use the same gateway.)


text:
Q: JavaScript function called only once instead of every time I need a javascript code that checks the input file size before uploading everytime the input value changes (i.e. everytime the user selects a file to upload).
So far I came up with this:
var file = document.getElementById("myFile");
    file.addEventListener('change', function() {
        if (this.files[0].size > 2*1024*1024) {
            alert('Max file size is 2 MB');
            file.removeAttribute('value');
            file.parentNode.replaceChild(file.cloneNode(true),file);
            }
        }
    );

and the HTML is:
<form action="?" method="post">
    <input type="file" id="myFile" name="myFile" />
    <input type="submit" value="upload" />
</form>

Now, if I leave the Javascript code like that, it doesn't work at all.
But if I change it like this
window.onload = function() {

      // Same code above

}

it works, but only for the first file the user selects.
How can I change it to make it work everytime the user selects a file? (if possible without jQuery)

A: From the documentation for cloneNode:

Cloning a node copies all of its attributes and their values, including intrinsic (in–line) listeners. It does not copy event listeners added using addEventListener()

You are deleting the element with the event handler on it and replacing it with one that doesn't have a change listener
You need to call addEventListener again (and store file.cloneNode(true), in a variable so you can call addEventListener on it and pass it to replaceChild).

A: No need to clone the node etc ... just set the value to '';
file.value = '';

see working snippet

document.getElementById("myFile").addEventListener('change', function() {
  if (this.files[0].size > 2*1024*1024) {
    alert('Max file size is 2 MB');
    this.value='';
  }
});
<form action="?" method="post">
    <input type="file" id="myFile" name="myFile" />
    <input type="submit" value="upload" />
</form>


text:
Q: django unicode error on admin page I'm vaguely familiar with the nature of unicode, but I'm not sure how all the pieces fit together.  I have an error when displaying specific instances in the admin page.

Caught UnicodeEncodeError while
  rendering: 'ascii' codec can't encode
  character u'\u2019' in position 29:
  ordinal not in range(128)

Here's my model:
class Proposal(models.Model):
    project = models.ForeignKey(Project)
    dateCreated = models.DateTimeField(editable=False)
    xml = models.TextField(max_length=1000000)

    def __str__(self):
        return str('Proposal for: %s' % self.project.name)

I've gone into my mysql database and verified that the DB, table, and column are all collated as utf8_unicode_ci, so I don't understand why the page is trying to render as ascii.  Looking at various forums and docs, I see mention of the str and unicode functions, but they don't seem to have anything to do with this as the list of instances shows up fine in on the admin page.  It's just showing the actual instance form that causes a problem.
Here's some example xml I pulled from phpmyadmin...
<?xml version="1.0"  encoding="UTF-8"?>
<proposal>

      <text>
    This proposal is not in the system because it was completed as an agreement in Word previous to us getting this application up and running.  Please refer to the attachments in this project for documentation or to see the agreement.
      </text>

</proposal>

I've even tried to deliberately exclude the xml (which I can't do in the long run since I'd like it to be editable in the admin section), but I still get the same error, so I'm not even convinced the xml is even the problem.  If the xml isn't the problem, I have no idea what else could be keeping this page from being displayed.
class ProposalAdmin(admin.ModelAdmin):
    exclude = ('xml',)
admin.site.register(Project)

A: 2019 is RIGHT SINGLE QUOTATION MARK, commonly used as a curly apostrophe.
The problem probably is caused by you using __str__ instead of __unicode__, and Django's documentation recommends that you only use __unicode__.
The list of instances probably shows up fine because it doesn't include the field that contains the apostrophe.

A: (I'd add this as a comment to Andre's but don't have the 50 points yet)
This:
def __unicode__(self):
    return 'Proposal for: %s' % self.project.name

Should be
def __unicode__(self):
    return u'Proposal for: %s' % self.project.name

This is especially true if you are using a variable in the definition that references another model that may return a string with characters unicode doesn't like.  Putting in the "u" in front of the text returned makes sure everything is kosher and returned as unicode.

A: There's a ' character somewhere, probably in self.project.name. You could probably find it if you check the whole error message.
However, if you're getting unicode results from your database it would probably be smarter to do something like this:
def __str__(self):
    return ('Proposal for: %s' % self.project.name).encode('ascii', errors='replace')

The smartest thing to do, since it's recommended by the Django documentation, is to implement the __unicode__ function instead:
def __unicode__(self):
    return u'Proposal for: %s' % self.project.name


text:
Q: Prove that $\ f(x)=x^{3}$ is continuous at $\ x = -2$ using the delta-epsilon approach Prove that $\ f(x)=x^{3}$ is continuous at $\ x = -2$.
I am really struggling on how to choose an initial $\delta_1$ value, are we able to choose any value or are there specific values to target, in this case I chose $\delta_1=1$
The below is the work I had:
For any given $\epsilon > 0$, we want to find a $\delta >0$ such that $\ |f(x) - (-8)| < \epsilon$ whenever $\ 0<|x-(-2)|<\delta$ each simplifies to $\ |x^{3} +8| < \epsilon$ and  $\ 0<|x+2|<\delta$
I expand the inequality so that I get
$$\ |(x+2)(x^{2}-2x+4)|<\epsilon$$
I temporarily set $\ |(x^{2}-2x+4)|<K$ so then the above inequality becomes:
$$\ K|x+2|<\epsilon\\
|x+2|<\frac{\epsilon}{K}$$
This is the part I am struggling with, now I need to find out K.
We know that $\ 0<|x+2|<\delta$, removing the absolute values results in $-\delta<x+2<\delta$ and getting to only x results in $-\delta-2<x<\delta-2$
If I make the assumption of $\delta_1=1$ then the resulting inequality is $-3<x<-1$
I also tried this with a $\delta=\frac{1}{2}$ just to make sure it fell inside these bounds.
Since we want to look at the upper bound here I plugged in -1 back into K and got the following
$$\
|x+2|<\frac{\epsilon}{|-1|^2+2|-1|+4|}\\
|x+2|<\frac{\epsilon}{7} \\
\delta=\frac{\epsilon}{7}\\
\delta=min(1,\frac{\epsilon}{7})
$$
Then I did the following to prove it
$$
|f(x) - (-8)| =|x^{3}+8|=|(x^{2}-2x+4)||x+2|\\
<|x+2|\cdot (|-1|^{2}+2|-1|+4)\\= |x+2|\cdot7\\
=7\delta \le 7 \cdot \frac{\epsilon}{7}=\epsilon
$$

A: Note that\begin{align}x^2-2x+4&=\bigl((x+2)-2\bigr)^2-2\bigl((x+2)-2\bigr)+4\\&=(x+2)^2-6(x+2)+12\end{align}and that therefore$$|x+2|<1\implies|x^2-2x+4|<1+6+12=19.$$So, take $\delta=\min\left\{1,\frac\varepsilon{19}\right\}$ and then$$|x+2|<\delta\implies\bigl|(x+2)(x^2-2x+4)\bigr|<\frac\varepsilon{19}\times19=\varepsilon.$$


text:
Q: Perl: Unable to exec I am trying to run few child processes on different platforms in parallel. Parent should only proceed further once all the child processes have completed on respective platforms.
The problem is that when I use fork and then run the 'exec' command in the child process, it ends almost instantly. Also, the output isn't consistent. Almost every time the log shows only one line.
-bash-2.05b$ cat Agent.SOLSPARC
caught SIGTERM signal, cleaning up

or
-bash-2.05b$ cat Agent.SOLSPARC
Host: EBSO9SPC  Login: esm2

Sometimes, there are few extra lines and at last the message, 'Killed by signal 15'. The command that i use in 'exec' actually calls a script which connects to remote boxes and runs make command on them. For testing purpose, i am currently passing only one platform i.e., SOLSPARC. Also, i'm only interested in knowing whether a command finished on any given platform.
I was not sure whether I was passing all the arguments to 'exec' correctly so I tried different combinations (after referring different links on the Internet) but to no avail. One important observation is that when i used strace to debug this issue, the command worked fine. I saw in the perldoc that exec uses /bin/sh -c on Unix platforms, but varies on other platforms. Is it that exec and strace use different shell?
Here's the relevant portion of my code:
sub compile {
    my %child_pids;
    foreach $plat (0 .. $#plat_list) {
        my $pid = fork;
        # Didn't check the undef condition for child
        if ($plat_list[$plat] eq "SOLSPARC") {
            print "\nStarted Solaris build \n";
            if ($pid == 0) {
                print "Inside Child Process \n\n";
                exec ( "${ROOT}/${REM_EXEC} -t 1200 -c \"make LANG=en_US distclean \" -b ${ROOT} -l Agent. $plat_list[$plat]" ) or die "exec failed";
            } elsif ($pid > 0) {
                $child_pids{"SOLSPARC"} = $pid;
            }
        } else {
           print "\nStarted build for other platforms \n";
           if ($pid == 0) {
                print "Inside Child Process \n\n";
                exec ( "${ROOT}/${REM_EXEC} -t 1200 -c \"make LANG=en_GB clean \" -b ${ROOT} -l Agent. $plat_list[$plat]" ) or die "exec failed";
           } elsif ($pid > 0) {
                $child_pids{"$plat_list[$plat]"} = $pid;
           }
        }
    }

    my %rev_child_pids = reverse %child_pids;
    while ((my $kid = waitpid -1, WNOHANG) > 0) {
        if ($rev_child_pids{$kid} eq "SOLSPARC") {
            print "\nChild process completed for SOLARIS platform $rev_child_pids{$kid} \n";
            print "Run some other command here \n";
        } else {
            print "\nChild process completed for other platform $rev_child_pids{$kid} \n";
            print "No more commands to run \n";
        }
    }
}

Any suggestions?

A: Try using 'system' instead of 'exec'.
system `${ROOT}/${REM_EXEC} -t 1200 -c "make LANG=en_US distclean " -b ${ROOT} -l Agent. $plat_list[$plat]`

'system' works slightly differently in relation to fork so it might solve the problem.


text:
Q: How to make image as toggle button to show two different images in react native I am doing react native project. In that, I have to show custom image like toggle button, In that, for OFF one image and ON another image I have to display, And in that, two components should have to display according to ON/OFF states.
I am new to this domain.
I have knowledge to set image touchable/Onpress, but, How to set custom image and act like toggle according to that components switch.
this.toggleAction() = () => {
//switching components for ON/OFF states

}

 <TouchableHighlight >
  <Image style={styles.imagestyle}
  source={require('./ic_toggle_on.png')} />
  onPress={() => this.toggleAction()}>
    </TouchableHighlight>

Any suggestions?

A: You need to store the current state of Toggle button in a state variable:

this.state={
toggle:false
}

then you need to change the state in the onPress method of your TouchableOpacity.
After that you just need conditional rendering to show the different images

   render(
<TouchableOpacity onPress={()=>this.setState({toggle:!this.state.toggle})}>

{
  this.state.toggle==true?
 <Image src={ YOUR TOGGLE ON SOURCE}/>
 :
 <Image src={ YOUR TOGGLE Off SOURCE}/>

}
)


text:
Q: Export all data to Excel using GridView with paging enabled..in asp.net with c# I am trying to export data to Excel. And I have GridView with paging enabled. When I download data using HtmlTextWriter it give download only to visible record in GridView. Can we download all the record in single excel file? And also downloaded-data should be with the same sorted state as sorted in GridView?
Client Source code
<asp:GridView ID="gvDetailFleet" runat="server" DataSourceID="SqlDataSource2"
        AllowPaging="false" AllowSorting="True"  AutoGenerateColumns="true"
        DataKeyNames="OracleId" CellPadding="4" ForeColor="#333333"
        GridLines="None"    >
        <RowStyle BackColor="#EFF3FB" />
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <EditRowStyle BackColor="#2461BF" />
        <AlternatingRowStyle BackColor="White" />
</asp:GridView>

Here is Server Side
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.IO;
public partial class FleetReportWithoutVehicle : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            btnFleetReportWithoutVehicle.Visible = false;
        }
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        btnFleetReportWithoutVehicle.Visible = true;
    }

    protected void btnExportSalary_Click(object sender, EventArgs e)
    {
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "AttendanceFollowUpReport.xls"));
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        gvDetailFleet.AllowPaging = false;
        gvDetailFleet.HeaderRow.Style.Add("background-color", "");
        for (int i = 0; i < gvDetailFleet.HeaderRow.Cells.Count; i++)
        {
            gvDetailFleet.HeaderRow.Cells[i].Style.Add("background-color", "");
        }
        gvDetailFleet.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }

    public override void VerifyRenderingInServerForm(Control control)
    {

    }
}

A: You may try to do like this
    GridView gv = new GridView();
      gv.DataSource = sourceList; //Your datasource from database
                gv.DataBind();
                Response.ClearContent();
                Response.Buffer = true;
                Response.AddHeader("content-disposition", "attachment; filename=Preferred_Funds-" + DateTime.Now.ToShortDateString() + ".xls");
                Response.ContentType = "application/ms-excel";
                Response.Charset = "";
                StringWriter sw = new StringWriter();
                HtmlTextWriter htw = new HtmlTextWriter(sw);
                gv.RenderControl(htw);
                Response.Output.Write(sw.ToString());
                Response.Flush();
                Response.End();

A: //try this code inside the button
    Response.Clear();
    Response.AddHeader("content-disposition", "attachment;filename=ExportData1.xls");
    Response.Charset = "";
    Response.ContentType = "application/vnd.xls";
    StringWriter StringWriter = new System.IO.StringWriter();
    HtmlTextWriter HtmlTextWriter = new HtmlTextWriter(StringWriter);

    //batigol
    GridView1.AllowPaging = false;
    GridView1.DataSource = Session["uu"];
    GridView1.DataBind();
    //

    GridView1.RenderControl(HtmlTextWriter);
    Response.Write(StringWriter.ToString());
    Response.End();


text:
Q: Combining json files in python I have 3 json files as below:
test1.json:
{"item":"book1","price":"10.00","location":"library"}

test2.json:
{"item":"book2","price":"15.00","location":"store"}

test3.json:
{"item":"book3","price":"9.50","location":"store"}

I have this code:
import json
import glob

result = ''
for f in glob.glob("*.json"):
    with open (f, "r") as infile:
        result += infile.read()

with open("m1.json", "w") as outfile:
    outfile.writelines(result)

I get the following output:
{"item":"book1","price":"10.00","location":"library"}
{"item":"book2","price":"15.00","location":"store"}
{"item":"book3","price":"9.50","location":"store"}

Is it possible to get each file as a new line separated by a comma like below?
{"item":"book1","price":"10.00","location":"library"},  <-- line 1
{"item":"book2","price":"15.00","location":"store"},    <-- line 2
{"item":"book3","price":"9.50","location":"store"}      <-- line 3

A: As others commented, your expected result is invalid json.
But if you really want the format, use str.join() is more convenient.
jsons = []
for f in glob.glob("*.json"):
    with open (f, "r") as infile:
        jsons.append(infile.read())
result = ',\n'.join(jsons)

infile.read() gets the string, d = json.loads(infile.read()) can get a real json object(dict).
To write a valid combined json(of type list(of dict)), just write s = json.dumps(jsons) to file.


text:
Q: 'While Statement' for jobs running oracle I have a cursor to get the data of the cursors in state RUNNING or SCHEDULED
CURSOR cursorJobStatus IS
     SELECT d.job_name, d.state
       FROM dba_scheduler_jobs d
       WHERE REGEXP_LIKE(d.job_name, '^(P_|S_|B_)')
         AND d.state IN ('RUNNING','SCHEDULED');

how i can execute a loop while exist data in 'cursorJobStatus', That is, as long as there are 'jobs' in state RUNNING or SCHEDULED?
i tried with this 'for' but its not works, because only go in the 'for' by the records it finds and does not ask all the time for the state of the cursor
FOR lrtJobStatus IN cursorJobStatus LOOP
   BEGIN
     DBMS_LOCK.SLEEP(5);
   EXCEPTION
     WHEN NO_DATA_FOUND THEN
       EXIT;
   END;
   EXIT WHEN cursorJobStatus%NOTFOUND;
END LOOP;

thanks for any help!

A: Maybe something like this:
declare
   l_job_running pls_integer;
begin
   loop
      begin
         select 1
           into l_job_running
           from dual
          where exists (select 1
                   from dba_scheduler_jobs d
                  where regexp_like(d.job_name, '^(P_|S_|B_)')
                    and d.state in ('RUNNING', 'SCHEDULED'));
      exception
         when no_data_found then
            l_job_running := 0;
      end;

      exit when l_job_running = 0;

      dbms_lock.sleep(5);

   end loop;
end;

A: Tried making an anonymous block which will check for the current jobs  running and will continue to execute till there is a job which is executing. I guess you can achieve your objective the same way.
set serveroutput on;
declare
var1 number default '1';
begin
loop
dbms_output.put_line('inside the loop');
select count(*) into var1 from dba_jobs_running;
exit when var1=0;
dbms_output.put_line('job/jobs are executing');
end loop;
dbms_output.put_line('anonymous block completes');
end;


text:
Q: VBscript in IE11 I need help on this one.
Basically what the codes does is it gets data from an excel file and displays it through htm. This happened because my company won't provide me a database and server for php which would have made things easier.
The thing is that the codes were working on WinXP. But recently, we transitioned to Win7 and suddenly the codes seem to be not working anymore.
The error that I get when I view the IE11 F12 console is that the answerkey() is undefined.

<TITLE></TITLE>

<FORM id=myguestbook name=myguestbook method=post>

    <select name="name">
    <option value=""> </option>
    <option value="MarianB">Marian Berso</option>
    <option value="JiomerD">Jiomer Dacaymat</option>
    <option value="JoyD">Joy Daffon</option>
    <option value="LeoD">John Leo Dela Rosa</option>
    <option value="NestorG">Nestor Garlan Jr.</option>
    <option value="EdelaineP">Edelaine Pasadas</option>
    <option value="RamelP">Ramel Pasadas</option>
    <option value="AbigaelS">Abigael Serrano</option>
    <option value="AlonzoV">Alonzo Villaflor</option>
    </select>

    <INPUT onclick=VBscript:answerkey() type=submit value=SUBMIT name=functional></form>

PS. I am not sure if the codes is actually VBscript cause a colleague of mine just gave it to me and I worked my way into it.


text:
Q: apixu.client.ApixuException: Error code 1003: "Parameter q is missing." I do not understand the error I got this time, I'm running the apixu.com API on rasa_core when running even issued this kind of error, can you help me to explain it?

ERROR:rasa_core.processor:Encountered an exception while running action 'action_weather'. Bot will continue, but the actions events are lost. Make sure to fix the exception in your custom code.
ERROR:rasa_core.processor:Error code 1003: "Parameter q is missing."
  Traceback (most recent call last):
 File "C:\Program Files\Anaconda3\lib\site-packages\rasa_core\processor.py", line 302, in _run_action
    events = action.run(dispatcher, tracker, self.domain)

 File "C:\Program Files\Anaconda3\actions.py", line 18, in run
    current = client.getCurrentWeather(q=loc)
 File "C:\Program Files\Anaconda3\lib\site-packages\apixu\client.py", line 37, in getCurrentWeather
    return self._get(url, args)

 File "C:\Program Files\Anaconda3\lib\site-packages\apixu\client.py", line 27, in _get
    raise ApixuException(message=err_msg, code=err_code)

apixu.client.ApixuException: Error code 1003: "Parameter q is missing."

A: You have to have q as a parameter in the url. apixu alovs you to find the weather of a city using lontitude and latitude, city name, ZIP codes, and so on. but no matter what you use, you have to have q in the url. in the link below, you can see how you can use the parameter q.
https://www.apixu.com/doc/request.aspx


text:
Q: What could be the faster replacement of this sed command? I have a script where below sed command works on the input file.
 sed -i 's/SESSION_ID/sid/g;s/TIME_HOUR/hh/g;s/TIME_MINUTE/mm/g;s/TIME_SECOND/ss/g;s/TIME_MILLISECOND/mss/g;s/MSISDN/MS/g;s/IMSI/IM/g;s/IMEISV/IV/g;s/name_ALLOCATED_UE_ADDRESS_IPV4/aI4/g;s/IPV6/I6/g;s/OPERATION_TYPE/OT/g;s/LOCATION_AREA_CODE/LC/g;s/CELL_IDENTITY/CI/g;s/RAT_TYPE/RT/g;s/APN/AP/g;s/COUNTRY_CODE/CC/g;s/NETWORK_CODE/NC/g;s/name_SGSN_ADDRESS_IPV4/sI4/g;s/QCI/QC/g;s/SUBSCRIBERGROUP/SG/g;s/MONITORING_KEY/MK/g;s/QUOTA_VOLUME_BIDIRECTIONAL/QV/g;s/MBR_UL/MU/g;s/MBR_DL/MD/g;s/RULE_ID/RD/g;' $FiletosqeezE

Now the problem is..it is taking more time than expected to get executed. Could you please advise what could be the faster replacement of this sed command...we can even take the help of perl here.....thanks.

A: Using a command line perl (joining all the replacements into a single expression):
perl -i -pe '
    BEGIN {
      %hash = qw(SESSION_ID sid TIME_HOUR hh TIME_MINUTE mm TIME_SECOND ss TIME_MILLISECOND mss MSISDN MS IMSI IM IMEISV IV name_ALLOCATED_UE_ADDRESS_IPV4 aI4 IPV6 I6 OPERATION_TYPE OT LOCATION_AREA_CODE LC CELL_IDENTITY CI RAT_TYPE RT APN AP COUNTRY_CODE CC NETWORK_CODE NC name_SGSN_ADDRESS_IPV4 sI4 QCI QC SUBSCRIBERGROUP SG MONITORING_KEY MK QUOTA_VOLUME_BIDIRECTIONAL QV MBR_UL MU MBR_DL MD RULE_ID RD);
      $pat = join "|", sort {length($b) <=> length($a)} keys %hash;
    }
    s/\b($pat)\b/$hash{$1}/g;
  '  $FiletosqeezE

Switches:

*

*-i: Edit <> files in place (makes backup if extension supplied)

*-p: Creates a while(<>){...; print} loop for each "line" in your input file.

*-e: Tells perl to execute the code on command line.

A: If you need to be able actually do all those replacements on each line, you're unlikely to be able to make it much faster, at least with sed itself. Other tools, such as awk and perl, may give you improvements.
If there's a possibility you can take advantage of extra information you may have, there are some ways to make it possibly better.
For example, if you only expect one occurrence of each string (such as SESSION_ID) on each line, you can get rid of the global flag g, which will mean it won't process the rest of the line for each replacement.
Or, if each line only ever contains one of the keywords (e.g., no lines with both SESSION_ID and TIME_HOUR, you can use something like awk to do the substituting, and use next so that the first substitute moves immediately on to the next line rather than checking all the others.
Or, if you know that all keywords are at the start of the line, you can change your substitutes from:
s/SESSION_ID/sid/g

into:
s/^SESSION_ID/sid/

which will probably speed things up since it won't have to look beyond the first few characters.
But, without extra information, you may get faster performance by creating a hard-coded program for this specific purpose rather than using the more general-purpose sed with a script.
With that, you can tweak things like how much data is loaded with each read call and so on. I wouldn't expect too much of an improvement since your sed strings are fixed rather than regular expressions but it may be worth a shot if you're willing to put in the upfront effort.

For what it's worth, that sed command breezed through a 100M source file in less than 12 seconds on my box, I don't consider that too bad.
Just make sure that, whatever options you test, you test them properly. Measure, don't guess!

A: According to the famous sed one-liner text:
http://sed.sourceforge.net/sed1line.txt
If you modify your substitutions like this:
sed 's/something/changed/g;s/another/one/g'

to
sed '/something/ s//changed/g; /another/ s//one/g'

you get improvement, i tested it on a small file and the sys portion was halved:
(precise)cronkilla@localhost:/tmp$ time sed 's/dog/cat/g;s/fox/horse/g;s/quick/slow/g;s/the/blah/g' n4.txt > n6.txt

real    0m0.043s
user    0m0.039s
sys 0m0.004s

(precise)cronkilla@localhost:/tmp$ time sed '/dog/ s//cat/g;/fox/ s//horse/g;/quick/ s//slow/g;/the/ s//blah/g' n4.txt > n6.txt
real    0m0.052s
user    0m0.050s
sys 0m0.002s


text:
Q: Is there something special about the wndProc messages for a RichEdit20WPT window? I am currently trying to subclass an Edit Control, in particular the subject of en Email in the Outlook Client.  This control is of class RichEdit20WPT.
I get a wndProc by using the following WINAPI methods.
<DllImport("ComCtl32.dll", CharSet:=CharSet.Auto)> _
    Public Shared Function SetWindowSubclass(hWnd As IntPtr, newProc As Win32SubClassProc, uIdSubclass As IntPtr, dwRefData As IntPtr) As Integer
    End Function

 <DllImport("comctl32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
    Public Shared Function DefSubclassProc(ByVal hWnd As IntPtr, ByVal uMsg As IntPtr, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer
    End Function

    Public Delegate Function Win32SubClassProc(hWnd As IntPtr, Msg As IntPtr, wParam As IntPtr, lParam As IntPtr, uIdSubclass As IntPtr, dwRefData As IntPtr) As Integer

And would then have a wndProc like this;
Private WM_CONTEXTMENU As IntPtr = &H7B

Private Function SubClassProc(hWnd As IntPtr, Msg As IntPtr, wParam As IntPtr, lParam As IntPtr, uIdSubclass As IntPtr, dwRefData As IntPtr) As Integer

        Select Case Msg

            Case WM_DESTROY

            Case WM_NCDESTROY

            Case WM_LBUTTONDOWN

            Case WM_CONTEXTMENU   'NEVER HAPPENS

            Case WM_RBUTTONDOWN

        End Select

        Return DefSubclassProc(hWnd, Msg, wParam, lParam)
    End Function

I get the L and R button down and up messages but no WM_CONTEXTMENU.  My current intention is to add a menu item to the context menu so as an alternative I am using the WM_RBUTTONDOWN message.
Is this control special and known to not show the WM_CONTEXTMENU message?
I also have a challenge to find the messages that occur after choosing something on the context menu.  My understanding is that the messages of the menu item clicked in the context menu are given to the parent which in this case is this RichEdit20WPT window. Is this correct?  Note I am not making my own context menu I am appending to the existing one so I am not changing the owner of the context menu or anything like that.

A: Thank you to all the comments which helped me to at least keep searching for answers or in this case messages.  For anyone coming here and wanting to add to the context menu of an Outlook Menu.
First here are two good links which explain generally what to do.
How to disable copy/paste commands in the Windows edit control context menu?
Modify right-click context menu in standard controls
Anyone reading them can assume for a standard edit control such as a text box on a windows form application that the messages will be sent.
For Outlook (At least 2007 / 2010) this is what I have found;

*

*The text box you need to find for both an Explorer and Inspector is RichEdit20WPT

*This window however does not get two of the key messages required. (a) it does not get WM_INITMENUPOPUP to know before the context menu is being shown and secondly (b) it does not get a message when you choose something in the context menu which is a WM_COMMAND in this case.

*Inorder to amend the context menu you need to subclass the subject text box's parent which is a window of class #32770.

*As the parent is subclassed there are a few challenges. To know when our target text box as had a right click from the #32770 window you need to look for the WM_SETCURSOR.

Something like this where the wParam will be the text box's Hwnd and the HiWord will be the mouse message;
Case NativeMethodsEX.WM_SETCURSOR
    If wParam = subjectHwnd Then
        Dim pMap As New NativeMethodsEX.LParamMap(lParam)
    If pMap.hiword = NativeMethodsEX.WM_RBUTTONUP Then
        rightClickOnSubject = True
    Else
        rightClickOnSubject = False
    End If
    End If

Then shortly after there will be this message
Case NativeMethodsEX.WM_INITMENUPOPUP
    If rightClickOnSubject Then
        'check here if you want to display something.
    End If

Once you know this, you can implement the ideas from the other forum answers.


text:
Q: Can you compute one eigenspace without computing them all? Maybe the simplest non-trivial settings in which the spectrum of the Laplacian be can be computed is on the round sphere $\mathbf{S}^n$, and for products of manifolds. I want to use the two as examples to situate my question, which goes as follows.
Question. Can the first few eigenvalues of the manifold
\begin{equation}
\mathbf{S}^n \quad \text{or} \quad (M \times N,g \oplus h)
\end{equation}
say
$\lambda_1 \leq \cdots \leq \lambda_D$
be computed 'directly', using an argument that does not involve the other, higher eigenspaces?
I would be happy with an argument that produces the first $D = 5$ eigenvalues for example in either setting. To be clear, in the latter case one would assume knowledge of the spectra of $M$ and $N$. The question arose in a more complicated setting, in which the larger eigenvalues seem inaccessible even a posteriori.
To explain potential difficulties, let me point out a step that the two computations have in common. (I am following the book of Berger, Gauduchon and Mazet [1].) Both rely on the Stone-Weierstrass theorem, combined with the following lemma [Lemma A.II.1 on p.143,1].
Lemma. Let $(M,g)$ be a compact manifold and $(V_i \mid i \in \mathbf{N})$ be a collection of vector subspaces of $C^\infty(M)$ so that for all $i \in \mathbf{N}$ there is $\lambda_i \in \mathbf{R}$ for which $\Delta \varphi = \lambda_i \varphi$ for all $\varphi \in V_i$. If $\sum_i V_i$ is $L^2$-dense in $C^\infty(M)$ then the spectrum of $(M,g)$ is $(\lambda_i \mid i \in \mathbf{N})$ and the $V_i$ are its eigenspaces.
I want to avoid going into too much detail, but just quickly illustrate how this is used in the latter example, to compute the spectrum of the product manifold
$(M \times N,g \oplus h)$ [Prop. A.II.3 on p. 144,1]. Basically this states that its eigenspaces all factor into
\begin{equation}
\mathcal{E}_\nu(M \times N) = \mathcal{E}_\lambda(M) \otimes \mathcal{E}_\mu(N) \quad \text{with $\nu = \lambda + \mu$.}
\end{equation}
The first inclusion $\mathcal{E}_\nu(M \times N) \supset \mathcal{E}_\lambda(M) \otimes \mathcal{E}_\mu(N)$ is easy. It is the reverse inclusion that uses Stone-Weierstrass and the lemma cited above. A by-product of this is that the relation above is simultaneously established for all eigenvalues.
[1] Berger, M., Gauduchon, P., Mazet, E. Le spectre d'une variete riemannienne. Lect. Notes Math. 194 (1971).


text:
Q: How to install Omnet++ 4.6 on windows I would like to install Omnet++ 4.6 on my Windows 10 64 bits system and I'm not able to do it. First, I checked in the install guide pdf file on the website and it says to double click on mingwenv.cmd. I don't have this file in the folder I have downloaded but I have vcenv.cmd file (maybe they renamed the file)
To see what files are in omnet++ 4.6 zip folder : https://gyazo.com/2643c45b11f5346cd891efcfb9478787
I tried to run vcenv.cmd file a cmd window pop-up and close. I need to install this for my job and this could be appreciated if you could help me. Thanks

A: You have downloaded linux version of OMNeT++. Download the package described as OMNeT++ 4.6 win32 (source + IDE + MinGW, zip).


text:
Q: Selection screen parameter with a dynamic matchcode I have a serie of entry parameters where there a match code, I need that this field (matchcode) will be dependent of a text parameter. For example, something like that :
SELECTION-SCREEN BEGIN OF BLOCK block02 WITH FRAME TITLE text-002.
  PARAMETERS:
    p_mona   TYPE ZTIPOSOL GROUP rad1 MATCHCODE OBJECT ZFIMC002,
    p_fcomp  TYPE SY-DATUM MODIF ID A OBLIGATORY.
SELECTION-SCREEN END OF BLOCK block02
ABAP Development

A: No, you cannot. However, you can populate search help values dynamically in AT SELECTION-SCREEN ON VALUE-REQUEST event:
DATA: LT_VBAK TYPE STANDARD TABLE OF VBAK.

PARAMETER P_VBELN TYPE VBELN.

AT SELECTION-SCREEN ON VALUE-REQUEST FOR P_VBELN.

  CALL FUNCTION 'F4IF_INT_TABLE_VALUE_REQUEST'
      EXPORTING
       RETFIELD       = 'VBELN'
       DYNPPROG       = SY-REPID
       DYNPNR         = SY-DYNNR
       DYNPROFIELD    = 'P_VBELN'
       VALUE_ORG      = 'S'
      TABLES
       VALUE_TAB      = LT_VBAK
      EXCEPTIONS
       PARAMETER_ERROR        = 1
       NO_VALUES_FOUND        = 2
       OTHERS                 = 3.

  IF SY-SUBRC <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
  ENDIF.

where LT_VBAK is a internal table you need to populate with values.
If your values are dependent on another selection screen parameter, use DYNP_VALUES_READ FM to read them from screen.
Another approach is not to dynamically fill values but to create a single Search Help in DDIC and create Search Help exit which will control SHELP behavior depending on some conditions.


text:
Q: Syntax for casting a receiver in Objective-C I have a class/super class pair declared thus:
@class WSStatement;
@interface WSIfStatement : WSStatement
@property (nonatomic, retain) WSStatement *thenstatement;
@end

I create an instance of the subclass using Core Data and assign it to a WSStatement * pointer (i.e. the super class).  At some later point I want to send a message to the object that is specific to the subclass, and the compiler is giving me a warning saying "instance method not found (return type defaults to 'id')"
I have tried casting like this ....
[(WSIfStatement *)statement setThenStatement:aVariableParameter];

but the warning persists.  The program executes perfectly, but I can't rid myself of the pesky compiler warning.  I couldn't find a complete formal Objective-C syntax description anywhere, so I apologise if the answer is obvious!!
Thanks

A: If it is not a typo then the problem is you are calling the wrong method.
@property (nonatomic, retain) WSStatement *thenstatement;

//Will be called with a lowercase s for statement
[(WSIfStatement *)statement setThenstatement:aVariableParameter];

Also you can not just forward declare a class that you inherit from. You will need to include the header for WSStatement. And if you still have an error make sure you synthesize thenstatement in the implementation.

A: Have you synthesised the properties?  In you .m file use:
@synthesize thenstatement;

This will generate the set function.

A: Try adding #import "WSIfStatement.h" to your .m file where you're making that call.


text:
Q: Is there a regular expression based servlet filter for web.xml? I am in the process of migrating some code from Guice to Spring. guice-servlet has the nice feature that allows you to match servlet filters using regular expressions. For example I am using
filterRegex("^.*\\.cache\\..*$").through(ForceCacheFilter.class);

I need to replicate this in Spring.
I could easily write a filter that takes a regular expression and the class name of a filter to delegate to as a parameter/attribute. It would match the URL against the regexp and delegate to the filter class if required. I guess this could be taken further and have a filter that dispatches to multiple filters based on regexps - just like what Guice is doing.
What I am surprised about is that I haven't been able to find something that does this already. Maybe I haven't looked hard enough or maybe its not such a good idea?
Does something like this exist or do I need to write some code?

A: do you mean something like?
<filter>
        <filter-name>someFilter</filter-name>
        <filter-class>org.springframework.web.filter.SomeFilter</filter-class>
</filter>

<filter-mapping>
        <filter-name>someFilter</filter-name>
        <url-pattern>/somePath/*</url-pattern>
</filter-mapping>


text:
Q: Jersey REST Client : Posting MultiPart data I am trying to write a Jersey client app which can post multi part form data to a Restful Jersey service. I need to post a CSV file with the data and a JSON with meta-data. I am using Jersey client 1.18.3. Here is my code (some names have been changed for company confidentiality )...
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/mariam/service/playWithDad");

    FileDataBodyPart filePart = new FileDataBodyPart("file",
            new File("C:/Users/Admin/Desktop/input/games.csv"));

    String playWithDadMetaJson
    = "{\n"
    + "    \"sandboxIndicator\": true,\n"
    + "    \"skipBadLines\": false,\n"
    + "    \"fileSeparator\": \"COMMA\",\n"
    + "    \"blockSize\": false,\n"
    + "    \"gameUUID\": \"43a004c9-2130-4e75-8fd4-e5fccae31840\",\n"
    + "    \"useFriends\": \"false\"\n"
    + "}\n"
    + "";

    MultiPart multipartEntity = new FormDataMultiPart()
    .field("meta", playWithDadMetaJson, MediaType.APPLICATION_JSON_TYPE)
    .bodyPart(filePart);

    ClientResponse response = webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(multipartEntity);

Right now I am getting a compile error at the last line saying it cannot convert from void to ClientResponse.
I got some guidance on the RestFul service itself previously from this post..
Java Rest Jersey : Posting multiple types of data (File and JSON)

A:
"Right now I am getting a compile error at the last line saying it cannot convert from void to ClientResponse."

Look at the javadoc for WebResource. Look at the post(Object) (with Object arg). It returns void.
You need to be using the overloaded post(Class returnType, requestEntity), which return an instance of returnType type.
So you should be doing something like
ClientResponse response = webResource
        .type(MediaType.MULTIPART_FORM_DATA_TYPE)
        .post(ClientResponse.class, multipartEntity);

A: Follow jersey documentation, they provide sample client code. Here is the snippet to post a multipart request:
final MultiPart multiPartEntity = new MultiPart()
        .bodyPart(new BodyPart().entity("hello"))
        .bodyPart(new BodyPart(new JaxbBean("xml"), MediaType.APPLICATION_XML_TYPE))
        .bodyPart(new BodyPart(new JaxbBean("json"), MediaType.APPLICATION_JSON_TYPE));

final WebTarget target = // Create WebTarget.
final Response response = target
        .request()
        .post(Entity.entity(multiPartEntity, multiPartEntity.getMediaType()));


text:
Q: Exception thrown when attempting to delete object from listview I'm working in javafx. I have a Listview which is updated by an ObservableList.
Here is my code.
//Dummy list for testing listview
    final ObservableList<String> names = FXCollections.observableArrayList(
            "Julia", "Ian", "Sue", "Matthew", "Hannah", "Stephan", "Denise");

    final ListView<String> listView = new ListView(names.sorted());

    //Try to remove the first element for testing purposes
    listView.getItems().remove(0);

When I try to delete I get this exception.
Exception in Application start method
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.UnsupportedOperationException
    at java.util.AbstractList.remove(AbstractList.java:161)
    at sample.Main.start(Main.java:39)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    ... 1 more
Exception running application sample.Main

Is there some step that I'm missing in this case? Or am I trying to use ObservableList and ListView in the wrong way?

A: You are using javafx.collections.transformation.SortedList<E> in an incorrect way.
It's only a wrapper, a view.
To remove an element, you have to use the source collection: names.
javafx.collections.transformation.SortedList<E> doesn't implements remove() but:

Wraps an ObservableList and sorts it's content. All changes in the
  ObservableList are propagated immediately to the SortedList. Note:
  invalid SortedList (as a result of broken comparison) doesn't send any
  notification to listeners on becoming valid again.

JavaDoc of javafx.collections.transformation.SortedList
This tutorial may help.


text:
Q: Send Multiple Device Tokens to Parse through CURL I am using Parse to send push notifications to my iOS app users. This works well, but the way I have constructed it leads to a page timeout when sending the push to many users.
The code below is in a while loop that sends the data one device token at a time through curl. How would I reconstruct the payload so that I can push a single JSON array that will contain all of the device tokens etc... Any ideas?
My While Loop:
$target_device = $row['device_token'];

$push_payload = json_encode(array(
        "where" => array(
                "deviceToken" => $target_device,
        ),
        "data" => array(
                "alert" => "$message"
        )
));

$rest = curl_init();
curl_setopt($rest,CURLOPT_URL,$url);
curl_setopt($rest,CURLOPT_PORT,443);
curl_setopt($rest,CURLOPT_POST,1);
curl_setopt($rest,CURLOPT_POSTFIELDS,$push_payload);
curl_setopt($rest,CURLOPT_HTTPHEADER,
        array("X-Parse-Application-Id: " . $appId,
                "X-Parse-REST-API-Key: " . $restKey,
                "Content-Type: application/json"));

$response = curl_exec($rest);

A: Use set_time_limit(0); so that your page doesn't get the timeout.
You are also try using the curl_milti for parallel curl requests. But it will not help you to avoid the timeout if the requests are too many.


text:
Q: Difference between standard price and the overall average standard price of all products I'm running this query basically word for word from the book.
Provide a listing of all of the products that includes the difference between its standard price and the overall average standard price of all products.
SELECT ProductStandardPrice – PriceAvg AS Difference
FROM Product_T, (SELECT AVG(ProductStandardPrice) AS PriceAvg
FROM Product_T);

I keep getting this error:

Msg 102, Level 15, State 1, Line 3  Incorrect syntax near ';'.

A: Your specific error is because you don't have a table alias.  I also abhor commas in the FROM clause, so:
SELECT (t.ProductStandardPrice – a.PriceAvg) AS Difference
FROM Product_T t CROSS JOIN
     (SELECT AVG(ProductStandardPrice) AS PriceAvg
      FROM Product_T
     ) a;

However, the best way to answer this question is to use window functions:
SELECT (t.ProductStandardPrice – AVG(t.ProductStandardPrice) OVER ()
       ) AS Difference
FROM Product_T t ;


text:
Q: Build docker image with python application using PyQt4 library I am trying to dockerise a small python application. The python code uses the PyQt4 library. The app has some test units which I run when I build the image. Something like the following:
RUN [ "/bin/bash", "-c", "source activate conda_environment && python -m unittest tests/tests_html_consistency.py" ]

The PyQt4 library in the python code needs a X server to do its things, but docker do not have one, therefore, unfortunately when I build the image I get the following error:
python -m unittest: cannot connect to X server

On other similar stack questions I found that a possible solution would be to simply mount the socket for the X server as a Docker volume and tell Docker to use that instead.
docker run -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY=unix$DISPLAY TheImage

But how do I do this at image build time? The above command works only when the image is already build, at 'docker run' time. Moreover, if the host machine is an aws instance (hence without x server) would that work? I don't think so...

A: Try using the --build-arg command so:
docker build -t yourContainer --build-arg DISPLAY=$DISPLAY .


text:
Q: Insert query with condition I am trying to create an SQL query wherein I need to check to sum of columns from 2 tables and then insert a new row into another table if the condition is satisfied. I know I can use a stored procedure with explicit locking but want to know is it is possible to do it in a single SQL query. I wrote the following but it gives syntax error in MySQL workbench
INSERT INTO table1 (`col1`, `col2`)
VALUES ('abc', 'xyz') WHERE
(
((select
COUNT(*) from table2 t2 where t2.id = 1)
+ (select sum(t3.counter) from table3 t3
WHERE t3.id = 1)) < (select t4.total_allowed
FROM table4 t4 where t4.id = 1)
);

A: This can be done because you can insert the results of a select query.
INSERT INTO table1 (`col1`, `col2`)
SELECT 'abc', 'xyz'
FROM DUAL WHERE
(
((select
COUNT(*) from table2 t2 where t2.id = 1)
+ (select sum(t3.counter) from table3 t3
WHERE t3.id = 1)) < (select t4.total_allowed
FROM table4 t4 where t4.id = 1)
);

A: MySQL INSERT Syntax does not support the WHERE clause.


text:
Q: Is there an inbuilt animation to switch ccsprites? Like you would with a card in real life I've recently started iPhone development, and doing a gameproject.
I have a Piece class that inherits CCSprite, that cointains 2 ccsprites, frontSprite and backsideSprite.
The idea with this is that when I touch the Piece object, it will do some magic and turn the piece, showing backsideSprite. This in itself is easy, but the animation is what I am curious about, and how to make it as easy on me as possible (I'm not that good at designing graphics).
So the question really is, is there a method, inbuilt method in cocos2d etc, that have animations for my wish? That takes this box/rectangle and turns its side? Like you would turn a card in real life.
If it is not an inbuilt method for this, I basically have to go into designmode and make a sequence of pictures that I run right?
Thanks for any feedback.

A: id firstAction = [CCOrbitCamera actionWithDuration:1 radius:1 deltaRadius:0 angleZ:0 deltaAngleZ:90 angleX:0 deltaAngleX:0];
id secondAction = [CCCallFunc actionWithTarget:self selector:@selector(changeCardImage)];
id thirdAction = [CCOrbitCamera actionWithDuration:1 radius:1 deltaRadius:0 angleZ:270 deltaAngleZ:90 angleX:0 deltaAngleX:0];

[art1 runAction:[CCSequence actions:firstAction,secondAction,thirdAction,nil]];

-(void)changeCardImage{

      front.texture = [[CCTextureCache sharedTextureCache] addImage:@"backSideSprite.png"];

}


text:
Q: What is conversation in jboss seam? I am new to seam framework and have been using it since few weeks now. I came across some tags related to seam conversation. But I did not understand what conversation means and when to use it?
Can anybody give me some details about this with an example?
Thanks in advance.

A: Conversation is a intermediate context between Request and Session. It is not only related to a SGBD session as glmlima said. You can use a conversation always that you want to maintain the state os your beans through many requests and pages (like when you wnat to buy a ticket to a show) and dont want to keep it in your session.
A conversation lasts as long as you want to use it and you can have as many conversations as you want in your session.
I hope it helps to understand conversational context.

A: Which Seam Framework version are you using? In short, persistence contexts scoped to the conversation allows you to program optimistic transactions that span multiple requests to the server without the need to use the merge() operation , without the need to re-load data at the beginning of each request, and without the need to wrestle with the LazyInitializationException or NonUniqueObjectException (Seam Docs).
If you want to know the basic concepts about conversation, I suggest reading this Seam Conversation.
If you are using the Seam 3, it has aggregate JavaEE6 new features, like CDI.


text:
Q: Is there anyway to force thread context switch, especially in some operation like ++? I am wondering any way to force thread context switch? Sleep, Yield? any recommended way? Need to do some testing. Specially, can we force context switch in the ++ operation?

A: You can try replacing
a++;

with
int tmp = a;
Thread.sleep(1);
a = tmp + 1;

A: Thread.yield() doesn't necessarily guarantee a switch will happen (in practice, at least, if nothing is waiting to run at that time, this is a noop).  Thread.sleep() will pretty near guarantee it - but there's no way to cause it to happen in a ++ operation, since there's no way to override the default implementation.   What are you actually trying to cause to happen?  Would causing the switch just before or after suffice?   Can you emulate what you're trying to do by setting a "watch" using your favorite IDE?


text:
Q: How to get items of generic type from ComboBox I thought this will be a trivial task, but all is not that simple. The thing is that a user can insert item(s) into ComboBox in two ways:

*

*By simply typing in a text

*By pasting data from clipboard (by means of a button).

First, I had this extension method:
internal static IEnumerable<T> GetItems<T>(this ComboBox comboBox)
{
    return comboBox.Items.Cast<T>();
}

And usage:
var items = comboBox.GetItems<string>();

This does not work for manually typed text, since this text doesn't belong to Items collection - and thus I get empty list. One trick I thought of is to insert this text into Items collection before returning:
internal static IEnumerable<T> GetItems<T>(this ComboBox comboBox)
{
    if (!comboBox.HasItems)
    {
        comboBox.Items.Add(comboBox.Text);
    }
    return comboBox.Items.Cast<T>();
}

But then we have a problem here: a user can type another text, and then we have two items, because previous text was inserted! We can clear Items collections before proceeding, but... what if items were inserted through clipboard? :) This way all items pasted will be cleared out? :)
Do I miss something? Is there some solution to it?

A: Fix combobox1.Items.Add() function. Change combobox1.Items.Add(combobox.Text); to combobox1.Items.Add(new ComboBoxItem(){Content=combobox1.Text});
That's all you have to do.


text:
Q: Emacs ligatures overwrite previous characters I'm setting up the Fira Code font/ligatures on Emacs 26 for Windows, according to the guide at https://github.com/tonsky/FiraCode/wiki/Emacs-instructions#using-font-lock-keywords.
It creates the ligatures, but they are all shifted back. I'm guessing it's shifted one space per character in the ligature.
I tested using the text:
int test()
{
    ptr->field = (a == b) ? 1 : 2;

}

https://www.website.com

screenshot

How do I correct this?


text:
Q: Hashing multiple values in golang I'm currently working on an application in go that needs to cache different resources. Different types of resources have handlers that will know what data is relevant to determine, if we have to rebuild a resource or if we can fetch it from cache. For this purpose handlers shall generate a hash of all relevant data for caching. Depending on the context that data can be primitives (int, float, ...), strings, slices, structs and maps. So almost everything. The number of objects used for hashing might also vary.
To calculate that hash in handlers, I've created a hashing function with variadic parameters of type interface{}.
My current approach is this:
func Hash(objs ...interface{})([]byte) {
    // Use MD5 because it's fast and is reasonably enough protected against accidental collisions.
    // There is no scenario here where intentional created collisions could do harm.
    digester := crypto.MD5.New()

    encoder := gob.NewEncoder(digester)
    encoder.Encode(objs) // In real life one would handle that error

    return digester.Sum(make([]byte, 0))
}

This works. But there are a few things that give me headaches with this implementation. Because I'm not sure that gob will always behave deterministic, for the current version that seems to be the case, but as the referenced answer points out, there might be changes between versions.
According to the documentation for gob, default values (0 for ints, empty strings, nil, ...) will be omitted when transporting structs. Also all int values will be transmitted as generic numbers. So unit64 and int will be the same. I can't think of an actual issue with this for my usecase, but this smells like a source for trouble.
Now if I would write that function from scratch I would properly play it safe, traverse the structure with reflection and create a hashing tree. But I don't want to do that.
I'm pretty sure I'm not the first one out there with these requirements, but I wasn't able to find any well tested go code on the web, that addresses this issue.
Appendix
Also see: https://crypto.stackexchange.com/questions/10058/how-to-hash-a-list-of-multiple-items
This is not as trivial as it may seem. Simply concatenating data as pointed out by Adrian won't work, because then Hash("12", "3") and Hash("123") will generate the same hash. One possible solution is to prepend the length of data (and the number of elements of lists) before hashing or to create a tree of hashes, but I can't think of a reliable way to do either of that with complex data structures, without writing a lot of reflection code that handles all the different cases (integers, floats, strings, structs, slices, ...) and walks through the entire structure. I want to avoid that, because there are a lot of special cases that can be overseen doing so and it seems unnecessary complicated to me. This is why I tried to solve the problem using serialization, which will take care of most of the problems described above. I'm just not sure if there are not some drawbacks of using gob in this scenario and if there isn't a smarter solution to the problem.

A: Perhaps to add to add to Adrian's answer. If you add fmt.Fprintf(digester, reflect.TypeOf(ob)) before each object. That would make Hash("12", "3") and Hash("123") different.
package main
import (
    "crypto"
    _ "crypto/md5"
    "fmt"
    "reflect"
)

func main() {
    fmt.Printf("%x\n", Hash("12", "3"))
    fmt.Printf("%x\n", Hash("123"))
}

func Hash(objs ...interface{}) []byte {
    digester := crypto.MD5.New()
    for _, ob := range objs {
        fmt.Fprint(digester, reflect.TypeOf(ob))
        fmt.Fprint(digester, ob)
    }
    return digester.Sum(nil)
}

Output:
c3d5dcf1d7540d3e46e7d7b5a8c6e8ae
787ca7e12a2fa991cea5051a64b49d0c

https://play.golang.org/p/nufD3wTJkb

A: Hash providers implement io.Writer, meaning you can just write data to them as necessary - you don't have to do it all in a single call to Sum:
for _,ob := range objs {
    fmt.Fprint(digester, ob)
}
return digester.Sum(nil)

Working playground example: https://play.golang.org/p/HtObhrmoaP
If you need to support non-primitive types, you can use something like:
fmt.Fprintf(digester, "%+v", ob)

Or even just:
json.NewEncoder(digester).Encode(&objs)

Like gob, the output of json may change between Go versions, but it seems much less likely as JSON is a very stable format with a very stable implementation.


text:
Q: Compare two columns and make the insert I want to compare two columns which come from two different tables.
One of the columns, I need to make SUM for all rows with identity let's say 3 and store to a variable.
After that, compare with one row from other table for same identity 3 and  to INSERT something ELSE to BREAK if first_column <= second_column.
Can someone suggest some query for this? For Postgresql...
CREATE OR REPLACE FUNCTION "SA_PRJ".usp_add_timesheet_test(p_uid integer, p_project_id integer, p_allocated_time numeric, p_achieved_time numeric, p_task_desc character varying, p_obs character varying, p_date timestamp without time zone)
  RETURNS character varying AS
$BODY$
DECLARE sum_alloc_time numeric;
DECLARE alloc_hours integer;
DECLARE fld_id integer;
DECLARE alloc_id integer;

BEGIN
   if not "SA_ADM".usp_check_permission(p_uid, 'SA_PRJ', 'usp_add_timesheet_record') then
    raise exception 'User ID % dont have permission!', p_uid;
   end if;

   select a.fld_id into alloc_id from "SD_PRJ".tbl_project_allocation a where a.fld_emp_id = p_uid and a.fld_project_id = p_project_id;

   SELECT SUM(fld_allocated_time)
   INTO           sum_alloc_time
   FROM   "SD_PRJ".tbl_project_timesheet
   WHERE  fld_project_id = p_project_id;

   SELECT p.fld_allocated_days, p.fld_id
   INTO            alloc_hours,   fld_id
   FROM   "SD_PRJ".tbl_project p
   JOIN   "SD_PRJ".tbl_project_timesheet t USING (fld_id)
   WHERE  t.fld_project_id = p_project_id;

  IF @sum_alloc_time <= @alloc_hours THEN

  INSERT INTO "SD_PRJ".tbl_project_timesheet
    (fld_emp_id, fld_project_id, fld_is_allocated,   fld_allocated_time
   , fld_achieved_time, fld_task_desc, fld_obs, fld_date)
  VALUES (p_uid,   p_project_id, coalesce(alloc_id,0), p_allocated_time
     , p_achieved_time,   p_task_desc,   p_obs,   p_date);

     RAISE NOTICE 'INSERT OK!';

 ELSE
  RAISE NOTICE 'NOT OK';
 END IF;
END

1.tbl_project (fld_id, fld_allocated_days,fld_project_id)
2.tbl_project_timesheet(fld_id,fld_allocated_time,fld_project_id), all INTEGER
I have this , but dosen't work as I wish.Thanks

A: I think one problem is here:
 SELECT p.fld_allocated_days, p.fld_id
   INTO            alloc_hours,   fld_id
   FROM   "SD_PRJ".tbl_project p
   JOIN   "SD_PRJ".tbl_project_timesheet t USING (fld_id)
   WHERE  t.fld_project_id = p_project_id;

That will cough (I think) whenever the select query returns more than one row i.e. whenever tbl_project_timesheet has more than one record for a fld_id,project_id combination.
Anyway. Here's a partial, simplified answer, but hopefully you get the idea...
I wouldn't use local variables. Do the insert in one step:
INSERT INTO timesheet(emp_id,project_id) -- other columns
SELECT
    p_uid,p.fld_project_id -- other columns
FROM

    projects p

INNER JOIN
    (SELECT SUM(fld_allocated_time) as sumtime
        FROM timesheet t WHERE fld_project_id = p_project_id) as sumtime_subquery
ON p.fld_allocated_days < sumtime -- just join on the allocated time
WHERE p.fld_project_id = p_project_id;

Now, you need to know if anything was actually inserted. I think you can use the RETURNING option of the INSERT statement, e.g. from here (caveat - I have never used RETURNING, nor set a local variable from a with statement):
WITH ROWS AS (
 INSERT INTO timesheet(emp_id,project_id) -- other columns
    SELECT
        p_uid,p.fld_project_id -- other columns
    FROM

        projects p

    INNER JOIN
        (SELECT SUM(fld_allocated_time) as sumtime
            FROM timesheet t WHERE fld_project_id = p_project_id) as sumtime_subquery
    ON p.fld_allocated_days < sumtime -- just join on the allocated time
    WHERE p.fld_project_id = p_project_id
    RETURNING 1
    )
    SELECT COUNT(*) into l_updatedCount FROM rows; -- you have to declare l_updatedCount

-- Now an if statement to handle l_updatedCount


text:
Q: EMR auto terminate cluster not completing spark application? I intend to create an auto terminating EMR cluster that executes a spark cluster and shuts down.
If I submit the application as a step to an existing cluster that does not auto terminate using the following command, it works and application completes in 3 minutes.
aws emr add-steps --cluster-id xxx \
--steps Name=imdbetlapp,Jar=command-runner.jar,Args=\
[spark-submit,--deploy-mode,cluster,--master,yarn,--conf,spark.yarn.submit.waitAppCompletion=true,\
--py-files,s3://bucketname/etl_module.zip,\
--files,s3://bucketname/etl_module/aws_config.cfg,\
s3://bucketname/run_etl.py],ActionOnFailure=CONTINUE --region us-east-1

However, when i use the following command to create an auto terminating cluster with a step function, the application keeps running for more that 30 minutes.
aws emr create-cluster --applications Name=Hadoop Name=Spark --use-default-roles \
--bootstrap-actions Path=s3://bucketname/emr_bootstrap.sh,Name=installPython \
--log-uri s3://logbucketname/elasticmapreduce/ \
--configurations https://s3.amazonaws.com/bucketname/emr_configurations.json \
--steps Name=imdbetlapp,Jar=command-runner.jar,Args=[spark-submit,--deploy-mode,cluster,\
--master,yarn,--conf,spark.yarn.submit.waitAppCompletion=true,\
--py-files,s3://bucketname/etl_module,\
--files,s3://bucketname/etl_module/aws_config.cfg,s3://bucketname/run_etl.py] \
--release-label emr-5.29.0 --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large \
InstanceGroupType=CORE,InstanceCount=1,InstanceType=m4.large \
--auto-terminate --region us-east-1

What am I missing out?
I have zipped my etl python module and uploaded that along with the actual folder and configuration file aws_config.cfg. It works perfectly if submitted as a step function to existing cluster as I can see output being written to another S3 bucket. However, if I issue a CLI command to create a cluster and execute the step the step keeps executing forever.