Daily Archives

Articles indexed Sunday October 20 2013

Page 7/16 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Android Can't get two virtual joysticks to move independently and at the same time

    - by Cole
    @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub float r = 70; float centerLx = (float) (screenWidth*.3425); float centerLy = (float) (screenHeight*.4958); float centerRx = (float) (screenWidth*.6538); float centerRy = (float) (screenHeight*.4917); float dx = 0; float dy = 0; float theta; float c; int action = event.getAction(); int actionCode = action & MotionEvent.ACTION_MASK; int pid = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; int fingerid = event.getPointerId(pid); int x = (int) event.getX(pid); int y = (int) event.getY(pid); c = FloatMath.sqrt(dx*dx + dy*dy); theta = (float) Math.atan(Math.abs(dy/dx)); switch (actionCode) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: //if touching down on left stick, set leftstick ID to this fingerid. if(x < screenWidth/2 && c<r*.8) { lsId = fingerid; dx = x-centerLx; dy = y-centerLy; touchingLs = true; } else if(x > screenWidth/2 && c<r*.8) { rsId = fingerid; dx = x-centerRx; dy = y-centerRy; touchingRs = true; } break; case MotionEvent.ACTION_MOVE: if (touchingLs && fingerid == lsId) { dx = x - centerLx; dy = y - centerLy; }else if (touchingRs && fingerid == rsId) { dx = x - centerRx; dy = y - centerRy; } c = FloatMath.sqrt(dx*dx + dy*dy); theta = (float) Math.atan(Math.abs(dy/dx)); //if touching outside left radius and moving left stick if(c >= r && touchingLs && fingerid == lsId) { if(dx>0 && dy<0) { //top right quadrant lsX = r * FloatMath.cos(theta); lsY = -(r * FloatMath.sin(theta)); Log.i("message", "top right"); } if(dx<0 && dy<0) { //top left quadrant lsX = -(r * FloatMath.cos(theta)); lsY = -(r * FloatMath.sin(theta)); Log.i("message", "top left"); } if(dx<0 && dy>0) { //bottom left quadrant lsX = -(r * FloatMath.cos(theta)); lsY = r * FloatMath.sin(theta); Log.i("message", "bottom left"); } else if(dx > 0 && dy > 0){ //bottom right quadrant lsX = r * FloatMath.cos(theta); lsY = r * FloatMath.sin(theta); Log.i("message", "bottom right"); } } if(c >= r && touchingRs && fingerid == rsId) { if(dx>0 && dy<0) { //top right quadrant rsX = r * FloatMath.cos(theta); rsY = -(r * FloatMath.sin(theta)); Log.i("message", "top right"); } if(dx<0 && dy<0) { //top left quadrant rsX = -(r * FloatMath.cos(theta)); rsY = -(r * FloatMath.sin(theta)); Log.i("message", "top left"); } if(dx<0 && dy>0) { //bottom left quadrant rsX = -(r * FloatMath.cos(theta)); rsY = r * FloatMath.sin(theta); Log.i("message", "bottom left"); } else if(dx > 0 && dy > 0) { rsX = r * FloatMath.cos(theta); rsY = r * FloatMath.sin(theta); Log.i("message", "bottom right"); } } else { if(c < r && touchingLs && fingerid == lsId) { lsX = dx; lsY = dy; } if(c < r && touchingRs && fingerid == rsId){ rsX = dx; rsY = dy; } } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: if (fingerid == lsId) { lsId = -1; lsX = 0; lsY = 0; touchingLs = false; } else if (fingerid == rsId) { rsId = -1; rsX = 0; rsY = 0; touchingRs = false; } break; } return true; } There's a left joystick and a right joystick. Right now only one will move at a time. If someone could set me on the right track I would be incredibly grateful cause I've been having nightmares about this problem.

    Read the article

  • Bouncing ball isssue

    - by user
    I am currently working on the 2D Bouncing ball physics that bounces the ball up and down. The physics behaviour works fine but at the end the velocity keep +3 then 0 non-stop even the ball has stopped bouncing. How should I modify the code to fix this issue? ballPos = D3DXVECTOR2( 50, 100 ); velocity = 0; accelaration = 3.0f; isBallUp = false; void GameClass::Update() { velocity += accelaration; ballPos.y += velocity; if ( ballPos.y >= 590 ) isBallUp = true; else isBallUp = false; if ( isBallUp ) { ballPos.y = 590; velocity *= -1; } // Graphics Rendering m_Graphics.BeginFrame(); ComposeFrame(); m_Graphics.EndFrame(); }

    Read the article

  • Ouya / Android : button mapping bitwise

    - by scorvi
    I am programming a game with the Gameplay3d Engine. But the Android site has no gamepad support and that is what I need to port my game to Ouya. So I implemented a simple gamepad support and it supports 2 gamepads. So my problem is that I put the button stats in a float array for every gamepad. But the Gameplay3d engine saves their stats in a unsigned int _buttons variable. It is set with bitwise operations and I have no clue how to translate my array to this.

    Read the article

  • How to categorize textures into atlases

    - by Esa
    I am going to use texture atlasing for the first time in my games, and at first it seemed like a great idea to split textures into atlases by categorizing them by terrain themes e.g ForestTextures, WinterTextures etc. But that could cause a problem when for example a flower has to use transparency shader and other models use a diffuse shader. So those cannot be atlased into the same texture. Thus, would atlasing textures into themes as mentioned before and then splitting them by shader like ForestDiffuse and ForestTransparent be good? Or is there a better way to categorize and build them?

    Read the article

  • How can I have multiple layers in my map array?

    - by Manl400
    How do I load Levels in my game, as in Layer 1 would be Objects, Layer 2 would be Characters and so on. I only need 3 layers, and they will all be put on top of each other. i.e having a flower with a transparent background to be put on grass or dirt on the layer below.I would like to Read From the same file too. How would i go about doing this? Any help would be appreciated. I load the map from a level file which are just numbers corresponding to a tile in the tilesheet. Here is the level file [Layer1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 [Layer2] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 [Layer3] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 And here is the code that interprets it void LoadMap(const char *filename, std::vector< std::vector <int> > &map) { std::ifstream openfile(filename); if(openfile.is_open()) { std::string line, value; int space; while(!openfile.eof()) { std::getline(openfile, line); if(line.find("[TileSet]") != std::string::npos) { state = TileSet; continue; } else if (line.find("[Layer1]") != std::string::npos) { state = Map; continue; } switch(state) { case TileSet: if(line.length() > 0) tileSet = al_load_bitmap(line.c_str()); break; case Map: std::stringstream str(line); std::vector<int> tempVector; while(!str.eof()) { std::getline(str, value, ' '); if(value.length() > 0) tempVector.push_back(atoi(value.c_str())); } map.push_back(tempVector); break; } } } else { } } and this is how it draws the map. Also the tile sheet is 1280 by 1280 and the tilesizeX and tilesizeY is 64 void DrawMap(std::vector <std::vector <int> > map) { int mapRowCount = map.size(); for(int i, j = 0; i < mapRowCount; i ++) { int mapColCount = map[i].size(); for (int j = 0; j < mapColCount; ++j) { int tilesetIndex = map[i][j]; int tilesetRow = floor(tilesetIndex / TILESET_COLCOUNT); int tilesetCol = tilesetIndex % TILESET_COLCOUNT; al_draw_bitmap_region(tileSet, tilesetCol * TileSizeX, tilesetRow * TileSizeY, TileSizeX, TileSizeY, j * TileSizeX, i * TileSizeX, NULL); } } } EDIT: http://i.imgur.com/Ygu0zRE.jpg

    Read the article

  • Rails / JBuilder - Entity array with has_many attributes

    - by seufagner
    I have two models, Person and Image and I want return an json array of Persons with your Images. But I dont want return all Image attributes, but produces a different result. Code below: class Person < ActiveRecord::Base has_many :images, as: :imageable validates :name, presence: true accepts_nested_attributes_for :images, :reject_if => lambda { |img| img['asset'].blank? } end class Image < ActiveRecord::Base belongs_to :imageable, polymorphic: true mount_uploader :asset, ImageUploader validates :asset, presence: true end zzz.jbuilder.json template json.persons(@rodas, :id, :name, :images) json produced: { "rodas": [{ "id": 4, "name": "John", "images": [ { "asset": { "url": "/uploads/image/xxxx.png" } }, { "asset": { "url": "/uploads/image/yyyyy.jpeg" } } ]}, { "id": 19, "name": "Mary", "images": [ { "asset": { "url": "/uploads/image/kkkkkkk.png" } } ] }] } I want something like: { "rodas": [ { "id": 4, "name": "John", "images": [ "/uploads/image/xxxx.png" , "/uploads/image/yyyy.jpeg" ] }, { "id": 10, "name": "Mary", "images": [ "/uploads/image/dddd.png" , "/uploads/image/xxxx.jpeg" ] } ]}

    Read the article

  • Issue with javascript array object

    - by ezhil
    I have the below JSON response. I am using $.getJSON method to loads JSON data and using callback function to do some manipulation by checking whether it is array as below. { "r": [{ "IsDefault": false, "re": { "Name": "Depo" }, "Valid": "Oct8, 2013", "Clg": [{ "Name": "james", "Rate": 0.05 }, { "Name": "Jack", "Rate": 0.55 }, { "Name": "Mcd", "Rate": 0.01, }], }, { "IsDefault": false, "re": { "Name": "Depo" }, "Valid": "Oct8, 2013", "Clg": [{ "Name": "james", "Rate": 0.05 }, { "Name": "Jack", "Rate": 0.55 }, { "Name": "Mcd", "Rate": 0.01, }], }, { "IsDefault": false, "re": { "Name": "Depo" }, "Valid": "Oct8, 2013", "Clg": [{ "Name": "james", "Rate": 0.05 }, { "Name": "Jack", "Rate": 0.55 }, { "Name": "Mcd", "Rate": 0.01, }], }] } I am passing the json responses on both loadFromJson1 and loadFromJson2 function as "input" as parameter as below. var tablesResult = loadFromJson1(resultstest.r[0].Clg); loadFromJson1 = function (input) { if (_.isArray(input)) { alert("loadFromJson1: Inside array function"); var collection = new CompeCollection(); _.each(input, function (modelData) { collection.add(loadFromJson1(modelData)); }); return collection; } return new CompeModel({ compeRates: loadFromJson2(input), compName: input.Name }); }; loadFromJson2 = function (input) // here is the problem, the 'input' is not an array object so it is not going to IF condition of the isArray method. { if (_.isArray(input)) { alert("loadFromJson2: Inside array function"); //alert is not coming here though it is an array var rcollect = new rateCollection(); _.each(input, function (modelData) { rcollect.add(modelData); }); return rcollect; } }; The above code i am passing json responses for both loadFromJson1 and loadFromJson2 function as "input". isArray is getting true on only loadFromJson1 function and giving alert inside the if condition but not coming in loadFromJson2 function though i am passing the same parameter. can anyone tell me why loadFromJson2 function is not getting the alert inside if condition though i pass array object?

    Read the article

  • What is the best practice in C# to propagate an exception thrown in a finally block without loosing an exception from a catch block?

    - by Sergey Smolnikov
    When an exception is possible to be thrown in a finally block how to propagate both exceptions - from catch and from finally? As a possible solution - using an AggregateException: internal class MyClass { public void Do() { Exception exception = null; try { //example of an error occured in main logic throw new InvalidOperationException(); } catch (Exception e) { exception = e; throw; } finally { try { //example of an error occured in finally throw new AccessViolationException(); } catch (Exception e) { if (exception != null) throw new AggregateException(exception, e); throw; } } } }

    Read the article

  • javascript will not work onload

    - by user2711818
    The javascript on the page needs to work onpage load. So I tried adding the document ready function into the code. It doesn't seem to work. http://janeucreative.com/daddychallenge/bag.html <script>$(document).ready(function() { function addItem(item) { var itemInCart = item.cloneNode(true); itemInCart.onclick = function() { removeItem(this); }; var cart = document.getElementById("cart"); cart.appendChild(itemInCart); } function removeItem(item) { var itemInItems = item.cloneNode(true); itemInItems.onclick = function() { addItem(this); }; var cart = document.getElementById("cart"); cart.removeChild(item); } init(); });</script> Any advice would be much appreciated! I'm very new to javascript and just trying to learn it a step at a time.

    Read the article

  • KnockoutJS - creating object doesn't work

    - by Kiwanax
    I'm doing a navigation list with menus and submenus. I have the following structure: function Menu(navigation) { this.NavigationUrl = ko.observable(navigation.NavigationUrl); this.NavigationTitle = ko.observable(navigation.NavigationTitle); this.NavigationDescription = ko.observable(navigation.NavigationDescription); var mappedChildren = ko.utils.arrayMap(navigation.Children, function (child) { return new Menu(child); }); this.Children = ko.observableArray(mappedChildren); } function DashboardViewModel() { var self = this; self.LoggedUser = ko.observable(""); self.Navigations = ko.observableArray([]); $.get('/Home/DashboardDependencies', {}, function (result) { self.LoggedUser(result.LoggedUser); var mappedNavigations = ko.utils.arrayMap(result.Navigations, function (item) { var menu = new Menu(item); // When I alert item, the result appears properly: // { "NavigationTitle": "blah", "NavigationDescription": "bleh" [...] } alert(JSON.stringify(item)); // But when I alert the new menu object, the result doesn't appear: // Just: "{}" alert(JSON.stringify(menu)); return menu; }); self.Navigations = mappedNavigations; }); } ko.applyBindings(new DashboardViewModel()); So, check it out. When I try to alert the item variable, the result appears properly. When I try to alert the new Menu object, the result just show {}. Why this' happening? Thank you all for the help!

    Read the article

  • python fdb save huge data from database to file

    - by peter
    I have this script SELECT = """ select coalesce (p.ID,'') as id, coalesce (p.name,'') as name, from TABLE as p """ self.cur.execute(SELECT) for row in self.cur.itermap(): xml +=" <item>\n" xml +=" <id>" + id + "</id>\n" xml +=" <name>" + name + "</name>\n" xml +=" </item>\n\n" #save xml to file here f = open... and I need to save data from huge database to file. There are 10 000s (up to 40000) of items in my database and it takes very long time when script runs (1 hour and more) until finish. How can I take data I need from database and save it to file "at once"? (as quick as possible? I don't need xml output because I can process data from output on my server later. I just need to do it as quickly as possible. Any idea?) Many thanks!

    Read the article

  • Is there a efficient way to do multiple test cases in c?

    - by Ahmed Abdelaal
    I use MS Visual Studio and I am new to C++, so I am just wondering if there is an faster more efficient way to do multiple test cases instead of keep clicking CTRL+F5 and re-opening the console many times. Like for example if I have this code #include <iostream> using namespace std; void main () { int x; cout<<"Enter a number"<<endl; cin>>x; cout<<x*2<<endl; } Is there a way I could try different values of x at once and getting the results together? Thanks

    Read the article

  • Specifying path in a preference file in Unison

    - by Curious2learn
    I am using Unison to sync a folder on my local computer with one on a server. I am using a unison preference file for this. If I specify the path of the local folder using Method 1 (see below) things work well. But Method 2 does not work. I would like to use something like Method 2 because I want to use the same preference file (synced using Dropbox) on two different computers. But the usernames are different on these two computers and I cannot change the usernames. Any ideas how this can be achieved? Thank you. METHOD 1 (works) root = /Users/username1/Dropbox/path_to_folder/folder METHOD 2a (Does not work) root = ~/Dropbox/path_to_folder/folder METHOD 2b (Does not work) root = $HOME/Dropbox/path_to_folder/folder

    Read the article

  • How to send a list of object from my MainPage.xaml to another page

    - by LivingThing
    When navigating to another page how can i make my list of object available to another page. for example in my mainpage.xaml var data2 = from query in document.Descendants("weather") select new Forecast { date = (string)query.Element("date"), tempMaxC = (string)query.Element("tempMaxC"), tempMinC = (string)query.Element("tempMinC"), weatherIconUrl = (string)query.Element("weatherIconUrl"), }; forecasts = data2.ToList<Forecast>(); .... NavigationService.Navigate(new Uri("/WeatherInfoPage.xaml", UriKind.Relative)); and then in my other class, i want to make it available so that i can use it like this private void AddPageItem(List<Forecast> forecasts) { .. }

    Read the article

  • SQLAlchemy sessions - DetachedInstanceError?

    - by benjaminhkaiser
    I have a function that attempts to take a list of usernames, look each one up in a user table, and then add them to a membership table. If even one username is invalid, I want the entire list to be rolled back, including any users that have already been processed. I thought that using sessions was the best way to do this but I'm running into a DetachedInstanceError: DetachedInstanceError: Instance <Organization at 0x7fc35cb5df90> is not bound to a Session; attribute refresh operation cannot proceed Full stack trace is here. The error seems to trigger when I attempt to access the user (model) object that is returned by the query. From my reading I understand that it has something to do with there being multiple sessions, but none of the suggestions I saw on other threads worked for me. Code is below: def add_members_in_bulk(organization_eid, users): """Add users to an organization in bulk - helper function for add_member()""" """Returns "success" on success and id of first failed student on failure""" session = query_session.get_session() session.begin_nested() users = users.split('\n') for u in users: try: user = user_lookup.by_student_id(u) except ObjectNotFoundError: session.rollback() return u if user: membership.add_user_to_organization( user.entity_id, organization_eid, '', [] ) session.flush() session.commit() return 'success' here's the membership.add_user_to_organization: def add_user_to_organization(user_eid, organization_eid, title, tag_ids): """Add a User to an Organization with the given title""" user = user_lookup.by_eid(user_eid) organization = organization_lookup.by_eid(organization_eid) new_membership = OrganizationMembership( organization_eid=organization.entity_id, user_eid=user.entity_id, title=title) new_membership.tags = [get_tag_by_id(tag_id) for tag_id in tag_ids] crud.add(new_membership) and here is the lookup by ID query: def by_student_id(student_id, include_disabled=False): """Get User by RIN""" try: return get_query_set(include_disabled).filter(User.student_id == student_id).one() except NoResultFound: raise ObjectNotFoundError("User with RIN %s does not exist." % student_id)

    Read the article

  • share image with url from database

    - by LauroSkr
    In my PHP web site will have a text converted to jpeg file,so it is a image. I want that i give users option to share the image. every image will have unique url so they can share image on facebook,twitter , do i need to put images with their url in mysql database or you do it in cloud? user will write text and then script will convert it to image and show it as image. then i want to provide user that he/she can share their created image. It would be great if you could provide me with a link or tutorial for my problem. Dont be hard on beginners,you were all in the same boat.. Thanks, LauroSkr

    Read the article

  • jquery accessing dynamic class selectors

    - by dinotom
    Given the following html rendering; <fieldset id="fld_Rye"> <legend>7 Main St.</legend> <div> <table> <tr> <th class="wideCol"><b><i>Service Description</i></b></th> <th class="wideCol"><b><i>Service Name</i></b></th> <th class="normalPlusWidth"><b><i>Contact Name</i></b></th> </tr> <ItemTemplate> <tr class=""> <td class="servDesc">&nbsp;<b>Plumbing Services</b></td> <td class="servName">&nbsp;<b>Flynnsters's Plumbing</b></td> <td class="servContact">&nbsp;<b>Jim Flynnster</b></td> </tr> </ItemTemplate> I am trying to access all the td's with a class of servDesc, get their width into an array and get the max width from that array to reset the css width of that class using jquery on page load. I cant seem to get the right selector for those tags, and I've tried at least 50 variations. My latest try; var maxTdWidth; var servDescCols = []; $("#fld_Rye td#servDesc").each(function () { alert("found one"); servDescCols.push(this.width()); }); maxTdWidth = Math.max.apply(Math, servDescCols);

    Read the article

  • How to navigate to another html page?

    - by newbie
    In my application there's a usual login page sending username and password to the server script, where it needs to be authenticated, and in case of an authentic user, the server should redirect to a page student.html. This is my code var ports = 3000; var portt = 3001; var express = require('express'); var student = require('express')(); var teacher = require('express')(); var server_s = require('http').createServer(student); var server_t = require('http').createServer(teacher); var ios = require('socket.io').listen(server_s); var iot = require('socket.io').listen(server_t); var path = require('path'); server_s.listen(ports); server_t.listen(portt); student.use(express.static(path.join(__dirname, 'public'))); student.get('/', function(req,res){ res.sendfile(__dirname + '/login.html'); }); teacher.use(express.static(path.join(__dirname, 'public'))); teacher.get('/', function(req,res){ res.sendfile(__dirname + '/mytry.html'); }); ios.sockets.on('connection', function(socket){ var username, password; socket.on('check',function(data){ username = data[0]; password = data[1]; //************* Database connection and query ************* var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'localhost', user : 'user', password: '*******', database: 'my_db' }); connection.connect(); var qstring = 'SELECT s_id FROM login_student WHERE username='+username+'AND password='+password; connection.query(qstring, function(err, rows, fields) { if (err) { console.log('ERROR: ' + err); socket.emit('login_failure','DB error'); return; } console.log('The solution is: ', rows[0].solution); if (rows>0) //***** Here i want redirection to another page ****** else socket.emit('login_failure','Invalid Username or password'); }); connection.end(); }); }); iot.sockets.on('connection', function(socket){ ; }); }); Can anyone suggest what should I do?

    Read the article

  • Django: Create custom template tag -> ImportError

    - by Alexander Scholz
    I'm sorry to ask this again, but I tried several solutions from stack overflow and some tutorials and I couldn't create a custom template tag yet. All I get is ImportError: No module named test_tag when I try to start the server via python manage.py runserver. I created a very basic template tag (found here: django templatetag?) like so: My folder structure: demo manage.py test __init__.py settings.py urls.py ... templatetags __init__.py test_tag.py test_tag.py: from django import template register = template.Library() @register.simple_tag def test_tag(input): if "foo" == input: return "foo" if "bar" == input: return "bar" if "baz" == input: return "baz" return "" index.html: {% load test_tag %} <html> <head> ... </head> <body> {% cms_toolbar %} {% foobarbaz "bar" %} {% foobarbaz "elephant" %} {% foobarbaz "foo" %} </body> </html> and my settings.py: INSTALLED_APPS = ( ... 'test_tag', ... ) Please let me know if you need further information from my settings.py and what I did wrong so I can't even start my server. (If I delete 'test_tag' from installed apps I can start the server but I get the error that test_tag is not known, of course). Thanks

    Read the article

  • Buttons, hover, text and transitions on pure css3

    - by Mascote Ricardo
    I bought a responsive html5 template to create a website for my band. But I miss a page of tour dates, and would create a unique content, simple and quick to load on any device. I have the idea ready, something like buttons (months) to change on hover and when clicked, shows the dates and cities, all with transitions and fadein / fadeout. (pure css3) to better explain and make me understand, follows an image I created in photoshop. http://img51.imageshack.us/img51/1542/l17u.jpg can someone give me a help, idea or tag to search the web, I thank you too!

    Read the article

  • Incorrect syntax inserting data into table

    - by SelectDistinct
    I am having some trouble with my update() method. The idea is that the user Provides a recipe name, ingredients, instructions and then selects an image using Filestream. Once the user clicks 'Add Recipe' this will call the update method, however as things stand I am getting an error which is mentioning the contents of the text box: Here is the update() method code: private void updatedata() { // filesteam object to read the image // full length of image to a byte array try { // try to see if the image has a valid path if (imagename != "") { FileStream fs; fs = new FileStream(@imagename, FileMode.Open, FileAccess.Read); // a byte array to read the image byte[] picbyte = new byte[fs.Length]; fs.Read(picbyte, 0, System.Convert.ToInt32(fs.Length)); fs.Close(); //open the database using odp.net and insert the lines string connstr = @"Server=mypcname\SQLEXPRESS;Database=RecipeOrganiser;Trusted_Connection=True"; SqlConnection conn = new SqlConnection(connstr); conn.Open(); string query; query = "insert into Recipes(RecipeName,RecipeImage,RecipeIngredients,RecipeInstructions) values (" + textBox1.Text + "," + " @pic" + "," + textBox2.Text + "," + textBox3.Text + ")"; SqlParameter picparameter = new SqlParameter(); picparameter.SqlDbType = SqlDbType.Image; picparameter.ParameterName = "pic"; picparameter.Value = picbyte; SqlCommand cmd = new SqlCommand(query, conn); cmd.Parameters.Add(picparameter); cmd.ExecuteNonQuery(); MessageBox.Show("Image successfully saved"); cmd.Dispose(); conn.Close(); conn.Dispose(); Connection(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } Can anyone see where I have gone wrong with the insert into Recipes query or suggest an alternative approach to this part of the code?

    Read the article

  • How to Append a div with javascript inside

    - by Damathryx
    I have this <div id="inprog_table"> </div> I tried this to insert var div = document.getElementById('inprog_table'); div.innerHTML = div.innerHTML+ "<div class='row'> <div class='col-xs-7'> "+ $(".row.active .col-xs-7 p:first-child").text()+" </div> <div class='col-xs-2'> "+ $(".row.active .col-xs-7 p:last-child").text()+" </div> <div class='col-xs-2'> 1 </div>" inside inprog_table div. I know it's really wrong, but I don't know how to append all of this.

    Read the article

  • How can i merge arrays like a gearwheel

    - by JuKe
    i have 3 arrays like this $a = array( 0 => 'a1', 1 => 'a2', 2 => 'a3' ); $b = array( 0 => 'b1', 1 => 'b2', 2 => 'b3' ); $c = array( 0 => 'c1', 1 => 'c2', 2 => 'c3' ); and i like to have somethink like this: $r = array( 0 => 'a1', 1 => 'b1', 2 => 'c1', 3 => 'a2', 4 => 'b2', 5 => 'c2', 6 => 'a3', .... ... ); how can i do this, with the opinion of more than 3 arrays EDIT: i have tried this: $a = array( 0 => 'a1', 1 => 'a2', 2 => 'a3', 3 => 'a4' ); $b = array( 0 => 'b1', 1 => 'b2', 2 => 'b3' ); $c = array( 0 => 'c1', 1 => 'c2', 2 => 'c3', 3 => 'c3', 4 => 'c3', 5 => 'c3' ); $l['a'] = count($a); $l['b'] = count($b); $l['c'] = count($c); arsort($l); $largest = key($l); $result = array(); foreach ($$largest as $key => $value) { $result[] = $a[$key]; if(array_key_exists($key, $b)) $result[] = $b[$key]; if(array_key_exists($key, $c)) $result[] = $c[$key]; } print_r($result); this work.. but the code isn't nice. so anyone has a better solution?

    Read the article

  • Java homework help, Error <identifier> expected

    - by user2900126
    Help with java homework this is my assignment that I have, this assignment code I've tried. But when I try to compile it I keep getting errors which I cant seem to find soloutions too: Error says <identifier> expected for Line 67 public static void () Assignment brief To write a simple java classMobile that models a mobile phone. Details the information stored about each mobile phone will include • Its type e.g. “Sony ericsson x90” or “Samsung Galaxy S”; • Its screen size in inches; You may assume that this a whole number from the scale 3 to 5 inclusive. • Its memory card capacity in gigabytes You may assume that this a whole number • The name of its present service provider You may assume this is a single line of text. • The type of contract with service provider You may assume this is a single line of text. • Its camera resolution in megapixels; You should not assume that this a whole number; • The percentage of charge left on the phone e.g. a fully charged phone will have a charge of 100. You may assume that this a whole number • Whether the phone has GPS or not. Your class will have fields corresponding to these attributes . Start by opening BlueJ, creating a new project called myMobile which has a classMobile and set up the fields that you need, Next you will need to write a Constructor for the class. Assume that each phone is manufactured by creating an object and specifying its type, its screen size, its memory card capacity, its camera resolution and whether it has GPS or not. Therefore you will need a constructor that allows you to pass arguments to initialise these five attributes. Other fields should be set to appropriate default values. You may assume that a new phone comes fully charged. When the phone is sold to its owner, you will need to set the service provider and type of contract with that provider so you will need mutator methods • setProvider () - - to set service provider. • setContractType - - to set the type of contract These methods will be used when the phones provider is changed. You should also write a mutator method ChargeUp () which simulates fully charging the phone. To obtain information about your mobile object you should write • accessor methods corresponding to four of its fields: • getType () – which returns the type of mobile; • getProvider () – which returns the present service provider; • getContractType () – which returns its type of contract; • getCharge () – which returns its remaining charge. An accessor method to printDetails () to print, to the terminal window, a report about the phone e.g. This mobile phone is a sony Erricsson X90 with Service provider BigAl and type of contract PAYG. At present it has 30% of its battery charge remaining. Check that the new method works correctly by for example, • creating a Mobile object and setting its fields; • calling printDetails () and t=checking the report corresponds to the details you have just given the mobile; • changing the service provider and contract type by calling setprovider () and setContractType (); • calling printDetails () and checking the report now prints out the new details. Challenging excercises • write a mutator methodswitchedOnFor () =which simulates using the phone for a specified period. You may assume the phone loses 1% of its charge for each hour that it is switched on . • write an accessor method checkcharge () whichg checks the phone remaing charge. If this charge has a value less than 25%, then this method returns a string containg the message Be aware that you will soon need to re-charge your phone, otherwise it returns a string your phone charge is sufficient. • Write a method changeProvider () which simulates changing the provider (and presumably also the type of service contract). Finally you may add up to four additional fields, with appropriate methods, that might be required in a more detailed model. above is my assignment that I have, this assignment code I've tried. But when I try to oompile it I keep getting errors which I cant seem to find soloutions too: Error says <identifier> expected for Line 67 public static void () /** * to write a simple java class Mobile that models a mobile phone. * * @author (Lewis Burte-Clarke) * @version (14/10/13) */ public class Mobile { // type of phone private String phonetype; // size of screen in inches private int screensize; // menory card capacity private int memorycardcapacity; // name of present service provider private String serviceprovider; // type of contract with service provider private int typeofcontract; // camera resolution in megapixels private int cameraresolution; // the percentage of charge left on the phone private int checkcharge; // wether the phone has GPS or not private String GPS; // instance variables - replace the example below with your own private int x; // The constructor method public Mobile(String mobilephonetype, int mobilescreensize, int mobilememorycardcapacity,int mobilecameraresolution,String mobileGPS, String newserviceprovider) { this.phonetype = mobilephonetype; this.screensize = mobilescreensize; this.memorycardcapacity = mobilememorycardcapacity; this.cameraresolution = mobilecameraresolution; this.GPS = mobileGPS; // you do not use this ones during instantiation,you can remove them if you do not need or assign them some default values //this.serviceprovider = newserviceprovider; //this.typeofcontract = 12; //this.checkcharge = checkcharge; Mobile samsungPhone = new Mobile("Samsung", "1024", "2", "verizon", "8", "GPS"); 1024 = screensize; 2 = memorycardcapacity; 8 = resolution; GPS = gps; "verizon"=serviceprovider; //typeofcontract = 12; //checkcharge = checkcharge; } // A method to display the state of the object to the screen public void displayMobileDetails() { System.out.println("phonetype: " + phonetype); System.out.println("screensize: " + screensize); System.out.println("memorycardcapacity: " + memorycardcapacity); System.out.println("cameraresolution: " + cameraresolution); System.out.println("GPS: " + GPS); System.out.println("serviceprovider: " + serviceprovider); System.out.println("typeofcontract: " + typeofcontract); } /** * The mymobile class implements an application that * simply displays "new Mobile!" to the standard output. */ public class mymobile { public static void main(String[] args) { System.out.println("new Mobile!"); //Display the string. } } public static void buildPhones(){ Mobile Samsung = new Mobile("Samsung", "3.0", "4gb", "8mega pixels", "GPS"); Mobile Blackberry = new Mobile("Blackberry", "3.0", "4gb", "8mega pixels", "GPS"); Samsung.displayMobileDetails(); Blackberry.displayMobileDetails(); } public static void main(String[] args) { buildPhones(); } } any answers.replies and help would be greatly appreciated as I really lost!

    Read the article

  • Variable loss in redirected bash while loop

    - by James Hadley
    I have the following code for ip in $(ifconfig | awk -F ":" '/inet addr/{split($2,a," ");print a[1]}') do bytesin=0; bytesout=0; while read line do if [[ $(echo ${line} | awk '{print $1}') == ${ip} ]] then increment=$(echo ${line} | awk '{print $4}') bytesout=$((${bytesout} + ${increment})) else increment=$(echo ${line} | awk '{print $4}') bytesin=$((${bytesin} + ${increment})) fi done < <(pmacct -s | grep ${ip}) echo "${ip} ${bytesin} ${bytesout}" >> /tmp/bwacct.txt done Which I would like to print the incremented values to bwacct.txt, but instead the file is full of zeroes: 91.227.223.66 0 0 91.227.221.126 0 0 127.0.0.1 0 0 My understanding of Bash is that a redirected for loop should preserve variables. What am I doing wrong?

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >