text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Why am I getting these errors when trying to add a UIWebView to this ViewController header file? I was following the steps here: http://matt.might.net/articles/how-to-native-iphone-ipad-apps-in-javascript/
Here are the bare bones steps to turning a web app into a native app:
*
*Open XCode.
*Create a new "View-based Application" iPhone project.
*Move the files for your web app into the Resources folder in XCode,
but strip out the cache manifest. (You don't want the manifest
screwing things up, since everything is now local.)
*Create a new instance variable, webView, inside the @interface
ViewController header file: IBOutlet UIWebView* webView ; //
IBOutlet means it's visible to Interface Builder.
*and create a property: @property (nonatomic, retain) UIWebView
*webView;
Here is what I have thus far (ViewController.h):
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
IBOutlet UIWebView* webView;
@property (nonatomic, retain) UIWebView *webView;
@end
However on step 4 I am getting two errors in my ViewController header file:
"cannot declare variable inside @interface or @protocol"
and
"iboutlet attribute can only be applied to instance variables or
properties"
So what am I doing wrong, or is that website tutorial wrong?
Note: I downloaded the sample project he had for iPhone and it worked, but I am following the tutorial so I can make an iPad version.
I am in XCode 4 and the error shows whether I do iOS 5 or iOS 4.3 doesn't seem to make a difference.
A: You're missing a couple of curly braces there:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController {
UIWebView *webView;
}
@property (nonatomic, retain) IBOutlet UIWebView *webView;
@end
A: I think you forgot the brackets; try to change your code to
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController {
IBOutlet UIWebView* webView;
}
@property (nonatomic, retain) UIWebView *webView;
@end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Combining Razor, Ajax, JSON I try to make following parts run, but always failed. The objective is: if a target in combobox is selected, the mediaId's combobox should be filled with respective values. At this moment I just emulate the values of mediaId combobox. Can anyone show me how to combine them correctly? Thx in advance.
The view Medium.cshtml:
<script src="@Url.Content("~/Scripts/PartialLoad.js")" type="text/javascript"></script>
<div class="editor-label">
@Html.LabelFor(model => model.Files[i].TargetId)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.Files[i].PTargetId, (ViewData["targets"] as SelectList).MakeSelection(Model.Files[i].PTargetId))
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Files[i].MediaId)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.Files[i].MediaId, (ViewData["mediaIds"] as SelectList).MakeSelection(1))
</div>
The javascript partialload.js
$(document).ready(function () {
$("#targets").change(function () { GetMValues("#targets", "#mediaIds"); });
});
function ClearDrop(objSource) {
$(objSource).empty();
}
function GetMValues(objSource, objDest) {
var url = '/GetMValues/';
$.getJSON(url, { id: $(objSource).val() },
function (data) {
ClearDrop(objDest); $.each(data, function (index, optionData) {
$(objDest).append("<option value='" + optionData.Value + "'>" + optionData.Text + "</option>");
});
});
}
The homecontroller.cs
public ActionResult GetMValues(String id)
{
int myId = 0;
int.TryParse(id, out myId);
var mediumIds = new List<long>();
int max = myId + 3;
// just to emulate the data in the list
for ( long l = 1 ; l < max ; l++ ){
mediumIds.Add(l);
}
var select = new SelectList(mediumIds, "PTargetId", "TargetId");
return Json(select, JsonRequestBehavior.AllowGet); //allow get needed to allow get calls
}
A: Here you are using an id selector for the dropdownlist: $("#targets") but your dropdown doesn't seem to have such id. Maybe you want to assign it an id or a class:
@Html.DropDownListFor(
model => model.Files[i].PTargetId,
(ViewData["targets"] as SelectList).MakeSelection(Model.Files[i].PTargetId),
new { id = "targets" }
)
But because this seems to be repeated and you cannot have multiple elements with the same id a class selector is probably more appropriate:
@Html.DropDownListFor(
model => model.Files[i].PTargetId,
(ViewData["targets"] as SelectList).MakeSelection(Model.Files[i].PTargetId),
new { @class = "targets" }
)
and then:
$(document).ready(function () {
$(".targets").change(function () {
...
});
});
Same remark obviously for #mediaIds.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Search XmlNode by attribute I have XmlDocument. I don't know XPath, I only know that this xml document has node named "h3" with attribute id="PortalName" and this attribute is unique for all xml document. How to find this node? I try:
XmlNode xnList = doc.SelectSingleNode("h3[@id='PortalName']");
but it does not work because it search only in root node. How to search in whole document?
Thanks
A: Fortunately that's pretty easy:
XmlNode xnList = doc.SelectSingleNode("//h3[@id='PortalName']");
The "//h3" means "any h3 element in the whole document". (See the abbreviated syntax in the XPath spec for more information.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: select columns from another table and create a column I have 2 tables
ads:
+------------+------------+-------------+
| id | width | height |
+------------+------------+-------------+
| 1 | 300 | 250 |
| 2 | 550 | 50 |
| 3 | 300 | 250 |
| 4 | 300 | 250 |
| 5 | 550 | 50 |
+------------+------------+-------------+
assigned_ads:
+------------+------------+-------------+
| id | location | ad_id |
+------------+------------+-------------+
| 1 | hp1 | 2 |
| 2 | hp2 | 3 |
| 3 | hp3 | 5 |
| 4 | hp4 | 1 |
| 5 | hp5 | 4 |
+------------+------------+-------------+
I have ad_id as a foreign key...
With PHP I will be need to output the size of the ad from ad_id but this information is held in the ads table. The information I will need is width x height. I know there's a query I can use to create an additional column with this information but for the life of me I can't remember, or find it.
Any help appreciated.
A: SELECT a.width, a.height
FROM assigned_ads aa
INNER JOIN ads a
ON aa.ad_id = a.id
WHERE aa.id = 123 -- Your value goes here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Finding missing rows in a multi-table MySQL database I've just started working on a MySQL database that somebody else put together, and I'm trying to clean it up. There are three relevant tables to my problem - a table listing auctions, a table listing the lots sold at each auction and a table listing the payment schedule for each lot.
The auctions table uses a primary key to identify each auction, and each lot has this key to identify it with the auction. Likewise, each lot has a different key, which each payment uses to identify it with the lot. Each auction should have at least one lot and each lot should have at least one payment. No payment should be attached to a lot which doesn't have a row in the lots table, and no lot should be attached to an auction which doesn't have a row in the auctions table. I'm trying to work out a query that will allow me to find the rows that break this rule - for example missing lots in the lots table or extra payments which don't have a lot attached.
At the moment I'm doing a count distinct query which gives me the number of lots/auctions mentioned in the relevant tables, but if the numbers don't match it doesn't help me find which ones are missing. Is there a query that I can use to find the rows that are missing?
Thanks
A: You could check for the keys in the related tables.
Select a.* from Auction a
Left Join Lot l on l.key = a.key
where l.key is null
or
select * from Auction a
where a.key not in (select key from lot)
something like these will help you. you'll need to change the table and column names to match and then script some for the other appropriate cases but the logic should be simmilar. hope this helps.
A: Something like,
SELECT lot.pk From lot
WHERE lot.fk NOT IN(SELECT DISTINCT(auction.pk) FROM auction)
would give you the lots attached to non existant auctions, amend as required for your other situations.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Windows transitions I am developing an iOS app using Appcelerator and I got a quick question.
How can I choose the transition animation when opening a new window? I do not
want to use the default slide to right.
This is my code that I use (single context).
tab['tab1'].open(Window.Contacts());
This works in a way, but I would like it to open in the current tab.
Window.ContactsAvatars().open({transition:Titanium.UI.iPhone.AnimationStyle.FLIP_FROM_LEFT});
Thankful for all input!
A: I suppose that your tabs group's name is tab.
Then, to force your transition style to the
tab.open({transition:Titanium.UI.iPhone.AnimationStyle.FLIP_FROM_LEFT})
if it doesn't work, then try with the following snippet while calling the window to display :
tab.activeTab.open(contactsWindow,{animated:true,{transition:Titanium.UI.iPhone.AnimationStyle.FLIP_FROM_LEFT});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: There is an error in XML document (2, 2) I have searched similar questions and still can't figure this out.
Inner Exception: {"<xml xmlns=''> was not expected."}
I am pulling the XML from an online source so cannot make changes to it.
http://api.ustream.tv/xml/user/techcrunch/listAllVideos?key=devkey
I generated the XSD file from XML using visual studio 2010. I used xsd.exe to generate the VB class.
Here is all of my code:
Form1:
Imports System.Xml
Imports System.Data
Imports System.IO
Imports System.Xml.Serialization
Public Class Form1
Private Const strURL As String = "http://api.ustream.tv/xml/user/techcrunch/listAllVideos?key=devkey"
Private Sub btnProcess_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnProcess.Click
Dim ds As New NewDataSet()
Dim myReader As TextReader = New StreamReader("../../listAllVideos.xml")
Dim serializer As New XmlSerializer(GetType(NewDataSet))
ds = DirectCast(serializer.Deserialize(myReader), NewDataSet)
myReader.Close()
End Sub
End Class
listAllVideos.xml: (shortened)
<?xml version="1.0" encoding="UTF-8"?>
<xml>
<results>
<array key="0">
<id>1916735</id>
<title><![CDATA[The TechCrunch Office live 8/2/09 04:50PM]]></title>
<protected>FALSE</protected>
<description><![CDATA[8/2/09 04:50PM PST]]></description>
<createdAt><![CDATA[2009-08-02 16:13:54]]></createdAt>
<rating>3.000</rating>
<lengthInSecond>2146.777</lengthInSecond>
<totalViews>1943</totalViews>
<codecIsForLiveHttp>0</codecIsForLiveHttp>
<serverId>992</serverId>
<videoName><![CDATA[1_170_1249254834012]]></videoName>
<url><![CDATA[http://www.ustream.tv/recorded/1916735]]></url>
<embedTag><![CDATA[<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="320" height="260" id="utv445187" name="utv_n_638715"><param name="flashvars" value="autoplay=false&vid=1916735" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.ustream.tv/flash/viewer.swf" /><embed flashvars="autoplay=false&vid=1916735" width="320" height="260" allowfullscreen="true" allowscriptaccess="always" id="utv445187" name="utv_n_638715" src="http://www.ustream.tv/flash/viewer.swf" type="application/x-shockwave-flash" /></object>]]></embedTag>
<liveHttpUrl><![CDATA[]]></liveHttpUrl>
<imageUrl>
<small><![CDATA[http://static-cdn2.ustream.tv/videopic/0/1/1/1916/1916735/1_170_1916735_120x90_b_1:1.jpg]]></small>
<medium><![CDATA[http://static-cdn2.ustream.tv/videopic/0/1/1/1916/1916735/1_170_1916735_320x240_b_1:1.jpg]]></medium>
</imageUrl>
<sourceChannel>
<id>170</id>
<url><![CDATA[http://www.ustream.tv/channel/170]]></url>
</sourceChannel>
</array>
</results>
<msg><![CDATA[]]></msg>
<error><![CDATA[]]></error>
<processTime>TRUE</processTime>
<version><![CDATA[mashery-r10]]></version>
</xml>
listAllVideos.xsd:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="xml">
<xs:complexType>
<xs:sequence>
<xs:element name="results">
<xs:complexType>
<xs:sequence>
<xs:element name="array">
<xs:complexType>
<xs:sequence>
<xs:element name="id" type="xs:unsignedInt" />
<xs:element name="title" type="xs:string" />
<xs:element name="protected" type="xs:string" />
<xs:element name="description" type="xs:string" />
<xs:element name="createdAt" type="xs:string" />
<xs:element name="rating" type="xs:decimal" />
<xs:element name="lengthInSecond" type="xs:decimal" />
<xs:element name="totalViews" type="xs:unsignedShort" />
<xs:element name="codecIsForLiveHttp" type="xs:unsignedByte" />
<xs:element name="serverId" type="xs:unsignedShort" />
<xs:element name="videoName" type="xs:string" />
<xs:element name="url" type="xs:string" />
<xs:element name="embedTag" type="xs:string" />
<xs:element name="liveHttpUrl" type="xs:string" />
<xs:element name="imageUrl">
<xs:complexType>
<xs:sequence>
<xs:element name="small" type="xs:string" />
<xs:element name="medium" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="sourceChannel">
<xs:complexType>
<xs:sequence>
<xs:element name="id" type="xs:unsignedByte" />
<xs:element name="url" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="key" type="xs:unsignedByte" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="msg" type="xs:string" />
<xs:element name="error" type="xs:string" />
<xs:element name="processTime" type="xs:string" />
<xs:element name="version" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
The VB class is really long and it won't let me post it. Thanks for your time.
Partial Public Class NewDataSet
Inherits Global.System.Data.DataSet
Private tablexml As xmlDataTable
Private tableresults As resultsDataTable
Private tablearray As arrayDataTable
Private tableimageUrl As imageUrlDataTable
Private tablesourceChannel As sourceChannelDataTable
Private relationxml_results As Global.System.Data.DataRelation
Private relationresults_array As Global.System.Data.DataRelation
Private relationarray_imageUrl As Global.System.Data.DataRelation
Private relationarray_sourceChannel As Global.System.Data.DataRelation
Private _schemaSerializationMode As Global.System.Data.SchemaSerializationMode = Global.System.Data.SchemaSerializationMode.IncludeSchema
A: I don't think an xml element can have the name "xml" can it?
http://www.w3.org/TR/xml/#sec-common-syn
[Definition: A Name is an Nmtoken with a restricted set of initial characters.] Disallowed initial characters for Names include digits, diacritics, the full stop and the hyphen.
Names beginning with the string "xml", or with any string which would match (('X'|'x') ('M'|'m') ('L'|'l')), are reserved for standardization in this or future versions of this specification.
A: The problem is that your NewDataSet class would match XML starting with <NewDataSet>, but you're passing XML that starts with <xml>. That's why it's unexpected.
Either wrap the XML with <NewDataSet></NewDataSet>, or else generate your classes by using the xsd /c command, which will only generate "plain" classes and not a dataset.
A: All of your XML Elements are correctly formatted. You can place this in an XML format validator such as OygenXML or your favorite XML Editor to validate that. The issue is with your values, you will need to encode the special characters correctly. This is a list of XML's special set of characters that cannot be used in normal XML strings. These characters are:
1. & - &
2. < - <
3. > - >
4. " - "
5. ' - '
You will want to format the values correctly in order to get beyond this error. I suggest using looping through the values and using System.Security.SecurityElement.Escape(stringValue); to encode the values.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: request.form for dropdownlist value i need to get value of selected item of dropdownlist using Post Method (request.form).
request.form["DropDownList"];
how can i get selectedvalue ,selectedindex or selecteditem.text ....
A: Try this (assuming the ID of your DropDownList is DropDownList1:
Request.Form[DropDownList1.UniqueID]
A: This way you can obtain a selected value.
string value=Request.Form["DropDownList1"];
A: With the method you are requesting. It can't be done.
That being said. If you are doing a Cross Page Postback, then that is one case where you can access the previous pages objects in it. Otherwise, if you don't have that type of control, then, you likely can't get to them.
In simple terms, you'd do a form on Page1.aspx like so
<form PostBackUrl="~/Page2.aspx" runat="server" id="frm">
On Page2.aspx, along with some other code, using the PreviousPage, you can do something like so:
((DropDownList)Page.PreviousPage.FindControl("DropDownList")).SelectedValue;
References:
How to: Post ASP.NET Web Pages to a Different Page
Cross-Page Posting in ASP.NET Web Pages
A: You can obtains the value from
Request.Form["DropDownList1"]
but if the ID of the drop down list is not static, you can do this..
Create a temporary static variable in some global.cs file
public class Global
{
public static string ddlID="";
}
and in .aspx.cs file where the drop down list is place.
Global.ddlID = DropDownList1.UniqueID
and on post pack
if (this.Request.Form["__EVENTTARGET"] == Globals.ddlID) {
//Perform action here, This postback is caused by **DropDownList1**
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: GWT in IE8 - Exception thrown and not caught in file *cache.html & but after reloading the page it works I was reading some posts about this error but it looks like that none of them have the same error.
My application runs perfectly in chrome and firefox but today I got shocked when I realized that it didn't work in IE8.
Now comes the really fun part. When I access the application with IE8, I just see a blank page (and the sign indicating an error at the bottom left), but when I refresh the website it works!!
So I think it must be something with the cache of IE. Because when I clear the cache, then it works for one time. When I enter the address in the browser again, it doesn't work anymore. After reloading the page it works again.
I found out that the
problem should be something with RPC calls.
So if a RPC call is being executed I get the java script error. Then I
reload the the site and execute the RPC call again => it works.
I hope someone can help me further.
A: So after all it looks like that using the slider of the jquery library produces the whole problem. Maybe jquery throws the exception but it get's handled when a RPC call is done...
Furthermore it looks like that when jquery is being cached by the browser it produces the error.
So after days of figuring out a solution I replaced the handsome jquery slider with a smartgwt slider.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Simulating Errors on the Amazon FPS sandbox I've set up my Amazon flexible payments sandbox account and have been using the PHP library to simulate accepting payments and what not.
I was just wondering if anyone knew of a way to simulate realistic error conditions I would expect to encounter, such as what happens when someone runs a card that gets declined.
The API guide does tell you what status codes will be returned, and something tells me I just have to trust them, but I always like to test as much as possible if possible.
A: A link to the answer is in the comments here, but it wouldn't hurt to have an actual answer with a summary. There's details about simulating error conditions in the testing sandbox in the advanced quick start guide.
The following errors can be simulated by setting the value for SenderTokenId:
Closed account: Z1LGRXR4HMDZBSFKXELA32KZASGWD8IHMHZCK4DETR784LDLD1GMFW4P3WT8VTGX
Email address not verified: E3FR7BARJV3PB631PMKV74PGKCJLBHI1Q1KMQN7BJ2JJICPDKN3N1CJIKFZ8D7NN
Suspended account: H216UECZ8ZM1G8G4QA3V7RKF8JDFZ9SI3SJAFSGUKBBNDHX1NVM8GUQRZNRNAHER
The following errors can be simulated by setting the value for RecipientTokenId:
Closed account: P1LL7A1LHK935DBGI5NAYCXOCLVEBHBNIU7PBXBAMRKKNLDEPI8M3MUSLZT2VANZ
Email address not verified: C4LGSEMXN11FTUXZ2X2C7QVFHN5DVBGQJNF17AIQXXXQSX4DRG4KJFCN2KRFUUZI
Suspended account: R3VK49XVGCAZTJSXKN7ZSBHPMFGKM5VEEQTXGMVE8CFUZ2G5RLLMAB4J6TQRL6BU
And finally, setting the amount value such that it includes a decimal value between the following values will simulate the following errors:
Temporary Decline: .60 to .69
Payment Error: .70 to .89
Unfortunately, that last detail may be out of date. This page seems to imply that having 7 or 8 after the decimal point will create the terribly generic "Failure". From testing, I can confirm that 0.6 does lead to a temporary failure (status is stuck in "Pending" for a while before eventually advancing to "Success"), and 0.7 and 0.8 result in the same "TransactionDenied" error.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Tomcat 7: Filter access log I'd like to know if there is a way to filter/supress entries from getting logged in the access log in Tomcat 7. Our logfile is groing rapitly and we'd like to know if we can filter out entries so the file doesn't grow as fast as it is doing right now.
We use the Access Log Valve as described in the Tomcat configuration documentation. The entry looks like this:
<Valve className="org.apache.catalina.valves.AccessLogValve"
directory="logs" prefix="localhost_access_log." suffix=".txt"
pattern="%h %l %u %t "%r" %s %b" resolveHosts="false" />
A: You can use "condition" attribute to filter out requests based on request attributes.
Details : http://tomcat.apache.org/tomcat-5.5-doc/config/valve.html#Access_Log_Valve/Attributes
You can subclass "org.apache.catalina.valves.AccessLogValve" to implement more specific filter.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Doc editor in JSP I'm developing a web application which has the need of a powerful .doc editor.
The user has to select a document template (normally a .doc file) filled with placeholders, and through some macros fill the placeholders with the correct values (maybe picked from a db).
I proposed my boss to let the user download the template, edit it with his desktop application (MS Word, OpenOffice Writer, ecc) but the boss wants it online and inside the jsp page.
To me it seems I have only two choices: applet or javascript (I'm aware of these two only, there are tons of other techologies I don't know).
The flow would be:
*
*the user selects a template from the server
*the client pc downloads the template chosen and loads it in the web editor
*the user edits the template
*the user sends the edited file to the server
*the server saves the file
I saw these two wsyiwyg editors (ckeditor and tinymce) but I didn't find .doc support (neither .odt).
Do you know any other plugin I could use to achieve this result?
Thank you!
A: Convert DOC to RTF or whatever format supported by those WYSISYG editors and then convert it back upon submit. There are some free Java APIs available which can salvage Word documents.
*
*Apache POI HWPF/XWPF (both .doc and .docx)
*OpenOffice.org UNO (only .docx)
*Docx4J (only .docx)
A: Sounds like you have your answer already but in case it's useful, I've seen a dev project using Docmosis to work with templates in DOC format. Docmosis does an analysis looking for fields and sections in the template and stores that somewhere in a Java object. You can get hold of it and use it as the basis for generating Web forms etc dynamicall - based on the doc template itself!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C#: Properties Map Is there a PropertiesMap in C# which exposes methods like GetDouble(string), GetDateTime(string), etc..?
IDictionary<string,string> forces users to take care of type conversion.
A: Yes there is ExpandoObject and it has a very clean syntax.
dynamic propertyMap = new ExpandoObject();
var item = propertyMap as IDictionary<String, object>;
item["A"] = DateTime.Now;
item["B"] = "New val 2";
propertyMap.C = 1234
Console.WriteLine(propertyMap.A);
Console.WriteLine(propertyMap.B);
Console.WriteLine(propertyMap.C);
A: You can use Convert, it can handle a lot of the conversions you will need.
Convert.ToDateTime(string value) //about 7 overloads
Convert.ToInt32(string value)
Convert.ToDouble(string value)
It has a lot of options for conversions, with plenty of overloads.
A: You can use the Dictionary class and add extension methods for all data types that you wanr to have Get method, or add a generic Get method and use it:
public static class Extensions
{
public static T Get<T>(this Dictionary<string, object> dictionary, string key)
{
if (dictionary == null)
{
throw new ArgumentNullException("dictionary");
}
if (key == null)
{
throw new ArgumentNullException("key");
}
return (T)dictionary[key];
}
}
You even can create alias for the Dictionary<string, object> type:
using PropertiesMap = System.Collections.Generic.Dictionary<string, object>;
And usage of this:
PropertiesMap pm = new PropertiesMap { { "1", 1 }, { "2", DateTime.Now }};
Console.WriteLine(pm.Get<int>("1"));
Console.WriteLine(pm.Get<DateTime>("2"));
A: Can you use Convert.ToXXX? Not sure what your question has to do with IDictionary<string, string> though...
See this MSDN page.
A: A Dictionary<string,object> can store anything without conversion. However you will have to cast when retrieving the values:
var dict = new Dictionary<string,object>();
dict.Add("Name", "John");
dict.Add("Age", 20);
...
string name = (string)dict["Name"];
int age = (int)dict["Age"];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why does my Perl script produce corrupted output with large files on Windows? I am new to Perl and am having a very weird print issue.
The Perl program runs on Windows XP. It first executes a SQL then loops through the results and outputs to 5 files via 5 sub routines. The 5 files are to be loaded up to a database, so it uses | as the delimiter. Each sub routine will have something like the following.
print outfile $array[field1] . '|' . $array[field2] . '|' . $array[field3] . "\n";
The weird thing is sometimes the program outputs OK. Sometimes, the output is corrupted, e.g. line feed is missing after some point, or the values from array are not correct.
I am wondering if it is something to do with memory. The output file sizes ranges from 500MB to 9GB. The program does read the output from SQL one record at a time and write one record at a time too.
Here is the complete Perl script.
#!/usr/bin/perl
use DBI;
use DBD::Oracle;
# Constants:
use constant field0 => 0;
use constant field1 => 1;
use constant field2 => 2;
use constant field3 => 3;
use constant field4 => 4;
use constant field5 => 5;
use constant field6 => 6;
use constant field7 => 7;
use constant field8 => 8;
use constant field9 => 9;
use constant field10 => 10;
use constant field11 => 11;
use constant field12 => 12;
use constant field13 => 13;
use constant field14 => 14;
use constant field15 => 15;
use constant field16 => 16;
use constant field17 => 17;
use constant field18 => 18;
use constant field19 => 19;
use constant field20 => 20;
use constant field21 => 21;
use constant field22 => 22;
use constant field23 => 23;
use constant field24 => 24;
use constant field25 => 25;
use constant field26 => 26;
use constant field27 => 27;
use constant field28 => 28;
use constant field29 => 29;
use constant field30 => 30;
use constant field31 => 31;
use constant field32 => 32;
use constant field33 => 33;
use constant field34 => 34;
use constant field35 => 35;
use constant field36 => 36;
use constant field37 => 37;
use constant field38 => 38;
use constant field39 => 39;
use constant field40 => 40;
use constant field41 => 41;
# Capture Directory Path from Environment Variable:
my $DIRECTORY = $ENV{DATADIR};
# Process Counters:
my %fileCntr = (
ccr1 => 0,
ccr2 => 0,
ccr3 => 0,
ccr4 => 0,
ccr5 => 0
);
# Process Control Hashes:
my %xref = ();
# Process Control Variables:
my $diag = 0;
my $proc = 0;
my $ndcc = 0;
my $previous = "";
# Claims Extract array:
my @arr = ();
my $hdr = "";
# Accept/Parse DSS Connection String:
$ENV{PSWD} =~ /(.+)\/(.+)\@(.+)/;
my $USER = $1;
my $PASS = $2;
my $CONN = 'DBI:Oracle:' . $3;
# ALTER Date format:
my $ATL = qq(ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD');
# Database Connection:
my $dbh = DBI->connect( $CONN, $USER, $PASS, { RaiseError => 1, AutoCommit => 0 } );
$dbh->do($ATL); # Execute ALTER session.
my $SQL = qq(
SELECT ... here is a big sql query
);
# Open OUTPUT file for CCR processing:
open OUT1, ">$DIRECTORY/ccr1.dat" or die "Unable to open OUT1 file: $!\n";
open OUT2, ">$DIRECTORY/ccr2.dat" or die "Unable to open OUT2 file: $!\n";
open OUT3, ">$DIRECTORY/ccr3.dat" or die "Unable to open OUT3 file: $!\n";
open OUT4, ">$DIRECTORY/ccr4.dat" or die "Unable to open OUT4 file: $!\n";
open OUT5, ">$DIRECTORY/ccr5.dat" or die "Unable to open OUT5 file: $!\n";
# Redirect STDOUT to log file:
open STDOUT, ">$DIRECTORY/ccr.log" or die "Unable to open LOG file: $!\n";
# Prepare $SQL for execution:
my $sth = $dbh->prepare($SQL);
$sth->execute();
# Produce out files:
{
local $, = "|";
local $\ = "\n";
while (@arr = $sth->fetchrow_array)
{
# Direct Write of CCR1&2 records:
&BuildCCR12();
# Write and Wipe CCR3 HASH Table:
&WriteCCR3() unless ($arr[field0] == $previous);
&BuildCCR3();
# Loop processing for CCR4:
&BuildCCR4();
# Loop processing for CCR5:
&BuildCCR5();
}
}
# Print Record Counts for OUTPUT files:
foreach my $key (keys %fileCntr) { print "$key: " . $fileCntr{$key} . "\n"; }
# Terminate DB connection:
$sth->finish();
$dbh->disconnect();
# Close all output files:
close(OUT1); close(OUT2); close(OUT3);
close(OUT4); close(OUT5);
{
# Reassign Output End-of-record across subroutine block:
local $\ = "\n";
sub BuildCCR12
{
# Write CCR1 Table:
print OUT1 $arr[field6] . '|' . $arr[field7] . '|' . $arr[field5] . '|' .
$arr[field0] . '|' . $arr[field8] . '|' . $arr[field9] . '|' .
$arr[field10] . '|' . $arr[field11] . '|' . $arr[field12] . '|' .
$arr[field13] . '|' . $arr[field2] . '|' . $arr[field3] . '|' .
$arr[field40] . '|' . $arr[field16];
$fileCntr{ccr1}++;
# Write CCR2 Table:
unless ($arr[field17] eq '###########') {
print OUT2 ++$ndcc . "|" . $arr[field0] . "|" .
$arr[field6] . '|' . $arr[field7] . '|' .
$arr[field17] . '|' . $arr[field19] . '|' . $arr[field18] . '|' .
$arr[field2] . '|' . $arr[field3] . '|' . $arr[field39];
$fileCntr{ccr2}++;
}
}
sub WriteCCR3
{
unless ($previous == "")
{
# Produce ccr3 from DISTINCT combo listing:
foreach $key (keys %xref) { print OUT3 $xref{$key}; $fileCntr{ccr3}++; }
%xref = ();
}
}
sub BuildCCR3
{
# Spin off relationship:
for (my $i = field8; $i <= field13; $i++)
{
unless ($arr[$i] == -1)
{
$xref{$arr[field0] . "|" . $arr[$i]} = $arr[field0] . "|" . $arr[$i];
}
}
$previous = $arr[field0];
}
sub BuildCCR4
{
# Spin off relationship:
for (my $i = field26; $i <= field37; $i++)
{
my $sak = $arr[field0] . $arr[field6] . $arr[field7] . $arr[$i];
unless (($arr[$i] eq '#######') or ($arr[$i] eq '######')) {
print OUT4 ++$diag . '|' . $arr[field0] . '|' .
$arr[field6] . '|' .
$arr[field7] . '|' . $arr[$i];
$fileCntr{ccr4}++;
}
}
}
sub BuildCCR5
{
# Spin off field0/Procedure relationship:
for (my $i = field20; $i <= field23; $i++)
{
my $sak = $arr[field0] . $arr[field6] . $arr[field7] . $arr[$i];
unless ($arr[$i] eq '######' or $arr[$i] eq '####') {
print OUT5 ++$proc . '|' . $arr[field0] . '|' . $arr[field6] . '|' .
$arr[field7] . '|' . $arr[$i];
$fileCntr{ccr5}++;
}
}
}
}
The issue is with CCR3 output. After some point, the line feed disappears for some reason, and data got corrupted as if the line feed ate some of the output. Starting that point, it becomes 1 continuous line.
3260183|147845
3260183|78246
3260183|13898
3260183|184783
3260183|116315
3260183|184483262216|105843262217|1461703262217|175593262217|1360303262217
Another thing is this program will run close to 26 hours and while looping through the sql, is there any chance, the data can get messed up ? But it still won't explain why suddenly line feed does not work any more.
A: I tried to reduce clutter. First, the constants you define create a lot of clutter instead of helping with readability. If you had something like
use constant LICENSE_NO => 42;
I would understand, but if the constants are just going to correspond to integer array indices, then I don't see the point.
I also put all printing in a separate subroutine and added error checking to print and close statements.
I do not claim any of this is a solution to your problem, but this is where I would begin to actually debug. There might be some typos here, so watch out.
#!/usr/bin/perl
use warnings; use strict;
use DBI;
use File::Spec::Functions qw( catfile );
my @proc = qw(ccr1 ccr2 ccr3 ccr4 ccr5);
# Capture Directory Path from Environment Variable:
my $DIRECTORY = $ENV{DATADIR};
# Process Counters:
my %fileCntr = map { $_ => 0 } @proc;
# Process Control Hashes:
my %xref = ();
# Process Control Variables:
my $diag = 0;
my $proc = 0;
my $ndcc = 0;
my $previous = "";
# Claims Extract array:
my @arr = ();
my $hdr = "";
# Accept/Parse DSS Connection String:
my ($USER, $PASS, $CONN) = ($ENV{PSWD} =~ m{^(.+)/(.+)\@(.+)});
# ALTER Date format:
my $ATL = qq(ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD');
# Database Connection:
my $dbh = DBI->connect(
"DBI::Oracle:$CONN", $USER, $PASS,
{ RaiseError => 1, AutoCommit => 0 },
);
$dbh->do($ATL); # Execute ALTER session.
my $SQL = qq(
SELECT ... here is a big sql query
);
my %outh;
for my $proc ( @proc ) {
my $fn = catfile $DIRECTORY, "$proc.dat";
open $outh{ $proc }, '>', $fn
or die "Cannot open '$fn' for writing: $!";
}
# Redirect STDOUT to log file:
open STDOUT, '>', catfile($DIRECTORY, 'ccr.log')
or die "Unable to open LOG file: $!";
# Prepare $SQL for execution:
my $sth = $dbh->prepare($SQL);
$sth->execute();
# Produce out files:
while (my @arr = $sth->fetchrow_array) {
# Direct Write of CCR1&2 records:
BuildCCR12(\@arr);
# Write and Wipe CCR3 HASH Table:
WriteCCR3(\@arr) unless ($arr[0] == $previous);
BuildCCR3(\@arr);
# Loop processing for CCR4:
BuildCCR4(\@arr);
# Loop processing for CCR5:
BuildCCR5(\@arr);
}
# Print Record Counts for OUTPUT files:
foreach my $key (keys %fileCntr) {
printf "%s: %s\n", $key, $fileCntr{$key};
}
# Terminate DB connection:
$sth->finish();
$dbh->disconnect();
for my $proc (keys %outh) {
close $outh{ $proc } or die "Cannot close filehandle for '$proc': $!";
}
sub print_to {
my ($dest, $data) = @_;
my $fh = $outh{$dest};
print $fh join('|', @$data), "\n"
or die "Error writing to '$dest' file: $!";
$fileCntr{$dest}++;
return;
}
sub BuildCCR12 {
my ($arr) = @_;
print_to(ccr1 =>
[@{$arr}[6, 7, 5, 0, 8, 9, 10, 13, 2, 3, 40, 16]]);
if ($arr->[17] ne '###########') {
print_to(ccr2 =>
[++$ndcc, @{ $arr }[0, 6, 7, 17, 19, 18, 2, 3, 39]]);
}
return;
}
sub WriteCCR3 {
my ($arr) = @_;
unless ($previous) {
# Produce ccr3 from DISTINCT combo listing:
print_to(ccr3 => [ keys %xref ]);
%xref = ();
}
return;
}
sub BuildCCR3 {
my ($arr) = @_;
# Spin off relationship:
for my $i (8 .. 13) {
unless ($arr->[$i] == -1) {
my $k = join '|', @{ $arr }[0, $i];
$xref{ $k } = $k;
}
}
$previous = $arr->[0];
return;
}
sub BuildCCR4 {
my ($arr) = @_;
# Spin off relationship:
for my $i (26 .. 37) {
my $sak = join '|', @{ $arr }[0, 6, 7, $i];
my $v = $arr->[$i];
unless ( $v =~ /^#{6,7}\z/ ) {
print_to(ccr4 => [++$diag, @{ $arr }[0, 6, 7, $v]]);
}
}
return;
}
sub BuildCCR5 {
my ($arr) = @_;
# Spin off field0/Procedure relationship:
for my $i (20 .. 23) {
my $v = $arr[$i];
my $sak = join('', @{ $arr }[0, 6, 7], $v);
unless ($v eq '######' or $v eq '####') {
print_to(ccr5 => [++$proc, @{ $arr }[0, 6, 7], $v]);
}
}
return;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Application symbols not showing up while time profiling iPhone app in XCode 4 I'm doing some time profiling XCode 4 but I can never seem to get the application symbols showin up in the call tree in Instruments. I'm only getting system calls.
I thought this might be from doing something wrong like not generating debug symbols but after ensuring they were enabled the problem still seems to be persisting for me. This has been working for me in XCode 3.x but I've never been able to get it to work in XCode 4. Has anyone experienced this type of behaviour before or can perhaps tell me what I might be missing?
A: The solution for this problem is pretty much as outline in this post referred to by John in comments...
Xcode 4 failure to symbolicate Crash Log
For me to get things to work I used...
mdimport ~/Library/Developer/
to have spotlight re-index the entire "Developer" folder in my user directory which is maybe a bit of overkill? Could've used mdimport ~/Library/Developer/XCode I suppose but I figure why not do one folder up.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Making a string out of array of arrays Sorry for asking probably a basic question, but I'm having a blackout.
If I have an array of arrays:
Array
(
[appsversion] => Array
(
[0] => appsversion='6.1.0.33'
[1] => appsversion='6.1.0.40'
),
[osversion] => Array
(
[0] => osversion='6.1.0.53'
[1] => osversion='6.1.0.42'
)
)
how do I please construct an SQL condition with OR and AND of it?
I.e. for something like:
$condition = '';
foreach ($CONDITIONS as $key => $value) {
# XXX I'm so lost here XXX
}
$sql = sprintf('select %s from mytable where %s', $condition);
$sth = $pg->prepare($sql);
$sth->execute();
I need the constructed string
(appsversion='6.1.0.33' OR appsversion='6.1.0.40') AND
(osversion='6.1.0.53' OR osversion='6.1.0.42')
or:
appsversion in ('6.1.0.33', '6.1.0.40') AND
osversion in ('6.1.0.53', '6.1.0.42')
Please give me few hints - to get my brain started again :-)
A: There:
$where = array();
foreach ($conditions as $values) {
$where[] = '('.implode(' OR ', $values).')';
}
$string = implode(' AND ', $where);
Yields:
(appsversion='6.1.0.33' OR appsversion='6.1.0.40') AND (osversion='6.1.0.53' OR osversion='6.1.0.42')
A: You mean something like this?
$condition = "(appsversion = '" . implode("' OR appsversion = '", $conditions['appsversion']) . "')";
$condition .= " AND (osversion = '" . implode("' OR osversion = '", $conditions['osversion']) . "')";
Or, cleaner with IN:
$condition = "appsversion IN ('" . implode("', '", $conditions['appsversion']) . "')";
$condition .= " AND osversion IN ('" . implode("', '", $conditions['osversion']) . "')";
A: In case your original array does not duplicate the key names and provides values "as-is" (I somehow misread your question, but probably it's useful):
$conditions = array(
'appsversion' => Array('6.1.0.33', '6.1.0.40'),
'osversion' => Array('6.1.0.53', '6.1.0.42'),
);
foreach ($conditions as $key => &$values) {
foreach($values as &$value)
$value = sprintf("%s='%s'", $key, $value);
$values = sprintf("(%s)", implode(' OR ', $values));
}
unset($values, $value);
echo implode(" AND \n", $conditions);
Output/Demo:
(appsversion='6.1.0.33' OR appsversion='6.1.0.40') AND
(osversion='6.1.0.53' OR osversion='6.1.0.42')
A: $conditions1 = array();
foreach ($CONDITIONS['appsversion'] as $value) {
$conditions1[] = sprintf("appversion = '%s'", mysql_real_escape_string($value));
}
$conditions2 = array();
foreach ($CONDITIONS['osversion'] as $value) {
$conditions1[] = sprintf("osversion = '%s'", mysql_real_escape_string($value));
}
$sql = sprintf('select %s from mytable where (%s) AND (%s)', $cols, implode(' OR ', $conditions1), implode(' OR ', $conditions2));
$sth = $pg->prepare($sql);
$sth->execute();
A: foreach($C as $key => $value)
{
$str .= ($str ? ' AND ' : '') . '(' . implode(' OR ',$value) . ')';
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rails: Dates without Hyphens I'd like to accept date params without hyphens, such as 20110929. In Rails/Ruby, how can I convert this to a DateTime object? Do I need to edit the string manually, adding the appropriate hyphens, or is there some magic I'm not aware of?
Thanks guys!
EDIT:
Answered my own question, but unfortunately I can't accept it yet (low reputation):
DateTime.parse('20110929')
EDIT 2:
As pointed out below, my above "answer" is probably not the best. See accepted answer below.
A: In Ruby 1.9.2 you can use #strptime. In some cases, if the date format to parse is common, #parse should work as well.
require 'date'
require 'time'
DateTime.strptime("20110929", "%Y%m%d")
# => #<DateTime: 2011-09-29T00:00:00+00:00 (4911667/2,0/1,2299161)>
A: You might want to use Date.strptime(params[:the_date], '%y%m%d'). See the apidock.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: view the changed values after an update statement just wondering if it is possible to view the changes of an update command on a table after it has happened?
would the transaction log store this kind of information i.e this is the previous/current value this is the new/changed value
not sure if this is possible. the server is ms sql 2008
A: you can use OUTPUT to insert the changes into another table and/or return a result set of the changes:
set nocount on
DECLARE @Table table (PK int, col1 varchar(5))
DECLARE @SavedPks table (PK int)
INSERT INTO @Table VALUES (1,'g')
INSERT INTO @Table VALUES (2,'g')
INSERT INTO @Table VALUES (3,'g')
INSERT INTO @Table VALUES (4,'g')
INSERT INTO @Table VALUES (5,'x')
INSERT INTO @Table VALUES (6,'x')
set nocount off
UPDATE @Table
SET col1='xyz'
OUTPUT INSERTED.PK INTO @SavedPks --save in a table
OUTPUT 'result set',INSERTED.PK, INSERTED.col1 AS new_col1, DELETED.col1 AS old_Col1 --result set
WHERE col1='g'
select * from @Table
select * from @SavedPks
OUTPUT:
PK new_col1 old_Col1
---------- ----------- -------- --------
result set 1 xyz g
result set 2 xyz g
result set 3 xyz g
result set 4 xyz g
(4 row(s) affected)
PK col1
----------- -----
1 xyz
2 xyz
3 xyz
4 xyz
5 x
6 x
(6 row(s) affected)
PK
-----------
1
2
3
4
A: The transaction log does contain the information, although decoding it is not trivial - I wrote a blog post with an example of decoding a simple update statement in the transaction log - http://sqlfascination.com/2010/02/21/decoding-a-simple-update-statement-within-the-transaction-log/
However, depending on the update being performed the entries in the log get a lot more complex and there is no documentation available on how to decode them. Reverse engineering them is quite difficult.
I would never recommend that this technique of inspecting the log is used to retrieve data, it is only worth looking into from an internals learning perspective / forensic perspective.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: windows phone 7.5 mango app size limit What is the size limit for an mango windows phone app?
i know that the size limit for a NoDo app is 225 mb. Does the limit remain?
A: As far as I know yes, there havent been any announcements I came across that addressed different limits for your App Sizes,
http://msdn.microsoft.com/en-us/library/hh184844(v=VS.92).aspx
however there have been changes made to the amount of memory they are allowed to use on devices with 256mb or less the limit is 90mb of RAM and I am unsure how high the limit would be for devices with more than 256mb or RAM
http://msdn.microsoft.com/en-us/library/hh184840(v=VS.92).aspx
There is no Limit on the space of files taken in IsolatedStorage, ApplicationStorage which is temporary can be up to 4mb in size and will be lost when the application is Closed
A: The maximum size of the XAP package file is 225 MB. I haven't seen any changes in this from Microsoft.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to get horizontal edges between nodes of two or more clusters? I have to clusters A and B with 3 nodes each. I need to connect nodes between clusters in a bipartite way.
This code:
digraph G {
subgraph cluster_A {
style=filled;
color=lightgrey;
edge [style=invisible,dir=none];
node [style=filled,color=white];
a1 -> a2 -> a3;
}
subgraph cluster_B {
style=filled;
color=lightgrey;
edge [style=invisible,dir=none];
node [style=filled,color=white];
b1 -> b2 -> b3;
}
a1 -> b1;
a2 -> b2;
a3 -> b3;
}
does almost what I want with dot but cluster B is not at the same level as cluster A. It is offset by some amount below A.
How can I prevent this offset and have both clusters at the same level?
A: For this particular graph, you could use
edge[constraint=false];
to not have the edges between the nodes influence the layout:
digraph G {
subgraph cluster_A {
style=filled;
color=lightgrey;
edge [style=invisible,dir=none];
node [style=filled,color=white];
a1 -> a2 -> a3;
}
subgraph cluster_B {
style=filled;
color=lightgrey;
edge [style=invisible,dir=none];
node [style=filled,color=white];
b1 -> b2 -> b3;
}
edge[constraint=false];
a1 -> b1;
a2 -> b2;
a3 -> b3;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Overloading a Rails module's class method in .irbrc I have a Rails 3 app with a presenter that lives in lib. The relevant part looks like:
lib/channels/channel.rb:
module Channels
class Channel
def current_user
ApplicationController.current_controller.try(:current_or_guest_user)
end
def self.find_by_key(key)
@@channels.find { |c| c.key == key.to_sym }
end
private
def self.class_initialize
@@channels = []
Dir.glob("#{Rails.root}/lib/channels/channel_defs/*.rb").each do |f|
require_dependency f
@@channels << "Channels::#{File.basename(f, '.rb').camelize}".constantize.new
end
end
class_initialize
end
end
lib/channels/channel_defs/activity.rb
module Channels
class Activity
def current_user
ApplicationController.current_controller.try(:current_or_guest_user)
end
def accessible?
current_user.registered_user?
end
end
end
ApplicationController.current_controller is a hack so our presenter can get to helpers; we set it to self in a before_filter. This of course doesn't work in console, and I want to be able to work with Channel.accessible? in console, so I tried overriding the method like so in .irbrc:
module Channels
class Channel
class << self
puts "in irbrc"
def current_user
User.find(475)
end
end
end
end
And it seems to work when called directly:
ruby-1.9.2-p290 :002 > Channels::Channel.current_user
=> #
But not when called from a channel itself:
Channels::Channel.find_by_key(:activity).accessible?NoMethodError: undefined method `registered_user?' for nil:NilClass
from /Users/jay/.rvm/gems/ruby-1.9.2-p290/gems/activesupport-3.0.9/lib/active_support/whiny_nil.rb:48:in `method_missing'
from /Users/jay/src/tiptap/2t2/lib/channels/channel_defs/activity.rb:16:in `accessible?'
from (irb):1
This is probably either something about the eigenclass vs the class, or something about the timing of loading Channels::Channel. I've tried adding a require channels/channel in .irbrc before we reopen the class, but that doesn't do it... ideas?
A: In development mode the model classes are defined as temporary copies and re-defined on reload! which can make extensions like this unreliable or ineffective.
It's better to layer this sort of hackery in as some kind of configuration option. For instance:
def current_user
ENV['USER_ID'] ? User.find(ENV['USER_ID']) : ApplicationController.current_controller.try(:current_or_guest_user)
end
This way you can start up with any user you'd like:
USER_ID=475 rails console
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: cocos2d. How to create a popup modal dialog (with CCLayer) I need to make a modal dialog(inherited from CCLayer) that is showing in the center of the main layer.
While it is showing, you can not press any other button outside the dialog.
Just like a normal modal window in MS Windows System.
The problem is that I can not figure out how to disable the mainlayer's touch events while the dialog is showing.
Any help would be aprreciated.
A: Just set
self.isTouchEnabled = NO;
in the main layer while the popup is displayed. Then later set it back to YES.
A: This works for me in Cocos2d-x but can be adapted to Cocos2d too.
I've change setParent to:
virtual void setParent(CCNode* parent)
{
CCLayerColor::setParent(parent);
if (parent)
{
saveTouchesRecursive(parent);
for (unsigned int i=0; i<mSavedTouches.size(); i++)
{
CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(mSavedTouches[i]);
}
}
else
{
for (unsigned int i=0; i<mSavedTouches.size(); i++)
{
CCStandardTouchDelegate* standardTouchDelegate = dynamic_cast<CCStandardTouchDelegate*>(mSavedTouches[i]);
CCTargetedTouchDelegate* targetedTouchDelegate = dynamic_cast<CCTargetedTouchDelegate*>(mSavedTouches[i]);
CCLayer* layer = dynamic_cast<CCLayer*>(mSavedTouches[i]);
if (layer)
{
layer->registerWithTouchDispatcher();
}
else if (standardTouchDelegate)
{
CCDirector::sharedDirector()->getTouchDispatcher()->addStandardDelegate(mSavedTouches[i], 0);
}
else if (targetedTouchDelegate)
{
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(mSavedTouches[i], 0, false);
}
else
{
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(mSavedTouches[i], 0, false);
}
}
}
}
And added the following recursive code to save the touch delegates so I can restore them when the dialog dismissed:
std::vector<CCTouchDelegate*> mSavedTouches;
void saveTouchesRecursive(CCNode* node)
{
if (node != this)
{
CCTouchDelegate* touchDelegate = dynamic_cast<CCTouchDelegate*>(node);
if (touchDelegate)
{
CCTouchHandler* handler = CCDirector::sharedDirector()->getTouchDispatcher()->findHandler(touchDelegate);
if (handler)
{
mSavedTouches.push_back(touchDelegate);
}
}
for (unsigned int i=0; i<node->getChildrenCount(); i++)
{
CCNode* childNode = dynamic_cast<CCNode*>(node->getChildren()->objectAtIndex(i));
if (childNode)
{
saveTouchesRecursive(childNode);
}
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Django.contrib.auth Unit tests fail with AUTHENTICATION_BACKENDS enabled I'm having an issue getting the django.contrib.auth unit tests shipped with Django (1.2.3-3+squeeze1) to pass once an AUTHENTICATION_BACKENDS is set. There are other posts such as Unit testing with remote authentication and How to Unit test with different settings in Django? in regards to fixing, however my tests are still failing with these suggestions.
I've tried adding the following to my SetUP() and TearDown() methods to get around this.
from django.conf import settings
def setUp(self):
self.old_backend = settings.AUTHENTICATION_BACKENDS
settings.AUTHENTICATION_BACKENDS = None
def tearDown(self):
settings.AUTHENTICATION_BACKENDS = self.old_backend
Anyone have any other suggestions for getting around this? Thanks in advance.
Here is a paste of the tracebacks. http://pastebin.com/xX4dmuzr
A: I was incorrect. Adding this hack to the setUP and tearDown methods to each individual class did work. Going to reach out to the community to find out if this is an actual bug.
A: You can find the bug and a patch here: https://code.djangoproject.com/ticket/13394. I am using 1.3.1 version of django and that patch was not applied yet (don't know why, since it was created a few months ago). I applied manually and it worked!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: End Conversation in Seam when the user leaves the page Is there some way to end a conversation in Seam 2 when the user leaves the page? I know, that I can of course end a conversation in the navigation rules( see this post), but I want to end a conversation when the user enters an url in the address bar of the browser.
Could this be achieved via Javascript (for example with onbeforeunload)? But how to stop a conversation via javascript?
A:
I want to end a conversation when the user enters an url in the
address bar of the browser.
Could this be achieved via Javascript (for example with
onbeforeunload)? But how to stop a conversation via javascript?
You could use JavaScript to implement an onbeforeunload event and use AJAX to communicate the user leaving to the site and end all your conversations. However, I don't recommend you this solution because you cannot rely on a event happening on the browser, Javascript is not a good option, since you can disable it client-side (Not only that, but the browser may crash, the network connection may drop, etc..)
I think an alternative aproach to do this is by setting a seam conversation timeout on the server. You can try and reduce the timeout in order to close inactive conversation faster, when the user leave your page.
Configuring the conversation-timeout period can be accomplished through the following in your components.xml:
<core:manager conversation-timeout="700000" />
Notice that conversation-timeout only affects background conversations, foreground conversation will only timeout when the session times out which is relevant for your requirements.
More information about conversation time out can be found in this article.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Objective-C – Working with subviews I'm a bit confused. I'm subclassing a UITableViewCell to create my own design of a cell. In the -initWithStyle: method I'm setting up some UILabels like so:
self.careerTitleLabel = [[UILabel alloc] init];
[self.contentView addSubview:careerTitleLabel];
[self.careerTitleLabel release];
Then to position the label I do this in -layoutSubviews like so:
CGRect careerTitleLabelFrame = CGRectMake(10, 10, 280, 20);
self.careerTitleLabel.frame = careerTitleLabelFrame;
This code actually works. It positions my label where I want it to be positioned. But what I don't understand is HOW this works. As I'm just modifying the frame of the careerTitleLabel ivar and not the careerTitleLabel that has been added as a subView to the contentView.
My assumption would be that to modify the frame of the label that I had added to the contentView I would have to pull it out by using -viewWithTag: and then modify that frame. Right now I'm merely modifying an ivar of the class?
P.S Another cliffhanger not related to this question is why does self.careerTitleLabel have a retainCount of 2 after being released? D.S
A: addSubview: doesn't copy the view you pass it, it retains it. So when you release it, it isn't actually deallocated. It's kept alive because self.contentView is still using it. That means that your reference to self.careerTitleLabel later on still works, though I think most would consider it bad style on the grounds that you should keep owning references to any objects you intend to message later rather than imputing knowledge from ownership patterns used elsewhere.
retainCount is never to be relied on absolutely. It's also opaque how much addSubview: will increase the retain count by, other than that it'll be at least 1. That said, the most likely reason if you've declared careerTitleLabel as a property and have a line like:
NSLog(@"%d", [self.careerTitleLabel retainCount]);
Is that the standard getter is:
return [[careerTitleLabel retain] autorelease];
So the retain count is temporarily increased by the getter, the reasoning being that the results of getters should live at least as long as the autorelease pool — even if the object from which you got them is deallocated before then.
A: careerTitleLabel is a pointer to an object. So when you do addSubview: careerTitleLabel, the code you call maintains a reference to careerTitleLabel.
Later, when you set the frame on careerTitleLabel in layoutSubviews, you are updating that same object.
layoutSubviews is absolutely the right place to do this. It's called automatically at the start, and again if the view bounds change. For example if the device's orientation changes.
viewWithTag is another way to access a subview. Personally I consider it cleaner to maintain an ivar. Don't forget you can use IBOutlets to hook up these things using Interface Builder.
Finally, you do have a memory issue and this explains the retain counts. It's good to run Analyze frequently to pick up these issues, and also profile with Instruments using Leaks. You can even set a flag in your build settings to always run Analyze every time you build.
Anyway here's the issue:
self.careerTitleLabel = [[UILabel alloc] init];
If your property in the .h file is set up like:
@property (nonatomic, retain)
then you will over-retain here. You will retain twice and this will cause memory issues.
Apple guidelines recommend you never call these setters in an init method. At that stage behaviour can be unpredictable as you could be going through a custom setWhatever method whilst your object has not yet completed it's init.
Much safer to just have:
careerTitleLabel = [[UILabel alloc] init];
Even better, in your .h file prefix this with an "m" for member variable. Then you'll have
mCareerTitleLabel = [[UILabel alloc] init];
In your synthesize, use:
synthesize careerTitleLabel = mCareerTitleLabel;
That will mean that from outside - or inside - your code, you can access this as:
self.careerTitleLabel
or
myObjectName.careerTitleLabel
I hope this helps! It's a lot to cover!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599292",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Intercept all current and future links Just wondering if there is a way with jquery to intercept a link when clicked. The problem is that some of the links on my page are not loaded when the page is first loaded. I have a vague recollection of hearing that jquery has a way of intercepting all current and future links. Here is the code I have. It works on all links there were there at the start but the links that were loaded onto the page later are not getting intercepted by this function
$('a').trackClick({
areaClick: function(element) { return getAreaClicked(element); },
href: function(element) { return getHrefFromElement(element); },
text: function(element) { return getTextFromElement(element); },
exceptions: function(element) { return isException(element); }
});
A: [edit: I get the occasional upvote on this answer, so I wanted to update it with more current (as of May 2015) practice]:
Per my original answer, delegating the listener is a better practice. The current "best practice" syntax for jQuery is .on(). It differs only in the order, and to me is more semantically intuitive:
$('#parent').on('click', 'a', function(event) {
event.preventDefault();
// do the rest of your stuff
}
The rest of my original answer still applies.
If you don't want the default click behaviour, you also need to stop the event bubbling. I prefer delegate over live, so here's my suggestion:
$('#parent').delegate('a', 'click', function(event) {
event.preventDefault();
// do the rest of your stuff
});
The "#parent" is just a sample. You would use any appropriate selector that's going to be a permanent ancestor of your anchor tags. Could even go up as high as "body", but often a wrapper ID of some description works as well.
[edit: I've seen an upvote recently which means this answer is being seen by someone out there. It should be noted that .live() is now deprecated, and although .delegate() is supported, the officially suggested syntax is .on() used as a delegator:
$('#parent').on('click', 'a', function(event) {
event.preventDefault();
// do the rest of your stuff
});
A: You need jquery Live see here : http://api.jquery.com/live/
$('a').live('click', function(e){
var element = $(this);
var data = {areaClick: function(element) { return getAreaClicked(element); },
href: function(element) { return getHrefFromElement(element); },
text: function(element) { return getTextFromElement(element); },
exceptions: function(element) { return isException(element); }
}
trackClick(data);
});
A: Use jQuery's live event handler:
$('a').live('click', function() {
...
});
A: The simplest option is to use jQuery's live() method, although that is fairly expensive. If possible, delegate() is a better option, and there are a couple posts here that describe the difference between the two:
Jquery live() vs delegate()
jQuery: live() vs delegate()
Generally the best option is to simply bind whatever you need to to the new <a> elements that are loaded via AJAX. For example:
$.ajax({
url: 'http://example.com'
type: 'GET'
data: 'whatever'
success: function(data){
//after inserting the response somewhere...
$('.insertedContent').find('a'.trackClick({
areaClick: function(element) { return getAreaClicked(element); },
href: function(element) { return getHrefFromElement(element); },
text: function(element) { return getTextFromElement(element); },
exceptions: function(element) { return isException(element); }
});
}
}
A: As has been said, the answers recommending .live() and .delegate() are out of date.
I had a similar problem: I had various click handlers in play already on various elements, but I wanted to add an additional click handler to catch everything and to possibly take action before the others.
My use-case for this was wanting various tools in a web-app to "reset" to default state when other tools were clicked.
Here is my solution...
$(document).on("click", function(e){
// This catches all clicks.
// It can be suppressed if the target uses e.stopPropagation()
});
// To start the bubbling from an element "higher" than the document,
// then use delegation, e.g.:
// $(document).on("click", ".your_class", function(e){ etc })
// This can be really useful if you only have one sensitive area in the layout,
// or you want different "master" click behaviours for different areas!
$("#my_element").on("click", function(e){
// prevent the default action, e.g. prevent "#" navigation on <a href="#">
e.preventDefault();
// prevent the click bubbling to the $(document) handler
e.stopPropagation();
// now do my stuff
// ...
});
$("#my_other_element").on("click", function(e){
// prevent the default action, e.g. prevent "#" navigation on <a href="#">
e.preventDefault();
// this time I want the "catch all" to fire
// so I don't do stopPropagation()
// now do my stuff
// ...
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Best solution for automated testing in a multiple application scenario I'm trying to choose automated UI testing tools for the following scenario, with 4 applications:
*
*app 1 one application with a WEB UI
*app 2 one flex application
*app 3 one html5 application
*app 4 one application with a WPF UI
So, ideally, I'm looking for a all-in-one solution. Something that can handle the tests for both WEB (apps 1, 2 and 3) and WPF (app 4), like SilkTest, TestComplete and Seapine QA Wizard.
However, app 4 will soon disappear, and the need for testing it will too. Leaving me with only WEB UI applications. In that scenario I'd go with Selenium, no question here.
So,
Question 1: Would you recommend the all-in-one solution, even knowing that in the future it'll only be used to test WEB applications? If so, what tool do you think it's best?
Question 2: If I choose to go with Selenium for the web apps, I still need something to test the WPF one. I'm looking at Project White. Would it be the best tool for the job, or should I look at something else?
A: I think you're setting yourself up for alot for pain if you try and find a one-fits-all-solution for this sort of problem.
You should definitely use Selenium to cover off the web stuff. I've yet to see an automated testing framework that's more functional or easier to pick up than Selenium (and it's various subprojects). That's the right solution for the web apps.
A particular consideration is that if you're making the automation investment for the long term, you don't want to saddle yourself with a sub-standard tool just because it supports web and WPF apps. Given that you'll eventually be getting rid of the WPF app, make that testing requirement secondary for now. Over the long term, the majority of your effort will go to testing the products, so use the best tool for that (in my opinion, Selenium).
As for the WPF app, there are probably some fairly decent tools available (I recall an HP rep saying that they were looking at getting WPF test automation into their enterprise testing suite).
Bottom line, you're looking at two very different sets of needs so finding a common test tool will be difficult. Use the best solution for each job and save yourself headaches down the line.
A: One advantage of an all-in-one solution is that there is only one learning curve for all technologies. You mentioned that app 4 (using WPF) will go away soon, but you may want to determine if other technologies will be used by your company in the future.
QA Wizard has worked well for me. The status tool allows me to remotely monitor results. QA Wizard also offers load testing and stress testing functionality which makes it a powerful tool.
A: I think a Gherkin-based language such as Cucumber or Specflow would be really helpful here. I'm assuming that most of the functionality should work similarly across each platform, so you should be able to write a single set of scenarios describing the behaviour at a sufficiently high-level, and then implement different step definitions for each platform, e.g.
*
*Selenium for the web or HTML 5 versions
*wipflash for WPF
*FunFX for Flex
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get PHP to execute a function only following successful completion of a download? I have the feeling this should be quite basic, but I've failed to find a solution anywhere.
I'm working on an application that sends out an email to admins when a file is downloaded. Currently the email is sent out when a download begins, but I need to change this so that it only sends when the download is completed.
I suspect something like PHP's register_shutdown_function might be what I need, but according to the PHP manual shutdown functions are now called before the request is completed. Which leaves me a bit stumped.
For what it's worth, the function that currently handles downloads outputs them like this:
readfile($path);
exit;
The site in question is pretty large and complicated, so ideally I'd like to make as little change to the current code as possible. Any advice on how to solve this problem would be very much appreciated! Thanks.
A: readfile() returns the number of bytes read or false if there was an error.
$ret = readfile($path);
if($ret && $ret != 0) {
// send e-mail
}
exit();
A: readfile($path);
mail('admin@example.com', 'Download completed', 'download be done, mon');
exit();
The readfile call will block the script until the file's been loaded and output to the webserver. Note that there is no way for a PHP script to detect if the client has actually successfully downloaded the file. The file itself will be cached partially by the webserver, and PHP's involvement ends when the webserver's cache absorbs the entire file. That means the user can abort the download (or a network glitch kills it), yet you'll still get notified that a download was completed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is it correct to put a Winsocket connect() and send() in a loop? i'm trying to figure out if i'm doing something wrong with this application i'm coding.
The goal of the app is to detect if an embedded devices connected on the same LAN disconnect. A common issue on which i read a lot here on stackoverflow.
Since this embedded devices has a webserver running on the default port, the idea was to create an infinite loop and continuosly send a message on that port. If i detect an error i assume that the host is disconnected.
However after a lot of research, packet sniffing on the lan and so on, i've found that putting a send() in an infinite loop wasn't the same as if you call it for the 1st time. The reason is that when you create a socket and call a send for the first time, it does the TCP HANDSHAKE and then send the message. But, in the same loop, when send is called again, there's no HANDSHAKE and the message is simple sent. So if i disconnect the embedded devices in this moment, the sent will return again a success and only after several attempts it fails. A similiar situation happens with the recv(). So my actual solution was to put in an infinite loop THE ENTIRE process of socket (creation,connection,send,destruction). Here's what i made in the end:
while(true){
SOCKET ConnectSocket = INVALID_SOCKET;
ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ConnectSocket == INVALID_SOCKET) {
cout <<"socket failed with error: "<< WSAGetLastError();
WSACleanup();
return 0;
}
iResult= ioctlsocket(ConnectSocket,FIONBIO,&ulMode);
if (iResult != NO_ERROR)
cout<<"ioctlsocket failed with error: "<<iResult<<endl;
iResult= setsockopt(ConnectSocket,SOL_SOCKET,SO_REUSEADDR,(char *) &bOptVal,bOptLen);
if (iResult == SOCKET_ERROR) {
wprintf(L"setsockopt for SO_REUSEADDR failed with error: %u\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
} else
wprintf(L"Set SO_REUSEADDR: ON\n");
iResult= setsockopt(ConnectSocket,SOL_SOCKET, SO_LINGER, (char FAR*)&linger, sizeof(linger));
if (iResult == SOCKET_ERROR) {
wprintf(L"setsockopt for SO_LINGER failed with error: %u\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
} else
wprintf(L"Set SO_LINGER: ON\n");
if(connect( ConnectSocket,(SOCKADDR*) &saServer, sizeof(saServer))==SOCKET_ERROR){
cout <<WSAGetLastError()<<endl;
if(WSAGetLastError() == WSAEWOULDBLOCK)
{
fd_set fsConnect;
FD_ZERO(&fsConnect);
FD_SET(ConnectSocket, &fsConnect);
timeval sTimeoutVal;
sTimeoutVal.tv_sec = (long)2;
sTimeoutVal.tv_usec = (long)0;
int retval = select(FD_SETSIZE, (fd_set *) NULL, &fsConnect, (fd_set *)
NULL, &sTimeoutVal);
if(retval != 1)
{
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
} else{
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
}
int iBytes = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
shutdown(ConnectSocket,SD_SEND);
closesocket(ConnectSocket);
if(iBytes == -1 || iBytes != (int)strlen(sendbuf))
{
//send failed machine went down
WSACleanup();
return 1;
}
Sleep(1000);}
Basically the program works fine. Since it iterates every second, i don't know if it's actually correct from a O.S. perspective cause i don't know if this way i'm doing something wrong. Moreover, i noticed that a lot of open ports remained in a TIME_WAIT status so for this reason i flag every time the socket as SO_REUSEADDR and as SO_LINGER. I have ~200 open ports in time wait after 3/4 hours of running this app.
Is it correct? Should i follow another, maybe, simpler way?
Thanks all! ;)
A: If you just checking for web server existence, there is no reason to send anything: connect() alone is enough to ensure target is alive at least on network stack level.
To be extra sure about target state you can ask something useful from web server and check result. It will put slightly more load on server but can be done with single connection, if server supports persistent HTTP connections. You better use some HTTP client library is this case: correctly implementing client-side may be tricky.
TIME_WAIT is ok, it's normal condition and this states will gradually timeout.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: list USB device with specified VID and PID without using Windows driver Kit is there a way to find a USB device with specified VID and PID on windows without involve calling to WDK functions?
A: Here's a simplified version of Guo Yanchao's code:
unsigned index;
HDEVINFO hDevInfo;
SP_DEVINFO_DATA DeviceInfoData;
TCHAR HardwareID[1024];
// List all connected USB devices
hDevInfo = SetupDiGetClassDevs(NULL, TEXT("USB"), NULL, DIGCF_PRESENT | DIGCF_ALLCLASSES);
for (index = 0; ; index++) {
DeviceInfoData.cbSize = sizeof(DeviceInfoData);
if (!SetupDiEnumDeviceInfo(hDevInfo, index, &DeviceInfoData)) {
return false; // no match
}
SetupDiGetDeviceRegistryProperty(hDevInfo, &DeviceInfoData, SPDRP_HARDWAREID, NULL, (BYTE*)HardwareID, sizeof(HardwareID), NULL);
if (_tcsstr(HardwareID, _T("VID_1234&PID_5678"))) {
return true; // match
}
}
A: The code below will do the trick:
static const char dongleVid[] = {'1', '2', '3', '4', '\0'};
static const char donglePid[] = {'5', '6', '7', '8', '\0'};
static const LPCTSTR arPrefix[3] = {TEXT("VID_"), TEXT("PID_"), TEXT("MI_")};
const std::string requiredVid = boost::to_upper_copy(std::string(arPrefix[0]) + std::string(dongleVid));
const std::string requiredPid = boost::to_upper_copy(std::string(arPrefix[1]) + std::string(donglePid));
unsigned i, j;
DWORD dwSize, dwPropertyRegDataType;
OSVERSIONINFO osvi;
CONFIGRET r;
HDEVINFO hDevInfo;
SP_DEVINFO_DATA DeviceInfoData;
TCHAR szDeviceInstanceID[MAX_DEVICE_ID_LEN];
TCHAR szDesc[1024];
LPTSTR pszToken, pszNextToken;
TCHAR szVid[MAX_DEVICE_ID_LEN], szPid[MAX_DEVICE_ID_LEN], szMi[MAX_DEVICE_ID_LEN];
#ifdef UNICODE
FN_SetupDiGetDeviceProperty fn_SetupDiGetDeviceProperty = (FN_SetupDiGetDeviceProperty)
GetProcAddress(GetModuleHandle(TEXT("Setupapi.dll")), "SetupDiGetDevicePropertyW");
#else
FN_SetupDiGetDeviceProperty fn_SetupDiGetDeviceProperty = (FN_SetupDiGetDeviceProperty)
GetProcAddress(GetModuleHandle(TEXT("Setupapi.dll")), "SetupDiGetDevicePropertyA");
#endif
// List all connected USB devices
hDevInfo = SetupDiGetClassDevs(NULL, TEXT("USB"), NULL, DIGCF_PRESENT|DIGCF_ALLCLASSES);
if (hDevInfo == INVALID_HANDLE_VALUE)
{
return false;
}
// Find the ones that are driverless
for (i = 0; ; i++)
{
DeviceInfoData.cbSize = sizeof(DeviceInfoData);
if (!SetupDiEnumDeviceInfo(hDevInfo, i, &DeviceInfoData))
{
break;
}
r = CM_Get_Device_ID(DeviceInfoData.DevInst, szDeviceInstanceID , MAX_PATH, 0);
if (r != CR_SUCCESS)
{
continue;
}
SetupDiGetDeviceRegistryProperty(hDevInfo, &DeviceInfoData, SPDRP_DEVICEDESC,
&dwPropertyRegDataType, (BYTE*)szDesc,
sizeof(szDesc), // The size, in bytes
&dwSize);
// Retreive the device description as reported by the device itself
memset(&osvi, 0, sizeof(OSVERSIONINFO));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
pszToken = _tcstok_s(szDeviceInstanceID , TEXT("\\#&"), &pszNextToken);
szVid[0] = TEXT('\0');
szPid[0] = TEXT('\0');
szMi[0] = TEXT('\0');
while (pszToken != NULL)
{
for (j = 0; j < 3; j++)
{
if (_tcsncmp(pszToken, arPrefix[j], lstrlen(arPrefix[j])) == 0)
{
switch (j)
{
case 0:
_tcscpy_s(szVid, ARRAY_SIZE(szVid), pszToken);
break;
case 1:
_tcscpy_s(szPid, ARRAY_SIZE(szPid), pszToken);
break;
case 2:
_tcscpy_s(szMi, ARRAY_SIZE(szMi), pszToken);
break;
default:
break;
}
}
}
pszToken = _tcstok_s(NULL, TEXT("\\#&"), &pszNextToken);
}
std::string foundVid = boost::to_upper_copy(std::string(szVid));
std::string foundPid = boost::to_upper_copy(std::string(szPid));
if (requiredVid == foundVid && requiredPid == foundPid)
{
return true;
}
}
A: Yes you can, you have all the necessary functions in Win32 API in user32.dll and setuapi.dll. This is a little C# sample:
internal static bool FindUsbDevice(string vendorId, string productId,
ref string deviceDesc, ref string deviceInstanceId, ref Guid classId)
{
bool returnValue = false;
string enumeratorClass = "USB";
IntPtr szClass = Marshal.StringToHGlobalAuto(enumeratorClass);
Guid classGuid = Guid.Empty;
IntPtr deviceInfoSet = new System.IntPtr();
try
{
deviceInfoSet = DeviceManagement.SetupDiGetClassDevs(ref classGuid, szClass, IntPtr.Zero,
DeviceManagement.DIGCF_ALLCLASSES | DeviceManagement.DIGCF_PRESENT);
DeviceManagement.SP_DEVINFO_DATA spDevInfoData = new DeviceManagement.SP_DEVINFO_DATA();
spDevInfoData.cbSize = Marshal.SizeOf(spDevInfoData);
for (int i = 0; DeviceManagement.SetupDiEnumDeviceInfo(deviceInfoSet, i, ref spDevInfoData); i++)
{
int nSize = 0;
string DeviceInstanceId = new string('0', 259);
IntPtr ptrDeviceInstanceId = Marshal.StringToHGlobalAuto(DeviceInstanceId);
if (!DeviceManagement.SetupDiGetDeviceInstanceId(deviceInfoSet, ref spDevInfoData, ptrDeviceInstanceId,
DeviceInstanceId.Length, ref nSize))
{
Console.WriteLine("SetupDiGetDeviceInstanceId() error");
continue;
}
DeviceInstanceId = Marshal.PtrToStringAnsi(ptrDeviceInstanceId);
if (!DeviceInstanceId.Contains(string.Format("USB\\VID_{0}&PID_{1}", vendorId, productId)))
continue;
returnValue = true;
deviceInstanceId = DeviceInstanceId;
classId = spDevInfoData.ClassGuid;
int DataT = 0;
string buffer = new string('0', 259);
IntPtr pBuffer = Marshal.StringToHGlobalAuto(buffer);
int bufferSize = 259;
if (!DeviceManagement.SetupDiGetDeviceRegistryProperty(
deviceInfoSet, ref spDevInfoData, DeviceManagement.SPDRP_DEVICEDESC,
ref DataT, pBuffer, bufferSize, ref bufferSize))
{
if (Marshal.GetLastWin32Error() == DeviceManagement.ERROR_INVALID_DATA)
Debug.WriteLine("Error invalid data");
else
Debug.WriteLine("error");
}
else
{
buffer = Marshal.PtrToStringAnsi(pBuffer, bufferSize);
deviceDesc = buffer;
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
DeviceManagement.SetupDiDestroyDeviceInfoList(deviceInfoSet);
}
return returnValue;
}
while the wrapper code is:
public sealed partial class DeviceManagement
{
///<summary >
// API declarations relating to device management (SetupDixxx and
// RegisterDeviceNotification functions).
/// </summary>
// from dbt.h
internal const Int32 DBT_DEVICEARRIVAL = 0X8000;
internal const Int32 DBT_DEVICEREMOVECOMPLETE = 0X8004;
internal const Int32 DBT_DEVTYP_DEVICEINTERFACE = 5;
internal const Int32 DBT_DEVTYP_HANDLE = 6;
internal const Int32 DEVICE_NOTIFY_ALL_INTERFACE_CLASSES = 4;
internal const Int32 DEVICE_NOTIFY_SERVICE_HANDLE = 1;
internal const Int32 DEVICE_NOTIFY_WINDOW_HANDLE = 0;
internal const Int32 WM_DEVICECHANGE = 0X219;
// from setupapi.h
internal const Int32 DIGCF_PRESENT = 2;
internal const Int32 DIGCF_DEVICEINTERFACE = 0X10;
internal const Int32 DIGCF_ALLCLASSES = 0x4;
internal const Int32 SPDRP_FRIENDLYNAME = 0xC;
internal const Int32 SPDRP_DEVICEDESC = 0x0;
internal const Int32 SPDRP_CLASSGUID = 0x8;
// from WinError.h
internal const Int32 ERROR_INSUFFICIENT_BUFFER = 122;
internal const Int32 ERROR_INVALID_DATA = 13;
// Two declarations for the DEV_BROADCAST_DEVICEINTERFACE structure.
// Use this one in the call to RegisterDeviceNotification() and
// in checking dbch_devicetype in a DEV_BROADCAST_HDR structure:
[StructLayout(LayoutKind.Sequential)]
internal class DEV_BROADCAST_DEVICEINTERFACE
{
internal Int32 dbcc_size;
internal Int32 dbcc_devicetype;
internal Int32 dbcc_reserved;
internal Guid dbcc_classguid;
internal Int16 dbcc_name;
}
// Use this to read the dbcc_name String and classguid:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal class DEV_BROADCAST_DEVICEINTERFACE_1
{
internal Int32 dbcc_size;
internal Int32 dbcc_devicetype;
internal Int32 dbcc_reserved;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.U1, SizeConst = 16)]
internal Byte[] dbcc_classguid;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 255)]
internal Char[] dbcc_name;
}
[StructLayout(LayoutKind.Sequential)]
internal class DEV_BROADCAST_HDR
{
internal Int32 dbch_size;
internal Int32 dbch_devicetype;
internal Int32 dbch_reserved;
}
internal struct SP_DEVICE_INTERFACE_DATA
{
internal Int32 cbSize;
internal System.Guid InterfaceClassGuid;
internal Int32 Flags;
internal IntPtr Reserved;
}
internal struct SP_DEVICE_INTERFACE_DETAIL_DATA
{
internal Int32 cbSize;
internal String DevicePath;
}
internal struct SP_DEVINFO_DATA
{
internal Int32 cbSize;
internal System.Guid ClassGuid;
internal Int32 DevInst;
internal Int32 Reserved;
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern IntPtr RegisterDeviceNotification(IntPtr hRecipient, IntPtr NotificationFilter, Int32 Flags);
[DllImport("setupapi.dll", SetLastError = true)]
internal static extern bool SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet, int MemberIndex, ref SP_DEVINFO_DATA DeviceInfoData);
[DllImport("setupapi.dll", SetLastError = true)]
internal static extern bool SetupDiGetDeviceInstanceId(IntPtr DeviceInfoSet, ref SP_DEVINFO_DATA DeviceInfoData, IntPtr DeviceInstanceId, int DeviceInstanceIdSize, ref int RequiredSize);
[DllImport("setupapi.dll", SetLastError = true)]
internal static extern bool SetupDiGetDeviceRegistryProperty(IntPtr DeviceInfoSet, ref SP_DEVINFO_DATA DeviceInfoData, int Property, ref int PropertyRegDataType, IntPtr PropertyBuffer, int PropertyBufferSize, ref int RequiredSize);
[DllImport("setupapi.dll", SetLastError = true)]
internal static extern Int32 SetupDiCreateDeviceInfoList(ref System.Guid ClassGuid, Int32 hwndParent);
[DllImport("setupapi.dll", SetLastError = true)]
internal static extern Int32 SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet);
[DllImport("setupapi.dll", SetLastError = true)]
internal static extern Boolean SetupDiEnumDeviceInterfaces(IntPtr DeviceInfoSet, IntPtr DeviceInfoData, ref System.Guid InterfaceClassGuid, Int32 MemberIndex, ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData);
[DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
internal static extern IntPtr SetupDiGetClassDevs(ref System.Guid ClassGuid, IntPtr Enumerator, IntPtr hwndParent, Int32 Flags);
[DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
internal static extern Boolean SetupDiGetDeviceInterfaceDetail(IntPtr DeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData, IntPtr DeviceInterfaceDetailData, Int32 DeviceInterfaceDetailDataSize, ref Int32 RequiredSize, IntPtr DeviceInfoData);
[DllImport("user32.dll", SetLastError = true)]
internal static extern Boolean UnregisterDeviceNotification(IntPtr Handle);
}
Hope it helps, you should quickly translate it into Visual C++
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Beginner Questions about Android 3D I am doing an academic project, which involves learning android and i needed to know the following details about android OS capabilities along with any good free and open-source 3D rendering API
*
*Can i display a sphere,cone, a sphere (divided into different positions) ... i want it more like a 3D Graph
*Can i display a 3D Terrain Map
*Can i move the camera 360 degrees, i.e i want to be able to see my models from all angles from just the swipe of a finger
*Can i connect to a remote server on a website and pull/push data through usual POST/GET methods?
*Can i mix the normal XML based android display with the 3D display, or should i open it in a different screen(aka full screen).
Please correct me if i am wrong anywhere, need to know the above things before i take up this project for sure. Helpful links would be appreciated.
A: I would recommend checking out the Google IO video on Android 3D rendering http://www.youtube.com/watch?v=YLVbLVtjDDw
A: Android SDK already comes with OpenGL which is a free and open source 3D rendering API.
*
*Yes, of course.
*Yes. You'll have to model it yourself of course.
*Yes, AFAIK that's what 3D is all about...
*Yes, of course, why it would be otherwise?
*Yes. You can divide the display with the usual XML layout, but 3D must be drawn over a special surface (GLSurfaceView).
Check here for more detailed information.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Javascript: replace string function not working in IE7-8 I've created a JSFiddle that shows my program:
http://jsfiddle.net/8Fx3a/10/
As you'll see when a user types in the input field and clicks 'go' the program will try to find that value in the list of links and highlight the word in yellow (by adding a span element around the word and giving it a class of 'highlight').
If a user checks for another word the existing spans are all removed and new ones are put in place.
It is this removeSpan function that is not working IE7-8. It will successfully highlight the relevant words but it won't remove the existing spans if the user enters another value.
Does anyone know what the problem might be here?
A: Some points:
Changing your regExp from /^\s+/ to /^\s+|\s+$/g might be useful as it will trim trailing whitespace, too.
Change if (text_input === "") { to if (removeSpaces === "") { otherwise you get horrible results if you just enter a space.
Why are you declaring the functions highlight, removeSpan and addSpan when you only call them in one place? Just put their code where you call them (unless, of course, you want to use them elsewhere, too).
Why are you creating the temporary vars newstr and newstr2? Just reassign the result of the anchor_text.replace() call back into anchor_text.
Pass regexes in the replace function instead of strings.
Implementing all of these changes, we get:
document.getElementById('check-list').onclick = function() {
text_input = document.search.search_list.value.replace(/^\s+|\s+$/g, "");
if (text_input.length) {
var anchor = document.getElementById('results').getElementsByTagName('a');
var alength = anchor.length;
for (var x = 0; x < alength; x++) {
var anchor_text = anchor[x].innerHTML;
anchor_text = anchor_text
.replace(/<span class="highlight">/gi, "")
.replace(/<\/span>/gi, "");
anchor[x].innerHTML = anchor_text;
var re = new RegExp(text_input, "gi");
if (anchor_text.search(re) !== -1) {
anchor_text = anchor_text.replace(re, "<span class='highlight'>$&</span>");
anchor[x].innerHTML = anchor_text;
}
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: C# opening unavailable network path with Process.Start() I'm opening directories over network using:
System.Diagnostics.Process.Start(path); // path = UNC network path
But having 2 network paths:
\\This_PC_Does_Not_Exist\dir
\\This_PC_Is_Turned_Off\dir
How come first one takes very fast to verify that the network PC doesn't exist, while 2nd takes around two minutes? If I'm not wrong it's 30 seconds in Windows environment to determine if network path is unreachable.
Why does it take so long in this case and how to speed up the info that PC is off?
A: In order to load the file, Windows must first make a file sharing connection to the machine. First it looks up the UNC name to get the IP address. If the machine doesn't exist, it can't get an IP address, and it fails quickly (as in the first example). If it does exist (as in the second example), Windows must then attempt to connect.
So why does it take two minutes when the time out is supposed to be 30 seconds? One possibility is that it retries a few times. Another possibility is that you have different network protocols and it has to try each one.
A: A faster way to check if the computer is on would be to ping the computer. Specify any timeout you like. There should be a response within a few seconds...
I guess the slow response has to do something with that the name of the turned off computer is still known in the network and associated with an ip. Then a longer timeout is chosen since the computer should be there...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599341",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Design Pattern Nomenclature & Clarification: Provider, Service, Broker Can someone define for me the conceptual difference is between a Provider, Service and Broker?
I regularly write MVC apps and offload much of the business logic to other classes. Nothing fancy, just pass in parameters and receive back POCO instance(s).
What is a correct label to give those classes performing the heavy lifting for my controller(s)?
A: These seem to be architectural patterns as opposed to design patterns;
*
*Service oriented architecture.
*Asp.net patterns every developer should know.
A: A Provider is really just another name for the Strategy Pattern
Typically when someone mentions the use of a provider they are talking about some abstract contract to which many implementations could exist.
//As an abstract base class
public void SetupRoles(RoleProvider provider){}
//As an interface
public void SetupRoles(IRoleProvider provider){}
//As a delegate
public void SetupRoles(Action<String> addRole){}
A Service is usually meant to indicate a stateless object that has only methods on it. A service could be used as a Strategy, but doesn't necessarily have to be.
//Plain old service... doesn't even need the web
// CRAZY TALK MAN!!!
public static class RoleService
{
public static void SetupRoles(){};
public static String[] GetRoles(){};
}
A Broker is really just responsible for well... brokering. It is designed to move messages between services and objects, orchestrating the interactions between services in order to keep them isolated.
public class Broker
{
public void SendImportantMessage(Message msg)
{
//Do some important processing here
// Maybe some validation
NotifySomeOtherServiceOrClassOrMaybeBobFromAccounting(msg);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
}
|
Q: Parse e-mail addresses with PHP? Similar to this question, how could I parse e-mail addresses which are in this format,
"Bob Smith" <bob@company.com>, joe@company.com, "John Doe"<john@company.com>
And get the a result like this:
array(
'bob@company.com'=>'Bob Smith'
'joe@company.com'=>''
'john@company.com'=>'John Doe'
);
A: This should work with just about anything:
$str = '"Bob Smith" <bob@company.com>, joe@company.com, "John Doe"<john@company.com>, Billy Doe<billy@company.com>';
$emails = array();
if(preg_match_all('/\s*"?([^><,"]+)"?\s*((?:<[^><,]+>)?)\s*/', $str, $matches, PREG_SET_ORDER) > 0)
{
foreach($matches as $m)
{
if(! empty($m[2]))
{
$emails[trim($m[2], '<>')] = $m[1];
}
else
{
$emails[$m[1]] = '';
}
}
}
print_r($emails);
Result:
Array
(
[bob@company.com] => Bob Smith
[joe@company.com] =>
[john@company.com] => John Doe
[billy@company.com] => Billy Doe
)
A: Well, you could use mailparse_rfc822_parse_addresses(), which does exactly that. It's a PECL extension, so it might be easier to use Mail_RFC822::parseAddressList() as mentioned in the comments.
A: This is a fully working piece of code below that even validates whether the email is correct or not ;)
<?php
$mails = '"Bob Smith" <bob@company.com>, joe@company.com, "John Doe"<john@company.com>';
$records = explode(",",$mails);
foreach($records as $r){
preg_match("#\"([\w\s]+)\"#",$r,$matches_1);
$name = $matches_1[1];
preg_match("/[^0-9<][A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}/i",$r,$matches_2);
$email = $matches_2[0];
echo "Name: $name <br /> Email: $email <br />";
}
?>
A: For a similar task I've used the following regex:
\s*(?:"([^"]*)"|([^,""<>]*))?\s*(?:(?:,|<|\s+|^)([^<@\s,]+@[^>@\s,]+)>?)\s*
https://regex101.com/r/Lpsjmr/1
PHP code:
$str = '"Bob Smith" <bob@company.com>, joe@company.com, "John Doe"<john@company.com>, Billy Doe<billy@company.com>';
if (preg_match_all('/\s*(?:"([^"]*)"|([^,""<>]*))?\s*(?:(?:,|<|\s+|^)([^<@\s,]+@[^>@\s,]+)>?)\s*/', $str, $matches, PREG_SET_ORDER) > 0) {
$matches = array_map(function($x) { return [$x[1] . $x[2], $x[3]]; }, $matches);
print_r($matches);
}
A: *
*Explode the string by comma
*If valid email then store it, if NO
*
*rtrim the '>' character
*explode by '<'
*trim the string for ('"', and ' ')
A: For input strings that are not properly parsed by the native function in @mario's answer, parse the substrings between delimiting commas using "branch resets" ((?|...)) and capture groups ((...)).
The branch reset ensure that (optionally occurring) names are always stored in column 1 of the matches array and that emails are always stored in column 2.
Code: (Demo)
$emails = '"Bob Smith" <bob@company.com>, joe@company.com, "John Doe"<john@company.com>, Billy Doe<billy@company.com>';
preg_match_all('/(?|(?|"([^"]+)"|([^<@]+)) ?<(.+?)>|()(.+?))(?:$|, ?)/', $emails, $matches, PREG_SET_ORDER);
var_export(
array_column($matches, 1, 2)
);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Python trying to Refactor (DRY out) a long Control Flow I am grabbing a lot of data from and SQL query that takes a long time to run. Since the SQL query takes so long to run, I am grabbing the data from the database in its most granular form. I then cycle through this data once and aggregate it in the forms that are useful to me.
My problem is that I am repeating myself over and over again. However, I am not sure of the best way to refactor this control flow. Thanks in advance!
def processClickOutData(cls, raw_data):
singles = {}
total={}
absolute_total = 0
channels = {}
singles_true = {}
total_true={}
channels_true = {}
absolute_total_true = 0
list_channels = set([])
list_tids = set([])
total_position = {}
total_position_true = {}
tid_position = {}
channel_position = {}
channel_position_true = {}
tid_position_true = {}
for row in raw_data:
gap=row[0]
count=row[1]
tid=row[2]
prefered=row[3]
channel=row[4]
position=row[5]
list_channels.add(channel)
list_tids.add(tid)
absolute_total += int(count)
if total.has_key(gap):
total[gap] += count
else:
total[gap] = count
if singles.has_key(gap) and singles[gap].has_key(tid):
singles[gap][tid] += count
elif singles.has_key(gap):
singles[gap][tid] = count
else:
singles[gap] = {}
singles[gap][tid] = count
if channels.has_key(gap) and channels[gap].has_key(channel):
channels[gap][channel] += count
elif channels.has_key(gap):
channels[gap][channel] = count
else:
channels[gap] = {}
channels[gap][channel] = count
if total_position.has_key(position):
total_position[position] += count
else:
total_position[position] = count
if tid_position.has_key(position) and tid_position[position].has_key(tid):
tid_position[position][tid] += count
elif tid_position.has_key(position):
tid_position[position][tid] = count
else:
tid_position[position] = {}
tid_position[position][tid] = count
if channel_position.has_key(position) and channel_position[position].has_key(channel):
channel_position[position][channel] += count
elif channel_position.has_key(position):
channel_position[position][channel] = count
else:
channel_position[position] = {}
channel_position[position][channel] = count
if prefered == 0:
absolute_total_true += count
if total_true.has_key(gap):
total_true[gap] += count
else:
total_true[gap] = count
if singles_true.has_key(gap) and singles_true[gap].has_key(tid):
singles_true[gap][tid] += count
elif singles_true.has_key(gap):
singles_true[gap][tid] = count
else:
singles_true[gap] = {}
singles_true[gap][tid] = count
if channels_true.has_key(gap) and channels_true[gap].has_key(channel):
channels_true[gap][channel] += count
elif channels_true.has_key(gap):
channels_true[gap][channel] = count
else:
channels_true[gap] = {}
channels_true[gap][channel] = count
if total_position_true.has_key(position):
total_position_true[position] += count
else:
total_position_true[position] = count
if tid_position_true.has_key(position) and tid_position_true[position].has_key(tid):
tid_position_true[position][tid] += count
elif tid_position_true.has_key(position):
tid_position_true[position][tid] = count
else:
tid_position_true[position] = {}
tid_position_true[position][tid] = count
if channel_position_true.has_key(position) and channel_position_true[position].has_key(channel):
channel_position_true[position][channel] += count
elif channel_position_true.has_key(position):
channel_position_true[position][channel] = count
else:
channel_position_true[position] = {}
channel_position_true[position][channel] = count
final_values = {"singles" : singles, "singles_true" : singles_true, "total" : total, "total_true": total_true, "absolute_total": absolute_total, "absolute_total_true": absolute_total_true, "channel_totals" : channels, "list_channels" : list_channels, "list_tids" : list_tids, "channel_totals_true" : channels_true,
"total_position" : total_position, "total_position_true" : total_position_true, "tid_position" : tid_position, "channel_position" : channel_position, "tid_position_true" : tid_position_true, "channel_position_true" : channel_position_true }
return final_values
A: The entire structure you're using to store the data is probably wrong, but since I don't know how you're using it, I can't help you with that.
You can get rid of all of those has_key() calls by using collections.defaultdict. Note thedict.has_key(key) is deprecated anyway, you should just use key in thedict instead.
Look at how I change the for loop too -- you can assign to names right in the for statement, no need to do it separately.
from collections import defaultdict
def processClickOutData(cls, raw_data):
absolute_total = 0
absolute_total_true = 0
list_channels = set()
list_tids = set()
total = defaultdict(int)
total_true = defaultdict(int)
total_position = defaultdict(int)
total_position_true = defaultdict(int)
def defaultdict_int():
return defaultdict(int)
singles = defaultdict(defaultdict_int)
singles_true = defaultdict(defaultdict_int)
channels = defaultdict(defaultdict_int)
channels_true = defaultdict(defaultdict_int)
tid_position = defaultdict(defaultdict_int)
tid_position_true = defaultdict(defaultdict_int)
channel_position = defaultdict(defaultdict_int)
channel_position_true = defaultdict(defaultdict_int)
for gap, count, prefered, channel, position in raw_data:
list_channels.add(channel)
list_tids.add(tid)
absolute_total += count
total[gap] += count
singles[gap][tid] += count
channels[gap][channel] += count
total_position[position] += count
tid_position[position][tid] += count
channel_position[position][channel] += count
if prefered == 0:
absolute_total_true += count
total_true[gap] += count
singles_true[gap][tid] += count
channels_true[gap][channel] += count
total_position_true[position] += count
tid_position_true[position][tid] += count
channel_position_true[position][channel] += count
final_values = {"singles" : singles, "singles_true" : singles_true, "total" : total, "total_true": total_true, "absolute_total": absolute_total, "absolute_total_true": absolute_total_true, "channel_totals" : channels, "list_channels" : list_channels, "list_tids" : list_tids, "channel_totals_true" : channels_true,
"total_position" : total_position, "total_position_true" : total_position_true, "tid_position" : tid_position, "channel_position" : channel_position, "tid_position_true" : tid_position_true, "channel_position_true" : channel_position_true }
return final_values
What this does is automatically fill in the correct default values if the keys don't exist. You've got two kinds here. Where you're adding ints, you want to start with 0 if it doesn't exist -- that's what int returns, hence defaultdict(int). Where you're adding a dictionary that adds ints, you need to use a function that returns a defaultdict(int) which is what defaultdict_int does.
Edit: Suggested alternate dictionary structure:
position = defaultdict(lambda: defaultdict(defaultdict_int))
gap = defaultdict(lambda: defaultdict(defaultdict_int))
absolute_total = 0
for gap, count, prefered, channel, position in raw_data:
absolute_total += count
posd = position[position]
posd.setdefault('total', 0)
posd['total'] += count
posd['tid'][tid] += count
posd['channel'][channel] += count
gapd = gap[gap]
gapd.setdefault('total', 0)
gapd['total'] += count
gapd['tid'][tid] += count
gapd['channel'][channel] += count
Do the same with the _true versions as well, and you've gone from 12 dicts to 4.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599347",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Adding named item to named list - guaranteed to append to end of list? When adding a named item to a list, is it guaranteed that the item will be added to the end of the list? In practice it appears to be the case, but not sure if this is a dangerous assumption?
test = list()
test[[ "one" ]] = 1
test[[ "two" ]] = 2 # will always appear after "one"?
test[[ "three" ]] = 3 # will always appear after "two"?
A: I suspect if you delved into the C code of R then you'd see that it was true, but as Joshua says, its not documented. You could ask on R-dev for an opinion on whether such behaviour should be documented. There may already be existing code that depends on it.
A: If it's not documented (and it doesn't appear to be), then I wouldn't rely on it. You can ensure it appears at the end of the list by doing something like:
test <- list()
test <- c(test, one=1)
test <- c(test, two=2)
test <- c(test, three=3)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
}
|
Q: Efficient search algorithm for files with specifed extension C/C++ I want to implement faster directory search.
Is there any algorithm in c/c++ is available for that ?
A: Check boost::filesystem library on http://www.boost.org/doc/libs/1_47_0/libs/filesystem/v3/doc/index.htm, there you have a recursive_directory_iterator class.
A: There isn't a C++ thing per se, but usually directory search is slow because of IO, and because you must stat each file (or whatever the OS equivalent is non-unix systems) to find out anything besides its name. One way to make this faster would be to keep write a server that keeps the inodes and filenames in memory. Of course the difficulty is that the inode information is not static. You would need to listen to file system changes to keep your cache up to date. That is definitely possible in linux, but I have no experience with it on other systems. As you can see, another theme of this problem is that it is very system and possibly filesystem dependent. Maybe a system-independent library like Boost::Filesystem can help, but I doubt it implements directory update callbacks.
Maybe just install Google Desktop?
A: Here's a windows solution (http://ideone.com/5dFVf)
class file_iterator : std::iterator<std::output_iterator_tag, const WIN32_FIND_DATA> {
HANDLE handle;
WIN32_FIND_DATA fdata;
public:
file_iterator() :handle(NULL) {
#ifdef _DEBUG
memset(&fdata, 0, sizeof(fdata);
#endif //_DEBUG
}
file_iterator(const std::wstring& path) :handle(FindFirstFile(path.c_str(), &fdata)) {}
file_iterator(file_iterator&& b) :handle(b.handle) {b.handle = NULL;}
file_iterator& operator=(file_iterator&& b) {close(); handle = b.handle; b.handle = NULL;}
void close() {
if (handle)
FindClose(handle);
#ifdef _DEBUG
memset(&fdata, 0, sizeof(fdata);
#endif //_DEBUG
}
const WIN32_FIND_DATA& operator*() {return fdata;}
file_iterator& operator++() {if (FindNextFile(handle , &fdata)==false) close(); return *this;}
bool operator==(const file_iterator& b) {return handle == b.handle;}
bool operator!=(const file_iterator& b) {return handle != b.handle;}
};
std::vector<std::wstring>
find_files_with_extension(
const std::wstring& folder,
const std::wstring& extension,
std::vector<std::wstring>* result=NULL)
{
std::wstring filepath = folder + L"/*";
std::vector<std::wstring> local_result;
std::deque<std::wstring> todo;
if (result == NULL)
result = &local_result;
file_iterator iter(filepath);
while(iter != file_iterator()) {
std::wstring folder_file((*iter).cFileName);
if ((*iter).dwFileAttributes | FILE_ATTRIBUTE_DIRECTORY)
todo.push_back(folder_file);
else if (folder_file.size() > extension.size() && folder_file.substr(folder_file.size()-extension.size())==extension)
result->push_back(folder_file);
++iter;
}
for(int i=0; i<todo.size(); ++i)
find_files_with_extension(todo[i], extension, result);
return *result;
}
This uses a breadth-first search, which takes a little more RAM and is slightly more complicated, but faster due to caching.
A: Searching is an OS feature these days, and those who are trying to implement third party indexing are giving up. Even Google Desktop is not being updated and most consider it dead:
https://superuser.com/questions/194082/is-google-desktop-search-a-dead-project
If you install a search server on someone's computer and get caught hogging disk and CPU--and you do not have a very, VERY good reason for doing so--you will not only waste a lot of time writing code and patching bugs but you will also alienate your users.
For most cross-platform apps, letting the users find the files in the Explorer/Finder/Nautilus and then making your app accept multi-file drag and drops is a better answer. Also, most "common dialogs" for opening files provide built in search functionality now.
If you're trying to write a search-accelerated tool for a specific platform, hook into that platform's API, which may even permit you to supplement its index. Here's Microsoft's Programmatic Search API:
http://msdn.microsoft.com/en-us/library/windows/desktop/bb266517(v=vs.85).aspx
OS/X has the spotlight API:
http://developer.apple.com/library/mac/#documentation/Carbon/Conceptual/SpotlightQuery/SpotlightQuery.html
I'm not quite sure if there's "canon" for search in the Linux world, but most all of the relevant versions of Ubuntu now ship with Tracker:
http://live.gnome.org/Tracker/Documentation
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Size of Unions in C How the union in C language allocate memory?
For example
union st
{
int i;
char ch;
};
A: An instance of that union will take up at least as much space as its biggest member, i.e. 1 word for the int.
If you had a union with a char and a short int, you might end up with a word on the stack anyway, since it's more efficient in most systems to allocate on word boundaries.
A: In a union all the members share the same memory space (or, to say it as it is specified in the standard, if you take the address of any of the members you'll get the same result - besides the type). Obviously the size of the union is the size of its biggest member.
Because of this, the standard allows only one of the union members to be "active" at the same time, i.e. if you write in i, then you can only read from i, until you write in some other member. Failure to do so results in undefined behavior, which often is getting garbage results from reinterpreting bits of the other types.
A: It should be as big as its largest member. It has to be at least that large, and there's no reason for it to be larger.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599355",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to hard code 7 int positions? I am using this method to retrieve some images.
The only problem is is where
aURL = new URL(myRemoteImages[position]);
Position is i dont know how to get the position for each image in order to set the tag in my code.
i.setTag(mImageURLs[position]);
As you see myRemoteimages has 7 strings and thats all. How can i hard code. the int Position to just have 7 positions?
public void RetrieveImages() {
ImageView i = new ImageView(this);
String[] mImageURLs = {
urlImage1, urlImage2, urlImage3, urlImage4, urlImage5, urlImage6,
urlImage7};
String[] myRemoteImages = {
imageUrl, imageUrl2, imageUrl3, imageUrl4,
imageUrl5, imageUrl6, imageUrl7};
URL aURL = null;
try {
aURL = new URL(myRemoteImages[position]);
} catch (MalformedURLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
Log.v("ImageLoader", "Remote images set");
i.setTag(mImageURLs[position]);
URI imageUri = null;
SharedPreferences myPrefs = getSharedPreferences("imageUri", 0);
SharedPreferences.Editor myPrefsEdit = myPrefs.edit();
// Setting the Uri of aURL to imageUri.
try {
imageUri = aURL.toURI();
myPrefsEdit.putString("uris", imageUri.toString());
myPrefsEdit.commit();
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
A: The question feels a little ambiguous, and to my mind there are a couple of answers, depending on what the OP is actually looking for. There are also some odd things being done in this code...
*
*The two arrays you create, mImageURLs and myRemoteImages, both contain conceptually identical string names. This is confusing, and will lead to maintenance problems. In addition, because the strings used appear to be instance variables, you should likely have the arrays as the instance variables, saving you the trouble of declaring 14 (and eventually more) string variables (and the related maintenance trouble of dealing with them). Declaring variable names like imageUrl, imageUrl2, ... imageUrl7 is often a sign that the problem is being implemented problematically - at the very least, if there are different strings for distinct things, they should be named as such (backImage, forwardImage, etc). Besides the issue that urlImage and imageUrl1 'appear' to be missing(due to the difference in the naming scheme).
*Your code prints a stack trace; this is possibly a problem when putting the code on the device. Your average consumer probably doesn't know java, and wouldn't know what to do with an error log if it bit them. You probably should be logging errors somehow, but this may have to be disabled if you don't have some sort of reporting tool to get the logs. Oh, and just name the exception you're catching e - it's the standard, you've already got them out-of-order and it's not like they can be accessed outside of the catch block.
*It looks like there may be a couple of smaller methods trying to break out of here. Without knowing specifically what you're trying to accomplish, it's a little difficult to know what those should contain.
If you know that a specific index in the array will always contain the desired URI (and you're only using one of them), you can go ahead and hard code that. Preferrably, you use a constant, which you then reference elsewhere as necessary:
i.setTag(mImageURLs[HOME_PAGE_IMAGE_ARRAY_INDEX]);
Of course, at that point (especially if you're declaring the array locally...), you may as well use the actual string:
i.setTag(urlImage3);
This also saves you the cost of dealing with an array.
If you need to go through all the images in an array...
There are two ways to loop over an array in Java: the foreach loop (which I'm not sure if android supports), and the standard for loop:
for(int i = 0; i < mImageURLs.length(); i++) {
i.setTag(mImageURLs[i]);
}
This has the added benefit that, if you always want to display all the strings in the array, this 'automatically' expands to deal with it. Whether exception handling belongs inside or outside of the array depends on the design, but I suspect that it likely belongs inside here...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599358",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to make a jQuery and AJAX call from a url instead of a form I know how to make a jQuery AJAX call from a form, but how do I make it from a link?
I have a list of items on a page and a link to delete each next to the item. How can I make the jQuery AJAX call from the link?
Thanks!
A: Bind to the click handler of the link. Use an attribute of the link to hold your data or use a data-val attribute.
<a class="myLink" href="item1">item 1</a>
<a class="myLink" href="item2">item 2</a>
$(".myLink").click(function(event){
var item = $(this).attr("href").val();
$.ajax({
url:"/delete/" + item,
type:"POST",
success: function(data){}
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to replace particular substring using regular expression using java? I have a string as below.
$Trap:com.oss.Event(description matches "abc")
In the above string the generic portions is $Trap:com.oss.Event(<Any string>).
when i encounter the above string i need to replace with the below string.
$Trap:com.oss.Event(description matches "abc") from entry-point "EventStream".
To achieve the above i am using the following logic in java.
String stmt= $Trap:com.oss.Event(description matches "abc")
if(stmt.matches(".*\\.Event(.*).*")&& s.equals(""))
{
stmt+=" from entry-point "+"ABCStream";
}
But the above logic is not working as expected when the string is as below.
stmt="$Trap:com.oss.Event(description matches "abc") or $Trap:com.oss.Event(description matches "cde");
I need to generate the following corresponding string using regular expression.
$Trap:com.oss.Event(description matches "abc") from entry-point "ABCStream" or $Trap:com.oss.Event(description matches "cde") from entry-point "ABCStream"
Please provide some pointers to achieve the same.
A: The following Java code works:
String stmt = "$Trap:com.oss.Event(description matches \"abc\")"
+ " or $Trap:com.oss.Event(description matches \"cde\")";
Pattern p = Pattern.compile(".*?\\.Event\\(.*?\\)");
String res = p.matcher(stmt).replaceAll("$0 from entry-point \"ABCStream\"");
System.err.println(res);
and produces the following result:
$Trap:com.oss.Event(description matches "abc") from entry-point "ABCStream" or $Trap:com.oss.Event(description matches "cde") from entry-point "ABCStream"
You need to quote special chars, e.g. round brackets, inside regexp and also use lazy match, i.e. *?. The $0 refers to the found matching group.
Using Pattern.compile() will save you some performance, if you are doing this replacement repeatedly.
A: This do the stuff:
public class A {
public static void main(String[] args) {
String stmt="$Trap:com.oss.Event(description matches \"abc\") or $Trap:com.oss.Event(description matches \"cde\")";
System.out.println(stmt);
System.out.println(stmt.replaceAll("(\\$Trap:com.oss.Event\\([^)]*\\))", "$1 from entry-point \"ABCStream\""));
}
}
As you can see, you must double escape some symbols. The first and last parenthesis are for grouping the regex, and you can print that group with "$1"
And procuded this output:
$Trap:com.oss.Event(description matches "abc") or $Trap:com.oss.Event(description matches "cde")
$Trap:com.oss.Event(description matches "abc") from entry-point "ABCStream" or $Trap:com.oss.Event(description matches "cde") from entry-point "ABCStream"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Get the title of a requested page using jQuery AJAX I have written the following to do AJAX requests in my app:
$(document).ready(function () {
$('ul#ui-ajax-tabs li:first').addClass('selected');
$('#ui-ajax-tabs li a').click(function (e) {
e.preventDefault();
$("#ui-ajax-tabs li").removeClass("selected");
$(this).parents('li').addClass("loading");
var url = $(this).attr("href");
var link = $(this);
console.log(url);
$.ajax({
url: url,
success: function (responseHtml) {
$('div#ui-tab-content').html($(responseHtml).find('div#ui-tab-content > div#ui-ajax-html'));
$(link).parents('li').addClass('selected');
$("#ui-ajax-tabs li").removeClass("loading");
},
error: function () {
$('div#ui-tab-content').html('<div class="message error">Sorry that page doesn\'t exist</div>');
$(link).parents('li').addClass('selected');
$("#ui-ajax-tabs li").removeClass("loading");
}
});
});
});
How would I grab the title from the requested page and use it?
I've thought about something like: var title = $(document).attr('title'); but how do I get the title from the requested page and set that as the new title? Thanks
A: I am new to jQuery, but I will give it a try anyways:
var newTitle = $(responseHtml).filter('title').text();
And if one of the above works, the current title could be changed by
document.title = newTitle;
Again I am a jQuery and Javascript beginner and just wanted to give it a try :) So excuse me if its stupid and wont work :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: ReportServer, ReportServerTempDB I have MS SQL Server 2008 installed on my machine and also ‘Reporting Services Configuration Manager’.
When I connect to (local) instance with Windows Authentication, I see following two DBs already available in this instance –
- ReportServer
- ReportServerTempDB
Do they come as a part of Reporting Services Configuration Manager?
Thank you!
A: Those databases are created when you install SQL Server Reporting Services.
read more here
http://msdn.microsoft.com/en-us/library/ms159093.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: jQuery - Get HTML content of page and remove form elements I have a page which outputs HTML in ASP.NET webforms.
I am making a request to this page via:
$(document).ready(function () {
$.get("Preview.aspx?ID=1", function (data) {
alert("Data Loaded: " + data);
});
});
The problem is that the preview.aspx page returns HTML with form elements in it. I want to replace these form elements with nothing.
How do I remove all form elements from the data object above?
EDIT: Just to be clear, I need to keep all HTML in place, only replacing form elements.
EDIT 2: Sorry I should have been more clear. This is for an HTML newsletter. Basically the page is pure HTML but being web forms (yuck) there is all the form mumbo jumbo. I want to get the content of this page without the form elements. So far the ideas below are not working. The .load works, but when I add the :not('form') the HTML is incorrectly formatted. The get var elem = $(data).find('form').html(); returns null even though the form is definitely there when I do an alert(data).
A: You might be better off using jQuery's .load method. This way, you can select a fragment from the external page using any jQuery selector.
If you wrap all of the relevant info from Preview.aspx in a <div id="whatever"> tag, you can extract just that with
$('<div/>').load('Preview.aspx?ID=1 #whatever', function() {
var preview = $(this).html();
});
-- which has the added benefit of ignoring all the html/head/body/etc. tags in that document.
You can also use it this way, which will get everything that's not a form or input tag but might let other stuff inside the form through. Use carefully and modify as needed:
$('<div/>').load('Preview.aspx?ID=1 :not("form"):not("input")', function() {
var preview = $(this).html();
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599369",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Facebook app dynamic like I am developing a facebook app where users watch videos from a playlist and view images from galleries. The app itself is hosted on my server then set as a canvas page in facebook. What I want is for users to be able to "Like" individual videos and photos. I have currently set it so that the when a photo/video is selected it ammends the href attribute of the "Like" button with the url of the appropriate page appended with a querystring for the image/video id.
e.g. href="http://www.myApp.com/index.php?id=0001"
This works but the problem is when that "Like" event is posted on the users wall the link created goes to hosted page and not to the facebook canvas page (in other words it leaves facebook). What I want is for the "Like" link on the users wall to take them to the canvas page and select the correct page and image/video within the page.
I could set the href to go to the canvas page but that would the app at the homepage and I want it to go straight to the liked image/video. Is there perhaps a way I can ammend the url so that when it is clicked it tells facebook exactly what url to set for the canvas page?
A: Incase anyone else is having difficulty with this I have found a solution.
Set the href attribute of your "Like" button to the facebook page of your app i.e. "apps.facebook.com/myApp/"
You can then add your own querystrings on the end to identify where in the app you want to go. Pick names which are likely to be unique to your app so it doesn't accidently clash with anything Facebook might be processing at the same time. i.e.
"apps.facebook.com/myApp/?myAppPage=photos&myAppId=003"
Now in your landing page code put something like this at the top:
if (isset($_REQUEST['myAppPage'])) {
$myAppPage = $_REQUEST['myAppPage'];
if (isset($_REQUEST['myAppId'])) {
$myAppId = $_REQUEST['myAppId'];
$qsName;
switch ($myAppPage) {
case "photos":
$qsName = 'gal';
break;
Case "videos":
$qsName = 'vid';
break;
}
header("Location: $myAppPage.php?$qsName=$myAppId");
}
}
This should redirect your app to the page you want without leaving Facebook. Then you just need to program your page to load the correct content based on the new querystrings passed in the header.
Hope this helps someone.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP imap_search no search results $some = imap_search($mbox, "TEXT \"{$q}\" ");
where $q - some sring query
but I haven't results if $q string in body, but results are present if $q is in the subject.
What may cause such behaviour? Server settings?
A: I have never used the TEXT option.
Try to use BODY and SUBJECT options.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: javascript popup window and reload I have a slight variation on the window.opener.reload javascript.
Normally, if I want to reload a page after closing a pop-up window I use
window.opener.reload(true)
But this time i want to load a different url into the opener window.
So i tried this:
window.opener.href('url').reload(true);
But this isn't working. Any ideas on why it isn't working and how I can make it work??
Thanks
jw
A: Assign to location.href:
opener.location.href = "url";
A: This might work (subject to same-origin policy restrictions):
window.opener.location = url;
A: Try this instead:
window.opener.location.href = "somepage.htm";
A: You dont need to reload page when set a new uri (second case) you must code directly:
opener.location.href = "url";
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Django ManyToMany 'str' object has no attribute I am having an issue with what appears Django using the string name and not getting the "object" associated with that name. I'm trying to use a ManyToMany relationship, but I can't quite figure it out. The error I am getting is:
AttributeError at <URL>
'str' object has no attribute '_default_manager'
Here's my model setup:
models/hood.py
class Hood(models.Model):
name = models.CharField(unique=True)
restaurants=models.ManyToManyField(Restaurant, through="restaurant_hood_map.RestaurantHoodMap")
class Meta:
db_table = "hoods"
app_label="delivery"
models/restaurant.py
class Restaurant(models.model):
name=models.ForeignKey(CompanyName)
is_active=models.BooleanField(default=True)
class Meta:
db_table="restaurants"
app_label="delivery"
models/restuarant_hood_map.py
<import restaurant and hood>
class RestaurantHoodMap(models.Model):
restaurant = models.ForeignKey(Restaurant)
hood = models.ForeignKey(Hood)
class Meta:
db_table="restaurant_hood_map"
app_label="delivery"
Now, I know what the problem is.....when I attempt to get the related restaurants off of Hood, I am getting this error. That's because it's treating the "restaurant.Restaurant" as a string value. However, I thought it was accepted to use string values in order to avoid circular dependencies? At least thats what I thought from the docs:
https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey
I also followed this example, which looked like exactly what I wanted:
How do I tell Django to not create a table for an M2M related field?
However, that doesn't seem to work when you get a Hood object and do hood.restaurants....it barfs.
Any help would be AWESOME!
UPDATE: I made a slight change to the models to more accurately show what's happening.
A: Alright, I got this figured out. It turns out that when you define the "through" parameter of the ManyToManyField it CANNOT point to a class in a different module.
So in my above example, the RestaurantHoodMap class has to be put into the "hood.py" module, and the through has to be changed so that it doesn't have the module in the name:
restaurants=models.ManyToManyField(Restaurant, through="RestaurantHoodMap")
Now, I'm not sure if this is a bug in Django or not. I thought you could reference a different class with strong notation, but that doesn't seem to be the case if the class is in a different module.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to read a json decoded array with php? I have the following array and I can't figure out how to get any values out of it, this is the array:
Array
(
[0] => stdClass Object
(
[aure] => test
[menu] => stdClass Object
(
[pizza] => stdClass Object
(
[Tomato & Cheese] => stdClass Object
(
[small] => 5.50
[large] => 9.75
)
[onion] => stdClass Object
(
[small] => 5.50
[large] => 9.75
)
)
[Special Dinners] => stdClass Object
(
[Chicken Wings Dinner] => stdClass Object
(
[price] => 15.80
)
[onion] => stdClass Object
(
[small] => 5.50
[large] => 9.75
)
)
)
)
)
would you be able to give me an example of how can I get the price for a small Tomato & cheese pizza?
A: $array[0]->menu->pizza->{"Tomato & Cheese"}->small;
I have used curly brackets because I'm not able to get "Tomato & Cheese" without them (they have spaces)
This will give you all pizzas
$pizzas = (array) $array[0]->menu->pizza;
foreach($pizzas as $pizzaname => $choices){
echo $pizzaname." (small) is for ".$choices->small."<br />";
echo $pizzaname." (large) is for ".$choices->large."<br />";
}
A: If your names are not only alphanumeric, consider setting the assoc parameter of json_decode to true to get a nested dictionary instead of objects.
However, you can still access strange member names, using the following syntax:
echo 'Large t&c: ' . jsonArray[0]->menu->pizza->{'Tomato & Cheese'}->large;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599402",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Remove all nodes after a specified node I'm grabbing a div of text from a url and would like to remove everything underneath a paragraph which has a backtotop class. I'd seen a traverse snippet of code here on stackoverflow which looks promising, but I can't figure out how to get it incorporated so @el only contains everything up to the first p.backtotop in the div.
my code:
@doc = Nokogiri::HTML(open(url))
@el = @doc.css("div")[0]
end
traverse snippet:
doc = Nokogiri::HTML(code)
stop_node = doc.css("p.backtotop")
doc.traverse do |node|
break if node == stop_node
# else, do whatever, e.g. `puts node.name`
end
A: *
*Find the div you want.
*Find the 'stop' item you want, and then find all the following siblings.
*Remove them.
For example:
<body>
<div id="a">
<h2>My Section</h2>
<p class="backtotop">Back to Top</p>
<p>More Content</p>
<p>Even More Content</p>
</div>
</body>
require 'nokogiri'
doc = Nokogiri::HTML(my_html)
div = doc.at('#a')
div.at('.backtotop').xpath('following-sibling::*').remove
puts div
#=> <div id="a">
#=> <h2>My Section</h2>
#=> <p class="backtotop">Back to Top</p>
#=>
#=>
#=> </div>
Here's a more complicated example, where the backtotop item may not be at the root of the div:
<body>
<div id="b">
<h2>Another Section</h2>
<section>
<p class="backtotop">Back to Top</p>
<p>More Content</p>
</section>
<p>Even More Content</p>
</div>
</body>
require 'nokogiri'
doc = Nokogiri::HTML(my_html)
div = doc.at('#b')
n = div.at('.backtotop')
until n==div
n.xpath('following-sibling::*').remove
n = n.parent
end
puts div
#=> <div id="b">
#=> <h2>Another Section</h2>
#=> <section><p class="backtotop">Back to Top</p>
#=>
#=> </section>
#=> </div>
If your HTML is more complicated than the above then please provide an actual sample along with the result you want. This is good advice for any future question you ask.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How would you make an iterator as a key of hash_map? How would you make an iterator as a key of hash_map?
How would you define it under gcc, Microsoft c++?
E.g.
vector<string>::iterator i;
hash_map<vector<string>::iterator, int> h;
or
list<string>::iterator i;
hash_map<list<string>::iterator, int> h;
THis gives an error as iterators are not predefined as string and other types are...
Blockquote
A: It is not a good idea to store vector's iterators of use them as keys in an associative container because vector's iterators are unstable, that is, they get invalidated on insert, remove, resize, push_back an so on (see Iterator invalidation rules).
Plain index is much safer in this regard:
hash_map<size_t, int> h;
You can convert an index to an iterator by simply:
size_t index = ...
std::vector<std::string> vec(...);
std::vector<std::string>::iterator i = vec.begin() + index;
And iterator back to index:
index = i - vec.begin();
A: FWIW:
using iterators in that way is NOT robust. Iterators get invalidates on certain operations that act on the container. Your hash_map keys will be invalidated from that moment.
I suggest using
hash_map<string, int> h;
or
vector<string*> i;
hash_map<string*, int> h;
or even
vector<shared_ptr<string> > i;
hash_map<shared_ptr<string>, int> h;
A: If you know what you're doing (e.g. if the iterators are taken from a non-modifiable container), you can try to exploit the fact that &*it should be unique for each element:
typedef std::string my_container;
typedef my_container::const_iterator my_iterator;
struct IteratorHasher
{
std::size_t operator()(const my_iterator & it) const
{
return hasher(&*it);
}
private:
std::hash<const char *> hasher;
};
Usage:
int main()
{
std::unordered_map<my_iterator, int, IteratorHasher> mymap;
std::string hello("hello");
mymap[hello.begin()] = 3;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MVC invoke model binder directly on a single object Is there a way that I can invoke the model binder for a single object?
I don't want/need a custom model binder - I just want to do something like this:
MyViewModel1 vModel1 = new MyViewModel1();
InvokeModelBinder(vModel1);
MyViewModel2 vModel2= new MyViewModel2();
InvokeModelBinder(vModel2);
And when I'm done, the properties of both vModel1 and vModel2 have been bound to what's in the incoming request. Because of the way that our controller/action is being written, I don't necessarily want to list vModel1 and vModel2 in the action method's input list (since there will end up being a potentially long list of view models to optionally bind against).
A: Use Controller.UpdateModel:
MyViewModel1 vModel1 = new MyViewModel1();
UpdateModel(vModel1);
Update
Note if ModelState in controller has validation errors (related to model passed in action), UpdateModel (with any model) throws excetion, despite UpdateModel success and vModel1 is updated. Therefore errors in ModelState should be removed, or put UpdateModel in try/catch and just ignore excetion
A: This is wrong on many levels IMHO:
*
*This is not how ASP.NET MVC is designed to work.
*Your actions do not define a clear contract of what data they expect.
*What do you get out of it? Smells like bad design.
Model binding is driven by reflection. Before an action is invoked it will reflect the method parameters list and for each object and its properties it will invoke a model binder to find a value for each property from the various value providers (form POST values provider, url parameters, etc). During model binding the ModelState validation is done as well.
So by not using the default ASP.NET MVC to do this you are losing all that.
Even if you were to manually get hold of a model binder like that:
IModelBinder modelBinder = ModelBinders.Binders.GetBinder(typeof(MyObject));
MyObject myObject = (MyObject ) modelBinder.BindModel(this.ControllerContext, ** ModelBindingContext HERE**);
You can see that you need to initalize a ModelBindingContext, something that ASP.NET MVC will do internally based on the current property it is reflecting. Here is the snipped from the ASP.NET MVC source code:
protected virtual object GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) {
// collect all of the necessary binding properties
Type parameterType = parameterDescriptor.ParameterType;
IModelBinder binder = GetModelBinder(parameterDescriptor);
IDictionary<string, ValueProviderResult> valueProvider = controllerContext.Controller.ValueProvider;
string parameterName = parameterDescriptor.BindingInfo.Prefix ?? parameterDescriptor.ParameterName;
Predicate<string> propertyFilter = GetPropertyFilter(parameterDescriptor);
// finally, call into the binder
ModelBindingContext bindingContext = new ModelBindingContext() {
FallbackToEmptyPrefix = (parameterDescriptor.BindingInfo.Prefix == null), // only fall back if prefix not specified
ModelName = parameterName,
ModelState = controllerContext.Controller.ViewData.ModelState,
ModelType = parameterType,
PropertyFilter = propertyFilter,
ValueProvider = valueProvider
};
object result = binder.BindModel(controllerContext, bindingContext);
return result;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: understanding clicks behaviour I wrote this simple code to understand why if I click the "click me" text for the second time JQuery does not display the "second" text.
<div id="clickme">Click me</div>
<div id="sometext">This is text ZERO</div>
<script type="text/javascript">
$(document).ready(function($) {
$("#clickme").click(function(){
if (a == 1) {
$('#sometext').replaceWith('<div id="sometext">This is text TWO</div>');
}
else {
$('#sometext').replaceWith('<div id="sometext">This is text ONE</div>');
var a = 1;
}
});
});
</script>
I expected the following behaviour:
*
*Page is loaded and the text 'This is text ZERO' is displayed
*I click the link the first time and JQuery displays 'This is text ONE'
*I click the link a second time and jQuery displays 'This is text TWO'
Instead point #3 is not processed or at least the text is not displayed. Why?
A: Because a is defined locally, it is a scope issue. Initialize a globally and it will work. See Below
$(document).ready(function($) {
var a = 0;
$("#clickme").click(function(){
if (a == 1) {
$('#sometext').replaceWith('<div id="sometext">This is text TWO</div>');
}
else {
$('#sometext').replaceWith('<div id="sometext">This is text ONE</div>');
a = 1;
}
});
});
Here is a fiddle
http://jsfiddle.net/jfhartsock/Khp7P/1/
A: It is a scope issue as mentioned above, the variable 'a' must be defined in the scope of the page, not the click event.
$(document).ready(function($) {
var a = 0;
$("#clickme").click(function() {
if (a == 1) {
$('#sometext').replaceWith('<div id="sometext">This is text TWO</div>');
a = 0;
}
else {
$('#sometext').replaceWith('<div id="sometext">This is text ONE</div>');
a = 1;
}
});
});
http://jsfiddle.net/d5xSH/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: System.Drawing.Rectangle Cannot find property setter for "bottom" or "Left" or "Right" or "Top" In Delphi Prism, I am trying to set the Rectangle properties, left right top or bottom, and compiler keeps saying that it can't find a setter to set a value to these properties for Rectangle.
I have looked at other stackoverflow questions related to this and have not found a good answer.
I want to be able to set the Rectangle it is top, bottom, right or left values to be able to do something like the following.
dragRect.right := dragRect.left;
dragRect.bottom := dragRect.top;
Obviously, you can't do this. How do you accomplish the samething in Delphi Prism?
A: As Hans Passant pointed out, it is important to understand the difference between value type and reference type. Because System.Drawing.Rectangle doesn't have setters for left, top, right or bottom, you simply can't set any values to them but only read what is already there.
The only time they get updated is when you actually create the Rectangle object passing the height, width and X-Y points OR setting X, Y, height and/or width of a rectangle properties.
Since in my program I am only trying to define the boundary or the area for drawing the shape of a rectangle, I set the X, Y, width or height. It works fine. As far as figuring out the width and height of a rectangle, you don't have to once you set its width and height once. Every time you reset the X and/or Y value of a rectangle, it maintains its width and height. Thus, it knows what its right and bottom values are.
For instance, you can do this:
dragRect.X := 100;
dragRect.width := 10;
but you can't do this:
dragRect.left := 100;
dragRect.right :=110;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Simple post to db in php/mysql - edit Pretty simple stuff, I know, but am getting an error
<?php
session_start();
$dbhost = "###"; // this will ususally be 'localhost', but can sometimes differ
$dbname = "###"; // the name of the database that you are going to use for this project
$dbuser = "###"; // the username that you created, or were given, to access your database
$dbpass = "###"; // the password that you created, or were given, to access your database
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
mysql_select_db("###", $con);
$safe_email = mysql_real_escape_string($_POST['email']);
$sql="INSERT INTO register (email) VALUES ('{$safe_email}')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
A: $con is not defined anywhere in your code, before you use it in the query call. You should have:
$con = mysql_connect(...) or die(mysql_error());
Beyond that, your code is WIDE open to SQL injection attacks. You should have:
$safe_email = mysql_real_escape_string($_POST['email']);
$sql="INSERT INTO register (email) VALUES ('{$safe_email}')";
A: Assuming the following:
*
*You don't have a lot of experience with PHP
*The information that has been provided to you is correct
*This is an example script and you know the values that need to be substituted for $dbname, $dbhost, $dbuser and $dbpass
Please try the following and report back if you get any output at all to screen:
<?php
session_start();
print "Connecting and inserting email: ".$_POST['email']."...";
$dbhost = "###"; // this will ususally be 'localhost', but can sometimes differ
$dbname = "###"; // the name of the database that you are going to use for this project
$dbuser = "###"; // the username that you created, or were given, to access your database
$dbpass = "###"; // the password that you created, or were given, to access your database
$con = mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
$safe_email = mysql_real_escape_string($_POST['email']);
$sql="INSERT INTO register (email) VALUES ('{$safe_email}')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
print "success! Inserted email with row id: ".mysql_insert_id();
mysql_close($con)
?>
A: this may just be me but you should but strings on a single line or use the concatenation (.) for the strings
$sql="INSERT INTO register (email) VALUES ('$_POST[email]')";
Other than that you should clean the information before adding it into the database otherwise your asking for sql injection attacks.
now to the actual problem. your using a variable that is undefined called conn. i am assuming your referencing the connection made, but you never set that variable to the connection like so
$conn = mysql_connect($dblocal,$dbuser,$dbpass) or die(xxx);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: JavaScript authentication with c# sdk. What happens on server? I have made a JS authentication on local server, and it also went fluently on server side. As I understood the sdk cached up with the JS auth and all went well. But When I have uploaded this on server, the IsAuthorized method returned false after the JS auth. Why could that happend? And how does the sdk handle the JS auth?
A: Check your website url in the facebook app configuration page. Maybe the domain is now different?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I want my text box to allow vb script code as text without getting an error in asp.net website I have a TextBox and I want to allow VB syntax, but when I run the site and try to save the VB code to the database, I am getting an error. I believe the error has something to do with the VB code.
I have put the httpRuntime requestValidationMode="2.0" setting in my web.config, and I've added validateRequest="false" in the directive at the top of the page, but it didn't resolve the issue.
How can I solve this problem?
Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim ra As Integer
myConnection = New SqlConnection("Integrated Security=True")
myConnection.Open()
myCommand = New SqlCommand("INSERT INTO [tblScripts] ([Script],[Script_Name]) VALUES ('" & txtScript.Text & "','" & txtName.Text & "'", myConnection)
ra = myCommand.ExecuteNonQuery()
myConnection.Close() –
A: Use a parametrized query.
Your query is now building on the fly, so everything around "" is taking literal, and is taking as part as the original query.
You should pass parameters to it to avoid it (and also avoid SQL injections and so on)...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Any java code samples for session management in OSWAP ESAPI? The documentation provided in ESAPI for Java is incomplete. Does anyone have operational code samples to share for session management?
P.S.: Other code samples explaining where and how to start with ESAPI would be welcome too. Thanks.
A: I think your best bet for examples would be to 1) look at the JUnit tests for the session manangement, and 2) the relevant portions of 'Swingset' (http://code.google.com/p/owasp-esapi-java-swingset/) or 'Swingset Interactive' (http://code.google.com/p/owasp-esapi-swingset-interactive/).
That said, the ESAPI dev team knows that most of the ESAPI docs are woefully inadequate and are seeking volunteers to pick in and help make them usable.
-kevin
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: update multiple svn projects in eclipse Is it possible to update multiple svn projects in eclipse in one action? Lets say they all in same folder and in same svn.
I know how to do it using external tools.
A: With Subclipse you can select those projects and invoke Team / Update to HEAD. Subversive has similar action.
Alternatively, you can setup new synchronization in Synchronize view and use update all action from the view toolbar. The major advantage of this approach is that you can review incoming changes before updating your workspace.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: $("input").focus is not working I seem to be having a strange jQuery issue. On my page I have a number of text fields and select boxes and this code:
$('input').focus(function() { alert($(this).attr("name")); });
(this is a placeholder code to be completed later on). When the page loads, there are no errors. However focusing any of the text inputs does nothing - at all. I also tried selector $(':input') - with the same result.
What am I missing?
A: Try using a document ready block, to ensure the input you want to bind to is loaded before you try and add the event.
$(document).ready( function () {
$('input').focus( function() {
alert($(this).attr("name"));
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: can't change text area style to field_with_error I'm dealing with this legacy form for creating a new conversation. It has two fields : Name and description (the first comment of a conversation)
Here are the fields :
_fields.haml
.conversation_title= f.label :name, t('.name')
.clear
= f.text_field :name, :style => 'width: 230px'
= errors_for f.object, :name
if f.object.new_record?
= f.fields_for :comments, f.object.comments.build do |comment_fields|
.conversation_title= comment_fields.label :description, t('.description')
= comment_fields.text_area :body, :placeholder => t("comments.new.conversation"), :style => 'width: 545px'
= errors_for f.object, :comments
from the new view for conversations
= form_for [@current_project, @conversation], :html => { 'data-project-id' => @current_project.id, :name => 'form_new_conversation', :multipart => true } do |f| #, :onsubmit => 'return validate_form_new_conversation(form_new_conversation)'
= render 'fields', :f => f, :project => @current_project
= render 'watcher_fields', :f => f, :project => @current_project
The associated validations are :
conversation.rb
validates_presence_of :name, :message => :no_title, :unless => :simple?
validates_presence_of :comments, :message => :must_have_one, :unless => :is_importing
comment.rb
validates_presence_of :body, :unless => lambda { |c| c.task_comment? or c.uploads.to_a.any? or c.google_docs.any? }
For some reason, the proc associated to fields with error from base.rb
@@field_error_proc = Proc.new{ |html_tag, instance| "<div class=\"field_with_errors\">#{html_tag}</div>".html_safe }
doesn't get called for the text area, so it doesn't change its style to make it turn red. It does for the :name field. Error messages get displayed properly
What am I missing?
Thanks!
A: The validation would be for the Comment model (rather than the Conversation model) on the body field. Check to make sure that validation exists. You can debug this to make sure that comment_fields.object has an error set on the body field, too.
A: I failed to notice one important part of this line in your code:
= f.fields_for :comments, f.object.comments.build do |comment_fields|
You call f.object.comments.build which means that you will always end up with a new instance of Comment (rather than the instance that was validated in the controller).
To avoid this you can build a comment in the controller. If you are using the normal restful actions you probably have two places where you want to build a comment. First in the new action and second, in the create action.
def new
@conversation = Conversation.new
@conversation.comments.build # Create a blank comment so that the fields will be shown on the form
end
def create
@conversation = Conversation.new(params[:conversation])
respond_to do |format|
if @conversation.save
format.html { redirect_to conversations_path }
else
format.html {
@conversation.comments.build if @conversation.comments.blank? # Create a blank comment only if none exists
render :action => "new"
}
end
end
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: less-style markdown viewer for UNIX systems I have a Markdown string in JavaScript, and I'd like to display it (with bolding, etc) in a less (or, I suppose, more)-style viewer for the command line.
For example, with a string
"hello\n" +
"_____\n" +
"*world*!"
I would like to have output pop up with scrollable content that looks like
hello
world
Is this possible, and if so how?
A: If you are into colors then maybe this is worth checking as well:
terminal_markdown_viewer
It can be used straightforward also from within other programs, or python modules.
And it has a lot of styles, like over 200 for markdown and code which can be combined.
Disclaimer
*
*It is pretty alpha there may be still bugs
*I'm the author of it, maybe some people like it ;-)
A: Pandoc can convert Markdown to groff man pages.
This (thanks to nenopera's comment):
pandoc -s -f markdown -t man foo.md | man -l -
should do the trick. The -s option tells it to generate proper headers and footers.
There may be other markdown-to-*roff converters out there; Pandoc just happens to be the first one I found.
Another alternative is the markdown command (apt-get install markdown on Debian systems), which converts Markdown to HTML. For example:
markdown README.md | lynx -stdin
(assuming you have the lynx terminal-based web browser).
Or (thanks to Danny's suggestion) you can do something like this:
markdown README.md > README.html && xdg-open README.html
where xdg-open (on some systems) opens the specified file or URL in the preferred application. This will probably open README.html in your preferred GUI web browser (which isn't exactly "less-style", but it might be useful).
A: A totally different alternative is mad. It is a shell script I've just discovered. It's very easy to install and it does render markdown in a console pretty well.
A: I tried to write this in a comment above, but I couldn't format my code block correctly. To write a 'less filter', try, for example, saving the following as ~/.lessfilter:
#!/bin/sh
case "$1" in
*.md)
extension-handler "$1"
pandoc -s -f markdown -t man "$1"|groff -T utf8 -man -
;;
*)
# We don't handle this format.
exit 1
esac
# No further processing by lesspipe necessary
exit 0
Then, you can type less FILENAME.md and it will be formatted like a manpage.
A: I wrote a couple functions based on Keith's answer:
mdt() {
markdown "$*" | lynx -stdin
}
mdb() {
local TMPFILE=$(mktemp)
markdown "$*" > $TMPFILE && ( xdg-open $TMPFILE > /dev/null 2>&1 & )
}
If you're using zsh, just place those two functions in ~/.zshrc and then call them from your terminal like
mdt README.md
mdb README.md
"t" is for "terminal", "b" is for browser.
A: Using OSX I prefer to use this command
brew install pandoc
pandoc -s -f markdown -t man README.md | groff -T utf8 -man | less
Convert markupm, format document with groff, and pipe into less
credit: http://blog.metamatt.com/blog/2013/01/09/previewing-markdown-files-from-the-terminal/
A: This is an alias that encapsulates a function:
alias mdless='_mdless() { if [ -n "$1" ] ; then if [ -f "$1" ] ; then cat <(echo ".TH $1 7 `date --iso-8601` Dr.Beco Markdown") <(pandoc -t man $1) | groff -K utf8 -t -T utf8 -man 2>/dev/null | less ; fi ; fi ;}; _mdless '
Explanation
*
*alias mdless='...' : creates an alias for mdless
*_mdless() {...}; : creates a temporary function to be called afterwards
*_mdless : at the end, call it (the function above)
Inside the function:
*
*if [ -n "$1" ] ; then : if the first argument is not null then...
*if [ -f "$1" ] ; then : also, if the file exists and is regular then...
*cat arg1 arg2 | groff ... : cat sends this two arguments concatenated to groff; the arguments being:
*
*arg1: <(echo ".TH $1 7date --iso-8601Dr.Beco Markdown") : something that starts the file and groff will understand as the header and footer notes. This substitutes the empty header from -s key on pandoc.
*arg2: <(pandoc -t man $1) : the file itself, filtered by pandoc, outputing the man style of file $1
*| groff -K utf8 -t -T utf8 -man 2>/dev/null : piping the resulting concatenated file to groff:
*
*-K utf8 so groff understands the input file code
*-t so it displays correctly tables in the file
*-T utf8 so it output in the correct format
*-man so it uses the MACRO package to outputs the file in man format
*2>/dev/null to ignore errors (after all, its a raw file being transformed in man by hand, we don't care the errors as long as we can see the file in a not-so-much-ugly format).
*| less : finally, shows the file paginating it with less (I've tried to avoid this pipe by using groffer instead of groff, but groffer is not as robust as less and some files hangs it or do not show at all. So, let it go through one more pipe, what the heck!
Add it to your ~/.bash_aliases (or alike)
A: I personally use this script:
#!/bin/bash
id=$(uuidgen | cut -c -8)
markdown $1 > /tmp/md-$id
google-chrome --app=file:///tmp/md-$id
It renders the markdown into HTML, puts it into a file in /tmp/md-... and opens that in a kiosk chrome session with no URI bar etc.. You just pass the md file as an argument or pipe it into stdin. Requires markdown and Google Chrome. Chromium should also work but you need to replace the last line with
chromium-browser --app=file:///tmp/md-$id
If you wanna get fancy about it, you can use some css to make it look nice, I edited the script and made it use Bootstrap3 (overkill) from a CDN.
#!/bin/bash
id=$(uuidgen | cut -c -8)
markdown $1 > /tmp/md-$id
sed -i "1i <html><head><style>body{padding:24px;}</style><link rel=\"stylesheet\" type=\"text/css\" href=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css\"></head><body>" /tmp/md-$id
echo "</body>" >> /tmp/md-$id
google-chrome --app=file:///tmp/md-$id > /dev/null 2>&1 &
A: I'll post my unix page answer here, too:
An IMHO heavily underestimated command line markdown viewer is the markdown-cli.
Installation
npm install markdown-cli --global
Usage
markdown-cli <file>
Features
Probably not noticed much, because it misses any documentation...
But as far as I could figure out by some example markdown files, some things that convinced me:
*
*handles ill formatted files much better (similarly to atom, github, etc.; eg. when blank lines are missing before lists)
*more stable with formatting in headers or lists (bold text in lists breaks sublists in some other viewers)
*proper table formatting
*syntax highlightning
*resolves footnote links to show the link instead of the footnote number (not everyone might want this)
Screenshot
Drawbacks
I have realized the following issues
*
*code blocks are flattened (all leading spaces disappear)
*two blank lines appear before lists
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "53"
}
|
Q: Springframework PropertyPlaceholderConfigurer Have question on PropertyPlaceholderConfigurer. If properties file is changed, will spring loads it dynamically or do we have to start app for the changes to take effect?
A: They're loaded on startup.
But making them reloadable is completely doable.
A: The properties are resolved and injected into your beans (only) during application startup. The PropertyPlaceholderConfigurer does not monitor and reload the configuration file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Checkboxes and options don't persist in HTML 5 local storage I'm coming to an unexpected conclusion regarding HTML5 local storage persistence and inputs. When I use < input type="text" > or < input type="textarea" >, then the data persists in local storage and on page load loads back into fields at the push of a button. But when I use type="radio" type="checkbox" or < select > options, none of those types of data persists.
Is this behavior by design, and I'm pushing against a brick wall trying to make it work, or is it my form element scripting that needs an overhaul? If it's by design, then you can answer yes. If not, you can check the details of my work below to give it a checkup and any feedback.
The user enters data into textarea fields like this:
<textarea name="s1frontTowerShockMtgOther" id="s1frontTowerShockMtgOther" cols="20" rows="4">
Then they tap on the save button coded like this:
<input type="button" value="Save Settings" onclick="persistData()" style="background-color:red; font-weight:bold">
The Javascript page does its magic:
function persistData()
{
if (html5StorageSupported())
{
var s1frontTowerShockMtgOther = document.form1["s1frontTowerShockMtgOther"].value;
var storageIndex = "practicelog.html.s1frontTowerShockMtgOther";
localStorage[storageIndex] = s1frontTowerShockMtgOther;
document.form1.numStored.value = determineNumberStoredElements();
}
}
When the user returns to the page, he taps on this button to populate the fields on that page:
<input class="loadButton" type="button" value="Load Data First" onclick="loadData()">
The Javascript is called:
function loadData()
{
document.form1["s1frontTowerShockMtgOther"].value = localStorage["practicelog.html.s1frontTowerShockMtgOther"];
}
That's it. The following does not work:
<select size="1" name="frontTowerMtgShock" id="frontTowerMtgShock">
<option value="">Tap to choose</option>
<option value="0 spacers">3-outer</option>
<option value="1 spacer">2-middle</option>
<option value="2 spacers">1-inner</option>
<option value="other">See notes</option>
</select>
The following type="checkbox" does not work. It doesn't work if "checkbox" was replaced by "radio" either:
<input type="checkbox" name="s1frontTowerMtgShock3" id="s1frontTowerMtgShock3" value="3-outer">
I am doing this project for the iPhone with HTML, CSS, and Javascript through PhoneGap 1.0 integration.
A: The following works fine for me:
function persistData()
{
var s1frontTowerShockMtgOther = document.form1["s1frontTowerShockMtgOther"].value;
var storageIndex = "practicelog.html.s1frontTowerShockMtgOther";
localStorage[storageIndex] = s1frontTowerShockMtgOther;
storageIndex = "practicelog.html.frontTowerMtgShock";
var frontTowerMtgShock = document.form1["frontTowerMtgShock"].value;
localStorage[storageIndex] = frontTowerMtgShock;
}
function loadData()
{
alert(localStorage["practicelog.html.frontTowerMtgShock"]);
document.form1["frontTowerMtgShock"].value = localStorage["practicelog.html.frontTowerMtgShock"];
}
Have you double checked your storage keys when setting and retrieving?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I pass a connection string to the constructor of a database-first DBContext with Entity Framework 4.1? For various reasons I would like to not store the connection string for my Entity Framework DB model in one of the various .config files. (I am using the latest and greatest DBContext API with the new Entity Framework version 4.1, .NET 4 and Visual Studio 2010 C#.) However, the code generation template for DBContext only creates a single parameterless constructor. (If I don't use the DBContext API, then my entity framework model has 7 different constructors to chose from, including the one I want.)
The only way I could figure out how to do this was to directly modify the code-generation template (context.tt file) to give me the constructor I want (example code below). This works, but it feels like I'm doing it "the hard way". What is the correct way to get a DBContext constructor that accepts a connection string?
public <#=Code.Escape(container)#>(string connectionString)
: base(connectionString)
{
<#
WriteLazyLoadingEnabled(container);
#>
}
One final note in case it might help somebody else. Although this method works, it took me a while to realize that the "connection string" is not strictly the DB connection string, but rather the special entity framework connection string which contains the DB connection string (just like what would be stored in the app.config file).
A: Your approach looks like the most correct way to do this. It's what the t4 templates were created for, and you're basically doing the same thing that the model-first templates do by default.
Another possibility would be to make the db context class be partial (if it isn't by default) and create another partial class file alongside it to add the constructor you want. But it seems likely that you'll want all of your t4-generated contexts to follow this pattern, so I think it's best to leverage the code generation to do this automatically the way you do in the question.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: CursorLoader with rawQuery I'm looking into implementing CursorLoader in my app but I'm having a small issue that it seems that there isn't a way to just a pass a raw query to the CursorLoader constructor.
I maybe missing something in the documentation (and google), so if anybody can point me to a simple way to run a raw query with a CursorLoader class I would appreciate it. Otherwise I will have to probably create my own CursorLoader class with the necessary functionality, which I'm trying to avoid.
A:
it seems that there isn't a way to just a pass a raw query to the CursorLoader constructor.
That is because CursorLoader works with content providers, and content providers do not support rawQuery().
so if anybody can point me to a simple way to run a raw query with a CursorLoader class I would appreciate it.
That is impossible, sorry. You are welcome to create your own AsyncTaskLoader that hits a SQLite database and supports rawQuery(). In fact, I will probably write one of these later this year, if I don't see where anyone has beaten me to it.
A: Raw query is not supported directly, but you can do a dirty hack: from your code call
getContentResolver().query(RAWQUERY_CONTENT_URI, null, rawquery, args, null);
and implement content provider like
@Override
public synchronized Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder)
{
int uriType = sURIMatcher.match(uri);
switch (uriType)
{
case RAW_QUERY:
return dbHelper.getReadableDatabase().rawQuery(selection, selectionArgs);
}
[...]
}
A: **For Custom Search using Content provider **
Change Cursor Loader as Follow (in onCreateLoader )
return new CursorLoader(
getActivity(), // Context
PRODUCT.CONTENT_URI, // URI
PROJECTION, // Projection
PRODUCT.PRODUCT_NAME+ " like ?", // Selection
new String[]{"%" + mCurFilter + "%"}, // Selection args
PRODUCT.PRODUCT_NAME + " asc");
In your Provider Change Accordingly
//C is Cursor object
switch (uriMatch) {
case ROUTE_PRODUCT_ID:
// Return a single entry, by ID.
String id = uri.getLastPathSegment();
builder.where(PRODUCT._ID + "=?", id);
c = builder.query(db, projection, sortOrder);
assert ctx != null;
c.setNotificationUri(ctx.getContentResolver(), uri);
return c;
// break;
case ROUTE_PRODUCT:
// Return all known entries.
builder.table(PRODUCT.PRODUCT_TABLE_NAME)
.where(selection, selectionArgs);
c = builder.query(db, projection, sortOrder);
assert ctx != null;
c.setNotificationUri(ctx.getContentResolver(), uri);
return c;
A: You can implement your own CursorLoader with raw query. This is the source of the original CursorLoader: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/content/CursorLoader.java
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: why applied template is repeating twice hi i have applied a template data should to be populate only once, here issue was it was repeating twice can any one suggest to stop that repeatation find the below my sample code of xsl
Here is my XSL:
<xsl:param name="PackageId" />
<xsl:template match="/">
<xsl:apply-templates mode="SequenceB" select="NewDataSet/Table[CTD_CTD_PKG_ID =$PackageId]"/>
<xsl:apply-templates mode="sequenceC" select="NewDataSet/Table[CTD_CTD_PKG_ID =$PackageId][position()=1]"/>
</xsl:template>
<xsl:template mode ="SequenceB" match="NewDataSet/Table">
<xsl:choose >
<xsl:when test ="substring(./MSG_TYPE_CODE,2,3)= '102'" >
<xsl:if test ="./CTD_SEQ_NUM" >
<xsl:if test=" position() > 1"></xsl:if>
<xsl:value-of select= "concat(':21:',./CTD_SEQ_NUM)" />
<xsl:text> </xsl:text >
</xsl:if>
<xsl:if test ="./CURRENCY_CODE" >
<xsl:if test=" position() > 1"></xsl:if>
<xsl:text/><xsl:value-of select= "concat(':32B:',./CURRENCY_CODE)"/>
</xsl:if>
<xsl:if test ="./CTD_SETLD_TRAN_AMT" >
<xsl:if test=" position() > 1"></xsl:if>
<xsl:text/><xsl:value-of select= "translate(./CTD_SETLD_TRAN_AMT ,'.',',')"/>
<xsl:text> </xsl:text >
</xsl:if>
</xsl:when>
<xsl:when test ="substring(./MSG_TYPE_CODE,2,3)= '103'">
<xsl:if test ="./TRAN_TYPE_CODE" >
<xsl:text/><xsl:value-of select= "concat(':26T:',./TRAN_TYPE_CODE)" /><xsl:text/>
</xsl:if>
<xsl:if test ="./CTD_VALUE_DATE" >
<xsl:text/><xsl:value-of select= "concat(':32A:',./CTD_VALUE_DATE)"/><xsl:text/>
</xsl:if>
<xsl:if test ="./CURRENCY_CODE" >
<xsl:text/><xsl:value-of select= "./CURRENCY_CODE"/><xsl:text/>
</xsl:if>
<xsl:if test ="./CTD_SETLD_TRAN_AMT" >
<xsl:text/><xsl:value-of select= "translate(./CTD_SETLD_TRAN_AMT,'.',',')"/><xsl:text/>
</xsl:if>
</xsl:when>
</xsl:choose>
</xsl:template>
<xsl:template mode="sequenceC" match="NewDataSet/Table">
<xsl:if test ="substring(./MSG_TYPE_CODE,2,3)= '102'">
<xsl:if test ="./CTD_VALUE_DATE" >
<xsl:text/><xsl:value-of select= "concat(':32A:',./CTD_VALUE_DATE)"/><xsl:text/>
</xsl:if>
<xsl:if test ="./CURRENCY_CODE" >
<xsl:text/><xsl:value-of select= "./CURRENCY_CODE"/><xsl:text/>
</xsl:if>
<xsl:if test ="./CTD_SETLD_TRAN_AMT" >
<xsl:text/><xsl:value-of select= "translate(./CTD_SETLD_TRAN_AMT,'.',',')"/>
<xsl:text> </xsl:text >
</xsl:if>
</xsl:template>
Here is my XML:
<?xml version="1.0" standalone="yes"?>
<NewDataSet>
<Table>
<RECORD_TYPE_CODE>CTD</RECORD_TYPE_CODE>
<MSG_TYPE_CODE>O102N</MSG_TYPE_CODE>
<CTD_SEQ_NUM>000001</CTD_SEQ_NUM>
<CTD_BEN_INS_ID>ABNAAEAD</CTD_BEN_INS_ID>
<TRAN_TYPE_CODE>MIS</TRAN_TYPE_CODE>
<CTD_VALUE_DATE>110911</CTD_VALUE_DATE>
<CURRENCY_CODE>AED</CURRENCY_CODE>
<CTD_SETLD_TRAN_AMT>42404.00</CTD_SETLD_TRAN_AMT>
<CTD_INS_AMT>42404.00</CTD_INS_AMT>
<CTD_CTD_PKG_ID>2</CTD_CTD_PKG_ID>
</Table>
<Table>
<RECORD_TYPE_CODE>CTD</RECORD_TYPE_CODE>
<MSG_TYPE_CODE>O102N</MSG_TYPE_CODE>
<CTD_SEQ_NUM>000002</CTD_SEQ_NUM>
<CTD_BEN_INS_ID>ABNAAEAD</CTD_BEN_INS_ID>
<TRAN_TYPE_CODE>MIS</TRAN_TYPE_CODE>
<CTD_VALUE_DATE>110911</CTD_VALUE_DATE>
<CURRENCY_CODE>AED</CURRENCY_CODE>
<CTD_SETLD_TRAN_AMT>154776.75</CTD_SETLD_TRAN_AMT>
<CTD_INS_AMT>154776.75</CTD_INS_AMT>
<CTD_CTD_PKG_ID>2</CTD_CTD_PKG_ID>
</Table>
<Table>
<RECORD_TYPE_CODE>CTD</RECORD_TYPE_CODE>
<MSG_TYPE_CODE>O102N</MSG_TYPE_CODE>
<CTD_SEQ_NUM>000003</CTD_SEQ_NUM>
<CTD_BEN_INS_ID>ABNAAEAD</CTD_BEN_INS_ID>
<TRAN_TYPE_CODE>MIS</TRAN_TYPE_CODE>
<CTD_VALUE_DATE>110911</CTD_VALUE_DATE>
<CURRENCY_CODE>AED</CURRENCY_CODE>
<CTD_SETLD_TRAN_AMT>1800.00</CTD_SETLD_TRAN_AMT>
<CTD_INS_AMT>1800.00</CTD_INS_AMT>
<CTD_CTD_PKG_ID>2</CTD_CTD_PKG_ID>
</Table>
</NewDataSet>
output:
:21:000001
:32B:AED42404,00
:21:000001
:32B:AED42404,00
:21:000002
:32B:AED154776,75
:21:000002
:32B:AED154776,75
:21:000003
:32B:AED1800,00
:21:000003
:32B:AED1800,00
:32A:110911AED42404,00
required output as :
:21:000001
:32B:AED42404,00
:21:000002
:32B:AED154776,75
:21:000003
:32B:AED1800,00
:32A:110911AED42404,00
A: In your first template you have several times the following line:
<xsl:if test=" position() > 1"></xsl:if>
This line doesn't do anything, code that is to be executed only when the condition is true should go between the tags (as you have done in other places).
Similarly, you have this kind of stuff in a few places:
<xsl:text/><xsl:value-of select= "./CURRENCY_CODE"/><xsl:text/>
The text tags serve no purpose as they are auto closing.
You should make a round of clean up on the opening/closing of all the tags. Even if the problem does not disappear, it will be a lot easier to analyze.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599462",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Purposefully Corrupting a FAT File System? Is there a way to purposefully corrupt a FAT file system using only Win32 calls or must you do it at lower level? We're encountering FAT corruption on a WinCE 5.0 device and have written a utility to detect and attempt to correct it, but don't have a means to create FAT corruption on demand. Thanks.
The media is a CF card, but it's not removable as a normal course as it's mounted internal to the device.
A: You can access device data as a raw file and write random data in that file to corrupt FAT. E.g. if you write random data on:
\?\Device\HarddiskVolume1
This would corrupt first partition.
This page has some hints on how to figure out paths for HDD/USB drive etc.
http://www.chrysocome.net/dd
A: What's the FAT on (e.g. inserted USB, on-board flash, etc)? That's going to make a large difference.
If it's the on-board flash, you need to get underneath the file system driver (FSD), which is typically going to be the flash driver itself. It's going to have access to the raw flash sectors (it's what the FSD uses for its reads and writes) either through Xxx_Write or Xxx_Ioctl. Exactly how it works is going to depend on the flash driver in use, so looking at the driver source is your best path.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Printing stack traces I have a very short test file:
let print_backtrace () = try raise Not_found with
Not_found -> Printexc.print_backtrace stdout;;
let f () = print_backtrace (); Printf.printf "this is to make f non-tail-recursive\n";;
f ();
I compile and run:
% ocamlc -g test.ml
% OCAMLRUNPARAM=b ./a.out
Raised at file "test.ml", line 1, characters 35-44
this is to make f non-tail-recursive
Why isn't f listed in the stack trace? How can I write a function that will print a stack trace of the location it's called from?
A: The documentation for Printexc.print_backtrace says:
The backtrace lists the program locations where the most-recently raised exception was raised and where it was propagated through function calls.
It actually seems to be doing the right thing. The exception hasn't been propagated back through f.
If I move the call to Printexc.print_backtrace outside the call to f, I see a full backtrace.
$ cat test2.ml
let print_backtrace () = raise Not_found
let f () = let res = print_backtrace () in res ;;
try f () with Not_found -> Printexc.print_backtrace stdout
$ /usr/local/ocaml312/bin/ocamlc -g test2.ml
$ OCAMLRUNPARAM=b a.out
Raised at file "test2.ml", line 1, characters 31-40
Called from file "test2.ml", line 3, characters 21-39
Called from file "test2.ml", line 5, characters 4-8
A: Here is the code to do what I suggested. I recommend using ocamldebug if at all possible, this code is much too tricky. But it works on my system for this simple example.
let print_backtrace () =
match Unix.fork () with
| 0 -> raise Not_found
| pid -> let _ = Unix.waitpid [] pid in ()
let f () =
begin
print_backtrace ();
Printf.printf "after the backtrace\n";
end
;;
f ()
Here is a test run.
$ /usr/local/ocaml312/bin/ocamlc unix.cma -g test3.ml
$ OCAMLRUNPARAM=b a.out
Fatal error: exception Not_found
Raised at file "test3.ml", line 3, characters 17-26
Called from file "test3.ml", line 8, characters 4-22
Called from file "test3.ml", line 14, characters 0-4
after the backtrace
I realized that because of the uncaught exception, you don't really have any control over the way the child process exits. That's one reason this code is much too tricky. Please don't blame me if it doesn't work for you, but I hope it does prove useful.
I tested the code on Mac OS X 10.6.8 using OCaml 3.12.0.
Best regards,
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How do I extract data from XML columns into their own columns? I have 280,000 rows that contain a column called body. This column has xml data.
A copy of one column value is shown below. I need to extract into new columns the data contained in the elements of the XML field esn, timestamp_utc, Latitude, Longitude, and triggers, with the column names being the same as the element names.
I have worked on this in the past, but gave up on it. I am not at a point I need to figure out how to do it. Please give me any suggestions you may have.
Thank you!!!
<?xml version="1.0" encoding="UTF-8"?>
<telemetry>
<esn>1127877</esn>
<timestamp_utc>5/28/2011 9:18:30 PM</timestamp_utc>
<latitude>59.023672</latitude>
<longitude>-118.836408</longitude>
<ignition>N</ignition>
<geofence>0</geofence>
<speed>0</speed>
<heading>0</heading>
<milestraveled>0.00</milestraveled>
<triggers>Contact_State_Change, IO_1_Closed, No_Vibration_Detected, </triggers>
<miscellaneous>Standard3</miscellaneous>
<contact1counts>0</contact1counts>
<contact2counts>0</contact2counts>
<io1state>0</io1state>
<io2state>0</io2state>
</telemetry>
A: You can use something like this:
SELECT
ID,
body.value('(telemetry/esn)[1]', 'bigint') AS 'esn',
body.value('(telemetry/timestamp_utc)[1]', 'varchar(50)') AS 'esn',
body.value('(telemetry/longitude)[1]', 'float') AS 'longitude',
body.value('(telemetry/latitude)[1]', 'float') AS 'latitude',
body.value('(telemetry/timestamp_utc)[1]', 'varchar(50)') AS 'triggers'
FROM
dbo.YourTableNameHere
Does that work, and give you the right data??
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What is the correct way to install Google Go and App Engine SDK? I've been playing with Go and GAE using GoClipse for a bit now on my Mac (since they won't run on Windows). Recently I noticed that when I goinstall a package from github it had some problems working. I figured I'd reinstall the whole thing and set it up properly. Go installed nicely, but when it came to integrating the GAE SDK it took me a couple hours of searching and came up with only this article:
http://code.google.com/p/goclipse/wiki/GoClipseAndTheGoogleAppEngine
But since it tell you to move files from the go/scr folder (where goinstall installs packages), I reckon it is not the correct way to set everything up.
Can anyone give me a clear, easy to follow step-by-step guide on how to install both Go and GAE SDK on a Mac?
A: The short answer is that Go and the GAE SDK do not integrate in the way that (I think) you are looking for. The GAE SDK includes its own version of the Go toolchain that differs in some important ways to the standard tools. Those differences are deep enough that it is unlikely you will derive much utility from trying to unify the two. Here are the big differences:
*
*GAE does not support some packages from the standard lib e.g. "unsafe"
*GAE does not support CGO
*GAE often lags the main distribution by one or more major versions
*You cannot use any binary libraries (go or otherwise) in a GAE project (you need source for everything)
*goinstall is not intended for use with GAE projects
Because of this I treat my GAE and non-GAE tools as completely separate. If you're only doing GAE development, you could do without the standard tools altogether.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Fibonacci Search Somebody please explain me the fibonacci search algorithm.
I have tried numerous resources around and searched a lot, but the algorithm is still unclear. Most of the resources described it in link with binary search, but I didn't understand 'em. I know fibonacci search algorithm is an extension of binary search, which I know quite well.
My books failed to explain as well.
I know about fibonacci numbers defined as F(n) = F(n-1) + F(n-2), so no need to explain that.
Updating the question by adding what exactly I didn't understand as @AnthonyLabarre said:
The book I'm using has strange symbols without any explanations. Posting the algo here, please help.
if(key == a[mid]) return mid; // understood this, comes from binary search
if(key > a[mid]) {
if(p == 1) return -1; // What is p? It comes as a function arg
mid = mid + q; //Now what's this q? Again comes a function arg
p = p - q; // Commented as p=fib(k-4)
q = q-p; // q = fib(k-5)
} else // key < a[mid] {
if(q == 0) return -1;
mid = mid - q;
temp = p - q;
p = q; // p=fib(k-3)
q = temp; // q = fib(k-4)
return fibsearch(a, key, mid, p, q);
}
A: The references provided in the comments are correct, but I'll try and word it differently for you.
It continually divides the list into sublists whose length is a number in the Fibonacci sequence (n = F(m)), then it searches at the next to last index which is also in the Fibonacci sequence (F(m-1)).
So if a list or sublist is n items long, where n = F(m), it will search at F(m-1) first, then if the sought value is greater than the found value, it will then work with the sublist from F(m-1)+1 to F(m), or if the sought value is less than the found value, it will work with the sublist from 1 to F(m-1).
Due to the nature of Fibonacci numbers, either of these sublists will also have a length that is a Fibonacci number, and the process will repeat. The advantage of the algorithm is that at each step the next address searched in the list will be closer to the current address than at the same step of a normal binary search, which is why this algorithm has an advantage in slow sequential access media such as tape drives.
A: I'll try to keep things short and clear. Let's say you have a sorted Array A. This array has elements in it, in increasing values. You must find a particular element inside this array. You want to partition this whole Array into sub arrays such that the access time to i th element in the Array is not directly proportional to i. That means a non liner quicker method. Here comes Fibonacci Series in help. One of the most important properties of Fibonacci series is the "golden ratio". You partition the array into sub-arrays at indexes which fall in fibonacci series (0,1,1,2,3,5,8,13,21, 34...).
So your array will be partitioned into intervals like A[0]...A[1], A[1]...A[1], A[1]...A[2], A[2]...A[3], A[3]...A[5], A[5]...A[13], A[13]...A[21], A[21]...A[34], and so on. Now since the array is sorted, just by looking at the starting and ending element of any partition will tell you which partition your number lies in. So, you traverse the elements A[0], A[1], A[2], A[3], A[5], A[8], A[13], A[21], A[34]... unless the current element is greater than the element you are looking for. Now you are sure that your number lies between this current element and the last element you visited.
Next, you keep the elements from A[f(i-1)]..A[f(i)], where i is the index you were currently traversing; f(x) is fibonacci series, and repeat the same procedure unless you find your element.
If you try to calculate the complexity of this approach, this comes to be O(log(x)). This has the advantage of reducing the "average" time required to search.
I believe you should be able to write down the code yourself.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Scroll View ignoring contentInset for large content areas I have an app which loads in a grid of images. I've used contentInset so that I have a nice 10pt margin at the top. When I load in an array of images that total less that the scrollView area, it works great. But when I load in an array of images that total more than the scrollView area, it completely ignores the contentInset value.
If I scroll down then back up it then acknowledges the fact there is a margin there. I'm going out of my mind trying to find out why. Anyone experienced this before?
float tempNumber = ((float)[faceArray count] / 3);
int numberOfRows = ceil(tempNumber);
// CGSizeMake (x, y, w, h)
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width,
(numberOfRows * (kThumbSpace + kThumbnailSize)));
scrollView.pagingEnabled = NO;
scrollView.showsVerticalScrollIndicator = YES;
scrollView.delegate = self;
scrollView.contentInset = UIEdgeInsetsMake(10.0, 0, 0, 0);
scrollView.alwaysBounceVertical = YES;
//.... code is then sent to a method which creates the grid of subviews in order
// to fill the scrollView
A: You could set the contentOffset property so that the scroll view always starts in the right position. It looks like it is automatically moving itself to show you as many subviews as possible, not sure if that is a setting somewhere you could change.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to implement Mobile express checkout using php I have created one php page and upon click of "Checkpres checkout" just redirecting into paypal sandbox url, however it's not working. We are using the php url in android webview to do payment everything. So i need your help to solve the problem. What are the information i need to POST to mobile paypal express checkout and with return, cancel url details?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I know the server path for adding to an include_path I have everything working locally with php_value include_path "C:/wamp/www/project" in my htaccess file, but I don't know what to set this value to once it's uploaded to the server. I tried the actual url but it didn't work; I'm guessing this needs to be relative to the server, but I'm not sure how to extrapolate the appropriate server path.
A: One of the ways is to upload a test script to your server and
echo dirname(__file__);
You can see the path of the directory in which your file is.
Another way is to
echo $_SERVER['DOCUMENT_ROOT']'
I hope it helps.
A: if you have "library.php" in your C:/wamp/www/project/libs you'd use
php_value include_path "C:/wamp/www/project/libs/"
and using it like
include("library.php");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Showing MultiPle UserControl in a Window as ChildWindows I have developed a WPF ERP in which i have a single main window and rest windows i have created as UserControls...
Currently I am displaying the user controls in a ContentFrame in the MainWindow but my problem is that i can only display a single user control in a WPF Content Frame and i cant create a Content Frame dynamically...
How can i overcome this...
I have opened the child window as
Stock s=new Stock(); //UserControll
mainGrid.Children.Add(s);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: OpenAL buffer update in real-time I'm working in iOS and have a simple OpenAL project running.
The difference to most openAL projects i've seen is that im not loading in a sound file. Instead I load an array of raw data into the alBufferData. Using a couple of equations I can load in data to produce white noise, sine and pulse waves. And all is working well.
My problem is that I need a way to modify this data whilst the sound is playing in real-time.
Is there a way to modify this data without having to create a new buffer (i tried the approach of creating a new buffer with new data and then use it instead but its nowhere near quick enough).
Any help or suggestions of other ways to accomplish this would be much appreciated.
Thanks
A: I haven't done it on iOS, but with openAL on the PC what you would do is chain a few buffers together. Each buffer would have a small time period's worth of data. Periodically, check to see if the playing buffer is done, and if so, add it to a free list for reuse When you want to change the sound, write the new waveform into a free buffer and add it to the chain. You select the buffer size to balance latency and required update rate - smaller buffers allow faster response to changes, but need to be generated more often.
This page suggests that a half second update rate is doable. Whether you can go faster depends on the complexity of your calculations as well as on the overhead of the OS.
A: Changing the data during playback is not supported in OpenAL.
However, you can still try it and see if you get acceptable defaults (though you'll be racing against the OpenAL playback mechanism, and any lag-outs in your app could throw it off, so do this at your own risk).
There's an Apple extension version of ALBufferData that tells OpenAL to use the data you give it directly, rather than making its own local copy. You set it up like so:
typedef ALvoid AL_APIENTRY (*alBufferDataStaticProcPtr) (const ALint bid,
ALenum format,
const ALvoid* data,
ALsizei size,
ALsizei freq);
static alBufferDataStaticProcPtr alBufferDataStatic = NULL;
alBufferDataStatic = (alBufferDataStaticProcPtr) alcGetProcAddress(NULL, (const ALCchar*) "alBufferDataStatic");
Call alBufferDataStatic() it like you would call alBufferData():
alBufferDataStatic(bufferId, format, data, size, frequency);
Since it's now using your sound data buffer rather than its own, you could conceivably modify that data and it won't be the wiser (provided you're not modifying things too close to where it's currently playing from in the buffer).
However, this approach is risky, since it depends on timing you're not fully in control of. To be 100% safe you'll need to use Audio Units.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: PHP mysql_db_query being deprecated. Can't fix it I'm getting the following error while connecting to my SQL database:
function mysql_query($query) {
$dbhost = "localhost";
$dbuser = "p39438_***";
$dbpass = "password";
$dbname = "p31417_***";
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($dbname); }
Using mysql_query gives me this error:
Cannot redeclare mysql_query() in
/home/p39438/domains/*/public_html/_/includes/functies.php
on line 10
A: Try mysql_query() not just query(). Also, don't put POST variables directly into a SQL query. That's a very bad idea.
A: You haven't actually EXECUTED your query:
$sql = "....";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result);
A: The function is mysql_query not query. There's a theme with these mysql function names...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get an array size in a function without counting or passing the length as a parameter? I tried use sizeof(array)/sizeof(int), but it seems this doesn't work if I passed the array into another function. So is there any other way to know the size of the array?
By the way: I know a char[] ends with '\0'; which character ends the int[]?
A: In C, there is a difference between an array and a pointer to data. When "passing an array to a function", you in effect pass a pointer to the function. Unfortunately, you can't know if a pointer points to one element, or to a sequence of elements, and it's not possible to tell how many elements the sequence consist of.
Also, unlike a string, an int array is not ended with a specific value.
A: A char array only ends with a \0 if it's being explicitly treated as a null-terminated string. There's no terminating character on arrays in general and no way to know the size of an array without passing the size around with it.
A: When an expression of array type appears in most contexts1, it is implicitly converted ("decays") to an expression of pointer type and its value is the address of the first element in the array. Similarly, in the context of a function parameter declaration (but only in that context), declarations like T a[] and T a[N] are interpreted as T *a; despite the array notation, the parameter a is a pointer, not an array type.
So given code like
int arr[10];
...
foo(arr);
The type of the expression arr in the call to foo is "10-element array of int". In this context, the type of the expression is converted to "pointer to int", so foo will receive a pointer value.
Similarly, given a function definition
void foo(int a[10])
{
...
}
the type of the parameter a is not "10-element array of int", but rather "pointer to int".
In short, you cannot pass an array argument to a function and have it received as an array type; all you get is a pointer value. As a result, you must either pass the array size as a separate parameter, or terminate the array with a sentinel value (such as using a 0 in an array of char to terminate strings).
1 The exceptions to this rule are when the array expression appears as an operand to either the sizeof or unary & operators, or if it is a string literal being used to initialize another array in a declaration.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is SVN global ignore recursive? I am new to SVN, and I want to ignore a directory recursively, like in Git. I have a directory, sample, which I want to ignore recursively.
>svn status
sample/first/1.jpg
sample/second/2.jpg
sample/third/3.jpg
I have tried:
*
*svn ps svn:ignore "*" . (under the sample directory)
*Setting global ignores in ~/.subversion/config as global-ignores = sample.
But still it shows the same result when I run svn status:
>svn status
sample/first/1.jpg
sample/second/2.jpg
sample/third/3.jpg
How can I recursively ignore a directory in SVN?
A: svn -R propset svn:ignore . -F somefile.txt
Where somefile.txt is a file containing all the svn ignore patterns you want recursively set.
A: If you want to ignore the directory samples and all the content within, you must set svn:ignore in the directory containing the samples directory. You did it within samples itself. Please note two things:
*
*svn:ignore affects only unversions files. This means, that files and directories already known to SVN will still show up.
*svn:ignore settings are not cumulative or recursive. If you want to ignore only the *.jpg files in you treee, you have to set svn:ignore to *.jpg in each directory.
Please note, that the command svn propset has an -R (aka. recursive) option, which might help. But keep in mind, that propset is not propadd. This is of course only a concern if you want to set different values in the tree.
A: There is a new SVN property to do this from SVN 1.8 onwards. See the bottom of this page from the SVN book:
svn:global-ignores
It applies to the folder you set it on and everything underneath, and you do not need to specify recursive. For example, to set on the current directory:
svn propset svn:global-ignores "bin obj" .
A: From http://svnbook.red-bean.com/en/1.5/svn-book.html#svn.advanced.props.special.ignore :
"The patterns found in the svn:ignore property apply only to the directory on which that property is set, and not to any of its subdirectories."
[...]
"Once an object is under Subversion's control, the ignore pattern mechanisms no longer apply to it. In other words, don't expect Subversion to avoid committing changes you've made to a versioned file simply because that file's name matches an ignore pattern—Subversion always notices all of its versioned objects."
You could use the -R flag but that only applies the property recursivly - it doesn't change the properties effect so won't apply to any new directories created.
Also I suggest using propedit instead of ps as it allows mulitline edit, otherwise it's tricky to deal with more than one ignore pattern.
A: For those on *nix:
Although the documentation implies that ~.subversion/config should already have the default configuration in it, mine (SVN 1.6.17 on Ubuntu) was empty.
Here's the format I finally got to work (this is the entire file), includes the default settings and I've added *.ignore on the end:
[Miscellany]
global-ignores=*.o *.lo *.la #*# .*.rej *.rej .*~ *~ .#* .DS_Store *.ignore
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: How to edit the commit message of a git merge I have merged with other branch, and there are few commits after merge, before pushing i want to change the message of the merge. git rebase -i is not displaying the merge commit.
A: Not sure if there is a more elegant version, but what you can do is the following:
git checkout <sha of merge>
git commit --amend # edit message
git rebase HEAD previous_branch
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: How can I delete the clicked item from my database... I am new entry for android lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
AlertDialog.Builder adb=new AlertDialog.Builder(activity2.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete " + arg0);
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Delete", Toast.LENGTH_LONG).show();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to change table columns name's prefix? I have a table like this below,
Field Type Collation Attributes Null Default
cde_id int(10) No 0
cde_title varchar(255) utf8_general_ci Yes NULL
cde_content mediumtext utf8_general_ci Yes NULL
pg_id varchar(255) utf8_general_ci Yes 0
cde_created timestamp No 0000-00-00 00:00:00
But I want to change the columns name's prefix from 'cde' to 'code'.
I use this query to change the name,
ALTER TABLE root_page_embed_codes
CHANGE cde_id code_id int(10)
Then I find that it is not dynamic enough because the column types are different from one to another and I have a foreign key - pg_id as well.
Any query method that I can use to change the prefix in a easier way?
A: An int in mysql is an int, always. The (10) portion is merely a hint to MySQL as to how many digits it should display. Regardless if whether you want 1 digit or 10, it's still going to be the same integer value definition internally.
What exactly do you mean, "not dynamic enough"? Changing the cde_id field's name won't affect pg_id field in any way.
followup: You can chain multiple field changes in a single alter query:
ALTER TABLE root_page_embed_codes CHANGE cde_id code_id int, cde_content code_content mediumtext, cde_created code_created timestamp
You can't get around having to specify the "new" field type, however, as MySQL is not smart enough to realize you're just renaming the field and not wanting to change anything BUT the name. There's no "rename" for fields as there is for tables and databases, unfortunately.
A: MySQL does not care about dependent FK when field is being renamed. As Luc M suggested - you should recreate the FK.
Also, you can try to rename this field in dbForge Studio for MySQL (Express Edition):
*
*Select field in the Database Explorer
*Rename it (press F2 or select Rename in popup menu)
*Click on 'Refactor' button in a message box. It will rename selected field and recreate all related foreign keys.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python: Confused about random.choice within join Here is my code:
s = 'Hello world'
c = ['a','b','c','d','e','f']
n = ['1','2','3','4','5','6']
l = [random.choice(c),random.choice(n)]
return ''.join('%s%s' % (x, random.choice(l) if random.random() > 0.5 else '') for x in s)
This will output:
He5lloe w5o5rl5de
But what I am aiming for is something like this code would produce:
s = 'Hello world'
n = ['1','2','3','4','5','6']
return ''.join('%s%s' % (x, random.choice(n) if random.random() > 0.5 else '') for x in s)
Which is:
H4e3l3l6o wo4r3ld
It would be great if someone could also explain as to why the two are reacting differently than I would have assumed.
Sorry, I should have stated my intentions. I would like to randomly select an element from the two lists through each iteration of the for loop within join. Instead what I have is 2 elements being selected once and randomly choosing between the two elements selected.
This is what I don't want:
n = [1,2,3,4,5]
s = ['!','-','=','~','|']
l = [random.choice(n), random.choice(s)] # 1,!
# He1l!lo W!or1l!d
This is what I want:
n = [1,2,3,4,5] # 1 or 2 or 3... etc.
s = ['!','-','=','~','|'] # ! or - or =... etc.
> code to randomly select a list and a new element from that list
# He4ll-o W!or3l~d
Not sure if I have worded myself correctly, but hopefully it is understandable,
A: By doing l = [random.choice(c),random.choice(n)] you're limiting random.choice(l) to only 2 possible chars (one from each list c and n).
Try this instead:
from random import random, choice
s = 'Hello world'
c = ['a','b','c','d','e','f']
n = ['1','2','3','4','5','6']
L = choice([c, n]) # randomly choose either c or n
return ''.join('%s%s' % (x, choice(L) if random() > 0.5 else '') for x in s)
As an aside, assuming you want to keep the probability of an insertion at 0.5, that can also be written as:
# for each char, either append an empty string or a random char from list
return ''.join('%s%s' % (x, choice((choice(L), ""))) for x in s)
Update
Note that the above answer chooses a substitution list (c or n) and uses it for the whole process. If you want to be able to use both lists in the substitution, you can either create an intermediate list (L = c + n), or perform the list selection in-line.
# This is rather convoluted
return ''.join('%s%s' % (x, choice((choice(choice([c, n])), ""))) for x in s)
Alternatively,
e = ("", ) # tuple with a single empty element
return ''.join('%s%s' % (x, choice(choice([c, n, e, e]))) for x in s)
*
*Choose between c, n, or empty list e (e appears twice to keep the non-empty probability at 50%. Change as required)
*From the chosen list/tuple, choose a random element
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Change the underscore to input area in HTML <P class="p3"><FONT class="ft4">Full Names as in Passport /NRIC_____________________________________________________________________</FONT></P>
As you can see, this is part of an HTML form. I want the long underscore to change to a text input area with the same length and as user types I want to display the words above. Please kindly help me, thanks. I have tried and havent gotten very far.
A:
input.user_input {
border: none;
border-bottom: 1px solid black;
}
input.user_input:focus {
box-shadow: 0 4px 2px -2px #666;
outline-width: 0;
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>My form</title>
</head>
<body>
<form action="form_action.php" method="get">
<fieldset>
<legend>My form</legend>
<label>First name</label>
<input type="text" name="fname" class="user_input" />
<input type="submit" value="Submit" />
</fieldset>
</form>
</body>
</html>
A: Try
<input type="text" style="border: none; border-bottom: 1px solid black;">
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599510",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: libc++ vs VC++: Can non-UTF conversions be done with wstring_convert? The C++11's std::wstring_convert works great* for the standard UTF-8 <-> UTF-16/UCS2/UCS4 conversions. However, when I attempted to instantiate a wstring_convert or wbuffer_convert with a facet not from <codecvt>, it didn't work as expected:
// works as expected
std::wstring_convert<std::codecvt_utf8<wchar_t>> ucs4conv;
// Now, by analogy, I want to try this:
std::wstring_convert<std::codecvt<wchar_t, char, std::mbstate_t>> gbconv(
new std::codecvt_byname<wchar_t, char, std::mbstate_t>("zh_CN.gb18030"));
Clang++ errors out saying "calling a protected destructor of codecvt<> in ~wstring_convert"
Visual Studio allows it (although it lacks that locale, but that's another story), because its wstring_convert pawns the lifetime management of the facet pointer off to a locale object it holds as a member, and locales know how to delete pointers to all facets.
Is Visual Studio right and libc++ wrong?
* as implemented in clang++-2.9/libc++-svn and Visual Studio 2010 EE SP1, the following example works on both, but not in GCC, sadly: https://ideone.com/hywz6
A: I am admittedly biased in this answer. But I will attempt to back up my claims with references to N3290 (which is unfortunately no longer publicly available). And I will also offer a solution.
Analysis:
The synopsis of wstring_convert in [conversions.string]/p2 includes:
private:
byte_string byte_err_string; // exposition only
wide_string wide_err_string; // exposition only
Codecvt *cvtptr; // exposition only
state_type cvtstate; // exposition only
size_t cvtcount; // exposition only
The "exposition only" means that the wstring_convert doesn't have to have these members in this order by this spelling. But "exposition only" members are used to describe the effects of various members, and those specifications are binding.
And so the question appears to become:
What is the specification of ~wstring_convert()?
This is found in p17 of the same section ([conversions.string]):
~wstring_convert();
Effects: The destructor shall delete cvtptr.
That implies to me that ~Codecvt() must be accessible, and therefore libc++ is following the C++11 specification.
I would also agree that this is a royal pain in the butt.
Solution:
Having all of the C++98/03 facets have protected destructors has turned out to be very inconvenient. Here's an adaptor that can take any facet and give it a public destructor:
template <class Facet>
class usable_facet
: public Facet
{
public:
template <class ...Args>
usable_facet(Args&& ...args)
: Facet(std::forward<Args>(args)...) {}
~usable_facet() {}
};
You can now use this general purpose adaptor in your code:
typedef usable_facet<std::codecvt<wchar_t, char, std::mbstate_t>> C;
std::wstring_convert<C> gbconv(new C("zh_CN.gb18030"));
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599514",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: PHP undefined index error when clicking a url and invoking a php script I have a call to a PHP script from my home page which I do like this:
echo '<a href="/problems/delete_problem.php?problem_id='.$problem_id.'">Delete</a>';
So it is pretty standard.
Then in my PHP I have this code:
<?php
// delete_problem
include '../connect.php'; // Here I have db connection settings
error_log ( ".......in delete problem");
$problem_id = mysql_real_escape_string($_GET["problem_id"]);
?>
And the last line where I try to get the problem_id is throwing the undefined index error. Any idea why?
Thanks!
A: Have you got an actual connection inside connect.php? Or does it just store variables and the like?
mysql_real_escape_string may be causing a problem as if a connection is not available it will fail.
Beyond that, try echoing out the contents of the GET variable. You can also check whether it exists by using (isset($_GET["problem_id"])).
A: For values coming from the user, always make sure they are present and possibly validate their format.
Use:
if (isset($_GET['problem_id']) && trim($_GET['problem_id']) != '') {
$problem_id = $_GET['problem_id'];
// make sure it is a number
} else {
echo "No problem id given!";
}
That warning appears because the $_GET array doesn't contain a value problem_id, most likely because it was not passed with the URL.
A: Bleh, all you people with the mysql_real_escape string...
Always check if a variable is set before you try and assign the value of it to another variable.
Also use (int) to cast!!
if (isset($_GET["problem_id"])){
$problem_id = (int) $_GET["problem_id"];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ALTER TABLE ADD COLUMN takes a long time I was just trying to add a column called "location" to a table (main_table) in a database. The command I run was
ALTER TABLE main_table ADD COLUMN location varchar (256);
The main_table contains > 2,000,000 rows. It keeps running for more than 2 hours and still not completed.
I tried to use mytop
to monitor the activity of this database to make sure that the query is not locked by other querying process, but it seems not. Is it supposed to take that long time? Actually, I just rebooted the machine before running this command. Now this command is still running. I am not sure what to do.
A: I think the appropriate answer for this is using a feature like pt-online-schema-change or gh-ost.
We have done migration of over 4 billion rows with this, though it can take upto 10 days, with less than a minute of downtime.
Percona works in a very similar fashion as above
*
*Create a temp table
*Creates triggers on the first table (for inserts, updates, deletes) so that they are replicated to the temp table
*In small batches, migrate data
*When done, rename table to new table, and drop the other table
A: You can speed up the process by temporarily turning off unique checks and foreign key checks. You can also change the algorithm that gets used.
If you want the new column to be at the end of the table, use algorithm=instant:
SET unique_checks = 0;
SET foreign_key_checks = 0;
ALTER TABLE main_table ADD location varchar(256), algorithm=instant;
SET unique_checks = 1;
SET foreign_key_checks = 1;
Otherwise, if you need the column to be in a specific location, use algorithm=inplace:
SET unique_checks = 0;
SET foreign_key_checks = 0;
ALTER TABLE main_table ADD location varchar(256) AFTER othercolumn, algorithm=inplace;
SET unique_checks = 1;
SET foreign_key_checks = 1;
For reference, it took my PC about 2 minutes to alter a table with 20 million rows using the inplace algorithm. If you're using a program like Workbench, then you may want to increase the default timeout period in your settings before starting the operation.
If you find that the operation is hanging indefinitely, then you may need to look through the list of processes and kill whatever process has a lock on the table. You can do that using these commands:
SHOW FULL PROCESSLIST;
KILL PROCESS_NUMBER_GOES_HERE;
A: Your ALTER TABLE statement implies mysql will have to re-write every single row of the table including the new column. Since you have more than 2 million rows, I would definitely expect it takes a significant amount of time, during which your server will likely be mostly IO-bound. You'd usually find it's more performant to do the following:
CREATE TABLE main_table_new LIKE main_table;
ALTER TABLE main_table_new ADD COLUMN location VARCHAR(256);
INSERT INTO main_table_new SELECT *, NULL FROM main_table;
RENAME TABLE main_table TO main_table_old, main_table_new TO main_table;
DROP TABLE main_table_old;
This way you add the column on the empty table, and basically write the data in that new table that you are sure no-one else will be looking at without locking as much resources.
A: Alter table takes a long time with a big data like in your case, so avoid to use it in such situations, and use some code like this one:
select main_table.*,
cast(null as varchar(256)) as null_location, -- any column you want accepts null
cast('' as varchar(256)) as not_null_location, --any column doesn't accept null
cast(0 as int) as not_null_int, -- int column doesn't accept null
into new_table
from main_table;
drop table main_table;
rename table new_table TO main_table;
A: DB2 z/OS does a virtual add of the column instantly. And puts the table into Advisory-Reorg status. Anything that runs before the reorg gets the default value or null if no default. When updates are done, they expand the rows updated. Inserts are done expanded. The next reorg expands every unexpanded row and assigns the default value to anything it expands.
Only a real database handles this well. DB2 z/OS.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "92"
}
|
Q: How to get the argument's type of a function? I want to guess the type of every argument from an anonymous function, something like mapping a class with reflection but just for a function, something like...
public function guessMyArgumentType(f:Function):void {
for each (argument:* in f.arguments) {
trace(typeof(argument));
}
}
thanks!
UPDATE
Maybe this is insane but what about:
public static function guessMyArgumentType(f:Function):String {
try {
f(2);
return "int";
} catch (error:Error) {
try {
f("a");
return "String";
} catch (error:Error) {
try {
f(["uno", "dos", "tres"]);
return "Array";
} catch (error:Error) {
try {
f(new ArrayCollection(["uno", "dos", "tres"]));
return "ArrayCollection";
} catch (error:Error) {
return "WTF?";
}
}
}
}
}
A: flash.utils.getQualifiedClassName() as referenced here: Get the type in flex
The arguments array is only accessible from inside a given function.
I don't think what you're asking is doable unless you do some crazy try/catch thing but that would always fail if the argument were a custom class so it's not a great solution.
Another option would be adding some custom metadata which describes the function arguments. [YourMeta(arg1="String",arg2="Array")] above each function and then you get use ObjectUtil.getClassInfo(f).metadata to find that info. This requires you add YourMeta to the compiled metatags args.
There might be another way through something not published to ASDocs but I don't know about it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: iOS forces rounded corners and glare on inputs iOS devices add a lot of annoying styles on form inputs, particularly on input[type=submit]. Shown below are the same simple search form on a desktop browser, and on an iPad.
Desktop:
iPad:
The input[type=text] uses a CSS box shadow inset and I even specified -webkit-border-radius:none; which apparently gets overridden. The color and shape of my input[type=submit] button gets completely bastardized on the iPad. Does anyone know what I can do to fix this?
A: For the submit button don't use:
<input type="submit" class="yourstylehere" value="submit" />
Instead use the button tag:
<button type="submit" class="yourstylehere">Submit</button>
This worked for me.
A: The version I had working is:
input {
-webkit-appearance: none;
}
In some webkit browser versions, you may also be faced with the border-radius still being in place. Reset with the following:
input {
-webkit-border-radius:0;
border-radius:0;
}
This can be extended to apply to all webkit styled form components such as input, select, button or textarea.
In reference to the original question, you wouldn't use the value 'none' when clearing any unit based css element.
Also be aware that this hides checkboxes in Chrome, so perhaps use something like input[type=text] or input[type=submit], input[type=text] or instead filter out those that don't use rounded corner settings such as input:not([type=checkbox]), input:not([type=radio]).
A: You can get rid of some more webkits form, input, etc. styling with this:
input, textarea, select {
-webkit-appearance: none;
}
A: have a look to normalize.css
There's a demo where you can test the form elements and see how they look like in ios.
There are multiple webkit oriented properties.
A: This is the what I use in my projects
* {
-webkit-tap-highlight-color: transparent;
}
a, article, div, h1, h2, h3, h4, h5, h6, img, section, span {
-moz-user-select: none;
-webkit-user-select: none;
}
input, select, textarea {
-webkit-appearance: none;
-webkit-border-radius:0;
border-radius: 0;
}
A: You also get this problem in some browsers if you have the following:
<a class="btn btn-primary" href="#" type="button">Link</a>
instead of:
<a class="btn btn-primary" href="#" role="button">Link</a>
This can happen if you change your input element for an anker element and forget to change type to role.
I had this problem on both Chrome and Safari on my IPad.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "96"
}
|
Q: Python: - How to search SQLite3 DB for Blob type? Following on from;
Python - Reading BLOB type from SQLite3 DB
Python - Converting Hex to INT/CHAR
I have a script that now queries a sqlite3 database with a given id. From this id it finds the IP of that device. This is all done within table1. It then takes this found IP and goes to table2.
Within table2 it then tries to do a search for rows which have the field IP that matches the previously discovered IP.
Thanks to help in the previous questions I have managed to convert the original blob type that the IP is stored in the sqlite3 database into a readable format (into hex and then into an actual IP). Now I have found that I can't actually do an sql where command to then search for this.
Perhaps naively I tried to do a search for the original return value from my first search however this returns a buffer
(<read-write buffer ptr 0x7f251c86d778, size 4 at 0x7f251c86d738>,)
This is something I can't obviously use to search for an exact copy of the blob as it contains other information. The only solution I have thought of is to traverse the db and convert each IP from a blob into hex and do a comparison against my previously stored variable where it has been converted into hex from the previous table.
Is this the only way I can perform a search like this? I have enjoyed a lot of help on this today so I am happy for pointers in the right direction
Code Excerpt:
This returns the IP from the first table
rows = c.execute('select ip from table1 where name= ' + "\"" + host + "\"")
for row in rows:
print str(row[0]).encode("hex")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: About Facebook AppID and URL Due to every AppID seems need a correspond URL, that means, every our device needs to apply one AppID with its URL. This is not suitable and not OK for our device goes into mass production due to we don't know the url of the end user. So, does anyone know how to solve this issue?
A: *
Facebook doesn't allow to create appid now, am having below error.
*You can no longer create apps because our systems indicated that your account may not be authentic. Facebook requires users to provide their
real first and last names, and fake accounts are a violation of our
Statement of Rights and Responsibilities (SRR 4.1), even when used to
host or test apps. Also note that maintaining multiple accounts, even
if they are authentic, is also prohibited. If you would like to create
a test user to test app functionality, you can do so here:
http://developers.facebook.com/docs/test_users/.*
*
*
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Should multiple databases share the same DAL? We have applications that must reach into multiple databases. Previously, we had separate DALs that would reach into only a single database. A separate business layer would sit on top would reach only their particular DAL. Applications (different websites) that would sit on top the business layer were free to call any number of business layers if they needed to share the data.
This worked well for a while. However, nowadays, the solutions to build an application have become massive. The application layers all seem to touch every business layer. Reuse is happening, but the builds have slowed to a crawl and the amount of unnecessary code that is brought into a single solution seems unreasonable.
Has anyone else dealt with this situation? Did you bring the data sharing down to the DAL later using an ORM like LLBLGen or NHibernate? Or did you come up with something else entirely?
A: The architecture you describe is a best practice providing re-usability, modularization and scalability. But one can lose the balance achieving these goals. One of the things to look at is the need to have the seperations and the size of the vertical Business Logic - DAL stack. Look at your modules and try to come up with a good reason why particular modules are seperated from each other. Are they to be deployed seperately at the customer for scalability, or to be sold seperately?
If you cannot find a good rationale for a vertical seperation, you might be able to merge some modules and get to a bigger module that can share the BL and DALs. The granularity of the modules increases, reducing the overhead.
Also the horizontal seperation you mention between the BL and DAL can be reviewed, but definately serve the purpose of being able to seperate the Logic from the Data part, which are typically deployed on seperate tiers in a large scale environment. And having a BL module call all needed DAL modules is a possibility, but makes scaling the database more complex if used with Entity DB mappers, because the would have to support multiple connections to databases if tables are divided over multiple servers.
So my personal approach is to start looking at the granularity of your BL - DAL combinations and see if you can combine some of them, reducing your overhead without losing to much of the good stuff. And if you have all these modules, I would guess that you could parallelarize the build per group of modules. That is an asset from your modularized architecture you can benefit from. Why not?
A: Kroonwijk makes a lot of good points.
Just don't forget that a DAL implementation is (usually) tied to the physical data source it's interacting with. This is different from the contracts that define interactions between the BL and DAL.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Flash CS5 won't execute AS3 code I am getting a strange issue in Flash CS5. I have a .fla file that was working fine up until recently. Now, when I Ctrl-Enter to Test Movie...nothing happens.
I have a Document Class set up (and when I click the pencil button, it opens up the right script, so Flash knows where the code is) called Main. In the constructor, there is a trace('Main()') just so I know the constructor got called, but that trace isn't showing up. A few days ago this same code was working fine, so i'm guessing I knocked around a setting or two in the IDE (not sure which, since Flash has the classpath set correctly)
Thanks in Advance,
-Esa
EDIT: Here's a worrying line from the Size report...Why is Actionscript Bytes '0'?
Scene Shape Bytes Text Bytes ActionScript Bytes
------- ----------- ---------- ------------------
Scene 1 0 0 0
EDIT 2: I also added a trace to the timeline, and that still doesn't show up (and ActionScript Bytes is still 0...the swf size hasn't actually changed even though I added the code).
Also I have restarted the program several times, and even restarted my computer (and did the 'Delete ASO' thing that Mattias suggested). No dice.
A: Try copying only the files you need (.as, .fla) into a different folder and recompile. If a big project has too many files within the main directory I think it just gets tired midway while compiling
A: Seems like Flash lost the connection to the document class.
First try to remove the cache:
*
*Control -> Delete ASO
*Hit Ctrl-Enter
If it still does not work:
*
*Remove the document class and hit Ctrl-Enter.
*Add the document class again and give it a new try.
If it still does not work, try changing to an other Document Class to see if that works.
Hope this helps.
A: Are you sure the FLA is set to AS3 (and not AS2) ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: php send 404 header problems A quick question. I know how to send a 404 header in php but when I do the page still continues to load content. In this case must I kill the script also with die(). I have a custom home made cms which is very fast and well suited to my site. But for some reason google has indexed an improper link to the site that was most likely due to some old code that no longer exists. What is happening is that directories such as "/AWebDirectory/AndAnother/function.fopen/" has gotten appended to the url i.e.
www.someurl.com/index.php/AWebDirectory/AndAnother/function.fopen/
This is not throwing a 404 as index.php exists but the css and stuff is not loading due to the directory structure. Any help is appreciated.
A: You need to exit the script or it will just keep going. This is normal. I'm not 100% sure, but I think you might be looking for a redirect:
<?php
/**
* @see http://php.net/manual/en/function.header.php
*/
header("Location: http://www.example.com/"); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
Try using both the 404 header, and redirect to your custom 404 page. That should get you up and running.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599544",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Remove newlines from a JSMin minified file and parsing error on IF condition I'm trying to minify on the fly a javascript file with php and JSMin.
Everything works fine, but when I try to remove newlines
$jsMinifiedClean = str_replace( array("\r","\n"),"",$jsMinified);
I get a javascript parse error.
After a quick search in the code I found the problem:
if( condition ) statement
else statement;
The "if" condition doesn't have the " ; " at the end of the line.
Why with a manual YUI compression of the code I get no error?
Is the semicolon really mandatory at the end of the if to avoid the problem in compressing with JSMin?
A:
Is the semicolon really mandatory at the end of the if to avoid the problem in compressing with JSMin?
It is if you remove the newline. By default, JSMin does not remove the newline for exactly this reason, the horror that is automatic semicolon insertion. From the JSMin page:
It is more conservative in omitting linefeeds, because linefeeds are sometimes treated as semicolons. A linefeed is not omitted if it precedes a non-ASCII character or an ASCII letter or digit or one of these characters:
\ $ _ { [ ( + -
and if it follows a non-ASCII character or an ASCII letter or digit or one of these characters:
\ $ _ } ] ) + - " '
If you then remove the newline, you're taking it upon yourself to be sure that the newline isn't significant because of ASI.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C++/CLI calling Interop wrapper methods with out parameters I've got an Interop wrapper to some unmanaged DLL calls that return details through out paremeters. The functions appear like this:
_myWrapper->My_Method( ... out UInt32 value ... );
So assuming the method is declared like this:
void My_Method(out UInt32 value);
How do I then call this method from within my C++/CLI code? I know how to call reference methods such as this easy enough:
void Another_Method(ref UInt32 value);
UInt32 _value;
_myWrapper->Another_Method(%_value);
I'm doing a little reading and I am reading it can't be done? I don't believe it... Likely this isn't impossible to overcome or workaround, but you've got to be kidding me? Is that really true?
Thank you...
A: In C++, there's no special call syntax for calling a function with a reference parameter, you just write the call like it was pass-by-value. Of course, you need to supply an lvalue to be overwritten, the rvalue (temporary) result of an arithmetic expression can't be used.
BTW, your code for calling a ref function is wrong too, that might be the source of your troubles.
Example:
C# definition:
void MySharpRef(ref int i) { i = 4; }
void MySharpOut(out int i) { i = 5; }
C++/CLI definition:
void MyPlusRef(System::Int32% i) { i = 14; }
void MyPlusOut([System::Runtime::InteropServices::OutAttribute] System::Int32% i) { i = 15; }
C# call:
int j;
o.MyPlusOut(out j);
o.MyPlusRef(ref j);
C++/CLI call:
System::Int32 k;
p->MySharpOut(k);
p->MySharpRef(k);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599552",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Complex Oracle query involving max date I'm having trouble getting the data I want from an Oracle database. Any help would be greatly appreciated. Here's a sample of what my table looks like:
Table: Vaccinations
Patient_ID | Shot_ID | Series | Date_Taken
-------------------------------------------
123 | 5 | B | 8/1/2011
123 | 5 | 3 | 2/1/2011
123 | 5 | 2 | 1/10/2011
123 | 5 | 1 | 1/1/2011
456 | 3 | 2 | 1/10/2011
456 | 3 | 1 | 1/1/2011
123 | 5 | 2 | 10/1/2010
123 | 5 | 1 | 9/1/2010
The series column indicates which shot was administered for a particular Shot_ID. 'B' indicates a booster was given, '2' means second, '1' means first, and so on but '3' is the max and then boosters follow. What I'm trying to do is grab all of the latest series of shots for a patient, for a particular type of shot (Shot_ID). For example, I want to grab patient 123's latest series of shots for Shot_ID = 5, so I would want to return the first four records in this case (all colums should be returned in those rows). The last two should be omitted because a new series of shots was started on 1/1/2011. Anyway, I have an algortihm in mind, but I'm having trouble writing the query for it. It would go something like this:
*
*Get the Max Date for patient 123, shot_id = 5. Return the row and look at its series (in this case, 'B').
*Get the next lowest date from the Max Date and look at its series (in this case, '3'). If the series is between 1 and B, return the row. If no other records exist, then end the query.
*Get the next lowest date from step 2 and look at its series (in this case, '2'). If the series is less than the series from step 2, return the row. Otherwise, end the query.
You keep repeating these steps till you get to series = 1, which is returned or till you reach a series that is greater than or equal to the current series, which is not returned. So , the output should look like this:
123 | 5 | B | 8/1/2011
123 | 5 | 3 | 2/1/2011
123 | 5 | 2 | 1/10/2011
123 | 5 | 1 | 1/1/2011
This query seems to be pretty complex, but maybe I'm just overthinking it. Thank y'all for your time.
A: I would do:
SELECT v1.* FROM vaccinations v1
LEFT JOIN vaccinations v2
ON v2.patient_id = v1.patient_id AND v2.shot_id = v1.shot_id
AND v2.series = '1' AND v2.date_taken > v1.date_taken
WHERE v2.series IS NULL
AND v1.patient_id = '123'
AND v1.shot_id = '5';
The left join looks up for the start of a new shot that is more recent. If it does not return any row (IS NULL) then this is the latest shot. This is equivalent to:
SELECT * FROM vaccinations v1
WHERE patient_id = '123'
AND shot_id = '5'
AND NOT EXISTS (SELECT NULL FROM vaccinations v2
WHERE v2.patient_id = v1.patient_id AND v2.shot_id = v1.shot_id
AND v2.series = '1' AND v2.date_taken > v1.date_taken
);
If the latest series does not necessarily begin with 1, then:
WITH all_series AS
( SELECT rownum rn, series, date_taken
FROM vaccinations
WHERE patient_id = '123' AND shot_id = '5' AND series <> 'B'
ORDER BY date_taken ASC
)
, last_series_beginning AS
( SELECT MAX(as1.date_taken) x
FROM all_series as1
LEFT JOIN all_series as2 -- we need to keep first row in as1
ON as2.rn = as1.rn - 1
WHERE as1.series < as2.series
OR as1.rn = 1
)
SELECT * FROM vaccinations
WHERE patient_id = '123' AND shot_id = '5'
AND date_taken > ( SELECT x FROM last_series_beginning );
A: I'd take a two-pronged approach. Get the most recent "series 1" shot and get all subsequent series after that one.
SELECT Patient_ID, Shot_ID, Series, Date_Taken
FROM Vaccinations v
WHERE Patient_ID = 123
AND Shot_ID = 5
AND Date_Taken >= (SELECT MAX(Date_Taken)
FROM Vaccinations v
WHERE Patine_ID = 123
AND Shot_ID = 5
AND Series = 1)
A: select * from vaccinations as v
inner join (
select a.series , max(a.date_taken) as max_date
from vaccinations as a, vaccinations as b
where a.series = b.series
and not exists (
select * from vaccinations as c where c.series = a.series
and c.date_taken between a.date_taken and b.date_taken)) as m
on v.date_taken >= m.max_date and patient_id = 123 and shot_id = 5
not exists - to keep pairs of repeating series from which to start (or stop)... but if there only 1 series there problem
A: This queries ignores any shots where there are newer ones with the same or lower series (for same Patient_ID and Shot_ID):
select s.*
from Shot s
inner join (
select Patient_ID, Shot_ID, max(Date_Taken) as MaxDate
from Shot
group by Patient_ID, Shot_ID
) sm on s.Patient_ID = sm.Patient_ID and s.Shot_ID = sm.Shot_ID
inner join Shot s2 on sm.Patient_ID = s2.Patient_ID and sm.Shot_ID = s2.Shot_ID and sm.MaxDate = s2.Date_Taken
where (s.Date_Taken = sm.MaxDate
or (
case when s.Series = 'B' then 4 else s.Series end < case when s2.Series = 'B' then 4 else s2.Series end
and not exists (
select 1
from Shot
where Date_Taken > s.Date_Taken
and Shot_id = s.Shot_ID
and case when Series = 'B' then 4 else Series end <= case when s.Series = 'B' then 4 else s.Series end
)
)
)
and s.Patient_ID = 123
A: `select A.patient_id , A.shot_id , A.series , max(date_taken)
From cs_study A
inner join
(
select max(shot_id) max_shotid, patient_id from cs_study
group by patient_id
) b
on A.shot_id =B.max_shotid
and a.patient_id = B.patient_id
group by A.patient_id , A.shot_id , A.series`
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Run a .dmg file through java code How can I mount a .dmg file through java code under OS X?
A: This will work (but only on OS X):
try {
String[] command = {"/usr/bin/hdiutil", "attach", "/Users/path/to/your.dmg"};
String sendback = "";
Process proc = Runtime.getRuntime().exec(command);
InputStream istr = proc.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(istr));
String str;
while ((str = br.readLine()) != null) {
sendback = sendback + str;
}
int resultCode = proc.waitFor();
br.close();
if (resultCode != 0) {
throw new Exception("failed to open system profiler");
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
A: DMGs are not executables, are apple diskimages
reference is here
thus you can't "run" it.
A: You can use a Process, of course. But it won't work anywhere except on a Mac.
A: Saying that is like asking how to run an ISO file through Java. You simply can't; it's a disk image.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599559",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.