text:
Q: How to correctly call servlet with window.open? I have servlet with url pattern /servlet. I'm calling it by
function func(id){window.open ("../servlet?fileId="+id, "hiddenFrame");}

via href in jsp which doesn't work. However accessing it via URL /servlet?fileId=2 works. I think it's a servlet mapping issue. Kindly help.
Update: I have added the code below
index.jsp has only the statement:
<%request.getRequestDispatcher("newjsp.jsp").forward(request,response);%>

newjsp.jsp has the code:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>

Hello World!

   <%
       out.println("Link");
   %>

servlet.java has code:
package newpackage;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "servlet", urlPatterns = {"/servlet"})
public class servlet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("");
        out.println("");
        out.println("<title>Servlet servlet</title>");
        out.println("");
        out.println("");
        out.println("
Servlet servlet at " + request.getContextPath() + "
");
        out.println("");
        out.println("");
    }
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>
}

A: Quite a funny issue. You have used "/servlet" as the URL in your window.open() method. This bypasses the application root folder and forms the URL as http://localhost/servet whereas actual URL should be something like http://localhost//servlet .
Any ways the solution in your case would be to just remove that "/" from the URL. Hence use :
window.open ("servlet?fileId="+id, "hiddenFrame")


text:
Q: Encontrar un objeto por el nombre en mysql y node js ¿Cómo puedo buscar en vez de por el ID, por un parámetro como NAME y que me devuelva sus valores para mostrarlos al usar un buscador?
router.get('/:id', (req, res) => {
    console.log(req.body)
    const { id } = req.params;
    connection.query(`SELECT * FROM product WHERE category = ?`, [id], (err, rows, fields) => {
        if (!err) {
            res.json(rows)
        } else {
            console.log(err);
        }

    })
})

redpajama_set_name: RedPajamaStackExchange


text:
Q: Intellij plugin/action - how to add caret listener to editor automatically on load? How to add a caret listener to the active editor during "on load", such as when the intellij application starts or when an editor is opened?
I know how to do so in actionPerformed but apparently it is not the right place to do so, and the constructor has no AnActionEvent being passed in so I couldn't get an Editor instance.

A: I'm not sure what you mean by 'active' editor here. Editor which is active when a particular action is invoked can be retrieved from DataContext passed to actionPerformed.
If you want to add a listener to any editor, when it's created, you can do it in EditorFactoryListener.editorCreated. It can be also simpler to register a listener which will get events from all editors (see EditorFactory.getEventMulticaster()).


text:
Q: How to I get the detail (custom error message) returned with a bad request status code? So that I can do an ASSERT on it Hi so I am setting up some Integration tests (using Xunit) and I would like to run an Assert to check whether the correct custom error message is returned.
This is the data I need to get is in the following response see image...
detail: "Username must be unique" Don't worry this message will be modified to be more useful later on I am just wanting to get it working first
Required Info
This is the current code...
        //Act

        response = await _httpClient.PostAsync("CompleteUserSetup", formContent);

        //Assert

        Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode) ; //Bad request should be returned
        //TODO: check custom error message is correct

So hoping for...
ASSERT.Equal("Username must be unique", some code to get detail from response)

A: Okay so I figured out how to get the data I needed. I just needed to convert the result into an object and then I was able to pull the detail data that I needed.
var resultModel = await System.Text.Json.JsonSerializer.DeserializeAsync<Result>(response.Content.ReadAsStream(), JsonSerializerHelper.DefaultDeserialisationOptions);

var errorMessage = resultModel.detail;


text:
Q: watir-webdriver change proxy while keeping browser open I am using the Watir-Webdriver library in Ruby to check some pages. I know I can connect through a proxy using
profile = Selenium::WebDriver::Firefox::Profile.new#create a new profile
profile.proxy = Selenium::WebDriver::Proxy.new(#create proxy data for in the profile
  :http => proxyadress,
  :ftp => nil,
  :ssl => nil,
  :no_proxy => nil
)
browser = Watir::Browser.new :firefox, :profile => profile#create a browser window with this profile
browser.goto "http://www.example.com"
browser.close

However, when wanting to connect to the same page multiple times using different proxies, I have to create a new browser for every proxy. Loading(and unloading) the browser takes quite some time.
So, my question: Is there any way to change, using webdriver in ruby,  the proxy adress Firefox uses to connect through while keeping the browser open?

A: If you want to test whether a page is blocked when accessed through a proxy server, you can do that through a headless library. I recently had success using mechanize. You can probably use net/http as well.
I am still not sure why you need to change the proxy server for a current session.
require 'Mechanize'
session = Mechanize.new
session.set_proxy(host, port, user, pass)
session.user_agent='Mac Safari'
session.agent.robots = true #observe of robots.txt rules
response = session.get(url)
puts response.code

You need to supply the proxy host/port/user/pass (user/pass are optional), and the url. If you get an exception, then the response.code is probably not friendly.

A: You may need to use an OS level automation tool to automate going through the FF menus to change the setting as a user would.
For windows users there is the option of either the new RAutomation tool, or AutoIT.  both can be used to automate things at the OS UI level, which would let you go into the browser settings and change the proxy there.
Still I'd think if you are checking a larger number of sites that the overhead to change the proxy settings would not be that much compared to all of the site navigation and waiting for pages to load etc.
Unless you are currently taking a 'row traverse' approach and changing proxy settings multiple times for each site you are checking?  If that's the case I would go towards more of a by-column method (if we were to presume each column is a proxy, and each row is a site) and fire up the browser for one proxy, check all the sites, then change the proxy and re-check all the sites.   That way you'd only be changing the proxy settings once for each proxy which should not add that much overhead to your script.
It might mean a little more work with storing and then reporting results at the end (if you had been writing them out a line at a time) but that's what hashes or arrays are for.


text:
Q: Is there any way to know that which categorical value has been given what label? I am working with this data containing a categorical column which has "Good","Medium","Bad", now I wish to know which number has been assigned to which category, i.e. is medium assigned 1 or 2?

A: If you use sklearn le.classes_ give the names of the classes enumerating them :
from sklearn import preprocessing

mylist = ['r', 'z', 'd', 'd', 'r', 'a']

le = preprocessing.LabelEncoder()
le.fit_transform(mylist)

>>> array([2, 3, 1, 1, 2, 0])

le.classes_

>>> array(['a', 'd', 'r', 'z'], dtype='<U1')

You can check using inverse_transform :
list(le.inverse_transform([i for i in range(len(le.classes_))]))

>>> ['a', 'd', 'r', 'z']


text:
Q: Pure first order logic formulations of Markov's principle Markov's principle is a statement of constructive arithmetic that allows classical reasoning on formulas of the shape $\exists x P$ when $P$ is a recursive predicate:
$\neg \neg \exists x P \to \exists x P$
Its formulation is well known in the context of arithmetic, and it is well known that adding it to Heyting Arithmetic gives rise to a constructive system: when $A \lor B$ is provable, either $A$ is provable or $B$ is provable; when $\exists x \, A(x)$ is provable, there is a $t$ such that $A(t)$ is provable.
However I think it is not clear how one could formulate it in the context of pure intuitionistic first order logic (if it does make sense at all).
Various sources ([1], [2]) state it as "$\neg \neg \exists x P \to \exists x P$ for $P$ $\forall, \to$-free". Another tempting formulation would be $\forall x (P \lor \neg P) \to \neg \neg \exists x P \to \exists x P$ for any propositional $P$. As far as I can see, these two formulations are not comparable. Both these axioms, though, share the property that if we add them to pure intuitionistic first order logic we still obtain a constructive system (this is proved in [1] for the first axiom; I couldn't find references for the second axiom, but a proof can be obtained with a very similar argument).
Is there a more general analog of Markov's rule for first-order logic which preserves the disjunction property and other proof-theoretic properties of constructive systems? Or alternatively, is there some other source justifying the choice of the formalization used in [1,2] for Markov's principle?
[1] H. Herbelin, An intuitionistic logic that proves Markov's principle https://hal.inria.fr/inria-00481815/
[2] U. Berger, A Computational Interpretation of Open Induction http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=1319627

A: This is not an answer to the question, but rather a comment which benefits from proper formatting.
For me personally, Markov's principle is specifically associated with the natural numbers and not with some other set. By that I mean that I don't think of
$$ \neg\neg \exists x \in X{:}\ P(x) \quad\Longrightarrow\quad \exists x \in X{:}\ P(x) $$
(with $P$ restricted in some form, as you detailed) as a reasonable constructive principle, if $X$ is some arbitrary set.
Recall that there is a concrete reason why some schools of constructive mathematics accept Markov's principle: consider the algorithmic interpretation. The property $P$ is such that we can test in some finite way, for any natural number $n$, whether $P(n)$ holds or not. The assumption that $\neg\neg\exists n \in \mathbb{N}{:}\ P(n)$ means that there is some number $n$ such that $P(n)$ holds, but we do not know such a number (we are not given a witness of the existential statement). But we can find such a number on our own, thereby providing a witness of the statement $\exists n \in \mathbb{N}{:}\ P(n)$, by checking $P(0)$, $P(1)$, $P(2)$, and so on. This algorithm terminates (but we couldn't provide an upper bound for its runtime).
For an arbitrary set $X$ in place of $\mathbb{N}$, no analogous approach is possible. Therefore I can't quite fathom what you're driving at. (Markov's principle certainly works for some relatives of $\mathbb{N}$, for instance $\mathbb{N}^2$, which we can too search in a sequential manner.)


text:
Q: How do change the strings on the list to be printed differently? I want made Auto Posting Program.using Python
and
I wanted to upload multiple JPG files using window dialog.
(that site don't working input type="file", only Dragging file and Open to window dialog)
So,
I made List like that
[['1.jpg'], ['2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg'], ['7.jpg'], ['8.jpg', '9.jpg']]

new_upload = []
idx = 0
for fileCount in amount:
    upload = []
    for n in range(fileCount):
        upload.append(fileList[idx])
        idx += 1
    new_upload.append(upload)

print(upload2)

new_upload = [['1.jpg', '2.jpg'], ['3.jpg', '4.jpg', '5.jpg', '6.jpg', '7.jpg', '8.jpg'], ['9.jpg', '10.jpg'], ['11.jpg', '12.jpg', '13.jpg']]

after that
folderPath = r"F:\test\{0}"
uploadfilePath = (folderPath.format(new_upload[i]))

   # USE pywinauto

app["open"]["Edit1"].set_text(uploadfilePath)

   # USE pyautoit

autoit.control_set_text(handle, "Edit1", uploadfilePath)

But, The result was terrible.
enter image description here
Plz Loot at the a picture.
I wanted it to be entered like this.
new_upload[1]  -->  "1.jpg""2.jpg"
But that entered
new_upload[1] --> ['1.jpg','2.jpg']
What should I do to change the way I want it to be inputted?
I haven't slept in a few days.

A: I think there are problems with your python code.
Please look at the example code below
Here in your list, we have an inner list. I think you are NOT iterating the inner list. So the whole inner list content is written to your UI.
Refer to the below code, We are using two For loops to iterate the outer loop and inner loop. So in your code, the print can be replaced with the Pywinauto code to set text into UI
new_upload = [['1.jpg', '2.jpg'], ['3.jpg', '4.jpg', '5.jpg', '6.jpg', '7.jpg', '8.jpg'], ['9.jpg', '10.jpg'], ['11.jpg', '12.jpg', '13.jpg']]
folderPath = r"F:\test\{0}"
for upload in new_upload:
    for load in upload:
        uploadfilePath = (folderPath.format(load))

print(uploadfilePath)

A: Python string has powerful method .join() that you can use for joining the list into string. Example:
l = ['2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg']
s = '"' + '" "'.join(l) + '"'
print(s)
# "2.jpg" "3.jpg" "4.jpg" "5.jpg" "6.jpg"

For your case this piece of code:
upload = []
for n in range(fileCount):
    upload.append(fileList[idx])
    idx += 1

can be re-written this way:
upload_list = [fileList[i] for i in range(idx, idx + fileCount)]
idx += fileCount
upload = '"' + '" "'.join(upload_list) + '"'


text:
Q: Can we combine css and javascript into one javascript file? Can we combine css and javascript into one ? I want to do this for sIFR. because sifr has .js and .css file and without js enabled no use of any file css or js.
i want to combine all sIFR related file into one combined javascript file.
so at end i will have only 2 file

*

*font.swf

*sifr3.js (which has all thing)
Here is latest sIFR 3 http://dev.novemberborn.net/sifr3/nightlies/sifr3-r436.zip

A: Yes you can. If you comment out your JavaScript code with CSS comment (< !-- -->) and comment CSS with Javascript comments (/* */) you can have CSS and JS inside the same file. You'll have to include file twice on the page, once as a JavaScript and once as CSS.
When you include your file as a javascript, JS engine will ignore CSS comments and process JS code just fine, and the other way around for CSS. Here's a link to an article that describes the process.

A: Or, you could completely get rid of sIFR and use css @font-face.
Here is an @font-face generator that will convert your font to different formats for different browsers (IE and Chrome) and even create a sub-set of your font if you don't need the whole character set.
http://www.fontsquirrel.com/fontface/generator
It works in all browsers, as described in this article http:// paulirish .com/2009/bulletproof-font-face-implementation-syntax/ and as demonstrated in this test page http:// dl.dropbox .com/u/39519/webfontsdemo/index.html.
I tested in IE5.5 6 7 8, FF3.6, Chrome 4.0.249.89, and Safari 4.0.4 on Windows XP.
(sorry about the links, SO won't let me post more than one until I get a higher reputation).

A: You can put your CSS into a Javascript string, then create a STYLE element in Javascript.
For example:  (Using jQuery)
$('<style type="text/css">p { color:red; }</style>').appendTo($('head'));

For sIFR3, you would write
$('<style type="text/css">@media screen {.sIFR-flash { visibility: visible !important; margin: 0; padding: 0;}.sIFR-replaced, .sIFR-ignore { visibility: visible !important;}.sIFR-alternate { position: absolute; left: 0; top: 0; width: 0; height: 0; display: block; overflow: hidden;}.sIFR-replaced div.sIFR-fixfocus { margin: 0pt;  padding: 0pt;  overflow: auto;  letter-spacing: 0px;  float: none;}}@media print {.sIFR-flash { display : none !important; height: 0; width: 0; position: absolute; overflow: hidden;}.sIFR-alternate { visibility : visible !important; display : block!important; position: static!important; left : auto !important; top: auto !important; width: auto !important; height: auto !important;}}</style>').appendTo($('head'));

(Take the CSS file, remove the comments, and remove all double-spaces and all newlines)

A: You can keep them as separate files and have Javascript write the css to the page. Then the CSS will only appear if javascript is enabled.

A: You could use something like smartoptimizer or php speedy.


text:
Q: T-SQL query - GROUP BY issue I have a table in SQL Server consisting of two columns that track how many users are logged into a system at a particular interval.   The first column is Time15, which is the time rounded to the nearest 15 minute interval (datetime).  The second column is UserCount, which is the number of users logged into the system during that 15 minute interval.
I need a query that will show me the peak number of users logged in for each day.  So if at 1 PM on 1/1/09 the system reached a peak of 100 users, I need output that looks like:
1/1/09 - 100
1/2/09 - 94
1/3/09 - 98
etc ...
Any idea what T-SQL is going to accomplish this?   Thanks!

A: Try this:
SELECT YEAR(Time15), MONTH(Time15), DAY(Time15), MAX(UserCount)
FROM Table
GROUP BY YEAR(Time15), MONTH(Time15), DAY(Time15)

I like Russ's approach for getting rid of the time portion - if you have SQL Server 2005+ you can use this approach to preserve the time of day the peak happened:
WITH cte AS
(
SELECT Time15, UserCount, ROW_NUMBER() OVER (PARTITION BY DATEADD(dd, DATEDIFF(d, 0, Time15), 0) ORDER BY UserCount DESC) AS RowNumber
FROM <Table>
)
SELECT Time15, UserCount
FROM cte
WHERE RowNumber = 1

A: You basically need to drop the time part from the Time15 field in order to get the Date. Then it's just a simple case of getting the Maximum UserCount when you group by the Date.
SELECT
    DATEADD(dd, DATEDIFF(d, 0, Time15), 0) As [Date],
    MAX(UserCount) As [Maximum Users]
FROM
    Table
GROUP BY
     DATEADD(dd, DATEDIFF(d, 0, Time15), 0)

A: I'd just convert it this way...seems to be the simplest..
SELECT convert(varchar,Time15,101) as da, max(UserCount)FROM TABLE GROUP BY convert(varchar,Time15,101)


text:
Q: Differentiate STUN, RTP, DTLS packets - java program I'm writing a small UDP server, where it might receive different UDP protocol messages like STUN, RTP, RTCP, DTLS packets in to the same port.
I should first be able to differentiate each kind of protocol messages in order to execute different logic.
Where can I find a sample for java, better a library to help me with this.

A: Here is a c++ version which I am sure can be rewritten in java, but it gives you an idea what to do. Btw buffer variable holds a most recent udp datagram received.
 if((buffer[0]==0) || (buffer[0]==1))
      return stun; // STUN packet

 if((buffer[0]>=128) && (buffer[0]<=191))
      return rtp; // RTP packet

 if((buffer[0]>=20)  && (buffer[0]<=64))
      return dtls; // DTLS packet

A:
I should first be able to differentiate each kind of protocol messages in order to execute different logic.

Why? I would simply run the logics in parallel; i.e., pass every packet on this port to every logic.
The logics should be designed to ignore ill-formed requests (after all, if they are going to run on the open Internet, they ought to be robust enough to deal with even maliciously crafted packets).
If some incoming requests are -polyglots-; i.e., they are valid in multiple protocols, then the client is going to receive multiple responses. In this design, it is left to the client code to deal with the response(s) that aren't legal. Maybe the client is robust enough to ignore them. Or maybe the client will retry the protocol from the start, possibly picking a new sequence number or something that isn't a polyglot anymore (by pure luck).
I don't think there's a "really good" solution to this problem, as UDP packets are too small to waste space with unique identifiers for each protocol. The UDP protocol was designed to use separate ports for different services. The only "correct" solution is to place services that run on the same port on different IP addresses.


text:
Q: Rest template post call returning 500 error I am trying to call a rest endpoint by passing an object and get the response. It is working in postman. Here is my url: https://test.ap.com/rest/user/create
body:{ "gender":"MALE", "weight":965.0, "height":40.0, "name":"testuser" }
and the response is
{ "id":"1234", "token":"1234%" }
Here is my code:
 @RequestMapping(value = "/createUser", method = { RequestMethod.POST})
    public  createUserInfo() throws Exception
    {
       UserData userData = new UserData();
       userData.setGender("MALE");
       userData.setWeight(965.0);
       userData.setHeight(40.0);
        userData.setName("test1");

        String url="https://test.ap.com/rest/user/create";

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();

        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Object> entity = new HttpEntity<Object>(userData, headers);

        ResponseEntity<Object[]> response= restTemplate.postForEntity(url, entity, Object[].class);

    }

I am getting the following error:
org.springframework.web.client.HttpServerErrorException: 500 null
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:66)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
    at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:407)
    at

I tried to change the headers and  created an object for response type but nothing worked for me. what else I should add to fix this?

A: I think
String url="https://test.ap.com/rest/user/create";

should be
String url="https://test.ap.com/rest/user/create/";

for some reason that last slash is really important


text:
Q: Asp.net mvc 4 deployment error I have developed a web application in mvc 4. Everything is fine on the development machine, however on the live server it is giving me the following error.
Could not load file or assembly

'System.Web.Http, Version=4.0.0.0, Culture=neutral,
  PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The
  module was expected to contain an assembly manifest.

I have tried the following solutions:

*

*Copied dll files to the bin folder from my local drive

*Checked that my hosting has asp.net 4 enabled

*Have checked that web.config file is properly configured.

Here is the exact screen trace. Notice that the last line shows .net version 4 as well as asp.net version 4 so I assume it is not the problem. Please guide me on it.
Could not load file or assembly 'System.Web.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The module was expected to contain an assembly manifest.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.BadImageFormatException: Could not load file or assembly 'System.Web.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The module was expected to contain an assembly manifest.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Assembly Load Trace: The following information can be helpful to determine why the assembly 'System.Web.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' could not be loaded.

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

Stack Trace:

[BadImageFormatException: Could not load file or assembly 'System.Web.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The module was expected to contain an assembly manifest.]
   innovationtimes.MvcApplication.Application_Start() +0

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272

Here is the entire web.config file
 <?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <appSettings>
    <add key="webpages:Version" value="2.0.0.0"/>
    <add key="webpages:Enabled" value="false"/>
    <add key="PreserveLoginUrl" value="true"/>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  </appSettings>
  <connectionStrings>
    <!--<add name="DataContext" providerName="System.Data.SqlClient" connectionString="Data Source=pc1\SQLEXPRESS;Initial Catalog=itdb;User Id=sa;Password=12345;"/>-->

  </connectionStrings>
  <system.web>
    <customErrors mode="Off"></customErrors>
    <compilation debug="true" targetFramework="4.0"/>
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers"/>
        <add namespace="System.Web.Mvc"/>
        <add namespace="System.Web.Mvc.Ajax"/>
        <add namespace="System.Web.Mvc.Html"/>
        <add namespace="System.Web.Routing"/>
        <add namespace="System.Web.WebPages"/>
      </namespaces>
    </pages>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules runAllManagedModulesForAllRequests="true"/>
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit"/>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit"/>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0"/>
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0"/>
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/>
    </handlers>
  </system.webServer>
</configuration>

A: I finally managed to get it done. Hope it will also help those with similar issues.
The culprit is publish wizard. I published my project using the publish tool. However when I  uploaded the published project, it was simply not working and showing the system.web.http assembly is corrupt.
How did I resolved it -
I uploaded the system.web.http dll from the bin folder of my project to overwrite the dll of publish wizard.
I was further prompted for other dlls and I did same for all of them.
The application started working as soon as I replaced all the erroneous dlls with one from my bin folder.
I am not sure if it is a bug with visual studio publish wizard or not. if Anybody have better idea of this issue, please post here for help of others.

A: I had the same problem. Somehow publish wizard did not like Release mode. In release mode, it kept failing to deploy system.web.http.dll and then also for razor assembly. when I changed to debug mode in publish wizard settings, it finally worked. of course, that doesn't make it a solution - just a nasty work around of publishing in debug mode. or else, use some other means of publishing than the VS publish wizard.


text:
Q: Get all items around a certain point from SQLite Database I have a database full of map Locations (Latitude, Longitude), is there a way I could do a SQL query to return me all points around a certain location?
Right now I basically grab everything in the database and loop through each one and check the distance using
Location.distanceBetween(startPoint.latitude, startPoint.longitude,endPoint.latitude,endPoint.longitude, results);

and keeping items that are within the set distance but there could be a lot of points to loop through.
So is there anyway to do this in an SQL statement?

A:
I have a database full of map Locations (Latitude, Longitude), is there a way I could do a SQL query to return me all points around a certain location?

You can easily check a square region.
Using very simplified latitude / longitude coordinates say you're at [25.86, 57.03] and you wanted everything in the "neighborhood" (+/- .05) you can use a query like this:
SELECT * FROM Coords WHERE (latitude BETWEEN 25.81 AND 25.91) AND (longitude BETWEEN 56.98 AND 57.08);

A: You can use a WHERE clause expression to filter on angular distance r from an origin (x0, y0). Since SQLite doesn't have a square root function, you'll have to use the squared distance:
SELECT ... FROM ...
    WHERE (Latitude-x0)*(Latitude-x0) + (Longitude-y0)*(Longitude-y0) < r*r;

The only place this won't work well is near the poles or the prime meridian. It's also a planar approximation to the sphere, so it will only work for values of r that are quite small. Finally, it scales latitude and longitude equally, so the selected region looks more and more elliptical the farther away the origin is from the equator.
You will have to convert linear distance (e.g., "within 30 meters") to latitude/longitude differences. This is a rather complex subject because the Earth is not a perfect sphere. However, for rough calculations you can use the approximation that 1 nautical mile = 1852 meters = 1 arc minute of longitude at the equator. Since lines of longitude get closer together as the latitude moves away from the equator, you will need to use some trig to figure out what value of r to use at a given latitude. For more info on this problem see this thread or this one, or search the web for "convert meters to latitude longitude".

A: You can also use the SQLite R*Tree extension.
An R-Tree is a special index that is designed for doing range queries. R-Trees are most commonly used in geospatial systems where each entry is a rectangle with minimum and maximum X and Y coordinates.
The source code to the SQLite R*Tree module is included as part of the SQLite3 amalgamation but is disabled by default. To enable the R*Tree module, simply compile with the SQLITE_ENABLE_RTREE C-preprocessor macro defined.


text:
Q: Find all php files which first or second line have more than N characters How would I go on writting a program that would look for all my php files which first or second line contain more than N characters? I would like to show the name of the file and the content of the line
I am able to go file by file with this:
    <title>Find String</title>
    <?php
    find_files('.');
    function find_files($seed) {
        if(! is_dir($seed)) return false;
        $files = array();
        $dirs = array($seed);
        while(NULL !== ($dir = array_pop($dirs)))
        {
            if($dh = opendir($dir))
            {
                while( false !== ($file = readdir($dh)))
                {
                    if($file == '.' || $file == '..') continue;
                    $path = $dir . '/' . $file;
                    if(is_dir($path)) { $dirs[] = $path; }
                    else { if(preg_match('/^.*\.(php[\d]?)$/i', $path)) { check_files($path); }}
                }
                closedir($dh);
            }
        }
    }

    function check_files($this_file){

        if(!($content = file_get_contents($this_file)))
        { echo("
Could not check $this_file You should check the contents manually!
\n"); }
        else
        {
            // What to do here??
        }
        unset($content);
    }
    ?>

A: I would go with the comments to restore from backup and also identify and eliminate the vulnerability.  But to answer the question:
foreach(glob('path/*.php') as $file) {
    $lines = file($file);

    if(strlen($lines[0]) > $N) {
        echo "$file : line 1 : {$line[0]}\n";
    }
    elseif(strlen($lines[1]) > $N) {
        echo "$file : line 2 : {$line[1]}\n";
    }
}

There is a similar question from yesterday: Find php files with strings that have more than 50 characters with the same issue.


text:
Q: CLang tidy does not recognize namespace keyword and interprets it as a variable I am ramping up a Platform IO project. Within there I am using clang-tidy for different checks (see documentation for PIO clang-tidy here).
Given the folder structure
- .
-- include
-- src

I placed a header file in the include folder, called ISomeInterface.h
The content looks like this:
#pragma once

namespace some_namespace { // interface declaration
}

When I run pio check (invokes clang-tidy) I get the warning
variable 'some_namespace' is non-const and globally accessible, consider making it const  [cppcoreguidelines-avoid-non-const-global-variables]

The Question is: Why is CLang not recognizing the namespace keyword? I found a possible solution here SO Thread that states
can't use clang-tidy directly on header files. Instead i have to check the cpp file and have to add -header-filter=.* to also check the headers

But this did not work for me :(


text:
Q: The action of a group on a set, and the size of an orbit. This question may be easy to solve with an example, but I am not able to think of any.
Let's say that you have a group G, and a subgroup H, it is show that a the cosets $(aH), a \in G$, form an equivalence relation, so they partition G, but the interesting part in this case is that every part of the partition has the same amount of elements.
But let's say you have a set X, which is not a group, but you have a group G, that acts on the group X.
Formally this means that:
$gx\in X, \forall g \in G, \forall x \in X$
$ex=x, \forall x \in X$
$(g_1g_2)x=g_1(g_2x)$.
It can be show that the relation $x_1$~$x_2$, if there is a g such that $gx_1=x_2$, exists. Hence since we have an equivalence relation we get a partition of X, and we call these partitions for orbits in X under G.
My question is: Are these orbits/partitions of the same size like in the coset case?

A: No, in general they aren't.
Easy example: Let $\mathbb R^\ast$ (the group of nonzero real numbers under multiplication) act on the set $\mathbb R$ via multiplication.  There are exactly two orbits, $\{0\}$ and $\mathbb R \setminus \{0\}$.
One thing to point out though it that while cosets of $H$ can be acted on by $G$, this action is transitive and has only one orbit, so the cosets themselves are not orbits under this action.
The cosets $G/H = \{gH \ | \ g \in G\}$ are actually the orbits of the right action of $H$ on $G$ by multiplication.  $G$ also has a left action on itself by multiplication and these actions are compatable, i.e., $g\cdot(x\cdot h) = (g\cdot x)\cdot h$ for all $g, x \in G$ and $h \in H$.  Whenever you have a set $X$ with a left $G$ action and a right $H$ action which are compatible in this way, then $G$ acts on the $H$-orbits $X/H$ and if two $H$-orbits in $X/H$ lie in the same $G$-orbit (of the action of $G$ on $X/H$) then indeed they will be the same size.
So you could say that the reason the partitions of $G$ into cosets of $H$ are all the same is precisely because the action of $G$ on these cosets is transitive.

A: In addition to Jim's answer, a group $G$ acts on its elements by conjugation; we have the map $\cdot^g : G \to G$ where $x \mapsto x^g = g^{-1}xg$.
It's definitely not the case that conjugacy classes all need to have the same size.


text:
Q: Android Navigation Instrument Test Exception java.lang.IllegalStateException: Method addObserver must be called on the main thread.
@Test
fun verifyAllRequiredViewsAreDisplayed() {
val navController = TestNavHostController(
    ApplicationProvider.getApplicationContext()
)

navController.setGraph(R.navigation.navigation_onboarding)

// Create a graphical FragmentScenario for the TitleScreen
val userEmailScenario = launchFragmentInContainer<EmailFragment>()

// Set the NavController property on the fragment
userEmailScenario.onFragment { fragment ->
    Navigation.setViewNavController(fragment.requireView(), navController)
}

assertThat(navController.currentDestination?.id).isEqualTo(R.id.emailFragment)

}


text:
Q: Joining two tables based on matching two columns I'm trying to join two tables:
Table A has three columns: State, County, and Count (of Farmer's Markets in said county)
Table B has several columns: State, County, and several data columns (like food access score)
I'm trying to combine them in such a way as to put the Count for each State/County combination (since there are multiple counties with the same name) together with the State and County and data columns from Table B.
I've been banging my head on SAS, trying to get a join to cooperate. I read a few other questions on here, but I can't find where the mistake is in my code.
PROC SQL;
CREATE TABLE WORK.QUERY1
AS
SELECT FMDV4.State, FMDV4.County, FMDV4.Count, CFSDV1.GROC14,
CFSDV1.SUPERC14, CFSDV1.CONVS14, CFSDV1.SPECS14, CFSDV1.FOODINSEC_13_15,
CFSDV1.PCT_LACCESS_POP15, CFSDV1.DIRSALES_FARMS12, CFSDV1.FMRKT16,
CFSDV1.FOODHUB16, CFSDV1.CSA12, CFSDV1.POVRATE15, CFSDV1.PERPOV10
    FROM FNLPRJT.CFSDV1 AS CFSDV1
    INNER JOIN FNLPRJT.FMDV4 AS FMDV4
    ON (( CFSDV1.State = FMDV4.State ) AND ( CFSDV1.County =
FMDV4.County ));
QUIT;

I also tried a few variants, like:
PROC SQL;
CREATE TABLE WORK.QUERY1
AS
SELECT FMDV4.State, FMDV4.County, FMDV4.Count, CFSDV1.GROC14,
CFSDV1.SUPERC14, CFSDV1.CONVS14, CFSDV1.SPECS14, CFSDV1.FOODINSEC_13_15,
CFSDV1.PCT_LACCESS_POP15, CFSDV1.DIRSALES_FARMS12, CFSDV1.FMRKT16,
CFSDV1.FOODHUB16, CFSDV1.CSA12, CFSDV1.POVRATE15, CFSDV1.PERPOV10
    FROM FNLPRJT.CFSDV1 AS CFSDV1
    INNER JOIN FNLPRJT.FMDV4 AS FMDV4
    ON CFSDV1.State = FMDV4.State
    WHERE CFSDV1.County = FMDV4.County;
QUIT;

I get a table of 0 rows with the columns as they should be (State, County, Count, ). I'm just missing the dang data! Can anyone please help me find my mistake?

A: Can you try
propcase(CFSDV1.State) = propcase(FMDV4.State)

and
propcase(CFSDV1.County) = propcase(FMDV4.County);

If this doesn't work try character functions like trim and compress to remove any blanks that might be present in the data.


text:
Q: Date parameter using with stored procedures in SQL Server I'm trying to retrieve data in iReport using stored procedure(SP) in SQL Server 2008.
My stored procedure uses two parameters Date_From & Date_To. I would like to run the report in specified (by these parameters) period but in any case I have info like "No data in report". In table the date is stored in format "yyyy-MM-dd 00:00:00.000". both of the parameters are set as "java.util.Date". In the Report query I have:

*

*Query language = plsql

*In query window: Name_of_procedure $P{Date_From}, $P{Date_To}
I found somewhere info that is possible to change the Date format and I have change it to:
Date format "yyyy-MM-dd", but after this change, instead of generate the report iReport is coming back to the Designer window, without any error or info.
May I ask for help, how to correct set the parameter that would provide the Date in format "yyyy-MM-dd"?
iReport version: 5.1.0

A: To see the error you can go to Window--> Report Output option there you can find the error.
To call the procedure syntax should be
  CALL  Name_of_procedure ( $P{Date_From}, $P{Date_To})

and to set the default value for parameters you can use this syntax.
   new  Date(114,7,06)  --> to set default date as 06 Aug 2014.


text:
Q: Notification doesn't show light with sound set When I add .setDefaults(DEFAULT_SOUND) or DEFAULT_LIGHTS or DEFAULT_ALL, it shows the heads up notification, but doesnt show the light set with .setLights(0x0FF00FF0, 300, 100). If I remove the .setDefaults it doesn't show the heads up, but shows the lights.
Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
    notificationIntent.setData(Uri.parse("http://www.wgn.com"));
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

Notification notification = new NotificationCompat.Builder(this)
        .setCategory(Notification.CATEGORY_MESSAGE)
        .setContentTitle("Yi Warning")
        .setContentText("Battery is below 20%")
        .setSmallIcon(R.drawable.ic_launcher)
        .setAutoCancel(true)
        .setVisibility(1)
        .setContentIntent(contentIntent)
        .setPriority(Notification.PRIORITY_MAX)
        .setDefaults(Notification.DEFAULT_SOUND)
        .setLights(0x0FF00FF00, 300, 100).build();
NotificationManager notificationManager =
        (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notification);

A: Removed
.setDefaults(Notification.DEFAULT_SOUND)

and added
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))

Now everything is working great :D


text:
Q: ANTLR v3: Missing method JavaParser.javaSource() and class JavaParser.javaSource_return With executing org.antlr.Tool in antlr-3.5.1-complete.jar with grammar Java.g (e.g. Java.g) there are no method JavaParser.javaSource() and class JavaParser.javaSource_return generated, but in Java Tree parser output for ANTLR - Stack Overflow. Why?

A: The two posts are not using the same Java.g file. For the file you referenced, the entry point is the rule compilationUnit, which produces JavaParser.compilationUnit() and JavaParser.compilationUnit_return.


text:
Q: Vanilla JavaScript running CSS animation on div scroll into view not working I'm trying to run a CSS Animation when a div enters the visible screen. However, I'm noticing the animations are playing when the page loads no matter what.
I've googled the problem, I've messed with the code, nothing seems to be giving me the right results.
JavaScript
    var animateHTML = function() {
    var elems;
    var windowHeight;
    function init() {
      elems = document.querySelectorAll('.animatemeplz');
      windowHeight = window.innerHeight;
      addEventHandlers();
      checkPosition();
    }
    function addEventHandlers() {
      window.addEventListener('scroll', checkPosition);
      window.addEventListener('resize', init);
    }
    function checkPosition() {
      for (var i = 0; i < elems.length; i++) {
        var positionFromTop = elems[i].getBoundingClientRect().top;
        if (positionFromTop - windowHeight <= 0) {
          elems[i].className = elems[i].className.replace(
            'animatemeplz',
            'animated fadeIn'
          );
        }
      }
    }
    return {
      init: init
    };
  };
  animateHTML().init();

HTML

01

02

03

04

SERVER MOTTO

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
 incididunt ut ero labore et dolore.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
 incididunt ut ero labore et dolore.

    Discord Server

100

50

25

0

STATISTICS

Lorem ipsum dolor sit amet,
consectetur adipsicing elit, sed do
eiusmod.

FILTER
 TodayA Month Ago4 Months Ago

Filter our updated statistic log through clicking designated buttons to alter your filtered result.

Features

Down to Roleplay ping-able role (@DTRP)

pingable only every 3 hours or something #DM-request ping spam

Expected Result: Animation plays when div is scrolled into view.
Actual Result: Animation is played when the page is loaded even when div is not visible.

A: The issue would seem to depend on your CSS. Your JavaScript is replacing the .animatemeplz class with the .animate and .fadeIn classes for elements that enter the viewport, so CSS of the following form should ensure the animation works:
.animatemeplz {
    opacity: 0;
}
.animated {
    transition: opacity 1s;
}
.fadeIn {
    opacity: 1;
}

A cleaner way of doing it might be to give elements that require animations a single .animate class:

STATISTICS

Lorem ipsum dolor sit amet... etc

with CSS for .animate and another class, .visible as follows:
.animate {
    transition: opacity 1s;
    opacity: 0;
}
.animate.visible {
    opacity: 1;
}

You could then toggle visibility using the JavaScript classList.add method.
...
if (positionFromTop - windowHeight <= 0) {
    elems[i].classList.add('visible');
} else {
    elems[i].classList.remove('visible');
}
...

This would fade out the elements when you scroll back up.

You are also calling checkPosition() on every scroll event. This will likely cause lag on some devices, especially if checkPosition() takes a while to compute. There are a number of ways to fix this, including debouncing where you would wait a specified length of time before calling checkPosition() again. Debouncing with a wait time of 100ms could be done by replacing the code where you add a scroll event listener with the following:
window.addEventListener( 'scroll', function() {
    if ( !checkPosition.debounce ) {
        checkPosition.debounce = setTimeout(function(){
            delete checkPosition.debounce;
            checkPosition();
        }, 100);
    }
} );


text:
Q: Overflow/Extend CSS Grid-Areas for Certain Elements I'm learning CSS Grid and am very fascinated by it. Particularly, I'm using the template-areas approach to define structure. Here's an example of the code I have written to define a basic article layout with two sidebars, a main content area, and an article footer:
HTML:

    Left Sidebar Content

        Main Article Content

            Overflow Content

        Right Sidebar Content

        Article Footer Content

CSS:
.article-wrapper{
  display:grid;
  grid-template-areas:
          "h h h h h h h h h h h h"
          "l l c c c c c c c c r r"
          "l l f f f f f f f f r r";
}

.article-wrapper > .article-sidebar-left{
  grid-area: l;
}
.article-wrapper > .article-sidebar-right{
  grid-area: r;
}
.article-wrapper > .article-content{
  grid-area: c;
}
.article-wrapper > .article-footer{
  grid-area: f;
}

My question; is there a way, using this approach of grid areas, that I can make the article-overflow element, which is wholly within the c grid-template-area to extend into the l and r areas?
Essentially, I'd like the width of the article-overflow element to be as such:
l x x x x x x x x x x x r whereas now it is l l x x x x x x x x r r
In other words, I'm trying to extend it one grid unit into each of the areas used by the sidebars currently.

A:
...is there a way, using this approach of grid areas, that I can make the .article-overflow element, which is wholly within the c grid-template-area to extend into the l and r areas?

No.
The .article-overflow element isn't even a grid item, so it doesn't recognize grid properties1.
There's a possibility that in a future version of Grid Layout the subgrid feature 2, which allows the children of grid items to respect the lines of the primary container, will be implemented. But that's speculation. And even then, there's no guarantee that the grid area you want will be available with grid-template-areas. It may only be available with line-based placement 3.

Notes:
1 Grid properties not working on elements inside grid container
2 Positioning content of grid items in primary container (subgrid feature)
3 Line-based placement with CSS Grid


text:
Q: Creating equal and pretty scale breaks with facet_grid() I want to create a plot using facet_grid(), with free scales for the y axis. However, for each row, the scale breaks should be distributed evenly, that is, with 3 breaks.
I lended from this question, but I was not able to adapt the code in a way that the scale breaks are actually pretty.
However, this is my current approach:
# Packages
  library(dplyr)
  library(ggplot2)
  library(scales)

# Test Data
  set.seed(123)

  result_df <- data.frame(
    variable = rep(c(1,2,3,4), each = 4),
    mode     = rep(c(1,2), each = 2),
    treat    = rep(c(1,2)) %>% as.factor(),
    mean     = rnorm(16, mean = .7, sd = 0.2),
    x       = abs(rnorm(16, mean = 0, sd = 0.5))) %>%
    mutate(lower = mean - x,upper = mean + x)

# Function for equal breaks, lended from

  equal_breaks <- function(n = 3, s = 0.05, ...) {
    function(x) {
      d <- s * diff(range(x)) / (1+2*s)
      round(seq(min(x)+d, max(x)-d, length=n), 2)
  }}

  ## Plot

 result_df %>%
   ggplot(aes(y = mean*100, x = treat)) +
   geom_pointrange(aes(ymin = lower*100, ymax = upper*100), shape = 20) +
   facet_grid(variable ~ mode, scales = "free_y")+
   scale_y_continuous(breaks = equal_breaks(n = 3, s = .2))+
   labs(x = "", y = "")

Which leads to this current plot. As one can see, the breaks are far from being reasonable.
Thanks in advance for any kind of recommendation, and please excuse me in case I have missed a already existing solution.
Best, Malte


text:
Q: How to split a long lines hex string? I've a long hex string like this 100000006465780A3033350025979BA5B30D4516F6.
Is there an easy way I can split these with a space per hex coded byte so I get 10000000 64 65 78 A3 03 33 35 00 25 97 9B A5 B3 0D 45 16 and remove the last two words F6?
I have multiple lines. I want to manage these lines.
Is there an easy way I can split these lines at a single time  (or another easily accessible tool) I can use under Windows?


text:
Q: use document.write() to write html in to iframe, but jquery not working in IE9 I have stored a html page in local system, and i try to get the contents then write to an iframe.

    <title></title>

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

<button id="buttonClick">Click Me</button>

i use document.write() to write the html code to the iframe, but error SCRIPT5009: '$' is undefined occur when page load in IE9, but work fine in google chrome & firefox.

A: The issue might be that IE is executing the JS code before loading in jquery, try loading it in dynamically and listening for onload:

  <title></title>
  <link href="styles/myStlye.css" rel="stylesheet" type="text/css" />

  <button id="buttonClick">Click Me</button>

A: (Posted solution on behalf of the question author).
Thank for Ralph Najm's answer, but I have found another method to solve this problem that I feel is more appropriate.
Wait until the page loaded before execute the script. Below is the example:

    <title></title>

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

<button id="buttonClick">Click Me</button>


text:
Q: Java - Two buffered writers Hello all ive been having issues with my BufferedWriter. at first i only had 1 buffered writer the 1 that is showed as cc and this worked perfectly along with the output but now that i have tried to implement 2 i continue to get an error else where
Multiple markers at this line
    - Syntax error, insert "}" to complete Statement
    - Syntax error, insert "Finally" to complete

Here is the code. The error starts at the }else if (command.equals("action 2")) line
if (selected) {
    if (command.equals("action1")) {
      BufferedWriter aa;
      try {
          File writerB = new File("output1.txt"); //set transaction-list.txt to be the destination file when writeTransactions is used
          if (!writerB.exists()) {
               writerB.createNewFile();
                    }

        FileWriter bb = new FileWriter(writeBalance, true); //filewriter
        aa = new BufferedWriter(bb); // bufferedwriter

      BufferedWriter cc;
            try {
                int x=0;
                File writerT = new File("output2.txt"); //set transaction-list.txt to be the destination file when writeTransactions is used
                if (!writerT.exists()) {
                    writerT.createNewFile();
                    }
                FileWriter dd = new FileWriter(writeTransactions, true); //filewriter
                cc = new BufferedWriter(dd); // bufferedwriter
                String newLine = System.getProperty("line.separator"); //creates a line separator which will be used with string newLine

        if (n==0) {
            bw.write(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(now) + newLine);
            wb.write(c);}
            bw.close;
            wb.close}

    }else if (command.equals("action 2"))

A: You don't handle your resources properly; for one they should be closed in finally blocks...
... However, there is even better and that is to use a try-with-resources statement, along with the new java.nio.file API:
final Path file1 = Paths.get("output1.txt");
final Path file2 = Paths.get("output2.txt");

try (
    final BufferedWriter writer1 = Files.newBufferedWriter(file1, StandardCharsets.UTF_8,
        StandardOpenOption.CREATE, StandardOpenOption.APPEND);
    final BufferedWriter writer2 = Files.newBufferedWriter(file2, StandardCharsets.UTF_8,
        StandardOpenOption.CREATE, StandardOpenOption.APPEND);
) {
    // use writer1 and writer2 here.
    // Note that BufferedWriter has a .newLine() method as well.
}

A: You did not make a catch block after the try - in neither cases. A catch or a finally block is mandatory after try.
As it was mentioned, the try-with-resources statement introduced in Java 7, is strongly recommended.


text:
Q: How do I convert CAML to use in the CQWP? I have the following CAML query which returns checked out files.
<Query><Where><Eq><FieldRef Name="CheckoutUser" /><Value Type="User">[Me]</Value></Eq></Where></Query>

I want to use this in a Content Query web part, within the 'QueryOverride' section.
<property name="QueryOverride" type="string" />

I'm new to this, but believe it can be done.  Can someone convert this for me please or point me in the right direction.
All help appreciated.

A: Follow these steps;

*

*Place the standard CQWP onto the page.

*Export the web part (in the web part pane, click edit -> Export and save the file to your PC)

*Open the webpart you just exported in Notepad or some other plain
text editor

*Find the property

*Embed your CAML query into a CDATA section, the above query will now
look like this;

< ![CDATA[ < Where > < Eq >< FieldRef
  ID="{fdc3b2ed-5bf2-4835-a4bc-b885f3396a61}"> < /FieldRef > < Value
  Type="Number">3< /Value>< /Eq>< /Where>]]>

*

*Place this CAML into the QueryOverride property in the webpart. That
line of markup should now look like this;

< property name="QueryOverride" type="string" > < ![CDATA[< Where><
  Eq>< FieldRef ID="{fdc3b2ed-5bf2-4835-a4bc-b885f3396a61}" >< /FieldRef

< Value Type="Number" > 3< /Value>< /Eq >< /Where >]] > < /property >

*

*Save the webpart text

*Import the webpart back into Sharepoint. Click 'Add a Web Part' in
the web part zone of the page ->Advanced web part gallery and
options -> Browse -> Import. Select your modified .webpart file that
you saved to your PC.

*An icon for your webpart will appear in Sharepoint. Drag that into
the webpart zone you want this to appear in.

Check in your page, and see the results.
Taken from : Using CAML in CQWP
Hope it helped :)


text:
Q: Определение DAO интерфейсов для агрегата Доброго времени суток.
Задача:
Имеется следующая схема БД

и следующая структура классов

Необходимо разработать DAO интерфейс или интерфейсы для агрегата, корнем которого является класс Product.
Взаимодействие с БД осуществляется с помощью JDBC. ORM использовать нельзя.
Что не получается:
Я не могу понять, как должен выглядеть правильный DAO интерфейс/интерфейсы для описанной модели. Я придерживался следующих принципов, хотя теперь у меня нет никакой уверенности, что они правильные:

*

*Для каждого класса бизнес модели свой интерфейс. (У меня получились соответствующие интерфейсы - ProductTagDao, ProductPriceDao, ProductDao и их реализации).

*Объекты каждого типа бизнес логики могут быть загружены, сохранены или удалены из БД только через соответствующий интерфейс.

*Интерфейсы DAO по возможности максимально "тупы" и предоставляют элементарные CRUD операции и их простые модификации.

Вот что получилось в итоге:
  public interface ProductTagDao {
      /**
      * Возвращает теги для выборки продуктов из всех продуктов отсортированных по имени. Выборка начинается с продукта под номером fromIndex
      * (первый продукт имеет номер 0), кол-во продуктов в выборке равно count. Теги возвращаются в виде коллекции HashMap, где ключами выступают
      * идентификаторы тегов.
      *
      * @param fromIndex - номер продукта из списка всех продуктов отсортированных по имени, с которого начинается выборка продуктов.
      * @param count - кол-во продуктов входящих в выборку из всех продуктов отсортированных по имени.
      *
      */
      public HashMap<Integer, ProductTag> getTagsByProductsSortedByName(
             int fromIndex, int count) throws SQLException;

      /**
      * Возвращает все теги для продукта с id равном productId. Теги возвращаются в виде коллекции HashMap, где ключами выступают идентификаторы
      * тегов.
      *
      * @param productId - идентификатор продукта, для которого возвращаются все принадлежащие ему теги.
      */
      public HashMap<Integer, ProductTag> getTagsByProductid(int productId) throws SQLException;

      public void add(ProductTag tag) throws SQLException;
      public void update(ProductTag tag) throws SQLException;
      public void removeById(int tagId) throws SQLException;
  }

  public interface ProductPriceDao {
      /**
      * Возвращает цены для выборки продуктов из всех продуктов отсортированных по имени. Выборка начинается с продукта под номером fromIndex
      * (первый продукт имеет номер 0), кол-во продуктов в выборке равно count. Цены возвращаются в виде коллекции HashMap, где ключами
      * выступают идентификаторы цен.
      *
      * @param fromIndex - номер продукта из списка всех продуктов отсортированных по имени, с которого начинается выборка продуктов.
      * @param count - кол-во продуктов входящих в выборку из всех продуктов отсортированных по имени.
      * @tags - коллекция всех тегов, которые понадобятся для всех объектов ProductPrice возвращаемых данным методом.
      */
      public HashMap<Integer, ProductPrice> getPricesByProductsSortedByName(
             int fromIndex, int count, HashMap<Integer, ProductTag> tags) throws SQLException;

      /**
      * Возвращает цены для продукта с id равном productId. Цены возвращаются в виде коллекции HashMap, где ключами
      * выступают идентификаторы цен.
      *
      * @param productId - идентификатор продукта, для которого возвращаются все принадлежащие ему теги.
      * @tags - коллекция всех тегов, которые понадобятся для всех объектов ProductPrice возвращаемых данным методом.
      */
      public HashMap<Integer, ProductPrice> getPricesByProductId(
             int productId, HashMap<Integer, ProductTag> tags) throws SQLException;

      public ProductPrice add(ProductPrice price) throws SQLException;
      public void update(ProductPrice price) throws SQLException;
      public void removeById(int id) throws SQLException;

      public void addTag(int productId, ProductTag tag) throws SQLException;
      public void removeTag(int productId, ProductTag tag) throws SQLException
  }

  public interface ProductDao {
      /**
      * Возвращает продукт по его идентификатору.
      *
      * @param id - идентификатор возвращаемого продукта.
      * @param prices - коллекция всех цен, которые понадобятся для возвращаемого объекта Product.
      */
      public Product getById(
            int id, HashMap<Integer, ProductPrice> prices) throws SQLException;

      /**
      * Возвращает выборку из списка всех продуктов отсортированных по имени, начиная с продукта под номером fromIndex
      * (первый продукт имеет номер 0) в колличестве равном count.
      *
      * @param fromIndex - номер продукта из списка всех продуктов отсортированных по имени, с которого начинается выборка продуктов.
      * @param count - кол-во продуктов входящих в выборку из всех продуктов отсортированных по имени.
      * @param prices - коллекция всех цен, которые понадобятся для всех возвращаемых объектов Product.
      */
      public List<Product> getSortedByName(
            int fromIndex, int count, HashMap<Integer, ProductPrice> prices) throws SQLException;

      public Product add(Product product) throws SQLException;
      public void update(Product product) throws SQLException;
      public void removeById(int id) throws SQLException;

      public void addPrice(int productId, ProductPrice price) throws SQLException;
      public void removePrice(int productId, ProductPrice price) throws SQLException;

      public void addTag(int productId, ProductTag tag) throws SQLException;
      public void removeTag(int productId, ProductTag tag) throws SQLException;
  }

Агрегат собирается в отдельном классе играющем роль сервиса:
public class NutritionManager {
     //какой-то код

     public Product getProductById(int id) throws Exception {
          HashMap<Integer, ProductTag> tags = productTagDao.getTagsByProductid(id);
          HashMap<Integer, ProductPrice> prices = productPriceDao.getPricesByProductId(id, tags);
          return productDao.getById(id, prices);
     }
}

В чем нужна помощь: пожалуйста, покритикуйте мое решение поставленной задачи и/или предложите свое решение.


text:
Q: C++/QtTestLib programatically get number of functions in class Within my C++/QtTestLib Class, how can I get a count of the number of private functions in this class so that I can output it at runtime?

A: Something like this? (Not tested)
QObject obj ();
QMetaObject metaobject = obj.MetaObject();
int num_methods = metaobject.methodCount();
int private_methods = 0;
for (int i=0; i<num_methods; i++) {
  if (metaobject.method(i).access() == QMetaMethod::Private)
     private_methods++;
}

where instead of just QObject you have the class that you need to examine.

A: ASAIK in C++ this is not possible without third-party parser.


text:
Q: Android: Wait for the longer running process [Timer vs AsyncTask] When my app is loading data in an AsyncTask, it shows a splash screen. Sometimes this data loading takes under a second and sometimes it takes much longer. However I want to ensure that the splash is up for at least 2 seconds if the data loading finished first, or otherwise wait until the data was done.
My first solution was to use a Countdown Timer, and two boolean values. When the processes would start, their booleans would be set to true. When the process was done, it would set it's boolean false. Then it would check if the other's boolean was false, and if it was dismiss the splash.
While this works, I feel like it is overly complicated and was hoping to find a more efficient  or better solution.

A:
I want to ensure that the splash is up for at least 2 seconds if the
  data loading finished first, or otherwise wait until the data was
  done.

You can asyncronously start a Thread(Splash) and AsyncTask for Loading data and call the new Activity on onPostExecute() of you AsyncTask.

A: Could you not use System.getCurrentTime(); To accomplish this?
At the start of the AsyncTask, call that method and store the result.
then, when the task finishes, call the method again and calculate the difference in the time values. If its not greater than 2000 milliseconds, have a while loop that continually requests the system time and compare the values until its equal to or greater than 2 milliseconds.


text:
Q: Trouble to connect to bluetooth device with password I'm currently working on package bluetooth_print .
Having an issue where I could not connect to the device with password(e.g 0000).
Tried to connect on the device with no password and it will give me the error.
getBluetoothService() called with no BluetoothManagerCallback
W/System.err(28164): java.io.IOException: read failed, socket might closed or timeout, read ret: -1
W/System.err(28164):    at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:822)
W/System.err(28164):    at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:836)
W/System.err(28164):    at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:425)
W/System.err(28164):    at com.gprinter.io.BluetoothPort.openPort(BluetoothPort.java:58)
W/System.err(28164):    at com.example.bluetooth_print.DeviceConnFactoryManager.openPort(DeviceConnFactoryManager.java:156)
W/System.err(28164):    at com.example.bluetooth_print.BluetoothPrintPlugin$3.run(BluetoothPrintPlugin.java:339)
W/System.err(28164):    at com.example.bluetooth_print.ThreadPool$1.run(ThreadPool.java:78)

Is there any suggested solution / package to use ?
Need some help..


text:
Q: How to search github repository at a specific commit Is there a way to search GitHub but constrain the search to a commit or range of commits. I often find myself navigating via blame or history to a specific commit, then wanting to search around the repo at this specific point in time:

I'm surprised I can't find any similar questions on SO, maybe I'm missing something obvious or its not possible?
I tried filtering by date but that seems to only operate on commits and won't show me any "Code" results

A: You can use the standard/advanced search by adding commit: 3A+a5494cb144af5d3b6d1854c2dbe3f3fae3050b2d, for example:
https://github.com/search?q=commit%3A+a5494cb144af5d3b6d1854c2dbe3f3fae3050b2d&type=commits
Related? How can I search for a commit message on GitHub?
&type=code also works, see https://github.com/cadamini/cadamini.github.io/search?q=regex&type=code but it doesn't seem to be available in the UI (simple/advanced search). You can click Code on the search results page or edit the URL.


text:
Q: User-entered data not being saved or appearing in tableview I'm having issues trying to append a core data entity called products - I used the same code that I used to add companies, which works fine. The only difference in the app is that there is just one "static" tableview of companies I guess you could say, whereas the tableview for products is dynamically set depending on which company cell is tapped. But I'm not sure how that would cause the problem.
I've been debugging/checking values all over the app since yesterday and it seems like no matter what I try to alter, products.count in numberOfRowsInSection remains 0.
I call a function called handleSave() when the user hits a done button after entering new values in three text fields, just like with my other object companies:
func handleSave() {

    guard let newProductUrl = NSURL(string: urlTextField.text!) else {
        print("error getting text from product url field")
        return
    }
    guard let newProductName = self.nameTextField.text else {
        print("error getting text from product name field")
        return
    }
    guard let newProductImage = self.logoTextField.text else {
        print("error getting text from product logo field")
        return
    }

    self.productController?.save(name: newProductName, url: newProductUrl as URL, image: newProductImage)

    let cc = UINavigationController()
    let companyController = CompanyController()
    viewController = companyController
    cc.viewControllers = [companyController]
    present(cc, animated: true, completion: nil)

}

This then calls the save function to append products:
func save(name: String, url: URL, image: String) {

    guard let appDelegate =
        UIApplication.shared.delegate as? AppDelegate else {
            return
    }

    let managedContext =
        appDelegate.persistentContainer.viewContext

    let entity =
        NSEntityDescription.entity(forEntityName: "Product",
                                   in: managedContext)!

    let product = NSManagedObject(entity: entity,
                                  insertInto: managedContext)

    product.setValue(name, forKey: "name")
    product.setValue(url, forKey: "url")
    product.setValue(image, forKey: "image")

    do {
        try managedContext.save()
        products.append(product)
    } catch let error as NSError {
        print("Could not save. \(error), \(error.userInfo)")
    }
    tableView.reloadData()
}

And the data is fetched in viewWillAppear
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    guard let appDelegate =
        UIApplication.shared.delegate as? AppDelegate else {
            return
    }
    let managedContext =
        appDelegate.persistentContainer.viewContext

    let companyToDisplay = self.navigationItem.title!

    let fetchRequest =
        NSFetchRequest<NSManagedObject>(entityName: "Product")

    fetchRequest.predicate = NSPredicate(format:"company.name == %@",companyToDisplay)

    do {
        products = try managedContext.fetch(fetchRequest)
        print(products)
    } catch let error as NSError {
        print("Could not fetch. \(error), \(error.userInfo)")
    }
}

When this exact same process is used for adding companies, the new company then appears in the tableview. However now with products, that is not the case; the tableview remains empty. I'm not sure what the difference is and I'm not experienced enough with core data that I feel like I can figure out where the problem lies.
Huge thanks in advance to anyone that can figure this out!

A: After invoking handleSave() & before performing table.reloadData(), you need to perform db fetch operations done in viewWillAppear().
Segregate your fetchRequest logic out of viewWillAppear() into a function called (say) fetchUpdatedData().
Now, after try managedContext.save(), do a fetchUpdatedData(), update your product data arrays & then update the UI by table.reloadData()

A: Use a NSFetchedResultsController to keep your view in sync with your model. NSFetchedResultsController monitors core-data and sends a delegate message when there are updates - then you can update your tableview. Otherwise you have to manually do a refresh whenever core-data changes.


text:
Q: What is the Elasticsearch equivalent of a negated 'LIKE' or CONTAINS' statement? I would like to do the Elasticsearch equivalent of the following SQL statement:

SELECT * FROM Users WHERE UserName NOT LIKE '%something%'

I don't care about efficiency or scoring... This only gets executed on occasion. I am using request body syntax.

A: Use a normal wildcard query, and negate it using a bool must_not query.
GET Users/_search
{
    "query": {
        "bool": {
            "must_not": [{
                "wildcard": {
                    "UserName": {
                        "value": "*something*"
                    }
                }
            }]
        }

    }
}

A: I'm not sure if your Users are your index in you Elastic - but this is the main idea anyway:
You could go with the regexp query by using Complement - "~" for negation:
GET Users/_search
{
    "query": {
        "regexp":{
            "UserName": {
                "value": ".*~(something).*"
            }
        }
    }
}

For more useful reference, you can check here
P.S:
You will not get the best performance but it will do the job


text:
Q:  Infopath form link to sharepoint list with specific view where filter is user = me I have a list with the following columns:
Field: User, Family, Entity, Approved, Comments
Value: John, trade,  swap,   (blank),  (blank)
Value:  Amy, trade,  bond,   (blank),  (blank)
This list is filtered under user = [Me] in view settings.  The user is based off of a permissions group in Sharepoint called User.
I added this list to a webpart enabled page and keep it hidden.
I also created an infopath form that shows the fields and value for Family, Entity, Approved, and Comments.
So far so good.  Now, I add the Infopath form via form webpart on the webpart enabled page alongside the list with filter user =[Me] (in view settings).
This is where the problem starts.  I need the form to retrieve values from the hidden list specific to the user who opens the page (hence the user=me in list view).
So for ex:  If my name is John, when the webpart enabled page opens, the list is hidden and I see the form populate with Family=trade, entity=swap.  I can then update the values for Approved and Comments, and it updates the hidden list.
I was able to use connections in the webpart dropdown and select get form from but it displays all of the values for every user.  I am able to see Amy's updates and Amy can see my updates, even though under list view, the filter user = me is set.
What is the best way to connect an Infopath form to the list on a webpart page so a user can only see their row data and make updates to that data only?  A code free solution is much appreciated if possible.
Thanks

A: This is best done with a data connection to your SharePoint list.

*

*Create a data connection to receive data from the desired list.

*Add the desired amount of fields to your infopath form

*Add a rule to the form load event to set each field.

*

*Within each rule, set the field to the equivalent field from your data connection.

*And add a filter so that the user column from your data connection is equal to the current user of the form.

I left out a few details, but this is the basic process.  Let me know if you need a more detailed walk through.


text:
Q: A database Schema to store a content type and a sub content (ANDROID _ SQLITE :) WHAT I WANT TO ACHIEVE
=> Create an ANDROID app that shows the list of car manufacturers and the type of models they make. So when the user opens the app they see list of manufacturers. (ALL THIS DATA WILL BE LOADED FROM A DATABASE)
Like
1.Toyota
2.GMC etc..
So when they click on Toyota they will see the different cars Toyota makes (BY LOADING THEM FROM DATABASES). There would be sequence of screens displaying the different models .
SCREEN 1: Toyota Camry[A PICTURE , LITTLE DETAIL , AND A (VIDEO OR AUDIO) ]
SCREEN 2: Toyota Carina II[SAME THING HERE, (VIDEO OR AUDIO) , PICTURE AND DETAILS ABOUT CAR] etc...
So in each SCREEN there would be some kind of media related to THE CAR MODEL as shown above. A video or an audio promoting the car and some kind of text related to that model.
Now I'm downloading this information and want to save this kind of information of manufacturers and their cars in a database . I just cant come up with a good DB schema that let me safe this kind of data and let me load back to the screens .
--> If you can give me a general database schema like the number of tables I should have etc.. i would really appreciate.
SCHEMA I THOUGHT OF BUT DOESN'T LOOK GOOD
==>MANUFACTURERS TABLE[*MANUFACTURERS _ID , COMPANY_NAME , *MODELS ???HERE WHAT AM I MISSING ??? **]
==>MODELS_TABLE [*MANUFACTURERS _ID , MODEL_ID ,MODEL_NAME*]
==>RELATED MEDIA [*MODEL_ID , VIDEO_LOCATION , AUDIO_LOCATION , DETAILS_ABOUT_THE_CAR*]
AS YOU SEE AM JUST NOT GOOD WITH THE DESIGN  :/ SO PLEASE HELP , THANKS IN ADVANCE

