text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: How can I make a facebook app work only on my page? I wrote an app that works as a page tab, but I don't want others to use it. Is it possible to make the app work only on my page?
Also, If it is possible to redirect the user to my page if he accessed the app through another page?
A: This is somewhat crude but should work. This will check if the current page ID is your page ID and if not display an error message.
<?php
// Include the Facebook PHP SDK
require('includes/fbSDK/facebook.php');
// Enter your app details
$app_id = "xxxxxxxxxxx";
$app_secret = "xxxxxxxxxxxxx";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
$signed_request = $facebook->getSignedRequest();
// Get the curren page ID
$page_id = $signed_request["page"]["id"];
// Enter your page ID
$mypageID = '123456789';
if ($page_id == $mypageID):
include('/your/app/files.php');
elseif ($page_id != $mypageID):
echo "This app only works on a single page!";
endif;
?>
Here are some examples of what you can check for:
$page_id = $signed_request["page"]["id"];
$page_admin = $signed_request["page"]["admin"];
$like_status = $signed_request["page"]["liked"];
$country = $signed_request["user"]["country"];
$locale = $signed_request["user"]["locale"];
You can for example use this method to require someone to like a page before you show content.
Hope this helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Merge two arrays by key but mantain the key of the first in PHP, array_combine fails I am trying to combine two arrays but mantaining the key of the first.
I've this data:
$days = array(
1 => array("name" => "Monday"),
2 => array("name" => "Tuesday"),
3 => ...
30 => array("name" => "Sunday"),
);
And another one with the clicks:
$clics = array(
2 => array("clicks" => 4),
10 => array("clicks" => 2),
);
My desired array is:
$final = array(
1 => array("name" => "Monday"),
2 => array("name" => "Tuesday", "clicks" => 4),
3 => ...
4 =>
5 =>
...
10 => array("name" => "Tuesday", "clicks" => 2),
..
30 => array("name" => "Sunday"),
);
In the second array if there is no click the index doesn't exists. I have tried array_combine but needs to have the same key and array_merge fails to.
What option I have?
Thank you in advance
A: Take a look at the array_merge_recursive function on PHP.net. Also, check out the comments there to seek if one of those functions are providing the desired array (I.E. comment #104145 and comment #102379
Also, please note that with the use of a foreach, you are sure to have the desired array eventually. Are there any specific reasons why you don't want, or cannot use foreach?
A: I can't see any way to do this with out a loop, but with a loop it's easy:
function merge_your_arrays ($days, $clicks) {
foreach ($days as $k => $v) {
if (isset($clicks[$k])) {
$days[$k] = array_merge($days[$k],$clicks[$k]);
}
}
return $days;
}
$final = merge_your_arrays($days, $clicks);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: playing audio from Application in blackberry? I want to play audio from my application. the following code is used
try{
Player p = javax.microedition.media.Manager.createPlayer("file:///store/home/user/recording.amr");
p.realize();
VolumeControl volume = (VolumeControl) p.getControl("VolumeControl");
volume.setLevel(30);
p.prefetch();
p.start();
}catch(MediaException me)
{
Dialog.alert(me.toString());
}
catch(IOException ioe)
{
Dialog.alert(ioe.toString());
}
then i get an exception net.rim.device.internal.media.rimmediaexception : Media unloded while initializing
Any idea about this exception?
A: Read the rim article: http://docs.blackberry.com/en/developers/deliverables/11941/BlackBerry_Java_Application-Development_Guide--741609-1109114520-001-5.0_Beta-US.pdf
Refer thw stack ovewr flow link Radio Streaming in Blackberry
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Jpa - Hibernate @Version incorrectly incremented I'm using jpa with hibernate (3.2.7) as orm implementation.
I have an entity being modified and then merged.
I also have an @EntityListeners on this entity to ensure some attribute being valued.
If I change a value before merge, and then change back that value in @PreUpdate method inside Listener, setting the original value, my version on entity results incremented, but on database version has previous value.
I think this is due to object didn't change, so on db it's not updated, but version on entity was alredy incremented without being restored after flush.
To explain better, i have this object:
@Entity
@EntityListeners({MyListener.class})
public class MyEntity {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String myValue;
@Version
private Long version ;
}
and this Listener:
public class MyListener {
@PreUpdate
public void preUpdate(MyEntity ua) {
ua.setMyValue("default");
}
}
Now suppose i have on db an object with these values: (id=1, myValue='defalut', version=1). I read this object, detach, pass it to client and get it back with myValue='new' and perform a merge operation (listener change myValue to 'default' and so object result unmodified to db), flush and exit from transaction (so is committed).
After that i find version=2 on my object, but version=1 on db.
Is that an hibernate bug? Or a Jpa bug?
A: I would say this is an expected behavior. According to the Hibernate manual, @PreUpdate is "Executed before the database UPDATE operation.". So, Hibernate has already figured out it has to do UPDATE by running the dirty check, and having it return true.
The dirty check can't happen AFTER @PreUpdate, because Hibernate shouldn't call @PreUpdate unless the dirty check is true. And if an update is going to be run, version should be incremented.
Have you thought about using a listener for @PrePersist, instead of @PreUpdate? I believe that's early enough in the process that it would be pre-dirty check, and thus have the behavior that you want.
A: For me it looks like specification violation. Or maybe that is too strong wording, better probably to say that such a corner case is not clearly enough specified. JPA 1.0 (Hibernate 3.2.7 being one of the implementations) specification spells quite clearly when version should be updated:
The version attribute is updated by the persistence provider runtime
when the object is written to the database.
Also setting basic attribute in invoked entity is aloud (JPA 2.0):
A lifecycle callback method may modify the non-relationship state of
the entity on which it is invoked.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: How can I get the property of ControlTemplate element? My XAML looks like this:
<charting:Chart
Name="pieSeries1">
<charting:PieSeries
IndependentValuePath="Category" DependentValuePath="Amount"
Palette="{StaticResource MyPalette}">
</charting:PieSeries>
<charting:Chart.Template>
<ControlTemplate TargetType="charting:Chart">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<datavis:Title Content="{TemplateBinding Title}" Style="{TemplateBinding TitleStyle}" Margin="1"/>
<Grid Grid.Row="1" Margin="5,0,5,0">
<chartingPrmtvs:EdgePanel x:Name="ChartArea" MinHeight="200" Style="{TemplateBinding ChartAreaStyle}">
<Grid Canvas.ZIndex="-1" Style="{TemplateBinding PlotAreaStyle}" />
<Border Canvas.ZIndex="10" BorderBrush="#FF919191" BorderThickness="1" />
</chartingPrmtvs:EdgePanel>
</Grid>
<datavis:Legend VerticalAlignment="Top" Grid.Row="2" Header="{TemplateBinding LegendTitle}" Style="{TemplateBinding LegendStyle}" x:Name="Legend"/>
</Grid>
</ControlTemplate>
</charting:Chart.Template>
</charting:Chart>
How can I get the height of ChartArea? Quick Watch shows the value of pieSeries1.ChartArea but this one is not available on Runtime. I also tried FindName but no result.
Should be fairly easy right?
A: You can add the following in your Chart class:
private EdgePanel panel;
public override void OnApplyTemplate()
{
panel = (EdgePanel)Template.FindName("ChartArea", this);
}
When and how to get the height depends on your own logic needs it.
A: Create an attached property (say ChartHeight) and bind the value of ActualHeight of ChartArea to it.
After that just check the value in your code.
A: Eventually I found the solution. The OnApplyTemplate solution from @Bubblewrap did not work, unfortunately.
*
*I gave my charting:PieSeries a name, e.g. pie.
*In the code behind I was able to access the ChartArea via pie.Parent as EdgePanel.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ivar check if it has been initialized and used let's say I have an instance variable
MyObject* test;
@property(nonatomic, retain) MyObject* test;
.m
@synthesize test;
I might initialize it or might now depending if I need to. If I don't need it, no point wasting on initialization.
The question is in the dealloc, is it safe to do the following check and release?
-(void) dealloc
{
if ( test != nil )
{
[test release];
}
{
Thanks!
A: Yes, it is safe. However, sending release to a nil won't cause any trouble, so you don't need to check for that.
A: You don't need to do that. You can simply do this if you assign an autoreleased object to the ivar:
self.test = nil;
Edit:
Don't forget to call [super dealloc] at the end of the dealloc function
A: It's safe but not standard practice. You can safely send messages to nil references, and this is a big part of how idiomatic Objective-C is written. Simply release the ivar:
- (void)dealloc
{
[test release];
// ...
A: that's perfectly fine. it is also more idiomatic to simply omit the test for nil.
behind the scenes, the compiler (typically*) generates a call to objc_msgSend or one of its variants. the implementation of objc_msgSend (and variants) allows the object you message to be nil, in the sense that it is well defined and not considered a programmer error to message nil. the return value of objc_msgSend+ variants is zeroed:
example:
NSString * string = nil;
NSString * copy = [string copy]; << copy will be 0/nil
NSUInteger length = [copy length]; << length will be 0
this means you must test for nil if returning a c++ object -- the constructor will not be invoked if the receiver is nil.
*typically, in the sense that there is a handful of c functions the compiler calls to perform messaging as well as some other common routines.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get URL from Eclipse's internal web browser I've been having a hard time figuring this one out.
I'm writing a plugin in eclipse which launches Eclipse's internal web browser. So far I've opened up the internal web browser:
IWebBrowser browser = PlatformUI.getWorkbench().getBrowserSupport().createBrowser(IWorkbenchBrowserSupport.LOCATION_BAR, null,"Expert Viewer", "Validation");
browser.openURL(new URL(some url));
and I want to get the url of the current page that is opened in the browser. How do I accomplish that?
A: The problem with using IWorkbenchBrowserSupport is that you're not guaranteed to get an internal browser back. It may open an external browser if the internal browser is not available, or the workbench is configured to use it, etc.
If you know you always want an internal browser (and that you're only supporting platforms where the internal browser is always available) then you can forego the IWorkbenchBrowserSupport interface and simply use the org.eclipse.swt.browser.Browser widget. Then you can hook up a LocationListener, for example:
Browser browser = new Browser(parent, SWT.NONE);
browser.addLocationListener(new LocationListener() {
public void changing(LocationEvent event)
{
System.out.println("Navigating to: " + event.location);
}
public void changed(LocationEvent event)
{
System.out.println("Location is: " + event.location);
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Are C++ Vectors always contiguous?
Possible Duplicate:
Are std::vector elements guaranteed to be contiguous?
I have come across a technique in which people use a vector in C++ to receive or send data for MPI operations as it is said to store elements contiguously in memory.
However, I remain skeptical of whether this approach would remain robust for a vector of any size, especially when the vector grows to a certain size, where this assumption could break down.
Below is an example of what I am talking about :
MPI_Recv( &partials[0] , partials.size() , mpi_partial , 0,
DALG_ELIMINATE_REQ_MSG ,MPI_COMM_WORLD , &status );
A: Yes, C++ vectors are always contiguous, regardless of size.
But that doesn't mean that they don't move around in memory as you shrink or expand them...
A: The C++ working draft ( www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3126.pdf ) says at 23.4.1:
The elements of a vector are stored contiguously, meaning that if v is
a vector where T is some type other than bool, then it
obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().
A: Basically, yes. All implementations I know of are, and the standard requires vector's to have O[1] lookup which basically requires a contiguous block of memory.
Standard "you shouldn't rely on implementation details" disclaimer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Cant change owner of new file I'm using PHP to retrieve some Base64 data, decode it and write it to a file, my code works fine. However, the owner is apache and the permissions are very low, so even if I FTP into the area where it's uploaded, i cannot download the file. However do i change the permission and owner so i have more control over the file? Here is my code
$path = "uploads/";
$filename = time().".png";
$full_path = $path.$filename;
$image_encoded = $_POST['image'];
$image_decoded = base64_decode($image_encoded);
$handle = fopen($full_path, 'x+');
fwrite($handle, $image_decoded);
fclose($handle);
A: you might want to use chmod to change file permissions.
Perhaps you are not entitled to download it... You may change it's permissions to 755 or something...
chmod($full_path, 0755);
$handle = fopen($full_path, 'x+');
//...
http://www.php.net/manual/en/function.chmod.php
You should be able to change it's permissions because the file was created by php(the owner)...
A: The superuser and the files' owner can change the owner with: chown ( string $filename , mixed $user )
The files' permissions can be changed using: chmod ( string $filename , int $mode )
Plese note you need to use octal notation for the files' permissions, string notation as in Unix won't work! To grant the files' owner every permission, and to allow the other users to be able to read (download) it, the permisison in octal notation is: 0744
See Wikipedia for more information about the octal notation of file permissions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Flex File download I'm currently working on a Flex3/blazeDS/Spring/Oracle project. My requirement is display a list of files from an external FTP server in a grid, user can select single file or multiple files to download, and if user selects multiple files I should tar the files on the FTP server and download the tar file from FTP server to user disk. As per my understanding on the File Download in Flex we have 2 ways to do it. 1) File Reference 2) Using navigateURL and call server side JSP/Servlets to download files.
1) For FileReference we need to download the data first and prompt the user to save the file by clicking on some button. We cannot prompt the 'Save' dialogue without the click event for Security reasons in Flex (Workaround). But my client hates this process because its two steps and he want it in one step like normal file download with only 'Save' dialogue. Then I tried the second option.
2) navigateURL. Open a new windows make a post url request for to JSP/Servlets and prompt the 'Save' dialogue. The problem I am facing here is the pop-up window does not close once the download is complete. navigateURL does not return any reference to the window to close the window. I even tried different content types and headers and java script but none seems to work. The window closes when it is a single file and not for the tar or zip file. I would like to download the popup window for any type of downloads. I am using IE7.
Any help or any other possible solutions are appreciated. Thanks in advance.
A: You could use a hidden iframe. This way there is no popup/new tab involved, just the "save" dialog.
To do this you need to use some JavaScript on the page. Something like this should do it:
<script language="JavaScript" type="text/javascript">
function makeFrame(theUrl) {
ifrm = document.createElement("IFRAME");
ifrm.setAttribute("src", theUrl);
ifrm.style.width = 640+"px";
ifrm.style.height = 480+"px";
document.body.appendChild(ifrm);
}
</script>
To call the function from Flex use the ExternalInterface
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Adding greyscale fx to a class using JavaScript? I'm trying to use jQuery to add a greyscale fx to every image that has a class greyscale, but the below doesn't seem to work. Has anyone got any ideas on why this may not be working?
$(function(){
var imgObj = $('.greyscale');
var canvas = document.createElement('canvas');
var canvasContext = canvas.getContext('2d');
var imgW = imgObj.width;
var imgH = imgObj.height;
canvas.width = imgW;
canvas.height = imgH;
canvasContext.drawImage(imgObj, 0, 0);
var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);
for(var y = 0; y < imgPixels.height; y++){
for(var x = 0; x < imgPixels.width; x++){
var i = (y * 4) * imgPixels.width + x * 4;
var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
imgPixels.data[i] = avg;
imgPixels.data[i + 1] = avg;
imgPixels.data[i + 2] = avg;
}
}
canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
return canvas.toDataURL();
});
A: What you're currently doing wrong is:
*
*Drawing a jQuery object and not a canvas
*Returning a data URL inside a ready handler, which seems to be meaningless
What you should do is:
*
*Iterate over all image elements, doing the following for each canvas:
*
*Make a greyscale version
*Set the image href to the data URL of the greyscale canvas
Like: http://jsfiddle.net/eGjak/140/.
$(window).load(function() { // wait for images to load also
var imgObj = $('.greyscale');
return imgObj.each(function() {
var canvas = document.createElement('canvas');
var canvasContext = canvas.getContext('2d');
var imgW = this.width;
var imgH = this.height;
canvas.width = imgW;
canvas.height = imgH;
canvasContext.drawImage(this, 0, 0);
var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);
for(var y = 0; y < imgPixels.height; y++){
for(var x = 0; x < imgPixels.width; x++){
var i = (y * 4) * imgPixels.width + x * 4;
var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
imgPixels.data[i] = avg;
imgPixels.data[i + 1] = avg;
imgPixels.data[i + 2] = avg;
}
}
canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
console.log(canvas.toDataURL())
this.src = canvas.toDataURL();
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JavaHL Library not found error I installed SVN using the instruction give here: http://alvijee.blogspot.com/2010/08/setting-up-subversion-with-adobe-flash.html
I did select JavaHL Native Library while installation are restarted Flex Builder too.
Now, from Window > Perspective > Other > SVN Repository Exploring, if I try to checkout a repository following error pops up:
Failed to load JavaHL Library.
These are the errors that were encountered:
no libapr-1 in java.library.path
no libapriconv-1 in java.library.path
no libeay32 in java.library.path
no ssleay32 in java.library.path
no libaprutil-1 in java.library.path
C:\Program Files\TortoiseSVN\bin\libsasl.dll: Can't load AMD 64-bit .dll on a IA 32-bit platform
no libsvn_subr-1 in java.library.path
no libsvn_delta-1 in java.library.path
no libsvn_diff-1 in java.library.path
no libsvn_wc-1 in java.library.path
no libsvn_fs-1 in java.library.path
no libsvn_repos-1 in java.library.path
no libsvn_ra-1 in java.library.path
no libsvn_client-1 in java.library.path
no libsvnjavahl-1 in java.library.path
no svnjavahl-1 in java.library.path
no svnjavahl in java.library.path
java.library.path = C:\Program Files (x86)\Adobe\Adobe Flash Builder 4;.;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files (x86)/Adobe/Adobe Flash Builder 4/jre/bin/client;C:/Program Files (x86)/Adobe/Adobe Flash Builder 4/jre/bin;C:\Program Files (x86)\Adobe\Adobe Flash Builder 4\;C:\Program Files (x86)\MiKTeX 2.7\miktex\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;c:\Program Files\WIDCOMM\Bluetooth Software\;c:\Program Files\WIDCOMM\Bluetooth Software\syswow64;C:\Program Files\Dell\Dell Wireless WLAN Card;C:\Program Files (x86)\Common Files\Roxio Shared\DLLShared\;C:\Program Files\MATLAB\R2010a\runtime\win64;C:\Program Files\MATLAB\R2010a\bin;C:\Program Files\TortoiseSVN\bin
Has anybody solved this problem on Windows. I have searched for a solution but people have got such problems on Linux machine. Couldn't find a solution for Flex Builder running in Windows. Has anyone encountered this error?
A: Thanks to mliebelt for directing me in the right direction. I was using 32-bit eclipse but had tortoise 64 bit installed and SVN+SSH environment variable was set to
C:\Program Files (x86)\TortoiseSVN\bin\TortoisePlink.exe. I just uninstalled Tortoise 64bit and installed its 32 bit version. The problem has now went away. :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: 403 Forbidden on when posting HTML chars after server move The site I'm working on was working perfectly on a development server, however the client has his own server so I transferred the files + database, sorted file permissions etc.
Now everything on the site works fine however when I send certain HTML characters via post (from WYSIWYG or regular textfield) e.g. <h1> or <ul> I get a Forbidden 403 Error - You don't have permission to access [THE-REQUESTED-URI] on this server.
It's a LAMP Server, PHP 5.3
By the way Apache mod_security isn't running. What else could be causing the problem??
Also there is nothing in the servers error log about this.
A: Add enctype="text/plain" to your form tag.
It might help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Code does not work in android 2.1 I'm working on an android application thats dealing with contact.
I have used the following code in android 1.6 and it works fine.
public static Uri getProfilepicture(Activity activity, String address)
{
Uri personUri = Uri.withAppendedPath(Phones.CONTENT_FILTER_URL, address);
Cursor phoneCursor = activity.getContentResolver().query(personUri,PHONE_PROJECTION, null, null, null);
if (phoneCursor.moveToFirst())
{
int indexPersonId = phoneCursor.getColumnIndex(Phones.PERSON_ID);
long personId = phoneCursor.getLong(indexPersonId);
phoneCursor.close();
Uri uri = ContentUris.withAppendedId(People.CONTENT_URI, personId);
return uri;
}
return null;
}
and getting photo in bitmap like
Bitmap bm = People.loadContactPhoto(activity,getProfilepicture(activity, ConNum, R.drawable.artist, null);
Can any one suggest code for android 2.1 please?
A: Thanks Friends to trying to help me. i have solve the problem by following code.
public static Bitmap getContactPhoto(Activity activity,int contactId)
{
Bitmap photo = null;
final String[] projection = new String[] {
Contacts.PHOTO_ID // the id of the column in the data table for the image
};
final Cursor contact = activity.managedQuery(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,projection,Contacts._ID + "=?",new String[]{String.valueOf(contactId)},null);
if(contact.moveToFirst())
{
final String photoId = contact.getString(
contact.getColumnIndex(Contacts.PHOTO_ID));
if(photoId != null)
{
photo = queryContactBitmap(activity,photoId);
}
else
{
photo = null;
}
contact.close();
}
contact.close();
return photo;
}
private static Bitmap queryContactBitmap(Activity activity,String photoId)
{
final Cursor photo = activity.managedQuery(Data.CONTENT_URI,new String[] {Photo.PHOTO},Data._ID + "=?",new String[]{photoId},null);
final Bitmap photoBitmap;
if(photo.moveToFirst())
{
byte[] photoBlob = photo.getBlob(
photo.getColumnIndex(Photo.PHOTO));
photoBitmap = BitmapFactory.decodeByteArray(
photoBlob, 0, photoBlob.length);
}
else
{
photoBitmap = null;
}
photo.close();
return photoBitmap;
}
in that just pass the activity object and contactId. and store it into bitmam.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Vb.net System.IO.StreamReader Empty path name is not legal I have a fault with System.IO.StreamReader.
Public Class Project
Dim merah As Integer
Dim File_Directory As OpenFileDialog = New OpenFileDialog()
Dim objReader As New System.IO.StreamReader(File_Directory.FileName)
Dim Text_LineByLine As String
Private Sub BrowseFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BrowseFile.Click
File_Operations()
'Do While objReader.Peek() <> -1
Default_Operations()
MessageBox.Show(Text_LineByLine)
'Loop
End Sub
Sub File_Operations()
File_Directory.InitialDirectory = "C:\"
File_Directory.Filter = "All files (*.txt)|*.txt|All files (*.txt)|*.txt"
If File_Directory.ShowDialog() = DialogResult.OK Then
BrowserPath.Text = File_Directory.FileName
End If
End Sub
When the program starts, The faultis 'Empty path name is not legal.'
How to solve this fault?
Thanks for any helping.
A: You write:
Dim File_Directory As OpenFileDialog = New OpenFileDialog()
Dim objReader As New System.IO.StreamReader(File_Directory.FileName)
but you need to use
Dim File_Directory As OpenFileDialog = New OpenFileDialog()
If File_Directory.ShowDialog() = DialogResult.OK Then
Dim objReader As New System.IO.StreamReader(File_Directory.FileName)
Endif
If you don't execute your open file dialog, dialog itself is not shown and contained filename is empty!!
EDITED:
I edit my post to reflect what you asked in your comment:
Dim File_Directory As OpenFileDialog = New OpenFileDialog()
File_Directory.Filename = initial_file_name
Dim objReader As New System.IO.StreamReader(File_Directory.FileName)
or better
Dim File_Directory As OpenFileDialog = New OpenFileDialog()
Dim objReader As New System.IO.StreamReader(initial_file_name)
A: Hans Passant's comment about As New is correct. You should not create your StreamReader as a global variable. Don't create it until you are ready to use it. And in the case of the StreamReader, you should instantiate it inside a Using block:
Imports System.IO
Sub Main()
Dim filename As String = someMethodThatGetsTheFilename()
Using objReader As New StreamReader(filename)
'Use the StreamReader here
End Using 'This line will automatically close and dispose of the StreamReader
End Sub
In general, you should try to avoid using global variables and declare them close to where you will be using them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Are Commas only used in a picture clause within Cobol I'm working from this parser http://mapage.noos.fr/~bpinon/cobol.jj and trying to get pictures to work with commas. It seems to just support commas out of the picture string as a separator.
Just wondering where else commas are used in Cobol.
Cheers
A: COBOL has several separators. A comma followed by a space is one of them. However,
a comma not followed by a space, as you may find in PICTURE strings, is not a separator but
part of the PICTURE string. The rules for COBOL separators
are not all that complex. Note that periods, commas and semicolons when followed by a space are always separators.
Strictly speaking, the space is necessary but several compilers (IBM Enterprise COBOL for z/OS for example) are
often capable of recognizing commas, periods and semicolons not followed by a space as separators based on the
context that they appear in (a warning may be issued but a valid object module is still generated).
To answer your specific question: A separator comma can appear anywhere a blank space can appear. A comma within the context of a PICTURE string is significant and is not treated as a spearator (ie. it cannot be followed by a blank space).
It may be usefull to note that a COBOL PICTURE strings are delimited only by the separator space, separator comma, separator semicolon, or separator period.
When building a robust COBOL parser you will soon recognize that there are three areas of
a COBOL source text (after the "text manipulation" phase has been completed)
that require special attention.
*
*COMMENT Entries. These are depreciated but still commonly found in many programs
*PICTURE Strings
*Everything else
The "Everything else" chunk constitutes the bulk of a source file, the tendency is to
focus on parsing that while pretty much ignoring the other two items. However, PICTURE strings are actually
fairly complex entities to deal with. COMMENT Entries are just silly and could potentially be removed
during Text Manipulation.
Before you get too deep into this, recognize that the grammar you are working with is only designed to
recognize COBOL source text after what is commonly known as "text manipulation" has been completed.
This is a pre-step where
COPY/REPLACE directives are expanded, continuation lines are dealt with and a number of other
COMPILER directing statements are processed. Do not
underestimate the work needed to perform this step.
Building a robust parser for COBOL is a truly daunting task. It can take years to get right.
Partly because the language was not designed to be parsed using what have since become
"industry" standard parsing techniques and partly because every COBOL compiler vendor has
its own set of idiosyncratic variances to the standard.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Export test lists in Visual Studio I have an application for which I am maintaining multiple versions. So, for that I have multiple versions of solution. I created test lists to group some unit test cases in one solution. Now, I have to do the same in another solution. Is there any way we can export the tests list and include them in another solution.
Both solutions have same unit test cases.
Thanks
Ashwani
A: I would try to copy the VSDMI file (containing the test lists) from the one solution to the other. Since it references the same unittest, I expect it to just work.
Another approach would be to get rid of your test lists and categorize your unittests. The categories are registered as attributes with the tests, so in any solution, you can re-use the test categories to group (much more flexible than test lists) test for execution. See http://msdn.microsoft.com/en-us/library/dd286683.aspx for details on using test categories.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to process WebResponse when .NET throws WebException ((400) Bad Request)? I'm using Facebook Graph Api and trying to get user data. I'm sending user access token and in case this token is expired or invalid Facebook returns status code 400 and this response:
{
"error": {
"message": "Error validating access token: The session is invalid because the user logged out.",
"type": "OAuthException"
}
}
The problem is that when I use this C# code:
try {
webResponse = webRequest.GetResponse(); // in case of status code 400 .NET throws WebException here
} catch (WebException ex) {
}
If status code is 400 .NET throws WebException and my webResponse is null after exception is caught so I have no chance to process it. I want to do it to make sure that the problem is in expired token and not somewhere else.
Is there a way to do it?
Thanks.
A: Using a try/catch block like this and processing the error message appropriately should work fine:
var request = (HttpWebRequest)WebRequest.Create(address);
try {
using (var response = request.GetResponse() as HttpWebResponse) {
if (request.HaveResponse && response != null) {
using (var reader = new StreamReader(response.GetResponseStream())) {
string result = reader.ReadToEnd();
}
}
}
}
catch (WebException wex) {
if (wex.Response != null) {
using (var errorResponse = (HttpWebResponse)wex.Response) {
using (var reader = new StreamReader(errorResponse.GetResponseStream())) {
string error = reader.ReadToEnd();
//TODO: use JSON.net to parse this string and look at the error message
}
}
}
}
}
However, using the Facebook C# SDK makes this all really easy so that you don't have to process this yourself.
A: The WebException still has the "real" response in the Response property (assuming there was a response at all) so you can get the data from that within the catch block.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609194",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "40"
}
|
Q: How can I correct this facebook error? I have a small facebook application where I want to publish a swf file to a user's wall and my wall.I have got this code so far.However, I am getting an error when I click on Click to share..How do I sort this out?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="../JQuery/JQuery.js"></script>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
function publishStream(targetId, name, links, picture, source, userName,message) {
FB.ui(
{
method: 'feed',
to: targetId,
name: name,
link: links,
picture: picture,
source: source, // The URL of a media file (e.g., a SWF or video file) attached to this post
caption: 'Shared by '+userName,
actions: {name: 'Try App', link: links},
message: message
},
function(response){
if (response && response.post_id) {
//alert('Post was published.');
} else {
// alert('Post was not published.');
}
});
}
</script>
</head>
<body>
<p onclick="publishStream('id', 'name', 'http://t2.gstatic.com/images?q=tbn:ANd9GcSclvwUe23dKnjge54JJH6kQM-8iyTRBT_N5-TCWojVmcD0bTi8YQ', 'http://t2.gstatic.com/images?q=tbn:ANd9GcSclvwUe23dKnjge54JJH6kQM-8iyTRBT_N5-TCWojVmcD0bTi8YQ', 'http://t2.gstatic.com/images?q=tbn:ANd9GcSclvwUe23dKnjge54JJH6kQM-8iyTRBT_N5-TCWojVmcD0bTi8YQ','username','Hello') ">Click to share</p>
</body>
</html>
The error is
API Error Code: 191
API Error Description: The specified URL is not owned by the application
Error Message: redirect_uri is not owned by the application.
A: The comment from Igy above is most likely correct. Under your applications advanced settings try disabling the stream post URL security option. This option forces you to essentially keep your links within your application so external references will fail.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609195",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Applying distinct to single column I have a sql query
select distinct
Process.ReportLogProcessID as [Process.ReportLogProcessID],
Process.ProcessTitle as [Process.ProcessTitle],
CAST(User0.PrimaryEmail AS nvarchar(max)) as [Process_Contacts.IsPrimaryContact]
from
ReportProcess as Process inner join
ReportProcessContact as ReportProcessContact0 on
((ReportProcessContact0.SessionID = Process.SessionID)) left outer join
[User] as User0 on
((ReportProcessContact0.ReferenceID = User0.UserID)) left outer join
[Group] as Group0 on
((ReportProcessContact0.ReferenceID = Group0.GroupID and
ReportProcessContact0.ReferenceType = 2))
order by
[Process.ProcessTitle] asc
and it give below result
if you see it returns two rows with the same 'Process Title'-'Testing123' is there any way I can distinct this in spite of whatever be the 'Process Contact'.
Is there any way to distinct the result on the base of particular column?
A: In your query [Process_Contacts.IsPrimaryContact] column have different emails for both records. If you remove that column then only it will distinct records.
UPDATE : You can try like :
select
Process.ReportLogProcessID as [Process.ReportLogProcessID],
Process.ProcessTitle as [Process.ProcessTitle],
MAX(CAST(User0.PrimaryEmail AS nvarchar(max))) as [Process_Contacts.IsPrimaryContact]
from ReportProcess as Process
inner join ReportProcessContact as ReportProcessContact0 on
((ReportProcessContact0.SessionID = Process.SessionID))
left outer join [User] as User0 on
((ReportProcessContact0.ReferenceID = User0.UserID))
left outer join [Group] as Group0 on
((ReportProcessContact0.ReferenceID = Group0.GroupID and
ReportProcessContact0.ReferenceType = 2))
group by Process.ReportLogProcessID, Process.ProcessTitle
order by [Process.ProcessTitle] asc
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Find and set css to html element in variable Suppose i have variable in js and that variable has html as text
like
sHtml = "<div id='dvPrint' ><table>";
sHtml += "<tr><td>" + "<img src='" + ImgPath + "' height='900' width='600' border='0'/>" + "</td></tr>";
sHtml += "<tr><td>" + $('#lblTxt').html() + "</td></tr>";
sHtml += "</table></div>";
So how could I set css to img element by jquery because it is stored in js variable.
can i set css in the below way
sHtml = "<div id='dvPrint'><table>";
sHtml += "<tr><td>" + "<img src='" + ImgPath + "' border='0'/>" + "</td></tr>";
sHtml += "<tr><td>" + $('#lblTxt').html() + "</td></tr>";
sHtml += "</table></div>";
var $dvPrint = $(sHtml);
$dvPrint.addClass('imageCss');
plzz tell me is there anything wrong. thanks
A: $('#dvPrint img').css() - http://api.jquery.com/css/
A: try below with live
$( '#dvPrint > img ').live ('click', function() {
$(this).addClass('imageCss');
});
Note: you must be adding that sHTml on an event, so you can write that event instead of click in above code
A: If the img element has been outputted to the page, then you can select it and assign a class using Javascript:
var elem = document.getElementById("myimg");
elem.className = "my_css_class";
You need to give the image an ID or some other way of being able to locate it though. There's lots of ways of doing that including walking the DOM.
If it hasn't been outputted to the page, and is just sitting in a Javascript variable, then edit the variable.
A: That HTML has to be put into the DOM in order to jQuery can work with it. Or you can use it as XML in jQuery.
A: Why not just use a style attribute when you build up your HTML, eg.
sHtml += "<img style=\""+ ImgCss +"\" src=\"" + ImgPath + "\" />";
A: why don't you use DOM's API ?
var newdiv = document.createElement('div');
$(newDiv).html('your html');
$(newDiv).addClass('whatever');
okay, misread the question, but I think answer may still apply.
Create the img node with create element then insert into div element via DOM.
A: You can't effectively use jQuery nor any other JavaScript solution to apply a css class to the <img> element, as long as it is just inserted into a string and is not actively part of the DOM.
You could eventually obtain the behaviour you're looking for using jQuery's .live() API, but you have to bound it to an event; that way you're guaranteed that even if your <img> element doesn't exist within the DOM initially, whenever it should be added it would automatically be bound to the event declared in .live() invocation, resulting (when the event fires) in the execution of the code which is interesting to you.
If this kind of scenario matches your requirements, then I suggest following the approach indicated by diEcho in this thread.
If, conversely, you only need to apply a css class or attribute to the <img> element in your string, you have 2 options only:
1) When your <img> element still lives only into your sHtml string, you can insert in it the correct css attribute, so whenever you will add sHtml content to the DOM, the image will be there with the correct css styles already;
2) When you already added sHtml content to the DOM, you can use a jQuery selector just like
$("#dvPrint > img").attr("class", "yourCssClass");
and it should do the job.
Hth.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL Query crafting Edited outputs: no file names or trailing slashes are included
I have a database with potentially thousands thousands of records (we're talking a 2MB result string if it was just SELECT * FROM xxx in a standard use case.
Now for reasons of security this result cannot be held anywhere for much more processing.
There is a path field where I want to extract all records with each level of folder structure.
So run the query one way I get every record in the root:
C:\
Query again another way I get every record in the first folder level:
C:\a\
C:\b\
etc
Then of course I will GROUP somehow in order to return
C:\a\
C:\b\
and not
C:\a\
C:\a\
C:\b\
C:\b\
hopefully you get the idea?
Any answers that at least move me in the right direction I will be grateful for. I really am stumped where to start with this as downloading every record and processing is far from the ideal solution in my context. (Which is what we do now).
SAMPLE DATA
C:\a\b\c\d
C:\a\b\c
C:\
C:\a\b
C:\g
D:\x
D:\x\y
Sample output 1
C:\
D:\
Sample output 2
C:\a
C:\g
D:\x
sample output 3
C:\a\b
D:\x\y
sample output 4
C:\a\b\c
sample output 5
C:\a\b\c\d
A: You could do if you have only folders: SELECT DISTINCT path FROM table WHERE LENGTH(path) - LENGTH(replace(path,'\','')) = N
If you have only file names then it depends on whether you have an INSTR function (or some regexp substitution function) provided by the RDBMS. In all cases, depends on the string functions that are available.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Class based GDClient use I study the document about Google API auth. And I little bit confused.
In document written:
import gdata.gauth
import gdata.docs.client
CONSUMER_KEY = 'example.com'
CONSUMER_SECRET = 'abc123doremi'
SCOPES = ['https://docs.google.com/feeds/', 'https://www.google.com/calendar/feeds/'] # example of a multi-scoped token
client = gdata.docs.client.DocsClient(source='yourCompany-YourAppName-v1')
oauth_callback_url = 'http://%s/get_access_token' % self.request.host
request_token = client.GetOAuthToken(
SCOPES, oauth_callback_url, CONSUMER_KEY, consumer_secret=CONSUMER_SECRET)
self.request.host are confused me. Should I inherit a class? What the class shoud be inherited?
A: When your code is called from a web request, self.request is request that came in. self.request.host is the hostname that the user called (i.e. your server).
So this code subsitutes your server name into the oauth_callback_url for sending to Google in the OAuth Request as the call back URL. If you don't want to do that, feel free to hardcode the URL of the callback URL.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: complete list of mime-type <-> file extension mapping I can't find a complete list of mime-type mappings on the internet.
I would like to have a list that refers a file extension to every existing mime type.
The list of all mime-types can be found here:
http://www.iana.org/assignments/media-types
but that resource doesn't include the file extension mapping.
I googled a while and couldn't find a mapping list with all mime-types. Only lists with most common ones. In all lists I found for example this entry is missing:
application/vnd.openxmlformats-officedocument.wordprocessingml.document -> .docx
Does someone know a resource where to find a complete mapping?
A: Using Jürgen's mime.types link and a little command line magic, you can generate the list you want very quickly:
wget -qO- http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types | egrep -v ^# | awk '{ for (i=2; i<=NF; i++) {print $i" "$1}}' | sort
A: I just want to let you know, there is a new class for this in framework 4.5
System.Web.MimeMapping.GetMimeMapping(filename);
source: https://msdn.microsoft.com/en-us/library/system.web.mimemapping(v=vs.110).aspx
A: You have to install apache or nginx or something else and look at the mime.types file.
# MIME type Extensions
# application/3gpp-ims+xml
# application/activemessage
application/andrew-inset ez
# application/applefile
application/applixware aw
application/atom+xml atom
application/atomcat+xml atomcat
# application/atomicmail
application/atomsvc+xml atomsvc
# application/auth-policy+xml
...
more, more, more over 1300 mine-types.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: Convert image to indexed color with custom palette through console I have image.png in truecolor,
palette.png (N colors, where N>256) or text file, where list RGB color palette.
How to get a picture with this palette?
If I use imagemagick:
convert image.png -remap palette.png remap_image.png
It does not work.
convert image.png -map palette.png remap_image.png
Gives a very bad quality. The image is very noisy. File size is bigger than before.
GIMP gives best quality:
Сonvert image to indexed color > use custom palette
But GIMP is GUI. I need to convert a lot images in the console without running the gimp and X.org.
A: Using a shared palette across multiple images requires a carefully crafted palette. If you don't take great care when using the palette of a single image across many images, the result will be poor.
This needn't be complicated though. If you have accesss to the GIMP (or other tool) which supports truecolor graphics, you can create a large image and fit all of the smaller images into it, then quantize the image to N colors, then use that palette as the source.
you should be able to closely mimic GIMP's behavior in the console using ImageMagick
Once you've got a truecolor image with all the colors you want to quantize,
# Create an 8-bit png from our source, with a 235-color palette as an example.
convert truecolor_source.png -colors 235 palette.png
# Create an 8-bit png from an arbitrary image and use the palette in palette.png
convert sample.png -map palette.png output.png
There are a number of options for down-sampling colors, like dithering. See the ImageMagickv6 example page for an excellent overview with example pictures and code.
Although I still don't exactly understand what you want to do, your currently most recent comment ("Yes, from RGB to palette will set independently. Need set correct quantity of colors"), it sounds like all you want to do is set a strict limit on the amount of colors of a bunch of images, but they don't need to use the same palette.
In that case, the solution is very simple:
convert sample.png -colors 135 output.png
Try playing with the quantization options if the result isn't to your satisfaction.
If the output image is too large for your liking, you can experiment with the -quality option.
If this still isn't satisfactory, please try to explain your goal in a more detailed manner.
Good luck!
A: cat photo.png | pngnq -s 1 > photoindexed.png
A: I tend to get good results with the "-remap" (single imge) or "+remap" (multiple images) functions in combination with "-colors". Read up on those functions here. Note that "with "-remap" you provide IM with the final set of colors you want to use for the image, whether you plan to dither those colors, or just replace the ones with their nearest neighbours.", meaning just remapping/replacing might not look good enough, as colors from the input image are simply replaced by those from the palette image. Some form of dithering will be necessary to distribute pixel color conversion errors throughout the output image, because not all colors in the palette match those of the input image.
I'd suggest you use the "-colors N" option for that. This will reduce your output image color count to a maximum of N. By default ImageMagick uses "-dither Riemersma" for this implicitly when you specify "-colors N". The are also other dithering options available.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How can we run JavaScript jasmine tests from Jenkins (Hudson) without loading a JSP? We have a rich web client. Our controllers and service facades are written in coffeescript (JavaScript) and jquery. In the past they would have been java.
To run our JavaScript jasmine tests from Jenkins/Hudson, we use java's junit and htmlunit to load a test oriented jsp page which includes the jasmine specs.
When the Htmlunit tries to run, it blows up trying to getPage() probably because of an XML parser class path which is extremely challenging to track down in our world.
We just want to be able to run our JavaScript tests from Jenkins and have it report failure if a JavaScript test does not pass. We are just using jsp and htmlunit in order to run JavaScript tests. Can we load the JavaScript tests and javascript code into a JavaScript engine with Jenkins as the thing that kicks it off? If so, how?
A: Jasmine Reporters would also be a solution. It has instructions for running headlessly via PhantomJS for example, and it can generate JUnit XML so Jenkins can understand the test results natively, graphing test count, duration, and failure over time.
Also, the "xvfb-run" wrapper often provided with xvfb is a great help here, so you can do "xvfb-run phantomjs.runner.sh ..." in a truly headless environment.
A: I've previously solved this problem by running the tests with a node.js plugin called jasmine-node
This solution of course requires node.js and a few node modules to properly run the jasmine tests. There is no real browser running the tests, but an emulated one using a module called jsdom, which basically creates a headless browser, and more specifically, a DOM, which the tests can interact with.
There's node modules for jQuery, underscore and propably other too, so these can be tested too. You can even skip the whole browser emulation if you'd rather run the tests in a browser, though I find it too cumbersome compared to automated Jenkins testing.
jasmine-node generates jUnit test reports, which Jenkins can interpret just fine.
I just realized there is some jenkins-jasmine-node plugin that might ease this process.
A: Sounds like you're in a Java environment. My jasmine-maven-plugin might be a good fit.
A: Grunt is your friend
*
*use grunt http://gruntjs.com/
*with grunt jasimine https://github.com/gruntjs/grunt-contrib-jasmine
*with nodejs http://nodejs.org/
*on jenkins using https://wiki.jenkins-ci.org/display/JENKINS/NodeJS+Plugin
got this setup and it's really nice, plus this gives you a place to start making your build server do other nice things such as deployment, unit testing, etc you know, other nice things
A: Can you use selenium? That would actually use a real browser then and get as close to the real environment as possible.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: C++ to C# event handling So I've got my C# WinForm Application, from it I call my C++ CLI MFC dll library.
But there are some events on my C++ library, even this events happens in native (non-CLI) part of this library. And I need to call some code from my C# application and get some data maybe right there on this event.
so when this native function is called from client side :
bool __stdcall ClassName::WorkQuery()
{
......
switch(pp->code)
{
case READCOMPLEX:
..........
I need to bring the Data from C# so I need to register this as event somehow.
A: So the problem is you need to run C# code in response to MFC event (or C++ callback), right?
Why can't you just register a native handler to the native event/callback, which then just invokes a .NET event, which can be the consumed from C#.
A: You can create a .NET event from the C++/CLI event handle, and then use it natively. Just use EventWaitHandle or the derived AutoResetEvent and ManualResetEvent.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: bind problems with radio input in jQuery Got a binding issue
Excerpt from html code
<table>
<tr>
<td haschildren="true"><input id="Grubbel_0" type="radio" name="Grubbel_0" value="0"></td>
<td haschildren="true"><input id="Grubbel_1" type="radio" name="Grubbel_1" value="1"></td>
</tr>
</table>
<img src="img.jpg" style="display:none;"/>
Some jQuery
<script language="javascript" type="text/javascript">
$(document).ready(function () {
// Check radiobuttons when clickin on a parent table cell
$("td[haschildren='true']").click(function () {
$(this).find('input:radio').attr('checked', true);
});
// What happens when a radiobutton is changed
$('*[haschildren="true"] input:radio').bind('change', function () {
// This does not work when clicking the td boxes
});
});
</script>
The bind('change'... works when I click directly on the radio box but not when I click on the td although the radiobox gets checked.
Im using jQuery 1.5.2.
Thanks
A: Try -
$(document).ready(function () {
// Check radiobuttons when clickin on a parent table cell
$("td[haschildren='true']").click(function () {
$(this).find('input:radio').attr('checked', true).trigger('change');
});
// What happens when a radiobutton is changed
$('*[haschildren="true"] input:radio').bind('change', function () {
// This does not work when clicking the td boxes
});
});
A: A small syntax error change $("td[haschildren="true"]") to $("td[haschildren='true']")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Howplay mp4 songs using NAudio Can we play mp4 songs using NAudio?
Please provide some code to play mp4 songs
I need a c# code that will help me play mp4 songs
A: Update: NAudio can now play MP4 files using the MediaFoundationReader assuming you have the appropriate codecs installed. This works on Windows Vista and above, and if you are running Windows Server you may need to have the "Desktop Experience" installed.
Alternative approaches would be to see if the WPF Media Element can play it, or using the Windows Media Player ActiveX control (on an OS that can play MP4s).
A: You can play .mp4 files using NAudio, there is a demo in the official page.
Donwload the Demo-Apps and look for the "Media Foundation Demo". The C# code of the demo can be found at the Source Code of NAudio.
*
*Link to Demo-Apps
*Link to Source Code
The implementation is in the WasapiOutGuiThread class:
WasapiOutGuiThread : IWavePlayer
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to access to a json object value when the key like 'foo$bar' I use the Youtube DATA Api and i receive a JSON which some object containing key like 'foo$bar'.
So when i do this
entry.media$group
Javascript says that the value is undefined
A: entry['media$group'] should do it nicely.
A: In js there are many ways to represent arrays and accessing it.
dot notation, entry.media$group is "syntactic sugar" for entry['media$group'] (as Kolink suggested)
Example:
var a = "green";
json_art= {
"colors_translation": {
"green": "verde"
}
}
console.log(json_art.colors_translation.a); //not work
console.log(json_art.colors_translation[a]); //work
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to remove spaces in the bottom of the UITextView? i am using UITextView and i want to remove spaces in the bottom of the UITextview.
A: Something like this?
textView.text = [textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
A: I have updated above code.try with it.i think you got desire result..
// Create a size with large height, but matching width to UITextView.
[myTextView setBackgroundColor:[UIColor greenColor]];
CGSize maxSize = CGSizeMake(myTextView.frame.size.width, 20);
// Determine the size needed to display the text - we just need the new height.
CGSize textSize = [myTextView.text sizeWithFont:myTextView.font constrainedToSize:maxSize lineBreakMode:UILineBreakModeWordWrap];
// Set the UITextView's frame to the new height.
CGRect textViewRect = myTextView.frame;
textViewRect.size.height = textSize.height+13;
myTextView.frame = textViewRect;
A: I'm assuming/guessing you wish to resize a UITextView to accommodate the text nicely. If so, I suggest you investigate:
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode;
For example:
// Create a size with large height, but matching width to UITextView.
CGSize maxSize = CGSizeMake(myTextView.frame.size.width, 9999);
// Determine the size needed to display the text - we just need the new height.
CGSize textSize = [myTextView.text sizeWithFont:myTextView.font constrainedToSize:maxSize lineBreakMode:UILineBreakModeWordWrap];
// Set the UITextView's frame to the new height.
CGRect textViewRect = myTextView.frame;
textViewRect.size.height = textSize.height;
myTextView.frame = textViewRect;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609242",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: A LEFT JOIN B ON @IncludeBJoin = 1 AND B.AID = A.ID WHERE @IncludeBJoin = 0 OR B.ID IS NOT NULL I know that the temptation to use generic stored procedures for code reuse can be a trap, but I don't know if this method of parameterizing a query has anything but a constant performance cost.
SELECT
...
FROM
A
LEFT JOIN
B ON
@IncludeBJoin = 1 AND
B.AID = A.ID
WHERE
@IncludeBJoin = 0
OR B.ID IS NOT NULL -- If included, only include INNER JOIN results
The intent of the above is to short-circuit conditionally unnecessary join to B when only results from A are necessary. This is the simple case, but a practical case would have many such optional joins. I'd like to avoid distinct stored procedures for each combination if it is worth the performance cost.
Then, what about this extension?
SELECT
...
FROM
A
LEFT JOIN
B ON
@IncludeBJoin = 1 AND
B.AID = A.ID
WHERE
@IncludeBJoin = 0
OR B.ID IS NOT NULL
GROUP BY A... WITH ROLLUP -- Extension
HAVING (@AggregatesOnly = 0) OR (GROUPING(A...) = 1) -- Extension
The intent of the above is to always return the rolled-up aggregates and optionally include the component rows. If @AggregatesOnly = 1, such that I only want the groupings, what performance price would I pay?
Execution plans seems somewhat magical to me as their representations can seem conceptually distant from the original statement definition, and the inner-workings of the SQL execution engine are not well documented publically AFAIK. I've read that procedural logic such as the use of IF statements in stored procedures can really kill the benefit of a compiled stored procedure. Does these short-circuiting mechanisms have the same effect, even though they seem more "set-based"?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MyFaces 2.0.2 + TinyMCE I was recently trying to integrate TinyMCE in my Myfaces application. I have downloaded and extracted TynyMCE in my webapp folder. I have written the following code:
<h:outputScript library="tiny_mce" name="tiny_mce.js" target="head" />
<h:outputScript target="head">
tinyMCE.init({
mode : "textareas",
theme : "advanced",
theme_advanced_buttons1 : "fullscreen,undo,redo,cleanup,|,formatselect,bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,outdent,indent,|,link,unlink,|,forecolor",
theme_advanced_buttons2 : "",
theme_advanced_buttons3 : "",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "none",
extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]",
width : "100%",
height : "260"
});
</h:outputScript>
<h:inputTextarea id="myTextArea" value="#{aboutBean.aboutInfo}"
rows="10" cols="50" style="width: 95%" />
As a result I see panel with instruments but there are no icons.
Any ideas how to fix it?
I just want to add that this code is part of ui:composition.
A: You need to add the plugin parameter to your config.
This might look something like (make sure you include all the pluginnames here that you need):
plugins: "preview,save,searchreplace,inlinepopups,paste,wordcount,contextmenu",
A: what happens when you load your tiny_mce.js file with a regular html tag:
<script type="text/javascript" src="#{request.contextPath}/resources/tiny_mce/tiny_mce.js"></script>
I solved my problem with jsf2 and tinymce by replacing the new jsf2 tag
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there a way to produce cumulative pivots in Excel? I have some data:
Week Commencing Channel Count
----------------------------------------
01/05/2011 C1 02
01/05/2011 C3 01
08/05/2011 C2 03
15/05/2011 C1 01
Which produces this pivot:
Week Commencing C1 C2 C3
------------------------------------------
01/05/2011 02 01
08/05/2011 03
15/05/2011 01
However, I would like the values to be cumulative and not to have any of the blanks:
Week Commencing C1 C2 C3
------------------------------------------
01/05/2011 02 00 01
08/05/2011 02 03 01
15/05/2011 03 03 01
This way I can create a stacked area graph over this data and show the cumulative growth of the channels.
I can see a possible solution is to "pad out" the source data so that all Channels have a row for all weeks, and also to have an additional column in the data that is the cumulative of count, per Channel, week-on-week... however, this is a fair bit of extra complexity!
A: I was able to get this working with a couple of CTE's, some cartesian joins and the help of a little table of numbers in master database:
WITH
TestData AS (
SELECT CAST('01 May 2011' AS DATETIME) AS StartDate,'C1' AS Channel, 02 AS COUNT
UNION
SELECT CAST('01 May 2011' AS DATETIME) AS StartDate,'C3' AS Channel, 01 AS COUNT
UNION
SELECT CAST('08 May 2011' AS DATETIME) AS StartDate,'C2' AS Channel, 03 AS COUNT
UNION
SELECT CAST('15 May 2011' AS DATETIME) AS StartDate,'C1' AS Channel, 01 AS COUNT
),
Data_CTE AS (
SELECT Channel, DATEADD(d, -(DATEPART(dw, startdate)+5), CAST(startdate AS DATE)) WeekCommencing, SUM(Count) AS Count
FROM TestData
GROUP BY DATEADD(d, -(DATEPART(dw, startdate)+5), CAST(startdate AS DATE)), Channel),
Sub_CTE AS (
SELECT Dates.RefWeek, Channels.Channel, ISNULL((SELECT Count FROM Data_CTE WHERE Channel = Channels.Channel AND WeekCommencing = Dates.RefWeek) , 0) AS [Count]
FROM
(SELECT DATEADD(day, number * 7, (SELECT MIN(WeekCommencing) FROM Data_CTE)) RefWeek
FROM ( SELECT DISTINCT
number
FROM master.dbo.spt_values
WHERE name IS NULL
) n
WHERE
DATEADD(day, number * 7, (SELECT MIN(WeekCommencing) FROM Data_CTE)) <= (SELECT MAX(WeekCommencing) FROM Data_CTE)) AS Dates,
(SELECT DISTINCT Channel FROM Data_CTE) AS Channels)
SELECT
RefWeek, Channel, ( SELECT SUM(Count) FROM Sub_CTE WHERE Channel = s.Channel AND RefWeek <= s.RefWeek)
FROM Sub_CTE s
ORDER BY s.Channel, s.RefWeek
Problem is that it's not really very understandable and I'm sure to wonder what the blazes I was on when I come back to look at it later :) - Oh well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Graceful degradation with Ajax.ActionLink(), unable to get it working please check my syntax. (MVC3) I have specified the Action method to use for the Async request with Url.Action, but unlike with specifying the ajax options for a form and storing them i.e
AjaxOptions ajaxOpts = new AjaxOptions {
UpdateTargetId = "tabledata",
Url = Url.Action("AppointmentData")
};
And than just passing this "ajaxOpts" into the Ajax.BeginForm() I am unable to store the ajax options in a variable and than pass that into Ajax.ActionLink. Please see the syntax I am attempting below:
@Ajax.ActionLink(cat.CATNAME, ajaxOpts, new { CatID = cat.CATID, count = Model.Count },
AjaxOptions ajaxOpts = new AjaxOptions
{
UpdateTargetId = "catlist-" + Model.Count,
Url = Url.Action("GetCats")
})
Whilst something like the below without trying to use graceful degradation works fine of course, but with jscript turned off it just emits the partialview without the rest of the page:
@Ajax.ActionLink(cat.CATNAME, "GetCats", new { CatID = cat.CATID, count = Model.Count },
new AjaxOptions
{
UpdateTargetId = "catlist-" + Model.Count,
})
It's understandable that when you don't specify the URL for the form and instead just use AjaxOptions as a parameter and jscript is turned off the form will just by default post back to the Action that rendered the page. But is something similar possible for the ActionLink ?
A: This is because you would need a different action and/or check for an AJAX post to your controller action method. When you have javascript turned on, you are requesting a partial view and telling the javascript what target (div or span or whatever) to update with that partial view. When javascript is turned off, it sounds like you are still only returning a partial view, not a complete view. Since the javascript is turned off, you are not updating a div - just rendering the partial by itself.
In short, when it is not an AJAX request (JS turned off) you will need to have your action method return a full view as you cannot update a portion of the page without javascript turned on.
A: You can use this sintax:
@Ajax.ActionLink(cat.CATNAME, "GetCats", new AjaxOptions { UpdateTargetId = "catlist-" + Model.Count })
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609250",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Force accessing of a def Considering
object A {
def m(i: Int) = i
val m = (i: Int) => i * 2
}
one gets
scala> A.m(2)
<console>: error: ambiguous reference to overloaded definition,
both value m in object A of type => (Int) => Int
and method m in object A of type (i: Int)Int
match argument types (Int)
A.m(2)
^
Accessing the val can be done with
scala> val fun = A.m
fun: (Int) => Int = <function1>
scala> fun(2)
res: Int = 4
or
scala> A.m.apply(2)
res: Int = 4
but how would one access the def?
A: It is total rubbish (please, don't do this at home), but you can do it by assigning A to a variable of structural type, that has only the first m.
val x : { def m(i:Int):Int } = A
x.m(10)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: How to get last scroll view position, scrollview I am using TableLayout. which have 100 of items to make it scrollable I am using Tablelayout inside ScrollView. But I have to detect whether the user have scrolled to the last row. If the user have scrolled to the last view then user will be shown a Toast message.
But How to know that the user has scrolled to the last row of the tablelayout. I have referred the code from TableLayout inside ScrollView.
http://huuah.com/using-tablelayout-on-android/
A: If new scrolled y position + scroll view height >= tableview height that means you have reached the end of list.
To achieve this you have to write your custiom scrollview.
Step-1 You have to create custom scroll view extending ScrollView
package com.sunil;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ScrollView;
public class LDObservableScrollView extends ScrollView {
private LDObservableScrollViewListener scrollViewListener = null;
public LDObservableScrollView(Context context) {
super(context);
}
public LDObservableScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public LDObservableScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setScrollViewListener(LDObservableScrollViewListener scrollViewListener) {
this.scrollViewListener = scrollViewListener;
}
@Override
protected void onScrollChanged(int x, int y, int oldx, int oldy) {
super.onScrollChanged(x, y, oldx, oldy);
if(scrollViewListener != null) {
scrollViewListener.onScrollChanged(this, x, y, oldx, oldy);
}
}
}
Step-2 Create a Listener to detect scrollchanged
package com.sunil;
import LDObservableScrollView;
public interface LDObservableScrollViewListener {
void onScrollChanged(LDObservableScrollView scrollView, int x, int y, int oldx, int oldy);
}
Step-3 in layout xml instead of ScrollView use the custom scroll view
<com.abc.LDObservableScrollView android:layout_width="fill_parent" android:layout_marginTop="1dip"
android:id="@+id/OLF_ScrollView" android:layout_height="fill_parent" android:background="@drawable/small_list_back">
<TableLayout android:layout_width="fill_parent" android:id="@+id/OLF_tableLayout_TableLayout" android:layout_height="fill_parent">
</TableLayout>
</com.abc.LDObservableScrollView>
Step-4 In your activity class or where you want to detect the scroll event use the follwoing code
public class DetectHere implements LDObservableScrollViewListener{
...
LDObservableScrollView scrollView = (LDObservableScrollView)view.findViewById(R.id.OLF_ScrollView);
scrollView.setScrollViewListener(this);
.....
@Override
public void onScrollChanged(LDObservableScrollView scrollView, int x,
int y, int oldx, int oldy) {
// TODO Auto-generated method stub
if((scrollView.getHeight()+y) >= tableLayout.getHeight()){
Log.e("Custom Listener ", "END OF LIST OCCURRED ::");
}
}
A: This also worked for me, but my y value on the onScrollChanged never gets higher than the height on my samsung galaxy tab 2 7".
But it works on the galaxy tab 2 10.1"
Any ideas why?
[Edit]
I've seen now that this occurs when the screen is less than a certain height, 1000px for instance. Because when I made the content of my scroll less than 1200 on the 10.1" Galaxy tab 2, it stopped working for the maximum height detection.
[Edit]
I've found the solution, it wasn't detecting the size of the scroll correctly, in order to do that, what I've done was the following:
protected void onScrollChanged(int horizontalScrollPosition, int verticalScrollPosition, int previousHorizontalScrollPosition, int previousVerticalScrollPosition) {
int scrollTotalHeight = this.getChildAt(0).getHeight() - super.getHeight();
if(_previousImage != null)
if(verticalScrollPosition <= 0) _previousImage.setVisibility(View.GONE);
if(_nextImage != null)
if(verticalScrollPosition >= scrollTotalHeight) _nextImage.setVisibility(View.GONE);
super.onScrollChanged(horizontalScrollPosition, verticalScrollPosition, previousHorizontalScrollPosition, previousVerticalScrollPosition);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Store connection string in service configuration for WCF Data Service I've got one class library project that contains an EF model that points to a SQL Azure database. I also have another Azure WCF Web Role project that contains a WCF Data Service exposing the data in my SQL Azure DB as a OData service. Right now I have the connection string stored in the web.config of the WCF Web Role project.
What I'd like to do is make this a configuration, so move it over to the service configuration files so I can change the connection string if necessary (putting it in the web.config seems shortsighted).
The problem I'm having is how to wire the OData service up to not use the web.config connection string but instead use one from the configuration.
A: RoleEnvironment.GetConfigurationSettingValue(NameofSetting);
???
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Edit Control not updating with Spin Control MFC I am trying to use an edit control along with a spin control using MFC visual studio .net 2003. I have carried out the basic settings for the spin control like setting the "AutoBuddy" property and "SetBuddyInteger" property to True so that the Spin control works in coordination with the edit control next to it. In my Spin control's event handler, I am facing a problem when I am trying to call my Invalidate() function. The float value in my edit control does not update and stays zero. If I remove the Invalidate(), then the value increments but my paint function is not updated obviously. A code of the following is given below:
void CMyDlg::OnSpinA(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMUPDOWN pNMUpDown = reinterpret_cast<LPNMUPDOWN>(pNMHDR);
// TODO: Add your control notification handler code here
UpdateData();
m_A = m_ASpinCtrl.GetPos(); // m_A is my edit control float value variable
Invalidate(); // Invalidate is to be called to update my paint function to redraw the drawing
UpdateData(false);
*pResult = 0;
}
I have carried out the tab order correctly as well for the two controls.
Any suggestions on where I am going wrong?
Thanks in advance.
A: If you just want to have a spinning integer, you don't have to override anything.
The spin control has to be right next to the edit control in the tab order. With AutoBuddy that's all you have to do.
A: m_A when getting the position back would do something weird and would not return you the correct value. Try using the pointer to get your position and value and then carry out the invalidate().
{
LPNMUPDOWN pNMUpDown = reinterpret_cast<LPNMUPDOWN>(pNMHDR);
// TODO: Add your control notification handler code here
UpdateData();
CString tempStr;
m_A += pNMUpDown->iDelta;
tempStr.Format("%f",m_A);
m_ACtrl.SetWindowText(tempStr); // Like a CEdit m_ACtrl to display your string
Invalidate();
UpdateData(false);
*pResult = 0;
}
This should work perfectly well. Let me know if you still get any problems.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: cakephp auth component allow redirect issue I am having problem with Auth component when I use $this->Auth->allow('index','view');
I am getting /users/login has resulted in too many redirects when I use $this->Auth->allow('*') it works fine. I am using cakephp 1.3.12 here is app_controller.php
class AppController extends Controller {
var $components = array('Auth','Session');
function beforeFilter(){
$this->Auth->allow('index','view');
}
}
I changed the app_controller.php
class AppController extends Controller {
var $components = array('Auth','Session');
function beforeFilter(){
$this->Auth->allow(array('index','view','display'));
}
}
users_controller.php
class UsersController extends AppController {
var $name = 'Users';
function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow(array('login','logout'));
}
function login() {
if ($this->Session->read('Auth.User')) {
$this->redirect('/', null, false);
}
}
routes.php
Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));
any suggestions?
Thanks
A: Don't know but you might want to check if you have any request actions.
"If you are using requestAction in your layout or elements you should allow those actions in order to be able to open login page properly."
http://book.cakephp.org/1.3/en/view/1257/allow
This had me stumped for the longest time.
Let's say you render an element somewhere in your template:
echo $this->element('comments');
And in views/elements/comments.ctp you have something that requests an action like
$comments = $this->requestAction('comments/index');
foreach($comments as $comment) {
// print stuff
}
In your CommentsController your have to:
function beforeFilter() {
$this->Auth->allow('index');
}
Notice you are requesting an index action from your comments controller in your element. That's why you have to allow 'index' for that specific controller.
I haven't seen this problem properly addressed anywhere. Hope that's what is causing your error.
A: its an array =)
$this->Auth->allow(array('index','view'));
your getting the too many redirects message becasuse the /user/login action is not accessible. So the server tries to display the login page, but it can't, because regular non-connected users dont have acces to /user/login. And when a user doesn't have access to a page, the server will redirect him to the login page... so you see, its an infinite loop.
The /user/login action should be authorized to everyone. Your Users controller should look like this:
class UsersController extends AppController {
var $name = 'Users';
function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow(array('login','logout'));
}
function login(){
if ($this->Session->read('Auth.User')) {
$this->redirect('/', null, false);
}
}
//if you're using prefix routes.
function admin_login(){
$this->redirect('/users/login');
}
if this doesn't the problem, maybe you're redirecting the page in the routes.php
Hope this helps
A: you are doing it wrong.How can app can get to know that which of your controller action you are trying to controller.Do it from your controller.
remove this from app
$this->Auth->allow(array('index','view','display'));
try this in your app controller with needed change
$this->Auth->loginError = "Wrong credentials. Please provide a valid username and password.";
$this->Auth->authError = "You don't have sufficient privilege to access this resource.";
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
$this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login');
$this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'dashboard');
do this from your user controller
$this->Auth->userModel = 'User';
$this->Auth->allow('*');
And in your login dont do anything all of your redirect and all will be doing by app controller.
If you have any doubt regarding this mail me
jafarkv9@gmail.com
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Register/Login from android using oauth2 and google API Working on a native app that requires the user to register to our server.
I would like the user to be able to use oauth2 with google contact api to login.
Not knowing exactly how this would work but idea is:
get default google account and get a token.
send relevant data to our server.(token/userinfo)
verify google account on server and create a one time password
send password to phone
let user register to our service with google account name and one time password
I am not really sure how to do this and what type of token / authorization code I need to do this.
A: Here is a project describing the use of oAuth.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Drupal module settings page construction I am refactoring some code is a Drupal module I wrote sometime age. In order for others to use it, I am adding a configuration page.
I have successfully defined a fieldset but I don't know how to 'insert' content in to it.
The following code sets up radios for each node type defined on my site:
$node_types = node_get_types('names');
$test = array(
'#title' => t('tweeting node'),
'#type' => 'radios',
'#options' => $node_types,
'#default_value' => 'Page',
'#weight' => 0,
);
And the following defines my fieldset into which I want to insert the radio buttons generated above:
$form['twitterhelper_nodecollection'] = array(
'#type' => 'fieldset',
'#title' => t('select a node'),
'#weight' => 0,
'#collapsible' => TRUE,
'#collapsed' => FALSE,
'#parents' => $test,
);
A: to add any form element inside the fieldset you should insert this form element inside the field set array ...
E.g
$form['myfieldset'] = array(
'#type' => 'fieldset' ,
'#collapsible' => TRUE ,
'#title' => t('My FIeldset'),
'#attributes' => array('id' => 'myfieldset-id'),
);
$form['myfieldset']['myradios'] = array(
'#type' => 'radios' ,
'#attributes' => array('id' =>'myradio-attributes') ,
....etc
);
so the fieldset is the parent of the radios not the contrast
hop that help you
UPDATE:
you can append the radios inside the field set by using the jquery as the following
jQuery(document).ready(start) ;
function start(){
jQuery("#myradio-attributes").appendTo("#myfieldset-id");
// i added this id by '#attributes'
}
but its not the drupal way
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Not able to access adb in OS X through Terminal, "command not found" I have installed Android SDK and Eclipse on my Mac system. I am able to program using Eclipse and have created few sample applications. But I am still not able to access adb through the terminal window. I have tried following command in terminal:
$ pwd
/Users/espireinfolabs/Desktop/soft/android-sdk-mac_x86/platform-tools
$ ls
NOTICE.txt dexdump llvm-rs-cc-2
aapt dx llvm-rs-cc.txt
adb lib source.properties
aidl llvm-rs-cc
$ adb --help
-bash: adb: command not found
I have also added the ls output so that you know in which window I am.
A: In addition to slhck, this is what worked for me (mac).
To check where your sdk is located.
*
*Open Android studio and go to:
File -> Project Structure -> Sdk location
*Copy the path.
*Create the hidden .bash_profile in your home.
*(open it with vim, or open -e) with the following:
export PATH=/Users/<Your session name>/Library/Android/sdk/platform-tools:/Users/<Your session name>/Library/Android/sdk/tools:$PATH
*Then simply use this in your terminal: . ~/.bash_profile
SO post on how to find adb devices
A: Quick Answer
Pasting this command in terminal solves the issue in most cases:
** For Current Terminal Session:
*
*(in macOS) export PATH="~/Library/Android/sdk/platform-tools":$PATH
*(in Windows) i will update asap
** Permanently:
*
*(in macOS) edit the ~/.bash_profile using vi ~/.bash_profile and add this line to it: export PATH="~/Library/Android/sdk/platform-tools":$PATH
However, if not, continue reading.
Detailed Answer
Android Debug Bridge, or adb for short, is usually located in Platform Tools and comes with
Android SDK, You simply need to add its location to system path. So system knows about it, and can use it if necessary.
Find ADB's Location
Path to this folder varies by installation scenario, but common ones are:
*
*If you have installed Android Studio, path to ADB would be: (Most Common)
*
*(in macOS) ~/Library/Android/sdk/platform-tools
*(in Windows) i will update asap
*
*If you have installed Android Studio somewhere else, determine its location by going to:
*
*(in macOS) Android Studio > Preferences > Appearance And Behavior > System Settings > Android SDK and pay attention to the box that says: Android SDK Location
*(in Windows) i will update asap
*
*However Android SDK could be Installed without Android studio, in this case your path might be different, and depends on your installation.
Add it to System Path
When you have determined ADB's location, add it to system, follow this syntax and type it in terminal:
*
*(in macOS)
export PATH="your/path/to/adb/here":$PATH
for example: export PATH="~/Library/Android/sdk/platform-tools":$PATH
A: The problem is: adb is not in your PATH. This is where the shell looks for executables. You can check your current PATH with echo $PATH.
Bash will first try to look for a binary called adb in your Path, and not in the current directory. Therefore, if you are currently in the platform-tools directory, just call
./adb --help
The dot is your current directory, and this tells Bash to use adb from there.
But actually, you should add platform-tools to your PATH, as well as some other tools that the Android SDK comes with. This is how you do it:
*
*Find out where you installed the Android SDK. This might be (where $HOME is your user's home directory) one of the following (or verify via Configure > SDK Manager in the Android Studio startup screen):
*
*Linux: $HOME/Android/Sdk
*macOS: $HOME/Library/Android/sdk
*Find out which shell profile to edit, depending on which file is used:
*
*Linux: typically $HOME/.bashrc
*macOS: typically $HOME/.bash_profile
*With Zsh: $HOME/.zshrc
*Open the shell profile from step two, and at the bottom of the file, add the following lines. Make sure to replace the path with the one where you installed platform-tools if it differs:
export ANDROID_HOME="$HOME/Android/Sdk"
export PATH="$ANDROID_HOME/tools:$ANDROID_HOME/tools/bin:$ANDROID_HOME/platform-tools:$PATH"
*Save the profile file, then, re-start the terminal or run source ~/.bashrc (or whatever you just modified).
Note that setting ANDROID_HOME is required for some third party frameworks, so it does not hurt to add it.
A: For Mac OS Catalina or Mojave
Enter command to open nano editor
nano $HOME/.zshrc
Set PATH variable, means append more path as shown here
FLUTTER_HOME="/Users/pankaj/Library/Android/flutter-sdk/flutter/bin"
DART_HOME="/Users/pankaj/Library/Android/flutter-sdk/flutter/bin/cache/dart-sdk/bin"
ANDROID_SDK_HOME="/Users/pankaj/Library/Android/sdk"
ANDROID_ADB_HOME="/Users/pankaj/Library/Android/sdk/platform-tools"
PATH="$PATH:$FLUTTER_HOME"
PATH="$PATH:$DART_HOME"
PATH="$PATH:$ANDROID_SDK_HOME"
PATH="$PATH:$ANDROID_ADB_HOME"
Now press Command + X to save file in editor,Enter Yes or No and hit Enter key.
A: This worked for me on my MAC - 2020
Go to directory containing adb:
cd ~/Library/Android/sdk/platform-tools/
Run adb command to list all services
./adb shell dumpsys activity services
A: I don't know how did you install the android SDK. But in Mac OS, what really worked for me is to reinstall it using brew. All problems solved in a row.
brew install --cask android-sdk
Later on:
android update sdk --no-ui --filter 'platform-tools'
Like a charm
A: This is how it worked for me
first I find my platform-tools than I was using zshrc instead of bash_profile so I run this command first
echo 'export PATH=${PATH}:$HOME/Library/Android/sdk/platform-tools/' >> ~/.zshrc
next refresh terminal
source ~/.zshrc
Check if it worked
adb devices
result of this command must be something similar to this if so then it worked.
List of devices attached
emulator-5554 device
A: For me, I ran into this issue after switching over from bash to zsh so I could get my console to look all awesome fantastic-ish with Hyper and the snazzy theme. I was trying to run my react-native application using react-native run-android and running into the op's issue. Adding the following into my ~.zshrc file solved the issue for me:
export ANDROID_HOME=~/Library/Android/sdk
export PATH=${PATH}:${ANDROID_HOME}/tools:${ANDROID_HOME}/platform-tools
A: If you have installed Android Studio on MAC here is how:
nano ~/.zshrc
or
open ~/.zshrc in VScode
Then edit the file
# Android ADB
export ANDROID_HOME="$HOME/Library/Android/sdk"
export PATH="$ANDROID_HOME/tools:$ANDROID_HOME/tools/bin:$ANDROID_HOME/platform-tools:$PATH"
control + X OR Save file.
Restart Terminal and try
> adb
A: I couldn't get the stupid path working so I created an alias for abd
alias abd ="~/Library/Android/sdk/platform-tools/adb"
works fine.
A: UPDATE
As @Loren.A mentioned in comment latest version of brew does not support cast. So one can simply use:
brew install android-platform-tools
*
*Simply install adb with brew
brew cask install android-platform-tools
*Check if adb is installed
adb devices
A: If you are using the Mac with the M1 chip add the below export command to the zshrc file using the nano command, if that file is not present the nano command will create it for you so run
nano ~/.zshrc
paste this path in that file without any modification
export PATH="/Users/$USER/Library/Android/sdk/platform-tools":$PATH
hit ctrl-x and then Hit y to save the changes and the hit return Key to close it without renaming the file.
then run
source ~/.zshrc
to refresh the .zshrc file
and then try runnning
adb
it should give you the desired output
A: For Mac, Android Studio 3.6.1, I added this to .bash_profile
export PATH="~/Library/Android/sdk/platform-tools/platform-tools":$PATH
A: For zsh users. Add alias adb='/Users/$USER/Library/Android/sdk/platform-tools/adb' to .zshrc file.
Then run source ~/.zshrc command
A: If you are using zsh on an OS X, you have to edit the zshrc file.
Use vim or your favorite text editor to open zshrc file:
vim ~/.zshrc
Paste the path to adb in this file:
export PATH="/Users/{$USER}/Library/Android/sdk/platform-tools":$PATH
A: *
*run command in terminal nano $HOME/.zshrc
*Must include next lines:
export PATH=$PATH:~/Library/Android/sdk/platform-tools
export ANDROID_HOME=~/Library/Android/sdk
export PATH="$HOME/.bin:$PATH"
export PATH="~/Library/Android/sdk/platform-tools":$PATH
*Press Ctrl + X to save file in editor,Enter Yes or No and hit Enter key
*Run source ~/.zshrc
*Check adb in terminal, run adb
A: Or the alternative solution could be
*
*Make sure you already install for android SDK. Usually it is located under
/Users/your-user-name/Library/Android/sdk
*If the SDK is there then run this command. ./platform-tools/adb install your-apk-location
*From there you can generate the APK file That's the only sample to check if adb
command is there
A: For some reason when installed Android Studio 3.6.1 the adb file was actually in $ANDROID_HOME/platform-tools/platform-tools. not sure if this is a bug with my installation or what but this fixed it for me.
A: For Mac Os the default shell has moved on to "zsh" from "bash" as of Mojave and later releases, so for all the Mac users I would suggest go with the creating ".zshrc" file. "adb" runs as it is intended to be. Thanks @slhck for your info.!
A: Follow steps below
*
*Open bash_profile using open -e .bash_profile
*write
export PATH="$ANDROID_HOME/tools:$ANDROID_HOME/tools/bin:$ANDROID_HOME/platform-tools:$PATH"
*close bash_profile file
*run source .bash_profile
*Done run your adb command now !!
In some cases, you may need to run source .bash_profile every time you open cmd to run adb commands
A: It's working fine..
brew install android-sdk
Later on:
android update sdk --no-ui --filter 'platform-tools'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "337"
}
|
Q: get all child elements that are not a table I try to get all children, but skip tables:
What I have is:
var allElements = $("body").children();
$.each(allElements, function(i, element)
{
// Do something
}); // each element
Now I look for either a way, that allElements does not include tables or a function, that returns true, if an element is a table:
if(element.is("table"));
I do not find anything. Does anyone know a solution for this issue?
A: children() accepts a selector, so use the :not one:
$('body').children(':not(table)').each(function () {
// Whatever
});
For future reference, you were on the right track with is(), but as it returns true if any of the elements in the jQuery object matches the selector, you'd have to use it as follows:
$('body').children().each(function () {
if (!$(this).is('table')) {
// It isn't a table, do whatever
}
});
To keep providing alternatives, you could also use the not() method:
$('body').children().not('table').each(function () {
// Do whatever
});
A: Use the .not() function like this:
$("body").children().not('table');
Or, if you want to check as part of a larger expression within the each loop, you can use is(), eg.
if (! $(this).is('table')) { ... }
A: Can do it in a single selector:
$('body > :not(table)').each...
A: $('body').children().each(function(){
if(!$(this).is('table'))
alert($(this).html())
})
an example here http://jsfiddle.net/S2tUS/
or maybe this
$('body').children(':not(table)').each(function(){
alert($(this).html())
})
http://jsfiddle.net/S2tUS/2/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C pthread segmentation fault when running many threads The following code is running without any problems if I keep nThreads under 300, but if I enter 400 for example, then I get a segmentation fault. I think this has to do with maximum number of threads, but I am not sure how to allow more threads, or at least how to determine the maximum number of threads I can run. any idea? thanks in advance
#include <stdlib.h>
#include <pthread.h>
#include <malloc.h>
#include <unistd.h>
void* thread(void* arg);
int counter=0;
pthread_mutex_t counterMutex = PTHREAD_MUTEX_INITIALIZER;
int main(){
int nThreads = 0;
printf("How many threads? ");
scanf("%d", &nThreads);
pthread_t* threads = (pthread_t*)malloc(nThreads*sizeof(pthread_t));
for(int i=0; i < nThreads; i++){
pthread_create(&threads[i], NULL, thread, (void*)&i);
}
for(int i=0; i < nThreads; i++){
pthread_join(threads[i], NULL);
}
printf("counter is %d\n\n", counter);
exit(0);
}
void* thread(void* arg){
pthread_mutex_lock(&counterMutex);
counter++;
printf("thread %d, counter is %d\n\n", *(int*)arg, counter);
pthread_mutex_unlock(&counterMutex);
pthread_exit(NULL);
}
A: You don't check if pthread_create succeeded or failed. If it fails, you wind up calling pthread_join with an invalid pthread_t.
A: You're doing something wrong if you're creating that many threads unless you're on a supercomputer. The 1990s method was to create a thread for each "state" (connection, task, etc.) but the current (and correct) approach is to create only as many threads as CPUs/Cores (give or take), and then use asynchronous events to pull off the rest.
A: Why do you even need 400 threads? Do you realise that having that huge number of threads which are additionally synchronised will slow down your program incredibly?
A: pthread_mutex_init would not go amiss! And try for the error conditions
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609272",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: JavaScript function order: why does it matter? Original Question:
JSHint complains when my JavaScript calls a function that is defined further down the page than the call to it. However, my page is for a game, and no functions are called until the whole thing has downloaded. So why does the order functions appear in my code matter?
EDIT: I think I may have found the answer.
http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
I am groaning inside. Looks like I need to spend ANOTHER day re-ordering six thousand lines of code. The learning curve with javascript is not steep at all, but it is very loooooong.
A: The main reason is probably that JSLint does only one pass on the file so it doesn't know you will define such a function.
If you used functions statement syntax
function foo(){ ... }
There is actually no difference at all where you declare the function (it always behaves as if the declaration is on the beginning).
On the other hand, if your function was set like a regular variable
var foo = function() { ... };
You have to guarantee you wont call it before the initialization (this can actually be a source of bugs).
Since reordering tons of code is complicated and can be a source of bugs in itself, I would suggest you search for a workaround. I'm pretty sure you can tell JSLint the name of global variables beforehand so it doesn't complain about undeclared stuff.
Put a comment on the beggining of the file
/*globals foo1 foo2 foo3*/
Or you can use a text box there for that. (I also think you can pass this in the arguments to the inner jslint function if you can meddle with it.)
A: There are way too many people pushing arbitrary rules about how JavaScript should be written. Most rules are utter rubbish.
Function hoisting is a feature in JavaScript because it is a good idea.
When you have an internal function which is often the utility of inner functions, adding it to the beginning of the outer function is an acceptable style of writing code, but it does have the drawback that you have to read through the details to get to what the outer function does.
You should stick to one principle throughout your codebase either put private functions first or last in your module or function. JSHint is good for enforcing consistency, but you should ABSOLUTELY adjust the .jshintrc to fit your needs, NOT adjust your source code to other peoples wacky coding concepts.
One coding style that you might see in the wild you should avoid because it gives you no advantages and only possible refactoring pain:
function bigProcess() {
var step1,step2;
step1();
step2();
step1 = function() {...};
step2 = function() {...};
}
This is exactly what function hoisting is there to avoid. Just learn the language and exploit its strengths.
A: tl;dr If you're not calling anything until everything loads, you should be fine.
Edit: For an overview which also covers some ES6 declarations (let, const): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Scope_Cheatsheet
This weird behavior depends on
*
*How you define the functions and
*When you call them.
Here's some examples.
bar(); //This won't throw an error
function bar() {}
foo(); //This will throw an error
var foo = function() {}
bar();
function bar() {
foo(); //This will throw an error
}
var foo = function() {}
bar();
function bar() {
foo(); //This _won't_ throw an error
}
function foo() {}
function bar() {
foo(); //no error
}
var foo = function() {}
bar();
This is because of something called hoisting!
There are two ways to define functions: Function declaration and function expression. The difference is annoying and minute, so let's just say this slightly wrong thing: If you're writing it like function name() {}, it's a declaration, and when you write it like var name = function() {} (or an anonymous function assigned to a return, things like that), it's a function expression.
First, let's look at how variables are handled:
var foo = 42;
//the interpreter turns it into this:
var foo;
foo = 42;
Now, how function declarations are handled:
var foo = 42;
function bar() {}
//turns into
var foo; //Insanity! It's now at the top
function bar() {}
foo = 42;
The var statements "throws" the creation of foo to the very top, but doesn't assign the value to it yet. The function declaration comes next in line, and finally a value is assigned to foo.
And what about this?
bar();
var foo = 42;
function bar() {}
//=>
var foo;
function bar() {}
bar();
foo = 42;
Only the declaration of foo is moved to the top. The assignment comes only after the call to bar is made, where it was before all the hoisting occurred.
And finally, for conciseness:
bar();
function bar() {}
//turns to
function bar() {}
bar();
Now, what about function expressions?
var foo = function() {}
foo();
//=>
var foo;
foo = function() {}
foo();
Just like regular variables, first foo is declared at the highest point of the scope, then it is assigned a value.
Let's see why the second example throws an error.
bar();
function bar() {
foo();
}
var foo = function() {}
//=>
var foo;
function bar() {
foo();
}
bar();
foo = function() {}
As we've seen before, only the creating of foo is hoisted, the assignment comes where it appeared in the "original" (un-hoisted) code. When bar is called, it is before foo is assigned a value, so foo === undefined. Now in the function-body of bar, it's as if you're doing undefined(), which throws an error.
A: Only function declaration are hoisted not function expression (assignment).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "121"
}
|
Q: add function to a string I need to add one of my functions to the following code:
$string = '<div class="row">;
<label class="col1">State or Province</label>
<span class="col2"><select name="billing[state]" class="mid2" onChange="ShopperPress_ChangeState_Value(this.valu e)">';
$string .= '<option value="0">-------- Select ----------</option>';
Where text is being printed, such as "State or Province", I need to add the function that will connect to my language file to display that text in different languages. I would normally replace such text with the following:
<?php echo SPEC($GLOBALS['_LANG']['State or Province']) ?>
But I can't get the syntax right amongst the other PHP.
A: $string = '<div class="row">;
<label class="col1">' . SPEC($GLOBALS['_LANG']['State or Province']). '</label>
<span class="col2"><select name="billing[state]" class="mid2" onChange="ShopperPress_ChangeState_Value(this.valu e)">';
$string .= '<option value="0">-------- Select ----------</option>';
A: Your syntax was a bit confusing, but it looks like you'd just need to do this:
<label class="col1">' . SPEC($GLOBALS['_LANG']['State or Province']) . '</label>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: php update value from an array except one I want update my database from an array except one value from $_POST
$_POST['value'] = 'b';
$array = array('a','ab','b','bb','c','cc');
//insert 'a','ab','bb','c','cc' except $_POST['value'] 'b'
mysql_query("UPDATE core SET list='".$newarray."' WHERE id='".$_POST['id']."' ");
How do I do? use preg_replace remove the $_POST['value'] --> difficulty judge the comma ','
or advanced mysql query skill?
A: If I understood the question correctly...
$newarray = implode( ',', array_diff( $array, array( $_POST[ 'value' ] ) ) );
// $newarray == "a,ab,bb,c,cc"
A: Try this if you need to filter by array value
$filtered = array_filter($array, function($value) {
// you need to return a boolean value which tells
// whether to include this element or not
return $value != 'b';
});
$fields = implode(', ', $filtered);
mysql_query("UPDATE core SET list='".$fields."' WHERE id='".$_POST['id']."' ");
Or if you need to filter by array keys
$keys = array('...'); // list here allowed keys
$filtered = array_merge(array_combine($keys, $keys), $_POST);
$fields = implode(', ', $filtered);
mysql_query("UPDATE core SET list='".$fields."' WHERE id='".$_POST['id']."' ");
A: $newarray = $array;
$key = array_search($_POST['value'], $newarray);
if ($key !== false)
{
unset($newarray[$key]);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL Server 2008 R2 connection on a VmWare Instance Here is the scenario I am facing.
*
*I have installed Windows 7 Professional on a VMWare.
*Installed SQL Server 2008 R2.
When I launch the Server Management Studio and try to connect to the instance I get the following error
"A network-related or instance-specific error occurred while
establishing a connection to SQL Server. The server was not found or
was not accessible. Verify that the instance name is correct and that
SQL Server is configured to allow remote connections. (provider: Named
Pipes Provider, error: 40 - Could not open a connection to SQL Server)
(Microsoft SQL Server, Error: 53)"
Now, I installed all the packages of SQL server with default settings. The only change that I had done is selected a mix-mode for authentication.
I setup a similar instance on a desktop and it works fine. Before posting it here I have searched on the web and made sure all the services, ports and protocols are enabled/running.
But I still cannot seem to connect, any help?
A: Ok, so finally found the solution the above mentioned problem. Not sure why, but when I give the instance name pre-appended with .\ it works fine.
.\<INSTANCENAME>
A: You may not have a default instance installed?
http://msdn.microsoft.com/en-us/library/ms143531.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: pyqtSignal and QObject.receivers(..) I need to check the signal for the presence of the listener, before it is emitted.
class Test(QObject):
test = pyqtSignal(str,dict)
def run(self):
if self.receivers(SIGNAL("test(str,dict)"):
self.test.emit('blablabla',{})`
The signal is connected to the slot right and successfully emits signals.
When checking the signature signal, the method QObject.receivers() shows that this signal is not connected.
I understood, reason was incorrect signature, I did not find a method, to specify the faithful signature of signal.
A: In pyqt5 SIGNAL is deprecated. It is replaced with signal attribute of each QObject
if QObject.receivers(QObject.signal) > 0:
print('signal connected')
To Check QPushButton signal clicked() is connected to any slot
button = QPushButton()
.
.
if button.receivers(button.clicked) > 0:
.....
A: The signature for your signal is "test(QString, PyQt_PyObject)".
So obviously, str is mapped to QString and other native python object types, dict, list... are mapped to the C++ type PyQt_PyObject.
The list of signal signatures can be obtained through the QMetaObject associated with your object:
test = Test()
metaobject = test.metaObject()
for i in range(metaobject.methodCount()):
print(metaobject.method(i).signature())
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: NoMethodError: undefined method `mock' with Mocha and Rails 3 I'm trying to use mocha in my Rails 3 project but keep getting the following exception:
NoMethodError: undefined method `mock' for #<MochaTest:0x00000101f434e8>
/Users/John/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.0.10/lib/action_dispatch/testing/assertions/routing.rb:175:in `method_missing'
test/functional/mocha_test.rb:7:in `block in <class:MochaTest>'
Test
I've written the simplest test possible:
require 'test_helper'
class MochaTest < ActionController::TestCase
test "test mocha" do
order = mock('order')
end
end
I run it using ruby -Itest test/functional/mocha_test.rb
I've tried rake test and it gives exactly the same exception.
test_helper.rb
ENV["RAILS_ENV"] = "test"
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
class ActiveSupport::TestCase
#....
require 'test/unit'
require 'mocha'
end
GemFile
source 'http://rubygems.org'
gem 'rails', '3.0.10'
gem 'sqlite3'
gem 'devise', '1.4.5'
gem 'activemerchant'
gem 'geo_location'
gem 'nokogiri'
gem "nifty-generators", :group => :development
gem 'mocha', '0.10.0'
Things I've Tried
*
*Installing mocha 0.9.5 after reading 0.9.5-7 had issues with this. I get an undefined method name exception instead
*Changing where I require mocha - at the bottom of test_helper.rb, top of test etc.
*Tried calling mock() in rails console test - I get the same exception
I'm tearing my hair out with this. Any ideas would be gratefully received.
A: I found the answer immediately after I'd posted this.
Here's the answer: Mocha Mock Carries To Another Test
In short, I changed
gem 'mocha', '0.10.0'
to
gem 'mocha', '0.10.0', :require => false
and it worked like a charm!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609292",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: C# : Passing Parameters to a function via a 2d object array I'm trying to write a neat little generic Sql method that will accept a SQL Query and a list of parameters, and return a result. I want to keep it neat enough that I can call it using one line from any other code.
Is there any really awesomely neat way of doing this? I don't want to create all the SqlParameters in the calling code, and I don't want to have to pass and split a string. In the past I've used a string[] array and accepted every odd member as a parameter name and every even as a param value but that's too easy to screw up when calling the method.
Ideally I'd love to do just this:
Data.SQL("Select * from Table where my_id = @my_id", { my_id = 1 });
I know that's a little unrealistic, So I tried this:
Data.SQL("Select * from Table where my_id = @my_id", new Object[,]{ { "my_id", 1 } });
However when I try and handle that on the other end, I get nothing but trouble:
public static Object SQL(String command, Object[,] parameters = null){
[ ... reusable SQL code here... ]
foreach(Object[] p in parameters){
cmd.Parameters.Add(new SqlParameter(p[0].ToString(), p[1].ToString());
}
}
Looks fine, but throws an error on the foreach statement
foreach (Object[] p in parameters)
Unable to cast object of type 'System.String' to type 'System.Object[]'
But I didn't pass it an array of System.String. What I passed was a 2D System.Object[]! Wasn't it?
Maybe this is just some small code problem, something stupid I'm doing wrong. It usually is. But I'm figuring you guys know some even neater way to do the above.
A:
Ideally I'd love to do just this:
Data.SQL("Select * from Table where my_id = @my_id", { my_id = 1 });
I know that's a little unrealistic,
Well, in exactly that form, yes... but try this instead:
Data.SQL("Select * from Table where my_id = @my_id", new { my_id = 1 });
That will use an anonymous type for the argument, which you can examine by reflection. You probably only need a single parameter (i.e. it would be SQL(string sql, object parameters)) because you would pass multiple parameters in a single object:
Data.SQL("Select * from Table where my_id = @my_id and name = @name",
new { my_id = 1, name = "Jon" });
More alternatives:
*
*If you're using C# 4, you might find dynamic typing useful; look at what Massive does for example.
*As mentioned by Ray, you could pass in a Dictionary<string, object>; again, C# 3 makes this easier than otherwise:
Data.SQL("...", new Dictionary<string, object> {
{ "my_id", 1 },
{ "name", "Jon" }});
EDIT: As for the exact problem you're running into: you need to understand the difference between a rectangular array (e.g. Object[,]) and a jagged array (e.g. Object[][]). The latter is an array of arrays, which is how you're trying to use the parameter, but it's really only a rectangular array. Changing your parameter type to Object[][] may well fix that immediate problem - but personally I'd move to one of the approaches above. I'd also try to avoid making everything into a string, by the way.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609293",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Loop through two querysets while highlighting differences in django I have a model class defined as below:
class Vehicle(models.Model):
stock_number = models.CharField(max_length=6)
vin = models.CharField(max_length=17)
year = models.PositiveSmallIntegerField()
manufacturer = models.CharField(max_length=15)
manufacturer_popularity = models.CharField(max_length=1, blank=True, null=True)
model = models.CharField(max_length=20)
series = models.CharField(max_length=35, blank=True, null=True)
exterior_colour = models.CharField(max_length=25)
interior_colour = models.CharField(max_length=25)
interior_type = models.CharField(max_length=25)
doors = models.PositiveSmallIntegerField()
passengers = models.PositiveSmallIntegerField()
body_style = models.CharField(max_length=30)
transmission = models.CharField(max_length=50)
fuel_type = models.CharField(max_length=50)
engine_capacity = models.DecimalField(max_digits=2, decimal_places=1)
cylinders = models.PositiveSmallIntegerField()
drive_train = models.CharField(max_length=50)
What I want to do is to query two databases based on the above class then display the data in a template while showing the differences between each paired Vehicle entry in red. The querying bit isn't the main issue I guess since I'll need something like:
set1 = Vehicle.objects.all()
set2 = Vehicle.objects.using('other_db').all()
But how can I have the pairing and display being handled? I hope someone can show me the light here.
UPDATE 1
vehicles = []
for v1 in set1:
for v2 in set2:
if v1['stock_number'] == v2['stock_number']:
vehicle1 = vehicle2 = {}
vehicle1['vehicle_1'] = v1
vehicle2['vehicle_2'] = v2
vehicles.append(vehicle1)
vehicles.append(vehicle2)
else:
vehicle1 = vehicle2 = {}
vehicle1['vehicle_1'] = v1
vehicle2['vehicle_2'] = {}
vehicles.append(vehicle1)
vehicles.append(vehicle2)
A: The idea
from itertools import izip
for obj1, obj2 in izip(set1, set2):
for field in obj1._meta.fields:
if field.value_from_object(obj1) == field.value_from_object(obj2):
print 'Same value', field.value_from_object(obj1)
else:
print 'Obj1 has', field.value_from_object(obj1)
print 'Obj2 has', field.value_from_object(obj2)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to find the interface where the method is declared I'm using Unity for interception. Because I have many interfaces I'm forced to using VirtualMethodInterceptor. In my behavior I would like to react only when the method called was declared in the particular type of interfaces (with special attribute). I thought that MethodBase.DeclaringType will solve my problem but it behaves different than I was hoping to. It returns implementing type.
I can agree that it makes sense as the method can be declared in multiple interfaces but there should be a way to easily get the list of them. Unfortunately I haven’t found it yet.
Small sample showing my problem
public interface ISample
{
void Do();
}
public class Sample : ISample
{
public void Do()
{
}
}
class Program
{
static void Main(string[] args)
{
var m = typeof(Sample).GetMethod("Do") as MethodBase;
Console.WriteLine(m.DeclaringType.Name); // Prints "Sample"
}
}
one awkward solution:
var interfaces = from i in input.MethodBase.DeclaringType.GetInterfaces()
where i.GetCustomAttributes(typeof(CustomAttribute), true).Length > 0
where i.GetMethod(input.MethodBase.Name, input.MethodBase.GetParameters().Select(p=>p.ParameterType).ToArray()) != null
select i;
A: The only solution I could come up with (similar to you not-so-awkward solution though).
public static bool IsMethodDeclaredInInterface(MethodBase method, Type myInterface)
{
var methodType = method.DeclaringType;
var typeFilter = new TypeFilter((t, crit) =>
{
var critTypes = crit as Type[];
return critTypes != null && critTypes.Any(ty => ty.FullName == t.FullName);
});
var res = methodType.FindInterfaces(typeFilter, new[] {myInterface});
return res.Length > 0;
}
A: Eventually I used this code:
var interfaces = from i in input.MethodBase.DeclaringType.GetInterfaces()
let parameters = input.MethodBase.GetParameters().Select(p=>p.ParameterType).ToArray()
where i.GetCustomAttributes(typeof(CustomAttribute), true).Length > 0
where i.GetMethod(input.MethodBase.Name, parameters) != null
select i;
A: I think you are stuck with enumerating the interfaces; I haven't seen a way to access a specific interface.
Also, there is a small edge case that could happen if the interface is implemented explicitly. In that case (void ISample.Do()) the MethodBase.Name will be the fully qualified method name (e.g. MyApp.ISample.Do) and not Do.
The only solution I found was to strip off the leading information. E.g.
string methodName = input.MethodBase.Name;
int methodIndex = methodName.LastIndexOf('.');
if (methodIndex != -1)
{
methodName = methodName.Substring(methodIndex + 1,
methodName.Length - methodIndex - 1);
}
var interfaces = from i in input.MethodBase.DeclaringType.GetInterfaces()
let parameters = input.MethodBase.GetParameters().
Select(p => p.ParameterType).ToArray()
where i.GetCustomAttributes(typeof(CustomAttribute), true).Length > 0
where i.GetMethod(methodName, parameters) != null
select i;
Also, if there is another method that has the same name and signature then I'm not sure how to determine if the method was called via the interface as opposed to the public method.
public class Sample : ISample
{
public void Do()
{
// this is a public method
}
void ISample.Do()
{
// this is the interface implementation
}
}
I guess it might be possible to look for other methods with the same name and signature and differentiate by looking at the other MethodBase properties.
I.e. public void Do() has IsHideBySig and IsPublic set to true while void ISample.Do() has IsFinal, IsVirtual, IsPrivate, IsHideBySig all set to true. But I'm not sure that is sufficient for all scenarios.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iUI Ajax hyperlinks not working in Chrome I am testing iUI for mobile web apps. Instead of putting all content into a single HTML page, I am using the Ajax hyperlink technique described by Joe Hewitt here. However I cannot get this to work in Chrome, although Joe Hewitt's own Digg demo, which uses the same technique, seems to work correctly.
Here is the simplified source code:
main.html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>
<link rel="stylesheet" href="iui/iui.css" type="text/css" />
<link rel="stylesheet" href="iui/t/default/default-theme.css" type="text/css"/>
<script type="application/x-javascript" src="iui/iui.js"></script>
</head>
<body>
<div class="toolbar">
<h1 id="pageTitle"></h1>
<a id="backButton" class="button" href="#"></a>
</div>
<ul id="main" title="Main" selected="true">
<li><a href="screen1.html">Go to Screen #1</a></li>
<li><a href="screen2.html">Go to Screen #2</a></li>
</ul>
</body>
</html>
screen1.html:
<div class="panel" title="Screen 1">
<ul><li>Hello 1</li></ul>
</div>
screen2.html:
<div title="Screen 2">
Hello 2
</div>
This works fine on Firefox (minus styling issue in screen2.html) but the links do not work on Chrome.
Any pointers?
A: The AJAX-based navigation used may need to be viewed on a web server to work in certain browsers. If you see an error message when you click a link, try a different browser. When I'm using jQuery Mobile, sometimes the Ajax hyperlink technique works, sometimes it doesn't. Although the same code works fine on Opera.
A: Looks like does not have anything to do with iUI, rather it is a Chrome issue that affects loading any local files via Ajax.
Here is another SO question related to this issue, this time showing up with JQuery:
*
*Problems with jQuery getJSON using local files in Chrome
The accepted answer includes a link to the bug in the Chromium bug tracker.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Query Performance: Search by postcode, company name or town See the SQL query below - it allow you to search the Shop by Postcode, Company Name or Town (location)... On the frontend website there will be only one search textbox without dropdown search type.
It will only show the result if shop_options.live is equal to 1 and depending which day shop is open: O_Hour.weekday = '5' (Friday).
If I search by S_D.postcode (for example: S_D.postcode = 'L14') it will then find L14 from shop_delivery_area table and then display list of shops from that postcode.
SELECT distinct S.*, S.company, S.street, S.town FROM shop as S
JOIN shop_delivery_area as S_D on S_D.shopID = S.shopID
JOIN shop_options on shop_options.shopID = S.shopID
JOIN shop_opening_hours as O_Hour on O_Hour.shopID = S.shopID
WHERE (S_D.postcode = 'Liverpool' OR S.company LIKE 'Liverpool' OR S.town LIKE 'Liverpool')
AND shop_options.live = '1' AND O_Hour.weekday = '5'
ORDER BY O_Hour.opentime
The query does work but its very slow. Almost a second to get the result. How to improve the performance faster?
Edit: Fixed SQL query.
A: If you need to keep the predicates i.e.
S_D.postcode = 'Liverpool' OR S.company LIKE 'Liverpool' OR S.town LIKE 'Liverpool'
Then consider adding indexes on the same columns. So:
ALTER TABLE shop_delivery_area ADD KEY `sda_idx1` (`postcode`);
ALTER TABLE shop ADD KEY `shop_idx1` (`company`);
ALTER TABLE shop ADD KEY `shop_idx2` (`town`);
One other point is about fuzzy searching. If you can replace the 'LIKE' with an '=' then you'll see a speed increase. There's not much point using 'LIKE' with no fuzzy searching though i.e. LIKE 'Liverpool'. Use either LIKE '%Liverpool%' or = 'Liverpool'. So either use:
S_D.postcode = 'Liverpool' OR S.company LIKE '%Liverpool%' OR S.town LIKE '%Liverpool%'
or
S_D.postcode = 'Liverpool' OR S.company = 'Liverpool' OR S.town = 'Liverpool'
If you use the latter and create the indexes then your query should run just fine!
A: The use of IFNULL instead of OR may provide substantial performance improvements, depending on your amount of data, indexes, etc.
A: *
*Get rid of conditions for empty strings (S_D.postcode = '' OR S.company LIKE '')
*Generally LIKE will slow down your queries a lot, so I'll avoid it whenever it's possible
*Add indexes on WHERE columns
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it possible to drag and drop GridView rows with jQuery sortable? I have tried to implement this in the following way:
GridView:
<asp:GridView ID="GridViewUnavailableDestination" runat="server" Visible="False"
Width="98%" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333"
GridLines="None" CssClass="sortable">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="idUnavailable" runat="server" Text='<%# bind("idUnavailable") %>' Visible="false"></asp:Label>
<asp:Label Visible="true" runat="server" ID="unavailableLabel" Text='<%# bind("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Type">
<ItemTemplate>
<asp:Label Visible="true" runat="server" ID="unavailableTypeLabel" Text='<%# bind("type") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="RT">
<ItemTemplate>
<asp:Label Visible="true" runat="server" ID="unavailableRTLabel" Text='<%# bind("ringingTime") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And this is my javascript in the MasterPage:
$(document).ready(function () {
$(function () {
$(".sortable tbody").sortable();
$(".sortable tbody").disableSelection();
});
});
However, it does not work.
Any ideas on how to make this work? Or if it is possible at all?
A: you should below links....
http://www.isocra.com/2008/02/table-drag-and-drop-jquery-plugin/
http://www.pedrera.com/blog/asp-net-listview-drag-and-drop-reordering-using-jquery/
http://www.codeproject.com/KB/webforms/DragAndDropGridView.aspx
http://www.foliotek.com/devblog/make-table-rows-sortable-using-jquery-ui-sortable/
A: To solve this issue, it is required to have a look at the following post:
http://www.isocra.com/2008/02/table-drag-and-drop-jquery-plugin/
It is about a recent jQuery plugin that allows to Drag and Drop table elements. This is useful for GridViews since the browser renders it as a table. However, this might not be enough to get the solution to the problem, as it has been clearly described by this post, which works with GridViews specifically:
http://forums.asp.net/t/1684346.aspx/1?tableDnD+onDragClass+not+working+on+asp+net+GRIDVIEW
Hope this helps people with the same issue!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I bind a servlet to everything except /? I have a server which I need to bind two servlets to.
The first is the "home" servlet, which I want to reside at /. This will display what is essentially a welcome page.
The second is a servlet which will serve content based on a url-shortener style link code. This needs to bind to any other request.
My problem is that if I bind the second servlet to /* then this also includes /
A: Exact mapping has a bigger priority that path mapping. So you shouldn't have any problem if you map your home servlet to / and the other one to /*, because / will take the precedence over /*.
A: *
*Map specific servlet to "/index"
*Map generic servlet to "/*"
*Add welcome-file "index" in the welcome-file-list
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Thinking sphinx updates delta index even when no fields are updated Even when no fields specified in update attributes actually changes , thinking sphinx sets delta = 1 which results in large number of unwanted queries being fired . can we do something to let sphinx know that there was no actual update.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Drop down list selection Excel VBA I want to populate a cell depending upon the drop down selection. How can i do it? The drop down list is created manually in the sheet.
EDIT: I have a column where every cell is a drop-drown. Depending upon what i select in the drop-down, the adjacent cell should get populated with a value.
A: Lets say you have a dropdown box in A1 allowing values 1,2, or 3, and you want B1 to show "A", "B", or "C" accordingly. Just type the formula
=IF(A1=1,"A",IF(A1=2,"B",IF(A1=3,"C","-")))
into B1. Of course, this works also when you have no dropdown box in A1.
A: Have a look on Vlookup and Index Match they are usually easier to create and mantain than nested If .
If you need examples let me know
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Redmine: Post attachments using API (or not) Is there any way to post attachments to issues in Redmine from an outside PHP script? If API doesnt support this (i didnt find anything on the wiki) then is there another way?
So far i have tried only this, but it doesnt work:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://192.168.1.115/redmine/login");
$useragent="Mozilla/5.0 (Windows NT 5.1; rv:8.0a2) Gecko/20110927 Firefox/8.0a2";
curl_setopt($ch, CURLOPT_COOKIEJAR, "C:\\xampp\\htdocs\\redmine\\cookie.txt");
curl_close($ch);
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_REFERER, "http://192.168.1.115/redmine/login");
curl_setopt($ch, curlopt_post, true);
curl_setopt($ch, CURLOPT_COOKIEFILE, "C:\\xampp\\htdocs\\redmine\\cookie.txt");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$token = getToken();
$data2 = array(
'password' => '1234',
'back_url' => 'http%3A%2F%2F192.168.1.115%2Fredmine%2F',
'username' => 'admin',
'authenticity_token' => $token,
'login' => 'Login Β»'
);
print_r($data2);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data2);
$out = curl_exec($ch);
echo $out;
curl_exec($ch);
curl_setopt($ch, CURLOPT_COOKIEJAR, "C:\\xampp\\htdocs\\redmine\\cookie2.txt");
$useragent="Mozilla/5.0 (Windows NT 5.1; rv:8.0a2) Gecko/20110927 Firefox/8.0a2";
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-Redmine-API-Key: 104a2e2b72d4f5d184775d8324c2e0cb6386815e'));
curl_setopt($ch, CURLOPT_URL, "http://192.168.1.115/redmine/projects/lvx/issues/new");
curl_setopt($ch, CURLOPT_COOKIEFILE, "C:\\xampp\\htdocs\\redmine\\cookie2.txt");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = array(
'key' => '104a2e2b72d4f5d184775d8324c2e0cb6386815e',
'is_private' => '0',
'tracker_id' => '1',
'subject' => 'This bug was sent from my API',
'description' => 'this is a description',
'status_id' => '0',
'priority_id' => '4',
'assigned_to_id' => '',
'parent_issue_id' => ''
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$out = curl_exec($ch);
echo $out;
curl_close($ch);
function getToken(){
$url = "http://192.168.1.115/redmine/login";
$input = @file_get_contents($url) or die("Could not access file: $url");
$regexp = "<input name=\"authenticity_token\" type=\"hidden\" value=\"(.+?)\" />";
if(preg_match_all("$regexp", $input, $matches))
{
return $matches[1][0];
}
}
A: You can chain method attach_files. There is example from plugin which pastes screenshot to wiki-page/issue.
module RedmineScreenshotPaste
def self.included(base)
base.send(:extend, ClassMethods)
base.class_eval do
class << self
alias_method_chain :attach_files, :screenshot
end
end
end
module ClassMethods
def attach_files_with_screenshot(obj, attachments)
if attachments.is_a?(Hash)
screenshot = attachments['screenshot']
if screenshot.is_a?(Hash)
file = UploadedScreenshot.new(screenshot.delete('content'),
screenshot.delete('name'))
screenshot['file'] = file
end
end
attach_files_without_screenshot(obj, attachments)
end
end
end
A: Following is simple curl call for php with redmine.
**flie class file in redmine/redmine_curl.php**
<?php # Redmine Api
class class_redmine{
function get_upload_token($filecontent){
global $redmine_url , $redmine_key;
$upload_url = $redmine_url.'uploads.json?key='.$redmine_key;
$request['type'] = 'post';
$request['content_type'] = 'application/octet-stream';
//$filecontent = file_get_contents('test.php');
return $token = $this->curl_redmine($upload_url,$request,$filecontent);
//$token->upload->token;
}
#Issue
function create_issue($post_data){
global $redmine_url , $redmine_key;
$issue_url = $redmine_url.'issues.json?key='.$redmine_key;
$request['type'] = 'post';
$request['content_type'] = 'application/json';
return $this->curl_redmine($issue_url,$request,$post_data);
}
function get_issue($issue_id='',$project_id=''){
global $redmine_url , $redmine_key;
if($project_id!=''){
$issue_url = $redmine_url.'issues.json?key='.$redmine_key.'&project_id='.$project_id;
}else{ $issue_url = ($issue_id=='')?$redmine_url.'issues.json?key='.$redmine_key : $redmine_url.'issues/'.$issue_id.'.json?key='.$redmine_key;
}
return $this->curl_redmine($issue_url,'','');
}
#Projects
function get_projects($project_id=''){
global $redmine_url , $redmine_key;
$proj_url = ($project_id=='')?$redmine_url.'projects.json?key='.$redmine_key : $redmine_url.'projects/'.$project_id.'.json?key='.$redmine_key;
return $this->curl_redmine($proj_url,'','');
}
#Curl
function curl_redmine($redmine_url,$request='',$post_data=''){
if(!isset($request['type'])){ $request['type']=null; }
if(!isset($request['content_type'])){ $request['content_type']=null; }
//Create a curl object
$ch = curl_init();
//Set the useragent
$agent = $_SERVER["HTTP_USER_AGENT"];
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
//Set the URL
curl_setopt($ch, CURLOPT_URL, $redmine_url );
if($request['type'] == 'post'){
//This is a POST query
curl_setopt($ch, CURLOPT_POST,1);
// curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
//Set the post data
curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: '.$request['content_type'],
'Content-Length: ' . strlen($post_data))
);
}
//We want the content after the query
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//Follow Location redirects
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
/*
Set the cookie storing files
Cookie files are necessary since we are logging and session data needs to be saved
*/
//curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
//curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
//Execute the action to login
$postResult = curl_exec($ch);
//if($postResult == false){ return $info = curl_getinfo($ch);}
$response = json_decode($postResult);
//echo '<pre>'; print_r($response); echo '</pre>';
return $response;
}
}//class_redmine
?>
**Example file example.php**
<?php
//code for class_settting.php
function get_redmine($methodName='',$data=''){
global $redmine_url , $redmine_key;
//$query='select * from '.VIS_TABLE_PREFIX.'integration where integration_type=37 and is_enabled=1 and domain_id='.VIS_DOMAIN;
//$res = $this->database->query_exec($query);
//$login_integrate=$this->database->fetch_result_array($res);
/*if($login_integrate==-1){ return $login_integrate; }
if(count($login_integrate)>0 && $login_integrate!=-1){
$redmine_url = $login_integrate[0]['billing_url'];
$redmine_username = $login_integrate[0]['admin_user'];
$redmine_password = $login_integrate[0]['admin_password'];
$redmine_key = $login_integrate[0]['api_key'];
}*/
$redmine_url = 'http://localhost/redmine/';
$redmine_key = '41f132773cc29887bc2e4566863aedc01cde6e2b';
include_once('redmine/redmine_curl.php');
$obj_redmine = new class_redmine();
#check Auth
$res = $obj_redmine->get_projects();
if(!isset($res->projects) || (isset($res->total_count) && ($res->total_count)==0)){ return -1; }
switch($methodName){
case 'check_status' : return $login_integrate; ##check redmine integration in vision
break;
##Trackers
//
##Issue statuses
//
##Project
case 'projectAll' : return $obj_redmine->get_projects(); #used
break;
case 'projectById' : return $obj_redmine->get_projects($data['project_id']);
break;
##Users
//
##Issues
case 'showIssue' : return $obj_redmine->get_issue($data['issue_id']);
break;
case 'issueAll' : return $obj_redmine->get_issue();
break;
case 'issueByProjectId' : return $obj_redmine->get_issue('',$data['project_id']);
break;
case 'createIssue' : return $obj_redmine->create_issue($data);
break;
case 'uploadFileToIssue' : return $obj_redmine->get_upload_token($data);
break;
default: return 0;
}
}
$filecontent = file_get_contents('test.php');
$token = get_redmine('uploadFileToIssue',$filecontent);
$filecontent = file_get_contents('Picture.jpg');
$token2 = get_redmine('uploadFileToIssue',$filecontent);
$uploads = array(
array(
'token' => $token->upload->token,
'filename' => 'MyFile.php',
'description' => 'MyFile is better then YourFile...',
'content_type' => 'application/txt',
),
array(
'token' => $token2->upload->token,
'filename' => 'Picture.jpg',
'description' => 'MyFile is better then YourFile...',
'content_type' => 'application/image',
),
);
$custom_fields = array(
array(
'id' => 1,
'name' => 'Phone',
'value' => '1234265689'
),
array(
'id' => 2,
'name' => 'Proj sub name',
'value' => 'Test'
),
);
$post_data = array('issue'=>array(
'project_id' => 4,
'subject' => 'ABCDEFG',
'description' => 'Test',
'uploads' => $uploads,
'custom_fields' => $custom_fields,
),);
$post_data = json_encode($post_data);
#all proj
//$res = get_redmine('projectAll');
#proj by id
//$res = get_redmine('projectById',array('project_id'=>'4'));
#get all issue
//$res = get_redmine('issueAll');
#get issue by id
//$res = get_redmine('showIssue',array('issue_id'=>'85'));
#get issue by project id
//$res = get_redmine('issueByProjectId',array('project_id'=>'5'));
#create issue
$res = get_redmine('createIssue',$post_data);
echo '<pre>';print_r($res);
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Replacing particular elements in a list Code:
>>> mylist = ['abc','def','ghi']
>>> mylist
['abc', 'def', 'ghi']
>>> for i,v in enumerate(mylist):
... if v=='abc':
... mylist[i] = 'XXX'
...
>>> mylist
['XXX', 'def', 'ghi']
>>>
Here, I try to replace all the occurrences of 'abc' with 'XXX'. Is there a shorter way to do this?
A: Instead of using an explicit for loop, you can use a list comprehension. This allows you to iterate over all the elements in the list and filter them or map them to a new value.
In this case you can use a conditional expression. It is similar to (v == 'abc') ? 'XXX' : v in other languages.
Putting it together, you can use this code:
mylist = ['XXX' if v == 'abc' else v for v in mylist]
A: Use a list comprehension with a ternary operation / conditional expression:
['XXX' if item == 'abc' else item for item in mylist]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Awk: Remove duplicate lines with conditions I have a tab-delimited text file with 8 columns:
Erythropoietin Receptor Integrin Beta 4 11.7 9.7 164 195 19 3.2
Erythropoietin Receptor Receptor Tyrosine Phosphatase F 10.8 2.6 97 107 15 3.2
Erythropoietin Receptor Leukemia Inhibitory Factor Receptor 12.0 3.6 171 479 14 3.2
Erythropoietin Receptor Immunoglobulin 9 10.4 3.1 100 108 24 3.3
Erythropoietin Receptor Collagen Alpha 1 Xx 10.7 2.7 93 105 18 3.3
Tumor Necrosis Factor Receptor Tumor Necrosis Factor Receptor 5 11.4 3.2 114 114 25 1.7
Tumor Necrosis Factor Receptor Tumor Necrosis Factor Receptor 14 11.1 2.1 99 100 28 1.8
Tumor Necrosis Factor Receptor Tumor Necrosis Factor Receptor 1B 10.9 4.9 133 162 29 1.9
Tumor Necrosis Factor Receptor Tumor Necrosis Factor Receptor 11A 11.5 5.1 130 166 25 1.9
The first and second column contain protein names and the 8th column contains the "distance" score between each protein pair. I would like to remove the lines containing duplicate protein pairs and keep only the pair with the lowest distance (the lowest value in the 8th column). This means that for the pair Protein A-Protein B I would like to remove all occurrences except the one with the lowest distance score. The pair is considered duplicate even if the protein names are swapped (in different columns). This means that Protein A Protein B is the same as Protein B Protein A.
A: Something like this (untested):
awk -F'\t' 'END {
for (r in rec) print rec[r]
}
{
if (mina[$1, $2] < $NF || minb[$2, $1] < $NF) {
mina[$1, $2] = $NF; minb[$2, $1] = $NF
rec[$1, $2] = $0
}
}' infile
A: I hope this would be the final update ^_^
kent$ awk -F'\t' '{if($1$2 in a){
if($8<a[$1$2]){
a[$1$2]=$8;r[$1$2]=$0;
}
}else if ($2$1 in a){
if($8<a[$2$1]){
a[$2$1] = $8;r[$2$1] = $0;
}
}else{
a[$1$2]=$8; r[$1$2]=$0;
}
} END{for(x in r)print r[x]}' yourFile
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to use jquery selector having element type and ID I'm using this selector
$("textarea #myTextArea").val(text); and it's not working. If I remove the ID and use the class it's working. Why isn't jquery able to find the element here?
A: Just remove the space:
$("textarea#myTextArea").val(text);
At the moment you're trying to select an element with ID myTextArea that is a descendant element of a textarea
As Jared Farrish mentions in the comments removing the element type would be more efficient:
$("#myTextArea").val(text);
If your document is valid then every ID will only used be once so this is still correct.
A: Because of the space. With the space it says the #myTextArea within a textarea.
$("textarea#myTextArea").val(text);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: Is it possible to create a job from within a DBMS_SCHEDULER job? Creating a job from within a job using DBMS_JOB throws an:
ORA-32317: cannot run a job from a job
Does anyone know if this restriction has been lifted in DBMS_SCHEDULER?
A: Yes you can:
DECLARE
BEGIN
dbms_scheduler.create_job
(job_name => 'TEST1',
job_type=> 'PLSQL_BLOCK',
job_action=>'BEGIN dbms_scheduler.create_job
(job_name => ''TEST2'',
job_type=> ''PLSQL_BLOCK'',
job_action=>''DECLARE v_result NUMBER; BEGIN SELECT 1 INTO v_result FROM dual; END;'',
start_date=>SYSDATE,
repeat_interval=>''FREQ=DAILY'',
end_date=>SYSDATE+1,
enabled=>true,
auto_drop=>false,
comments=>''Job submitted FROM a job''); end;',
start_date=>SYSDATE,
repeat_interval=>'FREQ=DAILY',
end_date=>SYSDATE+1,
enabled=>true,
auto_drop=>false,
comments=>'Job to submit a job');
END;
This demonstrates the concept. You could call a procedure instead of an inline PL/SQL block to do your job submittal. Clearly you can adjust any or all of the parameters to the create_job procedure. I would guess you could spawn a job that spawns yet another job.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609347",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to check open file in other process or not? I use simple script for writing in file between node.js process:
var stream = fs.createWriteStream('test');
stream.once('open', function(fd) {
stream.write(progress_percents);
});
In log I see error "to many open file". How to write to file only if this file not using other processes ?
A: You've diagnosed the problem incorrectly. The too many open files error means that too many files are opened by this process.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how call a python function from Jquery script in django template am new to django and jquery,I am searching for a 'hello world' sample for jquery using django1.3, Where hello world is returned as a string /json from the server to the client when user press a button or at loading of the page.
Note: I am using django1.3 and python 2.7.Sorry this is a very basic question.
I successed in a `shows a string "This is Hello World by JQuery" with out any view functions(using jquery only) .But am unaware of how to use view functions from jquery functions
If any one have idea please help me.Thanks in advance.om templates
I tried using following code snippets.
urls.py
(r'^hellofromserver/$',views.test),
def test(request):
if request.method == 'GET':
json = simplejson.dumps('hello world!')
return HttpResponse(json, mimetype = 'application/json')
jqueyhelloserver.html:
<html>
<head>
<title>jQuery Hello World</title>
<script type="text/javascript" src="{{STATIC_URL}}js/jquery-1.2.6.min.js"></script>
</head>
<body>
.....
<script type="text/javascript">
# how can I get'hello world' from test function(What is the sytax )
</script>
<div id="msgid">
</div>
</body>
</html>
How can I call the functions 'test' and 'hellofromserver' from jquery?(from templates).
A: Finally I got a 'hello' from the server!
urls.py:
from django.views.generic.simple import direct_to_template
(r'^hello/$',direct_to_template, {'template': 'jqueryserver.html'}),
(r'^jqueryserver/$',views.jqueryserver),
views.py:
#other imports
from django.views.decorators.csrf import csrf_exempt
from django.core.context_processors import csrf
from django.views.decorators.csrf import csrf_protect
def jqueryserver(request):
print "in jqueryserver"
response_string="hello"
if request.method == 'GET':
if request.is_ajax()== True:
return HttpResponse(response_string,mimetype='text/plain')
jqueryserver.html
<html>
<head>
<title>jQuery Hello World</title>
<script type="text/javascript" src="{{STATIC_URL}}js/jquery.js"></script>
<script>
$.ajax({
type: "GET",
url: "/jqueryserver/",
success: function(data){
alert(data);
}
});
</script>
</head>
<body>
<form method ="GET" >
<input type= "submit" id = "save" value ="Save" />
</form>
<div id= "test"></div>
</body>
</html>
A: ...And what's the problem you're having? Any information from your Javascript console? Maybe you haven't set up your django app to use CSRF protection.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Upload files from GAE to S3 directly I am creating XML files in my GAE web application and I would like to host them somewhere. The link has to be consistent HOST_URL + filename. So Amazon S3 looks like it would work - I can upload a file and the URL is pointing directly to the file.
Now my question is - how can I upload files from GAE to S3? The Amazon SDK does not work on GAE. What is the upload limit from GAE? Is it 1MB or 32MB? Can you provide maybe a sample HTTP request for uploading data directly to S3?
Would be using the Blobstore API easier? What is the file-size limit for uploading a file that is created in GAE and need to uploaded to Blobstore API directly?
Thanks.
A: As you have noticed already S3 api's don't work well with GAE. For storing files on GAE you can use either BigTable, Blobstore or google storage so pick the option which best suits your needs. There is a nice article describing them all with code samples here
You can save a filename and the blob location in a bigtable.
Once you have your data stored on GAE you can create a special servlet which would take the file name, find the correspoding data informatio in bigtable, retrive it from blobstore for example and return it to the user (just an idea).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Blank textField (Calculation) crashes app. I have an app that does a simple calculation from 2 text fields, the result is then displayed as label text. This is fine as long at each text field is populated, if no data is entered and the calculate button is pressed then the app closed. I assumed that blank would return a value of 0 and result would be displayed as 0. My code is as follows:
-(IBAction) tonerCalc: (id) sender{
NSString *tString;
int myInt = [textField1.text intValue];
int myInt1 = [textField2.text intValue];
int total = myInt/(myInt1/5);
tString = [[NSString alloc] initWithFormat:@"%i",total];
labelText.text = tString;
[tString release];
}
How can I stop the crash, I think it has something to do with the calculation. Any help is greatly appreciated.
A: intValue will return 0 because there is no number in the string. But then you're doing a division by zero.
A: You can put a check like
`if(![textField1.text isEqualToString:@""]|| ![textField2.text isEqualToString:@""])`
{
//perform calculation
}
else
{
//show alert that text field are empty
}
and if the condition is true then you can make your calculation do otherwise show alert.It will stop the crash.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: three Cron jobs runs every two days alternatively not in same day How can i set three cron jobs for every two days interval but not runs all.
This is is my three cron job process:
0 20 */2 * * /usr/local/bin/ruby /var/www/html/data_download1.rb >/dev/null 2>&1
0 20 */2 * * /usr/local/bin/ruby /var/www/html/data_download2.rb >/dev/null 2>&1
0 20 */2 * * /usr/local/bin/ruby /var/www/html/data_download3.rb >/dev/null 2>&1
A: You can use 1-31/2 for one task and 2-30/2 for the other to specify alternating days. This will fail on months with odd numbers of days as the 1-31/2 job will run twice in a row.
If you absolutely must have it right, you can check whether the number of days since a particular date is odd or even and have one script abort if it's odd and the other abort if it's even.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Symfony2 vendors install I'm trying to setup and create new bundle with symfony2, but getting so much error almost every step.
I'm download symfony and run this command;
php bin/vendors install
> Installing/Updating swiftmailer
Cloning into /var/www/Symfony/vendor/swiftmailer...
...
...
...
[ErrorException]
Warning: constant(): Couldn't find constant Monolog\Logger::iNFO in /var/www/Symfony/vendor/symfony/src/Symfony/Bundle/MonologBundle/DependencyInjection/MonologExtension.php line 103
what is the problem? what should I do?
A: Error reason is Turkish system language. so in Turkish language "i" upper case "İ" and "I" lowercase "ı". I'm change my system language to English and problem solved.
A: write handler level uppercased to bypass this code
strtoupper($handler['level']))
for example
level: INFO
A: This sounds very very strange. The MonologExtension uses constant() at one point, and it does it like that:
constant('Monolog\Logger::'.strtoupper($handler['level']))
So basically, it uppercases the given level. Seeing the exception about ::iNFO not being found does not make sense, unless perhaps you have the mbstring extension enabled with the mbstring.func_overload option enabled as well.
Can you check if ini_get('mbstring.func_overload') returns 0/null? Otherwise that may be the cause. I really can't think of anything else.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Performance of invoking unmanaged code from managed code I have a win32 dll and two applications which uses the same dll. One is written using c in unmanaged space and the other is the .net application which makes call to the unmanaged code using Pinvokes.
Sometimes the performance of the .net application is better than the c application. Technically speaking invoking unmanaged code from .net incurs performance overhead but not in this case.
I checked the msdn reference and there seems to be some kind of preprocessing that happens before actual call is made. During linkage the dll is loaded.
I want to understand in what scenarios .net application outperforms?
A: The pinvoke marshaller is one of the heaviest optimized chunks of code in the .NET framework. Very important, there's lots of pinvoke you cannot see when running a managed program on an unmanaged operating system. The amount of overhead is highly variable. It is but a handful of cpu cycles when the DLL is already loaded and the arguments to the pinvoked function are simple integral types. To many hundreds of cycles when, say, string conversions are necessary.
In no circumstance is it ever faster than a native call. Measuring overhead that's only a handful of cycles accurately is difficult. And keep in mind that you might unintentionally measure the perf of your test program instead of the pinvoke call.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: F# interactive vs. F# solution and WCF Try to run this in F# interactive:
#r "System.ServiceModel"
#r "System.Runtime.Serialization"
open System.ServiceModel
[<ServiceContract>]
type IWCF =
[<OperationContract>]
abstract Ping: float -> unit
type WCF () =
interface IWCF with
member o.Ping a = printfn "Hello, %g" a
let svh = new ServiceHost (typeof<WCF>)
You will probably succeed. Try to make a new solution.
Reference:
*
*System.Runtime.Serialization
*System.ServiceModel
Paste the following code into Program.fs:
open System.ServiceModel
[<ServiceContract>]
type IWCF =
[<OperationContract>]
abstract Ping: float -> unit
type WCF () =
interface IWCF with
member o.Ping a = printfn "Hello, %g" a
let svh = new ServiceHost (typeof<WCF>)
And run it. I get the following error:
All parameter names used in operations that make up a service contract must not be null. Parameter name: name
What is wrong?
PS: I use Visual Studio 2010 Ultimate SP1
EDIT: just to make sure, the C# equivalent works fine
A: The problem is indeed that you need to have names for the parameters in WCF-Operations.
Here is a solution to get named parameters in there (named it a just like you did) - as to why it is working in F#-Interactive? No clue, maybe it puts some standardnames for parameters in there.
The syntax is slightly strange but you can define names for the parameters in F#, try:
[<ServiceContract>]
type IWCF =
[<OperationContract>]
abstract member Ping: a:float -> unit
NOTE: I don't know if you need the member in there but I just checked some of my files and did put it in there. I have no compiler around ATM so I will let it sit there in case you really need it (but I don't think so)
A: I know this issue has been marked as answered, but I came across the same exception message, for a completely different reason. I just post in case someone else experience the same problem with the same cause I had.
In my case, I used dotNET_Reactor to obfuscate my service.exe with the flags '-exclude_types 1 -necrobit 1 -mapping_file 1' in addition to -file and -targetfile.
I haven't tracked down the actual "why" it didn't work, but removing the obfuscation helped. It was quite frustrating knowing everything worked from visual studio, but installing the application (which was obfuscated by the build server) on the same machine failed when starting the service.
Bjørnar Sundsbø
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: grails-doc creates copies of my classes in default package In my grails 1.3.7 project, I have put all of my classes in com.mycompany.myapp, as you do. So this goes for services, controllers, domain classes. I have a filter that goes in its own package. My app works fine.
However, when I run grails doc, grails decides to create two pages for every class:
*
*one in its right comp.mycompany.myapp package that has all the right Groovy Doc
*the other takes all the above classes and pretends as if those also live in the default package.
So, target/docs contains two directories: 'DefaultPackage' and 'com', with DefaultPackage holding a copy of everything that lives under com/
Consequently, my groovy doc looks messy because there is two copies for each class.
How can I solve this?
A: It has been documented as a bug at GRAILS-6605. There is no workaround listed there for the bug.
A: I too faced the same issue and so created a plugin "Grails Runtime Docs" ( http://grails.org/plugin/grails-runtime-docs ) that solves this issue and generates both Java and groovy docs properly only 1 copy per class. It's grails aware and categorizes the classes into Controllers, Commands, Domains, Services and Tag Libraries. The groovy documentation is actually generated from runtime so as to include the dynamic methods also, adding "Dynamic Method Summary" & "Dynamic Method Detail" in the generated html docs, that provide their source information. Hope you find it useful.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Datagridview event for enter key I have a bound datagridview.when i select a cell in datagridview and press enter, i want a event to be raised which passes the selected cell's row's first column value to another form. how to do it?
A: I solved this problem by using _EditingControlShowing Event to the datagridview and using PreviewKeyDown to the cell here the code:
DataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler (DataGridView1_EditingControlShowing);
private void dbg_EditingControlShowing (object sender, DataGridViewEditingControlShowingEventArgs e) {
TextBox txb = e.Control as TextBox;
txb.PreviewKeyDown += (S, E) => {
if (E.KeyCode == Keys.Enter) {
DataGridView1.CurrentCell = dbg.CurrentRow.Cells["Column_name"];
//Or any code you ...
}
};
}
A: void TextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.Handled = true;
}
}
void TextBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Return)
{
/* Your code here! */
}
}
A: Assuming this is for Winforms, you can subscribe to one of the Key events and use that event.
For example, here is using the KeyUp event.
private void myDataGridView_KeyUp(object sender, KeyEventArgs e)
{
// nothing is selected
if (myDataGridView.SelectedRows.Count == 0)
return;
if (e.KeyCode == Keys.Enter)
{
string firstColumnValue = myDataGridView.SelectedRows[0].Cells[0].Value.ToString();
// passes the value through the constructor to the
// second form.
MySecondForm f2 = new MySecondForm(firstColumnValue);
f2.Show();
}
}
A: Form 1 Code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Rows.Add();
dt.Rows[dt.Rows.Count - 1][0] = "1";
dt.Rows[dt.Rows.Count - 1][1] = "Stackoverflow";
dataGridView1.DataSource = dt;
}
string ID = string.Empty;
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
ID = dataGridView1.SelectedRows[0].Cells["ID"].Value.ToString();
}
private void dataGridView1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Form2 frmTwo = new Form2(ID);
frmTwo.Show();
}
}
}
Form 2 Code:
public partial class Form2 : Form
{
public string Id = string.Empty;
public Form2(string FormOneID)
{
InitializeComponent();
Id = FormOneID;
}
private void Form2_Load(object sender, EventArgs e)
{
MessageBox.Show("FormOne ID" + Environment.NewLine + Id + Environment.NewLine + "Displaying on FormTwo");
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Facebook Premissions View not showing I create an application integrate Facebook in it. After first login it shows Permissions screen in which it take rights from user. But after sign out and re-sign then it does not show any permissions view i want that it should show on each login. How can i achieve that.
A: You can't.
Once the set of permissions are granted, facebook won't show the permission dialog again.
The only way to display the permission dialog again is to ask for another permission, but in this case, only the new permission will show up in the dialog.
A: You would need to revoke the permissions to get this permissions screen to re-appear. To do that, you could add a logout button and then you would issue an HTTP DELETE request to /PROFILE_ID/permissions. Although from a user perspective this would be mildly annoying to have to approve each time.
A: It's supposed to be a feature! After the first time "Accept", Facebook remembers this & next time on, does not ask.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Universal database GUI i need one GUI that will work on windows and i need to connect on several databases. Access, mySQL, MSSQL, Postgres, SQLite and maybe in future i will need connection to oracle.
It would be nice that tool can move database schemas from one db engine to others without lot user interference...
Can someone recomend me tool for this?
Thanks in advance
A: Try with navicat. It should do everithing you need...
A: Try on of these:
*
*SQL Workbench/j
*Aqua Data Studio
Both work on Windows, Linux and Mac.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Can't debug servlet Eclipse + Glassfish The server is in debugging mode. I've set 10 breakpoints and the browser just skips them all. Why? This happens with JSPs also in that project. Why?
A: Have you checked that the Debbuger is indeed connected with Glassfish? Also please note that it is not possible for the debugger to stop at breakpoints which have been set inside jsp. AFAIK, debugger works only pure java code
A: So you are connecting to external server with "debug remote java application".
What is your server's debug port? Port 8000 is default setting in eclipse debug configuration for remote java appilcation. You should change that value to one that GlassFish server is configured for debugging.
Also, take a look at How do I debug GlassFish 3 using Eclipse Helios?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery Validation - Check if value matches label? I am using the jQuery Validation plugin on a form, and was wondering what's the easiest way of checking if the value of the input is the same as the label?
I'm using jQuery to take the text of each input's label and insert it as the default value of each form element, and then hide the label.
What I'm wanting to do is for the validation to fail if the form is submitted with the default input value unaltered.
Any ideas?
Thanks!
A: You can add a custom validate method (Need to test the code though) :-
$.validator.addMethod("value_label_same", function(value, element) {
var label = element.attr('label');
return label == value
}, "* Label and Value should match");
and use it to validate the field :-
value_label_same : true
Find the documentation here - http://docs.jquery.com/Plugins/Validation/Validator/addMethod#namemethodmessage
A: This answer shows how to create a custom rule. Assuming that you're using <label>s for your controls you'll be able to use a jQuery selector like $("label[for=" + $(element).id + "]) to get the label, and then compare the text to the value of the input.
A: I don't think you need a plugin to do that.
$("input").each(function() {
$(this).blur(function(){
var labelvalue = $("label").text();
var inputvalue = $(this).val();
if(labelvalue === inputvalue) {
console.log("we have a match");
}
else { console.log("no match") }
})
});
A: There are a few ways to achieve this one is with a custom validator method
I think you'll need to do something like this
There are many ways to get the label text
I'm assuming that you want the validation to fail if the label text = the value
$(function (){
jQuery.validator.addMethod(
"doesnotmatchlabel",
function(value, element) {
var label = $(element).closest('div.elHolder').find('label').text();
var result = ! label == value;
return this.optional(element) || result;
},
"required"
);
});
Also to add this method to your elements you might do this...
var textInputs= $('input:text');
if ( textInputs.length ){
textInputs.each(function (i,el){
var jqEl = $(el);
jqEl.rules( "add",
{"doesnotmatchlabel": true}
);
})
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609400",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how can i get the webkit-column-count value and current page or column Id? I am developing application using webview in android. i am loading a page into webview and splitting multiple columns dynamically using CSS3 webkit property. once user reach the last page/column i have to show the TOC confirmation dialog. can anyone please advice me how to do that ?
height:600px;
-webkit-column-width:600px;
-webkit-column-count:auto;
A: How your TOC confirmation dialog is setup?
One possible solution could be to use the :nth-last-of-type(N) selector to select last page/column element http://reference.sitepoint.com/css/pseudoclass-nthlastoftype.
A: Try putting a small element at the end of the text, and then wait for it to appear on screen. It is easily done using jQuery with jquery-appear.
I forked @visualidiot's jsfiddle to create an example using said techniques. Haven't tested it using jQuery Mobile though.
*
*I put a <span> element at the end of the text. The span is floated right to make sure (most of) the last column is shown. In this example, the <span> is not empty (and highly visible), but it would be better if it was just empty.
*The javascript confirm() dialog screws up the scrolling a bit by locking mouse focus on the scroll slider (tested in Chrome 16 on Windows). Showing a confirm dialog in HTML would not.
*Since .appear() works for vertical scrolling as well, this degrades nicely when not having -webkit-column-* available (tested using IE9).
A: Get the total width of your element, and divide it by the width of a single column. Here's an example: http://jsfiddle.net/Ecp9M/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: EXECUTE AS on truncate sproc - Incorrect syntax I'm getting an Incorrect syntax when trying to create a stored procedure to truncate a table then reseed it. Here's my code
CREATE PROCEDURE [dbo].[_TransportZipporah_Purge]
WITH EXECUTE AS owner
AS
TRUNCATE TABLE [dbo].[*tablename*];
GO
DBCC CHECKIDENT ('dbo.*tablename*', RESEED, 0);
As i have got this direct from MSDN I would have thought it would be correct.
Database server i'm using is : SQL Server 2008 v10.0.4064.0
Can anyone help please?
Thanks in advance
Scott
A: The syntax is correct - but you cannot have a GO statement inside a proc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Connect to Mongo DB on MongoLab without Authorization? My Question:
Is there any way to connect to Mongo DB (hosted on MongoLab) without username and password ?
My Case:
I have created a free MongoLab account (https://mongolab.com) and also create new database -> collection -> document in it.
When I connect to Mongo DB (on Mongo Lab) without username and password, I was able to connect, but when I try to retrieve any data it gives me "unauthorized db:testing lock type:-1 client:...." error.
So I have created a DB User in MongLab as well and provide username and password at the time of connection. After that I am able to connect and retrieve data from Mongo DB.
A: MongoLab's multi-tenant database plans are on shared servers. We cannot give you the choice to forgo authentication. Even if you were ok with others seeing you data, the other tenants on the server you share would still not want you to see their data.
We have dedicated server plans where you have your own server. On those we could turn off authentication for you. Email us at support@mongolab.com.
As for your benchmarks - auth will not slow things down. The drivers do not authentication on each request, just each connection. If you use the driver properly it should all work well.
-will (MongoLab)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java: Creating a multi threaded reader I'm creating a reader application. The reader identifies based on the parameters which file to read, does some processing and returns the result to the caller.
I am trying to make this multi-threaded, so that multiple requests can be processed. I thought it was simple but later realized it has some complexity. Even though i create threads using executor service, I still need to return the results back to the caller. So this means waiting for the thread to execute.
Only way i can think of is write to some common location or db and let the caller pick the result from there. Is there any approach possible?
A: Maybe an ExecutorCompletionService can help you. The submitted tasks are placed on a queue when completed. You can use the methods take or poll depending on if you want to wait or not for a task to be available on the completion queue.
ExecutorCompletionService javadoc
A: Use an ExecutorService with a thread pool of size > 1, post custom FutureTask derivatives which override the done() method to signal completion of the task to the UI:
public class MyTask extends FutureTask<MyModel> {
private final MyUI ui;
public MyTask(MyUI toUpdateWhenDone, Callable<MyModel> taskToRun) {
super(taskToRun);
ui=toUpdateWhenDone;
}
@Override
protected void done() {
try {
// retrieve computed result
final MyModel computed=get();
// trigger an UI update with the new model
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
ui.setModel(computed); // set the new UI model
}
});
}
catch(InterruptedException canceled) {
// task was canceled ... handle this case here
}
catch(TimeoutException timeout) {
// task timed out (if there are any such constraints).
// will not happen if there are no constraints on when the task must complete
}
catch(ExecutionException error) {
// handle exceptions thrown during computation of the MyModel object...
// happens if the callable passed during construction of the task throws an
// exception when it's call() method is invoked.
}
}
}
EDIT: For more complex tasks which need to signal status updates, it may be a good idea to create custom SwingWorker derivatives in this manner and post those on the ExecutorService. (You should for the time being not attempt to run multiple SwingWorkers concurrently as the current SwingWorker implementation effectively does not permit it.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Retrieving bitmap giving unknown host exception? I am using this code to get a bitmap from the web
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
InputStream is=conn.getInputStream(); ///Error is pointing me here
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
The only problem is i keep getting this errror. Every to i try to get the bitmap.
The error is pointing me here:
InputStream is=conn.getInputStream();
09-30 06:54:32.512: WARN/System.err(11149): at java.net.InetAddress.lookupHostByName(InetAddress.java:497)
09-30 06:54:32.512: WARN/System.err(11149): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:294)
09-30 06:54:32.512: WARN/System.err(11149): at java.net.InetAddress.getAllByName(InetAddress.java:256)
09-30 06:54:32.512: WARN/System.err(11149): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:69)
09-30 06:54:32.512: WARN/System.err(11149): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:48)
09-30 06:54:32.512: WARN/System.err(11149): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:322)
09-30 06:54:32.512: WARN/System.err(11149): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89)
09-30 06:54:32.512: WARN/System.err(11149): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:285)
09-30 06:54:32.512: WARN/System.err(11149): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:267)
09-30 06:54:32.512: WARN/System.err(11149): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.retrieveResponse(HttpURLConnectionImpl.java:1018)
09-30 06:54:32.512: WARN/System.err(11149): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:512)
A: Obviously, your url address is not valid. Copy your url manually into a browser window, and you should see the same error.
A: That is a network error, it may be that you didn't add an internet permission or your connection network isn't properly set or it may be that your url is wrong.................
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ASIHTTPRequest Asynchronous Download not canceling I am trying to cancel an Asynchronous Download using ASIHTTPRequest with no joy. I am downloading a movie to disk on the appearance of a ViewController. What I want is when the user click close to dismiss the view controller I want to cancel the download. Here is the code I have so far:
Making the request:
-(void)retrieveLatestFile{
NSURL *url = [NSURL URLWithString:[appDelegate.urlToLoad stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ashiRequest = [[ASIHTTPRequest requestWithURL:url] retain];
[ashiRequest setUsername:@"Appidae"];
[ashiRequest setPassword:@"Dubstance1"];
[ashiRequest setDelegate:self];
[ashiRequest startAsynchronous];
[ashiRequest setDownloadProgressDelegate:progressView];
NSLog(@"Value: %f", [progressView progress]);
if ([progressView progress]==1) {
[self hideInfoPane];
}
//NSLog(@"Max: %f, Value: %f", [myProgressIndicator maxValue],[myProgressIndicator doubleValue]);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *tempPath = [NSString stringWithFormat:@"%@/download/%@/%@", documentsDirectory, appDelegate.languageFolder,appDelegate.filename];
NSLog(@"Path: %@", tempPath);
[ashiRequest setDownloadDestinationPath:tempPath];
}
Cancel the the downloading:
- (IBAction)closeDocDisplay:(id)sender {
// Cancels an asynchronous request
[ashiRequest clearDelegatesAndCancel];
[self dismissModalViewControllerAnimated:YES];
}
Everything is working, the download is fine and the movie plays properly but when I dismiss the View Controller the request is not canceled and my file is still downloading (network activity indicator spins on the status bar. Even the ASIHTTP delegate error doesn't get called
A: Try using
ashiRequest.delegate = nil;
[ashiRequest cancel];
This should work.
A: I figured out what was wrong. I was using Reachability to call my retrieveLatestFileMethod. That's fine if Reachability is being used just once in the app, maybe from the delegate. But I had a few instances of it so it keept calling the same functions and downloads.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SWT: custom MessageBox / more text / how to get the icons? i want to display a second, not bold, text in my MessageBox, like seen for OSX here: http://welcome.solutions.brother.com/NR/rdonlyres/1EA4CC0C-F0B9-45D3-BD2C-EF2C430E3FAD/15107/error2.gif
Is there a way to do this with MessageBox? If not, I would create my own Dialog, problem is that i don't know how to load the appropriate icons.
A: Unfortunately, MessageBox is fairly constrained in its functionality. You can get the system icon from the Display class and then set it in a label:
final Image warningImage = getShell().getDisplay().getSystemImage(SWT.ICON_WARNING);
final Label imageLabel = new Label(dialogArea, SWT.NONE);
imageLabel.setImage(image);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Ogg to Riff/Wave encoding with acm My task is to record wave file, convert it to ogg and pack it to the riff container. First two parts were done, but I have problems with the third part. I've found a source code which can solve my problem, but it doesn't work correctly.
#include <windows.h>
#include <windowsx.h>
#include <mmsystem.h>
#include <memory.h>
#include <stdlib.h>
#include <mmreg.h>
#include <msacm.h>
#include <assert.h>
#include <math.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#define INPUT "record.wav"
#define OUTPUT "output_ogg.wav"
/* The following taken from the vorbis.acm sources */
/* Defines modes for encoding. Set this in 'fmt ' */
#define WAVE_FORMAT_VORBIS1 ((WORD)'O'+((WORD)'g'<<8)) // 0x674f("Og") ... Original stream compatible
#define WAVE_FORMAT_VORBIS2 ((WORD)'P'+((WORD)'g'<<8)) // 0x6750("Pg") ... Have independent header
#define WAVE_FORMAT_VORBIS3 ((WORD)'Q'+((WORD)'g'<<8)) // 0x6751("Qg") ... Have no codebook header
#define WAVE_FORMAT_VORBIS1P ((WORD)'o'+((WORD)'g'<<8)) // 0x676f("og") ... Original stream compatible
#define WAVE_FORMAT_VORBIS2P ((WORD)'p'+((WORD)'g'<<8)) // 0x6770("pg") ... Have independent header
#define WAVE_FORMAT_VORBIS3P ((WORD)'q'+((WORD)'g'<<8)) // 0x6771("qg") ... Have no codebook header
/* The 'fact' chunk required for compressed WAV files */
struct FACT {
unsigned long dwID;
unsigned long dwSize;
unsigned long dwSamples;
};
int main()
{
/* Open source file */
HMMIO hSrcWaveFile=mmioOpen(INPUT,NULL,MMIO_READ);
assert(hSrcWaveFile);
MMCKINFO SrcWaveFile;
mmioDescend(hSrcWaveFile,&SrcWaveFile,NULL,0);
assert(SrcWaveFile.ckid==mmioStringToFOURCC("RIFF",MMIO_TOUPPER));
assert(SrcWaveFile.fccType==mmioStringToFOURCC("WAVE",MMIO_TOUPPER));
MMCKINFO SrcWaveFmt;
/* Go to RIFF-WAVE*/
mmioDescend(hSrcWaveFile,&SrcWaveFmt,&SrcWaveFile,0);
assert(SrcWaveFmt.ckid==mmioStringToFOURCC("fmt ",0));
int SrcHeaderSize=SrcWaveFmt.cksize;
if(SrcHeaderSize<sizeof(WAVEFORMATEX))
SrcHeaderSize=sizeof(WAVEFORMATEX);
WAVEFORMATEX *SrcHeader=(WAVEFORMATEX *)new char[SrcHeaderSize];
ZeroMemory(SrcHeader,SrcHeaderSize);
/* Read fmt */
mmioRead(hSrcWaveFile,(char*)SrcHeader,SrcWaveFmt.cksize);
/* Leave the chunk */
mmioAscend(hSrcWaveFile,&SrcWaveFmt,0);
MMCKINFO SrcWaveData;
while(1){
MMRESULT Result=mmioDescend(hSrcWaveFile,&SrcWaveData,&SrcWaveFile,0);
assert(Result==0);
if(SrcWaveData.ckid==mmioStringToFOURCC("data",0))
break;
Result=mmioAscend(hSrcWaveFile,&SrcWaveData, 0);
assert(Result==0);
}
/* Destination header */
WAVEFORMATEX *DstHeader=(WAVEFORMATEX *)malloc(1024);
ZeroMemory(DstHeader,1024);
printf ("Going ACM!\n");
/* Suggest a format for us */
/* Try to coose the nmber 3 mode (whatever that is) */
DstHeader->wFormatTag = WAVE_FORMAT_VORBIS3;
DstHeader->nChannels = 2;
DstHeader->wBitsPerSample = 16;
DstHeader->nSamplesPerSec = 44100;
printf ("->acmFormatSuggest()\n");
if (acmFormatSuggest(NULL,SrcHeader,DstHeader,1024,ACM_FORMATSUGGESTF_WFORMATTAG))
printf ("ERROR: acmFormatSuggest()\n");
/* We shoudl have the DstHeader filled with data byt the ACM now */
/* Open destination */
HMMIO hDstWaveFile;
/* open the destination file */
hDstWaveFile=mmioOpen(OUTPUT,NULL,MMIO_CREATE|MMIO_WRITE);
assert(hDstWaveFile);
printf ("->mmioOpen() output.wav\n");
/* Create chunks */
MMCKINFO DstWaveFile;
DstWaveFile.fccType=mmioStringToFOURCC("WAVE",MMIO_TOUPPER);
mmioCreateChunk(hDstWaveFile,&DstWaveFile,MMIO_CREATERIFF);
printf ("->mmioCreateChunk() WAVE\n");
/* Create format chunk */
MMCKINFO DstWaveFmt;
DstWaveFmt.ckid=mmioStringToFOURCC("fmt ",0);
/* Create chunk write data and Ascend out of it */
mmioCreateChunk(hDstWaveFile,&DstWaveFmt,0);
printf ("->mmioCreateChunk() fmt\n");
mmioWrite(hDstWaveFile,(char*)DstHeader,sizeof(WAVEFORMATEX)+DstHeader->cbSize);
printf ("->mmioWrite() fmt header\n");
mmioAscend(hDstWaveFile,&DstWaveFmt,0);
printf ("->mmioAscend()\n");
/* fact chunk */
/* this is only my idea of what it should look like */
/* i found that some WAV files had more data than i write */
/* but that seems enough for most of apps i tested */
FACT DstFactChunk;
MMCKINFO FactChunk;
DstFactChunk.dwID = mmioStringToFOURCC ("fact", 0);
DstFactChunk.dwSamples = SrcWaveData.cksize / 4;
DstFactChunk.dwSize = sizeof (DstFactChunk) - sizeof (DstFactChunk.dwID) - sizeof (DstFactChunk.dwSize);
FactChunk.ckid = mmioStringToFOURCC ("fact", 0);
FactChunk.cksize = DstFactChunk.dwSize;
/* Calculate the time */
float TIME;
if (SrcHeader->nSamplesPerSec == 44100)
TIME = DstFactChunk.dwSamples / 44100.f;
mmioWrite (hDstWaveFile, (char *)&DstFactChunk, sizeof (DstFactChunk));
/* This ascend produced an error when i added this whole code */
/* to my Dialog based MFC full feature super duper app */
/* Don't know why really but i think that Write already moves the pointer */
/* past the chun sok this is unnecessery */
/* mmioAscend (hDstWaveFile, &FactChunk, 0); */
/* Create Data chunk */
MMCKINFO DstWaveData;
DstWaveData.ckid=mmioStringToFOURCC("data",0);
mmioCreateChunk(hDstWaveFile,&DstWaveData,0);
mmioAscend (hDstWaveFile, &DstWaveData, 0);
printf ("->mmioCreateChunk() data\n");
/* Print the data we have gathered so far */
printf ("------------Source-----------\n");
printf ("Format: \t\t%X\n", SrcHeader->wFormatTag);
printf ("Channels: \t\t%d\n", SrcHeader->nChannels);
printf ("Samples/Sec: \t\t%d\n", SrcHeader->nSamplesPerSec);
printf ("AverageBytes/Sec: \t%d\n", SrcHeader->nAvgBytesPerSec);
printf ("Bits/Sample: \t\t%d\n", SrcHeader->wBitsPerSample);
printf ("BlockAlign: \t\t%d\n", SrcHeader->nBlockAlign);
printf ("DataSize: \t\t%d\n", SrcWaveData.cksize);
printf ("Time: \t\t\t%.3f\n", TIME);
printf ("Samples: \t\t%d\n", DstFactChunk.dwSamples);
printf ("Extra: \t\t\t%d\n", SrcHeader->cbSize);
printf ("------------------------------\n");
printf ("\n------------Destination------\n");
printf ("Format: \t\t%X\n", DstHeader->wFormatTag);
printf ("Channels: \t\t%d\n", DstHeader->nChannels);
printf ("Samples/Sec: \t\t%d\n", DstHeader->nSamplesPerSec);
printf ("AverageBytes/Sec: \t%d\n", DstHeader->nAvgBytesPerSec);
printf ("Bits/Sample: \t\t%d\n", DstHeader->wBitsPerSample);
printf ("BlockAlign: \t\t%d\n", DstHeader->nBlockAlign);
printf ("Extra: \t\t\t%d\n", DstHeader->cbSize);
printf ("------------------------------\n");
DWORD maxFormatSize = 0;
MMRESULT ACMres;
/* Get the max possbile size from the system this really no necessery */
/* but i was experimenting a bit and so I left it here */
ACMres = acmMetrics( NULL, ACM_METRIC_MAX_SIZE_FORMAT, &maxFormatSize );
if (ACMres != MMSYSERR_NOERROR){
printf ("ERROR: acmMetrics()\n");
}
/* Open ACM stream */
HACMSTREAM acm = NULL;
MMRESULT Result=acmStreamOpen(&acm,NULL,SrcHeader,DstHeader,NULL,0,0,0);
printf ("->acmStreamOpen()\n");
if (Result != MMSYSERR_NOERROR){
printf ("ERROR: acmStreamOpen()\n");
exit (-1);
}
/* This is where the problem's begin, first the buffers */
/* Size of the dest/src is based on the size of src/dest */
DWORD DefaultWriteSize;
DWORD DefaultReadSize = SrcHeader->nBlockAlign * 1024;
/* If we know the dest */
/* Result=acmStreamSize(acm, DefaultWriteSize, &DefaultReadSize, ACM_STREAMSIZEF_DESTINATION); */
printf ("->acmStreamSize()\n");
/* If we know the source, well stay with the source PCM is less problematic */
Result = acmStreamSize (acm, DefaultReadSize, &DefaultWriteSize, ACM_STREAMSIZEF_SOURCE);
printf ("->acmStreamSize() gave us buffer size [%d]\n", DefaultWriteSize);
if (Result != MMSYSERR_NOERROR){
printf ("ERROR: acmStreamSize()\n");
exit (-1);
}
/* Allocate memory */
ACMSTREAMHEADER stream;
ZeroMemory(&stream,sizeof(stream));
stream.cbStruct=sizeof(stream);
stream.pbSrc=(BYTE*)GlobalAlloc(GMEM_FIXED,DefaultReadSize);
stream.cbSrcLength=DefaultReadSize;
stream.pbDst=(BYTE*)GlobalAlloc(GMEM_FIXED,DefaultWriteSize);
stream.cbDstLength=DefaultWriteSize;
/* Prepare header */
printf ("->acmStreamPrepareHeader()\n");
Result=acmStreamPrepareHeader(acm, &stream,0);
if (Result != MMSYSERR_NOERROR){
printf ("ERROR: acmStreamPrepareHeader()\n");
exit (-1);
}
/* The main encoding loop */
/* I'm pretty sure that before the actual reading of samples from the source */
/* I should feed the ACM some junk so that it would write the necessery headers */
/* that Ogg Vorbis requires */
/* but i dont know how much of that 'junk' i would have to write there */
/* i don't know if it can be junk */
/* well i'm pretty clueless here */
for(int RemainSize=SrcWaveData.cksize;RemainSize>0;){
// ????
int ReadSize=DefaultReadSize;
if(ReadSize>RemainSize)
ReadSize=RemainSize;
RemainSize-=ReadSize;
ReadSize=mmioRead(hSrcWaveFile,(char*)stream.pbSrc,ReadSize);
if (ReadSize == -1){
printf ("Can't read\n");
break;
}
stream.cbSrcLength=ReadSize;
/* Convert */
Result=acmStreamConvert(acm,&stream,0);
if (Result)
printf ("ERROR: acmStreamConvert()\n");
int WriteSize=stream.cbDstLengthUsed;
/* Wrtie data */
Result=mmioWrite(hDstWaveFile,(char*)stream.pbDst,WriteSize);
if (Result == -1){
printf ("Can't Write");
break;
}
/* Uncomment this if you want to see the buffer sizes */
/* printf ("READ[%d] :: WRITE[%d]\n", stream.cbSrcLengthUsed, stream.cbDstLengthUsed); */
}
/* Cleaup on Isle 5 !!! */
GlobalFree(stream.pbSrc);
GlobalFree(stream.pbDst);
acmStreamUnprepareHeader(acm,&stream,0);
acmStreamClose(acm,0);
mmioAscend(hSrcWaveFile,&SrcWaveData,0);
mmioAscend(hSrcWaveFile,&SrcWaveFile,0);
mmioAscend(hDstWaveFile,&DstWaveData,0);
mmioAscend(hDstWaveFile,&DstWaveFile,0);
free(DstHeader);
mmioClose(hSrcWaveFile,0);
mmioClose(hDstWaveFile,0);
delete[] SrcHeader;
return 0;
}
When I'm trying to execute this program, it shows me that acmFormatSuggest() and acmStreamOpen() failes. Please, help me finding the error.
A: acmFormatSuggest (by the way, what is the error code?) would possibly succeed if there is an ACM audio codec installed, which supports this format. There is no one available by default, do you actually have one installed?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to mock DbContext Here is the code I want to test
public DocumentDto SaveDocument(DocumentDto documentDto)
{
Document document = null;
using (_documentRepository.DbContext.BeginTransaction())
{
try
{
if (documentDto.IsDirty)
{
if (documentDto.Id == 0)
{
document = CreateNewDocument(documentDto);
}
else if (documentDto.Id > 0)
{
document = ChangeExistingDocument(documentDto);
}
document = _documentRepository.SaveOrUpdate(document);
_documentRepository.DbContext.CommitChanges();
}
}
catch
{
_documentRepository.DbContext.RollbackTransaction();
throw;
}
}
return MapperFactory.GetDocumentDto(document);
}
And here is my test code
[Test]
public void SaveDocumentsWithNewDocumentWillReturnTheSame()
{
//Arrange
IDocumentService documentService = new DocumentService(_ducumentMockRepository,
_identityOfSealMockRepository, _customsOfficeOfTransitMockRepository,
_accountMockRepository, _documentGuaranteeMockRepository,
_guaranteeMockRepository, _goodsPositionMockRepository);
var documentDto = new NctsDepartureNoDto();
//Act
var retDocumentDto = documentService.SaveDocument(documentDto);
//Assert
Assert.AreEqual(documentDto, documentDto);
}
Once I run the test I get Null exception for the DbContext on the line
using (_documentRepository.DbContext.BeginTransaction())
The problem I have is I don't have access to the DbContext. How would I go about solving it
A: As far as I understand you are injecting the repository through the constructor of Document Service as ducumentMockRepository.
So you can setup this mock with any expectations you want.
For your case you've to substitute DbContext by mock as well
// I hope you have an interface to abstract DbContext?
var dbContextMock = MockRepository.GenerateMock<IDbContext>();
// setup expectations for DbContext mock
dbContextMock.Expect(...)
// bind mock of the DbContext to property of repository.DbContext
ducumentMockRepository.Expect(mock => mock.DbContext)
.Return(dbContextMock)
.Repeat()
.Any();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: .NET MVC 3 Routes Recently I've made the transition from Web Forms to MVC 3 and I've been trying to get to grips with MVC routes. I have a somewhat peculiar problem in that when I receive a request to my application (e.g. subdomain1.organisation.com or subdomain2.organisation.com) I wish the default route to be used as follows:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
However, when a request is received by my application through a particular subdomain e.g. subdomain3.organisation.com, I want the application to default to a particular controller. I've been following code at:
http://blog.maartenballiauw.be/post/2009/05/20/ASPNET-MVC-Domain-Routing.aspx
which should what I want. So the code in my Global.asax is as follows:
routes.Add("DomainRoute", new DomainRoute(
"subdomain3.organisation.com", // Domain with parameters
"{action}/{id}", // URL with parameters
new { controller = "Subdomain3Controller", action = "Index", id = "" }
));
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
When deployed, my application behaves correctly when requests are sent to subdomain3.organisation.com, using Subdomain3Controller. However, when visiting any other subdomain e.g. localhost/Subdomain3Controller/Index my application seems to select the incorrect route.
My form helpers appear to return an incorrect value for:
ViewContext.Controller.ValueProvider.GetValue("controller").AttemptedValue
@using(Html.BeginForm(ViewContext.Controller.ValueProvider.GetValue("action").AttemptedValue, ViewContext.Controller.ValueProvider.GetValue("controller").AttemptedValue, FormMethod.Post, new Dictionary<string, object> {{ "id", "formid" } })){
Any ideas why this might be? Any light that anyone could shed on this issue would be much appreciated.
Many thanks in advance.
A: Have you tried the routing debugger, which is designed to help debug these sorts of problems
Looks like it's installable via Nuget now too.
A: I've also noticed that if I hard-code the controller name into the BeginForm helper, the incorrect action value is still returned:
using (Html.BeginForm("Index", "Subdomain3Controller", FormMethod.Post, new Dictionary<string, object> { { "id", "formid" } }))
{
generates:
<form id="formid" method="post" action="/">
rather than:
<form id="formid" method="post" action="/Subdomain3Controller">
when viewing:
http://localhost/Subdomain3Controller/ or http://localhost/Subdomain3Controller/Index
A: Stumbled on a similar problem and managed to find a solution for this problem. I'm aware this might not help the original author, but it might help some other people who end up here via search.
Anyway, it seems the route name "Default" doesn't add much weight. When BeginForm is constructing its URL it takes the first route from the route collection that 'fits'. I didn't dig too deep into how this all works internally.
What I did to solve this problem was add a constraint to the subdomain route so it can only be used for the Subdomain3Controller, as such:
var domainRoute = new DomainRoute(
"subdomain3.organisation.com", // Domain with parameters
"{action}/{id}", // URL with parameters
new { controller = "Subdomain3Controller", action = "Index", id = "" }
);
domainRoute.Constraints = new RouteValueDictionary();
webserviceRoute.Constraints.Add("Controller", "Subdomain3Controller");
routes.Add("DomainRoute", domainRoute);
[edit]
After thinking about this a little bit more and realizing my situation was a bit different from the situation of the original poster. The above won't work, because the controller is not inside of the URL anymore.
A solution might be to switch the order of the routes, and add a NotEqual constraint for the subdomains to the default route. As described in http://stephenwalther.com/archive/2008/08/07/asp-net-mvc-tip-30-create-custom-route-constraints.aspx
[/edit]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Setup Project msi builds+ claims successful install, but no output As per the title, I create a msi installer and then run it and it claims to have successfully installed and if I look in the control panel to add/remove program it appears there. However, when I look in the directory I specified, there is no change made to it. Nothing is copied into it.
When I run the installer and click the button to create a new directory and choose that new directory to install into, I get no errors. It all runs fine, but after exiting the installer, this new directory is not created.
I follow these steps to create my msi installer:
*
*Open Visual Studio and open the project I wish to create installer for
*File-> Add -> New Project -> Setup Wizard
*Select "Create a setup for Windows Application"
*Select "Primary output from (project)"
*Add additional file -> path to txt file
*Finish setup wizard
*Look at Application Folder for setup
*Right click primary output from (project)
*Click outputs and verify it is correct
*Build the setup project
This outputs the .msi file along with the .exe file. There is no problems/errors running either of these. It just doesn't install/copy the files.
A:
Ok, so it was a privileges issue when double clicking the .msi file.
It would run fine and claim to install successfully but it didn't create folders/copy stuff in etc. It needed admin privileges to install.
So, to give it the privileges I edited the .vdproj file that created the .msi file (edited in notepad). I went to the MsiBootstrapper section and changed "RequiresElevation" = "11:FALSE" to "RequiresElevation" = "11:TRUE".
More information can be found here: http://msdn.microsoft.com/en-us/library/2kt85ked.aspx
I'm still not completely happy with this, it requires double clicking the .exe file which gives the UAC prompt to get the .msi file to run with the required privileges. It seems very easy for a user to just double click the .msi file and believe things to have installed...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Visual studio 2010 project for windows and linux I'm trying to make a program that works on linux and windows.
I'm writing the program in visual studio in a windows environment.
So I wonder how I could compile my project from visual studio to linux.
A: The Microsoft C++ compiler is not capable of producing Linux executables.
You will need to use a more portable compiler for your Linux executables, e.g. gcc. Perhaps you may benefit from a cross-platform IDE like Code Blocks or Eclipse rather than Visual Studio.
A: You should try QT. It is pretty good framework for cross-platform development. The opensource version is free and very well maintained and has the LGPL license. That means you can sell your product as closed source but then you have to dynamically link to QT libraries.
A: You can use CMake. It will allow you to generate project/solution files for Visual Studio and Makefiles for Linux. This way, you can work using the native tool chain for a platform, while managing a single makefile. However, it's up to you to write portable code and to choose the appropriate libraries for your program to be truly portable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: HTML format to print on 8.5x11 I have multiple sets of data and I would like them to look identical on individual 8.5x11 (standard size) sheets of paper. I am rendering them in HTML for printing by putting each set in an 8.5x11 div, but that div for some reason will always get cut off. Is there any way I can fix this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Java Desktop Application and Functionality Autherization I'm fairly new to java development and I have found myself tasked with implementing a functionality authorization system for a desktop application written in java.
Currently the application requires user authentication at startup and users are authenticated against an active directory server via LDAP.
The application as it stands has no user privillage system in place, once a user is authenticated they have full access to the applications entire functionality.
What I need to do is define a number of user roles or groups which have access to different functionality i.e. user:Alice (of group:Admin) may see menuItem:EditCell in a popup menu for a JTable but user:Bob (of group:Peasant) may not.
It has been suggested that I look into Spring security and method/class annotation but I'm finding it a little difficult to get my head around the information I have found so far.
Is there anyone who has had a similar experience around who might be able to offer some assistance?
Cheers,
A: I would definitely recommend Shiro over Spring for your use case. Take a look at their website and go through the 10 minute quick guide. You'll be surprised at home much you can get done with simple, straightforward code.
For simple testing you can define roles within Shiro itself, but eventually you are going to want to put all the roles into your LDAP.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Array fundamental I have one array size of 11 with String, i add some item in it.
Decalration::
String arr_sound[] = new String[11];
Initialization::
arr_sound[0] = "bike_route.mp3";
arr_sound[1] = "closed.mp3";
arr_sound[2] = "exit.mp3";
arr_sound[3] = "no_parking.mp3";
....
....
arr_sound[11] = "touch_and_show.mp3";
Problem if i am initialize with arr_sound[01] = "closed.mp3" give error.any solution ?
Thanks
A: This line:
arr_sound[11] = "touch_and_show.mp3";
Should throw an ArrayOutOfBoundException.
Your array can contain 11 Items as defined.
The first goes into arr_sound[0]
And the 11th and last into arr_sound[10].
arr_sound[11] would be the 12th item.
A: You should know that in java numbers that start with 0 - are octal numbers.
A: you should not use code like this:
arr_sound[01] = ...
or
arr_sound[11] = ...
because the index is an int and has to be from 0 to 10
A: arr_sound[11] = "touch_and_show.mp3";
This will not work if your array has only 11 elements. You need to create an array with 12 elements:
new String[12];
A: Why are you initializing with O1?
The correct thing should start from 0 because that's the first default index for java, unless you set it otherwise.
arr_sound[0] arr_sound[1] . . . arr_sound[10]
Values that start with 0 are likely octal.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: MVC Ajax action relative to current controller I'm trying to get an Ajax call from a link in a master page.
So I want to specify only the action relative to the current page/controller.
i.e.
$.ajax({
url: '/Save',
type: "GET",
// .. etc
});
I want to call the "Save" action of whatever controller served the page. I thought this would work straight off, but it doesn't appear to. Is there an elegant solution?
A: If you got this straight into your view, you could do
$.ajax({
url: '@Url.Action("Save")',
type: "GET",
// .. etc
});
If not, and javascript is in external file, you could attach url generated with Url.Action to element as data-? html5 attribute. And then dynamically read that attribute value before doing ajax call.
<input type="text" data-save-action-url="@Url.Action("Save")" />
You should never hardcode url's in asp.net mvc. Always use Url.Action. It inspects your routing configuration when generating urls, and will always return correct value according to it. If you hardcode urls, your application may become unusable when you change routing configuration. And you will have to change every single url in you application manually.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: send Image byte data in json request in android? I would like to send image byte data in Http Post in android and iPhone.
Let me know hoe to send Image data in JSON Like below JSON String
{
"Request": {
"data": {
"Key": "keydata",
"info": {},
"param": {
"title": "Testingpostmultipartimageupload",
"photo": **"IMAGE BYTE DATA"**,
"photoFilename": "Test.png"
}
},
"info": {}
}
Thanks in advance,
A: ByteArrayOutputStream ba = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, ba);
byte[] bmpbyte_sign = ba.toByteArray();
pass bmpbyte_sign.
Hope will help u...
A: Dude just convert the image into the bytes then decode with this data with base64 string and pass that string in the json. BTW I'm from iPhone
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: cc static linking: How to import all symbols of just one .a library? I have 2 static libraries,
libalgha.a with 2 functions: func1() and func2()
and
libbeta.a with 2 functions: func3() and func4()
I have 1 executable (mytest) linked with these 2 libs. The executable calls only func1() and func3(). So as I understand the linker will put only the symbol of these 2 functions into the executable.
The executable is loading with dlopen() in runtime a shared library (libgamma.so) and this shared library uses the function func2() from libalgha.a. When running mytest I get the error:
symbol func2: referenced symbol not found
I can't include libalgha.a inside libgamma.so because of a Solaris 32/64 bits issue.
So how can I link mytest with all symbols of libalgha.a ?
A: Maybe -u func2 would help. See the manual page.
Unfortunately, there doesn't seem to be a --whole-archive option as on GNU.
A: Include a reference to func2 in your program source like:
extern void func2 ();
void (*pfunc2)() = func2;
Alternatively, link the whole library into one object, using ld -r, and link that object to the executable, instead of the library. You may or may not need to extract objects, e.g., if the following does not work:
ld -r -o libbeta.o libbeta.a
then do
mkdir x
cd x
ar x ../libbeta.a
ld -r -o ../libbeta.o *.o
cd ..
rm -rf x
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: get windows service used memory using wmi I'm trying to retrieve the amount of memory used by a windows service, for example, IIS. I'm using python and windows wmi extensions. I didn't find any method on WIN32_Service class that would give me the information I need. What's the best approach to get this information?
A: Information concerning process memory is exposed through WMI using the Win32_Process class. In particular, you'd probably be interested in the WorkingSetSize and VirtualSize properties. Since you are starting from a service, you will want to obtain the ProcessId property from your service in order to select the appropriate Win32_Process instance.
Monitoring the total memory consumption of IIS can be a bit complex as IIS spins up multiple processes and services depending on how it's configured (see the hierarchy of managed entities described here). But, let's assume for this example that we're only interested in the memory consumed by W3SVC, which implements the actual HTTP protocol. Assuming we are using Tim Golden's fantastic WMI library, we would need to do something like this:
import wmi
c = wmi.WMI()
for www_srv in c.Win32_Service(Name = 'W3SVC'):
for process in c.Win32_Process(ProcessId = www_srv.ProcessId):
print 'Memory used by W3SVC', process.WorkingSetSize
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MooTools using grab/inject to append child elements How do I append a new Element into another? The code below is using the examples on the library's site but nothing is rendered. I tested the containing Element by using .innerHTML which does render. what am I doing wrong?
var Article = new Class({
initialize: function(order, title, body){
this.order = order;
this.title = title;
this.body = body;
}
});
window.addEvent("domready", function() {
var Content = new Hash();
Content.set("dbitem15", new Article(1, "title1", "content1"));
Content.set("dbitem33", new Article(2, "title2", "content2"));
Hash.each(Content, function(value, key){
var article_title = new Element("div", {id: "title" + key});
article_title.set("class", "article_title");
article_title.innerHTML = value.title;
var article_content = new Element("div", {id: "content" + key});
article_content.set("class", "article_content");
article_content.innerHTML = value.body;
var article = new Element("div", {id: key});
article.set("class", "article");
article.inject(article_title, "after");
article.inject(article_content, "after");
//article.grab(article_title, "after");
//article.grab(article_content, "after");
//article.innerHTML = key;
$("plan").grab(article,"after");
});
});
A: Here is some (refactored) code that works: http://jsfiddle.net/mqchen/kJqLf/1/
The main difference is this:
article.grab(article_title, "bottom");
article.grab(article_content, "bottom");
The problem was that you used inject(..., after) which means that you added the created elements (title, content) after the article element, which means that when you later put the article element into the "plan" element, the title and content elements were not added (they are somewhere in the empty vacuum of space). You need to put the title and content elements inside the article element using grab(..., bottom).
A: Assuming I am not reading the code incorrectly, you are attempting to insert the article_title and article_content into article, yes?:
article.inject(article_title, "after");
article.inject(article_content, "after");
In that case, you've switched the elements around. .inject() references the element to be injected, and the first parameter is for the container element.
So try:
article_title.inject(article, "after");
article_content.inject(article, "after");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How could I prevent users from certain countries from uploading? I've noticed a lot of...suspicious activities from a few countries, so I'd like to "blanket ban" those countries (similar to how plentyoffish prevents users from certain countries from uploading their pics).
Would this just be a matter of hardcoding IP address ranges, and checking against that? Are there any examples of this in PHP?
A: A great resource for detecting countries by IP with PHP can be found from PHPTutorial.info. Uses text files for IP ranges and thus is very simple to set up - no database setup or data import needed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.