text:
Q: How do i halt execution of bash script when a python script fails? So I have the following in my shell script:
python get_link.py $password | wget --content-disposition -i-
mkdir web_folder
mv *.zip web_folder

So the first line is executing a python script i wrote which prints out a website link and wget immediately retrieves the link returned by the python script and downloads a zip file.
The second line makes a new folder called "web_folder" and the third line is moving the zip file that was downloaded by wget into the "web_folder"
The problem I'm facing is that, if the python script fails due to error such as $password is having the wrong password, the rest of the shell script command is still executing. In my case, the following is printed:
mv: cannot stat '*.zip': No such file or directory

The mkdir and the mv command somewhat still executes even if the python script fails. How do i ensure that the script comes to a complete halt when the python script fails?

A: If you are using bash, look into PIPESTATUS variable.
${PIPESTATUS[0]} will have the return code from the first pipe.
#!/bin/bash
python get_link.py $password | wget --content-disposition -i-
if  [ ${PIPESTATUS[0]} -eq 0 ]
then
    echo "python get_link.py successful code here"
else
    echo "python get_link.py failed code here"
fi

A: A compact solution, chain everything with and's:
(python get_link.py $password | wget --content-disposition -i-) && (mkdir web_folder) && (mv *.zip web_folder)

Less compact solution:
python get_link.py $password | wget --content-disposition -i-
if [ $? -eq 0 ]; then
  mkdir web_folder
  mv *.zip web_folder
fi


text:
Q: What is ICU data in Flutter APK? According to another post, Flutter APK contains ICU-data (maybe the icudtl.dat file was meant).
But my question; what is ICU data in Flutter APK required for?
Actually, what is ICU data? I mean, is it the same as react-native's bundle (which is compiled java-script and is executed by internal react-native C++ codes)?
Isn't Flutter (or Dart) supposed to compile to native code (like to ARM and x86 *.so format native-library for Android, and to ARM for iOS)?

A: according to :
https://developer.android.com/guide/topics/resources/internationalization
and
http://site.icu-project.org/home
ICU is a mature, widely used set of C/C++ and Java libraries providing Unicode and Globalization support for software applications.
Few highlights of the services provided by ICU:
Format numbers, dates, ..  , Time Calculations, etc..

A: To answer the question:
ICU is about localization.
Localizing is hard.
For example 1,000.50 (one thousand and fifty cents) can be written as:

*

*1 000,50

*1 000.50

*1.000,50

*1,000.50

*1000.50

*1000,50
All these variations are used by at least one language in the world.
There's a lot more stuff, like for example se-pa-ra-ting words in syllables to properly split them when words can't fit into a single line. You need a dictionary for this.
Some countries use MM/DD/YYYY for dates, others DD/MM/YYYY, others YYYY/MM/DD, etc.
A lot of this is data (i.e. what country/language does what), and in many languages there are no rules to easily determine them (i.e. syllables separation).
Hence ICU that's what's contained in ICU.dat.
Many dat files contain partial info on most popular languages and necessary info; since the full dat file can be huge (gigabytes).
i.e. do you need syllable separation for indonesian? If you are an OS developer, then the answer is likely yes. If you're a web developer targetting the USA and Europe, likely not.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How does Google Docs map mouse coordinates to text offset (for drag and drop)? I've spent some time searching SO for mapping mouse coordinates to text offset (for drag and drop), but the only solution I've come across is to wrap each character in its own span so that you may monitor mouse events on that span, which is not a scalable solution (for large documents).
But moreover, Google Docs is able to track the mouse cursor as it drags text around (drawing an insertion point in the text where the mouse is).  From monitoring the DOM at and around the text, it doesn't appear to be using the character-span technique.  Does anyone know how this is accomplished?

A: Unfortunately I don't have a Google account so I can't check what Google uses to accomplish Google Docs. But for obtaining the selection source you could be interested in this answer.
You also mentioned drag and drop. HTML5 supports an attribute called "contenteditable". The browser makes it (like the name implies) editable for the user. Here is a nice example.
To see how an editor (for example CKEditor or maybe even Google Docs) can be written with HTML 5 techniques, read http://www.quackit.com/html/codes/contenteditable.cfm.


text:
Q: how to parse html by using class name in lxml.etree python req = requests.get(url)
tree = etree.HTML(req.text)

now instead of using xpath tree.xpath(...) I would like to know if we can search by class name of id as we do in beautifulSoup
soup.find('div',attrs={'class':'myclass'})  I'm looking for something similar in lxml.

A: The far more concise way to do that in bs4 is to use a css selector:
soup.select('div.myclass') #  == soup.find_all('div',attrs={'class':'myclass'})

lxml provides cssselect as a module (which actually compiles XPath expressions) and as a convenience method on Element objects.
import lxml.html

tree = lxml.html.fromstring(req.text)
for div in tree.cssselect('div.myclass'):
    #stuff

Or optionally you can pre-compile the expression and apply that to your Element:
from lxml.cssselect import CSSSelector
selector = CSSSelector('div.myclass')

selection = selector(tree)

A: You say that you don't want to use xpath but don't explain why. If the goal is to search for a tag with a given class, you can do that easily with xpath.
For example, to find a div with the class "foo" you could do something like this:
tree.find("//div[@class='foo']")


text:
Q: Unable to set Google Chrome as default browser in Ubuntu 12.10 despite several attempts at making Google Chrome work as my default browser I simply cannot.
I've read countless threads on the internet, checked mimeapps.list and so on, tried about anything, from simple system configuration by going to settings and change as the default browser there, which, for some odd reason, won't allow me to set a default browser, to more advanced terminal scripting.
This is a clean install of Ubuntu 12.10 x64 bit updated to the latest version including kernels.

A: When I tried, choosing the default browser from System Settings worked for me. Here is the procedure.

*

*Go to System Setting > Details > Default Applications

*Choose Google Chrome from the dropdown for Web

If this is not working, then uninstall your chrome. Install it using Ubuntu Tweak and Try the procedure above. Ubuntu Tweak is a must have application.
To install Chrome using Ubuntu Tweak

*

*First install Ubuntu Tweak from Ubuntu Software Center

*Launch Ubuntu Tweak from Unity Dash

*Go to Apps Tab, you will get list available apps as follows

*

*Click on Google Chrome Stable.

*

*Check the checkbox for "Google Chrome Official Source" and Click on Install

When installation is over, launch chrome. At the first launch, it will ask if you want to set Chrome as default browser. You can choose Yes then otherwise you can set it from System Settings > Details > Default Applications > Web.

A: As I already answered earlier on this question:
There are a number of places an application might figure out which browser to launch and unfortunately there is no established standard. If the other answers don't work for you (as was the case for me with Skype) you could try:

*

*the $BROWSER environment variable

*/usr/bin/x-www-browser, which is configured via the alternatives mechanism: sudo update-alternatives --config x-www-browser (which is what Skype is launching it seems)


text:
Q: is there some device to make my laptop get wifi better (from a bigger distance) is there some device that I could connect to my laptop so that I could get wifi from a bigger distance ?

A: It depends on what your situation is, but you can try this:

*

*(Server) Add a gain antenna onto your wireless access point

*(Client) Buy an external wireless adapter that allows you to connect an antenna, and then buy a large antenna for it.

You may also want to consider switching between 54a and 54g and artificially limiting the connection speed to get a more stable connection. You can also try a different channel to remove interference.

A: If you are using 802.11g then moving to 802.11n may help as the expected indoor and outdoor range is higher (~70m and ~250m respectively, compared to ~35 and ~120). Obviously this range can be affected by a great many things so if your current distance problem is due to bad interference or signal being blocked by big solid walls you might see little of the benefit, put the range potentially doubles when moving from G to N. See http://en.wikipedia.org/wiki/802.11#Protocols for more detail. Of course you would need to both upgrade your access point (by replacing it with a newer model that supports 802.11n and your laptop. You may be able to replace the internal wireless adaptor though this may affect your warranty, I suggest just getting a plug in adaptor (USB, PCMCIA, what-ever your laptop supports) instead.
As taspeotis recommends, improving the quality of your antennas can help quite a bit too in some circumstances.
If you are looking to extend the range in a particular direction and don't mind reducing the range in other directions than moving the access point, or if you can't because it is also your DSL router and needs to be near the inlet getting another AP that can sit further away from the rest of the equipment. Turn off the first one if you do that though, as they will interferer with each other otherwise (unless you can get the both to cooperate in a bridged mode). Sometimes moving the access point just a little can make a surprising amount of difference to reception at certain locations due to different patterns in interfering signals and the locations of signal blocking/reflecting structures in your environment. If you can't move your AP to where you want it due to lack of a convenient power socket, you could get a power-over-ethernet adaptor (see wikipedia for a general discussion, this is one example of a consumer targeted product and there are others on the market) - that way you only need a long network cable not a separate trailing power-line extender too.


text:
Q: Why will Jupyter Notebook open from WSL but not MobaXterm? So I've installed and gotten Jupyter notebook to work quite well from WSL on my computer. I created a alias called juno which launches Jupyter notebook in my local browser. As of recently I've needed to be able to launch Jupyter Notebook from MobaXterm (non WSL environment), but whenever I launch from this environment my browser always says:

This site can't be reached. localhost refused to connect.

Does anyone have an idea how to be able to launch Jupyter notebook from my normal windows environment?


text:
Q: How to simulate network issues on a Android device? I need to test my app in following scenario:

*

*connect device to wifi (with the internet).

*simulate internet interruption (lack of the internet but the device must stay connected to the wifi network).

*after few seconds the internet need to be active again.

I could simulate this pulling the adsl cable out of my ruter, but then it won't reconnect fast enough.
Is this any way to simulate this programmatically?

A: If you have a Mac, you can do it with Network Link Conditionner. It's really efficient, see here the step to install it :
http://nshipster.com/network-link-conditioner/

A: If you happen to have another device, you can create a hotspot with it and disallow mobile networks internet. The testing device will be connected to the hotspot, but will not be able to reach anywhere due to lack of Internet. As for the connection there, I think it is faster than restarting a router. However, you have to have another device for this to happen... Otherwise I don't know, and I'd like to know a true answer, as well.

A: Try to pass all network requests (I use it with db transactions too) through a android.os.Handler. Use Runnables (better implement your own Runnable class) to implement the actions to perform (add callbacks, logging and other logic in your Runnable class). This way you can easily register listeners in your Runnable class to do whatever sleeping or failures your are interested in.
Here is some code from my project.
The M_ClientRunnable class implements Runnable and has additional methods for registering "cancellators", failure listeners and success listeners.
class LooperThread extends Thread {
    public Handler mHandler;

    public LooperThread() {
        super();
        start();
    }

