Search Results

Search found 509 results on 21 pages for 'ret'.

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

  • Clusterware 11gR2 &ndash; Setting up an Active/Passive failover configuration

    - by Gilles Haro
    Oracle is providing a large range of interesting solutions to ensure High Availability of the database. Dataguard, RAC or even both configurations (as recommended by Oracle for a Maximum Available Architecture - MAA) are the most frequently found and used solutions. But, when it comes to protecting a system with an Active/Passive architecture with failover capabilities, people often thinks to other expensive third party cluster systems. Oracle Clusterware technology, which comes along at no extra-cost with Oracle Database or Oracle Unbreakable Linux, is - in the knowing of most people - often linked to Oracle RAC and therefore, is seldom used to implement failover solutions. Oracle Clusterware 11gR2  (a part of Oracle 11gR2 Grid Infrastructure)  provides a comprehensive framework to setup automatic failover configurations. It is actually possible to make "failover-able'", and then to protect, almost any kind of application (from the simple xclock to the most complex Application Server). Quoting Oracle: “Oracle Clusterware is a portable cluster software that allows clustering of single servers so that they cooperate as a single system. Oracle Clusterware also provides the required infrastructure for Oracle Real Application Clusters (RAC). In addition Oracle Clusterware enables the protection of any Oracle application or any other kind of application within a cluster.” In the next couple of lines, I will try to present the different steps to achieve this goal : Have a fully operational 11gR2 database protected by automatic failover capabilities. I assume you are fluent in installing Oracle Database 11gR2, Oracle Grid Infrastructure 11gR2 on a Linux system and that ASM is not a problem for you (as I am using it as a shared storage). If not, please have a look at Oracle Documentation. As often, I made my tests using an Oracle VirtualBox environment. The scripts are tested and functional on my system. Unfortunately, there can always be a typo or a mistake. This blog entry does not replace a course around the Clusterware Framework. I just hope it will let you see how powerful it is and that it will give you the whilst to go further with it...  Note : This entry has been revised (rev.2) following comments from Philip Newlan. Prerequisite 2 Linux boxes (OELCluster01 and OELCluster02) at the same OS level. I used OEL 5 Update 5 with an Enterprise Kernel. Shared Storage (SAN). On my VirtualBox system, I used Openfiler to simulate the SAN Oracle 11gR2 Database (11.2.0.1) Oracle 11gR2 Grid Infrastructure (11.2.0.1)   Step 1 - Install the software Using asmlib, create 3 ASM disks (ASM_CRS, ASM_DTA and ASM_FRA) Install Grid Infrastructure for a cluster (OELCluster01 and OELCluster02 are the 2 nodes of the cluster) Use ASM_CRS to store Voting Disk and OCR. Use SCAN. Install Oracle Database Standalone binaries on both nodes. Use asmca to check/mount the disk groups on 2 nodes Use dbca to create and configure a database on the primary node Let's name it DB11G. Copy the pfile, password file to the second node. Create adump directoty on the second node.   Step 2 - Setup the resource to be protected After its creation with dbca, the database is automatically protected by the Oracle Restart technology available with Grid Infrastructure. Consequently, it restarts automatically (if possible) after a crash (ex: kill -9 smon). A database resource has been created for that in the Cluster Registry. We can observe this with the command : crsctl status resource that shows and ora.dba11g.db entry. Let's save the definition of this resource, for future use : mkdir -p /crs/11.2.0/HA_scripts chown oracle:oinstall /crs/11.2.0/HA_scripts crsctl status resource ora.db11g.db -p > /crs/11.2.0/HA_scripts/myResource.txt Although very interesting, Oracle Restart is not cluster aware and cannot restart the database on any other node of the cluster. So, let's remove it from the OCR definitions, we don't need it ! srvctl stop database -d DB11G srvctl remove database -d DB11G Instead of it, we need to create a new resource of a more general type : cluster_resource. Here are the steps to achieve this : Create an action script :  /crs/11.2.0/HA_scripts/my_ActivePassive_Cluster.sh #!/bin/bash export ORACLE_HOME=/oracle/product/11.2.0/dbhome_1 export ORACLE_SID=DB11G case $1 in 'start')   $ORACLE_HOME/bin/sqlplus /nolog <<EOF   connect / as sysdba   startup EOF   RET=0   ;; 'stop')   $ORACLE_HOME/bin/sqlplus /nolog <<EOF   connect / as sysdba   shutdown immediate EOF   RET=0   ;; 'clean')   $ORACLE_HOME/bin/sqlplus /nolog <<EOF   connect / as sysdba   shutdown abort    ##for i in `ps -ef | grep -i $ORACLE_SID | awk '{print $2}' ` ;do kill -9 $i; done EOF   RET=0   ;; 'check')    ok=`ps -ef | grep smon | grep $ORACLE_SID | wc -l`    if [ $ok = 0 ]; then      RET=1    else      RET=0    fi    ;; '*')      RET=0   ;; esac if [ $RET -eq 0 ]; then    exit 0 else    exit 1 fi   This script must provide, at least, methods to start, stop, clean and check the database. It is self-explaining and contains nothing special. Just be aware that it must be runnable (+x), it runs as Oracle user (because of the ACL property - see later) and needs to know about the environment. Also make sure it exists on every node of the cluster. Moreover, as of 11.2, the clean method is mandatory. It must provide the “last gasp clean up”, for example, a shutdown abort or a kill –9 of all the remaining processes. chmod +x /crs/11.2.0/HA_scripts/my_ActivePassive_Cluster.sh scp  /crs/11.2.0/HA_scripts/my_ActivePassive_Cluster.sh   oracle@OELCluster02:/crs/11.2.0/HA_scripts Create a new resource file, based on the information we got from previous  myResource.txt . Name it myNewResource.txt. myResource.txt  is shown below. As we can see, it defines an ora.database.type resource, named ora.db11g.db. A lot of properties are related to this type of resource and do not need to be used for a cluster_resource. NAME=ora.db11g.db TYPE=ora.database.type ACL=owner:oracle:rwx,pgrp:oinstall:rwx,other::r-- ACTION_FAILURE_TEMPLATE= ACTION_SCRIPT= ACTIVE_PLACEMENT=1 AGENT_FILENAME=%CRS_HOME%/bin/oraagent%CRS_EXE_SUFFIX% AUTO_START=restore CARDINALITY=1 CHECK_INTERVAL=1 CHECK_TIMEOUT=600 CLUSTER_DATABASE=false DB_UNIQUE_NAME=DB11G DEFAULT_TEMPLATE=PROPERTY(RESOURCE_CLASS=database) PROPERTY(DB_UNIQUE_NAME= CONCAT(PARSE(%NAME%, ., 2), %USR_ORA_DOMAIN%, .)) ELEMENT(INSTANCE_NAME= %GEN_USR_ORA_INST_NAME%) DEGREE=1 DESCRIPTION=Oracle Database resource ENABLED=1 FAILOVER_DELAY=0 FAILURE_INTERVAL=60 FAILURE_THRESHOLD=1 GEN_AUDIT_FILE_DEST=/oracle/admin/DB11G/adump GEN_USR_ORA_INST_NAME= GEN_USR_ORA_INST_NAME@SERVERNAME(oelcluster01)=DB11G HOSTING_MEMBERS= INSTANCE_FAILOVER=0 LOAD=1 LOGGING_LEVEL=1 MANAGEMENT_POLICY=AUTOMATIC NLS_LANG= NOT_RESTARTING_TEMPLATE= OFFLINE_CHECK_INTERVAL=0 ORACLE_HOME=/oracle/product/11.2.0/dbhome_1 PLACEMENT=restricted PROFILE_CHANGE_TEMPLATE= RESTART_ATTEMPTS=2 ROLE=PRIMARY SCRIPT_TIMEOUT=60 SERVER_POOLS=ora.DB11G SPFILE=+DTA/DB11G/spfileDB11G.ora START_DEPENDENCIES=hard(ora.DTA.dg,ora.FRA.dg) weak(type:ora.listener.type,uniform:ora.ons,uniform:ora.eons) pullup(ora.DTA.dg,ora.FRA.dg) START_TIMEOUT=600 STATE_CHANGE_TEMPLATE= STOP_DEPENDENCIES=hard(intermediate:ora.asm,shutdown:ora.DTA.dg,shutdown:ora.FRA.dg) STOP_TIMEOUT=600 UPTIME_THRESHOLD=1h USR_ORA_DB_NAME=DB11G USR_ORA_DOMAIN=haroland USR_ORA_ENV= USR_ORA_FLAGS= USR_ORA_INST_NAME=DB11G USR_ORA_OPEN_MODE=open USR_ORA_OPI=false USR_ORA_STOP_MODE=immediate VERSION=11.2.0.1.0 I removed database type related entries from myResource.txt and modified some other to produce the following myNewResource.txt. Notice the NAME property that should not have the ora. prefix Notice the TYPE property that is not ora.database.type but cluster_resource. Notice the definition of ACTION_SCRIPT. Notice the HOSTING_MEMBERS that enumerates the members of the cluster (as returned by the olsnodes command). NAME=DB11G.db TYPE=cluster_resource DESCRIPTION=Oracle Database resource ACL=owner:oracle:rwx,pgrp:oinstall:rwx,other::r-- ACTION_SCRIPT=/crs/11.2.0/HA_scripts/my_ActivePassive_Cluster.sh PLACEMENT=restricted ACTIVE_PLACEMENT=0 AUTO_START=restore CARDINALITY=1 CHECK_INTERVAL=10 DEGREE=1 ENABLED=1 HOSTING_MEMBERS=oelcluster01 oelcluster02 LOGGING_LEVEL=1 RESTART_ATTEMPTS=1 START_DEPENDENCIES=hard(ora.DTA.dg,ora.FRA.dg) weak(type:ora.listener.type,uniform:ora.ons,uniform:ora.eons) pullup(ora.DTA.dg,ora.FRA.dg) START_TIMEOUT=600 STOP_DEPENDENCIES=hard(intermediate:ora.asm,shutdown:ora.DTA.dg,shutdown:ora.FRA.dg) STOP_TIMEOUT=600 UPTIME_THRESHOLD=1h Register the resource. Take care of the resource type. It needs to be a cluster_resource and not a ora.database.type resource (Oracle recommendation) .   crsctl add resource DB11G.db  -type cluster_resource -file /crs/11.2.0/HA_scripts/myNewResource.txt Step 3 - Start the resource crsctl start resource DB11G.db This command launches the ACTION_SCRIPT with a start and a check parameter on the primary node of the cluster. Step 4 - Test this We will test the setup using 2 methods. crsctl relocate resource DB11G.db This command calls the ACTION_SCRIPT  (on the two nodes)  to stop the database on the active node and start it on the other node. Once done, we can revert back to the original node, but, this time we can use a more "MS$ like" method :Turn off the server on which the database is running. After short delay, you should observe that the database is relocated on node 1. Conclusion Once the software installed and the standalone database created (which is a rather common and usual task), the steps to reach the objective are quite easy : Create an executable action script on every node of the cluster. Create a resource file. Create/Register the resource with OCR using the resource file. Start the resource. This solution is a very interesting alternative to licensable third party solutions. References Clusterware 11gR2 documentation Oracle Clusterware Resource Reference Clusterware for Unbreakable Linux Using Oracle Clusterware to Protect A Single Instance Oracle Database 11gR1 (to have an idea of complexity) Oracle Clusterware on OTN   Gilles Haro Technical Expert - Core Technology, Oracle Consulting   

    Read the article

  • Code coverage (c++ code execution path)

    - by Poni
    Let's say I have this code: int function(bool b) { // execution path 1 int ret = 0; if(b) { // execution path 2 ret = 55; } else { // execution path 3 ret = 120; } return ret; } I need some sort of a mechanism to make sure that the code has gone in any possible path, i.e execution paths 1, 2 & 3 in the code above. I thought about having a global function, vector and a macro. This macro would simply call that function, passing as parameters the source file name and the line of code, and that function would mark that as "checked", by inserting to the vector the info that the macro passed. The problem is that I will not see anything about paths that did not "check". Any idea how do I do this? How to "register" a line of code at compile-time, so in run-time I can see that it didn't "check" yet? I hope I'm clear.

    Read the article

  • ShSetFolderPath works on win7, doesn't on XP

    - by pipboy3k
    Hey. I'm trying to use ShSetFolderPath function in C#. I work on Win7, I've managed to use ShSetKnownFolderPath and it works fine. Since this function is unavaible in WinXP, i tried to invoke ShSetFolderPath. Because i'm not familiar with invoking, I've done some searching and found something on some French forum. I don't speak French, but this declaration makes sense (as written in Remarks of function documentation in MSDN library): [DllImport( "Shell32.dll", CharSet = CharSet.Unicode, EntryPoint = "#232" ) ] private static extern int SHSetFolderPath( int csidl, IntPtr hToken, uint flags, string path ); I call it like that: private static int CSIDL_DESKTOP = 0x0000; public static void SetDesktopPath(string path) { int ret; ret = SHSetFolderPath(CSIDL_DESKTOP, IntPtr.Zero, 0, path); if (ret != 0) { Console.WriteLine(ret); Console.WriteLine(Marshal.GetExceptionForHR(ret)); } } It works in Win7, but in XP function returns -2147024809, which means "Value does not fall within the expected range". My guess is, it's something wrong with Dll importing. Any idea?

    Read the article

  • Check if BigDecimal is integer value

    - by Adamski
    Can anyone recommend an efficient way of determining whether a BigDecimal is an integer value in the mathematical sense? At present I have the following code: private boolean isIntegerValue(BigDecimal bd) { boolean ret; try { bd.toBigIntegerExact(); ret = true; } catch (ArithmeticException ex) { ret = false; } return ret; } ... but would like to avoid the object creation overhead if necessary. Previously I was using bd.longValueExact() which would avoid creating an object if the BigDecimal was using its compact representation internally, but obviously would fail if the value was too big to fit into a long. Any help appreciated.

    Read the article

  • Pythonic / itertools way to go through a dict?

    - by dmd
    def reportCSV(t): ret = '' for ev in t: for p in t[ev]: for w in t[ev][p]: ret += ','.join((ev, p, w, t[ev][p][w])) + '\n' return ret What is a more pythonic way to do this, e.g. using itertools or the like? In this case I'm just writing it out to a CSV file. t is a dict t[ev] is a dict t[ev][p] is a dict t[ev][p][w] is a float I'm not sure how I'd use itertools.product in this case.

    Read the article

  • ldap_bind_s returning LDAP_SUCCESS with wrong credentials

    - by rezna
    Hi guys, I have this little problem. I want to authenticate user against LDAP (Windows Active Directory), everything works OK, but the combination (good user, good password, wrong domain). LDAP* ldap = ldap_init(L"myserver", 389); ULONG ldap_version = 3; ULONG ret = LDAP_SUCCESS; ret = ldap_set_option(ldap, LDAP_OPT_PROTOCOL_VERSION, (void*)&ldap_version); ret = ldap_connect(ldap, NULL); SEC_WINNT_AUTH_IDENTITY ai; ai.Domain = (unsigned short*)BAD_DOMAIN; ai.DomainLength = wcslen(BAD_DOMAIN); ai.User = (unsigned short*)OK_USER; ai.UserLength = wcslen(OK_USER); ai.Password = (unsigned short*)OK_PASS; ai.PasswordLength = wcslen(OK_PASS); ai.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; ret = ldap_bind_s(ldap, NULL, (PWCHAR) &ai, LDAP_AUTH_NTLM); // !!! HERE !!! ret = ldap_unbind_s(ldap); On the line marke '!!! HERE !!!' I'd expect 0x31 or any other error returned. Instead I get LDAP_SUCCESS :( Any suggestions? Thx, Milan

    Read the article

  • strerror_r returns trash when I manually set errno during testing

    - by Robert S. Barnes
    During testing I have a mock object which sets errno = ETIMEDOUT; The object I'm testing sees the error and calls strerror_r to get back an error string: if (ret) { if (ret == EAI_SYSTEM) { char err[128]; strerror_r(errno, err, 128); err_string.assign(err); } else { err_string.assign(gai_strerror(ret)); } return ret; } I don't understand why strerror_r is returning trash. I even tried calling strerror_r(ETIMEDOUT, err, 128) directly and still got trash. I must be missing something. It seems I'm getting the gnu version of the function not the posix one, but that shouldn't make any difference in this case.

    Read the article

  • Vbscript / webcam. using flash API - Save streaming file as image

    - by remi
    Hi. Based on a php app we've tried to developp our own webapp in vbscript. All is working well. The camera starts, etc.. The problem we're left with is the following: the flash API is streaming the content of the video to a webpage, this page saves the photo as a jpg. The PHP code we're trying to emulate is as follow $str = file_get_contents("php://input"); file_put_contents("/tmp/upload.jpg", pack("H*", $str)); After intensive googling the best we can come up with is Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Dim sImagePath As String = Server.MapPath("/registration/") & "test.jpg" Dim data As Byte() = Request.BinaryRead(Request.TotalBytes) Dim Ret As Array Dim imgbmp As New System.Drawing.Bitmap("test.jpg") Dim ms As MemoryStream = New MemoryStream(data) imgbmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg) Ret = ms.ToArray() Dim fs As New FileStream(sImagePath, FileMode.Create, FileAccess.Write) fs.Write(Ret, 0, Ret.Length) fs.Flush() fs.Close() End Sub which is not working, does anybody have any suggestion?

    Read the article

  • JDO difficulties in retrieving persistent vector

    - by Michael Omer
    I know there are already some posts regarding this subject, but although I tried using them as a reference, I am still stuck. I have a persistent class as follows: @PersistenceCapable(identityType = IdentityType.APPLICATION) public class GameObject implements IMySerializable{ @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) protected Key m_databaseKey; @NotPersistent private final static int END_GAME_VAR = -1000; @Persistent(defaultFetchGroup = "true") protected GameObjectSet m_set; @Persistent protected int m_databaseType = IDatabaseAccess.TYPE_NONE; where GameObjectSet is: @PersistenceCapable(identityType = IdentityType.APPLICATION) @FetchGroup(name = "mySet", members = {@Persistent(name = "m_set")}) public class GameObjectSet { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Key id; @Persistent private Vector<GameObjectSetPair> m_set; and GameObjectSetPair is: @PersistenceCapable(identityType = IdentityType.APPLICATION) public class GameObjectSetPair { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Key id; @Persistent private String key; @Persistent(defaultFetchGroup = "true") private GameObjectVar value; When I try to fetch the entire structure by fetching the GameObject, the set doesn't have any elements (they are all null) I tried adding the fetching group to the PM, but to no avail. This is my fetching code Vector<GameObject> ret = new Vector<GameObject>(); PersistenceManager pm = PMF.get().getPersistenceManager(); pm.getFetchPlan().setMaxFetchDepth(-1); pm.getFetchPlan().addGroup("mySet"); Query myQuery = pm.newQuery(GameObject.class); myQuery.setFilter("m_databaseType == objectType"); myQuery.declareParameters("int objectType"); try { List<GameObject> res = (List<GameObject>)myQuery.execute(objectType); ret = new Vector<GameObject>(res); for (int i = 0; i < ret.size(); i++) { ret.elementAt(i).getSet(); ret.elementAt(i).getSet().touchSet(); } } catch (Exception e) { } finally { pm.close(); } Does anyone have any idea? Thanks Mike

    Read the article

  • C# String.Replace with a start/index (Added my (slow) implementation)

    - by Chris T
    I'd like an efficient method that would work something like this EDIT: Sorry I didn't put what I'd tried before. I updated the example now. // Method signature, Only replaces first instance or how many are specified in max public int MyReplace(ref string source,string org, string replace, int start, int max) { int ret = 0; int len = replace.Length; int olen = org.Length; for(int i = 0; i < max; i++) { // Find the next instance of the search string int x = source.IndexOf(org, ret + olen); if(x > ret) ret = x; else break; // Insert the replacement source = source.Insert(x, replace); // And remove the original source = source.Remove(x + len, olen); // removes original string } return ret; } string source = "The cat can fly but only if he is the cat in the hat"; int i = MyReplace(ref source,"cat", "giraffe", 8, 1); // Results in the string "The cat can fly but only if he is the giraffe in the hat" // i contains the index of the first letter of "giraffe" in the new string The only reason I'm asking is because my implementation I'd imagine getting slow with 1,000s of replaces.

    Read the article

  • I have this code .... Ethical Hacking

    - by kmitnick
    hello folks, I am following this EBook about Ethical Hacking, and I reached the Linux Exploit Chapter, this is the code with Aleph's 1 code. //shellcode.c char shellcode[] = //setuid(0) & Aleph1's famous shellcode, see ref. "\x31\xc0\x31\xdb\xb0\x17\xcd\x80" //setuid(0) first "\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b" "\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd" "\x80\xe8\xdc\xff\xff\xff/bin/sh"; int main() { //main function int *ret; //ret pointer for manipulating saved return. ret = (int *)&ret + 2; //setret to point to the saved return //value on the stack. (*ret) = (int)shellcode; //change the saved return value to the //address of the shellcode, so it executes. } I give this the super user privileges, with chmod u+s shellcode as a super user, then go back to normal user with su - normal_user but when I run ./shellcode I should be a root user but instead I still be normal_user so any help?? btw I am working on BT4-Final, I turned off the ASLR, and running BT4 in VMWare...

    Read the article

  • php - preg_replace not working when string contains a hashtag

    - by Steven
    I found a function online for turning a url within a string into a clickable link. However, when the url contains a hashtag it doesn't work. eg. http://www.bbc.co.uk/radio1/photos/fearnecotton/5759/1#gallery5759 Here's the part of the function concerned: $ret = preg_replace( "#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)#", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $ret ); $ret = preg_replace( "#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $ret ); Any ideas? thanks

    Read the article

  • template style matrix implementation in c

    - by monkeyking
    From time to time I use the following code for generating a matrix style datastructure typedef double myType; typedef struct matrix_t{ |Compilation started at Mon Apr 5 02:24:15 myType **matrix; | size_t x; |gcc structreaderGeneral.c -std=gnu99 -lz size_t y; | }matrix; |Compilation finished at Mon Apr 5 02:24:15 | | matrix alloc_matrix(size_t x, size_t y){ | if(0) | fprintf(stderr,"\t-> Alloc matrix with dim (%lu,%lu) byteprline=%lu bytetotal:%l\| u\n",x,y,y*sizeof(myType),x*y*sizeof(myType)); | | myType **m = (myType **)malloc(x*sizeof(myType **)); | for(size_t i=0;i<x;i++) | m[i] =(myType *) malloc(y*sizeof(myType *)); | | matrix ret; | ret.x=x; | ret.y=y; | ret.matrix=m; | return ret; | } And then I would change my typedef accordingly if I needed a different kind of type for the entries in my matrix. Now I need 2 matrices with different types, an easy solution would be to copy/paste the code, but is there some way to do a template styled implementation. Thanks

    Read the article

  • ede-proj-regenerate does weird things with my Makefile

    - by Xavier Maillard
    Hi, I have created a really basic project (Make) like this: (ede-proj-project "zrm" :name "zrm" :file "Project.ede" :targets (list (ede-proj-target-makefile-program "zm" :name "zrm" :path "" :source '("zrm.c") ) ) ) When doing M-x ede-proj-regenerate RET and M-x compile RET RET (accepting make -k as my compile command), make keeps bailing with a **missing separator error. When editing my Makefile outside of Emacs (with the darn evil vi) and replacing spaces by tabs, it works. Is there anything special I should pay attention in order to have this work ? Regards

    Read the article

  • C Check Substring of a String C

    - by user69514
    I'm trying to check whether or not the second argument in my program is a substring of the first argument. The problem is that it only work if the substring starts with the same letter of the string. EDIT: It must be done in C, not C++. Sorry #include <stdio.h> #include <string.h> int my_strstr( char const *s, char const *sub ) { char const *ret = sub; while ( ret = strchr( ret, *sub ) ) { if ( strcmp( ++ret, sub+1 ) == 0 ) return 1; } return 0; } int main(int argc, char **argv){ if (argc != 3) { printf ("Usage: check <string one> <string two>\n"); } int result = my_strstr(argv[1], argv[2]); if(result == 1){ printf("%s is a substring of %s\n", argv[2], argv[1]); } else{ printf("%s is not a substring of %s\n", argv[2], argv[1]); } return 0; }

    Read the article

  • Linq Query ignore empty parameters

    - by Cj Anderson
    How do I get Linq to ignore any parameters that are empty? So Lastname, Firstname, etc? If I have data in all parameters it works fine. refinedresult = From x In theresult _ Where x.<thelastname>.Value.TestPhoneElement(LastName) Or _ x.<thefirstname>.Value.TestPhoneElement(FirstName) Or _ x.<id>.Value.TestPhoneElement(Id) Or _ x.<number>.Value.TestPhoneElement(Telephone) Or _ x.<location>.Value.TestPhoneElement(Location) Or _ x.<building>.Value.TestPhoneElement(building) Or _ x.<department>.Value.TestPhoneElement(Department) _ Select x Public Function TestPhoneElement(ByVal parent As String, ByVal value2compare As String) As Boolean 'find out if a value is null, if not then compare the passed value to see if it starts with Dim ret As Boolean = False If String.IsNullOrEmpty(parent) Then Return False End If If String.IsNullOrEmpty(value2compare) Then Return ret Else ret = parent.ToLower.StartsWith(value2compare.ToLower.Trim) End If Return ret End Function

    Read the article

  • In jQuery datepicker beforeShowDay if fails

    - by michalzuber
    HI. I'm having problem to highlight more days. Somehow the if statement in beforeShowDay isn't true when it should be :( dateString typeof is string and an example is available in the screenshot at http://mikaelz.host.sk/datepicker.png Pasted code: var dates = new Array(); function addDate(date) {if (jQuery.inArray(date, dates) < 0) dates.push(date);} function removeDate(index) {dates.splice(index, 1);} function addOrRemoveDate(date) { var index = jQuery.inArray(date, dates); if (index >= 0) removeDate(index); else addDate(date); } function padNumber(number) { var ret = new String(number); if (ret.length == 1) ret = "0" + ret; return ret; } jQuery(document).ready(function(){ jQuery("#pick-date").datepicker({ onSelect: function(dateText, inst) { addOrRemoveDate(dateText); }, beforeShowDay: function (date){ var year = date.getFullYear(); var month = padNumber(date.getMonth()); var day = padNumber(date.getDate()); var dateString = day + "." + month + "." + year; if (dates.indexOf(dateString) >= 0) { return [true,"ui-state-highlight"]; } return [true, ""]; } }); }); Big thanks for any good ideas what could be wrong.

    Read the article

  • GDB disas question about address values

    - by user324994
    I'm working with a binary file that I disas'd in gdb. Right now I'm just examining the return value of a function. 0x08048604 <playGame+78>: ret Is the address shown the address where ret is stored in the function? Or is it just the address of the instruction to return the ret value?

    Read the article

  • Jquery Ajax not receiving php response correctly

    - by Theo
    I'm sending a JSON response from php to jquery: foreach ( $obj as $o ) { $a[ $o->key] = utf8_encode($o->id); } die(json_encode($a)); my html/jquery code is: $.ajax({ type:'POST', url: "imoveis/carrega_bairros", data: ({cidade:10}), dataType:"json", success: function(ret) { alert(ret) if(ret.success) { // ... } else alert("error"); } }); The json response is perfect (i get it on the console), but jquery is receiving a NULL ret object and it alerts "error". What's the problem???

    Read the article

  • [Embedded Python] Invoking a method on an object

    - by jmucchiello
    Given a PyObject* pointing to a python object, how do I invoke one of the object methods? The documentation never gives an example of this: PyObject* obj = .... PyObject* args = Py_BuildValue("(s)", "An arg"); PyObject* method = PyWHATGOESHERE(obj, "foo"); PyObject* ret = PyWHATGOESHERE(obj, method, args); if (!ret) { // check error... } This would be the equivalent of >>> ret = obj.foo("An arg")

    Read the article

  • c++ fread changing fgetpos strangely

    - by Steve
    If I run: FILE* pFile = fopen("c:\\08.bin", "r"); fpos_t pos; char buf[5000]; int ret = fread(&buf, 1, 9, pFile); fgetpos(pFile, &pos); I get ret = 9 and pos = 9. However if I run FILE* pFile = fopen("c:\\08.bin", "r"); fpos_t pos; char buf[5000]; int ret = fread(&buf, 1, 10, pFile); fgetpos(pFile, &pos); ret = 10 as expected, but pos = 11! How can this be?

    Read the article

  • JS Error:Cannot call method of null

    - by Nadeem
    I have the following method in a js file in ASP.Net web project. This method is giving the error Cannot call method 'split' of null function loadUser_InfoCallBack(res) { var ret=res.value; var senderGUID = ret.split(';')[0]; var senderText = ret.split(';')[1]; if(senderGUID.Length>0) { $('hiddenSender.value')=senderGUID; $('hiddenText.value')=senderText; } } Can anybody suggest the reasons for this error..

    Read the article

  • Converting Java code block to Objective-C

    - by user1123688
    I am trying to convert my Android app to iOS. This will be my first iOS app. I can't seem to translate this code properly. If someone wouldn't mind showing me how its done, that would be greatly appreciated. //scrambBase20 is a Byte array String descramble(String input){ char[] ret; ret = input.toCharArray(); int offset = -scrambBase20.length; for(int i=0;i<input.length();i++){ if(i%scrambBase20.length==0) offset+=scrambBase20.length; ret[scrambBase20[i%scrambBase20.length]+offset]=(char) ((byte) (input.charAt(i))^0x45); } String realRet = ""; for (char x : ret){ realRet+=x; } realRet = realRet.trim(); return realRet; }

    Read the article

  • SQLite delete the last 25% of records in a database.

    - by Steven smethurst
    I am using a SQLite database to store values from a data logger. The data logger will eventually fills up all the available hard drive space on the computer. I'm looking for a way to remove the last 25% of the logs from the database once it reaches a certain limit. Using the following code: $ret = Query( 'SELECT id as last FROM data ORDER BY id desc LIMIT 1 ;' ); $last_id = $ret[0]['last'] ; $ret = Query( 'SELECT count( * ) as total FROM data' ); $start_id = $last_id - $ret[0]['total'] * 0.75 ; Query( 'DELETE FROM data WHERE id < '. round( $start_id, 0 ) ); A journal file gets created next to the database that fills up the remaining space on the drive until the script fails. How/Can I stop this journal file from being created? Anyway to combined all three SQL queries in to one statement?

    Read the article

  • Is it reasonable that a random disk seek & read costs ~16ms?

    - by fzhang
    I am frustrated about the latency of random reading from a non-ssd disk. Based on results from following test program, it speeds ~16 ms for a random read of just 512 bytes without help of os cache. I tried changing 512 to larger values, such as 25k, and the latency did not increase as much. I guess it is because the disk seek dominates the time. I understand that random reading is inherently slow, but just want to be sure that ~16ms is reasonable, even for non-ssd disk. #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <sys/unistd.h> #include <fcntl.h> #include <limits.h> #include <stdio.h> #include <string.h> int main(int argc, char** argv) { int fd = open(argv[1], O_RDONLY); if (fd < 0) { fprintf(stderr, "Failed open %s\n", argv[1]); return -1; } const size_t count = 512; const off_t offset = 25990611 / 2; char buffer[count] = { '\0' }; struct timeval start_time; gettimeofday(&start_time, NULL); off_t ret = lseek(fd, offset, SEEK_SET); if (ret != offset) { perror("lseek error"); close(fd); return -1; } ret = read(fd, buffer, count); if (ret != count) { fprintf(stderr, "Failed reading all: %ld\n", ret); close(fd); return -1; } struct timeval end_time; gettimeofday(&end_time, NULL); printf("tv_sec: %ld, tv_usec: %ld\n", end_time.tv_sec - start_time.tv_sec, end_time.tv_usec - start_time.tv_usec); close(fd); return 0; }

    Read the article

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