A: Any answer to this might be slightly subjective but my personal approach would be as follows...
Two tables called MANUFACTURERS and MODELS.
For the MANUFACTURERS table I'd have the following columns...
_id, company_name

For the MODELS table I'd have the following columns...
_id, manufacturer_id, model_name, description, video_uri, audio_uri

I've used _id for both tables as an Android Cursor needs a column called _id when used with Adapters. Create _id as UNIQUE PRIMARY KEY.
I also don't think it is necessary to have a separate table for the media as it relates directly to each model of car and the data can be included directly in the MODELS table.
I've used description as a generic term instead of DETAILS_OF_CAR and used _uri for the video and audio as it implies the media may be either stored locally or on a network server.
Other people might take a different approach but from what you describe this is the way I would do things.


text:
Q: How to sort results based on join table in Rails? I have Account model,
class Account < ActiveRecord::Base
  has_many :account_games
  def score
    account_games.map(&:score).sum
  end
end

And AccountGame :
class AccountGame < ActiveRecord::Base
  belongs_to :account
end

What is the best way to get accounts with the highest score? as you can see, score is the summation of related account_games score field.
Thanks

A: try
Account.joins(:account_games).sum('account_games.score', group: :account_id, order: 'sum_account_games_score')

which will give you a hash where the keys are the account_ids and the values are the total score.
You can pass a limit option to accounts to get the top x accounts. something like
Account.limit(10).joins(:account_games).sum('account_games.score', group: :account_id, order: 'sum_account_games_score DESC')