    public void run() {
        Looper.prepare();
        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                getLogger().info(TAG, msg.toString());
            }
        };
        Looper.loop();
    }

    public boolean post(M_ClientRunnable runnable) {
        if(!isAlive()) {
            start();
        }
        if (mHandler!=null) {
            return mHandler.post(runnable);
        } else {
            return false;
        }
    }
};
private LooperThread looper = new LooperThread();
@Override
public boolean post(M_ClientRunnable runnable) {
    return looper.post(runnable);
}

A: I don't have a real solution yet, but I found a workaround for the task. I'm using MikroTik router and its Firewall filter allows me to disable internet access for the particular IP adress on the fly:
6 X chain=forward action=drop protocol=tcp dst-address=192.168.1.20
 in-interface=Internet(modem)


text:
Q: TURBO C++: Unable to open include file stdio.h I am trying to compile a simple C program using TUrbo C++ 3.2. But getting the following error: Unable to open include file 'STDIO.h'
I do have these files in INCLUDE library.

A: Cant help you if you dont post your code. Check if you use #include <cstdio> (not #include "cstdio" or #include <cstdio.h> or #include "cstdio.h".
#include <cstdio> will always work.


text:
Q: How to add ref="nofollow" on blogger reply and delete comment links I used seo analyser tool http://www.seoptimer.com for my blog post and found that my comment delete link are "dofollow". Now, how can i add "nofollow" in those links.
I am using embedded comments by blogger.
Page url: http://www.howbloggerz.com/2016/02/custom-stylish-search-boxes-blogger.html
Comment script:


text:
Q: Host key verification failed in Jenkins, working inside Docker I am integrating Jenkins for a build system and the Jenkins is installed in my local machine. The build is running in docker container and I need to checkout a db migration repo inside the container. Foe SSH authentication, I am executing a shell script, which like the following :
mkdir -p ~/.ssh
touch ~/.ssh/id_rsa

echo "-----BEGIN RSA PRIVATE KEY-----
KEY HERE
-----END RSA PRIVATE KEY-----" > ~/.ssh/id_rsa

chmod 600 ~/.ssh/id_rsa

After running this, I can clone the code inside the Docker container, but not from the pipeline or another shell script which does the checkout. It is returning error

Warning: Permanently added the RSA host key for IP address '192.30.253.113' to the list of known hosts.
      Permission denied (publickey).
      fatal: Could not read from remote repository.

      Please make sure you have the correct access rights and the repository exists.

The key is added correctly and working from inside docker. How can I make this work from the shell script ?


text:
Q: Warnings after moving WP site between local machines I have moved a local Wordpress site from one computer to another.
Now the site loads on the new machine and I can switch to other pages in the site but except for the homepage I get many "Creating default object from empty value in..." warnings on every page.
What's causing this?
Thanks
Edit:
Adding a sample of the warnings I get:
Warning: Creating default object from empty value in C:\wamp\www\maps_en2\wp-includes\user.php on line 657

1   0.0007  249320  {main}( )   ..\index.php:0
2   0.0010  252888  require( 'C:\wamp\www\maps_en2\wp-blog-header.php' )    ..\index.php:17
3   0.0013  265520  require_once( 'C:\wamp\www\maps_en2\wp-load.php' )  ..\wp-blog-header.php:12
4   0.0017  277032  require_once( 'C:\wamp\www\maps_en2\wp-config.php' )    ..\wp-load.php:30
5   0.0027  363752  require_once( 'C:\wamp\www\maps_en2\wp-settings.php' )  ..\wp-config.php:90
6   0.2085  14508248    do_action( )    ..\wp-settings.php:298
7   0.2282  14746528    call_user_func_array ( )    ..\plugin.php:395
8   0.2282  14746560    _wp_admin_bar_init( )   ..\plugin.php:395
9   0.2293  14807256    WP_Admin_Bar->initialize( ) ..\admin-bar.php:34
10  0.2294  14808136    get_blogs_of_user( )    ..\class-wp-admin-bar.php:18

A: Setting display_errors to 0 didn't work for me. But inserting this at the beginning of user.php to disable warnings did:
error_reporting(E_ERROR);

A: Your new environment might not be having E_STRICT warnings enabled.
Add the following line to your wp-config.php:
ini_set( 'display_errors', 0 );

Note: That should fix the issues, but it's recommended to create the object manually first.

A: Problem was different wamp versions.


text:
Q: Does Concurrency::parallel_for has a command similar to omp_set_lock? I have a class (say particle) which has a variable (say param1):
class particle
{
    double param1;
    . . .
    omp_lock_t particle_lck;
    . . .
};

and a std::vector containing some instances of the particle class,
vector <particle> Particles;

In omp parallel for loop, I use commands below to safely update "param1" in computations:
omp_set_lock(&currentParticle->particle_lck);
currentParticle->param1 += anything
omp_unset_lock(&currentParticle->particle_lck);

Now, I am going to convert my code from openMP to Concurrency library, I am wondering if there are any equivalent command to use in Concurrency::parallel_for loop instead of omp_set_lock, which can lock an object while is updating?
Thanks in advance.

A: I assume that by Concurrency library you mean Microsoft's Concurrency Runtime. Your use case is actually a critical section and for that Concurrency provides the concurrency::critical_section, which is a non-reentrant mutex lock:
using namespace concurrency;

class particle
{
    double param1;
    . . .
    critical_section particle_lck;
    . . .
};

Then the critical section becomes:
currentParticle->particle_lck.lock();
currentParticle->param1 += anything;
currentParticle->particle_lck.unlock();

If you prefer a scoped approach, use concurrency::critical_section::scoped_lock:
{
   critical_section::scoped_lock guard(currentParticle->particle_lck);
   currentParticle->param1 += anything;
}

scoped_lock is a simple wrapper. It takes a reference to a critical_section object and calls lock() in the constructor and then unlock() in the destructor, so it releases the lock when it goes out of scope.

As explained by Jim Cownie, using locks for something that can be done more efficiently with an atomic operation, is an overkill. In OpenMP, one would usually do:
#pragma omp atomic update
currentParticle->param1 += anything;

Atomic operations in standard C++ require the use of special atomic types and those are only trully available for floating-point types starting with C++20, so your code will be (assuming C++20 compiler):
#include <atomic>

class particle
{
    std::atomic<double> param1;
    . . .
};

Updating the value:
currentParticle->param1.fetch_add(anything, std::memory_order_relaxed);

Concurrency does not provide its own atomic types. Instead, it relies on the combinable class to provide an equvalent to OpenMP's reduction clause.


text:
Q: Reverse the order of an auto date format The function I am using formats inserts '-' at certain points to auto format the date field. Right now it prints in the format 'mm-dd-yyyy', I am trying to get it to print 'yyy-mm-dd'.
  <input type=textbox id=date onkeyup="dtval(this,event)" />

the js
  function dtval(d,e) {
  var pK = e ? e.which : window.event.keyCode;
    if (pK == 8) {d.value = substr(0,d.value.length-1); return;}
  var dt = d.value;
  var da = dt.split('-');
    for (var a = 0; a < da.length; a++) {if (da[a] != +da[a]) da[a] = da[a].substr(0,da[a].length-1);}
       if (da[0] > 31) {da[1] = da[0].substr(da[0].length-1,1);da[0] = '0'+da[0].substr(0,da[0].length-1);}
       if (da[1] > 12) {da[2] = da[1].substr(da[1].length-1,1);da[1] = '0'+da[1].substr(0,da[1].length-1);}
       if (da[2] > 9999) da[1] = da[2].substr(0,da[2].length-1);
    dt = da.join('-');
      if (dt.length == 2 || dt.length == 5) dt += '-';
    d.value = dt;
 }

A: I think you'd benefit from the Date class.
var date1 = new Date('02-04-2016');
    //Thu Feb 04 2016 00:00:00 GMT-0500 (Eastern Standard Time)

var date2 = date1.getFullYear() + '-'
       + ((date1.getMonth() + 1) > 9? date1.getMonth() + 1: '0' + (date1.getMonth() + 1)) + '-'
       + (date1.getDate() > 9? date1.getDate(): '0' + date1.getDate());
    //"2016-02-04"

A: Here it is for YYYY-MM-DD:

function dtval(d,e) {
  var pK = e ? e.which : window.event.keyCode;
  if (pK == 8) {d.value = d.value.substr(0,d.value.length-1); return;}
  var dt = d.value;
  var da = dt.split('-');
  for (var a = 0; a < da.length; a++) {
    if (da[a] != +da[a]) da[a] = da[a].substr(0,da[a].length-1);
  }
  if (da[0] > 9999) {da[1] = da[0].substr(da[0].length-1,1);da[0] = '0'+da[0].substr(0,da[0].length-1);}
  if (da[1] > 12) {da[2] = da[1].substr(da[1].length-1,1);da[1] = '0'+da[1].substr(0,da[1].length-1);}
  if (da[2] > 31) da[1] = da[2].substr(0,da[2].length-1);
  dt = da.join('-');
  if (dt.length == 4 || dt.length == 7) dt += '-';
  d.value = dt;
}
<input type=textbox id=date onkeyup="dtval(this,event)" />

BTW, you had this line:
if (pK == 8) {d.value = substr(0,d.value.length-1); return;}

There's no substr global function, it's a function of String:
if (pK == 8) {d.value = d.value.substr(0,d.value.length-1); return;}


text:
Q: How do I get my code to repeat itself if the desired input is not entered? I just started python 2 weeks ago and I don't know how to make my code repeat itself when the input is something like "fox" when that is not one of the three options I'm accepting (horse, oxen, mule). Also if I want to total up the cost of 2 horse and say 3 mules by having it ask "do you want to buy any more animals", how would i do that? Any help would be very appreciated.
zoo = {}

def main():
    print ("Animals available to purchase: " + "horse: 50, oxen: 35, mule: 20")
    total_money = 1000
    print ("You have " + str(total_money) + " to spend")
    cost(total_money)

def animal_cost(total_money):
        animal_type = raw_input("Please enter an animal:")
        print ("Animal Type Entered: " + str(animal_type))
        global animal_quantity
        animal_quantity = int(raw_input("Please enter quantity of animals:"))
        print ("Animal Quantity Entered: " + str(animal_quantity))
        if animal_type in zoo:
            zoo[animal_type] += animal_quantity
        else: zoo[animal_type] = animal_quantity

        while True:
            if animal_type == 'horse':
                return 50 * animal_quantity
            if animal_type == 'oxen':
                return 35 * animal_quantity
            if animal_type == 'mule':
                return 20 * animal_quantity
            else:
                cost(total_money)

def cost(total_money):
    costing = animal_cost(total_money)
    total_money -= costing
    if total_money <= 0:
        print ("No money left, resetting money to 1000.")
        total_money = 1000
        zoo.clear()

    print ("Cost of Animals: " + str(costing))
    print ("Remaining Balance:" + str(total_money))
    choice = raw_input("Do you want to buy any more animals?(Y/N):")
    if choice in('Y','y'):
        cost(total_money)
    elif choice in ('N','n'):
        choice_2 = raw_input("Enter 'zoo' to see the animals you have purchased:")
        if choice_2 in('zoo','Zoo'):
            print zoo
        choice_3 = raw_input("is everything correct?(Y/N):")
        if choice_3 in ('Y','y'):
            print ("Thank you for shopping!")
        elif choice in ('N','n'):
            print ("Restarting Transaction")
            zoo.clear()
            cost(total_money)

if __name__ == '__main__':
    main()

A: You may try this enhanced version of your code:
zoo = {}  # creating global dictionary for adding all animals into it.
# function to get animal cost
def animal_cost(total_money):
    animal_type = raw_input("Please enter an animal:")
    print ("Animal Type Entered: " + str(animal_type))
    animal_quantity = int(raw_input("Please enter quantity of animals:"))
    print ("Animal Quantity Entered: " + str(animal_quantity))
    if animal_type in zoo:
        zoo[animal_type] += animal_quantity
    else: zoo[animal_type] = animal_quantity
    if animal_type == 'horse':
        return 50 * animal_quantity
    if animal_type == 'oxen':
        return 35 * animal_quantity
    if animal_type == 'mule':
        return 20 * animal_quantity

# getting total_money after animal purchase
def cost(total_money):
    costing = animal_cost(total_money)
    total_money = total_money - costing
    if total_money <=0: # condition when money is less than or equal to 0.
        print("No Money left, resetting money to 1000.")
        total_money = 1000

    print ("Cost of Animals:" + str(costing))
    print ("Total Money Left:" + str(total_money))

    # Recursion for buying more animals:
    choice = raw_input("Do you want to buy any more animals?:")

    if choice in ('Yes','y','Y','yes','YES'):
        cost(total_money)

    # you can use this commented elif condition if you want.
    else: # elif choice in('no','No','n','N','NO'):
        print("thankyou!!")
        print("You have total animals: "+str(zoo))

# main function to initiate program
def main():
    print ("Animals available to purchase: " + "horse, oxen, mule")
    total_money = 1000
    print ("You have " + str(total_money) + " to spend")
    cost(total_money)

if __name__ == '__main__':
    main()

This might help you out.
Have a look into this  for last two lines


text:
Q: Multiple App delegates with storyboard Hello there everyone,
I am new to IOS development and currently I am trying to understand app delegates and how they work.
I know the fact once the project is created by default an app delegate.h/m is generated.
However, I am using my current AppDelegate for setting core data, and I need to work on Facebook integration as well in my storyboard, looking at the code, I can not use one method to recall tasks, am I right? .
Do I use both the Facebook integration and core in the same AppDelegate file?
Or do I create new AppDelegate file and make the Facebook integration?
And if yes, how do I create new AppDelegate?
Any links for tutorials?
Because I do not know if I can use two different view controllers for the same method:
 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

Note that I am using sotryboard no XIB

A: Try these sites; I cannot guarantee you will immediately find what your looking for, but as a fellow person working his way through app development, I'm sure you know how important it is to patiently and thoroughly analyze any helpful material.
https://developer.apple.com/library/ios/documentation/iphone/conceptual/iphoneosprogrammingguide/AppArchitecture/AppArchitecture.html
https://developers.facebook.com/docs/ios/ios-6/


text:
Q: How can I check the null response from url Here is my response which I from my url get when I check that array response is null or not its show me that error
org.json.JSONException: Value

[
  {
    "ReceiverFullName": "",
    "Description": "",
    "DateofAppointment": "/Date(1546322400000)/",
    "SenderFullName": "",
    "Behaviour": null,
    "AppointmentId": 1056,
    "UpdateBy": null,
    "AddDate": "/Date(1562821200000)/",
    "TimeofAppointment": "01:00PM",
    "Title": "",
    "ReceiverBadgeId": 1053,
    "TokenId": "",
    "Status": null,
    "ReceiverUserId": 193,
    "IsNotificationReceived": null,
    "IsNotificationSend": true,
    "UpdateDate": null,
    "SenderUserId": 188
  },
  {
    "ReceiverFullName": "IN",
    "Description": "i want to discuss something with you ",
    "DateofAppointment": "/Date(1570424400000)/",
    "SenderFullName": "MuhammadAbdullah",
    "Behaviour": true,
    "AppointmentId": 1055,
    "UpdateBy": null,
    "AddDate": "/Date(1562734800000)/",
    "TimeofAppointment": "04:00 PM",
    "Title": "hello",
    "ReceiverBadgeId": 330,
    "TokenId": "do8e3lb6fjE:APA91bFXpDpQ-BMg1AMok5RsMIrIodp9fDm30Yswwq08BowRdog8GbjD4apVlhVlTXES5vUZl6fjuNYobDvHhTHr0Aj9jqF-A0J8E64xhxsBXfaky58O6QHuKMipp4RJi2rZP7E4i7Aj",
    "Status": "accepted",
    "ReceiverUserId": 193,
    "IsNotificationReceived": null,
    "IsNotificationSend": true,
    "UpdateDate": null,
    "SenderUserId": 188
  },
  {
    "ReceiverFullName": "IN",
    "Description": "asdasasdasda",
    "DateofAppointment": "/Date(1546322400000)/",
    "SenderFullName": "Muhammad",
    "Behaviour": true,
    "AppointmentId": 1051,
    "UpdateBy": null,
    "AddDate": "/Date(1562648400000)/",
    "TimeofAppointment": "1:02PM",
    "Title": "sadas",
    "ReceiverBadgeId": 330,
    "TokenId": "",
    "Status": "accepted",
    "ReceiverUserId": 193,
    "IsNotificationReceived": null,
    "IsNotificationSend": true,
    "UpdateDate": null,
    "SenderUserId": 188
  },
  {
    "ReceiverFullName": "IN",
    "Description": "i want to meet you",
    "DateofAppointment": "/Date(1567832400000)/",
    "SenderFullName": "MuhammadAbdullah",
    "Behaviour": true,
    "AppointmentId": 1053,
    "UpdateBy": null,
    "AddDate": "/Date(1562648400000)/",
    "TimeofAppointment": "10:00 AM",
    "Title": "Meeting ",
    "ReceiverBadgeId": 330,
    "TokenId": "do8e3lb6fjE:APA91bFXpDpQ-BMg1AMok5RsMIrIodp9fDm30Yswwq08BowRdog8GbjD4apVlhVlTXES5vUZl6fjuNYobDvHhTHr0Aj9jqF-A0J8E64xhxsBXfaky58O6QHuKMipp4RJi2rZP7E4i7Aj",
    "Status": "rejected",
    "ReceiverUserId": 193,
    "IsNotificationReceived": null,
    "IsNotificationSend": true,
    "UpdateDate": null,
    "SenderUserId": 188
  }
]

of type org.json.JSONArray cannot be converted to JSONObject

A:
org.json.JSONException: Value
...
of type org.json.JSONArray cannot be converted to JSONObject

That's an expected error because your response is an Array like this:
[
  {},
  {},
  {},
]

So, you need to handle the response as an Array of object not an object. See https://www.json.org/ for more detail about JSON.


text:
Q: Google spreadsheet: Sum of all bold cells I'm trying to learn scripting in Google Spreadsheet, and I have gotten some simple scripts to work, but this one is a real pain.
I want to make a script that uses the onEdit() function to update a specific cell to show the sum of all bold values in the spreadsheet.
Fx:
1
2
3
4
Then the cell would have a value of (3+4) 7.
Hope it makes sense!

A: It's a bit late, but it's worth an answer and I've been working on a similar question.
The formula to use is:
=sumIfBold(A1:B4,COLUMN(A1), ROW(A1))

The script is:
/**
 * Sums cell values in a range if they are bold. The use of startcol and startrow
 * is to enable the formula to be copied / dragged relatively in the spreadsheet.
 *
 * @param  {Array.Array} range    Values of the desired range
 * @param  {int} startcol The column of the range
 * @param  {int} startrow The first row of the range
 *
 * @return {int}          Sum of all cell values matching the condition
 */
function sumIfBold(range, startcol, startrow){
  // convert from int to ALPHANUMERIC
  // - thanks to Daniel at http://stackoverflow.com/a/3145054/2828136
  var start_col_id = String.fromCharCode(64 + startcol);
  var end_col_id = String.fromCharCode(64 + startcol + range[0].length -1);
  var endrow = startrow + range.length - 1

  // build the range string, then get the font weights
  var range_string = start_col_id + startrow + ":" + end_col_id + endrow
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var getWeights = ss.getRange(range_string).getFontWeights();

  var x = 0;
  var value;
  for(var i = 0; i < range.length; i++) {
    for(var j = 0; j < range[0].length; j++) {
      if(getWeights[i][j].toString() == "bold") {
        value = range[i][j];
        if (!isNaN(value)){
          x += value;
        }
      }
    }
  }
  return x;
}

A: I want to add one tiny point to Tom's excellent answer. It currently returns a string. To return a number, change return x; to return x*1;
Also, for anyone looking to convert this to italics instead of bold, here's the code:
/**
 * Sums cell values in a range if they are italic. The use of startcol and startrow
 * is to enable the formula to be copied / dragged relatively in the spreadsheet.
 *
 * @param  {Array.Array} range    Values of the desired range
 * @param  {int} startcol The column of the range
 * @param  {int} startrow The first row of the range
 *
 * @return {int}          Sum of all cell values matching the condition
 */
function sumIfItalic(range, startcol, startrow){
  // convert from int to ALPHANUMERIC
  // - thanks to Daniel at http://stackoverflow.com/a/3145054/2828136
  var start_col_id = String.fromCharCode(64 + startcol);
  var end_col_id = String.fromCharCode(64 + startcol + range[0].length -1);
  var endrow = startrow + range.length - 1

  // build the range string, then get the font styles
  var range_string = start_col_id + startrow + ":" + end_col_id + endrow
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var getStyles = ss.getRange(range_string).getFontStyles();

  var x = 0;
  var value;
  for(var i = 0; i < range.length; i++) {
    for(var j = 0; j < range[0].length; j++) {
      if(getStyles[i][j].toString() == "italic") {
        value = range[i][j];
        if (!isNaN(value)){
          x += value;
        }
      }
    }
  }
  return x*1;
}

A: Those answers were great, but for me it breaks when pass the Z column (column number 26 to number 27, when we have two letters).
Added a small change to fix that (on the italic version)
    /**
     * Sums cell values in a range if they are italic. The use of startcol and startrow
     * is to enable the formula to be copied / dragged relatively in the spreadsheet.
     *
     * @param  {Array.Array} range    Values of the desired range
     * @param  {int} startcol The column of the range
     * @param  {int} startrow The first row of the range
     *
     * @return {int}          Sum of all cell values matching the condition
     * @customfunction
     */
    function sumIfItalic(range, startcol, startrow){
      // convert from int to ALPHANUMERIC
      // - thanks to Daniel at http://stackoverflow.com/a/3145054/2828136
      var secondColChar = parseInt(startcol / 27); //26 is the number of col Z, 26 letters, works for only for two char

      var start_col_id = ""
      var end_col_id = ""

      if(secondColChar > 0) {
        start_col_id += String.fromCharCode(64 + (secondColChar));
        end_col_id += String.fromCharCode(64 + secondColChar + range[0].length -1);
      }

      start_col_id += String.fromCharCode(64 + (startcol % 27 + (secondColChar * 1))  );
      end_col_id += String.fromCharCode(64 + (startcol % 27) + (secondColChar * 1) + range[0].length -1);

      var endrow = startrow + range.length - 1

      // build the range string, then get the font styles
      var range_string = start_col_id + startrow + ":" + end_col_id + endrow

      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var getStyles = ss.getRange(range_string).getFontStyles();

      var x = 0;
      var value;
      for(var i = 0; i < range.length; i++) {
        for(var j = 0; j < range[0].length; j++) {
          if(getStyles[i][j].toString() == "italic") {
            value = range[i][j];
            if (!isNaN(value)){
              x += value;
            }```
          }
        }
      }
      return x*1;
    }

tested only in my case, though...

A: Thanks for this code, but unfortunately with multiple values it was returning a string. I've made a small update in the FOR loop block at the bottom, and deleted some spurious backticks.
    /**
 * Sums cell values in a range if they are italic. The use of startcol and startrow
 * is to enable the formula to be copied / dragged relatively in the spreadsheet.
 *
 * @param  {Array.Array} range    Values of the desired range
 * @param  {int} startcol The column of the range
 * @param  {int} startrow The first row of the range
 *
 * @return {int}          Sum of all cell values matching the condition
 * @customfunction
 */
function sumIf_Italic(range, startcol, startrow){
  // convert from int to ALPHANUMERIC
  // - thanks to Daniel at http://stackoverflow.com/a/3145054/2828136
  var secondColChar = parseInt(startcol / 27); //26 is the number of col Z, 26 letters, works for only for two char

  var start_col_id = ""
  var end_col_id = ""

  if(secondColChar > 0) {
    start_col_id += String.fromCharCode(64 + (secondColChar));
    end_col_id += String.fromCharCode(64 + secondColChar + range[0].length -1);
  }

  start_col_id += String.fromCharCode(64 + (startcol % 27 + (secondColChar * 1))  );
  end_col_id += String.fromCharCode(64 + (startcol % 27) + (secondColChar * 1) + range[0].length -1);

  var endrow = startrow + range.length - 1

  // build the range string, then get the font styles
  var range_string = start_col_id + startrow + ":" + end_col_id + endrow

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var getStyles = ss.getRange(range_string).getFontStyles();

  var x = 0;
  var value;
  for(var i = 0; i < range.length; i++) {
    for(var j = 0; j < range[0].length; j++) {
      if(getStyles[i][j].toString() == "italic") {
        value = range[i][j];
        if (!isNaN(value)){
          x += value*1;
        }
      }
    }
  }
  return x*1;
}

A: My problem with the previous answers was an error (not returning a number).  I think this is because I had blank or non-numeric entries in my range.  The code below works for me by checking for numeric value before summing.
/**
 * Sums cell values in a range if they are bold. The use of startcol and startrow
 * is to enable the formula to be copied / dragged relatively in the spreadsheet.
 *
 * @param  {Array.Array} range    Values of the desired range
 * @param  {int} startcol The column of the range
 * @param  {int} startrow The first row of the range
 *
 * @return {int}          Sum of all cell values matching the condition
 * @customfunction
 */
function sumIfBold(range, startcol, startrow) {
  // convert from int to ALPHANUMERIC
  // - thanks to Daniel at http://stackoverflow.com/a/3145054/2828136
  var secondColChar = parseInt(startcol / 27); //26 is the number of col Z, 26 letters, works for only for two char

  var start_col_id = ""
  var end_col_id = ""

  if(secondColChar > 0) {
    start_col_id += String.fromCharCode(64 + (secondColChar));
    end_col_id += String.fromCharCode(64 + secondColChar + range[0].length -1);
  }

  start_col_id += String.fromCharCode(64 + (startcol % 27 + (secondColChar * 1))  );
  end_col_id += String.fromCharCode(64 + (startcol % 27) + (secondColChar * 1) + range[0].length -1);

  var endrow = startrow + range.length - 1

  // build the range string, then get the font styles
  var range_string = start_col_id + startrow + ":" + end_col_id + endrow

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var getWeights = ss.getRange(range_string).getFontWeights();

  var x = 0;
  var value;
  for(var i = 0; i < range.length; i++) {
    for(var j = 0; j < range[0].length; j++) {
      if(getWeights[i][j].toString() == "bold") {
        value = range[i][j];
        if (!isNaN(parseFloat(value)) && isFinite(value)) {
          x += value;
        }
      }
    }
  }

  return x;
}


text:
Q: store Expression> where as a class property I have a class that extends the System.Web.UI.WebControls.GridView control.
I want to have a property that can save my EF expression to use throughout the control.
Problem is, T is not defined.
public sealed class NCGridView : GridView
{
    private Expression<Func<T, bool>> _where;

    public void LoadWhere(Expression<Func<T, bool>> where)
    {
        _where = where;
    }
}

RedHat suggestion attempt
    private Expression<Func<BaseModel, bool>> _where;

    public void LoadWhere<T>(Expression<Func<T, bool>> where) where T : BaseModel
    {
       // Cannot cast from: Expression<Func<T, bool>> to:  Expression<Func<BaseModel, bool>>
        _where = where;
    }

A: Answer 2:
Update:
public Expression<Func<BaseModel, bool>> LoadWhere<T>(Expression<Func<T, bool>> where) where T : BaseModel
{
    where = LambdaExpression.Lambda<Func<BaseModel, bool>>(where.Body,where.Parameters);
}

Answer 1:
Use:
Expression<Func<object, bool>>

Supported any type.
Sample:
Expression<Func<object, bool>> exp = p => ((Table1)p).Code == 1;
var a = new MyContext().Table1.Where(exp).ToList();


text:
Q: Tomcat url redirection (not root) Is it possible to redirect specific url
http://10.99.77.170:8080/web/userview/MainView/_/inboxing
to
http://10.99.77.170:8080/web/userview/MainView/_/my_docs
It should not redirect url's like
http://10.99.77.170:8080/web/userview/MainView/_/inboxing?something=sth
As I am using one framework which doesnt allow me to do this, is it possible to make such and redirect using Apache Tomcat on which it is running ?
Thank you for any suggestions.

A: The easiest way to do conditional redirection is using tuckey's url-redirect project. It's packaged as a JAR file that you drop into your web app's WEB-INF/lib/ directory and configure using WEB-INF/lib/web.xml and an external configuration file (to map incoming to outgoing URLs).
Their web site has extensive documentation about how to set up those mappings. You should be able to come up with a rule that does what you want it to do. Something like this:
<urlrewrite>
  <rule match-type="wildcard">
    <!-- The 'condition' is what prevents redirection when there is a query string-->
    <condition type="query-string" operator="notequal"></condition>
    <from>/userview/MainView/_/inboxing</from>
    <to type="redirect">/userview/MainView/_/my_docs</to>
  </rule>
</urlrewrite>


text:
Q: How to show all files with some filters? I need to display on screen all the files that hang recursively from the root and that have not been modified in the last two days, with a size smaller than 5 KB.
I can show the files that hang recursively from the root with ls -R but it also show me directories, i dont know if is there any way to show only the files with the filters that i write.
I appreciate any help.

A: You should able to do that with find and something like:
find / -mtime +1 -type f

*

*find starting from root: /

*select anything that has not been modified in the last two days (48 hours): -mtime +1

*only select files: -type f
Be careful with units on mtime
As mentioned in comments and explained here, be aware of what the units on -mtime +1 means and then match that to your expectations.


text:
Q: average of the inverse of Euclidean norm of Guassian variable If we assume that $\mathbf{h}$ is a $N$-dimension complex Gaussian random vector that with zero mean and diagonal variance matrix $\Sigma$. Is there a closed-form result for the mean of the following expression $\frac{1}{||\mathbf{h}||_2^2}$ with the variance matrix?
I really appreciate for any comments.


text:
Q: Como cadastrar, consultar e exibir dados na mesma requisição? Tenho um formulário onde o usuário insere seus dados (nome, experiência, altura e peso), as informações são cadastradas no banco, comparadas e é retornado para o usuário o modelo de prancha ideal de acordo com as informações dele, dentro de um modal. Tudo isso já está feito e funcionando.
O problema é que, obviamente, como o SELECT já está dentro do código, assim que a página é carregada a REQUISIÇÃO no banco já está feita! E tenho como retorno o último usuário que cadastrou suas informações no banco.
O usuário tem que inserir seus dados no form, os dados dele é cadastrado no banco, é feita a comparação e o retorno com o resultado seja exibido na MESMA requisição.

Até agora, o que fiz:
Aqui é feito o SELECT. A comparação dos dados no BD:
function BuscaAlgo($conexao){
$query = "SELECT  USU.usuario,
                 USU.nome,
                 USU.exp,
                 USU.altura,
                 USU.peso,
                 PRAN.exp_ref,
                 PRAN.altura_ref,
                 PRAN.peso_ref,
                 PRAN.tipo_prancha,
                 PRAN.tamanho_prancha,
                 PRAN.meio_prancha,
                 PRAN.litragem_prancha
                  FROM DADOS_USUARIO AS USU
                       INNER JOIN PRANCHA AS PRAN
                           on USU.exp = PRAN.exp_ref
                            WHERE USU.altura = PRAN.altura_ref
                              AND USU.peso = PRAN.peso_ref
                                ORDER BY USU.usuario DESC LIMIT 1";

  $resultado = mysqli_query($conexao,$query);

  $retorno = array();

  while($experiencia = mysqli_fetch_assoc($resultado)){
    $retorno[] = $experiencia;
  }
 return $resultado;
}

Aqui exibe o resultado do SELECT feito no banco:
include "banco.php";

$resultado = array();
$resultado = BuscaAlgo($conexao);

foreach($resultado as $valor){
  echo $valor['usuario']; print('.  .');
  echo $valor['nome']; print('.  .');
  echo $valor['exp']; print('.  .');
  echo $valor['altura']; print('.  .');
  echo $valor['peso']; print('.  .');
  print('///////');
  echo $valor['tipo_prancha']; print('.  .');
  echo $valor['tamanho_prancha']; print('.  .');
  echo $valor['meio_prancha']; print('.  .');
  echo $valor['litragem_prancha'];
}

(Ignorem a parte visual. Neste momento, o objetivo é só trazer o resultado mesmo)
Como posso fazer isso dentro da mesma requisição?
Qual a melhor forma de fazer e como?


text:
Q: What is the timeframe for Dune 2000/Battle for Dune? I know that the video games Dune II/2000 and Battle for Dune are not considered canon with the 1984 movie, despite sharing props & overall look-and-feel. The games themselves do not mention the events of the books, and the political/economic structure shown no longer exists after the events of Dune (the first book). This leads me to believe that they take place at an earlier timeframe, but a quick search failed to reveal any official word on when they take place. And the books DID reference previous wars over control of Arrakis, so it should be possible to shoehorn the plot into the timeline.
Assuming a somewhat-intact timeline, approximately how long before the first book would the games take place? Or is this semi-intact timeline even possible?

A: They simply don't fit to the same time frame, if anything they are "alternative history".  While you could be generous with Dune II saying that it takes place some time before the first "Dune"  book, because Herbert didn't (please correct me here) mention how Harkonnens took the possession of the planet, even then the ending would make no sense with the winner becoming new Emperor.
Dune 2000 is even less closer to the canon with dead emperor starting the whole war. The guild and Tleilax treason also never had place...  But if we assume that it's alternative history (without Paul being born)  then it would take place few years after the ending of the first book, because Baron Harkonnen during the campaign dies of the old age.
EDIT: The Emperor in the Dune 2000 is called Emperor Frederick IV, not Padishah Emperor Shaddam IV, same with Baron Harkonnen who doesn't have first name (so it might not be Vladimir). So its quite possible that action takes place long in the past before books when House Corinno briefly lost power.

A: According to the Producer of Emperor: Battle for Dune, the game series (Emperor being the direct sequel of Dune 2000) was set several centuries before the events of the Dune novels

IGNPC: Tell us a little bit about the story if you can. We know you said that the game take place a few centuries before the story in
the novels, but can you be more specific about the setting for the
conflict?
Chris Longpre: The Emperor has been assassinated by the Lady Alara (in Dune 2000), leaving no heir and a huge power vacuum. Each
house is laying claim to the throne, but each realizes that
controlling Arrakis, home of the spice, is the key to winning the
Imperial throne. It finally blossoms into war among the three most
powerful houses, the noble Atreides, the insidious Ordos and the evil
Harkonnen.
EMPEROR: BATTLE FOR DUNE INTERVIEW - Producer Chris Longpre talks about the sequel to one of our favorite games.


text:
Q: Turn off an app in PowerApps Just a simple question, allmost all is in the title.
I would like to know if it's possible to turn off an app in PowerApps without deleting or unsharing it ?

A: There's no OFF button in PowerApps.
You may suggest it as an idea: https://powerusers.microsoft.com/t5/PowerApps-Ideas/idb-p/PowerAppsIdeas/status-key/Started

A: I think it is not possible. Either you will delete or unshare from all users.


text:
Q: How to make the webbrowser address bar uneditable? I want to open web browser with parameters in the url :
ConfigDb cfgDb = (new ConfigDb(getApplicationContext())).open();
String cfg_number = ConfigDb.getPhoneNumber(getApplicationContext());
Config cfg_url = cfgDb.getConfig("cfg.url");
String formul = "vidy;"+vokatraCode+";m="+tsenaCode+";l=mg;p=prepaid";
String url = cfg_url.getConfigValue()+"?from="+cfg_number+"&to=432&text="+formul;
cfgDb.close();
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(browserIntent);

As we can see there is a security issue : after the webbrowser is opened then the user can edit the parameters values in the address bar. So how to make the address bar uneditable ? Or how to make users unable to edit the url in the address bar ?

A: You are calling to browser application of phone instead of that you can create webView.
There is no way to hide address bar of native browser application because  the browser will not be modified by your manifest file or any other way, as it is an independent application
Please try adding this `WebView.setWebViewClient(new WebViewClient());


text:
Q: Want to cancel OnActionExecuted for Custom action filter created I have created a custom action filter, that runs some analtyics code on each action that has the filer.
On one controller's action, on the basis of one boolean flag, I would want to skip the OnActionExecuted code of that filter applied on this action.
I see Cancelled property in that in OnActionExecuted, but not sure how i can make this true in Controller's action.
One possibility is to have some value in RouteData, on the basis of that flag and then check that value if thats true then simple cancel this. But I am not sure this is the correct approach.
Thanks


text:
Q: Angular 4: Select option with 'disabled' attribute is not selected by default when model value is empty When the model is empty, the selected/disabled option is not selected in Chrome/firefox. This works perfectly fine is Safari.
<select [(ngModel)]="selectedProject" name="project" id="project">
   <option value="" [selected]=true [disabled]="true">Select project</option>
   <option [value]="project.id" *ngFor="let project of projects">{{project.title}}</option>
</select>

This was reported as a bug in AngularJS, however, neither [disabled] or disabled works for me.
https://github.com/angular/angular.js/issues/7202

A: Surprised this wasn't answered still. Anyways this worked for me..
For disabling it
<select [attr.disabled]=true class="custom-select" formControlName="title">
     <option [value]="project.id" *ngFor="let project of projects">{{project.title}}
     </option>
</select>

And For enabling it
<select [attr.disabled]=null class="custom-select" formControlName="title">
     <option [value]="project.id" *ngFor="let project of projects">{{project.title}}
     </option>
</select>

You can also set variable to it. Works like a charm!


text:
Q: Fundamental polygons with infinite pairwise identifications The topology of a closed surface can be constructed
by identifying edges of a fundamental polygon of an
even number $2n$ of edges.
Labeling the edges and using $\pm 1$ exponents to indicate
direction,
the construction can be specified by a string of $2n$ symbols:
$a b a^{-1} b^{-1}$ for the torus, $a a b b$ for the Klein bottle, etc.
My question is: Does it make sense to have an infinite
number of boundary identifications, i.e., does it
define some topological object?
More specifically:

*

* Does an infinite string of symbols representing pairwise
identifications correspond to some surface?
For example, the generalization of a non-orientable genus-$n$ surface as $n \rightarrow \infty$:
$$a_1 a_1 a_2 a_2 a_3 a_3 \cdots a_i a_i \cdots \;.$$

* Does it make sense to have an uncountable number of pairwise point identification
around a circle?
For example, parametrize the circle circumference from 0 to 1
and identify points with complementary binary representations:
$$.011100100011\ldots  \leftrightarrow
 .100011011100\ldots \;.$$

These extensions may be nonsensical, in which case I apologize for the distraction!
But if something along these lines has been studied, I'd appreciate a reference.  Thanks!
Edit. What was nonsensical was my bit-complement example, as pointed out by both
Victor and Sergei.  I'll leave it so their remarks make sense. I intended a more patternless
pairing.

A: I am not sure what the question is, but will try to answer anyway. This is basic general topology stuff, sorry if you meant something deeper in your question.
For any topological space $X$ and any equivalence relation $\sim$ on $X$ there is a natural topology on the quotient $X/\sim$, see e.g. this Wikipedia article. Intuitively, the quotient space is the result of "gluing together" all points in every equivalence class of $\sim$.
Making a surface from a polygon is a partial case. For example, the gluing scheme $aabb$ represent the following equivalence relation on a square $ABCD$: an interior points is not equivalent to anything but itself, a point $X$ on the side $AB$ is equivalent to a point $X'$ in $BC$ such that $AX:XB=BX:XC$ and similarly for the sides $CD$ and $DA$. By transitivity, all four vertices $A,B,C,D$ are in the same equivalence class. (In other gluing schemes, such as $abab$, the vertices can form more than one equivalence class.) The quotient space is a Klein bottle. In general, it is easy to prove that for any gluing scheme of a $2n$-gon (where every letter appears exactly two times) the resulting quotient space is a compact surface without boundary. Then there is a topological classification of such surfaces, and so on.
Note that you don't have to begin with a polygon. Any shape homeomorphic to a polygon (e.g., a 2-dimensional round disc) will work the same way because homeomorphic spaces are identical from the topological perspective.
Speaking about generalizations, once you have defined a topological space that serves as a "generalized polygon" and an equivalence relation (the gluing rule) on it, you get a valid topological space as a quotient. However it can be some "weird" space rather than a surface, and it may depend on how exactly you generalize the notion of a polygon.
For example, if you asked about a two-sided infinite string like "$\dots a_{-1}a_{-1}a_0a_0a_1a_1\dots$", it would be natural to take the half-plane as a "polygon", divide its boundary into unit segments and glue them according to the string. Sometimes the result is a (non-compact) surface, sometimes it is not. Namely, if every equivalence class is finite, the quotient is a surface (= two-dimensional manifold), otherwise it is not (because it is not locally compact). In my example, all "vertices" end up in the same equivalence class, so the quotient is not a surface.
Alternatively, you could pack these infinitely many segments around a circle. In this case the quotient is compact but most likely it will fail to be a surface around accumulation points.
You second example is clear. You identify points $x$ and $y$ if $x+y=1$. Equivalently, you could divide the circle into two segments $[0,1/2]$ and $[1/2,1]$ and apply the gluing scheme $aa^{-1}$ to this "2-gon". The resulting surface is the sphere. Another well-known construclion is to identify every point on the circle with the opposite one - this is the same as "$aa$" gluing and the result is the projective plane. However if you make some weird pairwise identification, most likely the result will be some weird topological space.

A: Identification spaces with infinitely complicated identifications do occur naturally in various contexts. Here are a few more remarks:

*

*If you define an involution on a countable set of intervals on the boundary of a surface, as in Victor Protsak's remark, and extend the equivalence relation to finite equivalence classes of the closure (i.e., vertices), you can construct arbitrary noncompact surfaces. The classification of these is known, and rather interesting.  In the orientable case: The first invariant is the set of ends of the space, meaning, the inverse limit of the set of components of complements of compact sets. I think this is the same as the closure of the equivalence relation extended to the rest of the circle, minus the surface, but I haven't thought it through properly.  The set of ends can be an arbitrary closed homemorphism type of compact totally disconnected space. I believe it's known that the number of types has the cardinality of the continuum; it's easy to see it's at least $\omega$ and at most $2^\omega$.  The second invariant is a closed subset of the set of ends, that is the limit of "handles", that is, pairs of curves that intersect in one point.  Finally, if there are only finitely many handles, you need the genus.

*There is a structure called a geodesic lamination in the disk: a closed collection of disjoint hyperbolic lines ending at infinity. Given a lamination, you can identify the endpoints. This kind of identification arises in multiple ways.  First, it describes the structure of the cut locus" for a curve in the plane. For which pairs of points is there a circle whose interior is contained on the inside, but touches only those two points? Second, if you identify all lines to points, the resulting space is still homeomorphic to the plane.  They give explanations for the structure of Julia sets and limit sets of Kleinian groups, etc.
More generally, one can represent identifications by collections of lines that are allowed to cross, but the theory becomes more complicated.  In the case of Julia sets, the identification is in some sense isometric. (Actually, the involution is nontrivial only on a set of measure 0 with dense complement, but it is a limit of isometric involution on finite collections of intervals.)  If you identify the circle using two geodesic laminations, one on the inside and one on the outside, you typically get $S^2$, and the circle becomes a space-filing curve: a sort of Hamiltonian path that is a limit of simple curves.

*For a dynamical system, it is natural to look at the set of all orbits.  This is an identification space that is somtimes "nice" but more often is (in Ivanov's words) weird:  non-Hausdorff and failing other separation properties. Nonetheless, these quotient spaces often carry structure that is helpful to understanding the dynamics. A simple example: the flow in the plane minus the origin $\phi_t(x,y) = (\exp(t) x, \exp(-t) y) of a linear differential equation. The orbit space is a 1-dimensional manifold, because you can take a cross-section near any point that meets any orbit at most once, so it embeds in the quotient space. However, the quotient is not Hausdorff.


text:
Q: MonoTouch How To: Get Title/Subtitle from Selected Annotation, Set Custom Property, Use Event Object 1st Question: How do I get the title and subtitle of a selected annotation?
2nd Question: How do I set a custom property such as 'placemark id' so that I can use it to fetch details from a datastore?
3rd Question: How do I use the event object that is thrown in say: mapview.DidDeselectAnnotationView += (o, e) ?

A: *

*Given an annotation "a", you do:
a.Title = "My Title";
a.Subtitle = "My Subtitle";

*I do not quite understand the question, can you post a code snippet?

*the type of the "o, e" in your sample is (object sender, MKAnnotationViewEventArgs eventArgs).
The "sender"  corresponds to the MKMapView that sent the event, but you probably have that already.
The "evt" contains a property "view" which is of type MKAnnotationView which corresponds to the MKAnnotationView that is being displayed.


text:
Q: Wix Not overwriting my app.config Hi everyone i'm using wix to install my current application and it successfully installs everything and the initial version of the installer has NeverOverwrite="yes" in the installer but in a future version I realized that i can overwrite it everytime but when i remove the NeverOverwrite attribute in the future version of the installer it doesn't overwrite the configuration. Do i have to change the guid or do a major upgrade to get the configuration file to get updated with the latest version of my installer?

A: When performing an upgrade the installer only replaces assemblies and associated files of assemblies that have changed from the current installation.
App.config files are associated with particular executable assemblies, which, if it has not had its version number increased in any way will not be updated on the installation machine (as the installer detects no change in version numbers).
You could either increase the version number of the executable associated with the app.config file, or use Orca to forcefully overwrite the app.config.


text:
Q: CSS: border-top on  not being applied I'm stuck on why the style on the
 doesn't seem to be working: (jsfiddle). What am I doing wrong?
<!DOCTYPE html>

    <title>Test</title>

            Product
            Unit Price
            Quantity
            Total

            Product 1
            £0.30
            <input value="2"/>
            £0.60

                Subtotal
                £0.60

                Shipping
                £0.00

                Total
                £0.60

A: Demo Fiddle
You need to add:
table {border-collapse: collapse;}
Incidentally, you should also separate out your styles from content and put your CSS in a separate stylesheet.

Alternative Solution
Add:
display:block
To your tbody.

A: This could probably work:
tbody > tr:first-child > td {
    border-top: 3px solid blue;
}

BUT! Normal rules about styling HTML with CSS ends at tables.


text:
Q: Style sheets and body and head tags in programmatically produced HTML I'm using Scala to produce HTTP, HTML and CSS. I also intend to use Scala to produce Javascript but I haven't got to that stage yet.
What are the advantages of using separate style sheets? CSS offers a form of multiple inheritance by which you can organise the styling of your mark up. However Scala already has its own system of multiple inheritance and other functional languages provide their own powerful methods of problem decomposition and declarative composition. While producing separate style sheets, adds algorithmic complexity and hinders the production of comprehensible clean code.
One of the claimed advantages of separate style sheets is that they use less bandwidth. However I find it difficult to believe that CSS uses significant bandwidth compared to images let alone video. So do separate style sheets give advantages to search engine ranks and site classification? Do they speed up or slow down rendering and layout? Do they help accessibility and user defined style? I would have thought not using separate style sheets might actually speed up delivery in HTTP 1.1 if not in 2.0
Similarly with Head and Body nodes /Tags. Do they serve any advantage to justify the added complexity of producing them programmatically? They don't seem to make any functional difference to what the browser produces.
So the question is how important are separate style sheets and Body and Head nodes to producing optimal web sites? Is it OK to put CSS into the HTML leaf Nodes?

A: The advantages to using separate stylesheets:

*

*Cachability: no need to re-load the same style over and over again

*Smaller size: even with gzip compression, 400 div tags all styled alike will be more bytes on the wire per-page than the page without the styles inlined.

*Possibility: Some CSS cannot be expressed in an inline style. For example, any pseudo-element or state selector (:hover, :focus, etc.)

*DRY: not applicable if you are building a style tree at compile time to apply to an HTML tree at compile time.

The disadvantages:

*

*Speed: inline styles will be faster to render, since when the browser parses the tag it knows what styles apply.

*Locality: inline styles make it easy to see what the element will look like (browser debugging tools make this a moot point)

html / head / body - do I need them?
The general consensus seems to be "yes", principally because you are more likely to run into obscure browser bugs if you don't include them (since the "how to choose what to make a child of which element" algorithm isn't blindingly obvious and some of the corner cases aren't necessarily obvious to the developer).


text:
Q: Css code for header Joomla I have been trying to edit my header in Joomla. I have added following class to my template to round the corners and add the background:
.holola {
background: #FFF!important;
border-top-left-radius: 15px;
border-top-right-radius: 15px; }

How I can bring the logo up and make it look offside the header, like in attached image. I know how to make this happen using image in header, but I want to make it pure CSS to make the page look better in mobile version.
I have tried to add padding but I think it should be more complicated code to use?

A: Remove the padding you've added.
Then add some top margin to the .wrapper to push the main content down a bit.
body.boxed .wrapper {
    margin: 60px auto 0 auto
}

And now add margin-top to the logo to move it up.
#header_logo {
    margin-top: -60px
}

A: Try adding these also
#zo2-header{

    margin-top: 50px;
}

#header_logo .logo_normal{
   position: absolute;
   top: -103px;
}

A: Remove your padding: 60px 0; from #zo2-header and replace with margin-top: 60px;.
Add
#header_logo {
  position: relative;
  top: -60px;
}

A: You would want to use position relative. See this jsfiddle for a simple example that should work for you situation.
#img {
    background-color:red;
    height: 80px;
    width: 80px;
    position:relative;
    top: -40px;
}

