text:
Q: Query multiple databases on Local host I'm trying to join two two tables in seperate databases on the same server.
I keep getting the error Invalid object name 'Unit.dbo.templates', as if it can't find my database when it's being queried on the Database name.
Database 1:
Name: Unit
Schema owner: dbo
Database 2:
Name Content
Schema owner: dbo
This is my connectionstring so far:
<add name="ConnectionString" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Unit.mdf;Integrated Security=True"
        providerName="System.Data.SqlClient" />

This is the query i'm using to test:
SELECT * FROM Unit.dbo.templates

Is anybody able to see what i am doing wrong?


text:
Q: How to translate JFileChooser column headers under Windows? I have finalized a translation of a JFileChooser dialog to Dutch. In doing so I found this resource very useful.
During the test of this translation, I ran into a problem that I am not able to resolve: under Windows (Windows 7 Professional Service Pack 1 64-bit) the headers of the columns in detail view are not translated. It does not matter which Look & Feel I am using. When I test on Mac the headers are properly translated. Here is some code to demonstrate the problem. Switch to Details to see the column headers. I added the translation of Refresh to Verversen in the context menu to demonstrate that other translations are picked up.
package translationjfilechooser;

import javax.swing.JFileChooser;
import javax.swing.UIManager;

public class TranslateColumnsJFileChooser {

    JFileChooser fc;

    public TranslateColumnsJFileChooser() {
        UIManager.put("FileChooser.fileNameHeaderText", "Naam");
        UIManager.put("FileChooser.fileSizeHeaderText", "Grootte");
        UIManager.put("FileChooser.fileTypeHeaderText", "Bestandstype");
        UIManager.put("FileChooser.fileDateHeaderText", "Gewijzigd op");
        UIManager.put("FileChooser.refreshActionLabelText", "Verversen");
        try {
            // It does not matter which Look & Feel you are using
            // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
        } catch (Exception e) {
            System.err.println("Could not change look and feel");
            return;
        }
        fc = new JFileChooser();
        fc.setDialogTitle("This demonstrates that column headers are not translated under Windows");
        fc.showOpenDialog(fc);
        return;
    }

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

Does anybody know a way to translate these headers? Or at least the reason why they cannot be translated?
In order to analyse the problem I tried to find the translation keys for these headers in the Java source code, but was not able to find them. Neither was I able to find the key FileChooser.refreshActionLabelText.

A: I can confirm it is fixed in Java 11 as VGR posted in the comments.

redpajama_set_name: RedPajamaStackExchange


text:
Q: error when calling the distributeMessage method using now.js Started playing with the now.js framework.  Using the example code in now.js I'm trying to implement a chat.  Including here for completeness.
<script src="http://localhost:8080/nowjs/now.js" type="text/javascript"></script>

<!-- HTML for Chat Here  -->

$(document).ready(function() {

  now.receiveMessage = function(name, message) {
    $(".chattext").append("<br>" + name + ": " + message);
    $(".chattext").attr({ scrollTop: $(".chattext").attr("scrollHeight") });
  }

  $("#send-button").click(function() {
    now.distributeMessage($("#text-input").val());
    $("#text-input").val("");
  });

  now.name = prompt("What's your name?", "")

});

I've got the node.js server with now.js working properly.
I'm trying to extend the chat so that when a user enters their name, a message is sent to the server noting that " has now joined the chat."  The example code prompts a user for a name and sets that to the now object's name.
now.name = prompt("What's your name?", "");

At this point, the now object is available.  So instead of simply setting the now.name, I'm trying to set the now.name AND send a message by calling distributeMessage('John has joined chat.')
var p = prompt("What's your name?", "");
if (!p) {
    // errs here
} else {
    now.name = p;
    now.distributeMessage(now.name + " has joined chat.");
}

Chrome and firefox report an error that reads
Object #<Object> has no method 'distributeMessage'.
I don't understand why.  The now.name property can be set.  The console log shows the object with get distributeMessage and set distributeMessage functions.  I can send the message when I click on the 'send-button' element.  But, I am unable to call the distributeMessage at this point.
Is the now object not fully loaded when I try to make the method call?  Do I need to include some sort of 'now' onLoadReady method?  What do I need to do in order to fire off the now.distributeMessage method after the prompt?

A: I've found a method to address my issue.  I need to surround the call to distribute message with a
now.ready(function() {
  now.distributeMessage(now.name + " has joined chat.");
})

It seems the client side now namespace was available but all serverside now calls still required javascript to finish processing.


text:
Q: Why does cmath pow give inaccurate answers? In C++11:
pow(1061,6);   // = 1426567426713180416

Check the last 3 digits.
I know for sure that result is wrong, because 1061^6 = 1426567426713180361.
But this other method does it right:
long a =1;
for(int i=0; i<6 ; i++){ a*=1061; }
cout << a;  // = 1426567426713180361

pow  is included from cmath.
If anyone knows, I'd like to know why both results aren't equal.

A: pow uses double  for its output, which has approximately 16 decimal digits of accuracy. A 64bit long however has 19.

A: std::pow will return double for the integral case and this answer here explains the first integral where double can not longer exactly represent every integral starts at 9007199254740993 after this we may have integers that can not be exactly repsented exactly as a double.
We can see this more easily using the fact that narrowing conversions are ill-formed using uniform initialization. Using the results you desire we see that:
double d2{1426567426713180361};

is a narrowing conversion (live godbolt)
error: constant expression evaluates to 9007199254740993 which cannot be narrowed to type 'double' [-Wc++11-narrowing]
double d1{9007199254740993} ;
        ^~~~~~~~~~~~~~~~

since it can not be exactly represented. We can also see the number from earlier is also a narrowing conversion:
double d1{9007199254740993} ;

while:
double d3{1426567426713180416};

is not.

A: std::pow works on doubles. It does not keep the precision of the resultant number for such large integral values as well as integer arithmetic does.


text:
Q: how do I duplicate a regular expression I want to search for all the phrases that are in quotes and then duplicate them.
In Emacs, my search looks like this:
M-x replace-regexp <RETURN> "*" <RETURN> $& $& <RETURN>
But it doesn't work...

A: "*" doesn't match a quote-delimited string; it matches any (nonzero) number of quotation marks in a row.
In regular expressions, * is a modifier, not the wildcard that it is in filename patterns. It means "match 0 or more of the previous pattern", so "*" is "0 or more quotation marks, followed by a quotation mark" - that is, any number of quotation marks in a row.
The usual regular expression for "anything" is .* which matches 0 or more of "any character" (.).  But that would include quotation marks; ".*" would match everything from the first quotation mark to the last as one big string.  What you want is "[^"]*", which matches a quotation mark, followed by any number of non-quotation marks, followed by another quotation mark.
Also, the matched pattern is \&, not $&. This might work better:
M-x replace-regexp <RETURN> "[^"]*" <RETURN> \& \& <RETURN>


text:
Q: Vue-Router only showing base route using Laravel Blade? I'm switching from routing with Laravel to using Vue-Router on my application, and I can only get the base route to load using Vue-Router. I've seperated the routes into two files, public and private using the example from this article: https://itnext.io/vue-router-99e334094362. I'm new to Vue-Router, what am I doing wrong?
Here's my code:
main.blade.php :

            <am-app-nav></am-app-nav>

            <router-view></router-view>

            <am-footer></am-footer>

app.js:
window.Vue = require('vue')

import Vue from 'vue'
import VueRouter from 'vue-router'
import router from './router/index.js'

Vue.use(VueRouter)

const app = new Vue({
  el: '#app',
  router,
})

router/index.js:
import Vue from 'vue'
import Router from 'vue-router'
import routes from './routes/index.js'
Vue.use(Router)

const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      redirect: '/welcome',
    },
  ].concat(routes),
})

export default router

router/routes/index/js :
import publicRoutes from './public.js'
import privateRoutes from './private.js'

export default publicRoutes.concat(privateRoutes)

router/routes/private.js:
const routes = [
  {
    path: '/dashboard',
    component: require('../../views/admin/Dashboard').default,
  },
  {
    path: '/client-details',
    component: require('../../views/admin/ClientDetails').default,
  },
  {
    path: '*', component: require('../../views/public/NotFound').default
  },
]

export default routes.map((route) => {
  return { ...route, meta: { public: false } }
})

A: I needed to add this to web.php:
// SPA Route
Route::get('{any}', function () {
    return view('_layouts.main');
})->where('any', '.*');


text:
Q: Java Spring omits fields when making a JSON public class ConnectedEntry {

    private EntryInScores scores;
    private EntryInValues values;
    private String someString;

    public ConnectedEntry(EntryInScores scores, EntryInValues values) {
        this.scores = scores;
        this.values = values;
        this.someString = "Adasd";
    }

I have an object that looks more or less like this, and I use it as a GET response for my API. scores and values are both database entities. I wanted to add a String to the response with some additional information.
What happens is that the objects are properly turned into a JSON and they show up in the response, but the string is omitted, with no error: it's just not there.
I tried wrapping the string in a wrapper class, but it didn't help.
What could I do?

A: You can go for creating json object and put the data as key value pair to resolve this issue.
Happy Coding!!!

A: Usually Spring uses Jackson as the default converter from objects to JSON. In order for Jackson to convert to JSON you must provide getters, so that Jackson can get and convert those values. As I can see in your representation you don't have any getters. Try providing getters for the fields that you wish to convert. Never make fields public!


text:
Q: Saving data.frames over a loop from a namelist in R I'm trying to save some data.frames and tables with a loop. I thought, that it will be easier if I put all the names of the data.frames in a list and call the list later in the for-loop. But I really don't get it. The namelist works for the filename, but I can not get the real dataframe from the namelist. I get always an error message...
That is my code at the moment:
ListTablesCharacter <- c("ResultsConditionDeltaFaceMean","ResultsConditionResponseTimeMean","ResultsManipulationDeltaFaceMean", ... ,"VPNCondition")

for (i in 1:length(ListTablesCharacter)){

  save(get(ListTablesCharacter[i]), file=paste(ListTablesCharacter[i],".rda", sep =""))
  write.csv(get(ListTablesCharacter[i]), file=paste(ListTablesCharacter[i],".csv", sep =""))
}

And this is the error message I get at the moment.
Error in save(get(ListTablesCharacter[ii]), file = paste(ListTablesCharacter[ii],  :
  Object 'get(ListTablesCharacter[ii])' not found

I believe that the second part, after file = works.
Is there a way to get the save-command over this approach?
It should work like this.
save(ResultsConditionDeltaFaceMean, file=paste("ResultsConditionDeltaFaceMean",".rda", sep =""))
write.csv(ResultsConditionDeltaFaceMean, file=paste("ResultsConditionDeltaFaceMean",".csv", sep =""))

save(ResultsConditionResponseTimeMean, file=paste("ResultsConditionResponseTimeMean",".rda", sep =""))
write.csv(ResultsConditionResponseTimeMean, file=paste("ResultsConditionResponseTimeMean",".csv", sep =""))
#etc.

Thanks for the help.


text:
Q: Use Apache Airflow to do a simple select * and dump it to email I am an Airflow newb and I have a very simple requirement to query an existing table using a somewhat complex select query and then email it's result to myself.
Assuming that it's a basic sql query like:
select * from table where somevar="some_value"

and I just want this data to be sent as an email from Airflow - how to do this.
I've already started watching some youtube tutorial here - but it's already feeling like an overkill for my usecase.
Would appreciate a simple gist of doing the above.
Thanks

A: First step is executing the query to get the result and store it somewhere (S3, GCS, ...). For the libs you can use, it depends on which database/processing tool you are using, for example if you want to query a postgres db, the operator PostgresOperator doesn't support storing result, so you need to use the hook PostgresHook in a new operator, to read the result and store it, same if you are using presto, you can use PrestoHook.
For the email sending, you can create a new subclass from EmailOperator, which download the file from S3/GCS, and send it using EmailOperator to your email.
Why you cannot store the file locally instead of uploading and downloading it to object store service? That's because in some Airflow executors (k8s, celery), the tasks are executing in different workers, so the data downloaded in a worker are not available for the others, but you have a LocalExecutor you can download the file locally and use the EmailOperator to send it.


text:
Q: Possible to hook up 3x 12V, .5A cooling fans to a single 12V, 2A power supply? If I have an adaptor with a power supply of 12V, 2A., will I be able to or will it even be safe to hook up three (3) computer cooling fans (on to the same adaptor) with this rating: DC 12V,0.5A? For any question on why am I asking this, well, it's basically just to save on the number of power points I'd need to plug in three basic cooling fans for an indoor hydroponic system. I'd really appreciate anyone's help on this. Much thanks in advance.

A: The voltage is the same.
0.5A × 3 = 1.5A.
That's less than power supply's capabilities, so you should be good.


text:
Q: Unnable to encode character while reading email body I'm using this code in Apache NiFi to read email body (found it on stackoverflow also):
import email
import mimetypes
from email.parser import Parser
from org.apache.commons.io import IOUtils
from java.nio.charset import StandardCharsets
from java.io import BufferedReader, InputStreamReader
from org.apache.nifi.processors.script import ExecuteScript
from org.apache.nifi.processor.io import InputStreamCallback
from org.apache.nifi.processor.io import StreamCallback

class PyInputStreamCallback(InputStreamCallback):
    _text = None

    def __init__(self):
        pass

    def getText(self) :
        return self._text

    def process(self, inputStream):
        self._text = IOUtils.toString(inputStream, StandardCharsets.UTF_8)

flowFile = session.get()
if flowFile is not None :
    reader = PyInputStreamCallback()
    session.read(flowFile, reader)

    msg = email.message_from_string(reader.getText())
    body = ""

    if msg.is_multipart():
        for part in msg.walk():
            ctype = part.get_content_type()
            cdispo = str(part.get('Content-Disposition'))

            if ctype == 'text/plain' and 'attachment' not in cdispo:
                body = part.get_payload(decode=True)  # decode
                break
    else:
        body = msg.get_payload(decode=True)

    flowFile = session.putAttribute(flowFile, 'msgbody', body.decode('utf-8', 'ignore'))

    session.transfer(flowFile, ExecuteScript.REL_SUCCESS)

It works OK in most scenarios, but sometimes I receive an error:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u041a' in position 4784: ordinal not in range(128)
I never work with Python and tried to fix it with .encode('utf-8') at this line: cdispo = str(part.get('Content-Disposition')), but it didn't help. Maybe I'm wrong with thought that problem is in this line.
Full error:
Processing failed: org.apache.nifi.processor.exception.ProcessException: javax.script.ScriptException: UnicodeEncodeError: 'ascii' codec can't encode character u'\u041a' in position 4784: ordinal not in range(128) in <script> at line number 30
- Caused by: javax.script.ScriptException: UnicodeEncodeError: 'ascii' codec can't encode character u'\u041a' in position 4784: ordinal not in range(128) in <script> at line number 30
- Caused by: Traceback (most recent call last):
  File "<script>", line 30, in <module>
  File "/opt/nifi/nifi-current/work/nar/extensions/nifi-scripting-nar-1.16.3.nar-unpacked/NAR-INF/bundled-dependencies/jython-standalone-2.7.2.jar/Lib/email/__init__$py.class", line 57, in message_from_string
  File "/opt/nifi/nifi-current/work/nar/extensions/nifi-scripting-nar-1.16.3.nar-unpacked/NAR-INF/bundled-dependencies/jython-standalone-2.7.2.jar/Lib/email/parser$py.class", line 82, in parsestr
UnicodeEncodeError: 'ascii' codec can't encode character u'\u041a' in position 4784: ordinal not in range(128)


text:
Q: How do I make readonly file writable in Netbeans I am using Netbeans 6.9.1.
Whenever I open readonly file and want to edit it I have to go to file directory manually and remove the readonly flag from properties.
Is there any plug-in or some way we can do directly make it writable in netbeans editor itself?


text:
Q: How to re-render after state has changed In React, I am working with a Kendo grid. I have a grid that is filled with a state array like this:
const [tempAtributi, setTempAtributi] = useState([]);

// ...

const MyCommandCell = (props) => {
    const indexObj = tempAtributi.findIndex(
        (e) => e.atribut_id === props.dataItem.atribut_id
    );

    const Remove = () => {
        if (indexObj > -1) {
            const lista = tempAtributi;
            lista.splice(indexObj, 1);
            setTempAtributi(lista);
        }
    };

    return (
        <td className="k-command-cell">
            <Button
                className="k-button k-button-md k-rounded-md k-button-solid k-button-solid-base k-grid-remove-command"
                onClick={() => Remove()}
            >
                <FaTrash /> Remove
            </Button>
        </td>
    );
};

const Cell = (props) => <MyCommandCell {...props} />;

useEffect(() => {
    (async () => {
        try {
            const resAtr = await services.getTemplateAtributi(
                state.data.sn_template_id
            );
            setTempAtributi(resAtr.data.rlista);
        } catch (e) {
            console.log(e);
        }
    })();
}, []);

//...

return (
    <>
        <Grid data={tempAtributi}>
            <GridColumn field="name" title="Atribut" filter="text" />
            <GridColumn cell={CommandCell} title="remove" filter="text" />
        </Grid>
    </>
);

So, on render I call an API in useeffect and fill the tempAtributi state with an array of objects. My grid is filled. After that, I have a column Remove where you can click and onClick, it is checked if that atribute is inside the tempAtributi array of objects. If it is, I update tempAtributi state with an array of object minus the object that is removed. After I finished removing, I must click confirm which calls an API and sets tempAtributi state as the updated/new value ( if I call services.getTemplateAtributi after Confirm is clicked I get updated values):
<Button themeColor={"primary"} style={{marginTop:'2%', marginRight:'2%'}} onClick={() => Confirm()}>
    Confirm
</Button>

If I click remove one or more times(without confirming) everything is ok, if I console log the state, it hasn't got the removed object, but the thing is that I can still see the object in the grid even though it is not in the tempAtributi state anymore. I want to refresh the grid after I click remmove so that row is not there.I don't know how to refresh the grid after the removal, because if I call useeffect, it will call the API and set it to the begging values. Help needed!

A: My first guess would be removing deep object copy. Since cloning objects in JavaScript ties them deeply.
You can test this with one simple example:
const a = { b: { c: 'd' } } }
const b = a
b.b.c = 'e'
console.log(a, b)

As you notice, both a and b, has same value, but yet we mutated only one of them.
You can kill this tie using b = JSON.parse(JSON.stringify(a)), which is most common approach.
So in your example your delete function should look like this:
const Remove = () => {
  if (indexObj > -1) {
    const deepCopy = JSON.parse(JSON.stringify(tempAtributi));
    deepCopy.splice(indexObj,1);
    setTempAtributi(deepCopy);
  }
}


text:
Q: Swing–JavaFX Interoperability ConcurrentModificationException bug I have spent the last 3 days (20+ hours) trying to solve this ConcurrentModificationException bug. I am trying to migrate my pretty large Java project to JavaFX and I am having trouble with managing Swing–JavaFX Interoperability and Threads, since I want my program to be hybrid in that respect.
The Bug
The Bug arises when I click sufficiently fast on the Add Particle button (but also from multiple other sources in my main project, other buttons also produce the same error). I get the following stacktrace
Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException
        at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1043)
        at java.base/java.util.ArrayList$Itr.next(ArrayList.java:997)
        at MainPanel$2.actionPerformed(MainPanel.java:40)
        at java.desktop/javax.swing.Timer.fireActionPerformed(Timer.java:317)
        at java.desktop/javax.swing.Timer$DoPostEvent.run(Timer.java:249)
        at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:313)
        at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:770)
        at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
        at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
        at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:740)
        at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
        at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
        at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
        at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
        at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
        at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

Here follows the most Minimally Reproducible Example (MRE) of my project that I can provide, with a Github link here :
testProjectFx.fxml
(FXML file)
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.BorderPane?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/16" xmlns:fx="http://javafx.com/fxml/1" fx:controller="SampleController">
   <children>
      <BorderPane fx:id="mainPanel" prefHeight="318.0" prefWidth="535.0" />
      <Button fx:id="addParticle" layoutX="26.0" layoutY="347.0" mnemonicParsing="false" text="Add Particle" />
   </children>
</AnchorPane>

SampleController.java
(FXML Controller file)
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;

public class SampleController {

    @FXML
    private BorderPane mainPanel;

    @FXML
    private Button addParticle;

    public void initializeButtons(MainPanel mainPanel) {
        addParticle.addEventHandler(ActionEvent.ACTION, event -> mainPanel.addParticle(
            100, 5
        ));

    }

}

App.java
(Main class that extends Application).
import javafx.application.Application;
import javafx.embed.swing.SwingNode;
import javafx.fxml.FXMLLoader;
import java.awt.Color;

import javax.swing.SwingUtilities;

import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class App extends Application{
    public static void main(String[] args) {
        launch(args);
    }

    public static SampleController controller;

    @Override
    public void start(Stage stage) throws Exception {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("testProjectFx.fxml"));
            Parent root = loader.load();

            controller = (SampleController) loader.getController();

            Scene scene = new Scene(root, 600 , 400);

            BorderPane scenePanel = (BorderPane) scene.lookup("#mainPanel");
            SwingNode swingNode = new SwingNode();
            MainPanel mainPanel = new MainPanel();

            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    mainPanel.setSize(535, 318);
                    mainPanel.setBackground(Color.black);
                    mainPanel.physicsTimer.start();
                    mainPanel.fpsTimer.start();
                    swingNode.setContent(mainPanel);
                }
            });
            scenePanel.setCenter(swingNode);

            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    mainPanel.initializeParticles(15, 100 ,5);
                    controller.initializeButtons(mainPanel);
                }
            });

            stage.setTitle("FXML Welcome");
            stage.setScene(scene);
            stage.show();

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

MainPanel.java
(JPanel where the painting occurs)
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Arc2D;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.JPanel;
import javax.swing.Timer;

public class MainPanel extends JPanel{

    static Random rand = new Random();
    static ArrayList<Particle> particleList = new ArrayList<Particle>();
    static int timeTick = 1000/60; //fps normal

    /*
     * Timer that updates the screen every at 60 FPS.
     */
    Timer fpsTimer = new Timer(timeTick, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
                for(Particle p : particleList) {
                    p.x += p.vx;
                    p.y += p.vy;
                }
            repaint();
        }
    });

    /*
     * Timer that updates the physics every 1 millisecond.
     */
    Timer physicsTimer = new Timer(1 , new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
                for(Particle p1 : particleList) {
                    for(Particle p2 : particleList) {
                        if(p1 == p2) continue;

                        // p1.edgeCollision(p2);
                        // applyForces(p1, p2);
                        // applyCollision(p1, p2);
                    }
                    p1.x += p1.vx;
                    p1.y += p1.vy;
                }
        }
    });

    /*
     * Function that initializes some particles on the canvas at the beggining.
     */
    public void initializeParticles(int numberOfParticles, int mass, int charge) {

        for(int i = 0 ; i < numberOfParticles ; i++) {
            int xPos;
            int yPos;
            do {
                xPos = rand.nextInt(100)+25;
                yPos = rand.nextInt(100)+25;
                Particle p = new Particle(xPos, yPos, 0, 0,mass, charge); //mass charge at end
                particleList.add(p);
            }while(!particleAlreadyExists(xPos, yPos));

        }
    }

    /*
     * Draw the particles on the canvas.
     */
    public void paintComponent(Graphics g) {

        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;

        for(Particle particle : particleList) {
            g2d.setColor(Color.WHITE);
            Shape circle = new Arc2D.Double(particle.x, particle.y, particle.width, particle.height,
                    0 , 360, Arc2D.CHORD);
            g2d.fill(circle);
        }
    }

    /*
     * Checks if a particle already exists at the generated position.
     */
    public boolean particleAlreadyExists(double x, double y) {

        boolean particleExistsAlready = false;
        for(Particle particle : particleList) {
            if(x >= particle.x-particle.width && x <= particle.x+ 2*particle.width &&
                    y >= particle.y-particle.height && y <= particle.y + 2*particle.height) {
                particleExistsAlready=true;
                break;
            }
        }
        return particleExistsAlready;

    }

    public void addParticle(int mass, int charge) {
        initializeParticles(1, mass, charge);
    }

}

Particle.java
(Particle object class)
import java.awt.Color;
import java.util.ArrayList;
import java.util.Random;

public class Particle{
    double x, y;
    double width, height;
    double mass;
    double vx, vy;
    int charge;
    public double radius = 0;
    public double centerX = 0;
    public double centerY = 0;
    static Random rand = new Random();

    public Particle(double x, double y, double velX, double velY,double mass, int charge) {
        this.x = x;
        this.y=y;
        this.width=mass/10;
        this.height=mass/10;
        this.vx=velX;
        this.vy = velY;
        this.mass=mass;
        this.charge = charge;
        this.radius = this.width/2;
        this.centerX = this.x + (this.width/2);
        this.centerY = this.y + (this.height/2);
    }

    public static double velInit() {
        double val;
        if(rand.nextBoolean()) {
            val = rand.nextDouble()*0.5;
        } else {
            val = -rand.nextDouble()*0.5;
        }
        return val;
    }

    public void reinitializeVel(ArrayList<Particle> particles) {
        for(Particle p : particles) {
            p.vx = velInit();
            p.vy = velInit();

        }

    }
}

Things I Have Tried
I tried wrapping parts of my code with
Platform.runLater(new Runnable() { });

and
SwingUtilities.invokeLater(new Runnable() { });

as described in Oracle's documentation but with no success. There are so many combination possible for that and every one of them seems to make my code behave differently (and wrongly).
I have tried so many combinations that at this point I believe that wrapping with these two functions may not even be the solution.
Does anyone know what I am doing wrong ?

A: While their might be other issues with the code, the root cause for ConcurrentModificationException is the attempt to iterate over a collection (in this case an ArrayList) while changing the same collection.
This is not allowed as stated here:
 it is not generally permissible for one thread to modify a Collection while
 another thread is iterating over it.

In the code posted initializeParticles modifies particleList by  adding elements to it: particleList.add(p); while paintComponent as well as physicsTimer and fpsTimer all iterate over the same collection using for(Particle particle : particleList)
While there are several ways to overcome this issue the simplest would be to simply change all iterations over  particleList to the form:
for(int i=0; i< particleList.size(); i++) {
   Particle p = particleList.get(i);
   .........
}

A: You are calling JavaFX functions from the swing and vice versa. Wrapping code with Platfrom.runlater and SwingUtilities.invokeLater is the correct way if you need javafx/swing communication, but you need to do it the right way ;).
Lets start with App.java
SwingNode and controller are not JavaFX components, but are called with SwingUtilities, can't be right.
Should look like this:
        SwingUtilities.invokeLater(() -> {
            mainPanel.setSize(535, 318);
            mainPanel.setBackground(Color.black);
            mainPanel.physicsTimer.start();
            mainPanel.fpsTimer.start();
            mainPanel.initializeParticles(15, 100 ,5);
        });

        scenePanel.setCenter(swingNode);
        swingNode.setContent(mainPanel);
        controller.initializeButtons(mainPanel);

Your main error comes from manipulating particleList in the javafx thread while your swing part is iterating the list in the paint functions.
Wrapping your initializeParticle function inside a SwingUtilities.invokeLater() function should fix that.
public void initializeParticles(int numberOfParticles, int mass, int charge) {
    SwingUtilities.invokeLater(() -> {
        for (int i = 0; i < numberOfParticles; i++) {
            int xPos;
            int yPos;
            do {
                xPos = rand.nextInt(100) + 25;
                yPos = rand.nextInt(100) + 25;
                Particle p = new Particle(xPos, yPos, 0, 0, mass, charge); //mass charge at end
                particleList.add(p);
            } while (!particleAlreadyExists(xPos, yPos));
        }
    });
}

However this is very ugly code and you shouldn't mix this two frameworks that way.


text:
Q: Is it possible to employ the circle as a primitive concept to measure the area of the rectangle? Historically, it seems that we have found more practical uses for the area of the rectangle than the area of the circle. The definition of the area of the rectangle was given and used as a primitive concept, with the area of the rectangle one can easily find the area of the triangle with a method such as the one given in this question, thus making the triangle the second geometrical object in the hierarchy (I guess that this is true in the context of euclidean geometry).
Having this area defined, it seems that we tried to find a definition for the area of the circle that was dependent on the definition for the area of the rectangle and triangle, then it was found the method of exhaustion, which employs regular polygons (which can be decomposed into triangles), then the given method is employed to find an approximation of the area of the circle with the sum of the area of these triangles.
So, given the hierarchy:
$$\begin{matrix}
{1}&{Rectangle}\\
{2}&{Triangle}\\
{3}&{Circle}
\end{matrix}$$
Has someone tried to find the area of the rectangle and triangle by using the area of the circle as a primitive? Is there a definition of the circle that is not dependent on the rectangle and triangle and that could be used to find the areas of them (triangle and rectangle)? Perhaps it's the dumbest thing to do on a lifetime, but I'm curious if such a thing exist and/or it has revealed something of value.

A: On one interpretation, this is the idea behind Hausdorff measure, which constructs a notion of "volume" given only a notion of "distance".  The circle is the unit ball of the usual Euclidean notion of distance, so in a sense this is taking the circle as fundamental.  In $\mathbb R^n$, Hausdorff measure is the same as the familiar notion of volume (up to a scaling factor); the real benefit of the construction is that you can apply it in other metric spaces, where you might not have any preconceived idea of volume.

A: If we would have first defined the primitive as a circle , what would have happened is that we would have divided the rectangle into small triangles to fit it inside the circle . Either way you do it $\pi$ will come into the picture .


text:
Q: Java how to change color on g.drawString I am trying to make the string currentTask in text red. However, it is white. I tried changing to red between like this, without any progress.
g.drawString("Task: " + g.setColor(Color.red) + currentTask, 13, 60);
g.setColor(Color.white);
g.drawString("Task: " + currentTask, 13, 60);

A: There are two drawString methods that accept an AttributedCharacterIterator. This is returned by AttributedString.getIterator(), so first such need to be created and configured.
Here a naïve solution:
var text = new AttributedString("Task: Test");
text.addAttribute(TextAttribute.FOREGROUND, Color.WHITE, 0, 6);
text.addAttribute(TextAttribute.FOREGROUND, Color.RED, 6, 10);

g.drawString(text.getIterator(), x, y);

obviously this must be expanded to concatenate currentTask instead of using the literal "Test" and have the respective indices calculated to be used in addAttribute

To do it without AttributedString, that is, setting the color of Graphics, you would have to do something like:
private static final LABEL = "Task: ";
...
g.setColor(Color.WHITE);
g.drawString(LABEL, x, y);
var delta = g.getFontMetrics().stringWidth(LABEL);
g.setColor(Color.RED);
g.drawString(currentTask, x+delta, y);


text:
Q: Issue with Dynamic Subheadings at Page Break in pdfmake I am using pdfmake to render data in Angular. I have five headings in each page:

*

*i have a tenant

*inside the tenant, i have activities

*inside the activities i have materials

I need to render like this
enter image description here
      4            3         4                 5

Here when the page breaks
enter image description here
It's taking the first activity value in the second PDF. I need to render the second activity where the page breaks.

generatePdf() {
  const documentDefinition = {
    pageSize: 'A4',
    pageOrientation: 'landscape',
    content: [
    this.generateReport04Structure()
    ]

    generateReport04Structure() {
  const retunData = [];
  this.reports.report04.forEach(element => {
    const data = [];
    data.push(
      {
        margin: [0, 20, 0, 0],
        style: 'tableExample',
        table: {
          headerRows: 5,
          // pageBreak: 'before',
          dontBreakRows: true,
          body: [
            [
              {text: 'TENANT', style: 'tableHeader', colSpan: 3, border: [false, false, false, false]}, {} , {},
              {text: 'BUILDING', style: 'tableHeader', colSpan: 3, border: [false, false, false, false]}, {}, {},
              {text: 'DATE', style: 'tableHeader', colSpan: 2, border: [false, false, false, false]}, {}
             ],
             [
              {text: element.tenantName, style: 'tableHeader', colSpan: 3, border: [true, true, true, true], bold: true, margin: [3, 6, 0, 10]}, {} , {},
              {text: element.tenantBuilding, style: 'tableHeader', colSpan: 3, border: [true, true, true, true], bold: true, margin: [3, 6, 0, 10]}, {}, {},
              {text: element.inspectionDate, style: 'tableHeader', colSpan: 2, border: [true, true, true, true], bold: true, margin: [3, 6, 0, 10]}, {}
             ],
             ...this.report04ActivityElements(element.activity),
          ],
          // widths: ['8%', '8%', '8%', '8%', '8%', '8%', '8%', '8%'],
          widths: ['12%', '12%', '12%', '12%', '12%', '12%', '12%', '12%'],
          layout: {
            hLineWidth(i, node) {
              return (i === 0 || i === node.table.body.length) ? 0.1 : 0.1;
            },
            vLineWidth(i, node) {
              return (i === 0 || i === node.table.widths.length) ? 0.1 : 0.1;
            },
            hLineColor(i, node) {
              return (i === 0 || i === node.table.body.length) ? 'black' : 'black';
            },
            vLineColor(i, node) {
              return (i === 0 || i === node.table.widths.length) ? 'black' : 'black';
            },
            paddingTop(i, node) { return 10; },
            paddingBottom(i, node) { return 10; }
          }
        },
      }
    );
    retunData.push(data);
  });
  return retunData;
}

report04ActivityElements(value) {
  let activity = [];
  value.forEach(element => {
    activity.push([
      {text: '', style: 'tableHeader', border: [false, false, false, false], margin: [3, 8, 0, 10]},
      {text: 'ACTIVITY #', style: 'tableHeader', border: [true, true, true, true], margin: [3, 8, 0, 10]} ,
      {text: 'ACTIVITY TYPE', style: 'tableHeader', colSpan: 2, border: [true, true, true, true], margin: [3, 8, 0, 10]}, {},
      {text: 'DESCRIPTION', style: 'tableHeader', colSpan: 3, border: [true, true, true, true], margin: [3, 8, 0, 10]}, {}, {},
      {text: 'PRACTICE', style: 'tableHeader', border: [true, true, true, true], margin: [3, 8, 0, 10]},
    ]);
    let returnData = [];
    returnData.push(
      {text: '', style: 'tableHeader',border: [false, false, false, false], margin: [3, 8, 0, 10]} ,
      {text: element.activityNumber, style: 'tableHeader',border: [true, true, true, true], margin: [3, 8, 0, 10]},
      {text: element.activityType, style: 'tableHeader', colSpan: 2, border: [true, true, true, true], margin: [3, 8, 0, 10]}, {},
      {text: element.description, style: 'tableHeader', colSpan: 3, border: [true, true, true, true], margin: [3, 8, 0, 10]}, {}, {},
      {text: element.practice, style: 'tableHeader', border: [true, true, true, true], margin: [3, 8, 0, 10] }
    );
    activity.push(returnData);
    if (element.material.length > 0) {
      activity.push(...this.report04Material(element.material));
    }
  });
  return activity;
}

report04Material(value) {
  let material = [];
  material.push([
    {text: '', border: [false, false, false, false]},
    {text: '', border: [false, false, false, false]},
    {text: 'MATERIAL #', style: 'tableHeader', border: [true, true, true, true], margin: [3, 8, 0, 10]},
    {text: 'MATERIAL NAME', style: 'tableHeader', border: [true, true, true, true], margin: [3, 8, 0, 10]},
    {text: 'QUANTITY', style: 'tableHeader', border: [true, true, true, true], margin: [3, 8, 0, 10]},
    {text: 'CAPACITY', style: 'tableHeader', border: [true, true, true, true], margin: [3, 8, 0, 10]},
    {text: 'SEC/SPILL CON', style: 'tableHeader', border: [true, true, true, true], margin: [3, 8, 0, 10]},
    {text: 'LEAK/STAIN', style: 'tableHeader', border: [true, true, true, true], margin: [3, 8, 0, 10]}
  ]);
  value.forEach(element => {
    let returnData = [];
    returnData.push(
      {text: '', border: [false, false, false, false]},
      {text: '', border: [false, false, false, false]},
      {text: element.materialNumber, style: 'tableHeader', border: [true, true, true, true], margin: [3, 8, 0, 10]},
      {text: element.materialName, style: 'tableHeader', border: [true, true, true, true], margin: [3, 8, 0, 10]},
      {text:  element.quantity, style: 'tableHeader',  border: [true, true, true, true], margin: [3, 8, 0, 10]},
      {text:  element.capacity, style: 'tableHeader', border: [true, true, true, true], margin: [3, 8, 0, 10]},
      {text:  element.secSpill, style: 'tableHeader', border: [true, true, true, true], margin: [3, 8, 0, 10]},
      {text:  element.leakStain, style: 'tableHeader', border: [true, true, true, true], margin: [3, 8, 0, 10]}
    );
    material.push(returnData);
  });
  return material;
}


text:
Q: why db execution doesn't stops even if I stops the web browser? Taking a scenario, If I insert something in db using any form of web application
and stops the browser in between , the process of db query execution still continues why is it so ?
can something be done to stop db execution whenever browser stops responding ?


text:
Q: Using public ntp servers for backup to local stratum 1 server In my data centers, I have access to a stratum 1 server but I set up our servers to use ntp pool servers in addition to it. My main thinking was for backup in case our local server goes down but I am concerned this is actually causing time to be off more than it should be.
Based on the ntpq output below, ntpd is using my local stratum 1 server and two public servers ("+") which have a very bad delay in its calculation. We have had reports are time we have been putting into messages is off and I am thinking having these public servers involved is making the time sync worse, we are trying to have time accurate to within a millisecond.
Edit:
The question I am looking for an answer on: is having these public ntp servers with high jitter making my accuracy of time worse compared to having my single local GPS data center ntp server (192.168.20.4) configured?
$ ntpq -pn
 remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
*192.168.20.4    .TSYN.           1 u   18   64  377    0.799    0.626   0.028
+67.219.95.113   128.138.141.172  2 u    3  256  377   45.266   -0.664   4.542
-50.116.55.65    209.51.161.238   2 u   46  256  377    2.979    0.876   0.217
+74.117.214.2    .GPS.            1 u  235  256  377   83.977   -4.988   0.106
-205.233.73.201  198.82.247.71    3 u  218  256  175    9.369    1.712   0.236

$ ntpq -c rl
associd=0 status=0615 leap_none, sync_ntp, 1 event, clock_sync,
version="ntpd 4.2.6p5@1.2349-o Sat Dec 20 19:00:16 UTC 2014 (1)",
processor="x86_64", system="Linux/2.6.32-431.11.2.el6.x86_64", leap=00,
stratum=2, precision=-24, rootdelay=0.934, rootdisp=5.188,
refid=192.168.20.4,
reftime=d8f8f71b.08d0821a  Sat, May  9 2015 17:14:03.034,
clock=d8f8f775.c8d11ec4  Sat, May  9 2015 17:15:33.784, peer=62815,
tc=10, mintc=3, offset=0.351, frequency=-16.428, sys_jitter=1.168,
clk_jitter=0.182, clk_wander=0.006

A: The NTP offsets you are seeing are milliseconds not seconds.  If you have problems with the dates put in your e-mail headers being off, then it may be your clients.  If you can get a copy of the headers, it should be easy to determine where the issue is.  The Date: header should have almost exactly the same time as your the last Received: header (first MTA server to handle e-mail).  NTP is far more accurate that is required for e-mail headers.  If there is an issue, check that your servers are synchronized with your NTP server.
It appears you gathered this data relatively soon after restarting your NTP client.  This is indicated by the poll vale of 256.  It should rise to 1024 once things have stabilized.
Your NTP server is tracking your local server as noted by the "*" to the left.  Given its stratum and jitter this is unlikely to change.  If it where to report a time significantly different from the other servers, it might get evicted.
Two other servers are being used to determine if the current clock can be trusted.  These are indicated by "+" to the left.  They will be chosen from the lowest statum servers.  The other two are not participating in voting as indicated by "-" to the left.  The voting servers may shift over time based on their stability as a source for your server.  The jitter of these servers should not cause you any issues, unless your local server gets evicted.

A: NTP cannot achieve such precision in its jitter.
You should proably have a look at PTP instead.
http://en.wikipedia.org/wiki/PTPd
If you want redundancy, you could just get two GPS clocks.
A high jitter may be symptomatic of a  congested (inter)network, or just a lack of some traffic shaping / reservation system. Make sure to pick a public NTP system that has a reasonably low, stable jitter, and tune your network to make this possible.


text:
Q: Shifting Android app development framework without relaunching the app I have an Android/iOS app built with Apache Cordova. I am having some issues in getting some enhancements done to it.
Is it possible to shift to a different architecture of the app like from Apache Cordova to Flutter, without relauncing the app in the AppStore?
It could be Cordova to Native Android App, or hybrid ones like Flutter, but  I want to know if I can change the app development framework architecture.
I have checked in here, but could not get the exact answer.
I dont think it is possible, but I wanted to check one final time before re-architecting. If the answer is yes, please do provide some pointers so that I can take a look.

A: So long as you sign it with the same key, yes.  The store doesn't know or care what framework an app is written in.  All it cares is that the signing key is the same, and that the version code increases.


text:
Q: problems with JavaScript/CSS when publishing ASP.NET forms to Azure cloud I have an ASP.NET Forms project (VS2013) which is running without any issues locally.
At the same time, when I publish it on Azure, all JavaScript/CSS/images files are missing.
Should I do something specific to work around this issue ?
some more details:
 this web site is based on the purchased bootstrap template which includes a bunch of JavaScript libs and css files. I moved all JavaScript libs under Scripts folder in my VS project and all css/images under Content folder. After these changes this project is running Ok locally but it looks unusable on Azure because js/css/images are missing on Azure.


text:
Q: PHP change code for youtube video in curly brackets I have a Joomla website that has this code to load a plugin and include a video from Youtube.
{youtube width="640" height="420"}kHRf01Gjosk{/youtube}

The thing is that this code was for Joomla 1.5, now I have upgraded my website to Joomla 2.5 and that plugin stopped working and the creator won't upgrate it to 2.5, so I figured if I install another plugin that uses a very similar code, I could make it work with regex.
The new plugin supports this kind of code:
{youtube}kHRf01Gjosk|640|420{/youtube}, or {youtube}kHRf01Gjosk{/youtube}

I'm a complete idiot in a complex regex, so if anyone could help I would really appreciate it!
Thanks :)

A: Nevermind after making some changes I figured it out... Thanks for all the help Newben!


text:
Q: Ionic Transparent Nav Bar in one view I am trying to get the nav bar to become transparent in a one view. However I'm having trouble doing that.
Here's my menu.html
<ion-side-menus enable-menu-with-back-views="true">
  <ion-side-menu-content>
    <ion-nav-bar class="bar-stable" ng-class="clear">
      <ion-nav-back-button>
      </ion-nav-back-button>

      <ion-nav-buttons side="left">
        <button class="button button-icon button-clear ion-navicon" menu-toggle="left">
        </button>
      </ion-nav-buttons>
    </ion-nav-bar>
    <ion-nav-view name="menuContent"></ion-nav-view>
  </ion-side-menu-content>

  <ion-side-menu side="left">
    <ion-header-bar class="bar-stable">

Menu

    </ion-header-bar>
    <ion-content>
      <ion-list>
      </ion-list>
    </ion-content>
  </ion-side-menu>
</ion-side-menus>

Here's my menu controller
  $rootScope.$on('noNavBar', function(){
    $scope.clear = 'bar-light';
    console.log($scope.clear);
  });

Here's the css
.bar.bar-light {
  background-color: rgba(255,255,255,.66) !important;  or transparent, or background:none
}

.scroll-content {
  overflow: visible !important;
}

Is it because the nav bar is cached?

A: If you need to hide nav-bar in a specific view use hide-nav-bar="true" inside <ion-view>.
If you need to customize nav-bar (i.e. apply a specific class) add an <ion-nav-bar> tag inside the <ion-view> you want with a custom nav bar:
<ion-nav-bar align-title="right" class="bar-positive">...</ion-nav-bar>

Here is an example: http://codepen.io/beaver71/pen/XXeydY


text:
Q: ASP.net multiple select always returns 0 selected items So i'm trying to build a User multi-select in order to get the participants to a project. This is my code:
  <form asp-page-handler="ProjectModalPartial">
                @*numele metodei*@
                <input name="IsValid" type="hidden" value="@ViewData.ModelState.IsValid.ToString()" />

                    Title
                    <input asp-for="ProjectsModel.ProjectName" class="form-control" placeholder="MyProject1" />

                    Description
                    <textarea asp-for="ProjectsModel.ProjectDescription" class="form-control" rows="3" placeholder="This is my first project"></textarea>

                    Project participants
                    <select multiple="multiple" class="form-control chosen_participants" id="listbox1" asp-for="ProjectsModel.MultiValues" asp-items="@Model.Items" style="width: 470px;">

                    </select>

            </form>

The page:
 public ApplicationDbContext _context;

    public ProjectsList(ApplicationDbContext context)
    {
        _context = context;
    }

    public List<Project> ProjectList { get; private set; } = new List<Project>();
    [BindProperty]
    public ProjectsModel ProjectsModel { get; set; }
    public List<User> UserList { get; private set; } = new List<User>();

    public IEnumerable<SelectListItem> Items { get; set; }
    = new List<SelectListItem>();
    public void OnGet()
    {

        ProjectList =  _context.Projects.ToList();
        Items = (from usr in this._context.Users
                 select new SelectListItem
                 {
                     Text = usr.Email.ToString(),
                     Value = usr.Id.ToString()
                 }).ToList();

    }

    public IActionResult OnPostProjectModalPartial()
    {
        Items = (from usr in this._context.Users
                 select new SelectListItem
                 {
                     Text = usr.Email.ToString(),
                     Value = usr.Id.ToString()
                 }).ToList();

        if (ModelState.IsValid)
        {
            var project = new Project
            {
                ProjectName = ProjectsModel.ProjectName,
                ProjectDescription = ProjectsModel.ProjectDescription,
                Created = DateTime.Now,
                Active = true,
                ProjectCreatorId = User.FindFirst(ClaimTypes.NameIdentifier).Value

            };
            _context.Projects.Add(project);
            _context.SaveChanges();
            foreach (var person in Items)
            {
                _context.ProjectParticipants.Add(new ProjectParticipant
                {
                    ProjectId = project.Id,
                    UserId = person.Value
                });

            }
            _context.SaveChanges();
        }
        return Page();
    }

And the model:
   public class ProjectsModel
{
    public int Id { get; set; }
    [Required]
    public string ProjectName { get; set; }
    [Required]
    public string ProjectDescription { get; set; }
    public DateTime Created { get; set; }
    public bool Active { get; set; }

    public string ProjectCreatorId { get; set; }

    [Required(ErrorMessage = "You must select atleast one participant")]
    public List<User> ProjectParticipants { get; set; }

    public IEnumerable<string> MultiValues { get; set; }

}

However, when i put a breakpoint inside the foreachloop of OnPostProjectModalPartial i can see the list is populated with all the users but none of them is selected. What am i doing wrong?
Do i need some jquery script to make this work?

A: If you want some of the list of users selected you need to change your code, this piece of code in the page part
ORIGINAL
foreach (var person in Items)
{
    _context.ProjectParticipants.Add(new ProjectParticipant
    {
         ProjectId = project.Id,
         UserId = person.Value
     });
} //ORIGINAL

Into this:
Filtering only the Model.Iems selected
foreach (var person in model.Items.Where(item=> item.Selected))
{
    _context.ProjectParticipants.Add(new ProjectParticipant
    {
         ProjectId = project.Id,
         UserId = person.Value
     });
}

Also you did'nt need to go get the list again from database, you got it in the model

A: You need indicate the property of your model associated to the selected option:
<select multiple="multiple"
   class="form-control chosen_participants"
   id="listbox1"
   asp-for="UserId" // <-- This property
   asp-items="@Model.Items"
   style="width: 470px;">

And add UserId property to your class:
public int UserId { get; set; }

Then, in the post, your model UserId has the selected user id and you can do a query to get all info that you need about that user.
NOTE: In your current OnPostProjectModalPartial, you are making a query in your database but without any kind of selection info getted from the post.


text:
Q: using the jquery tablesorter plugin-- possible to have a static column? what I mean by static column is one that is on the same table, but doesn't move when the other columns are called upon to sort

A: I haven't tried it, but I wonder if a tfoot element or a 2nd thead (after the sort headers) would be left alone... Those would handle the "at the top" and "at the bottom" cases, if it works.
(I've made this an answer, but a CW one because it's completely hypothetical. Doesn't mean it may not be right, but if it is, it seems wrong to get rep from a guess...)


text:
Q: Security : Role defined can be misused via url edit and changes. in ruby application In this applicatin there are four roles,
role can get into unauthorized pages by editing the url ids and perform actions on available options with respect to the page, misleading to malfunctioning of the application.
any one have idea about this. Is it the problem of closing the session Or routes permition
 problem ...
thanks in advance

A: Its nothing related to routes, you can restrict action access yourself with filters, i.e.
class MyController < ApplicationController
  before_filter :check_access

  def secure_action_a
  end

  def secure_action_b
  end

  private

  def check_access
    case params[:action]
      when 'secure_action_a':
        redirect_to root_path, error: "Not Allowed" unless current_user.role == 'admin'
      when 'secure_action_b':
        redirect_to root_path, error: "Not Allowed" unless current_user.role == 'user'
    end
  end
end

and also on an action, you should verify that the user has access to the resource, so let's say that you have an action that shows a transaction to the user, and that he can only see his transactions, if you write a code like:
def transaction
  @transaction = Transaction.find(params[:id])
end

then you have a big issue, because anyone can start writting requests like "http://mywebsite.com/transaction/23" and see the transaction because there are not any filters on the current user, so you usually make sure that the user owns the resource
def transaction
  @transaction = current_user.transactions.find(params[:id])
end

or either
def transaction
  @transaction = Transaction.where(user_id: current_user.id, id: params[:id])
end

later you can advanced gems like cancan to control the access to the resources
finally, make sure to read the rails security guide


text:
Q: Formatting Java Output Like a Table I am attempting to output information regarding students stored by my program in a tabular-like format as \t does not always provide the correct spacing. In order to do so, I came across this question and have attempted to enable a similar solution. However, I am obtaining errors with the format lines in my code when I attempt to execute it as such.
public void displayStudents (){
    System.out.println ("\n-----------------------------");
    System.out.println ("Email System - Display Students");
    System.out.println ("-----------------------------");
    System.out.format("%10s%15d%15s%15s%20s", "Grade", "Last Name", "First Name", "Student Number", "Parent Email");

    StudentNode current = top;
    while (current != null){
        Student read = current.getStudentNode();
        System.out.format ("%10s%15d%15s%15s%20s", ""+read.getClass(), read.getLastName(), read.getFirstName(), ""+read.getStudentNum(), read.getParentEmail());
        //This will output with a set number of character spaces per field, giving the list a table-like quality
    }
}//End of displayStudents

The goal of the code is to output in a manner similar to the following image.

Please aid me in finding my error. Is there perhaps an alternatively method to perform this?
Thanks.
EDIT: The error(s) I am getting are
GradeException in thread "main" java.util.IllegalFormatConversionException: d != java.lang.String
at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source)
at java.util.Formatter$FormatSpecifier.printInteger(Unknown Source)
at java.util.Formatter$FormatSpecifier.print(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.io.PrintStream.format(Unknown Source)
at StudentList.displayStudents(StudentList.java:184)
at OnlineCommunications.emailOption(OnlineCommunications.java:403)
at OnlineCommunications.main(OnlineCommunications.java:451)

It should be noted that Grade is an integer and Long is a double.

A: The error is because%d is for numeric non-floating point values (int, long, etc).
In the line where you print the titles, you have to use %XXs (where XX is a number) since you're passing Strings as parameters:
System.out.format("%10s%15s%15s%15s%20s",
    "Grade", "Last Name", "First Name", "Student Number", "Parent Email");

In the line inside the while-loop, you need to set %d for the int and long variables, like Grade and Student Number, there's no need to convert it to String using "" + intProperty:
System.out.format ("%10d%15s%15s%15d%20s",
    read.getClass(), read.getLastName(), read.getFirstName(),
    read.getStudentNum(), read.getParentEmail());

Since it looks like you want to format the output to the left (and not to the right), you should add a hypen (-) symbol before the XX number:
//similar for title
System.out.format ("%-10d%-15s%-15s%-15d%-20s",
    read.getClass(), read.getLastName(), read.getFirstName(),
    read.getStudentNum(), read.getParentEmail());

Note: I assumed read.getClass() and read.getStudentNum() would return the Grade and Student number values as int or long.

A: The problem is:

10s %15d %15s%15s%20s

should be:

10s %15s %15s%15s%20s

This is because all of the input parameters are String, so d (which applies to integral types only) is invalid.


text:
Q: Why Does MCF Channel Grouping ≠ Default Channel Grouping? I'm using the GA API.
This is a standard Goal completions metrics table (top) against an MCF goal report (bottom)
Check this out:

The total number adds up (12,238), but look how different the breakdown is by channel grouping! I assumed these would be close, but nope!
This the same View, no query filters applied, same date range, just one set of metrics by normal channel grouping above, and another set of metrics by mcf channel grouping below.

A: The standard reports use "last non-direct interaction" as attribution model (which means that direct is under-reported in favour of campaign traffic), while MFC actually uses "last click" (as it says in the table header), so the conversions are attributed differently to the channels.


text:
Q: Push notification in Android using Phonegap : Where do I need to put the sender id and the app id in my project? I want to implement push notification in Android using Phonegap. I have successfully created an app using https://github.com/marknutter/GCM-Cordova.
I have also created my app id and sender id using https://code.google.com/apis/console/.
Can anyone suggest where I should put these keys in my project?

A: I also use the plugin.
Not sure about the app id, but the send ID you pass in the function for registering:
GCM.register(STRING_YOUR_SENDER_ID, "GCM_Event", GCM_Success, GCM_Fail );

A: Check the GCM documentation here, here is a code snippet (I modified a bit from the original example in the documentation):
public class GCMIntentService extends GCMBaseIntentService {

private static final String SENDER_ID = ""; // Your project ID from the API Console

public GCMIntentService() {
    super(SENDER_ID);
}

@Override
public void onCreate() {
    super.onCreate();
    GCMRegistrar.checkDevice(this);
    GCMRegistrar.checkManifest(this);
    final String regId = GCMRegistrar.getRegistrationId(this);
    if (regId.equals("")) {
        GCMRegistrar.register(this, SENDER_ID);
    } else {
        Log.v(TAG, "Already registered");
    }
}

@Override
protected void onError(Context context, String error) {
}

@Override
protected void onMessage(Context context, Intent message) {
         //String value = message.getExtras().getString("message");
}

@Override
protected void onRegistered(Context context, String resId) {
        // You should save the resId to use it when sending a message from your server
}

@Override
protected void onUnregistered(Context arg0, String msg) {
        // Delete the resId from your server
}

}
To test it you need first to call the above service to register your device with GCM service (and get a registration id that you will use when sending the message), you can do something like:
Intent registrationIntent = new Intent(
            "com.google.android.c2dm.intent.REGISTER");
registrationIntent.putExtra("app",
            PendingIntent.getBroadcast(context, 0, new Intent(), 0));
// registrationIntent.putExtra("sender", "Your sender id"); // Better than keep the sender id hard coded in the service
context.startService(registrationIntent);

To send a message you can have a simple Java application as below (you can do it from other languages as well):
public static void sendMessage(String msg) throws IOException {
    String myApiKey = "Your Browser API Key";
    String regId = "Registeration id"; // the value you received in
                                        // onRegistered() in the above
                                        // onRegistered class
    Sender sender = new Sender(myApiKey);
    Message message = new Message.Builder().addData("message", msg).build();

    Result result = sender.send(message, regId, 5); // 5 is the maximum number of trials to deliver your message

    if (result.getMessageId() != null) {
        System.out.println("Message sent");
        String canonicalRegId = result.getCanonicalRegistrationId();

        if (canonicalRegId != null) {
            // This means that the registration id got updated, so use the new one for future messages
            System.out.println("canonicalRegId: " + canonicalRegId);
        }
    } else {
        System.out.println("error: " + result.getErrorCodeName());
    }
}

A: use the plugin
cordova plugin add phonegap-plugin-push --variable SENDER_ID="XXXXXXX"

replace the xxxxxx with your sender id
sender id is the project id/project number in google console
in your javascript add the following code for registering
    var push = PushNotification.init({
android: {
    senderID: "XXXXXXXX" //add your sender id here
},
ios: {
    alert: "true",
    badge: "true",
    sound: "true"
},
windows: {}
});

push.on('registration', function(data) {
    consol.log(data.registrationId);  //this function give registration id from the GCM server if you dont want to see it please comment it
    document.getElementById("gcm_id").value= data.registrationId; //showing registration id in our app. If it shows our registration process is suscess
    //$("#gcm_id").val(data.registrationId);  if you are using jquery
});

if you want to get  more detail in how to implement push notification in cordova please go through the following link
http://phonegaptut.com/2016/05/31/how-to-send-push-notifications-in-phonegap-application/


text:
Q: jQuery delaying a script I'm using this js to make two divs the same height which works fine with static content, but when images/content is being loaded in dynamically the height is being set as 0px because I imagine the script is firing before the content has been pulled. Is there a way to delay this from firing for a few seconds so the correct height gets set? Tried timeout function but couldnt get it to work
// make stuff the same height
equalheight = function (container) {

var currentTallest = 0,
 currentRowStart = 0,
 rowDivs = new Array(),
 $el,
 topPosition = 0;
$(container).each(function () {

    $el = $(this);
    $($el).height('auto')
    topPostion = $el.position().top;

    if (currentRowStart != topPostion) {
        for (currentDiv = 0; currentDiv < rowDivs.length; currentDiv++) {
            rowDivs[currentDiv].height(currentTallest);
        }
        rowDivs.length = 0; // empty the array
        currentRowStart = topPostion;
        currentTallest = $el.height();
        rowDivs.push($el);
    } else {
        rowDivs.push($el);
        currentTallest = (currentTallest < $el.height()) ? ($el.height()) :     (currentTallest);
    }
    for (currentDiv = 0; currentDiv < rowDivs.length; currentDiv++) {
        rowDivs[currentDiv].height(currentTallest);
    }
});
}

$(window).load(function () { equalheight('.equal'); });
$(window).resize(function () { equalheight('.equal'); });

A: Your answer does not provide enough information to provide a definite answer, I'm going to jump the gun and assume your tried setTimeout where you are calling the function, if this is the case then instead, try the setTimeout in the function itself like this.
// make stuff the same height

equalheight = function (container) {
    window.setTimeout(function () {  // Start setTimeout

        var currentTallest = 0,
            currentRowStart = 0,
            rowDivs = new Array(),
            $el,
            topPosition = 0;
        $(container).each(function () {

            $el = $(this);
            $($el).height('auto')
            topPostion = $el.position().top;

            if (currentRowStart != topPostion) {
                for (currentDiv = 0; currentDiv < rowDivs.length; currentDiv++) {
                    rowDivs[currentDiv].height(currentTallest);
                }
                rowDivs.length = 0; // empty the array
                currentRowStart = topPostion;
                currentTallest = $el.height();
                rowDivs.push($el);
            } else {
                rowDivs.push($el);
                currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest);
            }
            for (currentDiv = 0; currentDiv < rowDivs.length; currentDiv++) {
                rowDivs[currentDiv].height(currentTallest);
            }
        });
    }, 5000); // End setTimeout
};

A: Why when you select your element you make that :
$el = $(this);
$($el).height('auto');

You can't select a selector.
you just have to write:
$el = $(this);
$el.height('auto');

I don't know if I'm obvious by saying that but it seems weird.
Then for your problem you should try to do set the height in your ajax success.
And check your selector to be sure it is correct.


text:
Q: PHP and MYSQL time related query I am developing a web application in which remainders will be sent to subscribers at a particular time of the day. Let's say a person John fills a form and asks to send email remainder at 12 pm every day. I have developed a cron job for this purpose but I am having issues related to time. Here is my problem if John is from USA then the email have to be sent according to US time and so on. Now I use MYSQL to store the time zone and Time from each person. But How do I schedule the emails according to specific time zone. My server time is set to UTC. So if a person has time zone of GMT +5 how many hours I have to add in the UTC so that emails should be sent at correct time.
I don't need the code just give me a common formula to calculate the correct time of email.
Thanks a lot,
Ahmar.

A: Take a look at the convert-tz function.
mysql> SELECT CONVERT_TZ('2004-01-01 12:00:00','GMT','MET');
        -> '2004-01-01 13:00:00'
mysql> SELECT CONVERT_TZ('2004-01-01 12:00:00','+00:00','+10:00');
        -> '2004-01-01 22:00:00'

A: Don't calculate it, use the database. Mysql has the best timezone support of any of the mainstream RDBMS. Its even better than Oracle as far as having sensible ways of updating its database from Olson.
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_convert-tz
Should give you a clue.


text:
Q: Where is the cron / crontab log? I want to verify that my cron job is executing and at what time.  I believe there is a log for my sudo crontab -e jobs, but where?
I searched google and found recommendations to look in /var/log (in which I do not see anything with 'cron' in the name) and to edit the file /etc/syslog.conf which I also do not have.

A: You can also direct the output of the individual cronjobs to their own logs for better readability, you will just need to append the output of date somewhere.
 0 15 * * *    /home/andrew/daily-backup.sh >> /var/log/daily-backup.log 2>&1

A: this shows CRON runtime i used Centos 7
cat /var/log/cron

A: On Ubuntu 20.04, /var/mail/{user} had the cron messages i was looking for.
I couldn't find decent cron logs in /var/log/messages.

A: If you have systemd installed on your system, you could display cron job log by using the journalctl command.
For example, on my Ubuntu 17.10:
journalctl -u cron.service

A: Check all CRON related logs in syslog files included compressed log files as well like this way:
zless /var/log/syslog* | grep CRON

A: You can create a cron.log file to contain just the CRON entries that show up in syslog. Note that CRON jobs will still show up in syslog if you follow the following directions.
Open the file
/etc/rsyslog.d/50-default.conf

Find the line that starts with:
#cron.*

uncomment that line, save the file, and restart rsyslog:
sudo service rsyslog restart

You should now see a cron log file here:
/var/log/cron.log

Cron activity will now be logged to this file (in addition to syslog).
Note that in cron.log you will see entries for when cron ran scripts in /etc/cron.hourly, cron.daily, etc. - e.g. something like:
Apr 12 14:17:01 cd CRON[14368]: (root) CMD (   cd / && run-parts --report /etc/cron.hourly)

However, you will not see more information about what scripts were actually ran inside /etc/cron.daily or /etc/cron.hourly, unless those scripts direct output to the cron.log (or perhaps to some other log file).
If you want to verify if a crontab is running and not have to search for it in cron.log or syslog, create a crontab that redirects output to a log file of your choice - something like:
01 14 * * * /home/joe/myscript >> /home/log/myscript.log 2>&1

This will redirect all standard output and errors that may be produced by the script that is run to the log file specified.

A: journalctl -t CROND

on ubuntu >=18 it maybe
journalctl -t CRON

From the journalctl manual:
   -t, --identifier=SYSLOG_IDENTIFIER|PATTERN
       Show messages for the specified syslog identifier SYSLOG_IDENTIFIER,
       or for any of the messages with a "SYSLOG_IDENTIFIER" matched by PATTERN.

       This parameter can be specified multiple times.

A: This is a very old question, but none of these answers seem satisfactory.
First make your cron job run every minute, then run cron as non-daemon (temporarily, just kill any crond that may have already started) with test logging:
crond -nx test
And see the log of your program execution flowing through your terminal.

A: On a default installation the cron jobs get logged to
/var/log/syslog

You can see just cron jobs in that logfile by running
 grep CRON /var/log/syslog

If you haven't reconfigured anything,the entries will be in there.

A: You could redirect the output of cron to a temporary file.
Such as:
00 11 07 * * /bin/bash /home/ubuntu/command.sh > /tmp/output 2>&1

Error and normal output, both will be redirected to the same file

A: Sometimes it can be useful to continuously monitor it, in that case:
tail -f /var/log/syslog | grep CRON

A: It is in /var/log/syslog by default.
But it can be set up to create a separate cron.log, which is more useful.
This Q&A describes the process:
16.04: How do I make cron create cron.log and monitor it in real time?
Also in this answer is the instructions to create a wcron command that displays it is near-real-time.  Plus, it links to another answer,
How to change cron log level?
that shows how to change the log level to include more than just the start of jobs - level 15 will show errors and end time, also.

A: Like mentioned earlier, cron jobs get logged to /var/log/syslog
You can pipe the syslog to grep and filter out the CRON logs, like this
less /var/log/syslog | grep CRON

You can search through your crontab logs, like this
less /var/log/syslog | grep CRON | grep <search-keyword-comes-here>

You can search through your crontab history logs stored in gz files, like this
less /var/log/syslog.2.gz | grep CRON | grep <search-keyword-comes-here>

Its always considered good to have a logging mechanism, you can quickly setup ELK for your servers, you can also experiment with logz .

A: It may be different depending on the system type and edition. But in many cases, you have to figure out the time basis that the target crontab rule runs on. So for example, if you're searching for the related log for a daily crontab rule, then you'll find the log divided into different files, one per day, in:
$ ls -ltrh /var/log/cron-*

And you'll get the logfiles.

A: I found the current cron logs in /var/log/cron
and previous logs on /var/log/cron-date.


text:
Q: Can't get the if statements/while loop to work Can't get the if statements/while loop to work. If I make raceChosen an int it will never allow me to enter choose another race. When I use a char the if statements don't work. I have absolutely no idea who to fix this. Any assistance that could be provided would be appreciated.
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
#include <time.h>

struct player {   /*a struct to hold the player information.*/
int type[7];
int name[12];
int Smartness[7];
int Strength[7];
int MagicSkills[7];
int Luck[7];
int Dexterity[7];
int lifePoints[3];
}player;

int  main(void)
{
    struct player* ptr;
    srand(time(NULL));
    int numberPlayers,i,j,Smartness,Luck,Strength,Dexterity;
    int MagicSkills,name,slots,x,Hill,City,LevelGround,m,lifePoints;
    lifePoints = 100;
    char raceChosen[1];

    printf("Please enter the number of players you would like");
    scanf("%d",&numberPlayers);  /*take in the number of players*/

    struct player plyr[numberPlayers];
    i = 0;

    while( i<numberPlayers )
    {

    printf("Please enter the race you would like to play as \n"
    "Press elf for Elf \n"
    "Press 1 for Human \n"        /*taking in the race from the user*/
    "Press 2 for Ogre \n"
    "Press 3 for Wizard \n");
    scanf(" %c",&raceChosen);

    if(raceChosen == "0"){
        printf("Please enter your name \n:");
        scanf("%d", &ptr->name[i]);
        Smartness = rand()%31 + 70;
        printf("%d\n",Smartness);
        scanf("%d", &ptr->Smartness[i]);
        Luck = rand()%41 + 60;
        printf("%d \n",Luck);
        scanf("%d", &ptr->Luck[i]);
        Strength = rand()%50 + 1;
        printf("%d \n",Strength);          /* generating the character */
        scanf("%d", &ptr->Strength[i]);
        Dexterity = rand()%100 + 1;
        printf("%d\n",Dexterity);
        scanf("%d", &ptr->Dexterity[i]);
        MagicSkills = rand()%31 + 50;
        printf("%d \n",MagicSkills);
        scanf("%d", &ptr->MagicSkills[i]);
        printf("\n********\n");

    }

    if(raceChosen == "1"){
        printf("Please enter your name \n:");
        scanf("%d", &ptr->name[i]);
        Smartness = rand()%31 + 70;
        printf("%d\n",Smartness);
        scanf("%d", &ptr->Smartness[i]);
        Luck = rand()%41 + 60;
        printf("%d \n",Luck);
        scanf("%d", &ptr->Luck[i]);
        Strength = rand()%50 + 1;
        printf("%d \n",Strength);
        scanf("%d", &ptr->Strength[i]);
        Dexterity = rand()%100 + 1;
        printf("%d\n",Dexterity);
        scanf("%d", &ptr->Dexterity[i]);
        MagicSkills = rand()%31 + 50;
        printf("%d \n",MagicSkills);
        scanf("%d", &ptr->MagicSkills[i]);
        printf("\n********\n");

    }

    }
    i++;
    }

    }

A: First of all, I would recommend you try to compile your code before asking questions.
Anyways, let's go through your compile errors step by step:

*

*Line 43: Passing the wrong variable type to scanf
You only need one character from standard input, so no need for a string array (char *), just use a character variable (char)
So char raceChosen[1] becomes char raceChosen

*Lines 46 and 69: Comparing two strings with == operator
This is a good reason to start learning the basics of C programming. To compare two strings in C, you use strcmp(first_string, second_string).
Since raceChosen is not a character array anymore, we don't need strcmp, we can still use == but the quotes around 0 and 1 have to be single quotes.
So your if statements become if(raceChosen == '0') and if(raceChosen == '1'). This is how you compare two characters.

*Lines 23, 24 and 32, Lots of unused variables
I hope you're gonna use those later because this is bad practice.

*Line 48: Using an uninitialized variable
Just initialize ptr to NULL (ptr = NULL) right after you declare it.
Just a notice tho, you don't need to use a pointer to struct here, unless you were asked to. A simple struct would do the work.

*Line 98: Extraneous closing brace
Yup, just as it says, too many closing braces.

A: Change like this, i hope it work for you.
int  main(void)
{
    struct player* ptr;
    srand(time(NULL));
    int i,j,Smartness,Luck,Strength,Dexterity;
    int MagicSkills,name,slots,x,Hill,City,LevelGround,m,lifePoints;
    lifePoints = 100;
    char raceChosen[1];
    static int numberPlayers=0; //Changed

    printf("Please enter the number of players you would like");
    scanf("%d",&numberPlayers);  /*take in the number of players*/

    struct player plyr[numberPlayers];
    i = 0;

    while( i<numberPlayers )
    {

    printf("Please enter the race you would like to play as \n"
    "Press elf for Elf \n"
    "Press 1 for Human \n"        /*taking in the race from the user*/
    "Press 2 for Ogre \n"
    "Press 3 for Wizard \n");
    scanf("%c",&raceChosen);

    if(*raceChosen == '0'){ //Changed
        printf("Please enter your name \n:");
        scanf("%d", &ptr->name[i]);
        Smartness = rand()%31 + 70;
        printf("%d\n",Smartness);
        scanf("%d", &ptr->Smartness[i]);
        Luck = rand()%41 + 60;
        printf("%d \n",Luck);
        scanf("%d", &ptr->Luck[i]);
        Strength = rand()%50 + 1;
        printf("%d \n",Strength);          /* generating the character */
        scanf("%d", &ptr->Strength[i]);
        Dexterity = rand()%100 + 1;
        printf("%d\n",Dexterity);
        scanf("%d", &ptr->Dexterity[i]);
        MagicSkills = rand()%31 + 50;
        printf("%d \n",MagicSkills);
        scanf("%d", &ptr->MagicSkills[i]);
        printf("\n********\n");

    }

    if(*raceChosen == '1'){ //Changed
        printf("Please enter your name 1\n:");
        scanf("%d", &ptr->name[i]);
        Smartness = rand()%31 + 70;
        printf("%d\n",Smartness);
        scanf("%d", &ptr->Smartness[i]);
        Luck = rand()%41 + 60;
        printf("%d \n",Luck);
        scanf("%d", &ptr->Luck[i]);
        Strength = rand()%50 + 1;
        printf("%d \n",Strength);
        scanf("%d", &ptr->Strength[i]);
        Dexterity = rand()%100 + 1;
        printf("%d\n",Dexterity);
        scanf("%d", &ptr->Dexterity[i]);
        MagicSkills = rand()%31 + 50;
        printf("%d \n",MagicSkills);
        scanf("%d", &ptr->MagicSkills[i]);
        printf("\n********\n");

    }

    }
    i++;
    }

