text:
Q: Eclipse:GWT connect to MYSQL:error:the driver has not received any packets from the server I'm using GWT to connect to MYSQL.
But I every time I got the error as follows:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
I have putthe driver files to the war\WEB-INF\lib. And the driver has been load.
For a normal JAVA project I can use the same code to find file in MYSQL.
But why can't use the same code in GWT project?
public class GreetingServiceImpl extends RemoteServiceServlet implements
        GreetingService {
public String greetServer(String input) throws IllegalArgumentException {
                            Connection conn = null;
                    String url ="jdbc:mysql://localhost:3306/pcmorder";
            String driver = "com.mysql.jdbc.Driver";
            String user     = "root";
            String pass     = "123456";

            //String query = "SELECT id FROM tb_user WHERE username = ";
            String sql=null ;
            String[] namelist;
            int name1=0 ;

            try {
                Class.forName(driver).newInstance();
                System.out.println("OK");
                conn = DriverManager.getConnection(url, user, pass);


text:
Q: How to convert from unicode escape sequence to UTF-8 How can i convert unicode escape sequence to UTF-8.
The sequence are \uXXXX
Is there a functionality in POCO for it?

A: Not directly, only through JSON Parser.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dart: how do I initialize a class such that one of its properties is filled upon initialization via a function that returns a future? I have a file called database.dart. In it, I have a string property called currentUsername. This is the currently logged in user's username. I want this class to call the getUsernameFS() function only once and then be able to reuse this string for the rest of the class's existence inside its other functions. How do I accomplish this?
The code below gives an error: Error: A value of type 'Future<String>' can't be assigned to a variable of type 'String'.
class Database {

  late String currentUsername = getUsernameFS(); //ERROR IS HERE

  Future<String> getUsernameFS() async {...}

  String someFunction() {...//some function that uses currentUsername//...}

}

A: A direct (and perhaps naive) approach would be to add an asynchronous initialization step to initialize an instance of your class:
class Database {
  late String currentUsername;

  Future<void> initialize() async {
    currentUsername = await getUsernameFS();
  }
}

However, that's potentially error-prone since it creates more work for callers, and callers could accidentally neglect to call (or neglect to wait for) initialize, and there's no way to enforce that at compile-time.
Instead, I'd recommend a couple of other options:

*

*Make your member variable a Future instead:
late Future<String> currentUsername = getUsernameFS();

This has the advantage of safely avoiding accidental errors from callers who neglect to explicitly call an asynchronous initialization method first.  However, this has the disadvantage of forcing all callers to await the result, making them also asynchronous.

*If possible, make your class constructor private and force callers to obtain instances with an asynchronous, factory-like static method:
class Database {
  late String currentUsername;

  Database._();

  static Future<Database> create() async {
    var db = Database._();
    db.currentUsername = await db.getUsernameFS();
    return db;
  }

  ...
}

This also has the advantage of safely avoiding accidental errors, and it avoids forcing all consumers of currentUsername to be asynchronous.  A disadvantage is that a private constructor would prevent your class from being extended.
If possible, I'd also make getUsernameFS a static method and pass the username to the private constructor.  Then currentUsername wouldn't need to be late, and you would avoid any risk of accidentally using a late variable before it's initialized.


text:
Q: How to itearate over grep context groups in bash Grep, with the capture context option (-C), produces a text file with the captured groups separated by '--'. How can I loop over the whole groups in bash? Not just the lines, but the whole groups complete with \n characters. I'd like to loop over the groups and process them by another grep command.
Using a test file so.txt:
line 1
word
line 3
line 4
line 5
word ...other text
phrase ...yet another text
line 6
line 7

the following grep:
grep -C 1 "word" so.txt

produces:
line 1
word
line 3
--
line 5
word ...other text
phrase ...yet another text

A sketch of what I'm trying to use it for:
function searchGroup {
    grep1=$(grep "word" -A 1 "$1")
    if grep "phrase" "$grep1"; then
        echo "$1"
    fi
}

grep "word" -C 1 so.txt | {
    group=""
    while IFS= read -r line; do
         if [[ "$line" == "--" ]]; then
              searchGroup "$group"
              group=""
          else
              group+="$line"$'\n'
          fi
    done
    if [[ -n "$group" ]]; then
         searchGroup "$group"
    fi
}

A:
How can I loop over the whole groups in bash?

You may read line by line up until the -- line and then parse....:
.... | {
group=""
while IFS= read -r line; do
     if [[ "$line" == "--" ]]; then
          echo "group is $group"
          group=""
      else
          group+="$line"$'\n'
      fi
done
if [[ -n "$group" ]]; then
    echo "and the last group is $group"
fi
}

But usually it's simpler is to replace the magic -- sequence by a unique single byte, preferably by a zero byte, and then read it up until that byte, with bash extension and GNU sed:
... | sed 's/^--$/\x00/' |
while IFS= read -r -d '' group || [[ -n "$group" ]]; do
     echo "group is $group"
done

A: A single awk can handle this easily by grouping before/after lines along with matched line in one single string:
awk -v C=1 -v w='word' -v kw='phrase' '$0 ~ w {
   s = p ORS $0
   if (getline > 0)
      s = s ORS $0
   if (s ~ kw)
      printf "%s\n", s
}
{
   p = $0
}' so.txt

line 5
word ...other text
phrase ...yet another text


text:
Q: Multiple Input AJAX Post Hi there,
I'm working on a project, but I'm a bit stuck. It's a logical question. I'll explain: We have a list of articles - Table: articles - saved in the database. However, we have collapse-able elements (let's call them accordeons now), which are based on the enabled languages (Table: languages). Now I'm tasked with saving every input for every "Accordeon" in the database, where content for the accordeons is stored in "article_language".
The accordeon
(It's contained in a WHILE-loop)

        <div class="accordeon-head" data-id="<?php echo $language['shortname']; ?>"><?php echo $language['fullname']; ?>

        <div class="accordeon-body" data-id="<?php echo $language['shortname']; ?>">

                        <?php echo $lang['ARTS_INPL_TXT']; ?>
                        <textarea type="text" id="agg_e_txt" name="agg_e_txt"><?php echo $text['article_text']; ?></textarea>

                        <?php echo $lang['ARTS_INPL_RECUSE']; ?>
                        <textarea type="text" id="agg_e_rec" name="agg_e_rec"><?php echo $text['article_recuse']; ?></textarea>

                        <?php echo $lang['ARTS_INPL_SPEC']; ?>
                        <textarea type="text" id="agg_e_spec" name="agg_e_spec"><?php echo $text['article_spec']; ?></textarea>

I'd like to do this with an AJAX post. What is the best way to store everything for an accordeon in the article_language table with the correct language prefix?
My thoughts were a WHILE loop in the AJAX call, or a each in the jQuery. But, I'm not sure.
What is the best way to achieve this?


text:
Q: Why do we have to use IS NULL instead of = NULL? I don't know if this is the case for all database implementations but it is for SQL Server and MySQL which are the two I've worked with.
I've read articles about the topic and the manuals of SQL Server and MySQL and the reasoning always boils down to semantics around the meaning of the word NULL and how it represents an unknown and therefore nothing can be equal to NULL.
What I'd like to do here though is set aside semantics, legacy code considerations and existing developer expectations and see if there are any practical arguments against allowing = NULL. So what I mean is, if we were starting with a clean slate, had no legacy considerations, why would we not want to allow = NULL?
In my 20 years of dev experience I've never encountered a situation in which IS NULL has been anything but an annoyance, an extra condition that I have to handle separately from everything else.
So can someone give me an explanation of why the following examples shouldn't work as a naive, new dev might expect them to?
SELECT * FROM MyTable WHERE myField = NULL
SELECT * FROM MyTable WHERE myField <> NULL
SELECT * FROM MyTable WHERE myField IN (1, 2, 3, NULL)
What is the danger/problem here with collapsing IS into =? If these admittedly trivial examples would be fine but there are other examples where it would be a problem, feel free to bring those up.
I've never gotten a satisfactory answer to this and every time I'm writing a query and this comes up it gnaws at me.
The question is meant to be general and not tied to a specific implementation.

A: The question is when is a comparison NULL safe
It depends on

ANSI convention that NULL is an unknown value and cannot be compared with any other value, including other NULLs.

See for mysql https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html
And here for sql server https://learn.microsoft.com/en-us/sql/t-sql/language-elements/equals-transact-sql?view=sql-server-ver15
IS NULL is NULL safe and will always get the correct answer on most Databases, independent of sql modes


text:
Q: genus-zero Gromov-Witten invariants Let $(M, \omega)$ be a complex $n$-dimensional  Hermitian symmetric space of compact type, where $\omega$ is the symplectic (Kaehler) form on $M$ normalized so that $[\omega]$ generates  the integral cohomology class $H^2(M, Z)$. Let $A$ be the generator of $H_2(M, Z)$.
Problem: Find  two submanifolds $X$ and $Y$ of $M$ such that:
$$\dim_{\R} X+\dim_{\R} Y=4n-2c_1(TM)(A)$$
and
$$\Phi_A([X], [Y], [p])\neq 0,$$
where $\Phi_A([X], [Y], [p])$ is the genus-zero Gromov--Witten invariant of the triple $[p], [X], [Y]$ and $[p]$, $[X]$ and $[Y]$ denote   the homology classes of  a point $p\in M$,  $X$ and $Y$ respectively.)

A: I will just consider the simplest example, maybe someone will give the answer in complete generality.
So let $M=\mathbb CP^n$. Then $4n-2c_1(M)(A)=2n-2$. This means that we are in good shape. Basically we can take for $X$ and $Y$ any complex submanifolds of $M$ satisfying your condition. Indeed in this case for a generic point $p$ in $\mathbb CP^n$ there will be $deg X\cdot deg Y$ lines that contain $p$ and intersect both $X$ and $Y$. I assumed  $X$ (or $Y$) is not zero dimensional, in which case there is only one line and also that $X$ and $Y$ are in general position, but this does not matter for GW, of course.


text:
Q: Can I still use yarn or npm to install a package in an Expo app's node_modules? I created an Expo project because I thought it would be easier to the person I'm teaching to code in React Native. But my instinct is to just use yarn or npm. Am I damaging project structure in any way?

A: https://docs.expo.dev/workflow/using-libraries/#using-expo-sdk-libraries

The expo install command will pick a version of the library that is compatible with your project and then use your JavaScript package manager (such as npm) to install it.


text:
Q: Number of $4$-letter "words'' that can be constructed with the $12$-letter Hawaiian alphabet The Hawaiian alphabet consists of $12$ letters, the vowels a, e, i, o, u and the consonants h, k, l, m, n, p, w.
Show that $20,736$ different $4$-letter ''words'' could be constructed using the $12$-letter Hawaiian alphabet.
My answer: Isn't it $12 \cdot 11 \cdot 10 \cdot 9= 11880$?

A: No, because you don't need 4 different letters in the word.  The answer is $(12)^4,$ since each letter has 12 possibilities.

A: The other commentator is correct but I feel there can be a better explanation. The fundamental counting principle is as follows: $$\prod_{i=1} ^{n} c_i $$
Where $c_i$ is the number of choices at i. Since in this case we allow any random sequence of characters, $c_i$ will be 12 at all 4 (n) points in the word. Hence the answer, $12^4$ or 20,736.


text:
Q: How to upgrade a module already distributed with Drupal Commerce? Drupal Commerce 1 has included Crumbs 1.10.
I need to upgrade Crumbs to 2.7, and this version isn't included with Drupal Commerce.
How can I upgrade it without breaking Drupal Commerce distribution (and update) ?
Thanks.

A: Composer Package Management:
If you are using Composer to manage the installed modules/distributions for your Drupal 7 site, you can set the minimum version constraint and then run composer update for the Crumbs module:
composer require 'drupal/crumbs:^2.7'
composer update 'drupal/crumbs'

Traditional/Legacy code repositories:
For traditional/legacy code repositories that don't use composer, you can:

*

*Backup your database/codebase

*Download the desired version of the module

*replace the older version of the module (typically found in your codebase's /profiles/contrib/commerce/modules/ directory or /modules/contrib/ directory).

*Deploy the updated module code.

*Run update.php or drush updatedb.

*Clear caches.

In the case that the Drupal Commerce profile has a fixed version dependency for Crumbs 1.10, you should be able to update the version constraint in the .info file for the module.

A: You can use drush command as follow to update a specific version of module.
$ drush pm-update views_send-7.x-1.x-dev

Thanks


text:
Q: button click event from java script not working in IE 9 this is my javascript code :
document.getElementById("<%= btnUpload.ClientID %>").click();

This code is working perfectly in all other browsers except IE 9. what could be the possibility ?

A: Maybe you could use .on()
document.getElementById("<%= btnUpload.ClientID %>").on('click',function () {});
});
this is JQuery, but I'm assuming you are using it. If not you can use OnClick function from Javascript.


text:
Q: Posting a python dictionary as an entered field on a form I am writing an application which will allow users to set up python scripts to run at set intervals. I am using APSCheduler combined with SQLAlchemy as a data source and Flask for my web UI.
I have a screen with the following markup for setting up jobs:
<form method="POST">
    <input type="text" name="JobDesc">
    <input type="text" name="function">
    <input type="text" name="args">
    <input type="text" name="kwargs">
    <select name="trigger">
        <option value="interval" selected>Interval</option> <!--Adding other job types later-->
    </select>
    <input type="number" name="minutes">
    <select name="coalesce">
        <option value=1>True</option>
        <option value=0 selected>False</option>
    </select>
    <input type="submit">
</form>

This forms "submit" button triggers the below script, to add the record to the database
@app.route('/addjob', methods=['GET', 'POST'])
def JobConfig():
    if flask.request.method == 'POST':

        if flask.request.form['args'] == '': # '' == None returns False. :(
            args = None
        else:
            args = flask.request.form['args']

        if flask.request.form['kwargs'] == '':
            kwargs = None
        else:
            print(flask.request.form['kwargs'])
            kwargs = flask.request.form['kwargs']

        scheduler.add_job(
            trigger=str(flask.request.form['trigger']),
            func=str(flask.request.form['function']),
            minutes=int(flask.request.form['minutes']),
            coalesce=bool(flask.request.form['coalesce']),
            args=args,
            kwargs=kwargs,
            name=str(flask.request.form['JobDesc']),
        )

        return 'Success', 201
    elif flask.request.method == 'GET':
        return flask.render_template('JobEntry.html')
    else:
        return flask.abort(400)

APScheduler has a number of key fields:

*

*Function: Details of the function to be scheduled (for example: JOBS.TestJob:Test runs the Test function in the the Testjob.py file in the JOBS folder).

*args: List of functions to supply to the function.

*kwargs: Dictionary of functions to supply to the function.

Unfortunately, while the entry screen works fine when args and kwargs are blank, if you try to entry any arguments I get an error. For example, if I the Test function is expecting an argument "Abbrev" and I enter {"Abbrev":"Test1"} into the kwargs field:
File "C:\Python34\lib\site-packages\apscheduler\schedulers\base.py", line 334, in add_job
'kwargs': dict(kwargs) if kwargs is not None else {},
ValueError: dictionary update sequence element #0 has length 1; 2 is required

Would anyone be able to point me in the right direction? I'm not sure if this is an error in my python of if I need to use something other than vanilla HTTP POST requests (JSON?) to send the data.

A: This would indeed work better with JSON input. As the error implies, you need to give a dict as the "kwargs" argument and a tuple or list as the "args" argument. Alternatively you can parse the kwargs into a dict yourself, however you wish.


text:
Q: FTPS on IIS 8.5 Error on Command: LIST I'm trying to configure FTP over SSL on my server. I added an FTP site in IIS and followed the wizard, setting the bindings and certificate. However when I try to connect to the server using FileZilla the connection gets refused by the server. I also noticed that no welcome message appears. I also noticed that the server sends a reply with an unroutable address. I don't really know how to proceed from here as the setup seems OK for me.
Log:
Status: Resolving address of jensgm.com
Status: Connecting to 213.153.1.168:990...
Status: Connection established, initializing TLS...
Status: Verifying certificate...
Status: TLS connection established, waiting for welcome message...
Status: Connected
Status: Retrieving directory listing...
Status: Server sent passive reply with unroutable address. Using server address instead.
Command:    LIST
Response:   150 Opening BINARY mode data connection.
Error:  The data connection could not be established: ECONNREFUSED - Connection refused by server
Error:  Connection timed out after 20 seconds of inactivity
Error:  Failed to retrieve directory listing

Log file says:
'long time stanp' JENSGM\jensgm 192.168.1.2 21 LIST - 550 1236 15 1cf4a073-6f69-481f-8083-4ec4debfc810 /

'long time stanp' JENSGM\jensgm 192.168.1.2 21 ControlChannelClosed - - 1236 0 1cf4a073-6f69-481f-8083-4ec4debfc810 -

A: It seems you are using Passive mode.
Passive mode uses TCP ports from 1024 to 65534 for Data channel.
Make sure no Firewall is blocking this port range.
Else, switch to active mode to only use TCP/20 for Data channel.
EDIT :
Also, FTPS can operate in two distinct mode : implicit or explicit.

*

*Explicit will use standards ports (for Active mode) : TCP/21 & TCP/20

*Implicit will use TCP/990 for command and TCP/989 for Data channel

http://en.wikipedia.org/wiki/FTPS


text:
Q: Why zero-initialization is not a static Initialization In this topic they said that zero initialization is not static initialization.
Can anyone explain why?
3.6.2/2 said:

Together, zero-initialization and constant initialization are called
  static initialization;

It is definition of Static initialization, means that zero-initialization is static initialization and constant-initialization is static Initialization

A: This answer assumes that you know what  static storage duration means.
In C++03 this is specified as (3.6.2):

Objects with static storage duration (3.7.1) shall be zero-initialized
  (8.5) before any other initialization takes place. Zero-initialization
  and initialization with a constant expression are collectively called
  static initialization; all other initialization is dynamic
  initialization.

In practice, a program has different memory segments where it stores variables with static storage duration:

*

*One segment is usually called .bss, where all static storage variables that are initialized to zero are stored.

*Another segment is usually called .data, where all static storage variables that are explicitly initialized to a value are stored.

*And further, there is a segment called .rodata where all const variables are stored.

(The reason why these are two different segments is mainly program startup performance, you can read more about that here.)
Zero initialization applies to all variables stored in .bss and constant initialization applies to all variables stored in .data. (And perhaps constant initialization applies to .rodata as well, depending on whether your system is RAM-based or if it has true ROM).
Collectively, all of this is called static initialization, since it applies to objects with static storage duration.

A: You forgot to notify the word "Together", very important in this sentence.
Zero-initialization + constant initialization = static initialization. Is that clearer ?

A: It's just vocabulary.  There are clearly three phases of
initialization (for variables with static lifetime): zero
initialization, initialization using constant expressions, and
dynamic initialization.  I find it convenient when talking about
this to use the term static initialization for the second step
(because it does take place statically, without the execution of
any user written code), even if the standard uses a somewhat
different terminology.  In the end, it comes down to the same
thing:
int a;
int b = 42;
int c = someFunction();

Formally, all three variables will be zero-initialized.  Then
b will be initialized with the constant expression 42; in
all likelyhood, it will never actually be zero-initialized,
because there's no way your code can ever see it before the
constant initialization.  Finally, c will be initialized by
calling someFunction().
This order is true regardless of the order of the definitions,
and is guaranteed by the standard.

A: The post you link to says that zero-initialization is not static initialization. This is correct.
That is very different from zero-initialization is not a static initialization! This is not correct.


text:
Q: Interesting Console Program for C++ beginners I'm teaching an entry-level C++ programming class. We only use iostream in the class (No GUI). It seems like students are not so excited to printout strings and numbers to their console. (Most students even never used the console before.) It is hard to motivate or convey the excitement of programming by showing strings in their console.
What would be a good and exciting console program that can be written by C++ beginners? I'm looking for something doable with basic C++ skill + a bit challenging + very exciting, which can motivate students to learn programming languages.
Any comments will be appreciated.

A: When I taught an undergrad intro course, we did the Game of Fifteen in straight C as the third homework project. It's pretty well scoped, and it's a game, so there's some inherent motivation there.

A: Back when I taught, I made an early project be an ATM machine.
Text-only interface, with basic operations like withdraw, deposit, query balance, transfer between accounts, etc.
It was something that everyone was already familiar with, it didn't take huge amounts of programming time, but it did help students feel like it was a practical and realistic program.
Other similar ideas would be a cash-register (handle refunds, coupons, items priced by the pound, sales-tax, store specials, etc, etc), or a cell-phone billing program (separate daytime, night, and weekend minutes, bill text messages, picture messages separately, etc).

A: How about a system that generates a set of poker hands from a deck? While clearly defined, the intricacies of ensuring no duplicate cards etc, make it a good entry level challenge.
As an extension, you could have the system take an input as to whether you want to bet or fold, and effectively play a poker game.
Finally, a good design would allow them to switch the console for a gui front-end later on (e.g. intermediate class).

A: I always enjoyed problems where there's a real world purpose for doing it. Something like calculating a mathematical equation, or a range of prime numbers. A lot of stuff on ProjectEuler would be good, I would think. Not everybody likes math (but then again, it's kind of a necessary thing for computer science!).

A: Instead of just printing to the screen you could make ascii animations.

A: Introduce your students to pipes and filters. Create a useful utility that takes data from stdin and directs its output to stdout. Create another utility that does something else using that same protocol. Create a third utility. Demonstrate how robustly the utilities can work together.
For example, create a clone of the GNU head and tee utilities, and perhaps add a new utility called cap which capitalizes letters. Then demonstrate how you can get the first 3 lines of a text file capitalized and tee'd to a file and stdout. Next, demonstrate how you use the same utilities, without changing a single line of code, to take the first 5 lines of a file and output to the screen the capitalized letters and to a file the original letters.

A: When I took C++ we had to replicate a Theseus and the Minotaur game. It lends well to outputting multiple lines to the console to form something "graphical" and it's easily based on a set of implemented rules.

A: I've had to program a Tower of Hanoi game in the console before, I found that quite fun. It requires use of basic data structures, user input, checking for game end conditions so it would be good for a beginner I believe.

A: New programming students usually find graphical programs to be the most exciting.
It doesn't have to be anything really advanced, just being able to manipulate pixels and stuff should be enough to keep them interested. Making a simple graphic class around SDL should be ok. Maybe something like this:
int main()
{
   GraphicWindow graphic;
   graphic.setPixel(10,20,GraphicWindow::Red);
   graphic.idle();
}

Then you give out assignments like "implement a drawRect function" etc.

A: Perhaps a text-only version of the Lunar Lander game. You could do full ASCII art and animations (with ncurses, perhaps) as an advanced exercise, but even in a pure text form it can be interesting.
I recall playing the version that ran on the HP 67 calculator, and it was entertaining with only a seven segment display to work with.
I vaguely recall a version that probably ran on an ALTAIR 8800 written in MITS/Microsoft BASIC that used the leading part of the line to show height above ground as ASCII art, with your prompt for the next tick's burn at the right.
Another traditional choice would be to implement Hunt the Wumpus, or for the ambitious, Battleship.

A: One of my first programming class had a long homework about implementing a (reduced) Monopoly game.
You can use chained lists for the board.
You can use Inheritance for board tiles.
You need some logic to process players turns.
It was probably the first project I've done in CS that I could talk about to my non-tech friends and generate some interest.


text:
Q: how can i traverse to specific child A by locating child B of same Parent? I am trying to traverse to three dots button (overflow_menu) via locating "Premium" tag on Parent element.
Additional info:
1. I am trying for Appium using Java.
My aim:
Child B--> Same Parent --> action on Child A
I have tried few x-paths but nothing is working for me.
I would appreciate help for the same. Please let me know if you need any more info.
Thanks.

A: Here is the xpath that will get all the premium movies "Overflow_menu".
//*[@class='android.widget.TextView' and .='Premium']/parent::*/*[@class='android.widget.ImageView']


text:
Q: how to do python DNS lookup in the list of domain in a file import dns.resolver

with open('fname.txt') as f:
    read_data = f.read().strip("\n")

for aline in read_data:
    nameservers = dns.resolver.query(read_data, 'NS')
    for data in nameservers:
        print (data)

f.close()

I have a list of domain on fname.txt and I would like to do NS lookup on every domain on it. can anyone please help me to read on the domain on my file and then output the result of each domain that has the same ns lookup result.

A: You are almost there.
Instead of reading all at once, you can simply iterate over the opened file object, reading line by line (just remember to strip \n). Also, you don't need to close the file when using a context manager (with), since it does that for you.
import dns.resolver

with open('fname.txt') as fin:
    for line in fin:
        domain = line.strip()
        nameservers = dns.resolver.query(domain, 'NS')
        for data in nameservers:
            print(data)


text:
Q: Failed matplotlib installation (tried everything) on (OS X 10.8.4 & Python 2.7.5) I'm a little new at this, but have honestly exhausted every thread and possible installation option to have run into an error or issue every time.
Could list multiple issues experienced, but the main one:
 pip install matplotlib

 error: could not create '/Library/Python/2.7/site-packages/matplotlib': Permission denied

Could anybody help me figure out how to change these permissions or point me in the right direction?

A: If you have admin rights you can do

sudo pip install matplotlb

It will prompt for your password, and when you enter it you will be able to install there.
Another option is to install locally with the --user flag for pip

pip install --user matplotlib

Another option is to go with a scientific distribution like Enthought Canopy or the Anaconda python distribution from Continuum Analytics. Both of these come with matplotlib (and a lot of other very useful packages) already installed and working properly.


text:
Q: Can class methods be added to some instances of Ruby objects but not others? Here is a module containing some methods:
module M
  def x; y; end
  def y; ...; end
end

Here's a class:
class C
  def z; ...; end
end

I have two instances of C:
 c1 = C.new
 c2 = C.new

Is there something I can do to c1 such that c1.class has x and y, but c2.class doesn't? I don't see a straightforward way to subvert the method lookup.

A: Rather than doing c1.class.x, why not do c1.x, as the Law Of Demeter would suggest?
class C
  def self.x
    "hi"
  end
end

c1 = C.new
c2 = C.new
def c1.x
  self.class.x
end
c1.x # => "hi"
c2.x # NoMethodError

A: You could override c1.class to return something other than C (and that other thing would extend M). Other than that, no.
Note that overriding c1.class is almost certainly a bad idea. An object shouldn't lie about what its class is.

A: Maybe this
c1.extend(M)

c1.methods & [:x, :y] #=> [:x, :y]
c2.methods & [:x, :y] #=> []


text:
Q: Java Error: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference I get the error "Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference" when I want the start my app.
The error output
02-09 19:39:20.364 18846-18846/com.michael1011.tweetcomposer E/AndroidRuntime: FATAL EXCEPTION: main
   Process: com.michael1011.tweetcomposer, PID: 18846
   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.michael1011.tweetcomposer/com.michael1011.tweetcomposer.login}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2450)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2520)
       at android.app.ActivityThread.-wrap11(ActivityThread.java)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:148)
       at android.app.ActivityThread.main(ActivityThread.java:5466)
       at java.lang.reflect.Method.invoke(Native Method)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
       at android.support.design.widget.Snackbar.setText(Snackbar.java:334)
       at android.support.design.widget.Snackbar.make(Snackbar.java:210)
       at com.michael1011.tweetcomposer.login.onCreate(login.java:43)
       at android.app.Activity.performCreate(Activity.java:6251)
       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2403)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2520)
       at android.app.ActivityThread.-wrap11(ActivityThread.java)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:148)
       at android.app.ActivityThread.main(ActivityThread.java:5466)
       at java.lang.reflect.Method.invoke(Native Method)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

mainActivity.java
public class login extends AppCompatActivity {

public boolean isOnline() {
    NetworkInfo netInfo = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
    if (netInfo == null || !netInfo.isConnectedOrConnecting()) {
        return false;
    }
    return true;
}

Intent sb_login = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    Toolbar login_toolbar = (Toolbar) findViewById(R.id.toolbar_login);
    setSupportActionBar(login_toolbar);

    RelativeLayout login_sb_layout = (RelativeLayout)findViewById(R.id.login_layout);

    Snackbar sb_login = Snackbar
            .make(login_sb_layout, "@string/no_internet_connection", Snackbar.LENGTH_INDEFINITE)
            .setAction("RETRY", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    recreate();
                }
            });

    sb_login.setActionTextColor(Color.parseColor("#55acee"));

    View sb_login_view = sb_login.getView();
    TextView sb_login_textView = (TextView)sb_login_view.findViewById(android.support.design.R.id.snackbar_text);
    sb_login_textView.setTextColor(Color.parseColor("#ffffff"));

    if(!isOnline()) {
        sb_login.show();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_login, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    if (id == R.id.action_settings) {

        startActivity(new Intent(this, settings.class));
        return true;
    }

    return super.onOptionsItemSelected(item);
}}

Please help.

A: I guess you have to replace the line
Intent sb_login = null;

with
Intent sb_login;

then try


text:
Q: Setting up a FTP cron job on Windows Is there a way to have an FTP client or setup a task where the system will connect to an FTP server and download all files at a certain time in the night? I'm on Windows and was unsure if there is a way to this with the OS cmd line or if an FTP client could do this.

A: Yes, there are two parts: Windows Task Scheduler and Powershell.
First create a small powershell script to connect and transfer your file. For security, Powershell is disabled from running scripts, so you'll need to first enable to run locally created scripts.
Here's one example of powershell ftp script.
Once you have it running the way you like, use the task scheduler (from the control panel) to run the script nightly.


text:
Q: I am working vbscript in HTA. Using SQLite for database need. And SQLite doesn't recognize equal to an integer The target field is pk_2013_1qrt and its type is integer. But when i run the query below, results includes pk_2013_1qrt=1 values too.
Where did i go wrong?
Regards
SELECT *,ims_2012_modifiye.id AS imsID, ims_2012_modifiye.ilac_id AS ilacID,
         ims_2012_modifiye.ilac_adi_duzgun AS iaDuzgun
FROM ims_2012_modifiye
LEFT JOIN ilaclar ON ims_2012_modifiye.ilac_id=ilaclar.id
WHERE ims_2012_modifiye.ilac_id NOTNULL
  AND ims_2012_modifiye.asil_listede_mi=1
  AND ims_2012_modifiye.ilac_id NOT IN
      (SELECT ilac_id FROM piyasa_kontrol
       WHERE pk_yil IN (2012,2011,2010,1900,1901))
OR
  ims_2012_modifiye.oncelik_verilsin_mi=1
  AND ims_2012_modifiye.pk_2013_1qrt=0
LIMIT 5

A: OR has lesser priority than AND. What you want is unclear, but the latest AND ims_2012_modifiye.pk_2013_1qrt=0 is applied only to the rows with ims_2012_modifiye.oncelik_verilsin_mi=1. Maybe this:
SELECT *,ims_2012_modifiye.id AS imsID, ims_2012_modifiye.ilac_id AS ilacID,
         ims_2012_modifiye.ilac_adi_duzgun AS iaDuzgun
FROM ims_2012_modifiye
LEFT JOIN ilaclar ON ims_2012_modifiye.ilac_id=ilaclar.id
WHERE (ims_2012_modifiye.ilac_id NOTNULL
         AND ims_2012_modifiye.asil_listede_mi=1
         AND ims_2012_modifiye.ilac_id NOT IN
           (SELECT ilac_id FROM piyasa_kontrol
            WHERE pk_yil IN (2012,2011,2010,1900,1901))
       OR
         ims_2012_modifiye.oncelik_verilsin_mi=1)
  AND ims_2012_modifiye.pk_2013_1qrt=0
LIMIT 5

A: Problem solved. As @Anton said AND has prior accessibility to query results. Move AND ims_2012_modifiye.pk_2013_1qrt=0 part just after to WHERE solves my problem. Thank you Anton, Regards


text:
Q: Devise & Custom Rails User URLs I am currently using Rails 3.2.5 with the latest devise gem.
Currently users can access their profile page at...
example.com/users/john-doe
I want to remove the users portion of the url, so the url would be example.com/john-doe.  Is this possible with devise?
Right now in my routes file I have the following...
devise_for :users, :controllers => {:omniauth_callbacks => 'omniauth_callbacks'}

A: Just add a route for it. You will probably want it to be the last one in the routes file.
Something like:
match '/:user' => "users#show", :as => :user_profile


text:
Q: Web security, are there issues with hidden fields (no sensitive data)? I was having a discussion with coworkers.  We have to implement some security standards.  We know not to store 'sensitive, addresses, date of birth' information in hidden fields but is it OK to use hidden fields for your application, in general.
For example:
action=goback

It seems like it would be safer to use hidden fields for that kind of information as opposed to adding it in the query string.  It is  one less piece of information that a hacker could use against your application.

A: Making a field "hidden" has pretty much nothing to do with security, and should be considered a UI decision.  Any "hacker" will read your HTML source anyway.
Better to either not show sensitive information at all, or, if you must, to use SSL (to prevent data interception by network intermediaries) and some combination of login challenges (to prevent unauthorized access).

A: It's only a security hole if you're exposing information that wouldn't be otherwise available to the end user and/or aren't validating it on return.
I'd look instead to storing said information in a server side session variable instead...

A: Storing your data in a hidden field is, from a security standpoint, exactly the same as storing it in the query string.  In fact, if your form uses the GET action, it ends up int he query string anyway.
Hidden fields are completely unrelated to security in any way; they are simply a method by which data can be stored in a form without forcing the user to see it.  They do not provide a way of preventing the user from seeing it.

A: Hidden fields are not always an issue, but they should always ring alarm bells as they have two potential problems:
1) If the data is sensitive, it exposes it to the client (e.g. using a proxy, or simply view source - and it is pointless to try and prevent this programmatically)
2) If the data is interpreted by the server, a knowledgeable user can change it. To take a silly example, if the hidden field contains the user's bank balance, they could use a proxy or some non standard client to make the server think their bank balance is anything they choose.
The second one is a big source of vulnerabilities in webapps. Data associated with the session should be held server side, unless you have a means of validating it on the server (for example if the field is signed or encrypted by the server).
Provided you are sure you're not falling into either of these traps, they can be OK to use. As a rule of thumb, I would not use hidden fields except for data you would be happy to see in the query string, or if javascript needs them for processing. In the latter case, you still need to make sure the server is validating though, don't assume the client will run your javascript.

A: A hacker can access hidden fields just as easily as querystring values by using an intercepting proxy (or any number of tools).
I dont think there is anything wrong with using hidden fields as long as they aren't used for anything sensitive and you validate them like you would any other value from the client.

A: Consider encrypting the name and value of your hidden field for the purpose of tamper checking since hackers can still get hold of your hidden fields and manipulate them the way they wanted to.

A: As other people have mentioned both the query string and hidden fields are essentially public data, viewable by the user.
One thing to keep in mind if you place data on the querystring is that people pass urls around, and because of this should never contain any information specific to the current user.
It is also probably a good idea not to include state information in the url, if that state can not be entered directly.  Or at least you would need to handle invalid state information in the querystring.

A: I would say that this is no more or less safe than placing the item in the query string.  After all, one could always view source on the site (and there isn't any way to prevent that, since one could always programmatically download the source).
A better solution here would be to encrypt the names of the fields and the values with a key that is generated on the server, and only the server.  Unless the server was hacked, the client wouldn't have any clue what the name of the value is, or its value.
Of course, since this is coming from the client, you still have to check the validity of the data coming back, don't just take for granted that it hasn't been altered in a manner that you didn't dictate.
To that end, you will want to use hashing to make sure that the value hasn't been tampered.

A: In general don't use hidden form fields for sensitive data. Only for static non sensitive POST data that you realise is not safe to handle "as its recieved". The only time i use them is to store Session Tokens as they're rendered and checked upon recieving the POST. To prevent CSRF attacks or atleast make them a great deal harder.

A: In addition to all the other useful advice by other posters, I'd also add that hidden fields make your app no less vulnerable to SQL injection attacks as url query string values do. As always, sanitise your input.


text:
Q: Pandas: How to delete string with some value I have df
              subdomain search_engine search_term
0                    vk.com          None        None
1                    vk.com          None        None
2              facebook.com          None        None
3                    vk.com          None        None
4                    vk.com          None        vkontakte

I need to get 4                    vk.com          None        vkontakte
I try
df[~df.search_term.str == r"None"]

But it returns TypeError: bad operand type for unary ~: 'StringMethods'

A: I think this should do it:
In[75]:df[df.search_term.str.strip()!='None']
Out[75]:
  subdomain search_engine search_term
4    vk.com          None   vkontakte

or will this work:
df[~df.search_term.str.match('None')]


text:
Q: Docker Compose understanding the ports mapping Docker newbie here. I am trying to understand the meaning of the following:
services:
  mongo1:
   hostname: mongo1
   container_name: mongo1
   image: mongo:5.0.6
   expose:
      - 27017
   ports:
     - 27011:27017
   restart: always

Note the ports: 27011:27017. When the Docker is up and running, I can access the MongoDB server via port 27011, so what is the 27017? And why do I need to expose it like the following?
expose:
  - 27017

A: expose: is a legacy implementation detail of first-generation Docker networking.  It does almost nothing in current Docker, and it's always safe to remove it from Compose files.  No other changes are required.
ports: describes how to map a port from the host system to a port in the container.  The second port number is a fixed property of the image and is typically the "normal" port the container listens on; in your example MongoDB normally listens on port 27017 and the second port number must be exactly that.  The first port number can be any otherwise-unused port on the host system.


text:
Q: How to add an alpha value to surface objects in pygame? I am trying to make a menu screen where the 'New Game' and 'Load Game' icons appear to have no box around them until the mouse is over them at which point they have an opaque blue box. I have yet to implement the mouse controls in the code as I currently cannot get the blue box to become opaque. Any advice would be great. Currently the screen is black when the code is run, however removing line 30 causes the screen to appear as it should but with no alpha values.
import random, pygame, sys
from pygame.locals import *

FPS = 30 # frames per second, the general speed of the program
WINDOWWIDTH = 1000 # size of the window's width in pixels
WINDOWHEIGHT = 600 # size of window's height in pixels

#            R    G    B
WHITE    = (255, 255, 255)
RED      = (255, 0, 0)
BLUEINVIS = (0, 0, 255, 255)
BLUEOP = (0, 0, 255, 128)

# Colors

TEXTCOLOR = WHITE
TEXTBOXCOLOR = BLUEINVIS
HIGHLIGHTCOLOR = BLUEOP

BASICFONTSIZE = 20

def main():
    global FPSCLOCK, DISPLAYSURF, BASICFONT
    pygame.init()
    FPSCLOCK = pygame.time.Clock()
    DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
    DISPLAYSURF = DISPLAYSURF.convert_alpha()
    pygame.display.set_caption('Menu')

    BASICFONT = pygame.font.Font('freesansbold.ttf', 50)

    NEW_SURF, NEW_RECT = makeText('New Game', TEXTCOLOR, TEXTBOXCOLOR, WINDOWWIDTH /     2, WINDOWHEIGHT - (WINDOWHEIGHT * 3 / 8))
    LOAD_SURF, LOAD_RECT = makeText('Load Game', TEXTCOLOR, TEXTBOXCOLOR, WINDOWWIDTH / 2, WINDOWHEIGHT - (WINDOWHEIGHT / 4))

    DISPLAYSURF.convert_alpha()

    while True: # main game loop

        DISPLAYSURF.fill(RED)
        DISPLAYSURF.blit(NEW_SURF, NEW_RECT)
        DISPLAYSURF.blit(LOAD_SURF, LOAD_RECT)

        for event in pygame.event.get(): # event handling loop
            #if event.type == MOUSEBUTTONUP:

                #if NEW_RECT.collidepoint(event.pos):

                #elif LOAD_RECT.collidepoint(event.pos):

            #if newRectObj.collidepoint(event.pos):
                #newSurfaceObj = fontObj.render('New Game', True, TEXTCOLOR, HIGHLIGHTCOLOR)

            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        pygame.display.update()
        FPSCLOCK.tick(FPS)

def makeText(text, color, bgcolor, x, y):
    # create the Surface and Rect objects for some text.
    textSurf = BASICFONT.render(text, True, color, bgcolor)
    textRect = textSurf.get_rect()
    textRect.center = (x, y)
    return (textSurf, textRect)

if __name__ == '__main__':
    main()

A: Use: surface = surface.convert_alpha()
Using surface.convert_alpha() alone does nothing. The convert_alpha() returns a suface with an alpha value.
http://www.pygame.org/docs/ref/surface.html#pygame.Surface.convert_alpha
Eg.: image1 = pygame.image.load("images/person.png").convert_alpha()

A: If I replace your code by this snippet, it displays your text (white on blue) when the cursor hovers it (inspired from this SO question). I also added some transparency if you want (uncomment the set_alpha lines):
def main():
    global BASICFONT
    pygame.init()
    FPSCLOCK = pygame.time.Clock()
    DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
    background=pygame.Surface((DISPLAYSURF.get_rect().width, DISPLAYSURF.get_rect().height))
    background.fill(RED)

    BASICFONT = pygame.font.Font('freesansbold.ttf', 50)

    pygame.display.set_caption('Menu')

    NEW_SURF, NEW_RECT = makeText('New Game', TEXTCOLOR, TEXTBOXCOLOR, WINDOWWIDTH /     2, WINDOWHEIGHT - (WINDOWHEIGHT * 3 / 8))
    LOAD_SURF, LOAD_RECT = makeText('Load Game', TEXTCOLOR, TEXTBOXCOLOR, WINDOWWIDTH / 2, WINDOWHEIGHT - (WINDOWHEIGHT / 4))
    #NEW_SURF.set_alpha(128)
    #LOAD_SURF.set_alpha(128)

    while True: # main game loop

        DISPLAYSURF.blit(background, background.get_rect())
        DISPLAYSURF.blit(NEW_SURF, NEW_RECT)
        DISPLAYSURF.blit(LOAD_SURF, LOAD_RECT)

        for event in pygame.event.get(): # event handling loop
            if event.type == MOUSEMOTION:
                if NEW_RECT.collidepoint(event.pos):
                  NEW_SURF = BASICFONT.render('New Game', True, TEXTCOLOR, HIGHLIGHTCOLOR)
                  #NEW_SURF.set_alpha(255)

                elif LOAD_RECT.collidepoint(event.pos):
                  LOAD_SURF = BASICFONT.render('Load Game', True, TEXTCOLOR, HIGHLIGHTCOLOR)
                  #LOAD_SURF.set_alpha(255)

                else:
                  NEW_SURF = BASICFONT.render('New Game', True, TEXTCOLOR, TEXTBOXCOLOR)
                  LOAD_SURF = BASICFONT.render('Load Game', True, TEXTCOLOR, TEXTBOXCOLOR)
                  #NEW_SURF.set_alpha(128)
                  #LOAD_SURF.set_alpha(128)


text:
Q: CALayer mask not working correctly I am trying to mask a UIView to an image using it's layer's mask property. I have seen countless examples that say, "it's just that easy". However, after quite a bit of tweaking, I cannot seem to reproduce the results described. Setting the layer mask only makes the view disappear. Here is the code that I am using:
- (void)setMaskImage:(UIImage *)maskImage
{
    _maskImage = maskImage;

    self.layer.mask.contents = (__bridge id)(_maskImage.CGImage);
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self != nil) {
        self.layer.mask = [CALayer layer];
    }

    return self;
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];

    self.layer.mask.frame = self.layer.bounds;
}

And here is the image that I am trying to use to mask the view: http://cl.ly/0a300G2r133V

A: One possibility is that the system's not actually using setFrame: to set your view's geometry.  It can use setCenter: and setBounds:.  Another possibility is that the system is not setting your view's geometry at all, and it's only being set once, in the [super initWithFrame:frame] call, before you add the mask layer.
Anyway, instead of overriding setFrame:, you should override layoutSubviews:
- (void)layoutSubviews {
    [super layoutSubviews];
    self.layer.mask.frame = self.bounds;
}

A: The following works as expected:
- (void)setMaskImage:(UIImage *)maskImage
{
    if (_maskView == nil) {
        _maskView = [[UIImageView alloc] initWithImage:maskImage];
        _maskView.frame = self.bounds;
        self.layer.mask = _maskView.layer;
    } else {
        _maskView.image = maskImage;
    }
}

- (UIImage *)maskImage
{
    return _maskView.image;
}

- (void)setBounds:(CGRect)bounds
{
    [super setBounds:bounds];

    _maskView.frame = self.bounds;
}

I'm not sure why just using a plain CALayer wasn't working, but this adds the bonus of working well with stretchable images.

A: You  can override the UIView drawRect() method for its custom appearance on the screen.
Try to use following approach.
//code for drawRect()

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextAddRect(context,ImageFrame);
CGContextClip(context);
CGContextClearRect(context,ImageFrame);
[super drawRect:rect];

It will make your view transparent in your imageFrame area.


text:
Q: How to automatically fill other form fields after one field is filled? I'm creating a form in moodle using moodleform class. I have many fields in the form. What I'm wanting to do is when the user fills in the first field, I want to get the data that he/she entered, search the relevant DB table for a field that matches that input, then populate the other fields for that record.
Please note that the user hasn't pressed any submit button yet. I've been trying to find a function that gets the entered data but all efforts have been in vain. What I found was a get_data() method but I don't even know how to use that correctly. I've been reading the moodle docs but nothing is helping. I'm not a beginner to coding but neither am I an expert.
Here's a code snippet:
class requestcourse_form extends moodleform
{
    function definition()
    {
    global $CFG, $currentsess, $DB, $USER, $currentrecord;

    $mform =& $this->_form; // Don't forget the underscore!

    // Form header
    $mform->addElement('header', 'mainheader',''.get_string('courserequestform','block_usp_mcrs'). '');

    // Course Code field.
    $coursecodearray = array();
    $coursecodearray[0] = get_string('choosecoursecode', 'block_usp_mcrs');
    $allcoursecodes = $DB->get_records_select('block_usp_mcrs_courses', 'id > 0', array(), 'id', 'id, course_code');
    foreach ($allcoursecodes as $id => $coursecodeobject) {
        $coursecodearray[$id] = $coursecodeobject->course_code;
    }
    $coursecode = $mform->addElement('select', 'coursecode', get_string('coursecode', 'block_usp_mcrs'), $coursecodearray);
    $mform->addRule('coursecode', get_string('required'), 'required', null, 'client');
    $mform->setType('coursecode', PARAM_RAW);

    // Course Name field. TODO: Course Name to pick automatically after entering Course Code
    $coursenamearray = array();
    $coursenamearray[0] = get_string('choosecoursename', 'block_usp_mcrs');
    $allcoursenames = $DB->get_records_select('block_usp_mcrs_courses', 'id > 0', array(), 'id', 'id, course_name');
    foreach ($allcoursenames as $id => $coursenameobject) {
        $coursenamearray[$id] = $coursenameobject->course_name;
    }
    $mform->addElement('select', 'coursename', get_string('coursename', 'block_usp_mcrs'), $coursenamearray);
    $mform->addRule('coursename', get_string('required'), 'required', null, 'client');
    $mform->setType('coursename', PARAM_RAW);

Any help would be appreciated.

A: You have to achieve this using javascript, as Moodle has no functionality to fill data in a nested way.
Add AMD module js file where you are calling your mform for display purpose.
In the file where you render your mform
$mform->render();

add below line to call you amd js file.
$PAGE->requires->js_call_amd('local_acestructure/registration', 'init');

In your amd js file make httprequest / ajax call to fetch data based on your course_code select drop down change.
Thank you.


text:
Q: A new line inside subscript I have formula:
\[ A_k = \bigcup_{I \subset \{ 1,...,k \} \text{card} J = K} B_j\]

which generates

I would like ask how to make the new line inside subscript.
It should look like  formula below:

I've tried with \newline and \begin{align*} but it doesn't work.

A: While not as streamlined as the accepted solution, I add this solution to the mix, because it shows the 2-line subscript left justified, as was provided in your example, which the accepted solution (to this point) does not.  I also made the subscript in \scriptscriptstyle, which may be preferable for a multi-line subscript.  Vertical gaps between the stacked lines are adjustable.
\documentclass{article}
\usepackage{stackengine}
\usepackage{amsmath}
\parskip 1em
\begin{document}
\[ \def\useanchorwidth{T}\stackMath
  A_k = \mathop{\stackunder{\bigcup}{\def\stackalignment{l}%
    \stackunder[2pt]{\scriptscriptstyle I \subset \{ 1,...,k \}}
                    {\scriptscriptstyle\text{card} J = K}
  }} B_j\]

\[ \def\useanchorwidth{F}\stackMath
  A_k = \mathop{\stackunder{\bigcup}{\def\stackalignment{l}%
    \stackunder[2pt]{\scriptscriptstyle I \subset \{ 1,...,k \}}
                    {\scriptscriptstyle\text{card} J = K}
  }} B_j\]
\end{document}

A: You can use \substack
\documentclass{article}
\usepackage{amsmath}

\begin{document}
\[ A_k = \bigcup_{\substack{I \subset \{ 1,\dots,k \}\\ \text{card} J = K}} B_j\]
\end{document}

If you feel that there is lot of empty space, here is how to get it out. This one uses \mathclap from mathtools.
\documentclass{article}
\usepackage{mathtools}

\begin{document}
\[ A_k = \bigcup_{\mathclap{\substack{I \subset \{ 1,\dots,k \}\\ \text{card} J = K}}} B_j\]
\end{document}

Response to comment
It works inside align*:
\documentclass{article}
\usepackage{mathtools}

\begin{document}
\begin{align*}
    A_k &= \bigcup_{\mathclap{\substack{I \subset \{ 1,\dots,k \}\\ \text{card} J = K}}} B_j\\
    A_k &= \bigcup_{\mathclap{\substack{I \subset \{ 1,\dots,k \}\\ \text{card} J = K}}} B_j
\end{align*}
\end{document}


text:
Q: How to practice basic probabilistic modeling? I'm heavily struggling in learning simple and basic probabilistic modeling. So I'm learning probability from this probability book Introduction to Probability by Dimitri P. Bertsekas.
Although I understand the theory but when I do the exercises (even the ones in the chapter not at the end of the chapter) I almost always fail to solve them. So for example, I understand the idea of Bayes' rule but then when I face a problem that i have to solve (i.e model it from text into equations) I almost always fail.
The problem I'm facing in learning probabilistic modeling is that I can't find a way to assess how correct my modeling/approach is. For example, if when try to solve an equation in linear algebra you can make sure that your solution is correct by plugging the solutions of the variables into the equation and check if it's correct. However, with probabilities I can't find a way to assess my solution. So I usually end up with a solution at the end of the problem and say "yeah that makes sense". But then when I check the solutions from the authors everything turns out to be wrong.
My questions to you:
1- How should I practice probabilistic modeling? As I said, I understand the theory but I almost always fail when I have to solve a real exercise that involves a problem description that needs to be translated into equations.
2- Is there a way to make sure that my process/solution is correct before consulting the solutions from the authors? Because usually they provide the complete solution to the problem not just the final answers. Actually sometimes even if they simply provide only the final answers you can get a clue of how to solve the problem. Or even I end up just trying with solution strategies until I get a number similar to the solution given by the authors. So I don't end up learning why I should have chosen that approach but rather just used a brute-force way to find the answer.
Edit:
I don't know if anyone here has read that book, but when the authors are explaining an idea and then they give an example, they often omit how they thought about the problem to end up with that modeling. I'm not sure if all probability books are like that, but I would have really appreciated seeing how the authors reached that modeling/solution. So what I would assume is that if you are going to explain how to model a problem using a tree structure, then be consistent and show how you would use a tree structure to solve the examples.

A: Moving from probability theory to the application of the theory
is often difficult. If the application is at all realistic, you
usually have to make assumptions that may not be explicitly
stated, to think carefully about what parts of the real-life
situations involve probability and which don't, and to try to
understand the exact role that probability theory can play in answering
the question. Unlike many other parts of mathematics, understanding
the theory is necessary, but not enough to make a probability
model of a real-life situation.
But making sure you do understand the theory really helps.
If there are trivial-looking drill examples or exercises
illustrating the theory, don't skip them.
Practice really helps. Each time you succeed in doing an
applied problem, you learn something about the thought processes
necessary to do other applied problems.
Plunging into the problems at the end of the chapter without
working your way through the chapter first, then hoping the
right equation will jump off the page to rescue you...that
almost never helps.
All that said, your question is very vaguely stated. It is
easier to give help on a specific problem than to answer
a general 'not getting anywhere' complaint. Maybe your
instructor can help you through a few problems and then
have you do some similar ones, followed by some related,
but not so similar ones.
Maybe you can put a few carefully
chosen problems on this site, being very clear what theoretical
ideas you think might be related, what you have tried already,
and what aspects are particularly puzzling to you. Sometimes
you may get snarky comments, and sometimes you
may just get the answer with no helpful information, and sometimes you may get help from
someone who understands just what is bothering you.
Sometimes students come to me the third or fourth week of the
term and say they haven't understood anything I have said so far.
In these cases, I can offer sympathy and apology, but not much help.
Usually, I ask them to find the first thing they did not
understand. With something specific to discuss, it is often
possible to be really helpful.


text:
Q: Android - Convert/Display A Proper Value I'm developing an android application recently and I found out that the display of the output are quite weird especially when it comes to number.
For example, after going through a formulation.
The value shown on the TextView is 1.5460385687E-11
My question is, how can I display the current above output in a proper way such as
1.546E-11 or 1.546x10^11 ?
As requested, my code for displaying to the output.
double result = tPower * tGain * rGain * Math.pow(lamda / (4 * Math.PI *distance),2)/ light / 100;
((TextView)findViewById(R.id.textFreeSpacePrw)).setText(Double.toString(result));

A: You could use a DecimalFormat to format the result of your calculation before adding it to the TextView. The DecimalFormat class is configured using a pattern given in the constructor, such as "0.###E+0"
See http://developer.android.com/reference/java/text/DecimalFormat.html


text:
Q: Could not initialize Applet Error I have installed java version 1.7 on my ubuntu pc . I have latest iced tea web plugin installed on my firefox . I have installed java3d 1.5.2 api . I have set paths for both java and java-3d . Still when I click http://ccnsb06-iiith.vlabs.ac.in/exp2/ve_exp2.html which has an applet runs based on java 3d api,
it is giving an error
https://drive.google.com/file/d/0B41p1ExqjUEOM3hjdUNwNjBldXc/view?usp=sharing
P.S : I have same problem with my CentOs 6 machine


text:
Q: Why aren't my HTML5 video control buttons working with Javascript? I am working on a project using <video>, trying to make external HTML buttons play/pause, rewind slow, rewind fast, and fast forward control a video using JavaScript. I have the buttons appearing where I want them, but when I try to use them in the browser, they don't do anything to control the video, and the play button doesn't switch to pause and vice versa. I've tried for hours, looking all over the Web to find anything that I can use to help. Most solutions I find are using jQuery which I understand is easier, but it's not what I need. I just want to do it using pure JavaScript so I can better understand it. Included is my existing code. Any help on how I can get them to work would be appreciated!
HTML:

        <video id="video" poster="images/art/preview.png" width="100%" controls>
            <source src="images/art/sample.mp4" type="video/mp4; codecs="avc1.42E01E, mp4a.40.2"">
                <source src="images/art/sample.webm" type="video/webm; codecs="vp8, vorbis"">
                    <source src="images/art/sample.ogv" type="video/ogg; codecs="theora, vorbis"">
    Your browser does not support HTML5 video

                    </video>

                        <button type="button" id="fastBck">

                        </button>
                        <button type="button" id="rew">

                        </button>
                        <button type="button" id="play-pause">

                        </button>
                        <button type="button" id="fastFwd">

                        </button>

JavaScript:
window.onload = function() {
    var video = document.getElementById("video");
    var playButton = document.getElementById("play-pause");
    var rewButton = document.getElementById("rew");
    var fastBckButton = document.getElementById("fastBck");
    var fastFwdButton = document.getElementById("fastFwd");
}

playButton.addEventListener("click", function(){

    if (video.paused==true) {
        video.play();
        playButton.className="glyphicon glyphicon-pause";
    } else{
        video.pause();
        playButton.className="glyphicon glyphicon-play";
    }
})

rewButton.addEventListener("click", function(){
    //not sure exactly how to use currentTime to rewind, or fast forward
})

A: *

*let the browser pick the right codecs for your video

*you defined your variables out of scope (you've encapsulated them inside the onload function)

window.onload = function() {
  var video = document.getElementById("video");
  var playButton = document.getElementById("play-pause");
  var rewButton = document.getElementById("rew");
  var fastBckButton = document.getElementById("fastBck");
  var fastFwdButton = document.getElementById("fastFwd");

  playButton.addEventListener("click", function(){

    if (video.paused===true) {
      video.play();
      playButton.className="glyphicon glyphicon-pause";
    } else{
      video.pause();
      playButton.className="glyphicon glyphicon-play";
    }
  });

  rewButton.addEventListener("click", function(){
    //not sure exactly how to use currentTime to rewind, or fast forward
  });
};
@import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css");

    <video id="video"  width="100%" controls>
      <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type="video/mp4">
      <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.webm" type="video/webm">
      <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.ogv" type="video/ogg">
      Your browser does not support HTML5 video
    </video>

      <button type="button" id="fastBck"></button>
      <button type="button" id="rew"></button>
      <button type="button" id="play-pause"></button>
      <button type="button" id="fastFwd"></button>

Good luck with the fast forward and your other methods

A: window.onload = function() {
       var video = document.getElementById("video");
        var playButton = document.getElementById("play-pause");
    var rewButton = document.getElementById("rew");
    var fastBckButton = document.getElementById("fastBck");
    var fastFwdButton = document.getElementById("fastFwd");
playButton.addEventListener("click", function(){
 if (video.paused==true) {
   video.play();
   playButton.className="glyphicon glyphicon-pause";
    } else{
        video.pause();
        playButton.className="glyphicon glyphicon-play";
     }
   })
    rewButton.addEventListener("click", function(){
       //not sure exactly how to use
       currentTime to rewind, or fast forward
    })
 }

Move listeners inside onload function. Listeners won't be attached until the page is loaded. Respect for wanting to use vanilla JS, however unnecessary.


text:
Q: Listview item empty at first but when you scroll out and in, it shows the content I have a ListView and BaseAdapter and its list items are created dynamically. However, there is an issue.
At first, list item appears very long and empty, but when you scroll down until it is out of screen, then scroll it back on screen, it is visible without problems. What is the issue here?
TableLayout tableLayout = new TableLayout(activity);
                        tableLayout.setLayoutParams(params);
                        tableLayout.setGravity(Gravity.CENTER);

                        JSONObject table = new JSONObject(inputs.getJSONObject(i).getString("Data"));
                        int rowCount = table.getJSONArray("Rows").length();
                        int columnCount = table.getJSONArray("Rows").getJSONObject(0).getJSONArray("Column").length();
                        String tableData[][] = new String[rowCount][columnCount];

                        for (int row = 0; row < rowCount; row++) {

                            TableRow tableRow = new TableRow(activity);
                            TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);
                            tableRow.setLayoutParams(layoutParams);
                            if(row%2==1){ tableRow.setBackgroundColor(Color.LTGRAY); }

                            for (int column = 0; column < columnCount; column++) {
                                tableData[row][column] = table.getJSONArray("Rows").getJSONObject(row).getJSONArray("Column").getString(column);

                                TextView tableItem = new TextView(activity);
                                tableItem.setText(table.getJSONArray("Rows").getJSONObject(row).getJSONArray("Column").getString(column));
                                if(columnCount>1){
                                    tableItem.setMaxWidth(holder.innerLinearLayout.getWidth()/columnCount-1);
                                }
                                tableItem.setLayoutParams(layoutParams);
                                tableItem.setGravity(Gravity.CENTER);
                                tableItem.setPadding(8, 0, 8, 0);
                                if (row == 0) tableItem.setTypeface(null, Typeface.BOLD);
                                tableRow.addView(tableItem);
                            }

                            tableLayout.addView(tableRow);

                        }

                        holder.innerLinearLayout.addView(tableLayout);

Edit:
tableItem.setMaxWidth(holder.innerLinearLayout.getWidth()/columnCount-1);

This is the line causing the issue, when I remove it the height is fixed too, but table item widths are broken.

A: I thing the problem is that the holder.innerLinearLayout's width is 0 until the first layout pass. When you scroll back the view are reused, so they have a width.
If you want the columns to have the same width, a possible solution is to set them stretchable with an initial width of 0.
tableLayout.setStretchAllColumns(true);

....

// use TableLayout.LayoutParams on TableLayout's children
TableLayout.LayoutParams rowLayoutParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT)
tableRow.setLayoutParams(rowLayoutParams);

...

/// TableRow.LayoutParams on TableRow's children
/// with a 0 initial width
TableRow.LayoutParams itemLayoutParams = new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT);
tableItem.setLayoutParams(itemLayoutParams);


text:
Q: How to determine p(a) in bayes' formula with this example of symmetric conditional probabilities? Why is P(A) in this example 1?
In class, we were shown an illustrative example of bayes that no one including the professor could understand.
P(A|B) = P(A) * P(B|A) / P(B)
Question is:
Use Bayes Theorem to compute the probability of each hair color given that the subject has blue eyes.
Table for the question:
eye_hair = pandas.DataFrame({
    'black': [0.11, 0.03, 0.03, 0.01],
    'brunette': [0.2, 0.14, 0.09, 0.05],
    'red': [0.04, 0.03, 0.02, 0.02],
    'blond': [0.01, 0.16, 0.02, 0.03],
}, index=['brown', 'blue', 'hazel', 'green'])

eye_hair['marginal_eye'] = eye_hair.sum(axis=1)
eye_hair.loc['marginal_hair'] = eye_hair.sum(axis=0)

print(eye_hair)

black brunette red    blond   marginal_eye
brown   0.11    0.20    0.04    0.01    0.36
blue    0.03    0.14    0.03    0.16    0.36
hazel   0.03    0.09    0.02    0.02    0.16
green   0.01    0.05    0.02    0.03    0.11
marg_hair 0.18  0.48    0.11    0.22    0.99
Answer given in class:
for color in eye_hair.columns[:4]:
    p = eye_hair.loc['blue', color] * 1.0 /eye_hair.loc['blue', 'marginal_eye']
    print('Probability of blue eyes, for Hair color of ' + color + ': ' + '%0.3f' % p)

Probability of blue eyes, for Hair color of black: 0.083
Probability of blue eyes, for Hair color of brunette: 0.389
Probability of blue eyes, for Hair color of red: 0.083
Probability of blue eyes, for Hair color of blond: 0.444
Why do we use 1.0 here?
Aka why is P(A) == 1?
My professor's explanation was because it makes all the final probabilities sum to one.
Thanks!

A: The formula that your Professor is using in this code is the following:
P(A|B) = P(A & B) / P(B)

And NOT
P(A|B) = P(A) * P(B|A) / P(B)

(they are equivalent)
eye_hair.loc['blue', color] is P(blue & color) i.e., the probability that someone has blue hair and the given color. This value is divided by P(blue).
Thus, we end up with:
P(color | blue) = P(blue & color) / P(blue)

The 1.0 is used to convert the results to float, which is not really needed because the data is already in float, even if you're using python 2.* (python 3 automatically returns a float).
In short, ignore the 1.0 and if I may add, try to learn these things online instead.

A: None of the rows or columns sum to 1, but the entire table sums to 0.99.  I guess there is a typo in one of the numbers.
This means that the numbers we're looking at are not the conditional probabilities, P(B|A), but the joint probabilities, P(A & B).
This is because sum(P(B|A), axis=B) == 1, so they cannot be the conditionals.
They are related: P(A & B) == P(B|A) * P(A). So the real reason why using 1.0 works is that P(A) is already included in the table.
BTW, this was a question about probability, not programming, so it ought to be on https://stats.stackexchange.com rather than here.

A: In your code, eye_hair.loc['blue', color] is actually the probability of both events happening simultaneously: "eye color = blue" and "hair color = color".
Mathematically, that is: P(A∩B).
Which is equal to the numerator in the right side of your Bayes theorem expression:
P(A∩B) = P(A) * P(B|A)
Your professor's explanation is right in terms of how to develop an intuition for Bayes' theorem from a practical point of view: it is basically redefining the sample space to the event you're conditioning on. So the answer to the question is just taking the probabilities for the events in your "eye color = blue" row and "re-scaling" them so they sum up to 1 (which is achieved by dividing the probability values in that row by the marginal of "eye color = blue").
Hope that helps.


text:
Q: nlme analysis growth curve I am trying to fit a sigmoid curve (SSasymp or another) to a series of repeated measures data with the nlme function:
fm5 <- nlme(IncAlt ~ SSasymp(fecha, Asym, R0, lrc),
                fixed=Asym + R0 + lrc~ poblacion,
                random =Asym ~ 1|bloque/familia/id,data=data,
                start =c(Asym=83 ,R0=-9,lrc=-3),correlation = corCAR1(form=~fecha|id))

but I can´t fit it.
I am really want to know if there are differences between populations and what is the variance of families, blocks and id.
My data is a series of height measurements in different times in several plants(id), nested in families (familia), nested in Populations (poblacion), all of them randomly blocked (bloque). The measurements of each plant are correlated (AR1) but they are independent of other plants.
My dataframe looks like this:
 fecha id bloque poblacion familia IncAlt
     1  1      1        PA      11    0.0
     2  1      1        PA      11    0.0
     3  1      1        PA      11    0.0
     4  1      1        PA      11    1.8
     5  1      1        PA      11    1.8
     6  1      1        PA      11    3.3
     7  1      1        PA      11    3.8
     ...
     1 16      1       TRB      11    0.0
     2 16      1       TRB      11    0.0
     3 16      1       TRB      11    0.0
     4 16      1       TRB      11    0.0
     5 16      1       TRB      11    0.5
     6 16      1       TRB      11    3.0
     7 16      1       TRB      11    8.5
     8 16      1       TRB      11   13.5
     9 16      1       TRB      11   14.5
     ...
    16 16      1       TRB      11   40.5
    17 16      1       TRB      11   43.0
    18 16      1       TRB      11   43.5
    19 16      1       TRB      11   43.5
    ...


text:
Q: Three20 Navigation: View don't show I rework my app to use Three20 and I wanna use Three20 navigation now.
Here is my code, that works perfectly before:
ENSListViewController *vc = [ENSListViewController alloc];
NSArray *ensArray;
NSDictionary *dic;
NSInteger folder_id;
NSString* folder_type;
NSString* barTitle;
NSString* folderName;

if (indexPath.section == 0)
{
    ensArray = [ensFolderList objectForKey:@"an"];
    dic = [ensArray objectAtIndex:indexPath.row];
    folder_type = @"an";
    barTitle = [NSString stringWithFormat:@"%@", [dic objectForKey:@"name"]];
    folder_id = [[dic objectForKey:@"ordner_id"] intValue];
    folderName = [dic objectForKey:@"name"];
}
else
{
    ensArray = [ensFolderList objectForKey:@"von"];
    dic = [ensArray objectAtIndex:indexPath.row];
    folder_type = @"von";
    barTitle = [NSString stringWithFormat:@"%@", [dic objectForKey:@"name"]];
    folder_id = [[dic objectForKey:@"ordner_id"] intValue];
    folderName = [dic objectForKey:@"name"];
}

vc.folder_id = folder_id;
vc.folder_type = folder_type;
vc.barTitle = barTitle;
vc.folderName = folderName;
[vc initWithNibName:@"ENSListViewController" bundle:nil];
[self.view addSubview:vc.view];

It works perfectly.
It allocs a ViewController, sets a lot of data in the ViewController (Properties) and then show the view.
Here is my code now:
  NSArray *ensArray;
NSDictionary *dic;
NSInteger folder_id;
NSString* folder_type;
NSString* barTitle;
NSString* folderName;

if (indexPath.section == 0)
{
    ensArray = [ensFolderList objectForKey:@"an"];
    dic = [ensArray objectAtIndex:indexPath.row];
    folder_type = @"an";
    barTitle = [NSString stringWithFormat:@"%@", [dic objectForKey:@"name"]];
    folder_id = [[dic objectForKey:@"ordner_id"] intValue];
    folderName = [dic objectForKey:@"name"];
}
else
{
    ensArray = [ensFolderList objectForKey:@"von"];
    dic = [ensArray objectAtIndex:indexPath.row];
    folder_type = @"von";
    barTitle = [NSString stringWithFormat:@"%@", [dic objectForKey:@"name"]];
    folder_id = [[dic objectForKey:@"ordner_id"] intValue];
    folderName = [dic objectForKey:@"name"];
}

/*
vc.folder_id = folder_id;
vc.folder_type = folder_type;
vc.barTitle = barTitle;
vc.folderName = folderName;
[vc initWithNibName:@"ENSListViewController" bundle:nil];
//[self.view addSubview:vc.view];
 */
NSString *url = [NSString stringWithFormat:@"tt://ensList/%@/%@/%d/%@/%@/%@", @"ENSListViewController", nil, folder_id, folder_type, barTitle, folderName];
TTURLAction *action = [TTURLAction actionWithURLPath:url];
[[TTNavigator navigator] openURLAction:action];

Here is my Navigator:
navigator = [TTNavigator navigator]; // create the navigator
navigator.persistenceMode = TTNavigatorPersistenceModeAll; // and he will save the data :)

TTURLMap* map = navigator.URLMap;

[map            from: @"tt://ens"
    toSharedViewController: [ENSOverviewViewController class]];

[map from: @"tt://ensList/(initWithNibName:)/(bundle:)/(folderId:)/(folderType:)/(barTitle:)/(folderName:)" toViewController:[ENSListViewController class]

transition:3];
And here is my new Constructor method:
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self LoadENSList];
    }
    return self;
}

- (void) initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil folderId:(NSInteger)folder_id2 folderType:(NSString*)folder_type2 barTitle:(NSString*)barTitle2 folderName:(NSString*)folderName2
{
    self.folder_id = folder_id2;
    self.folder_type = folder_type2;
    self.barTitle = barTitle2;
    self.folderName = folderName2;
    [self initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

}

So, if you read it up to here: big thanks!
Now my problem is: The view doesn't open. Nothing happens.
I think there is a mistake in my self made constructor, the order of calling my constructor or something like this. Im on it since 2 hours but can't find the error.
I know Three20 is much undocumented and I am not expacting a fast answer, but if anyone have an idea: please comment or answer.

A: Found the solution:
1) I forget the return-value in my constructur.
After adding this (changing (void) to (id) and add "return self") it goes on...
2) After he changes in 1) the system crashes because initWithNibName throws an NSInvalidArgument error.
After changing this to init, it works perfectly


text:
Q: Oauth 2.0 problem after publish apps script to add-ons I'm working on Integrate Google spreadsheet with Salesforce using Google AppsScript.
https://github.com/googleworkspace/apps-script-oauth2
I proceeded with the OAuth2.0 authorization by referring to the above and confirmed that it was working normally.
The problem happened after I published the Google Apps script as a Google Workspace add-ons.
(App Visbility is Priavte -Only available to users in your domain.)
When multiple people download the add-ons and proceed with authorization,
the credentials(OAuth2.0 access token, OAUth2.0 instance_url) of all downloaded people are changed to the credentials(OAuth2.0 access token, OAUth2.0 instance_url) of the last person who authenticated.
for example
A person named Olivia downloads add-ons and login in to org called A.salesforce.com, then a person named Lucas downloads add-ons and login in to org called B.salesforce.com
Then Olivia's credentials will also be replaced by the credentials of B.salesforce.com where Lucas logged in.
I don't know why this is happening.
Is there any part of the code that needs to be modified?
function run() {
  var service = getService_();
  if (service.hasAccess()) {
   var url = service.getToken().instance_url +
    '/services/data/v24.0/chatter/users/me';

   // Make the HTTP request using a wrapper function that handles expired
  // sessions.
   var response = withRetry(service, function() {
     return UrlFetchApp.fetch(url, {
        headers: {
          Authorization: 'Bearer ' + service.getAccessToken(),
        }
     });
  });
  var result = JSON.parse(response.getContentText());
  } else {
     openUrl()
  }
}

function withRetry(service, func) {
  var response;
  var content;
  try {
    response = func();
    content = response.getContentText();
  } catch (e) {
    content = e.toString();
  }
  if (content.indexOf('INVALID_SESSION_ID') !== -1) {
    service.refresh();
    return func();
  }
  return response;
}

/**
 * Reset the authorization state, so that it can be re-tested.
*/
function reset() {
  getService_().reset();
}

/**
 * Configures the service.
 */
function getService_() {
  return OAuth2.createService('Saleforce')
      // Set the endpoint URLs.
   .setAuthorizationBaseUrl('https://login.salesforce.com/services/oauth2/authorize')
   .setTokenUrl('https://login.salesforce.com/services/oauth2/token')

   // Set the client ID and secret.
  .setClientId(CLIENT_ID)
  .setClientSecret(CLIENT_SECRET)

  // Set the name of the callback function that should be invoked to
  // complete the OAuth flow.
  .setCallbackFunction('authCallback')

  // Set the property store where authorized tokens should be persisted.

  .setPropertyStore(PropertiesService.getScriptProperties())

  // Set the scopes to be requested.
  //.setScope('chatter_api refresh_token');
}

/**
 * Handles the OAuth callback.
 */
function authCallback(request) {
  var service = getService_();
  var authorized = service.handleCallback(request);
  if (authorized) {
    return HtmlService.createHtmlOutput('Success!');
  } else {
    return HtmlService.createHtmlOutput('Denied.');
  }
}

/**
 * Open authorizationUrl
 */
function openUrl() {
  var service = getService_();
   var authorizationUrl = service.getAuthorizationUrl();
  var html = HtmlService.createHtmlOutput(''
    // Offer URL as clickable link in case above code fails.
    + 'Failed to open
  automatically. Click here to proceed.'
    + ''
       + '')
      .setWidth(90).setHeight(1);
      SpreadsheetApp.getUi().showModalDialog(html, "Open ...");
   }

/**
 * Logs the redict URI to register.
 */
function logRedirectUri() {
  Logger.log(OAuth2.getRedirectUri());
}

A: The problem occurs because the script is using the Script store (PropertiesService.getScriptProperties()) to store the OAuth authorization token. This could be fixed by using the User Store (PropertiesService.getUserProperties()) instead.
Use the Script Store to store properties for all users
Use the Document Store to store properties for each file no matter what user uses it.
Use the User Store to store properties for each user, no matter what file is used


text:
Q: Refused to connect to 'https://rpc-mainnet.matic.network/' because it violates the following Content Security Policy directive: "default-src 'self'" After deploying my MERN app to heroku, I get this error on the browser console. Even though I specified the correct CSP directives. This is the meta tag it renders on the browser
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self' 'unsafe-inline'; connect-src 'self' https://rpc-mainnet.matic.network/; img-src 'self'; style-src 'self' 'unsafe-inline'; base-uri 'self'; form-action 'self'; font-src 'self' https://fonts.gstatic.com; ">

What am I doing wrong?


text:
Q: AngularJS .success method and .then method Hi I need help with Angular JS
instead of using .success and .error how can I build this code using .then and .catch? I guess simply changing .success and .error to .then and .catch doesn't work.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
 $scope.formData = {};
 $http.get('/api/work')
 .success(function(data) {
 $scope.tasks = data;
 })
 .error(function(data) {
 console.log('Error: ' + data);
 });
});

A: The angular api for this changed quite a long time.
Right now you should replace:
$http.get('/api/work')
    .success(function(data) {
        $scope.tasks = data;
    })
    .error(function(data) {
        console.log('Error: ' + data);
    });

to this
$http.get('/api/work')
    .then(function(response) {
        $scope.tasks = response.data;
    }, function(data) {
        console.log('Error: ' + data);
    });

because "then" works like this:
.then(successCallback, errorCallback, notifyCallback)

A: In order to use "then" I believe you must use a Promise. Take a look here Angular Promises


text:
Q: Similar queries taking different times to complete I had the following query:
SELECT nvl(sum(adjust1),0)
FROM (
  SELECT
    ManyOperationsOnFieldX adjust1,
    a, b, c, d, e
  FROM (
    SELECT
      a, b, c, d, e,
      SubStr(balance, INSTR(balance, '[&&2~', 1, 1)) X
    FROM
      table
    WHERE
      a >= To_Date('&&1','YYYYMMDD')
      AND a < To_Date('&&1','YYYYMMDD')+1
  )
)
WHERE
  b LIKE ...
  AND e IS NULL
  AND adjust1>0
  AND (b NOT IN ('...','...','...'))
  OR  (b = '... AND c <> NULL)

I tried to change it to this:
SELECT nvl(sum(adjust1),0)
FROM (
  SELECT
    ManyOperationsOnFieldX adjust1,
  FROM (
    SELECT
      SubStr(balance, INSTR(balance, '[&&2~', 1, 1))
    FROM
      table
    WHERE
      a >= To_Date('&&1','YYYYMMDD')
      AND a < To_Date('&&1','YYYYMMDD')+1
      AND b LIKE '..'
      AND e IS NULL
      AND (b NOT IN ('..','..','..'))
      OR  (b='..' AND c <> NULL)
  )
)
WHERE
  adjust1>0

My intention is to have all the filtering in the innermost query, and only give the outer ones the field X which is the one I have to use a lot. However, the original query takes a couple of seconds to execute, while the second one won't even finish.  I waited for almost 20 minutes and still no results.
Is there an obvious reason for this to happen that I might be overlooking?

A: These 2 queries are not the same and don't return the same result .
You end up with following filters:
1st Query:
 WHERE
 (
 a >= To_Date('&&1','YYYYMMDD')
  AND a < To_Date('&&1','YYYYMMDD')+1
 )
 AND
(
    b LIKE ...
   AND e IS NULL
   AND adjust1>0
   AND (b NOT IN ('...','...','...'))
   OR  (b = '... AND c <> NULL)
)

Second:
WHERE
  (
  a >= To_Date('&&1','YYYYMMDD')
  AND a < To_Date('&&1','YYYYMMDD')+1
  AND b LIKE '..'
  AND e IS NULL
  AND (b NOT IN ('..','..','..'))
  )
  OR
 (b='..' AND c <> NULL)

You need to use parenthesis carefully while combining  AND and OR predicates in one condition.


text:
Q: Is it possible to code Windows Mobile 7 using a Linux Environment? Is it possible to code Windows Mobile 7 using a Linux Environment ?
I have found the MonoDevelopement and I was wondering if this is achievable ?
Thank you for your guidance.

A: You can use MonoDevelop for your development but Mono Team takes some time to port the latest additions in .Net Framework to Mono. Hence if you want to use the latest features, Mono would not be your best bet.


text:
Q: how to use __str__ with foreign key '__str__ returned non-string (type Product)' while i try to
__str__()

method for a foreign it provide this error
__str__ returned non-string (type Product)

models.py
class Product(models.Model):
    product_name = models.CharField(unique=True, max_length=50 ,
    blank=False,null=False)
    price = models.PositiveIntegerField()
    active = models.BooleanField(default=True)
    def __str__(self):
        return self.product_name
class ProductOrder(models.Model):

    product = models.ForeignKey(Product, on_delete=models.CASCADE ,
    null=True)
    ordering = models.ForeignKey(Order,
    on_delete=models.CASCADE,blank=True,null=True)
    pass

    def __str__(self):
        return self.product

i also tried this
def __str__(self):
        return self.product.product_name

#product_name is a field from Product table

the error will provide is
__str__ returned non-string (type QuerySet)

how to represent it , thanks for reply !

A: You can not return something other than a string from the __str__ method. self.product is not a string, but a Product object.
You can however call str(..) over it, to get the textual representation of that Product:
class ProductOrder(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True)
    ordering = models.ForeignKey(Order, on_delete=models.CASCADE,blank=True,null=True)

    def __str__(self):
        return str(self.product)

A: that because models.ForeignKey(Product, on_delete=models.CASCADE ,
    null=True) is not returning a str so return a string for that function or try to do
return str(self.product)

A: Try
def __str__(self):
    return str(self.product)

Also you may need to define the __str__ method on your Product model

A: ForeignKey returns whole linked base connected to Key. You need to return CharFeiled from ProductOrder or stiring like self.product.product_name from other class.

A: i face the same problem .
i resolve it.
the code is
     def __str__(self):
     return self.product.product_name


text:
Q: http connection reuse I would like to better understand how .Net http connection reuse works.

*

*When I use HttpWebRequest to send something to some server twice from the same appdomain, is the connection (optionally) reused? So the server would see both requests as coming from the same connection even though in my application they are different logical requests.

*If yes, can this behavior be turned off?

*What about connections that use authentication/ssl - are they also also reused? If I supply different credentials/policy for each request this can be a security hole.

A: The connection re-use is using HTTP Keep-alive which is a feature of HTTP/1.1. By using HTTP Keep-alive one TCP connection is used for handling multiple HTTP requests sequentially so one saves time to open a new TCP connection for every request. Each HTTP request itself is then again independent so authentification and similar won't be re-used automatically.

A: As it says the RFC in https://www.rfc-editor.org/rfc/rfc2616#section-8.1
The HTTP header:
Connection: Keep-Alive
is something used by Http 1.0, because connection weren't persistent.
as of http 1.1 all connections are persistent by default, which means that this header is not used anymore.


text:
Q: how to get summation of pair(key) values in a map in java? I have a map which represents a matrix of string-int that maps to a value:
static Map<Pair<String,Integer>, Integer> wordTopic = new HashMap<>();

I want to get the summation of values that has a specific string (a part of the pair) not the whole pair Pair<String,Integer> AKA the summation of one row.
Example:  the matrix
string/int  1           2
value1      13            26
value2      11            22
i want the summation of row values of string "value1"  ..output should be =39
I have found this: Integer integerSum = wordTopic.values().stream().mapToInt(Integer::intValue).sum();

but this will get me the summation of the values of the whole key AKA the whole matrix ,i want the summation of the row only..any hints?

A: I presume this:
Input:
a-1 = 100
a-2 = 200
b-4 = 400
b-8 = 800

Output:
a = 300
b = 1200

Using map.entries() will probably help deal with the row more easily.
You seem to want to group by strings first, so a .group() lambda examining the Map.Entry.getKey().getValue0() would make a map of <String, List<Map.Entry>>
and for each one of those, you would do the desired .map & .sum, etc (left as homework...)
You can probably tell that a good old for loop with another hashmap is going to be more readable...

A: Assuming Pair is as follows.
public class Pair<T, U> {

    public final T first;
    public final U second;

    public static <T, U> Pair<T, U> of(T first, U second) {
        return new Pair<>(first, second);
    }

    public Pair(T first, U second) {
        this.first = first;
        this.second = second;
    }

}

Then how about:
    String wordToFilterFor = "abc";
    Integer integerSum = wordTopic.entrySet()
            .stream()
            .filter(entry -> entry.getKey().first.equals(wordToFilterFor))
            .map(e -> e.getValue())
            .mapToInt(Integer::intValue).sum();

Basically start the Stream with the entrySet, so that you have access to the Pair kay.  Then filter for the Pair's word.

A: You can create a function as such:
int getSummationOfValuesByKey(Map<Pair<String,Integer>, Integer> map, String key) {
          return map.entrySet()
                    .stream()
                    .filter(e -> e.getKey().getKey().equals(key))
                    .mapToInt(Map.Entry::getValue)
                    .sum();
}

which given a map and a key will return the summation of the values where the Pair's key is equal to the provided key.


text:
Q: Dissimilarity between point and centroid in a kmode cluster Is there a way to measure and plot the dissimilarity between cluster centroids and rows in a matrix - maybe without clustering both? The centroids are from previous cluster analysis. I have five cluster centroids and want to check if the rows in the matrix can be assigned to a cluster. Both are categorical data.
In [1]: matrixDf = array([['a', 'a', 'c', 'b', 'b'],
                          ['a', 'c', 'c', 'b', 'b'],
                          ['a', 'c', 'e', 'c', 'b'],
                          ['a', 'c', 'e', 'b', 'b'],
                          ...
                          ['a', 'a', 'c', 'c', 'b']])

In [10]: clusterCentroidsDf = pd.DataFrame(km_cao.cluster_centroids_)

Out [3]: clusterCentroidsDf = array([['c', 'a', 'a', 'c', 'b'],
                                     ['a', 'c', 'a', 'c', 'a'],
                                     ['b', 'f', 'b', 'd', 'c'],
                                     ['d', 'c', 'f', 'd', 'd'],
                                     ['d', 'e', 'd', 'c', 'b']])


text:
Q: Gaussian elemination method question? Change rows if neccessary We have the following system.I have to solve this using Gaussian elemination.
We have here
x1+x2+x4=2
2x1+x2-x3+x4=2
4x1-x2-2x3+2x4=0
3x1-x2-x3+2x4=-3
The augmented matrix is
\begin{matrix}
  1 & 1 & 0 & 1   | 2\\
  2 & 1 & -1&1   |1\\
  4 & -1 & -2 & 2 |0 \\
  3 & -1&  -1&2  |3
 \end{matrix}
I multiply the first row with -2 and add it to the second row.Then I multiply the first row with -3 and add it to the last row.So I have
\begin{matrix}
  1 & 1 & 0 & 1   | 2\\
  0 & -1 & -1&1   |-3\\
  4 & -1 & -2 & 2 |0 \\
  0 & -4&  -1&1  |-3
 \end{matrix}
How do I continue to solve this now?

A: First make zero all the entries on the first column behind the firsty entry:
$$\begin{pmatrix}1&1&0&1&2\\2&1&\!\!-1&1&2\\4&\!\!-1&\!\!-2&2&0\\3&\!\!-1&\!\!-1&2&\!\!-3\end{pmatrix}\stackrel{\begin{align}&R_2-R_1\\&R_3-4R_1\\&R_4-3R_1\end{align}}\longrightarrow\begin{pmatrix}1&1&0&1&2\\0&\!\!-1&\!\!-1&\!\!-1&\!\!-2\\0&\!\!-5&\!\!-2&\!\!-2&\!\!-8\\0&\!\!-4&\!\!-1&\!\!-1&\!\!-9\end{pmatrix}$$
Now the same with the entries on the second column below the $\;2-2\;$ entry (which is $\;-1\;$) , to get :
$$\begin{pmatrix}1&1&0&1&2\\0&\!\!-1&\!\!-1&\!\!-1&\!\!-2\\0&\;0&3&3&2\\0&0&3&3&\!\!-1\end{pmatrix}\stackrel{R_4-R_3}\longrightarrow\begin{pmatrix}1&1&0&1&2\\0&\!\!-1&\!\!-1&\!\!-1&\!\!-2\\0&\;0&3&3&2\\0&0&0&0&\!\!-3\end{pmatrix}$$
So what can you deduce from this?