text:
Q: Should Windows Multipoint Server stations on individual video cards support hardware video acceleration? I've set up a test machine with multiple PCI-e nVidia GF440 Video cards and installed Windows Multipoint Server 2011.
I use the same kind of hardware set up with a BeTwin multiseat solution to create a class lab for Google SketchUp teaching (highly OpenGL dependent) and it works ok.
On the Multipoint Windows test machine the drivers seem to be installed OK but I don´t seem to get any hardware video acceleration. Is this a intrinsic limitation of this solution or am I doing something wrong?

A: I understand 3D acceleration is not supported with Multipoint Server. There has been a similar question on superuser.com and an observation similar to yours documented at the MS support forum.


text:
Q: Any suggestion to tune this query using group by function I am trying to simplify this query using group by but got stuck. Any suggestions?
SELECT Distinct  Model,Age,Gender,
      (Select count(Gender) From [EDW].[sio].[TB_R_SURVEY_IN_OPERATION] g Where
          g.Model = t.Model And Gender <> 'NULL') Total_Gender,
      (Select count(Gender) From [EDW].[sio].[TB_R_SURVEY_IN_OPERATION] g Where
          g.Model = t.Model AND Gender = 'Laki-Laki') Male_Gender,
      (Select count(Gender) From [EDW].[sio].[TB_R_SURVEY_IN_OPERATION]
          g Where g.Model = t.Model AND Gender = 'Perempuan') Female_Gender,
      (Select Count(Age) From [EDW].[sio].[TB_R_SURVEY_IN_OPERATION]
         t1 Where t1.Model = t.Model AND t1.Age = t.Age AND (t1.Age <> 'NULL' AND t1.Age IS
              NOT NULL)) Age_Count
from [EDW].[sio].[TB_R_SURVEY_IN_OPERATION]  t

A: Your request is very vague. I understand this as: "My query is almost doing what I want it to do, but somehow the result is not as well structured as I want it to be. Please help me get a grip on this."
You select one row per model, age and gender. For this to happen we would usually GROUP BY model, age, gender, but you are rather using DISTINCT, because you are doing the aggregations in subqueries, and the aggregations only partly refer to the group. So for instance you show a row for model = A, age = 30, gender = male, but the counts show

*

*the model's total count for all genders and ages

*the model's males count, no matter what age

*the model's females count, no matter what age

*and at last the model's and age's overall count (i.e. regardless of the gender).

The next row may be for model = A, age = 30, gender = female, and you'll show exactly the same figures. And a row for model = A, age = 100, gender = female will show the same figures again, except for the age count.
What you must do here is think about what result you really want. Take a paper, draw a table, fill it with the desired result. You will see that you either want one result row per model and age and gender (GROUP BY model, age, gender) or per model and age (GROUP BY model, age). Then do your counting. COUNT(*) simply counts the rows for the group, and it's likely you are interested in the group's count.
Then you can get sub counts, be using conditional aggregation. This means you apply a condition inside the aggregation function. COUNT(CASE WHEN GENDER = 'Laki-Laki' THEN 1 END) gives you the count of males in the group for instance.
At last you can count super groups by applying SUM OVER on the counts. Thus you can get the model's overall count for instance via SUM(COUNT(*)) OVER (PARTITION BY model).
Here are two examples. Adjust them according to what you really need.
select
  model,
  age,
  gender,
  count(*) as count_for_model_age_and_gender,
  sum(count(*)) over (partition by model) as count_for_model,
  sum(count(*)) over (partition by model, gender) as count_for_model_and_gender,
  sum(count(*)) over (partition by model, age) as count_for_model_and_age
from edw.sio.tb_r_survey_in_operation
group by model, age, gender
order by model, age, gender;

select
  model,
  age,
  count(*) as count_for_model_and_age,
  sum(count(*)) over (partition by model) as count_for_model,
  count(case when gender = 'Laki-Laki' then 1 end) as count_male_for_model_and_age,
  count(case when gender = 'Perempuan' then 1 end) as count_female_for_model_and_age,
  sum(count(case when gender = 'Laki-Laki' then 1 end)) over (partition by model) as count_male_for_model,
  sum(count(case when gender = 'Perempuan' then 1 end)) over (partition by model) as count_female_for_model
from edw.sio.tb_r_survey_in_operation
group by model, age
order by model, age;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Load the tableview in another viewcontroller's view Is there any way to load a uitableview from a storyboard?

Such as the Table View in my image.
What I did is:
self.view addSubView:vc.view not worked.
I want to load the tableview in another viewcontroller's view.
thanks in advance!


text:
Q: Is automatic widget install still not possible in Android? Can I install/add widgets during app installation or from within the app? (With User persmission, if possible)
Found an old, answered question. Is this still not possible in Nov'16?

A:
Can I install/add widgets during app installation or from within the app?

No.
As Android users know, there are many home screen implementations for Android. Across the thousands of device models there are hundreds of different pre-installed home screen implementations. And there are hundreds, if not thousands, of additional home screen implementations that the user can download and install from places like the Play Store.
None of these home screens have to support app widgets.
As such, Google did not implement an API to ask the home screen to install an app widget, let alone implement an API to force the home screen to install an app widget.
It is possible that some home screen implementations expose their own API for this, though I am not aware of any that do.


text:
Q: Flask_restPLUS + NGINX TypeError I am developing an api using FLASK restPLUS + NGINX and with my intial route getting a type error:
The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a Employee.
My api.py looks like:
from flask import Flask
from flask_restplus import Api, Resource

app = Flask(__name__)
api = Api(app)

@app.route("/employee")
class Employee(Resource):
    def get(self):
        response = dict({'hey': 'there'})
        return response

My project tree is:
app
├── docker-compose.yml
├── flask
│   ├── Dockerfile
│   ├── .dockerignore
│   ├── app
│   │   ├── __init__.py
│   │   └── api.py
│   ├── app.ini
│   ├── requirements.txt
│   └── run.py
├── nginx
│   ├── Dockerfile
│   └── nginx.conf
├── .gitignore
└── readme.md

A: The decorator is wrong.  I have app.route needs to be api.route


text:
Q: How can I make a regular expression that contains special characters, like word boundaries, with a variable? In Javascript, I am trying to write a regular expression that will match a word that is contained in a variable, but only when the word is a whole word. I wanted to do this by using word boundaries, like this:
var data = 'In this example of data, word has to be replaced by suggestion, but newword must not be replaced';
var item = {word: 'exampleWord', suggestion: 'suggestion'}
var word = "\b"+item.word+"\b";
var suggestion = item.suggestion;
var re = new RegExp(word, "gi");
data = data.replace(re, suggestion);

However, constructing a regular expression in this fashion apparently does not work. Can anyone suggest a way to construct this regular expression containing the variable and the word boundaries?

A: You should use double escaped \\b:
var word = "\\b"+item.word+"\\b";

In case your item.word may contain special characters, use the RegExp.escape function.

var word = "PRICE: $56.23"
RegExp.escape= function(s) {
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
alert("\\b"+RegExp.escape(word)+"\\b");


text:
Q: asp.net mvc dropdownlist with directory files list I want to show all files from a folder "newsletter" with category list. but when I use following code, I got error, my code is :
public ActionResult templatelist()
        {
            var data = _session.emailForcampaigns.Select(m => m.category).Distinct().AsQueryable();
            ViewBag.ddlCategory = new SelectList(data, "category", "category");
            return View(Directory.EnumerateFiles(Server.MapPath("~/newsletter")));
        }

and i have following lines in view

        Fiels

            <select id="template" name="template">
            @foreach (var fullPath in Model)
            {
                var fileName = Path.GetFileName(fullPath);
                <option value="@fileName"> @fileName</option>
            }
            </select>

        Category

             @Html.DropDownList("ddlCategory", null, new { @class = "dropdown " })

but i am getting error

A: You forgot to specify a data source for the drop-down list:
 @Html.DropDownList("ddlCategory", new SelectList(ViewBag.ddlCategory , "category", "category"))


text:
Q: How to reduce execution time in long video using ffmpeg I am using ffmpeg for adding text over video and add overlay image over video in android everything works for me but it takes too long to execute command mostly in long video that more than or equals to 10 sec
 String  imgcmd[]=new String[]{"-i", inputpath ,"-i",imagepath ,"-filter_complex", "[0:v][1:v]overlay=main_w-overlay_w-10:main_h-overlay_h-10", "-codec:a", "copy",output};

                    String[] txtcmd = new String[]{"-i",""+inputpath, "-filter_complex", "drawtext=text=Vikram Dulagach:fontcolor=#000000:fontsize=54:x=533:y=503:fontfile="+"/sdcard/retro.ttf", "-y" ,""+output};

I want reduce execution time in ffmpeg


text:
Q: in my laravel project some datas are not passed to controller from form submit.What could be the reasons? in my laravel project i have made a form with input field name,size,price,etc. My problem is that when i type name in name field datas arenot passed to controller.This is happening only to some specific names.For some other names working fine.And this problem is raised in live in local working fine
below is form blade
<form class="form-horizontal form-label-left" method="post"
  action="{{route('product')}}" enctype="multipart/form-data">

{{csrf_field()}}

    Select Catagory:*
    <select class="form-control" id="category" name="category">
        <option value="">Choose</option>
        @foreach($allcategory as $cat)
            <option value="{{$cat->id}}">{{$cat->name}}</option>
        @endforeach
    </select>

    Select SubCategory:*
    <select name="submenu_id" id="submenu"  class="form-control">
        <option value="">Choose</option>
    </select>

    Product Name *

        <input type="text" name="name"   required class="form-control">

    Image *

        <input type="file" name="image" required  class="form-control">

    Old Price *

        <input type="text" name="old_price"   required class="form-control">

    New Price *

        <input type="text" name="new_price"   required class="form-control">

    Detail *

        <textarea class="form-control" id="detail" name="detail" ></textarea>

        <button type="submit" class="btn btn-success pull-right" style="background: #1abb9c;">Submit</button>

below is controller
public function add_action(Request $request){
//dd($request->all());
$datas=new Product();
$this->validate($request,['name'=>'required|unique:products',
'image'=>'required',
'old_price'=>'required',
'new_price'=>'required',
'detail'=>'required',
'total_products'=>'required',
'size'=>'required',
'total_sizeproducts'=>'required']);

$datas->category_id=$request->category;
$datas->menu_id=$request->submenu_id;
$datas->name=$request->name;
$datas->slug=str_slug($request->name);
if($request->hasFile('image')){
$file=$request->file('image');
$filename=time().$file->getClientOriginalName();
$file->move(public_path().'/backend/images/products/',$filename);
$datas->image=$filename;
}
$datas->new_price=$request->new_price;
$datas->old_price=$request->old_price;
$datas->rating=$request->rating;
$datas->brand=$request->brand;
$datas->availability=$request->availability;
$datas->total_products=$request->total_products;
$datas->discount=$request->discount;
$datas->detail=$request->detail;
$datas->save();
}
return redirect()->back()->with('success','products added successfully!!!');
}

