小编eri*_*cso的帖子

如何使我的ArrayList线程安全?Java中另一种解决问题的方法?

我有一个ArrayList,我想用它来保存RaceCar对象,一旦完成执行就会扩展Thread类.一个名为Race的类使用RaceCar对象在完成执行时调用的回调方法处理此ArrayList.回调方法addFinisher(RaceCar finisher)将RaceCar对象添加到ArrayList.这应该给出Threads完成执行的顺序.

我知道ArrayList不是同步的,因此不是线程安全的.我尝试使用Collections.synchronizedCollection(c Collection)方法,传入一个新的ArrayList并将返回的Collection分配给ArrayList.但是,这给了我一个编译器错误:

Race.java:41: incompatible types
found   : java.util.Collection
required: java.util.ArrayList
finishingOrder = Collections.synchronizedCollection(new ArrayList(numberOfRaceCars));
Run Code Online (Sandbox Code Playgroud)

这是相关代码:

public class Race implements RaceListener {
    private Thread[] racers;
    private ArrayList finishingOrder;

    //Make an ArrayList to hold RaceCar objects to determine winners
    finishingOrder = Collections.synchronizedCollection(new ArrayList(numberOfRaceCars));

    //Fill array with RaceCar objects
    for(int i=0; i<numberOfRaceCars; i++) {
    racers[i] = new RaceCar(laps, inputs[i]);

        //Add this as a RaceListener to each RaceCar
        ((RaceCar) racers[i]).addRaceListener(this);
    }

    //Implement the one method in the RaceListener interface
    public void addFinisher(RaceCar …
Run Code Online (Sandbox Code Playgroud)

java collections multithreading synchronization arraylist

82
推荐指数
5
解决办法
16万
查看次数

Java解析XML文档给出了"prolog中不允许的内容".错误

我正在用Java编写一个程序,它接受一个自定义XML文件并解析它.我正在使用XML文件进行存储.我在Eclipse中收到以下错误.

[Fatal Error] :1:1: Content is not allowed in prolog.
org.xml.sax.SAXParseException: Content is not allowed in prolog.
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:239)
    at     com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:283  )
    at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:208)
    at me.ericso.psusoc.RequirementSatisfier.parseXML(RequirementSatisfier.java:61)
    at me.ericso.psusoc.RequirementSatisfier.getCourses(RequirementSatisfier.java:35)
    at     me.ericso.psusoc.programs.RequirementSatisfierProgram.main(RequirementSatisfierProgram.java:23  )
Run Code Online (Sandbox Code Playgroud)

包含XML文件的开头:

<?xml version="1.0" ?>
<PSU>
     <Major id="IST">
        <name>Information Science and Technology</name>
        <degree>B.S.</degree>
        <option> Information Systems: Design and Development Option</option>
        <requirements>
            <firstlevel type="General_Education" credits="45">
                <component type="Writing_Speaking">GWS</component>
                <component type="Quantification">GQ</component>
Run Code Online (Sandbox Code Playgroud)

该程序能够读取XML文件,但是当我调用DocumentBuilder.parse(XMLFile)解析时org.w3c.dom.Document,我得到上面的错误.

在我看来,我的XML文件的prolog中包含无效内容.我无法弄清楚出了什么问题.请帮忙.谢谢.

java xml eclipse xml-parsing

49
推荐指数
4
解决办法
29万
查看次数

如何暂停main()直到所有其他线程都死掉?

在我的程序中,我在main()方法中创建了几个线程.main方法的最后一行是对System.out.println()的调用,在所有线程都死之前我不想调用它.我已经尝试在每个线程上调用Thread.join()但是阻塞每个线程以便它们顺序执行而不是并行执行.

有没有办法阻止main()线程,直到所有其他线程完成执行?这是我的代码的相关部分:

public static void main(String[] args) {

//some other initialization code

//Make array of Thread objects
Thread[] racecars = new Thread[numberOfRaceCars];

//Fill array with RaceCar objects
for(int i=0; i<numberOfRaceCars; i++) {
    racecars[i] = new RaceCar(laps, args[i]);
}

//Call start() on each Thread
for(int i=0; i<numberOfRaceCars; i++) {
    racecars[i].start();
    try {
        racecars[i].join(); //This is where I tried to using join()
                            //It just blocks all other threads until the current                            
                            //thread finishes.
    } catch(InterruptedException e) {
        e.printStackTrace();
    }
}

//This is …
Run Code Online (Sandbox Code Playgroud)

java multithreading

23
推荐指数
2
解决办法
4万
查看次数

Java创建一个新的ObjectInputStream块

我正在尝试使用从Socket检索的InputStream创建一个新的ObjectInputStream.这是我的代码:

这是我的MessageGetterSender类的构造函数.该程序没有到达Checkpoint 4.

public MessageGetterSender(Socket socket) {

    System.out.println("MessageGetterSender: Checkpoint 1");

    this.socket = socket;

    // Get input and output streams
    try {
        System.out.println("MessageGetterSender: Checkpoint 2");

        InputStream is = socket.getInputStream();

        System.out.println("MessageGetterSender: Checkpoint 3");

        this.in = new ObjectInputStream(is);

        System.out.println("MessageGetterSender: Checkpoint 4");

    } catch (IOException ioe) {
        System.out.println("Could not get ObjectInputStream on socket: " + socket.getLocalPort());
    }

    try {
        this.out = new ObjectOutputStream(socket.getOutputStream());
    } catch (IOException ioe) {
        System.out.println("Could not get ObjectOutputStream on socket: " + socket.getLocalPort());
    }

    System.out.println("MessageGetterSender: Checkpoint 5");
}
Run Code Online (Sandbox Code Playgroud)

我正在从我连接到服务器以获取套接字的类中实例化一个新的MessageGetterSender对象.这是相关的代码.它是InstantMessageClass的构造函数,即实例化MessageGetterSender对象的类:

public …
Run Code Online (Sandbox Code Playgroud)

java sockets debugging inputstream

21
推荐指数
2
解决办法
1万
查看次数

如何从SQLAlchemy JOIN中的两个表返回结果?

我的ORM中定义了两个表:

Base = declarative_base()

class GeneralLedger(Base):
  __tablename__ = 'generalledgers'
  id = Column(Integer, primary_key=True)
  invoiceId = Column(Integer)
  ..

class ConsolidatedLedger(Base):
  __tablename__ = 'consolidatedledgers'
  id = Column(Integer, primary_key = True)
  invoiceId = Column(Integer)
Run Code Online (Sandbox Code Playgroud)

..

我没有在两个表之间设置任何关系.我按以下方式加入:

records = DBSession.query(GeneralLedger).join(ConsolidatedLedger, GeneralLedger.invoiceId == ConsolidatedLedger.invoiceId).all()
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

records = DBSession.query(GeneralLedger).filter(GeneralLedger.invoiceId == ConsolidatedLedger.invoiceId).all()
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,当我在视图中显示结果时,只显示GeneralLedger表中的条目.如何从同一结果集中的两个表中获取结果?我试过这个:

records = DBSession.query(GeneralLedger, ConsolidatedLedger).join(ConsolidatedLedger, GeneralLedger.invoiceId == ConsolidatedLedger.invoiceId).all()
Run Code Online (Sandbox Code Playgroud)

但是,出于某种原因,当我在模板(Jinja2)中迭代结果时,列的值对于每一行都是空的.此外,当计数:

total = DBSession.query(GeneralLedger).join(ConsolidatedLedger, GeneralLedger.invoiceId == ConsolidatedLedger.invoiceId).count()
Run Code Online (Sandbox Code Playgroud)

总行数是两个表中匹配记录的总和.我正在使用webhelpers.paginate来处理分页:

query = DBSession.query(GeneralLedger).join(ConsolidatedLedger, GeneralLedger.invoiceId == ConsolidatedLedger.invoiceId)
records = paginate.Page(query, current_page, url=page_url)
Run Code Online (Sandbox Code Playgroud)

并且发送到模板的结果集就好像除了ConslidatedLedger表上的结果之外的所有结果都被删除了.例如,我的页面总数设置为20条记录.如果该页面上存在来自ConslidatedLedger的记录,则页面将被截断,仅显示来自GeneralLedger的记录,但分页不会中断.

有什么想法吗?谢谢!

python sqlalchemy pyramid

10
推荐指数
1
解决办法
5352
查看次数

比较ArrayList问题中的新整数对象

我存储的Integer对象表示我想要跟踪的对象的索引.稍后在我的代码中,我想检查特定对象的索引是否对应于我之前存储的那些整数之一.我这样做是通过创建一个ArrayList并从for循环的索引创建一个新的Integer:

ArrayList<Integer> courseselectItems = new ArrayList();

//Find the course elements that are within a courseselect element and add their indicies to the ArrayList
for(int i=0; i<numberElementsInNodeList; i++) {
    if (nodeList.item(i).getParentNode().getNodeName().equals("courseselect")) {
        courseselectItems.add(new Integer(i));
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,我想稍后检查ArrayList是否包含特定索引:

//Cycle through the namedNodeMap array to find each of the course codes
for(int i=0; i<numberElementsInNodeList; i++) {
    if(!courseselectItems.contains(new Integer(i))) {
        //Do Stuff
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,当我使用new Integer(i)will 创建一个新的Integer时,我可以使用比较整数ArrayList.contains()吗?也就是说,当我使用创建新对象时new Integer(i),如果用于创建它们的int值相同,那么它是否与先前创建的Integer对象相同?

我希望我没有把它弄得太清楚.谢谢您的帮助!

java integer arraylist

7
推荐指数
1
解决办法
2万
查看次数

Google Visualization API不支持GID或工作表参数

我正在使用Google Visualization Javascript API从Google表格中加载图表并将其显示在div中.我的应用程序托管在Google App Engine上.我提供了工作表的URL,其中的参数gid=1用于指定第二个工作表,但显示的图表是第一个工作表.这是我的简化代码(它基本上是文档中提供的示例代码):

// sheetUrl is the URL of the Google sheet, e.g., http://https://docs.google.com/a/google.com/spreadsheet/ccc?key=0AobNU9T3MusKdGFqRHNJYkFnb3RuSkt4QlE#gid=1
// divId is the id of the <div> element I'm displaying in

google.load('visualization', '1.0', {packages: ['table']});
google.setOnLoadCallback(drawChart);

function drawChart() {
    var query = new google.visualization.Query(sheetUrl);
    query.send(handleQueryResponse);
}

function handleQueryResponse(response) {

    var data = response.getDataTable();
    var table = new google.visualization.Table(document.getElementById(divId));
    table.draw(data);
}
Run Code Online (Sandbox Code Playgroud)

您可以#gid=1在URL中看到.我也试过&gid=1&sheet='Volume',这是选项卡的名称,但在页面加载时,从第一标签中的数据被渲染.

我已经注意到我上面的表格中的Google表格网址,但也是以这种形式:

https://docs.google.com/spreadsheet/tq?key=0AobNU9T3MusKdGFqRHNJYkFnb3RuSkt4QlE
Run Code Online (Sandbox Code Playgroud)

我无法找到任何明确解释tq端点的文档.我尝试使用此表单中的URL,但在尝试加载图表时出现超时错误.任何人都遇到这个问题或者对tq事情有所了解?谢谢!

编辑2014-02-17:

我已经更改了我的URL以使用tq端点,我尝试了以下参数:

#gid=1
&gid=1
#sheet=Volume
&sheet=Volume
Run Code Online (Sandbox Code Playgroud)

当我在浏览器中查询url时:

https://docs.google.com/spreadsheet/tq?key=0AobNU9T3MusKdGFqRHNJYkFnb3RuSkt4QlE&sheet=Volume
Run Code Online (Sandbox Code Playgroud)

我得到了合适的纸张.但是当我使用Visualization API进行查询时,我得到了第一张表.

javascript google-app-engine google-visualization google-spreadsheet-api

7
推荐指数
2
解决办法
1712
查看次数

读取.xml文件进行解析时出现FileNotFoundException

我正在用Java编写一个程序,我从XML文件中读取数据并解析它.该文件将导入到项目的src目录中名为"Resources"的文件夹中.我正在使用Eclipse.当我运行该程序时,我收到以下错误:

java.io.FileNotFoundException: /Users/thechiman/Dropbox/introcs/PSU SOC Crawler/resources/majors_xml_db.xml (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at java.io.FileInputStream.<init>(FileInputStream.java:66)
...
Run Code Online (Sandbox Code Playgroud)

相关代码在这里:

private void parseXML() {
    //Get a factory
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    try {
        //Use factory to get a new DocumentBuilder
        DocumentBuilder db = dbf.newDocumentBuilder();

        //Parse the XML file, get DOM representation
        dom = db.parse("resources/majors_xml_db.xml");
    } catch(ParserConfigurationException pce) {
        pce.printStackTrace();
    } catch(SAXException se) {
        se.printStackTrace();
    } catch(IOException ioe) {
        ioe.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么我在文件存在时收到FileNotFoundException.谢谢您的帮助.

java filenotfoundexception xml-parsing

5
推荐指数
1
解决办法
7885
查看次数

为什么将io.BytesIO流作为参数传递时关闭?

我有一个Django应用,用户在其中发布文件。视图将获取文件,将其传递给线程函数并进行处理。问题是,有时io.BytesIO流在无法读取之前就被关闭了,我无法弄清为什么关闭了它。

我正在使用Xlrd库处理Excel文件。对于某些上载的Excel文件,流保持打开状态,而另一些保持关闭。我不知道到底是怎么回事找出原因。我要的是调试建议。我无法提供完整的代码,但下面概述了代码路径。

我的Django视图从POST请求中获取文件:

ufile = request.FILES['upload-file'].file
Run Code Online (Sandbox Code Playgroud)

ufile是的实例io.BytesIO。我有一个将流复制到命名临时文件的功能

@contextmanager
def temp_input_file(file_):
  temp = tempfile.NamedTemporaryFile(delete=False)
  shutil.copyfileobj(file_, temp)
  temp.close()
  yield temp.name
  os.unlink(temp.name)
Run Code Online (Sandbox Code Playgroud)

此contextmanager装饰的功能稍后使用。下一步是创建一个线程来处理上传的文件:

  job.run_job(
    method=process_excel_file,
    uploaded_file=ufile
  )
Run Code Online (Sandbox Code Playgroud)

我正在做的是传递一个函数process_excel_file和上载的“文件”,但实际上是io.BytesIO流到job.run_job,它创建了一个线程

def run_job(self, method, **kwargs):
  thread = threading.Thread()
  thread.run = lambda : method(
    job_id=self.job_db_record.id,
    **kwargs
  )
  thread.start()
Run Code Online (Sandbox Code Playgroud)

因此process_excel_file被传递到method变量中,而ufile在中kwargs。在线程中运行的函数process_excel_file如下所示:

def process_excel_file(ufile):
  with temp_input_file(ufile) as temp_file:
    in_book = xlrd.open_workbook(temp_file)
    ... # do stuff with in_book
Run Code Online (Sandbox Code Playgroud)

因此,发生什么事情是当我使用temp_input_file上下文管理器功能时,ValueError由于流关闭而引发了异常。相反,如果我重构代码以在视图中创建临时文件并传递临时文件名而不是类似文件的对象,则它起作用,因为流在​​传递到后在某处关闭job.run_job。有什么想法为什么会关闭流?更麻烦的是,某些文件不会关闭流。

python django stream

5
推荐指数
0
解决办法
826
查看次数

getattr()调用的Python模拟返回

编辑:我可能会落在这里的XY问题陷阱。这是我真正想知道的

我有以下功能:

def foo():
  bar = funcToGetBar()
  return bar.getattr("some_attr", None)
Run Code Online (Sandbox Code Playgroud)

在测试中,我尝试执行以下操作:

mocked_bar = MagicMock()
expected_return_val = [obj1, obj2, ...]
funcToGetBar.return_value = mocked_bar  # funcToGetBar is patched

def testGetBar(self):
  assertEqual(expected_return_val, foo())
Run Code Online (Sandbox Code Playgroud)

现在,我要做的是在对象expected_return_valsome_attr属性上提供bar

我尝试使用PropertyMock:

type(mocked_bar).getattr = PropertyMock(return_value=expected_return_value)
Run Code Online (Sandbox Code Playgroud)

运行测试我得到了错误:

TypeError: 'list' object is not callable
Run Code Online (Sandbox Code Playgroud)

如果将return_value设置为标量(而不是列表),则getattr在实函数中的调用结果是模拟的,而不是我提供的标量。

另外,我担心会模仿该getattr方法,因为它是一种通用方法,可能会在我的函数中的其他地方使用。如何在被测试的模拟对象的属性上设置列表?

python unit-testing mocking

5
推荐指数
1
解决办法
2050
查看次数

使用 Java 将对象添加到 Vector 会丢失引用吗?

我有一个包含许多对象的向量。我的代码使用循环根据特定条件将对象添加到 Vector。我的问题是,当我将对象添加到 Vector 时,原始对象引用是否添加到向量中,或者 Vector 是否创建该对象的新实例并添加它?

例如,在以下代码中:

private Vector numbersToCalculate;
StringBuffer temp = new StringBuffer();

while(currentBuffer.length() > i) {
    //Some other code
    numbersToCalculate.add(temp);
    temp.setLength(0); //resets the temp StringBuffer
}
Run Code Online (Sandbox Code Playgroud)

我正在做的是将“temp”StringBuffer 添加到numbersToCalculate Vector 中。我应该在循环中创建一个新的 StringBuffer 并添加它,还是这段代码可以工作?谢谢您的帮助!

埃里克

java vector stringbuffer

2
推荐指数
1
解决办法
5256
查看次数

奇怪的行为从Python中的循环中的列表中删除元素

我知道如果您当前正在迭代该列表,则无法从列表中删除元素.我正在尝试做的是将该列表中我不想删除的元素复制到另一个列表,然后用新列表替换原始列表.这是我的相关代码:

while len(tokenList) > 0:
    # loop through the tokenList list

    # reset the updated token list and the remove flag
    updatedTokenList = []
    removeFlag = False

    for token in tokenList:

        completionHash = aciServer.checkTaskForCompletion(token)

        # If the completion hash is not the empty hash, parse the information
        if completionHash != {}:
            # if we find that a task has completed, remove it from the list
            if completionHash['Status'] == 'FINISHED' and completionHash['Error'] == '':
                # The task completed successfully, remove the …
Run Code Online (Sandbox Code Playgroud)

python list

2
推荐指数
1
解决办法
234
查看次数

从匿名javascript函数中获取变量

我正在使用匿名函数对html执行一些工作我使用Restler的get函数返回:

var some_function() {
    var outer_var;
    rest.get(url).on('complete', function(result, response) {
        if (result instanceof Error) {
            sys.puts('Error: ' + result.message);
        } else {
            var inner_var;
            // do stuff on **result** to build **inner_var**
            outer_var = inner_var;
        }
    });
    return outer_var;
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能得到的值inner_var输出到some_function范围和退货吗?我在这里写的不起作用.

javascript node.js

2
推荐指数
1
解决办法
1330
查看次数