text:
Q: UIButton isSelected by default I need to call the IBAction method as soon as the View Controller is loaded.
I have IBOutlet for Button and IBAction. How to call IBAction by default ?

A: @IBAction func buttonPressed(_ sender: UIButton) {
    // do something
}

Okay, what is called inside @IBAction is some code. Let's think about it. We can move this code somewhere else, right?
But where? Okay, it really depends on logic and architecture of your app, but for example, move it to another method.
func doSomething() {
    // do something
}

Do you see? Now we have code which was originally in action inside another method which we can call from @IBAction
@IBAction func buttonPressed(_ sender: UIButton) {
    doSomething()
}

as well as from another place from our class
override func viewDidLoad() {
    super.viewDidLoad()
    doSomething()
}

A: A view controller doesn't really have a specific button that would have "the IBAction method". You can have 0, 1, two, or a dozen buttons in a view controller. Thus there's no general way to call "the IBAction method" for a view controller when it's first loaded.
If you have a button method:
@IBAction func buttonMethod(_ sender: Any?)

Then you can just call that method from viewDidAppear:
override dynamic public func viewDidAppear(_ animated: Bool) {
      buttonMethod(nil)
      //The rest of your viewDidAppear method
   }
Note that viewDidAppear() gets called very time the view controller is re-shown, so if you cover it with a modal and then uncover it, viewDidAppear() will get called again. In contrast, viewDidLoad() only gets called once in the lifetime of a view controller.

A: You can call the IBAction method in viewDidLoad by using the IBOutlet button as sender.
class ViewController: UIViewController {
    @IBOutlet weak var submtButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        submtButtonAction(submtButton)
    }
    @IBAction func submtButtonAction(_ sender: Any) {

    }
}


text:
Q: Hashmap stuck on get I have a strange issue with HashMap.
There are multiple threads that accessing same hashmap (not threadsafe).
Sometime, the process gets stuck.
when I inspect the thread stack, i see many threads in state:
java.lang.Thread.State: RUNNABLE
    at java.util.HashMap.get(HashMap.java:303)

Note this happens very rare. And can't be reproduced on demand.
Why it gets stuck?
There is no synchronization on hashmap.
keys are strings

A:
There are multiple threads that accessing same hashmap (not threadsafe).

Sounds like you are using this HashMap in a threaded environment without proper synchronization.  You are hitting a problem where the HashMap memory is corrupted and a thread is most likely spinning because of this.  You cannot update an unsynchronized map and read from it using multiple threads.  In some situations you can build a read-only map and then share it without synchronization in multiple threads.
I would suggest switching to use ConcurrentHashMap instead or wrap your HashMap with Collections.synchronizedMap(...).
To elaborate more, the issue here is two fold.  You cannot have two threads updating an unsynchronized map because of race conditions when altering internal map data.  Locking is necessary to ensure mutex and proper data synchronization.  One thread might make changes not seen by the other thread which could overwrite them.
The other issue is memory synchronization.  If one thread updates the HashMap in its memory, other threads won't necessarily get the same view of the map's storage.  This isn't a problem until a thread gets partial memory update -- where some of the HashMap memory has been updated and other portions have not.  You might, for example, get a portion of the bucket array or a portion of the bucket storage which when traversed causes the thread to spin.
One of the main reasons multi-processor boxes run threaded code faster is that the threads can use per-processor cached memory.  The cached memory is the problem.  One processor could be reading or changing its cached memory at the same time another processor is doing the same.  Synchronizing local cached memory with central storage is one of things you need to worry about and the reasons why synchronization is so important.
If you are using a pre-populated HashMap that is only going to be read by your threads and never updated then it may be ok.  I depends highly on how each of the threads got the reference to the new HashMap.  If the HashMap was constructed and then populated and passed into the threads via their constructor (or before they were started) then you are good.  However if the threads are already running then it depends on how they get a reference to the map.  They may still get a partial copy of the map's memory depending on the circumstances and your memory architecture.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Restore history of divergent, then convergent repo I am working on restoring the history of a codebase. I have recovered commits lost at the root of my git repo, and have now discovered a new complication.
A large chunk of code was split into a separate codebase for a while... and then merged back in.
 Main repo:  A -- B -- C -- D -- E
                  |         ^
Code moved:       |         |
                  V         |
Other repo:       X -- Y -- Z

When the split (and merge) occurred, the files were simply copied into the target repo, and the history was lost.
To complicate matters further, the files were slightly modified on each copy before commit, so it's likely that I will need an extra commit for those changes.
This leads me to two questions:
Will it be possible to replace commit D (which copies the files back in) with the lower branch (X-Y-Z)? (This is my priority.)
If that's possible, will it be possible to restore the history of the files created at commit X as well?
There are around 300 commits on the "other" repo, and around 5000 on the "main" repo from D onwards.
I suspect git-rebase is probably required, but ideally, I would like to make use of git-filter-branch so that I do not have to manually resolve historical merge conflicts.

A: You may want to set up some git replace-ments to surgically alter / splice the history, without changing the contents of any existing commits.  Then do the filter-branch as we already discussed elsewhere, to cause these replacement grafts to become permanent.
Because git replace lets you substitute in one replacement object wherever Git would normally "see" the original, and because commits have parent commit IDs, you can replace a single commit with a chain of several commits.  For instance, if commit X is "bad" in some well-defined way:
...--o--P--X--Q--o--...

then we construct a new sequence of "good" commits G1 ... Gn:
...--o--P--X--Q--o--...
         \
          G1--G2--...--Gn

(where G1's parent commit ID is P, which is our bad X commit's parent; if X needs, or deserves, multiple parents, we can set all of those in good commit G1).  Then we instruct Git to "replace" X with Gn, so that traversal looks like this:
...--o--P--X- [replaced]  -Q--o--...
         \               /
          G1--G2--...--Gn

Once filtered, X vanishes entirely, with commits Q and later being copied to their new copies in the usual filter-branch fashion.
To construct the "good" commits, you can literally git checkout -b tempbranch <P> and then start making the commits, though if you need to set multiple parents this is a bit more tricky (you can use git commit-tree instead of plain git commit, or cheat by creating .git/MERGE_HEAD with the remaining extra hashes in it).  You may want to backdate the new "good" commits, and/or set arbitrary authors (git commit has command line switches for these, git commit-tree makes you use the magic env variables).


text:
Q: Get continuous RSSI values BLE I want to do BLE scanning in Android and here is my code -
try {
        if (Build.VERSION.SDK_INT < 21) {
            Log.d(TAG, "Starting BLE scan (SDK < 21)");
            bluetoothAdapter.startLeScan(this);
        }
        else {
            try {
                Log.d(TAG, "Starting BLE scan (SDK >= 21)");
                androidBleScanner.startScan(filters, settings, androidScannerCallback);
            } catch (NullPointerException e) {
                Log.w(TAG, "BLE scan for SDK >= 21 failed, using fallback to SDK < 21!");
                e.printStackTrace();
                bluetoothAdapter.startLeScan(this);
            }
        }

    } catch (NullPointerException e) {
        Log.e(TAG, "Fatal error trying to start BLE scanner!");
    }

The problem is it only does scanning once and gives me RSSI value once which I receive it in -
 @Override
    public void onLeScan(BluetoothDevice bluetoothDevice, int rssi, byte[] bytes) {
        //RSSI got only once
    }

How can I scan for 30 seconds and keep getting continuous RSSI values?


text:
Q: Bypass windows authentication when user is logged in IIS I have created an application in IIS 7.5. For security reasons i have disabled Anonymous authentication and enabled Windows Authentication. Now, is there a way to bypass the alert box to enter windows login credentials when accessing the page assuming that the user is already logged in?
My application is written in PHP.
Thank you in advance

A: If you are being prompted to enter your credentials after enabling windows auth, it means you haven't configured it correctly. I am assuming the user who is trying to access the application is part of the same domain as that of the server. There are multiple things that you need to take care of in order to configure windows auth (SPN's, application pool identity, etc). Few questions here -

*

*How do you access the web application? Do you use a custom hostname or you use the server name in the URL ?

*Is the client machine part of the same domain as that of the server?

*What identity is the application pool running under ?

*Is this a load balanced environment ?


text:
Q: how to put divider line between elements with text in the middle android? i'm trying to design my android application so i need to create a separator line with text in the middle.
i used this code XML to create the separator line:
   <View
    style="?android:attr/listSeparatorTextViewStyle"
    android:layout_width="fill_parent"
    android:layout_height="1dp"
    android:layout_below="@+id/login_button"
    android:layout_marginTop="20dp"
    android:background="@android:color/white"
/>

but i didn't figure out how to put the text in the middle.
like this : ------- Text ------- but a coherent line

A: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent"
    android:text="-----------------------------"
    android:textColor="#ffff00" />

<TextView
    android:id="@+id/but_book_now"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
   android:background="@android:color/transparent"
    android:text="This is button"
    android:textColor="#ffff00" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent"
    android:text="-----------------------------"
    android:textColor="#ffff00" />

A: For future references, here is a simple solution that resizes properly to the parent's width, and shows a continuous divider line.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="40dp">

    <View android:layout_width="match_parent"
          android:layout_height="1dp"
          android:layout_centerVertical="true"
          android:layout_marginStart="40dp"
          android:layout_marginEnd="8dp"
          android:layout_toStartOf="@id/sep_text"
          android:background="@android:color/black"/>

    <TextView android:id="@+id/sep_text"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_centerInParent="true"
              android:text="misc"/>

    <View android:layout_width="match_parent"
          android:layout_height="1dp"
          android:layout_centerVertical="true"
          android:layout_marginStart="8dp"
          android:layout_marginEnd="40dp"
          android:layout_toEndOf="@id/sep_text"
          android:background="@android:color/black"/>

</RelativeLayout>

The text can be accessed by the sep_text id.
The height has been fixed to 40dp but could be changed to wrap_content.


text:
Q: Median and mode Consider grouped data with frequencies and more specifically data that are discrete.
If I have for example different xi with the same frequencies, what is the right answer: there is no mode or all the modalities are modes?
Example value/ frequency , 0 / 42, 1 / 42, 2 / 42, 3 /42, 4 / 42, 5 / 42, 6 / 42, so what is the right answer no mode or multi modes??
For the median, some literature computes the median as the average of both xi between  $F<0.5$ and  $F>0.5$ OR gives the interval $[a,b]$. Others say that the median is the first xi having $F \ge 0.5$ because in the discrete case, the xi is an integer, so maybe the average did not give an integer.  Also the median is the middle value so why do we have to create a fictitious value (average)? to develop this point
a)To determine the median of a discrete statistical series: It stores values of the variable in ascending order. When the total number N is odd, the median is the value of the series of row (N+1/2) When the total number N is even, the median is the half sum of the ranks (N/2) and (N/2 +1)
it is clear point
b)To determine the statistical median of a discrete series where each value x   n is assigned frequencies, We can calculate the cumulative increasing numbers to exceed or equal to the half of the total N. (i want to verify this last point)
From the previous example
The average in the case even number and serie of data, it is clear that we compute the average of the both middle values, in the case of grouped data value/ frequency , 0 / 42, 1 / 42, 2 / 42, 3 /42, 4 / 42, 5 / 42, 6 / 42, the median is the average of the both modalities (2 and3) or the first modality having (Ni>=N/2(=126)) in the example it will be 'x= me=2 or 3 '(42+42+42=126) also let's suppose that  We get an no integer value (1.5 for example, it is logical to say we have mode 1.5 children??) that is why i prefer this definition "To determine the statistical median of a discrete series where each value x n is assigned frequencies, We can calculate the cumulative increasing numbers to exceed half of the total N. "

A: Your question raises small questions of terminology and more interesting questions of how to think about data. I will stick with your question and focus on discrete variables. Most of what I say carries over to continuous variables, but with some need for re-wording and/or some differences in procedures.
First off, the mode is usually introduced and defined as just the most common value, namely the value with the highest frequency. That is the strictest sense of the term mode. When data are discrete, we look at frequencies and identify the value with the highest frequency.
When there are ties for the highest frequency, then so also there are ties for mode. With these invented data
value       frequency
 0            1
 1           42
 2            1
 3            1
 4           42
 5            1
 6            1

there is clearly a tie, with two modes at 1 and 4. However, had the frequencies been 42 and 41 it's my guess that most experienced users of statistics would still say that there were two modes, regardless of the rule that the mode is the value with the highest frequency. So, it is also true that a mode is a value with a pronounced peak in a frequency distribution, i.e. with a frequency notably higher than neighbouring values. (It's possible and common for a mode to be either the minimum or the maximum.)
Don't ask for a precise rule, or even rule of thumb, on what counts as pronounced or notable; it's what is obvious when you graph it and the decision comes quickly with a little experience.
The importance and interest of modes often lies in what they indicate, which is sometimes that there are qualitatively different groups being mixed together in the sample, such as men and women or healthy and sick people. Sometimes there are physical reasons for having two modes. In some climates, there are two common states of cloudiness of the sky, almost cloud-free days and clouded-over days.
I've not seen the term modality being used except occasionally as meaning the number of modes. Statistical people certainly talk about bimodality, meaning that the data are bimodal, or have two modes; or multimodality, meaning that the data are multimodal, or have many modes. Some of these terms are a little unnecessary and arguably relict from a time when there was a stronger inclination among scholars and scientists to invent words based on Latin and Greek roots, but they are quite often used.
The second part of your question I read as asking whether the median should be computed as the average of two modes. I may be missing something here, but I guess you are mixing in a quite different question. The computation of medians  has nothing to do with modes at all. It's just the convention that with an even number of values, you should report the median as the mean of the two middle values. That's a convention, but it is taught in introductory statistics courses as a rule to be followed. With grouped data, the principle is still the same. It's quite possible with discrete data that interpolation will cause the median to be reported as a value that is not observable, e.g. 2.5 children. That's not something to worry about.
Back to terminology: I'd assert that modality is not another word for mode. Still less can it be used to refer to any value.
EDIT: I tried to pitch my original answer in a way that should help others apart from the OP. I focused on what seemed the more interesting question of a mode is, and downplayed a question about the median which seems confused on a point well covered in just about every elementary text. I've not tried to keep pace with repeated edits of the original question with more emphasis on how to compute medians.


text:
Q: Localization of $\mathbb Z/n\mathbb Z$ w.r.t. the set of all nonzero divisors
Let $R=\mathbb Z/n\mathbb Z$ and $S$ the set of all nonzero divisors of $R$. Then what is the localization $S^{-1}R$?

Help me plz.

A: Hint: show that in $R$, the non zero-divisors are precisely the units. What do you get if you localize a ring at the set of its units? (Use the universal property of localization.)

A: $$S^{-1}R=\left\{\;\frac ab\;\;;\;\;a\in R\;,\;\;b\in S\;\right\}$$
Remember that, by definition, we have
$$\text{For}\;\;\frac ab\,,\,\frac cd\in S^{-1}R\;,\;\;\frac ab=\frac cd\iff\exists\,s\in S\;s.t.\; (ad-bc)s=0\stackrel{\text{why?}}\iff ad-bc=0\;$$
Now work some examples with small $\;n\;$ to get a feeling of what you get each time...


text:
Q: Twitter Python program giving connection error I am working on a Twitter data mining application in Python, using the modules twitter and redis, based upon the book "Mining the Social Web" by Matthew A.Russell. Whenever I try to get the  information of friends and followers using the redis module, it gives me the following error:
raise ConnectionError(self._error_message(e))
ConnectionError: Error 10061 connecting localhost:6379. No connection could be made because the target machine actively refused it.

When I don't use Redis, I can get the ids of all friends and followers. But I require Redis to perform certain analysis stuff on the data. My source code is as follows:
import json
import locale
import redis
from prettytable import PrettyTable

# Pretty printing numbers
from twitter__util import pp

# These functions create consistent keys from
# screen names and user id values
from twitter__util import getRedisIdByScreenName
from twitter__util import getRedisIdByUserId

SCREEN_NAME = "timoreilly"

locale.setlocale(locale.LC_ALL, '')

def calculate():
    r = redis.Redis()  # Default connection settings on localhost

    follower_ids = list(r.smembers(getRedisIdByScreenName(SCREEN_NAME,
                        'follower_ids')))

    followers = r.mget([getRedisIdByUserId(follower_id, 'info.json')
                       for follower_id in follower_ids])
    followers = [json.loads(f) for f in followers if f is not None]

    freqs = {}
    for f in followers:
        cnt = f['followers_count']
        if not freqs.has_key(cnt):
            freqs[cnt] = []

        freqs[cnt].append({'screen_name': f['screen_name'], 'user_id': f['id']})

    # It could take a few minutes to calculate freqs, so store a snapshot for later use

    r.set(getRedisIdByScreenName(SCREEN_NAME, 'follower_freqs'),
          json.dumps(freqs))

    keys = freqs.keys()
    keys.sort()

    print 'The top 10 followers from the sample:'

    fields = ['Date', 'Count']
    pt = PrettyTable(fields=fields)
    [pt.set_field_align(f, 'l') for f in fields]

    for (user, freq) in reversed([(user['screen_name'], k) for k in keys[-10:]
                                    for user in freqs[k]]):
        pt.add_row([user, pp(freq)])

    pt.printt()

    all_freqs = [k for k in keys for user in freqs[k]]
    avg = reduce(lambda x, y: x + y, all_freqs) / len(all_freqs)

    print "\nThe average number of followers for %s's followers: %s" \
        % (SCREEN_NAME, pp(avg))

# psyco can only compile functions, so wrap code in a function

try:
    import psyco
    psyco.bind(calculate)
except ImportError, e:
    pass  # psyco not installed

calculate()

Any and all help would be really appreciated. Thanks!

A: That's the port that Redis runs on. If I were you, I'd double-check that the Redis server is running on the correct port and interface. To test that, ensure that you've a telnet client installed and do the following:
$ telnet localhost 6379

If that fails, then the Redis server isn't actually running where the Redis client library expects it to be by default, in which case, you'll have to provide the client with the correct details in the constructor arguments.


text:
Q: ArticleException error in web scraping news articles by python I am trying to web scrape news articles by certain keywords. I use Python 3. However, I am not able to get all the articles from the newspaper. After scraping some articles as output in the csv file I get ArticleException error. Could anyone help me with this? Ideally, I would like to solve the problem and download all the related articles from the newspaper website. Otherwise, it would also be useful to just skip the URL that shows error and continue from the next one. Thanks in advance for your help.
This is the code I am using:
import urllib.request
import newspaper
from newspaper import Article
import csv, os
from bs4 import BeautifulSoup
import urllib

req_keywords = ['coronavirus', 'covid-19']

newspaper_base_url = 'http://www.thedailystar.net'
category = 'country'

def checkif_kw_exist(list_one, list_two):
    common_kw = set(list_one) & set(list_two)
    if len(common_kw) == 0: return False, common_kw
    else: return True, common_kw

def get_article_info(url):
    a = Article(url)
    a.download()
    a.parse()
    a.nlp()
    success, checked_kws = checkif_kw_exist(req_keywords, a.text.split())
    if success:
        return [url, a.publish_date, a.title, a.text]
    else: return False

output_file = "J:/B/output.csv"
if not os.path.exists(output_file):
    open(output_file, 'w').close()

for index in range(1,50000,1):

    page_soup = BeautifulSoup( urllib.request.urlopen(page_url).read())

    primary_tag = page_soup.find_all("h4", attrs={"class": "pad-bottom-small"})

    for tag in primary_tag:

        url = tag.find("a")
        #print (url)
        url = newspaper_base_url + url.get('href')
        result = get_article_info(url)
        if result is not False:
            with open(output_file, 'a', encoding='utf-8') as f:
                writeFile = csv.writer(f)
                writeFile.writerow(result)
                f.close
        else:
            pass

This is the error I am getting:
---------------------------------------------------------------------------
ArticleException                          Traceback (most recent call last)
<ipython-input-1-991b432d3bd0> in <module>
     65         #print (url)
     66         url = newspaper_base_url + url.get('href')
---> 67         result = get_article_info(url)
     68         if result is not False:
     69             with open(output_file, 'a', encoding='utf-8') as f:

<ipython-input-1-991b432d3bd0> in get_article_info(url)
     28     a = Article(url)
     29     a.download()
---> 30     a.parse()
     31     a.nlp()
     32     success, checked_kws = checkif_kw_exist(req_keywords, a.text.split())

~\Anaconda3\lib\site-packages\newspaper\article.py in parse(self)
    189
    190     def parse(self):
--> 191         self.throw_if_not_downloaded_verbose()
    192
    193         self.doc = self.config.get_parser().fromstring(self.html)

~\Anaconda3\lib\site-packages\newspaper\article.py in throw_if_not_downloaded_verbose(self)
    530         elif self.download_state == ArticleDownloadState.FAILED_RESPONSE:
    531             raise ArticleException('Article `download()` failed with %s on URL %s' %
--> 532                   (self.download_exception_msg, self.url))
    533
    534     def throw_if_not_parsed_verbose(self):

ArticleException: Article `download()` failed with HTTPSConnectionPool(host='www.thedailystar.net', port=443): Read timed out. (read timeout=7) on URL http://www.thedailystar.net/ugc-asks-private-universities-stop-admissions-grades-without-test-for-coronavirus-pandemic-1890151

A: The quickest way to 'skip' failures related to the downloaded content is to use a try/except as follows:
def get_article_info(url):
  a = Article(url)
  try:
    a.download()
    a.parse()
    a.nlp()
    success, checked_kws = checkif_kw_exist(req_keywords, a.text.split())
    if success:
      return [url, a.publish_date, a.title, a.text]
    else: return False
  except:
    return False

Using an except to catch every possible exception, and ignore it, isn't recommended, and this answer would be downvoted if I didn't suggest that you deal with exceptions a little better. You did also ask about solving the issue. Without reading the documentation for libraries you import, you won't know what exceptions might occur, so printing out details of exceptions while you're skipping them will give you the details, like the ArticleException you are getting now. And you can start added individual except sections to deal with them for the ones you have already encountered:
def get_article_info(url):
  a = Article(url)
  try:
    a.download()
    a.parse()
    a.nlp()
    success, checked_kws = checkif_kw_exist(req_keywords, a.text.split())
    if success:
      return [url, a.publish_date, a.title, a.text]
    else:
      return False
   except ArticleException as ae:
     print (ae)
     return False
   except Exception as e:
     print(e)
     return False

The ArticleException you are getting is telling you that you are getting a timeout error, which means the response from the Daily Star hasn't completed within a time limit. Maybe it's very busy :) You could try downloading several times before giving up.


text:
Q: How to filter data for an attribute that is not part of the Datagrid object? I am trying to add a filter to my page but the column name I am trying to filter is not part of the object assigned to the Grid. It was dynamically added to the table results.
Given the object/model: Car
For example this:
filter(:status, :enum, select: ['Good', 'Bad']) works fine, as :status is an attribute of Car.
In the case of this filter(:name, :enum, select: ['A1', 'A5']) fails because :name is part of another object and not part of the Car object.
Of course this is just a sample object and adding :name is not an option for my real data model.
Query Error: Car.name Undefined column name.
Is there a way to filter a column of another object? I could not find anything in the documentation found here https://github.com/bogdan/datagrid/wiki
Thanks

A: I have managed to do it, I mean, placing a filter-field unrelated to the Datagrid object, as follows. For an example model Article), I place an arbitrary user field, max_per_page, to (pass it to a pagination module).
The key is :dummy => true option in the filter.
In the Grid definition:
 /app/grids/articles_grid.rb
class ArticlesGrid < BaseGrid
  scope do
    Article
  end
  filter(:max_per_page, :integer, dummy: true)  ## <= Key!!
  column(:content, mandatory: true)
end

In your model controller:
class ArticlesController < ApplicationController
  def index
    @grid = ArticlesGrid.new(grid_params) do |scope|
      maxval = grid_params[:max_per_page].to_i  ## <= How to fetch it.
      scope.page(params[:page]).per(maxval)
    end
  end

  private
    def grid_params
      params.fetch(:articles_grid, {}).permit!
    end
end

An example in the official doc includes the option, but there is no description, unfortunately……
Or, in the source code annotation Datagrid RDoc.


text:
Q: Can Google App Engine kill an instance which is waiting for an HTTP response? Can Google App Engine Auto Scaling kill an instance while it is waiting for a HTTP response from a server? Or is Auto Scaling intelligent enough to only kill an instance after the instance has done all of it's work?

A: The app engine scheduler won't kill an instance while the instance its serving or waiting for a response since it only kill idle instances. If the instance it's waiting for a response when the scheduler decides to kill the instance the scheduler will give 30 second of margin to complete, and new requests immediately return 404. You can see more detailed information in the App Engine How Instances are Managed documentation


text:
Q: What is the most efficient power source in Direwolf20 1.10.2 I was wondering about the best, most efficient power source that exist in the whole direwolf20 1.10.2 modpack. It does not matter how expensive it is, but what the best power source is.

A: For infinite power, near infinite expansion capabilities and relatively low level tech, I've used a Forestry mod tree farm in conjunction with a Railcraft steam boiler/steam engine configuration. Downsides include massive space requirements, but once you have a designated site the system can be easily upgraded with more boilers and a second tree farm if and when necessary.
Have the tree farm up and running, use piping to get the saplings back to the machine and separate the junk to somewhere else(if you're using trees that have fruit, this is an infinite food source as well), direct the wood to furnaces, and charcoal from the furnaces to a storage space between the furnace and the boiler. A 3*3 boiler will take A LOT of charcoal to get heated up, but once it gets to the maximum temperature, the consumption of coal plummets down. It's been a while since I've done this, but a full iron chest of charcoal probably isn't enough to fully warm up a single Boiler. Once it is at the optimal temperature, you can run three or four boilers off a single farm.
As long as the piping filters all items to their correct storage spaces and there's water to the boilers, this setup will provide infinite energy with no hands-on required.
From Thaumcraft, you can also look into some golem based solutions, though I'm not convinced the energy output will compete with the aforementioned steam boiler one.
This setup (one tree farm and 4 boilers) is/was sufficient to run a fully automated base that harvests materials off three different Mystcraft worlds with quarries that transmit all the materials back and that has a a fully automated crafting/ordering system via Applied Energetics and Industrycraft. It wasn't a Direwolf20 world, I believe we were running Techworld at the time, but the relevant mods are all the same.
Another, arguably more novel approach is to use bees. There are bees that produce oil. You can further refine the oil to gasoline and burn that for energy. Producing new strains of bees takes a long time and it took me roughly three weeks of active playing to acquire the correct bee lineages, but it's a fun one. You can further refine the bee lineages to ignore sunlight and flowers entirely, so this solution can be installed to wherever your base is. The initial workload is huge as you need to find several different bees to start the breeding, but as you get a few of the critical lineages purified and a stable supply of their workers, you can pretty much change any queen to any other strand within hours. This system is also much faster if you have the machines for genetic manipulation and you can simply extract the specific traits from the bees you wish to have on your super-bees.
The bee method also requires quite a large space to function, as you need to have a large supply of apiaries(20+ single block apiaries), then machinery to extract the oil, container for the oil, a refinery to turn the oil to gas, another container for the gas, and the generators themselves. But again, once the machinery is operational, the system is fully automatic.

A: I didn't see the boilers or turbines needed to use the railcraft steam power gen option in the DW20 1.10 pack.  Either they aren't in yet, or aren't coming over at all.
What I did for early power gen is ender io stirling generators and some actually additions coal generators. When I had the resources, I started up an ender io farming station for wood coupled with a rftools crafter to make cheap wooden axes feed back into it, Direwolf20 started out his current let's play series with a similar setup for tree farming.
I fed the wood from the tree farm into two actually additions double furnaces to turn into renewable charcoal, and fed those back into the stirling generators. Once I could start affording capacitor upgrades, I switched over to only ender io stirling generators, and built them up to 16 with octadic capacitors each putting out 80 rf/t.
That gave me enough infrastructure and resources to buid a 7x7x7 (chamber size) extreme reactor that produces about 11K rf/t on its most efficient settings, and have it set up to kick on if I start running out of power.
Whatever you decide to do with power, keep in mind when you get in the tens of thousands of rf/t, you're going to run into issues with power transmission and storage with just ender io conduits that max out at 20,480 rf/t and vibrant capacitors that each only hold 25 mil, but can be built up into multiblock capacitor banks. If you want to get into the ridiculous power options you can start into draconic evolution, but you'll have a tough time getting enough draconium to get very far into it, and you'll be sinking millions of rf into the neat stuff you can build with DE at that point as well.


text:
Q: WebPage loading on browser instead of Webview in Activity In my xml file I'm having text and below that text,I have placed a webview.
I am trying to open google's home page in Webview. Instead of opening in webview,webpage is opening on browser.What I want is web page should load in webview which is below some text.Below is my code:
           <TextView
                  android:id="@+id/txt"

                  android:text="Hello Android"
                  android:textSize="30sp"
                  android:textStyle="bold"
                  android:textColor="#003399"
                  android:layout_height="wrap_content"
                  android:layout_width="wrap_content"
                  android:layout_centerHorizontal="true"
                  />

      <WebView

                 android:id="@+id/webview"
                 android:layout_marginTop="50dp"
                 android:layout_below="@id/txt"
                 android:layout_height="fill_parent"
                 android:layout_width="fill_parent"/>

Kindly help to solve this.Thank you

A: This is because a combination of two things:

*

*the WebViewClient is not set (set to null), this makes the WebView try and offer every navigation as an intent to the system. Since you have a browser installed the system will try to handle that navigation there.

*going to google.com ususally results in a redirect, which is why the stuff about navigations in the previous point matters.

Try this:
webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new WebViewClient());

A: Create your activity and than use this code...

mWebview = (WebView) findViewById(R.id.webview);
            mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
      mWebview.setWebViewClient(new WebViewClient() {
          public void onReceivedError(WebView view, int errorCode,String description, String failingUrl) {
              Toast.makeText(youractivity_name.this, description, Toast.LENGTH_SHORT).show();
          }
      });

      mWebview.loadUrl("http://www.yahoo.com");


text:
Q: How to set the NODE_SKIP_PLATFORM_CHECK environment variable to 1 which skips the version check So earlier I was using node version v13.6 bascially because I am on windows 7 and node.js supports only windows 7 till v13.6 . So what I did was I downloaded the node.js latest version(v14.x.x) in '.zip' package and replaced all the files in the nodejs folder with the newer version file. I also know how to set environment variable but how can I set NODE_SKIP_PLATFORM_CHECK to 1 from the system properties in order to bypass the and run the latest version of node.jsenter image description here?

A: This work for me

*

*Go to System-Properties (run: systempropertiesadvanced.exe), in
Advanced tab, click Environment Variables.

*Still on the System variables, click 'New', add "NODE_PATH" with value "C:\nodejs64\node_modules", and click OK.

*click 'New' again, add "NODE_SKIP_PLATFORM_CHECK" with value "1", and click OK.

*Click OK of all dialogs close.

*Restart your machine, so explore and cmd will get the fresh set of variables.


text:
Q: Is this rotation matrix (angle about vector) limited to certain orientations? From a couple references (i.e., http://en.wikipedia.org/wiki/Rotation_matrix "Rotation matrix from axis and angle", and exercise 5.15 in "Computer Graphics - Principles and Practice" by Foley et al, 2nd edition in C), I've seen this definition of a rotation matrix (implemented below in Octave) that rotates points by a specified angle about a specified vector. Although I have used it before, I'm now seeing rotation problems that appear to be related to orientation. The problem is recreated in the following Octave code that

*

*takes two unit vectors: src (green in figures) and dst (red in figures),

*calculates the angle between them: theta,

*calculates the vector normal to both: pivot (blue in figures),

*and finally attempts to rotate src into dst by rotating it about vector pivot by angle theta.
% This test fails: rotated unit vector is not at expected location and is no longer normalized.
s = [-0.49647; -0.82397; -0.27311]
d = [ 0.43726; -0.85770; -0.27048]
test_rotation(s, d, 1);

% Determine rotation matrix that rotates the source and normal vectors to the x and z axes, respectively.
normal = cross(s, d);
normal /= norm(normal);
R = zeros(3,3);
R(1,:) = s;
R(2,:) = cross(normal, s);
R(3,:) = normal;
R

% After rotation of the source and destination vectors, this test passes.
s2 = R * s
d2 = R * d
test_rotation(s2, d2, 2);

function test_rotation(src, dst, iFig)
    norm_src = norm(src)
    norm_dst = norm(dst)

    % Determine rotation axis (i.e., normal to two vectors) and rotation angle.
    pivot = cross(src, dst);
    theta = asin(norm(pivot))
    theta_degrees = theta * 180 / pi
    pivot /= norm(pivot)

    % Initialize matrix to rotate by an angle theta about pivot vector.
    ct = cos(theta);
    st = sin(theta);
    omct = 1 - ct;

    M(1,1) = ct - pivot(1)*pivot(1)*omct;
    M(1,2) = pivot(1)*pivot(2)*omct - pivot(3)*st;
    M(1,3) = pivot(1)*pivot(3)*omct + pivot(2)*st;
    M(2,1) = pivot(1)*pivot(2)*omct + pivot(3)*st;
    M(2,2) = ct - pivot(2)*pivot(2)*omct;
    M(2,3) = pivot(2)*pivot(3)*omct - pivot(1)*st;
    M(3,1) = pivot(1)*pivot(3)*omct - pivot(2)*st;
    M(3,2) = pivot(2)*pivot(3)*omct + pivot(1)*st;
    M(3,3) = ct - pivot(3)*pivot(3)*omct;

    % Rotate src about pivot by angle theta ... and check the result.
    dst2 = M * src
    dot_dst_dst2 = dot(dst, dst2)
    if (dot_dst_dst2 >= 0.99999)
        "success"
    else
        "FAIL"
    end

    % Draw the vectors: green is source, red is destination, blue is normal.
    figure(iFig);
    x(1) = y(1) = z(1) = 0;
    ubounds = [-1.25 1.25 -1.25 1.25 -1.25 1.25];
    x(2)=src(1); y(2)=src(2); z(2)=src(3);
    plot3(x,y,z,'g-o');
    hold on
    x(2)=dst(1); y(2)=dst(2); z(2)=dst(3);
    plot3(x,y,z,'r-o');
    x(2)=pivot(1); y(2)=pivot(2); z(2)=pivot(3);
    plot3(x,y,z,'b-o');
    x(2)=dst2(1); y(2)=dst2(2); z(2)=dst2(3);
    plot3(x,y,z,'k.o');
    axis(ubounds, 'square');
    view(45,45);
    xlabel("xd");
    ylabel("yd");
    zlabel("zd");
    hold off
end

Here are the resulting figures. Figure 1 shows an orientation that doesn't work. Figure 2 shows an orientation that works: the same src and dst vectors but rotated into the first quadrant.

I was expecting the src vector to always rotate onto the dst vector, as shown in Figure 2 by the black circle covering the red circle, for all vector orientations. However Figure 1 shows an orientation where the src vector does not rotate onto the dst vector (i.e., the black circle is not on top of the red circle, and is not even on the unit sphere).
For what it's worth, the references that defined the rotation matrix did not mention orientation limitations, and I derived (in a few hours and a few pages) the rotation matrix equation and didn't spot any orientation limitations there. I'm hoping the problem is an implementation error on my part, but I haven't been able to find it yet in either of my implementations: C and Octave. Have you experienced orientation limitations when implementing this rotation matrix? If so, how did you work around them? I would prefer to avoid the extra translation into the first quadrant if it isn't necessary.
Thanks,
Greg

A: Seems two minus signs have escaped:
M(1,1) = ct - P(1)*P(1)*omct;
M(1,2) = P(1)*P(2)*omct - P(3)*st;
M(1,3) = P(1)*P(3)*omct + P(2)*st;

M(2,1) = P(1)*P(2)*omct + P(3)*st;
M(2,2) = ct + P(2)*P(2)*omct;      %% ERR HERE; THIS IS THE CORRECT SIGN
M(2,3) = P(2)*P(3)*omct - P(1)*st;

M(3,1) = P(1)*P(3)*omct - P(2)*st;
M(3,2) = P(2)*P(3)*omct + P(1)*st;
M(3,3) = ct + P(3)*P(3)*omct;      %% ERR HERE; THIS IS THE CORRECT SIGN

Here is a version that is much more compact, faster, and also based on Rodrigues' rotation formula:
function test

% first test: pass
s  = [-0.49647; -0.82397; -0.27311];
d  = [ 0.43726; -0.85770; -0.27048]
d2 = axis_angle_rotation(s, d)

% Determine rotation matrix that rotates the source and normal vectors to the x and z axes, respectively.
normal = cross(s, d);
normal = normal/norm(normal);

R(1,:) = s;
R(2,:) = cross(normal, s);
R(3,:) = normal;

% Second test: pass
s2 = R * s;
d2 = R * d
d3 = axis_angle_rotation(s2, d2)

end

function vec = axis_angle_rotation(vec, dst)

    % These following commands are just here for the function to act
    % the same as your original function. Eventually, the function is
    % probably best defined as
    %
    %     vec = axis_angle_rotation(vec, axs, angle)
    %
    % or even
    %
    %     vec = axis_angle_rotation(vec, axs)
    %
    % where the length of axs defines the angle.
    %
    axs = cross(vec, dst);
    theta = asin(norm(axs));

    % some preparations
    aa = axs.'*axs;
    ra = vec.'*axs;

    % location of circle centers
    c = ra.*axs./aa;

    % first coordinate axis on the circle's plane
    u = vec-c;

    % second coordinate axis on the circle's plane
    v = [axs(2)*vec(3)-axs(3)*vec(2)
         axs(3)*vec(1)-axs(1)*vec(3)
         axs(1)*vec(2)-axs(2)*vec(1)]./sqrt(aa);

    % the output vector
    vec = c + u*cos(theta) + v*sin(theta);

end


text:
Q: nanoScroller and IE9 I trying to use the nanoScroller JS script, and it works on Chrome and Firefox except in IE9. I don't know the problem, 'cause I've made a test in a teste page and it works, but in my project it doesn't work. Here it goes the script:
$(".lista-noticia").click(function () {
    $(".noticia-completa:visible").hide("slow");
    if ($(this).closest("li").find(".noticia-completa").is(':visible')) {
        $(".noticia-completa").hide("slow");
        $(".lista-noticia").removeClass("ativo");
    } else {
        $(this).closest("li").toggleClass("ativo").find(".noticia-completa").slideToggle(1200, function(){
           $(this).nanoScroller();
        });
        $(".lista-noticia").not(this).removeClass("ativo");
     }
});

and the HTML

Lorem ipsum dolor sit amet.....

Donec non egestas magna....

Donec non egestas magna....

Donec non egestas magna....

A: IE up to 9 accepts only 4095 style rules per file, maybe thats the problem.
see also:
Rails asset pipeline solution for IE 4096 selector/stylesheet limit


text:
Q: PDF.js HTA, promise being rejected I'm trying to develop an HTA for extracting and processing the data from PDF files for a number of people in a large office.  I've been looking into using the PDF.js package for this, but I've not been able to get it working.
I've forked the project and created an HTA version of the helloworld example with the compatibility.js file included. I can get an HTML version of this working on Firefox and IE11 through a gulp server, but the HTA doesn't give any output - no text, no error messages.
After peppering the source files with alert() statements, I've discovered that the original hello.js file is missing promise reject function, and that this fires when added, but here where my I meet the limits of my knowledge.  I don't really know an awful lot about promises, so I don't understand why this one fails.  Is this solvable or does it mean that the package simply won't run in an HTA?

EDIT:
I've been looking more into this and the failure doesn't make sense.
Tracing the logic through, the hello.js file calls the function api.getDocument from api.js.  Following this back, there is only one return statement and the alert statement just before this line is running. However the fulfilled function is not triggering.
From my very limited understanding, the failure clause on a promise will be triggered from a throw() statement within the asynchronous operation.  If that is the case then I would expect that operation to immediately cease and the reject function to trigger,  but why would the line immediately before the return statement still run?
I did pursue one theory that this line from api.js was the one throwing the error:
}).catch(task._capability.reject);

To check this, I added an alert statement to the reject() function statement in util.js, but it did not trigger, so I can't tell where the error is coming from.
Is anyone able to give me any additional pointers to help me trace this down?

A: Solved!
By changing the compatibility setting to IE10 instead of IE9 (which I didn't know I could do) I got a more useful error in the right place.  Looking more into this, this issue appears to be a duplicate of this one:
Access denied in IE 10 and 11 when ajax target is localhost


text:
Q: Why doesn't Perl's XML::LibXML module (specifically XPathContext) evaluate positions? I have an XML representation of a document that has the form:
<response>
  <paragraph>
    <sentence id="1">Hey</sentence>
    <sentence id="2">Hello</sentence>
  </paragraph>
</response>

I'm trying to use XML::LibXML to parse a document and get the position of the sentences.
my $root_node = XML::LibXML->load_xml( ... )->documentElement;
foreach my $sentence_node ( $root_node->findnodes('//sentence')->get_nodelist ){
  print $sentence_node->find( 'position()' );
}

The error I get is "XPath error : Invalid context position error".  I've read up on the docs and found this interesting tidbit

evaluating XPath function position() in the initial context raises an XPath error

My problem is that I have no idea what to do with this information.  What is the 'initial context'?  How do I make the engine automatically track the context position?

Re: @Dan
Appreciate the answer. I tried your example and it worked. In my code, I was assuming context to be the node represented by my perl variable. So, $sentence->find( 'position()' ) I wanted to be './position()'. Despite seeing a working example, I still can't do
foreach my $sentence ...
  my $id = $sentence->getAttribute('id');
  print $root_node->findvalue( '//sentence[@id=' . "$id]/position()");

I can, however, do
$root_node->findvalue( '//sentence[@id=' . "$id]/text()");

Can position() only be used to limit a query like you have?

A: position() does work in LibXML. For example see
my $root_node = $doc->documentElement;
foreach my $sentence_node ( $root_node->findnodes('//sentence[position()=2]')->get_nodelist ){
  print $sentence_node->textContent;
}

This will print Hello with your sample data.
But the way you're using it here, there's no context. For each sentence_node, you want its position relative to what?
If you're looking for specific nodes by position, use a selector like I have above, that's simplest.


text:
Q: How to get the median of a Binned Column Suppose that i have a data frame below:
df[['Age']]
    Age
1   22-24
2   40-44
3   55-59
4   40-44
5   22-24

How do i get a column with the median age just as below.
df[['MedianAge']]
    MedianAge
1   23
2   42.5
3   56.5
4   42.5
5   23

A: def f(x):
   ages = x.split('-')
   return (float(ages[1]) + float(ages[0])) / 2
df['MedianAge'] = df['Age'].apply(lambda x: f(x))


text:
Q: Find all points on a plane I am trying to get all points on a 2d plane in the range (0..10,0..10) with a step of 0.5. I would like two store these values in a dataframe like this:
  x   y
1 1   1.5
2 0   0.5
3 4   2.0

I am considering using a loop to start from 0.0 for the x column and fill the y column such that I get something like this:
  x   y
1 0   0
2 0   0.5
3 0   1

and so on upto 10. And increment it by 0.5 and do for 1 and so on. I would like to know a more efficient way of doing this in R?.

A: Is this what you want?
expand.grid(x=seq(0,10,by=0.5),y=seq(0,10,by=0.5))

      x   y
1   0.0 0.0
2   0.5 0.0
3   1.0 0.0
4   1.5 0.0
5   2.0 0.0
6   2.5 0.0
7   3.0 0.0
8   3.5 0.0
9   4.0 0.0
10  4.5 0.0
11  5.0 0.0
12  5.5 0.0
13  6.0 0.0
14  6.5 0.0
15  7.0 0.0
16  7.5 0.0
17  8.0 0.0
18  8.5 0.0
19  9.0 0.0
20  9.5 0.0
21 10.0 0.0
22  0.0 0.5
23  0.5 0.5
24  1.0 0.5
25  1.5 0.5
26  2.0 0.5
27  2.5 0.5
28  3.0 0.5
29  3.5 0.5
30  4.0 0.5
...


text:
Q: Track user location in Teams I am building a bot using Microsoft Bot Framework, I wanted to track the location of users location who is using the bot. Is this possible ?
I found one library Microsoft.Bot.Builder.Location which return the Maps when you enter the address.

A: *

*You can try with Microsoft Location control for Microsoft BOT Framework.

*I tested it and it works!!


text:
Q: Pdf signature invalidates existing signature in Acrobat Reader I'm using iText 7.1.15 and SignDeferred to apply signatures to pdf documents.
SignDeferred is required since the signature is created PKCS11 hardware token (usb key).
When i sign a "regular" pdf, e.g. created via word, i can apply multiple signatures and all signatures are shown as valid in the adobe acrobat reader.
If the pdf was created by combining multiple pdf documents with adobe DC, the first signature is valid but becomes invalid as soon as the seconds signature is applied.
Document in Adobe reader after the first signature is applied:

Document in Adobe reader after the second signature is applied:

The signatures of the same document are shown as valid in foxit reader.
I've found a similar issue on stackoverflow (multiple signatures invalidate first signature in iTextSharp pdf signing), but it was using iText 5 and i'm not sure it is the same problem.
Question: What can i do in order to keep both signatures valid in the Acrobat Reader?
Unsigned Pdf document on which the first signature becomes invalid:
https://github.com/suntsu42/iTextDemoInvalidSecondSignature/blob/master/test.pdf
Twice signed document which is invalid:
https://github.com/suntsu42/iTextDemoInvalidSecondSignature/blob/master/InvalidDocumentSignedTwice.pdf
Code used for signing
  //Step #1 >> prepare pdf for signing (Allocate space for the signature and calculate hash)
            using (MemoryStream input = new MemoryStream(pdfToSign))
            {
                using (var reader = new PdfReader(input))
                {
                    StampingProperties sp = new StampingProperties();
                    sp.UseAppendMode();

                    using (MemoryStream baos = new MemoryStream())
                    {
                        var signer = new PdfSigner(reader, baos, sp);

                        //Has to be NOT_CERTIFIED since otherwiese a pdf cannot be signed multiple times
                        signer.SetCertificationLevel(PdfSigner.NOT_CERTIFIED);

                        if (visualRepresentation != null)
                        {
                            try
                            {
                                PdfSignatureAppearance appearance = signer.GetSignatureAppearance();
                                base.SetPdfSignatureAppearance(appearance, visualRepresentation);
                            }
                            catch (Exception ex)
                            {
                                throw new Exception("Unable to set provided signature image", ex);
                            }
                        }

                        //Make the SignatureAttributeName unique
                        SignatureAttributeName = $"SignatureAttributeName_{DateTime.Now:yyyyMMddTHHmmss}";
                        signer.SetFieldName(SignatureAttributeName);
                        DigestCalcBlankSigner external = new DigestCalcBlankSigner(PdfName.Adobe_PPKLite, PdfName.Adbe_pkcs7_detached);

                        signer.SignExternalContainer(external, EstimateSize);
                        hash = external.GetDocBytesHash();
                        tmpPdf = baos.ToArray();
                    }
                }

                //Step #2 >> Create the signature based on the document hash
                // This is the part which accesses the HSM via PCKS11
                byte[] signature = null;
                if (LocalSigningCertificate == null)
                {
                    signature = CreatePKCS7SignatureViaPKCS11(hash, pin);
                }
                else
                {
                    signature = CreatePKCS7SignatureViaX509Certificate(hash);
                }

                //Step #3 >> Apply the signature to the document
                ReadySignatureSigner extSigContainer = new ReadySignatureSigner(signature);
                using (MemoryStream preparedPdfStream = new MemoryStream(tmpPdf))
                {
                    using (var pdfReader = new PdfReader(preparedPdfStream))
                    {
                        using (PdfDocument docToSign = new PdfDocument(pdfReader))
                        {
                            using (MemoryStream outStream = new MemoryStream())
                            {
                                PdfSigner.SignDeferred(docToSign, SignatureAttributeName, outStream, extSigContainer);
                                return outStream.ToArray();
                            }
                        }
                    }
                }

            }

Sample project
I've created a working sample project which uses a local certificate for signing. I also did update iText to version 7.2 but with the same result.
It also contains the document which cannot be signed twice (test.pdf)
https://github.com/suntsu42/iTextDemoInvalidSecondSignature/tree/master
Edit
I've applied the solution provided by MKL to the sample project on github.
As a second note, It is also possible to use PdfSigner but in this case, the bookmarks of the original document must be removed.

A: As already mentioned in a comment, the example document "InvalidDocumentSignedTwice.pdf" has the signature not applied in an incremental update, so here it is obvious that former signatures will break. But this is not the issue of the OP's example project. Thus, the issue is processed with an eye on the actual outputs of the example project.
Analyzing the Issue
When validating signed PDFs Adobe Acrobat executes two types of checks:

*

*It checks the signature itself and whether the revision of the PDF it covers is untouched.

*(If there are additions to the PDF after the revision covered by the signature:) It checks whether changes applied in incremental updates only consist of allowed changes.

The former check is pretty stable and standard but the second one is very whimsical and prone to incorrect negative validation results. Like in your case...
In case of your example document one can simply determine that the first check must positively validate the first signature: The file with only one (valid!) signature constitutes a byte-wise starting piece of the file with two signatures, so nothing can have been broken here.
Thus, the second type of check, the fickle type, must go wrong in the case at hand.
To find out what change one has to analyze the changes done during signing. A helpful fact is that doing the same using iText 5 does not produce the issue; thus, the change that triggered the check must be in what iText 7 does differently than iText 5 here. And the main difference in this context is that iText 7 has a more thorough tagging support than iText 5 and, therefore, also adds a reference to the new signature field to the document structure tree.
This by itself does not yet trigger the whimsical check, though, it only does so here because one outline element refers to the parent structure tree element of the change as its structure element (SE). Apparently Adobe Acrobat considers the change in the associated structure element as a change of the outline link and, therefore, as a (disallowed) change of the behavior of the document revision signed by the first signature.
So is this an iText error (adding entries to the structure tree) or an Adobe Acrobat error (complaining about the additions)? Well, in a tagged PDF (and your PDF has the corresponding Marked entry set to true) the content including annotations and form fields is expected to be tagged. Thus, addition of structure tree entries for the newly added signature field and its appearance not only should be allowed but actually recommended or even required! So this appears to be an error of Adobe Acrobat.
A Work-Around
Knowing that this appears to be an Adobe Acrobat bug is all well and good, but at the end of the day one might need a way now to sign such documents multiple times without current Adobe Acrobat calling that invalid.
It is possible to make iText believe there is no structure tree and no need to update a structure tree. This can be done by making the initialization of the document tag structure fail. For this we override the PdfDocument method TryInitTagStructure. As the iText PdfSigner creates its document object internally, we do this in an override of the PdfSigner method InitDocument.
I.e. instead of PdfSigner we use the class MySigner defined like this:
public class MySigner : PdfSigner
{
    public MySigner(PdfReader reader, Stream outputStream, StampingProperties properties) : base(reader, outputStream, properties)
    {
    }

    override protected PdfDocument InitDocument(PdfReader reader, PdfWriter writer, StampingProperties properties)
    {
        return new MyDocument(reader, writer, properties);
    }
}

public class MyDocument : PdfDocument
{
    public MyDocument(PdfReader reader, PdfWriter writer, StampingProperties properties) : base(reader, writer, properties)
    {

    }

    override protected void TryInitTagStructure(PdfDictionary str)
    {
        structTreeRoot = null;
        structParentIndex = -1;
    }
}

Using MySigner for signing documents iText won't add tagging anymore and so won't make Adobe Acrobat complain about new entries in the structure tree.
The Same Work-Around in Java
As I feel more comfortable working in Java, I analyzed this and tested the work-around in Java.
Here this can be put into a more closed form (maybe it also can for C#, I don't know), instead of initializing the signer like this
PdfSigner pdfSigner = new PdfSigner(pdfReader, os, new StampingProperties().useAppendMode());

we do it like this:
PdfSigner pdfSigner = new PdfSigner(pdfReader, os, new StampingProperties().useAppendMode()) {
    @Override
    protected PdfDocument initDocument(PdfReader reader, PdfWriter writer, StampingProperties properties) {
        return new PdfDocument(reader, writer, properties) {
            @Override
            protected void tryInitTagStructure(PdfDictionary str) {
                structTreeRoot = null;
                structParentIndex = -1;
            }
        };
    }
};

(MultipleSignaturesAndTagging test testSignTestManuelTwiceNoTag)
TL;DR
iText 7 adds a structure element for the new signature field to the document structure tree during signing. If the parent node of this new node is referenced as associated structure element of an outline element, though, Adobe Acrobat incorrectly considers this a disallowed change. As a work-around one can tweak iText signing to not add structure elements.

A: I've got a similar problem with signatures after last update of Adobe Reader. I wrote a post on their community, but they still didn't answer me.
Take a look:
https://community.adobe.com/t5/acrobat-reader-discussions/invalid-signatures-after-adobe-reader-update-2022-001-20085/td-p/12892048
I am using a iText v.5.5.5 to generate pdf. I sign and certify pdf document in single method. Moreover, foxit reader shows that signatures are valid. I believe that this is an Adobe bug and it will be fixed soon :)  Key are an log.


text:
Q: OData with ServiceStack? I just saw ServiceStack and I am considering building a service with it.
Is it possible to serve OData feeds with service stack so that I'd be able to expose IQueryable and query it from the client?

A: Edit
ServiceStack has now added Auto Query which is our approach to enabling data-driven services that avoids the pitfalls and anti-patterns promoted by OData.

Will ServiceStack support OData.

No.
Not directly anyway. If anyone sees any value in OData they are free to add the necessary functionality as an optional Plugin - but it will never be built into the ServiceStack core.
Poor development practices
OData is a poor fit for ServiceStack who vehemently opposes heavy abstractions and "magic behavior" which we view as a classic example of:

Every minute you save when your fancy framework does magical things to
  help you out costs future-you ten minutes of debugging. Not worth it.

We don't think relying on magic behavior from black-box blobs ever lasts the test of time. Historically whenever we've used this (e.g. ADO.NET DataSets, ASP.NET Dynamic Data) we've quickly run into the inherent in-flexible limitations of these frameworks which are in-capable of evolving to support new developer practices, paradigms and technologies they weren't designed to support, resulting in being quickly deprecated in favor of newer frameworks that can. This is a re-write cycle we don't wish to promote.
Promotes bad web service practices
OData also promotes the anti-pattern where you're exposing internal implementation details of your service tightly coupling your implicit service contract to the underlying RDBMS tables giving you limited control over the cachability, re-factoring or version-ability of your services in future.
This is akin to handing your db connection string where as soon as you have clients in production binding to it, the structure of the tables become frozen inhibiting the ability to evolve your existing DB tables since it could potentially break existing clients. ServiceStack's recommendation is having your clients binded to a well defined service layer that you are free to re-factor the implementation of.
To summarize OData does indeed provide rich functionality but I personally don't recommend its use outside the intranet where you don't control and can deploy both Client and Server.
WebApi is the best option with implicit support for oData via returning the IQueryable<T> interface.
Only used in Microsoft only technologies
One of the major benefits of web/remote services (and SOA in particular) is that it provides a technology-agnostic and interoperable facade over any functionality you wish to expose. Although OData is an open standard, the technology itself has essentially only been adopted by Microsoft and .NET related initiatives.
OData is slow
OData itself has found to be slow (which is contra to our core objectives) and the lack of control over the implementation makes it difficult to cleanly implement performance enhancing techniques like caching over it.
Concrete example
I've given a concrete example in the comments of why oData is a bad idea, at the end of the  IQueryable is Tight Coupling post which I'll repeat here for preservation:

The whole idea of web service interfaces is to expose a
  technology-agnostic interoperable API to the outside world.
Exposing an IQueryable/OData endpoint effectively couples your
  services to using OData indefinitely as you wont be able to feasibly
  determine what 'query space' existing clients are binded to, i.e. what
  existing queries/tables/views/properties you need to freeze/support
  indefinitely. This is an issue when exposing any implementation at the
  surface area of your API, as it limits your ability to add your own
  custom logic on it, e.g. Authorization, Caching, Monitoring,
  Rate-Limiting, etc. And because OData is really slow, you'll hit
  performance/scaling problems with it early. The lack of control over
  the endpoint, means you're effectively heading for a rewrite:
  https://coldie.net/?tag=servicestack
Lets see how feasible is would be to move off an oData provider
  implementation by looking at an existing query from Netflix's OData
  api:
http://odata.netflix.com/Catalog/Titles?$filter=Type%20eq%20'Movie'%20and%20(Rating%20eq%20'G'%20or%20Rating%20eq%20'PG-13')
This service is effectively now coupled to a Table/View called
  'Titles' with a column called 'Type'.
And how it would be naturally written if you weren't using OData:
http://api.netflix.com/movies?ratings=G,PG-13
Now if for whatever reason you need to replace the implementation of
  the existing service (e.g. a better technology platform has emerged,
  it runs too slow and you need to move this dataset over to a
  NoSQL/Full-TextIndexing-backed sln) how much effort would it take to
  replace the OData impl (which is effectively binded to an RDBMS schema
  and OData binary impl) to the more intuitive impl-agnostic query
  below? It's not impossible, but as it's prohibitively difficult to
  implement an OData API for a new technology, that rewriting + breaking
  existing clients would tend to be the preferred option.
Letting internal implementations dictate the external facing url
  structure is a sure way to break existing clients when things need to
  change. This is why you should expose your services behind Cool URIs,
  i.e. logical permanent urls (that are unimpeded by implementation)
  that do not change, as you generally don't want to limit the
  technology choices of your services.
It might be a good option if you want to deliver adhoc 'exploratory
  services' on it, but it's not something I'd ever want external clients
  binded to in a production system. And if I'm only going to limit its
  use to my local intranet what advantages does it have over just giving
  out a read-only connection string? which will allow others use with
  their favourite Sql Explorer, Reporting or any other tools that speaks
  SQL.

Update
Netflix has just retired its OData catalog, effective on April 8, 2013.
Added new answer on why we recommend using clean, well-defined untainted DTO's for defining any remote services with, which is a remote services best-practices that using OData doesn't promote.
Good article on why generic based APIs like OData are much more fragile, complex and harder to use than equivalent intent-based APIs.


text:
Q: Getting TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' when splitting class functions into multiple cells I am running a decision tree code in Jupyter Notebook and created a class called DTC. Within DTC has multiple functions. In Jupyter Notebook, I have split these class functions into multiple cell by calling class DTC(DTC): ... at the top of each function in the cell.
Most of the functions work except for one. Below is the code:
class DTC:
    def __init__(self):
        self.__root = None

...

class DTC(DTC):
    def __predict_what(self,data,node):
        if len(node.children) == 0 :
            return node.output
        val = data[node.data]
        if val not in node.children :
            return node.output

        return self.__predict_what(data,node.children[val])

class DTC(DTC):
    def prediction(self,X):
        Y = np.array([0 for i in range(len(X))])
        for i in range(len(X)):
            Y[i] = self.__predict_what(X[i],self.__root)
        return Y

The function prediction() is giving an error TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' when attempt to run. I have diagnosed and found that this is the line with the issue:
Y[i] = self.__predict_what(X[i],self.__root)

If I remove this, the prediction() function can return i. Either that if I remove Y[i] without [i], the function can run too.
To call this prediction() function, I pass in a 2D array of X - classification.prediction(test_data.values)
One weird thing is that the code works with no issue if I run the class and all its function in a single Jupyter Notebook cell.
Any idea why this occur and what is the fix? Thanks.

A: Each Cell is runn as separate statement operating on the same global enviromnet.
The first thing I would say is that what you are doing is horrible - making a class inherit a previous version of itself is not a good way to organise code. It just feels 'hacky'.
As you yourself said, the line giving the error is :
Y[i] = self.__predict_what(X[i],self.__root)

But in the code you have provided you never set self.__root;  It is only ever set to None in your first class statement.
which means when you call self.__predict_what - you are always calling :
Y[i] = self.__predict_what(X[i],None)


text:
Q: Why can I dynamic_cast to a non-virtual class? Why does this compile, if A has no virtual functions?

class A {
    int a = 42;
};

class B {

    void* f() {
        return dynamic_cast<A*>(this);
    }

    virtual void my_virtual() {};
};

Note: Though it makes no sense to write something like this, this was the result of a refactor, after the base class was removed. I feel like there should have been a compiler error.

A: Because it's not a requirement, and it shouldn't be an error.
Consider the following addition to your classes (after making B::f() public):
class C: public A, public B
{
};

int main()
{
    C c;
    void* p = c.f();
}

which should, and does, return to p a pointer to the A subobject of c.
Only the conversion source is required to be of polymorphic type, and that is only if it is not known at compile time that the target is a base class of the source.
In the latter case, a decent compiler will not do any conversion at runtime.


text:
Q: SQL Query and special chars I'm having a problem when I try to make a INSERT query with a value that has '>', '%' and other special chars on a SQL Server Database...
The application if of course a ASP Net Web application (C#)
The way I'm preparing the insert query is:
string Query1 =
    "UPDATE message SET message = '" + mymessage + "' " +
    "WHERE  operationType = '" + value_operationType + "' " +
    "AND    languageType = '" + value_languageType + "';";

Using IIS 7 I don't have this problem but using IIS 6 I have it.
Is there some configuration I should change on IIS 6?
Thanks!

A: Creating an SQL command like that can result in SQL injection - the correct approach is to use SQL parameters.
Have a look at:
C# Update Table using SqlCommand.Parameters ASP.NET

A: Just so you know, this is a dangerous way to run a query as someone can drop your entire database if they know how, and it will probably happen one day!
In answer to your original question, you can HTML encode the values:
string htmlEncodedMessage = Server.HtmlEncode(mymessage);

string Query1 =
    "UPDATE message SET message = '" + htmlEncodedMessage + "' " +
    "WHERE  operationType = '" + value_operationType + "' " +
    "AND    languageType = '" + value_languageType + "';";

I highly advise you look at other methods of database manipulation, such as LINQ to SQL.

A: Just to answer my question since a coleague was able to provide it, the solution was to add this single line on web.config:
<system.web>
   ...
   <httpRuntime requestValidationMode="2.0" />
   ...
</system.web>

Thanks


text:
Q: Microsoft and bpm This question is for people who follow Microsoft's BPM offering and WF. I was looking at their website http://www.microsoft.com/soa/ but much of the info seems to be from 2007 as if nothing new is happening after that. I know that IBM and others are more stronger in the whole SOA, ESB area but is it that microsoft not paying too much attention to this area? or is it the market is not interested as much as they are in Java based offerings from other vendors who have consulting arms?
Also what do you think about the success of WF?


text:
Q: ISL85403 buck-boost converter I have a requirement for a 24V +- 15% rail to power a laser sensor off of a 24V lead acid battery pack. I implemented the reference design provided by renesas for a 12V buck-boost converter(ISL85403EVAL2Z userguide) with input range of 8V-40V. The only thing that i had to change was the feedback resistors in order to drive higher output voltage. This is the design below. I have also pasted the link for the gerber and kicad files if anyone is interested in the design.

The issue i'm facing now is that the converter never enters boost mode. The condition for the converter to operate in boost mode according to the datasheet is that the EXT_BOOST voltage has to be between 200mV and 800mV. My choice of resistors R10 and R11 ensures that this voltage stays around 500mV. Also the output falls rapidly, almost instantaneously to ~1-2V as soon as i connect the load (laser sensor). I tested it by adding load resistors and with a load of 40 ohms the output falls down to 5V. The LGate pin has no activity at all when monitored on a scope. I use an old lecroy scope and wont be able to paste the output waveform here. I'm not experienced with power converter designing. My background is mostly robotics and mechatronics. If anyone could be kind enough to have a look at my design and point out the errors i'd be deeply grateful.
P.S. I have some extra pcb's for this design available. If anyone is interested in tinkering please let me know, i could have them shipped to you.
https://github.com/Tal-seven/isl85403_referenceDesign
Regards

A: The 1st problem is the high Ron resistance of Q1 = BS138 = 3.5 Ohms.
  This ought to be ~10 mOhm ~100 mOhm . The IC BOM list  BSZ100N06LS3G is 10mOhm is used in order to boost the voltage by sinking high current from the inductor then "flying back" that current into a boost voltage during off time.


text:
Q: Characterizing the set of first-order definable real functions I am trying to characterize the set of first-order definable functions $f: \Bbb R \to \Bbb R$ and see what properties they have.
It is immediately clear that these functions are not all analytic everywhere, since you have things like the absolute value function, the nearest integer function, the "give me the 10'th bit of the binary expansion of this real number" function, and so on. All of these above functions are instead piecewise-analytic functions.
Being piecewise-analytic is a fairly broad notion, but it still isn't everything: there are some important first-order definable functions such as the Weierstrass function, which are not piecewise-analytic. This is instead an infinite series of cosine functions, which are all analytic.
Similarly, the Cantor function is first-order definable, and expressed fairly easily as the limit of a sequence of piecewise-analytic functions (in particular piecewise-constant functions).
Both of these series/sequences are themselves first-order definable and converge pointwise. So far, every first-order definable function I have seen is of this form.
Is every first-order definable function of this form, i.e. the limit of some first-order definable sequence of analytic (or piecewise-analytic) functions that converges pointwise to it?
(To keep it simple I wrote the above in terms of total functions $\Bbb R \to \Bbb R$ but also interested in partial functions, e.g. $f(x) = 1/x$.)


text:
Q: How do I find the error details using the match function on Lua? I'm just asking a question on finding error details from the error function.
Like I would like to find error details from example.lua:50: "then" expected near "if".
Any ways on how to do that on Lua? I'm working on something for ComputerCraft on Lua. (Minecraft Java mod)
EDIT:
I'm trying make a function that returns the error parsed out. It's supposed to return 3 variables, var1: file name, var2: line number (if none it is specified nil), var3: error text.

A: example.lua is the file where the error is. 50 is the line number. There is a syntax error, likely in the if condition. (I'm not familiar with ComputerCraft, so I don't know where that file might be.)


text:
Q: how to redirect url on helicon I'm just getting into helicon , so forgive me if this is a basic question. my asp.net website contain bellow fixed urls.want to redirect this fixed url to my defined fixed  url.
Base URL=http://www.abc.ca/category/233/incontinence
Redirect URL=http://www.abc.ca/browse/652/free_wipes

In my asp.net website,I use helicon to redirect url ,I need help on helicon ISAPI_Rewrite configuration file,I need a rule that redirect  my rules.When only my base url appear I want helicon redirect this url to above Redirect URL page.
if have any query plz ask,thanks in advanced.

A: It seems like ISAPI_Rewritedocs is similar to mod_rewrite. Hence giving it a try.
Try this:
Options +FollowSymLinks -Indexes -MultiViews
RewriteEngine on
RewriteBase /

RewriteRule ^category/233/incontinence/? browse/652/free_wipes [NC,R=301,L]

A: Agree with ThinkingMonkey, but I'd apply the following in your site's .htaccess(as you need the 301-redirect, I assume):
RewriteEngine on
RewriteBase /

RewriteRule ^category/233/incontinence$ /browse/652/free_wipes [NC,R=301,L]


text:
Q: Extract all h6 tags from a TextArea using JavaScript Here is what I'm looking to do.
1: Have a jQuery WYSIWYG editor that allows users to enter text
2: Have a box that displays extracted text from the WYSIWYG editor that is only viewable. The extracted text should be bulleted. Each bullet item should be anything that is contained in an  tag in the WYSIWYG.
Example:
WYSIWYG editor would contain the following text:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas ut ipsum eget
enim porttitor pretium.
Ut eget purus.
 In nisi congue accumsan. Nulla
mattis nisl at dui porta non lacinia nulla condimentum.
Maecenas convallis
suscipit magna et venenatis.
 Phasellus a justo sed mauris hendrerit porttitor.

The view only box below would then show:
- Ut eget purus
- Maecenas convallis suscipit magna et venenatis
Thanks for the help!

A: Inspiration courtesy of Pekka:
var editorContents = $('
');          // Inject the stuff from the textbox
editorContents.html( $('#editor').val() ); // into the DOM.

// Adjust to taste -- this is where we're putting the info we extract.
var bulletList = $('
').class('whatever').appendTo('wherever');

// Now just find the headings and put their contents into bullet points.
$('h6', editorContents).each( function (i) {
  $('
').text( this.text() ).appendTo(bulletList);
} );

If you're doing this over and over, you're going to want to reuse bulletList, and you're going to want to either reuse editorContents, or else .remove() it each time you're done with it, to keep from leaking DOM objects all over the place :)
Oh, and you might want to use .html() instead of .text() for transferring the contents of the h6's into the li's. Up to you.

A: var text = 'foo
head1
 bar
head2
 waa';
var regex = /\
(.*?)\<\/h6\>/g;
var match = null;
while (match = regex.exec(text)) {
    alert(match[1]); // head1, head2.
}

Use on own risk, do not use regex to parse HTML!
Edit: d'oh, I missed the jQuery piece. Go ahead with the proposed jQuery solution, it is much better :)

A: In jQuery you may select them with
h6s = $('#wysiwyg h6');

A: You could create an invisible DIV, put the HTML into the innerHTML property and then query for h6's in the way that JQuery is so loved for. I don't speak JQuery but it should read something like $("h6") that, of course, requires that your HTML input is valid.


text:
Q: $\lim_{x\to 0} x^{\alpha}e^{|\log x|^{1/2}}=0$ Given any $\alpha > 0$, I need to show that for $ x \in [0,\infty)$
 \begin{equation}
     \lim_{x\to 0} x^{\alpha}e^{|\log x|^{1/2}}=0
\end{equation}
I have tried using L'Hospital's rule. But I am not able to arrive at answer.
Thank you in advance.

A: Let
$f(x)
=x^{a}e^{|\log x|^{1/2}}
$.
$\ln f(x)
=a\ln x+|\log x|^{1/2}
$.
Let
$x = 1/y$,
so
$y \to \infty$
as
$x \to 0$.
$\ln f(1/y)
=a\ln (1/y)+|\log (1/y)|^{1/2}
=-a\ln (y)+|\log y|^{1/2}
$.
The key is that
$\dfrac{|\log y|^{1/2}}{\ln(y)}
\to 0$
as $y \to \infty$.
Therefore
$\ln f(1/y)
=\ln (y)(-a +\dfrac{|\log y|^{1/2}}{\ln(y)})
$.
Since
$\dfrac{|\log y|^{1/2}}{\ln(y)}
\to 0$
as $y \to \infty$
and $a > 0$,
$-a +\dfrac{|\log y|^{1/2}}{\ln(y)}
\lt -a/2$
for large enough $y$
so that
$\ln f(1/y)
\to -\infty$
so
$f(1/y) \to 0$.
Note that this works
for any exponent
less than $1$,
not just
$\frac12$.

A: Let $$f(x) = x^{\alpha} e^{\sqrt{\vert \log x \vert}}$$
Consider
$$\log f(x) = \alpha \log x + \sqrt{\vert \log x \vert} = \log x (\alpha + \frac{ \sqrt{\vert \log x \vert}}{\log x} )=\log x (\alpha - \frac{ \sqrt{\vert \log x \vert}}{\sqrt{\vert \log x \vert}\sqrt{\vert \log x \vert}} )$$
which is
$$\log f(x) = \log x (\alpha - \frac{ 1}{\sqrt{\vert \log x \vert}} )$$
As $x$ goes to zero $\sqrt{\vert \log x \vert}$ goes to $+ \infty$ hence $\alpha - \frac{ 1}{\sqrt{\vert \log x \vert}}$ goes to $\alpha$. Hence
$$\lim_{x \rightarrow 0}\log f(x) =\lim_{x \rightarrow 0} \alpha \log x  = -\infty$$
So
$$\lim_{x \rightarrow 0} f(x)  = e^{-\infty} = 0$$

A: Let $x=e^{-y}\to 0$ as  $y\to \infty$ then
$$\large{x^{\alpha}e^{|\log x|^{1/2}}=e^{-\alpha y}\,e^{\sqrt y}=e^{\sqrt y\,-\,\alpha y}\to 0}$$
indeed
$$\sqrt y-\alpha y=y\left(\frac {\sqrt y}y -\alpha\right)=y\left(\frac 1 {\sqrt y}-\alpha\right) \to -\infty$$


text:
Q: How to force mysql.exe to run in "interactive" mode? I'd like to get emacs sql-mysql mode working in windows xp. I'm able to enter sql-mysql mode and connect to mysql database successfully. The problem is that the SQL buffer doesn't show the "mysql>" prompt. In other words, it's not interacting with mysql.exe.
I think it's because the mysql.exe program is going into "non-interactive" mode when it's started behind the scenes by emacs.
None of the mysql options seem to be of any help.
Any ideas about how to fix this? I can see this being a problem for emacs comint mode interacting with other command line utilities in windows as well, so maybe there's a os level solution?

A: The problem is that emacs' builtin terminal uses pipes to talk to the client process. Mysql.exe is a native Windows programs, hence isatty() actually checks whether the file descriptor/handle in question is a console. That fails on pipes, hence mysql enters batch mode. I can't see a way to force interactive mode either. Shame, as it would presumably be trivial to implement.
Running it in xterm or other terminal based on Cygwin ptys will show the same issue, because Cygwin's pty emulation is based on Windows pipes.

A: There is actually no way if you don't run it from a (pseudo)terminal. It checks file descriptors 0 1 by isatty and it sets batch mode if at least one of them is not a terminal. On the other side you can force batch mode.
Anyway this makes quite sense, because readline which is used for prompting needs a terminal to work reasonably. So the proper way to fix this is to run it in a pseudoterminal.


text:
Q: Regex to get youtube video ID from full  Had a look round but couldn't find a working (and recent) solution for this.
Using an API I am receiving a string like this:
<object width="600" height="338">
    <param name="movie" value="http://www.youtube.com/v/ItT88H3nAWw?version=3&feature=oembed"></param>
    <param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>
    <embed src="http://www.youtube.com/v/ItT88H3nAWw?version=3&feature=oembed" type="application/x-shockwave-flash" width="600" height="338" allowscriptaccess="always" allowfullscreen="true"></embed>
</object>

What would be a regular expression in PHP to extract just the video id? e.g. ItT88H3nAWw

A: Get src param from embed tag WITHOUT regexp. Then parse it in following way:
$youtubeUrl = 'http://www.youtube.com/v/ItT88H3nAWw?version=3&feature=oembed';

if ( preg_match('youtube\.\w+.*?v[/=](\w+)', $youtubeUrl, $matches) ) {
  $youtubeId = $matches[1];
}

This regexp will handle both:

*

*http://www.youtube.com/v/ItT88H3nAWw

*http://www.youtube.com/watch?v=ItT88H3nAWw
To convert HTML string to an object use SimpleXMLElement.
$obj = new SimpleXMLElement($htmlCode);
$youtubeUrl = $obj->embed->src;

A: Regexp is ugly. Use something like: getBetween('www.youtube.com/v/', '?version')
Ok, here another version. Assuming $s is your string and youtube does not change it's ID length:
$p = strpos($s, 'youtube.com/v/') + count('youtube.com/v/');
$id = substr($s, $p, count('ItT88H3nAWw') );


text:
Q: One-to-one, Compact, Preimages, Continuous. Recall that the set $\mathbb{Q}$ of rational numbers is countable; thus we can put them all in a sequence ({ i.e.}~we can enumerate them).  Let $(r_n)$ be such a sequence and let $f(x)=\begin{cases} \frac{1}{n} &\text{ if } x=r_n\in \mathbb{Q}\\ 0 &\text{ if }x\notin \mathbb{Q}\end{cases}$.\
(1) Is this function injective (one-to-one)?  Why or why not?
(2) Is $f(\mathbb{R})$ (the image/range of $f$) compact?  Justify your answer.
(3) Which of the following preimages are countable: $f^{-1}(\{1/2\})$, $f^{-1}([0,1/2])$, $f^{-1}([1/2,1])$?  Justify your answers.
(4) Prove that $f$ is continuous at every $x\in \mathbb{R}-\mathbb{Q}$ and discontinuous at every $x\in \mathbb{Q}$.
Response: I haven't got any work to show for any of them.

A: For $(1)$ we have that since $f(e)=f(\pi)$, but $e \neq \pi$ we have that $f$ is not one-to-one.
For $(2)$, we have that since $f(\mathbb{R}) \subset [0,1]$ and by the Heine-Borel Theorem $[0,1]$ is compact (clearly, closed intervals are closed and bounded) we have that $f(\mathbb{R})$ is compact.
For $(3)$, we have that $f^{-1}(\{1/2\})=x \in \mathbb{Q}$ so clearly $f^{-1}(\{1/2\})$ is countable since it is equal to a single value. We have that $f^{-1}([0,1/2])$ is uncountable since there are uncountably many irrationals in $\mathbb{R}$. We also have that $f^{-1}([1/2,1])$ is countable since $\mathbb{Q}$ is countable.
For $(4)$, Clearly, f is discontinuous at all rational numbers: since the irrationals are dense in the reals, for any rational x, no matter what ε we select, there is an irrational a even nearer to our x where f(a) = 0 (while f(x) is positive). In other words, f can never get "close" and "stay close" to any positive number because its domain is dense with zeroes.
To show continuity at the irrationals, assume without loss of generality that our ε is rational (for any irrational ε, we can choose a smaller rational ε and the proof is transitive). Since ε is rational, it can be expressed in lowest terms as a/b. We want to show that f(x) is continuous when x is irrational.
Note that f takes a maximum value of 1 at each whole integer, so we may limit our examination to the space between $\lfloor x \rfloor$ and $\lceil x \rceil$. Since ε has a finite denominator of b, the only values for which f may return a value greater than ε are those with a reduced denominator no larger than b. There exist only a finite number of values between two integers with denominator no larger than b, so these can be exhaustively listed. Setting δ to be smaller than the nearest distance from x to one of these values guarantees every value within δ of x has f(x) < ε.


text:
Q: Understanding the Cartesian product is the set of functions According Wikipedia, "if a tuple is defined as a function on ${1, 2, ..., n}$ that takes its value at $i$ to be the $i$th element of the tuple, then the Cartesian product $X_1×...×X_n$ is the set of functions
${\displaystyle \{x:\{1,\ldots ,n\}\to X_{1}\cup \ldots \cup X_{n}\ |\ x(i)\in X_{i}\ {\text{for every}}\ i\in \{1,\ldots ,n\}\}.}$"
For me, it is hard to understand the above definition. Could you give some example to illustrate the concept?
For example, let $X_1 = \{1,2\},X_2=\{a,b\}$. Then, $X_1×X_2= \{?\}$.
Thank you in advance.

A: We are looking for functions $f:\{1,2\}\to\{1,2,a,b\}$ such $f(1)\in X_1=\{1,2\}$ and $f(2)\in X_2=\{a,b\}$.
There are $4$ such functions and writing each function as a set of ordered pairs they are:

*

*$f_{1,a}:=\{\langle 1,1\rangle,\langle 2,a\rangle\}$

*$f_{1,b}:=\{\langle 1,1\rangle,\langle 2,b\rangle\}$

*$f_{2,a}:=\{\langle 1,2\rangle,\langle 2,a\rangle\}$

*$f_{2,b}:=\{\langle 1,2\rangle,\langle 2,b\rangle\}$

Then according to the mentioned definition:$$X_1\times X_2=\{f_{1,a},f_{1,b},f_{2,a},f_{2,b}\}=$$$$\{\{\langle 1,1\rangle,\langle 2,a\rangle\},\{\langle 1,1\rangle,\langle 2,b\rangle\},\{\langle 1,2\rangle,\langle 2,a\rangle\},\{\langle 1,2\rangle,\langle 2,b\rangle\}\}$$
We can go even further by writing order pair $\langle r,s\rangle$ as $\{\{r\},\{r,s\}\}$ according to the definition of Kuratowski, but I don't think that that will increase your understanding.
Note that we get back the "familiar" definition of $X_1\times X_2$ just by replacing $f_{1,a},f_{1,b},f_{2,a},f_{2,b}$ by $\langle 1,a\rangle,\langle 1,b\rangle,\langle 2,a\rangle,\langle 2,b\rangle$ respectively.

A: In terms of the definition you've quoted, in your example $X_1\times X_2$ is the set of all functions $x$ from $\{\,1,2\,\}$ to $\{\,1,2,a,b\,\}$ such that $x(1)$ is in $\{\,1,2\,\}$ and $x(2)$ is in $\{\,a,b,\,\}$. There are four such functions, which I'll call $x_1,x_2,x_3,x_4$, given by
$x_1(1)=1,x_1(2)=a$
$x_2(1)=1,x_2(2)=b$
$x_3(1)=2,x_3(2)=a$
$x_4(1)=2,x_4(2)=b$


text:
Q: Question about drawing and replacing a pack of cards A card is drawn and replaced in an ordinary pack of 52 playing cards. Minimum number of times must a card be drawn so that there is at least an even chance of drawing a heart?
What does the second sentence of the question mean?
Why should there be any change in the chance of drawing a heart, as the cards are being "replaced" (kept back into the pack after drawing)?

A: The question asks you to find the number of draws such that
$$P(\text{at least one heart has been drawn})\geq \frac{1}{2}.$$
In such cases (when "at least" is at play), it is often useful to look at the probability of the negation ("no hearts are drawn"), i.e.,
$$P(\text{at least one heart has been drawn})=1-P(\text{no hearts have been drawn}).$$
The latter follows a geometric distribution. Try solving it now; if it is still causing you trouble, let me know and I'll come back to you sometime tomorrow.

A: For one draw, we have a chance $\frac{1}{4}$ of drawing a heart.
For $n$ cards, the chance we don't draw any hearts at all is $(\frac{3}{4})^n$ as we need (independent, as we put cards back) events of not drawing a heart.
So the complementary probability $1-(\frac{3}{4})^n$ computes the probability of drawing at least a heart, which is what was asked.
So for what $n$ (number of draws) does this become $\ge \frac{1}{2}$?
Solve for $n$ using logarithms, say.


text:
Q: What is the difference between a PUT and a normal transistor? What is the difference between a Programmable Unijunction Transistor and a normal transistor? I am reading the book Make:Electronics and it says I need one of those. Can somebody explain to me in somewhat non-tech terms what it is?

A: As far as I know these are completely different beasts (and a simple google search agrees).
The built-in negative resistance of the unijunction transistors is what makes them attractive (or maybe "cute" is a better word) in "simple" oscillators but IMHO you will be better off building a 3xRC (\$180^\circ\$ phase shift network) oscillator on one normal bipolar transistor or a simple oscillator on an op amp. Almost nobody uses negative resistance devices nowadays.
Negative resistance is fairly common in nature (a humble spark gap has this property) so this may be the reason why historically they were used for intro level oscillators. But there also were times when people notoriously made their own rectifying diodes out of some kind of rock and a piece of wire so they could build a long-wave radio receiver, so... :P

A: According to Wikipedia:

Unijunction transistor circuits were popular in hobbyist electronics circuits in the 1960s and 1970s because they allowed simple oscillators to be built using just one active device. … Later, as integrated circuits became more popular, oscillators such as the 555 timer IC became more commonly used.

The 555 Timer is probably the easiest way to build an oscillator, programmable or not. It can be bought at Radio Shack, or anywhere chips are sold. Instructions can be found in Wikipedia, various datasheets published by its many manufacturers, or hobbyist websites. It's old as rocks. Calculate the waveform and frequency you want and smooth with a resistor + capacitor if necessary.
I remember when I was a 10-year-old electronic hobbyist and Mac programmer. I guess some things don't change! Have tons of fun.


text:
Q: What's wrong with my python solution to Project Euler #12? Possible Spoiler Warning
I've spent ages trying to improve this algorithm and work out what's going wrong, but I can't seem to work out why the outputted answer is incorrect.
I'm trying to solve Project Euler #12, to get the lowest triangular number to have over 500 divisors, but it says my answer is incorrect.
Here is my Python code:
import time

# function to get the number of divisors
def div(n):
    d=2
    for i in range(2,int(n**.5)+2):
        if (n % i) == 0:
            d += 1
    return d

start = time.time()

w = True
n=m=1
while w:
    n += 1
    s = (n*(n+1))/2 # nth triangle number
    r = div(s)
    if r > m:
        m = r
        print s,"has",r,"divisors"
        if r > 500:
            w = False

print "Solved in",((time.time()-start)*1000),"milliseconds"

And the output for that code is this (in 66 seconds):
3 has 2 divisors
6 has 4 divisors
36 has 6 divisors
120 has 9 divisors

...
76576500 has 289 divisors
103672800 has 325 divisors
236215980 has 385 divisors
842161320 has 513 divisors
Solved in 65505.5799484 milliseconds

However, if I input 842161320 into the Project Euler problem, it says it's incorrect.
What am I doing wrong?

A: I see two bugs:

*

*Your div function is broken: div(24) == 5, while it should be 8

*Your 1st triangular number would be 3, although it should be 1
You could implement a working div like this:
import math
def divisors(n):
  return sum(1 for x in range(1, n+1) if n % x == 0)

Also, that code is inefficient as hell, some suggestions to improve it are:
Instead of calculating the nth triangular number using your formula, use a rolling sum:
import itertools

s = 0
for i in itertools.count(1):
  s += i
  if div(s) > 500:
    print s
    break

Also, Use prime factors to calculate the number of divisors. You can create a prime factor cache for maximum performance.

A: You are undercounting the total number of divisors. 36, for example, has 9 divisors: 1,2,3,4,6,9,12,18,36. It's true the algorithm only needs to test numbers smaller than sqrt(n) to find all divisors, but you still need to include the implied "large" divisors in your count.

A: Solved
With the help of Niklas, and changing my div method, I've got the answer. Also, it's now only takes 8% of the time my previous algorithm took.
The algorithm now looks like this:
import time
import itertools

def div(n):
    d=0
    for i in range(1,int(n**.5)+1):
        if (n % i) == 0:
            d += 1
    return 2*d

start = time.time()

s = m = 0
for i in itertools.count(1):
    s += i
    r = div(s)
    if r > m:
        m = r
        print s,"has",r,"factors"
        if div(s) > 500:
            break

print "Solved in",((time.time()-start)*1000),"milliseconds"