text:
Q: json column with nested values I have a JSON type SQL column in SQL table as below example. I want the below code to be converted into separate columns such as drugs as table name and other attribute as column name, how can I use adf or any other means please guide. The below code is a example of table called report where I need to convert this into separate columns .
{
    "drugs": {
        "Codeine": {
            "bin": "Y",
            "name": "Codeine",
            "icons": [
                93,
                100,
                103
            ],
            "drug_id": 36,
            "pathway": {
                "code": "prodrug",
                "text": "is **inactive**, its metabolites are active."
            },
            "targets": [
                "OPRM1"
            ],
            "rxnorm_id": "2670",
            "priclasses": [
                "Analgesic/Anesthesiology"
            ],
            "references": [
                1,
                2,
                9,
                17,
                29,
                30,
                159,
                171
            ],
            "subclasses": [
                "Analgesic agent",
                "Antitussive agent",
                "Opioid agonist",
                "Phenanthrene "
            ],
            "metabolizers": [
                "CYP2D6"
            ],
            "phenotype_ids": {
                "OPRM1": "78",
                "metabolic": "6"
            },
            "relevant_genes": [
                "CYP2D6",
                "OPRM1"
            ],
            "dosing_guidelines": [
                {
                    "text": "Normal to reduced morphine formation. Use label recommended age- or weight-specific dosing. If no response, may need to consider alternative analgesics such as morphine or a non-opioid.",
                    "source": "Genotype predicted",
                    "guidelines_id": 103
                }
            ],
            "drug_report_notes": [
                {
                    "text": "Predicted codeine metabolism is reduced.",
                    "icons_id": 58,
                    "sort_key": 58,
                    "references_id": null
                },
                {
                    "text": "Genotype suggests a possible decrease in exposure to the active metabolite(s) of codeine.",
                    "icons_id": 93,
                    "sort_key": 56,
                    "references_id": null
                },
                {
                    "text": "Decreased analgesic effects due to OPRM1 genotype.",
                    "icons_id": 100,
                    "sort_key": 52,
                    "references_id": null
                },
                {
                    "text": "Professional guidelines exist for the use of codeine in patients with this genotype and/or phenotype.",
                    "icons_id": 103,
                    "sort_key": 50,
                    "references_id": null
                }
            ]
        },
        "Dapsone": {
            "bin": "X",
            "name": "Dapsone",
            "icons": [
                99
            ],
            "drug_id": 514,
            "pathway": {
                "code": "dualactive",
                "text": "and its metabolites are **active**."
            },
            "targets": [],
            "rxnorm_id": "3108",
            "priclasses": [
                "Infectious disease"
            ],
            "references": [
                1
            ],
            "subclasses": [
                "Miscellaneous antibiotic agent"
            ],
            "metabolizers": [],
            "phenotype_ids": {},
            "relevant_genes": [],
            "dosing_guidelines": [
                {
                    "text": "Hemolysis and Heinz body formation may be exaggerated in individuals with a glucose-6-phosphate dehydrogenase (G6PD) deficiency, or methemoglobin reductase deficiency, or hemoglobin M. This reaction is frequently dose-related. Dapsone should be given with caution to these patients or if the patient is exposed to other agents or conditions such as infection or diabetic ketosis capable of producing hemolysis. Drugs or chemicals which have produced significant hemolysis in G6PD or methemoglobin reductase deficient patients include dapsone, sulfanilamide, nitrite, aniline, phenylhydrazine, napthalene, niridazole, nitro-furantoin and 8-amino-antimalarials such as primaquine. Toxic hepatitis and cholestatic jaundice have been reported early in therapy. Hyperbilirubinemia may occur more often in G6PD deficient patients. When feasible, baseline and subsequent monitoring of liver function is recommended; if abnormal, dapsone should be discontinued until the source of the abnormality is established.",
                    "source": "FDA - Additional testing",
                    "guidelines_id": 453
                }
            ],
            "drug_report_notes": [
                {
                    "text": "According to FDA labeling, additional laboratory testing may be indicated.",
                    "icons_id": 99,
                    "sort_key": 51,
                    "references_id": null
                }
            ]
        },
        "Digoxin": {
            "bin": "B",
            "name": "Digoxin",
            "icons": [],
            "drug_id": 47,
            "pathway": {
                "code": "nometab",
                "text": "is not significantly metabolized, or not absorbed."
            },
            "targets": [],
            "rxnorm_id": "3407",
            "priclasses": [
                "Cardiovascular"
            ],
            "references": [
                1
            ],
            "subclasses": [
                "Antiarrhythmic agent",
                "Cardiac glycoside",
                "Miscellaneous antiarrhythmic agent"
            ],
            "metabolizers": [],
            "phenotype_ids": {},
            "relevant_genes": [],
            "dosing_guidelines": [],
            "drug_report_notes": [
                {
                    "text": "All of digoxin's actions are mediated through its effects on Na-K ATPase. Up to 70% of the dose is excreted unchanged in the urine and only a small percentage (13%) of a dose of digoxin is metabolized in healthy volunteers. The metabolism of digoxin is not dependent upon the cytochrome P-450 system, and digoxin is not known to induce or inhibit the cytochrome P-450 system. Digoxin is a substrate for P-glycoprotein (P-gp). As an efflux protein on the apical membrane of enterocytes and of renal tubular cells, P-glycoprotein may limit the absorption and enhance the excretion of digoxin, respectively. Studies have suggested that variants of the ABCB1 gene (encoding P-gp) may influence digoxin serum levels; however, changes in digoxin exposure related to ABCB1 genotype are generally small (10-30%), account only for approximately 10% of the variability seen in digoxin pharmacokinetics, and are unlikely to be clinically significant.",
                    "icons_id": 60,
                    "sort_key": 1,
                    "references_id": null
                }
            ]
        },
        "Doxepin": {
            "bin": "Y",
            "name": "Doxepin",
            "icons": [
                92,
                103
            ],
            "drug_id": 452,
            "pathway": {
                "code": "dualactive",
                "text": "and its metabolites are **active**."
            },
            "targets": [],
            "rxnorm_id": "3638",
            "priclasses": [
                "Psychiatry"
            ],
            "references": [
                1,
                2,
                50
            ],
            "subclasses": [
                "Antidepressant",
                "Tricyclic antidepressant"
            ],
            "metabolizers": [
                "CYP2C19",
                "CYP2D6"
            ],
            "phenotype_ids": {
                "metabolic": "5"
            },
            "relevant_genes": [
                "CYP2C19",
                "CYP2D6"
            ],
            "dosing_guidelines": [
                {
                    "text": "Certain drugs inhibit the activity of CYP2D6 and make normal metabolizers resemble poor metabolizers. An individual who is stable on a given dose of TCA may become abruptly toxic when given one of these inhibiting drugs as concomitant therapy. Concomitant use of tricyclic antidepressants with drugs that can inhibit cytochrome P450 2D6 may require lower doses than usually prescribed for either the tricyclic antidepressant or the other drug. Furthermore, whenever one of these other drugs is withdrawn from co-therapy, an increased dose of tricyclic antidepressant may be required. It is desirable to monitor TCA plasma levels whenever a TCA is going to be coadministered with another drug known to be an inhibitor of cytochrome P450 2D6.",
                    "source": "FDA",
                    "guidelines_id": 349
                },
                {
                    "text": "A 25% reduction of recommended starting dose may need to be considered. Utilize therapeutic drug monitoring to guide dose adjustments.",
                    "source": "Genotype predicted",
                    "guidelines_id": 66
                }
            ],
            "drug_report_notes": [
                {
                    "text": "Genotype suggests a possible increase in exposure to doxepin.",
                    "icons_id": 92,
                    "sort_key": 57,
                    "references_id": null
                },
                {
                    "text": "Professional guidelines exist for the use of doxepin in patients with this genotype and/or phenotype.",
                    "icons_id": 103,
                    "sort_key": 50,
                    "references_id": null
                }
            ]

The expected output i need is
Table name : drugs
bin
name
n so on for other values

A: You can use openjson to shred the document into smaller pieces:
DECLARE @json NVARCHAR(MAX) = 'your json'

select json_value(x.value,'$.name') AS name
  , json_value(x.value,'$.bin') AS bin
  , json_value(x.value,'$.drug_id') AS drugId
  , json_value(x.value,'$.pathway.code') AS pathcode
  , json_value(x.value,'$.icons[0]') icon1
from openjson(@json, '$.drugs') x

Some of your properties are arrays etc, and those are a bit harder to put into single columns, so you got some work for you. You might wanna read about JSON_VALUE, JSON_QUERY to figure out what exactly you might need

A: This is a quick example of how to parse json and nested arrays. You just have to OUTER APPLY OPENJSON() on the nested array and define the columns with WITH
    SELECT
        main.ID
        , Owner.email
    FROM
        tblWithJson aj
        OUTER APPLY OPENJSON(aj.JsonColumnName)
    WITH
        (
            ID INT 'strict $.ID'
            , Owner NVARCHAR(MAX) '$.ActualNameOfElementFromNestedArray' AS JSON  --nested array
        ) AS main
    OUTER APPLY OPENJSON(Owner)
    WITH
        (
             Email VARCHAR(255) ' $.Email'
        ) AS Owner
    ;

A: You can use zq and the Zed language to transform your data into a table format. Once it's in a neat table you can easily insert it into a schema-defined table in a database. You will have to figure out what to do with the arrays though. Some dbs support arrays but others do not.
over drugs
| {name: key[0], ...value}
| over flatten(this) => ( {key: join(key, "."), value}
    | collect(this)
    | yield collect
  )
| unflatten(this)
| fuse

That will output data that looks like so:

You can either download the Zui Desktop App and use it to transform your data into a csv file. Or you can use the zq command line tool. The command for zq would be:
zq -f csv 'over drugs
| {name: key[0], ...value}
| over flatten(this) => ( {key: join(key, "."), value}
    | collect(this)
    | yield collect
  )
| unflatten(this)
| fuse' json-column-with-nested-values.json


text:
Q: How to replace a mathfrak uppercase letter by a "large" lowercase My students find it difficult to read (and reproduce) \mathfrak{S}. I'd like to replace it with a large \mathfrak{s}.
Here is what I've done so far
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utopia]{mathdesign}
\usepackage{graphicx,amsmath}
\begin{document}
\begin{gather}
\mathfrak{s}(t) = \mathfrak{S}\cos(\omega t) \\
\mathfrak{s}(t) = \scalebox{1.6}{$\mathfrak{s}$}\cos(\omega t)
\end{gather}
\end{document}

*

*Is there a cleaner way to scale the \mathfrak{s}?

*Is it possible to make \mathfrak{S} expands to \scalebox{1.6}{$\mathfrak{s}$}?

*Is there a better aproach?

A: *

*Scaling is surely good with \scalebox

*Define a \mathfrakS command along these lines
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utopia]{mathdesign}
\usepackage{graphicx,amsmath}
\newcommand{\mathfrakS}{\mathpalette\bigmathfrakS\relax}
\newcommand{\bigmathfrakS}[2]{\scalebox{1.6}{$#1\mathfrak{s}$}}

\begin{document}
\begin{gather}
\mathfrak{s}(t) = \mathfrakS\cos(\omega t) \\
\mathfrakS_{\mathfrakS_{\mathfrakS}}
\end{gather}
\end{document}

*Use \mathfrak{S} and the students will learn it. Or use a different symbol altogether.

Alternative approach, which uses \mathfrak{S}, so that you can remove the macros when you decide that a Fraktur S is not a problem any more:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utopia]{mathdesign}
\usepackage{graphicx,amsmath}

\let\ORGmathfrak\mathfrak
\def\mathfrak#1{{\ifnum\pdfstrcmp{#1}{S}=0 \mathfrakS\else\ORGmathfrak{#1}\fi}}

\newcommand{\mathfrakS}{\mathpalette\bigmathfrakS\relax}
\newcommand{\bigmathfrakS}[2]{\scalebox{1.6}{$#1\ORGmathfrak{s}$}}

\begin{document}
\begin{gather}
\mathfrak{s}(t) = \mathfrak{S}\cos(\omega t) \\
\mathfrak{S}_{\mathfrak{S}_\mathfrak{S}}
\end{gather}
\end{document}

A: Try using the relsize package:
\documentclass{article}
\usepackage{amssymb,relsize}

\begin{document}
\[
  \mathfrak{s} \mapsto \mathlarger{\mathfrak{s}}
\]
\end{document}

If you want yet larger font, repeat the command.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to link to another liferay page I'm trying to figure out how to link to another page within the same liferay site.
Obviously I could hardcode the url in my portlet's view but I'm worried about having to update all of my portlets in case the friendly url changes in the future.
I know the name of the page I'm trying to link to, but what if the page name changes too?
I've found infinity of classes that have methods that return friendlyUrls, such as PortalUtil, LayoutLocalServiceUtil, and even LayoutFriendlyURLLocalServiceUtil, but they all require parameters that I'm not sure how to obtain.
Is there a standard way of obtaining friendly urls in liferay?

A: If you want to link to another Page, you can either use LayoutId or friendly url names.
Both are unique for each companyId, so you are going to be pretty safe using them.
You can set the friendlyUrl as a PortletConfig parameters, so you can set them on portlet Level, and you won't have them hard-coded in your Portlet. Alternatively, you can also save them as custom params in portal-ext.properties (will apply for all portlets of that portal).
Now, that's a lot of code for this, so if you're dealing with specific problems, like creating Portlet Configuration or Reading portal-ext.properties, or creating renderUrls programatically, you should start new questions


text:
Q: Trying to create sudoku game using tkinter grid, got problem with the GUI grid I am trying to build a sudoku game. I got problem with the GUI. The game is consisted of 9 blocks, each block has 9 cells. But I can only get the last 3 blocks. I miss the first 6 rows. This is the result I got:

The code is as follow:
import tkinter as tk

root = tk.Tk()

# Create the puzzle
puzzle = tk.Frame(root, bg='white')
puzzle.pack()

# Add the 3 * 3 big blocks
blocks = [[None] * 3] * 3
for i in range(3):
    for j in range(3):
        blocks[i][j] = tk.Frame(puzzle, bd=1, highlightbackground='light blue',
                                highlightcolor='light blue', highlightthickness=1)
        blocks[i][j].grid(row=i, column=j, sticky='nsew')

# Add the 9 * 9 cells
btn_cells = [[None] * 9] * 9
for i in range(9):
    for j in range(9):
        # Add cell to the block
        # Add a frame so that the cell can form a square
        frm_cell = tk.Frame(blocks[i // 3][j // 3])
        frm_cell.grid(row=(i % 3), column=(j % 3), sticky='nsew')
        frm_cell.rowconfigure(0, minsize=50, weight=1)
        frm_cell.columnconfigure(0, minsize=50, weight=1)
        var = tk.StringVar()
        btn_cells[i][j] = tk.Button(frm_cell, relief='ridge', bg='white', textvariable=var)
        btn_cells[i][j].grid(sticky='nsew')

        # Show the index for reference
        var.set(str((i, j)))

root.mainloop()

Any help is appreciated.

A: The problem is
blocks = [[None] * 3] * 3

it doesn't create 3 unique sublists but it creates 3 reference to the same list.
It should be
blocks = [[None for x in range(3)] for x in range(3)]

I would also use
btn_cells = [[None for x in range(9)] for x in range(9)]

Frankly, I would write it in different way - using apppend()
blocks = []
for r in range(3):  # `r` like `row`
    row = []
    for c in range(3):  # `c` like `column`
        frame = tk.Frame(puzzle, bd=1, highlightbackground='light blue',
                                highlightcolor='light blue', highlightthickness=1)
        frame.grid(row=r, column=c, sticky='nsew')
        row.append(frame)
    blocks.append(row)


text:
Q: Multiple fullstops in regex for RewriteRule I use the following rule to redirect pretty urls from http://hostname.co.za/geoip/123.12.123.34 to http://hostname.co.za/geoip/index.py?ip=123.12.123.34
.htaccess in /geoip
RewriteEngine on
RewriteRule ^(.*\..*\..*\..*)$ /geoip/index.py?ip=$1

This works fine to match only ip's, but when I try this, it gives a 500 server error:
RewriteEngine on
RewriteRule ^(.*\..*)$ /geoip/index.py?ip=$1

I want to match not only ip's, but hostnames with at least one fullstop as well.
I have no idea why this shouldn't work...

A: The problem with the second pattern is that it also matches index.py and thus yields an infinite recursion. You can exclude that by using a RewriteCond:
RewriteCond $1 !=index.py
RewriteRule ^(.*\..*)$ /geoip/index.py?ip=$1

Furthermore, you should use a more specific pattern than .* like [^/.]+, so:
RewriteCond $1 !=index.py
RewriteRule ^([^/.]+\.[^/.]+)$ /geoip/index.py?ip=$1
RewriteRule ^([^/.]+\.[^/.]+\.[^/.]+\.[^/.]+)$ /geoip/index.py?ip=$1


text:
Q: Angular Universal page doesn't update until mouse event I've ported an Angular 5 app over to Angular Universal and I'm seeing odd behaviour. My pages are rendering fine, but only after some sort of mouse action. For example, the page loads (I assume just the server-side version), and then when I mouse over a menu item, the page instantly updates to show the actual updated page with content.
I tried adding a manual change detection update (see below) just to see if it would help. It did not.
constructor(... , private changeRef: ChangeDetectorRef ) {}

// after calling my web service to get content (browser side)
this.changeRef.detectChanges();

Here's my main.ts file:
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule);

A: The solution seems to be to use NgZone.run().
import { NgZone, } from '@angular/core';

...
constructor( private _ngZone: NgZone ) {}
...

this._ngZone.run(() => {
  // code that calls the REST API here
});


text:
Q: Error occurred during initialization of boot layer in JavaFX Creating simple javafx 17.0.2 application. Getting error.

*

*OS: Windows 11

*Java SE Development Kit: 17.0.2

*javafx: 17.0.2

Error
Error occurred during initialization of boot layer
java.lang.module.FindException: Module aparajita.suman.demo not found

hello-view.fxml
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.media.MediaView?>

<fx:root maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" type="AnchorPane" xmlns="http://javafx.com/javafx/18" xmlns:fx="http://javafx.com/fxml/1" fx:controller="aparajita.suman.demo.HelloController">
   <children>
      <MediaView fitHeight="360.0" fitWidth="600.0" layoutY="7.0" />
      <Button fx:id="playButton" layoutX="72.0" layoutY="367.0" mnemonicParsing="false" text="Play" />
      <Button fx:id="pauseButton" layoutX="236.0" layoutY="367.0" mnemonicParsing="false" text="Pause" />
   </children>
</fx:root>

HelloApplication.java
package aparajita.suman.demo;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;

public class HelloApplication extends Application {
    @Override
    public void start(Stage stage) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("hello-view.fxml"));
        Scene scene = new Scene(fxmlLoader.load(), 600, 400);
        stage.setTitle("Hello!");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}

In pom.xml
<dependency>
   <groupId>org.openjfx</groupId>
   <artifactId>javafx-media</artifactId>
   <version>17.0.2</version>
</dependency>

module-info.java
module aparajita.suman.demo {
    requires javafx.controls;
    requires javafx.fxml;
    requires javafx.media;

    opens aparajita.suman.demo to javafx.fxml;
    exports aparajita.suman.demo;
}

In VM option
--module-path "C:\Users\HP\Downloads\javafx-sdk-17.0.2\lib" --add-modules javafx.media,javafx.controls
This is my project structure


text:
Q: Word to describe someone who makes frequent bodily sounds I am wondering if there is a word for someone whose bodily noises are especially loud. Example actions include:
Sample sentence:

The world had never quite seen a body like Jared's. Between the lip smacking, farting, and labored breathing, he was the embodiment of .

-Lip smacking
-Breathing heavily
-Frequently humming/murmuring
-Flatulent
-Heft or weight to all their actions resulting in noise
Someone similar question here, except this word would extend beyond eating. The character is not dirty, so words like slovenly don't really work.
I thought the appropriate word might be gesticulating, but that is more concerned with the behavior of how someone delivers speech.

A: Not an exact answer, but an aversion to these sounds is sometimes called misophonia. Finally discovered a word to capture my original feeling.


text:
Q: Why's the button displayed only when refreshing the page? I want the logout button to show up only when the user's logged in.  It kind of works now but it's not working the way it should.
With the code below, the logout button shows up when the user's logged in only if the page's refreshed.  That's because upon the <App/> component being loaded, the <Navbar/> component mounted along with it.
But how can I make it so that even if <Navbar/>'s loaded, it can still be possible to manipulate when the button can appear based on if the auth token is not null?
Here's App.js:
const App = () => {
let [logoutButtonFlag, setLogoutButtonFlag] = useState(false);
let authToken = localStorage.getItem('token');

useEffect(() => {
    if (authToken !== null) {
        setLogoutButtonFlag(true);
    }
}, [authToken]);

return (
    <>
      <Navbar logoutButtonFlag={logoutButtonFlag}/>
    </>
  );
}

export default App;

Here's Navbar.js:
const Navbar = (props) => {
    return (
      {!props.logoutButtonFlag ? null : <button className="learn-more">Logout</button>}
    );
};

export default Navbar;

A: you are providing a non-state variable to the list of states that useEffect hook 'listen' to, so it will not run again after you change its value.
const [authToken, setAuthToken] = useState(localStorage.getItem('token'));

and when you update the local storge "token" also update authToken to the same value.
and your useEffect will retrigger on authToken change because now its a state
useEffect(() => {
    if (authToken !== null) {
        setLogoutButtonFlag(true);
    }
}, [authToken]);

The reason way only on refresh it was updating is because the value of the "token" in local storage was changed already.


text:
Q: authenticate to Google Cloud Platform from a Linux Server I have developed a java program that involves API connections, DataFlow pipelines and BigQuery to load data.
Locally in my computer it works fine with GCP authenticator and running pipelines in the cloud.
But when I run a class in the linux server it ask me for authentication but with an url.
this is the output in the server
I tried "gcloud init" sending credentials but it still asking me for authentication.
has anyone faced this situation?
thanks!

A: Your application is attempting to use OAuth 2.0 Flow to obtain credentials. Since your server does not have a web browser, you are given a URL to go to in your browser. Once you do that you will receive a code to copy-and-paste back into your server.
The solution is to change your program to use Google Service Account Credentials.
This link has a detailed explanation and code examples including Java.
Setting Up Authentication for Server to Server Production Applications


text:
Q: Show that each $a_n$ is divisible by a prime which does not appear in the factorization of any $a_i$, iConsider the sequence of integers $a_n$ defined recursively by $a_n=a_{n-1}a_{n-2}...a_0 + 1$ with $a_0=1$. Show that each $a_n$ is divisible by a prime which does not appear in the factorization of any $a_i$, i

I was thinking of resembling it to Euclid's proof of infinitely many primes.

A: it's exactly the same. since $a_n$ is not divisible by any of the prime factors of $a_1,\, a_2,\, \cdots ,\, a_{n-1}$, there must be a prime that does not appear in their factorization that divides $a_n$

A: Suppose $p$ divides $a_i$ for $i<n$. Then $a_n=bp+1$. So if $p$ divides $a$ then $p$ divides 1, a contradiction.


text:
Q: Auto-add 'sort=unanswered' when searching from Unanswered tab? Given this recent question, would it be possible to automatically add sort=unanswered whenever a search is initiated while browsing the Unanswered tab?
Update: Sorry for my confusion, I had posted this requesting 'answers:0' which is not the same as unanswered.  Thank you for clarifying @Bill & @ChrisF.
Update 2: Note that my request pertains to Stack Overflow, as I've now realized that the default searching behavior is different from that of Meta.  These two actions take the user to different places within the UI:

*

*Click on the Meta Unanswered tab and search for java.

*Click on the Stack Overflow Unanswered tab and search for java.

A: answers:0 is not what "Unanswered" means on Stack Exchange.  "Unanswered" means there have been no upvoted or accepted answers posted.

A: You can already do this.
Use the "No Answers" tab:
https://stackoverflow.com/unanswered/tagged/?tab=noanswers


text:
Q: Can I give fish/bugs I catch in animal crossing new leaf to other people online? My girlfriend recently got the game, and I wanna help her out a bit. Is there anyway I can give her fish or bugs?

A: According to this: https://gamefaqs.gamespot.com/3ds/997811-animal-crossing-new-leaf/answers/353555-can-i-give-fish-and-bugs-to-friends
You cannot give somebody else fish or bugs.


text:
Q: how do I change a directory /root and copy a file school to txt root@47dac26876d7:/# cd /root
root@47dac26876d7:~# ls
empty_directory  not_here  old_school  ready_to_be_removed  school  so_cool
root@47dac26876d7:~# cp school
cp: missing destination file operand after 'school'
Try 'cp --help' for more information.

A: man cp will provide you with a brief manual on the command. It is written in compact and rather technical language, efficient if you have some experience with the linux shell, but rather terse and difficult to access for new users. It is rather advised that new users should learn the basics from either textbooks or tutorial websites.
The documentation, man cp says
cp [OPTION]... [-T] SOURCE DEST
cp [OPTION]... SOURCE... DIRECTORY
cp [OPTION]... -t DIRECTORY SOURCE...

In each of the three use forms, at least two arguments are needed, the SOURCE and the DEST or target DIRECTORY.
So you need a second argument that tells the cp command where to copy the file. That could be another file name, in the current directory or in a totally different location (first form), or an existing directory (second form). Third form uses the option -t to specify a target DIRECTORY before the SOURCE (one or multiple file names, ad indicated by the ...).
Warning As a new user unfamiliar with a basic command such as cp, you are playing with fire running a terminal as root user and trying to shuffle files around in the system files area. Don't, or be prepared to reinstall your system now and then. Only use sudo privileges where absolutely necessary to modify the system. In that context, it is good practice to never drop to a root prompt, but just prepend these commands that need to be run with root privileges with sudo.


text:
Q: How to fix my app to login using id and password online using Firebase I'm a beginner in Android Studio. By watching a video I made this app to login to my application by using id and password stored in Firebase. Everything in my view is OK but when I run the app and enter id and password (even right one), it will crash.
I checked everything but still have problem. I took a picture of Logcat and upload here.
This is mainactivity:
public class MainActivity extends AppCompatActivity {

    EditText edtUsername, edtPassword;
    Button btnSignIn;
    DatabaseReference databaseReference;

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

        edtUsername=(EditText)findViewById(R.id.edtUsername);
        edtPassword=(EditText)findViewById(R.id.edtPassword);
        btnSignIn=(Button) findViewById(R.id.btnSignIn);

        databaseReference= FirebaseDatabase.getInstance().getReference("Students");

        btnSignIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                logIn(edtUsername.getText().toString(),edtPassword.getText().toString());
            }
        });
    }

    private void logIn(final String id, final String password) {

        databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                if (dataSnapshot.child(id).exists()){

                    if (!id.isEmpty()){
                        User user=dataSnapshot.child(id).getValue(User.class);
                        if (user.getPassword().equals(password)){
                            Toast.makeText(MainActivity.this, "Successful Login", Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(MainActivity.this, "Incorrect Password", Toast.LENGTH_SHORT).show();
                        }
                    }else{
                        Toast.makeText(MainActivity.this, "User is Not Registered", Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(MainActivity.this, "User is Not Registered", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
}

this is User.class page:
public class User {

    private String id;
    private String password;

    public String getId() {

        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getPassword() {

        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public User() {
    }
}

and this is log result:

A: You User.class defines password as String whereas in the firebase it is stored as Long.
User user=dataSnapshot.child(id).getValue(User.class);

SOLUTION
Simply change your User.class file to:
public class User {

  private String id;
  private Long password;

  public String getId() {
    return "" + id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public String getPassword() {
    return password.toString();
  }

  public void setPassword(Long password) {
    this.password = password;
  }

  public User() {
  }
}


text:
Q: can I stop all email sending from a wordpress site ?where to do this wp-includes/class-phpmailer.php? howto close all email sending option in that word press config. should i use
wp-includes/class-phpmailer.php ? or where ?
 if ($this->SingleTo === true && count($toArr) > 1) {
        foreach ($toArr as $key => $val) {
          $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
          // implement call back function if it exists
          $isSent = ($rt == 1) ? 1 : 0;
          $this->doCallback($isSent,$val,$this->cc,$this->bcc,$this->Subject,$body);
        }
      }

will this do ?

A: Add the following code to wp-config.php, it will stop sending of all emails
function wp_mail()
{
    //silence is golden!!
}


text:
Q: Reading and displaying multiple MRI images I want to read 100 different MRI images in MATLAB using this code:
% Preallocate the 256-by-256-by-1-by-20 image array.
X = repmat(int16(0), [256 256 1 20]);
% Read the series of images.
 for p=1:20
   filename = sprintf('brain_%03d.dcm', p);
   X(:,:,1,p) = dicomread(filename);
end
% Display the image stack.
montage(X,[])

but this error is showing up:

Subscripted assignment dimension mismatch.

What is wrong with this code?

A: You have a subscripted assignment dimension mismatch. sprintf() is not of size (256x256), because X(:,:,1,p)is using the wrong dimensions.
Let's say that you wanted to store a 4 rows, 4 cols image. With intensity ranging from 0-255. Then you have a total of 16 elements, that each have a unique intensity value.
This
(:,:,1) implies N dimension, by N dimension by 1.
Given a 4x4 is ([1:4],[1:4],1).
X(:,:,1,p) is a set of a set of images.


text:
Q: Smarter Window Opening? I doubt if a tool like this exists, but it would be nice. So many times, I open an explorer window, and then another explorer window or a different app so that I can drag something from the explorer window into that app to open it, or to copy the file to my USB stick. Every single time one window opens on top of the other. I have TWO monitors, a lot of screen real-estate... why does Windows find it necessary to put the new window the one place I don't want it?
Is there an app that can look at the last window I had active, and then when a new window opens, put it somewhere else? Like, on the opposite monitor, or at least beside the other window?

A: You might love WinSplit Revolution together with AllSnap and optionally Finestra Virtual Desktops.

A: In Windows7 you can winleft for the first explorer, then wine for the 2nd explorer which you then winright to the right side of the screen.
If that does not satisfy you: look into something like
What Tiling Window Manager for Windows do you recommend?
and http://www.autohotkey.net/~joten/bug.n/help.html to let others do the placement of the windows for you.


text:
Q: Multiple int input in same line python I want to take multiple integer inputs in the same line. I know I can take str input and then convert them into integer in the next line but is there any way I can do it in the same line.
I have tried this:
x,y = int(input("->")).split()
print(x,y)

I am getting this error :
 ValueError: invalid literal for int() with base 10

A: You messed up with parenthesis (split works on string not int)
then you expect a tuple for x,y = ...
the solution is:
x, y = [int(i) for i in input("->").split()]
print(x, y)

A: You are taking int as input which cant be split
x,y = input("->").split()
print(x,y)

you can change to int if you like later
print(int(x),int(y))


text:
Q: Converting a string into a mathematical object I don't know if this is possible. I'm in a situation where the input is going to look like this:
[int, String, int]

Where the string is either "<", ">", "=", "<=", ">=".
Is there the way to implement a method that would help me compare the two ints with respect to the string compare parameter without multiple if statements?
I hope I've explained it well.
Thanks.

A: There's no way to apply a string as if were an operator in Java source code. You're going to have to test each string value and do the appropriate test.
public boolean eval(int arg1, String op, int arg2) {
    if (op.equals("<")) {
        return arg1 < arg2;
    } else if (op.equals("<=")) {
        return arg1 <= arg2;
    } else . . .
}

There are ways to get very fancy about this (with, for example, a Map<String, Callable<Boolean>>), but it doesn't seem worth it for what you're describing.
Alternatively (as CM Kanode and screppedcola suggest in their comments) you can evaluate an expression as JavaScript, using a ScriptEngine, but this also seems like overkill.


text:
Q: jQgrid's gridComplete event is firing but loadComplete is not firing..... why? In my ASP.NET project I am integrating jQgrid to show data. My Problem is loadComplete event is not firing. My entire jQgrid code is as follows:
function getData(jqGridParams)
    {
        var sortcookieval = $.cookie("ItemGridSortInfo");
        var sname = "";
        var sorder = "";
        if (sortcookieval != null)
        {
            var sortInfo = sortInfoFromCookie("ItemGridSortInfo");
            sname = sortInfo.sortname;
            sorder = sortInfo.sortorder;
        }
        else
        {
            sname = "";
            sorder = "asc";
        }
        var params = new Object();
        params.pageIndex = jqGridParams.page;
        params.pageSize = jqGridParams.rows;
        params.sortIndex = sname; //jqGridParams.sidx;
        params.sortDirection = sorder;  //jqGridParams.sord;
        params._search = jqGridParams._search;
        if (jqGridParams.filters === undefined)
            params.filters = null;
        else
            params.filters = jqGridParams.filters;

        $.ajax({
            url: 'WSAjax.asmx/GetDataForGrid',
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: JSON.stringify(params),
            success: function (data, textStatus)
            {
                if (textStatus == "success")
                {
                    var grid = $("#ItemGrid")[0];
                    grid.addJSONData(data.d);
                }
            },
            error: function (jqXHR, textStatus, errorThrown)
            {
                alert(textStatus, errorThrown);
            }
        });
    }

    function saveSortInfoToCookie(name, grid)
    {
        var sortInfo = new Object();
        sortInfo.sortname = grid.jqGrid('getGridParam', 'sortname');
        sortInfo.sortorder = grid.jqGrid('getGridParam', 'sortorder');
        //$('#Hidden').val(JSON.stringify(gridInfo));
        //alert($('#Hidden').val());
        $.cookie(name, JSON.stringify(sortInfo), {expires: 5});
    }

    function sortInfoFromCookie(name)
    {
        var c = $.cookie(name);
        if (c === null)
            return;
        return $.parseJSON(c);
    }

    $(document).ready(function () {
        var oItemGrid = $("#ItemGrid");
        oItemGrid.jqGrid({
            datatype:
                function (jqGridParams) {
                    getData(jqGridParams);
                },
            colNames: ['Type', 'Name', 'Desc'],
            colModel: [
                { name: 'Type', index: 'Type', width: 40 },
                { name: 'Name', index: 'Name', width: 40 },
                { name: 'Desc', index: 'Desc', width: 40, sortable: false}],
            autowidth: true,
            height: 'auto',
            rowNum: 10,
            rowList: [10, 20, 30, 40],
            viewrecords: true,
            gridview: true,
            autoencode: true,
            ignoreCase: true,
            caption: 'Remember Sorting and Filtering Functionality',
            pager: '#IGPager',
            onSortCol: function (colModel, colName, sortOrder) {
                saveSortInfoToCookie("ItemGridSortInfo", $("#ItemGrid"));
                var storeval = $.cookie("ItemGridSortInfo");
                alert("Saving sort info in cookie: " + storeval);
            },
            gridComplete: function () {
                var prvData = $.cookie("ItemGridSortInfo");
                alert("Reading saved sort info from cookie : " + prvData);

                var pageno = $.cookie("ItemGridPageInfo");
                alert("Reading saved page no. from cookie:" + pageno);
            },
            loadComplete: function (data) {
                if(data != null)
                {
                    alert("Inside loadComplete..");
                }
            },
            //loadonce: true
        }).jqGrid('navGrid', '#IGPager', { edit: false, add: false, del: false }, {}, {}, {}, {}, {});
    });

and if possible please tell me difference between gridComplete and loadComplete according to my scenario....

A: The problem is you set datatype as a function (custom defined function for retrieving data) instead of local. If you use a function, then you should call loadComplete in your own implementation.
So if you change it to other type like local, the loadComplete will be handled automatically by jqGrid. I created a demo for you.
Demo


text:
Q: Defining a closed BSpline curve in Python geomdl I would like to define a closed BSpline curve in Python geomdl, but it seems the only option is an open curve, which is weird to me. I would like to create something like this:
this
Can someone help?


text:
Q: Update Table1 with the help of Table2 Scenario :
Table1 and Table2 has same columns
=>Table1 has All data
=>Table2 has updated values except "ProductCode"(this one column remain same)
I just want to match productcode from both table and need to update in Table1

please help me out

A: You can do it by this -
Update `Table1`
  INNER JOIN `Table2` ON (Table1.ProductCode = Table2.ProductCode)
  SET Table1.Category = Table2.Category
  ....

You need to give all fields to be updated.


text:
Q: Android getting URI from Camera I am having an issue when taking a photo with the camera on my Nexus 5.  I can take photos from the gallery no problem and save them to the back end.  However when I try to take a picture using the camera, after I take the picture and select the tick, then the app crashes...
I can see that the intent passed to the onActivityResult() is empty but I don't know how to fix this. Can anyone help? thanks.
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.khackett.runmate.R;
import com.khackett.runmate.utils.FileHelper;
import com.khackett.runmate.utils.ParseConstants;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseUser;
import com.parse.SaveCallback;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class MyProfileFragment extends Fragment implements View.OnClickListener {

    public static final String TAG = MyProfileFragment.class.getSimpleName();

    protected Button mTakePicture;
    protected Button mChoosePicture;

    /**
     * Default constructor
     */
    public MyProfileFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_my_profile, container, false);

        mTakePicture = (Button) rootView.findViewById(R.id.takePictureButton);
        mChoosePicture = (Button) rootView.findViewById(R.id.choosePictureButton);

        mTakePicture.setOnClickListener(this);
        mChoosePicture.setOnClickListener(this);

        return rootView;

    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        // Switch statement to select which action to take depending on button/text pressed
        switch (v.getId()) {
            case R.id.takePictureButton:
                takeCameraPicture();
                break;
            case R.id.choosePictureButton:
                chooseGalleryPicture();
                break;
            default:
                System.out.println("Problem with input");
        }
    }

    public static final int TAKE_PHOTO_REQUEST = 1888;
    public static final int PICK_PHOTO_REQUEST = 1888;
    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1888;

    // member variable to store the media type as a URI, that can be stored in multiple places
    // Uri = uniform resource identifier
    protected Uri mMediaUri;

    public void takeCameraPicture() {
        // Take picture
        // use an existing camera app on the phone by starting an intent
        // declare intent to capture a photo using whatever camera app is available
        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // after invoking the camera,
        mMediaUri = getOutputMediaFileUri();

        // check that a null value is not returned
        if (mMediaUri == null) {
            // display an error
            Toast.makeText(getActivity(), R.string.error_external_storage, Toast.LENGTH_LONG).show();
        } else {
            // to add extra data to an intent, use the putExtra() method
            takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mMediaUri);
            // start an activity for a result so that the activity exits and returns a result back for us
            // ie, the main activity will wait for the result
            startActivityForResult(takePhotoIntent, TAKE_PHOTO_REQUEST);
        }
    }

    public void chooseGalleryPicture() {
        // Choose picture
        Intent choosePhotoIntent = new Intent(Intent.ACTION_GET_CONTENT);
        // need to specify which type of action we want to get - an image in this case
        choosePhotoIntent.setType("image/*");
        startActivityForResult(choosePhotoIntent, PICK_PHOTO_REQUEST);
    }

    private Uri getOutputMediaFileUri() {
        // To be safe, you should check that the SD card / external storage is mounted
        // using Environment.getExternalStorageState() before doing this.
        // see method below...
        if (isExternalStorageAvailable()) {
            String appName = MyProfileFragment.this.getString(R.string.app_name);
            // get the Uri

            // Get the external storage directory - we want to return a file object
            File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), appName);

            // Create our subdirectory
            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdir()) {
                    Log.e(TAG, "Failed to create directory");
                    return null;
                }
            }

            // Create a file to hold the image
            File mediaFile;
            // get the current date and time
            Date now = new Date();
            // convert the date and time into a String datetimestamp
            // see http://developer.android.com/guide/topics/media/camera.html#saving-media for the methods used
            // need to append a timestamp to make it unique - otherwise it will overwrite the previous photo
            String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ENGLISH).format(now);

            String path = mediaStorageDir.getPath() + File.separator;

            // create a new file using the constructor that takes a name

            mediaFile = new File(path + "IMG_" + timestamp + ".jpg");

            Log.d(TAG, "File: " + Uri.fromFile(mediaFile));

            // Return the files URI
            Log.d(TAG, "Returning the files URI");
            return Uri.fromFile(mediaFile);
        } else {
            return null;
        }
    }

    /**
     * check if external storage is available on the users device
     *
     * @return
     */
    private boolean isExternalStorageAvailable() {
        // find out what state external storage is in
        String state = Environment.getExternalStorageState();
        // if external storage is available, return true,
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
                if (data == null) {
                    Log.d(TAG, "Data is null");
                    Toast.makeText(getActivity(), getString(R.string.general_error), Toast.LENGTH_LONG).show();
                } else {
                    Log.d(TAG, "Data: " + data);
                    // the intent has data, so set the media uri
                    Log.d(TAG, "adding the data using the getData() method");
                    mMediaUri = data.getData();
                    Log.d(TAG, "Media Uri: " + mMediaUri);
                }

                // ParseUser.getCurrentUser().put("profilePic", mMediaUri);

                saveImageToParse();

            }
        } else if (resultCode != Activity.RESULT_CANCELED) {
            Log.d(TAG, "Problem getting the picture from gallery");
            // Toast.makeText(getActivity(), R.string.general_error, Toast.LENGTH_LONG).show();
        }
    }

    public void saveImageToParse() {
        Log.d(TAG, "entering saveImageToParse() method");
        byte[] fileBytes = FileHelper.getByteArrayFromFile(getActivity(), mMediaUri);

        fileBytes = FileHelper.reduceImageForUpload(fileBytes);

        String fileName = FileHelper.getFileName(getActivity(), mMediaUri, "file");
        ParseFile file = new ParseFile(fileName, fileBytes);
        ParseUser.getCurrentUser().put("profilePic", file);

        ParseUser.getCurrentUser().saveInBackground(new SaveCallback() {
            public void done(ParseException e) {
                if (e == null) {
                    Log.d(TAG, "Image saved successfully");
                    // myObjectSavedSuccessfully();
                } else {
                    Log.d(TAG, "Image not saved");
                    // myObjectSaveDidNotSucceed();
                }
            }
        });

    }

