Daily Archives

Articles indexed Monday October 28 2013

Page 3/17 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Disable incognito in chrome or chromium

    - by TheIronKnuckle
    I'm addicted to certain websites to the point where it's interfering with my life regularly and sick of it. I want to install website blockers that aren't easy to circumvent. In Chrome, incognito mode is easily accessible with a ctrl-shift-n. That is ridiculous. Whenever I feel an urge to go on an addictive website, it doesn't matter what blockers and regulators I've got installed; three keys can get round them in a second. Simply uninstalling chrome isn't an option either, as it's way too easy to sudo apt-get install it right back. So yes, I want to disable incognito mode completely (and if possible making it totally impossible to get it back). I note that some guy has figured out how to do it on windows with a registry entry: http://wmwood.net/software/incognito-gone-get-rid-of-private-browsing/ If it can be done on windows it can be done on ubuntu!

    Read the article

  • PNG file loading error in ImageMagick

    - by khanhhh89
    I'm trying to understand the tutorial 16 at http://ogldev.atspace.co.uk, which requires the image processing library ImageMagick. But when I run the tutorial, I encountered an following error: freeglut: failed to change scree settings Error loading textures 'test.png': no decode delegates for this image format 'C:/../appdata/magick-6024a_cIJcw90t-j'@error/constitute.c/ReadImage/552 I searched for google and found that my ImageMagick library do not have PNG Delegaes, but when I checked for the information of ImageMagick, it sees PNG in its delegate lists. Command line: convert -configure Result: LIB_VERSION 0x687 DELEGATES: bzlib, freetype, jpeg, jp2, lcms, png, tiff, x11, xml, wmf, zlib Could you explain to me this error, thanks so much!

    Read the article

  • Checker AI in visual basic not working [on hold]

    - by Eugene Galkine
    I am trying to a make checkers in visual basic with ai. I am using the minimax algorithm (or at least what I understand of it) and it works, except the ai is retarded and plays like it is trying to loose and I tried to switch around the min and the max but the results are IDENTICAL. I am pissed of and have been trying to fix it for over a week now, I would really appreciate it if someone could help me out here. I have 3 years experience of programming (in Java, only about of month of VB experience) and I always am able to solve all my errors on my own so I don't know why I can't get this to work. The program is not at all optimized or anything at this point and is over 1.2K lines long, so here is the entire vb project instead: https://www.dropbox.com/sh/evii0jendn93ir2/9fntwH2dNW I would really appreciate any help I could get.

    Read the article

  • Help with collision detection method [on hold]

    - by derek jones
    I was wondering if any of you could spare me some time to go over some collision detection on my platform engine. i tried XNA a few years back but for reasons i wont go into online could not continue, my health is now at a state where i am ready to try again but due to my current circumstances (and age) schooling is out of the question so i turn to you guys for help. Whilst i can adapt the MS sample ok and have some great features, you will agree modifying code is not really learning. So i have spent the last couple of week going over my old MS code and lots of stuff online and decided on what i want and have ported most of it over to code that i understand 90% of. I have my player class that moves about, jumps with gravity, has animations and a bounding box that follows it around. I have my map & basic level class to load levels from text files. Its just how i handle the collisions that i am struggling with as i will want per pixel collision on some tiles(i have code for this in a pong game i made so that should be ok). I'm pretty clear in my mind on what i need to do its just putting it in code and in the right place, here's what i was thinking. I was going to do it all in layers, have a tile layer, a collision layer & an item layer this way i could make a nice map editor in Win Forms at some point. Anyway i need to read in the collision layer the assign each tile a rectangle and collision property, and this is where i get me. Would any of you be able to spare some time and go over this with me ? I will post some code later Regards Del

    Read the article

  • Multi Threading - How to split the tasks

    - by Motig
    if I have a game engine with the basic 'game engine' components, what is the best way to 'split' the tasks with a multi-threaded approach? Assuming I have the standard components of: Rendering Physics Scripts Networking And a quad-core, I see two ways of multi-threading: Option A ('Vertical'): Using this approach I can allow one core for each component of the engine; e.g. one core for the Rendering task, one for the Physics, etc. Advantages: I do not need to worry about thread-safety within each component I can take advantage of special optimizations provided for single-threaded access (e.g. DirectX offers a flag that can be set to tell it that you will only use single-threading) Option B ('Horizontal'): Using this approach, each task may be split up into 1 <= n <= numCores threads, and executed simultaneously, one after the other. Advantages: Allows for work-sharing, i.e. each thread can take over work still remaining as the others are still processing I can take advantage of libraries that are designed for multi-threading (i.e. ... DirectX) I think, in retrospect, I would pick Option B, but I wanted to hear you guys' thoughts on the matter.

    Read the article

  • How do I implement collision detection with a sprite walking up a rocky-terrain hill?

    - by detectivecalcite
    I'm working in SDL and have bounding rectangles for collisions set up for each frame of the sprite's animation. However, I recently stumbled upon the issue of putting together collisions for characters walking up and down hills/slopes with irregularly curved or rocky terrain - what's a good way to do collisions for that type of situation? Per-pixel? Loading up the points of the incline and doing player-line collision checking? Should I use bounding rectangles in general or circle collision detection?

    Read the article

  • Pixel Perfect Collision Detection in Cocos2dx

    - by Happybirthday
    I am trying to port the pixel perfect collision detection in Cocos2d-x the original version was made for Cocos2D and can be found here: http://www.cocos2d-iphone.org/forums/topic/pixel-perfect-collision-detection-using-color-blending/ Here is my code for the Cocos2d-x version bool CollisionDetection::areTheSpritesColliding(cocos2d::CCSprite *spr1, cocos2d::CCSprite *spr2, bool pp, CCRenderTexture* _rt) { bool isColliding = false; CCRect intersection; CCRect r1 = spr1-boundingBox(); CCRect r2 = spr2-boundingBox(); intersection = CCRectMake(fmax(r1.getMinX(),r2.getMinX()), fmax( r1.getMinY(), r2.getMinY()) ,0,0); intersection.size.width = fmin(r1.getMaxX(), r2.getMaxX() - intersection.getMinX()); intersection.size.height = fmin(r1.getMaxY(), r2.getMaxY() - intersection.getMinY()); // Look for simple bounding box collision if ( (intersection.size.width0) && (intersection.size.height0) ) { // If we're not checking for pixel perfect collisions, return true if (!pp) { return true; } unsigned int x = intersection.origin.x; unsigned int y = intersection.origin.y; unsigned int w = intersection.size.width; unsigned int h = intersection.size.height; unsigned int numPixels = w * h; //CCLog("Intersection X and Y %d, %d", x, y); //CCLog("Number of pixels %d", numPixels); // Draw into the RenderTexture _rt-beginWithClear( 0, 0, 0, 0); // Render both sprites: first one in RED and second one in GREEN glColorMask(1, 0, 0, 1); spr1-visit(); glColorMask(0, 1, 0, 1); spr2-visit(); glColorMask(1, 1, 1, 1); // Get color values of intersection area ccColor4B *buffer = (ccColor4B *)malloc( sizeof(ccColor4B) * numPixels ); glReadPixels(x, y, w, h, GL_RGBA, GL_UNSIGNED_BYTE, buffer); _rt-end(); // Read buffer unsigned int step = 1; for(unsigned int i=0; i 0 && color.g 0) { isColliding = true; break; } } // Free buffer memory free(buffer); } return isColliding; } My code is working perfectly if I send the "pp" parameter as false. That is if I do only a bounding box collision but I am not able to get it working correctly for the case when I need Pixel Perfect collision. I think the opengl masking code is not working as I intended. Here is the code for "_rt" _rt = CCRenderTexture::create(visibleSize.width, visibleSize.height); _rt-setPosition(ccp(origin.x + visibleSize.width * 0.5f, origin.y + visibleSize.height * 0.5f)); this-addChild(_rt, 1000000); _rt-setVisible(true); //For testing I think I am making a mistake with the implementation of this CCRenderTexture Can anyone guide me with what I am doing wrong ? Thank you for your time :)

    Read the article

  • custom string format 0,0 with slash or back slash

    - by Mamad R
    i have a WPF TextBox that user can type number in that . now i am searching for a string format that can separate TextBox number each 3 point (like 0,0) but i want separate text with Slash or Back Slash or another character. and we do not know how much point our number has. i am searching for string format not Linq solution or etc . i read Microsoft help but cant find any way . sample = 123456789 == 123/456/789 (good) --- 123,456,789 (bad)

    Read the article

  • Collections not read from hibernate/ehcache second-level-cache

    - by Mark van Venrooij
    I'm trying to cache lazy loaded collections with ehcache/hibernate in a Spring project. When I execute a session.get(Parent.class, 123) and browse through the children multiple times a query is executed every time to fetch the children. The parent is only queried the first time and then resolved from the cache. Probably I'm missing something, but I can't find the solution. Please see the relevant code below. I'm using Spring (3.2.4.RELEASE) Hibernate(4.2.1.Final) and ehcache(2.6.6) The parent class: @Entity @Table(name = "PARENT") @Cacheable @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, include = "all") public class ServiceSubscriptionGroup implements Serializable { /** The Id. */ @Id @Column(name = "ID") private int id; @OneToMany(fetch = FetchType.LAZY, mappedBy = "parent") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) private List<Child> children; public List<Child> getChildren() { return children; } public void setChildren(List<Child> children) { this.children = children; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Parent that = (Parent) o; if (id != that.id) return false; return true; } @Override public int hashCode() { return id; } } The child class: @Entity @Table(name = "CHILD") @Cacheable @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, include = "all") public class Child { @Id @Column(name = "ID") private int id; @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @JoinColumn(name = "PARENT_ID") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) private Parent parent; public int getId() { return id; } public void setId(final int id) { this.id = id; } private Parent getParent(){ return parent; } private void setParent(Parent parent) { this.parent = parent; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Child that = (Child) o; return id == that.id; } @Override public int hashCode() { return id; } } The application context: <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="annotatedClasses"> <list> <value>Parent</value> <value>Child</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.SQLServer2008Dialect</prop> <prop key="hibernate.hbm2ddl.auto">validate</prop> <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop> <prop key="hibernate.connection.charSet">UTF-8</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.use_sql_comments">true</prop> <!-- cache settings ehcache--> <prop key="hibernate.cache.use_second_level_cache">true</prop> <prop key="hibernate.cache.use_query_cache">true</prop> <prop key="hibernate.cache.region.factory_class"> org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</prop> <prop key="hibernate.generate_statistics">true</prop> <prop key="hibernate.cache.use_structured_entries">true</prop> <prop key="hibernate.cache.use_query_cache">true</prop> <prop key="hibernate.transaction.factory_class"> org.hibernate.engine.transaction.internal.jta.JtaTransactionFactory</prop> <prop key="hibernate.transaction.jta.platform"> org.hibernate.service.jta.platform.internal.JBossStandAloneJtaPlatform</prop> </props> </property> </bean> The testcase I'm running: @Test public void testGetParentFromCache() { for (int i = 0; i <3 ; i++ ) { getEntity(); } } private void getEntity() { Session sess = sessionFactory.openSession() sess.setCacheMode(CacheMode.NORMAL); Transaction t = sess.beginTransaction(); Parent p = (Parent) s.get(Parent.class, 123); Assert.assertNotNull(p); Assert.assertNotNull(p.getChildren().size()); t.commit(); sess.flush(); sess.clear(); sess.close(); } In the logging I can see that the first time 2 queries are executed getting the parent and getting the children. Furthermore the logging shows that the child entities as well as the collection are stored in the 2nd level cache. However when reading the collection a query is executed to fetch the children on second and third attempt.

    Read the article

  • Optimization of running total calculation in SQL for multiple values per join condition

    - by Kiril
    I have the following table (test_table): date value --------------- d1 10.0 d1 20.0 d2 60.0 d2 10.0 d2 -20.0 d3 40.0 I calculate the running total as follows. I use the same query twice, because first I need to calculate the values for a specifi date, and afterwards I can calculate the running total. Otherwise, joining the two tables where date is not unique, I would get too many results from the join: SELECT t1.date, SUM(t2.value) AS total FROM (SELECT date, SUM(value) AS value FROM test_table GROUP BY date) AS t1 JOIN (SELECT date, SUM(value) AS value FROM test_table GROUP BY date) AS t2 ON t1.date >= t2.date GROUP BY t1.date ORDER BY t1.date This gives me (which is fine): date total ------------- d1 30.0 d2 80.0 d3 120.0 BUT, this query isn't very efficient, because I need to change conditions in two places, if necessary. In production, the test_table is a lot bigger ( 4 Mio. rows), and the query takes too much time to complete. Question: How can I avoid using the same query twice?

    Read the article

  • I can't compile android projetc wiht JNI code

    - by lobi
    I'm trying to build simple android app with some JNI code. When I press build project in eclipse I get this error: Description Resource Path Location Type fatal error: algorithm: No such file or directory Tracker line 56, external location: /home/slani/code/OpenCV-2.4.6-android-sdk/sdk/native/jni/include/opencv2/core/core.hpp C/C++ Problem make: *** [obj/local/armeabi/objs/detect_jni/detect_jni.o] Error 1 Tracker C/C++ Problem Line 56 in core.hpp contains the relevant include. This is my Android.mk file jni folder: LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) include /home/slani/code/OpenCV-2.4.6-android-sdk/sdk/native/jni/OpenCV.mk LOCAL_MODULE := detect_jni LOCAL_SRC_FILES := detect_jni.cpp include $(BUILD_SHARED_LIBRARY) This is my Aplication.mk file in jni folder: APP_STL := gnustl_static APP_CPPFLAGS := -frtti -fexceptions APP_ABI := armeabi-v7a APP_PLATFORM := all This is my .cpp file: #include <jni.h> #include <opencv/cv.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/features2d/features2d.hpp> using namespace cv; extern "C"{ JNIEXPORT void JNICALL Java_com_slani_tracker_OpenCamera_findObject((JNIEnv *env, jlong addRgba, jlong addHsv); JNIEXPORT void JNICALL Java_com_slani_tracker_OpenCamera_findObject((JNIEnv *env, jlong addRgba, jlong addHsv) { Mat& rgba = *(Mat*)addRgba; Mat& hsv = *(Mat*)addHsv; cvtColor(rgba, hsv,CV_RGBA2HSV); } } Can someone please help me? What could be causing this problem? Thanks

    Read the article

  • Can some explain why this wont draw a circle? It is drawing roughly 3/4?

    - by Brandon Shockley
    If we want to use n small lines to outline our circle then we can just divide both the circumference and 360 degrees by n (i.e , (2*pi*r)/n and 360/n). Did I not do that? import turtle, math window = turtle.Screen() window.bgcolor('blue') body = turtle.Turtle() body.pencolor('black') body.fillcolor('white') body.speed(10) body.width(3) body.hideturtle() body.up() body.goto(0, 200) lines = 40 toprad = 40 top_circum = 2 * math.pi * toprad sol = top_circum / lines circle = 360 / lines for stops in range(lines): body.pendown() body.left(sol) body.forward(circle) window.exitonclick()

    Read the article

  • Union results of two functions in php class

    - by Max
    I have php class(simple example): <?php class test{ public function __construct() { //some code } public function __destruct() { //some code } public function echo1 { //some code return 1; } public function echo2 { //some code return 2; } } How could I return results of this two functions echo1 and echo2 in class in one row don't creating two new objects for each function?

    Read the article

  • How to avoid CSS conflict using jquery?

    - by user2885137
    I am experiencing a CSS conflict issue. Here are the details: I have a search results page in which products are shown in grid format. The CSS for that is grid search results is "product-grid.css" which is included header of the page. On this page I have button which when clicked shows the search results in list format. The css for list format is "product-list.css" which is also included in head tag of the page. Now the HTML guy has made the name of classes to be same in both product-grid.css and product-list.css. What I want is that when I am viewing the page in grid style only product-grid.css should apply to respective portion of the page. And when I am viewing the page in list format then product-grid.css should be disabled and product-list.css should apply on whole page. I have tried enabling and disabling css files using jquery but may be I am doing something wrong. Also when the page loads both css files are active in head tag and due to conflict in classes names the page is malformed even without shifting to other view. Any help what should I do?

    Read the article

  • Programmatically adding an object and selecting the correspondig row does not make it become the CurrentRow

    - by Robert
    I'm in a struggle with the DataGridView: I do have a BindingList of some simple objects that implement INotifyPropertyChanged. The DataGridView's datasource is set to this BindingList. Now I need to add an object to the list by hitting the "+" key. When an object is added, it should appear as a new row and it shall become the current row. As the CurrentRow-property is readonly, I iterate through all rows, check if its bound item is the newly created object, and if it is, I set this row to "Selected = true;" The problem: although the new object and thereby a new row gets inserted and selected in the DataGridView, it still is not the CurrentRow! It does not become the CurrentRow unless I do a mouse click into this new row. In this test program you can add new objects (and thereby rows) with the "+" key, and with the "i" key the data-bound object of the CurrentRow is shown in a MessageBox. How can I make a newly added object become the CurrentObject? Thanks for your help! Here's the sample: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { BindingList<item> myItems; public Form1() { InitializeComponent(); myItems = new BindingList<item>(); for (int i = 1; i <= 10; i++) { myItems.Add(new item(i)); } dataGridView1.DataSource = myItems; } public void Form1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Add) { addItem(); } } public void addItem() { item i = new item(myItems.Count + 1); myItems.Add(i); foreach (DataGridViewRow dr in dataGridView1.Rows) { if (dr.DataBoundItem == i) { dr.Selected = true; } } } private void btAdd_Click(object sender, EventArgs e) { addItem(); } private void dataGridView1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Add) { addItem(); } if (e.KeyCode == Keys.I) { MessageBox.Show(((item)dataGridView1.CurrentRow.DataBoundItem).title); } } } public class item : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private int _id; public int id { get { return _id; } set { this.title = "This is item number " + value.ToString(); _id = value; InvokePropertyChanged(new PropertyChangedEventArgs("id")); } } private string _title; public string title { get { return _title; } set { _title = value; InvokePropertyChanged(new PropertyChangedEventArgs("title")); } } public item(int id) { this.id = id; } #region Implementation of INotifyPropertyChanged public void InvokePropertyChanged(PropertyChangedEventArgs e) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, e); } #endregion } }

    Read the article

  • Android - doInBackground() error in AsyncTask

    - by AimanB
    What my app here basically does is it captures a photo or import from gallery, and when the Upload button is pressed, the image will be uploaded to a localhost server. Before I implemented AsyncTask into the process, it doesn't have any problem uploading whatsoever. Now that I've put AsyncTask, everything went wrong. I don't know which part that I do wrong in this phase. This is what logcat shows when I try to upload an image file: 10-28 17:23:25.989: E/AndroidRuntime(3356): FATAL EXCEPTION: AsyncTask #5 10-28 17:23:25.989: E/AndroidRuntime(3356): java.lang.RuntimeException: An error occured while executing doInBackground() 10-28 17:23:25.989: E/AndroidRuntime(3356): at android.os.AsyncTask$3.done(AsyncTask.java:299) 10-28 17:23:25.989: E/AndroidRuntime(3356): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352) 10-28 17:23:25.989: E/AndroidRuntime(3356): at java.util.concurrent.FutureTask.setException(FutureTask.java:219) 10-28 17:23:25.989: E/AndroidRuntime(3356): at java.util.concurrent.FutureTask.run(FutureTask.java:239) 10-28 17:23:25.989: E/AndroidRuntime(3356): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 10-28 17:23:25.989: E/AndroidRuntime(3356): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 10-28 17:23:25.989: E/AndroidRuntime(3356): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 10-28 17:23:25.989: E/AndroidRuntime(3356): at java.lang.Thread.run(Thread.java:856) 10-28 17:23:25.989: E/AndroidRuntime(3356): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() 10-28 17:23:25.989: E/AndroidRuntime(3356): at android.os.Handler.<init>(Handler.java:197) 10-28 17:23:25.989: E/AndroidRuntime(3356): at android.os.Handler.<init>(Handler.java:111) 10-28 17:23:25.989: E/AndroidRuntime(3356): at android.widget.Toast$TN.<init>(Toast.java:324) 10-28 17:23:25.989: E/AndroidRuntime(3356): at android.widget.Toast.<init>(Toast.java:91) 10-28 17:23:25.989: E/AndroidRuntime(3356): at android.widget.Toast.makeText(Toast.java:238) 10-28 17:23:25.989: E/AndroidRuntime(3356): at com.aiman.webshopper.UploadImageActivity$1execMultiPostAsync.doInBackground(UploadImageActivity.java:268) 10-28 17:23:25.989: E/AndroidRuntime(3356): at com.aiman.webshopper.UploadImageActivity$1execMultiPostAsync.doInBackground(UploadImageActivity.java:1) 10-28 17:23:25.989: E/AndroidRuntime(3356): at android.os.AsyncTask$2.call(AsyncTask.java:287) 10-28 17:23:25.989: E/AndroidRuntime(3356): at java.util.concurrent.FutureTask.run(FutureTask.java:234) This is my code for the Upload activity: public class UploadImageActivity extends Activity implements OnItemSelectedListener { InputStream inputStream; private ImageView imageView; String the_string_response; private static final int SELECT_PICTURE = 0; private static final int CAMERA_REQUEST = 1888; private static final String SERVER_UPLOAD_URI = "...myserver.php"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_upload_image); imageView = (ImageView) findViewById(R.id.imgUpload); } public void capturePhoto(View view) { Intent cameraIntent = new Intent( android.provider.MediaStore.ACTION_IMAGE_CAPTURE); File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg"); cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)); startActivityForResult(cameraIntent, CAMERA_REQUEST); } public void pickPhoto(View view) { // TODO: launch the photo picker Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) { File f = new File(Environment.getExternalStorageDirectory() .toString()); for (File temp : f.listFiles()) { if (temp.getName().equals("temp.jpg")) { f = temp; break; } } try { BitmapFactory.Options bitmapOptions = new BitmapFactory.Options(); Bitmap bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), bitmapOptions); imageView.setImageBitmap(bitmap); String path = android.os.Environment .getExternalStorageDirectory() + File.separator + "Phoenix" + File.separator + "default"; f.delete(); OutputStream outFile = null; File file = new File(path, String.valueOf(System .currentTimeMillis()) + ".jpg"); try { outFile = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile); outFile.flush(); outFile.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } } if (requestCode == SELECT_PICTURE && resultCode == RESULT_OK) { Bitmap bitmap = getPath(data.getData()); imageView.setImageBitmap(bitmap); } } private Bitmap getPath(Uri uri) { String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(uri, projection, null, null, null); int column_index = cursor.getColumnIndexOrThrow(projection[0]); cursor.moveToFirst(); String filePath = cursor.getString(column_index); cursor.close(); // Convert file path into bitmap image using below line. Bitmap bitmap = BitmapFactory.decodeFile(filePath); return bitmap; } public void uploadPhoto(View view) { try { executeMultipartPost(); } catch (Exception e) { e.printStackTrace(); } } public void executeMultipartPost() throws Exception { class execMultiPostAsync extends AsyncTask<String, Void, String>{ @Override protected String doInBackground(String... params){ // Choose image here BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable(); Bitmap bitmap = drawable.getBitmap(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 50, stream); // compress to // which // format // you want. byte[] byte_arr = stream.toByteArray(); String image_str = Base64.encodeBytes(byte_arr); ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("image", image_str)); try { HttpClient httpclient = new DefaultHttpClient(); /* * HttpPost(parameter): Server URI */ HttpPost httppost = new HttpPost(SERVER_UPLOAD_URI); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); the_string_response = convertResponseToString(response); } catch (Exception e) { Toast.makeText(UploadImageActivity.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show(); System.out.println("Error in http connection " + e.toString()); } return the_string_response; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); Toast.makeText(UploadImageActivity.this, "Response " + result, Toast.LENGTH_LONG) .show(); } public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException { String res = ""; StringBuffer buffer = new StringBuffer(); inputStream = response.getEntity().getContent(); int contentLength = (int) response.getEntity().getContentLength(); // getting // content // lengt Toast.makeText(UploadImageActivity.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show(); if (contentLength < 0) { } else { byte[] data = new byte[512]; int len = 0; try { while (-1 != (len = inputStream.read(data))) { buffer.append(new String(data, 0, len)); // converting to // string and // appending to // stringbuffer } } catch (IOException e) { e.printStackTrace(); } try { inputStream.close(); // closing the stream } catch (IOException e) { e.printStackTrace(); } res = buffer.toString(); // converting stringbuffer to string Toast.makeText(UploadImageActivity.this, "Result : " + res, Toast.LENGTH_LONG).show(); // System.out.println("Response => " + // EntityUtils.toString(response.getEntity())); } return res; } } execMultiPostAsync exec = new execMultiPostAsync(); exec.execute(); } } Can someone please check if I put the AsyncTask task correctly in this activity? I think I've made a mistake somewhere.

    Read the article

  • How to append text into text file dynamically

    - by niraj deshmukh
    [12] key1=val1 key2=val2 key3=val3 key4=val4 key5=val5 [13] key1=val1 key2=val2 key3=val3 key4=val4 key5=xyz [14] key1=val1 key2=val2 key3=val3 key4=val4 key5=val5 I want to update key5=val5 where [13]. try { br = new BufferedReader(new FileReader(oldFileName)); bw = new BufferedWriter(new FileWriter(tmpFileName)); String line; while ((line = br.readLine()) != null) { System.out.println(line); if (line.contains("[13]")) { while (line.contains("key5")) { if (line.contains("key5")) { line = line.replace("key5", "key5= Val5"); bw.write(line+"\n"); } } } } } catch (Exception e) { return; } finally { try { if(br != null) br.close(); } catch (IOException e) { // } try { if(bw != null) bw.close(); } catch (IOException e) { // } }

    Read the article

  • Variable from block is put into a calculation but throws off wrong reading

    - by user2926620
    I am having troubles with trying to retrieve a double variable that is already established outside the block and called inside but I want to return the value of the same variable so that I can apply it to a calculation. the variable that I want returned is: double quarter = 0; but when I plug it into quarter in my first else/if statement, it plugs in 0 and not the value in my switch block. What can I do to retrieve the value? double quarter = 0; //Date entry will be calculated by how much KW user enters switch (input) { case "2/15/13": quarter = kwUsed * 0.10; break; case "4/15/13": quarter = kwUsed * 0.12; break; case "8/15/13": quarter = kwUsed * 0.15; break; case "11/15/13": quarter = kwUsed * 0.15; break; default: System.out.println("Invalid date"); } //Declaring variables for calculations double base = 0; double over = 0; double excess = 0; double math1 = 0; double math2 = 0; //KW Calculations if (kwUsed <= 350) { base = quarter; }else if (kwUsed <= 500) { math1 = ((kwUsed - 350) * quarter); base = ((kwUsed * quarter) - math1); over = ((math1 * 0.1) + math1); }else if (kwUsed > 500) { math2 = ((kwUsed - 350) * 0.1); base = ((kwUsed * 0.1) - math2); math2 = ((kwUsed -350) - 50); over = ((math2 * 0.1) + (15 * 0.1)); double math3 =((kwUsed - 500) * 0.1); excess = ((math3 * 0.25) + math3); } Edited to clarify question.

    Read the article

  • How to retain a row which is foreign key in another table and remove other duplicate rows?

    - by Mithril
    I have two table: A: id code 1 A1 2 A1 3 B1 4 B1 5 C1 6 C1 ===================== B: id Aid 1 1 2 4 (B doesn't contain the Aid which link to code C1) Let me explain the overall flow: I want to make each row in table A have different code(by delete duplicate),and I want to retain the Aid which I can find in table B.If Aid which not be saved in table B,I retain the id bigger one. so I can not just do something as below: DELETE FROM A WHERE id NOT IN (SELECT MAX(id) FROM A GROUP BY code, ) I can get each duplicate_code_groups by below sql statement: SELECT code FROM A GROUP BY code HAVING COUNT(*) > 1 Is there some code in sql like for (var ids in duplicate_code_groups){ for (var id in ids) { if (id in B){ return id } } return max(ids) } and put the return id into a idtable?? I just don't know how to write such code in sql. then I can do DELETE FROM A WHERE id NOT IN idtable

    Read the article

  • Insert and remove Template textbox column in grid view

    - by user1545215
    class TextColumn : ITemplate { private string controlId; private string cssClass; public TextColumn(string id, string cssClass = "inputFromTo") { controlId = id; this.cssClass = cssClass; } public void InstantiateIn(Control container) { TextBox txt = new TextBox(); txt.ID = controlId; txt.CssClass = cssClass; container.Visible = true; container.Controls.Add(txt); } } /******************* Add column code snippet ***************/ TemplateField dentry = new TemplateField(); TemplateField dexit = new TemplateField(); TemplateField dslack = new TemplateField(); dentry.ItemTemplate = new TextColumn("txtHH" + nameCount + "DEntry"); dexit.ItemTemplate = new TextColumn("txtHH" + nameCount + "DExit"); dslack.ItemTemplate = new TextColumn("txtHH" + nameCount + "DSlack"); gvOfcBlowingReport.Columns.Insert(startPoint, dentry); gvOfcBlowingReport.Columns.Insert(startPoint + 1, dexit); gvOfcBlowingReport.Columns.Insert(startPoint + 2, dslack); /***************** Remove column code snippet ************/ gvOfcBlowingReport.Columns.RemoveAt(startPoint - 1); gvOfcBlowingReport.Columns.RemoveAt(startPoint - 2); gvOfcBlowingReport.Columns.RemoveAt(startPoint - 3); // after executing this code all the columns vanish. Anyone know how to remove this text box template column?

    Read the article

  • list in loop, Nonetype errors

    - by user2926755
    Here is my Code def printList(stringlist): empty = [] if stringlist is None: print empty else: print stringlist def add (stringlist, string): string = [] if string is None else string if stringlist is not None: stringlist.insert(0, string) else: stringlist.append(1) it somehow appears "AttributeError: 'NoneType' object has no attribute 'append'" I was originally looking for the code to be run like this: >>> myList = None >>> printList(myList) [] >>> for word in ['laundry','homework','cooking','cleaning']: myList = add(myList, word) printList(myList) [laundry] [homework, laundry] [cooking, homework, laundry] [cleaning, cooking, homework, laundry]

    Read the article

  • i want to search my database for example i want to search the word "google yahoo"

    - by user2926370
    i want to search my database for example i want to search the word "google yahoo" and when i enter that i should able to look the rows which has google and yahoo. It is not required to be in the same order and google besides yahoo. No matter wherever it is in the line and give me a simple logic to it. i can able to query that thing.something like select * from table where column like("%google%yahoo%"). I want to develop this thing in php but how can i insert %. Do i need to use if statement so that i can insert % in between the words whenever i find spaces orelse is there any other logic to do it simpler?

    Read the article

  • Imitating Mouse click - point with known coordinates on a fusion table layer - google maps

    - by Yavor Tashev
    I have been making a script using a fusion table's layer in google maps. I am using geocoder and get the coordinates of a point that I need. I put a script that changes the style of a polygon from the fusion table when you click on it, using the google.maps.event.addListener(layer, "click", function(e) {}); I would like to use the same function that I call in the case of a click on the layer, but this time with a click with the coordinates that I got. I have tried google.maps.event.trigger(map, 'click', {latLng: new google.maps.LatLng(42.701487,26.772308)}); As well as the example here Google Fusion Table Double Click (dblClick) I have tried changing map with layer... I am sorry if my question is quite stupid, but I have tried many options. P.S. I have seen many post about getting the info from the table, but I do not need that. I want to change the style of the KML element in the selected row, so I do not see it happening by a query. Here is the model of my script: function initialize() { geocoder = new google.maps.Geocoder(); map = new google.maps.Map(document.getElementById("map_canvas"),myOptions); layer = new google.maps.FusionTablesLayer({ suppressInfoWindows:true, map : map, query : { select: '??????????????', from: '12ZoroPjIfBR4J-XwM6Rex7LmfhzCDJc9_vyG5SM' } }); google.maps.event.addListener(layer, "click", function(e) { SmeniStilRaionni(layer,e); marker.setMap(null); }); } function SmeniStilRaionni(layer,e) { ... } function showAddress(address) { geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { var point = results[0].geometry.location; //IMITATE THE CLICK } }); } In response to geocodezip This way you hide all the other elements... I do not wish that. It is like if I want to change the border of the selected element. And I do not wish for a new layer. In the function that I use now I push the style of the options of the layer and then set the option. I use the e from google.maps.event.addListener(layer, "click", function(e)); by inserting e.row['Name'].value inside the where rule. I would like to ask you if there is any info on the e variable in google.maps.event.addListener(layer, "click", function(e)); I found out how to get the results I wanted: For my query after I get the point I use this: var queryText ="SELECT '??????? ???','??????? ???','?????????? ???','??????????????' FROM "+FusionTableID+" WHERE ST_INTERSECTS(\'??????????????\', CIRCLE(LATLNG(" + point.toUrlValue(6) + "),0.5));"; queryText = encodeURIComponent(queryText); document.getElementById("vij query").innerHTML = queryText; var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText); And then I get these results: var rsyd = response.getDataTable().getValue(0,0); var osyd = response.getDataTable().getValue(0,1); var apsyd = response.getDataTable().getValue(0,2); And then, I use the following: where: "'??????? ???' = '"+rsyd+"'", Which is the same as: where: "'??????? ???' = '"+e.row['??????? ???'].value+"'", in the click function. This is a working solution for my problem. But still, I cannot find a way to Imitate a Mouse click.

    Read the article

  • KnpLabs / DoctrineBehaviors Translatable - currentLocale = null

    - by Ruben
    Using the trait \Knp\DoctrineBehaviors\Model\Translatable\Translation inside an Entity, I see that the property currentLocale is never setted , so we always obtain the default locale ('en') in all the calls to $this->translate(). If I change this getDefaultLocale, all the translations are made correctly, so I think that is no problem with the fallback. I tried debug the currentLocaleCallable. I see that if I put a "var_dump ($this-container-get('request'));" in the contructor of currentLocaleCallable, the request have a locale to null. And outside the request has the correct locale.It seems that container is not in the scope: request , i don't know how can I get it to work I post an issue in github https://github.com/KnpLabs/DoctrineBehaviors/issues/71 EDITED This service is defined in vendor/knplabs/doctrine-behaviors/config/orm-services.yml and is: knp.doctrine_behaviors.reflection.class_analyzer: class: "%knp.doctrine_behaviors.reflection.class_analyzer.class%" public: false knp.doctrine_behaviors.translatable_listener: class: "%knp.doctrine_behaviors.translatable_listener.class%" public: false arguments: - "@knp.doctrine_behaviors.reflection.class_analyzer" - "%knp.doctrine_behaviors.reflection.is_recursive%" - "@knp.doctrine_behaviors.translatable_listener.current_locale_callable" tags: - { name: doctrine.event_subscriber } knp.doctrine_behaviors.translatable_listener.current_locale_callable: class: "%knp.doctrine_behaviors.translatable_listener.current_locale_callable.class%" arguments: - "@service_container" # lazy request resolution public: false EDIT 2: My composer.json "php": ">=5.3.3", "symfony/symfony": "2.3.*", "doctrine/orm": ">=2.2.3,<2.4-dev", "doctrine/doctrine-bundle": "1.2.*", "twig/extensions": "1.0.*", "symfony/assetic-bundle": "2.3.*", "symfony/swiftmailer-bundle": "2.3.*", "symfony/monolog-bundle": "2.3.*", "sensio/distribution-bundle": "2.3.*", "sensio/framework-extra-bundle": "2.3.*", "sensio/generator-bundle": "2.3.*", "incenteev/composer-parameter-handler": "~2.0", "friendsofsymfony/user-bundle": "1.3.*", "avalanche123/imagine-bundle": "v2.1", "raulfraile/ladybug-bundle": "~1.0", "genemu/form-bundle": "2.2.*", "friendsofsymfony/rest-bundle": "0.12.0", "stof/doctrine-extensions-bundle": "dev-master", "sonata-project/admin-bundle": "dev-master", "a2lix/translation-form-bundle": "1.*@dev", "sonata-project/user-bundle": "dev-master", "psliwa/pdf-bundle": "dev-master", "jms/serializer-bundle": "dev-master", "jms/di-extra-bundle": "dev-master", "knplabs/doctrine-behaviors": "dev-master", "sonata-project/doctrine-orm-admin-bundle": "dev-master", "knplabs/knp-paginator-bundle": "dev-master", "friendsofsymfony/jsrouting-bundle": "~1.1", "zendframework/zend-validator": ">=2.0.0-rc2", "zendframework/zend-barcode": ">=2.0.0-rc2"

    Read the article

  • Adding picture in symfony 2 from symfony form?

    - by user2833510
    How do I add a picture in symfony2 from form to a database. I want to make a logo as a picture field and store project picture in database from form. How do I do this? Here is my form: <?php namespace Projects\ProjectsBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class ProjectsType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('name') ->add('description') ->add('priority','choice', array( 'choices' => array('high' => 'high', 'low' => 'low', 'medium' => 'medium'))) ->add('logo') ->add('startedAt','datetime',array('label' => false,'data'=>new \DateTime(),'attr'=>array('style'=>'display:none;'))) ->add('completedOn','datetime',array('label' => false,'data'=>new \DateTime(),'attr'=>array('style'=>'display:none;'))) ->add('createdDatetime','datetime',array('label' => false,'data'=>new \DateTime(),'attr'=>array('style'=>'display:none;'))) ->add('updatedDatetime','datetime',array('label' => false,'data'=>new \DateTime(),'attr'=>array('style'=>'display:none;'))) ; } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Projects\ProjectsBundle\Entity\Projects' )); } public function getName() { return 'projects_projectsbundle_projectstype'; } } and here is my controller: public function createAction(Request $request) { $user = $this->get('security.context')->getToken()->getUser(); $userId = $user->getId(); $entity = new Projects(); $form = $this->createForm(new ProjectsType(), $entity); $form->bind($request); $entity->setCreatedBy($userId); $entity->setUpdatedBy($userId); $entity->setCompletedBy($userId); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($entity); $em->flush(); $_SESSION['projectid'] =$entity->getId(); if($request->isXmlHttpRequest()) { $response = new Response(); $output = array('success' => true, 'description' => $entity->getdescription(), 'id' => $entity->getId(), 'name' => $entity->getname(), 'priority' => $entity->getpriority(), 'logo' => $entity->getlogo(), 'startedat' => $entity->getstartedat(),'completedon' => $entity->getcompletedon(),'completedby' => $entity->getCompletedBy(), 'createdby' => $entity->getcreatedby(), 'updatedby' => $entity->getupdatedby(), 'createddatetime' => $entity->getcreateddatetime(), 'updateddatetime' => $entity->getupdateddatetime()); $response->headers->set('Content-Type', 'application/json'); $response->setContent(json_encode($output)); return $response; } return $this->redirect($this->generateUrl('projects_show', array('id' => $entity->getId()))); } return $this->render('ProjectsProjectsBundle:Projects:new.html.twig', array( 'entity' => $entity, 'form' => $form->createView(), )); }

    Read the article

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