below is route
Route::group(['namespace'=>'product','prefix'=>'product','middleware'=>'auth'],function (){
   Route::get('/','ProductController@add')->name('product');
  Route::post('/','ProductController@add_action');
});

A: Post some code. But you can use dd($request) and you will be able to see the data thats being sent to the controller. Make sure you are using the correct route for that action.


text:
Q: Running ELK on docker, Kibana says: Unable to retrieve version information from Elasticsearch nodes I was referring to example given in the elasticsearch documentation for starting elastic stack (elastic and kibana) on docker using docker compose. It gives example of docker compose version 2.2 file. So, I tried to convert it to docker compose version 3.8 file. Also, it creates three elastic nodes and has security enabled. I want to keep it minimal to start with. So I tried to turn off security and also reduce the number of elastic nodes to 2. This is how my current compose file looks like:
version: "3.8"

services:
  es01:
    image: docker.elastic.co/elasticsearch/elasticsearch:8.0.0-amd64
    volumes:
      - esdata01:/usr/share/elasticsearch/data
    ports:
      - 9200:9200
    environment:
      - node.name=es01
      - cluster.name=docker-cluster
      - cluster.initial_master_nodes=es01
      - bootstrap.memory_lock=true
      - xpack.security.enabled=false
    deploy:
      resources:
        limits:
          memory: 1g

    ulimits:
      memlock:
        soft: -1
        hard: -1
    healthcheck:
      # [
      #   "CMD-SHELL",
      #   # "curl -s --cacert config/certs/ca/ca.crt https://localhost:9200 | grep -q 'missing authentication credentials'",
      # ]

      # Changed to:
      test: ["CMD-SHELL", "curl -f http://localhost:9200 || exit 1"]

      interval: 10s
      timeout: 10s
      retries: 120
  kibana:
    depends_on:
      - es01
    image: docker.elastic.co/kibana/kibana:8.0.0-amd64
    volumes:
      - kibanadata:/usr/share/kibana/data
    ports:
      - 5601:5601
    environment:
      - SERVERNAME=kibana
      - ELASTICSEARCH_HOSTS=https://localhost:9200
    deploy:
      resources:
        limits:
          memory: 1g
    healthcheck:
      test:
        [
          "CMD-SHELL",
          "curl -s -I http://localhost:5601 | grep -q 'HTTP/1.1 302 Found'",
        ]
      interval: 10s
      timeout: 10s
      retries: 120
volumes:
  esdata01:
    driver: local
  kibanadata:
    driver: local

Then, I tried to run it:
docker stack deploy -c docker-compose.nosec.noenv.yml elk
Creating network elk_default
Creating service elk_es01
Creating service elk_kibana

When I tried to check their status, it displayed following:
$ docker container list
CONTAINER ID   IMAGE                                                       COMMAND                  CREATED         STATUS                            PORTS                NAMES
3dcd08134e38   docker.elastic.co/kibana/kibana:8.0.0-amd64                 "/bin/tini -- /usr/l…"   3 minutes ago   Up 3 minutes (health: starting)   5601/tcp             elk_kibana.1.ng8aspz9krfnejfpsnqzl2sci
7b548a43c45c   docker.elastic.co/elasticsearch/elasticsearch:8.0.0-amd64   "/bin/tini -- /usr/l…"   3 minutes ago   Up 3 minutes (healthy)            9200/tcp, 9300/tcp   elk_es01.1.d9a107j6wkz42shti3n6kpfmx

I noticed that kibana's status gets stuck at (health: starting). When I checked Kibana's logs with command docker service logs -f elk_kibana, it had following WARN and ERROR lines:
[WARN ][plugins.security.config] Generating a random key for xpack.security.encryptionKey. To prevent sessions from being invalidated on restart, please set xpack.security.encryptionKey in the kibana.yml or use the bin/kibana-encryption-keys command.
[WARN ][plugins.security.config] Session cookies will be transmitted over insecure connections. This is not recommended.
[WARN ][plugins.security.config] Generating a random key for xpack.security.encryptionKey. To prevent sessions from being invalidated on restart, please set xpack.security.encryptionKey in the kibana.yml or use the bin/kibana-encryption-keys command.
[WARN ][plugins.security.config] Session cookies will be transmitted over insecure connections. This is not recommended.
[WARN ][plugins.reporting.config] Generating a random key for xpack.reporting.encryptionKey. To prevent sessions from being invalidated on restart, please set xpack.reporting.encryptionKey in the kibana.yml or use the bin/kibana-encryption-keys command.
[WARN ][plugins.reporting.config] Found 'server.host: "0.0.0.0"' in Kibana configuration. Reporting is not able to use this as the Kibana server hostname. To enable PNG/PDF Reporting to work, 'xpack.reporting.kibanaServer.hostname: localhost' is automatically set in the configuration. You can prevent this message by adding 'xpack.reporting.kibanaServer.hostname: localhost' in kibana.yml.
[ERROR][elasticsearch-service] Unable to retrieve version information from Elasticsearch nodes. connect ECONNREFUSED 127.0.0.1:9200

It seems that kibana is not able to connect with Elasticsearch, but why? Is it because of disabling of security and that we cannot have security disabled?
PS-1: Earlier, when I set elasticsearch host as follows in kibana's environment in the docker compose file:
ELASTICSEARCH_HOSTS=https://es01:9200  # that is 'es01' instead of `localhost`

it gave me following error:
[ERROR][elasticsearch-service] Unable to retrieve version information from Elasticsearch nodes. getaddrinfo ENOTFOUND es01

So, after checking this question, I changed es01 to localhost as specified earlier (that is in complete docker compose file content before PS-1.)
PS-2: Replacing localhost with 192.168.0.104 gives following error
[ERROR][elasticsearch-service] Unable to retrieve version information from Elasticsearch nodes. connect ECONNREFUSED 192.168.0.104:9200
[ERROR][elasticsearch-service] Unable to retrieve version information from Elasticsearch nodes. write EPROTO 140274197346240:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:../deps/openssl/openssl/ssl/record/ssl3_record.c:332:

A: Try this :
ELASTICSEARCH_HOSTS=http://es01:9200

I don't know why it can run in my PC, since Elasticsearch is supossed use SSL. But in your case using http working just fine.


text:
Q: Python - How do I find a link on webpage that has no class? I am a beginner python programmer and I am trying to make a webcrawler as practice.
Currently I am facing a problem that I cannot find the right solution for. The problem is that I am trying to get a link location/address from a page that has no class, so I have no idea how to filter that specific link.
It is probably better to show you.
The page I am trying to get the link from.
As you can see, I am trying to get what is inside of the href attribute of the "Historical prices" link. Here is my python code:
import requests
from bs4 import BeautifulSoup

def find_historicalprices_link(url):
    source = requests.get(url)
    text = source.text
    soup = BeautifulSoup(text, 'html.parser')
    link = soup.find_all('li', 'fjfe-nav-sub')
    href = str(link.get('href'))
    find_spreadsheet(href)

def find_spreadsheet(url):
    source = requests.get(url)
    text = source.text
    soup = BeautifulSoup(text, 'html.parser')
    link = soup.find('a', {'class' : 'nowrap'})
    href = str(link.get('href'))
    download_spreadsheet(href)

def download_spreadsheet(url):
    response = requests.get(url)
    text = response.text
    lines = text.split("\\n")
    filename = r'google.csv'
    file = open(filename, 'w')
    for line in lines:
        file.write(line + "\n")
    file.close()

find_historicalprices_link('https://www.google.com/finance?q=NASDAQ%3AGOOGL&ei=3lowWYGRJNSvsgGPgaywDw')

In the function "find_spreadsheet(url)", I could easily filter the link by looking for the class called "nowrap". Unfortunately, the Historical prices link does not have such a class and right now my script just gives me the following error:
AttributeError: ResultSet object has no attribute 'get'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?

How do I make sure that my crawler only takes the href from the "Historical prices"?
Thank you in advance.
UPDATE:
I found the way to do it. By only looking for the link with a specific text attached to it, I could find the href I needed.
Solution:
soup.find('a', string="Historical prices")

A: Does the following code sniplet helps you? I think you can solve your problem with the following code as I hope:
from bs4 import BeautifulSoup

html = """Something else
          Historical prices"""

soup = BeautifulSoup(html, "html5lib")

urls = soup.find_all("a")

print(urls)

print([a["href"] for a in urls if a.text == "Historical prices"])


text:
Q: Generators of Sylow subgroups Is there a function $f : \mathbb{N} \rightarrow \mathbb{N}$ such that for each finite supersolvable group $G$, and a Sylow subgroup $S \leq G$ we have $d(S) \leq f(d(G))$?
Here $d(H)$ denotes the minimal cardinality of a generating set of a group $H$. It is enough to consider the case of $G$ having a trivial Frattini subgroup.
In the language of profinite groups, an equivalent reformulation would be:
Let $F$ be a free finitely generated nonabelian prosupersolvable group. Is there a bound on the number of generators of the Sylow subgroups of $F$? (the sylow subgroups must be finitely generated by a theorem of Oltikar and Ribes).

A: I don't think so. Let $p$ and $q$ be primes with $q|p-1$. Then there are $q$ inequivalent $1$-dimensional modules for $C_q$ over ${\mathbb F}_p$, If we take the semidirect product of the direct sum of these modules by $C_q$, then we get a supersolvable group $G$ of order $p^qq$ with $d(G)=2$, with an elementary abelian Sylow $p$-subgroup $P$ of order $p^q$, so $d(P)=q$.
In terms of presentations, suppose that $\langle x,y \mid x^p=y^q=1, x^y=x^a \rangle$ is a presentation of a nonabelian group of order $pq$. Then we can take
$$G = \langle x_i,y \mid y^q=1, x_i^p=1, [x_i,x_j]=1, x_i^y = x_i^{a^i} \rangle$$
where $1 \le i,j \le q$. Then $G = \langle x_1x_2 \cdots x_q, y \rangle$, so $d(G)=2$.
PS: in fact there is no need to assume that $q$ is prime.


