Search Results

Search found 37183 results on 1488 pages for 'string conversion'.

Page 127/1488 | < Previous Page | 123 124 125 126 127 128 129 130 131 132 133 134  | Next Page >

  • "Function object is unsubscriptable" in basic integer to string mapping function

    - by IanWhalen
    I'm trying to write a function to return the word string of any number less than 1000. Everytime I run my code at the interactive prompt it appears to work without issue but when I try to import wordify and run it with a test number higher than 20 it fails as "TypeError: 'function' object is unsubscriptable". Based on the error message, it seems the issue is when it tries to index numString (for example trying to extract the number 4 out of the test case of n = 24) and the compiler thinks numString is a function instead of a string. since the first line of the function is me defining numString as a string of the variable n, I'm not really sure why that is. Any help in getting around this error, or even just help in explaining why I'm seeing it, would be awesome. def wordify(n): # Convert n to a string to parse out ones, tens and hundreds later. numString = str(n) # N less than 20 is hard-coded. if n < 21: return numToWordMap(n) # N between 21 and 99 parses ones and tens then concatenates. elif n < 100: onesNum = numString[-1] ones = numToWordMap(int(onesNum)) tensNum = numString[-2] tens = numToWordMap(int(tensNum)*10) return tens+ones else: # TODO pass def numToWordMap(num): mapping = { 0:"", 1:"one", 2:"two", 3:"three", 4:"four", 5:"five", 6:"six", 7:"seven", 8:"eight", 9:"nine", 10:"ten", 11:"eleven", 12:"twelve", 13:"thirteen", 14:"fourteen", 15:"fifteen", 16:"sixteen", 17:"seventeen", 18:"eighteen", 19:"nineteen", 20:"twenty", 30:"thirty", 40:"fourty", 50:"fifty", 60:"sixty", 70:"seventy", 80:"eighty", 90:"ninety", 100:"onehundred", 200:"twohundred", 300:"threehundred", 400:"fourhundred", 500:"fivehundred", 600:"sixhundred", 700:"sevenhundred", 800:"eighthundred", 900:"ninehundred", } return mapping[num] if __name__ == '__main__': pass

    Read the article

  • Getting the full-name of the current user, returns an empty string (C#/C++)

    - by Nir
    I try to get the full-name of the current log-in user (Fullname, not username). The following code C#, C++ works fine but on XP computers not connected to the Net, I get empty string as result if I run it ~20 minutes after login (It runs OK whithin the first ~20 minutes after login) A Win32 API (GetUserNameEx) is used rather that PrincipalContext since it PrincipalContext may takes up to 15 seconds when working offline. Any Help why am I getting an empty string as result though a user full name is specified??? - C# Code public static string CurrentUserFullName { get { const int EXTENDED_NAME_FORMAT_NAME_DISPLAY = 3; StringBuilder userName = new StringBuilder(256); uint length = (uint) userName.Capacity; string ret; if (GetUserNameEx(EXTENDED_NAME_FORMAT_NAME_DISPLAY, userName, ref length)) { ret = userName.ToString(); } else { int errorCode = Marshal.GetLastWin32Error(); throw new Win32Exception("GetUserNameEx Failed. Error code - " + errorCode); } return ret; } } [DllImport("Secur32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern bool GetUserNameEx(int nameFormat, StringBuilder lpNameBuffer, ref uint lpnSize); - Code in C++ #include "stdafx.h" #include <windows.h> #define SECURITY_WIN32 #include <Security.h> #pragma comment( lib, "Secur32.lib" ) int _tmain(int argc, _TCHAR* argv[]) { char szName[100]; ULONG nChars = sizeof( szName ); if ( GetUserNameEx( NameDisplay, szName, &nChars ) ) { printf( "Name: %s\n", szName); } else { printf( "Failed to GetUserNameEx\n" ); printf( "%d\n", GetLastError() ); } return 0; }

    Read the article

  • Passing.getText() String to another class

    - by DanMc
    I'm currently working on a first year university project and I have a problem, although I doubt it's a very complicated one, but I've been searching and I just can't find a suitable answer to it. The problem concerns two classes. A gui class (class1) and another class (class2). I have a JTextField in class1 and am trying to pass through the .getText() value to class2 and store it in a String type variable. The current code I'm trying to achieve this with is the following: (Class1) private JTextField textField = new JTextField("Something"); ... public String getTextFieldString() { return textField.getText(); } (Class2) private c1 Class1 = new Class1(); private String s = new String(); ... s = c1.getTextFieldString(); I'm pretty new to coding, I've read that maybe I need to pass through an argument somewhere and I assume that's because textField is not static in itself, it changes when somebody enters a new value. (sorry for stating the obvious there.) Anyway, help is appreciated. Thanks a lot!

    Read the article

  • How to update a string property of an sqlite database item

    - by Thomas Joos
    hi all, I'm trying to write an application that checks if there is an active internet connection. If so it reads an xml and checks every 'lastupdated' item ( php generated string ). It compares it to the database items and if there is a new value, this particular item needs to be updated. My code seems to work ( compiles, no error messages, no failures, .. ) but I notice that the particular property does not change, it becomese (null). When I output the binded string value it returns the correct string value I want to update into the db.. Any idea what I'm doing wrong? const char *sql = "update myTable Set last_updated=? Where node_id =?"; sqlite3_stmt *statement; // Preparing a statement compiles the SQL query into a byte-code program in the SQLite library. // The third parameter is either the length of the SQL string or -1 to read up to the first null terminator. if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK){ NSLog(@"last updated item: %@", [d lastupdated]); sqlite3_bind_text(statement, 1, [d lastupdated],-1,SQLITE_TRANSIENT); sqlite3_bind_int (statement, 2, [d node_id]); }else { NSLog(@"SQLite statement error!"); } if(SQLITE_DONE != sqlite3_step(statement)){ NSAssert1(0, @"Error while updating. '%s'", sqlite3_errmsg(database)); }else { NSLog(@"SQLite Update done!"); }

    Read the article

  • Unable to parse variable length string separated by delimiter

    - by Technext
    Hi, I have a problem with parsing a string, which consists only of directory path. For ex. My input string is Abc\Program Files\sample\ My output should be Abc//Program Files//sample The script should work for input path of any length i.e., it can contain any no. of subdirectories. (For ex., abc\temp\sample\folder\joe) I have looked for help in many links but to no avail. Looks like FOR command extracts only one whole line or a string (when we use ‘token’ keyword in FOR syntax) but my problem is that I am not aware of the input path length and hence, the no. of tokens. My idea was to use \ as a delimiter and then extract each word before and after it (), and put the words to an output file along with // till we reach the end of the string. I tried implementing the following but it did not work: @echo off FOR /F "delims=\" %%x in (orig.txt) do ( IF NOT %%x == "" echo.%%x//output.txt ) The file orig.txt contains only one line i.e, Abc\Program Files\sample\ The output that I get contains only: Abc// The above output contains blank spaces as well after ‘Abc//’ My desired output should be: Abc//program Files//sample// Can anyone please help me with this? Regards, Technext

    Read the article

  • .Net SQL Parameter for String List Problem

    - by JK
    I am writing a C# program in which I send a query to SQL Server to be processed and a dataset returns. I am using parameters to pass information to the query before it is sent to SQL server. This works fine except in the situation below. The query looks like this: reportQuery = " Select * From tableName Where Account_Number in (@AccountNum); and Account_Date = @AccountDate "; The AccountDate parameter works find but not the AccountNum parameter. I need the final query to execute like this: Select * From tableName Where Account_Number in ('AX3456','YZYL123','ZZZ123'); and Account_Date = '1-Jan-2010' The problem is that I have these account numbers (actually text) in a C# string list. To feed it to the parameter, I have been declaring the parameter as a string. I turn the list into one string and feed it to the parameter. I think the problem is that I am feeding the paramater this: "'AX3456','YZYL123','ZZZ123'" when it wants this 'AX3456','YZYL123','ZZZ123' How do I get the string list into the query using a parameter and have it execute as shown above? This is how I am declaring and assigning the parameter. SqlParameter AccountNumsParam = new SqlParameter(); AccountNumsParam.ParameterName = "@AccountNums"; AccountNumsParam.SqlDbType = SqlDbType.NVarChar; AccountNumsParam.Value = AccountNumsString; FYI, AccountNumString == "'AX3456','YZYL123','ZZZ123'"

    Read the article

  • Java - Counting how many characters show up in another string

    - by Vu Châu
    I am comparing two strings, in Java, to see how many characters from the first string show up in the second string. The following is some expectations: matchingChars("AC", "BA") ? 1 matchingChars("ABBA", "B") ? 2 matchingChars("B", "ABBA") ? 1 My approach is as follows: public int matchingChars(String str1, String str2) { int count = 0; for (int a = 0; a < str1.length(); a++) { for (int b = 0; b < str2.length(); b++) { char str1Char = str1.charAt(a); char str2Char = str2.charAt(b); if (str1Char == str2Char) { count++; str1 = str1.replace(str1Char, '0'); } } } return count; } I know my approach is not the best, but I think it should do it. However, for matchingChars("ABBA", "B") ? 2 My code yields "1" instead of "2". Does anyone have any suggestion or advice? Thank you very much.

    Read the article

  • String Index Out Of Bound Exception error

    - by Fd Fehfhd
    Im not really sure why a am getting this error. But here is my code it is meant to test palindromes disregarding punctuation. So here is my code import java.util.Scanner; public class PalindromeTester { public static void main(String [] args) { Scanner kb = new Scanner(System.in); String txt = ""; int left; int right; int cntr = 0; do { System.out.println("Enter a word, phrase, or sentence (blank line to stop):"); txt = kb.nextLine(); txt = txt.toLowerCase(); char yP; String noP = ""; for (int i = 0; i < txt.length(); i++) { yP = txt.charAt(i); if (Character.isLetterOrDigit(txt.charAt(yP))) { noP += yP; } } txt = noP; left = 0; right = txt.length() -1; while (txt.charAt(left) == txt.charAt(right) && right > left) { left++; right--; } if (left > right) { System.out.println("Palindrome"); cntr++; } else { System.out.println("Not a palindrome"); } } while (!txt.equals("")); System.out.println("You found " + cntr + " palindromes. Thank you for using palindromeTester."); } } And if i test it and then i put enter so it will tell me how many palindromes you found the error i am getting is javav.lang.StringIndexOutOfBoundException : String index out of range 0 at PalindromeTester.main(PalindromeTester.java:38) and line 28 is while (txt.charAt(left) == txt.charAt(right) && right > left) Thanks for the help in advance

    Read the article

  • SQL Server 2008 Prior String Extract

    - by Saidur Rahman
    I have strings like the ones below in a SQL column. I want to extract them as a Gigabyte amount in aggregate. Example: Original Column ---------> Expected Output from a TSQL function ------------------------------------------- $15 / 1GB 24m + Intern 120MB ----------> 1.12 GB $19.95 / 500MB + $49.95 / 9GB Blackberry -----> 9.5GB $174.95 Blackberry 24GB + $10 / 1GB Datapack ----> 25GB $79 / 6GB --> 6GB Null --> Null $20 Plan --> 0GB Note: for our purpose, 1000MB = 1 GB (not 1024). The pattern is numbers followed by GB/MB, usually they are combined like 1GB (without any space but may sometimes may contain a space, it is not particularly important if hard to implement for this exception). Sometimes there are up to three or four instances of GB/MB occurring in the same string which are usually separated by a + sign (see row 2 and 3 of my example above). I have seen how we extract the dollar values in one of the answers where numbers were followed by $ or extract all integers in a string but I don't want to extract the dollar values or all the integers in a string. I just want the sum of GB/MB in the string.

    Read the article

  • NHibernate with string primary key and relationships

    - by John_
    I've have just been stumped with this problem for an hour and I annoyingly found the problem eventually. THE CIRCUMSTANCES I have a table which users a string as a primary key, this table has various many to one and many to many relationships all off this primary key. When searching for multiple items from the table all relationships were brought back. However whenever I tried to get the object by the primary key (string) it was not bringing back any relationships, they were always set to 0. THE PARTIAL SOLUTION So I looked into my logs to see what the SQL was doing and that was returning the correct results. So I tried various things in all sorts of random ways and eventually worked out it was. The case of the string being passed into the get method was not EXACTLY the same case as it was in the database, so when it tried to match up the relationship items with the main entity it was finding nothing (Or at least NHIbernate wasn't because as I stated above the SQL was actually returning the correct results) THE REAL SOLUTION Has anyone else come across this? If so how do you tell NHibernate to ignore case when matching SQL results to the entity? It is silly because it worked perfectly well before now all of a sudden it has started to pay attention to the case of the string.

    Read the article

  • Iterating over a String to check for a number and printing out the String value if it doesn't have a number

    - by wheelerlc64
    I have set up my function for checking for a number in a String, and printing out that String if it has no numbers, and putting up an error message if it does. Here is my code: public class NumberFunction { public boolean containsNbr(String str) { boolean containsNbr = false; if(str != null && !str.isEmpty()) { for(char c : str.toCharArray()) { if(containsNbr = Character.isDigit(c)) { System.out.println("Can't contain numbers in the word."); break; } else { System.out.println(str); } } } return containsNbr; } } import com.imports.validationexample.function.NumberFunction; public class Main { public static void main(String[] args) { NumberFunction nf = new NumberFunction(); System.out.println(nf.containsNbr("bill4")); } } I am trying to get it to print out the result to the console, but the result keeps printing multiple times and prints the boolean value, which I do not want, something like this: bill4 bill4 bill4 bill4 Can't contain numbers in the word. true Why is this happening? I've tried casting but that hasn't worked out either. Any help would be much appreciated.

    Read the article

  • Help with string equality in Java

    - by annayena
    The following function accepts 2 strings, the 2nd (not 1st) possibly containing *'s (asterisks). An * is a replacement for a string (empty, 1 char or more), it can appear appear (only in s2) once, twice, more or not at all, it cannot be adjacent to another * (ab**c), no need to check that. public static boolean samePattern(String s1, String s2) It returns true if strings are of the same pattern. It must be recursive, not use any loops, static or global variables. Also it's prohibited to use the method equals in the String class. Can use local variables and method overloading. Can use only these methods: charAt(i), substring(i), substring(i, j), length(). Examples: 1: TheExamIsEasy; 2: "The*xamIs*y" ---> true 1: TheExamIsEasy; 2: "Th*mIsEasy*" ---> true 1: TheExamIsEasy; 2: "*" ---> true 1: TheExamIsEasy; 2: "TheExamIsEasy" ---> true 1: TheExamIsEasy; 2: "The*IsHard" ---> FALSE I am stucked on this question for many hours now! I need the solution in Java please kindly help me.

    Read the article

  • Working with a string as an array of characters

    - by Malfunction
    I'm having some trouble with a string represented as an array of characters. What I'd like to do, as I would do in java, is the following: while (i < chars.length) { char ch = chars[i]; if ((WORD_CHARS.indexOf(ch) >= 0) == punctuation) { String token = buffer.toString(); if (token.length() > 0) { parts.add(token); } buffer = new StringBuffer(); } buffer.append(ch); i++; } What I'm doing is something like this: while(i < strlen(chars)) { char ch = chars[i]; if(([WORD_CHARS rangeOfString:ch] >= 0) == punctuation) { NSString *token = buffer.toString(); if([token length] > 0) { [parts addObject:token]; } buffer = [NSMutableString string]; } [buffer append(ch)]; i++; } I'm not sure how I'm supposed to convert String token = buffer.toString(); to objective c, where buffer is an NSMutableString. Also, how do I check this if condition in objective c? if ((WORD_CHARS.indexOf(ch) >= 0) == punctuation) WORD_CHARS is an NSString. I'm also having trouble with appending ch to buffer. Any help is greatly appreciated.

    Read the article

  • Taking item from string array that *might* be there

    - by AndyC
    Hi all, I have a string array, and it may contain an element with the text "mytext" within the string. eg: mystringarray { [0] => "hello world"; [1] => "some of mytext"; } I also have an array that doesn't have the mytext text in it. mystringarray { [0] => "hello world"; [1] => "some of notmy"; } My problem is when I use: string mytextdata = mystringarray.Single<string>(t => t.Contains("mytext")).ToString(); I get an exception for the second array as it can't find an element that matches the expression. Is there a quick way I can edit this one line to not throw an exception if it finds nothing, and instead just ignore? I have a lot of these lines and I don't want to have to wrap each in an if statement. Apologies if question isn't clear.

    Read the article

  • Escaping an equals sign in DOS batch string replacement command

    - by Alastair
    Hi, I need to replace some text in a JNLP file using a DOS batch file to tune it for the local machine. The problem is that the search pattern contains an equals sign which is messing up the string replacement in the batch file. I want to replace the line, <j2se version="1.5" initial-heap-size="100M" max-heap-size="100M"/> with specific settings for the initial and max heap sizes. For example at the moment I have, for /f "tokens=* delims=" %%a in (%filePath%agility.jnlp) do ( set str=%%a set str=!str:initial-heap-size="100M"=initial-heap-size="%min%M"! echo !str!>>%filePath%new.jnlp) but the = in the search pattern is being read as part of the replacement command. How do I escape the equals sign so it is processed as text?

    Read the article

  • WLS MBeans

    - by Jani Rautiainen
    WLS provides a set of Managed Beans (MBeans) to configure, monitor and manage WLS resources. We can use the WLS MBeans to automate some of the tasks related to the configuration and maintenance of the WLS instance. The MBeans can be accessed a number of ways; using various UIs and programmatically using Java or WLST Python scripts.For customization development we can use the features to e.g. manage the deployed customization in MDS, control logging levels, automate deployment of dependent libraries etc. This article is an introduction on how to access and use the WLS MBeans. The goal is to illustrate the various access methods in a single article; the details of the features are left to the linked documentation.This article covers Windows based environment, steps for Linux would be similar however there would be some differences e.g. on how the file paths are defined. MBeansThe WLS MBeans can be categorized to runtime and configuration MBeans.The Runtime MBeans can be used to access the runtime information about the server and its resources. The data from runtime beans is only available while the server is running. The runtime beans can be used to e.g. check the state of the server or deployment.The Configuration MBeans contain information about the configuration of servers and resources. The configuration of the domain is stored in the config.xml file and the configuration MBeans can be used to access and modify the configuration data. For more information on the WLS MBeans refer to: Understanding WebLogic Server MBeans WLS MBean reference Java Management Extensions (JMX)We can use JMX APIs to access the WLS MBeans. This allows us to create Java programs to configure, monitor, and manage WLS resources. In order to use the WLS MBeans we need to add the following library into the class-path: WL_HOME\lib\wljmxclient.jar Connecting to a WLS MBean server The WLS MBeans are contained in a Mbean server, depending on the requirement we can connect to (MBean Server / JNDI Name): Domain Runtime MBean Server weblogic.management.mbeanservers.domainruntime Runtime MBean Server weblogic.management.mbeanservers.runtime Edit MBean Server weblogic.management.mbeanservers.edit To connect to the WLS MBean server first we need to create a map containing the credentials; Hashtable<String, String> param = new Hashtable<String, String>(); param.put(Context.SECURITY_PRINCIPAL, "weblogic");        param.put(Context.SECURITY_CREDENTIALS, "weblogic1");        param.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote"); These define the user, password and package containing the protocol. Next we create the connection: JMXServiceURL serviceURL =     new JMXServiceURL("t3","127.0.0.1",7101,     "/jndi/weblogic.management.mbeanservers.domainruntime"); JMXConnector connector = JMXConnectorFactory.connect(serviceURL, param); MBeanServerConnection connection = connector.getMBeanServerConnection(); With the connection we can now access the MBeans for the WLS instance. For a complete example see Appendix A of this post. For more details refer to Accessing WebLogic Server MBeans with JMX Accessing WLS MBeans The WLS MBeans are structured hierarchically; in order to access content we need to know the path to the MBean we are interested in. The MBean is accessed using “MBeanServerConnection. getAttribute” API.  WLS provides entry points to the hierarchy allowing us to navigate all the WLS MBeans in the hierarchy (MBean Server / JMX object name): Domain Runtime MBean Server com.bea:Name=DomainRuntimeService,Type=weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean Runtime MBean Servers com.bea:Name=RuntimeService,Type=weblogic.management.mbeanservers.runtime.RuntimeServiceMBean Edit MBean Server com.bea:Name=EditService,Type=weblogic.management.mbeanservers.edit.EditServiceMBean For example we can access the Domain Runtime MBean using: ObjectName service = new ObjectName( "com.bea:Name=DomainRuntimeService," + "Type=weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean"); Same syntax works for any “child” WLS MBeans e.g. to find out all application deployments we can: ObjectName domainConfig = (ObjectName)connection.getAttribute(service,"DomainConfiguration"); ObjectName[] appDeployments = (ObjectName[])connection.getAttribute(domainConfig,"AppDeployments"); Alternatively we could access the same MBean using the full syntax: ObjectName domainConfig = new ObjectName("com.bea:Location=DefaultDomain,Name=DefaultDomain,Type=Domain"); ObjectName[] appDeployments = (ObjectName[])connection.getAttribute(domainConfig,"AppDeployments"); For more details refer to Accessing WebLogic Server MBeans with JMX Invoking operations on WLS MBeans The WLS MBean operations can be invoked with MBeanServerConnection. invoke API; in the following example we query the state of “AppsLoggerService” application: ObjectName appRuntimeStateRuntime = new ObjectName("com.bea:Name=AppRuntimeStateRuntime,Type=AppRuntimeStateRuntime"); Object[] parameters = { "AppsLoggerService", "DefaultServer" }; String[] signature = { "java.lang.String", "java.lang.String" }; String result = (String)connection.invoke(appRuntimeStateRuntime,"getCurrentState",parameters, signature); The result returned should be "STATE_ACTIVE" assuming the "AppsLoggerService" application is up and running. WebLogic Scripting Tool (WLST) The WebLogic Scripting Tool (WLST) is a command-line scripting environment that we can access the same WLS MBeans. The tool is located under: $MW_HOME\oracle_common\common\bin\wlst.bat Do note that there are several instances of the wlst script under the $MW_HOME, each of them works, however the commands available vary, so we want to use the one under “oracle_common”. The tool is started in offline mode. In offline mode we can access and manipulate the domain configuration. In online mode we can access the runtime information. We connect to the Administration Server : connect("weblogic","weblogic1", "t3://127.0.0.1:7101") In both online and offline modes we can navigate the WLS MBean using commands like "ls" to print content and "cd" to navigate between objects, for example: All the commands available can be obtained with: help('all') For details of the tool refer to WebLogic Scripting Tool and for the commands available WLST Command and Variable Reference. Also do note that the WLST tool can be invoked from Java code in Embedded Mode. Running Scripts The WLST tool allows us to automate tasks using Python scripts in Script Mode. The script can be manually created or recorded by the WLST tool. Example commands of recording a script: startRecording("c:/temp/recording.py") <commands that we want to record> stopRecording() We can run the script from WLST: execfile("c:/temp/recording.py") We can also run the script from the command line: C:\apps\Oracle\Middleware\oracle_common\common\bin\wlst.cmd c:/temp/recording.py There are various sample scripts are provided with the WLS instance. UI to Access the WLS MBeans There are various UIs through which we can access the WLS MBeans. Oracle Enterprise Manager Fusion Middleware Control Oracle WebLogic Server Administration Console Fusion Middleware Control MBean Browser In the integrated JDeveloper environment only the Oracle WebLogic Server Administration Console is available to us. For more information refer to the documentation, one noteworthy feature in the console is the ability to record WLST scripts based on the navigation. In addition to the UIs above the JConsole included in the JDK can be used to access the WLS MBeans. The JConsole needs to be started with specific parameter to force WLS objects to be used and jar files in the classpath: "C:\apps\Oracle\Middleware\jdk160_24\bin\jconsole" -J-Djava.class.path=C:\apps\Oracle\Middleware\jdk160_24\lib\jconsole.jar;C:\apps\Oracle\Middleware\jdk160_24\lib\tools.jar;C:\apps\Oracle\Middleware\wlserver_10.3\server\lib\wljmxclient.jar -J-Djmx.remote.protocol.provider.pkgs=weblogic.management.remote For more details refer to the Accessing Custom MBeans from JConsole. Summary In this article we have covered various ways we can access and use the WLS MBeans in context of integrated WLS in JDeveloper to be used for Fusion Application customization development. References Developing Custom Management Utilities With JMX for Oracle WebLogic Server Accessing WebLogic Server MBeans with JMX WebLogic Server MBean Reference WebLogic Scripting Tool WLST Command and Variable Reference Appendix A package oracle.apps.test; import java.io.IOException;import java.net.MalformedURLException;import java.util.Hashtable;import javax.management.MBeanServerConnection;import javax.management.MalformedObjectNameException;import javax.management.ObjectName;import javax.management.remote.JMXConnector;import javax.management.remote.JMXConnectorFactory;import javax.management.remote.JMXServiceURL;import javax.naming.Context;/** * This class contains simple examples on how to access WLS MBeans using JMX. */public class BlogExample {    /**     * Connection to the WLS MBeans     */    private MBeanServerConnection connection;    /**     * Constructor that takes in the connection information for the      * domain and obtains the resources from WLS MBeans using JMX.     * @param hostName host name to connect to for the WLS server     * @param port port to connect to for the WLS server     * @param userName user name to connect to for the WLS server     * @param password password to connect to for the WLS server     */    public BlogExample(String hostName, String port, String userName,                       String password) {        super();        try {            initConnection(hostName, port, userName, password);        } catch (Exception e) {            throw new RuntimeException("Unable to connect to the domain " +                                       hostName + ":" + port);        }    }    /**     * Default constructor.     * Tries to create connection with default values. Runtime exception will be     * thrown if the default values are not used in the local instance.     */    public BlogExample() {        this("127.0.0.1", "7101", "weblogic", "weblogic1");    }    /**     * Initializes the JMX connection to the WLS Beans     * @param hostName host name to connect to for the WLS server     * @param port port to connect to for the WLS server     * @param userName user name to connect to for the WLS server     * @param password password to connect to for the WLS server     * @throws IOException error connecting to the WLS MBeans     * @throws MalformedURLException error connecting to the WLS MBeans     * @throws MalformedObjectNameException error connecting to the WLS MBeans     */    private void initConnection(String hostName, String port, String userName,                                String password)                                 throws IOException, MalformedURLException,                                        MalformedObjectNameException {        String protocol = "t3";        String jndiroot = "/jndi/";        String mserver = "weblogic.management.mbeanservers.domainruntime";        JMXServiceURL serviceURL =            new JMXServiceURL(protocol, hostName, Integer.valueOf(port),                              jndiroot + mserver);        Hashtable<String, String> h = new Hashtable<String, String>();        h.put(Context.SECURITY_PRINCIPAL, userName);        h.put(Context.SECURITY_CREDENTIALS, password);        h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES,              "weblogic.management.remote");        JMXConnector connector = JMXConnectorFactory.connect(serviceURL, h);        connection = connector.getMBeanServerConnection();    }    /**     * Main method used to invoke the logic for testing     * @param args arguments passed to the program     */    public static void main(String[] args) {        BlogExample blogExample = new BlogExample();        blogExample.testEntryPoint();        blogExample.testDirectAccess();        blogExample.testInvokeOperation();    }    /**     * Example of using an entry point to navigate the WLS MBean hierarchy.     */    public void testEntryPoint() {        try {            System.out.println("testEntryPoint");            ObjectName service =             new ObjectName("com.bea:Name=DomainRuntimeService,Type=" +"weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean");            ObjectName domainConfig =                (ObjectName)connection.getAttribute(service,                                                    "DomainConfiguration");            ObjectName[] appDeployments =                (ObjectName[])connection.getAttribute(domainConfig,                                                      "AppDeployments");            for (ObjectName appDeployment : appDeployments) {                String resourceIdentifier =                    (String)connection.getAttribute(appDeployment,                                                    "SourcePath");                System.out.println(resourceIdentifier);            }        } catch (Exception e) {            throw new RuntimeException(e);        }    }    /**     * Example of accessing WLS MBean directly with a full reference.     * This does the same thing as testEntryPoint in slightly difference way.     */    public void testDirectAccess() {        try {            System.out.println("testDirectAccess");            ObjectName appDeployment =                new ObjectName("com.bea:Location=DefaultDomain,"+                               "Name=AppsLoggerService,Type=AppDeployment");            String resourceIdentifier =                (String)connection.getAttribute(appDeployment, "SourcePath");            System.out.println(resourceIdentifier);        } catch (Exception e) {            throw new RuntimeException(e);        }    }    /**     * Example of invoking operation on a WLS MBean.     */    public void testInvokeOperation() {        try {            System.out.println("testInvokeOperation");            ObjectName appRuntimeStateRuntime =                new ObjectName("com.bea:Name=AppRuntimeStateRuntime,"+                               "Type=AppRuntimeStateRuntime");            String identifier = "AppsLoggerService";            String serverName = "DefaultServer";            Object[] parameters = { identifier, serverName };            String[] signature = { "java.lang.String", "java.lang.String" };            String result =                (String)connection.invoke(appRuntimeStateRuntime, "getCurrentState",                                          parameters, signature);            System.out.println("State of " + identifier + " = " + result);        } catch (Exception e) {            throw new RuntimeException(e);        }    }}

    Read the article

  • Uploading and Importing CSV file to SQL Server in ASP.NET WebForms

    - by Vincent Maverick Durano
    Few weeks ago I was working with a small internal project  that involves importing CSV file to Sql Server database and thought I'd share the simple implementation that I did on the project. In this post I will demonstrate how to upload and import CSV file to SQL Server database. As some may have already know, importing CSV file to SQL Server is easy and simple but difficulties arise when the CSV file contains, many columns with different data types. Basically, the provider cannot differentiate data types between the columns or the rows, blindly it will consider them as a data type based on first few rows and leave all the data which does not match the data type. To overcome this problem, I used schema.ini file to define the data type of the CSV file and allow the provider to read that and recognize the exact data types of each column. Now what is schema.ini? Taken from the documentation: The Schema.ini is a information file, used to define the data structure and format of each column that contains data in the CSV file. If schema.ini file exists in the directory, Microsoft.Jet.OLEDB provider automatically reads it and recognizes the data type information of each column in the CSV file. Thus, the provider intelligently avoids the misinterpretation of data types before inserting the data into the database. For more information see: http://msdn.microsoft.com/en-us/library/ms709353%28VS.85%29.aspx Points to remember before creating schema.ini:   1. The schema information file, must always named as 'schema.ini'.   2. The schema.ini file must be kept in the same directory where the CSV file exists.   3. The schema.ini file must be created before reading the CSV file.   4. The first line of the schema.ini, must the name of the CSV file, followed by the properties of the CSV file, and then the properties of the each column in the CSV file. Here's an example of how the schema looked like: [Employee.csv] ColNameHeader=False Format=CSVDelimited DateTimeFormat=dd-MMM-yyyy Col1=EmployeeID Long Col2=EmployeeFirstName Text Width 100 Col3=EmployeeLastName Text Width 50 Col4=EmployeeEmailAddress Text Width 50 To get started lets's go a head and create a simple blank database. Just for the purpose of this demo I created a database called TestDB. After creating the database then lets go a head and fire up Visual Studio and then create a new WebApplication project. Under the root application create a folder called UploadedCSVFiles and then place the schema.ini on that folder. The uploaded CSV files will be stored in this folder after the user imports the file. Now add a WebForm in the project and set up the HTML mark up and add one (1) FileUpload control one(1)Button and three (3) Label controls. After that we can now proceed with the codes for uploading and importing the CSV file to SQL Server database. Here are the full code blocks below: 1: using System; 2: using System.Data; 3: using System.Data.SqlClient; 4: using System.Data.OleDb; 5: using System.IO; 6: using System.Text; 7:   8: namespace WebApplication1 9: { 10: public partial class CSVToSQLImporting : System.Web.UI.Page 11: { 12: private string GetConnectionString() 13: { 14: return System.Configuration.ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString; 15: } 16: private void CreateDatabaseTable(DataTable dt, string tableName) 17: { 18:   19: string sqlQuery = string.Empty; 20: string sqlDBType = string.Empty; 21: string dataType = string.Empty; 22: int maxLength = 0; 23: StringBuilder sb = new StringBuilder(); 24:   25: sb.AppendFormat(string.Format("CREATE TABLE {0} (", tableName)); 26:   27: for (int i = 0; i < dt.Columns.Count; i++) 28: { 29: dataType = dt.Columns[i].DataType.ToString(); 30: if (dataType == "System.Int32") 31: { 32: sqlDBType = "INT"; 33: } 34: else if (dataType == "System.String") 35: { 36: sqlDBType = "NVARCHAR"; 37: maxLength = dt.Columns[i].MaxLength; 38: } 39:   40: if (maxLength > 0) 41: { 42: sb.AppendFormat(string.Format(" {0} {1} ({2}), ", dt.Columns[i].ColumnName, sqlDBType, maxLength)); 43: } 44: else 45: { 46: sb.AppendFormat(string.Format(" {0} {1}, ", dt.Columns[i].ColumnName, sqlDBType)); 47: } 48: } 49:   50: sqlQuery = sb.ToString(); 51: sqlQuery = sqlQuery.Trim().TrimEnd(','); 52: sqlQuery = sqlQuery + " )"; 53:   54: using (SqlConnection sqlConn = new SqlConnection(GetConnectionString())) 55: { 56: sqlConn.Open(); 57: SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn); 58: sqlCmd.ExecuteNonQuery(); 59: sqlConn.Close(); 60: } 61:   62: } 63: private void LoadDataToDatabase(string tableName, string fileFullPath, string delimeter) 64: { 65: string sqlQuery = string.Empty; 66: StringBuilder sb = new StringBuilder(); 67:   68: sb.AppendFormat(string.Format("BULK INSERT {0} ", tableName)); 69: sb.AppendFormat(string.Format(" FROM '{0}'", fileFullPath)); 70: sb.AppendFormat(string.Format(" WITH ( FIELDTERMINATOR = '{0}' , ROWTERMINATOR = '\n' )", delimeter)); 71:   72: sqlQuery = sb.ToString(); 73:   74: using (SqlConnection sqlConn = new SqlConnection(GetConnectionString())) 75: { 76: sqlConn.Open(); 77: SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn); 78: sqlCmd.ExecuteNonQuery(); 79: sqlConn.Close(); 80: } 81: } 82: protected void Page_Load(object sender, EventArgs e) 83: { 84:   85: } 86: protected void BTNImport_Click(object sender, EventArgs e) 87: { 88: if (FileUpload1.HasFile) 89: { 90: FileInfo fileInfo = new FileInfo(FileUpload1.PostedFile.FileName); 91: if (fileInfo.Name.Contains(".csv")) 92: { 93:   94: string fileName = fileInfo.Name.Replace(".csv", "").ToString(); 95: string csvFilePath = Server.MapPath("UploadedCSVFiles") + "\\" + fileInfo.Name; 96:   97: //Save the CSV file in the Server inside 'MyCSVFolder' 98: FileUpload1.SaveAs(csvFilePath); 99:   100: //Fetch the location of CSV file 101: string filePath = Server.MapPath("UploadedCSVFiles") + "\\"; 102: string strSql = "SELECT * FROM [" + fileInfo.Name + "]"; 103: string strCSVConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";" + "Extended Properties='text;HDR=YES;'"; 104:   105: // load the data from CSV to DataTable 106:   107: OleDbDataAdapter adapter = new OleDbDataAdapter(strSql, strCSVConnString); 108: DataTable dtCSV = new DataTable(); 109: DataTable dtSchema = new DataTable(); 110:   111: adapter.FillSchema(dtCSV, SchemaType.Mapped); 112: adapter.Fill(dtCSV); 113:   114: if (dtCSV.Rows.Count > 0) 115: { 116: CreateDatabaseTable(dtCSV, fileName); 117: Label2.Text = string.Format("The table ({0}) has been successfully created to the database.", fileName); 118:   119: string fileFullPath = filePath + fileInfo.Name; 120: LoadDataToDatabase(fileName, fileFullPath, ","); 121:   122: Label1.Text = string.Format("({0}) records has been loaded to the table {1}.", dtCSV.Rows.Count, fileName); 123: } 124: else 125: { 126: LBLError.Text = "File is empty."; 127: } 128: } 129: else 130: { 131: LBLError.Text = "Unable to recognize file."; 132: } 133:   134: } 135: } 136: } 137: } The code above consists of three (3) private methods which are the GetConnectionString(), CreateDatabaseTable() and LoadDataToDatabase(). The GetConnectionString() is a method that returns a string. This method basically gets the connection string that is configured in the web.config file. The CreateDatabaseTable() is method that accepts two (2) parameters which are the DataTable and the filename. As the method name already suggested, this method automatically create a Table to the database based on the source DataTable and the filename of the CSV file. The LoadDataToDatabase() is a method that accepts three (3) parameters which are the tableName, fileFullPath and delimeter value. This method is where the actual saving or importing of data from CSV to SQL server happend. The codes at BTNImport_Click event handles the uploading of CSV file to the specified location and at the same time this is where the CreateDatabaseTable() and LoadDataToDatabase() are being called. If you notice I also added some basic trappings and validations within that event. Now to test the importing utility then let's create a simple data in a CSV format. Just for the simplicity of this demo let's create a CSV file and name it as "Employee" and add some data on it. Here's an example below: 1,VMS,Durano,[email protected] 2,Jennifer,Cortes,[email protected] 3,Xhaiden,Durano,[email protected] 4,Angel,Santos,[email protected] 5,Kier,Binks,[email protected] 6,Erika,Bird,[email protected] 7,Vianne,Durano,[email protected] 8,Lilibeth,Tree,[email protected] 9,Bon,Bolger,[email protected] 10,Brian,Jones,[email protected] Now save the newly created CSV file in some location in your hard drive. Okay let's run the application and browse the CSV file that we have just created. Take a look at the sample screen shots below: After browsing the CSV file. After clicking the Import Button Now if we look at the database that we have created earlier you'll notice that the Employee table is created with the imported data on it. See below screen shot.   That's it! I hope someone find this post useful! Technorati Tags: ASP.NET,CSV,SQL,C#,ADO.NET

    Read the article

  • AuthResend query string being appended to URL

    - by Alastair Pitts
    One of our clients is having an issue where POSTBACK seems to be broken when they connect to our Sharepoint application. When they navigate to a URL, an erroneous query string gets appended to the URL, so the end of the URL becomes: .../default.aspx&AuthResend1908BC2350124b5095AB75012FA405BA this isn't something that appears on any other clients computers or ours internally. This is the only difference and it seems to be breaking their pages. I had a quick Google and it seems that it's to do with a Microsoft ISA server, but I have no experience with that. Is this a bug or setting on their ISA server?

    Read the article

  • Using a redirect of any form to remove a query string with Apache

    - by Bart B
    Because of the silly way iTunes works the only way to update the URL for a feed is by setting up a permanent redirect from the old feed to the new. This seems easy, but I've hit a snag. The old URL ended in /?feed=rss2, the new URL is just a file, so it ends in podcast.xml. When I redirected from the old URL to the new, iTunes picked up the new URL BUT, WITH the query string, so now the URL ends in podcast.xml?feed=rss2. This is allowing listers to download the show - which is good, but causing some other problems. Is there any possible way to set up a permanent redirect that will redired podcast.xml?feed=rss2 to just podcast.xml? Mod_Rewrite seems to just pass through query strings, so I'm at a loss! Bart.

    Read the article

  • Pass quoted argument string to Start-Process in PowerShell

    - by Luke Puplett
    Hello I'm trying to very simply run an executable and pass a file path in as the first argument. In DOS, this would be the command: import.exe "C:\Some Path\With\Spaces.txt" By placing the path in quotes, the path is correctly parsed as the first token into the executable. In PowerShell I'm using this: $feeds = dir 'T:\Documents\Company\Product Development\Data foreach ($feed in $feeds) { start -FilePath import.exe -ArgumentList $feed.FullName } The problem with the Start-Process cmdlet in PowerShell is that it uses a string array for arguments, so the path is broken up and sent to the executable as separate tokens. Quotes in PowerShell force $feed.FullName to be treated literally. Double quotes "" make PowerShell not see anything in the argument list. "The argument is null or empty." it tells me. I expect that this is a known headache and has had a known workaround from day one. Thanks Luke

    Read the article

  • iptables: How to read this OPT string?

    - by alex
    I have a simple INPUT rule for iptables that logs any new connections to a logfile. --log-tcp-options and --log-ip-options flags are both set and I get the appropriate OPT output. One line of my log looks something like this: Nov 29 17:00:00 IN=venet0 OUT= MAC= SRC=x.x.x.x DST=x.x.x.x LEN=64 TOS=0x00 PREC=0x00 TTL=53 ID=37898 DF PROTO=TCP SPT=57755 DPT=8888 WINDOW=65535 RES=0x00 SYN URGP=0 OPT (0204057D010303010101080A3E521D4D0000000004020000) I would like to understand how to interpret the OPT string (bold). Is there some documentation available on what it actually means? How could I make it human-readable?

    Read the article

  • CMD Echo date but show month as string

    - by Asim Rehman
    I am using the robocopy command to create a backup system, I have successfully managed to copy the folders, but the date stamp is wrong. The folders are prefixed with the date and time . The robocopy command is this: robocopy U:\Data\ X:\Private\Backups\FolderName_%date:/=-%-(%time::=-%) /e The out of the folder is displayed like this: FolderName_09-11-2013-(20-24-06.60) The only thing I want to change is the date, I want to show the month as a string with only the first 3 characters like Oct. Can someone please guide me. Thanks.

    Read the article

  • Search for index.php and index.html and replace string

    - by Jonas
    Hello. I recently had some sort of Malware on my computer that added to all index.php and index.html ON THE WEBSERVER! the following string(s): echo "<iframe src=\"http://fabujob.com/?click=AD4A4\" width=1 height=1 style=\"visibility:hidden;position:absolute\"></iframe>"; echo "<iframe src=\"http://fabujob.com/?click=AC785\" width=1 height=1 style=\"visibility:hidden;position:absolute\"></iframe>"; So the parameter after "click=" always changes. These two were only examples. Is there a way to do that quick and fast? . . EDIT: It is on my webserver, so no use of find...

    Read the article

  • How to write simple code using TDD [migrated]

    - by adeel41
    Me and my colleagues do a small TDD-Kata practice everyday for 30 minutes. For reference this is the link for the excercise http://osherove.com/tdd-kata-1/ The objective is to write better code using TDD. This is my code which I've written public class Calculator { public int Add( string numbers ) { const string commaSeparator = ","; int result = 0; if ( !String.IsNullOrEmpty( numbers ) ) result = numbers.Contains( commaSeparator ) ? AddMultipleNumbers( GetNumbers( commaSeparator, numbers ) ) : ConvertToNumber( numbers ); return result; } private int AddMultipleNumbers( IEnumerable getNumbers ) { return getNumbers.Sum(); } private IEnumerable GetNumbers( string separator, string numbers ) { var allNumbers = numbers .Replace( "\n", separator ) .Split( new string[] { separator }, StringSplitOptions.RemoveEmptyEntries ); return allNumbers.Select( ConvertToNumber ); } private int ConvertToNumber( string number ) { return Convert.ToInt32( number ); } } and the tests for this class are [TestFixture] public class CalculatorTests { private int ArrangeAct( string numbers ) { var calculator = new Calculator(); return calculator.Add( numbers ); } [Test] public void Add_WhenEmptyString_Returns0() { Assert.AreEqual( 0, ArrangeAct( String.Empty ) ); } [Test] [Sequential] public void Add_When1Number_ReturnNumber( [Values( "1", "56" )] string number, [Values( 1, 56 )] int expected ) { Assert.AreEqual( expected, ArrangeAct( number ) ); } [Test] public void Add_When2Numbers_AddThem() { Assert.AreEqual( 3, ArrangeAct( "1,2" ) ); } [Test] public void Add_WhenMoreThan2Numbers_AddThemAll() { Assert.AreEqual( 6, ArrangeAct( "1,2,3" ) ); } [Test] public void Add_SeparatorIsNewLine_AddThem() { Assert.AreEqual( 6, ArrangeAct( @"1 2,3" ) ); } } Now I'll paste code which they have written public class StringCalculator { private const char Separator = ','; public int Add( string numbers ) { const int defaultValue = 0; if ( ShouldReturnDefaultValue( numbers ) ) return defaultValue; return ConvertNumbers( numbers ); } private int ConvertNumbers( string numbers ) { var numberParts = GetNumberParts( numbers ); return numberParts.Select( ConvertSingleNumber ).Sum(); } private string[] GetNumberParts( string numbers ) { return numbers.Split( Separator ); } private int ConvertSingleNumber( string numbers ) { return Convert.ToInt32( numbers ); } private bool ShouldReturnDefaultValue( string numbers ) { return String.IsNullOrEmpty( numbers ); } } and the tests [TestFixture] public class StringCalculatorTests { [Test] public void Add_EmptyString_Returns0() { ArrangeActAndAssert( String.Empty, 0 ); } [Test] [TestCase( "1", 1 )] [TestCase( "2", 2 )] public void Add_WithOneNumber_ReturnsThatNumber( string numberText, int expected ) { ArrangeActAndAssert( numberText, expected ); } [Test] [TestCase( "1,2", 3 )] [TestCase( "3,4", 7 )] public void Add_WithTwoNumbers_ReturnsSum( string numbers, int expected ) { ArrangeActAndAssert( numbers, expected ); } [Test] public void Add_WithThreeNumbers_ReturnsSum() { ArrangeActAndAssert( "1,2,3", 6 ); } private void ArrangeActAndAssert( string numbers, int expected ) { var calculator = new StringCalculator(); var result = calculator.Add( numbers ); Assert.AreEqual( expected, result ); } } Now the question is which one is better? My point here is that we do not need so many small methods initially because StringCalculator has no sub classes and secondly the code itself is so simple that we don't need to break it up too much that it gets confusing after having so many small methods. Their point is that code should read like english and also its better if they can break it up earlier than doing refactoring later and third when they will do refactoring it would be much easier to move these methods quite easily into separate classes. My point of view against is that we never made a decision that code is difficult to understand so why we are breaking it up so early. So I need a third person's opinion to understand which option is much better.

    Read the article

  • iptables drop packet by hex string match

    - by Flint
    I got this packet captured with tcpdump but I'm not sure how to use the --hex-string param to match the packet. Can someone show me how to do it? 11:18:26.614537 IP (tos 0x0, ttl 17, id 19245, offset 0, flags [DF], proto UDP (17), length 37) x.x.187.207.1234 > x.x.152.202.6543: [no cksum] UDP, length 9 0x0000: f46d 0425 b202 000a b853 22cc 0800 4500 .m.%.....S"...E. 0x0010: 0025 4b2d 4000 1111 0442 5ebe bbcf 6701 .%[email protected]^...g. 0x0020: 98ca 697d 6989 0011 0000 ffff ffff 5630 ..i}i.........V0 0x0030: 3230 3300 0000 0000 0000 0000 203.........

    Read the article

< Previous Page | 123 124 125 126 127 128 129 130 131 132 133 134  | Next Page >