text:
Q: Wso2am - Error in creating and login in tenants I am trying to create multiple tenants in a wso2am (1.10) installation.
When i create the tenant i get the following error "Failed to add tenant config" with the following exception
TID: [-1234] [] [2017-02-01 13:23:58,740] ERROR {org.wso2.carbon.tenant.mgt.ui.utils.TenantMgtUtil} -  Failed to add tenant config. tenant-domain: public.xxxxx, tenant-admin: admin. {org.wso2.carbon.tenant.mgt.ui.utils.TenantMgtUtil}
org.apache.axis2.AxisFault: Could not initialize class org.wso2.carbon.utils.i18n.Messages

Nevertheless when i try to enable the tenant it gets enabled and the required folders are created.
Unfortunately the tenants are not usable. On my first login i get the same exception
TID: [6] [] [2017-02-01 13:26:40,577] admin@remote.gunet [6] [AM]ERROR {org.wso2.carbon.authenticator.proxy.AuthenticationAdminClient} -  Error occurred while logging in {org.wso2.carbon.authenticator.proxy.AuthenticationAdminClient}
org.apache.axis2.AxisFault: Could not initialize class org.wso2.carbon.utils.i18n.Messages

I have tried a clean installation of the server but that had no effect.
Is there some official guideline for the specific problem?

A: Fixed the keystore and the matter was resolved.


text:
Q: Python throwing an error - String indices must be integers I'm working on my python script using the version 2.6 for XBMC media application.
I have got a problem with my python script, I'm trying to pull the data off from the sqlite3 database but I'm getting an error TypeError: string indices must be integers.
The error are jumping on this line:
programming = channelMap[row['channel']], row["title"], row["start_date"], row["stop_date"]

Here is the full code:
import xbmc
import xbmcgui
import xbmcaddon
import os
import urllib2
import StringIO
import sqlite3
from sqlite3 import dbapi2 as database
from xml.etree import ElementTree
import xml.etree.ElementTree as ET
from UserDict import DictMixin
import datetime
import time

class MyClass(xbmcgui.WindowXML):

    def onAction(self, action):

        #DOWNLOAD THE XML SOURCE HERE
        url = ADDON.getSetting('allchannels.url')
        req = urllib2.Request(url)
        response = urllib2.urlopen(req)
        data = response.read()
        response.close()
        profilePath = xbmc.translatePath(os.path.join('special://userdata/addon_data/script.tvguide', ''))

        if os.path.exists(profilePath):
           profilePath = profilePath + 'source.db'
           con = database.connect(profilePath)
           cur = con.cursor()
           cur.execute('CREATE TABLE programs(channel TEXT, title TEXT, start_date TIMESTAMP, stop_date TIMESTAMP, description TEXT)')
           con.commit()
           con.close
           tv_elem = ElementTree.parse(StringIO.StringIO(data)).getroot()
           profilePath = xbmc.translatePath(os.path.join('special://userdata/addon_data/script.tvguide', ''))
           profilePath = profilePath + 'source.db'
           con = sqlite3.connect(profilePath)
           cur = con.cursor()
           channels = OrderedDict()

           # Get the loaded data
           for channel in tv_elem.findall('channel'):
                channel_name = channel.find('display-name').text
                for program in channel.findall('programme'):
                   title = program.find('title').text
                   start_time = program.get("start")
                   stop_time = program.get("stop")
                   cur.execute("INSERT INTO programs(channel, title, start_date, stop_date)" + " VALUES(?, ?, ?, ?)", [channel_name, title, start_time, stop_time])
                   con.commit()
                   print 'Channels store into database are now successfully!'

                   cur.execute('SELECT channel, title, start_date, stop_date FROM programs')
                   programList = list()
                   channelMap = dict()
                   results = cur.fetchall()
                   cur.close

                   for channel_result in results:
                      for row in channel_result:
                         programming = channelMap[row['channel']], row["title"], row["start_date"], row["stop_date"]
                         print(programming)

I keep getting a same request of error in my XBMC log.
EDIT: When I try this:
programList = list()
channelMap = dict()
for c in channels:
if c.id:
   channelMap[c.id] = c
   strCh = '(\'' + '\',\''.join(channelMap.keys()) + '\')'
   cur.execute('SELECT * FROM programs WHERE channel')
   for row in cur:
      programming = program(channelMap[row['channel']], row["title"], row["start_date"], row["stop_date"])
      programList.append(programming)
      print(programming)

Here is the error on the xbmc log:
- NOTE: IGNORING THIS CAN LEAD TO MEMORY LEAKS!
Error Type: <type 'exceptions.TypeError'>
Error Contents: tuple indices must be integers, not str
Traceback (most recent call last):
File "C:\Users\user\AppData\Roaming\XBMC\addons\script.tvguide\test.py", line 1679, in onAction
programming = program(channelMap[row['channel']], row["title"], row["start_date"], row["stop_date"])
TypeError: tuple indices must be integers, not str
-->End of Python script error report<--

A: You are looping over each row in the result, then over each column. The columns are strings:
for channel_result in results:
    for row in channel_result:

So channel_result is a row (a tuple by default), then you loop over that with for row in channel_result. This makes each row object a single column value.
You appear to expect row to be a dictionary instead; that is not the case here. You could just print the row directly; the columns are listed in the same order as the original SELECT:
for row in results:
    programming = (channelMap[row[0]],) + row[1:]

If you really wanted a dictionary for each row, you'll have to tell sqlite3 to so by setting the row_factory attribute on the connection:
def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

con = sqlite3.connect(profilePath)
con.row_factory = dict_factory

after which you use the one loop:
for row in results:

and row will be a dictionary with keys corresponding to the column names.

A: If I see it right, the error is pretty precise. Your return value should be a list of strings. And as such, you need to user integers for indices in that line. Python just simply doesn't know what to do with row['channel'], because there's no index 'channel' defined for row.
The easiest is probably to try and print the value of row there, then you should be able to debug it.
Here are a the docs: https://docs.python.org/2/library/sqlite3.html#sqlite3.Cursor


text:
Q: Modificar intervalos de obs de variable, acorde a dummies de otras dos variables. DF. for Soy nuevo en python. Mi data es la siguiente (DataFrame):
 var1 var2 var3
  0      0   1
  0      0   1
  0      0   1
 -1      0  -1
  0      0   1
  0      0   1
  0      1   1
  0      0   1
 ...    ... ...
  0      0   1
  0      0   1
 -1      0  -1
  0      0   1
  0      0   1
 ...    ... ...

A lo que necesito llegar es a:
 var1 var2 var3
  0      0   1
  0      0   1
  0      0   1
 -1      0  -1
  0      0  -1
  0      0  -1
  0      1   1
  0      0   1
 ...    ... ...
  0      0   1
  0      0   1
 -1      0  -1
  0      0  -1
  0      0  -1
 ...    ... ...

Es decir, que después de la Dummy negativa en la columna var1, me cambia las siguientes obs de signo hasta encontrar otra dummy positiva en la columna var2 y así sucesivamente... lo intenté hacer con un for pero no termina nunca de ejecutarse. No se si habrá alguna otra forma?
for x, y in enumerate(df['var3']):
    if (df['var3'][x]!=df['var3'][x-1]) and (df['var1'][x+1]==df['var2'][x+1]):
        df['var3'][x]=df['var3'][x]*-1
    else:
        df['var3'][x]=df['var3'][x]

A: Sin asumir nada, tal como planteas el problema, se puede resolver usando simplemente condicionales y una variable bandera que indique cuando estamos dentro de un intervalo en el que debemos invertir el signo de la tercera columna (entre un valor negativo en la primera columna y el siguiente positivo en la segunda):
import io
import pandas as pd

data = io.StringIO("""\
var1 var2 var3
  0      0   1
  0      0   1
  0      0   1
 -1      0  -1
  0      0   1
  0      0   1
  0      1   1
  0      0   1
  0      0   1
  0      0   1
 -1      0  -1
  0      0   1
  0      0   1
  0      1   1
  0      0   1
""")

df = pd.read_csv(data, sep="\s+")

cambiar_signo = False
for idx in df.index:
    if cambiar_signo:
        if df.loc[idx, "var2"] > 0:
            cambiar_signo = False
        else:
            df.loc[idx, "var3"] *= -1
    else:
        if df.loc[idx, "var1"] < 0:
            cambiar_signo = True

>>> df

    var1  var2  var3
0      0     0     1
1      0     0     1
2      0     0     1
3     -1     0    -1
4      0     0    -1
5      0     0    -1
6      0     1     1
7      0     0     1
8      0     0     1
9      0     0     1
10    -1     0    -1
11     0     0    -1
12     0     0    -1
13     0     1     1
14     0     0     1

Si asumimos que la secuencia es siempre tal como se muestra en el ejemplo de la pregunta (negativo en var1 seguido de positivo en var2), es decir que no se dan situaciones como:
var1  var2
  1      0  # <<< Valor positivo en valor1
 -1      0
  0      0
 -1      0  # <<< Dos valores negativos sin intercalar positivo en var2
  0      1

var1  var2
  0      0
  0      1  # <<< Valor positivo en var2 sin que le preceda uno negativo en var1
 -1      0
  0      0
  0      1

var1  var2
  0      0
 -1      0
  0     -1  # <<< Valor negativo en var2
  0      0
  0      1

En este supuesto, podemos simplificar la cosa y vectorizar la operación usando una suma acumulativa por ejemplo:
aux = (df['var1'] + df['var2']).cumsum()
aux.loc[df["var1"] < 0] = False # La fila donde var1 tiene valor negativo no se cambia
df.loc[aux != 0, "var3"] *= -1

No importaría que los valores de las columnas var1 y var2 fueran distintos de 1 ó -1, en tal caso bastaría con usar numpy.sing previamente sobre ellas:
aux = (np.sign(df['var1']) + np.sign(df['var2'])).cumsum()
aux.loc[df["var1"] < 0] = False
df.loc[aux != 0, "var3"] *= -1


text:
Q: Unrecognized selector sent to instance using Storyboards I'm using storyboard for an iOS application, my storyboard looks like this: http://d.pr/7yAY (droplr url)
The problem is when I click the login button, I send the username captured to the events table view controller. To do that I use prepareForSegue function, but apparently when I try to set the username in throws an exception.
My code is as follows:
ViewController.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

- (IBAction) logintButton:(id)sender;
@property (weak, nonatomic) IBOutlet UITextField *username_tf; // textfield

@end

ViewController.m
#import "ViewController.h"
#import "EventsTableViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize username_tf;

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([[segue identifier] isEqualToString:@"ToMainApp"])
    {
        EventsTableViewController * dest = (EventsTableViewController *)[segue destinationViewController];
        NSString * username = [[NSString alloc] initWithFormat:@"%@", username_tf.text];
        [dest setUsername:username];
    }
}

- (IBAction) logintButton:(id)sender
{
    //NSLog(@"Logint button pressed");
    [self performSegueWithIdentifier:@"ToMainApp" sender:sender];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [self setUsername_tf:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

EventsTableViewController.h
#import <UIKit/UIKit.h>

@interface EventsTableViewController : UITableViewController
{
    NSString * username;
}

@property (nonatomic, retain) NSString * username;

@end

EventsTableViewController.m
#import "EventsTableViewController.h"

@interface EventsTableViewController ()
@end

@implementation EventsTableViewController

@synthesize username;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

...

@end

The throwed exception is:
2012-03-15 14:19:27.304 StoryboardAssistance[30989:f803]
-[UINavigationController setUsername:]: unrecognized selector sent to instance 0x68abf60 2012-03-15 14:19:27.306
StoryboardAssistance[30989:f803] *** Terminating app due to uncaught
exception 'NSInvalidArgumentException', reason:
'-[UINavigationController setUsername:]: unrecognized selector sent to
instance 0x68abf60'
*** First throw call stack: (0x13c9022 0x155acd6 0x13cacbd 0x132fed0 0x132fcb2 0x28e6 0x43e4be 0xdb5ab 0x2974 0x13cae99 0x1614e 0x160e6
0xbcade 0xbcfa7 0xbc266 0x3b3c0 0x3b5e6 0x21dc4 0x15634 0x12b3ef5
0x139d195 0x1301ff2 0x13008da 0x12ffd84 0x12ffc9b 0x12b27d8 0x12b288a
0x13626 0x253d 0x24a5) terminate called throwing an exception(lldb)

Any suggestions?

A: Another thing to verify is that you have properly assigned your destination ViewController as the proper class in Interface Builder. By default this will be UIViewController or UITableViewController etc. If you have a custom class with getters/setters, you need to remember to change the class in the Interface Builder to reflect accordingly, otherwise you will receive an invalid selector error message.

A: Your segue's destination view controller is your Navigation Controller, not your Events Table View controller.
You can get the Events controller by accessing the Navigation controller's topViewController property.
Try this:
UINavigationController *navController = (UINavigationController*)[segue destinationViewController];
EventsTableViewController *eventsController = [navController topViewController];

NSString * username = [[NSString alloc] initWithFormat:@"%@", username_tf.text];
[eventsController setUsername:username];

A: Alternatively, try this:-
(It does the same as jonkroll's answer but in one line and removes the warning "Incompatible pointer types initializing 'ViewController *__strong' with an expression of type UIViewController *"
 NameOfViewController *vc = (NameOfViewController *)[[segue destinationViewController] topViewController];


text:
Q: How to get ICompilationUnit open after getting from PackageFragment? Java Currently I am writing a plugin and one of its functions is to traverse packages and java files. I can grab the java file names but they all say that they are not open. Is there a way to open them?
Thanks in advance.

A: IComplilationUnit has IOpenable as a superinterface. Call open() on the object.


text:
Q: Soma de varios arquivos de texto *.txt Tenho uma serie de arquivos em .txt e gostaria de soma-los / juntar todos num só (Independente da ordem).
É possível fazer isso pelo vba do word, algum outro editor de texto, ou outros meios?

A: Uma maneira relativamente simples é usar o CMD do Windows.
Usando for + type:
cd /d c:\caminho\para\a\pasta
for %f in (*.txt) do type "%f" >> amalgama.out

no lugar de amalgama.out você põe o nome desejado de saída.
Não precisa nem fazer um .bat, basta executar direto no prompt de comando.
Informação relevante: eu usei .out na saída para evitar que haja dupla concatenação (adicionar o amalgama.txt nele mesmo). Qualquer extensão diferente de .txt serve, mas convém usar uma que não seja "escondida" pelo Windows. Nada que um rename não resolva ao final ;)
Usando copy:
Esta é uma alternativa mais simples, mas não força quebras de linha ao fim de cada arquivo. Pode acontecer de "colar" duas linhas se a última de algum arquivo não terminar com quebra.
cd /d c:\caminho\para\a\pasta
copy /b *.txt amalgama.out

O /b indica "binário", mas pode ser usado com .txts normalmente, para ignorar qualquer caractere especial.
De curiosidade, o /d usado nos comandos cd acima serve para mudar de unidade se necessário, evitando executar cd c: e cd \caminho separadamente, caso o prompt não esteja aberto já na unidade correta.