A: There are 2 major things to be considered within your code, lets correct them one by one:

*

*char raceChosen[1]; <=> Here you have declared a charecter array of size 1
Please note : Array is collection of data of same type, so when you want to store at least 2 or more data, you could had used array, but here you are using a single charecter variable so you should avoid using array.
correct way: char raceChosen;

*Secondly,
 scanf(" %c",&raceChosen);
 if (raceChosen == "0")

Here you are taking input racechosen as a charecter : "%c" is for charecter input, and while comapring you are comapring it with string : " "double quote is for string. ie; You are comapring
    if (raceChosen == "0")

       (char)       (string)

This condition is not going to be true, hence you are not entering these if blocks.
correct way:
   if (raceChosen == '0')

        char         char


text:
Q: How do I browse a column of strings and convert any integers to the word in Python? I am creating a function that will go through a column of strings. In some of these strings there are numbers, and some strings there are not. If a string contains a number, I would like to change that number to the text version (i.e 'I was on hold for 20 minutes' to 'I was on hold for twenty minutes')
This is what I have so far, but I think the isdigit() is looking at the entire string instead of the tokens within the string.
import inflect

def int_to_word(words):
    p = inflect.engine()
    new_words = []
    for word in words:
        if word.isdigit():
            new_word = p.number_to_words(word)
            new_words.append(new_word)
        else:
            new_words.append(word)
    return new_words

A: This entirely depends on the input you're passing to int_to_words which you have not included in your question.

Input: string
You need to split your string into a list, which is split by spaces. This way you ensure that you're iterating over the entire number, and not the individual chars of the string.
def int_to_word(words):
    p = inflect.engine()
    new_words = []
    for word in words.split():
        if word.isdigit():
            new_words.append(p.number_to_words(word))
        else:
            new_words.append(word)
    return ' '.join(new_words)

print(int_to_word('I was on hold for 20 minutes'))
#I was on hold for twenty minutes

Input: list
With a list of sentences, you will need to add an extra iteration.
def int_to_word(words):
    p = inflect.engine()
    result = []
    for element in words:
        new_words = []
        for word in element.split():
            if word.isdigit():
                new_words.append(p.number_to_words(word)
                         )
            else:
                new_words.append(word)
        result.append(' '.join(new_words))
    return result

print(int_to_word(['I was on hold for 20 minutes', '1 2 3']))
#['I was on hold for twenty minutes', 'one two three']


text:
Q: proc_open working directory I have a PHP script at the following location
C:\wamp\www\tcl\bin\
I am accessing the same through a browser (http://localhost/tcl/bin/xxx.php
In the PHP script . I am doing a proc_open
$app = 'C:/wamp/www/tcl/bin/tclsh84.exe';
$process = proc_open($app, $descriptorspec, $pipes);

if i give the full path it works , but if I just give tclsh84.exe it does not work .
Although the PHP manual states if you don't give  4th parameter of proc_open (CWD) it takes the directory of the currently executing process.
Can someone guide me as I can't hardcode the tcl executable path as this needs to work both in windows and linux .
Regards,
Mithun

A: You say it works if you use the full path to tclsh84.exe. So, a solution might be to find out that full path and use it in your call to proc_open.

If you know your tclsh84.exe is in the directory in which your PHP script is, you could use something based on dirname and __FILE__ ; a bit like this, I suppose :
$dir = dirname(__FILE__);
var_dump($dir);   // directory in which the current PHP script is in

$path = $dir . DIRECTORY_SEPARATOR . 'tclsh84.exe';
var_dump($path);

Considering the PHP script I am using is /home/squale/developpement/tests/temp/temp.php, I would get :
string '/home/squale/developpement/tests/temp' (length=37)
string '/home/squale/developpement/tests/temp/tclsh84.exe' (length=49)

And, if needed, you can use '..' to go up in the directories tree, and, then use directories names to go down.

Another solution might be to make sure that the program you are trying to execute is in your PATH environment variables -- but if it's a program that's used only by your application, it doesn't make much sense to modify your PATH, I guess...

A: I believe by the executing process it means you PHP path, not the script path. Otherwise you can use a define in config file, it won't hurt.


text:
Q: How to get/list all field names of a JSON data with ExtJS? I have this json data:
[
{"ID":"1","name":"google","IP":"69.5.33.22","active":"true"},
{"ID":"2","name":"bing","IP":"70.5.232.33","active":"false"}
]

I want to get the all property names (?), like:
name,ID,IP,active
Note: I don't mind what is there at "name" and "IP" like google, 70.5.232.33, etc. Just, I want to get the fields itself.

A: var jsonString = [
    {"ID":"1","name":"google","IP":"69.5.33.22","active":"true"},
    {"ID":"2","name":"bing","IP":"70.5.232.33","active":"false"}
];
var keyArray = Ext.Object.getKeys(Ext.JSON.decode(jsonString));
console.log(keyArray) // ["ID","name","IP","active"]

A: Iterate over the object after you've parsed it.
js> for(i in {"ID":"1","name":"google","IP":"69.5.33.22","active":"true"})
{
  print(i);
}
ID
name
IP
active
js>


text:
Q: How to loop through child elements of XML type data column in talend I want to migrate data from an old table which has one column which has data in XML form. I am trying to break the XML using talend but always getting the first element again and again.
This is the data i have in my OLD DB:
ID                                              DETAIL
1               <ORDER_DETAIL>
                 <PACK>
                  <ID>703</ID>
                  <NAME>iPhone 6-16 GB-Space Grey-KD 57 Pack</NAME>
                  <STANDALONE_PRICE>0</STANDALONE_PRICE>
                  <MONTHLY_PRICE>57</MONTHLY_PRICE>
                  <UPFRONT_PRICE>0</UPFRONT_PRICE>
                 <ITEMS>
                  <ITEM>
                   <ID>177</ID>
                   <NAME>Bundle_2500_30GB_UNLIMITED</NAME>
                   <ROLE>Primary</ROLE>
                   <TYPE>Service</TYPE>
                   <ITEM_MINUTES>2500|Local Mins.</ITEM_MINUTES>
                   <ITEM_MESSAGES>Unlimited|SMS and MMS</ITEM_MESSAGES>
                   <ITEM_INTERNET>30 GB|4G LTE Internet</ITEM_INTERNET>
                  </ITEM>
                  <ITEM>
                     <ID>226</ID>
                     <NAME>Gold</NAME>
                     <ROLE>Primary</ROLE>
                     <TYPE>SIM</TYPE>
                     <NUMBER_CLASS>G</NUMBER_CLASS>
                  </ITEM>
                  <ITEM>
                     <ID>560</ID>
                     <NAME>iPhone 6 - 16 GB - Space Grey</NAME>
                     <ROLE>Primary</ROLE>
                     <TYPE>Device</TYPE>
                     <COLOR>Space Gray|#808080</COLOR>
                     <SIZE>16 GB</SIZE>
                  </ITEM>
                  <ITEM>
                     <ID>561</ID>
                     <NAME>4G LTE Hotspot - 0 GB - Black</NAME>
          <ROLE>Secondary Optional</ROLE>
          <TYPE>Device</TYPE>
          <COLOR>Black|#000000</COLOR>
          <SIZE>16 GB</SIZE>
       </ITEM>
    </ITEMS>
</PACK>
</ORDER_DETAIL>

I am getting below output:
    -------------+--------------------------+--------.
|                    tLogRow_2                    |
|=------------+--------------------------+-------=|
|pivot_key    |pivot_value               |ORDER_ID|
|=------------+--------------------------+-------=|
|NAME         |Bundle_2500_30GB_UNLIMITED|3150711 |
|ID           |177                       |3150711 |
|ROLE         |Primary                   |3150711 |
|TYPE         |Service                   |3150711 |
|ITEM_MINUTES |2500|Local Mins.          |3150711 |
|ITEM_MESSAGES|Unlimited|SMS and MMS     |3150711 |
|ITEM_INTERNET|30 GB|4G LTE Internet     |3150711 |
|SIZE         |16 GB                     |3150711 |
|COLOR        |Space Gray|#808080        |3150711 |
|NUMBER_CLASS |G                         |3150711 |
|NAME         |Bundle_2500_30GB_UNLIMITED|3150711 |
|ID           |177                       |3150711 |
|ROLE         |Primary                   |3150711 |
|TYPE         |Service                   |3150711 |
|ITEM_MINUTES |2500|Local Mins.          |3150711 |
|ITEM_MESSAGES|Unlimited|SMS and MMS     |3150711 |
|ITEM_INTERNET|30 GB|4G LTE Internet     |3150711 |
|SIZE         |16 GB                     |3150711 |
|COLOR        |Space Gray|#808080        |3150711 |
|NUMBER_CLASS |G                         |3150711 |
|NAME         |Bundle_2500_30GB_UNLIMITED|3150711 |
|ID           |177                       |3150711 |
|ROLE         |Primary                   |3150711 |
|TYPE         |Service                   |3150711 |
|ITEM_MINUTES |2500|Local Mins.          |3150711 |
|ITEM_MESSAGES|Unlimited|SMS and MMS     |3150711 |
|ITEM_INTERNET|30 GB|4G LTE Internet     |3150711 |
|SIZE         |16 GB                     |3150711 |
|COLOR        |Space Gray|#808080        |3150711 |
|NUMBER_CLASS |G                         |3150711 |
|NAME         |Bundle_2500_30GB_UNLIMITED|3150711 |
|ID           |177                       |3150711 |
|ROLE         |Primary                   |3150711 |
|TYPE         |Service                   |3150711 |
|ITEM_MINUTES |2500|Local Mins.          |3150711 |
|ITEM_MESSAGES|Unlimited|SMS and MMS     |3150711 |
|ITEM_INTERNET|30 GB|4G LTE Internet     |3150711 |
|SIZE         |16 GB                     |3150711 |
|COLOR        |Space Gray|#808080        |3150711 |
|NUMBER_CLASS |G                         |3150711 |
'-------------+--------------------------+--------'

Getting first element of all child nodes again and again.
This is my job:
tOracleInput-->tMap>tExtraxtXMLField-->tUnPivotRow--tLogRow
Someone please help me on this

A: Do you set up "as optional loop" for your  tag in tXmlMap?
You can try to read "Items" separatly, using tExtractXmlFiled with "Loop XPATH query" : "/ORDER_DETAIL/ITEMS" and then "tFlowToIterate".


text:
Q: Define assembly for extension method I'm trying to use extension method, but the method is defined twice with same name.
Let's say A.Extensions.Ext() and B.Extensions.Ext() I need both references in my class and when trying
using A.Extensions;
using B.Extensions;
class C
{
    public void Main()
    {
        somevalue.Ext();
    }
}

I want to somehow define which method to use and I don't know how to do that.
Thanks for help!

A: There is a way to choose an extension method to be used
Assume you have two classes with extension methods for string
public static class Extension1
    {
        public static string GetLowerCaseResult(this string str)
        {
            return str.ToLowerInvariant();
        }
    }

    public static class Extension2
    {
        public static string GetLowerCaseResult(this string str)
        {
            return str.ToLowerInvariant();
        }
    }

to call it in Main method you have to explicitly specify class and method in this way
static void Main(string[] args)
        {
            var str = "QWERTY";
            Extension2.GetLowerCaseResult(str);
            Console.Read();
        }