.
package com.khackett.runmate.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.util.Log;

import org.apache.commons.io.IOUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

// https://github.com/treehouse/treehouse_android_utilities
public class FileHelper {

    public static final String TAG = FileHelper.class.getSimpleName();

    public static final int SHORT_SIDE_TARGET = 1280;

    public static byte[] getByteArrayFromFile(Context context, Uri uri) {
        byte[] fileBytes = null;
        InputStream inStream = null;
        ByteArrayOutputStream outStream = null;
        Log.d(TAG, "in the getByteArrayFromFile() method");

        if (uri.getScheme() != null && uri.getScheme().equals("content")) {
            try {
                Log.d(TAG, "entering try to set inputstream");
                inStream = context.getContentResolver().openInputStream(uri);
                outStream = new ByteArrayOutputStream();

                byte[] bytesFromFile = new byte[1024 * 1024]; // buffer size (1 MB)
                int bytesRead = inStream.read(bytesFromFile);
                while (bytesRead != -1) {
                    outStream.write(bytesFromFile, 0, bytesRead);
                    bytesRead = inStream.read(bytesFromFile);
                }

                fileBytes = outStream.toByteArray();
            } catch (IOException e) {
                Log.e(TAG, e.getMessage());
            } finally {
                try {
                    inStream.close();
                    outStream.close();
                } catch (IOException e) { /*( Intentionally blank */ }
            }
        } else {
            try {
                File file = new File(uri.getPath());
                FileInputStream fileInput = new FileInputStream(file);
                fileBytes = IOUtils.toByteArray(fileInput);
            } catch (IOException e) {
                Log.e(TAG, e.getMessage());
            }
        }

        return fileBytes;
    }

    public static byte[] reduceImageForUpload(byte[] imageData) {
        Bitmap bitmap = ImageResizer.resizeImageMaintainAspectRatio(imageData, SHORT_SIDE_TARGET);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
        byte[] reducedData = outputStream.toByteArray();
        try {
            outputStream.close();
        } catch (IOException e) {
            // Intentionally blank
        }

        return reducedData;
    }

    public static String getFileName(Context context, Uri uri, String fileType) {
        String fileName = "uploaded_file.";

        if (fileType.equals(ParseConstants.TYPE_IMAGE)) {
            fileName += "png";
        } else {
            // For video, we want to get the actual file extension
            if (uri.getScheme().equals("content")) {
                // do it using the mime type
                String mimeType = context.getContentResolver().getType(uri);
                int slashIndex = mimeType.indexOf("/");
                String fileExtension = mimeType.substring(slashIndex + 1);
                fileName += fileExtension;
            } else {
                fileName = uri.getLastPathSegment();
            }
        }

        return fileName;
    }
}

.
09-01 20:15:49.322  23271-23271/com.khackett.runmate E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.khackett.runmate, PID: 23271
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=67424, result=-1, data=Intent {  }} to activity {com.khackett.runmate/com.khackett.runmate.ui.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()' on a null object reference
            at android.app.ActivityThread.deliverResults(ActivityThread.java:3574)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3617)
            at android.app.ActivityThread.access$1300(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1352)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()' on a null object reference
            at com.khackett.runmate.utils.FileHelper.getByteArrayFromFile(FileHelper.java:29)
            at com.khackett.runmate.ui.MyProfileFragment.saveImageToParse(MyProfileFragment.java:233)
            at com.khackett.runmate.ui.MyProfileFragment.onActivityResult(MyProfileFragment.java:210)
            at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:165)
            at android.app.Activity.dispatchActivityResult(Activity.java:6192)
            at android.app.ActivityThread.deliverResults(ActivityThread.java:3570)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3617)
            at android.app.ActivityThread.access$1300(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1352)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

A: From the log, and your code, you can track that it is mMediaUri being null.
This should be caused by activity recreate because of screen rotation, for example, if your app usually run in Portrait, while the camera force to Landscape or you rotated when you use camera.
Anyway to solve this, you have to save the mMediaUrl and restore it in onCreate, modify your Fragment like this:
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current state
    savedInstanceState.putString("media_url", mMediaUrl.toString());

    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        mMediaUrl = Uri.parse(savedInstanceState.getString("media_url"));
    }
}

Edit:
noticed another problem, change the followings:
public static final int TAKE_PHOTO_REQUEST = 1889;
public static final int PICK_PHOTO_REQUEST = 1888;

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == PICK_PHOTO_REQUEST) {
            if (data == null) {
                Log.d(TAG, "Data is null");
                Toast.makeText(getActivity(), getString(R.string.general_error), Toast.LENGTH_LONG).show();
            } else {
                Log.d(TAG, "Data: " + data);
                // the intent has data, so set the media uri
                Log.d(TAG, "adding the data using the getData() method");
                mMediaUri = data.getData();
                Log.d(TAG, "Media Uri: " + mMediaUri);
            }

            // ParseUser.getCurrentUser().put("profilePic", mMediaUri);

            saveImageToParse();

        } else if(requestCode  == TAKE_PHOTO_REQUEST) {
            saveImageToParse();
        }
    } else if (resultCode != Activity.RESULT_CANCELED) {
        Log.d(TAG, "Problem getting the picture from gallery");
        // Toast.makeText(getActivity(), R.string.general_error, Toast.LENGTH_LONG).show();
    }
}


text:
Q: MockBukkit#mock() throwing NPE I'm trying to test my Minecraft plugin with MockBukkit, but when I'm trying to mock a server (via MockBukkit#mock()) a NPE is thrown:
java.lang.NullPointerException: Cannot invoke "org.eclipse.aether.RepositorySystem.newLocalRepositoryManager(org.eclipse.aether.RepositorySystemSession, org.eclipse.aether.repository.LocalRepository)" because "this.repository" is null

    at org.bukkit.plugin.java.LibraryLoader.<init>(LibraryLoader.java:59)
    at org.bukkit.plugin.java.JavaPluginLoader.<init>(JavaPluginLoader.java:73)
    at be.seeseemelk.mockbukkit.plugin.PluginManagerMock.<init>(PluginManagerMock.java:90)
    at be.seeseemelk.mockbukkit.ServerMock.<init>(ServerMock.java:166)
    at be.seeseemelk.mockbukkit.MockBukkit.mock(MockBukkit.java:56)

Here you can find my pom.xml: https://pastebin.com/TPjDRr9f
My test contains just a method with the annotation @BeforeAll in which I mock via MockBukkit#mock(). This issue is also mentioned here https://github.com/MockBukkit/MockBukkit/issues/614, but this issue is currently in backlog, so I'm trying to find a solution / workaround for this.
I tried mocking the server in a test method with the annotation @BeforeAll:
@BeforeAll
public void setUp() {
    MockBukkit.mock();
}

I expected the test to work.
I actually got a NPE, which origin's located in the MockBukkit code.

A: So I finally managed to fix this error: it occured because of this dependency:
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>2.0.4</version>
</dependency>

Watch this for updates: https://github.com/MockBukkit/MockBukkit/issues/614


text:
Q: HTML/JS : Required input X ignored if input Y is filled Good day!
So I have a simple HTML form which has 4 inputs:
name | email | name2 | email2
Currently all the fields are required but, is it possible that if I fill the first two inputs (name, email), the required other inputs (name2, email2) can be left blank, and the other way around too ..
Here's my code
<form action="register.php" method="post">

Name
        <input name="name" style="height:30px;" type="text" value="" placeholder="" required="required" />

Email
      <input name="email" style="height:30px;" type="text" value="" placeholder="" required="required" />;
      <button class="indiv" type="submit">Submit ></button>

-Company name

        <input name="name2" type="text" value=""  style="height:30px;" placeholder="" required="required" />

-Email

        <input name="email2" type="text" value="" style="height:30px;" placeholder="" required="required" />
        <button type="submit" class="busin">Submit ></button>

For now, I can't move on until the 4 inputs are filled, I have been searching for the solution but since I have no skills in programming I couldn't fix it.
Please help.
Thank you in advance

A: Run this after the user has inputted the data and it will disable the "required" attribute for the "Individual" or "Enterprise" depending on which two input tags are filled.

function checkRequired(){
 if(document.querySelector("[name=name]").value != "" && document.querySelector("[name=email]").value != ""){
  document.querySelector("[name=name2]").required  = false;
  document.querySelector("[name=email2]").required = false;
 }else{
  document.querySelector("[name=name]").required  = false;
  document.querySelector("[name=email]").required = false;
 }
}


text:
Q: RegEx to return string between 2 specific characters? Can you please advise on how to return a string between 2 specific characters?
Example

http://sds.01/create/http/capital/870745800/create/period_1_1364871116_438861511.ssa

I want to return : 1364871116_438861511, which is between "period_1_" AND ".ssa"

A: Use this regex:
period_1_(.*)\.ssa

For example, in Perl you would extract it like this:
my ($substr) = ($string =~ /period_1_(.*)\.ssa/);

For Python, use this code:
m = re.match(r"period_1_(.*)\.ssa", my_long_string)
print m.group(1)

Last print will print string you are looking for (if there is a match).

A: (?<=period_1_)(.*)(?=.ssa)

This extracts the part between "period_1_" and ".ssa".
https://regexr.com/3jtbm


text:
Q: Significant p-value and anecdotical BF I'm conducting frequentist as well as Bayesian analyses. However, I have difficulties to interpret data.
Indeed, results showed significant p-value, but anecdotal BF10 (< 3). Likewise, there are non-significant p-value but anecdotal B01 (< 3).
I'm reading an article written by Wetzels et al. (2011) in link with this topic.
In both case, I don't conclude about acception of H0 or H1 ?
Generally, I have evidence when I conduct a test with BF10, but small evidence when test aims to assess evidence for H0. Are there reasons?
And is there a link with statistical power ? Indeed I have small sample, can we imagine that more participants would conduct to increase the evidence for H1 or H0 of BFs ?
Have a nice day
Cheers,
PM


text:
Q: How do I list the first value from a three-way joined table query? Ugh ok I'm terrible at explaining things, so I'll just give you the quotes and links first:
Problem 4b (near bottom):

4b. List the film title and the leading actor for all of 'Julie Andrews' films.

movie(id, title, yr, score, votes, director)
    actor(id, name)
    casting(movieid, actorid, ord)
(Note: movie.id = casting.movieid, actor.id = casting.actorid)

My answer (doesn't work):
    SELECT title, name
      FROM casting JOIN movie
              ON casting.movieid = movie.id
      JOIN actor
              ON casting.actorid = actor.id
     WHERE name = 'Julie Andrews'
       AND ord = 1
The problem here is that it wants the list of lead actors of movies with 'Julie Andrews' as an actor (who is not necessarily the lead actor), but all I'm doing with my answer is getting the movies where she is the lead (ord = 1).
How do I specify the list of lead actors without 'Julie Andrews' being it?  I suspect I have to do something with GROUP BY, but I can't figure out what at the moment...
Edit: Do I need to use a nested SELECT?

A: There are wonderful ways of doing this with subqueries, but it appears that t this point in the tutorial you're only working with JOINs. The following is how you would do it with only JOINs:
SELECT
  movie.title,
  a2.name
FROM
  actor AS a1
  JOIN casting AS c1 ON (a1.id = c1.actorid)
  JOIN movie ON (c1.movieid = movie.id)
  JOIN casting AS c2 ON (movie.id = c2.movieid)
  JOIN actor AS a2 ON (c2.actorid = a2.id)
WHERE
  a1.name = 'Julie Andrews'
  AND c2.ord = 1

EDIT (more descriptive):
This will give us a table containing all of the movies Julie Andrews acted in. I'm aliasing the actor and casting tables as a1 and c1 respectively because now that we've found a list of movies, we'll have to turn and match that against the casting table again.
SELECT
  movie.*
FROM
  actor a1
  JOIN casting c1 ON (a1.id = c1.actorid)
  JOIN movie ON (c1.movieid = movie.id)
WHERE
  a1.name = 'Julie Andrews'

Now that we have a list of all movies she acted, we need to join that against the casting table (as c2) and that to the actor table (as a2) to get the list of leading roles for these films:
SELECT
  movie.title,  -- we'll keep the movie title from our last query
  a2.name       -- and select the actor's name (from a2, which is defined below)
FROM
  actor a1                                     -- \
  JOIN casting AS c1 ON (a1.id = c1.actorid)   --  )- no changes here
  JOIN movie ON (c1.movieid = movie.id)        -- /
  JOIN casting AS c2 ON (movie.id = c2.movieid)  -- join list of JA movies to the cast
  JOIN actor AS a2 ON (c2.actorid = a2.id)  -- join cast of JA movies to the actors
WHERE
  a1.name = 'Julie Andrews'  -- no changes
  AND c2.ord = 1    -- only select the star of the JA film

Edit: In aliasing, the 'AS' keyword is optional. I've inserted it above to help the query make more sense

A: You want to match movies to two potentially separate rows in the casting table:  one row where Julie Andrews is the actor, and the second row which may or may not be Julie Andrews, but which is the lead actor for the film.

Julie <---> cast in <---> a movie <---> starring <---> Lead actor

So you need to join to the casting table twice.
SELECT m.title, lead.name
FROM actor AS julie
 JOIN casting AS c1 ON (julie.id = c1.actorid)
 JOIN movie AS m ON (c1.movieid = m.id)
 JOIN casting AS c2 ON (m.id = c2.movieid)
 JOIN actor AS lead ON (c2.actorid = lead.id)
WHERE julie.name = 'Julie Andrews'
 AND c2.ord = 1;

Remember that "table aliases" reference potentially different rows, even if they are aliases to the same table.

A: SELECT title, name
      FROM casting JOIN movie
              ON casting.movieid = movie.id
      JOIN actor
              ON casting.actorid = actor.id
     WHERE ord = 1
     and   casting.movieid in
          (select movieid
           from   casting
                  join actor
                      on actor.id = casting.actorid
           where  actor.name = 'Julie Andrews')

A: By the way, this was the answer posted on the site (I just found out about it):
SELECT title, name
  FROM movie, casting, actor
  WHERE movieid=movie.id
    AND actorid=actor.id
    AND ord=1
    AND movieid IN
    (SELECT movieid FROM casting, actor
     WHERE actorid=actor.id
     AND name='Julie Andrews')

Go figure. :P

A: select title, name  from movie join casting on movie.id=movieid
join actor on actor.id=actorid
where ord=1 and movieid in (select movieid from actor join casting
                                            on actor.id=actorid
         where name='julie andrews' and (ord=1 or ord<>1))group by title, name

A: @Bill Karwin 's answer is good for the direction.
However, the result turns out some movies' title has been appear more than one time.
So we need added a DISTINCT function before title in SELECT row.
SELECT DISTINCT m.title, lead.name

And if you want more quick response, you also could write code in this way.
SELECT DISTINCT m.title, lead.name
 FROM actor AS julie
  JOIN casting AS c1 ON (julie.id = c1.actorid AND julie.name = 'Julie Andrews')
  JOIN movie AS m ON (c1.movieid = m.id)
  JOIN casting AS c2 ON (m.id = c2.movieid)
  JOIN actor AS lead ON (c2.actorid = lead.id)
 WHERE  c2.ord = 1;

A: I ve done simply like this

select distinct title,name from
(select movie.* from movie
inner join casting on (movie.id = casting.movieid)
inner join actor on (casting.actorid = actor.id)
where actor.name = 'Julie Andrews' ) as moviesFromJulie

inner join casting on (moviesFromJulie.id = casting.movieid)
inner join actor on (casting.actorid = actor.id)
where ord = 1

Retreive all movies julie andrews played in, then for those movies retreive all movies and actors for them with ordinal number = 1, and distinct for unique results

A: Sharing an easy answer to this-
select title, name from movie
join casting on movie.id=movieid
join actor on actor.id=actorid where ord=1 and movie.id in (select movie.id from movie
join casting on movie.id=movieid
join actor on actor.id=actorid where name='Julie Andrews')

A: SELECT title , name
FROM movie JOIN casting ON (casting.movieid=movie.id) JOIN actor ON (actor.id=actorid)
WHERE (movieid IN (SELECT movieid
FROM casting JOIN actor ON (actor.id=actorid)
WHERE name =  'Julie Andrews')) AND (ord=1)


text:
Q: White squares around selected words When I leave my coursor in vscode at some word or select it, an awful white box appears around all similar words.
How to turn it off?

A: There are two types of highlighting, full words and selection highlighting.
To disable them, open your settings.json (Ctrl+Shift + P > Preferences: Open Settings (JSON))
And add the following lines:
"editor.occurrencesHighlight": false,
"editor.selectionHighlight": false

Then save the file and the changes should apply immediately.

A: Go to

File->Preferences->Settings

Select

Text Editor

Scroll down to

Occurrences Highlight

Uncheck Controls whether the editor should highlight semantic symbol occurrences.


text:
Q: Error in ddply {plyr}: Error in vector(type, length) : vector: cannot make a vector of mode 'NULL'. Is it a bug? I want to calculate the change from baseline of my simulated data over time, per ID and per simulation with ddply:
My code:
tm2<- ddply(tm1, .(NSIM,ID), function(df1){
  base<-df1$DV[1]
  df1$CB<-round(df1$DV/base*100,2)
  df1})

It worked well till last week, and now I rerun the same code it keeps giving me error
"Error in vector(type, length) :
  vector: cannot make a vector of mode 'NULL'."

I'm wondering if this is due to something went wrong with the plyr package, does anyone else have the same issue? Anyone can help?

A: We can do this with tidyverse
library(tidyverse)
tm1 %>%
   group_by(NSIM, ID) %>%
   mutate(CB = round(DV/base * 100, 2))


text:
Q: Adding additional Entities to game causes player to move slower Warning: Big post, small problem
I'm trying to use SFML 2.3.2 to make a game, things have been going pretty well. I've got moving platforms, a movable, jumping, colliding player character (albeit a box). And I'm also making things move distance according to time passed instead of according to a locked framerate, but it seems I messed up somewhere.
The Problem:
The more Entities I add (boxes for my player character to collide with and moving platforms) the slower the player moves and the lower he jumps, despite using a (deltaTime * movement speed) calculation (The moving platforms seem to be consistent in their movements though, no matter the quantity of Entities)
This is the biggest project I've made up to this point so I'll try my best to give all the relevant information.
So first I'll show the structure of all of the files in my project, that way if there's code that's needed that I left out you can just ask me "Hey, what's in there?". Besides that I'll copy the code that I think is relevant to this problem. Which is code of the Engine(a veeeery basic one), Player, and VelocityModule
Project Files:
.h = header file only
.cpp = source file only
.h/.cpp = both header and source files
Dutchtilities:

*

*DutchFunctions.h/.cpp

*ExternalInclusion.h

*gameHeaders.h

*sheepPointer.h

Entities:

*

*Entity.h/.cpp

*MovingPlatform.h/.cpp

*Player.h/.cpp

*Quadrangle.h/.cpp

*EntityPack.h (Collection of all other Entity headers)

Modules:

*

*Module.h/.cpp

*TransformModule.h/.cpp

*HitboxModule.h/.cpp

*DrawModule.h/.cpp

*VelocityModule.h/.cpp

*ModulePack.h (collection of all other module headers)

System:

*

*Engine.h/.cpp

*Level.h/.cpp

*Reader.h/.cpp

I believe the problems are centred around the VelocityModule and the way it updates
Relevant Code:
Engine.h
#ifndef ENGINE_H
#define ENGINE_H

// Forward Declaration
class Level;
#include "Reader.h"

class Engine
{
public:

    // Functions - System
    bool            update();
    void            initWindow();

    // Functions - Time
    sf::Time        getLastFrameTime();
    void            resetLastFrameTime();

    // Functions - Camera
    void            updateCamera();
    void            setCameraTransform( TransformModule* transform );
    void            setCameraOffset( sf::Vector2f &offset );
    void            setCameraOffset( float x, float y );
    sf::Vector2f    getCameraOffset();

    // Functions - Window
    void            setWindowName( const std::string &name );
    void            setWindowDimensions( sf::Vector2u &widthHeight );
    void            setWindowDimensions( unsigned width, unsigned height );
    sf::Vector2u    getWindowDimensions();

    // Functions - Levels
    void            loadLevel( Level* level );

    // Variables - Camera
    sf::View                camera;

    // Variables - Time
    sf::Clock               clock;
    sf::Time                deltaTime;

    // Variables - Window
    sf::RenderWindow        window;

    // Variables - Reader
    Reader                  fileReader;

    // Structors
    Engine();

protected:

    // Variables - Level
    Level*                      m_level;

    // Variables - Camera
    sheepPtr<TransformModule>   m_cameraTarget;
    sf::Vector2f                m_cameraOffset;

    // Variables - Time
    float                       m_frameTime;

    // Variables - Window
    sf::Event                   m_eventHandler;
    std::string                 m_windowName;
    sf::Vector2u                m_windowDimensions;

    // Variables - Game Loop
    bool                        m_paused;
};

#endif

The engine contains 3 functions I believe to be important:

*

*update() this is the main game loop

*getLastFrameTime()

*resetLastFrameTime()

Engine::update()
bool    Engine::update()
{
    this->resetLastFrameTime();

    bool isRunning = true;

    // if the window is open...
    if( this->window.isOpen() )
    {
        // Shortcuts
        Level &level = *(this->m_level);

        // LOOK AT WINDOW EVENTS ////////////////////////////////////////////////////////////////////////////////////////////////

        // Keyboard Events
        while( window.pollEvent( this->m_eventHandler ) )
        {
            // Stop program when X is pressed
            switch( this->m_eventHandler.type )
            {
            case sf::Event::Closed:
                this->window.close();
                isRunning = false;
                break;
            }
            // Pause/Resume game when escape is pressed
            if( this->m_eventHandler.type == sf::Event::KeyReleased &&
                this->m_eventHandler.key.code == sf::Keyboard::Escape)
            {
                this->m_paused = !m_paused;
                std::string line = (m_paused) ? "Game has paused\n" : "Game has unpaused\n";
                std::cout << line;
            }
        }

        // The main game loop
        if( this->window.hasFocus() &&
            m_paused == false )
        {
            // UPDATE ENTITY HITBOXES ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            level.hitboxUpdateEntities();
            // APPLY VELOCITIES TO TRANSFORMS ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            level.updateVelocities();
            // DETECT COLLISIONS //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            level.resetCollisionLists();
            level.createCollisionLists();
            // APPLY EFFECTS ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            level.updateEntities();
            // ADJUST FOR COLLISION ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            level.adjustHitboxes();
            // DRAW STUFF /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            level.updateDraws();

            this->updateCamera();
            this->window.display();
            this->window.clear();
        }
    }
    // Otherwise the window has closed
    else
        isRunning = false;

    return isRunning;
}

Engine::getLastFrameTime()
sf::Time        Engine::getLastFrameTime()
{
    return this->deltaTime;
}

Engine::resetLastFrameTime()
void            Engine::resetLastFrameTime()
{
    this->deltaTime = clock.getElapsedTime();
    this->clock.restart();
}

Player.h
#ifndef PLAYER_H
#define PLAYER_H

class Player : public Entity
{
public:

    void virtual update() final;
    void virtual hitboxUpdate() final;

    short health;
    float movementSpeed;
    float jumpingPower;

    Player();
    ~Player();

private:

    // Modules
    sheepPtr<TransformModule>   transform;
    sheepPtr<DrawModule>        draw;
    sheepPtr<HitboxModule>      collisionHitbox;
    sheepPtr<HitboxModule>      jumpHitbox;
    sheepPtr<VelocityModule>    velocity;

    bool m_grounded;
};

#endif // PLAYER_H

Functions I believe to be important:

*

*hitboxUpdate()

Player::hitboxUpdate()
void Player::hitboxUpdate()
{

    // Calculate the distance the player will move this update
    float distance = (this->movementSpeed * this->m_pEngine->getLastFrameTime().asSeconds() );

    // Jumping (Up)
    if( sf::Keyboard::isKeyPressed(sf::Keyboard::Space) &&
        this->m_grounded == true)
    {
        this->velocity->addVelocity( sf::Vector2f( 0, -(this->jumpingPower) ));
    }
    // Left
    if( sf::Keyboard::isKeyPressed(sf::Keyboard::A) )
        this->velocity->addVelocity( sf::Vector2f( -distance, 0 ));
    // Right
    else if( sf::Keyboard::isKeyPressed(sf::Keyboard::D) )
        this->velocity->addVelocity( sf::Vector2f( distance, 0 ));
}

VelocityModule.h
#ifndef VELOCITYMODULE_H
#define VELOCITYMODULE_H

class VelocityModule : public Module
{
public:
    // Functions - System
    void            update();

    // Functions - Velocity
    void            addVelocity( sf::Vector2f &velocity);
    sf::Vector2f    getVelocity();
    void            setVelocity( sf::Vector2f velocity );
    void            applyVelocity();
    void            setMaxVelocity( float maxVelocity );
    float           getMaxVelocity();
    void            setMinVelocity( float minVelovity );
    float           getMinVelocity();

    // Functions - Drag
    void            setDrag( float dragForce );
    float           getDrag();
    void            setApplyDrag( bool trueOrFalse );
    bool            getApplyDrag();

    // Functions - Gravity
    void            setGravity( float gravity );
    float           getGravity();
    void            setApplyGravity( bool trueOrFalse );
    bool            getApplyGravity();

    // Functions - Transform
    void                setTargetTransform( TransformModule* transform );
    TransformModule*    getTargetTransform();

    // Structors
    VelocityModule();
    ~VelocityModule();

private:
    // Variables - Velocity
    sf::Vector2f            m_velocity;
    float                   m_minVelocity;
    float                   m_maxVelocity;

    // Variables - Drag
    float                   m_dragForce;
    bool                    m_applyingDrag;
    static const float      MAX_DRAG;
    static const float      MIN_DRAG;

    // Variables - Gravity
    float                   m_gravityForce;
    bool                    m_applyingGravity;

    // Variables - Transform
    sheepPtr<TransformModule> m_targetTransform;

};

#endif // VELOCITYMODULE_H

VelocityModule functions I believe to be relevant:

*

*update()

*addVelocity()

*applyVelocity()
void            VelocityModule::update()
{
// Shortcut frametime
float seconds = this->m_pParentEntity->getLinkedEngine()->getLastFrameTime().asSeconds();

// Apply Gravity, if it's enabled
this->m_velocity.y += ( this->m_applyingGravity ) ? (this->m_gravityForce * seconds) : 0 ;
// Apply drag, if it's enabled
this->m_velocity *= ( this->m_applyingDrag ) ? pow( 1 - (m_dragForce/100), seconds ) : 1 ;

// Shortcutting via calculations
sf::Vector2f absoluteVelocity = sf::Vector2f(abs(this->m_velocity.x), abs(this->m_velocity.y));
float maxFrameVel = this->m_maxVelocity * seconds;
float minFrameVel = this->m_minVelocity * seconds;

// Change velocities according to maximum and minimum barriers
this->m_velocity.x = ( absoluteVelocity.x < minFrameVel ) ? 0 :
                     ( absoluteVelocity.x > maxFrameVel && m_velocity.x < 0 ) ? -maxFrameVel :
                     ( absoluteVelocity.x > maxFrameVel && m_velocity.x > 0 ) ? maxFrameVel :
                      m_velocity.x;

this->m_velocity.y = ( absoluteVelocity.y < minFrameVel ) ? 0 :
                     ( absoluteVelocity.y > maxFrameVel && m_velocity.y < 0 ) ? -maxFrameVel :
                     ( absoluteVelocity.y > maxFrameVel && m_velocity.y > 0 ) ? maxFrameVel :
                      m_velocity.y;

this->applyVelocity();

}
VelocityModule::addVelocity()
void            VelocityModule::addVelocity( sf::Vector2f &velocity)
{
    this->m_velocity += velocity;
}

VelocityModule::applyVelocity()
void            VelocityModule::applyVelocity()
{
    if( m_targetTransform.ptr != nullptr )
    {
        // Shortcutting
        this->m_targetTransform->move( this->m_velocity );
    }
}


text:
Q: Concatenate into database for voting system I am making a voting system for my website, but the website has no registration so I wanted to make it so that people that have already voted can not vote again. I wanted to do this by storing all of the ip addresses into a database by concatenating them and making it so that if someone that has one of those ips tries to vote on the same post then it sends out an error message.
Thank you in advance.

A: For your question as is: I would do it slightly differently. I would create a table in my database called "votes" that acts like a sratch table. The fields I would have would be simply: IP and PostID
When your script runs it can take the IP and PostId, search for both values using a WHERE IP = theirIP AND PostID = the_post_ID. If a match is found then show the error.
But, as has been commented, what happens when multiple people using the same Internet connection complete your voting?
Realistically, the method you are employing is flawed because of above. This is where a simple user registration should be used. This will guarantee your system works as desired.


text:
Q: how to configure Firefox to only allow certain iframe access In order to modernize our old web application we changed our frames to iframes.
The web application runs ok with the change, but sometimes errors occur.
Today I had the chance to get to a users desktop and firefox (he has problems) via teamviewer (it's a remote troubleshooting tool, it's is similar to having a vnc session on a remote desktop).
I installed firebug on the remote firefox and tried to log into our web application.
In the console I found the error line:
 Permission denied to access property "document".

After googling for this I found out that it has to do with iframes and sameorigin policy:
 http://davidwalsh.name/iframe-permission-denied
 https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options

My question now is:
The user has a current Firefox (version 38 or 39). I did not have the time to ask him about possible changes in his settings. In the short time I had the chance being at his firefox I only saw that he has a lot of addons.
I also have Firefox 39 and I do not have problems with iframes. There must be a setting or addon for this to change.
Can somebody tell me what to change in Firefox in order to tighten the security policies that I also get this error?


text:
Q: Why this java code works in debug but not in run? Below are the codes. I have excluded import declarations here. IDE.java contains main method. Please look below '//Menus' comment in IDE.java file. That is where the problem starts. I am using java Swing api and when I hit 'debug' the window pops out correctly with menubar containing menu items ("Help" in this case) as I expected. But when I hit 'run' the window pops out but there is no option (menubar is there but it contains no menu item). I am new to this and have no idea where is the problem.
IDE.java
public class IDE {

public static void main(String[] args) {
    JFrame frame1=new JFrame();
    frame1.setSize(1024,620);
    frame1.setExtendedState(frame1.getExtendedState()|JFrame.MAXIMIZED_BOTH);
    frame1.setVisible(true);
    JMenuBar menubar1=new JMenuBar();
    frame1.setJMenuBar(menubar1);
    //Menus
    JCustomMenu help=new JCustomMenu("Help",1);
    help.init(menubar1);
}}

JCustomMenu.java
public class JCustomMenu extends JMenu{

public JCustomMenu(String s,int x){
    super(s);
    menuid=x;
}

public int menuid=0;

public int init(JMenuBar menubar){
    menubar.add((JMenu)this);
    return 0;
}}

What have I missed?


text:
Q: Parsing with BeautifulSoup, error message TypeError: coercing to Unicode: need string or buffer, NoneType found so I'm trying to scrape an Amazon page for data, and I'm getting an error when I try to parse for where the seller is located. Here's my code:
#getting the html
request = urllib2.Request('http://www.amazon.com/gp/offer-listing/0393934241/')
opener = urllib2.build_opener()
#hiding that I'm a webscraper
request.add_header('User-Agent', 'Mozilla/5 (Solaris 10) Gecko')
#opening it up, putting into soup form
html = opener.open(request).read()
soup = BeautifulSoup(html, "html5lib")

#parsing for the seller info
sellers = soup.findAll('div', {'class' : 'a-row a-spacing-medium olpOffer'})
for eachseller in sellers:
    #parsing for price
    price = eachseller.find('span', {'class' : 'a-size-large a-color-price olpOfferPrice a-text-bold'})
    #parsing for shipping costs
    shippingprice = eachseller.find('span'
    , {'class' : 'olpShippingPrice'})
    #parsing for condition
    condition = eachseller.find('span', {'class' : 'a-size-medium'})
    #parsing for seller name
    sellername = eachseller.find('b')
     #parsing for seller location
    location = eachseller.find('div', {'class' : 'olpAvailability'})

    #printing it all out
    print "price, " + price.string + ", shipping price, " + shippingprice.string + ", condition," + condition.string + ", seller name, " + sellername.string + ", location, " + location.string

I get the error message, pertaining to the 'print' command at the end:
TypeError: coercing to Unicode: need string or buffer, NoneType found
I know that it's coming from this line - location = eachseller.find('div', {'class' : 'olpAvailability'}) - because the code works fine without that line, and I know that I'm getting NoneType because the line isn't finding anything. Here's the html from the section I'm looking to parse:

    In Stock.
        Ships from WI, United States.

Domestic shipping rates
         and return policy.

I don't see what's the problem with the 'location' line of code, or why it's not pulling the data I want.
EDIT: I figured it out, but I don't know why. If I change the print command to
    print location.find(text=True)
it outputs the location that I want. Hope this helps somebody, someday.

A: seems like you searching wrong class name

            Ships from WI, United States.

Shipping rates
                   and return policy.

change this line in your code:
location = eachseller.find('div', {'class' : 'olpDeliveryColumn'})


text:
Q: Setting up Procmail Filtering for Spam on Postfix/Courier+MySQL Virtual Users I've been searching for a resource on how to do this but not having much luck.
I am running a working MTA/MUA that is based on Postfix and Courier with MySQL as a backend for virtual users.  I based my system on the following article:
https://help.ubuntu.com/community/PostfixCompleteVirtualMailSystemHowto
It was great up until the empty sections!  My SMTP/IMAP setup is working great, and I managed to get SpamAssassin and ClamAV installed as well with some separate documentation I found online.
What I need help with is setting up Postfix to use Procmail as the mailbox_command so that it will work with virtual users.  I want to be able to define different Procmail rules for each virtual user separately.  I've read the Postfix documentation, and as I understand it the default functionality for mailbox_command will only work for local (non-virtual) users.
Thanks in advance!
UPDATE:
Since this post, I've come to realize that mailbox_command is not tenable.  Instead I found a way to do this using transport_maps.  Read my own answer below.

A: Create one global procmailrc, and for each user make a rule like this:
:0
^TOsomeuser@yourdomain.com
| /usr/bin/procmail -m /etc/procmailrcs/someuser

The usual final rule of each file in /etc/procmailrcs/ should then be to pipe the message to deliver(8).
If you have many users and don't want to maintain a file of this nature, then instead consider writing a script that parses the mail headers to figure out which file in /etc/procmailrcs/ is wanted and executes procmail accordingly, and setting that script as your mailbox_command.

A: This article was of help:  http://www.linuxbackups.org/virtual-procmail.
There were two problems I had to overcome.  First, the solution calls for a static file to hold the user/transport map.  I need a virtual solution.  So instead of creating /etc/postfix/transport, my main.cf says:
transport_maps = mysql:/etc/postfix/mysql_virtual_transport_maps.cf

Here is my mysql_virtual_transport_maps.cf:
user = ******
password = ******
hosts = 127.0.0.1
dbname = postfix
table = mailbox
select_field = transport
where_field = username

So that solved the "virtual" requirement.  The other problem is my directory structure is different than the procmailrc.common example.  Here is my procmailrc.common:
:0
* RECIPIENT ?? .*@\/.*$
{ DOMAIN = "$MATCH" }
#added RECIPIENT variable and we extract domain name
MAILDIR="$HOME/$DOMAIN/$USER@$DOMAIN"
DEFAULT="$MAILDIR/"
LOGFILE="./procmail.log"
VERBOSE=YES
#each user will set his own log file
NL="
"
WS=" "
SWITCHRC="$HOME/$DOMAIN/$USER@$DOMAIN/.procmail"

Hope this helps others that might be trying to do something similar.
-aj


text:
Q: why are equivalence relations called so? "an equivalence relation is the relation that holds between two elements if and only if they are members of the same cell within a set that has been partitioned into cells such that every element of the set is a member of one and only one cell of the partition.
A given binary relation ~ on a set X is said to be an equivalence relation if and only if it is reflexive, symmetric and transitive. Equivalently, for all a, b and c in X:
a ~ a. (Reflexivity)
if a ~ b then b ~ a. (Symmetry)
if a ~ b and b ~ c then a ~ c. (Transitivity) "
But   Why are "equivalence" relations called so?

A: The word "equivalent" is built from "equal" and "value" — well, actually from the Latin words aequus (equal) and valere (to be worth). So two elements are equivalent if they are in a sense equal-valued, or interchangeable. Often this is indeed used literally, by defining some quantities as equivalence classes; for example, the fraction $\frac42$ has the same value as (is equivalent to) the fraction $\frac21$.
Now the properties of an equivalence relation can be directly obtained from that interpretation of the word:

*

*Clearly some object has to have the same value as itself; thus any equivalence relation fulfils $a\sim a$ for all $a$ (reflexivity).

*Just as clearly, if $a$ has the same value as $b$, then $b$ has the same value as $a$. That is $a\sim b\implies b\sim a$ (symmetry).

*And of course, if $a$ has the same value as $b$, and $b$ has the same value as $c$, then $a$ has the same value as $c$, that is $a\sim b\land b\sim c\implies a\sim c$ (transitivity).

You may note that in the list above, I've ultimately used the exact same properties of equality. That is not accidental; equality is in a way the prototype of an equivalence relation.
Or in short, an equivalence relation describes a more general notion of "sameness".

A: I would guess it is because they partition the set into smaller sets, sometimes called equivalence classes. The idea is that the elements of each of these classes are all equivalent (when looked at in a specific way).
For example lets consider the relation $a\sim b$ if and only if $b-a$ is a multiple of $n$. This is an equivalence relation and it splits the integers into equivalence classes. In this case we say the elements of each class are all equivalent because they all give the same residue when we divide by $n$, so if we have an expression and only want to calculate the residue when dividing that expression by $n$ then we can swap some of the element of the expression for "equivalent" elements and this won't alter our result.


text:
Q: IBM Integration Toolkit Issue for Validation I am working on IBM Integration toolkit. I wanted to understand the exact validation feature of a particular input node via an example. Can anyone help?

A: Validation on inputs node you can see them in validation tab, you can choose how to validate (content, conent and value or none if you like to implement your own vaildation and what to do if this validate is failure (Exception , Exception List , user trace, log local error),
validation done automatically depends on the message parser : [BLOB, XMLNSC, XMLNS, SOAP, MRM, ..etc ], and message structurewhich is defined in your message set.
for example :
If you create a message set with message definition file and this message definition has got and element and this element is required and integer, and you set this message set to your input node, validation feature runs automatically if you put for example string value or you left it empty validation exception occurs.