text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: DataGridView: DefaultCellStyle working with decimals
I am using a Datagidview control on winforms. This is getting filled dynamically. I am trying to display 4 decimal format number in the grid. I applied the DefaultCellStyle property as;
dataGridViewCellStyle2.Format = "N4";
dataGridView1.DefaultCellStyle= dataGridViewCellStyle2;
When I enter data as 21.2134 it displays it properly. But when I enter a complete number like 20, it shows me number as 20.0000. I want to get rid of those trailing 0's.
Edit:
One more issue just encountered. with this code it accepts data as 21.2100.
Please help me to resolve this issue.
Thanks in advance.
Vijay
A: You should try setting the format as
dataGridViewCellStyle2.Format = "0.####";
This will ensure for upto four decimnal points and would be displayed only if values are present
So in your case it should be 21.2134 and just 20. When you want to access the values use FormattedValue which will do the formatting as specified for the entered value.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to get PathVariable (String) in a Controller method @RequestMapping(value = "/user/search/{email}")
public String auditUseremail(@PathVariable("email") String email,Map<String, Object> map) {
System.out.println(email);
}
this is my conroller class function, which is called when the action is http://localhost:8080/LACASServer/secure/user/search/user@cohaesus.co.uk
as u can look, email is in URL, but when i print it in the above method, i get it user@cohaesus.co, can anybody tell me, what can be the issue and how to resolve it.
A: I think you should use URL Encoding for this path and then decode it inside of controller
java.net.URLEncoder.encode(email, "ISO-8859-1");
You can read more about it here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Where can i find the jboss-j2ee.jar file in JBoss 6? In jboss 4.0 the file called jboss-j2ee.jar. But i can't find this jar in jboss 6.0's client directory. I need just for compilation to resolve few annotation. I'm not using maven, so adding pom reference would not help. I have to download jar file from somewhere and it dependencies.
A: jboss-ejb-api_3.1_spec.jar is enough for my purpose. Can be found in Jboss client folder
A: Check JBoss community wiki .
You can also download the jarsHope this helps.
A: For those who are using JBoss EAP 6, I found this file suited my purposes:jboss-ejb-api_3.1_spec-1.0.2.Final-redhat-2.jar
Found here:
..\jboss-eap-6.3\modules\system\layers\base\javax\ejb\api\main
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Wix 3.5 desktop shortcut In my application, a shortcut to desktop is provided. After it's installed, when mouse points to shortcut, it shows location details (installation path).
What should do in order to hide this information in wix?
My code is:
<Component>
<File Id ="Scan" Name="Scan.exe" Source="Scan.exe">
<Shortcut Id ="Shortcut" Name="Scanner" Directory="DesktopFolder" Advertise="no" />
</File>
<RegistryValue Root="HKCU" Key="Software\Scanner\Company\Device" Name="Scan" Type="integer" Value="0" KeyPath="yes"/>
</Component>
A: If I remember correctly, the Description attribute defines what is displayed in the shortcut's tooltip. It seems the installation path is the default value. So, I think you should add Description attribute to the Shortcut element in order to overwrite the text.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Monitor assignment PHP extension I'm trying to figure out if it is possible to make an extension that monitors every assignment that is made in PHP.
I want to do some taint detection, I've seen the PHP taint project, but it would be nicer to have it as an extension for my project.
Additionally, where can I find API documentation and similar for Zend/PHP extensions, I haven't been able to find anything good :/
A: http://pecl.php.net/package/taint
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MySQL and C#.NET DataGridView, Updates, Inserts and Deletes The other day I started working on a project in C#.NET using Windows Forms and it's been quite a while since I last used Windows Forms so I'm feeling a bit rusty.
First off I should point out that I'm using Visual C# 2010 Express which does not have GUI wizard support for databindings (well it does, if you enjoy MS Access or locally stored database files) and I need to speak to a MySQL database and make it play nice with a DataGridView.
My problem stems from the fact that I can't quite figure out how to do updates and deletes. Most online sources I've found seem to just refer to running the data binding wizard, something I can't do (since I'm running Visual C# 2010 Express).
Now, I've been able to select data from the database without any major problems (using a MySqlDataAdapter, a BindingSource and a DataTable) but when I try to use MySqlDataAdapter.Update(<DataTable>) nothing happens.
I'm assuming there is some setup work I need to do which is normally handwaved away as "just use the wizard". So, does anyone have a simple example of what I need to do to be able to do updates, inserts and deletes? With or without stored procedures, both ways are fine (although I'll probably end up used stored procs in the finished program).
A: I suggest you to do not use those DragDroppable DataAdapter or BindingSources from the VS Toolbox, just layer your project properly in different projects each one with its own concern, like Data Access, Business Logic and Presentation (GUI).
see my answer here: MVC3 and Entity Framework
if you have a solid layered / m-tier architecture you will find out that data management logic belongs only to the Data Access Layer and the UI just has to ask what is needed going through the Business Logic.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to upload files to Google Docs through Google Data API? I developing an application which works with Google API, according to my understanding.
def push_to_ga(request):
client = gdata.docs.service.DocsService()
client.ClientLogin('account@gmail.com', 'password')
entrys = Entry.objects.all()
for entry in entrys:
splitted = entry.file.split('/')
client.UploadDocument(entry.file, splitted[-1])
return HttpResponseRedirect('https://docs.google.com/#home')
Have an error:
Traceback:
File "/home/i159/Env/googleapi/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/home/i159/workspace/apiroot/googleapi/../googleapi/apiapp/views.py" in push_to_ga
38. client.UploadDocument(entry.file, 'My entry #' + str(entry.id))
File "/home/i159/Env/googleapi/lib/python2.6/site-packages/atom/init.py" in deprecated_function
1475. return f(*args, **kwargs)
File "/home/i159/Env/googleapi/lib/python2.6/site-packages/gdata/docs/service.py" in UploadDocument
494. folder_or_uri=folder_or_uri)
File "/home/i159/Env/googleapi/lib/python2.6/site-packages/gdata/docs/service.py" in _UploadFile
160. extra_headers={'Slug': media_source.file_name},
Exception Type: AttributeError at /push_to_ga/
Exception Value: 'unicode' object has no attribute 'file_name'
I can't find docs with description of the methods. How to upload file into Google Docs through API?
A: Which version of the Google API are you using?
According to the Google documentation, for versions 1.0 and 2.0 you have to wrap the document as a MediaSource object in order to pass it to the Upload method. So, I think you need to replace:
client.UploadDocument(entry.file, splitted[-1])
with:
ms = gdata.MediaSource(file_path=entry.file, content_type=gdata.docs.service.SUPPORTED_FILETYPES['DOC'])
client.Upload(ms, splitted[-1])
Note: this assumes that you are uploading Word files. You should set the content_type parameter to the correct type for each file that you upload.
If you're using version 3.0, you no longer need to create a MediaSource object - you can simply pass the pathname, title and mime type directly to the Upload method:
client.Upload(entry.file, splitted[-1], content_type='application/msword')
Uploading PDFs
If you attempt to upload PDF files using version 2.0 of the API, it fails with the error:
{'status': 415, 'body': 'Content-Type application/pdf is not a valid input type.', 'reason': 'Unsupported Media Type'}
This can be fixed using the workaround shown in comment 77 on issue 591 on the Google Code site. Simple edit the _UploadFile method in your site-packages/gdata/docs/services.py file as shown on that ticket. Once you have made this change, PDF uploads should work fine (I have checked this & it works for me).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Need to know object locking information In java, I have created an object with global scope.
At some point I am in a different thread and need to know whether the global object is currently locked by any threads.
*
*Krishna
A: This is not possible using the synchronized keyword on ordinary Objects.
You need a "lock" object, perhaps one implementing java.lang.concurrent.locks.Lock, which offers a tryLock() method or similar.
This allows your thread to attempt to acquire the lock, returning true if the Lock is not currently locked elsewhere.
Of course, in this case, you may then need to unlock the lock immediately - otherwise your thread will prevent other threads from making progress.
A: The big problem here is defining 'currently'.
The best I can suggest is to try to acquire the lock with a zero timeout. If you get the lock, you are sure that the global object is locked - by your 'different thread'. If not, the object may be locked or not by some other thread, probably it is, but the lock may have been released while your failed lock attempt was returning. You should be able to get more reliable results if you raise the priority of your 'different thread' to the highest possible during your lock attempt.
If this test is for some temporary debugging, optimization or statistical purpose then fine, but you should not use anything like this to implement deliverable functionality.
Rgds,
Martin
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595175",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Loop to create form I want to create a for loop to create 10 text inputs with unique names/ids. Currently I am using the following code.
<?php
for ($i = 0; $i < 10; $i++) {
echo "<input name='person'" + $i + "' type='text' id='person'" + $i + "' /><br />";
}
?>
Now it just outputs the number in the loop, but doesn't output any inputs.
Thanks.
A: Concatenation in php is done via '.' and not '+'
<?php
for ($i = 0; $i < 10; $i++) {
echo "<input name='person". $i . "' type='text' id='person" . $i . "' /><br />";
}
?>
A: I think you have a slight error in your HTML attribute syntax, so your quote marks are in the wrong place.
<?php
for ($i = 0; $i < 10; $i++) {
echo "<input name='person" + $i + "' type='text' id='person" + $i + "' /><br />";
}
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: android, Manifest shows error for android:targetSdkVersion I have defined following line in My manifest file but an error occurs.
<uses-sdk android:minSdkVersion="3" android:targetSdkVersion="8" />
and the error message is:
error: No resource identifier found for attribute 'targetSdkVersion'
in package 'android'
How can I handle this problem?
A: android:targetSdkVersion was added in api level 4 which is android 1.6. Make sure you are compiling your project with 1.6 and above and you have not set 1.5 as build target.
A: In addition to above, make sure you delete the project's bin directory too so it's rebuilt with the updated android build target.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Log4j Multiple Threads I am adding ConsoleAppender to rootlogger for log4j as
BasicConfigurator.configure(new ConsoleAppender(layout, "System.err"));
But somehow log messages in some loggers down the hierarchy are not reaching console. I have not seen any instance in the hierarchy setting the additivity flag as false.
Some loggers are running in different threads, do you I need to do any configuration? How can I debug this?
A: Log4j is thread-safe. See Is log4j thread-safe?. You should not need any special configuration for multi-threading.
However, the messages can appear in a mixed-up order from different threads, so check that they aren't somewhere else in the logs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to get an IP camera stream into C#? I've used AForge library to make this little program, that shows live feed from a webcam into a PictureBox.
private FilterInfoCollection VideoCaptureDevices;
private VideoCaptureDevice FinalVideoDevice;
private void Form1_Load(object sender, EventArgs e)
{
VideoCaptureDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
try
{
foreach (FilterInfo VidCapDev in VideoCaptureDevices)
{
comboBox1.Items.Add(VidCapDev.Name);
comboBox1.SelectedIndex = 0;
}
FinalVideoDevice = new VideoCaptureDevice(VideoCaptureDevices[comboBox1.SelectedIndex].MonikerString);
FinalVideoDevice.NewFrame += new NewFrameEventHandler(FinalVideoDevice_NewFrame);
FinalVideoDevice.Start();
}
catch
{
MessageBox.Show("No camera found. Please connect your camera and click RESET.");
}
}
//////////////////////////////////////////////////////////////////////////////////////////
void FinalVideoDevice_NewFrame(object sender, NewFrameEventArgs e)
{
try
{
pictureBox1.Image = (Bitmap)e.Frame.Clone();
}
catch { }
}
But I also need to get a stream from an IP camera. Any ideas what would be the best way to get it?
A: IP cameras do not have specific media interfaces/APIs in Windows, they are just devices on LAN. Also there are hundreds and thousands of models and they don't share common access interfaces (even close).
So first of all, you have to be specific about the model of your interest.
Also some vendors provide additional "drivers" that expose IP cameras as multimedia devices, such as "DirectShow driver for IP camera". In most cases these are vendor specific and won't work with other cameras.
Next chance is that camera implements a well known streaming protocol, in which case some generic driver might work out fine as well.
Or, as long as you are C# guy, you can check HTTP/CGI API of the IP camera and implement streaming yourself in code, sending and receiving data over HTTP/TCP/UDP connection with the device.
A: I once worked with the directShow.net library. It gives you access to the most functions of DirectShow and one of them is Capturing. If you can use the ip webcam with DirectShow you can use it in your program as well.
A: Same problem was with me like you, and that was my final year project to develop or customize the Ip camera solutions using c#. But i wasted my time a lot on by doing browsing to get any piece of code that written in C# that can easily access the ip camera stream, and i found very soon third party Ozeeki sdk. But this one is the trial and expire near a week and wont work also.Or may be Ozeeki wants just a Backlinks for their site.
First of all you have to limit yourself to select one of the camera. In my case i have a HIkvision Network Camera.
Just download the Device Network SDK for Hikvision Camera from here:
http://www.hikvision.com/en/us/download_more.asp?id=1482
Extract it and you may found in the SDK folder, 4 sub folders.
Inside the "doc" folder, you will find "Device Network SDK Programming Manual"
Open it and expand the "Programming Guideline" tree.
Click on Main Procedure API Reference or Preview Module Procedure. Here you will find all the road Map what steps you have to take to call the functions to get live stream from the camera.
The declaration of all the functions are inside the "Basic Interface Definition" tree expand it and read them all one by one.
The Game is not over here but just got a start;
The SDk with all of the functions are written in C/C++ Unmanaged code base.And cant be added in a Manged C# project solution References. So you have to make a wrapper for all of them that are use in getting a stream from the camera, and call them from c#.Just go through the documentation manual what functions they are.
follow me on twitter :
https://twitter.com/CodingVampire
Wish you Best of Luck
A: Solved it with MJPEGStream from the same AForge.net :)
MJPEGStream stream = new MJPEGStream("http://192.168.2.5:8080/videofeed");
stream.NewFrame += new NewFrameEventHandler(video_NewFrame);
stream.Start();
A: Nager.VideoStream is based on ffmpeg and can therefore easily be used across platforms. Network cameras and webcams can be accessed via ffmpeg.
PM> install-package Nager.VideoStream
var inputSource = new StreamInputSource("rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov");
//var inputSource = new WebcamInputSource("Microsoft® LifeCam HD-3000");
var cancellationTokenSource = new CancellationTokenSource();
var client = new VideoStreamClient();
client.NewImageReceived += NewImageReceived;
var task = client.StartFrameReaderAsync(inputSource, OutputImageFormat.Bmp, cancellationTokenSource.Token);
//Console.ReadLine();
client.NewImageReceived -= NewImageReceived;
private static void NewImageReceived(byte[] imageData)
{
File.WriteAllBytes($@"{DateTime.Now.Ticks}.bmp", imageData);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: What's the best practice to deploy (manage dependency) the django reusable apps in a real production project? In our project we are using some django reusable apps, we are considering how to make the continuous and automatic deployment easy and painless.
We have 2 options:
option#1: use "pip install xxx" to install all dependencies reusable apps. Write a script to install and check the dependencies.
option#2: make a copy of all used reusable apps under our own directory, so we basically will deploy everything in our project directory.
both options have its pros and cons, I am wondering if you can share your the best practice of doing this?
A: You can create a file of dependencies with pip very easily which will mean that the correct versions of each app will be maintained between servers
# Save dependancies to a file
pip freeze > requirement_file.txt
creates a file something like:
django==1.3
django-tagging
markdown
...
which can be later used to reinstall the listed apps on a different server
# Install all dependencies in the file
pip install -r requirement_file.txt
This is a nice and simple approach. You can get more complicated with the likes of zc.buildout
http://pypi.python.org/pypi/zc.buildout
which helps manage packages (python and non-python) via scripts (you create 'recipes' containing the details of the packages you need installed)
If you need broader control over server installs you could use 'puppet' or 'chef'
http://projects.puppetlabs.com/projects/1/wiki/Big_Picture
http://wiki.opscode.com/display/chef/Chef+Server
which are aimed at automating and deploying more than just dependencies, but entire servers
I haven't needed to use more then simple pip requirements files, but the other options are great if you need more.
EDIT
Keeping your own version of the apps in your project root/python path can become cumbersome and difficult to track, I'd suggest using a pip requirement file.
A: I found one in django's website:
https://code.djangoproject.com/wiki/best-practices-to-work-with-3rd-party-apps-and-making-yours-portable
Looks like he is suggesting what I listed in question as option #2.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595194",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Javascript - XMLHttpRequest how to send multiple simultaneous requests? I'm encountering a very paranormal problem. I'm trying to implement a shopping cart, whereby I have cookies stored on the client side to identify which items' ID have been ordered and their quantities. When I load the checkout HTML page, I'm reading the cookies and getting the item id one after the other; then for each item id I ll be sending the request to my servlet which would return the information. I have truncated redundant lines to keep it simple to follow:
var arrXhr = new Array();
function ProcessCheckout(){
try
{
var myArr = new Array();
myArr[0]=84234;
myArr[1]=84239;
myArr[2]=84240;
for (var intLoop=0; intLoop < myArr.length; intLoop++){
var intIcint=myArr[intLoop];
arrXhr[intIcint]= new XMLHttpRequest();
function Populate_CheckOutCart(){
arrXhr[intIcint].open('POST', strRemoteUriReq, true);
arrXhr[intIcint].send(null);
arrXhr[intIcint].onreadystatechange= ProcessSrvRsp(intIcint);
}
}catch(errors)
{
alert(errors.message);
}
}
}
function ProcessSrvRsp(ItemToProcess){
if (arrXhr[ItemToProcess].readyState==4){
//doing some functionality here on item code: ItemToProcess
}
}
The problem here is in line
arrXhr[intIcint].open('POST', strRemoteUriReq, true);
If I change the request type to SYNCHRONOUS communication, i.e. from TRUE to FALSE, everything works correctly, but as you know the web page will have to wait for the server to process every item. Hence, the web page will send a request for item 84234, waits, when there is a response then sends a request for item 84239, etc..
From my knowledge, if I change back ASYNCHRONOUS XMLHttpRequest, nothing happens except/only when arrXhr[ItemToProcess].readyState==1. But as regards the other states, 2,3,4 (4 being the most important to start working with), they are never triggered.
Any idea why? And most importantly how can we overcome this? I'm aware that the XMLHttpRequest works on a separate thread and most probably this is the issue, but I can't figure out a solution.
My objective is simple, I want my web page to send multiple requests to my servlet simultaneously as soon as it is reading from the cookies on the disk; hence for each cookie I want to send a request and expect to receive a response in an asynchronous way. I don't want the browser stuck waiting until the final request has been completed. So, if you have any other idea/implementation, I can be a very open minded person ;)
p.s. I'm using TomCat 7
A: Something like next:
function ProcessCheckout() {
var arrXhr=[];
var myArr=[];
myArr.push(84234);
myArr.push(84239);
myArr.push(84240);
var helperFunc=function(arrIndex,itemId) {
return function() {
if(arrXhr[arrIndex].readyState===4) {
//doing some functionality here on item
ProcessResponseForItem(arrIndex,myArr,arrXhr);
// doing some code if all xhr's is completed
ProcessResponseForAllItems(myArr,arrXhr);
}
}
}
for(var i=0; i<myArr.length; i++) {
var itemId=myArr[i];
arrXhr[i]=new XMLHttpRequest();
arrXhr[i].open('POST', strRemoteUriReq, true);
arrXhr[i].onreadystatechange=helperFunc(i,itemId);
arrXhr[i].send(/*some item data sended to server for item with id itemId*/);
}
}
function ProcessResponseForItem(arrIndex,myArr,arrXhr) {
if(arrXhr[arrIndex].status===200) {
// do some code if response is succ
}
else {
// if fail
}
}
function ProcessResponseForAllItems(myArr,arrXhr) {
var i,isAllComplete=true,isAllCompleteSucc=true;
for(i=0;i<myArr.length;i++) if((!arrXhr[i])||(arrXhr[i].readyState!==4)) {
isAllComplete=false;
break;
}
if(isAllComplete) {
for(i=0;i<myArr.length;i++) if(arrXhr[i].readyState!==200) {
isAllCompleteSucc=false;
break;
}
if(isAllCompleteSucc) {
// do some code when all is completed and all is succ
}
else {
// do some code when all is completed and some is fail
}
}
}
A: I'd strongly suggest using the Event Listeners in case You're willing to use asynchronous processing.
Note that Gecko 30.0 (Firefox 30.0 etc.) deprecated the synchronous requests due to negative impact on user's experience.
This (understand Event Listener) is of course asynchronous and processes the responses as soon as it arrives.
So far the onreadystatechange could bring a lot of complications and headaches. This is especially true when You're handling more than one responses and the order of the response processing matters.
When You want to process the responses as it arrives there is a simple way to add EventListener to each of the requests.
arrXhr[intIcint].open('POST', strRemoteUriReq, true);
arrXhr[intIcint].addEventListener("load", processResponse);
arrXhr[intIcint].send(null);
...
function processResponse() {
console.log("Response arrived.");
}
... You can even customize the state You're going to process. These are the currently allowed states of response:
arrXhr[intIcint].addEventListener("progress", updateProgress);
arrXhr[intIcint].addEventListener("load", transferComplete);
arrXhr[intIcint].addEventListener("error", transferFailed);
arrXhr[intIcint].addEventListener("abort", transferCanceled);
A: You have to use "this" instead arrXhr[intIcint]
var arrXhr = new Array();
function ProcessCheckout(){
try
{
var myArr = new Array();
myArr[0]=84234;
myArr[1]=84239;
myArr[2]=84240;
for (var intLoop=0; intLoop < myArr.length; intLoop++){
var intIcint=myArr[intLoop];
xhr= new XMLHttpRequest();
function Populate_CheckOutCart(){
xhr.open('POST', strRemoteUriReq, true);
xhr.send(null);
xhr.onreadystatechange= ProcessSrvRsp();
// or xhr.addEventListener("load", ProcessSrvRsp);
}
}catch(errors)
{
alert(errors.message);
}
}
}
function ProcessSrvRsp(){
if (this.readyState==4){
//doing some functionality here on item code: this
}
}
A: instead of sending multiple simultanous requests for each product id, wrap all the ids into an array, serialize it and use only one request.
var ids = [1, 2, 3];
var serializedIds = ids.join('|'); // serializedIds = '1|2|3';
send only the serializedIds variable through the request
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Customizing a form using Zend_Form_Decorator How can I customize my form using Zend_Form_Decorator? And how can I add a paragraph inside the form? It is just so difficult to do some simple things using Zend_Form :(
A: While it's not technically the same question, something very similar was asked not long ago: Using ViewScript Decorator on Nested Subforms (Zend Form)
You can get many interesting links in the answers, that can help you to get started with decorators. For instance, if you want to add some markup inside the form, you could render the elements separately (details and links in the above question).
Hope that helps,
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595209",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Update Couchdb document I have a Couchdb document id and revision id and I would like to update the document. How can I achieve this using CouchRest?
I have tried including "_rev" in "put" as suggested somewhere but that doesn't work. This is what I've tried so far:
CouchRest.put('connection/db/docid',{"_rev": "id"},"Name": "XVZ"})
A: I advise you to read this doc : http://guide.couchdb.org/draft/tour.html#first
It might make couchdb clearer!
PS : You must specify id and rev to make it work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: AspectJ pointcut not working with external classes and LTW I am trying to use AspectJ (which until yesterday I didn’t know) with LTW in order to understand how an existing framework works.
In brief, I am interested at how framework's input XML files get parsed.
I have written the following aspect:
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.CodeSignature;
public aspect UnitContextTrace {
static final void println(String s){ System.out.println(s); }
pointcut unitContextMethodsExec(): call(public * org.ivalidator.framework.test.UnitContext.* (..)) ||
call(public void org.ivalidator.repository..*.set* (..));
Object around(): unitContextMethodsExec() {
println("Intercepted message: " +
thisJoinPointStaticPart.getSignature().getName());
println("in class: " +
thisJoinPointStaticPart.getSignature().getDeclaringType().getName());
printParameters(thisJoinPoint);
println("Running original method: \n" );
Object result = proceed();
println(" result: " + result );
return result;
}
static private void printParameters(JoinPoint jp) {
println("Arguments: " );
Object[] args = jp.getArgs();
String[] names = ((CodeSignature)jp.getSignature()).getParameterNames();
Class[] types = ((CodeSignature)jp.getSignature()).getParameterTypes();
for (int i = 0; i < args.length; i++) {
println(" " + i + ". " + names[i] +
" : " + types[i].getName() +
" = " + args[i]);
}
}
}
This should debug both calls to methods of UnitContext interface’s implementations and those to setXXX() methods of any class belonging to org.ivalidator.repository.* package.
I packaged my Aspect in its own jar using
ajc UnitContextTrace.aj -outxml -outjar aspectTrace.jar -extdirs "C:\aspectj1.6\lib\"
and I started the program (I use an ant script) passing -javaagent:${aspectj.home}/lib/aspectjweaver.jar to the JVM.
The first part of the aspect (UnitContext methods) works and I can see for example
Intercepted message: getAdapter…
But unfortunately there are no logs for calls to setXXX() methods. The package org.ivalidator.repository.* is part of ivalidator.jar, which of course uses 3rd parties libraries stored in a lib folder. The structure is something like this:
*
*Ivalidator.jar
*/lib
*
*Castor-0.9.7.jar
*xercesImpl.jar
Using the debugger, I noticed that setXXX() methods are invoked from external classes (belonging to castor-0.9.7.jar, which in turn are invoked by xerces’ classes). To be more precise, the stack trace I can see in the debugger is this:
**ParameterXml.setName(String) line: 60 (I want to intercept this)**
NativeMethodAccessorImpl.invoke0(Method, Object, Object[]) line: not available [native method]
NativeMethodAccessorImpl.invoke(Object, Object[]) line: not available
DelegatingMethodAccessorImpl.invoke(Object, Object[]) line: not available
Method.invoke(Object, Object...) line: not available
FieldHandlerImpl.setValue(Object, Object) line: 501
UnmarshalHandler.processAttribute(String, String, String, XMLFieldDescriptor, XMLClassDescriptor, Object) line: 3028
UnmarshalHandler.processAttributes(AttributeSet, XMLClassDescriptor) line: 2702
UnmarshalHandler.startElement(String, String, AttributeSet) line: 2325
UnmarshalHandler.startElement(String, String, String, Attributes) line: 1388
SAXParser(AbstractSAXParser).startElement(QName, XMLAttributes, Augmentations) line: not available
SAXParser(AbstractXMLDocumentParser).emptyElement(QName, XMLAttributes, Augmentations) line: not available
XMLNSDocumentScannerImpl.scanStartElement() line: not available
XMLNSDocumentScannerImpl$NSContentDispatcher(XMLDocumentFragmentScannerImpl$FragmentContentDispatcher).dispatch(boolean) line: not available
XMLNSDocumentScannerImpl(XMLDocumentFragmentScannerImpl).scanDocument(boolean) line: not available
XML11Configuration.parse(boolean) line: not available
XML11Configuration.parse(XMLInputSource) line: not available
SAXParser(XMLParser).parse(XMLInputSource) line: not available
SAXParser(AbstractSAXParser).parse(InputSource) line: not available
**DescriptorRepositoryXml(XmlObject).fromXml(InputSource) line: 341 (last call within ivalidator.jar)**
I wonder whether calls to external classes (external jars but also i.e. org.xml.sax.xmlreader) may cause the problem?
A: I guess you do not want to intercept call(), but execution(). In that case it does not matter whether your third party classes are woven or not.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to Change Color selected Picked value from pickerview? pickerArray = [[NSArray arrayWithObjects:@"20", @"40", @"60",@"80", @"100", @"120", @"140", @"160", @"180", @"200",nil] retain];
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
//On Selecting the component row
if (component == 0) {
} else if (component == 1) {
[quantityPickerDelegate didChangeLabelText:[pickerArray objectAtIndex:row]];// delegate passing the selected value
pickerLabel.textColor = [UIColor colorWithRed:0.0745 green:0.357 blue:1.0 alpha:1];
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
//Picker view content added
pickerLabel = [[UILabel alloc] init];
pickerLabel.backgroundColor=[UIColor clearColor];
if (component == 0)
{
[pickerLabel setText:@"Total"];
pickerLabel.frame = CGRectMake(0.0, 200,220,44);
pickerLabel.textColor = [UIColor colorWithRed:0.0745 green:0.357 blue:1.0 alpha:1];
}
else
{
pickerLabel = [[UILabel alloc] init];
pickerLabel.backgroundColor=[UIColor clearColor];
pickerLabel.frame = CGRectMake(0.0, 200,70,44);
[pickerLabel setText:[pickerArray objectAtIndex:row]];
pickerLabel.textColor = [UIColor blackColor];
}
[pickerLabel setTextAlignment:UITextAlignmentCenter];
pickerLabel.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:20];
pickerLabel.font = [UIFont boldSystemFontOfSize:20];
//return [pickerLabel autorelease];
return pickerLabel;
}
I am trying to change the selected Picked Value Color from UIPickerView
I am trying to change it but its not effected perfectly its changing other values below the selected value.
A: This is incorrect. You should reload the selected component. Then you need to fetch the selected row and update its color in viewForRow:forComponent:. Something like-
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
//On Selecting the component row
if (component == 0) {
} else if (component == 1) {
[quantityPickerDelegate didChangeLabelText:[pickerArray objectAtIndex:row]];// delegate passing the selected value
[pickerView reloadComponent:component]; //This will cause your viewForComp to hit
}
}
- (UIView *)viewForRow:(NSInteger)row forComponent:(NSInteger)component
{
//...
//Your usual code
pickerLabel.textColor = defaultColor;
if([self.pickerView selectedRowInComponent:component] == row) //this is the selected one, change its color
{
pickerLabel.textColor = [UIColor colorWithRed:0.0745 green:0.357 blue:1.0 alpha:1];
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Facebook Authentication Finished Open Another App Using Facebook authentication, the procedures are that Facebook library will open either Safari/installed Facebook app for executing the authentication and then return back to the app.
I have built multiple apps (Let's say : First App, SecondApp and ThirdApp) and compiled them to my devices. When I tried to authenticating Facebook account, what was happening is that when I finished authenticating Facebook on FirstApp, instead of re-open the same app, it opened SecondApp (sometime ThirdApp).
My hunch is it has something to do with App ID, but I am not sure.
What do you think?
Thanks in advance.
A: Your URI scheme is messed up. Also make sure that you have 3 separate apps on Facebook so there will be 3 different URI schemes one for each app.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: select onclick that contains _blank i select links with a blank target to set a title attribute
jQuery('a[target~="_blank"]').attr('title', 'New window');
that works.
But when i select the onclick attribute that doesn't work
jQuery('a[onclick~="_blank"]').attr('title', 'New window');
any clues?
the link looks like that:
<a onclick="javascript:this.target="_blank"" title="" href="http://link.com">link</a>
A: Use below code :
jQuery('a[onclick*="_blank"]').attr('title', 'New window');
A: This seems to work for me using the Attribute Contains Selector -
$("a[onclick*='_blank']")
Could you use that instead?
Demo - http://jsfiddle.net/uZaCW/
A: found that contains is * and not ~
jQuery("a[onclick*='_blank']").attr('alt', 'New window');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Open cart site transferred to another host with images broken I have transferred the Open Cart site over to another domain but all the images are broken adn I cannot get into admin. Is there a reason why?
I have changed the config database credentials.
A: In addition to changing the database credentials, you have to change the directory paths in both config.php and admin/config.php.
Old server
define('DIR_APPLICATION', '/home/oldhost/sites/example.com/html/catalog/');
New server
define('DIR_APPLICATION', '/home/newhost/sites/example.com/public_html/catalog/');
A: I know it is old but there may be some other guys out there who run into this same problem nowadays too and are stuck with it or can't figure out what the problem is. After migrating your shop, you will receive broken image errors and/or not displaying images (even after you have set everything correctly in the config files and changed the file/folder permissions) because the paths in the database are probably incorrect. You need to update the links in your database based on your new FTP file structure. 'product_images' table for the images and 'product' table for miniatures. You can do it manually from the admin panel by actually opening all products and adding the photos again (This is rather ridiculous) or they may have a module to do the job. I honestly did not find anything - not even a proper answer on the official forum of the provider in question to what the problem was so I created a simple JAVA application that updates the image paths (leaving the file names "untouched") in the database based on the FTP file structure. You can download it by clicking the following MEGA link. Before doing anything, please make sure you have a back-up of everything (database and files). Link: https://mega.nz/#!8cF1DawQ!C_pzuJJvxOBkPa8Koss_yfMxlF59l_8c0OewghoAzuA
Hope it is helpful!
Regards
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: include from output buffer? I have a dynamically generated page with some BBcode on.
For example I have one named [PHP]file.php[/PHP]..
The output is buffered using ob_start("parser);. Is it possible to replace [PHP]file.php[/PHP] with include("file.php"); on the output buffer?
<?php
function parser($buffer){
//This is where I want 'it to happen'
}
ob_start("parser");
?>
<html>
..........
<body>
Some text<br /><br />
[PHP]file1.php[/PHP]<br /><br />
More text..<br /><br />
[PHP]file2.php[/PHP]
<?php
ob_end_flush();
?>
A: Sure; replacing it with a call to include() will execute file.php and add the output to the buffer. Make sure to do some checks on the filename before including it, to prevent remote script injection etc!!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery: changing the available options in a list based on the selected option <select id="studentinst" size="6">
<option value="1">First Installment</option>
<option value="2">Second Installment</option>
<option value="3">Third Installment</option>
<option value="4">Fourth Installment</option>
<option value="5">Fifth Installment</option>
<option value="6">Sixth Installment</option>
</select>
If I select 4, it should only display the first 4 options and the rest should be hidden.
Desired output:
First Installment
Second Installment
Third Installment
Fourth Installment
How can I achieve this using jQuery?
see sample link check this link... for loop doesn't work over here
A: $('#studentinst').change(function() {
if ($('option:selected').val() == 4) {
$("#studentinst option[value=5]").remove();
$("#studentinst option[value=6]").remove();
}
else {
if ($('#studentinst option[value=5]').val() == null)
$('<option>').text('Fifth Installment').val(5).appendTo($('#studentinst'));
if ($('#studentinst option[value=6]').val() == null) $('<option>').text('Sixth Installment').val(6).appendTo($('#studentinst'));
}
});
If hide doesn't work as expected, this is another way to do it.
see sample
A: Something like this should work, there may be a shorter way to do it?
$(document).ready(function(){
$('#studentinst').change(function(){
var selectedIndex = $('#studentinst :selected').index();
$('#studentinst option').each(function(){
if($(this).index() > selectedIndex){
$(this).hide(); //or you can use .remove();
}
});
});
});
This method is based on the options index but you could use .val() instead if .index() if you are basing the removal on the values
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do i get the input content that follows the rake command all.
How do i get the content that follows the rake command ,
for example, when i type this command in terminal # rake make_file myfile so that it will creates a file named myfile.txt, how do i write this rake task ?
Thanks in advance.
A: rake task_name some_param will actually try to fire two rake tasks: task_name and some_param unless the parameters are in the format of param=value, in which case the parameter is populated in the ENV constant.
So, rake task_name myfile=/some/file can be read from ENV["myfile"].
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595242",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Specialize template for any vector I have got a template method with two specialized versions for type bool and vector<string>.
Base version:
template <class T>
const T InternGetValue(const std::string& pfad) const
{
...
}
Specialized versions:
template <>
const bool InternGetValue(const std::string& pfad) const
{
...
}
template <>
const std::vector<std::string> InternGetValue< std::vector<std::string>>(const std::string& pfad) const
{
...
}
Now I would like to implement one specialization that will accept all types of vector<aritmethic_data_type> like vector<double> vector<int> or vector<float>.
I could achieve this by writing overloads for the above types, but I'm interested in reaching my goal with another specialization.
This is what I tried so far (leads to error 'illegal use of explicit template arguments'):
template <class T>
const std::vector<T> InternGetValue< std::vector<T>>(const std::string& pfad, typename boost::enable_if<boost::is_arithmetic<T>>::type* dummy = 0) const
{
}
A: I think std::enable_if and std::is_integral together can solve this problem:
template<typename T>
std::vector<typename std::enable_if<std::is_integral<T>::value, T>::type>
f(const std::string& d);
If std:: doesn't have them, then use boost:: if you can. It has them.
A: OK uber complicated, but I got it all working. I couldn't just check is_integral on the value_type type inside the first (default) function overload as this would cause SFINAE to remove the overload for non-vectors.
Unlike Nawaz's solution, this doesn't require a dummy parameter to be added, but it does require an enable_if condition on the default function template.
This works on VS2010.
#include <vector>
#include <string>
#include <type_traits>
using namespace std;
template <typename T> struct is_vector { static const bool value = false; };
template <typename T> struct is_vector< std::vector<T> > { static const bool value = true; };
// metafunction to extract what type a vector is specialised on
// vector_type<vector<T>>::type == T
template <class T>
struct vector_type
{
private:
template <class T>
struct ident
{
typedef T type;
};
template <class C>
static ident<C> test(vector<C>);
static ident<void> test(...);
typedef decltype(test(T())) vec_type;
public:
typedef typename vec_type::type type;
};
// default version
template <class T>
const typename enable_if<!is_vector<T>::value || !is_integral<typename vector_type<T>::type>::value, T>::type
InternGetValue(const std::string& pfad)
{
return T();
}
// bool specialisation
template <>
const bool
InternGetValue<bool>(const std::string& pfad)
{
return true;
}
// vector<string> specialisation
template <>
const vector<string>
InternGetValue<vector<string>>(const std::string& pfad)
{
return vector<string>();
}
// vector<T> specialisation (where T is integral)
template <class T>
const typename enable_if<is_vector<T>::value && is_integral<typename vector_type<T>::type>::value, T>::type
InternGetValue(const std::string& pfad)
{
return T();
}
int main()
{
string x;
auto a = InternGetValue<int>(x);
auto b = InternGetValue<bool>(x);
auto c = InternGetValue<vector<string>>(x);
auto d = InternGetValue<vector<pair<int, int>>>(x);
auto e = InternGetValue<vector<int>>(x);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Testing toolkit I've been assigned the job of testing a small Windows application for the company I work for. I'm a little experienced with testing web applications using the Google Chrome Developer Tools. Apart from that, I don't know much.
For the moment, I manual test keeping an eye on the Windows Task Manager for memory and CPU usage.
What other basic tools should I be using to do manual (as opposed to unit testing) Windows application testing?
A: There're a number of tools that can be handy:
*
*Debugger: either built-in in the IDE (Visual C++ or whatever) or WinDbg
*Application verifier:
http://msdn.microsoft.com/en-us/library/ms220948%28v=VS.90%29.aspx
*SysInternals tools:
http://technet.microsoft.com/en-us/sysinternals/bb545021
Process Explorer from SysInternals is much more useful that the task manager.
Off top of my head, here are a few things that you can do without modifying the code or writing test code:
*
*see if there're memory leaks or corruptions (use Application Verifier + WinDbg)
*inject failures (that is, at some point modify a status/error code/pointer/some other variable in the debugger as if a piece of code failed to open a file or allocate memory or do something else) and see if the app gracefully handles that
Play with SysInternals tools.
Also, it may be a good idea to buy this book to familiarize yourself with Windows: http://www.amazon.com/Windows%C2%AE-Internals-Including-Windows-Developer/dp/0735625301/
There're also a few good ones on debugging Windows applications, like this one: http://www.amazon.com/Advanced-Windows-Debugging-Mario-Hewardt/dp/0321374460/
Among the other things it explains how to automatically collect crash dumps from your applications (using Windows Error Reporting AKA WER) and then inspect them in the debugger. I found that useful.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Array increment types in C - array[i]++ vs array[i++] What is the difference between array[i]++ and array[i++], where the array is an int array[10]?
A: array[i]++ means ( *(array+i) )++. --> Increments the Value.
array[i++] means *( array + (i++) ). --> Increments the Index.
A: int a[] = {1, 2, 3, 4, 5};
int i = 1; // Second index number of the array a[]
a[i]++;
printf("%d %d\n", i, a[i]);
a[i++];
printf("%d %d\n", i, a[i]);
Output
1 3
2 3
a[i]++ increments the element at index i, it doesn't increment i. And a[i++] increments i, not the element at index i.
A: *
*array[i]++ increments the value of array[i]. The expression evaluates to array[i] before it has been incremented.
*array[i++] increments the value of i. The expression evaluates to array[i], before i has been incremented.
An illustration.
Suppose that array contains three integers, 0, 1, 2, and that i is equal to 1.
*
*array[i]++ changes array[1] to 2, evaluates to 1 and leaves i equal to 1.
*array[i++] does not modify array, evaluates to 1 and changes i to 2.
A suffix operators, which you are using here, evaluates to the value of the expression before it is incremented.
A: Here the Array[i]++ increments the value of the element array[i],
but array[i++] increments the i value which effects or changes the indication of the array element (i.e. it indicates the next element of an array after array[i]).
A: Let's say we have this example, array[i++] = x[m++]. This means that first set array[i] = x[m] then increase the indexes like i + 1, m + 1.
A: I believe it's also worth mentioning that array[++i] increments before the evaluation, and as has been mentioned earlier array[i++] increments the i (or index) value after the evaluation.
Example:
array[++i]; = i++; array[i];
array[i++]; = array[i]; i++;
A: Here array[i++] increments the index number.
On the contrary, array[i]++ increments the data value of i index.
Code Snippet:
#include <iostream>
using namespace std;
int main()
{
int array[] = {5, 2, 9, 7, 15};
int i = 0;
array[i]++;
printf("%d %d\n", i, array[i]);
array[i]++;
printf("%d %d\n", i, array[i]);
array[i++];
printf("%d %d\n", i, array[i]);
array[i++];
printf("%d %d\n", i, array[i]);
return 0;
}
A: #include<iostream>
using namespace std;
int main()
{
int arr[]={1,2,37,40,5,7};
int i = 3;
arr[i]++;
cout<<i<<" "<<arr[i]<<endl;
arr[i++];
cout<<i<<" "<<arr[i]<<endl;
return 0;
}
output:
3 41
4 5
In this example i = 3 so,arr[3]= 40 and then it increases the value 40 to 41.So arr[i]++ increments the value of this particular index and a[i++] first
increment the index and then gives the values of this index.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: Keep RPM from changing directory permissions is it possible to keep RPM from changing the permissions of a directory when an update is done. I.e. we have some directories that are needed for the application to work correctly. However the user might also add some more features using other applications and for this needs to change the permissions on these directories after the installation. However if our Application is then updated, it changes the permissions on these directories back to the ones they have after installation.
Is there any way to change the spec file, so that these permissions will be kept after an update? Currently we are following the route, that we excluded these directories from the rpm, so they do not get changed (but also will not be created when a new installation is done). Is there any better way to handle this?
Also in one case the directories in questions are later replaced by symlinks to other directories. The change in permission on the symlinks then propagates to the real directories. Would this need a different setup than the one above, or would the same solution still work?
A: Create the directories only during installation. Skip it during upgrade. RPM sets $1 to 1 during installation and $1 to 2 during upgrade.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JavaScript Tabs - 2 Instances On One Page I'm using this JavaScript tabbed script:
http://net.tutsplus.com/tutorials/html-css-techniques/how-to-create-a-slick-tabbed-content-area/comment-page-2/#comments
I have it working 100% if I'm using 1 set of tabs on a page, but I want to add a second set.(It's possible with this script, as per the "A More Complex Script" section in the tutorial.)
When I add a second set, the top tabs work ok, however the bottom set don't work when I click on them and in fact they change the top tabs.
Here's a link to what happens: http://www.europefiles.com/
any help appreciated.
thanks
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head><title>Tabbed Structure - Regular</title>
<script language="javascript" type="text/javascript">
function tabSwitch(new_tab, new_content) {
document.getElementById('content_1').style.display = 'none';
document.getElementById('content_2').style.display = 'none';
document.getElementById('content_3').style.display = 'none';
document.getElementById(new_content).style.display = 'block';
document.getElementById('tab_1').className = '';
document.getElementById('tab_2').className = '';
document.getElementById('tab_3').className = '';
document.getElementById(new_tab).className = 'active';
}
function tabSwitch_2(active, number, tab_prefix, content_prefix) {
for (var i=1; i < number+1; i++) {
document.getElementById(content_prefix+i).style.display = 'none';
document.getElementById(tab_prefix+i).className = '';
}
document.getElementById(content_prefix+active).style.display = 'block';
document.getElementById(tab_prefix+active).className = 'active';
}
</script>
<style type="text/css">
#wrapper {position: relative;margin: 0 auto;width: 980px;height: 800px;}
#top {width: 980px;height: 400px;padding:0;margin:0px;color: #333;background: #fff;padding:0;}
#bottom {width: 980px;height: 400px;float:left;padding:0;margin:0;color:#333;background: #fff;padding:0;}
#tabbed_box {margin: 0px auto 0px auto; width:300px;}
.tabbed_box h4 {font-family:Arial, Helvetica, sans-serif;font-size:23px;color:#ffffff;letter-spacing:-1px;margin-bottom:10px;}
.tabbed_box h4 small {color:#e3e9ec;font-weight:normal;font-size:9px;font-family:Verdana, Arial, Helvetica, sans-serif;text-transform:uppercase;position:relative;top:-4px;left:6px;letter-spacing:0px;}
.tabbed_area {border:1px solid #494e52;background-color:#636d76;padding:8px;}
ul.tabs {margin:0px; padding:0px;}
ul.tabs li {list-style:none;display:inline;}
ul.tabs li a {background-color:#464c54;color:#ffebb5;padding:8px 14px 8px 14px;text-decoration:none; font-size:9px;font-family:Verdana, Arial, Helvetica, sans-serif;font-weight:bold;text-transform:uppercase;border:1px solid #464c54;}
ul.tabs li a:hover {background-color:#2f343a;border-color:#2f343a;}
ul.tabs li a.active {background-color:#ffffff;color:#282e32;border:1px solid #464c54;border-bottom: 1px solid #ffffff;}
.content {background-color:#ffffff;padding:10px;border:1px solid #464c54;}
#content_2, #content_3 { display:none; }
ul.tabs {margin:0px; padding:0px;margin-top:5px;margin-bottom:6px;}
.content ul {margin:0px;padding:0px 20px 0px 20px;}
.content ul li {list-style:none;border-bottom:1px solid #d6dde0;padding-top:15px;padding-bottom:15px; font-size:13px;}
.content ul li a {text-decoration:none;color:#3e4346;}
.content ul li a small {color:#8b959c;font-size:9px;text-transform:uppercase;font-family:Verdana, Arial, Helvetica, sans-serif;position:relative;left:4px;top:0px;}
.content ul li:last-child {border-bottom:none;}
ul.tabs li a {background-image:url(images/tab_off.jpg);background-repeat:repeat-x;background-position:bottom;}
ul.tabs li a.active {background-image:url(images/tab_on.jpg); background-repeat:repeat-x;background-position:top;}
.content {background-image:url(images/content_bottom.jpg);background-repeat:repeat-x;background-position:bottom;}
</style>
</head>
<body>
<div id="wrapper">
<div id="top">
<div id="tabbed_box_1" class="tabbed_box">
<div class="tabbed_area">
<ul class="tabs">
<li><a href="javascript:tabSwitch_2(1, 3, 'tab_', 'content_');" id="tab_1" class="active">Topics</a></li>
<li><a href="javascript:tabSwitch_2(2, 3, 'tab_', 'content_');" id="tab_2">Archives</a></li>
<li><a href="javascript:tabSwitch_2(3, 3, 'tab_', 'content_');" id="tab_3">Pages</a></li>
</ul>
<div id="content_1" class="content">
<ul>
<li><a href="">HTML Techniques <small>4 Posts</small></a></li>
<li><a href="">CSS Styling <small>32 Posts</small></a></li>
<li><a href="">Flash Tutorials <small>2 Posts</small></a></li>
<li><a href="">Web Miscellanea <small>19 Posts</small></a></li>
<li><a href="">Site News <small>6 Posts</small></a></li>
<li><a href="">Web Development <small>8 Posts</small></a></li>
</ul>
</div>
<div id="content_2" class="content">
<ul>
<li><a href="">December 2008 <small>6 Posts</small></a></li>
<li><a href="">November 2008 <small>4 Posts</small></a></li>
<li><a href="">October 2008 <small>22 Posts</small></a></li>
<li><a href="">September 2008 <small>12 Posts</small></a></li>
<li><a href="">August 2008 <small>3 Posts</small></a></li>
<li><a href="">July 2008 <small>1 Posts</small></a></li>
</ul>
</div>
<div id="content_3" class="content">
<ul>
<li><a href="">Home</a></li>
<li><a href="">About</a></li>
<li><a href="">Contribute</a></li>
<li><a href="">Contact</a></li>
</ul>
</div>
</div>
</div>
</div>
<div id="bottom">
<div id="tabbed_box_1" class="tabbed_box">
<div class="tabbed_area">
<ul class="tabs">
<li><a href="javascript:tabSwitch_2(1, 3, 'tab_', 'content_');" id="tab_1" class="active">Topics</a></li>
<li><a href="javascript:tabSwitch_2(2, 3, 'tab_', 'content_');" id="tab_2">Archives</a></li>
<li><a href="javascript:tabSwitch_2(3, 3, 'tab_', 'content_');" id="tab_3">Pages</a></li>
</ul>
<div id="content_1" class="content">
<ul>
<li><a href="">HTML Techniques <small>4 Posts</small></a></li>
<li><a href="">CSS Styling <small>32 Posts</small></a></li>
<li><a href="">Flash Tutorials <small>2 Posts</small></a></li>
<li><a href="">Web Miscellanea <small>19 Posts</small></a></li>
<li><a href="">Site News <small>6 Posts</small></a></li>
<li><a href="">Web Development <small>8 Posts</small></a></li>
</ul>
</div>
<div id="content_2" class="content">
<ul>
<li><a href="">December 2008 <small>6 Posts</small></a></li>
<li><a href="">November 2008 <small>4 Posts</small></a></li>
<li><a href="">October 2008 <small>22 Posts</small></a></li>
<li><a href="">September 2008 <small>12 Posts</small></a></li>
<li><a href="">August 2008 <small>3 Posts</small></a></li>
<li><a href="">July 2008 <small>1 Posts</small></a></li>
</ul>
</div>
<div id="content_3" class="content">
<ul>
<li><a href="">Home</a></li>
<li><a href="">About</a></li>
<li><a href="">Contribute</a></li>
<li><a href="">Contact</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
A: I'm not sleeping too well so where I am. Not my most elegant work, but here's your script with some jquery to help do what I think it is you are wanting to do:
http://jsfiddle.net/XPWxw/
** jquery addition **
$(document).ready(function() {
$(".tabs a").click(function() {
$(this).addClass("active").parent().siblings().find("a.active").removeClass("active");
var id = $(this).parent().parent().find("a").index(this);
$(this).parent().parent().parent().find(".content").css({
display: "none"
}).eq(id).css({
display: "block"
});
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Array Reduce PHP I have an :
$arr = array(321,0.4,0.8,1.2);
$result = array_reduce($arr,create_function('$op1,$op2','return $op1-=$op2;'));
echo $result; //the result should be 318.6, but i got -323.4
would you please tell me what's wrong with this?
A: The array_reduce function has 3 parameters. The 3rd is $initial.
This is by default NULL. You should fill this one too. Look here: http://nl.php.net/array_reduce
If the optional initial is available, it will be used at the
beginning of the process, or as a final result in case the array is
empty.
A: Just substract the sum of all elements but the first from the first element:
echo array_shift($arr) - array_sum($arr); # 318.6
A: Try...
array_reduce($arr,
create_function('$op1,$op2','print "$op1, $op2\n";
return $op1-=$op2;'));
and all should become clear.
A: You are using the array_reduce in the wrong way. The first item in the array needs to be shifted out of the array and used as the initial value.
$arr = array(321,0.4,0.8,1.2);
$initial = array_shift($arr);
$result = array_reduce($arr, create_function('$op1,$op2','return $op1-=$op2;'), $initial);
echo $result;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cancel multiple SharePoint Workflows using PowerShell How is it possible to cancel all running workflows in a SharePoint (2010) List?
I found this script via technet.
http://social.technet.microsoft.com/Forums/en-US/sharepoint2010programming/thread/d3913265-9712-4e61-9e38-1f9b78c8f718/
CODE:
using (SPSite oSite = new SPSite("<your url>"))
{
foreach (SPWeb oWeb in oSite.AllWebs)
{
oWeb.AllowUnsafeUpdates = true;
// stop list workflows
foreach (SPList list in oWeb.Lists)
{
foreach (SPListItem oItem in list.Items)
{
foreach (SPWorkflow workflow in oItem.Workflows)
{
SPWorkflowManager.CancelWorkflow(workflow);
}
}
}
// stop site workflows
foreach (SPWorkflow workflow in oWeb.Workflows)
{
SPWorkflowManager.CancelWorkflow(workflow);
}
oWeb.AllowUnsafeUpdates = false;
oWeb.Dispose();
}
}
Many thanks for your help.
A: This script has been wickedly useful to me. I make a modification to allow me to cancel all the workflows in one list or just one workflow and thought I would post it here too:
#Parameters
param($listToCancel,$WfToCancel)
#Site URL
$web = Get-SPWeb "http://mydomain.com";
$web.AllowUnsafeUpdates = $true;
#List Name
$list = $web.Lists[$listToCancel];
#Add wildcards to Wf variable
$WildcardWfToCancel = "*"+$WfToCancel+"*";
# Iterate through all Items in List and all Workflows on Items.
foreach ($item in $list.Items) {
foreach ($wf in $item.Workflows) {
#Test for workflow complete and match criteria
if (($wf.ParentAssociation.InternalName -like $WildcardWfToCancel) -and ($wf.IsCompleted -ne $true)) {
#Show status and cancel Workflows
write-Host $wf.ItemName -nonewline;
write-host " " -nonewline;
write-host $wf.ParentAssociation.InternalName;
Write-Host " Status " -nonewline;
Write-host $wf.InternalState;
[Microsoft.SharePoint.Workflow.SPWorkflowManager]::CancelWorkflow($wf);
}
}
}
$web.Dispose();
A: Give this one a shot.
I modified it so that it is done on a specific list on a specific web.
#Site URL
$web = Get-SPWeb "http://urlforsite.com";
$web.AllowUnsafeUpdates = $true;
#List Name
$list = $web.Lists["ListName"];
# Iterate through all Items in List and all Workflows on Items.
foreach ($item in $list.Items) {
foreach ($wf in $item.Workflows) {
#Cancel Workflows
[Microsoft.SharePoint.Workflow.SPWorkflowManager]::CancelWorkflow($wf);
}
}
$web.Dispose();
Worked just fine for me. Let me know if it works for you.
A: Try this (simple "translation" of C# to powershell):
$site = Get-SPSite "<your url>";
$site.AllWebs | foreach {
$web = $_;
$web.AllowUnsafeUpdates = $true;
# stop list workflows
$web.Lists | foreach {
$list = $_;
$list.Items | foreach {
$item = $_;
$item.Workflows | foreach {
$wf = $_;
[Microsoft.SharePoint.Workflow.SPWorkflowManager]::CancelWorkflow($wf);
}
}
}
# stop site workflows
$web.Workflows | foreach {
$wf = $_;
[Microsoft.SharePoint.Workflow.SPWorkflowManager]::CancelWorkflow($wf);
}
$web.AllowUnsafeUpdates = $false;
$web.Dispose();
}
$site.Dispose();
A: here is my modified script:
$web = Get-SPWeb "http://site/subsite";
$web.allowUnsafeUpdates = 'true';
# stop list workflows
$web.Lists | foreach {
$list = $_;
$list.Items | foreach {
$item = $_;
$item.Workflows | foreach {
$wf = $_;
[Microsoft.SharePoint.Workflow.SPWorkflowManager]::CancelWorkflow($wf);
}
}
}
$web.allowUnsafeUpdates = 'false';
$web.Dispose();
an this is the error i get (i am using a german localized version of the server and sharepoint):
Fehler bei der Enumeration einer Auflistung: Collection was modified; enumeration operation may not execute..
Bei C:\stopwf.ps1:7 Zeichen:3
+ <<<< $web.Lists | foreach {
+ CategoryInfo : InvalidOperation: (Microsoft.Share...on+SPEnumerator:SPEnumerator) [], RuntimeException
+ FullyQualifiedErrorId : BadEnumeration
the user runnig the script is admin on the machine it self, sitecollection admin and sql-admin. i also created the subsite with this account, so i don't think that useracces would be the problem.
I found this answer (Differences Between PowerShell and C# when Enumerating a Collection) but i don't get a clue how to use this information for me?!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: In context of WAS, what is the difference between application bounce and jvm bounce In context of WAS, what is the difference between application bounce and jvm bounce.
In case we only want to reload the data at server startup , whch one should we go for.
A: The same application can be restarted multiple times while a server is running. If you only want to load data once per server start, then I would recommend placing a class in a shared library associated with a server class loader. This will make it accessible to all applications, and the static variables will retain their contents until the server is restarted. Of course, this also means you cannot update these classes without restarting the server.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: RESTful Rails controller ans net/http as client - slow on many requests I have an Array populated with potentially lots of records. Every records shall be saved by the server in a RESTful RecordsController. My Solution in the moment looks like this:
def self.send! options = nil
records = fetch_records
records.each do |r|
send_data!(r) ? records = records.delete_if{|rec| rec == r } : break
end
storage.save! records
true
end
private
def self.send_data! record, options = nil
begin
response = Net::HTTP.Proxy(configuration.proxy_host, configuration.proxy_port).start(configuration.host, configuration.port) do |http|
request = Net::HTTP::Post.new(request_path options)
request.body = record.to_json
http.request request
end
raise StandardError unless response.code == "200"
rescue Exception => e
return false
end
true
end
The advantage of that solution is, that if a ConnectionError, ConnectionTimeout or ServerError occurs, the unsent records get stored locally and can be submitted again later. The matching controller is a standard Rails controller.
My Problem now is, that in production mode this seems very slow. It's about 4 requests/s where there the server is not the bottleneck.
The question now is, wether it could help to instantiate the HTTP client only once and send all the records using the same connection. I did not find a solution to implement that, cause I need the save_or_store behavior of the code up here.
Another solution could be not to transfer the records done after another but group them and create a new controller that accepts groups of my records to store them.
So this questions boils down to a more architectural one than a technical. Either way I wonder if I can keep a HTTP connection open and speed up my solution that way.
Any ideas?
Regards
Felix
A: Switch to em-http-request - an EventMachine-based HTTP client - and use its Multi interface to send several request at the same time could raise your throughput a bit.
But the benefit of a better HTTP client is negligible. Since you don't do anything with the HTTP response you get from your controller -- which means you're not using HTTP as an application protocol - the best solution for your problem is to actually send the whole Array for processing on the server side. After all, you don't have to pay the price of making a single request for every single record.
Eventually, if you so desire, it would be nice to expose a URI with the list of records that failed to process, so you could re-submit then or just ignore, at your will.
And I would throw MessagePack in the mix, to serialize the Array and reduce the size of the payload and speed the message exchange.
A: If i am reading the send! method correctly, you are looping through each record, and inside that loop just removing the current record from the array and sending everything else? To save a bit of effort on the computing side, use the delete() method of the Array class instead of the delete_if.
def self.send! options = nil
records = fetch_records
records.each do |r|
if send_data!(r)
records.delete(r)
else
break
end
end
storage.save! records
true
end
Though i'm not sure where you're passing the record parameter for the send_data! method. Since the terinary would be using the result from that method.
Net http can take some time to run through all its requests. I know when i've ran a few hundred URLs to check their response codes it's taken anywhere between 5-10 minutes to complete. I haven't used it much myself, but take a look at: https://github.com/jnunemaker/httparty. Maybe it will work better for you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: pUnkOuter parameter of IClassFactory::CreateInstance method What's the reason behind the pUnkOuter parameter of IClassFactory::CreateInstance method?
HRESULT CreateInstance(
[in] IUnknown *pUnkOuter,
[in] REFIID riid,
[out] void **ppvObject
);
The MSDN's description of pUnkOuter parameter notes:
If the object is being created as part of an aggregate, specify a pointer to the controlling IUnknown interface of the aggregate. Otherwise, this parameter must be NULL.
Can you good people please enlighten me on what is this parameter for?
A: See Aggregation in COM fundamentals. If you create an instance of COM object which is a part of an aggregate, you have to supply so called "outer IUnknown", which is owner COM object interface.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: is view spec necessary with cucumber Is it necessary to use view spec even if I am using cucumber?
I think cucumber takes care of the view and the flow.So is it required to use view spec?
A little explanation is appreciated..Thanks
A: I prefer to test everything in isolation. So I test the models, the controllers, the helpers and the views with rspec. With isolation I mean that in the controller I tend to stub out all activerecord and model methods.
With my model-, controller- and viewtests I tend to aim for complete coverage. Views is a bit harder. I like the view-tests if i want to make sure some fields are definitely shown, or some status is represented correctly. But view-tests could be very detailed, they could even test if certain elements have the correct classes. It depends on the situation or the view itself how much I really test.
I use cucumber tests to then tie everything together. Cucumber is my integration test: no stubbing there. I also use cucumber to verify my javascript in the view.
So, to answer your question: I do no think that view-testing and cucumber overlap. I use my view-tests to check that certain fields are rendered correctly. Something I do not in the same depth in cucumber. I use cucumber to go through the complete stack (integration), and to test the flow.
Hope this helps.
A: In my opinion, no. I keep the view as simple as I can by extracting any complexity into view helpers, which I test separately.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Parallelization of a quadratic algorithm Let's say I have a vector (array, list, whatever...) V of N elements, let's say V0 to V(N-1). For each element Vi, a function f(Vi,Vj) needs to be computed for every index j (including the case i=j). The function is symmetric so that once f(Vi, Vj) is computed, there is no need to recompute f(Vj,Vi). Then we have N(N+1)/2 total evaluations of the function, making this a O(N2) algorithm. Let's assume the time it takes to compute f is relatively long but consistent.
Now, I want to parallelize the execution of the algorithm. I need to determine a schedule for (some number M of) worker threads so that two threads do not use the same part of memory (i.e. the same element) at the same time. For example, f(V1,V2) could be evaluated parallel to f(V3,V4), but not parallel to f(V2,V3). The workflow is divided into steps such that for each step, every worker thread performs one evaluation of f. The threads are then synchronized, after which they proceed to the next step and so on.
The question is, how do I determine (preferably optimally) the schedule for each thread as a series of index pairs (i,j) so that the complete problem is solved (i.e. each index pair visited exactly once, considering the symmetry)? While a direct answer would of course be nice, I'd also appreciate a pointer to an algorithm or even to relevant websites/literature.
A: This reminds me of a common sports scheduling problem: In a league with N teams, arrange N-1 gamedays, so that every team has one game per day and plays every other team once.
Playing chess, there is a quite illustrative solution to this problem. Arrange all boards side by side on a long table. One player always remains at the same chair. The other players rotate around the table in the same direction skipping that player.
A: Let's see direct implementation:
for(i=0; i < N; ++i)
{
for(j=1; j < i; ++J)
{
compute i,j pair and assign to i,j, and j,i result
}
}
I am C++ programmer, so I can think about external loop parallelization, let's say, with OpenMP:
#pragma OMP parallel for
for(i=0; i < N; ++i)
{
....
}
If you don't know OpenMP, it just divides the loop into n loops, according to number of processors, and executes them in parallel. I don't think that in this case result will be good, because every i+1 loop is shorter than i loop. Let's write this algorithm by such way, that all loops have the same length. Total number of loops will be N/2. First loop handles 0 and N-1 lines. Second loop handles 1 and N-2 lines etc. Such loop may be parallelized successfully, without conflicts. Simplified code, without details about even/odd N etc.:
#pragma OMP parallel for
for(i=0; i < N/2; ++i)
{
Handle i value
...
Handle N - 1 - i value
...
}
This is just general idea, there are incorrect details that you can fix.
A: I see two possibilities.
One is to divide the K = N(N+1)/2 tasks among the M threads apriori. The following is just pseudo-code:
allocateTasks() {
num = ceil(N*(N+1)/2/M); // number of tasks per thread
i0 = 0, j0 = 0;
n = 0;
for (i = 0; i < N; ++i) {
for (j = i; j < N; ++j) { // skip symmetries
if (n == 0) {i0 = i; j0 = j;}
++n;
if (n == num) {
thread(i0, j0, num);
n = 0;
}
}
}
if (n > 0) thread(i0, j0, n);
}
thread(i0, j0, num) {
// perform num tasks starting at (i0, j0)
i = i0; j = j0;
for (n = 0; n < num; ++n) {
// f[i, j] = ...
++j;
if (j >= N) {++i; j = i;}
}
}
The problem here is that when the computation of f(i, j) does not take the same time,
then the load is not balanced among the threads.
So, perhaps the second approach is better. Each thread takes the next available
task. There is no global pre-allocation of tasks.
// init boolean array: done[0..N-1, 0..N-1] = false
thread() {
for (i = 0; i < N; ++i) {
for (j = i; j < N; ++j) { // skip symmetries
boolean mytask = false;
lock(mutex); // synchronize access to global array done[][]
if (!done[i, j]) {
done[i, j] = true;
mytask = true;
}
unlock(mutex);
if (mytask) {
f(i, j) = ...
}
}
}
}
In any case the access to f(i, j) would be via
g(i, j) = j >= i ? f(i, j) : f(j, i)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: asp.net mvc 3 load html table with data net mvc 3 with the world first ever razor engine
lets say i have an array of string, well call it online users
string [] onlineusers --> it has data inside of it
now, how can i make a table using razor, and fill out it with the contents of onlineusers array? tnx
possible output
online users table (generated by mvc 3 razor | view engine)
------------
jack |
jason |
peter |
juan |
------------
also, is there a way that i can customize the html table? like make it center, upward, down, leftward. im also planning to place 3 tables loaded with different sets of data.
A: using the Razor syntax you could simply the data from a strongly typed model in your view
e.g.
<table>
@foreach(var onlineuser in Model.Users){
<tr>
<td><b>Name : </b></td>
<td>@onlineuser</td>
</tr>
}
<table>
A: Assuming your passing it in as a model
<table>
@foreach (string User in Model)
{
<tr>
@User
<tr>
}
</table>
Would give you a basic table. Past that you need to use CSS to customize it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: TFS Team build database build fails intermittently with missing dbschema reference TSD01236 I have a team build that is building a database project. The build has been failing intermittently for a while. Several of the projects build successfully but the "main" project in the solution fails to build because of this error
""D:\Builds\13\TeamProjectName\my_build_name\Sources\my.project.name\master.dbschema : Build error TSD01236: Failed to load D:\BUILDS\13\TeamProjectName\my_build_name\SOURCES\my.project.name\MASTER.DBSCHEMA. [D:\Builds\13\TeamProjectName\my_build_name\Sources\my.project.name\my.project.name.dbproj]""
(names changed to protect the innocent)
This looks like the file is not there, but it is included as a file in the database project and I have enough logging turned on so I can see the "get" for that file. I have verified by remoting to the build machine that the dbschema file IS there.
Rerunning the build always fixes it; remoting to the machine and running msbuild on the solution always works; remoting in and loading the database solution in Vs.net and rebuilding always works. Developers working with the solution never see this error.
Googling on that error code hasn't helped much, as with MSBuild I can't see the command line that is being send to the vsdbcmd (i don't even know if that is being used, msbuild may access it in another way).
We are running tfs 2010 but the build is running the "upgrade" template and is executing a hand written build file that executes the database build and then some other vital stuff. Changing all that to the new build template will probably be unpopular unless there is good reason to think it will be a low amount of work as this is a minor niggle.
my solutions are guesses as I can't repro the issue repeatably:
*
*wait, see if enough fails show a pattern. I suspect something to do
with how the build is triggered, it is on a timer, not doing CI.
manual triggers seem not to fail.
*change the builds to "rebuild" and hope that flushes something out
*change the referencing solution as at this msdn
*(wild guess) change the build templates to 2010 and/or rewrite the whole thing to work using a different method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is it worth to insert `const`-correctness I'm currently confronted with a C++ project written by some senior programmers consisting of about 400 files and 200 classes.
The code is well elaborated, works fine and stable.
While I'm adding some features, for me it is just ordinary practice to take care about const-correctness.
But if I start to declare my new member functions const, there is no end with adapting old code in order make things work.
*
*Should I invest the amount of time to introduce const-correctness
into this code?
*Even worse, I have to touch and alter the old mature code and explain
to the seniors what I did during the code review. Is it worth it?
A: Const correctness is a kind of additional layer over static typing that is meant to make it easier to develop mature, reliable and robust code. You say that you already have the latter. In that case, enforcing const correctness in such codebase doesn't seem to have significant, added value from the pragmatic point of view.
A: It's worth the effort... Unless you have more important things to do.
A:
Should I invest the amount of time to introduce const-correctness into this code?
If you feel that you can get it all done in a reasonable time, sure. const-correctness is a good thing, so if you can adjust the codebase to employ it properly then that can never be bad.
It all comes down to how much time you have available and what else you could be doing instead, which is more about project management and more appropriate on programmers.SE.
Even worse, I have to touch and alter the old mature code and explain to the seniors what I did during the code review. Is it worth it?
It's certainly worth it for them (and, by extension, to everybody else). It sounds like they will learn a lot in code review, which is fantastic!
Edit
As molbdnilo rightly points out, this is a big change and you should definitely have a group discussion about it before starting. This would be more appropriate than leaving it to code review in two weeks' time, when you've already done it.
A: It's a difficult issue. Retrofitting const correctness is a non-trivial
job (as you're noticing). If the code is otherwise clean and
maintainable, it probably shouldn't be undertaken lightly. On the other
hand, const correctness is almost essential in some cases—or would
be, if all compilers enforced the rule about not initializing a
reference to non-const with a temporary.
If you're not the sole owner of the code, the thing to do would be to
discuss the issue with the other people involved, decide in common
whether it is important, and program the time necessary to do it if it
is deemed important. What you shouldn't do is just start introducing it
on your own, as a "side effect" of the changes you were mandated to do.
It's a project level decision.
A: yes and yes. Const correctness is a Good Thing for a number of reasons, amongst which that it helps prevents bugs. I actually already discovered bugs while applying const correctness in a situation similar to yours.
A: Yes. Once you get over the hurdle of converting your current code to be const correct it becomes second nature.
Also if you start to follow a spec like MISRA it requires your code to be const correct (amongst many other things).
A: There are two technical steps in enforcing const-correctness.
Before you start though, you need to involve your team members, and explain the benefits of const-correctness. If you cannot convince your team mates, it's not really worth launching into this...
Now, since we're on StackOverflow, and not SE, I'd rather concentrate on the technical approach.
The two steps are drawn from the fact that:
*
*you cannot call a non-const function on a const object
*you can call a const function on a non-`const object
Therefore:
*
*Tag as const those functions who are
*const-ify the variable/parameters/attributes
The first step is non-invasive and already yields its own benefits, since it will prevent accidental modifications of the inner attributes of a class within the tagged method.
Even if you face slight resistance in your team, you can still tag the methods you develop or touch as const without any hindrance for the rest of the team.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595284",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Module's source changes don't take effect I am having an issue with python which looks really weird to me. My script starts to be quite big and is suposed to run a test suite for a program.
My inclusion tree is:
run.py --> Module --> Section --> Test
The weird behavior I am having is that when I add a modification to my Module, Section or Test module's source file, they don't take effect at all.
I am developing with emacs in my terminal and simply run my script using:
python run.py
I tried:
*
*Restarting the term
*Restarting the computer (after a few days, it wasn't a bad idea anyway)
*Cleaning the *.pyc files
The version of my python is 2.5.2 and I am working under a Debian Lenny in VirtualBox.
And I haven't been able to reproduce this behavior on another smaller program to observe it better.
A: I suspect you have at least one other module with the same name as one of yours in your PYTHONPATH. Either look for old copies you left around or try changing your module names and see what happens.
You'd see a similar effect if you forgot to reload your modules before running them after you modified them, but restarting your Python session would obviously cause all your modules to be loaded afresh at the first import of each.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Get the sender touch for ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event How can i find in a multi touch cocos2d app what was the touch that called ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event ? I can get all the touches using [event allTouches] but how can i find which touch called the function, for example when i would like for that specific touch to display a specific NSLog.
A: The touch events provide you with a UITouch* object for each finger. The UITouch* remains the same throughout the whole touch, from began to ended/cancelled. You can retain the UITouch* in the began event and release it (and set it to nil) in the ended and cancelled events.
Btw, the input class KKInput (class reference) of Kobold2D (improved Cocos2D makes that a whole lot easier. Starting with Preview 5 you can just get the list of current touches at any time, in any class or method because KKInput keeps track of the touches for you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Dojo: javascript execution in page loaded via ajax I have a template loaded via ajax and template contains the following lines:
<script type="text/javascript">
alert('11');
</script>
But I don't see neither alert window not any errors. Maybe the thing is in request and response Content-type headers? Mine are following:
Response Headers:
Content-Type text/html
Request Headers:
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Content-Type application/x-www-form-urlencoded
X-Requested-With XMLHttpRequest
A: The thing is: I loaded that template via contentPane.
The moral: use dojox.layout.ContentPane istead of dijit.layout.ContentPane.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: iphone app flow diagram map for the bigger picture I have been teaching myself iPhone development for a few months now (actually more than a few!!), when I realised that the information I was getting from text books wasn't sticking and is swimming around in my brain like object soup.
I understand bits and pieces, but for the most part can never grasp the bigger picture and connections that need to be made. So I thought I would try and put the bigger picture into a flow diagram. So I sat down and without using any text books put together a flow diagram of the bigger picture to how an iPhone app works, well how I see that it works.
Would be good if anyone could take a look, see what you think, correct mistakes, contribute to make it better or even tell me that if for works for me great, but actually it wont make sense to anyone else!
Take a look at the flow diagram so far here.
http://theknowledgeoflondon.com/Iphoneflowchart.pdf
Email me if you have any further ideas - design@securitieslendingtimes.com
Thanks, Laff
ps - What would people agree to be the definitive iPhone development text. I think I have learnt that some explain things better than others and that there isn't one good book that does what it says on the tin!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595308",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to limit Interval time between 2 click in jquery? How do I limit Interval time between 2 clicks in jQuery?
$('button').click(function(){
// do some stuff
}
After the first click, how do I wait one second, then the next click will effect. thanks.
A: You could do:
var clicked = false;
$('button').click(function(){
// do some stuff
if (!clicked){
alert('true');
clicked = true;
setTimeout(function(){ clicked = false; }, 1000);
} else {
return false;
}
}
A: Preventing double Ajax requests
$("button").click(function(evt){
evt.preventDefault();
// save button context
var ctx = this;
if (ctx.preventAjax === false)
{
ctx.preventAjax = true;
// make a request
$.ajax({
...
complete: function() {
delete ctx.preventAjax;
}
});
}
});
Not using attributes on elements is faster than using those and checking them on each click.
A: It seems like you are looking for a way to throttle the clicks. Have a look at the jQuery throttle/debounce plugin by Ben Alman.
A: After first click you can disable the button untill your ajax finshed.
$('button').click(function(){
$('button').attr('disabled',true); //disable the button
// do some stuff
$('button').attr('disabled',false);//enable button back .(most probably u need to write it in success event of ajax request)
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android google maps groundoverlay In the google maps javascript api you can add a groundoverlay and just pass two points, the point lefttoplat&lefttoplong and the point rightbottomlat&rightbottomlong... (The normal overlays don't stay between these two points, but stay the same size when you zoom in or out.)
I have been searching for something like that in the Android google maps api, but I can't find it anywhere. Is there such a thing in the android maps api and if there's not, what's the best way to simulate this function?
A: This is better. Using the draw-method makes sure you only draw the part of the bitmap that is actually on the screen. I still get the exceeded VM-budget error sometimes. I'm still looking into that.
public class GroundOverlay extends Overlay {
Bitmap original;
Bitmap resized;
int lastZoomlevel;
SnowmapsOverlayObject snowmapsObject;
public static Boolean DRAW = false;
GeoPoint topGeoPoint;
GeoPoint bottomGeoPoint;
OnReady _onReady = null;
Boolean ready = false;
public GroundOverlay(Bitmap original, SnowmapsOverlayObject snowmapsObject) {
this.original = Bitmap.createScaledBitmap(original, original.getWidth(), original.getHeight(), true);
this.snowmapsObject = snowmapsObject;
topGeoPoint = new GeoPoint((int) ((snowmapsObject.topLat).doubleValue() * 1E6), (int) ((snowmapsObject.topLng).doubleValue() * 1E6));
bottomGeoPoint = new GeoPoint((int) ((snowmapsObject.bottomLat).doubleValue() * 1E6), (int) ((snowmapsObject.bottomLng).doubleValue() * 1E6));
}
@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
super.draw(canvas, mapView, false);
Projection projection = mapView.getProjection();
Point leftTop = new Point();
Point rightTop = new Point();
Point rightBottom = new Point();
Point leftBottom = new Point();
projection.toPixels(topGeoPoint, leftTop);
projection.toPixels(new GeoPoint(topGeoPoint.getLatitudeE6(), bottomGeoPoint.getLongitudeE6()), rightTop);
projection.toPixels(bottomGeoPoint, rightBottom);
projection.toPixels(new GeoPoint(bottomGeoPoint.getLatitudeE6(), topGeoPoint.getLongitudeE6()), leftBottom);
if (
(leftTop.x < 0 || leftTop.y < 0) &&
(rightTop.x < 0 || rightTop.y < 0) &&
(rightBottom.x < 0 || rightBottom.y < 0) &&
(leftBottom.x < 0 || leftBottom.y < 0)) {
// Not on screen? Don't draw the overlay
return;
}
// GeoPoint mapCenter = mapView.getMapCenter();
Paint paint = new Paint();
paint.setFilterBitmap(true);
paint.setAntiAlias(true);
canvas.drawBitmap(original, null, new Rect(leftTop.x, leftTop.y, rightBottom.x, rightBottom.y), paint);
if (!ready && _onReady != null) {
ready = true;
_onReady.done();
}
}
@Override
public boolean onTouchEvent(MotionEvent e, MapView mapView) {
super.onTouchEvent(e, mapView);
if (e.getAction() == MotionEvent.ACTION_UP) {
setDrawTrue();
}
return false;
}
private void setDrawTrue() {
DRAW = true;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
DRAW = false;
}
}, 100);
}
public void setOnReady(OnReady onReady) {
this._onReady = onReady;
}
public interface OnReady {
public void done();
}
}
A: Fixed it myself.
For everyone with the same problem, here is my code:
public class GroundOverlay extends OverlayItem {
private MapView map;
private Bitmap overlay;
private GeoPoint topGeoPoint;
private GeoPoint bottomGeoPoint;
public Drawable drawable;
public GroundOverlay(
MapView map,
GeoPoint topLeftGeoPoint,
GeoPoint bottomRightGeoPoint,
Bitmap overlay,
String title,
String snippet) {
super(bottomRightGeoPoint, title, snippet);
this.map = map;
this.overlay = overlay;
this.topGeoPoint = topLeftGeoPoint;
this.bottomGeoPoint = bottomRightGeoPoint;
_init();
}
private void _init() {
Point topPoint = new Point();
Point bottomPoint = new Point();
map.getProjection().toPixels(topGeoPoint, topPoint);
map.getProjection().toPixels(bottomGeoPoint, bottomPoint);
int width = bottomPoint.x - topPoint.x;
int height = bottomPoint.y - topPoint.y;
drawable = overlayDrawable(overlay, width, height);
}
public BitmapDrawable overlayDrawable(Bitmap bitmap, int newWidth, int newHeight) {
Matrix scale = new Matrix();
float scaleFloat = (float)newWidth / (float)bitmap.getWidth();
scale.postScale(scaleFloat, scaleFloat);
Bitmap bitmapScaled = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), scale, false);
BitmapDrawable bm = new BitmapDrawable(bitmapScaled);
bm.setBounds(0,0,bitmapScaled.getWidth(),bitmapScaled.getHeight());
return bm;
}
}
You'll have to do the setMarker(drawable) somewhere and it should work. I'm doing that somewhere else (hence the public drawable).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: SQL Server and SSIS Permission issue? Hi all i'm banging my head against a wall with this one and hope someone can help. I have a ssis package written in BIDS 2005, which basically selects some data rows from a table in DatabaseA and transfers the data to a table in DatabaseB. Its a fairly straightforward and easy SSIS package. I've installed the package on our dev server (which is running sql server 2008 r2) into integration services. When i'm logged onto the server with my username (v_ashby-smith) and run the package directly through integration services, the package completes successfully and moves the data across as expected.
I want the package to run on a schedule so i've created a job under sql server agent. Now when i run the job the package says it completes successfully, however when inspecting the destination database table (DatabaseB), all the data in the table has been wiped!! The SSIS package does not do any sort of delete it literally just copies data across. The sql server agent services has been set to run as a domain user COMPANY\devsqladm and a user in sql server has been created with the necessary permissions to access the required databases.
To also add to the puzzle, when i run the package in BIDS, it works fine and copies the data across as expected!
If anyone has any ideas i would really appreciate it, this should be alot simpler than it is turning out to be!!
A: SSIS Package nor SQL Agent deletes anything by default... the deletion is either happening inside the package (which is usually the first task if you selected "delete rows" option) or there's a delete logic as a separate step in the agent.
You might want to run the profiler to see what exactly is being called. Or maybe try remove delete permissions from the user to see if the package fails.
Unfortunately, the information given is not enough.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: javascript does not work in Dynamic ajax content I am trying to use
http://net.tutsplus.com/tutorials/javascript-ajax/how-to-load-in-and-animate-content-with-jquery/
and modifying it myself, I added fancybox and tinyscrollbar it is working at the first, however, after I switch between some pages it is no longer working. I tried to find my answer in the comments of the tutorial page, I used .live() but it seams it is not working and I can not figure out the solution,
hear is my code:
$(document).ready(function() {
var hash = window.location.hash.substr(1);
var href = $('#nav li a').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href.length-5)){
var toLoad = hash+'.html #content';
$('#content').load(toLoad)
}
});
$('#nav li a').live ('click', function(){
var toLoad = $(this).attr('href')+' #content';
$('#content').slideToggle('fast',loadContent);
$('#load').remove();
$('#wrapper').append('<span id="load">LOADING...</span>');
$('#load').fadeIn(500);
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);
function loadContent() {
$('#content').load(toLoad,'',showNewContent())
}
function showNewContent() {
$('#content').show(500,hideLoader());
}
function hideLoader() {
$('#load').fadeOut(500);
}
return false;
});
$("#scrollbar1").tinyscrollbar();
$("a#example1").fancybox();
});
thank you,
Andrew
A: Its hard to see what your trying to do when there isn't a complete page to look at. But i think the problem is that when you load new content you should update the scrollbar and the fancybox accordingly.
For tinyscrollbar you can use the update method.
you can see how to use it on the tinyscrollbar site.
You could try to put it in the succes callback of your loading event.
$("#scrollbar1").tinyscrollbar_update();
You could try to put that rule on the end of your hideLoader function or showNewContent function.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Creating temporary files in Android with NDK I am currently working on a C-based, NDK-based, Android application. This application needs to create temporary files. On a regular Linux system, I would use tmpfile to ensure that these files are properly created in a temporary directory and cleaned-up at process end.
However, my investigations on various Android devices seem to indicate that
*
*tmpfile always fails;
*there is no /tmp directory;
*directory /data/local/tmp isn't present on all variants of Android;
*there is no TEMP environment variable set;
*mkstemp doesn't work any better than tmpfile.
Now, I'm sure that I could hack something together, but seeing that the SDK offers context.getCacheDir and File.createTempFile for Java applications, I hope that there is an equivalent at C-level.
Does anyone know of a good reliable and cross-Android method for creating a temporary file?
A: Below is the GetMethodID / CallObjectMethod procedure that Ertebolle refers to. It is necessary if you are working with a pure native app (such as built by Visual Studio 2015) and cannot use java code.
std::string android_temp_folder( struct android_app *app ) {
JNIEnv* env;
app->activity->vm->AttachCurrentThread( &env, NULL );
jclass activityClass = env->FindClass( "android/app/NativeActivity" );
jmethodID getCacheDir = env->GetMethodID( activityClass, "getCacheDir", "()Ljava/io/File;" );
jobject cache_dir = env->CallObjectMethod( app->activity->clazz, getCacheDir );
jclass fileClass = env->FindClass( "java/io/File" );
jmethodID getPath = env->GetMethodID( fileClass, "getPath", "()Ljava/lang/String;" );
jstring path_string = (jstring)env->CallObjectMethod( cache_dir, getPath );
const char *path_chars = env->GetStringUTFChars( path_string, NULL );
std::string temp_folder( path_chars );
env->ReleaseStringUTFChars( path_string, path_chars );
app->activity->vm->DetachCurrentThread();
return temp_folder;
}
A: The best way we've found is to call Context.getCacheDir on startup, get its path with getAbsolutePath, then call a JNI function to store that path in a global. Any function that wants to create a temporary file simply appends a suitable temporary file name to that path.
If you really want to fetch it from JNI another alternative would be to pass in a Context to a JNI function and use a bunch of GetMethodID / CallObjectMethod stuff to call back into Java to getCacheDir, but the former approach is a lot simpler.
Unfortunately, there does not appear to be a more elegant solution at the moment.
A: As far as I know there is no global /tmp in android, you should use the cache dir. Use getCacheDir() to get the "tmp" dir.
http://developer.android.com/guide/topics/data/data-storage.html#filesInternal and http://developer.android.com/reference/android/content/Context.html#getCacheDir%28%29
A: mkstemp is available in the NDK under stdlib.h
A: *
*Obtain path to cache directory on application's startup using a ContentProvider.
*Implement tmpfile function with the same signature as POSIX's tmpfile.
*Call mkstemp from your tmpfile function using the previously obtained cache directory
Packaged it as .aar, so it could be consumed through gradle.
https://github.com/ViliusSutkus89/tmpfile-Android
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
}
|
Q: How can I use AddSubType on a type that is a collection? RuntimeTypeModel.Default[typeof(IMyClass2)].AddSubType(1, typeof(MyClass)) threw "Repeated data (a list, collection, etc) has inbuilt behaviour and cannot be subclassed" exception. Following is the code snippet
public partial class TestClass
{
public TestClass()
{
}
private void Serialize(object sender, EventArgs e)
{
Stream stream = new FileStream(resultFilePath,
FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
RuntimeTypeModel.Default[typeof(IMyClass2)].AddSubType(1, typeof(MyClass));
Serializer.Serialize(stream, myDict);
stream.Close();
}
private void DeSerialize(object sender, EventArgs e)
{
Stream stream = new
FileStream(resultFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
Dictionary<int, IMyClass2> myNewDict = Serializer.Deserialize<Dictionary<int, IMyClass2>>(stream);
stream.Close();
}
}
[ProtoContract]
[Serializable]
public class MyClass : IMyClass2
{
#region IMyClass2 Members
//members
#endregion
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
#endregion
}
public interface IMyClass2 : IMyClass1
{
//members
}
public interface IMyClass1 : IEnumerable
{
//members
}
How should I handle this exception? Please help.
A: protobuf-net has concluded (quite reasonably) that your base-type there is a collection-type. Collections (in common with most other serializers and data-binding etc) get treated differently to individual items. In "protocol buffers" this is even more pronounced, since the container doesn't even exist in the stream - all that is serialized is the individual elements. To illustrate this in xml terms (clarification: protobuf-net is nothing to do with xml, but this helps visualise), then in xml there are 2 approaches for sub-items:
<foo> <foo>
<items> <bar/>
<bar/> <bar/>
<bar/> <bar/>
<bar/> </foo>
</items>
</foo>
of those, protobuf-net would be more like the example on the right - there is no representation at all of the container (items).
Because of this (which is related to the Google specification, not protobuf-net's implementation), it cannot store anything particular to the collection, so it does not have anywhere to note any particulars like inheritance (which also doesn't exist in the Google specification, but I can work around it for individual items).
In short, I would suggest "don't do that". Perhaps if I understood the scenario a bit more completely I could give a more useful answer.
Note (as hinted above) that it can handle inheritance of individual items, so a List<SomeBaseType> can contain DerivedType1, DerivedType2 and YetAnotherDerivedType instances.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: JPA 2.0 native query results as map I run a JPA 2.0 native query like this:
Query query = em.createNativeQuery("SELECT NAME, SURNAME, AGE FROM PERSON");
List list = query.getResultList();
now list has all the rows returned by the query. I can iterate over them, but every entry is an Object[] where:
*
*at index 0 I find NAME
*at index 1 I find SURNAME
*at index 3 I find AGE
Did anyone find a way to do something like this:
Map<String, Object> row = list.get(index);
String name = row.get("NAME");
String surname = row.get("SURNAME");
Integer age = row.get("AGE");
I would need this since the native query that I execute is a dynamic one and I don't know the order of the field in SELECT clause, so I don't know id the query will look like:
SELECT SURNAME, NAME, AGE FROM PERSON
or
SELECT AGE, NAME, SURNAME FROM PERSON
or even
SELECT AGE, SURNAME, NAME FROM PERSON
A: As other already mentioned, older JPA does not support it, however I have workaround solution with Postgres 9.4 in my situation, while working with Jackson,
List<String> list = em.createNativeQuery("select cast(json_object_agg(c.config_key,c.config_value) as text) from myschema.configuration c")
.getResultList();
To use it in Bean layer use below method, otherwise directly return.
//handle exception here, this is just sample
Map map = new ObjectMapper().readValue(list.get(0), Map.class);
Few more json functions, https://www.postgresql.org/docs/9.4/static/functions-json.html. I am sure you can find same for other databases.
A: Take a look on this I got it when working on project that I could not use all JPA features so I tried the traditional jdbc method even if I would not recommend this but it's working for me.
@LocalBean
public class TCotisationEJB {
@PersistenceContext(unitName="ClaimsProjectPU")
private EntityManager em;
@TransactionAttribute(TransactionAttributeType.NEVER)
public List getCotisation(){
Query query=em.createNativeQuery("select Annee,Mois,RetSonarwa from TCotisMIFOTRA2008 where matricule='10000493' order by Annee");
List<Object[]> cotisation=query.getResultList();
Object[] cotisationData;
for(int i=0;i<cotisation.size();i++){
cotisationData=cotisation.get(i);
System.out.print("Annee: "+cotisationData[0]+" Mois :"+cotisationData[1]+" Amount :"+cotisationData[2]+"\n");
}
return query.getResultList();
}
}
A: Which JPA are you using - Hibernate, EclipseLink or something else?
There is no standard way to do this in JPA but your specific implementation may allow it - for example, Eclipselink has a query result type hint.
http://dev.eclipse.org/mhonarc/lists/eclipselink-users/msg03013.html
Query query = entityManager.createNativeQuery(sql);
query.setHint(QueryHints.RESULT_TYPE, ResultType.Map);
For Hibernate, with javax.persistence.Query dbQuery:
org.hibernate.Query hibernateQuery =((org.hibernate.jpa.HibernateQuery)dbQuery)
.getHibernateQuery();
hibernateQuery.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
}
|
Q: how do i get jsoup to work? ive been going through these joup bits to get some information from a div:
http://jsoup.org/cookbook/extracting-data/dom-navigation
Document doc = Jsoup.connect(path).get();
Element cat = doc.getElementById("category_1");
Elements links = cat.getElementsByTag("a");
for (Element link : links)
{
rstring += link.attr("href");
rstring += link.text() + "\n";
}
that code bit i wrote does not work, and ive been working on this for hours.
i can get some of what i want with different jsoup functions, but i need to get the links in this particular action so i can populate and array of certain things for my android app.
im attempting to parse http://android.myfewclicks.com for testing and building an app for my real site.
any assistance at all would be wonderful. jsoup just wont cooperate.
<table class="table_list">
<tbody class="header" id="category_1">
<tr>
<td colspan="4">
<div class="cat_bar">
<h3 class="catbg">
<a class="collapse" href="http://android.myfewclicks.com/index.php?action=collapse;c=1;sa=collapse;c707bdb315=de9d7f201a0964cbab3d56e683507ad7#c1"><img src="http://android.myfewclicks.com/Themes/default/images/collapse.gif" alt="-" /></a>
<a class="unreadlink" href="http://android.myfewclicks.com/index.php?action=unread;c=1">Unread Posts</a>
<a id="c1"></a><a href="http://android.myfewclicks.com/index.php?action=collapse;c=1;sa=collapse;c707bdb315=de9d7f201a0964cbab3d56e683507ad7#c1">Category A</a>
</h3>
</div>
</td>
</tr>
</tbody>
on my test forum, there are four categorys. the three links inside this particular part is 1 set of the 4. if i can figure out how to adaquitely parse these out, then i should be able to make a big leap on my app. but jsoup isnt behaving the way im thinking it should, or im missing something very crucial.
A: You apparently need to login first in order to get the links with href. When I open the site in my browser while not logged in, I see
<tbody class="header" id="category_1">
<tr>
<td colspan="4">
<div class="cat_bar">
<h3 class="catbg">
<a id="c1"></a>Category A
</h3>
</div>
</td>
</tr>
</tbody>
I can get the links as follows:
Document document = Jsoup.connect("http://android.myfewclicks.com/").get();
Elements category1links = document.select("#category_1 a");
for (Element category1link : category1links) {
System.out.println(category1links);
}
Which prints
<a id="c1"></a>
Note that there's no href or text!
Jsoup does not login for you automatically, nor does it take over the cookies of an arbitrary browser which is already installed on your machine. You need to login and maintain the session cookie yourself. See also Sending POST request with username and password and save session cookie for an example.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595333",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting Sum Of Numbers In Each Line Of File i have a file that there is some numbers that i want to sum number one with number two in each line.here is numbers in my file:
-944 -857
-158 356
540 70
15 148
for example i want to sum -944 and -857 what should i do??
i did it like the code below to check whats the numbers and the output is -158 and 15(it doesnt show -944 and 540 !!!):
StreamReader ar = new StreamReader(@"C:\Users\arash\Desktop\problem1 (3).in");
while (ar.ReadLine() != null)
{
string[] spl = ar.ReadLine().Split(' ');
MessageBox.Show(spl[0]);
}
A: You are reading a line in the while check, and then again to parse the value - which is why it only seems to read the even lines.
Proposed solution:
StreamReader ar = new StreamReader(@"C:\Users\arash\Desktop\problem1 (3).in");
// Prepare the first line.
string line = ar.ReadLine();
while (line != null) {
// http://msdn.microsoft.com/en-us/library/1bwe3zdy.aspx
string[] spl = line.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
MessageBox.Show(spl[0]);
// Prepare the next line.
line = ar.ReadLine();
}
update: using an overload of string.Split() that returns no empty results and max 2 values (1 and the rest of the string).
A: Try this (streamlined version):
StreamReader ar = new StreamReader(@"C:\Users\arash\Desktop\problem1 (3).in");
while ((string line = ar.ReadLine()) != null)
{
string[] spl = line.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
MessageBox.Show(spl[0]);
}
You are reading twice but only using the second read.
Note: You are also not trimming spaces from the start of the lines so you will lose numbers if the data has leading spaces (as shown in the example).
A: you're doing a readline in your while condition and again in the body of your while scope, thus skipping 1 readline instruction (in the while condition). try this instead:
StreamReader ar = new StreamReader(@"C:\Users\arash\Desktop\problem1 (3).in");
string s = ar.ReadLine();
while (s != null)
{
//string[] spl = s.Split(' ');
// below code seems safer, blatantly copied from one of the other answers..
string[] spl = s.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
MessageBox.Show(spl[0]);
s = ar.ReadLine();
}
A: StreamReader ar = new StreamReader(@"C:\Users\arash\Desktop\problem1 (3).in");
// Load a line into s
string s = ar.ReadLine();
while (s != null)
{
// Split on space
string[] spl = s.Trim(' ').Split(' ');
// Declare two variables to hold the numbers
int one;
int two;
// Try to parse the strings into the numbers and display the sum
if ( int.TryParse( spl[0], out one ) && int.TryParse( spl[1], out two) ) {
MessageBox.Show( (one + two).ToString() )
}
// Error if the parsing failed
else {
MessageBox.Show("Error: Numbers were not in integer format");
}
// Read the next line into s
s = ar.ReadLine();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Mapping lists in my Mapper class using using AutoMapper I am using ASP.NET MVC 3 and AutoMapper.
In my category controller I return a list of categories and I want to map each category to a category view model which is used in my grid. I have my own mapper class method that accepts the source, source type and destination type and then does the mapping of single objects. How would I add and additional method so that I can map lists?
For example, if I want to map a single category to my category edit view model then the following mapping will be used:
Mapper.CreateMap<CategoryCreateViewModel, Category>();
In my controller I would map the 2 like this:
Category category = (Category)categoryMapper.Map(viewModel, typeof(CategoryCreateViewModel), typeof(Category));
This is what my mapping method looks like:
public class CategoryMapper : ICategoryMapper
{
static CategoryMapper()
{
Mapper.CreateMap<Category, CategoryCreateViewModel>();
Mapper.CreateMap<Category, CategoryViewModel>();
Mapper.CreateMap<CategoryCreateViewModel, Category>();
}
public object Map(object source, Type sourceType, Type destinationType)
{
return Mapper.Map(source, sourceType, destinationType);
}
// I have been trying to get this right but not working
//public object Map(object source, IEnumerable<Type> sourceType, IEnumerable<Type> destinationType)
//{
// return Mapper.Map(sourceType, destinationType);
//}
}
I want to add another method where I can map lists. How would I do this?
A: AutoMapper knows how to map lists, you don't need any extra code.
As long as you provide the mapping for the single object, it will work.
E.g:
Mapper.CreateMap<Source,Dest>();
Then:
var mappedCollection = Mapper.Map<IEnumerable<Source>,IEnumerable<Dest>>(items);
And it will work.
A: try
var maplist= Mapper.Map<IEnumerable<TSource>, IEnumerable<TDestination>>(IEnumerable<TSource>source);
i'm not sure but try something like
var category = CategoryMapper.Map(viewModel, CategoryCreateViewModel, Category);
public object Map(object source, IEnumerable<T> sourceType, IEnumerable<T> destinationType)
{
return Mapper.Map<sourceType,destinationType>(source);
}
A: I wanted to use my IMapper methods like I mentioned above. With the help of Darin Dimitrov I got this to work. Here is my controller code:
public ActionResult JsonGetParentCategoryList()
{
IEnumerable<Category> categoryList = categoryService.GetAll();
// Mapping
IEnumerable<CategoryViewModel> viewModelList = (IEnumerable<CategoryViewModel>)
categoryMapper.Map(
categoryList,
typeof(IEnumerable<Category>),
typeof(IEnumerable<CategoryViewModel>)
);
JsonEncapsulatorDto<CategoryViewModel> data = new JsonEncapsulatorDto<CategoryViewModel>
{
DataResultSet = viewModelList
};
return Json(data, JsonRequestBehavior.AllowGet);
}
It works with my current IMapper Map method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595341",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Jpa2/hibernate c3p0 pool configuration lead connection and thread leaks I am trying to use c3p0 as connection pool provider in my application (jpa 2 and hibernate core 3.3.2) but c3p0 getting too much connection from database.This is same problem but answer not helped.I am getting entitymanager from entitymanager factory and storing entitymanager in a thread local variable,thus a am using a fresh entiymanager for each request.(by the way if i use hibernate default pool no problem)
<property name="hibernate.connection.provider_class"
value="org.hibernate.connection.C3P0ConnectionProvider" />
<property name="hibernate.c3p0.min_size" value="1" />
<property name="hibernate.c3p0.max_size" value="10" />
<property name="hibernate. c3p0.initialPoolSize" value="3" />
<property name="hibernate.c3p0.numHelperThreads" value="3" />
<property name="hibernate.c3p0.maxPoolSize" value="10" />
<property name="hibernate.c3p0.minPoolSize" value="1" />
<property name="hibernate.c3p0.maxIdleTime" value="3600" />
<property name="hibernate.c3p0.maxIdleTimeExcessConnections" value="300" />
<property name="hibernate.c3p0.unreturnedConnectionTimeout" value="3600" />
<property name="hibernate.c3p0.acquire_increment" value="1" />
<property name="hibernate.c3p0.idle_test_period" value="3000" />
<property name="hibernate.c3p0.max_statements" value="0" />
<property name="hibernate.c3p0.timeout" value="300" />
<property name="hibernate.c3p0.breakAfterAcquireFailure" value="false" />
<property name="hibernate.c3p0.acquireRetryAttempts" value="1" />
<property name="hibernate.c3p0.acquireRetryDelay" value="100" / >
A: Can you ensure that you are not defining pool at both datasource and sessionFactory level.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I add projects to my list of favorites on Google Code? In Google Code there is a list of favorites. How do I add projects to my list of favorites?
A: The above answer is not correct. You can "star" a project (upper left corner of project home page, in the sidebar), which adds it to your list of favorites without being a participant in the project.
A: As far as I know this is automatically done for every project you participate in. You can not manually add a project to your favorites.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: C++: Logical Comparison as conditional statement? Ran across some code that used this, which led me to wonder.
if(condition) foo = bar();
condition && (foo = bar());
Are these two segments of code equal to a compiler? If not, in what ways would they differ?
A: Due to operator precendence, the latter is interpreted as:
(condition && foo) = bar();
Additionally, there is a possibility of && being overloaded, which may result in pretty much anything.
So in short: they are not equal at all - at least in general case.
A: The first version is just a plain old statement.
The second version is an expression that will return the result of the entire expression. That probably allows some tricky one-line syntax that, as per usual, could potentially make code more readable but will more likely make it more complex and harder to parse quickly due to unfamiliarity.
IMO either use it everywhere consistently so that readers of your code get used to it, or don't use it at all.
A: Unless condition && foo evaluates to an lvalue , condition && foo = bar(); is meaningless.
A: Unless && is overloaded for the combination of types of condition and foo they will have identical behavior - the latter will work this way:
bool result;
if( !condition ) {
result = false;
} else {
foo = bar();
result = foo != 0;
}
and result gets ignored
that's usual short-circuiting - if the first component of && is false the second is not evaluated.
IMO the second variant is much less readable.
A: There is a compiler error: invalid l-value. To have same functionality you must use
conticion ? foo = bar( ) : <other accion>;
A: If && is not overloaded for neither condition nor foo:
condition && (foo = bar());
will be treated as
(condition.operator bool()) && (foo = bar());
if (condition.operator bool()) isn't true, (foo = bar()) won't be executed and vice versa.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Slide functionality with dynamic changing views in it
Please have a look on this image
The whole review section will slide according to days of week saturday monday etc..
Inside values are dynamic and will come from server accordingly
there are also buttons named comment,agreeand report abuse which will update values as according to their name
How can I achieve this kind of functionality in android.
That is I am in need of sliding functionality (Left and right both)which contains a list view with dynamic changing elements. and button on click which functionality will be there as accordingly
Please help me ASAP
thanks
Abhinav
A: HI guys I have found the solution of my own question
See this
android gestures
and this link
Switching between activities stack over flow
Thanks for visiting my question
A: Try to look at ViewPager class in Android Compatibility Package.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iPhone - Getting the lock screen background image Into my app, I need to display the lock screen background image chosen by the user.
How can I get that image to display it without using private API ?
A: There is no public API to get the lock screen or home screen images.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to properly modelize an object with localized (i18n) properties I have an Entity which has an id and a title. The id is always the same but the title value change given a locale. I found three way to modelize this :
class Entity
String getId()
String getTitle(Locale)
or
class Entity
String getId()
LocalizedEntity getLocalizedEntity(Locale)
class LocalizedEntity
String getTitle()
or
class Entity
String getId()
class LocalizedEntity extends Entity
Locale getLocale()
String getTitle()
I tend to prefer the first one because it does not corrupt the way you modelize the Entity, it is just a kind of view of your object. The second is the worst case for me.
Which one is better ? Is there another way ?
A: To my mind, that your data are localised should not impact on your object design, so I would go with your first option.
We built a localisation engine in my day job, a few years ago, and that is the model we used, where the Locale object was specified with three properties (ISO 639-1 α-2 language code, ISO 15924 α-4 script code and ISO 3166 α-2 territory code, together making up an IETF language tag, like en-Latn-GB, zh-Hans-CN, sr-Cyrl-RS and so on).
I hope that helps, though I'm guessing you probably made your decision last year, given the date of your question.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595358",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: NUnit Tests in generic abstract base class are ignored I have create a generic abstract base class to do some common tests. The test are showing up, but they are ignored. Why?
Example
public abstract class FooBase<TA, TB> : TestBase<TA, TB>
{
[Test]
public void SomeBaseTest(){}
}
[TestFixture]
public class ConcreteFooTest:FooBase<IFoo,MyContext>
{
[Test]
public void WorkingTest(){}
}
It this example are SomeBaseTest ignored.
TestBase are used by all my tests and are only containing some help methods, and no tests
A: As Ritch states it is due to RS' test runner. This is a bug in RS 6.0 which is scheduled for fix in 6.1.
See RSRP-273687 Unit test runner shows inconclusive with test class with generic base class.
A: Which test runner are you using?
And have you tried to add the TestFixture attribute?
[TestFixture]
public abstract class FooBase<TA, TB> : TestBase<TA, TB>
{
[Test]
public void SomeBaseTest(){}
}
A: The problem is likely with your test runner. Nunit 2.5.10's test runner ran it, Autotest.Net (1.3.1) ran it, and Resharper 6.0's test runner saw it, but wouldn't automatically run it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: MySQL Duplicate rows - specify columns How can I run a query that finds duplicates between rows? It needs to not match one field but multiple.
Here is the EXPLAIN of the table.
+-------------+--------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+-------------------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| token | varchar(64) | NO | MUL | NULL | |
| maxvar | float | NO | | NULL | |
| maxvbr | float | NO | | NULL | |
| minvcr | float | NO | | NULL | |
| minvdr | float | NO | | NULL | |
| atype | int(11) | NO | | NULL | |
| avalue | varchar(255) | NO | | NULL | |
| createddate | timestamp | NO | | CURRENT_TIMESTAMP | |
| timesrun | int(11) | NO | | NULL | |
+-------------+--------------+------+-----+-------------------+----------------+
I need to match all rows that match: token,maxvar,maxvbr,minvcr,minvdr,type and avalue. If all of those fields match those in another row then treat it as a "duplicate".
Ultimately I want to run this as a delete command but I can easily alter the select.
UPDATE Still looking for solution that deletes with single query in MySQL
A: Just join the table to itself and compare the rows. You can make sure you keep the duplicate with the lowest ID by requiring the id to be deleted to be greater than the id of a duplicate:
DELETE FROM my_table WHERE id IN (
SELECT DISTINCT t1.id
FROM my_table t1
JOIN my_table t2
WHERE t1.id > t2.id
AND t1.token = t2.token AND t1.maxvar = t2.maxvar
AND t1.maxvbr = t2.maxvbr AND t1.minvcr = t2.minvcr
AND t1.minvdr = t2.minvdr AND t1.type = t2.type)
A: SELECT token,maxvar,maxvbr,minvcr,minvdr,type, avalue,
Count(*)
FROM yourtable
GROUP BY token,maxvar,maxvbr,minvcr,minvdr,type, avalue
HAVING Count(*) > 1
This query returns all the rows that are in the table two times or more often (and how often they are).
A: Try:
SELECT token,maxvar,maxvbr,minvcr,minvdr,type,avalue, COUNT(*)
FROM table
GROUP BY token,maxvar,maxvbr,minvcr,minvdr,type,avalue
HAVING COUNT(*)>1
A: This query will find all duplicate records which should be deleted -
SELECT t1.id FROM table_duplicates t1
INNER JOIN (
SELECT MIN(id) id, token, maxvar, maxvbr, minvcr, minvdr, atype, avalue FROM table_duplicates
GROUP BY token, maxvar, maxvbr, minvcr, minvdr, atype, avalue
HAVING COUNT(*) > 1
) t2
ON t1.id <> t2.id AND t1.token = t2.token AND t1.maxvar=t2.maxvar AND t1.maxvbr = t2.maxvbr AND t1.minvcr = t2.minvcr AND t1.minvdr = t2.minvdr AND t1.atype = t2.atype AND t1.avalue = t2.avalue;
This query will remove all duplicates -
DELETE t1 FROM table_duplicates t1
INNER JOIN (
SELECT MIN(id) id, token, maxvar, maxvbr, minvcr, minvdr, atype, avalue FROM table_duplicates
GROUP BY token, maxvar, maxvbr, minvcr, minvdr, atype, avalue
HAVING COUNT(*) > 1
) t2
ON t1.id <> t2.id AND t1.token = t2.token AND t1.maxvar=t2.maxvar AND t1.maxvbr = t2.maxvbr AND t1.minvcr = t2.minvcr AND t1.minvdr = t2.minvdr AND t1.atype = t2.atype AND t1.avalue = t2.avalue;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Open Source application on GAE/Java Is there any Free and Open Source web application which is developed on Google App Engine's Java platform?
A: I guess there are many. Here's mine: https://memwords.appspot.com/. Its source code is hosted on Google Code. See http://code.google.com/hosting/search?q=label%3aAppEngine for a list of other projects hosted on google code and labeled with AppEngine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Is there a situation in which Dispose won't be called for a 'using' block? This was a telephone interview question I had: Is there a time when Dispose will not be called on an object whose scope is declared by a using block?
My answer was no - even if an exception happens during the using block, Dispose will still be called.
The interviewer disagreed and said if using is wrapped in a try-catch block then Dispose will not be called by the time you enter the catch block.
This goes contrary to my understanding of the construct, and I haven't been able to find anything that backs up the interviewers point of view. Is he correct or might I have misunderstood the question?
A: Four things that will cause Dispose to not be called in a using block:
*
*A power failure on your machine when inside the using block.
*Your machine getting melted by an atomic bomb while in the inside of the using block.
*Uncatchable exceptions like StackOverflowException, AccessViolationException and possibly others.
*Environment.FailFast
A: void Main()
{
try
{
using(var d = new MyDisposable())
{
throw new Exception("Hello");
}
}
catch
{
"Exception caught.".Dump();
}
}
class MyDisposable : IDisposable
{
public void Dispose()
{
"Disposed".Dump();
}
}
This produced :
Disposed
Exception caught
So I agree with you and not with the smarty interviewer...
A: Yes there is a case when dispose won't be called... you are over thinking it. The case is when the variable in the using block is null
class foo
{
public static IDisposable factory()
{
return null;
}
}
using (var disp = foo.factory())
{
//do some stuff
}
will not throw an exception but would if dispose was called in every case. The specific case that your interviewer mentioned is wrong though.
A: Bizarrely I read about a circumstance where Dispose won't get called in a using block just this morning. Checkout this blog on MSDN. It's around using Dispose with IEnumerable and the yield keyword, when you don't iterate the entire collection.
Unfortunately this doesn't deal with the exception case, honestly I'm not sure about that one. I would have expected it to be done but maybe it's worth checking with a quick bit of code?
A: The other answers about power failure, Environment.FailFast(), iterators or cheating by using something that is null are all interesting. But I find it curious that nobody mentioned what I think is the most common situation when Dispose() won't be called even in the presence of using: when the expression inside using throws an exception.
Of course, this is logical: the expression in using threw an exception, so the assignment didn't take place and there is nothing we could call Dispose() on. But the disposable object can already exist, although it can be in half initialized state. And even in this state it can already hold some unmanaged resources. This is another reason why correctly implementing the disposable pattern is important.
Example of the problematic code:
using (var f = new Foo())
{
// something
}
…
class Foo : IDisposable
{
UnmanagedResource m_resource;
public Foo()
{
// obtain m_resource
throw new Exception();
}
public void Dispose()
{
// release m_resource
}
}
Here, it looks like Foo releases m_resource correctly and we are using using correctly too. But the Dispose() on Foo is never called, because of the exception. The fix in this case is to use finalizer and release the resource there too.
A: The using block gets turned by the compiler into a try/finally block of its own, within the existing try block.
For example:
try
{
using (MemoryStream ms = new MemoryStream())
throw new Exception();
}
catch (Exception)
{
throw;
}
becomes
.try
{
IL_0000: newobj instance void [mscorlib]System.IO.MemoryStream::.ctor()
IL_0005: stloc.0
.try
{
IL_0006: newobj instance void [mscorlib]System.Exception::.ctor()
IL_000b: throw
} // end .try
finally
{
IL_000c: ldloc.0
IL_000d: brfalse.s IL_0015
IL_000f: ldloc.0
IL_0010: callvirt instance void [mscorlib]System.IDisposable::Dispose()
IL_0015: endfinally
} // end handler
} // end .try
catch [mscorlib]System.Exception
{
IL_0016: pop
IL_0017: rethrow
} // end handler
The compiler won't rearrange things. So it happens like this:
*
*Exception is thrown in, or propagates to, the using block's try part
*Control leaves the using block's try part, and enters its finally part
*Object is disposed by the code in the finally block
*Control leaves the finally block, and the exception propagates out to the outer try
*Control leaves the outer try and goes into the exception handler
Point being, the inner finally block always runs before the outer catch, because the exception doesn't propagate til the finally block finishes.
The only normal case where this won't happen, is in a generator (excuse me, "iterator").
An iterator gets turned into a semi-complicated state machine, and finally blocks are not guaranteed to run if it becomes unreachable after a yield return (but before it has been disposed).
A: using (var d = new SomeDisposable()) {
Environment.FailFast("no dispose");
}
A: The interviewer is partially right. Dispose may not correctly clean up the underlying object on a case-by-case basis.
WCF for example has a few known issues if an exception is thrown while in a using block. Your interviewer was probably thinking of this.
Here is an article from MSDN on how to avoid issues with the using block with WCF. Here is Microsoft's official workaround, although I now think that a combination of that answer and this one is the most elegant approach.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "66"
}
|
Q: iOS 5 segue implementation While implementing a segue between two view controllers how to change a property of the destination view controller using the segue object? The documentation says that this can be done inside the prepareForSegue: sender: method. i tried it but not was not successful
A: I have written a tutorial that gives code examples for passing information to the new scene and information back from a scene using delegation so check it out it should solve your problem. iOS 5 Storyboard: How To use Segues, Scenes and Static Content UITableViews
A: I don't know if you still need an answer to this, but it was such a lonely post, and if I'm correct, this doesn't fall under NDA any longer. If I'm mistaken, please moderate my answer into oblivion, so here we go: I just finished doing something that uses what you need. This is code that works for me:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"relevantSegueIdentifier"])
{
// [segue destinationViewController] is read-only, so in order to
// write to that view controller you'll have to locally instantiate
// it here:
ViewController *upcomingViewController = [segue destinationViewController];
// You now have a solid reference to the upcoming / destination view
// controller. Example use: Allocate and initialize some property of
// the destination view controller before you reach it and inject a
// reference to the current view controller into the upcoming one:
upcomingViewController.someProperty = [[SomePropertyClass alloc] initWithString:@"Whatever!"];
upcomingViewController.initialViewController = [segue sourceViewController];
// Or, equivalent, but more straightforward:
//upcomingViewController.initialViewController = self;
}
}
This assumes that both someProperty and initialViewController are synthesized accessors of the destination view controller. Hope this helps!
A: What I use in source view controller is:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
UIViewController *upcomingViewController = [segue destinationViewController];
upcomingViewController.view.tag = [[segue identifier] hash];
}
And then in the destination view controller I use (use for instance in the viewDidAppear)
if(self.view.tag == [@"MySeqgueIdentifier" hash])
{
// Do something here...
}
This is cool, since you don't have to create any properties etc. and everything works right from interface builder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How can I add exceptions for sorting Django models? I've got a line in python:
streams = Stream.objects.filter(info__isnull = False)\
.order_by('-score', 'info__title')
I feed that to a RequestContext
c = RequestContext(request, {
'online_streams': streams.filter(online = True),
'offline_streams': streams.filter(online = False)
})
It sorts a table of ~50 rows by their score and title. This is good, but there is one row I would like to always be top. Simply fetching it beforehand and filtering it out of the line above, then give it to the RequestContext separately won't work, since I'd have to modify the template. Also I might change which row should be on top later, or perhaps make it multiple rows instead.
Is there a filter argument I can insert that says something in the lines of "Order all rows by score then title, except row ID 8, which should always be top"? Or could I perhaps change the order of the QuerySet manually after the filtering?
Thanks for any suggestions
A: You can override Model manager method:
class MyManager(models.Manager):
def filter(self, *args, **kwargs):
return super(MyManager, self).filter(*args, **kwargs).exclude(id=8).order_by(...)
then in model
class Stream(models.Model):
...
objects = MyManager()
EDIT
to make sure it is included you can query:
from django.db.models import Q
return super(MyManager, self).filter(Q(id=8) | Q(*args, **kwargs)).order_by(...)
A: I couldn't find a way to use query sets to do this, so I ended up converting the query set to a list and sorting it using the magic compare function. It ended up looking something like this:
The magic sorter, checking for names that should be stuck "on top":
# Comparison magic
def __cmp__(self, other):
# On top
if self.name in stream_ontop:
return 1
if other.name in stream_ontop:
return -1
# Score
if self.score > other.score:
return 1
if self.score < other.score:
return -1
# Title alphabetical
if self.info.title > other.info.title:
return -1
if self.info.title < other.info.title:
return 1
return 0
Then I fetched and sorted them like this from my model class
# Custom sorting
@staticmethod
def getAllSorted(online):
streams = list(Stream.objects.filter(online=online, info__isnull=False))
streams.sort(key=None, reverse=True)
return streams
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Threadsafe Guice Binding I am currently refactoring the server side of an existing project.
We are using now guice to bind the specific modules and its objects.
Over the last 2 weeks we often have a problem which looks like that guice is mixing up some of the used object instances.
The problem is a class which is reponsible for building up a String which will be inserted in a database. This class is used from a rpc service which can be called quite fast in a row. So what happens is that RPC service 1 calls this class and in the meantime RPC service 2 is calling this class as well and changing the global parameter which are used for string building. The builder class is kind of stupid as it takes a param from a method sets some parts of the param as global variables and processes the string.
I think the main problem are the global variables but I dont know how I could get rid of them in an elegant way. They are used in all other methods which are called from the init method(e.g. startMethod() calls buildStringOne(), buildStringTwo() and those are accessing both global variables which are set in startMethod()).
Is there a better way how I could bind this object or do I need to remove the global variables and provide them as paramter in the other methods?
Thanks for your help.
A: Using shared mutable state is asking for trouble. It sounds like your root problem is really a thread safety issue. However, you don't have to solve thread safety issues by making mutable state thread safe -- you can also just make it so the state is only visible to one thread.
You may be able to use Guice's request-scoped objects to solve this problem. If the troublesome class can be used in such a way that it's injected, Guice will provide a new instance for each servlet request. If you're using it in classes with longer scope than Request (such as Singleton), inject a Provider. Calling get() will return the appropriate Foo instance for the request that the calling thread is handling.
See https://code.google.com/p/google-guice/wiki/ServletModule#Using_RequestScope for more.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android view animation: replacing view by itself In my android app, I have a notion of "trails": a sequence of objects that the user can navigate. The same view, naturally, is used to display all objects, just updating components (texts, images, etc.) when the next object is to be shown.
Now, I want to animate the transition between objects: when the user navigates from an object to the next object, I want to use the slide animation from right to left (and the other way around). The issue is that I don't have two views to animate between - only one view. Therefore when I try to animate displaying this view (when the next object is to be loaded), the visible view disappears, I get a blank screen - and then the view slides in from the right.
What I want instead is to have the existing view to slide out and be replaced by a new view (same View but with different content) to slide in from the right.
How should I go about it?
A: Looks to me like a combination of LayoutTransition and GestureDetector. You might even a ViewFlipper in there too.
The LayoutTransition has an animation feature you might want to look into.
A: I haven't been able to figure out how to use LayoutTransition in my case, so instead of having my View, I replaced it with ViewFlipper containing two copies of my View. When I need to replace the view with another, I keep track of which of the two is currently displayed, then update the other off-screen and then use standard "slide-from-left" and "slide-from-right" animation with showNext(). This is more complicated than I really wanted it to be and uses more memory, but it does the job.
A: The solution turned out to be very simple: ViewPager. I provide PageAdapter, which returns two similar views (same layout, different content) and ViewPager takes care of the rest. If I wanted to disable the swipe page changes, all I had to do is extend ViewPager, override onInterseptTouchListener and return false.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I see jQuery errors? When an error occurs in jQuery code, IE9, Firefox and Chrome's script debugging tools dont see them - is there a way to make them see jQuery errors?
A: I don't know if you got this, but jQuery is plain javascript.
Every error that is not caught by the code will be thrown.
Wait... caught?
Yes, you can always avoid throwing errors if you want to manipulate their behaviour. For example, to log it internally or simply give a nicer message to the end user, this is done using, what we call, the try-catch block.
try {
// you can do some pretty nasty stuff here
addNumbers(12, 10);
}
catch(err) {
// now that the error was thrown, you can "catch" it
// and play with it, but be nice.
alert("Ops, there was an error!\n\n" + err);
}
You will never see any error on the console with this.
Back to jQuery, everything is javascript, so you will see every thrown error right in the console of your favorite browser.
A: PROBLEM SOLVED
The errors I was referring to were infact not errors at all e.g. a selector for a non-existent element does in fact not fail at all, it simply returns an array with 0 objects in it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: ways to bind model classes in Objective-C (I hope someone will correct my terminology if I get it wrong -- I'm still sorting out terms)
I have a series of classes in my model. I need to get some data from a url (SatDataGetter) and combine it with a location and date specific calculation (DayCalculater), do some further calculations (DataMixer), some interpretation to make it user-understandable (Advisor), and then present the results in a view.
There are issues with setting up the dependencies and making sure that, for instance, the SatDataGetter has valid data before it gets called by DataMixer, before it gets called by.. you get the idea. Of course, if the location changes, I need to update the whole thing from the bottom up. At minimum I have to get a message to the ViewController and the Advisor to reload their data.
The research I've done suggests that NSNotification is one way to go, but I could also try Key-Value Observing. I found some old posts (2009) on KVO, suggesting some possible problems and difficulties with debugging. http://www.mikeash.com/pyblog/key-value-observing-done-right.html
What's the preferred method? What are the issues I should be considering in deciding --
For instance:
The SatDataGetter essentially returns a single number. KVO seems like a reasonable way for DataMixer to keep track of what that value is, but I don't think I want all the parent classes to be doing KVO on the dependent variables.
When do you choose an NSNotification and when KVO?
A: The difference between NSNotifications and Key-Value Observation is largely one of coupling, but there are also performance implications.
Anyone can subscribe to your NSNotifications. All they need to know is the string/key that you notify under. They don't need to know anything about your classes/object-graph etc. So when you want to notify a world that doesn't know about the details of your class, NSNotification is the way to go. For instance, if you're vending a framework to other developers, it's probably better to notify by NSNotification than by exposing the internals of your framework to the degree that might be necessary to allow consumers to Key-Value Observe your objects.
In order to KVO observe an object you first have to be able to get a reference to it, which is not strictly true of NSNotifications (but usually happens to be true in my experience.) Secondly, you need to know enough about the implementation to know what to observe. With NSNotification the notifier need only publish a notification string/key. With KVO, you need to know the name of a property of the object. Sure, someone could publish static strings and tell you "you can KVO me for these properties" but that effectively becomes an API contract that may be harder to maintain going forward. (Say, for instance, you want to remove that property in a future version -- then you have to rig up other things to continue to send those notifications and provide values when people call valueForKey: -- in short, once you do that, you can never change that property.)
The other thing to remember with these various degrees of coupling is that with KVO, there can be an expectation that the observer knows about the details of your classes/objects. After all, they're registering a very specific interest in your object; they claim to know what that means -- how it works. Therefore you might expect them to be sensitive to the performance implications. With NSNotifications, the consumer can observe your notification knowing virtually nothing about you, and may not be aware of performance implications of how they act in response to the notification.
The drawback shared between the two approaches is that, absent extra work, they're both delivered synchronously. The notifying object is at the mercy of what the observer chooses to do (synchronously) when it receives the notification. The two mechanisms differ here in that for NSNotification it's quite easy for the notifying object to use performSelector:afterDelay: to cause the notification to be sent "asynchronously" (with respect to the call that spawns the notification) on the next pass of the run loop (see also NSNotificationQueue). This is not as readily possible with KVO. This difference alone may be crucial in certain situation.
Generally, I find that the loose coupling of NSNotification lends itself to events that are either large-granule (i.e. potentially represent a large group of changes) or relatively infrequent. KVO notifications are, by their very nature, fine-grained. You're explicitly observing a change of a single property (per registration) on a single object. This has the potential to blow up the number of registrations and the number of notifications. Every observation has a performance cost to it.
Another shared drawback to both of these is debuggability. I mentioned in a comment above that KVO can be a challenge to debug, and it shares that challenge with NSNotificationCenter as well.
The key difference between these two and the delegate pattern is that delegate relationships are typically 1:1 (one delegate.) (Sure, you could have an array of delegates, but that's pretty uncommon, and debatably an anti-pattern.) NSNotification and KVO are both inherently 1:N (many observers.)
In closing, I always like to say, "use the highest level of abstraction that will get the job done." If you only need a 1:1 relationship, use a delegate. For 1:N notifications, if an NSNotification will work -- in other words if the desired coupling is low and/or the notifications are large-grained or infrequent, use NSNotifications. If the coupling is tight, or the need is fine grained, use KVO. Also remember that you can adapt a delegate pattern from 1:1 to 1:N by having the delegate send NSNotifiations. With NSNotifications and KVO, you can't really control who observes you or how many observers you have.
A: I generally use KVO to watch for changes to properties within an object - so, instead of overriding the setter for an object, I'll use KVO to fire the observe method on a change, and then call other methods at that point.
I tend to use NSNotifications to inform other objects that something has happened. In your example, I may have a singleton to handle the location stuff, and then send a notification when userLocation changes.
And, of course, you can also use the delegate pattern to notify another object of a change.
These aren't hard and fast rules though...I'm wont to change on a whim!
A: You probably don't need any of those strategies, you can probably get by with some sort of delegate hierarchy. If you are using core location or any other service that you can't get reliable data from synchronously, then you can use that as your starting point... if you have 2 such services, (getting http data, and Core Location for instance), Then you may have to perform some caching and delegation... i.e. last best location + current http data get pushed to the view.
A: How about NSOperations?
// create two ops, and set a dependency
DownloadOp *op = [[Download alloc] initWithURL:@"http://xxx"];
CalculationOp *op = [CalculationOp new];
[calculationOp addDependency:downloadOp];
// ... more steps
// add to the queue
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperation:downloadOp];
[queue addOperation:calculationOp];
// runloop for unit testing
while(!parserOp.isFinished) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:1]];
}
Inside the -[CalcuationOp start]:
// get the result from the previous step
id obj = [self.dependencies objectAtIndex:0];
if ([obj isKindOfClass:[DownloadOp class]]){
DownloadOp *op = (DownloadOp*) obj;
self.input = op.output;
}
Inside the AdvisorOp:
// update the GUI from the main thread
dispatch_queue_t mainQueue = dispatch_get_main_queue();
dispatch_async(mainQueue,^{
// update some UI element
});
Then listen to location updates on the CLLocationManager delegate to start the whole thing. I'm using this with the logic decoupled from the operations so I can unit test each part alone.
Benefit: it runs asynchronously and you can cancel the operations on the queue at any time. Downside: you have to learn NSOperation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I just check if a given username exists? I have an application that uses both LDAP and simple database authentication to log users in. Only if the user does not exists in the LDAP context, the application checks if he exists in the database. So I need a way to check if the users exists in LDAP, without knowing the password. I mention that usernames are unique.
I use this code, which works if I have a correct username and password. If the password OR the username are wrong, I get an exception. It would be ideal if I could get different exceptions, one if the username does not exist, other if the password provided is wrong.
String username = "test";
String password = "pass";
Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
environment.put(Context.PROVIDER_URL, "ldap://server.example.com:389");
environment.put(Context.SECURITY_AUTHENTICATION, "simple");
String user = username + "@example.com";
environment.put(Context.SECURITY_PRINCIPAL, user );
environment.put(Context.SECURITY_CREDENTIALS, password);
try
{
DirContext context = new InitialDirContext(environment);
String searchBase = "DC=server,DC=example,DC=COM";
String FILTER = "(&(objectClass=user)(objectCategory=person)((sAMAccountName=" + username + ")))";
SearchControls ctls = new SearchControls();
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> answer = context.search(searchBase, FILTER, ctls);
SearchResult result = answer.next();
Attribute email = result.getAttributes().get("mail");
Attribute cn = result.getAttributes().get("cn");
System.out.println(cn + " : " + email);
context.close();
}
catch (AuthenticationException a)
{
Logger.getLogger().info("Authentication failed: " + a.getExplanation());
}
catch (NamingException e)
{
Logger.getLogger().info("Failed to bind to LDAP: " + e.getExplanation());
}
A: You're searching for a user in the LDAP, using only his user name. But to authenticate to the LDAP, you're using the searched user name and his password.
Just use another (admin) user and password to authenticate, and return true if the search for the user returns something.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to dynamically display a list of SubReports from a DataSet in SSRS? Context
I am actually working on a project where I need to compose a report which will be designed from our custom tool. The user will compose this report using existing reports that he will put in particular order. So basically, to record the composed report design, we keep it in an object model that contains the list of underlying reports with their order.
Challenge
The goal is to simply display a list of SubReport which ReportName is retrieved from a DataSet.
What I tried
I did a DataSet which will return rows containing the order in which the report is displayed, the report path on the server and the report parameters if available. So I added a Tablix with a single cell which contains a SubReport. As the Tablix will iterate through all the DataSet rows I tried to set the ReportName of the SubReport. But unfortunaltely it looks like SubReport.ReportName does not accept values computed from the DataSet.
I tried this but it does not work:
...
<Tablix Name="ReportModuleTablix">
<DataSetName>ReportModules</DataSetName>
...
<TablixBody>
...
<TablixRows>
<TablixRow>
...
<TablixCells>
<TablixCell>
<CellContents>
<Rectangle Name="SubReportRectangle">
<ReportItems>
...
<Subreport Name="ModuleReport">
<ReportName>=Fields!Path.Value</ReportName>
</Subreport>
</ReportItems>
</Rectangle>
</CellContents>
</TablixCell>
</TablixCells>
</TablixRow>
</TablixRows>
</TablixBody>
...
</Tablix>
...
=Fields!Path.Value represents the report path for the current DataSet row.
I really need to be able to display a list of report parameterized from DataSet, therefore I would like to know how I could achieve my goal. I had a look at custom ReportItem but the documentation is pretty awkward and not really up to date.
Thanks.
A: We finally opted for RDL generation from code which means the SubReport items will be manually added by using the RDL object model but it required some hacking into internal classes (RdlSerializer).
I wrote about it in this article: https://github.com/Ucodia/Blog-CustomReportingServices
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: permutation computing in c++ I want to write a program that gets an integer n and prints all the permutations of 1,2,...,n.
I know there is a recursive way to do this and I know the overhead of function calls.
Is there any way to do this without recursion??
A: Yes, you can do it iteratively with std::next_permutation from <algorithm> as a while condition, or depending on how you set up the loop this may be one of the occasions where do...while is more appropriate.
A: #include <vector>
#include <algorithm>
std::vector<int> v = { 1,2,3,4,5,6,7,8,9,10 }; // see std::iota also
// important: sort v if not sorted
std::sort(v.begin(), v.end());
while (std::next_permutation(v.begin(), v.end()))
{
// use v (unique permutation)
}
// use v: first sorted position
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP & XML Read element by attribute value $xml = '<?xml version="1.0"?>
<entries>
<response>
<category>client</category>
<action>Greeting</action>
<code>1000</code>
<msg>Your Connection with API Server is Successful</msg>
<resData>
<data name="svDate">2010-10-10 02:27:14</data>
</resData>
</response>
<response>
<category>client</category>
<action>Login</action>
<code>1000</code>
<msg>Command completed successfully</msg>
<value>L116:no value</value>
</response>
<response>
<category>domain</category>
<action>InfoDomain</action>
<code>1000</code>
<msg>Command completed successfully</msg>
<value>L125:no value</value>
<resData>
<data name="domain">google.com</data>
<data name="crDate">2004-12-16</data>
<data name="exDate">2013-12-16</data>
</resData>
</response>
</entries>';
$xml = simplexml_load_string($xml);
$domain = $xml->response[2]->resData[0]->data[0];
$crdate = $xml->response[2]->resData[0]->data[1];
$exdate = $xml->response[2]->resData[0]->data[2];
With the above code i can get the values.
But how can i get the values by attribute value?
For example i want to get the values with something like this:
$domain = $xml->response[2]->resData[0]->data["domain"];
$crdate = $xml->response[2]->resData[0]->data["crdate"];
$exdate = $xml->response[2]->resData[0]->data["exdate"];
One more question.
If i have two elements with the same name?
For example i would like to parse the dns. How could i do it?
The xml code is like this:
<?xml version="1.0"?>
<entries>
<response>
<category>client</category>
<action>Greeting</action>
<code>1000</code>
<msg>Your Connection with API Server is Successful</msg>
<resData>
<data name="svDate">2010-10-10 02:27:14</data>
</resData>
</response>
<response>
<category>client</category>
<action>Login</action>
<code>1000</code>
<msg>Command completed successfully</msg>
<value>L116:no value</value>
</response>
<response>
<category>domain</category>
<action>InfoDomain</action>
<code>1000</code>
<msg>Command completed successfully</msg>
<value>L125:no value</value>
<resData>
<data name="domain">google.com</data>
<data name="crDate">2004-12-16</data>
<data name="exDate">2013-12-16</data>
<data name="dns">ns1.google.com</data>
<data name="dns">ns2.google.com</data>
</resData>
</response>
</entries>
As you can see the ns1 and ns2 have the same name. name="dns".
How can i parse each one in a different variable?
Thank you!
A: With the element["attribute"] syntax, attribute is the name of an attribute on the element. It is not the value of some randomly chosen attribute belonging to an element.
The example below creates an array containing a mapping for the data elements of name attribute value to text value.
$data = array();
foreach ($xml->response[2]->resData->data as $d) {
$data[strtolower($d['name'])] = (string) $d;
}
// Now you can access the values via $data['domain'], $data['crdate'], etc.
Nick, your code expects XML structured like:
<resData>
<data domain="google.com" crdate="2004-12-16" exdate="2013-12-16" />
</resData>
Edit due to question change
In a marvelous dose of eating my own words, due to the change in the question an XPath approach would be more appropriate (don't you love OPs who do that?).
You can easily get an array of the name="dns" elements with a basic XPath expression.
$xml = simplexml_load_string($xml);
$dns = $xml->xpath('response[category="domain"]/resData/data[@name="dns"]');
A: You can use XPath to to do queries against your XML, e.g.
$entries = simplexml_load_string($xml);
$dataElements = $entries->xpath('/entries/response/resData/data[@name="dns"]');
foreach ($dataElements as $dataElement) {
echo $dataElement;
}
The above XPath finds all <data> elements with a name attribute of "dns" that are direct children of the given element hierarchy, e.g.
<entries>
…
<response>
…
<resData>
…
<data name="dns">
IMO this is easier and more appropriate than having the extra step of copying over the values into an array which would disconnect it from the actual DOM tree and which you would have to repeat for all the elements you want to map this way. XPath is built-in. You just query and get the result.
Because $dataElements is an array, you can also access the elements in it individually with
echo $dataElements[0]; // prints "ns1.google.com"
echo $dataElements[1]; // prints "ns2.google.com"
Note that the $dataElements array actually contains SimpleXmlElements connected to the main document. Any changes you do to them will also be reflected in the main document.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to synchronize equal lines in two stringlists I have two stringlists that I wish to synchronize, so that equal lines get the same index, while different lines will be kept in the list where they originally were, and the other stringlist should get a "filler" for that index. Consider this example:
SL1: 1,1,2,3,5,8
SL2: 1,3,5,7,9
procedure SyncStringlists(aSL1,aSL2 : TStringList; aFill : string = '-');
The procedure should change the lists to this
SL1: 1,1,2,3,5,8,-,-
SL2: 1,-,-,3,5,-,7,9
or, if the lists are sorted, to this
SL1: 1,1,2,3,5,-,8,-
SL2: 1,-,-,3,5,7,',9
How should I go about doing this?
A: Try this for the case where your lists are monotone increasing.
procedure SyncStringlists(SL1, SL2: TStringList; const Fill: string='-');
var
i1, i2: Integer;
begin
i1 := 0;
i2 := 0;
while (i1<SL1.Count) and (i2<SL2.Count) do begin
if SL1[i1]<SL2[i2] then begin
SL2.Insert(i2, Fill);
end else if SL1[i1]>SL2[i2] then begin
SL1.Insert(i1, Fill);
end;
inc(i1);
inc(i2);
end;
while SL1.Count<SL2.Count do begin
SL1.Add(Fill);
end;
while SL2.Count<SL1.Count do begin
SL2.Add(Fill);
end;
end;
A: I actually managed to make a method that suits my need:
procedure SyncStringlists(aSL1,aSL2 : TStringList; aFill : string = '-');
var
I,J : integer;
begin
I := 0;
J := 0;
aSL1.Sort;
aSL2.Sort;
while (I<aSL1.Count) and (J<aSL2.Count) do
begin
if aSL1[I] > aSL2[J] then
aSL1.Insert(I,aFill)
else if aSL1[I] < aSL2[J] then
aSL2.Insert(J,aFill);
inc(I);
inc(J);
end;
while aSL1.Count < aSL2.Count do aSL1.Add(aFill);
while aSL2.Count < aSL1.Count do aSL2.Add(aFill);
end;
It requires the lists to be sorted, but NOT to have the sorted property true (because then we can't insert into it)
Sample run:
SL1: 1,1,2,3,5,8,a,b,c,d,e,f
SL2: 1,3,5,7,9,e,f,g,h,i
synced:
SL1: 1,1,2,3,5,-,8,-,a,b,c,d,e,f,-,-,-
SL2: 1,-,-,3,5,7,-,9,-,-,-,-,e,f,g,h,i
A: I hope some kind of this (Levenshtein distance) algorithm can help you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595400",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Oracle OCI - failing with ORA-12705 when running as another user I've got a C application using OCI to talk to a database. I'm using the instant client method so there is no standalone Oracle installation on the server - just a couple of libraries that the application is linked against.
Normally, the application runs as user dai, and everything works just fine. But if the application is run as another user (in group dai), it fails to run, reporting:
Error while trying to retrieve text for error ORA-12705
So I can imagine that this is a permissions error, but I'm not sure what files it is trying to access. The permissions of the Oracle libraries are
dai:/dai/oracle/lib> ls -l
total 201872
-rwxrwxrwx 1 dai dai 24719097 16 Feb 2009 libclntsh.a
-rwxrwxrwx 1 dai dai 5972457 16 Feb 2009 libocci.a
-rwxrwxrwx 1 dai dai 72651344 04 Jun 2010 libociei.so
As you can guess the main OCI libraries are statically linked, but there is one dynamically linked library (not sure why, but the AIX instantclient package came with these files...). My LIBPATH looks OK from both users:
LIBPATH=/dai/oracle/lib
Which other permissions do I need to check?
EDIT: I have just tried running truss (AIX equivalent of Linux strace) to see what is happening. I couldn't see it reading any unexpected files when running as the dai user. Truss seemed to have problems tracing a set-uid program - permissions on the C application were set like this:
dai:/dai/bin> ls -l stats_backup
-rwsrwsr-x 1 dai dai 6173358 Aug 12 10:08 stats_backup
So I did chmod a-s and tried again, and it now works!
So the program runs OK without the s-bit, but as soon as I put it back, it breaks again. I can't run truss with the s-bit set, which makes it difficult to find out why this should be. The program doesn't work in other circumstances without the s-bit set, so this isn't a viable solution, but hopefully a pointer to where the problem may be.
A: There are presumably some Oracle data files located somewhere that your other users don't have access to. According to Google, ORA-12705 happens because the NLS data files (wherever they are) can't be accessed, or perhaps there is some environment variable issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Signing mixed code assembly I have a mixed assambly written in C++ managed and unmanaged. To sign this assembly I use delayed signing with the following Post-build event:
sn -R $(TargetPath) $(ProjectDir)Fischer.snk
This works without any problems on my own PC (VS2010 english, Windows XP 32Bit).
If I transfer this project on another PC (VS2010 german, Win7 32Bit), this build step failes with an error message.
Fehler 1 error MSB3073: Der Befehl "sn -R C:\Daten\APRGX\DotNet\VisualData\Master3DControlClasses\Project\Debug\Fischer.APRGX.MathAlg.Native.dll c:\Daten\APRGX\DotNet\MathAlg\Native\Fischer.snk :VCEnd" wurde mit dem Code 1 beendet. C:\Program Files\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets 113 6 Fischer.APRGX.MathAlg.Native
What can be the reason?
Edit:
Starting the tool in command prompt it says:
"C:\Daten\APRGX\DotNet\VisualData\Master3DControlClasses\Project\Debug\Fischer.APRGX.MathAlg.Native.dll" stellt keine Assembly mit einem starken Namen dar.
It says that the dll doesn't have a strong name. I don't understand that, because the same project builds without problems on my first machine.
A: I found the solution:
The problem was that on my original PC I'm using VS2010 and on the second PC I'm using VS2010 SP1.
VS2010 without SP1 stores in project file:
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>
</AdditionalDependencies>
<KeyFile>$(ProjectDir)Fischer.snk</KeyFile>
<DelaySign>true</DelaySign>
</Link>
VS2010 with SP1 stores:
<LinkKeyFile>$(ProjectDir)Fischer.snk</LinkKeyFile>
<LinkDelaySign>true</LinkDelaySign>
So VS2010 with SP1 igonores the /DELAYSIGN option that was set without SP1. And so sn.exe couldn't sign the assembly.
Installing SP1 on my original PC and setting the delay sign option again solved the problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: String operators C++ I was wondering if you can compare two strings using ==. I have a function which takes in a const value &item and since its a value type there is no way I can determine what type the value is, hence if the value type is a string, == may not work.
Hence the question, what would be the best way to tackle this problem? I was thinking of overloading the == operator, but is there an easy way?
A: In C++ operator == for std::string compares the content of the strings.
A: If the string is a std::string it already has an operator== defined. It compares the contents of the strings.
If it is a C string (char*) the comparison is a pointer comparison that tells us if the pointers points to the same string. You cannot overload this either as it is a built in operator.
A: There is already a bunch of operators implemented for std::string (compare std::string and const char* etc.)
If you have a custom type, then you'll need to provide operators for those.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Honeycomb ActionBar Title Shadow How can I add shadow under the title text?
The following xml doesn't do the trick.
<style name="Theme" parent="android:style/Theme.Holo.Light">
<item name="android:actionBarStyle">@style/ActionBar</item>
<item name="android:windowBackground">@drawable/background</item>
</style>
<style name="ActionBar" parent="android:style/Widget.Holo.ActionBar">
<item name="android:background">@drawable/action_bar</item>
<item name="android:titleTextStyle">@style/TitleTextStyle</item>
</style>
<style name="TitleTextStyle" parent="android:style/TextAppearance.Large">
<item name="android:textColor">@color/title_text_color</item>
<item name="android:textStyle">bold</item>
<item name="android:shadowColor">@color/title_shadow_color</item>
<item name="android:shadowDx">0</item>
<item name="android:shadowDy">0</item>
<item name="android:shadowRadius">1</item>
</style>
A: It's there, you just don't see it. You need to displace the shadow using either (or both) shadowDx or shadowDy
(wow, quite an old question, how come no answers except the totally relevant comment by @James)
A: Adding a shadow under the title of the (native) ActionBar works starting with API Level 18 (Android Jelly Bean 4.3). Works fine in API Level 19 (Android KitKat 4.4).
See my answer for XML code and a screenshot.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: How do i create a dropdown menu which puts data from an array in a textfield I want to add this functionality to my form. when a option from a dropdown menu is selected i want it to input the text field above with the corresponding info.
objBMW = {
"Sedan":"5-series",
"Convertible":"6-series",
"Truck":"X5",
"Coupe":"3-series",
"Hatchback":"5-series GT"
};
<form name="form1" action="formhandler">
<input type="text" name="typecar">
<select name="BMWCars">
<option value="Sedan">Sedan</option> // when this option is chosen put string "5-series" in textfield above
<option value="Convertible">Convertible</option> // when this option is chosen put string "6-series" in textfield above
<option value="Truck">Truck</option> // when this option is chosen put string "X5" in textfield above
<option value="Coupe">Coupe</option> // when this option is chosen put string "3-series" in textfield above
<option value="Hatchback">Hatchback</option> // when this option is chosen put string "5-series GT" in textfield above
</select>
A: Javascript:
document.forms.form1.BMWCars.onchange = function(){
document.forms.form1.typecar.value = objBMW[this.value];
}
http://jsfiddle.net/xZsc7/
A: I would do it like this:
<input type="text" name="typecar" id="typecar" />
<?php
$objBMW = array('Sedan' => '5-series', 'Convertible' => '6-series');
?>
<select name="BMWCars" id="BMWCars">
<?php
foreach($objBMW as $key => $value)
{
echo '<option value="'.$value.'">'.$key.'</option>';
}
?>
</select>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#BMWCars').change(function() {
$('#typecar').val($("#BMWCars option:selected").val());
}).trigger('change');
});
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What's the way to access the assets-folder in an Android project? I access to an XML file placed in a project folder (for instance 'assets') for open and read data from file.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = factory.newDocumentBuilder();
InputStream iS = this.getAssets().open("myFile.xml");
Document doc = docBuilder.parse(iS);
but If I want to edit the file, I can't find the path to save it.
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
//create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
String xmlString = sw.toString();
OutputStream f0;
byte buf[] = xmlString.getBytes();
**f0 = new FileOutputStream("/assets/wines.xml");**
//f0 = new FileOutputStream("file:///assets/wines.xml");
for(int i=0;i<buf .length;i++) {
f0.write(buf[i]);
}
f0.close();
buf = null;
I obtain always a FileNotFoundException at line:
f0 = new FileOutputStream("/assets/wines.xml");
Any ideas? Thanks!
A: If you are trying to edit or write file to assets or raw folder. I guess it is not possible. It cannot be done
A: Bettery try saving it to sd card or internal storage
Use File sdDir = [Environment.getExternalStorageDirectory()][1]; to get the sdcard path.
And don't forget to give permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: JQuery issues with SharePoint I am having a strange problem with jQuery inside sharepoint. My jQuery code works fine in Web Applications but when I use the same code on a Web Part it creates problem.
Here is the problem with jQuery in Web Parts. I have external JavaScript file which I reference on my web part.
This is my function in a separate JavaScript file.
function CallJS() {
alert($("#txt1")); **// It returns the object**
alert($('#txt1').attr('value')); **// Always return 'undefined'**
return false;
}
My development environment is VS2008, SharePoint 2007 and jQuery version is 1.4.4.
A: First try to pass value using jquery attribute like this $('#txt1').attr('value','Test')
after passing value try this $('#txt1').attr('value') it returs your value.
In you case solution is that use $('#txt1').val(), or try to pass value dynamically than you can access that value using attribute method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Convert Dictionary To Anonymous Object? First, and to make things clearer I'll explain my scenario from the top:
I have a method which has the following signature:
public virtual void SendEmail(String from, List<String> recepients, Object model)
What I want to do is generate an anonymous object which has the properties of the model object along with the first two parameters as well. Flattening the model object into a PropertyInfo[] is very straightforward. Accordingly, I thought of creating a Dictionary which would hold the PropertyInfo's and the first two params, and then be converted into the anonymous object where the key is the name of the property and the value is the actual value of the property.
Is that possible? Any other suggestions?
A: Slightly more modular version of svick's answer, using a couple extension methods:
public static class Extensions
{
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> items)
{
foreach (var item in items)
{
collection.Add(item);
}
}
public static dynamic ToDynamicObject(this IDictionary<string, object> source)
{
ICollection<KeyValuePair<string, object>> someObject = new ExpandoObject();
someObject.AddRange(source);
return someObject;
}
}
A: The code below handles sub-dictionaries and converts them to nested dynamic objects as well:
[return: NotNullIfNotNull(nameof(dictionary))]
static dynamic? ToDynamic(IReadOnlyDictionary<string, object?>? dictionary) =>
dictionary?.Aggregate(
(IDictionary<string, object?>)new ExpandoObject(),
(obj, i) =>
{
if (i.Value is IReadOnlyDictionary<string, object?> nestedDictionary)
obj.Add(new(i.Key, ToDynamic(nestedDictionary)));
else
obj.Add(i);
return obj;
});
This approach allows you to access the contents of nested dictionaries just by accessing the dynamic object itself:
var record = ToDynamic(...);
string cityName = record.city.name;
A: I tried to do this in one statement with a reduce function (Aggregate in Linq). The code below does the same as the accepted answer:
var dict = new Dictionary<string, object> { { "Property", "foo" } };
dynamic eo = dict.Aggregate(new ExpandoObject() as IDictionary<string, Object>,
(a, p) => { a.Add(p); return a; });
string value = eo.Property;
A: Anonymous objects are one that generated for you by compiler. You cannot generate dynamically create one. On the other hand you can emit such object, but I really do not think this is good idea.
May be you can try dynamic objects? The result will be an object with all properties you need.
A: The credit here goes to the accepted answer. Adding this because I wanted to turn a List< Dictionary< string,object >> into a List< dynamic>. The purpose is for pulling records from a database table. Here is what I did.
public static List<dynamic> ListDictionaryToListDynamic(List<Dictionary<string,object>> dbRecords)
{
var eRecords = new List<dynamic>();
foreach (var record in dbRecords)
{
var eRecord = new ExpandoObject() as IDictionary<string, object>;
foreach (var kvp in record)
{
eRecord.Add(kvp);
}
eRecords.Add(eRecord);
}
return eRecords;
}
A: If you really want to convert the dictionary to an object that has the items of the dictionary as properties, you can use ExpandoObject:
var dict = new Dictionary<string, object> { { "Property", "foo" } };
var eo = new ExpandoObject();
var eoColl = (ICollection<KeyValuePair<string, object>>)eo;
foreach (var kvp in dict)
{
eoColl.Add(kvp);
}
dynamic eoDynamic = eo;
string value = eoDynamic.Property;
A: If you have a class you want to covert the dictionary too, you can use the following to convert a dictionary to an object of that class:
Example class:
public class Properties1
{
public string Property { get; set; }
}
The solution:
JavaScriptSerializer serializer = new JavaScriptSerializer();
Dictionary<string, object> dict = new Dictionary<string, object> { { "Property", "foo" } };
Properties1 properties = serializer.ConvertToType<Properties1>(dict);
string value = properties.Property;
You could also use a method like this to build the object from the dictionary, obviously this also requires you to have a class.
private static T DictionaryToObject<T>(IDictionary<string, object> dict) where T : new()
{
T t = new T();
PropertyInfo[] properties = t.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
if (!dict.Any(x => x.Key.Equals(property.Name,
StringComparison.InvariantCultureIgnoreCase)))
continue;
KeyValuePair<string, object> item = dict.First(x => x.Key.Equals(property.Name,
StringComparison.InvariantCultureIgnoreCase));
Type tPropertyType = t.GetType().GetProperty(property.Name).PropertyType;
Type newT = Nullable.GetUnderlyingType(tPropertyType) ?? tPropertyType;
object newA = Convert.ChangeType(item.Value, newT);
t.GetType().GetProperty(property.Name).SetValue(t, newA, null);
}
return t;
}
However if you do not have the class you can create a dynamic object from a dictionary like this:
private static dynamic DictionaryToObject(Dictionary<string, object> dict)
{
IDictionary<string, object> eo = (IDictionary<string, object>)new ExpandoObject();
foreach (KeyValuePair<string, object> kvp in dict)
{
eo.Add(kvp);
}
return eo;
}
You can use it like this:
Dictionary<string, object> dict = new Dictionary<string, object> {{ "Property", "foo" }};
dynamic properties = DictionaryToObject(dict);
string value = properties.Property;
A: If you want to convert Dictionary<string, object> To Anonymous System.Object. You can use this method:
public static object FromDictToAnonymousObj<TValue>(IDictionary<string, TValue> dict)
{
var types = new Type[dict.Count];
for (int i = 0; i < types.Length; i++)
{
types[i] = typeof(TValue);
}
// dictionaries don't have an order, so we force an order based
// on the Key
var ordered = dict.OrderBy(x => x.Key).ToArray();
string[] names = Array.ConvertAll(ordered, x => x.Key);
Type type = AnonymousType.CreateType(types, names);
object[] values = Array.ConvertAll(ordered, x => (object)x.Value);
object obj = type.GetConstructor(types).Invoke(values);
return obj;
}
like this:
var dict = new Dictionary<string, string>
{
{"Id", "1"},
{"Title", "My title"},
{"Description", "Blah blah blah"},
};
object obj1 = FromDictToAnonymousObj(dict);
to obtain your object.
Where AnonymousType class code is:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
/// <summary>
/// The code generated should be nearly equal to the one generated by
/// csc 12.0.31101.0 when compiling with /optimize+ /debug-. The main
/// difference is in the GetHashCode() (the base init_hash used is
/// compiler-dependant) and in the maxstack of the generated methods.
/// Note that Roslyn (at least the one present at
/// tryroslyn.azurewebsites.net) generates different code for anonymous
/// types.
/// </summary>
public static class AnonymousType
{
private static readonly ConcurrentDictionary<string, Type> GeneratedTypes = new ConcurrentDictionary<string, Type>();
private static readonly AssemblyBuilder AssemblyBuilder;
private static readonly ModuleBuilder ModuleBuilder;
private static readonly string FileName;
// Some objects we cache
private static readonly CustomAttributeBuilder CompilerGeneratedAttributeBuilder = new CustomAttributeBuilder(typeof(CompilerGeneratedAttribute).GetConstructor(Type.EmptyTypes), new object[0]);
private static readonly CustomAttributeBuilder DebuggerBrowsableAttributeBuilder = new CustomAttributeBuilder(typeof(DebuggerBrowsableAttribute).GetConstructor(new[] { typeof(DebuggerBrowsableState) }), new object[] { DebuggerBrowsableState.Never });
private static readonly CustomAttributeBuilder DebuggerHiddenAttributeBuilder = new CustomAttributeBuilder(typeof(DebuggerHiddenAttribute).GetConstructor(Type.EmptyTypes), new object[0]);
private static readonly ConstructorInfo ObjectCtor = typeof(object).GetConstructor(Type.EmptyTypes);
private static readonly MethodInfo ObjectToString = typeof(object).GetMethod("ToString", BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null);
private static readonly ConstructorInfo StringBuilderCtor = typeof(StringBuilder).GetConstructor(Type.EmptyTypes);
private static readonly MethodInfo StringBuilderAppendString = typeof(StringBuilder).GetMethod("Append", BindingFlags.Instance | BindingFlags.Public, null, new[] { typeof(string) }, null);
private static readonly MethodInfo StringBuilderAppendObject = typeof(StringBuilder).GetMethod("Append", BindingFlags.Instance | BindingFlags.Public, null, new[] { typeof(object) }, null);
private static readonly Type EqualityComparer = typeof(EqualityComparer<>);
private static readonly Type EqualityComparerGenericArgument = EqualityComparer.GetGenericArguments()[0];
private static readonly MethodInfo EqualityComparerDefault = EqualityComparer.GetMethod("get_Default", BindingFlags.Static | BindingFlags.Public, null, Type.EmptyTypes, null);
private static readonly MethodInfo EqualityComparerEquals = EqualityComparer.GetMethod("Equals", BindingFlags.Instance | BindingFlags.Public, null, new[] { EqualityComparerGenericArgument, EqualityComparerGenericArgument }, null);
private static readonly MethodInfo EqualityComparerGetHashCode = EqualityComparer.GetMethod("GetHashCode", BindingFlags.Instance | BindingFlags.Public, null, new[] { EqualityComparerGenericArgument }, null);
private static int Index = -1;
static AnonymousType()
{
var assemblyName = new AssemblyName("AnonymousTypes");
FileName = assemblyName.Name + ".dll";
AssemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
ModuleBuilder = AssemblyBuilder.DefineDynamicModule("AnonymousTypes", FileName);
}
public static void Dump()
{
AssemblyBuilder.Save(FileName);
}
/// <summary>
///
/// </summary>
/// <param name="types"></param>
/// <param name="names"></param>
/// <returns></returns>
public static Type CreateType(Type[] types, string[] names)
{
if (types == null)
{
throw new ArgumentNullException("types");
}
if (names == null)
{
throw new ArgumentNullException("names");
}
if (types.Length != names.Length)
{
throw new ArgumentException("names");
}
// Anonymous classes are generics based. The generic classes
// are distinguished by number of parameters and name of
// parameters. The specific types of the parameters are the
// generic arguments. We recreate this by creating a fullName
// composed of all the property names, separated by a "|"
string fullName = string.Join("|", names.Select(x => Escape(x)));
Type type;
if (!GeneratedTypes.TryGetValue(fullName, out type))
{
// We create only a single class at a time, through this lock
// Note that this is a variant of the double-checked locking.
// It is safe because we are using a thread safe class.
lock (GeneratedTypes)
{
if (!GeneratedTypes.TryGetValue(fullName, out type))
{
int index = Interlocked.Increment(ref Index);
string name = names.Length != 0 ? string.Format("<>f__AnonymousType{0}`{1}", index, names.Length) : string.Format("<>f__AnonymousType{0}", index);
TypeBuilder tb = ModuleBuilder.DefineType(name, TypeAttributes.AnsiClass | TypeAttributes.Class | TypeAttributes.AutoLayout | TypeAttributes.NotPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit);
tb.SetCustomAttribute(CompilerGeneratedAttributeBuilder);
GenericTypeParameterBuilder[] generics = null;
if (names.Length != 0)
{
string[] genericNames = Array.ConvertAll(names, x => string.Format("<{0}>j__TPar", x));
generics = tb.DefineGenericParameters(genericNames);
}
else
{
generics = new GenericTypeParameterBuilder[0];
}
// .ctor
ConstructorBuilder constructor = tb.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig, CallingConventions.HasThis, generics);
constructor.SetCustomAttribute(DebuggerHiddenAttributeBuilder);
ILGenerator ilgeneratorConstructor = constructor.GetILGenerator();
ilgeneratorConstructor.Emit(OpCodes.Ldarg_0);
ilgeneratorConstructor.Emit(OpCodes.Call, ObjectCtor);
var fields = new FieldBuilder[names.Length];
// There are two for cycles because we want to have
// all the getter methods before all the other
// methods
for (int i = 0; i < names.Length; i++)
{
// field
fields[i] = tb.DefineField(string.Format("<{0}>i__Field", names[i]), generics[i], FieldAttributes.Private | FieldAttributes.InitOnly);
fields[i].SetCustomAttribute(DebuggerBrowsableAttributeBuilder);
// .ctor
constructor.DefineParameter(i + 1, ParameterAttributes.None, names[i]);
ilgeneratorConstructor.Emit(OpCodes.Ldarg_0);
if (i == 0)
{
ilgeneratorConstructor.Emit(OpCodes.Ldarg_1);
}
else if (i == 1)
{
ilgeneratorConstructor.Emit(OpCodes.Ldarg_2);
}
else if (i == 2)
{
ilgeneratorConstructor.Emit(OpCodes.Ldarg_3);
}
else if (i < 255)
{
ilgeneratorConstructor.Emit(OpCodes.Ldarg_S, (byte)(i + 1));
}
else
{
// Ldarg uses a ushort, but the Emit only
// accepts short, so we use a unchecked(...),
// cast to short and let the CLR interpret it
// as ushort
ilgeneratorConstructor.Emit(OpCodes.Ldarg, unchecked((short)(i + 1)));
}
ilgeneratorConstructor.Emit(OpCodes.Stfld, fields[i]);
// getter
MethodBuilder getter = tb.DefineMethod(string.Format("get_{0}", names[i]), MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName, CallingConventions.HasThis, generics[i], Type.EmptyTypes);
ILGenerator ilgeneratorGetter = getter.GetILGenerator();
ilgeneratorGetter.Emit(OpCodes.Ldarg_0);
ilgeneratorGetter.Emit(OpCodes.Ldfld, fields[i]);
ilgeneratorGetter.Emit(OpCodes.Ret);
PropertyBuilder property = tb.DefineProperty(names[i], PropertyAttributes.None, CallingConventions.HasThis, generics[i], Type.EmptyTypes);
property.SetGetMethod(getter);
}
// ToString()
MethodBuilder toString = tb.DefineMethod("ToString", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, CallingConventions.HasThis, typeof(string), Type.EmptyTypes);
toString.SetCustomAttribute(DebuggerHiddenAttributeBuilder);
ILGenerator ilgeneratorToString = toString.GetILGenerator();
ilgeneratorToString.DeclareLocal(typeof(StringBuilder));
ilgeneratorToString.Emit(OpCodes.Newobj, StringBuilderCtor);
ilgeneratorToString.Emit(OpCodes.Stloc_0);
// Equals
MethodBuilder equals = tb.DefineMethod("Equals", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, CallingConventions.HasThis, typeof(bool), new[] { typeof(object) });
equals.SetCustomAttribute(DebuggerHiddenAttributeBuilder);
equals.DefineParameter(1, ParameterAttributes.None, "value");
ILGenerator ilgeneratorEquals = equals.GetILGenerator();
ilgeneratorEquals.DeclareLocal(tb);
ilgeneratorEquals.Emit(OpCodes.Ldarg_1);
ilgeneratorEquals.Emit(OpCodes.Isinst, tb);
ilgeneratorEquals.Emit(OpCodes.Stloc_0);
ilgeneratorEquals.Emit(OpCodes.Ldloc_0);
Label equalsLabel = ilgeneratorEquals.DefineLabel();
// GetHashCode()
MethodBuilder getHashCode = tb.DefineMethod("GetHashCode", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, CallingConventions.HasThis, typeof(int), Type.EmptyTypes);
getHashCode.SetCustomAttribute(DebuggerHiddenAttributeBuilder);
ILGenerator ilgeneratorGetHashCode = getHashCode.GetILGenerator();
ilgeneratorGetHashCode.DeclareLocal(typeof(int));
if (names.Length == 0)
{
ilgeneratorGetHashCode.Emit(OpCodes.Ldc_I4_0);
}
else
{
// As done by Roslyn
// Note that initHash can vary, because
// string.GetHashCode() isn't "stable" for
// different compilation of the code
int initHash = 0;
for (int i = 0; i < names.Length; i++)
{
initHash = unchecked(initHash * (-1521134295) + fields[i].Name.GetHashCode());
}
// Note that the CSC seems to generate a
// different seed for every anonymous class
ilgeneratorGetHashCode.Emit(OpCodes.Ldc_I4, initHash);
}
for (int i = 0; i < names.Length; i++)
{
// Equals()
Type equalityComparerT = EqualityComparer.MakeGenericType(generics[i]);
MethodInfo equalityComparerTDefault = TypeBuilder.GetMethod(equalityComparerT, EqualityComparerDefault);
MethodInfo equalityComparerTEquals = TypeBuilder.GetMethod(equalityComparerT, EqualityComparerEquals);
ilgeneratorEquals.Emit(OpCodes.Brfalse_S, equalsLabel);
ilgeneratorEquals.Emit(OpCodes.Call, equalityComparerTDefault);
ilgeneratorEquals.Emit(OpCodes.Ldarg_0);
ilgeneratorEquals.Emit(OpCodes.Ldfld, fields[i]);
ilgeneratorEquals.Emit(OpCodes.Ldloc_0);
ilgeneratorEquals.Emit(OpCodes.Ldfld, fields[i]);
ilgeneratorEquals.Emit(OpCodes.Callvirt, equalityComparerTEquals);
// GetHashCode();
MethodInfo EqualityComparerTGetHashCode = TypeBuilder.GetMethod(equalityComparerT, EqualityComparerGetHashCode);
ilgeneratorGetHashCode.Emit(OpCodes.Stloc_0);
ilgeneratorGetHashCode.Emit(OpCodes.Ldc_I4, -1521134295);
ilgeneratorGetHashCode.Emit(OpCodes.Ldloc_0);
ilgeneratorGetHashCode.Emit(OpCodes.Mul);
ilgeneratorGetHashCode.Emit(OpCodes.Call, EqualityComparerDefault);
ilgeneratorGetHashCode.Emit(OpCodes.Ldarg_0);
ilgeneratorGetHashCode.Emit(OpCodes.Ldfld, fields[i]);
ilgeneratorGetHashCode.Emit(OpCodes.Callvirt, EqualityComparerGetHashCode);
ilgeneratorGetHashCode.Emit(OpCodes.Add);
// ToString()
ilgeneratorToString.Emit(OpCodes.Ldloc_0);
ilgeneratorToString.Emit(OpCodes.Ldstr, i == 0 ? string.Format("{{ {0} = ", names[i]) : string.Format(", {0} = ", names[i]));
ilgeneratorToString.Emit(OpCodes.Callvirt, StringBuilderAppendString);
ilgeneratorToString.Emit(OpCodes.Pop);
ilgeneratorToString.Emit(OpCodes.Ldloc_0);
ilgeneratorToString.Emit(OpCodes.Ldarg_0);
ilgeneratorToString.Emit(OpCodes.Ldfld, fields[i]);
ilgeneratorToString.Emit(OpCodes.Box, generics[i]);
ilgeneratorToString.Emit(OpCodes.Callvirt, StringBuilderAppendObject);
ilgeneratorToString.Emit(OpCodes.Pop);
}
// .ctor
ilgeneratorConstructor.Emit(OpCodes.Ret);
// Equals()
if (names.Length == 0)
{
ilgeneratorEquals.Emit(OpCodes.Ldnull);
ilgeneratorEquals.Emit(OpCodes.Ceq);
ilgeneratorEquals.Emit(OpCodes.Ldc_I4_0);
ilgeneratorEquals.Emit(OpCodes.Ceq);
}
else
{
ilgeneratorEquals.Emit(OpCodes.Ret);
ilgeneratorEquals.MarkLabel(equalsLabel);
ilgeneratorEquals.Emit(OpCodes.Ldc_I4_0);
}
ilgeneratorEquals.Emit(OpCodes.Ret);
// GetHashCode()
ilgeneratorGetHashCode.Emit(OpCodes.Stloc_0);
ilgeneratorGetHashCode.Emit(OpCodes.Ldloc_0);
ilgeneratorGetHashCode.Emit(OpCodes.Ret);
// ToString()
ilgeneratorToString.Emit(OpCodes.Ldloc_0);
ilgeneratorToString.Emit(OpCodes.Ldstr, names.Length == 0 ? "{ }" : " }");
ilgeneratorToString.Emit(OpCodes.Callvirt, StringBuilderAppendString);
ilgeneratorToString.Emit(OpCodes.Pop);
ilgeneratorToString.Emit(OpCodes.Ldloc_0);
ilgeneratorToString.Emit(OpCodes.Callvirt, ObjectToString);
ilgeneratorToString.Emit(OpCodes.Ret);
type = tb.CreateType();
type = GeneratedTypes.GetOrAdd(fullName, type);
}
}
}
if (types.Length != 0)
{
type = type.MakeGenericType(types);
}
return type;
}
private static string Escape(string str)
{
// We escape the \ with \\, so that we can safely escape the
// "|" (that we use as a separator) with "\|"
str = str.Replace(@"\", @"\\");
str = str.Replace(@"|", @"\|");
return str;
}
}
Reference: https://stackoverflow.com/a/29428640/2073920
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "98"
}
|
Q: Where to put js files in CodeIgniter
Possible Duplicate:
Where should someone put the static files such as CS, JS and images in the Codeigniter folder structure?
I have few JavaScript files in my codiginter project. Currently the js files are in a direcotry in the app root. I call the js files by "../js/jq.js". Is it right way to include js files?
or
Where to put my own javascript files in the codigniter directory structure???
What is the best practices???
A: See this similar question:-
Where should someone put the static files such as CS, JS and images in the Codeigniter folder structure?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: how to add percentage completion on parallel nested loops? for example, i wish I can see 1% ~ 100%, how could I do that?
Parallel.For<Dictionary<int, long>>(0, r1, () => new Dictionary<int, long>(), (j, loop, tmpWinRange) =>
{
for (int k = 0; k < r2; k++)
for (int l = 0; l < r3; l++)
for (int m = 0; m < r4; m++)
{
int pay = GetPay(j, k, l, m);
tmpWinRange[pay]++;
}
return tmpWinRange;
},
(x) => { tmpWinRangeCollection.Add(x); }
);
A: How about using an interlocked increment to update the progress?
int progressCount = 0;
Parallel.For<Dictionary<int, long>>(0, r1, () => new Dictionary<int, long>(),
(j, loop, tmpWinRange) =>
{
for (int k = 0; k < r2; k++)
for (int l = 0; l < r3; l++)
for (int m = 0; m < r4; m++)
{
int pay = GetPay(j, k, l, m);
tmpWinRange[pay]++;
}
Interlocked.Increment(ref progressCount);
return tmpWinRange;
},
(x) => { tmpWinRangeCollection.Add(x); }
);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get total memory usage in blackberry How can I get the Total memory usage by all running applications? Basically I want to find whether the memory usage is greater than 30% or above.
A: As suggested by Rafael, you can make use of the Memory class. More specifically, you can use the following which will help you:
Memory.getRAMStats().getFree();
Memory.getRAMStats().getAllocated());
If you compare the two mathematically, you can get the percentage from that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to load options.html in jQuery-colorbox, upon a context menu item click? I am adding 'options' to my chrome extension. I wonder how can I user colorbox) from background page or content scripts, when context menu item is clicked.
I have spent more than a day on this without success. Is there anybody who has done this? Any help is appreciated.
A: While you certainly can't use this from a background page, since colorbox shows UI, you have a few options from a content script:
*
*You could do an XHR to fetch the contents of the background page (chrome.extension.getURL may be helpful) and write the contents of the result into the colorbox.
*You could embed an <iframe src="/path/to/options.html"> in your colorbox.
I'm assuming you know how to bind JS functions to context menus? Just in case, the contextMenu docs.
Have you tried either of these options?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: iPhone - Can't adjust sound volume with hard buttons When my app is launched (no sound emitted, Ambiant category set for AudioSession), using the up and down volume button on the iPhone does not do anything :
- on screen, nothing is displayed (I mean, the iOS black and white "slider" overlay does not appear to show me that volume is changing).
- in app, after playing with hard buttons, no impact on the sound volume when some sound is played (I use an AVAudioPlayer)
- this is the same if I quit the app, adjust the sound volume (onscreen "slider"overlay shows up to show me that the sound level have decreased for example), kill the app and relaunch it : same sound level that before
Using those hard buttons work though on the springboard and into other apps ("slider" overlay is displayed and volume is changing).
What is the problem with my app ?
As far as I've seen, many app, and angry birds for an example, make sounds, does not have a hard slider to change it's volume when playing game, and sound can be adjusted just playing with hard buttons.
A: I got some users of my app with the same problem, it was not my code but their iPhone settings:
Go to Settings->Sound->Change with Buttons and set it to Off
A: How your app behaves with that stuff depends on how you have set up your audio session. There are as I recall five different categories to choose from. Which category you choose affects how your app behaves with respect to hardware buttons, volume, backgrounding, and so on.
Best bet is to have a look at the Apple docs here:
http://developer.apple.com/library/ios/#DOCUMENTATION/Audio/Conceptual/AudioSessionProgrammingGuide/Configuration/Configuration.html#//apple_ref/doc/uid/TP40007875-CH3-SW1
Also, there is a really great tutorial video by Apple that covers this stuff really well. Here's the link:
https://developer.apple.com/videos/iphone/#video-advanced-audiodev
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595434",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How often will calculate works in Orbeon Xforms I have a bind definition as follows:
<xforms:bind nodeset="instance('demo')/pointer"
type="xforms:integer"
calculate="
if($current-page < '2') then '0'
else (
if($current-page > '2')
then ($max-pages - 1)
else .
)"/>
For every user click on the form, the current-page value changes. I wanted to understand how often does the calculate in the above the bind defnition execute?
The problem is that the pointer variable and current-page are dependent on each other, so if I click on something first, the value of pointer should be evaluated immediately and in the next instruction I have to set the current-page value based on the pointer value that is changed. On the click, the code will be as below:
<xforms:setvalue ref="$pointer"
value="($pointer + 1)"/>
<!-- i am assuming if the current-page is 2,
it will increment, else the value is set as per calculate -->
<xforms:setvalue ref="$current-page"
value="($current-page + 1)"
xxforms:if="($pointer = $max-pages)" />
A: *
*When users click on the button (assuming it is a button) that trigger the two xforms:setvalue, those xforms:setvalue run first and the xforms:bind calculate runs later.
*Pretty much all users' interaction with the form will cause the xforms:bind calculate to be be reevaluated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Related to result of eager loading in ROR Active Record I have an Invoice model which belongs to Customer (and of course Customer has_many invoices).
If I do:
{
@invs = Invoice.find(
:all,
:include => ["customer"],
:conditions => ['somecondition']
)
}
The class of @invs is an Array and I can see all the attributes for the 6th invoice in the array if I do: @invs[5]. However at that point I don't see the associated Customer record attributes. To get that I need to do @invs[5].customer.
My question is what is the Ruby structure that allows access to the customer record from the invoice record? I want to create a new arbitrary record of SomeClass and attach that to the invoice record within the recordset so that I can do @inv[5].someclass. Is that possible? and if so how?
[EDIT - FULL STORY]
The following tries to explain why I'm asking the question.
Although my Invoice model relates to a single table in the Db my Customer record can get archived and moved to another table called Archcustomer which is identical to Customer in structure. So I have additional associations like Invoice belongs_to Archcustomer and Archcustomer has_many Invoices.
I need to get a list of Invoices together with their associated customer record (regardless of where it's held i.e. Customer or Archcustomer) but sorted by Customer.category_id and Customer.id and Invoice.id.
In my original example above of @invs I am including the customer record and I could include the :order => 'customer.category_id, customer.id, invoice.id' clause but where the customer is archived the customer record is nil.
So I thought I would do the following:
{
@invs.each do |inv|
next if inv.customer != nil
archcust = Archcustomer.find(inv.customer_id) #since it's not in customer get it from Archcustomer
inv.customer.category_id = archcust.category_id
etc...
...
end
}
and then use @inv.sort_by. However that complains because I'm trying to allocate a value to customer.category_id of Nil class.
That's when I thought if I could attach an arbitrary record to Invoice I could fill in the info from either Archcustomer or Customer and have a common set of attributes to call my sort_by on.
Of course if there is some other way of achieving my set of Invoices ordered as I want them then I'll be happy to go with that.
A: In your invoice model (assuming you have your Archcustomer relationship in place):
class Invoice < ActiveRecord::Base
def customer_record
customer or archcustomer
end
end
Use @invoice.customer_record instead of @invoice.customer or @invoice.archcustomer when you need to get a record from any available source. .include both when you're loading.
Don't bother assigning stuff to an imaginary Customer when you already have a real Archcustomer. Just run sort_by on customer_record.category_id.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: session retrieving on page I have big problem related to login. actually some time it work fine but some time not working.
I have setting.php in which session_start() is executing. this file is including in all file. another file is config.php where all variable is defined including session name
$siteConfig_session_name = 'dhoombox';
then created a class user in which there is function userlogin as following:-
function user_front_end_login($_POST,$checkout_page,$check){
$errorMessage = '';
$userName = trim($_POST['username']);
$password = md5(trim($_POST['password']));
$user_login = mysql_query("SELECT user_id, email_id,username, password , firstname, lastname, status FROM tbl_users WHERE username= '".$userName."' AND password = '".$password."' ");
$select_user = mysql_fetch_array($user_login);
if( mysql_num_rows($user_login)==1){
$user_status = $select_user['status'];
//setAdminError('<span class="errormsg">Information has not been deleted!</span>');
if( $user_status==1){
$this->setUserLoginSession($select_user['user_id'], $select_user['email_id'], $select_user['username'],$select_user['firstname'],$select_user['lastname']);
if($checkout_page==1){
siteRedirect("billing_info.php");
}
else{
print_r($_SESSION);
siteRedirect("index.php");
}
}else{
setAdminError('<span class="errormsg" style="color:#FF0000;">Sorry your account is not activated.</span>'); siteRedirect("login.php");
}
}else{
setAdminError('<span class="errormsg" style="color:#FF0000;">Username or password mismatch</span>');
if($checkout_page==1){
siteRedirect("checkout.php");
}
else{
siteRedirect("login.php");
}
}
}
$this->setUserLoginSession($select_user['user_id'], $select_user['email_id'], $select_user['username'],$select_user['firstname'],$select_user['lastname']); is as following:-
function setUserLoginSession($uid, $email, $un, $fn,$ln) {
global $siteConfig_session_name;
$_SESSION['user_id'] = $uid;
$_SESSION['email_id'] = $email;
$_SESSION['username'] = $un;
$_SESSION['firstname'] = $fn;
$_SESSION['lastname'] = $ln;
}
some time it work fine and some time not.
A: What problems are you having? Are you getting an error?
session_start() has to be called in every page you want to use session variables in, you cannot start a session from an include.
<?php
session_start();
include'your_include.php';
user_front_end_login(post,checkout_page,check);
?>
<?php
session_start();
function user_front_end_login($_POST,$checkout_page,$check){
$errorMessage = '';
$userName = trim($_POST['username']);
$password = md5(trim($_POST['password']));
$user_login = mysql_query("SELECT user_id, email_id,username, password , firstname, lastname, status FROM tbl_users WHERE username= '".$userName."' AND password = '".$password."' ");
$select_user = mysql_fetch_array($user_login);
if( mysql_num_rows($user_login)==1){
$user_status = $select_user['status'];
//setAdminError('<span class="errormsg">Information has not been deleted!</span>');
if( $user_status==1){
$this->setUserLoginSession($select_user['user_id'], $select_user['email_id'], $select_user['username'],$select_user['firstname'],$select_user['lastname']);
if($checkout_page==1){
siteRedirect("billing_info.php");
}
else{
print_r($_SESSION);
siteRedirect("index.php");
}
}else{
setAdminError('<span class="errormsg" style="color:#FF0000;">Sorry your account is not activated.</span>'); siteRedirect("login.php");
}
}else{
setAdminError('<span class="errormsg" style="color:#FF0000;">Username or password mismatch</span>');
if($checkout_page==1){
siteRedirect("checkout.php");
}
else{
siteRedirect("login.php");
}
}
}
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How should I implement interface composition? I have this situation:
public interface IHasValue<T>
{
T Value { get; set; }
}
public interface IClickable
{
void SubscribeOnClick(EventHandler click);
}
public interface ILoginView : IView
{
IHasValue<string> Username { get; }
IHasValue<string> Password { get; }
IClickable Login { get; }
IClickable Cancel { get; }
}
public partial class LoginVIew : Form, ILoginView
{
public LoginVIew()
{
InitializeComponent();
}
#region ILoginView Members
public IHasValue<string> Username
{
get { ?? }
}
public IHasValue<string> Password
{
get { ?? }
}
public IClickable Login
{
get { ?? }
}
public IClickable Cancel
{
get { ?? }
}
#endregion
}
How should I implement this? I have no idea.
A: Well you'll need to implement IHasValue<T> and IClickable in order to be able to create an implementation of ILoginView (because you need to be able to create instances of object implementing those interfaces in the ILoginView members.
public class StringValue : IHasValue<string>
{
public string Value { get; set; }
}
public interface LoginClickable : IClickable
{
public void SubscribeOnClick(EventHandler click)
{
// do something to login
}
}
public interface CancelClickable : IClickable
{
public void SubscribeOnClick(EventHandler click)
{
// do something to cancel
}
}
...
public IHasValue<string> Username
{
get { return new StringValue { Value = "Username" }; }
}
public IHasValue<string> Password
{
get { return new StringValue { Value = "Password" }; }
}
public IClickable Login
{
get { return new LoginClickable(); }
}
public IClickable Cancel
{
get { return new CancelClickable(); }
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: trying to count the number of times something comes up on a dice. ruby code This is my code for a dice that shows a direction.
It shows either north, south, east or west when rolled.
I'm trying to figure out a way to count how many times each one of these appears anytime I roll the dice.
Any one any ideas?
class Dice
#def initialize()
#end
def roll
@dice = Array['north','south','east','west'] # makes dice with four sides (directions)
@dice_index = 0 + rand(4) # gets the random index of the array
puts @dice[@dice_index] # prints random direction like a dice
end
def stats
puts @dice_index
north_count =0;
south_count =0;
east_count=0;
west_count=0;
end
end
game_dice = Dice.new
game_dice.roll
game_dice.stats
A: Your class should look something like this:
class Dice
SIDES = [:north, :south, :east, :west]
def initialize
@rolls = Hash.new(0)
@num_of_sides = SIDES.count
end
def roll
roll = SIDES[rand(@num_of_sides)]
@rolls[roll] += 1
roll
end
def stats
puts @rolls.inspect
end
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: why resque-web is not showing all running resque workers? question in the title
i can see resque workers in htop: resque-1.15.0: Processing low since 1317112029 but they don't show up in resque-web
anyone had this issue?
A: Check your namespace in resque-web. If you are using redis-namespace in your resque installation, and the namespace doesn't match that of the worker, you won't see those workers in resque-web
A: solved by upgrading to resque 1.19
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Shell script to rename multiple files and folders I have the following structure
Before
-1.2.3.4
--1.2.3.4
---1.2.3.4-->1.2.3.4.file
After
-5.6.7.8
--5.6.7.8
---5.6.7.8-->5.6.7.8.file
...
I would like to use a bash script that searches files and subdirectories name in a specific directory /home for a specific string, and when it finds the search string (in file or
name, file content, subdirectories name), replaces the string (old1) with new string (new1), and so on old2 with new2 ....oldn with newn.
#!/bin/bash
FILES_PATH="/home/pons/test"
FILES=$(find $FILES_PATH -type f -name "*")
for FILE in $FILES; do
sed -i 's/old1/new1/ ; .... ; s/oldn/newn/' $FILE
done
e.g. replace fadi to server in all
[pons@server1 ~]$ pwd
/home/pons
[pons@server1 ~]$ cd test
[pons@server1 test]$ ls -al
total 12
drwxrwxr-x 3 pons pons 4096 Sep 29 09:50 .
drwx------. 26 pons pons 4096 Sep 29 10:21 ..
drwxrwxr-x 2 pons pons 4096 Sep 29 09:47 fadi
[pons@server1 test]$ cd fadi/
[pons@server1 fadi]$ pwd
/home/pons/test/fadi
[pons@server1 fadi]$ ls -al
total 12<br/>
drwxrwxr-x 2 pons pons 4096 Sep 29 09:47 .
drwxrwxr-x 3 pons pons 4096 Sep 29 09:50 ..
-rw-rw-r-- 1 pons pons 27 Sep 29 09:47 xxxfadixx.txt
[pons@server1 fadi]$ cat xxxfadixx.txt
xxxxxxxxxxxxfadixxxxxxxxxx
[pons@server1 fadi]$
Can I add multiple string in one file and do the replace
e.g. create a file that specify filtering routines:
filter.txt
s/old1/new1/
s/old2/new2/
s/old3/new3/
......
s/oldn/newn/
and then read that file in the script
#!/bin/bash
ROOT_DIR="$HOME/root" # your target dir
P_FROM="1.2.3.4"
P_TO="5.6.7.8"
# for each directory, starting from deepest first
while IFS= read -r -d $'\0' DIR_NAME; do
cd "$DIR_NAME" # go to target dir
rename $P_FROM $P_TO * # rename files
find . -type f -maxdepth 1 -exec sed -i "s/$P_FROM/$P_TO/g" {} \;
cd - > /dev/null # back to original dir. Suppress stdout
done < <(find $ROOT_DIR -type d -depth -print0) # get only dirs
This above script from Shawn Chin worked perfectly replacing/renaming strings, how can I modify it if I have multiple string to be modified and these strings allocated in a file
filter.txt
s/old1/new1/
s/old2/new2/
s/old3/new3/
......
s/oldn/newn/
#!/bin/bash
ROOT_DIR="$HOME/test" # your target dir
FILTER_FILE="$HOME/filter.sed" # the sed script for renaming
# custom rename function that uses $FILTER_FILE (via sed)
function rename_using_filter {
CURRENT_NAME="$1"
NEW_NAME="$(echo $1 | sed -f $FILTER_FILE)" # derive new name
if [ "$CURRENT_NAME" != "$NEW_NAME" ]; then # rename if diff
mv "$CURRENT_NAME" "$NEW_NAME"
fi
}
# for each directory, starting from deepest first
while IFS= read -r -d $'\0' DIR_NAME; do
cd "$DIR_NAME" # go to target dir
# for each file/dir at this level
while IFS= read -r -d $'\0' FILE_NAME; do
rename_using_filter "$FILE_NAME" # rename it
if [ -f "$FILE_NAME" ]; then # if it's a file
sed -i -f "$FILTER_FILE" "$FILE_NAME"; # replace content
fi
done < <(find . -maxdepth 1 -print0)
cd - > /dev/null # back to original dir. Suppress stdout
done < <(find $ROOT_DIR -depth -type d -print0) # get only dirs
I did the above with filter.sed, it works replacing name files/directories but didnt replace the content of the file... can you check it please.
[pons@server1 test]$ find .
.
./boy_dir
./boy_dir/boy.txt
./papa
./papa/papa_new
./papa/papa_new/papa.txt
./boy
[pons@server1 test]$ cat ./papa/papa_new/papa.txt
xxxxxxxxxxxxxxxxxxxxpapaxxxxxxxxxxxx
[pons@server1 test]$ cat ./boy_dir/boy.txt
xxxxxxxxxxxxboyxxxxxxxxx
[pons@server1 test]$ cd ..
[pons@server1 ~]$ ./replace.sh
[pons@server1 ~]$ cd test
[pons@server1 test]$ find .
.
./girl_dir
./girl_dir/girl.txt
./girl
./mama
./mama/mama_new
./mama/mama_new/mama.txt
[pons@server1 test]$ cat ./mama/mama_new/mama.txt
xxxxxxxxxxxxxxxxxxxxpapaxxxxxxxxxxxx
[pons@server1 test]$ cat ./girl_dir/girl.txt
xxxxxxxxxxxxboyxxxxxxxxx
[pons@server1 test]$
I used this filter
[pons@server1 ~]$ cat filter.sed
s/papa/mama/g;
s/boy/girl/g;
s/old3/new3/g;
s/old3/new4/g;
s/oldn/newn/g;
"filter.sed" 5L, 95C written
[pons@server1 ~]$ ./replace.sh
[pons@server1 ~]$ cd test
[pons@server1 test]$ find .
.
./A.B.C.D.E_
./a.b.c.d.e
./a.b.c.d.e/a.b.c.d.e
./a.b.c.d.e_
./A.B.C.D.E
./A.B.C.D.E/A.B.C.D.E
[pons@server1 test]$ cat ./A.B.C.D.E/A.B.C.D.E
1.2.3.4.5
[pons@server1 test]$ cat ./a.b.c.d.e/a.b.c.d.e
6.7.8.9.0
[pons@server1 test]$ cat ./A.B.C.D.E_
1.2.3.4.5
[pons@server1 test]$ cat ./a.b.c.d.e_
6.7.8.9.0
[pons@server1 test]$ cd ..
[pons@server1 ~]$ ./replace.sh
[pons@server1 ~]$ cd test
[pons@server1 test]$ find .
.
./A.B.C.D.E_
./a.b.c.d.e
./a.b.c.d.e/a.b.c.d.e
./a.b.c.d.e_
./A.B.C.D.E
./A.B.C.D.E/A.B.C.D.E
[pons@server1 test]$ cat ./A.B.C.D.E/A.B.C.D.E
A.B.C.D.E
[pons@server1 test]$ cat ./a.b.c.d.e/a.b.c.d.e
a.b.c.d.e
[pons@server1 test]$ cat ./A.B.C.D.E_
A.B.C.D.E
[pons@server1 test]$ cat ./a.b.c.d.e_
a.b.c.d.e
[pons@server1 test]$
[pons@server1 ~]$ vi filter.sed
s/1.2.3.4.5/A.B.C.D.E/g;
s/6.7.8.9.0/a.b.c.d.e/g;
s/old3/new3/g;
s/old3/new4/g;
s/oldn/newn/g;
~
A: You can run rename (yes, that's an existing program) for each replacement. For example, in Bash >=4.0, here's how to remove a ".bak" extension from all files within the current directory:
shopt -s globstar # Enable recursive globs with **
rename 's/\.bak$//' **.bak
Another example, to do several replacements:
$ touch /tmp/foobarbaz
$ rename 's/foo/bar/g;s/bar/baz/g' /tmp/foobarbaz
$ ls /tmp
bazbazbaz
For your specific replacements, this should work:
rename 's/old1/new1/ ; .... ; s/oldn/newn/' /home/pons/test/**
A: From what I gather, you want to traverse a directory structure and do the following:
*
*Replace keywords/patterns within file or directory names.
*Replace occurrences of the keywords/patterns within the content of files.
Here's how I would do it.
Warning: long answer. If you're in a hurry, jump straight to the last section for complete script. Might also be over-engineer (there should be an easier way to do this, really...).
Assuming the following file structure (based on your first example):
[me@home]$ find .
.
./1.2.3.4
./1.2.3.4/1.2.3.4
./1.2.3.4/1.2.3.4/1.2.3.4
./1.2.3.4/1.2.3.4/1.2.3.4/1.2.3.4.file
./1.2.3.4/1.2.3.4/1.2.3.4/1.2.3.4-2.file
[me@home]$ cat ./1.2.3.4/1.2.3.4/1.2.3.4/1.2.3.4.file
IP: 1.2.3.4
[me@home]$ cat ./1.2.3.4/1.2.3.4/1.2.3.4/1.2.3.4-2.file
IP: 1.2.3.4 (also)
Replacing patterns within files
This is the easy bit. One can do that quite simply using find and sed
[me@home]$ find . -type f -exec sed -i "s/1\.2\.3\.4/5.6.7.8/g" {} \;
[me@home]$ cat ./1.2.3.4/1.2.3.4/1.2.3.4/1.2.3.4.file
IP: 5.6.7.8
[me@home]$ cat ./1.2.3.4/1.2.3.4/1.2.3.4/1.2.3.4-2.file
IP: 5.6.7.8 (also)
Recursively renaming files/dirs
I first assumed it would be as simple as find . -exec rename 1.2.3.4 5.6.7.8 {} \;.
Unfortunately, that does not work. Prepending the command with an echo shows why it won't work.
[me@home]$ find . -exec echo rename 1.2.3.4 5.6.7.8 {} \;
rename 1.2.3.4 5.6.7.8 .
rename 1.2.3.4 5.6.7.8 ./1.2.3.4
rename 1.2.3.4 5.6.7.8 ./1.2.3.4/1.2.3.4
rename 1.2.3.4 5.6.7.8 ./1.2.3.4/1.2.3.4/1.2.3.4
rename 1.2.3.4 5.6.7.8 ./1.2.3.4/1.2.3.4/1.2.3.4/1.2.3.4.file
rename 1.2.3.4 5.6.7.8 ./1.2.3.4/1.2.3.4/1.2.3.4/1.2.3.4-2.file
The renaming of the top-level directory (./1.2.3.4) will succeed, but once we go down a level to rename ./1.2.3.4/1.2.3.4 this will fail because the parent directory has already been renamed.
We can reverse the order of traversal (using -depth) but that only solves half the problem since we need each step to rename only the lowest-level match and not the whole path.
What we therefore have to do is start the renaming process from the lowest level and work upwards. Here's one way to do it:
#!/bin/bash
ROOT_DIR="$HOME/root" # your target dir
P_FROM="1.2.3.4"
P_TO="5.6.7.8"
# for each directory, starting from deepest first
while IFS= read -r -d $'\0' DIR_NAME; do
(cd "$DIR_NAME" && rename $P_FROM $P_TO *)
done < <(find $ROOT_DIR -depth -type d -print0) # get only dirs
The complicated-looking while loop allows us to handle filenames that contain spaces (see http://mywiki.wooledge.org/BashFAQ/020 for details).
This script assumes the rename command exists.
Running that script on our test directory gives the following results:
[me@home]$ bash renamer.sh
[me@home]$ find .
.
./5.6.7.8
./5.6.7.8/5.6.7.8
./5.6.7.8/5.6.7.8/5.6.7.8
./5.6.7.8/5.6.7.8/5.6.7.8/5.6.7.8.file
./5.6.7.8/5.6.7.8/5.6.7.8/5.6.7.8-2.file
Combining both steps into one script
We can combine both the steps above into one solution by simple adding the find+sed call into the loop.
#!/bin/bash
ROOT_DIR="$HOME/root" # your target dir
P_FROM="1.2.3.4"
P_TO="5.6.7.8"
# for each directory, starting from deepest first
while IFS= read -r -d $'\0' DIR_NAME; do
cd "$DIR_NAME" # go to target dir
rename $P_FROM $P_TO * # rename files
find . -type f -maxdepth 1 -exec sed -i "s/$P_FROM/$P_TO/g" {} \;
cd - > /dev/null # back to original dir. Suppress stdout
done < <(find $ROOT_DIR -depth -type d -print0) # get only dirs
Update (renaming and rewriting files based on external sed file)
Assuming you have a sed file filter.sed:
s/old1/new1/g;
s/old2/new2/g;
s/old3/new3/g;
s/old3/new4/g;
s/oldn/newn/g;
Replacing contents of a file is simple as long as filter.sed is a valid sed file. We simply use the -f option:
[me@home]$ cat somefile.txt
hello old1 old2 old3 world
[me@home]$ sed -i -f filter.sed somefile.txt
[me@home]$ cat somefile.txt
hello new1 new2 new3 world
However, renaming files/dirs however is trickier (unless you use the Perl-based rename command available only on debian-based systems. With this you may be able to do something along the lines of rename "$(cat filter.sed)" *).
Using only the standard mv command, here's one way to do it. I suspect this may not the most efficient approach, but after briefly testing it, it appears to work. YMMV.
#!/bin/bash
ROOT_DIR="$HOME/root" # your target dir
FILTER_FILE="$HOME/filter.sed" # the sed script for renaming
# custom rename function that uses $FILTER_FILE (via sed)
function rename_using_filter {
CURRENT_NAME="$1"
NEW_NAME="$(echo $1 | sed -f $FILTER_FILE)" # derive new name
if [ "$CURRENT_NAME" != "$NEW_NAME" ]; then # rename if diff
mv "$CURRENT_NAME" "$NEW_NAME"
fi
}
# for each directory, starting from deepest first
while IFS= read -r -d $'\0' DIR_NAME; do
cd "$DIR_NAME" # go to target dir
# for each file/dir at this level
while IFS= read -r -d $'\0' FILE_NAME; do
if [ -f "$FILE_NAME" ]; then # if it's a file
sed -i -f "$FILTER_FILE" "$FILE_NAME" # replace content
fi
rename_using_filter "$FILE_NAME" # rename it
done < <(find . -maxdepth 1 -print0)
cd - > /dev/null # back to original dir. Suppress stdout
done < <(find $ROOT_DIR -depth -type d -print0) # get only dirs
Here's the script in action:
[me@home]$ find .
.
./old1_old2
./old1_old2/old3_old4
./old1_old2/old3_old4/some-oldn.txt
./renamr.sh
[me@home]$ cat old1_old2/old3_old4/some-oldn.txt
hello old1 old2 old3 old4 oldn world
[me@home]$ bash renamr.sh
[me@home]$ find .
.
./.renamr.sh.swp
./new1_new2
./new1_new2/new3_new4
./new1_new2/new3_new4/some-newn.txt
./renamr.sh
[me@home]$ cat ./new1_new2/new3_new4/some-newn.txt
hello new1 new2 new3 new4 newn world
A: I didn't completely understand what you want to achieve, but I think this will at least fix your code:
mv "$FILE" "$(echo "$FILE" | sed -i 's/old1/new1/ ; .... ; s/oldn/newn/')"
A: *
*Sed works on standard input or file content, not argument text or file names or anything like that.
*When reading output of find, do not store it all in variable, but read it line by line.
So you want to do something like:
find $FILES_PATH -type f | while read FILE; do
NEWNAME="$(printf '%s\n' "$FILE" | sed 's/old1/new1/ ; .... ; s/oldn/newn/')"
mv "$FILE" "$NEWNAME"
done
Note, that you do not want -i for sed, stdin can't be modified in place.
It can be more efficient by having sed output both names, so you can run it just once on the whole output, but with multiple substitutions that requires using the hold space. It goes like:
find $FILES_PATH -type f | sed 'h;s/old1/new1/;...;s/oldn/newn/;x;G' | while read OLD && read NEW; do
mv "$OLD" "$NEW"
done
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I save my application now-oauth and HTTPS? Well, I am a non-Facebook developer, and a normal .NET programmer who have created a Facebook application for a regular website around one year ago using FBML. I have no time to read the roadmap every day and know what will be next. So I had no idea about OAuth and HTTPS till yesterday.
All of a sudden I received an email yesterday saying (27 Sep) upgrade to OAuth 2.0 and HTTPS,
otherwise the application will be disabled from 1st Oct.
Now, I read about OAuth 2.0 the whole day yesterday, and think I can get around it now chaining things, but I found that the site which currently host my Facebook application doesn't have SSL (HTTPS support) or dedicated IP address and I found that I need to invest around 20$ to get SSL and another $20 for a dedicated IP address. I am ready to pay
for it, but as you know a response from hosting are not that quick.
Now I have emailed my hosting to make arrangement for it, but sadly they have not responded yet, and I now only have one day left (I don't know they will respond or not).
So how can I save my application? I don't have any server that support HTTPS for now. Even if I get some free SSL I am not able to implement it as I don't have a dedicated IP address.
Is there some way I can put a "will be back soon" kind of message. Or how can I save the application now?
I think I need to update that HTTPS canvas page in the setting anyhow.
A: FBML applications are not required to migrate and support HTTPS and signed requests.
Source: http://developers.facebook.com/blog/post/567/
Also, be aware that Facebook will stop supporting FBML apps at the end of the year.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: C# How to use Interlocked.CompareExchange My goal is the following:
There is a certain range of integers, and I have to test every integer in that range for something random. I want to use multiple threads for this, and divide the work equally among the threads using a shared counter. I set the counter at the beginning value, and let every thread take a number, increase it, do some calculations, and return a result. This shared counter has to be incremented with locks, because otherwise there will be gaps / overlaps in the range of integers to test.
I have no idea where to start. Let's say I want 12 threads to do the work, I do:
for (int t = 0; t < threads; t++)
{
Thread thr = new Thread(new ThreadStart(startThread));
}
startThread() isthe method I use for the calculations.
Can you help me on my way? I know I have to use the Interlocked class, but that's all….
A: Say you have an int field somewhere (initialized to -1 initially) then:
int newVal = Interlocked.Increment(ref theField);
is a thread-safe increment; assuming you don't mind the (very small) risk of overflowing the upper int limit, then:
int next;
while((next = Interlocked.Increment(ref theField)) <= upperInclusive) {
// do item with index "next"
}
However, Parallel.For will do all of this a lot more conveniently:
Parallel.For(lowerInclusive, upperExclusive, i => DoWork(i));
or (to constrain to 12 threads):
var options = new ParallelOptions { MaxDegreeOfParallelism = 12 };
Parallel.For(lowerInclusive, upperExclusive, options, i => DoWork(i));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Right to left UILabels I need to display a text using a UILabel ( can't use UIWebView ), and it sometimes contains both Hebrew and English. using UILabel's default settings the sentence gets mixed up and doesn't make sense. I have failed to found a way to make UILabel display text rtl.
Does anybody know anyway to do that, or a code that implements this?
A: Have a look at this SO, it contains some info on this subject that might help you out.
It seems to work for some by adding the code \u200F to the strings to be displayed.
NSString *RTFstr = "1. בבוקר"; //This could be any right-to-left string
NSString *directionalString = [@"\u200F" stringByAppendingString:[note text]];
[someUITextView setString:directionalString];
A: This will work
-(void)fnForWritingDirection:(UILabel*)label textFor:(NSString *)stringForText{
NSMutableAttributedString* attrStr = [[NSMutableAttributedString alloc] initWithString: [stringForText stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setBaseWritingDirection:NSWritingDirectionRightToLeft];
[attrStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [attrStr length])];
label.attributedText=attrStr;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Filter some type of data in float how to filter out float values with only zeroes beyond decimal & others having some non-zero values beyond decimal too.
for example.
13.000000
13.120001
i want it like this:
13.0
13.120001
A: If your application stores the floating point values in something like C/C++'s float's or double's, you may have a problem here.
First of all, float/double in the majority of cases represents values using base-2 and when you do something like double x = 0.1;, x in fact will never be equal to 0.1, but it will be very close to 0.1. That is because not every decimal (base-10) fraction can be represented exactly in base-2.
When you print or convert that x to a string using one of the printf-like functions, the resultant string can vary from something like 0.099999999 to 0.1 to 0.10000000000000000555. The result will depend on what's in x and on how you convert it to a string (how many digits you allow for the integer part, fractional part or all).
Generally there's no one-size-fits-all solution here. In one case the exactness and rounding issues can be unimportant, while in another they can be the most important. When performance is more important than the exact representation of decimal fractions, you use base-2 types. Otherwise, for example, when you're counting money, you use special types (and you may first need to construct them) that can represent decimal fractions exactly and then you avoid some of the described issues at a cost of extra computation time and maybe storage.
You may sometimes use fixed-point types and arithmetic. For example, if your numbers should not have more than 3 fractional digits and aren't too big, you can use scaled integers:
long x = 123456; // x represents 123.456
You add, subtract and compare them just as regular integers, but you multiply and divide them differently, for example like this:
long x = 123456; // x represents 123.456
long y = 12345; // y represents 12.345
long p = (long)(((long long)x * y) / 1000); // p=1524064, representing x*y=1524.064
long q = (long)((long long)x * 1000) / y); // q=10000, representing x/y=10.000
And in this case it is relatively easy to figure out the digits of the fractional part, just look at (x%1000)/100, (x%100)/10 and x%10.
A: split 13.00000 or 13.20001 into 2 values like in 13.0000 as 13 and 0000 ...so compare 2nd value whether it is greater than 0 (ex:13.20001 where 2001>0) if its yes then set same value . else (ex 13.0000 where 0000=0) then set %.2f=> 13.00
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Retrieve by value from an Object? This must be a duplicate, but I've been Googling "retrieve by value from object javascript" and "javascript lookup object by value" and every variant and got nowhere, so apologies and here goes.
Say I have a JavaScript object like this:
var options = {"ford": "red", "citroen": "blue"};
How do I do look up value blue to get citroen back?
There's always the 'write your own function' route, I guess:
function returnbyValue(options, v):
for (var prop in options) {
if (options.hasOwnProperty(v)) {
if (options[prop] === v) {
return prop;
}
}
}
return null;
but does JavaScript have anything inbuilt, or is there a neater way to do this?
A: There is no such built-in method. And your own function looks good to me. I can't figure out any improvement of it.
A: The property of an object can be accessed just like an associative array!
This worked like a charm!
var obj = {
'key': 'val'
};
alert( obj['key'] );
Alternatively, if you wish to use a method you can create a prototype method.
Object.prototype.getPropertyByString = function( str ) {
return this[str];
};
alert( obj.getPropertyByString( 'key' ) );
Edit: Wow I just noticed I failed to answer your question, my apologies! Allow me to get a second chance.
There is no built in function, but my script below works!
var obj = {
'key': 'val'
};
Object.prototype.getKeyByValue = function( object ) {
for(var key in this) {
if(this.key === object) {
return key;
}
}
return null;
};
alert( obj.getKeyByValue( 'val' ) );
It loops through the object and returns the key if it matches a value. This wil work, no matter if the value is an int, string, object, anything. This is because I've used the strict equal comparison ("===") which also checks if the object type is the same.
Also, please note that checking if the property exists is silly if you're looping through all keys of the object anyway. Obviously, when you're looping through all keys, they exist.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Configuring Quercus on Google App Engine I am currently working with GAE and was trying to figure out if there was some way that I can run php on GAE. Fortunately, I came across Quercus and was very happy to find that it had all that i needed.
But the problem now is that once I include the resin.jar to the WEB-INF/lib folder and try to update app using the google plugin in eclipse, it gives me an error saying that the size of the jar file is big and recommends me adding --enable_jar_splitting flag.
Now I have gone through a lot of sites where people have had similar problems. So what do I do to overcome this?
So here's what I am looking for in short:
1. Either a way to include this flag in the eclipse plugin
2. Finding out a way to split the jar file.
SOLUTION:
The only way that the above is currently possible is by using the command line utility present in the sdk/bin folder called - appcfg.sh
appcfg.sh --enable_jar_splitting -e user@domain.com update /path/to/war/file
PS: It is assumed that you have added the path to the bin folder as a environmental variable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.