text:
Q: Difficulties setting up overlapped serial port communication I am struggling to communicate with a device via serial COM port.
At first I managed to READ and WRITE to the port with a fairly simple non-overlapped setup. But now I've realized that I have a delay between the WRITE and the READ functions of about 100ms.
Problem: I need to check for an answer after about 15ms in order to reply immediately.
I have no clue how to achieve this, so I tried to set up an overlapped communication and came across this Microsoft Documentation: Serial Communications
Now I cant even get the READ part to work.
Here is my code for now
int main() {
    LPCWSTR port = L"COM3:";

    HANDLE hComm = CreateFile(port, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
    if (hComm == INVALID_HANDLE_VALUE) cout << "ERROR " << GetLastError() << endl;
    else {
        DWORD dwRead;
        DWORD dwRes;
        BOOL fWaitingOnRead = FALSE;
        OVERLAPPED osReader = { 0 };

        //Create overlapped event
        osReader.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
        if (osReader.hEvent == NULL) cout << "ERROR " << GetLastError() << endl;
        else {
            BYTE Byte[2];
            while (true) {
                if (!fWaitingOnRead) {
                    //Issue read operation
                    if (!ReadFile(hComm, &Byte, sizeof(Byte), &dwRead, &osReader)); cout << "ERROR " << GetLastError() << endl;
                    else {
                        cout << std::hex << (int)Byte[0] << " " << std::hex << (int)Byte[1] << endl;
                        fWaitingOnRead = TRUE;
                    }
                }
                else {
                    dwRes = WaitForSingleObject(osReader.hEvent, 500);
                    switch (dwRes) {
                        // Read completed.
                        case WAIT_OBJECT_0:
                            if (!GetOverlappedResult(hComm, &osReader, &dwRead, FALSE)) cout << "ERROR " << GetLastError() << endl;
                            else {
                                cout << std::hex << (int)Byte[0] << " " << std::hex << (int)Byte[1] << endl;
                            }

                            //  Reset flag so that another opertion can be issued.
                            fWaitingOnRead = FALSE;
                            break;

                        default:
                            break;
                    }
                }

                Sleep(100);
            }
        }
    }
    return 0;
}

This Code should output the Results of the READ function to the console. But it fails everytime and GetLastError() gives me 997
I hope somebody can point out my mistakes, or give me a hint how to work around this overlapped construction which I don't quiet understand yet.


text:
Q: Resolving conflits during pull request using intellij My team uses individual feature branches for each developer, then merge the code to develop branch through a pull request and then merge the develop branch to testing branch through a pull request.
I know if multiple developers are working on a single branch and pushing their code, in case they get a conflict, intellij would automatically pop up the conflict resolution windows, which we can easily use to accept the required changes from respective commits.
I have been trying to use the same intellij option for merge conflicts in a pull request from develop to testing. Is it possible to do so. I have referred some intellij docs but none of them address this issue. I am using bitbucket stash, if it helps.

A: Check if IntelliJ IDEA does support git rerere, which would allows you to reuse conflict resolutions from one PR merge step to the next.
The other approach would be to:

*

*refuse merging any PR with conflict

*force a local rebase (or local merge probably, since rebase a common branch like develop or testing is not convenient) in order to resolve conflicts locally.

*make a new PR from the updated branch, this time without conflicts, since they were resolved locally in the previous step.

A: Found the solution for this.
If we are getting merge conflict in a PR raised from source branch to destination branch, to resolve it through Intellij gui, follow below steps:

*

*Checkout the destination brach from the bottom right side option (testing)

*Make sure the latest code is in local branch through a git pull

*Pull the source branch (source) through the menu options VCS -> Git -> Pull
This will bring up the diff UI of intellij.

*Accept the changes and then do a git push

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to write a C program that reads a user input strings and prints only those are not 'a-z' or 'A-Z' I am trying to create a program that reads a user input strings and prints only those are not 'a-z' or 'A-Z'. The following program can print string of characters. But how do I write a C program that reads a user input strings and prints only those are not 'a-z' or 'A-Z'? I appreciate any help that I can get.
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
gets(name);     // read string
printf("Name: ");
puts(name);    // display string
return 0;
}

A: To start with... Never use gets (nor scanf("%s" …). Use fgets.
Then you just to iterate over the string and check if the individual character is in the range of characters you don't want to print.
#define MAX_LEN 30

int main()
{
    char name[30];
    printf("Enter name: ");
    if (fgets(name, MAX_LEN, stdin) != NULL)
    {
         int i = 0;
         while (name[i])
         {
            if ((name[i] < 'a' || name[i] > 'z') &&
                (name[i] < 'A' || name[i] > 'Z'))
                putchar(name[i]);
            ++i;
         }
    }

    return 0;
}

Input:
12john34BEN56 78Al9
Output:
Enter name: 12john34BEN56 78Al9

123456 789


text:
Q: strip characters after finding special character I am using jsp for a web based project. i want to remove all the characters after '@' including '@'.
suppose I got "stackoverflow@stack.com" as input from a user. I have to remove the characters after @ and also '@' i.e.
o/p is stackoverflow

I think one way is using java array OR by regex.
Please suggest me the better way of solving this problem. Are there any other ways of solving this??
How can I do it using JSP? I can not use javascript for this only jsp.
Thank You.

A: Why not use the Java String?
One way:
String output = input;
int at = input.indexOf('@');
if (at != -1) {
    output = input.substring(0, at);
}

(it could be optimised into less lines, but this is the clearest way to write it).
Or
String output = input.split("@", 2)[0];
// I prefer the first way, this is a bit more wasteful, but that is probably
// just a personal hang up from the days of embedded C ;-)


text:
Q: Persistent data still causing application to crash even after app update I am using Firebase for my data and using persistence to allow offline viewing of that data. My app is still in beta so I am still finding bugs that crash the app and fixing them but when I push a new update the app still crashes until I delete the app and reinstall a fresh version. For example, I have a list of users. If a user signs up for the app and it gets entered incorrectly in the database, the rest of the app works fine but just the users menu where the user can see all of the users crashes. So I fix the error and push out a new version on TestFlight but that users view still crashes even though I fixed the issue. It's not until I delete the app and reinstall that it works.
I know this is due to my having persistence turned on but is there a way to programmatically clear what is in memory only when a new version of the app is installed? I don't want to have to tell all of my testers to delete and reinstall every time a bug comes up if I don't have to.

A: It sounds like you changed the database/content structure in the new version. So read/write to the old (persisted) database/content failed. Normally you have to define migration rules that convert your database/content from an old version to the new one, so you can use it after the update without problems. I do not know Firebase, so I can't help you with it.
Another alternative is to remove the persisted data whenever you have an incompatible new version and start with a cleanup directly after the update. Assuming that the already launched app has the version 1.0.0 you can do something like that early in your app flow:
NSString *lastKnownVersion = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastKnownAppVersion"];
NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]
if (!lastKnownVersion || [currentVersion compare:newVersion options:NSNumericSearch]==NSOrderedAscending) {
    if (!lastKnownVersion) {
        // first start after update from version 1.0.0 (or lower) to a larger version
        // cleanup code here
    } else if ([lastKnownVersion compare:@"2.0.0" options:NSNumericSearch]==NSOrderedAscending) {
        // first start after update from version 1.0.1 up to 2.0.0 to a larger version
        // cleanup code here
    } // ... add more versions that need a legacy handling
    [[NSUserDefaults standardUserDefaults] setObject:currentVersion forKey:@"LastKnownAppVersion"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}


text:
Q: cordova (javascript) file.moveTo wait until finished I'm using cordova (phonegap) to build an Android/iOS App
The App has to cache data. It receives a JSON file from a Server which is then processed (data displayed as HTML).
My problem is in this code:
function moveExercisesJSON(){
    console.log("moving exercises json");
    var fail = function(err) { console.log(err) }
    window.resolveLocalFileSystemURL(fileSave, function(file){
        window.resolveLocalFileSystemURL(store, function(store){
            file.moveTo(store, "exercises.json");
            console.log("done moving");
            displayExerciseList();
        },fail);
    },fail);
}

The JSON file (exercises.json) is downloaded to a downloads-folder, then this function is opened.
The file is moved via file.moveTo. Then displayExerciseList() is opened (which processes/displays the data in the json file).
However, it seems displayExerciseList() is called before file.moveTo is done.
Therefor I am always one version behind when first opened (since the new version has not yet been moved from the downloads-folder)
How can I wait for .moveTo to finish before calling displayExerciseList()
A timer doesn't seem to be a solution since I have to do the same for movie-files (which differ a lot in size).

A: Try this:
function moveExercisesJSON(){
    console.log("moving exercises json");
    var fail = function(err) { console.log(err) }
    window.resolveLocalFileSystemURL(fileSave, function(file){
        window.resolveLocalFileSystemURL(store, function(store){
            file.moveTo(store, "exercises.json",function(){
                console.log("done moving");
                displayExerciseList();
            },function(){
                console.log("error moving");
            });
        },fail);
    },fail);
}

The moveTo function has optional parameters for success and error callbacks.
For more details, you can check this page about HTML5 file API (on which is based the Cordova File plugin)


text:
Q: Undefined symbols for architecture armv7 - using Xcode 6.0.1 and Cocos2d-x 3.2 When I choose "Build Active Architecture Only" = "YES", I can run the project in my devices. But when I choose "NO", it shows more than 200 errors with the same project.
Provided, I chose Standard architectures (armv7, arm64) as the Architecture and arm64, armv7, armv7s as the Valid Architectures for this project.
Here is the part of the errors I received:
ld: warning: ld: warning: ignoring file /Users/john/Library/Developer/Xcode/DerivedData/Hero-hbrtqluudvdwemgbwcyacbfeysqv/Build/Products/Debug-iphoneos/libbox2d iOS.a, file was built for archive which is not the architecture being linked (armv7): /Users/john/Library/Developer/Xcode/DerivedData/Hero-hbrtqluudvdwemgbwcyacbfeysqv/Build/Products/Debug-iphoneos/libbox2d iOS.aignoring file /Users/john/Library/Developer/Xcode/DerivedData/Hero-hbrtqluudvdwemgbwcyacbfeysqv/Build/Products/Debug-iphoneos/libchipmunk iOS.a, file was built for archive which is not the architecture being linked (armv7): /Users/john/Library/Developer/Xcode/DerivedData/Hero-hbrtqluudvdwemgbwcyacbfeysqv/Build/Products/Debug-iphoneos/libchipmunk iOS.a

ld: warning: ignoring file /Users/john/Library/Developer/Xcode/DerivedData/Hero-hbrtqluudvdwemgbwcyacbfeysqv/Build/Products/Debug-iphoneos/libcocos2dx-extensions iOS.a, file was built for archive which is not the architecture being linked (armv7): /Users/john/Library/Developer/Xcode/DerivedData/Hero-hbrtqluudvdwemgbwcyacbfeysqv/Build/Products/Debug-iphoneos/libcocos2dx-extensions iOS.a
ld: warning: ignoring file /Users/john/Library/Developer/Xcode/DerivedData/Hero-hbrtqluudvdwemgbwcyacbfeysqv/Build/Products/Debug-iphoneos/libCocosDenshion iOS.a, file was built for archive which is not the architecture being linked (armv7): /Users/john/Library/Developer/Xcode/DerivedData/Hero-hbrtqluudvdwemgbwcyacbfeysqv/Build/Products/Debug-iphoneos/libCocosDenshion iOS.a
ld: warning: ignoring file /Users/john/Library/Developer/Xcode/DerivedData/Hero-hbrtqluudvdwemgbwcyacbfeysqv/Build/Products/Debug-iphoneos/libcocos2dx iOS.a, file was built for archive which is not the architecture being linked (armv7): /Users/john/Library/Developer/Xcode/DerivedData/Hero-hbrtqluudvdwemgbwcyacbfeysqv/Build/Products/Debug-iphoneos/libcocos2dx iOS.a

Undefined symbols for architecture armv7:
  "cocos2d::Touch::getLocation() const", referenced from:
  Credits::onTouchBegan(cocos2d::Touch*, cocos2d::Event*) in Credits.o
  Credits::onTouchMoved(cocos2d::Touch*, cocos2d::Event*) in Credits.o
  "cocos2d::MoveTo::create(float, cocos2d::Vec2 const&)", referenced from:
  Credits::resetCreditAction() in Credits.o
  "cocos2d::CallFunc::create(std::__1::function<void ()> const&)", referenced from:
  Credits::resetCreditAction() in Credits.o
  "cocos2d::Application::setAnimationInterval(double)", referenced from:
  vtable for AppDelegate in AppDelegate.o
  "cocos2d::Director::runWithScene(cocos2d::Scene*)", referenced from:
  AppDelegate::applicationDidFinishLaunching() in AppDelegate.o
  "cocos2d::Application::~Application()", referenced from:
  AppDelegate::~AppDelegate() in AppDelegate.o
  "cocos2d::Application::Application()", referenced from:
  AppDelegate::AppDelegate() in AppDelegate.o

A: add armv7 and armv7s only in the valid architecture as well as architecture section of the game   and cocos2d-x project. (in both project and target section build settings)

A: I have fixed this issue by using the following settings in my Cocos2d-x 3.7 projects.

*

*Select your top-level project in Xcode (in this case 'ZooCubes')

*Set iOS Deployment Target to "iOS 7"

*Set Valid Architectures to: "arm64 arm7"

*Also make sure that Architectures to set to "Standard architectures arm7, arm64"

Make sure to repeat this process for cocos2d_libs.xcodeproj

Sometimes the same error message may also be shown when a class references a missing framework. In my case I had to add the GameKit framework since one of my classes was trying to reference it.
Finally, I have also encountered situations (e.g. Creating a new project in cocos2dx-2.2.6) where the "Build Active Architecture Only" option needs to be set to 'No' for all targets in order to fix the 'Undefined symbols' error.


text:
Q: how to insert multiple checkbox values as successive rows in mysql codeigniter employer_rgn.php

    <?php echo $this->lang->line('spclzd_ctgry'); ?>

    <input type="checkbox" name="spec_cat[]" value="Information Technology"> Information Technology
    <input type="checkbox" name="spec_cat[]" value="Engineering / Manufacturing">Engineering / Manufacturing

    <input type="checkbox" name="spec_cat[]" value="Banking & Financial Services"> Banking & Financial Services
    <input type="checkbox" name="spec_cat[]" value="BPO / ITES"> BPO / ITES

    <input type="checkbox" name="spec_cat[]" value="FMCG / Retail"> FMCG / Retail
    <input type="checkbox" name="spec_cat[]" value="Telecom / ISP"> Telecom / ISP

    <input type="checkbox" name="spec_cat[]" value="Pharmaceuticals / Health Care"> Pharmaceuticals / Health Care
    <input type="checkbox" name="spec_cat[]" value="Sales & Marketing"> Sales & Marketing

    <input type="checkbox" name="spec_cat[]" value="Other Non IT"> Other Non IT

employer_model
public function insert()
{
  //Insert second stage details for employer into database.
  $Specilized_category = $this->input->post('spec_cat');
  $data=array('Specilized_category'=>implode(",", $Specilized_category),);
  $this->db->insert('tbl_employer', $data);

I'm inserting check box values into database separated by commas. But the problem is, I need to get back the checked values from database in order to edit my code. How could I get those values as I had used the implode method? Or do I have to change my code for inserting values into database?

A: when you implode it create an array so its type can be array when it try to insert in to mysql. but you can store multiple values after converting in to string or json string.
Like...
public function insert()
{
    //Insert second stage details for employer into database.
    $Specilized_category = $this->input->post('spec_cat');
    $data=array(
    'Specilized_category'=>json_encode(implode(",", $Specilized_category)),
);
$this->db->insert('tbl_employer', $data);

Try it and let me know if you facing any problem while inserting.. ['}

A: this model gives the following error
A Database Error Occurred
Error Number: 1452
Cannot add or update a child row: a foreign key constraint fails (shubhttc_online.destination_route, CONSTRAINT destination_route_ibfk_2 FOREIGN KEY (to_id) REFERENCES departure_city (dep_id))
INSERT INTO destination_route (to_id) VALUES ('\"2,4,5\"')
Filename: C:/xampp/htdocs/shubhttc_online/system/database/DB_driver.php


text:
Q: Помогите сократить код на Haskell пожалуйста Надо найти все множества анаграмм, которые содержат в себе наибольшее количество слов.
Функция должна иметь следующий тип:
anagram :: [String] -> [[String]]

Пример:
GHCi> anagram ["abc", "hehe", "foo", "cba", "eheh", "hhee", "oof", "ofo"]
[["eheh","hehe","hhee"],["foo","ofo","oof"]]

То есть в вывод идут только самые длинные списки, в данном случае состоящие из 3 слов
Код в одну строку и символов не более 100
Это было само задание, такой код получился:
anagram lst =  let {t = map (nub. map snd) $ groupBy (\(l,_) (r,_) -> l == r) $ sortOn fst $  map (\s -> (sort s,s)) lst;  cmax = maximum $ map length t} in  filter (\l -> cmax == length l) t

Он не проходит по длине, (если что import Data.List прописывать не нужно), заранее спасибо

A: Во-первых: необязательно сначала ставить каждое слово в пару с его отсортированной версией, потом группировать по первому элементу, а потом его выбрасывать. Можно сразу группировать по отсортированной версии.
Было:  map (nub. map snd) $ groupBy (\(l,_) (r,_) -> l == r) $ sortOn fst $  map (\s -> (sort s,s)) lst

Стало: groupBy (\a b -> sort a == sort b) $ sortOn sort lst

Это, правда, приведёт к потере производительности, потому что каждое слово будет сортироваться по нескольку раз. Но в вашем вопросе производительность не упоминается, а упоминается только длина кода, так что именно в эту сторону я и оптимизирую.
Во-вторых: если ваша цель короткий код, то лямбда-выражения можно сократить с помощью функций-комбинаторов. Например, f a == f b можно выразить как (==) `on` f. Правда функцию on придётся импортировать из Data.Function - не знаю, отвечает ли это вашим правилам.
Было:  \a b -> sort a == sort b
Стало: (==) `on` sort

То же самое со вторым лямбда-выражением:
Было:  \l -> cmax == length l
Стало: (cmax ==) . length

В-третьих: если ваша цель короткий код, то выбирать многобуквенные идентификаторы - это самоубийство.
Было:  cmax
Стало: m

В-четвёртых: пробелы. Они на фиг не нужны (в основном), но отнимают кучу места.
Было:  anagram lst =  let {t = groupBy ((==) `on` sort) $ sortOn sort lst;  m = maximum $ map length t} in  filter ((m ==) . length) t

Стало: anagram lst=let{t=groupBy((==)`on`sort)$ sortOn sort lst;m=maximum$ map length t}in filter((m==).length)t

Уже 106 символов. Почти.
В-пятых: map можно заменить на его операторную форму <$>. Количество символов то же, но можно сэкономить два пробела с двух сторон.
 Было:  map length t
 Стало: length<$>t

В-шестых: последний вызов filter можно записать в виде list comprehension (не знаю как это по-русски) и получится короче:
 Было:  filter((m ==).length)t
 Стало: [x|x<-t,length x==m]

И наконец: (==) `on` sort можно заменить на on(==)sort и тем сэконочить две обратные кавычки.
 Было:  (==)`on`sort
 Стыло: on(==)sort

И вуаля: 100 символов!
anagram lst=let{t=groupBy(on(==)sort)$ sortOn sort lst;m=maximum$ length<$>t}in [x|x<-t,length x==m]


text:
Q: Why should I use stored procedures to perform INSERT, UPDATE and DELETE operations? An answer to this question states that "Ideally, though, you would not allow ad hoc DML against your tables, and control all DML through stored procedures."
Why is this ideal? What problem does this solve versus GRANTing SELECT, UPDATE, INSERT, DELETE to the tables which a user needs to manipulate?

A: Views and stored procedures are like an API. They allow you to hide the implementation, version changes, provide security and prevent unfortunate client operations like "get all fields from all invoices since the company started".
Views and stored procedures allow the DBA to modify the schema to meet performance requirements without breaking applications. The data may need to be partitioned horizontally or vertically, split across files, fields may have to be added or removed etc. Without stored procedures, these changes would require extensive application changes.
By controlling the stored procedures and views each application uses you can provide versioning of schema changes - each application will see the database API it expects.
Permissions can also be assigned on specific stored procedures, allowing you to restrict what users can do without giving them full access to a table. Eg, you could allow regular employees to change only their contact details on the employee table but allow HR to make more drastic changes.
Additionally, you can encapsulate complex data-intensive operations in a single testable procedure, instead of managing raw SQL statement strings inside a client's source code.
Stored procedure execution can also be tracked a lot easier with SQL Server Profiler or with dynamic management views. This allows a DBA to find the hotspots and culprits for possible performance degradation.

A: I would believe this follows the general idea that actions should have defined allowable input and return the expected output.  The idea of ad-hoc changes to the data or database structure poses risk on several levels, but may be necessary based on what is required.
zerkms noted in the comments: there are no absolutes, only best practices.  As a best practice, if you can correctly scope the intended outcomes and restrict users and processes to only necessary actions and permissions, you should for the safety and integrity of the system.

A: There are a few solid reasons for why you need to use Stored procedure

*

*Stored procedures are compiled once and stored in executable form, so procedure calls are quick and efficient. Executable code is automatically cached and shared among users.

*Stored procedure avoids SQL injection.

*A set of queries in a stored procedure is executed with a single call. This minimizes the use of slow networks, reduces network traffic, and improves round-trip response time(for example in the case of bulk inserts).


text:
Q: How to submit form from a button outside that component in React? I have a form in one of my React components, and and in the outside component that calls it I want to pass a reference to a button there, so that I can also submit that using that button.
To make it more clear I have the following:
import React, { Component } from "react";
import ReactDOM from "react-dom";

class CustomForm extends Component {
  render() {
    return (
      <form onSubmit={alert('Form submitted!')}>
        <button type='submit'>Inside Custom</button>
      </form>
    );
  }
}

function App() {
  return (

      <CustomForm />
      <button>In Root</button>

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Now, I can submit the form using the button titled 'Inside Custom', but I also want to be able to submit the form using the button titled 'In Root' that is located in the root component. Is there a way to somehow pass reference from that button to that custom component, and actually submit the form when In Root button is clicked?

A: You can set in the state a flag propery for example rootBtnClicked: false and a method that handles the click in the App component. Also in the <CustomForm />, add a prop e.g. rootBtnClicked={this.state.rootBtnClicked}. When "In Root" button is clicked, trigger that method; then the method changes the state with setState(). Then inside the CustomForm component's render() method, check if the prop is true. If it is, manually trigger .submit() using React's ref.

A: Well, set up a button with type of submit and attribute form which has value equal to id of the form you want to submit

A: You can achieve this by using regular HTML capabilities (HTML form Attribute), no need to use the React hacks:
Add "id" attribute to your form: id='my-form'
class CustomForm extends Component {
    render() {
        return (
             <form id='my-form' onSubmit={alert('Form submitted!')}>
                // Form Inputs go here
             </form>
        );
    }
}

Then add the same Id to the "form" attribute of the target button outside of the form:
<button form='my-form' type="submit">Outside Button</button>

Now, the 'Outside Button' button will be absolutely equivalent as if it is inside the form.
Note: This is not supported by IE11.

A: Edit: Simple and correct answer: https://stackoverflow.com/a/53573760/5271656
In React, data flows down and actions flow up. So notify child component about button click in the parent.
This is how you can do this.
import React, { Component } from "react";
import ReactDOM from "react-dom";

class CustomForm extends Component {
  handleOnSubmit = e => {
    e.preventDefault();
    // pass form data
    // get it from state
    const formData = {};
    this.finallySubmit(formData);
  };

  finallySubmit = formData => {
    alert("Form submitted!");
  };

  componentDidUpdate(prevProps, prevState) {
    if (this.props.submitFromOutside) {
      // pass form data
      // get it from state
      const formData = {};
      this.finallySubmit();
    }
  }

  render() {
    return (
      <form onSubmit={this.handleOnSubmit}>
        <button type="submit">Inside Custom</button>
      </form>
    );
  }
}

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      submitFromOutside: false
    };
  }
  submitCustomForm = () => {
    this.setState({
      submitFromOutside: true
    });
  };

  componentDidMount() {
    console.log(this.form);
  }

  render() {
    return (

        <CustomForm submitFromOutside={this.state.submitFromOutside} />
        <button onClick={this.submitCustomForm}>In Root</button>

    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

To me, this solution is hacky and not in a react way but serves your use-case.
Find working solution here:https://codesandbox.io/s/r52xll420m

A: You can pass the submit function as a prop and use this method whenever you want.
for more complex situations you can use redux save your form data on redux and whenever the button is clicked you read data from redux and submit them

A: None of these solutions worked for me, but I finally figured it out by doing
document.forms[0].submit()

Since there was only one form on the page, I selected it with the 0 index, but if there are multiple forms then you'd need to use the applicable index for the forms array.

A: You can pass the onSubmit click handler as a props as follows:
import React, { Component } from "react";
import ReactDOM from "react-dom";

class CustomForm extends Component {

  render() {
    return (
      <form onSubmit={this.props.handleSubmit}>
        <button type='submit'>Inside Custom</button>
      </form>
    );
  }
}

function App() {
 handleSubmit = () => {
   alert('Form submitted!')
}
  return (

      <CustomForm onSubmit={this.handleSubmit} />
      <button>In Root</button>

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Passing function as a props to handle form submit makes the CustomForm element more reusable since the business logic for the submit is not part of CustomForm component.


text:
Q: How to access nonlocal scope inside class definition in python? I want to do this (dummy example):
def func():
    nonlocal var
    print (var)

class A:
    var = 'hola'
    func()

But I get: "SyntaxError: no binding for nonlocal 'var' found"
What I really intend to do is append a method name to a list in the scope of the class if that method is decorated. Something like this:
def decorator(func):
    nonlocal decorated
    decorated.append(func.__name__)
    return func

class A:
    decorated = []
    @decorate
    def f(self):
        pass

A: Use the decorator to mark the functions, then have decorated be a class method which returns all decorated functions.
import inspect

def decorate(func):
    func.decorated = True
    return func

class A:
    def foo():
        print('foo')

    @decorate
    def bar():
        print('bar')

    @classmethod
    def decorated(cls):
        def is_decorated_method(obj):
            try:
                return inspect.isfunction(obj) and obj.decorated
            except AttributeError:
                # The object has no decorated attribute
                return False

        return [result[1] for result in inspect.getmembers(cls, predicate=is_decorated_method)]

print(A.decorated())
# [<function A.bar at 0x6ffffc0aa60>]

A: Python just doesn't let you do this. You can access the class namespace by using locals(). But at this point, you might as well just pass the variable you're interested in to the decorator.
# using locals()

def decorator(class_namespace):
    def _decorator(func):
        class_namespace["decorated"].append(func)
        return func
    return _decorator

class A:
    store = decorator(locals())

    decorated = []

    @store
    def func(self):
        pass

    del store

Generally, it's easy to use a pair of decorators. One to mark the functions you're interested in, and one to collect them.
from types import FunctionType

def collect(cls):
    for item in vars(cls).values():
        print(item)
        if isinstance(item, FunctionType) and getattr(item, "marked", False):
            cls.marked_funcs.append(item)
    return cls

def mark(func):
    func.marked = True
    return func

@collect
class B:
    marked_funcs = []

    @mark
    def func(self):
        pass

But in your case it might just be simpler to create the set of function names at the end of the class. eg.
class C:
    def func(self):
        pass

    func_names = [f.__name__ for f in [func]]

A: y = 20
def f():
    x = 7
    def g():
        nonlocal x # 7
        global y # 20

nonlocal qualifier refers to a name in the outer function scope, which does not include the module scope. While global does the complementary. So you are using nonlocal incorrectly.

A: How about that?
decorated = []

def decorator(func):
    decorated.append(func.__name__)
    def wrapper(self):
        print('wrapper called')
        func(self)
    return wrapper

class A:
    @decorator
    def f(self): print('function called')

print(decorated)
A().f()

OUTPUT:
['f']
wrapper called
function called

NOTES:
The code you provided experiencing the issue you've described because var is class variable so it must be referenced as A.var but you cannot do that in your code because you try to use it before A is defined. if it were different classes it would be possible:
class X:
    decorated = []

def decorator(func):
    X.decorated.append(func.__name__)
    return func

class A:

    @decorator
    def f(self):
        pass

print(X.decorated)

Please note that you don't need to specify nonlocal if you don't assign to variable but call methods like append().


text:
Q: Exploring Android embeded SQLite in the command line I am trying to exploring Android embedded SQLite database in the command line.
My Android emulator already created with a database named "notebase2" (see the screen shot), but the results in the command line does not reflect that.
The screen shot shows part of my Ubuntu terminal placed on the File Explorer view of my Exclipse DDMS perspective.

A: .databases lists the attached databases. You haven't opened or attached any databases. Try this instead:
sqlite3 /data/data/your.applications.package/databases/notebase2


text:
Q: java.lang.AssertionError: Response content expected: but was:<> @RunWith(MockitoJUnitRunner.class)
public class VersionResourceImplTest {

    @Configuration
    public static class MockConfig {
        @Bean
        public Properties myProp() {
            Properties properties = new Properties();
            properties.setProperty("ra.bank.app.version", "TestVersion");
            return properties;
        }
    }

    @Value("#{myProp['ra.bank.app.version']}")
    private String applicationVersion;

    @Test
    public void testVersion() {
        Assert.assertEquals("TestVersion", applicationVersion);
    }

}

This is my test file. It is giving the following error
java.lang.AssertionError: Response content expected:<TestVersion> but was:<>
    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54)
    at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81)
    at org.springframework.test.web.servlet.result.ContentResultMatchers$5.match(ContentResultMatchers.java:149)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
    at com.db.creditrisk.rating.analysis.bank.ui.facade.v2.common.ws.VersionResourceImplTest.shouldReturnCorrectVersion(VersionResourceImplTest.java:49)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

A: For app.version=version2 in properties file we read it using @Value annotation like below.
@Value("${app.version}")
private String appVersion;

So things to troubleshoot for your issue are.
1.Ensure that the property file is present in your classpath.
@PropertySource("classpath:application-test.properties")

OR
@TestPropertySource("classpath:application-test.properties")

2.Print the value before assert statement to know whether @Value is really injecting value or not.
3.Change @Value("#{myProp['ra.bank.app.version']}") to @Value("${ra.bank.app.version}")

A: Please try to use below code and let me know if it's works.
 @RunWith(MockitoJUnitRunner.class)
  @ContextConfiguration(classes = VersionResourceImplTest.myProp.class)
  @TestPropertySource(properties = {
    "ra.bank.app.version=TestVersion",
})
    public class VersionResourceImplTest {

        @Value("${ra.bank.app.version}")
        private String applicationVersion;

        @Test
        public void testVersion() {
            Assert.assertEquals("TestVersion", applicationVersion);
        }

@Configuration
    public static class myProp{
        @Bean
    public static PropertySourcesPlaceholderConfigurer propertiesResolver() {
        return new PropertySourcesPlaceholderConfigurer();

    }

    }

or you can also use below approach as well.
@SpringBootTest
@SpringBootConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(properties = {
    "ra.bank.app.version=TestVersion"
})
public class FooTest {

  @Value("${ra.bank.app.version}")
  String applicationVersion;

  @Test
  public void testVersion() {
    Assert.assertEquals("TestVersion", applicationVersion);
 }

}


text:
Q: how to format inputs on python 3.2 while True:

    letter,Text,numRails= input("").split('\"')
    if numRails ==(""):
        numRails=(2)
        plainText= Text.strip()
    numRails=int(numRails)

    if letter.strip() == "E" or "e":
        x =Encrypt(numRails,Text)

    elif letter.strip()=="D" or "d":
        x =scramble2Decrypt(numRails,Text)

    else: print("invalid encryption command")

E "WEAREDISCOVEREDGO" 2
I need to be able to input all 3 variables on the same line. however I want to have some conditional statements. but I don't know how to do that. like do I just do it as you would normally do if it was just one variable or there's a specific way you have to do this ?

A: Note if conditions are wrong! it always evaluates to True:
 letter.strip() == "E" or "e":
 #                      ^^^^ always True

should be:
 letter.strip() in ["E", "e"]:

Similar mistake is present in second if code.
Note: a Boolean equivalent of a non-empty string is always True e.g.
>>> bool("") # bool of empty string
False
>>> bool(" ") # bool of non-empty string
True
>>> bool("e")
True

So for this reason your if condition e.g. letter.strip() == "E" or "e": == letter.strip() == "E" or True: == Ture
As @roippi is suggesting in comment, you can further simplify if conditional expressions just as follows:
letter.strip().lower() == 'e':


text:
Q: Rounded corners on spark buttonbar incorrect I am having an issue with the spark ButtonBar. I use it on 2 places in my application with some custom CSS, but they look different in the 2 places and I have no idea why. This is a screenshot showing how I want it to look:

This is what I don't want in the other location of my app:

Notice how it seems like 2 separate buttons.
This is the CSS I use:
s|ButtonBar {
    chromeColor: #cfcfcf;
    color: #000000;
}

s|ButtonBarButton:up,
s|ButtonBarButton:over,
s|ButtonBarButton:down,
s|ButtonBarButton:disabled {
    chromeColor: #cfcfcf;
    color: #000000;
    cornerRadius: 4;
}

s|ButtonBarButton:upAndSelected,
s|ButtonBarButton:downAndSelected,
s|ButtonBarButton:disabledAndSelected,
s|ButtonBarButton:overAndSelected {
    chromeColor: #6D9EBA;
    cornerRadius: 4;
    color: #ffffff;
}

I have already checked that it is 1 buttonbar, not 2 separate ones in the incorrect case. Any ideas what might be causing this?
UPDATE: I discoverd it is always is wrong when using a ButtonBar in a NativeWindow and correct in the normal AIR application. But why? And is there a workaround?


text:
Q: Change Elements HTML but Ignore Last Child With the way I have my HTML marked up....
<textarea></textarea>

don't change this

Is it possible to change the html inside of .body without changing the html inside of .content?
EDIT:
I'm working on my code editor and my
<textarea></textarea>

don't change this

A: This is tricky, because .body may contain text nodes.
jQuery's contents() method helps :

$('textarea').keyup(function() {
  $('.body')
    .contents()                             //get both text nodes and element nodes
    .each(function() {
      if(this.className !== 'content') {
        this.nodeValue= this.innerHTML= ''; //nodeValue needed for text nodes,
                                            //innerHTML for element nodes
      }
    });

  $('.content').before(this.value);
}).trigger('keyup');
textarea {
  width: 98%;
  height: 100px;
}

<textarea>

test data here

</textarea>

don't change this

A: One workaround would be to get the reference to the .content element and append() it back in to the .body element after re-setting the html(). Try this:

$("textarea").keyup(function() {
  var $content = $('.content');
  $(".body").html(this.value).append($content);
}).trigger("keyup")
textarea {
  width: 98%;
  height: 100px;
}

<textarea></textarea>

don't change this

A: you can append into $contentrather than changing the entire html
$('textarea').keyup(function(){
 $('.body').html(this.value).append($content)
}).trigger('keyup');

fiddle : https://jsfiddle.net/atg5m6ym/3320/

A: Keep HTML, CSS, and JS separate. See Snippet.
SNIPPET

$(".html").keyup(function() {
  $(".body").html(this.value)
}).trigger("keyup")
$(".css").keyup(function() {
  $(".style").html(this.value)
}).trigger("keyup")
$(".js").keyup(function() {
  $(".script").html(this.value)
}).trigger("keyup")
textarea {
  width: 98%;
  height: 100px;
}
.tag {
  font: 700 16px/1.45 'Consolas';
  color: grey;
  }

<fieldset>
<legend>HTML</legend>
<textarea class="edit html">

</textarea>
</fieldset>

<fieldset>
<legend>CSS</legend>
<textarea class="edit css">

</textarea>
</fieldset>

<fieldset>
<legend>JavaScript</legend>
<textarea class="edit js">

</textarea>
</fieldset>

<html>

<head>

<style>

</style>

</head>

<body>

<script>

</script>

</body>

</html>


text:
Q: setting plt.text() coordinates to a variable location I am creating a loop that goes through a large dataset to create a data summary report.  I am trying to use a text box to display some summary statistics on top of a histogram and I want the upper right corner of my text box to be at the upper right corner of my histogram.
plt.hist(current_var.dropna(), bins=num_bins, label=str(variables_list[i]))
plt.text(x_coordinate, y_coordinate, summary_statistics, verticalalignment='top',
        horizontalalignment='right',
        fontsize=10,
        bbox={'facecolor':'white', 'alpha':0.6})
plt.show()

I could set the x_coordinate variable as a max of my dataset but is there a way to know what the max of my y axis will be on each iteration so that I can set my y_coordinate variable to that?

A: This made it work (Thanks to CT Zhu):
plt.hist(current_var.dropna(), bins=num_bins, label=str(variables_list[i]))
ymin, ymax = plt.ylim()
xmin, xmax = plt.xlim()
plt.text(xmax-1, ymax-1, summary_statistics, verticalalignment='top',
        horizontalalignment='right',
        fontsize=10,
        bbox={'facecolor':'white', 'alpha':0.6})
plt.show()

I figured I would leave it up just in case someone else asks this..


text:
Q: AWS EKS - Create Load Balancer Service throws out of service I have a quick question regarding AWS EKS that whenever I create a K8s service with of type LoadBalancer, it provisions a classic ELB backed the EC2 where services are running. Now whenever I try to hit the Load Balancer ELB from the Internet, it returns ERR_EMPTY_RESPONSE error. If I navigate back to ELB and look at the instances behind ELB, it shows the status of EC2 instances as OutOfService.
This happens either I use my own K8s deployments & services or the one provided with documentation. Anyone can help me with this? More over, is there any way to provision a different type of Load Balancer for a K8s service? Thanks.

A: This is default behavior or K8S with on cloud providers , A service type Load Balancer will spins up real one which affect cost.
Better to use K8S Ingress as best practice and can use as Endpoint or you can add under External Load Balancer.


text:
Q: Phonegap, iphone - applicationDidFinishLaunching not invoking I'm trying to get started with Phonegap.
I have added some code to applicationDidFinishLaunching but this doesn't seem to be getting called.
I've added breakpoints (log, continue) to each of the init and applicationDidFinishLaunching methods. This confirms that the latter indeed isn't getting invoked.
Xcode, Objective-C and Phonegap are all foreign to me and so Im a bit lost as to how to resolve this.
thanks
EDIT: I've just tried creating a brand new blank unmodified phonegap project, and the same thing happens. init breakpoint fires, but applicationDidFinishLaunching does not.

A: The reason this is occurring is because the Phonegap Xcode template is using the wrong UIApplication method for the app load event.  As of iOS 4.0 and higher, Apple recommends to use didFinishLaunchingWithOptions instead of applicationDidFinishLaunching because the former contains option parameters that lets the developer know how the app was called.  Since iOS 4.0 and higher supports background processing, the app may have been launched from an Apple Push Notification and needs to be handled appropriately.
So to solve this problem, you need to remove the code in your AppDelegate.m file that references applicationDidFinishLaunching and include the following code instead:
(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
     //     Add custom code here

     return [ super application:application didFinishLaunchingWithOptions:launchOptions ];
}

For some reason the Phonegap 0.9.3 library has the correct implementation of didFinishLaunchingWithOptions in the PhoneGapDelegate.m, but the main XCode template still references applicationDidFinishLaunching, which will never get called.

A: I am new to iphone development. But i have done one small app using phonegap framework.
Yes When we use phonegap framework our Project's applicationDidFinishLaunching does not work and other methods like webViewDidFinishLoad and webViewDidStartLoad in app delegate also not work..
Instead of this applicationDidFinishLaunchinWithOptions of PhoneGapLib.xcodeproj which is included in our project of phonegap gets excute.
Try to write NSLog(); there. U will get output on consol..


text:
Q: How to sort with 2 Objects from 2 Classes by 1 properties Assume I have two classes:
class 1:
class Person{
    String name;
    int age;
    public Person(){}
    public Person(String name, int age){
        this.name = name;
        this.age = age;
    }
    @Override
    String toString(){
        return "Name: "+name + "\tAge: "+age;
    }
}

class 2
class Animal{
    String name;
    int age;
    public Animal(){}
    public Animal(String name, int age){
        this.name = name;
        this.age = age;
    }
    @Override
    String toString(){
        return "Name: "+name + "\tAge: "+age;
    }
}

And I create a List Object to stored 2 classes Person and Animal
List newList = new ArrayList<>();
newList.add( new Person("person", 20);
newList.add( new Person("aPerson",20);
newList.add( new Animal("animal",20);
newList.add( new Animal("aAnimal",20);

Now i want sort newList by name but i don't know how to do it.
With one Class I can Create Class SortByName and compare name between two Object, But with two Class i can not

A: What you need is an Interface. Both your Animal and Person class offer name as one of their properties, so you can have an Interface say Nameable in this regard to essentially specify that your class definitely has name property.
You'll code to the Nameable interface so as to create a list of Nameable's and you can create a sorter on that list.
List<Nameable> list = new ArrayList<>();
newList.add( new Person("person", 20);
newList.add( new Person("aPerson",20);
newList.add( new Animal("animal",20);
newList.add( new Animal("aAnimal",20);

list.sort(new Comparator<Nameable>() {
    public int compare(Nameable o1, Nameable o2) {
        return o1.getName().compareTo(o2.getName());
    }
});

The interface ans its usage:
Nameable.java

public interface Nameable {
    String getName();
}

public class Person implements Nameable {
   ...

   String getName() {
      return name;
   }

   ...
}

public class Animal implements Nameable {
   ...

   String getName() {
      return name;
   }

   ...
}

A: An abstraction for that specific case is needed that holds all the information which both entities need. E. g. an interface called Entity which has the method getName().
Example:
public interface Entity {
    String getName();
}

public class Person implements Entity {

...
    @Override
    public String getName() {
        return name;
    }
}

public class Animal implements Entity {

...
    @Override
    public String getName() {
        return name;
    }
}

After you got this you can use it by type:
List<Entity> entities = new ArrayList<>();
entities.add(new Person("person", 20);
entities.add(new Person("aPerson", 20);
entities.add(new Animal("animal", 20);
entities.add(new Animal("aAnimal", 20);
entities.sort((o1, o2) -> o1.getName().compareTo(o2.getName());

It would also be possible to use an abstract class.

A: After creating a Base class/interface as suggested in other answers, you can sort as with Comparator.comparing,
newList.sort(Comparator.comparing(Entity::getName));


text:
Q: Product of sheaf of ideals Let $(X, O_X)$ be a ringed space, $I$ be a sheaf of ideals on $(X, O_X)$ and let $F$ be an $O_X$-module.
I have two questions.
a) Is there an example where the presheaf $P : U \mapsto I(U) \cdot F(U) \leq F(U)$ is not a sheaf on $X$ ?
b) Is it correct that we define the product $I \cdot F$ as being the image of the sheaf morphism
$$I \otimes_{O_X} F \to O_X \otimes_{O_X} F \cong F,$$
and if so, do we necessarily have that $I \cdot F$ is isomorphic (as sheaf of $O_X$-module) to the sheafification of $P$ ? According to this question, this is true but the comment has no further explanation as to why this is true.
For a), if I consider a collection of pairwise compatible sections $s_U \in P(U)$, we can write
$$s_U = \sum_{i=1}^{n_U} a_i^U b_i^U$$
with $a_i^U \in I(U), b_i^U \in F(U)$, but I don't see how the conditions $s_U\vert_{U \cap V} = s_V\vert_{U \cap V}$ could help to glue the various $s_U$ together.
Thank you for your help.

A: Let me answer b) first, because it helps with answering a): The image of the sheaf morphism $$I \otimes F \to O_X \otimes F \cong F$$ is by definition the sheafification of the presheaf $$U \mapsto Im(I(U) \otimes_{O_X(U)} F(U) \to F(U))$$ which is just your presheaf $P$. So the image is by definition the sheafification of your presheaf.
Answering a): Now I can talk about presheaves of tensor products being or not being sheaves, where an extremely important and instructive example is given by the projective line $X = \mathbb{P}^1_k$ over a field $k$. The ideal sheaf $I$ corresponding to a closed, $k$-rational point is isomorphic to $O(-1)$. Considering $F = O(1)$ we know $$I \otimes F \cong O_X,$$ but $I(X) = 0$, so the tensor product presheaf is not equal to its sheafification which satisfies $O_X(X) = k$.
Note that $F$ is a flat $O_X$-module, so the tensor product presheaf is actually isomorphic to the product, so this also gives an example for your situation.


text:
Q: Where could I find the apis or guide to apply "Share" Action on Push Notification on Android So I'm trying to fiddle around with push notification, and couldn't find any leads to implement the "Share" Action on push Notification on the Android platform. Any ideas on how I could do something similar to the images below.
Thanks in advance!
enter image description here

A: It's just a action to a Notification. You can add such action where you create your notification in GCM Intent Service by adding NotificationCompact.Builder.addAction() and attaching a PendingIntent with Share action.
If you want to share a Image as shown in the screenshot, Make sure you store the image in a bitmap and then share the path of the bitmap while sharing


text:
Q: dplyr lookup from same table I have data of how team members rated one another, from multiple teams. Each person has their own id number but also a team and rater number within the team like so:
  StudyID TeamID CATMERater Rated   Rating
    (int)  (int)      (int) (dbl)    (dbl)
1    2930    551          1     1 5.000000 #How rater 1 rated 1 (themselves)
2    2938    551          2     1 3.800000 #How rater 2 rated 1
3    2939    551          3     1 5.000000 #How rater 3 rated 1
4    2930    551          1     2 3.666667 #How rater 1 rated 2
5    2938    551          2     2 4.000000 #...
6    2939    551          3     2 3.866667
...

and so on. I got this format using tidyr and am trying to get a new column of the StudyID where the TeamID and person being rated are the same. This is what I've tried, but doesn't work because I'm not sure how to reference the same table:
edges %>% mutate(RatedStudyID = filter(edges, TeamID == TeamID & Rated == CATMERater))

Hopefully this makes sense, but I'd appreciate a recommendation to get headed in the right direction. If it is something with left_join how do I say where TeamID == TeamID?
Here's what I'd like to see in the end (mostly the last column though):
  StudyID TeamID CATMERater Rated   Rating   RatedStudyID
    (int)  (int)      (int) (dbl)    (dbl)
1    2930    551          1     1 5.000000   2930
2    2938    551          2     1 3.800000   2930
3    2939    551          3     1 5.000000   2930
4    2930    551          1     2 3.666667   2938
5    2938    551          2     2 4.000000   2938
6    2939    551          3     2 3.866667   2938
...

dput results per @akron that gives an error:
structure(list(StudyID = c(2930L, 2938L, 2939L, 2930L, 2938L,
2939L, 2930L, 2938L, 2939L, 2930L, 2938L, 2939L, 2930L, 2938L,
2939L, 2930L, 2938L, 2939L, 2920L, 2941L, 2989L, 2920L, 2941L,
2989L, 2920L, 2941L, 2989L, 2920L, 2941L, 2989L, 2920L, 2941L,
2989L, 2920L, 2941L, 2989L, 2922L, 2924L, 2943L, 2922L, 2924L,
2943L, 2922L, 2924L, 2943L, 2922L, 2924L, 2943L, 2922L, 2924L
), TeamID = c(551L, 551L, 551L, 551L, 551L, 551L, 551L, 551L,
551L, 551L, 551L, 551L, 551L, 551L, 551L, 551L, 551L, 551L, 552L,
552L, 552L, 552L, 552L, 552L, 552L, 552L, 552L, 552L, 552L, 552L,
552L, 552L, 552L, 552L, 552L, 552L, 553L, 553L, 553L, 553L, 553L,
553L, 553L, 553L, 553L, 553L, 553L, 553L, 553L, 553L), CATMERater = c(1L,
2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L,
3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L,
2L, 1L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L,
2L), Rated = c(1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6,
6, 6, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 1,
1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5), Rating = c(5, 3.8, 5,
3.66666666666667, 4, 3.86666666666667, 4.53333333333333, 4, 4.8,
NaN, NaN, NaN, NaN, NaN, NaN, NA, NA, NA, 3.93333333333333, 5,
5, 5, 5, 5, 5, 5, 5, NaN, NaN, NaN, NaN, NaN, NaN, NA, NA, NA,
4, 4, 4, 4, 4, 4, 4, 3.86666666666667, 4, NaN, NaN, NaN, NaN,
NaN)), .Names = c("StudyID", "TeamID", "CATMERater", "Rated",
"Rating"), class = c("tbl_df", "data.frame"), row.names = c(NA,
-50L))

A: From the comments:
library(dplyr)
x %>%
   group_by(Rated, TeamID) %>% #group by each team/rated individual
   filter(any(CATMERater == Rated)) %>% #filter out any groups with unrated individuals
   mutate(new = StudyID[CATMERater == Rated]) #make the new column

The new column is created by subsetting each group - it is the same as x$StudyID[x$CATMERater == x$Rated] would be on the whole dataframe. As long as we have one place where this is true (ie self rating) the value is set to every member of that group.

A: With data.table
library(data.table)
setDT(edges)[ , RatedStudyID := StudyID[CATMERater == Rated] , .(Rated, TeamID)]
edges
#   StudyID TeamID CATMERater Rated   Rating RatedStudyID
#1:    2930    551          1     1 5.000000         2930
#2:    2938    551          2     1 3.800000         2930
#3:    2939    551          3     1 5.000000         2930
#4:    2930    551          1     2 3.666667         2938
#5:    2938    551          2     2 4.000000         2938
#6:    2939    551          3     2 3.866667         2938

In the new dataset, there are groups that don't have any similar values for CATMERater and Rated in the same row.  So, we can use an exception to return NA for those.
setDT(df1)[, RatedStudyID :=if(!any(CATMERater==Rated)) NA_integer_
             else StudyID[CATMERater ==Rated], .(Rated, TeamID)]

A: I think you can solve this with a join
edges %>%
  select(TeamID, Rated = CATMERater, RaterStudyID = StudyID) %>%
  inner_join(edges, by = c("TeamID", "Rated"))


text:
Q: Need clarification on the Azure Functions ecosystem I am having a hard time understand the current set of options and components currently available (January 2019) to us with respect to Azure Functions. Part of my issue could also be what is seemingly confusing terminology and/or versioning and what seems like very stale documentation (many of the pages listed here (https://learn.microsoft.com/en-us/azure/app-service/overview-diagnostics) are still dated from 2017.).
As I understand it

*

*There is the original Version 1 of Azure Functions which allows you to run code snippets targeting .NET Full Framework

*There is the newer Version 2 of Azure Functions which allows you to run code snippets targeting .NET Standard / Core. This was in beta (??), preview (??) last year and went GA around September / October 2018?

*All new features will be targeted at version 2 of the Function Runtime (??)

*There is a UI Portal (??) (https://learn.microsoft.com/en-us/azure/azure-functions/functions-runtime-install and https://aka.ms/azafrv2) that is labeled as Preview 2 which seems to be from November 2017. Interestingly, it does provide the option of running both v1 and v2 Azure Functions on-premise.

*

*Cannot seem to find a newer version of this portal. This post (https://github.com/MicrosoftDocs/azure-docs/issues/15820#issuecomment-427089585) states there are no plans to update the Portal. Does this mean that MS is abandoning running Azure Functions on-premise?

*I am guessing that the Runtimes bundled in the Portal site are from 2017 and not running the latest runtimes?

*Unsure what the relationship is between Azure Webjobs SDK, Azure Functions Host, WebJobs Script, Azure Core Tools, andAzure Functions Runtime.

Ultimately, I am looking to run Azure Functions on-premise and need to support both v1 and v2. While the vast majority of functions we are going to create will target the newer v2, we have two or three .NET libraries that have yet to be ported away from Full Framework and since they are 3rd party, we cannot control the time frame.)
Ideally we would like to provide a on-premise Portal for developers to upload the functions from Visual Studio or even create them via the browser.
Even better would be to containerize the functions and run them in an on-premise Azure Service Fabric. (I realize this is advanced and probably beyond the scope of this posting.)

A: Conclude your questions to 3 points

*

*Runtime difference(The first three items)
Your understanding is totally right that V1 targeting Full NetFramework and V2 on .NET Core, which is announced to be GA since 9/24/2018. And yes, all new features will be only targeted at V2.

*The relationship between those terms(The 5th item).
Azure Webjobs SDK is a framework that simplifies the task of writing background processing code that runs in Azure. In .NET functions, it(along with Webjobs extensions) is referenced by Microsoft.NET.Sdk.Functions.
WebJobs.Script = Azure Functions host = Azure Functions Runtime, where our functions work. It's built upon Azure WebJobs SDK and enables a light-weight scripting model for it, the scripting library does the work necessary to plug our function scripts into the Azure WebJobs SDK runtime.
Azure Functions Core Tools(CLI) is a command line tool integrated with Azure Functions Runtime. Our local development(e.g. running, debugging) depends on this tool.

*Azure Functions Runtime preview 2(The 4th item)
It offers a UI similar to Azure Function portal and consumes very old Function runtime from obsolete docker hub image. As you have found in the thread, no plan to update, not sure whether it will be abandoned or not.
So far we are not able to get a working on-premises Portal and could only turn to CLI or container for local running. Note that there's No image for v1 function. Not familiar with Azure Service Fabric so no more suggestions.


text:
Q: Multiple inheriting classes with different scoped properties I'm not sure if what I'm trying to do just isn't possible or if I'm just thinking about this completely wrong but what I'm trying to do is essentially this. I have a sealed class with multiple classes within like this:
sealed class MySealedClass(val thing: Thing) : MyPropertyInterface
{
    val name: String = thing.name

    /** Base Methods Here */

    /** Obj 1 Constructor */
    class ObjOne(thing: Thing) : MySealedClass(thing)
    {
        override val properties = PropertyTypeOne()
        override val otherProperties = PropertyTypeTwo()

        inner class PropertyTypeOne(){
            val one = 1
        }

        inner class PropertyTypeTwo(){
            val two = 2
        }
    }

    /** Obj 2 Constructor */
    class ObjTwo(thing: Thing) : MySealedClass(thing)
    {
        override val properties = PropertyTypeOne()
        override val otherProperties = PropertyTypeTwo()

        inner class PropertyTypeOne(){
            val one = 1
        }

        inner class PropertyTypeTwo(){
            val two = 2
        }
    }
}

Basically I want the classes within my sealed class to inherit these scoped properties in the way an interface would to force them to initialize them since they will contain the same type of properties but different values. The reason I want the properties to be scoped is because rather than accessing them through a list I want to access them directly (simply for more readability) and without the scoping it could become unclear what you're accessing. I realize that I could create a custom interface for each class inside the sealed class containing said classes with said properties, but my issue there is that I want to, in a way, enforce this as a rule upon the classes within the sealed class that they must construct these two data structures. By creating a custom interface per class it would then be possible that one of them no longer fits the criteria due to human error.

A: This is the solution that I have come to to obtain my desired result:
sealed class MySealedClass(val p0: Int, val p1: Int) : MyProperties{

    /** Base properties and methods */

    class MyClassA(p0: Int, p1: Int) : MySealedClass(p0, p1){
        override val propertyListOne: MyProperties.PropertiesA = MyProperties.PropertiesA()
        override val propertyListTwo: MyProperties.PropertiesB = MyProperties.PropertiesB()
    }

    class MyClassB(p0: Int, p1: Int) : MySealedClass(p0, p1){
        override val propertyListOne: MyProperties.PropertiesC = MyProperties.PropertiesC()
        override val propertyListTwo: MyProperties.PropertiesD = MyProperties.PropertiesD()
    }
}

interface MyProperties{
    val propertyListOne: Any
    val propertyListTwo: Any

    class PropertiesA{
        val one = 1
    }

    class PropertiesB{
        val two = 2
    }

    class PropertiesC{
        val three = 3
    }

    class PropertiesD{
        val four = 4
    }
}

fun testMethod(){
    val newClassA = MyClassA(0, 0)
    newClassA.propertyListOne.one
    newClassA.propertyListTwo.two
    val newClassB = MyClassB(0, 0)
    newClassB.propertyListOne.three
    newClassB.propertyListTwo.four
}

I realize that all of this could be done easier by just simply creating lists but I specifically am not looking to index these values. Also this structure makes the hierarchy of the object structures of the code I'm working on much easier to understand and read.


text:
Q: Migration to Compose MongoDB on Heroku We use old add-on Mongodb classic which will reach end of life soon. We must migrate to the new one Compose Mongodb but I've noticed that Compose discontinued it and it will be soon migrated to IBM cloud. It is even not possible to create MongoDB on Compose since Feb 2019.
Ok, but there is another Mongodb add-on: mLab MongoDB. Unfortunatelly there is another cach: mLab is acquired by MongoDB, Inc and mLab is being migrated to Atlas.
So where should be migrate to avoid another migration withing a year? Is it worth to migrate to Compose MongoDB and then wait until we must migrate it to IBM Cloud or should we directly migrate to Atlas?

A: For IBM Cloud, you will want to look at Databases for MongoDB
You can review the differences between Compose on IBM Cloud and Databases for MongoDB here.
Ultimately, Atlas and Databases for MongoDB both have different platform feature sets, pricing, and integrations. Ultimately, the choice is based on your requirements and preferences.
One neat thing about Databases for MongoDB is that it allows you to control disk and RAM completely independently, unlike the instance sizes found on Compose Heroku add-on or Atlas (at least based on their public pricing)
Hope this helps!
If you reach out to Compose support, we can help out.

A: Another Heroku add-on option to consider is ObjectRocket.
You can find details on the ObjectRocket MongoDB offering to see if it fits your use case.
If you decide you do want to migrate to ObjectRocket, these self-service docs will help you gauge the level of effort required.
Stay on the lookout for a MongoDB migration tool in coming weeks that will automate most of the migration steps to switch over from the Compose add-on to ObjectRocket.
Good luck!
Disclosure: I work for ObjectRocket.


text:
Q: Concatenate videos and add black frames between them with ffmpeg I have three videos that I am concatenating with ffmpeg. I would like to add a few black frames in between them. Although I've found a few hints on the web it has not worked for me yet. I have tried to generate an 'empty' video with just black frames with:
ffmpeg -t 20 -s 1920x1080 -f rawvideo -pix_fmt rgb24 -r 25 -i c:\nul  E:\empty.avi

and then concatenate with another one but doesn't work. I have tried a few other things without success. Any help would be greatly appreciated
EDIT: also tried to add black frames before and after video with the following code, but no success:
ffmpeg -f lavfi -i color=c=black:s=1920x1080:r=25:d=100 -i middle_video.avi -filter_complex
"[0:v]trim=start_frame=1:end_frame=21[blackstart];
[0:v] trim=start_frame=1:end_frame=21 [blackend];
[blackstart] [1:v] [blackend] concat=n=3:v=1:a=0[out]" -map "[out]" -c:v qtrle -c:a -copy output.avi

EDIT2:
Output from ffprobe
Metadata:
encoder: Lavf57.3.100
Duration: 00:00:10.05, start: 0.000000, bitrate: 43302 kb/s
Stream #0:0: Video: mpeg4 (Simple Profile) (FMP4 / 0x34504D46), yuv420p, 192
0x1080 [SAR 1:1 DAR 16:9], 43333 kb/s, 23.98 fps, 23.98 tbr, 23.98 tbn, 10k tbc
Stream #0:1: Audio: mp3 (U[0][0][0] / 0x0055), 48000 Hz, stereo, s16p, 128 k
b/s

EDIT 3
Link to the report of the ffmpeg console output:
FFMPEG session report

A: #1 Generate your blank video
ffmpeg -f lavfi -i color=black:s=1920x1080:r=24000/1001 -f lavfi -i anullsrc \
       -ar 48000 -ac 2 -t 20 empty.avi

#2 Prepare a text file with list of files
file '1.avi'
file 'empty.avi'
duration 1
file '2.avi'
file 'empty.avi'
duration 1
file '3.avi'

#3 Concat
ffmpeg -f concat -i list.txt -c:v qtrle -c:a copy joined.avi

The above assumes that all 3 videos have the same properties as shown in the ffprobe readout. You can control the duration of the blank segment using the duration argument in the textfile (currently 1 second). Only upto the duration of empty.avi, of course.


text:
Q: How can I prevent integer value from going negative I am working in an app in which I have option to choose quantity number for selected product by default quantity is set to 1 while increasing and decreasing quantity I am able to go to negative numbers like -1 ,-2,-3...
How do I restrict quantity from going negative.
this my code for reducing quantity value
setState(() {
  itemCount = itemCount - 1;
  price = itemCount - price;
});

A: You can do an if check as @Mobina said:
if (itemCount > 0) price = itemCount - price;

Or use the max function from the math library:
import 'dart:math';

void main() {
  final itemCount = 1;
  final price = max(0, itemCount - 5);
}


text:
Q: ViewBag Is Producing a Null Reference Exception I'm passing a ViewModel to the view, along with a few ViewBags. I was re-writing a significant portion of the program, but I didn't touch this page, nor anything related particularly. Suddenly the ViewBag is coming with a null reference exception, which I don't understand because empty ViewBags, in my experience, just come blank.
I debugged, and the date string is being generated. If I change the value to a simple string, "test", it still comes with the exception. Also, I'm using "return View(ViewModel);" to pull the view.
This is the controller. There is more code, but it doesn't affect the issue.
public IActionResult Calendar(string DateString)
    {
        if (String.IsNullOrEmpty(DateString))
        {
            DateString = DateTime.Now.AddDays(2).ToString("yyyy-MM-dd");
            //ToString("yyyy-MM-dd");
        }

        DateTime mDate = System.DateTime.Parse(DateString);

        DateTime dateX = mDate.AddDays(-3);
        //ViewBag.dateX = dateX.ToString("D");
        ViewBag.dateA = "test";

This is the view, focused on the error section. The error is specifically "@ViewBag.dateA" which as you can see above in the controller is set to "test".

@*
@ViewBag.dateX
*@
@ViewBag.dateA

    @foreach (var item in Model.Thr0X)

My question is literally how to make the ViewBag work again. I'm hoping someone will look at this and just see a simple error on my part that I'm missing, or something like that.
TBH, I can't see anything wrong with the code I provided, nor the code in general.


text:
Q: How could I log on the Central Administration by Form Based Authentication user I noticed that there is a value PeoplePicker which may control this. But I dont know how to do it.

A: You can migrate existing web application from classic-mode to claims-based authentication and hence allow the FBA there, using PowerShell. Follow this TechNet article for details:

*

*http://technet.microsoft.com/en-us/library/gg251985.aspx
I don't see any reasons why you can't try this approach with the Central Administration application.
P.S. If something went wrong, I believe SharePoint Configuration Wizard could recover the CA web application.

A: I would not advise this unless there was no windows authentication.
You risk locking yourself out and not being able to alter configuration to fix access problems.
If you need to provide external access to central admin, I advise using a secure Citrix server or VPN to expose central admin to users who are not directly connected to the domain.


text:
Q: MS Access - "phantom" process created by canceling report I have encountered a problem in Access 2010 for Windows:

*

*Launch a report using doCmd.OpenReport

*Set "Cancel = True" in an event associated with the report

*Close Access

*Access continues to run as a "phantom" process and must be killed in Task Manager.  Access cannot open another database until this process is killed.  The task initially shows some CPU utilization but quiets down to 0%.

I discovered this while using doCmd.OpenReport to launch a report. The report opens a form in the Report_Open event. The form prompts the user for report parameters and allows them to press "OK" to display the report or press "Cancel".  The On Click event for "Cancel" sets "Cancel = True".
It appears that OpenReport() is not responding gracefully to the cancel.  This seems like a frequently used technique so I hesitate to call it a bug and am wondering if I am doing something wrong.  Actually... the more I explain this, it does sound like a bug.  At this point, I am hoping somebody has a workaround or that I am missing something obvious.
This is just a simplified example I created to illustrate the problem:
form
Private Sub Form_Open(Cancel As Integer)
On Error GoTo errHandler

DoCmd.OpenReport "Test Report", acViewPreview, , , acDialog

Exit Sub

errHandler:
Select Case Err.Number
Case 2501   ' Cancelled by user, or by NoData event.
    MsgBox "Report cancelled, or no matching data.", vbInformation, "Information"
Case Else
    MsgBox "Error " & Err & ": " & Error$, vbInformation, "Form_Open()"
End Select
Resume Next

End Sub

report
Private Sub Report_Open(Cancel As Integer)
    Cancel = True
End Sub

A: The reason for the problem in this case is acDialog:
 DoCmd.OpenReport "Test Report", acViewPreview, , , acDialog

I think you will find:
 DoCmd.OpenReport "Test Report", acViewPreview

Works without problems.
Edit re Comment
You should not need to cancel the report. For the most part, it is better to avoid errors than to trap them, so check for data and get parameters before opening the form. Move the form from the report open event to step of its own and use DLookUp or a query to check for data before launching the form.

A: I'm not in a position to test this problem, so I'll just offer a generic solution: Remove the data/recordset/recordsource from the report definition.
You can apply the recordsource to the report after you have determined the parameters. If the report is canceled, it is canceled without ever having a data connection.


text:
Q: How do a reference a variable in another object I am an absolute programming beginner, and I am trying to learn Java from a book. I'm very confused.
The book has an exercise (this is like halfway through the chapter, so there's a lot building up to this, but I'll try to make it clear) that asks us to add a method to a class. Basically, we were given a prebuilt set of classes that are supposed to be like a simple auction program. So there is an array list which contains a list of bidders, how much they bid, and the lot number. This exercise asks us to add a method that will print out a list of the names of the winning bidders and the value of their bids.
Okay, that makes sense. I can wrap my mind around how it is supposed to work. I even wrote the following code: `
    /**
 * Exercise 4.48
 * for each item in the list of lots, get the highest bid.
 * if highest bid is not null, print the bidder and value
 * otherwise, print "lot not sold"
 */
 public void close()
{
    for(Lot lot : lots) {
        Bid highestBid = lot.getHighestBid();
        if(highestBid != null) {
            System.out.println(bidder, value);
        }
        else{
            System.out.println("Lot not sold.");
        }
    }
}

When try to compile it, it stops on bidder because I haven't defined the variable. So obviously I am supposed to tell it what "bidder" is supposed to mean. Bidder is the name of the variable in the "Person" object in the same program and is used throughout the project, but I'm still not clear on how to get it to understand that my "bidder" is the same "bidder." I assume that I will have the same issue with "value."
What am I missing?
Edited to make the code actually look like code.
As requested, here is the Person... class? (I'm not great with the terminology. I'll get there. Sorry.)
        /**
     * Maintain details of someone who participates in an auction.
     * @author David J. Barnes and Michael Kölling.
     * @version 2011.07.31
     */
    public class Person
    {
        // The name of this person.
        private final String name;

        /**
         * Create a new person with the given name.
         * @param name The person's name.
         */
        public Person(String name)
        {
            this.name = name;
        }

        /**
         * @return The person's name.
         */
        public String getName()
        {
            return name;
        }
    }

        **/**
     * A class to model an item (or set of items) in an
     * auction: a lot.
     *
     * @author David J. Barnes and Michael Kölling.
     * @version 2011.07.31
     */
    public class Lot
    {
        // A unique identifying number.
        private final int number;
        // A description of the lot.
        private String description;
        // The current highest bid for this lot.
        private Bid highestBid;

        /**
         * Construct a Lot, setting its number and description.
         * @param number The lot number.
         * @param description A description of this lot.
         */
        public Lot(int number, String description)
        {
            this.number = number;
            this.description = description;
            this.highestBid = null;
        }

        /**
         * Attempt to bid for this lot. A successful bid
         * must have a value higher than any existing bid.
         * @param bid A new bid.
         * @return true if successful, false otherwise
         */
        public boolean bidFor(Bid bid)
        {
            if(highestBid == null) {
                // There is no previous bid.
                highestBid = bid;
                return true;
            }
            else if(bid.getValue() > highestBid.getValue()) {
                // The bid is better than the previous one.
                highestBid = bid;
                return true;
            }
            else {
                // The bid is not better.
                return false;
            }
        }

        /**
         * @return A string representation of this lot's details.
         */
        public String toString()
        {
            String details = number + ": " + description;
            if(highestBid != null) {
                details += "    Bid: " +
                           highestBid.getValue();
            }
            else {
                details += "    (No bid)";
            }
            return details;
        }

        /**
         * @return The lot's number.
         */
        public int getNumber()
        {
            return number;
        }

        /**
         * @return The lot's description.
         */
        public String getDescription()
        {
            return description;
        }

        /**
         * @return The highest bid for this lot.
         *         This could be null if there is
         *         no current bid.
         */
        public Bid getHighestBid()
        {
            return highestBid;
        }
    }
    **

    /**
 * A class that models an auction bid.
 * It contains a reference to the Person bidding and the amount bid.
 *
 * @author David J. Barnes and Michael Kölling.
 * @version 2011.07.31
 */
public class Bid
{
    // The person making the bid.
    private final Person bidder;
    // The value of the bid. This could be a large number so
    // the long type has been used.
    private final long value;

        /**
         * Create a bid.
         * @param bidder Who is bidding for the lot.
         * @param value The value of the bid.
         */
        public Bid(Person bidder, long value)
        {
            this.bidder = bidder;
            this.value = value;
        }

        /**
         * @return The bidder.
         */
        public Person getBidder()
        {
            return bidder;
        }

        /**
         * @return The value of the bid.
         */
        public long getValue()
        {
            return value;
        }
    }

    import java.util.ArrayList;

    /**
     * A simple model of an auction.
     * The auction maintains a list of lots of arbitrary length.
     *
     * @author David J. Barnes and Michael Kölling.
     * @version 2011.07.31
     *
     * 3/12/15 added close method exercise 4.48
     *
     */

        public class Auction
        {
            // The list of Lots in this auction.
            private ArrayList<Lot> lots;
            // The number that will be given to the next lot entered
            // into this auction.
            private int nextLotNumber;

            /**
             * Create a new auction.
             */
            public Auction()
            {
                lots = new ArrayList<Lot>();
                nextLotNumber = 1;
            }

            /**
             * Enter a new lot into the auction.
             * @param description A description of the lot.
             */
            public void enterLot(String description)
            {
                lots.add(new Lot(nextLotNumber, description));
                nextLotNumber++;
            }

            /**
             * Show the full list of lots in this auction.
             */
            public void showLots()
            {
                for(Lot lot : lots) {
                    System.out.println(lot.toString());
                }
            }

            /**
             * Make a bid for a lot.
             * A message is printed indicating whether the bid is
             * successful or not.
             *
             * @param lotNumber The lot being bid for.
             * @param bidder The person bidding for the lot.
             * @param value  The value of the bid.
             */
            public void makeABid(int lotNumber, Person bidder, long value)
            {
                Lot selectedLot = getLot(lotNumber);
                if(selectedLot != null) {
                    Bid bid = new Bid(bidder, value);
                    boolean successful = selectedLot.bidFor(bid);
                    if(successful) {
                        System.out.println("The bid for lot number " +
                                           lotNumber + " was successful.");
                    }
                    else {
                        // Report which bid is higher.
                        Bid highestBid = selectedLot.getHighestBid();
                        System.out.println("Lot number: " + lotNumber +
                                           " already has a bid of: " +
                                           highestBid.getValue());
                    }
                }
            }

            /**
             * Return the lot with the given number. Return null
             * if a lot with this number does not exist.
             * @param lotNumber The number of the lot to return.
             */
            public Lot getLot(int lotNumber)
            {
                if((lotNumber >= 1) && (lotNumber < nextLotNumber)) {
                    // The number seems to be reasonable.
                    Lot selectedLot = lots.get(lotNumber - 1);
                    // Include a confidence check to be sure we have the
                    // right lot.
                    if(selectedLot.getNumber() != lotNumber) {
                        System.out.println("Internal error: Lot number " +
                                           selectedLot.getNumber() +
                                           " was returned instead of " +
                                           lotNumber);
                        // Don't return an invalid lot.
                        selectedLot = null;
                    }
                    return selectedLot;
                }
                else {
                    System.out.println("Lot number: " + lotNumber +
                                       " does not exist.");
                    return null;
                }
            }
            /**
             * Exercise 4.48
             * for each item in the list of lots, get the highest bid.
             * if highest bid is not null, print the bidder and value
             * otherwise, print "lot not sold"
             */
             public void close()
            {
                for(Lot lot : lots) {
                    Bid highestBid = lot.getHighestBid();
                    if(highestBid != null) {
                        System.out.println(bidder, value);
                    }
                    else{
                        System.out.println("Lot not sold.");
                    }
                }
            }

A: Thanks for clarifying your question by providing the supporting code!
This should fix your problem. Change this line:
System.out.println(bidder, value);

to this:
System.out.println(highestBid.getBidder().getName() + " bids " + highestBid.getValue())

The highestBid variable stores an object of type Bid. You can see the Bid class definition to see what it means for an object to have type Bid. Basically, a Bid object has a method called getValue(), which returns the value of the bid, and a method getBidder(), which returns a Person object (an object that abides by the Person class definition). So, look in the Person class and see how a Person object has a method called getName(), which returns the name of the person as a String.
Finally, we can just print the name and value with our handy built-in System.out.println() function.

A: To teach you the very basic,
Consider a class as a real life object,
It has it own characteristics which you define as class variables.
These should be (generally) defined private so a call to them has to happen from a class-function (getters and setters). The reason why we do this is so you can setup some restrictions. (like: "not higher than 3" or "must be min. 4 char. long" ...)
The class functions are like: small hidden classes within a Class they execute some code. Notice the "In", functions IN class. not the other way around. So the variables you create inside the functions are not known to the class, but the function knows the class-variables.
I would suspect in your case that you called to bidderand value:

*

*Without use of getters if they are defined private outside the same class where your close() function is defined.

But really it is very hard for us to know what is wrong. Please provide us with the classof the close() function
EDIT:
the code for close()should be...
public void close()
        {
            for(Lot lot : lots) {
                Bid highestBid = lot.getHighestBid();
                if(highestBid != null) {
                    System.out.println(highestBid.getBidder(), highestBid.getValue());
                }
                else{
                    System.out.println("Lot not sold.");
                }
            }


text:
Q: Angular Nx and NgRx : application not responding Please assist, i'm learning angular nx with ngRx, and trying to implement a basic state. i have workspace and inside i have an app called company-portal with its own state. to create the state i ran the following command :
   ng generate ngrx company-state --module=apps/company-portal/src/app/app.module.ts  --onlyEmptyRoot

after i created a lib called login as follows :
   ng g lib shared/login --routing --lazy --parent-module=apps/company-portal/src/app/app.module.ts

and added a state as follows:
   ng g ngrx login-state --module=libs/shared/login/src/lib/shared-login.module.ts

then after i created a component :
   ng g c view/login-form --project=shared-login

inside the component.ts file i injected a store and added a login function as follows :
   constructor(private store: Store<LoginSharedState>) {}

   login() {
     this.store.dispatch(new loginActions.LoginShared());
   }

i have a button that execute the login function but as i click the button the application freezes(stops responding). i implemented storeFreeze and added the metaReducer, still its not working.
what should i add to make the app respond when i click the login button.

A: It is not visible in your code and it is quite late to answer this question. But maybe my insights can help someone out there.
I use NgRX almost every day and the only time I see it freeze (and it is related to NgRX) is when there is an Effect which does not emit a new action and you have not configured the effect with the option { dispatch: false } like for example demonstrated in the two snippets:
// Freezing
createEffect(() => this.actions$.pipe(
  ofType(myAction),
  tap(() => { /* do something */ })
))

// Not Freezing
createEffect(() => this.actions$.pipe(
  ofType(myAction),
  tap(() => { /* do something */ })
), { dispatch: false })

It is not necessary that there is a tap operator, but it is a common use case. As I said, the important thing here is, that it does not emit a new action in the stream. You can see another demo in the last snippet on the official effects docs.


text:
Q: jQuery animation callback running early I created jsfiddle and the code(a click version of the following) works fine, but on my actual site the text switches before it hides. This makes the whole thing look ridiculous. I am using icefaces, which reloads certain parts of the page and that's when the code is running. Essentially I'm animating the change that icefaces sends.
function slideValue(id, newValue){
id = id.replace("`", "");

val = '#' + id;
if(jQuery(val).text() != newValue){
    jQuery(val).hide('slide',{
        duration: 300,
        direction: 'up',
        complete: function(){jQuery(val).text(newValue);}
    });
    jQuery(val).show('slide', {direction: 'down'}, 300);
}

}

A: you can try
$('#hey').click(function () {
newValue = "newwww";
val = '#' + "hey";
if (jQuery(val).text() != newValue) {
    jQuery(val).hide('slide', {
        duration: 300,
        direction: 'up',
        complete: function () {
            jQuery(val).text(newValue);
            jQuery(val).show('slide', {
                direction: 'down'
            }, 300);
        }
    });
}
} );

http://jsfiddle.net/RAQzm/5/

A: No matter how I tried to set up a queue, this wasn't working. It worked fine on JSfiddle but not in the actual web application. I eventually got this to work by using javascripts setTimeout() method.


text:
Q: If $a,b,c\in\mathbb Z$ then show that $c\cdot\gcd(a,b)\leq\gcd(ac,bc)$
If $a,b,c\in\mathbb Z$, then show that $c\cdot\gcd(a,b)\le\gcd(ac,bc)$.

My try: we know that $\gcd(ca,cb)=c\cdot \gcd(a,b)$, but here I don't know what to do.

A: You're wrong when you say $gcd(ac,bc)=c\cdot gcd(a,b)$. The correct equation is $gcd(ac,bc)=|c|\cdot gcd(a,b)$. Do you know how to prove this equation (hint: prime factorization)? From this equation the theorem follows immediately because $c\leq |c|$ holds for all $c\in\mathbb{Z}$


text:
Q: How to make a uibutton zoomout and then crossblur? I have got an UIButton animation implemented, as for now it zooms but I also want to cross fade the UIButton while it disappears.
This is my sample code for button animation.
(void)centerButtonAnimation{
    CAKeyframeAnimation *centerZoom = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    centerZoom.duration = 1.5f;
    centerZoom.values = @[[NSValue valueWithCATransform3D:CATransform3DMakeScale(1, 1, 1)],[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.5, 1.5, 1.5)],[NSValue valueWithCATransform3D:CATransform3DMakeScale(4, 4, 4)],[NSValue valueWithCATransform3D:CATransform3DMakeScale(5, 5, 5)]];
    centerZoom.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    centerButton.transform = CGAffineTransformMakeScale(5, 5);
    [centerButton.layer addAnimation:centerZoom forKey:@"buttonScale"];
    [centerButton setUserInteractionEnabled:NO];
}

A: To chain the animations, you can set your class to be a delegate for the animation.
@property CAKeyframeAnimation *centerZoom;

- (void) centerButtonAnimation
{
    self.centerZoom = [CAKeyframeAnimation animationWithKeyPath:@"transform"];

    // Set the delegate to this instance.
    centerZoom.delegate=self;

    centerZoom.duration = 1.5f;
    centerZoom.values = @[[NSValue valueWithCATransform3D:CATransform3DMakeScale(1, 1, 1)],[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.5, 1.5, 1.5)],[NSValue valueWithCATransform3D:CATransform3DMakeScale(4, 4, 4)],[NSValue valueWithCATransform3D:CATransform3DMakeScale(5, 5, 5)]];
    centerZoom.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    centerButton.transform = CGAffineTransformMakeScale(5, 5);
    [centerButton.layer addAnimation:centerZoom forKey:@"buttonScale"];
    [centerButton setUserInteractionEnabled:NO];
}

- (void) crossFadeAnimation
{
   // Insert animation code for cross fade.
}

Then implement the delegate function to detect the end of the animation. If its the end of a zoom, start the cross fade.
- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag
{
   if ((theAnimation == self.centerZoom) && flag){
     [self crossFadeAnimation];
   }
}


text:
Q: Issue with LoadContent converting XNA 2.0 to 4.0 Hello I am doing this project in school and I ran into a problem when I got a pdf with instructions to make a small and simple game. There was all the code in the pdf but the problem is that my teacher wrote the code in XNA 2.0 and we are using XNA 4.0.
The thing is that in my LoadContent part of the Game1.cs there is a bit of code that dont work.
protected override void LoadContent()
{
    foreach (GameObject g in gameObjects)
    {
        g.LoadContent();
    }
    // Create a new SpriteBatch, which can be used to draw textures.
    spriteBatch = new SpriteBatch(GraphicsDevice);
    // TODO: use this.Content to load your game content here
}

The part of the code that fails is the g. When I try to Debug it shows this error message

An unhandled exception of type 'System.NullReferenceException' occurred in First XNA.exe
  Additional information: Objektreferensen har inte angetts till en instans av ett objekt.

I have no idea how to fix it. If you need more info please say it so I will try to provide it.

A: As the exception states : "NullReferenceError" means that g is null when you try to invoke LoadContent(). I have a feeling that you need to check gameObjects for consistency.
Hope this helps!


text:
Q: Drupal import users from one install to another install I have 2 drupal databases, 1 current database and a backup. I'm now in the situation where I need to restore the backup. I'm looking for a way to import the new users in the current database into the backup.
How should I go about doing this?

A: If you are comfortable with SQL, just copy the appropriate SQL insert statements from a backup of your current site (the 'user' table, and possibly the 'profile_fields' and 'profile_values' if you have profile enabled).
Alternatively, it looks like these modules could possibly work together:
http://drupal.org/project/user_import
http://drupal.org/project/profile_csv
Although I haven't actually used either....


text:
Q: How to know when a perspective is selected rcp In my class, I'm implementing IPerspectiveListener, IPartListener, in order to perform certain actions if certain perspective is activated in the method perspectiveActivated(IWorkbenchPage page, IPerspectiveDescriptor perspective) and do something in the partActivated(IWorkbenchPart part). But the problem is, partActivated(IWorkbenchPart part) is getting called before perspectiveActivated(IWorkbenchPage page, IPerspectiveDescriptor perspective). Doesn't seem like above method is getting called on perspective switch manually. Is there any way to implement what I mentioned.
public class MyClass implements IPerspectiveListener, IPartListener {

 private boolean buttonClicked = false;

        @Override
        public void partActivated(IWorkbenchPart part) {
            try {
                if(buttonClicked){

                     //do something

               }
            } catch (WorkbenchException e) {
                e.printStackTrace();
            }

        }

        @Override
        public void partBroughtToTop(IWorkbenchPart part) {
        }

        @Override
        public void partClosed(IWorkbenchPart part) {}

        @Override
        public void partDeactivated(IWorkbenchPart part) {}

        @Override
        public void partOpened(IWorkbenchPart part) {}

        @Override
        public void perspectiveActivated(IWorkbenchPage page, IPerspectiveDescriptor perspective) {
        buttonClicked = true;
        }

        @Override
        public void perspectiveChanged(IWorkbenchPage page, IPerspectiveDescriptor perspective, String changeId) {

        }

    }


text:
Q: Randomly losing connection but still in LAN At work I am using ubuntu 12.04 on my laptop.
Throughout the day I randomly lose connection to the internet, but I am still in the WLAN.
Like, when I try to connect to google it will timeout and not do anything.  Then after about 30 seconds I will be able to connect to google again.
Does anyone have an idea as to why this may be happening?  There is a coffee shop next door and I can connect to it and surf the internet all day without having any issues.
Is it possible that someone is de-authenticating me?  In this case, wouldn't I also lose connection to the WLAN?  Is it possible to use wireshark to see is this is happening?
Kindest Regards,


text:
Q: Expression to run job on end of every month : Camel,Quartz I am trying to run my job every end of month but i am getting an error every time i add cron expression :
from("timer://ratingTimer?cron=0+52+12+++")
this is i am trying to run my job for specific time.
Caused by: org.apache.camel.ResolveEndpointFailedException: Failed to resolve endpoint: timer://ratingTimer?cron=0+52+12+%3F++* due to: There are 1 parameters that couldn't be set on the endpoint. Check the uri if the parameters are spelt correctly and that they are properties of the endpoint. Unknown parameters=[{cron=0 52 12 ? * *}]

A: We will schedule cron on 28,28,29 and 31'st of each month. Now find if today is the last day of the month. To find it check if the next day is 01'st of next day and then only execute any command.
Below command will return the date of the next day.

date +%d -d tomorrow

Now check if tomorrow is 01.

[ "$(date +%d -d tomorrow)" = "01" ] && echo "True"

If the next day is 01 then above command will print "True" on screen. Here you can use the above script in crontab and change echo with your command.

59 23 28-31 * * [ "$(date +%d -d tomorrow)" = "01" ] && /root/script.sh

Check more in below url.
CRON job to run on the last day of the month
AND
quartz scheduler: run on last day of the month

from("cron://ratingTimer?schedule=0+0+3+L+*+?")


text:
Q: Add a new entry in KDialog "Save as" window I have running KDE Plasma for a few months now, and I have been able to fix some minor issues with the Google Drive integration in Dolphin. The only thing I cannot get done is to add an entry to my Google Drive in the standard KDialog "save as" when, for example, I want to save a picture in my computer from the web. I got it in Dolphin:
Dolphin Drive links
But I can't get same result in KDialog:
KDialog links
Any help with this?
Thanks a lot.
Borja.


text:
Q: Get date for a specific day which is after today's date If I have date like 22-11-2016(d-m-Y) and the day is Saturday for whom I have to search the date and it would be 26-11-2016(d-m-Y). So How to get it?

A: If you want to get next week day's date then might be this can help you.
date('d-m-Y', strtotime('next saturday'));

Or also you can use PHP date object as below.
// Create a new DateTime object
$date = new DateTime('22-11-2016');

// Modify the date it contains
$date->modify('next saturday');

// Output
echo $date->format('d-m-Y');

A: Here you going, using DateTime you could do this.
$date = new DateTime( '22-11-2016' );
$date = $date->modify( 'next saturday' );
echo $date->format( 'd-m-Y' );