Search Results

Search found 2136 results on 86 pages for 'dominik str'.

Page 10/86 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • String replacment in batch file

    - by Faisal
    We can replace strings in a batch file using the following command set str="jump over the chair" set str=%str:chair=table% These lines work fine and change the string "jump over the chair" to "jump over the table". Now I want to replace the word "chair" in the string with some variable and I don't know how to do it. set word=table set str="jump over the chair" ?? Any ideas?

    Read the article

  • Feedback on Optimizing C# NET Code Block

    - by Brett Powell
    I just spent quite a few hours reading up on TCP servers and my desired protocol I was trying to implement, and finally got everything working great. I noticed the code looks like absolute bollocks (is the the correct usage? Im not a brit) and would like some feedback on optimizing it, mostly for reuse and readability. The packet formats are always int, int, int, string, string. try { BinaryReader reader = new BinaryReader(clientStream); int packetsize = reader.ReadInt32(); int requestid = reader.ReadInt32(); int serverdata = reader.ReadInt32(); Console.WriteLine("Packet Size: {0} RequestID: {1} ServerData: {2}", packetsize, requestid, serverdata); List<byte> str = new List<byte>(); byte nextByte = reader.ReadByte(); while (nextByte != 0) { str.Add(nextByte); nextByte = reader.ReadByte(); } // Password Sent to be Authenticated string string1 = Encoding.UTF8.GetString(str.ToArray()); str.Clear(); nextByte = reader.ReadByte(); while (nextByte != 0) { str.Add(nextByte); nextByte = reader.ReadByte(); } // NULL string string string2 = Encoding.UTF8.GetString(str.ToArray()); Console.WriteLine("String1: {0} String2: {1}", string1, string2); // Reply to Authentication Request MemoryStream stream = new MemoryStream(); BinaryWriter writer = new BinaryWriter(stream); writer.Write((int)(1)); // Packet Size writer.Write((int)(requestid)); // Mirror RequestID if Authenticated, -1 if Failed byte[] buffer = stream.ToArray(); clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); } I am going to be dealing with other packet types as well that are formatted the same (int/int/int/str/str), but different values. I could probably create a packet class, but this is a bit outside my scope of knowledge for how to apply it to this scenario. If it makes any difference, this is the Protocol I am implementing. http://developer.valvesoftware.com/wiki/Source_RCON_Protocol

    Read the article

  • c#: can you use a boolean predicate as the parameter to an if statement?

    - by Craig Johnston
    In C#, can you use a boolean predicate on its own as the parameter for an if statement? eg: string str = "HELLO"; if (str.Equals("HELLO")) { Console.WriteLine("HELLO"); } Will this code output "HELLO", or does it need to be: string str = "HELLO"; if (str.Equals("HELLO") == true) { Console.WriteLine("HELLO"); } If there is anything else wrong with the above code segments, please point it out.

    Read the article

  • C++ STL: Trouble with iterators

    - by Rosarch
    I'm having a beginner problem: bool _isPalindrome(const string& str) { return _isPalindrome(str.begin(), str.end()); // won't compile } bool _isPalindrome(string::iterator begin, string::iterator end) { return begin == end || *begin == *end && _isPalindrome(++begin, --end); } What am I doing wrong here? Why doesn't str.begin() get type checked to be a string::iterator?

    Read the article

  • Add collison detection to enemy sprites?

    - by xBroak
    i'd like to add the same collision detection used by the player sprite to the enemy sprites or 'creeps' ive added all the relevant code I can see yet collisons are still not being detected and handled, please find below the class, I have no idea what is wrong currently, the list of walls to collide with is 'wall_list' import pygame import pauseScreen as dm import re from pygame.sprite import Sprite from pygame import Rect, Color from random import randint, choice from vec2d import vec2d from simpleanimation import SimpleAnimation import displattxt black = (0,0,0) white = (255,255,255) blue = (0,0,255) green = (101,194,151) global currentEditTool currentEditTool = "Tree" global editMap editMap = False open('MapMaker.txt', 'w').close() def draw_background(screen, tile_img): screen.fill(black) img_rect = tile_img.get_rect() global rect rect = img_rect nrows = int(screen.get_height() / img_rect.height) + 1 ncols = int(screen.get_width() / img_rect.width) + 1 for y in range(nrows): for x in range(ncols): img_rect.topleft = (x * img_rect.width, y * img_rect.height) screen.blit(tile_img, img_rect) def changeTool(): if currentEditTool == "Tree": None elif currentEditTool == "Rock": None def pauseGame(): red = 255, 0, 0 green = 0,255, 0 blue = 0, 0,255 screen.fill(black) pygame.display.update() if editMap == False: choose = dm.dumbmenu(screen, [ 'Resume', 'Enable Map Editor', 'Quit Game'], 64,64,None,32,1.4,green,red) if choose == 0: print("hi") elif choose ==1: global editMap editMap = True elif choose ==2: print("bob") elif choose ==3: print("bob") elif choose ==4: print("bob") else: None else: choose = dm.dumbmenu(screen, [ 'Resume', 'Disable Map Editor', 'Quit Game'], 64,64,None,32,1.4,green,red) if choose == 0: print("Resume") elif choose ==1: print("Dis ME") global editMap editMap = False elif choose ==2: print("bob") elif choose ==3: print("bob") elif choose ==4: print("bob") else: None class Wall(pygame.sprite.Sprite): # Constructor function def __init__(self,x,y,width,height): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface([width, height]) self.image.fill(green) self.rect = self.image.get_rect() self.rect.y = y self.rect.x = x class insertTree(pygame.sprite.Sprite): def __init__(self,x,y,width,height, typ): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("images/map/tree.png").convert() self.image.set_colorkey(white) self.rect = self.image.get_rect() self.rect.y = y self.rect.x = x class insertRock(pygame.sprite.Sprite): def __init__(self,x,y,width,height, typ): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("images/map/rock.png").convert() self.image.set_colorkey(white) self.rect = self.image.get_rect() self.rect.y = y self.rect.x = x class Creep(pygame.sprite.Sprite): """ A creep sprite that bounces off walls and changes its direction from time to time. """ change_x=0 change_y=0 def __init__( self, screen, creep_image, explosion_images, field, init_position, init_direction, speed): """ Create a new Creep. screen: The screen on which the creep lives (must be a pygame Surface object, such as pygame.display) creep_image: Image (surface) object for the creep explosion_images: A list of image objects for the explosion animation. field: A Rect specifying the 'playing field' boundaries. The Creep will bounce off the 'walls' of this field. init_position: A vec2d or a pair specifying the initial position of the creep on the screen. init_direction: A vec2d or a pair specifying the initial direction of the creep. Must have an angle that is a multiple of 45 degres. speed: Creep speed, in pixels/millisecond (px/ms) """ Sprite.__init__(self) self.screen = screen self.speed = speed self.field = field self.rect = creep_image.get_rect() # base_image holds the original image, positioned to # angle 0. # image will be rotated. # self.base_image = creep_image self.image = self.base_image self.explosion_images = explosion_images # A vector specifying the creep's position on the screen # self.pos = vec2d(init_position) # The direction is a normalized vector # self.direction = vec2d(init_direction).normalized() self.state = Creep.ALIVE self.health = 15 def is_alive(self): return self.state in (Creep.ALIVE, Creep.EXPLODING) def changespeed(self,x,y): self.change_x+=x self.change_y+=y def update(self, time_passed, walls): """ Update the creep. time_passed: The time passed (in ms) since the previous update. """ if self.state == Creep.ALIVE: # Maybe it's time to change the direction ? # self._change_direction(time_passed) # Make the creep point in the correct direction. # Since our direction vector is in screen coordinates # (i.e. right bottom is 1, 1), and rotate() rotates # counter-clockwise, the angle must be inverted to # work correctly. # self.image = pygame.transform.rotate( self.base_image, -self.direction.angle) # Compute and apply the displacement to the position # vector. The displacement is a vector, having the angle # of self.direction (which is normalized to not affect # the magnitude of the displacement) # displacement = vec2d( self.direction.x * self.speed * time_passed, self.direction.y * self.speed * time_passed) self.pos += displacement # When the image is rotated, its size is changed. # We must take the size into account for detecting # collisions with the walls. # self.image_w, self.image_h = self.image.get_size() bounds_rect = self.field.inflate( -self.image_w, -self.image_h) if self.pos.x < bounds_rect.left: self.pos.x = bounds_rect.left self.direction.x *= -1 elif self.pos.x > bounds_rect.right: self.pos.x = bounds_rect.right self.direction.x *= -1 elif self.pos.y < bounds_rect.top: self.pos.y = bounds_rect.top self.direction.y *= -1 elif self.pos.y > bounds_rect.bottom: self.pos.y = bounds_rect.bottom self.direction.y *= -1 # collision detection old_x=bounds_rect.left new_x=old_x+self.direction.x bounds_rect.left = new_x # hit a wall? collide = pygame.sprite.spritecollide(self, walls, False) if collide: # yes bounds_rect.left=old_x old_y=self.pos.y new_y=old_y+self.direction.y self.pos.y = new_y collide = pygame.sprite.spritecollide(self, walls, False) if collide: # yes self.pos.y=old_y elif self.state == Creep.EXPLODING: if self.explode_animation.active: self.explode_animation.update(time_passed) else: self.state = Creep.DEAD self.kill() elif self.state == Creep.DEAD: pass #------------------ PRIVATE PARTS ------------------# # States the creep can be in. # # ALIVE: The creep is roaming around the screen # EXPLODING: # The creep is now exploding, just a moment before dying. # DEAD: The creep is dead and inactive # (ALIVE, EXPLODING, DEAD) = range(3) _counter = 0 def _change_direction(self, time_passed): """ Turn by 45 degrees in a random direction once per 0.4 to 0.5 seconds. """ self._counter += time_passed if self._counter > randint(400, 500): self.direction.rotate(45 * randint(-1, 1)) self._counter = 0 def _point_is_inside(self, point): """ Is the point (given as a vec2d) inside our creep's body? """ img_point = point - vec2d( int(self.pos.x - self.image_w / 2), int(self.pos.y - self.image_h / 2)) try: pix = self.image.get_at(img_point) return pix[3] > 0 except IndexError: return False def _decrease_health(self, n): """ Decrease my health by n (or to 0, if it's currently less than n) """ self.health = max(0, self.health - n) if self.health == 0: self._explode() def _explode(self): """ Starts the explosion animation that ends the Creep's life. """ self.state = Creep.EXPLODING pos = ( self.pos.x - self.explosion_images[0].get_width() / 2, self.pos.y - self.explosion_images[0].get_height() / 2) self.explode_animation = SimpleAnimation( self.screen, pos, self.explosion_images, 100, 300) global remainingCreeps remainingCreeps-=1 if remainingCreeps == 0: print("all dead") def draw(self): """ Blit the creep onto the screen that was provided in the constructor. """ if self.state == Creep.ALIVE: # The creep image is placed at self.pos. To allow for # smooth movement even when the creep rotates and the # image size changes, its placement is always # centered. # self.draw_rect = self.image.get_rect().move( self.pos.x - self.image_w / 2, self.pos.y - self.image_h / 2) self.screen.blit(self.image, self.draw_rect) # The health bar is 15x4 px. # health_bar_x = self.pos.x - 7 health_bar_y = self.pos.y - self.image_h / 2 - 6 self.screen.fill( Color('red'), (health_bar_x, health_bar_y, 15, 4)) self.screen.fill( Color('green'), ( health_bar_x, health_bar_y, self.health, 4)) elif self.state == Creep.EXPLODING: self.explode_animation.draw() elif self.state == Creep.DEAD: pass def mouse_click_event(self, pos): """ The mouse was clicked in pos. """ if self._point_is_inside(vec2d(pos)): self._decrease_health(3) #begin new player class Player(pygame.sprite.Sprite): change_x=0 change_y=0 frame = 0 def __init__(self,x,y): pygame.sprite.Sprite.__init__(self) # LOAD PLATER IMAGES # Set height, width self.images = [] for i in range(1,17): img = pygame.image.load("images/player/" + str(i)+".png").convert() #player images img.set_colorkey(white) self.images.append(img) self.image = self.images[0] self.rect = self.image.get_rect() self.rect.y = y self.rect.x = x self.health = 15 self.image_w, self.image_h = self.image.get_size() health_bar_x = self.rect.x - 7 health_bar_y = self.rect.y - self.image_h / 2 - 6 screen.fill( Color('red'), (health_bar_x, health_bar_y, 15, 4)) screen.fill( Color('green'), ( health_bar_x, health_bar_y, self.health, 4)) def changespeed(self,x,y): self.change_x+=x self.change_y+=y def _decrease_health(self, n): """ Decrease my health by n (or to 0, if it's currently less than n) """ self.health = max(0, self.health - n) if self.health == 0: self._explode() def update(self,walls): # collision detection old_x=self.rect.x new_x=old_x+self.change_x self.rect.x = new_x # hit a wall? collide = pygame.sprite.spritecollide(self, walls, False) if collide: # yes self.rect.x=old_x old_y=self.rect.y new_y=old_y+self.change_y self.rect.y = new_y collide = pygame.sprite.spritecollide(self, walls, False) if collide: # yes self.rect.y=old_y # right to left if self.change_x < 0: self.frame += 1 if self.frame > 3*4: self.frame = 0 # Grab the image, divide by 4 # every 4 frames. self.image = self.images[self.frame//4] # Move left to right. # images 4...7 instead of 0...3. if self.change_x > 0: self.frame += 1 if self.frame > 3*4: self.frame = 0 self.image = self.images[self.frame//4+4] if self.change_y > 0: self.frame += 1 if self.frame > 3*4: self.frame = 0 self.image = self.images[self.frame//4+4+4] if self.change_y < 0: self.frame += 1 if self.frame > 3*4: self.frame = 0 self.image = self.images[self.frame//4+4+4+4] score = 0 # initialize pyGame pygame.init() # 800x600 sized screen global screen screen = pygame.display.set_mode([800, 600]) screen.fill(black) #bg_tile_img = pygame.image.load('images/map/grass.png').convert_alpha() #draw_background(screen, bg_tile_img) #pygame.display.flip() # Set title pygame.display.set_caption('Test') #background = pygame.Surface(screen.get_size()) #background = background.convert() #background.fill(black) # Create the player player = Player( 50,50 ) player.rect.x=50 player.rect.y=50 movingsprites = pygame.sprite.RenderPlain() movingsprites.add(player) # Make the walls. (x_pos, y_pos, width, height) global wall_list wall_list=pygame.sprite.RenderPlain() wall=Wall(0,0,10,600) # left wall wall_list.add(wall) wall=Wall(10,0,790,10) # top wall wall_list.add(wall) #wall=Wall(10,200,100,10) # poke wall wall_list.add(wall) wall=Wall(790,0,10,600) #(x,y,thickness, height) wall_list.add(wall) wall=Wall(10,590,790,10) #(x,y,thickness, height) wall_list.add(wall) f = open('MapMaker.txt') num_lines = sum(1 for line in f) print(num_lines) lineCount = 0 with open("MapMaker.txt") as infile: for line in infile: f = open('MapMaker.txt') print(line) coords = line.split(',') #print(coords[0]) #print(coords[1]) #print(coords[2]) #print(coords[3]) #print(coords[4]) if "tree" in line: print("tree in") wall=insertTree(int(coords[0]),int(coords[1]), int(coords[2]),int(coords[3]),coords[4]) wall_list.add(wall) elif "rock" in line: print("rock in") wall=insertRock(int(coords[0]),int(coords[1]), int(coords[2]),int(coords[3]),coords[4] ) wall_list.add(wall) width = 20 height = 540 height = height - 48 for i in range(0,23): width = width + 32 name = insertTree(width,540,790,10,"tree") #wall_list.add(name) name = insertTree(width,height,690,10,"tree") #wall_list.add(name) CREEP_SPAWN_TIME = 200 # frames creep_spawn = CREEP_SPAWN_TIME clock = pygame.time.Clock() bg_tile_img = pygame.image.load('images/map/grass.png').convert() img_rect = bg_tile_img FIELD_RECT = Rect(50, 50, 700, 500) CREEP_FILENAMES = [ 'images/player/1.png', 'images/player/1.png', 'images/player/1.png'] N_CREEPS = 3 creep_images = [ pygame.image.load(filename).convert_alpha() for filename in CREEP_FILENAMES] explosion_img = pygame.image.load('images/map/tree.png').convert_alpha() explosion_images = [ explosion_img, pygame.transform.rotate(explosion_img, 90)] creeps = pygame.sprite.RenderPlain() done = False #bg_tile_img = pygame.image.load('images/map/grass.png').convert() #draw_background(screen, bg_tile_img) totalCreeps = 0 remainingCreeps = 3 while done == False: creep_images = pygame.image.load("images/player/1.png").convert() creep_images.set_colorkey(white) draw_background(screen, bg_tile_img) if len(creeps) != N_CREEPS: if totalCreeps < N_CREEPS: totalCreeps = totalCreeps + 1 print(totalCreeps) creeps.add( Creep( screen=screen, creep_image=creep_images, explosion_images=explosion_images, field=FIELD_RECT, init_position=( randint(FIELD_RECT.left, FIELD_RECT.right), randint(FIELD_RECT.top, FIELD_RECT.bottom)), init_direction=(choice([-1, 1]), choice([-1, 1])), speed=0.01)) for creep in creeps: creep.update(60,wall_list) creep.draw() for event in pygame.event.get(): if event.type == pygame.QUIT: done=True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: player.changespeed(-2,0) creep.changespeed(-2,0) if event.key == pygame.K_RIGHT: player.changespeed(2,0) creep.changespeed(2,0) if event.key == pygame.K_UP: player.changespeed(0,-2) creep.changespeed(0,-2) if event.key == pygame.K_DOWN: player.changespeed(0,2) creep.changespeed(0,2) if event.key == pygame.K_ESCAPE: pauseGame() if event.key == pygame.K_1: global currentEditTool currentEditTool = "Tree" changeTool() if event.key == pygame.K_2: global currentEditTool currentEditTool = "Rock" changeTool() if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: player.changespeed(2,0) creep.changespeed(2,0) if event.key == pygame.K_RIGHT: player.changespeed(-2,0) creep.changespeed(-2,0) if event.key == pygame.K_UP: player.changespeed(0,2) creep.changespeed(0,2) if event.key == pygame.K_DOWN: player.changespeed(0,-2) creep.changespeed(0,-2) if event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed()[0]: for creep in creeps: creep.mouse_click_event(pygame.mouse.get_pos()) if editMap == True: x,y = pygame.mouse.get_pos() if currentEditTool == "Tree": name = insertTree(x-10,y-25, 10 , 10, "tree") wall_list.add(name) wall_list.draw(screen) f = open('MapMaker.txt', "a+") image = pygame.image.load("images/map/tree.png").convert() screen.blit(image, (30,10)) pygame.display.flip() f.write(str(x) + "," + str(y) + ",790,10, tree\n") #f.write("wall=insertTree(" + str(x) + "," + str(y) + ",790,10)\nwall_list.add(wall)\n") elif currentEditTool == "Rock": name = insertRock(x-10,y-25, 10 , 10,"rock") wall_list.add(name) wall_list.draw(screen) f = open('MapMaker.txt', "a+") f.write(str(x) + "," + str(y) + ",790,10,rock\n") #f.write("wall=insertRock(" + str(x) + "," + str(y) + ",790,10)\nwall_list.add(wall)\n") else: None #pygame.display.flip() player.update(wall_list) movingsprites.draw(screen) wall_list.draw(screen) pygame.display.flip() clock.tick(60) pygame.quit()

    Read the article

  • jqGrid multiplesearch - How do I add and/or column for each row?

    - by jimasp
    I have a jqGrid multiple search dialog as below: (Note the first empty td in each row). What I want is a search grid like this (below), where: The first td is filled in with "and/or" accordingly. The corresponding search filters are also built that way. The empty td is there by default, so I assume that this is a standard jqGrid feature that I can turn on, but I can't seem to find it in the docs. My code looks like this: <script type="text/javascript"> $(document).ready(function () { var lastSel; var pageSize = 10; // the initial pageSize $("#grid").jqGrid({ url: '/Ajax/GetJqGridActivities', editurl: '/Ajax/UpdateJqGridActivities', datatype: "json", colNames: [ 'Id', 'Description', 'Progress', 'Actual Start', 'Actual End', 'Status', 'Scheduled Start', 'Scheduled End' ], colModel: [ { name: 'Id', index: 'Id', searchoptions: { sopt: ['eq', 'ne']} }, { name: 'Description', index: 'Description', searchoptions: { sopt: ['eq', 'ne']} }, { name: 'Progress', index: 'Progress', editable: true, searchoptions: { sopt: ['eq', 'ne', "gt", "ge", "lt", "le"]} }, { name: 'ActualStart', index: 'ActualStart', editable: true, searchoptions: { sopt: ['eq', 'ne', "gt", "ge", "lt", "le"]} }, { name: 'ActualEnd', index: 'ActualEnd', editable: true, searchoptions: { sopt: ['eq', 'ne', "gt", "ge", "lt", "le"]} }, { name: 'Status', index: 'Status.Name', editable: true, searchoptions: { sopt: ['eq', 'ne']} }, { name: 'ScheduledStart', index: 'ScheduledStart', searchoptions: { sopt: ['eq', 'ne', "gt", "ge", "lt", "le"]} }, { name: 'ScheduledEnd', index: 'ScheduledEnd', searchoptions: { sopt: ['eq', 'ne', "gt", "ge", "lt", "le"]} } ], jsonReader: { root: 'rows', id: 'Id', repeatitems: false }, rowNum: pageSize, // this is the pageSize rowList: [pageSize, 50, 100], pager: '#pager', sortname: 'Id', autowidth: true, shrinkToFit: false, viewrecords: true, sortorder: "desc", caption: "JSON Example", onSelectRow: function (id) { if (id && id !== lastSel) { $('#grid').jqGrid('restoreRow', lastSel); $('#grid').jqGrid('editRow', id, true); lastSel = id; } } }); // change the options (called via searchoptions) var updateGroupOpText = function ($form) { $('select.opsel option[value="AND"]', $form[0]).text('and'); $('select.opsel option[value="OR"]', $form[0]).text('or'); $('select.opsel', $form[0]).trigger('change'); }; // $(window).bind('resize', function() { // ("#grid").setGridWidth($(window).width()); //}).trigger('resize'); // paging bar settings (inc. buttons) // and advanced search $("#grid").jqGrid('navGrid', '#pager', { edit: true, add: false, del: false }, // buttons {}, // edit option - these are ordered params! {}, // add options {}, // del options {closeOnEscape: true, multipleSearch: true, closeAfterSearch: true, onInitializeSearch: updateGroupOpText, afterRedraw: updateGroupOpText}, // search options {} ); // TODO: work out how to use global $.ajaxSetup instead $('#grid').ajaxError(function (e, jqxhr, settings, exception) { var str = "Ajax Error!\n\n"; if (jqxhr.status === 0) { str += 'Not connect.\n Verify Network.'; } else if (jqxhr.status == 404) { str += 'Requested page not found. [404]'; } else if (jqxhr.status == 500) { str += 'Internal Server Error [500].'; } else if (exception === 'parsererror') { str += 'Requested JSON parse failed.'; } else if (exception === 'timeout') { str += 'Time out error.'; } else if (exception === 'abort') { str += 'Ajax request aborted.'; } else { str += 'Uncaught Error.\n' + jqxhr.responseText; } alert(str); }); $("#grid").jqGrid('bindKeys'); $("#grid").jqGrid('inlineNav', "#grid"); }); </script> <table id="grid"/> <div id="pager"/>

    Read the article

  • How to map code points to unicode characters depending on the font used?

    - by Alex Schröder
    The client prints labels and has been using a set of symbolic (?) fonts to do this. The application uses a single byte database (Oracle with Latin-1). The old application I am replacing was not Unicode aware. It somehow did OK. The replacement application I am writing is supposed to handle the old data. The symbols picked from the charmap application often map to particular Unicode characters, but sometimes they don't. What looks like the Moon using the LAB3 font, for example, is in fact U+2014 (EM DASH). When users paste this character into a Swing text field, the character has the code point 8212. It was "moved" into the Private Use Area (by Windows? Java?). When saving this character to the database, Oracle decides that it cannot be safely encoded and replaces it with the dreaded ¿. Thus, I started shifting the characters by 8000: -= 8000 when saving, += 8000 when displaying the field. Unfortunately I discovered that other characters were not shifted by the same amount. In one particular font, for example, ž has the code point 382, so I shifted it by +/-256 to "fix" it. By now I'm dreading the discovery of more strange offsets and I wonder: Can I get at this mapping using Java? Perhaps the TTF font has a list of the 255 glyphs it encodes and what Unicode characters those correspond to and I can do it "right"? Right now I'm using the following kludge: static String fromDatabase(String str, String fontFamily) { if (str != null && fontFamily != null) { Font font = new Font(fontFamily, Font.PLAIN, 1); boolean changed = false; char[] chars = str.toCharArray(); for (int i = 0; i < chars.length; i++) { if (font.canDisplay(chars[i] + 0xF000)) { // WE8MSWIN1252 + WinXP chars[i] += 0xF000; changed = true; } else if (chars[i] >= 128 && font.canDisplay(chars[i] + 8000)) { // WE8ISO8859P1 + WinXP chars[i] += 8000; changed = true; } else if (font.canDisplay(chars[i] + 256)) { // ž in LAB1 Eastern = 382 chars[i] += 256; changed = true; } } if (changed) str = new String(chars); } return str; } static String toDatabase(String str, String fontFamily) { if (str != null && fontFamily != null) { boolean changed = false; char[] chars = str.toCharArray(); for (int i = 0; i < chars.length; i++) { int chr = chars[i]; if (chars[i] > 0xF000) { // WE8MSWIN1252 + WinXP chars[i] -= 0xF000; changed = true; } else if (chars[i] > 8000) { // WE8ISO8859P1 + WinXP chars[i] = (char) (chars[i] - 8000); changed = true; } else if (chars[i] > 256) { // ž in LAB1 Eastern = 382 chars[i] = (char) (chars[i] - 256); changed = true; } } if (changed) return new String(chars); } return str; }

    Read the article

  • a php script to get lat/long from google maps using CellID

    - by user296516
    Hi guys, I have found this script that supposedly connects to google maps and gets lat/long coordinates, based on CID/LAC/MNC/MCC info. But I can't really make it work... where do I input CID/LAC/MNC/MCC ? <?php $data = "\x00\x0e". // Function Code? "\x00\x00\x00\x00\x00\x00\x00\x00". //Session ID? "\x00\x00". // Contry Code "\x00\x00". // Client descriptor "\x00\x00". // Version "\x1b". // Op Code? "\x00\x00\x00\x00". // MNC "\x00\x00\x00\x00". // MCC "\x00\x00\x00\x03". "\x00\x00". "\x00\x00\x00\x00". //CID "\x00\x00\x00\x00". //LAC "\x00\x00\x00\x00". //MNC "\x00\x00\x00\x00". //MCC "\xff\xff\xff\xff". // ?? "\x00\x00\x00\x00" // Rx Level? ; if ($_REQUEST["myl"] != "") { $temp = split(":", $_REQUEST["myl"]); $mcc = substr("00000000".dechex($temp[0]),-8); $mnc = substr("00000000".dechex($temp[1]),-8); $lac = substr("00000000".dechex($temp[2]),-8); $cid = substr("00000000".dechex($temp[3]),-8); } else { $mcc = substr("00000000".$_REQUEST["mcc"],-8); $mnc = substr("00000000".$_REQUEST["mnc"],-8); $lac = substr("00000000".$_REQUEST["lac"],-8); $cid = substr("00000000".$_REQUEST["cid"],-8); } $init_pos = strlen($data); $data[$init_pos - 38]= pack("H*",substr($mnc,0,2)); $data[$init_pos - 37]= pack("H*",substr($mnc,2,2)); $data[$init_pos - 36]= pack("H*",substr($mnc,4,2)); $data[$init_pos - 35]= pack("H*",substr($mnc,6,2)); $data[$init_pos - 34]= pack("H*",substr($mcc,0,2)); $data[$init_pos - 33]= pack("H*",substr($mcc,2,2)); $data[$init_pos - 32]= pack("H*",substr($mcc,4,2)); $data[$init_pos - 31]= pack("H*",substr($mcc,6,2)); $data[$init_pos - 24]= pack("H*",substr($cid,0,2)); $data[$init_pos - 23]= pack("H*",substr($cid,2,2)); $data[$init_pos - 22]= pack("H*",substr($cid,4,2)); $data[$init_pos - 21]= pack("H*",substr($cid,6,2)); $data[$init_pos - 20]= pack("H*",substr($lac,0,2)); $data[$init_pos - 19]= pack("H*",substr($lac,2,2)); $data[$init_pos - 18]= pack("H*",substr($lac,4,2)); $data[$init_pos - 17]= pack("H*",substr($lac,6,2)); $data[$init_pos - 16]= pack("H*",substr($mnc,0,2)); $data[$init_pos - 15]= pack("H*",substr($mnc,2,2)); $data[$init_pos - 14]= pack("H*",substr($mnc,4,2)); $data[$init_pos - 13]= pack("H*",substr($mnc,6,2)); $data[$init_pos - 12]= pack("H*",substr($mcc,0,2)); $data[$init_pos - 11]= pack("H*",substr($mcc,2,2)); $data[$init_pos - 10]= pack("H*",substr($mcc,4,2)); $data[$init_pos - 9]= pack("H*",substr($mcc,6,2)); if ((hexdec($cid) > 0xffff) && ($mcc != "00000000") && ($mnc != "00000000")) { $data[$init_pos - 27] = chr(5); } else { $data[$init_pos - 24]= chr(0); $data[$init_pos - 23]= chr(0); } $context = array ( 'http' => array ( 'method' => 'POST', 'header'=> "Content-type: application/binary\r\n" . "Content-Length: " . strlen($data) . "\r\n", 'content' => $data ) ); $xcontext = stream_context_create($context); $str=file_get_contents("http://www.google.com/glm/mmap",FALSE,$xcontext); if (strlen($str) > 10) { $lat_tmp = unpack("l",$str[10].$str[9].$str[8].$str[7]); $lat = $lat_tmp[1]/1000000; $lon_tmp = unpack("l",$str[14].$str[13].$str[12].$str[11]); $lon = $lon_tmp[1]/1000000; echo "Lat=$lat <br> Lon=$lon"; } else { echo "Not found!"; } ?> also I found this one http://code.google.com/intl/ru/apis/gears/geolocation_network_protocol.html , but it isn't php.

    Read the article

  • Numerology with Python And Django

    - by Asinox
    Hi guys, i have a function that give me the result that im expecting in console mode, but if i try to use the function with Django, the page never load and just have a loop calculating and never end. Any idea ? *sorry with my english Console function (WORK GREAT): def sum_digitos(n): sum = 0; while n != 0: sum += n % 10 n /= 10 if sum > 9: x = str(sum) y =list(x) sum = int(y[0]) + int(y[1]) return sum print sum_digitos(2461978) Django views: def Calcular(request): if request.method == 'POST': form = NumerologiaForm(request.POST) if form.is_valid(): sum = 0; ano = str(request.POST['fecha_year']) mes = str(request.POST['fecha_month']) dia = str(request.POST['fecha_day']) data = dia + mes + ano fecha = int(data) while fecha != 0: f = fecha sum += f % 10 f /= 10 if sum > 9: x = str(sum) y =list(x) sum = int(y[0]) + int(y[1]) resultado = get_object_or_404(Numero,numero = sum) return HttpResponseRedirect(resultado.get_absolute_url()) else: form = NumerologiaForm() return render_to_response('numerologiaForm.html',{'form':form})

    Read the article

  • JavaScript - string regex backreferences

    - by quano
    You can backreference like this in JavaScript: var str = "123 $test 123"; str = str.replace(/(\$)([a-z]+)/gi, "$2"); This would (quite silly) replace "$test" with "test". But imagine I'd like to pass the resulting string of $2 into a function, which returns another value. I tried doing this, but instead of getting the string "test", I get "$2". Is there a way to achieve this? // Instead of getting "$2" passed into somefunc, I want "test" // (i.e. the result of the regex) str = str.replace(/(\$)([a-z]+)/gi, somefunc("$2"));

    Read the article

  • Segmentation fault in strcpy

    - by Alien01
    consider the program below char str[5]; strcpy(str,"Hello12345678"); printf("%s",str); When run this program gives segmentation fault. But when strcpy is replaced with following, program runs fine. strcpy(str,"Hello1234567"); So question is it should crash when trying to copy to str any other string of more than 5 chars length. So why it is not crashing for "Hello1234567" and only crashing for "Hello12345678" ie of string with length 13 or more than 13. This program was run on 32 bit machine .

    Read the article

  • Complexity of a web application

    - by Dominik G
    I am currently writing my Master's Thesis on maintainability of a web application. I found some methods like the "Maintainability Index" by Coleman et.al. or the "Software Maintainability Index" by Muthanna et.al. For both of them one needs to calculate the cyclomatic complexity. So my question is: Is it possible to measure the cyclomatic complexity of a web application? In my opinion there are three parts to a web application: Server code (PHP, C#, Python, Perl, etc.) Client code (JavaScript) HTML (links and forms as operators, GET-parameters and form fields as operands!?) What do you think? Is there another point of view on the complexity of web application? Did I miss something?

    Read the article

  • array iteration strstr in c

    - by lex0273
    I was wondering if it's safe to do the following iteration to find the first occurrence of str within the array or if there is a better way. Thanks #include <stdio.h> #include <string.h> const char * list[] = {"One","Two","Three","Four","Five"}; char *c(char * str) { int i; for (i = 0; i < 5; i++) { if (strstr(str, list[i]) != NULL) return list[i]; } return "Not Found"; } int main() { char str[] = "This is a simple string of hshhs wo a char"; printf("%s", c(str)); return 0; }

    Read the article

  • how to upload the fie from user to server in asp.net mvc2

    - by Richa Media and services
    in my apps (dev in MVC2) user can upload his images to server. how i can set url routing who handle the image and upload it to a specific location currently i used it like a parameter ex;- routes.MapRoute("abcd2", "abcd/{id}/{param1}/{param2}/", new { controller = "abcd", action = "Index", id = 0, qxt = "" }, new { action = new IsIndexConstraint() }, new string[] { "myapps.Controllers" }); by this code param2 is work i used param1 for sending file to server but he not worked public ActionResult Index(HttpPostedFileBase param1 , string param2) { string str = "null"; if (param1 != null) { param1.SaveAs(@"C:\img\" + param1.FileName); str = "func is work"; //picture.SaveAs("C:\wherever\" + picture.FileName); return Content(str); } else { str = "func is not worked"; } return Content(str); } are anyone really want to help me. param2 is work but param1 is not handle by web apps. are you suggest me how to do it.

    Read the article

  • Too many values problem

    - by DraskyVanderhoff
    Hi , i was trying to make a full lot of ips for testing using this code : ip_is = [i for i in range(256)] ports = [i for i in range(1024,49152)] return [str(i1)+"."+str(i2)+"."+str(i3)+"."+str(i4)+":"+str(p) for i1,i2,i3,i4,port in ip_is,ip_is,ip_is,ip_is,ports] The problem is the 3rd line in which is made the ip list. If there is a way to make it all at once or how can make one at time in a lazy way ? I'm pretty noob at python :P. Thanks for the Help :)

    Read the article

  • Address component type in google maps geocoding

    - by user552828
    this is a part of my geocoding code. I want it to show only country of the selected place, but it shows all address components, My problem is I cant specify the address components object. There is a way of doing it that is written on documentation but I didnt understand, can you do it for me. if (geocoder) { geocoder.geocode({'latLng': latlng}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { var str = ""; $.each(results, function(){ str += "address components: <ul>" $.each(this.address_components, function(){ str +="<li>"+this.types.join(", ")+": "+this.long_name+"</li>"; }); str +="</ul>"; }); $("#geocode_info").html(str);

    Read the article

  • How to Inspect Javascript Object

    - by Madhan ayyasamy
    You can inspect any JavaScript objects and list them as indented, ordered by levels.It shows you type and property name. If an object property can't be accessed, an error message will be shown.Here the snippets for inspect javascript object.function inspect(obj, maxLevels, level){  var str = '', type, msg;    // Start Input Validations    // Don't touch, we start iterating at level zero    if(level == null)  level = 0;    // At least you want to show the first level    if(maxLevels == null) maxLevels = 1;    if(maxLevels < 1)             return '<font color="red">Error: Levels number must be > 0</font>';    // We start with a non null object    if(obj == null)    return '<font color="red">Error: Object <b>NULL</b></font>';    // End Input Validations    // Each Iteration must be indented    str += '<ul>';    // Start iterations for all objects in obj    for(property in obj)    {      try      {          // Show "property" and "type property"          type =  typeof(obj[property]);          str += '<li>(' + type + ') ' + property +                  ( (obj[property]==null)?(': <b>null</b>'):('')) + '</li>';          // We keep iterating if this property is an Object, non null          // and we are inside the required number of levels          if((type == 'object') && (obj[property] != null) && (level+1 < maxLevels))          str += inspect(obj[property], maxLevels, level+1);      }      catch(err)      {        // Is there some properties in obj we can't access? Print it red.        if(typeof(err) == 'string') msg = err;        else if(err.message)        msg = err.message;        else if(err.description)    msg = err.description;        else                        msg = 'Unknown';        str += '<li><font color="red">(Error) ' + property + ': ' + msg +'</font></li>';      }    }      // Close indent      str += '</ul>';    return str;}Method Call:function inspect(obj [, maxLevels [, level]]) Input Vars * obj: Object to inspect * maxLevels: Optional. Number of levels you will inspect inside the object. Default MaxLevels=1 * level: RESERVED for internal use of the functionReturn ValueHTML formatted string containing all values of inspected object obj.

    Read the article

  • how to show all method and data when the object not has "__iter__" function in python..

    - by zjm1126
    i find a way : (1):the dir(object) is : a="['__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__iter__', '__metaclass__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', '__weakref__', '_errors', '_fields', '_prefix', '_unbound_fields', 'confirm', 'data', 'email', 'errors', 'password', 'populate_obj', 'process', 'username', 'validate']" (2): b=eval(a) (3)and it became a list of all method : ['__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__iter__', '__metaclass__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', '__weakref__', '_errors', '_fields', '_prefix', '_unbound_fields', 'confirm', 'data', 'email', 'errors', 'password', 'populate_obj', 'process', 'username', 'validate'] (3)then show the object's method,and all code is : s='' a=eval(str(dir(object))) for i in a: s+=str(i)+':'+str(object[i]) print s but it show error : KeyError: '__class__' so how to make my code running . thanks

    Read the article

  • how to format date when i load data from google-app-engine..

    - by zjm1126
    i use remote_api to load data from google-app-engine. appcfg.py download_data --config_file=helloworld/GreetingLoad.py --filename=a.csv --kind=Greeting helloworld the setting is: class AlbumExporter(bulkloader.Exporter): def __init__(self): bulkloader.Exporter.__init__(self, 'Greeting', [('author', str, None), ('content', str, None), ('date', str, None), ]) exporters = [AlbumExporter] and i download a.csv is : the date is not readable , and the date in appspot.com admin is : so how to get the full date ?? thanks i change this : class AlbumExporter(bulkloader.Exporter): def __init__(self): bulkloader.Exporter.__init__(self, 'Greeting', [('author', str, None), ('content', str, None), ('date', lambda x: datetime.datetime.strptime(x, '%m/%d/%Y').date(), None), ]) exporters = [AlbumExporter] but the error is :

    Read the article

  • Java regex basic usage problem

    - by Ernelli
    The following code works: String str= "test with foo hoo"; Pattern pattern = Pattern.compile("foo"); Matcher matcher = pattern.matcher(str); if(matcher.find()) { ... } But this example does not: if(Pattern.matches("foo", str)) { ... } And neither this version: if(str.matches("foo")) { ... } In the real code, str is a chunk of text with multiple lines if that is treated differently by the matcher, also in the real code, replace will be used to replace a string of text. Anyway, it is strange that it works in the first version but not the other two versions.

    Read the article

  • Does the google crawler really guess URL patterns and index pages that were never linked against?

    - by Dominik
    I'm experiencing problems with indexed pages which were (probably) never linked to. Here's the setup: Data-Server: Application with RESTful interface which provides the data Website A: Provides the data of (1) at http://website-a.example.com/?id=RESOURCE_ID Website B: Provides the data of (1) at http://website-b.example.com/?id=OTHER_RESOURCE_ID So the whole, non-private data is stored on (1) and the websites (2) and (3) can fetch and display this data, which is a representation of the data with additional cross-linking between those. In fact, the URL /?id=1 of website-a points to the same resource as /?id=1 of website-b. However, the resource id:1 is useless at website-b. Unfortunately, the google index for website-b now contains several links of resources belonging to website-a and vice versa. I "heard" that the google crawler tries to determine the URL-pattern (which makes sense for deciding which page should go into the index and which not) and furthermore guesses other URLs by trying different values (like "I know that id 1 exists, let's try 2, 3, 4, ..."). Is there any evidence that the google crawler really behaves that way (which I doubt). My guess is that the google crawler submitted a HTML-Form and somehow got links to those unwanted resources. I found some similar posted questions about that, including "Google webmaster central: indexing and posting false pages" [link removed] however, none of those pages give an evidence.

    Read the article

  • Parser line break if string contains &#8211;

    - by pask
    Hi all, My NSXMLParser breaks on this string: <title>AAA &#8211; BCDEFGQWERTYUIO</title> I parsed it in this way, hope is the right way: - (void) parser: (NSXMLParser *) parser foundCharacters: (NSString *) string{ [...] if ([currentElement isEqualToString:@"title"]) { if (![string isEqualToString:@""]) { [title addObject:string]; NSLog(@"str: %@", string); } } it returns me: str: AAA str: - str: BCDEFGQWERTYUIO But i want to return a single string: str: AAA - BCDEFGQWERTYUIO because it's the correct title. Any idea? Thanks.

    Read the article

  • Add links to specific words within span tag in PHP

    - by dazhall
    I have a list of words that I'd like to add a link to, I can do this fairly easily using preg_match_all and preg_replace: $str = "<span class=\"cz\">Dám si jedno pivo prosím.</span> = I'll have a beer please."; preg_match_all('/[a-ztúuýžácdéeínórš]+/i',$str,$matches); $matches = array_unique($matches[0]); foreach ($matches as $match) { if(!empty($words[$match])) { $str = preg_replace("/(^|[^\w]){1}(".preg_quote($match,"/").")($|[^\w]){1}/i", '\\1<a href="#">\\2</a>\\3', $str); } } echo $str; What I'd like to do is restrict the linking to only within the span tag. My brain is all regex-ed out, so any help would be appreciated! Thanks! Darren.

    Read the article

  • is this a simple monad example?

    - by zcaudate
    This is my attempt to grok monadic functions after watching http://channel9.msdn.com/Shows/Going+Deep/Brian-Beckman-Dont-fear-the-Monads. h uses bind to compose together two arbitrary functions f and g. What is the unit operator in this case? ;; f :: int - [str] ;; g :: str = [keyword] ;; bind :: [str] - (str - [keyword]) - [keyword] ;; h :: int - [keyword] (defn f [v] (map str (range v))) (defn g [s] (map keyword (repeat 4 s))) (defn bind [l f] (flatten (map f l))) (f 8) ;; = (0 1 2 3 4 5 6 7) (g "s") ;; = (:s :s :s :s) (defn h [v] (bind (f v) g)) (h 9) ;; = (:0 :0 :0 :0 :1 :1 :1 :1 :2 :2 :2 :2 :3 :3 :3 :3 :4 :4 :4 :4 :5 :5 :5 :5)

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >