text:
Q: How Would I Go About Making My Python Scoring System Work? I've been learning through an online course and I was trying to come up with ideas for things I could create to "test" myself as it were so I came up with a rock paper scissors game. It was working well so I decided to try and add a way of keeping track of your score vs the computer. Didn't go so well.
Here's what I have:
from random import randint

ai_score = 0
user_score = 0

def newgame():
    print('New Game')
    try:
        while(1):
            ai_guess = str(randint(1,3))
            print('\n1) Rock \n2) Paper \n3) Scissors')
            user_guess = input("Select An Option: ")

            if(user_guess == '1'):
                print('\nYou Selected Rock')

            elif(user_guess == '2'):
                print('\nYou Selected Paper')

            elif(user_guess == '3'):
                print('\nYou Selected Scissors')

            else:
                print('%s is not an option' % user_guess)

            if(user_guess == ai_guess):
                print('Draw - Please Try Again')
            elif (user_guess == '1' and ai_guess == '2'):
                print("AI Selected Paper")
                print("Paper Beats Rock")
                print("AI Wins!")
                ai_score += 1
                break
            elif (user_guess == '1' and ai_guess == '3'):
                print("AI Selected Scissors")
                print("Rock Beats Scissors")
                print("You Win!")
                user_score += 1
                break
            elif (user_guess == '2' and ai_guess == '1'):
                print("AI Selected Rock")
                print("Paper Beats Rock")
                print("You Win!")
                user_score += 1
                break
            elif (user_guess == '2' and ai_guess == '3'):
                print("AI Selected Scissors")
                print("Scissors Beats Paper")
                print("AI Wins!")
                ai_score += 1
                break
            elif (user_guess == '3' and ai_guess == '1'):
                print("AI Selected Rock")
                print("Rock Beats Scissors")
                print("AI Wins!")
                ai_score += 1
                break
            elif (user_guess == '3' and ai_guess == '2'):
                print("AI Selected Paper")
                print("Scissors Beats Paper")
                print("You Win!")
                user_score += 1
                break
            else:
                pass
                break

    except KeyboardInterrupt:
        print("\nKeyboard Interrupt - Exiting...")
        exit()

#1 = Rock, 2 = Paper, 3 = Scissors

def main():
    while(1):
        print("\n1) New Game \n2) View Score \n3) Exit")
        try:
            option = input("Select An Option: ")

            if option == '1':
                newgame()
            if option == '2':
                print("\nScores")
                print("Your Score: " + str(user_score))
                print("AI Score: " + str(ai_score))
            elif option == '3':
                print('\nExiting...')
                break
            else:
                print('%s is not an option' % option)
        except KeyboardInterrupt:
            print("\nKeyboard Interrupt - Exiting...")
            exit()

main()

I read somewhere that global variables can work but are generally frowned upon. Not sure why but then I can't say they're =0 so couldn't get that to work. Putting the ai_score and user_score in the newgame() doesn't work because it sets it to 0 every time you re run. Any help would be much appreciated.
As a quick extra note, the second
else:
   print('%s is not an option' % option)

in main() always seems to execute and always says "1 is not an option" and I have no idea why it does that. I would assume something to do with while loops but I need those to keep it running so an explanation of why and how to fix would be great. At the end of the day, I'm just here to learn more.

A: from random import randint

class newgame():

    ai_score = 0
    user_score = 0

    def __init__(self):
        self.ai_score = 0
        self.user_score = 0

    def playgame(self):
        print('New Game')
        try:
            while(1):
                ai_guess = str(randint(1,3))
                print('\n1) Rock \n2) Paper \n3) Scissors')
                user_guess = input("Select An Option: ")

                if(user_guess == '1'):
                    print('\nYou Selected Rock')

                elif(user_guess == '2'):
                    print('\nYou Selected Paper')

                elif(user_guess == '3'):
                    print('\nYou Selected Scissors')

                else:
                    print('%s is not an option' % user_guess)

                if(user_guess == ai_guess):
                    print('Draw - Please Try Again')
                elif (user_guess == '1' and ai_guess == '2'):
                    print("AI Selected Paper")
                    print("Paper Beats Rock")
                    print("AI Wins!")
                    self.ai_score += 1
                    break
                elif (user_guess == '1' and ai_guess == '3'):
                    print("AI Selected Scissors")
                    print("Rock Beats Scissors")
                    print("You Win!")
                    self.user_score += 1
                    break
                elif (user_guess == '2' and ai_guess == '1'):
                    print("AI Selected Rock")
                    print("Paper Beats Rock")
                    print("You Win!")
                    self.user_score += 1
                    break
                elif (user_guess == '2' and ai_guess == '3'):
                    print("AI Selected Scissors")
                    print("Scissors Beats Paper")
                    print("AI Wins!")
                    self.ai_score += 1
                    break
                elif (user_guess == '3' and ai_guess == '1'):
                    print("AI Selected Rock")
                    print("Rock Beats Scissors")
                    print("AI Wins!")
                    self.ai_score += 1
                    break
                elif (user_guess == '3' and ai_guess == '2'):
                    print("AI Selected Paper")
                    print("Scissors Beats Paper")
                    print("You Win!")
                    self.user_score += 1
                    break
                else:
                    pass
                    break

        except KeyboardInterrupt:
            print("\nKeyboard Interrupt - Exiting...")
            exit()

    #1 = Rock, 2 = Paper, 3 = Scissors

def main():
    game_object = newgame()
    while(1):
        print("\n1) New Game \n2) View Score \n3) Exit")
        try:
            option = input("Select An Option: ")

            if option == '1':
                game_object.playgame()
            elif option == '2':
                print("\nScores")
                print("Your Score: " + str(game_object.user_score))
                print("AI Score: " + str(game_object.ai_score))
            elif option == '3':
                print('\nExiting...')
                break
            else:
                print('%s is not an option' % option)
        except KeyboardInterrupt:
            print("\nKeyboard Interrupt - Exiting...")
            exit()

main()

Classes are wonderful. __init__ is  the constructor for this class. It basically makes the object instant for the class and sets the variable to what you want. game_object = newgame() makes the class object and stores it into game_object. To get the class variable of the game_object, we use game_object.ai_score. Since you made a class object it's class variables are still in scope of the object you made, even though it might be outside of your function. Generally, if I need to use a variable outside of a function, and is tempted to use Global, I make a class instead. There are some cases where you wouldn't want this, but personally I haven't come across one. Also you might want to look into like what the comments were saying about using dictionary as options. Any other questions?
Edit:
To answer your new question about print('%s is not an option' % option) always running, is because in your code you had if option == '1': and then if option == '2': You want the option 2 to be elif. I fixed it in my code. If statements are in blocks. since you started a new if, the else didn't check first first if to see if it's a valid option. It was out of it's scope in a sense. So since your code was basically saying is option equal to 1? is it equal to 2 or 3 or anything else? notice these are two different questions?

A: It seems that  the variable option is not '1', right ? Well, that's because the function input does not return a character string, but an integer. You can see this by adding a little trace in this program.
print (option, type (option))

after a line where the variable option has been set.
This will tell you of what type is the variable option, in that case it is an integer. So first, you need to replace the comparisons against strings (like  if option == '1':  by comparisons against integers, that is : if option == 1:.
As for the second question : variables declared or assigned inside of a function exist for the scope of that function only. If you need to use a variable inside a function that has outer scope, it should be redeclared inside the function as global (even if they are "frowned upon" -- and there are good reasons for this). At the beginning of def newgame(): you need to declare again your global variables : global ai_score, user_score. You can also use classes to get familiar with object oriented programming and write nicer code. There is an other error left in this program, but I'm sure you'll find out.

A: At least one problem is this: your main has if...if...elif...else. The second if probably needs to be an elif. Tip: When you have a flow-of-control problem, put print statements inside each control branch, printing out the control variable and everything else that might possibly be relevant. This tells you which branch is being taken -- in this case, which branches, plural.
You don't say exactly what the problem was with keeping score, but I imagine it was an exception along the lines of variable referenced before assignment. If so, you should put "global ai_score" somewhere at the top of the function. What's going on is that Python can, but doesn't like to, recognize variables outside a function that are being used inside the function. You have to push a little. Consider:
>>> bleem = 0
>>> def incrbleem():
...   bleem += 1
...
>>> incrbleem()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in incrbleem
UnboundLocalError: local variable 'bleem' referenced before assignment
>>> def incrbleem():
...   global bleem
...   bleem += 1
...
>>> bleem
0
>>> incrbleem()
>>> bleem
1

By the way, your code isn't bad at all, for a newbie.  I've seen much, much worse! For what it's worth, I don't think global variables are bad for a small, throw-away program like this. Once you have two programmers, or two threads, or two months between work sessions on the program, globals can definitely cause problems.


text:
Q: how to fetch testplans from rally through python pyral API I am trying to fetch test-plan details from Rally tool.
We have user-story,defects,release arguments to fetch respective data.
I want to understand how to fetch test plans from rally through python pyral  API

A: This worked for me...
$ cat -n tf.py
 1  import sys
 2  import re
 3
 4  if sys.version_info[0] < 3:
 5      print ("ERROR: This script is using Python version %s" % (sys.version_info[0]))
 6      print ("       It must be using Python 3 or greater")
 7      exit(-1)
 8
 9  from pyral import Rally, rallyWorkset
10
11  options = [arg for arg in sys.argv[1:] if arg.startswith('--')]
12  args    = [arg for arg in sys.argv[1:] if arg not in options]
13  server, user, password, apikey, workspace, project = rallyWorkset(options)
14
15  print("Using Python version '%s'" % sys.version_info[0])
16  print("Connecting to Rally with options:")
17  print("\t   server: %s" % server)
18  print("\t     user: %s" % user)
19  hidden_apikey = apikey[:4] + re.sub(".",".",apikey[4:-4]) + apikey[-4:]
20  print("\t   apikey: %s" % hidden_apikey)
21  print("\tworkspace: %s" % workspace)
22  print("\t  project: %s" % project)
23
24  rally = Rally(server, user, password, apikey, workspace=workspace, project=project)
25
26  testfolders = rally.get('TestFolder', fetch=True, query='')
27  folders_found = testfolders.resultCount
28  print ("TestFolders found: %s" % folders_found)
29
30  for folder_index,folder in enumerate(testfolders, start=1):
31      print ("\ttestfolder (%s of %s): FormattedID=%s  ObjectID=%s  Name='%s'" %
32          (folder_index, folders_found, folder.FormattedID,folder.ObjectID,folder.Name))

Command line:
$ python ./tf.py --user=wiley.com@acme.com  --password=coyote  --workspace=WS-test  --project='Sample'

Output:
Using Python version '3'
Connecting to Rally with options:
       server: rally1.rallydev.com
         user: wiley@acme.com
    workspace: WS-test
      project: Sample
TestFolders found: 2
  testfolder (1 of 2): FormattedID=TF1  ObjectID=229499794780  Name='JP 1st TestFolder'
  testfolder (2 of 2): FormattedID=TF3  ObjectID=289446576888  Name='JP 2nd TestFolder'

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting rid of the root $(x-\sqrt[3]{x^3-1})$ How should I get rid of the 3rd root $$(x-\sqrt[3]{x^3-1})?$$
I know how to use $(\sqrt{a}+\sqrt{b})(\sqrt{a}-\sqrt{b})=a-b$ but what can I do in this case?

A: HINT:
Recall that
$$x^3-y^3=(x-y)(x^2+xy+y^2)$$
Now, let $y=\sqrt[3]{x^3-1}$


text:
Q: jQuery dialog box is not opening 2nd time I found this thread which basically has the same issue I have. But their solution is not working for me.
Here is my code :
$(document).ready(function() {

    // create the loading window and set autoOpen to false
    $("#loadingScreen").dialog({
        autoOpen: false,    // set this to false so we can manually open it
        dialogClass: "loadingScreenWindow",
        closeOnEscape: false,
        draggable: false,
        width: 460,
        minHeight: 50,
        modal: true,
        buttons: {},
        resizable: false,
        open: function() {
            // scrollbar fix for IE
            $('body').css('overflow','hidden');
        },
        close: function() {
            // reset overflow
            $('body').css('overflow','auto');
        }
    }); // end of dialog

});

function waitingDialog(waiting) {
    $("#loadingScreen").html(waiting.message && '' != waiting.message ? waiting.message : 'Bekleyin...');
    $("#loadingScreen").dialog('option', 'title', waiting.title && '' != waiting.title ? waiting.title : 'Yükleniyor');
    $("#loadingScreen").dialog('open');
}

Thank you...

A: use $("#loadingScreen").dialog('option' .... just once, and then call $("#loadingScreen").dialog('open') as many times as you need


text:
Q: How to make a program which loops over all saved photos on Instagram I am in the process of creating a program for saving Instagram photos from "Saved" area of the page.
There are 2 elements:

*

*"chevrones", which allow you to switch photos inside a multi-publication;

*right arrow", which allow you to move to a next publication.

I want to create a program which goes through all saved photos. If there is a chevron the program should loop through all photos inside this multiple photo publication (click on chevron when it is available). If there is no chevron available when the program should move to the next saved photo (click on the next arrow).
My question is: How to write the proper "IF clause" for 1)firstly loop inside a multiple-publication and 2)then (when all the photos inside multi-pub will finished) go to a next publication.
So far I have following code:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import java.util.List;

public class TestSelenium {
    public static void main(String[] args){
        WebElement img;
        String src;
        int i =0;

// Set webdriver option
        System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Common Files\\Oracle\\Java\\Webdrivers\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.instagram.com/accounts/login/");
// Set waits
        WebDriverWait wait = new WebDriverWait(driver, 5);

// Write down the login
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input[name='username']"))).sendKeys("%%MY_INSTA_LOGGIN%%");
// Write down the password
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input[name='password']"))).sendKeys("%%MY_INSTA_PASSWORD%%");
// Click on the Signin button
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("button[type='submit']"))).click();

// Go to the saved page
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div[class='SKguc']"))).click();
        driver.get("https://www.instagram.com/aleksandrqa/saved/");

// Click on the first element
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div[class='eLAPa']"))).click();

            // Click on the next chevron
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("a[class='SWk3c  Zk-Zb coreSpriteRightChevron']"))).click();

            // Click on the next arrow
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("a[class='HBoOv coreSpriteRightPaginationArrow']"))).click();

// TODO
// Save all photos URLs

    }
}

A: You can identify an next image > arrow using the below xpath :
String xpath = "//div[contains(@class, 'RightChevron')]";

If you move to the last image then the above xpath will not return any matches because that image > arrow is not present for the last/single image.
To check whether the locator is present or not without handling any exceptions, you can use the findElements() method like below :
List<WebElement> imageArrow = driver.findElements(By.xpath(xpath));
if(imageArrow.size() > 0) {
    System.out.println("=> The image arrow is present...");
    // Perform some action here
} else {
    System.out.println("=> The image arrow is not present...");
}

If the list size is greater than zero then there is an arrow otherwise not, so the below code will loop through until the size is greater than zero and will click on the image arrow.
boolean isThereAnArrow = true;
while(isThereAnArrow) {
    final String xpath = "//div[contains(@class, 'RightChevron')]";
    List<WebElement> imageArrow = driver.findElements(By.xpath(xpath));
    if(imageArrow.size() > 0) {
        System.out.println("=> The image arrow is present...");
        imageArrow.get(0).click(); // Clicking on the image arrow
    } else {
        System.out.println("=> The image arrow is not present...");
        isThereAnArrow = false; // If there is no match then it will help us to break the loop
    }

}
Same like an above, you can check for the posts next > arrow. Below is the whole code which clicks on the image > arrow if its present or it will click on the next post button until there are some posts.
boolean isThereNextPostArrow = true;
while(isThereNextPostArrow) {
    // Checks for the next '>' image arrow, if not then will break the loop
    // ---------------------------------------------------------------------------
    boolean isThereAnArrow = true;
    while(isThereAnArrow) {
        final String xpath = "//div[contains(@class, 'RightChevron')]";
        List<WebElement> imageArrow = driver.findElements(By.xpath(xpath));
        if(imageArrow.size() > 0) {
            System.out.println("=> The image arrow is present...");

            // Do something here

            imageArrow.get(0).click(); // Clicking on the image arrow
        } else {
            System.out.println("=> The image arrow is not present...");
            isThereAnArrow = false; // If there is no match then it will help us to break the loop
        }
    }
    // ---------------------------------------------------------------------------
    // Checks for the next '>' post arrow, if not then will break the loop
    List<WebElement> nextPost = driver.findElements(By.xpath("//a[contains(@class, 'PaginationArrow')]"));
    if(nextPost.size() > 0) {
        System.out.println("=> The next post arrow is there...");
        nextPost.get(0).click(); // Clicking on the next post
    } else {
        System.out.println("=> The next post arrow is not there...");
        isThereNextPostArrow = false; // If there is no match then it will help us to break the outer loop
    }
}

I hope it helps...


text:
Q: Calculating quantile of distribution function I'm having a problem with a statitics example.
The calculation for my quantile is not difficult. But I'm wondering which part of my function I need to use.
Let's say my distribution function is like:
$$ F(x)=\begin{cases} \frac {1}{4} x - \frac {3}{2} & \mbox{for } 6 \le x \le 8 \\
\frac {5}{2} - \frac {1}{4} x & \mbox{for } 8 < x \le 10 \\
0 & \mbox{else} \end{cases} $$
Now. If I need to calculate a Quantile - 0.7 or 0.3 - I know that $ F(x) = 0.3 $, but how do I know which part of my function I need to use?

A:
The only important "transition" from one formula to another occurs at $x=8$. By finding $F(8)$, which turns out to be $1/2$, you discover that if you want, for example, to find out where $F(x)=0.2$, you need to find where $\frac{1}{4}x-3/2=0.2$. If on the other hand you want to find out where $F(x)=0.9$, then since $0.9\gt F(8)=1/2$, you need to find out where $\frac{5}{2}-\frac{1}{4}x=0.9$.

-- André Nicolas


text:
Q: Two Switches to Control a Pump I have a water tank that I want to fill up with a well. I have a float switch at the top of the tank and another float switch in the middle of the tank. What I want to do is have the pump only turn on when the middle tank switch opens and to keep pumping until the top switch closes.
This is trivial with a microcontroller but I feel there must be a way to do this with solid-state components. I can convert logic-level to what is needed to drive my contactor - I just need to get the actual logic circuit sorted out. I feel I'm missing something obvious and would appreciate any guidance. Thanks!

A:
simulate this circuit – Schematic created using CircuitLab
Figure 1. Pump control circuit.
How it works:

*

*As the tank empties the TOP switch closes first.

*When it passes the low-level switch it closes and RLY1 is energised.

*The pump starts via contact RLY1b.

*Meanwhile RLY1a bridges out MIDDLE so that the pump continues to run as the water level passes that switch.

*RLY1 remains latched on until the top switch is opened.

Rate the relay coil for your control voltage. Rate the relay contacts for your pump voltage, AC or DC as required, and pump starting current.


text:
Q: Simple logarithmic question (fundamentals) I'm studying Asymptotic Analysis and I need to refresh the log functions, so on this particular case:
$(log\ N)^3$ what would that be equal to? is it:
$log^3(N)$ ?   which would be $log(log(log(N)))$ right? I'm a little confused... lol
In case someone knows:
Why $f(N) = N! + 2^n$ the upper bound using Big O is: $O(N^n)$ ?
isn't N! in the long run greater than $2^n$? and why is it $n^n$ and not $2^n$?
Thank you

A: $\log(N)^3$ is exactly what it appears to be: the cube of the logarithm of $N$. However, you are right to note that $\log^3(N)$ is ambiguous. The convention is that $\log^3(N) = \log(N)^3$, but it would be more consistent mathematically to have it mean $\log(\log(\log(N)))$. But it's convention that matters, so $\log^3(N) = \log(N)^3$. (And of course none of these should be confused with $\log(N^3)$.)
Your factorial question is kind of unrelated, but Stirling's approximation tells us that $n! \approx (n/e)^n\sqrt{2\pi n}$. This dominates all exponential functions, but grows slower than $n^n$. So $n! = O(n^n)$ is true, but $n! = O(a^n)$ is false for all $a$.


text:
Q: webpack : AngularJS 1.6.1(ES6) and SCSS packaging Somebody can help me on configuring webpack for following requirements

*

*AngularJS (1.6) ES6 to ES5 converstion

*SCSS to CSS compiler

*All js to single bundle

*All css to single bundle

*All folder structure should created with html only ( no js files, since we alrady bundling it )

This is what I have tried so far
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
    entry: path.resolve(__dirname, './app/app.module.js'),
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: 'bundle.js'
    },
    module: {
        loaders: [{
            test: /\.js$/,
            loader: 'babel-loader',
            exclude: /node_modules/
        },
        { test: /\.scss$/, loader: 'style-loader!css-loader!sass-loader'},
        {
            test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
            loader: 'url?limit=10000&minetype=application/font-woff'
        },
        {
            test: /\.woff2$/,
            loader: 'url?limit=10000&minetype=application/font-woff'
        },
        {
            test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
            loader: 'url?limit=10000&minetype=application/octet-stream'
        },
        {
            test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
            loader: 'file'
        },
        {
            test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
            loader: 'url?limit=10000&minetype=image/svg+xml'
        }
        ]
    },
    plugins: [
        //new ExtractTextPlugin("styles.css"),
    ]
};

A: Updated webpack conf
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
  entry: path.resolve(__dirname, './app/app.module.js'),
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  devtool: 'source-map',
  module: {
    loaders: [{
      test: /\.js$/,
      loader: 'babel-loader',
      exclude: /node_modules/,
      query: {
        presets: ['es2015']
      }
    }, {
      test: /\.css$/,
      loader: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: 'css-loader'
      })
    }, {
      test: /\.woff($|\?)|\.woff2($|\?)|\.ttf($|\?)|\.eot($|\?)|\.svg($|\?)/,
      loader: 'file-loader?name=[name].[ext]&publicPath=../fonts/&outputPath=/assets/fonts/'
    },
            { test: /\.(jpe?g|png|gif)$/i, loader: 'file-loader?name=/assets/images/[name].[ext]' },
    {
      test: /\.(html)$/,
      loader: 'file-loader?name=[path][name].[ext]'
    },
    {
      test: /\.(json)$/,
      loader: 'file-loader?name=[path][name].[ext]'
    },
    {
      test: /\.scss$/,
      loader: ExtractTextPlugin.extract({
        use: [{
          loader: 'css-loader'
        }, {
          loader: 'sass-loader' // compiles Sass to CSS
        }],
        fallback: 'style-loader'
      })
    }
    ]
  },
  plugins: [
    new ExtractTextPlugin('assets/css/styles.css')
  ]
};

sample project with webpack configured posted it in my github


text:
Q: How does jsp work? I am wondering does JSP ever get compiled ? The reasons why that I am asking is because whenever I deploy my Java EE application on the web server I only see those servlet and beans class file in the WEB-INF folder as they are compiled, but not that JSP, so how does it work, and what's the logical flow and the big picture of the normal request/response cycle.

A: Yes, they are compiled!
Older compilers even produced java and class files.
Looks like with newer compilers ( at least starting with Sun JDK 6 update 30 ), they can do all the byte-code generation in-memory, so you do not see any traces in your application work or temp directories.

A: JSPs compile to Servlets. They just have a special compiler that is typically embedded in the container.
From good ole wikipedia:

Architecturally, JSP may be viewed as a high-level abstraction of Java servlets. JSPs are translated into servlets at runtime; each JSP's servlet is cached and re-used until the original JSP is modified.

A: Basically:

*

*In your servlet container, the JSP servlet is mapped to any URL that ends in .jsp (usually)

*When one of those .jsp URLs is requested, the request goes to the JSP servlet. Then, this servlet checks if the JSP is already compiled.

*If the JSP is not compiled yet, the JSP servlet translates the JSP to some Java source code implementing the Servlet interface. Then it compiles this Java source code to a .class file. This .class file usually is located somewhere in the servlet container's work directory for the application.

*Once the JSP servlet has compiled the servlet class from the JSP source code, it just forwards the request to this servlet class.
The thing is, unless you specifically precompile your JSP, all this happens at runtime, and hidden in the servlet container's work directory, so it is "invisible". Also have in mind that this is what happens "conceptually", several optimizations are possible in this workflow.

A: At run time, the JSP code is interpreted by the
JSP compiler, which parses out all the special features in the JSP code and translates them to Java
code. The Java class created from each JSP implements Servlet. Then, the Java code goes through
the same cycle it normally does. Still at run time, it is compiled into bytecode and then into machine
code. Finally, the JSP-turned-Servlet responds to requests like any other Servlet.
If you look at the *_jsp.java file, what you should find is a class that extends org.apache.jasper.runtime.HttpJspBase. This
abstract class extends HttpServlet. HttpJspBase provides some base
functionality that will be used by all JSPs that Tomcat compiles, and when your JSP is executed,
ultimately the service method on that Servlet is executed, which eventually executes the
_jspService method.
If you inspect the _jspService method, you'll find a series of method calls writing your HTML to
the output stream. This code should look very familiar to you because it's not that different from
the Java code that you replaced with this JSP.
Of course, the JSP Servlet class does not look the same
on every web container. The org.apache.jasper classes, for example, are Tomcat-specific classes.
Your JSP compiles differently on each different web container you run it on. The important point
is that there is a standard specification for the behavior and syntax of JSPs, and as long as the web
containers you use are compliant with the specification, your JSPs should run the same on all of
them, even if the Java code they get translated into looks completely different.
Taken (and paraphrased) from Professional Java for Web Applications by Nicholas S Williams


text:
Q: In Xcode, is it possible to reuse intermedian objects from i386 configuration where building with universal configuration? My application should be built as both of x86 and universal(x86 & x86_64) versions. As a result, every source file, says file A, must be compiled three times:

*

*As i386, when building with the x86 configuration

*As i386, when building with universal configuration

*As x86, when building with universal configuration

Since A has already be compiled as i386 when building with x86 configuration, could the universal configuration reuses objects from x86 configuration?
I found the intermedian objects resided under simliar path: Objects-normal/{i386,x86_64}. So could I set the intermedian object path of both configurations into a same path? So that, the universal building could reuse objects from x86 build?
I have not tried it, and just want to known whether anyone has tried this before?

A: Just build the universal version and then if you really need an i386-only version as well you can add a post build step which uses lipo to generate the "thin" version of the executable.


text:
Q: Recover files from LUKS-encrypted partition I have a partition encrypted with LUKS. I used it without problems every day until suddenly the password stopped working. Is there anything I can do?
I have tried with a different keyboard and from a different computer. I am 100% certain that I typed in the correct password. So (correct me if I am wrong) it seems to me that my hard disk must be corrupted. If this is the case, is it reasonable to assume that only one byte is corrupted, and if yes, can I try all possible one byte changes of the partition header?
EDIT: I should have mentioned that the encrypted partition contains /, so it was always in use. I don't know if LUKS does any write protection though.

A: You should restore from your backup.  If you have no backup then you are screwed.  That is the entire point of full-disk-encryption.  There are methods to restore a corrupt luks header, but you would have had to make a backup of the header first.
See: cryptsetup FAQ - Backup and Data Recovery
The idea that you could somehow try all the possible changes if one byte was off is extremely silly, unless you know exactly which byte was broken.
Lets pretend for a second that your the header was only 1megabyte (it is bigger, I believe it is ~2MB).  Then the number of possible changes is 2**(8,388,608) (or 4.2644×10^2,525,222) even if you could try a billion different possible changes per second you would still be attempting changes well past the time when our sun destroys our planet.


text:
Q: Debian: How to get rid of half-installed packages after aborted installation of kde-standard? I accidentally executed "apt-get install kde-standard" on a system with a very small root partition (6 GB). The installation stopped when the disk was full. You can imagine the mess I have on the system now.
apt-get * says: "301 not fully installed or removed."
Is there a way to remove all packages that came with kde-standard?

A: I think this will work:
apt-get purge kde-standard
apt-get autoremove

A: So, while there are better ways to do this, this one worked for me: set up a new machine (debian wheezy), run
apt-get update
apt-get dist-upgrade
apt-get install kde-standard

then copy the list of 748 packages and remove them on the first machine. Looks like this:
apt-get purge acl akonadi-backend-mysql akonadi-server akregator ark aspell aspell-en binutils colord consolekit cpp cpp-4.7 crda     cryptsetup-bin dbus dbus-x11 dconf-gsettings-backend dconf-service dnsmasq-base docbook-xml docbook-xsl dolphin dosfstools  dragonplayer enchant fontconfig fontconfig-config fonts-droid fonts-freefont-ttf freespacenotifier fuse gconf-service gconf2  gconf2-common ghostscript gnupg-agent gnupg2 gsfonts gwenview hdparm hicolor-icon-theme htdig hunspell-en-us imagemagick  imagemagick-common iw juk kaddressbook kamera kate kate-data katepart kcalc kde-baseapps kde-baseapps-bin kde-baseapps-data  kde-plasma-desktop kde-runtime kde-runtime-data kde-standard kde-style-oxygen kde-wallpapers kde-wallpapers-default  kde-window-manager kde-workspace kde-workspace-bin kde-workspace-data kde-workspace-kgreet-plugins kdebase-runtime  kdelibs-bin kdelibs5-data kdelibs5-plugins kdepasswd kdepim-runtime kdepimlibs-kio-plugins kdeplasma-addons kdm kdoctools  kfind khelpcenter4 kinfocenter klipper kmail kmenuedit kmix knotes konq-plugins konqueror konqueror-nsplugins konsole kopete  korganizer kscreensaver kscreensaver-xsavers ksnapshot ksysguard ksysguardd kwalletmanager kwrite liba52-0.7.4 libaa1  libaacs0 libaio1 libakonadi-contact4 libakonadi-kabc4 libakonadi-kcal4 libakonadi-kde4 libakonadi-kmime4  libakonadiprotocolinternals1 libarchive12 libasound2 libaspell15 libass4 libassuan0 libasyncns0 libatasmart4 libatk1.0-0  libatk1.0-data libattica0 libaudio2 libaudit0 libavahi-client3 libavahi-common-data libavahi-common3 libavc1394-0  libavcodec53 libavformat53 libavutil51 libbluetooth3 libbluray1 libboost-program-options1.49.0 libcaca0 libcairo-gobject2  libcairo2 libcanberra-gtk3-0 libcanberra-gtk3-module libcanberra0 libcddb2 libcdio13 libck-connector0 libcln6 libclucene0ldbl  libcolord1 libcroco3 libcryptsetup4 libcrystalhd3 libcups2 libcupsimage2 libcurl3-gnutls libdatrie1 libdbus-1-3  libdbus-glib-1-2 libdbusmenu-qt2 libdc1394-22 libdca0 libdconf0 libdevmapper-event1.02.1 libdirac-decoder0 libdirac-encoder0  libdirectfb-1.2-9 libdjvulibre-text libdjvulibre21 libdlrestrictions1 libdmtx0a libdrm-intel1 libdrm-nouveau1a libdrm-radeon1  libdrm2 libdvbpsi7 libdvdnav4 libdvdread4 libebml3 libenca0 libenchant1c2a libencode-locale-perl libexif12 libexiv2-12  libfaad2 libfam0 libffi5 libfile-basedir-perl libfile-copy-recursive-perl libfile-desktopentry-perl libfile-listing-perl  libfile-mimeinfo-perl libflac8 libfont-afm-perl libfontconfig1 libfontenc1 libfribidi0 libgadu3 libgconf-2-4 libgd2-xpm  libgdk-pixbuf2.0-0 libgdk-pixbuf2.0-common libgif4 libgl1-mesa-dri libgl1-mesa-glx libglapi-mesa libgle3 libglib2.0-0  libglib2.0-data libglu1-mesa libgmp10 libgomp1 libgpgme++2 libgphoto2-2 libgphoto2-l10n libgphoto2-port0 libgps20 libgs9  libgs9-common libgsm1 libgstreamer-plugins-base0.10-0 libgstreamer0.10-0 libgtk-3-0 libgtk-3-bin libgtk-3-common libgtk2.0-0  libgtk2.0-bin libgtk2.0-common libgudev-1.0-0 libgusb2 libhtml-form-perl libhtml-format-perl libhtml-parser-perl  libhtml-tagset-perl libhtml-tree-perl libhttp-cookies-perl libhttp-daemon-perl libhttp-date-perl libhttp-message-perl  libhttp-negotiate-perl libhunspell-1.3-0 libical0 libice6 libieee1284-3 libijs-0.35 libilmbase6 libimobiledevice2  libio-socket-ip-perl libio-socket-ssl-perl libiodbc2 libiso9660-8 libjasper1 libjbig0 libjbig2dec0 libjim0debian2  libjpeg-progs libjpeg8 libjson0 libkabc4 libkactivities-bin libkactivities6 libkate1 libkateinterfaces4  libkatepartinterfaces4 libkcal4 libkcalcore4 libkcalutils4 libkcmutils4 libkde3support4 libkdeclarative5 libkdecorations4  libkdecore5 libkdepim4 libkdesu5 libkdeui5 libkdewebkit5 libkdnssd4 libkemoticons4 libkephal4abi1 libkexiv2-10 libkexiv2-data  libkfile4 libkholidays4 libkhtml5 libkidletime4 libkimap4 libkimproxy4 libkio5 libkipi-data libkipi8 libkjsapi4 libkjsembed4  libkldap4 libkleo4 libkmediaplayer4 libkmime4 libknewstuff2-4 libknewstuff3-4 libknotifyconfig4 libkntlm4 libkonq-common  libkonq5-templates libkonq5abi1 libkonqsidebarplugin4a libkontactinterface4 libkopete4 libkparts4 libkpgp4 libkpimidentities4  libkpimtextedit4 libkpimutils4 libkprintutils4 libkpty4 libkresources4 libkrosscore4 libksba8 libkscreensaver5 libksgrd4  libksieve4 libksignalplotter4 libktexteditor4 libktnef4 libkunitconversion4 libkutils4 libkwineffects1abi3 libkwinglutils1  libkworkspace4abi1 liblcms1 liblcms2-2 liblensfun-data liblensfun0 liblircclient0 liblqr-1-0 libltdl7 liblua5.1-0  liblvm2app2.2 liblwp-mediatypes-perl liblwp-protocol-https-perl liblzo2-2 libmad0 libmagickcore5 libmagickcore5-extra  libmagickwand5 libmailtools-perl libmailtransport4 libmarblewidget13 libmatroska5 libmeanwhile1 libmediastreamer1  libmessagecore4 libmessagelist4 libmhash2 libmicroblog4 libmimelib4 libmng1 libmodplug1 libmozjs10d libmp3lame0 libmpc2  libmpcdec6 libmpeg2-4 libmpfr4 libmsn0.3 libmtdev1 libmtp-common libmtp-runtime libmtp9 libmysqlclient18 libnepomuk4  libnepomukquery4a libnepomukutils4 libnet-dbus-perl libnet-http-perl libnet-ssleay-perl libnetfilter-conntrack3 libnetpbm10  libnettle4 libnl-3-200 libnl-genl-3-200 libnl-route-3-200 libnm-glib-vpn1 libnm-glib4 libnm-util2 libnotify4 libnspr4  libntrack-qt4-1 libntrack0 libogg0 libokularcore1 libopenexr6 libopenjpeg2 liborc-0.4-0 libortp8 libotr2 libpam-ck-connector  libpango1.0-0 libpaper-utils libpaper1 libparted0debian1 libpcap0.8 libpciaccess0 libpcsclite1 libphonon4 libpixman-1-0  libpkcs11-helper1 libplasma-geolocation-interface4 libplasma3 libplasmaclock4abi3 libplasmagenericshell4 libplist1 libpng12-0  libpolkit-agent-1-0 libpolkit-backend-1-0 libpolkit-gobject-1-0 libpolkit-qt-1-1 libpoppler-qt4-3 libpoppler19 libpostproc52  libprison0 libprocesscore4abi1 libprocessui4a libproxy0 libpulse-mainloop-glib0 libpulse0 libpython2.7 libqalculate5  libqalculate5-data libqca2 libqca2-plugin-ossl libqgpgme1 libqimageblitz4 libqrencode3 libqt4-dbus libqt4-declarative  libqt4-designer libqt4-help libqt4-network libqt4-opengl libqt4-qt3support libqt4-script libqt4-scripttools libqt4-sql  libqt4-sql-mysql libqt4-sql-sqlite libqt4-svg libqt4-test libqt4-xml libqt4-xmlpatterns libqtassistantclient4 libqtcore4  libqtdbus4 libqtgui4 libqtlocation1 libqtruby4shared2 libqtwebkit4 libraptor2-0 librasqal3 libraw1394-11 librdf0 libreadline5  libresid-builder0c2a librsvg2-2 librsvg2-common librtmp0 libruby1.8 libsamplerate0 libsane libsane-common libsane-extras  libsane-extras-common libschroedinger-1.0-0 libsdl-image1.2 libsdl1.2debian libsensors4 libsgutils2-2 libshout3 libsidplay2  libsm6 libsmbclient libsmokebase3 libsmokekdecore4-3 libsmokekdeui4-3 libsmokekfile3 libsmokekhtml3 libsmokekio3  libsmokeknewstuff2-3 libsmokeknewstuff3-3 libsmokekparts3 libsmokektexteditor3 libsmokekutils3 libsmokenepomuk3  libsmokeplasma3 libsmokeqtcore4-3 libsmokeqtdbus4-3 libsmokeqtgui4-3 libsmokeqtnetwork4-3 libsmokeqtopengl4-3  libsmokeqtsql4-3 libsmokeqtsvg4-3 libsmokeqtwebkit4-3 libsmokeqtxml4-3 libsmokesolid3 libsndfile1 libsocket-perl libsolid4  libsolidcontrol4abi2 libsolidcontrolifaces4abi2 libsoprano4 libspandsp2 libspectre1 libspeex1 libspeexdsp1 libsrtp0 libssh-4  libssh2-1 libstreamanalyzer0 libstreams0 libswscale2 libsyndication4 libsystemd-login0 libtag1-vanilla libtag1c2a libtalloc2  libtar0 libtaskmanager4abi3 libtdb1 libthai-data libthai0 libtheora0 libthreadweaver4 libtidy-0.99-0 libtie-ixhash-perl  libtiff4 libtimedate-perl libts-0.0-0 libtwolame0 libupnp6 libupower-glib1 liburi-perl libusbmuxd1 libutempter0 libv4l-0  libv4lconvert0 libva-x11-1 libva1 libvcdinfo0 libvirtodbc0 libvlc5 libvlccore5 libvorbis0a libvorbisenc2 libvorbisfile3  libvpx1 libwbclient0 libweather-ion6 libwebp2 libwmf0.2-7 libwww-perl libwww-robotrules-perl libx11-protocol-perl libx11-xcb1  libx264-123 libx86-1 libxaw7 libxcb-composite0 libxcb-dri2-0 libxcb-glx0 libxcb-keysyms1 libxcb-randr0 libxcb-render0  libxcb-shape0 libxcb-shm0 libxcb-util0 libxcb-xfixes0 libxcb-xv0 libxcomposite1 libxcursor1 libxdamage1 libxfixes3 libxfont1  libxft2 libxi6 libxinerama1 libxkbfile1 libxml-parser-perl libxml-twig-perl libxml-xpathengine-perl libxml2-utils libxmu6  libxpm4 libxrandr2 libxrender1 libxslt1.1 libxss1 libxt6 libxtst6 libxv1 libxvidcore4 libxvmc1 libxxf86dga1 libxxf86vm1  libyajl2 libzvbi-common libzvbi0 lockfile-progs marble-data marble-plugins mobile-broadband-provider-info modemmanager  mysql-common mysql-server-core-5.5 netpbm network-manager network-manager-openvpn network-manager-pptp network-manager-vpnc  notification-daemon ntfs-3g ntrack-module-libnl-0 odbcinst odbcinst1debian2 okular openvpn oxygen-icon-theme oxygencursors  p7zip-full phonon phonon-backend-vlc pinentry-gtk2 plasma-containments-addons plasma-dataengines-addons  plasma-dataengines-workspace plasma-desktop plasma-desktopthemes-artwork plasma-runners-addons plasma-scriptengine-javascript  plasma-scriptengine-python plasma-scriptengine-ruby plasma-scriptengine-superkaramba plasma-scriptengine-webkit  plasma-scriptengines plasma-wallpapers-addons plasma-widget-folderview plasma-widget-lancelot plasma-widget-networkmanagement  plasma-widgets-addons plasma-widgets-workspace pm-utils policykit-1 polkit-kde-1 poppler-data powermgmt-base ppp pptp-linux  python-dbus python-dbus-dev python-kde4 python-qt4 python-qt4-dbus python-sip qdbus ruby-kde4 ruby-plasma ruby-qt4  ruby-qt4-webkit ruby1.8 sane-utils sgml-data shared-desktop-ontologies shared-mime-info soprano-daemon sweeper systemsettings  tsconf ttf-dejavu ttf-dejavu-core ttf-dejavu-extra udisks ufraw-batch unzip update-inetd upower usb-modeswitch  usb-modeswitch-data usbmuxd vbetool virtuoso-minimal virtuoso-opensource-6.1-bin virtuoso-opensource-6.1-common vlc vlc-data  vlc-nox vlc-plugin-notify vlc-plugin-pulse vpnc wireless-regdb wpasupplicant x11-common x11-utils x11-xkb-utils  x11-xserver-utils xbitmaps xdg-utils xfonts-base xfonts-encodings xfonts-utils xscreensaver-data xscreensaver-data-extra  xscreensaver-gl xscreensaver-gl-extra xscreensaver-screensaver-bsod xserver-common xserver-xorg xserver-xorg-core  xserver-xorg-input-all xserver-xorg-input-evdev xserver-xorg-input-mouse xserver-xorg-input-synaptics  xserver-xorg-input-vmmouse xserver-xorg-input-wacom xserver-xorg-video-all xserver-xorg-video-apm xserver-xorg-video-ark  xserver-xorg-video-ati xserver-xorg-video-chips xserver-xorg-video-cirrus xserver-xorg-video-fbdev xserver-xorg-video-i128  xserver-xorg-video-intel xserver-xorg-video-mach64 xserver-xorg-video-mga xserver-xorg-video-neomagic  xserver-xorg-video-nouveau xserver-xorg-video-openchrome xserver-xorg-video-r128 xserver-xorg-video-radeon  xserver-xorg-video-rendition xserver-xorg-video-s3 xserver-xorg-video-s3virge xserver-xorg-video-savage  xserver-xorg-video-siliconmotion xserver-xorg-video-sis xserver-xorg-video-sisusb xserver-xorg-video-tdfx  xserver-xorg-video-trident xserver-xorg-video-tseng xserver-xorg-video-vesa xserver-xorg-video-vmware  xserver-xorg-video-voodoo xterm zip

After that call
apt-get autoremove

System is free again.


text:
Q: Backorder List: Comparison of total quantities to check the backorder, I am working with the following SQL query which matches the stock of an item per sales order with the current stock of the item:
SELECT

null, null

--, 'Orders with shipping backlog '+cast(datepart(Iso_week,getdate()) as nvarchar)+'. KW
('+convert(nvarchar(8),getdate(),104)+')' -- today

, 'Orders with production and purchasing backlog  '+cast(datepart(Iso_week,getdate()) as
nvarchar)+'. KW (bis zum '+convert(nvarchar(8),(SELECT CAST(DATEADD(DAY, -DATEPART(WEEKDAY,
CURRENT_TIMESTAMP) + 6, CURRENT_TIMESTAMP) AS DATE) ),104)+')' -- Friday of the current week

, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null

union all

SELECT

T2.SlpName

, T0.ItemCode

, T0.Dscription

, T1.DocNum

, T0.OpenQty

, T1.CardCode

, T1.CardName

, T0.ShipDate

, DATEPART(iso_week,T0.shipdate) AS 'Calendar week'

, DATEDIFF(day,getdate(),T0.shipdate) AS 'Days overdue'

, -1*DATEDIFF(WEEK,getdate(),T0.shipdate) AS 'Weeks overdue'

, CASE -1*DATEDIFF(WEEK,getdate(),T0.shipdate)

when 0 then 'green'

when 1 then 'yellow'

ELSE 'red'

END AS 'Ranking'

, CASE WHEN T1.Pick = 'Y' then cast(1 AS bit) else cast(0 AS bit) END AS 'Check'

, CASE WHEN T4.PymntGroup like '%Prepayment%' then 'Prepayment' else '' END AS 'Payment'

--, CASE WHEN T1.GroupNum in ('21','22') then 'Prepayment' else '' END AS 'Payment'

, CASE WHEN T1.Pick != 'Y' then 'rot' END AS 'red mark from checkmark'

, T5.OnHand

, Case when T5.OnHand >= T0.OpenQty then 'on stock' Else '' END AS 'Available for delivery'

, T1.DocEntry

FROM RDR1 T0

LEFT JOIN ORDR T1 on T1.DocEntry = T0.DocEntry

LEFT JOIN OSLP T2 on T2.SlpCode = T1.SlpCode

LEFT JOIN OITM T3 on T3.ItemCode = T0.ItemCode

LEFT JOIN OCTG T4 on T4.GroupNum = T1.GroupNum

LEFT JOIN OITW T5 on T5.ItemCode = T0.ItemCode AND T5.WHSCode = 'A'

where

T0.LineStatus = 'O'

AND

T1.DocStatus = 'O'

AND

T0.shipdate <= (SELECT CAST(DATEADD(DAY, -DATEPART(WEEKDAY, CURRENT_TIMESTAMP) + 6,
CURRENT_TIMESTAMP) AS DATE))

AND

T3.InvntItem = 'Y' -- only stocked items

AND

T5.OnHand < T0.OpenQty

ORDER BY 1,2

The result of this query shows all items whose demand per order is less than the current stock of the item. The problem here, however, is that the items may appear in several different sales orders. Nevertheless, the query compares the quantities of the article with the stock level only at the order level. Actually, the demand of the article should be summed up from all orders and compared with the stock level.
To solve this problem, I made the following changes in the source code in these three parts. Unfortunately, I get an error message that the syntax is incorrect:
, SUM(T0.OpenQty) as 'Total open quantity'

, Case when MAX(T5.OnHand) >= SUM(T0.OpenQty) then 'on stock' Else '' END AS 'Available for
delivery'

MAX(T5.OnHand) < SUM(T0.OpenQty)

Can anyone give me a hint as to where my error lies in this?
Thanks for any advice in advance!


text:
Q: Excessive blank space after a graphic using R and kntir The problem is the following:

I want to have the text from section 6 way closer to the graphics.
This is the code I am using:
\documentclass{article}
\usepackage{graphicx}
\usepackage{microtype}
\usepackage{float}
\emergencystretch=20pt
\usepackage{vmargin}
\setpapersize{A4}
\begin{document}
<<results='markup',fig.keep='all', message=FALSE, warning=FALSE>>=
par(mfrow= c(2,2))
boxplot(a5,b5,col=c("azure4","azure3"),ylab="Calor latente(cal/gm)",
        xlab="Muestras",names=c("A","B"))
qqplot(a5,b5,ylab="Muestra B",xlab="Muestra A")
par(mfrow= c(1,1))
@
\section{Ejercicio 6}
blabla
\end{document}

I guess that the problem is that Latex still taking the whole graphic window size, even though I need just half of it.
Thank you very much!

A: For two plots use par(mfrow= c(1,2)) (not 2,2) and set the height accordingly if necessary:
\documentclass[a4paper]{article}
\usepackage{graphicx}
\begin{document}
<<results='markup',fig.keep='all',fig.height=4, message=F, warning=F,echo=F>>=
a5=c(1,2,3,5)
b5=c(1,2,3,5)
par(mfrow= c(1,2))
boxplot(a5,b5,col=c("azure4","azure3"),ylab="Calor latente(cal/gm)",
        xlab="Muestras",names=c("A","B"))
qqplot(a5,b5,ylab="Muestra B",xlab="Muestra A")
par(mfrow= c(1,1))
@
\section{Ejercicio 6}
blabla
\end{document}


text:
Q: How to use enum in switch vs integer using I have enum in header file.
typedef enum{
     up = 8, down = 2, left = 4, right = 6
}direction;

I want use enum to identify type of move.
Like this:
void sayTypeOfMove(int type){

     switch(type){
          case direction.up:
                 printf("IT IS UP MOVE...");
                 break;
     }

}

The code does not compile , where is the problem?

A: C understands the enum elements when it knows you're dealing with that enum, so the right code would be
void sayTypeOfMove(direction type){

     switch(type){
          case up:
                 printf("IT IS UP MOVE...");
                 break;
     }

}

By the way, type is a really bad name, because it feels so much like it should be a reserved keyword.

A: With a definition like
typedef enum{
     up = 8, down = 2, left = 4, right = 6
}direction;

direction is a type, it's not a variable.
You need to define a variable of that type, and then use the value.
And remember, the enum does not have a member variable access concept, at all. The enumerator list contains "enumeration-constant" s. You can just use them directly, as a value.


text:
Q: Tic tac Toe javascript stop switching turns after winner has been announced i'm stuck with my tic tac toe program for what seems like the 100th time. I am running my program through selenium and everything works fine except that if there is a winner announced it will still switch turns and click another box. for example if player 2 wins then it will click another box and then it will make player 1 win. How can i make it so when a winner is announced it stops switching turns?
Here is my js:
var cell;
var nextTurn = 'X';

function mouseMotion(ref,motion){
if(motion == 'over')
    {
        ref.style.borderColor='#E00';
    }
    else if(motion == 'out')
    {
        ref.style.borderColor='#CCC';
    }
}

function cellClick(cell){
if (cell.innerHTML === 'X' || cell.innerHTML === 'O')
{ alert ('Square has already been choosen, please select another square');
return
}
cell.innerHTML = nextTurn;
playersTurn();
winnerIs();

 }
function playersTurn(){
if(nextTurn == 'X'){
    nextTurn = 'O';
    }
else {
    nextTurn = 'X';
    }
}

function winnerIs(){

if (document.getElementById("cell1x1").innerHTML == 'X' &&    document.getElementById("cell1x2").innerHTML == 'X' && document.getElementById("cell1x3").innerHTML == 'X')
{document.getElementById('winnerIs').innerHTML = 'Player 1 Wins!';
 document.getElementById('winnerIs').style.display = 'block';

}

else if (document.getElementById("cell2x1").innerHTML == 'X' && document.getElementById("cell2x2").innerHTML == 'X' && document.getElementById("cell2x3").innerHTML == 'X')
{document.getElementById('winnerIs').innerHTML = 'Player 1 Wins!';
 document.getElementById('winnerIs').style.display = 'block';
 }
else if (document.getElementById("cell3x1").innerHTML == 'X' && document.getElementById("cell3x2").innerHTML == 'X' && document.getElementById("cell3x3").innerHTML == 'X')
{document.getElementById('winnerIs').innerHTML = 'Player 1 Wins!';
 document.getElementById('winnerIs').style.display = 'block';
 }
else if (document.getElementById("cell1x1").innerHTML == 'X' && document.getElementById("cell2x2").innerHTML == 'X' && document.getElementById("cell3x3").innerHTML == 'X')
{document.getElementById('winnerIs').innerHTML = 'Player 1 Wins!';
 document.getElementById('winnerIs').style.display = 'block';
 }
else if (document.getElementById("cell1x3").innerHTML == 'X' && document.getElementById("cell2x2").innerHTML == 'X' && document.getElementById("cell3x1").innerHTML == 'X')
{document.getElementById('winnerIs').innerHTML = 'Player 1 Wins!';
 document.getElementById('winnerIs').style.display = 'block';
 }
else if(document.getElementById("cell1x1").innerHTML == 'X' && document.getElementById("cell2x1").innerHTML == 'X' && document.getElementById("cell3x1").innerHTML == 'X')
{document.getElementById('winnerIs').innerHTML = 'Player 1 Wins!';
 document.getElementById('winnerIs').style.display = 'block';
 }
else if(document.getElementById("cell1x2").innerHTML == 'X' && document.getElementById("cell2x2").innerHTML == 'X' && document.getElementById("cell3x2").innerHTML == 'X')
{document.getElementById('winnerIs').innerHTML = 'Player 1 Wins!';
 document.getElementById('winnerIs').style.display = 'block';
 }
else if(document.getElementById("cell1x3").innerHTML == 'X' && document.getElementById("cell2x3").innerHTML == 'X' && document.getElementById("cell3x3").innerHTML == 'X')
{document.getElementById('winnerIs').innerHTML = 'Player 1 Wins!';
 document.getElementById('winnerIs').style.display = 'block';
 }
else if (document.getElementById("cell1x1").innerHTML == 'O' && document.getElementById("cell1x2").innerHTML == 'O' && document.getElementById("cell1x3").innerHTML == 'O')
{document.getElementById('winnerIs').innerHTML = 'Player 2 Wins!';
 document.getElementById('winnerIs').style.display = 'block';
 }
else if (document.getElementById("cell2x1").innerHTML == 'O' && document.getElementById("cell2x2").innerHTML == 'O' && document.getElementById("cell2x3").innerHTML == 'O')
    {document.getElementById('winnerIs').innerHTML = 'Player 2 Wins!';
 document.getElementById('winnerIs').style.display = 'block';
 }
else if (document.getElementById("cell3x1").innerHTML == 'O' && document.getElementById("cell3x2").innerHTML == 'O' && document.getElementById("cell3x3").innerHTML == 'O')
    {document.getElementById('winnerIs').innerHTML = 'Player 2 Wins!';
 document.getElementById('winnerIs').style.display = 'block';
 }
else if (document.getElementById("cell1x1").innerHTML == 'O' && document.getElementById("cell2x2").innerHTML == 'O' && document.getElementById("cell3x3").innerHTML == 'O')
    {document.getElementById('winnerIs').innerHTML = 'Player 2 Wins!';
 document.getElementById('winnerIs').style.display = 'block';
 }
else if (document.getElementById("cell1x1").innerHTML == 'O' && document.getElementById("cell1x2").innerHTML == 'O' && document.getElementById("cell1x3").innerHTML == 'O')
    {document.getElementById('winnerIs').innerHTML = 'Player 2 Wins!';
 document.getElementById('winnerIs').style.display = 'block';
 }
else if(document.getElementById("cell1x1").innerHTML == 'O' && document.getElementById("cell2x1").innerHTML == 'O' && document.getElementById("cell3x1").innerHTML == 'O')
    {document.getElementById('winnerIs').innerHTML = 'Player 2 Wins!';
 document.getElementById('winnerIs').style.display = 'block';
 }
else if(document.getElementById("cell1x2").innerHTML == 'O' && document.getElementById("cell2x2").innerHTML == 'O' && document.getElementById("cell3x2").innerHTML == 'O')
    {document.getElementById('winnerIs').innerHTML = 'Player 2 Wins!';
 document.getElementById('winnerIs').style.display = 'block';
 }
else if(document.getElementById("cell1x3").innerHTML == 'O' && document.getElementById("cell2x3").innerHTML == 'O' && document.getElementById("cell3x3").innerHTML == 'O')
    {document.getElementById('winnerIs').innerHTML = 'Player 2 Wins!';
 document.getElementById('winnerIs').style.display = 'block';
 }
}

function startNewGame(){
    location.reload(true);
}

Here is my HTML:

<title>Tic Tac Toe</title>

 <link rel="stylesheet" type="text/css" href="tictactoestyle.css">

  <input id="newGameBtn" type="button" value="Start New Game" onclick="startNewGame();" />

And here is my CSS:
 #tttTable
  {
    width: 600px;
   height: 600px;
  }

 .cell
  {
  width: 200px;
  height: 200px;
  border: 1px solid #CCC;
  text-align: center;
  font-weight: bold;
  font-size: 4em;
 }

#newGameBtn
{
  margin-left: 46%;
}

#playersTurn
{
 text-align: center;
 font-weight: bold;
 font-size: 1.1em;
 height: 10px;
}

#outer
{
 width: 600px;
}

#winnerIs
{
  background-color: #EEE;
  text-align: center;
  font-weight: bold;
  font-size: 5em;
  width:700px;
 height:100px;
  position:fixed;
  top:50%;
  left:50%;
  margin-top:-150px;
  margin-left:-350px;
 display: none;
 }

Thank you for taking the time to read my code and help me. If you seen anything i could improve upon then i would love to hear what you have to say. Thank you again!

A: You could track a "game over" flag such as var gameOver = false then set that to true when you detect a winner. Then your cellClick function could ignore inputs once the game is over:
function cellClick(cell){
    if(gameOver == true)
        return;

    if (cell.innerHTML === 'X' || cell.innerHTML === 'O')
    {
        alert ('Square has already been choosen, please select another square');
        return;
    }
    cell.innerHTML = nextTurn;
    playersTurn();
    winnerIs();
}

Note, your code still needs to handle the case of a "draw".

A: I think you can just make a variable that keeps track of whether the game has ended or not. Then in your cellClick function you only execute the code only if your variable is false.

A: When player wins you make "winnerIs" DIV visible. Without adding any variables or flags you can just add this block before anything else into function function cellClick(cell):
if (document.getElementById("winnerIs").style.display == "block") {
   alert('Game has already been won!');
   return
}

It will check if "winnerIs" DIV is visible and if so - will prevent further moves.
Demo: http://jsfiddle.net/zG3pm/4/


text:
Q: call buttons function on enter I'm trying to submit a dialog form when the user presses enter.  I had the form setup as below:
$("#band-dialog-form").dialog({
        buttons : {
            "Save" : function(){
                        $(this).dialog("close");
            $("#editBandForm").submit();
                            },
            Cancel : function() {
                $(this).dialog("close");
            }
        },
        close : function() {

        }
    });

When I added the key listener I changed to:
                "Save" : function submitBand(){
                            $(this).dialog("close");
                $("#editBandForm").submit();
                                },

But my key listener can't find the function submitBand.  If I try and pull the function out of the dialog and make it:
"Save" : submitBand(),

The submitBand function is called on initialization and the page is sent without the user doing anything.  What is the propper way to used named functions in the buttons object?

A: You are assigning the result of executing submitBand to the "Save" key, as the parentheses following submitBand (or "function call" construct) means "execute this function object and return the result". Try passing the function object without the function invocation construct:
"Save" : submitBand,

A: You should do:
var  submitBand = function(){
           $("#band-dialog-form").dialog("close");
           $("#editBandForm").submit();
      };

and thenn pass a reference to the function to the button:
$("#band-dialog-form").dialog({
        buttons : {
            "Save" :submitBand ,
            "Cancel" : function() {
                $(this).dialog("close");
            }
        },
        close : function() {

        }
    });


text:
Q: RegEx: match digits from a comma-seperated number I want to only match the digits from a comma seperated number. Example:
123,456 should match 123 and 456
75,432,444 should match 75 and 432 and 444

My expression currently looks like this \b[0-9]+(!\,)?+\b. It matches numbers that are NOT seperated with a comma, but it doesn't select numbers that are seperacted with a coma. If I seperate numbers with a | character or a space the numbers are selected.
Splitting the string is not an option.
I'm trying to learn RegEx, but I'm now stumbled at this.

A: You can try this regex:
\b(\d{1,3}(?:,\d{3})+)\b

It matches numbers that are separated by commas in group of three. Once you have the number in the capturing parentheses you can split on comma if you want to have its parts separated.


text:
Q: How to get images from frames of a gif video? I was wondering how to get the images of the frames of a .gif video?

A: ImageMagick can split the animation into frames.

A: If you're looking for something web-based, you can upload a .gif to Free Online Image Editor, and go to Edit > Gif Only > Split Into Frames.
(I used to use another site, GifWorks.com, for this, but I just now found out their site was hijacked or sold or something. It's a shame; it really was a good web application.)


text:
Q: java save jpg as png I have an image on disk which is a jpg file . I want to convert and save it as png and delete original jpg. Whats best way to do this in java?
String justNameJpg = "something.jpg";
String justNamePng = ImageEditor.GetImageNameNoExtension(justName) + "." + "png";
java.awt.image.BufferedImage bufferedImage = ImageIO.read(new File(folder, justNameJpg));
ImageIO.write(bufferedImage, "png", new File(folder, justNamePng));

A: If you want to use ImageIO this should work:
ImageIO.write(image, "png", new File("new output file name"));

A: The best way is to call the external tool "imagemagick". This is no joke. I do it like that in my app, because it is much faster and more reliable than everything you get in Java.

A: imagemagick is a good option, from @Daniels answer.  If you want to convert the thumbails in code, I had great luck with
http://code.google.com/p/thumbnailator/
it supports changing the file format for you, from the example page:
OutputStream os = ...;

Thumbnails.of("large-picture.jpg")
        .size(200, 200)
        .outputFormat("png")
        .toOutputStream(os);


text:
Q: Flex custom component doesn't accept Script: Multiple initializer values for default property, 'text', of type 'String' I'm using Flex 4 and Flash Builder 4. I just want to learn to create components and I created an mxml component as follows and included it in my application:
<?xml version="1.0" encoding="utf-8"?>
<s:TextInput xmlns:fx="http://ns.adobe.com/mxml/2009"
             xmlns:s="library://ns.adobe.com/flex/spark"
             xmlns:mx="library://ns.adobe.com/flex/mx">
    <fx:Script>
    </fx:Script>
</s:TextInput>

If I take out the fx:Script tags it works, but as soon as I have those tags (regardless of whether any actual code is in there) I get the error: "Flex custom component doesn't accept script: Multiple initializer values for default property, 'text', of type 'String'."
Why would that be? Is script not allowed in components?

A: If you change TextInput to Button it will be OK.
The problem is that TextInput treats Script as a value for text property. I believe it is a compiler bug.

A: Another way around this is to extend TextInput using actionscript rather than mxml:
package
{
    import spark.components.TextInput;

    public class TestTextInput extends TextInput
    {
        public function TestTextInput()
        {
            super();
        }
    }
}

A: this is a known bug SDK-25184. Milestone is the next Flex SDK Hero Release. You still can use mxml if you explicitly set the text property.
<?xml version="1.0" encoding="utf-8"?>
<s:TextInput xmlns:fx="http://ns.adobe.com/mxml/2009"
             xmlns:s="library://ns.adobe.com/flex/spark"
             xmlns:mx="library://ns.adobe.com/flex/mx"
             text="">
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
</s:TextInput>

Thanks.


text:
Q: DatePicker not getting disabled on change in state Please see the following code. I have a dropdown with 3 values, the DatePicker should conditionally get disabled when the user chooses 1, or 2 from the dropdown. But this is not happening.
import React, { useState } from 'react';
import ReactDatePicker from "react-datepicker";

export default function DateRangePicker() {
    const [startDate, setStartDate] = useState("");
    const [rangeType, setRangeType] = useState(1);

    return

        <select value={rangeType} onChange={e => setRangeType(e.target.value)}>
            <option value="1">This Month</option>
            <option value="2">This Year</option>
            <option value="3">Date Range</option>
        </select>

        <ReactDatePicker
            disabled={rangeType !== 3}
            selected={startDate}
            onChange={e => setStartDate(e)}
        />

;
}

What am I doing wrong here?
Thanks

A: Print a console log on the onChange, but from what I'm reading I suppose that the problem is the type: you're comparing string and numbers.


text:
Q: Rails / RSpec: mail render in spec results in missing template Using rspec-rails, how should I test the correct rendering of a mail template?
I started with this test in spec/views/user_mailer.spec:
describe Mailer do
  it 'sends an message email' do
    render 'send_message'
  end
end

It tells me:
Failure/Error: render 'mailer/send_message.html.erb'
 ActionView::MissingTemplate:
   Missing partial mailer/send_message.html with {:formats=>[:html, :text, :js, :css, :ics, :csv, :png, :jpeg, :gif, :bmp, :tiff, :mpeg, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip], :handlers=>[:erb, :builder, :haml, :coffee], :locale=>[:de]}.
 Searched in:
   * ".../app/views"`

But there is the template I want to render in app/views/mailer/send_message.html.erb
How should I spec this? (I want to check if the CSS rules result in the correct color for the footer, which I thought to extract with jQuery-Javascript if there is no better way)

A: You may have to use:
render template: 'send_message'

The Rails Guides mention:

Rails knows that this view belongs to a different controller because
  of the embedded slash character in the string. If you want to be
  explicit, you can use the :template option

Note that your template name doesn't have an embedded slash character.


text:
Q: How do I deactivate css code on tablet and mobile? hey community I want to deactivate the following code for column count on mobile and tablet:
<!DOCTYPE html>
<html>
<head>
<style>

    div {
  text-align: justify;
  text-justify: inter-word;
}
  .newspaper2 {
    column-count: 2;
    column-gap: 68px
  }

.newspaper {
  column-count: 3;
  column-gap: 68px;
}

</style>
  </head>
</html>

A: As per my opinion Media Query for Laptops and Desktops is as follows
@media (min-width: 1025px) and (max-width: 1280px)
And from your requirements for mobile device media query be like
@media (max-width: 480px)
and for tablets like Ipads in portrait mode
@media (min-width: 768px) and (max-width: 1024px)
So just add your code under Media query for Laptop and desktop...
Hope it works for you :)
@media (min-width: 1025px) and (max-width: 1280px) {
div {
text-align: justify;
text-justify: inter-word;
}
.newspaper2 {
    column-count: 2;
    column-gap: 68px
}

.newspaper {
column-count: 3;
column-gap: 68px;
}

}

A: Look into media queries
https://www.w3schools.com/cssref/css3_pr_mediaquery.asp
this will only be used when the screen is larger than 600px
@media only screen and (min-width: 600px) {
    div {
    text-align: justify;
    text-justify: inter-word;
    }
    .newspaper2 {
        column-count: 2;
        column-gap: 68px
    }

    .newspaper {
    column-count: 3;
    column-gap: 68px;
    }
}


text:
Q: TypeError: unsupported operand type(s) for +: 'line' and 'line' here is the code:
class line:

    def __init__(self, name):
        self.name = name

    def __str__(self):
        return f"< {self.name} >"

print(line('te') + line('st'))

this is the error I'm getting:
Traceback (most recent call last):
    File "C:\Users\ronil\Documents\Calculator\main.py", line 9, in <module>
        print(line('roni') + line('levin'))
TypeError: unsupported operand type(s) for +: 'line' and 'line'

the code output must be "< te st >"
the class line gives new variable type and "print(line('te') + line('st'))"
needs to join "te" and "st" that has new type line

A: You defined what is the string representation of the object but you just added the objects and not their string representation. As @MisterMiyagi said you get an error message because Python is searching for the __add__() method in the objects and doesn't find one. Since I don't think adding the actual objects is your goal, just use str() to get the strings which you can then concatenate:
print(str(line('te')) + str(line('st')))
# < te >< st >

Or use the f-string notation which automatically calls the string method on objects:
print(f"{line('te')}{line('st')}")
# < te >< st >

If you actually want to add the objects define an __add__() method:
    def __add__(self, other):
        return line(self.name + other.name)

print(line('te') + line('st'))
# < test >


text:
Q: How to create a hard link when installing an application in CMake I have two applications that share a lot of code. Creating a shared library is a bit of overkill though. So I'd like to have a single executable hard linked to two executable names and then, depending on the name in argv[0], decide which main to use. May sound exotic, but is not that unusual.
Now the point is, how do I create the hard link at install time? I tried something like this:
add_excutable(foo ${PROJECT_SOURCE_DIR}/foo.cpp)
install(TARGETS foo RUNTIME DESTINATION ${BIN_INSTALL_DIR})
install(CODE "file(CREATE_LINK ${BIN_INSTALL_DIR}/foo ${BIN_INSTALL_DIR}/bar)")

The last line is executed at install time, but BIN_INSTALL_DIR does not seem to be defined in the last line resulting in the error that /foo could not be found. Duh.
Of course, there are many ways to do this differently, like simply creating two applications. But I hope I overlooked a simple way to achieve what I intended in the first place.


text:
Q: Hot Reload doesnt work in Visual Studio 2022 - C# (No code changes were found) It has worked well in past, but since a while Hot Reload doesn't work to me in Visual Studio 2022 - C#
No matter what change I made it says 'No code changes were found' and obviously changes made are not being honoured

Im running app in debug mode, solution has debug config
Below my settings.
Any idea how to make this working again? I very miss this feature... :(

A: This issue seems to have been resolved with 17.3.6 of Visual Studio. I was experiencing the same issue with 17.2.5 where it reported no code changes. Upgrading fixed the issue.
There was evidence of others having the same issue with 17.2.5 in this microsoft thread;
https://developercommunity.visualstudio.com/t/vs2022-hot-reload-edits-were-made-which-cannot-be/1703108#T-N10079489
Also reports that it was fixed with 17.3.0 release.
https://developercommunity.visualstudio.com/t/vs2022-hot-reload-edits-were-made-which-cannot-be/1703108#T-N10109880

A: I am also having this annoying problem.
For now I solved it like this, to run the app:
dotnet watch run --no-hot-reload

I am using the command.
The --no-hot-reload argument works.


text:
Q: Filter selection based on first selection <select ng-model="chosenCategory" >
<option ng-repeat="category in categories">{{category}}</option>
</select>

<select id="selectedFeed" name="selectedFeed" ng-model="selectedFeed" ng-init="selectedFeed=feed.url" ng-change="loadFeed(selectedFeed, $event)" ng-options="feed as feed.name for feed in userfeeds | filter: feed.category = chosenCategory">
</select>

I have been trying for a day now to get this filter to work i don't know what's wrong.. i've tried many variations of code. This code was working then all of a sudden it stopped. Please help! I am trying to filter the second option if the feed category matches the chosen category in the first option

A: Ok I solved my question by using ng-options on the first select as well.. dont know why this was preventing the filter from working
<select ng-model="chosenCategory" ng-options="category as category for category in categories" >
</select>


text:
Q: Core data, search for objects based on objects own property I have an NSManagedObject, foo that stores the NSDate it was created. It also has another field, lifespan which store how many seconds the object is valid for.  Each foo can have a different lifespan value. Is it possible to return all foos who have not exceed their lifespan?  I'm not sure how to express that in my NSPredicate or if it is even possible?

A: Yes, it is possible.
eg:
NSDate * yesterday = [NSDate dateWithTimeIntervalSinceNow:-(60 * 60 * 24)];
NSPredicate * predicate = [[NSPredicate alloc] initWithFormat:@"dateCreated > %@", yesterday];
NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setPredicate:predicate];
NSError * error = nil;
NSArray * results = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

Here is more info on writing predicates: http://developer.apple.com/library/ios/#DOCUMENTATION/Cocoa/Conceptual/Predicates/Articles/pCreating.html

A: A Core Data fetch request can actually contain simple arithmetic expression.
So to find all objects where "created + lifespan  >= now",
the following works:
NSDate *now = [NSDate date];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"created + lifespan >= %@", now];


text:
Q: Devise + Omniauth: disable email login when users enable SSO I have a website that used a normal Devise login with email and password.
Then I have completed this tutorial to add Omniauth / SSO:
https://github.com/heartcombo/devise/wiki/OmniAuth:-Overview
Now when some users choose to use "Sign in with Google" I want to disable the normal login with email and password for those users (for enhanced security).
How can I achieve that?


text:
Q: How to isolate a single digit in a decimal? I am trying to isolate a single digit inside of a decimal in order to display a formatted percentage.
I am getting:
result = 8 / 10
print(result)
#Output: 0.8

I want to solely isolate the 8 so I can print:
print(f"The answer is {result}%")
#Output: The answer is 80%

How would I do this?

A: Do you mean strip the "0."?
If so, you can use:
print(str(result * 100) + '%')

P.S. 0.8 means 80%, not 8%.

A: Firstly, .8 is 80% not 8%.
to format a decimal as a percentage use print(f'{result:.0%}') this will produce 80%


text:
Q: Identifying key=value pairs in *.properties files using Java We have many *.properties files in my project, and in each, we have lots and lots of key=value pairs.
The task is to find all keys that start with _format_
followed by any word (we can freely assume that that word will not contain any special characters nor whitespace characters) AND the value of that key IS NOT EQUAL to null (case-insensitive).
Using an example:
_format_Date1=null
_format_Date2=null
_format_endTerm=null
_isUpdatable_somethingA=false
_isUpdatable_somethingB=false
_format_begingTerm=null
_format_countOfMoney=\#0.00#\ -- The kind of row that must be identified with the pattern
_javaType_name1=String
_javaType_name2=String

We can also assume all of the key=values pairs will loaded up in a collection and read line by line.
Any help would be appreciated...

A: Just iterate over the files, read them in and filter line by line.
I suppose something like this could do it:
    Files.walk(Paths.get("path"))
         .filter(Files::isRegularFile)
         .filter(path -> path.endsWith(".properties"))
         .forEach(path -> {
                      try {
                          Files.lines(path)
                               .filter(s -> s.startsWith("_format_"))
                               .filter(s -> !s.split("=")[1].toLowerCase().equals("null"))
                               .forEach(s -> System.out.println("File " + path.toString() + " has amtching line " + s));
                      } catch (final IOException e) {
                          e.printStackTrace();
                      }
                  }
         );


text:
Q: Does Ubuntu come with dictionary/list of words file? I was wondering if Ubuntu comes with a file that lists all of the words in, say, the Webster's dictionary, for the purposes of spell checking and whatnot.
I looked around a bit and I couldn't find anything.

A: The package wamerican has a word list for American English (installed in /usr/share/dict/american-english). There are dictionaries for other languages available, which you can find by searching the repositories for the desired language (e.g. wbritish has a word list for British English).


text:
Q: PrimeNG export to CSV I have a PrimeNG grid and the data served by the PrimeNG is from a service which have server side paginated data and from the server we would receive only our current page record.
I have my HTML code as below:

                    <button type="button" pButton icon="fa-file-o" iconPos="left"
                  label="CSV" (click)="dataTable.exportCSV()" style="float:left">
                    </button>

JSONArray variable will only have 10 records (my page size), but we want to export all the data from the server. Let say I have 5 page, I would like to export all the 50 records.
dataTable.exportCSV() is only exporting my current page 10 record only. Is there any way to export all the 50 records?

A: There no direct solution, sharing a solution hoping that it might help someone.
My HTML looks like this.

                    <button type="button" pButton icon="fa-file-o" iconPos="left"
                  label="CSV" (click)="exportCSV(dataTable)" style="float:left">
                    </button>

my typescript looks like this.
private _dataTable: any;
private rowCount: Number;
private pageNoSize: any;

exportCSV(dataTable) {
        this.rowCount = 50;
        this.pageNoSize = 'page=0&size=' + this.rowCount;
        this._dataTable = dataTable;
        this.getJSONData();
    }

getJSONData() {
    this.getJSONDataService.get(uri + this.pageNoSize)
        .subscribe(
        data => {

                this._dataTable.value = data;
                this._dataTable.exportCSV();
                this.rowCount = 10;

        },
        error => {
        },
    );
}

A: Another way would be disabling paginator temporarily:

TABLE CONTENT

In the export event of a button:
<button type="button" pButton (click)="yourTable.paginator=false;yourTable.exportCSV();yourTable.paginator=true;" label="Export"></button>

A: You could make one extra call loadAllData() first time on loading your component and store data in JsonArrayAll[] and keep the paginated data in your JsonArray[].

TABLE

<button (click)="dt.value=JsonArrayAll;dt.exportCSV();dt.value=JsonArray;">

A: Just change :
[rows]="10"

to any value you want.
Like :
[rows]="50"
You can also change this dynamically.


text:
Q: Jquery draggable using localstorage not working after page refresh So I have set up Jquery draggable so a user can change the positions of divs within a parent div.
When the first drop is performed, all the positions are saved to localstorage. This data is then updated each time a drop is conducted.
When the page is refreshed, the div positions are all displayed correctly based on the saved positions in the localstorage. When I then click a div to begin the drag and drop procedure, the surrounding divs do not move as expected or how they did prior to the page refresh.
HTML

Test0

Test1

Test2

Test3

Test4

<button onclick="localStorage.clear();">Clear Local Storage</button>

Javascript
    $( function() {

    newPosVal = [];

    if (localStorage.getItem("newData") != null){

        var storedData = JSON.parse(localStorage.getItem("newData"));

        console.log("New position Local Storage data being used:");
        console.log(storedData);

                    for (var i = 0; i < storedData.length; i++) {
                        console.log("stored: #test" + storedData[i]['div_id'] + " " + storedData[i]['offset_top_position']);
                        var id = storedData[i]['div_id'];
                        var position = storedData[i]['offset_top_position'];
                        $('#test' + id).offset({top:position});

                        console.log("Pos Check: #test" + id, $("#test" + id).offset().top);
                    }

    }

    $( '#sortable' ).sortable({
        revert: false,
        stop: function() {

            if (localStorage.getItem("newData") != null){

                var dataNew = jQuery.parseJSON(localStorage.getItem("newData"));

                console.log("New position Local Storage data being used:");
                console.log(dataNew);

                    for (var i = 0; i < dataNew.length; i++) {
                        console.log("previous: #test" + dataNew[i]['div_id'] + " " + dataNew[i]['offset_top_position']);
                        id = dataNew[i]['div_id'];
                        position = dataNew[i]['offset_top_position'];
                        offset = $('#test' + id).offset();
                        newPosVal[i] = {"div_id":id, "offset_top_position":offset.top};
                        console.log("Newly stored: #test" + id, $("#test" + id).offset().top);
                    }

                console.log("New Position Using Local Storage data: " + JSON.stringify(newPosVal));
                localStorage.setItem("newData", JSON.stringify(newPosVal));

            } else {

                console.log("No div position data is being used");

                    for(var i=0; i < 5; i++) {
                        var id = i;
                        var offset = $('#test' + id).offset();
                        newPosVal[i] = {"div_id":id, "offset_top_position":offset.top};
                    }

                console.log("First Position Data: " + JSON.stringify(newPosVal));
                localStorage.setItem("newData", JSON.stringify(newPosVal));

            }

        }
    });

    $( '#draggable' ).draggable({
        connectToSortable: '#sortable',
        //helper: 'clone',
        revert: false
    });

});


text:
Q: How to Pass Dropdown selected value to Controller on Selected index change i am new to MVC and i am stuck at one point into project i wanted to check the Availability of a Batch,i am using a Dropdownlist and it is populate by Batch table.
My Question is when i am selecting a batch from drop downlist on same time it will give Msg that Batch is available or Not.
Batch Table Structure is:
BatchID BachName TotalSeat AvailableSeat
01 L1 50 40
02 L2 20 20
i don't know how to do this task.

A: You can see the different solutions form this link:
@using (Html.BeginForm("Method", "YourController")) {

@Html.DropDownList("Id", ViewBag.DropDownCollection as SelectList, "--pick--", new {
    title = "Pick Batch",
    onchange = "submit();"
});

}

ActionResult

public ActionResult Method(string Id)
{
 //do the logic here
}


text:
Q: An $\omega$-categorical theory $T$ with no finite models is complete. I'm trying to understand the following proof of this result, but I don't understand:

*

*where the assumption that $T$ has no finite models is used;

*why the final step is valid.
Take two models $\mathcal{M},\mathcal{N}$ of $T$, and suppose $\mathcal{M}\models\phi$. We need to show $\mathcal{N}\models\phi$ (the proof works exactly the same if $\mathcal{M}\not\models \phi$).
By the definition I have of $\omega$-categorical, $T$ must be in a countable language with an infinite model. So, by the Downward Lowenheim Skolem theorem, $\mathcal{M},\mathcal{N}$ both have countable elementary substructures, $\mathcal{M}',\mathcal{N}'$. Since $T$ is $\omega$-categorical, $\mathcal{M}'$ is isomorphic to $\mathcal{N}'$.
Thus far I am fine, but the proof then concludes "by elementarily, $\mathcal{N}\models\phi$". This is the step that I don't follow. What I have thought of is: "by the Tarski-Vaught test, $\mathcal{M}\models \phi$ precisely when $\mathcal{M}' \models \phi$, which is precisely when $\mathcal{N}'\models\phi$, and if $\mathcal{N}'\models\phi$ then $\mathcal{N}$ models $\phi$ since $\mathcal{N}'$ is a substructure", but I'm not comfortable with this.

A: You use the fact that $T$ has no finite models because you apply Löwenheim-Skolem to $\mathcal{M}$ and $\mathcal{N}$, which you can only do if they are infinite structures (Löwenheim-Skolem does not apply to finite structures).
For the second question: this follows directly from the definition of an elementary embedding. An embedding $f: \mathcal{M}' \to \mathcal{M}$ is elementary if for all tuples $a \in \mathcal{M}'$ and every formula $\varphi(x)$ we have that $\mathcal{M}' \models \varphi(a)$ if and only if $\mathcal{M} \models \varphi(f(a))$.
In this case we do not even need any parameters. That is, we are only interested in sentences. So particularly, having an elementary embedding $f: \mathcal{M}' \to \mathcal{M}$ means that for every sentence $\varphi$ we have $\mathcal{M}' \models \varphi$ if and only if $\mathcal{M} \models \varphi$.
The proof of Löwenheim-Skolem uses the Tarski-Vaught test to show that the embeddings obtained in that proof are elementary. After that, you need not concern yourself with the Tarski-Vaught test, it is the fact that we have elementary embeddings that is useful.
So if $f: \mathcal{M'} \to \mathcal{M}$ and $g: \mathcal{N'} \to \mathcal{N}$ are the elementary embeddings obtained from Löwenheim-Skolem ($\mathcal{M'}$ and $\mathcal{N'}$ both countable), then the argument should go as follows. Suppose that $\mathcal{M} \models \varphi$, then $\mathcal{M'} \models \varphi$ because $f$ is an elementary embedding. So by isomorphism of $\mathcal{M'}$ and $\mathcal{N'}$ (which we have by $\omega$-categoricity) we must have $\mathcal{N'} \models \varphi$. Then because $g$ is an elementary embedding, we find $\mathcal{N} \models \varphi$.


text:
Q: I can't redirect user after login I have login page which take username and password from user after user will be login. I am getting response for successfully login. but I can not redirect to index.php.
I am getting console message that User successfully login, But then page is not redirect on other page.
My JS file is like this.

$(document).ready(function() {
    //alert('ss');
 $("#login-form").submit(function(e){
  e.preventDefault();

  var username = $("#email").val();
  var password = $("#password").val();
  var isValid = true;
  var re =  /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

  if(!re.test($("#email").val())){
   isValid = false;
   $("#message").html("Please enter valid email.");
  }

  if($('#remember').is(':checked')){
   $.cookie('adminCookie', $("#loginUser").val(), { expires: 7 });
  }
  else{
   if($.cookie('adminCookie') == null) {
    $.removeCookie("adminCookie");
   }
  }
  if(password == ""){
   isValid = false;
   $("#message").html("Please enter password.");
  }

  if(isValid){

   $.ajax({
    type : "POST",
    url : "process/login.php?rand="+Math.random(),
    data : {
      username : $("#email").val(),
      password : $("#password").val(),
     }
   }).
   done(function(response){
                //alert(response);
    var JSONArray = $.parseJSON(rawJSON);

    console.log(response);
    if(jsonObj.success=="1"){

                    window.location("index.php");
    }else{
     $("#userDiv").addClass("form-group has-error");
     $("#passDiv").addClass("form-group has-error");
     $("#passWarning").css("display","");
     $("#passWarning").html("Invalid User Name or Password");
     $.when($('#passWarning').fadeOut(5000)).done(function() {
      $("#userDiv").attr('class', 'form-group');
      $("#passDiv").attr('class', 'form-group');
     });
    }
   }).fail(function(){

   }).always(function() {

   });
  }
 });
});

my PHP file is looks like this.

<?php
include "../connection.php";
extract($_POST);
$data = array();
$resArr = array();
if (isset($_POST['username']) && isset($_POST['password'])) {
    $check_user = mysqli_query($conn, "select * from cut_users where email like '$username' and password like '$password' and user_role like 'A'");
    if ($check_user) {
        if (mysqli_num_rows($check_user) > 0) {
            $message = "Login successfully.";
            $success = 1;
            while ($row = mysqli_fetch_array($check_user)) {
                if ($row['is_active'] == "0") {
                    $message = "Your account is blocked. Please contact admin.";
                    $success = 0;
                }
                $data["id"] = $row['cut_users_id'];
                $data["name"] = $row['name'];
                $data["emailID"] = $row['email'];
                $data["device"] = $row['device_type'];
                $data["is_reset"] = $row['is_reset'];
                $_SESSION['userID'] = $row['cut_users_id'];
                $_SESSION['name'] = $row['name'];
                $_SESSION['emailID'] = $row['email'];
            }
            $resArr = array("success" => $success, "data" => $data, "message" => $message);

        } else {
            $resArr = array("success" => 0, "data" => array(), "message" => "Email or password invalid.");
        }
    } else {
        $resArr = array("success" => 0, "data" => array(), "message" => "Something went wrong!!!" . mysqli_error($conn));
    }
} else {
    $resArr = array("success" => 0, "data" => array(), "message" => "Parameter Missing");
}
header('Content-Type: application/json');
echo str_replace("\/", "/", json_encode($resArr, JSON_UNESCAPED_UNICODE));
?>

A: 1) Why you are using variable jsonObj instead of response ?
2) Modify your if statement like this
if(response.success==1){
     window.location.href="index.php";
}

A: window.location is not a function it is an object. Please change href property in window.location object to redirect to new url.
window.location.href = "./index.php";

A: Simple redirect to specific file

if(jsonObj.success==1)
{
window.location.href = "http://www.example.com/index.php";

}


text:
Q: Dump with special characters in table column name I'm taking over an old database, and while doing recovery tests from my dump I found out a table is wrongly backed up, the table definition is truncated.
Looking at the live db I've found a column name with special character in the name. That is the column name is Località.
My current mysql dump produces the following:
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `contabilita_banche` (
  `ID_Banca` int(6) unsigned NOT NULL default '0',
  `Descrizione` varchar(70) default NULL,
  `Località;
/*!40101 SET character_set_client = @saved_cs_client */;

The first problem is that the table doesn't end there, there are other fields after Località, so the structure dump is incomplete. Other than this the dump doesn't throw any error and the data is dumped correctly to the end.
I tried several commands, all without success:
mysqldump -r /tmp/cbnew2.sql --default-character-set=latin1 --no-tablespaces --skip-lock-tables --quick -u root -p -h host Dbname contabilita_banche
mysqldump -r /tmp/cbnew2.sql --default-character-set=utf8 --no-tablespaces --skip-lock-tables --quick -u root -p -h host Dbname contabilita_banche

Server version is 4.1.22-log, client 5.5.38. Is there any way to correctly produce the dump?

A: I tried renaming the table via "adminer" (php mysql manager) but even there the table name was not correct (not showing at all, to be honest). I tried renaming but of course I produced a new table column.
In the end I had to recreate the table.
I managed to get most of the schema from the SHOW CREATE TABLE contabilita_banche\G above.
Then I took the dump with the data, adjusted the CREATE TABLE command with a utf-8 column name and restored the new dump.
Thank you very much Rolando for your support!


text:
Q: Not able to figure out Common Expression Language conditional statement I have a Common Expression Language (CEL) expression as below
request.headers['host'].lower().contains('test.example.com')

Now above expression make sure the HTTP host header matches test.example.com domain. Now how to create a expression that will validate if there is only one host header present in the HTTP request using CEL


text:
Q: Animation is effecting every view even after calling commitAnimation I am developing a Cocos2D game. On a stage a show a UIView giving users a list of tasks to perform. There are text fields which I move up or down using Animation. My code is below.
        [textField setFrame:CGRectMake(textField.frame.origin.x, textField.frame.origin.y, textField.frame.size.width, textField.frame.size.height)];
        [inviteButton setFrame:CGRectMake(inviteButton.frame.origin.x, inviteButton.frame.origin.y, inviteButton.frame.size.width, inviteButton.frame.size.height)];
        [headingLabel setFrame:CGRectMake(headingLabel.frame.origin.x, headingLabel.frame.origin.y, headingLabel.frame.size.width, headingLabel.frame.size.height)];

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.3];
        [UIView setAnimationDelegate:self];
        [textField setFrame:CGRectMake(textField.frame.origin.x, textField.frame.origin.y-50, textField.frame.size.width, textField.frame.size.height)];
        [inviteButton setFrame:CGRectMake(inviteButton.frame.origin.x, inviteButton.frame.origin.y-50, inviteButton.frame.size.width, inviteButton.frame.size.height)];
        [headingLabel setFrame:CGRectMake(headingLabel.frame.origin.x, headingLabel.frame.origin.y-30, headingLabel.frame.size.width, headingLabel.frame.size.height)];
        [UIView commitAnimations];
        [self.view.layer removeAllAnimations];

Problem is that even after user is done and he presses the cancel button to remove this view from the super view, every view including UIAlertView and other subviews appearing in my map after removing that view are effected by the animation i used to move text fields and label up or down. UIAlertView is using same Animation to show up and so is happening other subviews. Can anyone please tell me why this is happening?
Best Regards

A: You have to set the animationID to a unique value in the beginAnimations:context: method.
See the official doc
Also this doc states:

Use of this method is discouraged in iOS 4.0 and later. You should use the block-based animation methods to specify your animations instead.


text:
Q: Solving system of congruences where $m$'s are not coprime I'm really struggling with how to find the solution to a system of congruences where the m_i's are not relatively prime. For example:
$x ≡ 3 (mod4)$
$x ≡ 1 (mod6)$.
I know this has a unique solution mod 12 but I'm stuck here. I read through some similar questions but I'm still confused. Since I can't use the Chinese Remainder Theorem, how do I find the solution?

A: Write $$4k+3 =x=6l+1$$ so we have
$$2k+1=3l \Longrightarrow 2\mid 3l-1 \Longrightarrow 2\mid l-1 \Longrightarrow l-1=2n$$
Thus $l=2n+1$ and $k=3n+1$ and finally $x= 12n+7$. Or if you want $x\equiv 7 \pmod {12}$.

A: For small values, like your problem, you can use the method of adding the modulus:
$\pmod{6}: x\equiv 1\equiv 7 $.
Then noting that also $7\equiv 3 \pmod{4}$, you have your solution:
$x\equiv 7 \pmod{12}$
(Sometimes you may have to add the modulus more than once.)

A: You use the CRT for each modulus, then combine the results.  For your system,
$x \cong 3 \pmod{4}$ just gives you that congruence (because $4$ is a power of a prime) and then $x \cong 1 \pmod{6}$ gives \begin{align*}
    x &\cong 1 \pmod{2}  \\
    x &\cong 1 \pmod{3}  \text{.}
\end{align*}
The first of these is redundant with the previous equation ("$x$ is odd" is compatible with but tells you less than $x \cong 3 \pmod{4}$.)  So your three equations reduce to \begin{align*}
    x &\cong 3 \pmod{4}  \\
    x &\cong 1 \pmod{3}  \text{.}
\end{align*}
Then reassemble using the CRT: $x \cong 7 \pmod{12}$.