text:
Q: How to handle sets with less than $k$ elements when using a single hash function to minhash? A minhash implementation with multiple hash functions can easily handle comparisons between sets with a vastly different number of elements because the denominator of the unbiased estimator $k$ is based on the number of hash functions, which is always fixed.
However, when calculating a minhash using a single hash function, you need to choose a value $k$ which represents the minimum $k$ values when all the items in $S$ are run through a single hash function.
How can you process a set $S$ that has less than $k$ elements and get an unbiased estimate?
I see two possible approaches.  The first is to simply void any sets that don't have more than $k$ elements for comparison.  This is undesirable because even for sets with a small number of values, I'd still like to compare it to other sets (which I can do with the multiple hashing variant).
The second is to get the intersection of $h_k(S_1)$ and $h_{k}(S_2)$ where $|S_{1 and/or 2}| < k$ as you would normally. This seems like it would work, but for small sets that are very similar (if not outright duplicates of each other) it seems it would provide erroneous values; you'd possibly miss matches, but at least you won't get false positives for reasons other than your hash function not being a perfect hash.

A: I've outlined some of the approaches above, and giving it some thought, I've gone with what I'm choosing and why.

Sampling with (or without) replacement (suggested by Anony-Mousse)

I'm not a fan of this.  This could very easily produce values that produce similarities that are higher than they actually are, which could (not always) lead to a flawed prediction/outcome.  I'm personally trying to avoid false positives as much as possible, and while a bad hash function can certainly lead to false positives, I'd rather not introduce the possibility of more if I can avoid it.

Taking intersection of $h_k(S_1)$ and $h_{k}(S_2)$ where $min(|S_1|, |S_2|) < k$

While this was what I was leaning towards, I decided against this.  The key was in looking at the error estimate, $1 \over \sqrt{k}$ (same as the multiple hash function version).
Assuming that $k_1 = min(|S_1|,|S_2|)$, the error estimate for that hash comparison would be different than if $k$ samples were taken.
While it would be accurate for that comparison, it would be like comparing apples and oranges, as the expected error for all the other sets with $k$ elements is different.  This is unacceptable.
The other approach:

Void any sets that don't have more than $k$ elements for comparison.

I've chosen to produce an error when this happens.  Given the reasons stated in the first option, I'd rather have an error than return an erroneous value that I presume is correct.
The error indicates to me that my selection of $k$ needs adjustment (or I need to take another look at the data) if I want to be able to process sets that small.
Whether it's an error or skipping the comparison of those sets, the point is the same don't produce an error that's assumed to be correct.


text:
Q: How to use MapFish print module for GeoServer-GeoWebCache layer? I am in the process of developing a webGIS application using GeoServer (2.1.1), GeoWebCache(1.2.6), OpenLayers(2.11), GeoExt. All my layers are served as wms through GeoWebCache. A sample definition for any layer is as follows:
 var My_Layer = new OpenLayers.Layer.WMS( "My_Layer",
            "http://my-ip + my-port/geoserver/gwc/service/wms",
            {layers: 'layer-name',transparent: "true",format: "image/png",
             tileSize: new OpenLayers.Size(256,256),
             tilesOrigin : map.maxExtent.left + ',' + map.maxExtent.bottom },
            { isBaseLayer: false, visibility:false} );

Everything was working fine, till this point. But, when I planned to move a bit ahead and tried implementing MapFish Printing module...... the output pdf is blank!!! I am getting the following error message:

java.io.IOException: Error (status=400) while reading the image
  from........

I have searched a lot. According to this one option is to access my layers as TMS layer. But I don't want a static image layer, instead of a GeoServer WMS map layer.
Again another option found here is using OpenLayers.Control.ExportMap().
But that restricts using different scales, since my data extent is too big . As a result at a specific scale if user wants to take a print of the entire map area(may be in an A0 paper), which is not visible fully in the Openlayers div, this can not solve the purpose.
So the question is how can I accomplish this, without using a TMS or GeoWebCache layer?
Edit # 1 :
Sorry I am late, as I was out of office. Following is my config.yaml file. I feel there is no error, this can print my WMS layers, coming directly from GeoServer.
dpis: [75, 150, 300]

outputFormats:
  - pdf

scales:
  - 10000
  - 25000
  - 50000
  - 100000

hosts:
  - !localMatch
    dummy: true
  - !ipMatch
    ip: www.camptocamp.org
  - !dnsMatch
    host: labs.metacarta.com
    port: 80
  - !dnsMatch
    host: terraservice.net
    port: 80
  - !dnsMatch
    host: sigma.openplans.org
  - !dnsMatch
    host: demo.mapfish.org

layouts:
  A4 portrait:
    metaData:
      title: 'Arunava TopoMap PDF'
      author: 'Arunava print module'
      subject: 'Map layout'
      keywords: 'map,print'
      creator: 'Arunava'
    mainPage:
      pageSize: A4
      rotation: true
      items:
        - !text
          text: '${mapTitle}  ${now MM.dd.yyyy}'
          fontSize: 20
          spacingAfter: 30
        - !map
          spacingAfter: 30
          width: 440
          height: 600
        - !scalebar
          type: bar
          maxSize: 100
          barBgColor: white
          fontSize: 8
          align: right
        - !text
          font: Helvetica
          fontSize: 9
          align: right
          text: '1:${scale}'
      footer: *commonFooter

  A2 portrait:
    metaData:
      title: 'Arunava TopoMap PDF'
      author: 'Arunava print module'
      subject: 'Map layout'
      keywords: 'map,print'
      creator: 'Arunava'
    mainPage:
      pageSize: A2
      rotation: true
      items:
        - !text
          text: '${mapTitle}  ${now MM.dd.yyyy}'
          fontSize: 20
          spacingAfter: 30
        - !map
          spacingAfter: 30
          width: 880
          height: 1200
        - !scalebar
          type: bar
          maxSize: 100
          barBgColor: white
          fontSize: 8
          align: right
        - !text
          font: Helvetica
          fontSize: 9
          align: right
          text: '1:${scale}'
      footer: *commonFooter

A: Without further debugging, the 400 error is too vague for much help.  From experience, I can tell you I've seen an issue before where the geowebcache server doesn't like serving the wms layer you are requesting.  Mapfish tries to do weird things with different tile sizes (and you eventually get a 10% threshold error).  Does your log show the image it was requesting?  Can you go to that tile in our browser to see what the server actually says?  This is how I eventually exposed my issues.
For easier debugging, I've also created a seperate mapfish log to make it easier to find my mapfish issues.  Use the Geoserver admin screen to figure out which logging profile you are using, then in that log4j.properties file, add a seperate file appender for mapfish, and direct all org.mapfish activity to it.  This makes debugging much easier.
And FINALLY, my own personal crusade:  in your config.yaml, don't use outputFormats: [pdf],
instead, use formats: ['pdf'].
Even though all the docs describe outputFormat (and that's what required in the client "spec"), the actual server config is uses the 'formats' variable.  I've submitted a patch to make this more clear in the docs, but until then, let's this note be a guide.  If you want to get into the image output, this is key.


text:
Q: What is the difference between release and iteration? The title says What is the difference between release and iteration? Can you explain what the difference is?

A: Iterations are basically single units of work within your release plan.  Typically, your iteration planning phase will be a short (1-4 week) series of tasks that will be done.
After an iteration, there should be a series of acceptance tests.  This verifies that the problem domain was handled correctly.
The series of iterations plus acceptance lead to a single release.  The release leads to deployment, whether to a customer or internal usage by the end user (which is the critical difference).
Granted, in many teams, the lines can blur a bit, especially if you're releasing every iteration, etc...

A: An iteration can be purely internal. A release goes out to a customer.

A: We can say in simple words, Release is "What to do" and Iteration is "How to do".
Release focuses on User stories and iterations focuses on Tasks decomposed from user stories.


text:
Q: Python BeautifulSOUP find text in html I am trying to do google searcher by keyword and go through all the results and find if they have an text in like "
" "<!DOCTYPE>" or anything else, it's getting the html but my if always says div does not exist in any site.
Code :
from google import google
import urllib.request
from bs4 import BeautifulSoup

def google_scrape(url):
    thepage = urllib.request.urlopen(url)
    soup = BeautifulSoup(thepage, "html.parser")
    return soup.html

i = 1
query = 'תקליטן'
for url in google.search(query, 10):
    print("Trying : %s" % (url.link))
    try :
        html = google_scrape(url.link)
        if "
" in html:
            print("He have it")
        else:
            print("He doesnt have it")
    except Exception as e: print(e)
    #print(url.link)

Response:
Trying : https://www.youtube.com/?hl=iw&gl=IL
He doesnt have it
Trying : None

'NoneType' object has no attribute 'timeout'

Trying : https://he.wikipedia.org/wiki/%D7%99%D7%95%D7%98%D7%99%D7%95%D7%91
He doesnt have it
Trying : https://en.wikipedia.org/wiki/YouTube
He doesnt have it
Trying : https://www.facebook.com/youtube/


text:
Q: Convert string to array of strings by regex What is the best way to achieve the following result?
input string: this is a {test} for {performance}.
output string[]: ["this is a ", "{test}", " for ", "{performance}", "."]
This is what I have so far:
private void StringToArray(string text)
    {
        var firstSplit = text.Split('{');
        var list = new List<string>();
        foreach(var s in firstSplit)
        {
            if (s.Contains("}"))
            {
                var secondSplit = s.Split('}');
                list.Add("{" + secondSplit[0] + "}");
                if(secondSplit.Count() > 1)
                {
                    list.Add(secondSplit[1]);
                }
            }
            else
            {
                list.Add(s);
            }
        }
        Console.WriteLine(string.Join(",", list.ToArray()));
    }

A: If you want to get all computer-science-y, you could build a state machine that walks the string one character at a time, using a stack to track the start position for your next string section. When you find a { or } character, you pop the prior stack value and use it to create a substring you can add to your array. Then you push the current index onto the stack.
This can be more or less complex based on how carefully you want to handle nesting (ie: "This is { a {test}.}"), escape characters (ie: {{ or \{), unbalanced strings (ie: This {is} a {Test), whitespace within brace values (ie: This {is some} text) or excluding things like quoted strings (ie: "This is the text, "A {person} lived there."") But a character-by-character state machine will tend to be the best-performing option.
At a higher level, you can look at a domain specific language, or using a lexxer/parser tool. Unfortunately, there's very little in the middle. RegEx can be made to work, but it's generally awful for this because your input can't be said to be formally "regular". Splitting on word boundaries will be error-prone. Basic string manipulation (ie: IndexOf()) is slower and no simpler or easier to write than the state machine would be.


text:
Q: Gradient on a Rectangle's Border in QML This Question I have seems to be quite common for other languages and frameworks:
How do you apply a gradient on a rectangle's border?
My solution so far is a custom component such as:
Item {
    id: root
    property int borderWidth
    property alias borderGradient: border.gradient
    property alias gradient: fill.gradient
    property alias color: fill.color
    property int radius

    Rectangle {
        id: border
        anchors.fill: parent
        radius: root.radius

        Rectangle {
            id: fill
            anchors.fill: parent
            anchors.margins: root.borderWidth
            radius: root.radius * width / border.width / 2
        }
    }
}

This however does not allow me, to set the rectangle's color to 'transparent', which is sad, but I can live with it. Still I wonder, if there might be a more elegant way (besides using Context2D or  the QSG directly...)
Greetings,
-m-

A: Following the suggestion of ddriver from the comments, I put together a working sample of a rectangle, where you can set a gradient for the border, using the OpacityMask.
I heard somewhere, that the QtGraphicalEffects have bad performance, so I might try one without, in the future, but for whomever that is no concern, this is a working example:
import QtQuick 2.0
import QtGraphicalEffects 1.0

Rectangle {
    id: root
    property Gradient borderGradient
    property int borderWidth: 0

    Loader {
        id: loader
        active: borderGradient
        anchors.fill: parent
        sourceComponent: border
    }

    Component.onCompleted: console.log(loader.active)

    Component {
        id: border
        Item {
            Rectangle {
                id: borderFill
                radius: root.radius
                anchors.fill: parent
                gradient: root.borderGradient
                visible: false
            }

            Rectangle {
                id: mask
                radius: root.radius
                border.width: root.borderWidth
                anchors.fill: parent
                color: 'transparent'
                visible: false   // otherwise a thin border might be seen.
            }

            OpacityMask {
                id: opM
                anchors.fill: parent
                source: borderFill
                maskSource: mask
            }
        }
    }
}

It will only use the OpacityMask when needed (when a borderGradient is set), otherwise it behaves like a common rectangle.
I hope I might help someone, with this.


text:
Q: LDAP bind response - password expiring overrides force password change I'm implementing the LDAP feature of forcing password change on first login, when a user is added or when admin is changing user's password.
I set ds-cfg-force-change-on-add and ds-cfg-force-change-on-reset to true, and following the spec, which defines:

*Password Change After Reset
This policy forces the user to select a new password on first bind or after password reset. After bind operation succeed with authentication, the server should check if the password change after reset policy is on and this is the first time logon. If so, the server should send bindResponse with the resultCode: LDAP_SUCCESS, and should include the password expired control in the controls field of the bindResponse message:
controlType: 2.16.840.1.113730.3.4.4,
controlValue: an octet string: "0",
criticality: false
Indeed, when I call Client.bind, I get return value LDAP_SUCCESS, and the controls field as defined in the spec.
BUT -
when I call Client.bind when the user is within its password expiration warning interval, I get the controls field only with the password expiring controlType (2.16.840.1.113730.3.4.5). I would expect to get both controlType elements (controls is an array), but 2.16.840.1.113730.3.4.4 is not there.
This is a major problem because if the controlType 2.16.840.1.113730.3.4.4 is not there - the user will be able to login although he supposed to be not.
What am I missing here?
Thanks.

A: The Netscape controls are very old and predate the OpenDJ password policy work. They are just there to ensure some form of compatibility with very old applications.
New applications should send the Password Policy Request Control (1.3.6.1.4.1.42.2.27.8.5.1) and will receive the proper PwdPolicy control response.


text:
Q: While loop not stopping Java I've recently started to code using Java, and I've been trying to close this while loop but it doesn't stop even after adding a line that should in theory make it stop.
Here's my code sample, I've translated objects and methods from french to make it easier for you guys to read, so if there's a syntax error, it's 100% due to the translation and not an error in my actual code.
PS: every object you see is instanciated before the code shown.
while (player1.money > 0 || player2.money > 0 || player3.money > 0) {
        System.out.println("Turn number: " + turn);
        System.out.println("-------------------");
        System.out.println("-------------------");
        System.out.println("Player : " + player1.name);
        System.out.println("Bank Account : " + player1.money);
        System.out.println("-------------------");
        player1.rollDice(player1, table, chanceCard, commuCard);
        System.out.println("-------------------");
        System.out.println("Player : " + player2.name);
        System.out.println("Bank Account : " + player2.money);
        System.out.println("-------------------");
        player2.rollDice(player2, table, chanceCard, commuCard);
        System.out.println("-------------------");
        System.out.println("Player : " + player3.name);
        System.out.println("Bank Account : " + player3.money);
        System.out.println("-------------------");
        player3.rollDice(player3, table, chanceCard, commuCard);
        turn++;
        player1.money=-1000;//Trying to stop the loop
    }

A: It will not stop because you use "or" || in your while statement. so If one expression at least is true then the loop will keep executing. You have to use "and" && instead.
For example:
while (player1.money > 0 && player2.money > 0 && player3.money > 0) {
..

Or to set all money values that used in your condition  to be less or equles to  0
For example:
 ...
 player1.money=-1000;
 player2.money=-1000;
 player3.money=-1000;

A: player1.money > 0 || player2.money > 0 || player3.money > 0

This check returns true if at least one of these three conditions is fulfilled. To make your code exit loop when at least of players doesn't have enough money, change OR (||) operator to AND (&&) operator:
player1.money > 0 && player2.money > 0 && player3.money > 0

This check returns true only if all of the particular conditions are fulfilled.


text:
Q: Release a NSMutableArray when using ARC I'm developing an iOS application using latest SDK and ARC.
I have this variable:
NSMutableArray* _previewImageBuffer;

And this method:
- (void)shutdown
{
    [self stop];
    _previewImageBuffer = nil;
}

Is _previewImageBuffer = nil; correct? If I do it, what happens with memory allocated in _previewImageBuffer`? Is this a memory leak?
I want to release this object because I need to release the memory used by it.

A: What you're doing is exactly right. Nilifying an object instance variable under ARC releases the object. Releasing an NSArray, if it causes the NSArray to be deallocated, also releases all its elements.
If you're in doubt or confused about memory management and ARC, you might do well to stop and read up on the facts until you're no longer in doubt or confused. My book has a possibly helpful explanation:
http://www.apeth.com/iOSBook/ch12.html#_memory_management

A: Under ARC this is not a leak. The memory will be released. When learning ARC you should also look at the difference between a strong or weak reference.
You should also check out Apple's official introduction to ARC.


text:
Q: Cannot find the output of XMLTestRunner I'm using a unittest to xml library so I can see my test results from python in Jenkins.
I don't know how to configure the Unit testresult plugin the right way.
if __name__ == '__main__':
    unittest.main(testRunner=xmlrunner.XMLTestRunner(output='test-reports'))

I can't find the output (test-reports) anywhere in my directory, i've searched my whole ubuntu system but cannot seem to find it. The tests are running

A: Two things to try:

*

*use an absolute path to the directory

*set the buffer to False:
unittest.main(testRunner=xmlrunner.XMLTestRunner(output='/absolute/path/to/test-reports',
                                                 buffer=False))


text:
Q: Pandas - define pandas functions, pandas classes or write it like SQL? I have been thinking what the best way is to use pandas in Python. Whether that is to define small functions, a class, or just write entire pandas code in SQL-syntax-style? With SQL-syntax I mean just write everything line by line and execute the code until you get the dataframe you need to process.
So for example:
1. df['split_string'] = df['string'].str.split()

2. def split_strings(dataframe, s):
       dataframe['split_string'] = dataframe[s].str.split()
       return dataframe['split_string']

3. class splitAllStrings:
       def __init__(self, dataframe, s):
           self.dataframe = dataframe
           self.s = s

       def split_string(self):
           self.dataframe['string_split'] = self.dataframe[self.s].str.split()
           return self.dataframe['string_split']

3.1 split_s = splitAllStrings(df, column_to_split)
3.2 split_s.split_string()

So for software development, with a heavy use of Pandas, what is the best approach for maintainability? Moreover, are there any resources that teach how to build maintainable code with Python - preferably Pandas included?
Any help is appreciated.

A: It depends on your application and taste. In notebooks we usually end up with imperative line-by-line commands. Any time you feel like repeating, it makes sense to create functions.
Pandas encourages chaining. pipe, pd.DataFrame.assign, pd.DataFrame.query, and apply are crucial for long chains of transformation.


text:
Q: If condition not working in trigger I have written a trigger to update one custom field on activity which is a lookup to account.
I have to update that field with the account for account and one custom object (property relation)
When i just run a trigger for Account , it works .But when i have written the whole trigger, Its not updating the activity field for account .The trigger is working fine for Property relation object.
This is my trigger
trigger populateAccount on Task (before insert,before update) {
    List<Id> AccountIds = new List<Id>();
    String strTempId;
    if(trigger.isInsert || trigger.isUpdate){
        for(Task t : trigger.new){
            strTempId = string.valueOf(t.WhatId);
            System.debug('++++++++Test strTempId+++++++++++:'+strTempId.startsWith('001'));
            if(strTempId != null && strTempId.startsWith('001')){
                System.debug('++++++++InIF+++++++++++');
                t.Account__C = t.WhatId;
            }
            else if(strTempId.startsWith('a0p')){
                AccountIds.add(t.WhatId);
            }
        }
        map<id,id> mapAccounts  = new map<Id,id>();
        if(AccountIds.size() > 0 && AccountIds!= null){
            for(Property_Relation__c objPropertyRelation:[select id,Account__c from Property_Relation__c where id in:AccountIds]){
                mapAccounts.put(objPropertyRelation.id,objPropertyRelation.Account__c);
            }
        }

        for(Task t : trigger.new){
            t.Account__c = mapAccounts.get(t.whatId);
        }
    }
}

A: Your trigger won't update Account__c when you create the Task under an Account. Its because Account__c field is overridden to blank in this line
for(Task t : trigger.new){
    t.Account__c = mapAccounts.get(t.whatId);
}

Reason:
When you do a get from the map mapAccounts using t.whatId which is an Account Id it returns null and assigns it to Account__c because your map is populated with key as id of Property relation object and value as id of Account. So when you do a get from the map with id of Account it will always return null. So change that to
for(Task t : trigger.new){
    if(t.Account__c == NULL){
        t.Account__c = mapAccounts.get(t.whatId);
    }
}

Explanation:
The added if condition checks whether the Account__c field is null and assign the value returned from mapAccounts.
For task created on Property relation object, the Account__c will be
    null it will be populated here.
For task created on Account, the Account__c is already populated in this line.
if(strTempId != null && strTempId.startsWith('001')){
    System.debug('++++++++InIF+++++++++++');
    t.Account__C = t.WhatId;
}

So it won't be null and the if condition gets skipped keeping the value.
Hope it helps.


text:
Q: JSP foreach doesnt print the content of list I have a small problem with foreach in jsp
I tried to do everything like in jstl/jsp - iterating over a vector of beans but I cant get anything printed on my screen
here is some code:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

Shop products

            <c:forEach var="item" items="${products}">

                        <c:out value="${item.name}"/>

                    <c:out value="${item.amount}"/>

            </c:forEach>

My servlet processRequest():
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    products = new LinkedList<ProductHandler>();
    products.add(new ProductHandler("A", 5));
    products.add(new ProductHandler("B", 10));
    products.add(new ProductHandler("C", 7));
    request.setAttribute("products", products);
    getServletContext().getRequestDispatcher("/JSP/shop.jsp").forward(request, response);
}

And ProductHandler:
public class ProductHandler {
    private String name;
    private int amount;

    public ProductHandler() {
        name = null;
        amount = 0;
    }

    public ProductHandler(String name, int amount) {
        this.name = name;
        this.amount = amount;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the amount
     */
    public int getAmount() {
        return amount;
    }

    /**
     * @param amount the amount to set
     */
    public void setAmount(int amount) {
        this.amount = amount;
    }

}

Id be very grateful for pointing out any mistake I made

A: Try adding this line to the top of shop.jsp
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>


text:
Q: Parse line in bash, using nova to get the line So I am running the following command to extract the information of the instance I'm interested in:
nova list | grep derpInstance
I get:
| 37696b22-1afa-40fa-81cc-241493ef09e1 | derpInstance    | ACTIVE | None       | Running     | devcos-shared-net-10-9-254-0_24=10.9.254.129 |

I'm interested in the IP address (the stuff after the = sign), how do I extract that in a shell script?
Thanks!

A: Or use sed:
nova list | grep derpInstance | sed 's/.*=//;s/ .*//'

Note that solutions like these are generally brittle.  If you want a robust program you should make sure you know the grammar of the fields so that simple regular expressions don't break when characters you haven't seen before show up in the output.  For example, if an = sign can occur in any other field, this one will break.

A: give this a try:
nova list | grep derpInstance|grep -Po '(?<==)[0-9.]*'


text:
Q: Adding action to notification button in reminder app In my program, a user gets a notification of the task which he has created, and in the notifications there's is a button which converts user written tasks in to speech.
It means I want to add an action to the notification button which converts user written reminders to speech.
ReminderalramService.java:
public class ReminderAlarmService extends IntentService {
private static final String TAG = ReminderAlarmService.class.getSimpleName();

private static final int NOTIFICATION_ID = 42;
//This is a deep link intent, and needs the task stack
public static PendingIntent getReminderPendingIntent(Context context, Uri uri) {
    Intent action = new Intent(context, ReminderAlarmService.class);
    action.setData(uri);
    return PendingIntent.getService(context, 0, action, PendingIntent.FLAG_UPDATE_CURRENT);
}

public ReminderAlarmService() {
    super(TAG);
}

@Override
protected void onHandleIntent(Intent intent) {

    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Uri uri = intent.getData();

    //Display a notification to view the task details
    Intent action = new Intent(this, AddReminderActivity.class);
    action.setData(uri);
    PendingIntent operation = TaskStackBuilder.create(this)
            .addNextIntentWithParentStack(action)
            .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    //Grab the task description
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);

    String description = "";
    try {
        if (cursor != null && cursor.moveToFirst()) {
            description = AlarmReminderContract.getColumnString(cursor, AlarmReminderContract.AlarmReminderEntry.KEY_TITLE);
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    Notification note = new NotificationCompat.Builder(this)
            .setContentTitle(getString(R.string.reminder_title))
            .setContentText(description)
            .setSmallIcon(R.drawable.ic_add_alert_black_24dp)
            .setContentIntent(operation)
            .setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
            .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
            .setAutoCancel(true)
            .build();

    manager.notify(NOTIFICATION_ID, note);
}
}

I want to add an action to the notification of text to speech.

A: you can an action like this:
// Create an intent
Intent snoozeIntent = new Intent(this, MyBroadcastReceiver.class);
snoozeIntent.setAction(ACTION_SNOOZE);
snoozeIntent.putExtra(EXTRA_NOTIFICATION_ID, 0);

// Create the action pending intent
PendingIntent snoozePendingIntent =
        PendingIntent.getBroadcast(this, 0, snoozeIntent, 0);

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setContentIntent(pendingIntent)

// add the action to your build like this
        .addAction(R.drawable.ic_snooze, getString(R.string.snooze),
                snoozePendingIntent);


text:
Q: Sql comparaison nested on one column Imagine a table :
 ID  Month     Year  Value 1
  1  May        17   58
  2  June       09   42
  3  December   18   58
  4  December   18   58
  5  September  10   84
  6  May        17   42
  7  January    16   3

I want to return all the data that shares the same month and year where Value 1 is different. So in our example, I want to return 1 and 6 only but not 3 and 4 or any of the other entries.
Is there a way to do this? I am thinking about a combination of distinct and group by but can't seem to come up with the right answer being new to SQL.
Thanks.

A: For each row you can examine aggregates in its group with the OVER clause.  eg:
create table #t(id int, month varchar(20), year int, value int)

insert into #t(id,month,year,value)
values
 (1,'May'      ,17,  58      ),
 (2,'June'     ,09,  42      ),
 (3,'December' ,18,  58      ),
 (4,'December' ,18,  58      ),
 (5,'September',10,  84      ),
 (6,'May'      ,17,  42      ),
 (7,'January'  ,16,  3       );

 with q as
 (
     select *,
            min(value) over (partition by month,year) value_min,
            max(value) over (partition by month,year) value_max
     from #t
)
select id,month,year,value
from q
where value_min <> value_max;

A: It could be done without grouping, but with simple self-join:
    select distinct t1.*
    from [Table] t1
    inner join [Table] t2 on
        t1.Month = t2.Month
        and t1.Year = t2.Year
        and t1.Value_1 <> t2.Value_1

You can find some information and self-join examples here and here.

A: If I understood your question correctly, you are looking for the HAVING keyword.
If you GROUP BY Month, Year, Value_1 HAVING COUNT(*) = 1, you get all combinations of Month, Year and Value_1 that have no other occurrence.


text:
Q: jquery ajax overlay covers only half of screen While doing the classic $.ajax(...) call, the overlay appears on screen, but when I scroll down the page, the overlay doesn't cover the entire page.
What do I do to make all ajax initiated overlays to appear correctly?
EDIT:
here's the code:
<script type="text/css">
.overlay {
   position: fixed;
}
</script>

<script type="text/javascript">
$(document).ready(function (){

    $('a.trigger').click(function(event){
        event.preventDefault();
        var href = $(this).attr('href');
        $.ajax({
            type: 'POST',
            url: href,
            dataType: "json",
            data: {
                'somekey' : 'value'
            }});
        .done(function(data){
            // do something
        });

    });
});
</script>

EDIT2:
I forgot to mention it is under Zend Framework.

A: You can set in css
.overlay {
   position: fixed;
}

or change position on scroll event
$(window).scroll(function() {
    $('.overlay').css({top: $('body').prop('scrollTop')+'px'})
});

on some browsers you will need to use window instead of 'body'


text:
Q: Rows do not appear in SQL Server CE WP7 ToDoDataContext
Here I create a context for database.
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Data.Linq;

namespace My_CookBook
{
    public class ToDoDataContext : DataContext
    {
        public static string DBConnectionString = "Data Source=isostore:/kupa.sdf";

        public ToDoDataContext(string connectionString)
            : base(connectionString)
        { }

        public Table<ToDoItem> ToDoItems;
    }
}

ToDoItem
Here is model of item.
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Data.Linq.Mapping;

namespace My_CookBook
{
    [Table]
    public class ToDoItem : INotifyPropertyChanged, INotifyPropertyChanging
    {
        // Define ID: private field, public property and database column.
        private int _toDoItemId;

        [Column(IsPrimaryKey=true, IsDbGenerated=true,DbType = "INT NOT NULL Identity", CanBeNull=false, AutoSync= AutoSync.OnInsert)]
        public int ToDoItemId
        {
            get
            {
                return _toDoItemId;
            }
            set
            {
                if (_toDoItemId != value)
                {
                    NotifyPropertyChanging("ToDoItemId");
                    _toDoItemId = value;
                    NotifyPropertyChanged("ToDoItemId");
                }
            }
        }

        /////////////////////////////////////// Nazwa //////////////////////////////////////////

        private string _Name;

        [Column]
        public string Name
        {
            get
            {
                return _Name;
            }
            set
            {
                if (_Name != value)
                {
                    NotifyPropertyChanging("Name");
                    _Name = value;
                    NotifyPropertyChanged("Name");
                }
            }
        }

        /////////////////////////////////////// Autor //////////////////////////////////////////

        private string _Autor;

        [Column]
        public string Autor
        {
            get
            {
                return _Autor;
            }
            set
            {
                if (_Autor != value)
                {
                    NotifyPropertyChanging("Autor");
                    _Autor = value;
                    NotifyPropertyChanged("Autor");
                }
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        // Used to notify the page that a data context property changed
        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion

        #region INotifyPropertyChanging Members

        public event PropertyChangingEventHandler PropertyChanging;

        // Used to notify the data context that a data context property is about to change
        private void NotifyPropertyChanging(string propertyName)
        {
            if (PropertyChanging != null)
            {
                PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
            }
        }

        #endregion
    }
}

Show all
On this page should be display rows.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace My_CookBook
{
    public partial class show_all : PhoneApplicationPage
    {

        // Data context for the local database
        private ToDoDataContext toDoDB;

        // Define an observable collection property that controls can bind to.
        private ObservableCollection<ToDoItem> _toDoItems;
        public ObservableCollection<ToDoItem> ToDoItems
        {
            get
            {
                return _toDoItems;
            }
            set
            {
                if (_toDoItems != value)
                {
                    _toDoItems = value;
                    NotifyPropertyChanged("ToDoItems");
                }
            }
        }

        // Constructor
        public show_all()
        {
            InitializeComponent();
            // Connect to the database and instantiate data context.
            toDoDB = new ToDoDataContext(ToDoDataContext.DBConnectionString);

            // Define the query to gather all of the to-do items.
            var toDoItemsInDB = from ToDoItem todo in toDoDB.ToDoItems
                                select todo;

            // Execute the query and place the results into a collection.
            ToDoItems = new ObservableCollection<ToDoItem>(toDoItemsInDB);

            toDoDB.SubmitChanges();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        // Used to notify the page that a data context property changed
        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion

    }
}

Show All xaml
I use binding to retrieve rows.
<Grid x:Name="ContentPanel1" Grid.Row="1" Margin="12,0,12,0">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>

            <ListBox x:Name="toDoItemsListBox" ItemsSource="{Binding ToDoItems}"
                     Grid.Row="0" Margin="12, 0, 12, 0" Width="440">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <Grid HorizontalAlignment="Stretch" Width="440">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="50" />
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition Width="100" />
                            </Grid.ColumnDefinitions>

                            <TextBlock
                                Text="{Binding Path=Name}"
                                FontSize="{StaticResource PhoneFontSizeLarge}"
                                Grid.Column="1"
                                VerticalAlignment="Center"/>
                            <Button
                                Grid.Column="2"
                                x:Name="deleteTaskButton"
                                BorderThickness="0"
                                Margin="0">
                                <Image Source="Images/appbar.delete.rest.png"/>
                            </Button>
                        </Grid>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </Grid>

Add New
Here I add new row to the database:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data.Linq;
using System.Data.Linq.Mapping;

namespace My_CookBook
{
    public partial class add_new : PhoneApplicationPage
    {
        // Constructor
        public add_new()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (slider1 != null)
            {
                slider1.Value = Math.Round(e.NewValue);
                qwe((int)slider1.Value);
            }
        }

        private void qwe(int a)
        {
          stackPanel1.Height = 1250 + a * 159;
          stackPanel2.Height = a * 159;
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            CameraCaptureTask camera = new CameraCaptureTask();
            camera.Show();
            ManipulationCompletedEventArgs photo = new ManipulationCompletedEventArgs();
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            ToDoDataContext toDoDB = new ToDoDataContext(ToDoDataContext.DBConnectionString);
            ToDoItem newToDo = new ToDoItem();
            newToDo.Name = textBox1.Text;
            newToDo.Autor = textBox2.Text;

            toDoDB.ToDoItems.InsertOnSubmit(newToDo);
            toDoDB.SubmitChanges();
            MessageBox.Show("Pomyślnie dodano przepis.");

            this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        // Used to notify the page that a data context property changed
        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion
    }
}

My problem is this, the program does not display any rows (in Show all page) from the database. Why?
In debugger is ok. I really don't knew what is wrong.


text:
Q: What was the need of correlated and noncorrelated query? Today I came across a feature of sql server known as correlated query and non-correlated query. As per my understanding the task done by the above mention concept can be achieved using joins.
So as per my understanding, the architecture of sql server might have some predefined objective before coming up with this concept. I would like to know it.

A: In many cases, correlated subqueries can be rewritten as queries.  You should also understand the SQL Server did not invent any of these ideas -- SQL, correlated subqueries, or non-correlated subqueries.  I'm pretty sure these go back to the original SQL language as specified by IBM in the late 1970s.  They were definitely in the first SQL standard in 1992.
I can think of three cases where you need correlated subqueries or where they are desirable.
First, when using update or delete when trying to match rows between two tables.  In this case, the syntax seems to require correlated subqueries for what would otherwise be joins.  Actually, SQL Server does offer syntax to get around this, but it ends up introducing even more complicated ideas -- what does it mean to update one table in a join, for instance.
Second, when the correlated subquery uses certain window functions such as row_number().  In this case, it may not be possible to unroll them.
The third case is one of efficiency.  Consider the following query:
select *
from a
where a.blah in (select blah from b where b.foo = a.foo) and a.id in (list)

You can unroll this as:
select a.*
from a join
     (select distinct b.foo, b.blah
      from b
     ) b
     on a.foo = b.foo and
        a.blah = b.blah
where a.id in (list)

In the first case, if there is an index on foo and blah in b, then the optimizer will probably use the index and not do any aggregation.  In the second case, almost all optimizers (that I know of) will do the aggregation on the subquery, even when only one row may be used.


text:
Q: Minimum value of plt.pause() I'm using matplotlib's pause function.
https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.pause.html
What is the range of the value which is acceptable in the pause function?

A: [ 0.01000...00001 seconds ] minimum value
This is what i found..
plt.pause(interval=timeout)

calls to:
def start_event_loop(timeout):
  if timeout <= 0: timeout = np.inf
  timestep = 0.01
  counter = 0
  self._looping = True
  while self._looping and counter * timestep < timeout:
    self.flush_events()
    time.sleep(timestep)
    counter += 1

wich calls time.sleep at intervals of 0.01 sec.
If you want faster try this:
Faster rendering by using blitting


text:
Q: Elabore un codigo para leer la temperatura de celsius a farenheit y a kelvin pero cuando pulso la opcion 3 me retorna las opciones y no la solucion def fahrenheit_celsius():
    '''convierte temperatura en grados fahrenheit a grados celsius'''
    fahrenheit = int(input('Ingrese la temperatura en grados Fahrenheit: '))
    celsius = (fahrenheit -32 ) * 5.0/9.0
    return '{} grados Fahrenheit son {} grados Celsius'.format(fahrenheit, celsius)
def celsius_fahrenheit():
    '''convierte temperatura en grados celsius a fahrenheit'''
    celsius = int(input('Ingrese la temperatura en grados Celsius: '))
    fahrenheit = 9.0/5.0 * celsius +32
    return '{} grados Fahrenheit son {} grados Celsius'.format(fahrenheit, celsius)
def celsius_kelvin():
   '''convierte temperatura en grados celsius a kelvin'''
   celsius = int(input('Ingrese la temperatura en grados Celsius: '))
   kelvin = celsius +273.15
   return '{} grados Celsius son {} grados Kelvin'.format(celsius, kelvin)
while True:
    print('1.- Fahrenheit a Celsius')
    print('2.- Celsius a Fahrenheit')
    print('3.- Celsius a Kelvin')
    try:
        opcion = int(input('Seleccione una opcion: '))
        if opcion == 1:
            print(fahrenheit_celsius())
        elif opcion == 2:
            print(celsius_fahrenheit())
        elif opcion == 3:
            print(celsius_kelvin)
        else:
            raise ValueError
    except ValueError:
        print('Ingrese solo numeros.(1/3)')

A: Debes llamar a la función celsius_kelvin, como:
print(celsius_kelvin())


text:
Q: Objective-C Draw a Circle with a Ring shape I wrote this class that draws a animated progress with a circle (it draws a circular sector based on a float progress)
@implementation MXMProgressView

@synthesize progress;

- (id)initWithDefaultSize {
    int circleOffset = 45.0f;
    self = [super initWithFrame:CGRectMake(0.0f,
                                           0.0f,
                                           135.0f + circleOffset,
                                           135.0f + circleOffset)];
    self.backgroundColor = [UIColor clearColor];
    return self;
}

- (void)drawRect:(CGRect)rect {

    CGRect allRect = self.bounds;
    CGRect circleRect = CGRectMake(allRect.origin.x + 2, allRect.origin.y + 2, allRect.size.width - 4,
                                   allRect.size.height - 4);

    CGContextRef context = UIGraphicsGetCurrentContext();

    // background image
    //UIImage *image = [UIImage imageNamed:@"loader_disc_hover.png"];
    //[image drawInRect:circleRect];

    // Orange: E27006
    CGContextSetRGBFillColor(context,
                             ((CGFloat)0xE2/(CGFloat)0xFF),
                             ((CGFloat)0x70/(CGFloat)0xFF),
                             ((CGFloat)0x06/(CGFloat)0xFF),
                             0.01f); // fill

    //CGContextSetLineWidth(context, 2.0);
    CGContextFillEllipseInRect(context, circleRect);
    //CGContextStrokeEllipseInRect(context, circleRect);

    // Draw progress
    float x = (allRect.size.width / 2);
    float y = (allRect.size.height / 2);

    // Orange: E27006
    CGContextSetRGBFillColor(context,
                             ((CGFloat)0xE2/(CGFloat)0xFF),
                             ((CGFloat)0x70/(CGFloat)0xFF),
                             ((CGFloat)0x06/(CGFloat)0xFF),
                             1.0f); // progress

    CGContextMoveToPoint(context, x, y);
    CGContextAddArc(context, x, y, (allRect.size.width - 4) / 2, -M_PI_2, (self.progress * 2 * M_PI) - M_PI_2, 0);
    CGContextClosePath(context);
    CGContextFillPath(context);
}

@end

Now what I want to do I to draw a ring shape with the same progress animation, instead of filling the full circle, so a circular sector again not starting from the center of the circle.
I tried with CGContextAddEllipseInRect and the CGContextEOFillPath(context);
with no success.

A: I think you'll need to construct a more complex path, something like:
// Move to start point of outer arc  (which might not be required)
CGContextMoveToPoint(context, x+outerRadius*cos(startAngle), y+outerRadius*sin(startAngle));
// Add outer arc to path (counterclockwise)
CGContextAddArc(context, x, y, outerRadius, startAngle, endAngle, 0);
// move *inward* to start point of inner arc
CGContextMoveToPoint(context, x+innerRadius*cos(endAngle), y+innerRadius*sin(endAngle));
// Add inner arc to path (clockwise)
CGContextAddArc(context, x, y, innerRadius, endAngle, StartAngle, 1);
// Close the path from end of inner arc to start of outer arc
CGContextClosePath(context);

Note: I haven't tried the above code myself

A: Cheap and nasty solution:

*

*Draw a solid circle that is smaller than the original circle by the thickness of the ring you want to draw.

*Draw this circle on top of the original circle, all that you will see animating is the ring.


text:
Q: Is it possible to display a visual representation of a SCRIPT tag in CKEditor's WYSIWYG mode? I have CKEditor allowing the insertion of a SCRIPT tag into the source, which works fine. But I'd like a visual representation of this in WYSIWYG mode so that the editor knows something is back there.
Can I show something in WYSIWYG mode which lets the editor know that there is a SCRIPT tag in the source at that location?

A: Have a look at the Show Protected plugin.


text:
Q: Set window.owner from Process.GetCurrentProcess().MainWindowHandle I am in a Win Form application, somewhere in a document I need to call this dialog written in wpf and I want to set the window.owner.  The only thing close I found to get the main window of my application is the following.
I want to set the Window.Owner with a Process.GetCurrentProcess().MainWindowHandle, but have no idea how to cast the window handle into a window.

A: The WindowInteropHelper class allows you to set the owner of a WPF Window using an HWND (as an IntPtr).
In your case, it should be:
WindowInteropHelper wih = new WindowInteropHelper(theWpfWindow);
wih.Owner = Process.GetCurrentProcess().MainWindowHandle;

theWpfWindow.ShowDialog();


text:
Q: Flow: Getting error when using Map I have just started to implement type checking using Facebook Flow in one of my projects, and have encountered some issues. I am trying to do the following with a Map:
/* @flow */

let testMap: Map<string, Array<number>> = new Map();
let key: string = "testString";

if (!testMap.has(key)) {
  testMap.set(key, [])
}

testMap.get(key).push(1);

But I am getting an error saying:
Cannot call `testMap.get(...).push` because property `push` is missing in undefined [1]

Se example in try flow:
https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoVMCmAXM3MDO2AsgIYAOAXGGeQDxEBOAlgHYDmANGAIKOOkAnnVYBXALYAjTIwB8ssAF4wrTEloAKAJQBuDDjABrTIOpM27JWABE+IgGVsLDtb2pmUMBoCEdkhQA6AAtSAg1jQS0tMABvVDA8Qn9yAIIccJNuAG0AXS1UAF90P1oA9nSIrQDyUQIgjQBGXVQgA
This is of course because the get function in the Map interface is defined as:
get(key: K): V | void;

But I was expecting Flow to recognize that the key is actually being set just above.
Any suggestions on how I should change my code in order to make Flow happy?
Thank you very much!

A: As you mentioned, the problem here is that your call to Map.get may return void as you can see in V | void.
Flow has no chance to know whether your key was defined or not as this may change during runtime.
Thus you need to check whether the returned value is not undefined before accessing it's push method.
const arr = testMap.get(key);

if (arr) {
  arr.push(1)
} else {
  // map "testMap" didn't contain a value for key "key"
}

full demo in flow repl: https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoVMCmAXM3MDO2AsgIYAOAXGGeQDxEBOAlgHYDmANGAIKOOkAnnVYBXALYAjTIwB8ssAF4wrTEloAKAJQBuDDjABrTIOpM27JWABE+IgGVsLDtb2pmUMBoCEdkhQA6AAtSAg1jQS0tMABvVDA8Qn9yAIIccJNuAG0AXS1UAF90AGM4ViIwUn4rP1oA9nSI3XQPLyrGaLiE9oDyUQIgjQBGfIKwTBg02PiwYGAwcQobWoprMAATZnXWAHJcUtZsUjZKsAA3UhhRTDAoOEYjExsI60KgA

Another approach would be like this:
let arr = testMap.get(key);

if (!arr) {
  arr = [];
  testMap.set(key, arr);
}

arr.push(1);


text:
Q: Can I read a text file into objects from my classes and read in VO in JAVA ADF? I have a text file which is being parsed to some objects from classes predefined by me. I want to use those objects to add them to JSF pages in JAVA ADF. can it be done in this way using the View objects?
Thanks

A: You can right click your java classes to expose them as data controls you can drag into an ADF UI page.
Basic tutorial:
http://docs.oracle.com/cd/E53569_01/tutorials/tut_bean_dc/tut_bean_dc.html


text:
Q: Empty combo box when editable is true I want to auto select the first element in a combo box:
final ComboBox selectStatus = new ComboBox();
        selectStatus.getItems().addAll(
            "Active",
            "Blocked",
            "Suspended"
        );

        selectStatus.getSelectionModel().select(0);
        selectStatus.setEditable(true);

But when I add editable=true the combo box is empty. Can I solve this problem somehow?

A: Do like this:
    //first set it editable
    selectStatus.setEditable(true);

    //then, set the value of the first item
    selectStatus.getSelectionModel().select(0);

When you set it editable the values displayed is cleared, so you have to set the value after set it editable.
See the javadocs.


text:
Q: Add one minute to a date field in mongodb When my template is rendered, I create a schedule into a null collection. The data looks as follows:
{
  _id: "someid",
  day: "Saturday",
  start: Date,
  end: Date,
  jobs: [{
    _id: '123',
    start: Date,
    end: Date
  }, {
    _id: '567',
    start: Date,
    end: Date
  }]
}

Every minute, I want to update every entry to be the date plus one minute. I can do the following
Template.schedule.onCreated(function () {
  Meteor.setInterval(function () {
    DaySchedule.update({}, {
      $inc: {
        'start': ???,
        'end': ???,
        'cycles.start': ???,
        'cycles.end': ???
      },
    });
  });
});

How can this be done with mongodb?

A: $inc for dates and times is not implemented yet: SERVER-3174.
So your best bet is to calculate new values in your app and then do the $set.

A: You could save the date as an integer representation instead of Date object and use $inc to increment. When consuming you would retrieve the number and turn into a Date.
You could always use $set as Sergio's answers suggests.
However it's NOT a good idea to perform a single op against a database every minute and for a kinda of known value. I mean theres's not sense to store such value in these sort of logics.


text:
Q: How to integrate a function in R? In R, I am trying to integrate the following function and verify that it is a pdf, as well as get the expected value and variance.... though I'm not entirely sure how to do this.
The function that needs to be verified is: f(x) = (x/4)*e^((-x^2)/8), x >= 0.
So far, I only have:
fun = expression((x/4)*e^((-x^2)/8))
integrate(fun,0,Inf)

It states error with the code above...
I know to get the expected value would be:
mean(x)

and the variance would be:
vcov(x)

A: You need to pass a function into integrate
fun = function(x) {(x/4)*exp((-x^2)/8)}
integrate(fun,0,10)

# Mean
fun2 = function(x) {x*fun(x)}
integrate(fun2,0,Inf)

# Variance
fun3 = function(x){(x-2.506628)^2 * fun(x)}
integrate(fun3,0,Inf)


text:
Q: Best way to share data between Javascript and Sass in Rails? What is the best way to share data between Javascript and Sass?
The two options I see are:
1) Use something like sass-json-vars to be able to @import JSON files into Sass, then simply import the JSON into Javascript.
2) Use .css.scss.erb files the Rails asset pipeline, and in that CSS file import the JSON using the json Ruby gem, then simply import the JSON into Javascript.
Is one better than the other? Is there an even better option?

A: I'm not quite sure I understand what kind of data you want to share, or why this would be necessary. Have you considered simply setting the dynamic properties with inline CSS in your views instead?
Let's say you've got a bunch articles on a page, and each article has a dynamic background colour that's set in the database, I think the best thing would be to create your article class with a sensible default background in SASS, and then override it in your erb views like this:
SASS
.article {
  background-color: #ddd;
}

ERB
<% @articles.each do |article| %>
  <article class="article" style="background-color: <%= article.background_colour %>">
    <%= article.title %>
  </article>
<% end %>


text:
Q: How to find out how many decimals a number has? How can I verify how many decimals a number has in Java?
I need to calculate PI to a certain number of decimal, and I want to know how I can stop my loop when I reach the desired decimals number?

A: You can't check the number of decimals on a double directly, but you can convert it to a String using String str = number + ""; and then check str.length.

A: If you use BigDecimal for your calculation you could set the scale to the desired value.

A: If you only need a small precision e.g. 15 decimal places, you can use double for that. To specify the number of digits you could use Math.pow(10, -decimalPlaces) to calculate the smallest allowed deviation.

A: 1) you firstly convert it to string
2)Then take a  substring from '.' to end
3) Thenget the length of this substring


text:
Q: How to assert elements of lists using Pytest? I'm writing Pytest and have two functions that return two lists. How to use assert and compare two unordered lists in Python 3.7? I would like to compare that each element(subnets) of  exists in expected_list and preferably use table driven tests
expected_list= ['subnet-123', 'subnet-456', 'subnet-789', 'subnet-000']

second_list= ['subnet-789', 'subnet-123', 'subnet-456', 'subnet-000']

def test_subnet_exist():
    expected_list = get_expected_list()
    second_list = get(second_list)
    for expected_list in second_list:
        assert second_list, "Subnet {} not found".format(subnet)

Because of the order of the list, it results in a 'AssertionError'. Using assert sorted is one way but I'm interested in knowing if it's possible to check if each element of second_list exists in expected_list

A: Side-note: get_expected_list() and get(second_list) are kind of odd choices and don't run in the question as written.
If your elements aren't hashable, sortable, or don't have any methods other than equality defined then IIRC you can't do better than O(n^2), so I'll assume hashability (for most reasonable objects that have equality defined you could also subclass and define a custom __hash__(self) method if necessary).
As long as your elements are hashable you can rely on builtin functions for testing membership.
def test_subnet_exists():
    assert set(get_expected_list()).issubset(get(second_list))

If you need a loop for any reason (e.g. for detailed logging as to which elements are missing) then you still probably want to use sets to make the process efficient.
def test_subnet_exists():
    # if hashability is impossible, leave this as `outer = get(second_list)`
    # and accept the O(n^2) performance impact
    outer = set(get(second_list))

    for item in get_expected_list():
        assert item in outer

A: Since you have to loop over the list and we know they aren't unique (123 appears twice, and 789 twice in second, you could just iterate over them, right?
Just as an aside, it seems to be like the 'expected list' would be the key and you would want to instead be making sure the values in second list all appear in 'expected list' rather than vice versa.
expected_list= ['subnet-123', 'subnet-456', 'subnet-789', 'subnet-123', 'subnet-wrong']

second_list= ['subnet-789', 'subnet-123', 'subnet-456', 'subnet-789']

def test_subnet_exist():
    expected = expected_list
    second = second_list
    for element in expected:
        assert element in second, f"{element} not found"
    print ("All elements found")

test_subnet_exist()

>>>AssertionError: subnet-wrong not found


text:
Q: How can I enable ctrl-c / ctrl+break after calling system? I have written a program that invokes a system command from inside:
#include <stdlib.h>

int main(void)
{
    while(1)
    {
        system("ls 2>&1 1>/dev/null"); // comment this line out to enable ctrl+break
    }

    return 0;
}

However, when it is running, CTRL+C and CTRL+BREAK no longer work and appear to be ignored.
I am trying to write a program that performs some operations in the background involving the shell, but I also want to be able to break out of the program when the user wants to break.
Is there a way to make it work the way I want?  Should I change the architecture to perform some kind of fork / exec?

A: From the POSIX specification for system():

The system() function ignores the SIGINT and SIGQUIT signals, and blocks the SIGCHLD signal, while waiting for the command to terminate. If this might cause the application to miss a signal that would have killed it, then the application should examine the return value from system() and take whatever action is appropriate to the application if the command terminated due to receipt of a signal.

So, in order to respond properly to signals, you need to examine the return value of system().

system() returns the termination status of the command language interpreter in the format specified by waitpid()

And the docs of waitpid() refer to the docs for wait(), which instruct you to use the following macros to find out why a process exited:

*

*WIFEXITED(stat_val)
  Evaluates to a non-zero value if status was returned for a child process that terminated normally.

*WEXITSTATUS(stat_val)
  If the value of WIFEXITED(stat_val) is non-zero, this macro evaluates to the low-order 8 bits of the status argument that the child process passed to _exit() or exit(), or the value the child process returned from main().

*WIFSIGNALED(stat_val)
  Evaluates to non-zero value if status was returned for a child process that terminated due to the receipt of a signal that was not caught (see ).

*WTERMSIG(stat_val)
  If the value of WIFSIGNALED(stat_val) is non-zero, this macro evaluates to the number of the signal that caused the termination of the child process.

*WIFSTOPPED(stat_val)
  Evaluates to a non-zero value if status was returned for a child process that is currently stopped.

*WSTOPSIG(stat_val)
  If the value of WIFSTOPPED(stat_val) is non-zero, this macro evaluates to the number of the signal that caused the child process to stop.

*WIFCONTINUED(stat_val)
  Evaluates to a non-zero value if status was returned for a child process that has continued from a job control stop.

Here is an example of how you would use this information, without having to fork a separate process. Note that you won't actually receive the signal in the parent process, but you can determine the signal sent to the child process:
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
    while(1)
    {
        int result = system("ls 2>&1 1>/dev/null");
        if (WIFEXITED(result)) {
          printf("Exited normally with status %d\n", WEXITSTATUS(result));
        } else if (WIFSIGNALED(result)) {
          printf("Exited with signal %d\n", WTERMSIG(result));
          exit(1);
        } else {
          printf("Not sure how we exited.\n");
        }
    }

    return 0;
}

And if you run it, you get:

$ ./sys
Exited normally with status 0
Exited normally with status 0
Exited normally with status 0
Exited normally with status 0
Exited normally with status 0
Exited normally with status 0
^CExited with signal 2

A: According to IEEE Std 1003.1-2008 (POSIX):

*

*The system() function shall behave as if a child process were created using fork(), ...

*The system() function shall ignore the SIGINT and SIGQUIT signals, and shall block the SIGCHLD signal, while waiting for the command to terminate. If this might cause the application to miss a signal that would have killed it, then the application should examine the return value from system() and take whatever action is appropriate to the application if the command terminated due to receipt of a signal.

*The system() function shall not return until the child process has terminated.

A: From San Jacinto's comment above:
system() essentially forks, blocks the parent, and ignores certain signals in the child, as per the POSIX spec links. You can bypass this by first creating another process for system() to block. This leaves the original process (the grandparent of the process which the shell is running on) free to accept kill signals.
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>

int main(void)
{
    pid_t pid;

    while(1)
    {
        pid = fork();

        if(pid > 0) // parent
        {
            wait(0);
        }
        else if(pid == 0) // child
        {
            system("ls 2>&1 1>/dev/null");
            return 0;
        }
        else // could not fork
        {
            return 1;
        }
    }

    return 0;
}

On the surface, this appears to do what I need.


text:
Q: Como chamar um método de um fragment em uma activity? eu preciso usar um método de uma fragment dentro de uma activity, mas eu não consigo passar uma referencia para essa activity. Alguem pode me ajudar?
A ideia é essa:
    public class MinhaFragment extends Fragment{
    ...

      @Override
      public void onClick(View view) {
         if (view.getId() == R.id.fab) {
          Intent intent = new Intent(this.getContext(),MinhaActivity.class);
          startActivity(intent);
        }
      }

      public void showMessage(String message) {
         Snackbar snackbar = Snackbar.make(this.getView(), message,
         Snackbar.LENGTH_LONG);
         snackbar.show();
      }
   }

Essa é a minha activity
public class MinhaActivity extends Activity{
   ...

   @Override
   public void onClick(View view) {
     //chamar o metodo do fragment aqui por exemplo
     minhaFragment.showMessage("Teste");
   }

   ...
 }

Qualquer ajuda é bem vinda.
Desde já agradeço.

A: Você pode colocar essa função numa classe model e chamar instanciando:
Classe c = new Classe();
c.mostrarMsg(this, "mensagem")

Você também precisa passar o contexto
public void mostrarMsg(Context contexto, String mensagem) {
    Toast.makeText(contexto, mensagem, Toast.LENGTH_SHORT).show();
}

Observação se você for chamar essa função dentro de click de um botão, por exemplo, terá que criar uma variável Context fora do escopo:
final Context contexto = this;

public void onClick(View view) {
    c.mostrarMsg(contexto, "mensagem");
}

e usar dentro do click

A: Olá! :) Não existe uma solução ideal para esse tipo de problema, no máximo se pode identificar nomes, por exemplo, você pode descobrir o nome da activity que chamou outra activity atráves do método getCallingActivity.
Uma solução não recomendada seria usar um método estático na activity e passar o fragment para uma variável estática.
Mas muito provavelmente você está querendo fazer algo que existe um jeito melhor de fazer, se você deseja passar informações para o fragment que chamou a activity e identificar o momento que activity é encerrada, você deve chamar essa activity com o método startActivityForResult e na activity antes de encerrar ela você deve passar as informações por intent com o método setResult
Exemplo:
No fragment:
Intent i = new Intent(this, MinhaActivity.class);
getActivity().startActivityForResult(i, 1);

Na activity que foi chamada (MinhaActivity):
Intent retornoIntent = new Intent();
retornoIntent.putExtra("resultadoid",resultado);
setResult(Activity.RESULT_OK,retornoIntent);
finish();

E no fragment que chamou MinhaActivity:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1) {
        if(resultCode == Activity.RESULT_OK){
            String resultado = data.getStringExtra("resultadoid");
            //Momento exato quando a activity chamada por esse fragment é
            //encerrada e o estado do app volta para esse fragment
        }
    }
}

Ou seja, como não existe um bom motivo para chamar um método de um fragment que não está sendo usado (pois o estado atual do app está numa Activity depois do Fragment), não devemos chamar um método de algum lugar do app que não pertence ao estado atual, ao invés, devemos identificar o momento exato que voltamos para o estado anterior e quando necessário utilizar as informações necessárias do estado que acabou de ser encerrado
Observação
É muito importante mostrar aqui que o Fragment não irá ter chegado no método onActivityResult sem que a Activity que possua esse Fragment chame onActivityResult deste Fragment. Exemplo supondo que o FragmentA está dentro da ActivityA:
Exemplo - ActivityA:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    fragmentA.onActivityResult(requestCode,resultCode,data);
    //É necessário fazer isso para que o fragmentA tenha seu método onActivityResult chamado
}

Abraços :)


text:
Q: variable to change for finding OpenCV I compiled an OpenCV.
I installed the .so files in /usr/local/lib/opencv/ rather than /usr/local/lib, and the headers in /usr/local/include/opencv rather than /usr/local/include.
Now I am trying to compile Caffe library for another application and face some challenge for make it understand where are my OpenCV's files.
I do think a part of the solution is somewhere in the /usr/local/share files.
So I would like to know what I have to modify in :
OpenCVConfig.cmake,
OpenCVConfig-version.cmake
OpenCVModules.cmake
OpenCVModules-release.cmake

for make cmake understand where are my include / lib files ?

A: As identify by Tsyvarev when you compile opencv and want to install opencv it in an different path the default one (e.g. /usr/local/ on linux) it is better to modify the variable CMAKE_INSTALL_PREFIX in the CMakeFile.txt rather than move everything after installation.


text:
Q: Get path for every file python loads when importing modules I'm trying to make a directory containing all the modules a python script depends on. Rather than manually tracking down all those files, I would like to automatically find these files as python imports them. To do this, I've added a module finder to sys.meta_path:
import sys, imp
class ImportPrint(object):
    def find_module(self, name, path=None):
        toks = name.split(".")
        pre, loc = ".".join(toks[:-1]), toks[-1]
        try:
            module_info = imp.find_module(loc, path)
        except ImportError:
            module_info = imp.find_module(loc)
        if module_info[0]: module_info[0].close
        print "A", name, module_info[1]
        return None
sys.meta_path = [ImportPrint()]

import mymod1, mymod2, etc..

This almost works, but the __init__.py files are not found this way. Is there a better way to find them, or should I just hackily add them whenever the file found is a directory? Will this method miss any other files.

A: According to the documentation for sys.meta_path, your find_module method will be called with the path argument set to the path of a package if it is one. Why not use os.path.join(path, '__init__.py') for when path exists?


text:
Q: Back button which goes back to filled in form Is there a way to add a Back button which reloads  a form with the inputs filled in?
I have a form with some input fields and a save (submit) button. When clicking submit, if the mandatory fields aren't filled in, a new page opens with a message. If I use the browser's Back button, I receive this message:

Confirm Form Resubmission
This webpage requires data that you entered earlier in order to be
  properly displayed. You can send this data again, but by doing so you
  will repeat any action this page previously performed. Press the
  reload button to resubmit the data needed to load the page.
  ERR_CACHE_MISS

So basically, it asks me to Refresh, and then confirm by clicking OK on a pop up window, after which the form reloads but with empty fields.
I have tried thinking of everything, but I can't find a solution. Thanks.

A: If it's possible, I would change the structure so that the form posts back to itself, and runs the validation of the mandatory fields. Then, if everything's ok, it will continue whatever processing is necessary. If there's a problem, it can show the form again, but in your code you will have access to the values already submitted, so you can pre-populate the form with these values and then display it to the user. It's a pretty standard design technique for this sort of thing.


text:
Q: Order by in exists sub query When I execute below query I give this error:

ORA-00907: missing right parenthesis

error hint to like.
select *
from image img, imageinfo info
where
   img.i_id = info.i_id and
   (info.i_state like 'delete%' or
    exists (select * from back bk where rownum = 1 order by bk.b_date desc)
   )

A: Remove order by clause from your exists clause