Basically the important parts here is the combination of position: relative and top: -40px. This says position the element relative to the parent element and "anchor" its top -40 pixels from where it would normally be (top aligned with the header's top)


text:
Q: Visibilty of statements in a view related to transaction? i have a question about data visibility in database views.
I use Oracle.
I have a table myscheme.users and a table global.users (myscheme and global are schemes)
There is a view "globalusers" in the global scheme which merges both user tables.
I have a java application that inserts a new user in the myscheme.users table. After that it makes a query for the new user in the globalusers-view to load the newly created user.
As all this happens inside the same transaction. My question is now, why is the newly created user visible in the myscheme.user table but not in the globalusers-view?
When the transaction has been closed, the user is also in the globaluser-view.
My application is running inside a JBoss 5 using hibernate.
The view is defined in that way:
CREATE OR REPLACE VIEW V_USERACCOUNT AS
    SELECT u.USERACCOUNT_ID,u.USERNAME,u.INITIALS,u.COMMONNAME,u.PASSWORD,'local' AS source
        FROM "USERACCOUNT" u
    UNION
        SELECT u1.USERACCOUNT_ID,u1.USERNAME,u1.INITIALS,u1.COMMONNAME,u1.PASSWORD 'global' AS source
        FROM GLOBAL."USERACCOUNT" u1

A: If the INSERT into the table and the SELECT from the view are, in fact, part of the same database transaction (which necessarily implies that they are executed in the same database session), the newly inserted row would be visible in the view (assuming the row meets whatever criteria the view uses to determine which rows to display).  If the new user is not in the view, that implies that either

*

*The INSERT and the SELECT are not part of the same database transaction, or

*The INSERT is not sufficient to cause the row to be available in the view.  Perhaps there is some other lookup table that is joined in the view that doesn't have the data for the new row when you query the view but the lookup is populated later in the transaction.

*You have a bug somewhere in your code where the INSERT isn't actually happening when you think it is or the query isn't happening after the INSERT or the query isn't actually hitting the view you posted.

Based on your latest update, it appears that #1 is almost certainly the problem.  If you have different DataSources, the INSERT uses one DataSource, and the SELECT uses a second DataSource, the two operations are not happening in the same database transaction.  They may be happening in the same application server transaction-- the application server may well be creating a distributed transaction-- but if it's not the same database transaction, you won't be able to see uncommitted changes.


text:
Q: Seriously. A mod won't migrate? I posted two flags on this question: https://meta.stackexchange.com/q/115179/155556
The 1st one was accepted and the 2nd one was rejected.
Here is my flag requests:

declined - if the user cannot work out how to post on the proper site, migration will not make the question any better

Really??
We beat down newbies because they don't know any better? Why not just migrate it??
(The user has since reposted his Q: jQuery's .position conflicts with CSS3's transform )

A: Yes really.
Meta is a black hole. You come, you read, you lose your mind.
There are two reasons programming questions are posted on Meta:

*

*To get around a ban or any rate limiting in effect.

*They have no idea where to find their pants and instead wear their socks on their ears.

In either of these cases, migration only hurts small children and faeries who enjoy a coked up sleuth who plays the fiddle. If you enjoy such molestation, feel free to request migrations for questions that also are subpar pr0blams. Expect to be denied.
You want out of Meta? That's not going to happen unless you do it yourself.

A: Yes, seriously.  We don't migrate away from Meta.  The majority of cases where programming questions gets asked here are cases where the OP is trying to get around an account ban.

We beat down newbies because they don't know any better?

How is that beating them down?  They can just go post it on SO if they aren't banned.  I don't see the harm.


text:
Q: Returning an image using Web API I have a web service method, which looks like this:
[HttpGet("{id}")]
public ActionResult<byte[]> Get(Guid id)
{
    var files = Directory.GetFiles(@"Pictures\");
    foreach (var file in files)
    {
        if (file.Contains(id.ToString()))
        {
            return System.IO.File.ReadAllBytes(file);
        }
    }
    return null;
}

Here is the client code, which is definitely working i.e. it is calling the web service and the web service is returning the image:
var response2 = await client.GetAsync("http://localhost:59999/api/Images/5c60f693-bef5-e011-a485-80ee7300c692");
byte[] image2 = await response2.Content.ReadAsByteArrayAsync(); //https://stackoverflow.com/questions/39190018/how-to-get-object-using-httpclient-with-response-ok-in-web-api
System.IO.File.WriteAllBytes("image.jpg", image2);

When I try to open image.jpg in Paint; it says it is an invalid file.  What is the problem?

A: If you want to return file do not return byte[] from action because it gets base64 encoded. You can decode base64 string on client or better would be using File method in action
[HttpGet("{id}")]
public ActionResult Get(Guid id)
{
    var files = Directory.GetFiles(@"Pictures\");
    foreach (var file in files)
    {
        if (file.Contains(id.ToString()))
        {
            return File(System.IO.File.ReadAllBytes(file), "image/jpeg");
        }
    }
    return null;
}


text:
Q: How to wrap an element with a link override it events? I have got 2 elements that i want to wrap and cancel their events. one is iframe and the other is an object ..

<object height="400" width="500"><param name="allowfullscreen" value="false">
<param name="AllowScriptAccess" value="always">
<param name="movie" value="http://embed.rede.com/player/">
<param name="FlashVars" value="id=97219&&autostart=false">
<embed src="http://embed.rube" allowfullscreen="false" AllowScriptAccess="always"
flashvars="autostart=false" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash"
type="application/x-shockwave-flash" height="400" width="500" /></object>

I want to override their events with html or css, instead of using javacript.. but javascript option is also an option..
How do I override the event of the object and the iframe with the event of the link?
UPDATE:
I thought to do something like this:

Put the div of the iframe below the div of the link..
doesnt work .. but i think the solution should be along those lines
An alternative way would be to use javascript to disable click on the div
UPDATE:
I need a simple solution. the solution is to put the div above the iframe

A: assuming jQuery:
$("iframe").click(function(){
   window.location = <yourDesiredHref>;
});

same applies for the object.

A: You could make the link cover the object by putting it before the object and giving it an absolute position. See fiddle for example: http://jsfiddle.net/sveinatle/BP9xc/4/
The important bits are:

and styling it so the link covers the object:
.container{
    position:relative;
    border: 2px solid red;
    overflow:hidden;
}
#overlay{
    display:block;
    position:absolute;
    width:100%;
    height:50%;
    background-color:rgba(255,0,0,0.5);
}

A: With html/css you could try something like this:

*

*create an empty div "overlay" beneath the object

*make it as high as the iframe and object combined (815px if you don't use any padding/margin)

*make it as wide as the bigger element (500px)

*position it so that it overlays the other elements, for example with margin-top:-500px;
give it a display:block; and a bigger z-index than the other two elements just to be sure it's on top

*put a link in there/around it that stretches as big as "overlay" is

You could also try if it's possible to put "overlay" around the elements and putting it on top with z-index then.


text:
Q: Super CSV (org.supercsv.io) invalid content length on Spring REST controller: ERR_CONTENT_LENGTH_MISMATCH 200 Im using Super CSV to provide REST endpoint with some data. It was working fine for a long time, but now data is too large and half of it is not delivered by Spring REST Controller. I have to set content length to make this endpoint provide all data, but I cannot find any way, how to provide correct content length. With some hardcoded value I get the whole file with Postman, but browser blocks it with error:
@GetMapping(value = "/file", produces = "text/csv")
    public void getFile(HttpServletResponse response) throws IOException {
        String headerKey = "Content-Disposition";
        String headerValue = "attachment; filename=file.csv";
        response.setHeader(headerKey, headerValue);
        response.setContentType("text/html; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentLength(0); //how to set content length?

        ICsvBeanWriter csvWriter = new CsvBeanWriter(response.getWriter(), CsvPreference.STANDARD_PREFERENCE);

        String[] csvHeader = {"header"};
        String[] nameMapping = {"name"};

        csvWriter.writeHeader(csvHeader);
        csvWriter.write("some object", nameMapping);

        csvWriter.close();
    }

nginx version: nginx/1.12.2
nginx settings:
location ^~ /endpoint {
    proxy_pass http://localhost:8090;
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Scheme $scheme;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_buffering off;
    proxy_cache off;
  }

A: Ok, I've found a solution if someone needs it in future. The trick is to use reflection and set content length manually:
response.setContentLength(getContentLength(response));
csvWriter.close();

private int getContentLength(HttpServletResponse response) {
    try {
        Field innerResponseField = ServletResponseWrapper.class.getDeclaredField("response");
        innerResponseField.setAccessible(true);
        innerResponseField.get(response);
        Field contentWrittenField = OnCommittedResponseWrapper.class.getDeclaredField("contentWritten");
        contentWrittenField.setAccessible(true);
        return (int) contentWrittenField.get(response);
    } catch (Exception e) {
        return 0;
    }
}


text:
Q: Inheritance-Finding size of an object of a class I have to find the size of an object of a derived class.But the thing is do I have to count the size of private members since object has only access to public members?
Thanks in advance.

A: sizeof tells you the size of an object, regardless of inheritance. Summing the size of members will not give you a reliable size for your object, it doesn't account for padding between those members or other size overhead. Private members, even inherited ones, contribute to the size of the object in the same way public members do.
The usage is sizeof(obj) or sizeof(type).


text:
Q: Send all files on Desktop to Evernote then delete Good morning,
I am trying to write an AppleScript that I can run that will send all the files on my desktop to Evernote, and then delete the files. My code to date is:
on run {input}

tell application "Finder"
    select every file of desktop
end tell

tell application "Evernote"
    repeat with SelectedFile in input
        try
            create note from file SelectedFile notebook "Auto Import"
        end try

    end repeat

end tell

tell application "Finder"
    delete every file of desktop
end tell

end run

If I run this then the first and last 'tell' work fine (ie. the script highlights then deletes all the files on the desktop), but the middle 'tell' doesn't do anything.
However, if I manually highlight all the files on the desktop and then run just the middle 'tell' then it imports fine - each item into a separate note as intended.
As you can tell, I am new to AppleScript - I suspect I need to put the selected files in an array of some sort, but can't figure it out. Help!
Many thanks
Rich

A: Your code fails because there is no relation between your input variable and the selection of files via Finder – which means that your list is empty, and Evernote is not processing anything at all. You have obfuscated the problem by wrapping the Evernote import command in a try block without any error processing, which means all errors just go unnoticed (to avoid this kind of problem, it is good practice to always log the error message in an on error clause, if nothing else).
Also, you don't actually need to select files on the Desktop via AppleScript to process them. The following code will grab all visible files (excluding pseudo-files like packages / apps):
tell application "System Events"
    set desktopFiles to every disk item of (desktop folder of user domain) whose visible is true and class is file
end tell

Pass the list you retrieved that way to Evernote for processing:
repeat with aFile in desktopFiles as list
    try
        tell application "Evernote" to create note from file (aFile as alias) notebook "Auto Import"
        tell application "System Events" to delete aFile
    on error errorMessage
        log errorMessage
    end try
end repeat

and you are good to go.
Note that by judiciously placing the deletion command (right after the import command, inside the try block, inside the loop over all files), you make sure it is only called if Evernote does not error on import while avoiding having to iterate over the files several times.
A final note: you don't have to use the block syntax for tell statements if there is only one command to execute – using tell <target> to <command> is easier and will keep you out of nested context hell.
Thanks @adayzone for corrections on list handling and alias coercion

A: Try
tell application "System Events" to set xxx to get every file of (desktop folder of user domain) whose visible is true

repeat with i from 1 to count of xxx
    set SelectedFile to item i of xxx as alias
    try
        tell application "Evernote" to create note from file SelectedFile notebook "Auto Import"
        tell application "Finder" to delete SelectedFile
    end try
end repeat

Thanks @fanaugen


text:
Q: Selectively emitting values by an accumulated value from an Observable I have an Observable of Foo's which contain a timestamp field. I want to group these objects into "chunks", and then select the object with the most recent timestamp.
A "chunk" is a group of Foo's that occur within a cutoff, in this example it would be 1-7 since these occur within 300 units of each other, and 8-10 likewise.
Here is a toy example:
import rx.lang.scala.Observable

case class Foo(id: Int, timestamp: Long)

val timestamp: Long = 1447118577892L
val cutOff: Long = 300L
val elements = List(
  Foo(1, timestamp),
  Foo(2, timestamp + 50),
  Foo(3, timestamp + 100),
  Foo(4, timestamp + 150),
  Foo(5, timestamp + 200),
  Foo(6, timestamp + 250),
  Foo(7, timestamp + 300),    // chunk 1
  Foo(8, timestamp + 500),
  Foo(9, timestamp + 550),
  Foo(10, timestamp + 600),   // chunk 2
  Foo(11, timestamp + 800))

val obs: Observable[Foo] = Observable.from(elements)

So I would expect a Foo's 7 and 10 to be produced from this observable. Naturally, I don't want to block when doing this.

A: Assuming I understood correctly, this is exactly what the debounce operator does:

Returns an Observable that mirrors the source Observable, except that
  it drops items emitted by the source Observable that are followed by
  another item within a computed debounce duration.

You can have it return the last Timestamp from the source observable after no timestamps were observed for a period of time (i.e. the most recent timestamp in each "chunk")


text:
Q: itext signing pdf I'm currently developing an ERP application which uses iText for creating and signing PDF files. The idea is that the app can generate a PDF file with a bill, then use PdfStamper or any other class to sign it with a digital signature. Here's my code:
CREATING AND EDITING THE BILL
File f1 = null;
f1 = new File("myFilePath");
f1.delete();
if ((f1 != null) && (f1.createNewFile()))
{
    //Here I call the procedure that creates the bill
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(f1));
    PdfFormField field = PdfFormField.createSignature(writer);

    PdfSigner pdfSigner = new PdfSigner();
    pdfSigner.setFileIn(f1.getAbsolutePath());
    pdfSigner.setFileKey("myKeyPath.pfx");
    pdfSigner.setFileKeyPassword("myPassword");
    pdfSigner.setFileOut("myOutputPath");

    if (pdfGenerator.factura(writer, pdfSigner, document))
    {
        //Here I show the File to the user
    }
}
else
{
    //Here I show an error
}

PROCEDURE "factura"
public boolean factura (PdfWriter writer, PdfSigner signer, Document document) throws NullPointerException
{
    try
    {
        //Here I set a PdfPageEvent before attaching it to the PdfWriter
        writer.setPageEvent(myPdfPageEvent);
        document.open();
        //Here I manipulate the Document to generate the bill
        signer.signPdf();
        document.close();
        return true;
    }
    //catch 4 or 5 different types of exceptions and return false if needed
}

CLASS PdfSigner
public class PdfSigner
{

private String fileKey = null;
private String fileKeyPassword = null;
private String fileIn = null;
private String fileOut = null;

public PdfSigner() {}

public boolean signPdf() throws IOException, DocumentException, Exception
{

    if (fileKey == null || fileKeyPassword == null || fileIn == null || fileOut == null) return false;

    try
    {
        KeyStore ks = KeyStore.getInstance("pkcs12");
        ks.load(new FileInputStream(fileKey), fileKeyPassword.toCharArray());
        String alias = (String) ks.aliases().nextElement();
        PrivateKey key = (PrivateKey) ks.getKey(alias, fileKeyPassword.toCharArray());
        Certificate[] chain = ks.getCertificateChain(alias);
        //BOOOOOM!
        PdfReader pdfReader = new PdfReader((new File(fileIn)).getAbsolutePath());
        FileOutputStream outputFile = new FileOutputStream(fileOut);
        PdfStamper pdfStamper = PdfStamper.createSignature(pdfReader, outputFile, '?');
        PdfSignatureAppearance sap = pdfStamper.getSignatureAppearance();
        sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED);
        sap.setVisibleSignature(new Rectangle(10, 10, 50, 30), 1, "sign_rbl");
        pdfStamper.close();
        return true;
    }
    catch (Exception key)
    {
        throw new Exception(key);
    }
}

//getters and setters

}

Well, this is wrong, but I don't know where does it fail. If I try to run it, it usually throw an exception in the line that I've marked with a "BOOOOM!", before setting the PdfReader. But if I try to sign it outside the procedure "factura", after closing the document, the exception is usually thrown almost in the last line, when I close the PdfStamper. In both cases, the cause is always the same: "PDF header signature not found."
Anyone has an idea of what's happening? I am 99% sure the paths I'm giving to the program are right, and the digital signature and password are also right...
Thanks
PS: I swear I've tried to find a solution among the multiple answers in this page, but none of them proved to be of any use to me


text:
Q: How to properly use flask @auth.login_required in multi-files project? My Flask API REST server is becoming larger and larger so I decided to split methods (urls) into different sub files.
My previous version (single file app) worked with verify_password() callback function to override standard method as in this example: https://github.com/miguelgrinberg/REST-auth/blob/master/api.py
Now, in my new multi file project, i need to make verify_password() function accessible from all @auth.login_required decorator in any single file but i cannot find a way to make it working.
How can I do?
Regards
    @auth.verify_password
    def verify_password(username, password):
        user = User.query.filter_by(username = username).first()
        if not user or not user.verify_password(password):
            return False
        g.user = user
        return True


text:
Q: Using sigaction, SIGKILL and an alarm handler to kill a forked process that takes longer than 3 seconds I'm writing a C program that pipes the output of a first program into the input of a second program. The program needs to terminate with the use of sigaction and SIGKILL if either program takes longer than 3 seconds to reach termination.
My program works on "good" inputs. I'm not sure how to implement it so that it behaves as it should for processes that exceed 3 seconds. This is my first time working with interprocess communication and I'm forced to use sigaction to facilitate it. I'm completely lost with the implementation of this part of the program.
I create two child processes: one for each program. How can I use system calls, sigaction, and SIGKILL to terminate the entire program if one of my child processes takes longer than 3 seconds to terminate?


text:
Q: Launcher activity instance restarts when widget configuration activity closes I have an activity A which can be used to configure a widget. But it can be also directly started from the launcher. The launcher instance gets restarted when a widget configuration instance is saved. I wonder why.
First I start the activity from the launcher. Then I press the Home button so that the activity is stopped.
Now I click on an widget on the home screen and the widget configuration activity instance starts. This is how I call it.
Intent intent = new Intent(context, A.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);

PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, intent,
PendingIntent.FLAG_UPDATE_CURRENT);

When leaving the widget configuration activity instance e.g. through a save button click the launcher activity instance gets restarted.
public void onClick(View v) {
        settings.save();

        // Signal that saving was performed and widget should be shown
        Intent resultValue = new Intent();
        resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
        setResult(RESULT_OK, resultValue);

        BreakWidgetProvider.updateWidgets(new int[] { appWidgetId }, this);

        this.finish();
    }

The activities should belong to different tasks. I wonder why they are related.
How can I prevent the restart of the launcher activity instance?

A: I solved it.
It seems the widget configuration activity instance got child of the the one started by the launcher. So I adjusted the manifest like below.
<activity
    android:name=".BreakMainActivity"
    android:label="@string/app_name"
    android:launchMode="standard"
    **android:allowTaskReparenting="false"**
    **android:noHistory="true"**
    android:theme="@android:style/Theme.Light" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

I suppose allowTaskReparenting="false" would have been enough.


text:
Q: Points in plane with every pair having at least two equidistant points? I was given this question in person by a fellow trainee at the downtime of an IMO training session, which made me think this problem is Olympiad related. I am interested in the solution as much as the origin!

$\textbf{Problem:}$Does there exist a non-empty finite set of points $P$ in $\mathbb{R}^2$ such that for each pair of points $x$, $y$ in $P$ there exists at least two distinct points $a$ and $b$ in $P$ such that both $a$ and $b$ are equidistant from $x$ and $y$.

To be honest, in over a decade and getting a degree in Mathematics, I have not made much headway into this problem. I tried to do some counting based on the number of pairs and pigeonhole to get the conclusion that there must be a point that is the circumcenter of a triangle made up of points in $P$. Assuming $P$ is a minimal solution (in terms of size of $P$) does not seem to help that much.
EDIT: originally the question left open whether it was in the plane or space, but the space case is trivial.
EDIT EDIT: added a note to say the set should be non-empty. Note that we do not need at least two points, because when we say "pairs of points" we don't say "distinct pair of points"!

A: Before I begin, a bit of philosophy on this problem:
I sincerely think there is no such set. I tried some onfigurations and I cannot seem to find one that works. So from now on, I will just talk about disproving the problem
This problem is clearly a geometric-combitoric style question. As far as I see, I don't think the geometric part of the problem is very important; I think only the simple notions of perpendicular bisectors and maybe polygons is enough. The important part is the combinatorical part and here are the main ideas that come in mind:

*

*extremal principle

*pigeonhole principle

*double countings of any useful thing (angles, triangles, edges etc.)

*considering a graph or the set of lines which pass through (at least) $2$ points or maybe the set of perpendicular bisectors of the set of segments

However, here is the big big issue:
We were never told that the points cannot be collinear or form parralel lines
As a bit of theory, we say that some points are in general position when no $3$ are collinear and no $2$ lines formed by points from our set are parralel. So we were never told that the set of points we are looking for is a general position! This means that we cannot use most of the ideas listed above as counterexamples are easy to find.
And yet is seems so easy.
I have tried myself various applications of the extremal principle and double countings but didnt actually manage to get a contradiction. However, I did manage to get a contradiction assuming that the points are in general position! So here is the solution:

Let $P$ be the set of points. Let $S$ be the set of lines that pass through exactly $2$ points of $P$. Observe that $|S|=\binom{n}{2}$ because the points are in general position.
Consider $S'$ the set of the perpendicular bisectors of the segments whose endpoints are in $P$. Because there are $\binom{n}{2}$ segments whose endpoints are in $P$ and the points are in general position, there are $\binom{n}{2}$ perpendicular bisectors, so $|S'|=\binom{n}{2}$.
BUT, for any segment $AB$ there are at least $2$ points $X,Y$ which both lie on the perpendicular bisector of the segment, thus every perpendicular bisector in $S'$ is actually one of the lines in $S$, so there exists an injection from $S'$ to $S$.
But we have shown that $|S|=|S'|$, so there must be a bijection from $S'$ to $S$, so every line that passes through $2$ points from $P$ is the perpendicular bisector of a segment whose endpoints are in $P$.
Take the convex hull of the points in $P$ and take any line formed by $2$ points on the convex hull. That line clearly cannot be the perpendicular bisector of a segment whose endpoints are in $P$
$\mathcal{Q.E.D}$

The fact that the points are in general position let us prove that there is an injection from $S'$ to $S$. If the points can actually be collinear or form parralel lines, then the above argument is false.

To conclude, there is no such set assuming the points are in general position. As for the general case, I am not sure. To be honest, the original statement might involve this detail, and Cryvate might have forgotten to add it, because in my experience, $99\%$ of geometric-combinatorical problems involve points in general position.

EDIT: $2$ people have pointed out in the comments that the question did not involve general position.
Yes, I know, I simply wanted to show a solution for the case in which the points are indeed in general position and highlight why the problem is much harder when they are not.
I discussed some approcahes and this was purely theoretical on te main issue, while providing the solution for the special case.
Moreover, as I said above, it is highly possible that if this was at an olympiad preparation camp, the original question actually involved general position. I am myself an olympiad student and for all I know, $99\%$ of these problems involve a general position, and when they don't they usually involve osmething else, like colorings or supplementary conditions.

A: A picture is worth a thousand words:

... but I will write a few words, nevertheless. This configuration has many symmetries and interesting properties, some of which I will describe here; however, I recommend trying to explore the configuration and figure them out on your own before reading further.
The eight points are arranged in two squares of different side lengths, with the same centre, and at a 45 degree angle from each other, the internal square coloured red and the external coloured blue. There are also eight equilateral triangles with vertices from the eight points: each side of the internal red square is completed to an outward-pointing equilateral red triangle, and each side of the external blue square is completed to an inward-pointing blue triangle.
All twelve red segments have equal lengths, as do all twelve blue segments. These equalities suffice to verify that any pair of points has a pair of two equidistant points. Up to symmetries, there are only six cases to check: two where both vertices are from the
blue square (adjacent or opposite); two where both vertices are from the red square (adjacent or opposite); and two where each vertex is from a different square (and the distance between the two vertices is either red or blue). The final two cases are the nicest and most interesting, and the latter of which is shown in the diagram, where the green perpendicular bisector of the two green points passes through a different pair of points, obtained from the first pair by a 90 degree rotation.

I do not know the origin of the problem, but I have encountered it before—on the xkcd forums (or "fora"), of all places, at least 10, maybe 15 years ago. I had recently recalled this problem and had presented it to some of our IMO students. My attempt to look up the original formulation and my original answer led me here. Sadly, the xkcd fora seem to have been offline since August 2019, and apparently they were not archived in full (or at least, I am unable to find such an archive), and thus some small pages in the history of this question might now be forever lost...

A: Let $P$ be the finite set of points above mentioned.
We have, by definition, that for every pair of points $x$ and $y$, there is another different pair $a$ and $b$ that are located in the line that passes through the midpoint of $x$ and $y$ and is perpendicular to the line segment $\overline{\rm xy}$ connecting such points.
Let $L$ be the set of all lines that can be constructed by passing through each pair of points in $P$ (this is a much bigger set, but still finite). Now consider the pair of lines $l_1,l_2\in L$ which present the smallest nonzero angle between them (there can be more than one, but it's enough to consider one pair). Then there is a pair of points $x_1\in l_1$ and $x_2\in l_2$ which doesn't satisfy the condition, i.e., there is no other pair $a,b$ equidistant from $x_1$ and $x_2$, which leads to a contradiction.
Note that if such pair $a,b$ existed, the condition "$l_1$ and $l_2$ having the smallest nonzero angle between them" would not hold, as the angle between $l_1$ or $l_2$ and the line perpendicular to the segment $\overline{\rm x_1x_2}$ (the line passing through $a$ and $b$) would be smaller.
Therefore, $P$ and $L$ must be both infinite sets.