Search Results

Search found 549 results on 22 pages for 'stderr'.

Page 18/22 | < Previous Page | 14 15 16 17 18 19 20 21 22  | Next Page >

  • Problem when trying to connect to a desktop server from android on wifi

    - by thiagolee
    Hello, I am trying to send a file from the phone running Android 1.5 to a server on a desktop. I wrote some code, which works on emulator, but on the phone it doesn't. I'm connecting to the network through WiFi. It works, I can access the internet through my phone and I've configured my router. The application stops when I'm trying to connect. I have the permissions. Someone have any ideas, below is my code. Running on Android package br.ufs.reconhecimento; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.Socket; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.ImageButton; /** * Sample code that invokes the speech recognition intent API. */ public class Reconhecimento extends Activity implements OnClickListener { static final int VOICE_RECOGNITION_REQUEST_CODE = 1234; static final String LOG_VOZ = "UFS-Reconhecimento"; final int INICIAR_GRAVACAO = 01; int porta = 5158; // Porta definida no servidor int tempoEspera = 1000; String ipConexao = "172.20.0.189"; EditText ipEdit; /** * Called with the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Inflate our UI from its XML layout description. setContentView(R.layout.main); // Get display items for later interaction ImageButton speakButton = (ImageButton) findViewById(R.id.btn_speak); speakButton.setPadding(10, 10, 10, 10); speakButton.setOnClickListener(this); //Alerta para o endereço IP AlertDialog.Builder alerta = new AlertDialog.Builder(this); alerta.setTitle("IP");//+mainWifi.getWifiState()); ipEdit = new EditText(this); ipEdit.setText(ipConexao); alerta.setView(ipEdit); alerta.setMessage("Por favor, Confirme o endereço IP."); alerta.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { ipConexao = ipEdit.getText().toString(); Log.d(LOG_VOZ, "Nova Atribuição do Endreço IP: " + ipConexao); } }); alerta.create(); alerta.show(); } /** * Handle the click on the start recognition button. */ public void onClick(View v) { if (v.getId() == R.id.btn_speak) { //startVoiceRecognitionActivity(); Log.d(LOG_VOZ, "Iniciando a próxima tela"); Intent recordIntent = new Intent(this, GravacaoAtivity.class); Log.d(LOG_VOZ, "Iniciando a tela (instancia criada)"); startActivityForResult(recordIntent, INICIAR_GRAVACAO); Log.d(LOG_VOZ, "Gravação iniciada ..."); } } /** * Handle the results from the recognition activity. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(LOG_VOZ, "Iniciando onActivityResult()"); if (requestCode == INICIAR_GRAVACAO && resultCode == RESULT_OK) { String path = data.getStringExtra(GravacaoAtivity.RETORNO); conexaoSocket(path); } else Log.e(LOG_VOZ, "Resultado Inexperado ..."); } private void conexaoSocket(String path) { Socket socket = SocketOpener.openSocket(ipConexao, porta, tempoEspera); if(socket == null) return; try { DataOutputStream conexao = new DataOutputStream(socket.getOutputStream()); Log.d(LOG_VOZ, "Acessando arquivo ..."); File file = new File(path); DataInputStream arquivo = new DataInputStream(new FileInputStream(file)); Log.d(LOG_VOZ, "Iniciando Transmissão ..."); conexao.writeLong(file.length()); for(int i = 0; i < file.length(); i++) conexao.writeByte(arquivo.readByte()); Log.d(LOG_VOZ, "Transmissão realizada com sucesso..."); Log.d(LOG_VOZ, "Fechando a conexão..."); conexao.close(); socket.close(); Log.d(LOG_VOZ, "============ Processo finalizado com Sucesso =============="); } catch (IOException e) { Log.e(LOG_VOZ, "Erro ao fazer a conexão via Socket. " + e.getMessage()); // TODO Auto-generated catch block } } } class SocketOpener implements Runnable { private String host; private int porta; private Socket socket; public SocketOpener(String host, int porta) { this.host = host; this.porta = porta; socket = null; } public static Socket openSocket(String host, int porta, int timeOut) { SocketOpener opener = new SocketOpener(host, porta); Thread t = new Thread(opener); t.start(); try { t.join(timeOut); } catch(InterruptedException e) { Log.e(Reconhecimento.LOG_VOZ, "Erro ao fazer o join da thread do socket. " + e.getMessage()); //TODO: Mensagem informativa return null; } return opener.getSocket(); } public void run() { try { socket = new Socket(host, porta); }catch(IOException e) { Log.e(Reconhecimento.LOG_VOZ, "Erro na criação do socket. " + e.getMessage()); //TODO: Mensagem informativa } } public Socket getSocket() { return socket; } } Running on the desktop Java: import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class ServidorArquivo { private static int porta = 5158; static String ARQUIVO = "voz.amr"; /** * Caminho que será gravado o arquivo de audio */ static String PATH = "/home/iade/Trabalho/lib/"; public static void main(String[] args) { int i = 1; try { System.out.println("Iniciando o Servidor Socket - Android."); ServerSocket s = new ServerSocket(porta); System.out.println("Servidor Iniciado com Sucesso..."); System.out.println("Aguardando conexões na porta: " + porta); while(true) { Socket recebendo = s.accept(); System.out.println("Aceitando conexão de nº " + i); new ThreadedHandler(recebendo).start(); i++; } } catch (Exception e) { System.out.println("Erro: " + e.getMessage()); e.printStackTrace(); } } } class ThreadedHandler extends Thread { private Socket socket; public ThreadedHandler(Socket so) { socket = so; } public void run() { DataInputStream entrada = null; DataOutputStream arquivo = null; try { entrada = new DataInputStream(socket.getInputStream()); System.out.println("========== Iniciando a leitura dos dados via Sockets =========="); long tamanho = entrada.readLong(); System.out.println("Tamanho do vetor " + tamanho); File file = new File(ServidorArquivo.PATH + ServidorArquivo.ARQUIVO); if(!file.exists()) file.createNewFile(); arquivo = new DataOutputStream(new FileOutputStream(file)); for(int j = 0; j < tamanho; j++) { arquivo.write(entrada.readByte()); } System.out.println("========== Dados recebidos com sucesso =========="); } catch (Exception e) { System.out.println("Erro ao tratar do socket: " + e.getMessage()); e.printStackTrace(); } finally { System.out.println("**** Fechando as conexões ****"); try { entrada.close(); socket.close(); arquivo.close(); } catch (IOException e) { System.out.println("Erro ao fechar conex&#65533;es " + e.getMessage()); e.printStackTrace(); } } System.out.println("============= Fim da Gravação ==========="); // tratar o arquivo String cmd1 = "ffmpeg -i voz.amr -ab 12288 -ar 16000 voz.wav"; String cmd2 = "soundstretch voz.wav voz2.wav -tempo=100"; String dir = "/home/iade/Trabalho/lib"; File workDir = new File(dir); File f1 = new File(dir+"/voz.wav"); File f2 = new File(dir+"/voz2.wav"); f1.delete(); f2.delete(); try { executeCommand(cmd1, workDir); System.out.println("realizou cmd1"); executeCommand(cmd2, workDir); System.out.println("realizou cmd2"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void executeCommand(String cmd1, File workDir) throws IOException, InterruptedException { String s; Process p = Runtime.getRuntime().exec(cmd1,null,workDir); int i = p.waitFor(); if (i == 0) { BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); // read the output from the command while ((s = stdInput.readLine()) != null) { System.out.println(s); } } else { BufferedReader stdErr = new BufferedReader(new InputStreamReader(p.getErrorStream())); // read the output from the command while ((s = stdErr.readLine()) != null) { System.out.println(s); } } } } Thanks in advance.

    Read the article

  • getaddrinfo appears to return different results between Windows and Ubuntu?

    - by MrDuk
    I have the following two sets of code: Windows #undef UNICODE #include <winsock2.h> #include <ws2tcpip.h> #include <stdio.h> // link with Ws2_32.lib #pragma comment (lib, "Ws2_32.lib") int __cdecl main(int argc, char **argv) { //----------------------------------------- // Declare and initialize variables WSADATA wsaData; int iResult; INT iRetval; DWORD dwRetval; argv[1] = "www.google.com"; argv[2] = "80"; int i = 1; struct addrinfo *result = NULL; struct addrinfo *ptr = NULL; struct addrinfo hints; struct sockaddr_in *sockaddr_ipv4; // struct sockaddr_in6 *sockaddr_ipv6; LPSOCKADDR sockaddr_ip; char ipstringbuffer[46]; DWORD ipbufferlength = 46; /* // Validate the parameters if (argc != 3) { printf("usage: %s <hostname> <servicename>\n", argv[0]); printf("getaddrinfo provides protocol-independent translation\n"); printf(" from an ANSI host name to an IP address\n"); printf("%s example usage\n", argv[0]); printf(" %s www.contoso.com 0\n", argv[0]); return 1; } */ // Initialize Winsock iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { printf("WSAStartup failed: %d\n", iResult); return 1; } //-------------------------------- // Setup the hints address info structure // which is passed to the getaddrinfo() function ZeroMemory( &hints, sizeof(hints) ); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; // hints.ai_protocol = IPPROTO_TCP; printf("Calling getaddrinfo with following parameters:\n"); printf("\tnodename = %s\n", argv[1]); printf("\tservname (or port) = %s\n\n", argv[2]); //-------------------------------- // Call getaddrinfo(). If the call succeeds, // the result variable will hold a linked list // of addrinfo structures containing response // information dwRetval = getaddrinfo(argv[1], argv[2], &hints, &result); if ( dwRetval != 0 ) { printf("getaddrinfo failed with error: %d\n", dwRetval); WSACleanup(); return 1; } printf("getaddrinfo returned success\n"); // Retrieve each address and print out the hex bytes for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) { printf("getaddrinfo response %d\n", i++); printf("\tFlags: 0x%x\n", ptr->ai_flags); printf("\tFamily: "); switch (ptr->ai_family) { case AF_UNSPEC: printf("Unspecified\n"); break; case AF_INET: printf("AF_INET (IPv4)\n"); sockaddr_ipv4 = (struct sockaddr_in *) ptr->ai_addr; printf("\tIPv4 address %s\n", inet_ntoa(sockaddr_ipv4->sin_addr) ); break; case AF_INET6: printf("AF_INET6 (IPv6)\n"); // the InetNtop function is available on Windows Vista and later // sockaddr_ipv6 = (struct sockaddr_in6 *) ptr->ai_addr; // printf("\tIPv6 address %s\n", // InetNtop(AF_INET6, &sockaddr_ipv6->sin6_addr, ipstringbuffer, 46) ); // We use WSAAddressToString since it is supported on Windows XP and later sockaddr_ip = (LPSOCKADDR) ptr->ai_addr; // The buffer length is changed by each call to WSAAddresstoString // So we need to set it for each iteration through the loop for safety ipbufferlength = 46; iRetval = WSAAddressToString(sockaddr_ip, (DWORD) ptr->ai_addrlen, NULL, ipstringbuffer, &ipbufferlength ); if (iRetval) printf("WSAAddressToString failed with %u\n", WSAGetLastError() ); else printf("\tIPv6 address %s\n", ipstringbuffer); break; case AF_NETBIOS: printf("AF_NETBIOS (NetBIOS)\n"); break; default: printf("Other %ld\n", ptr->ai_family); break; } printf("\tSocket type: "); switch (ptr->ai_socktype) { case 0: printf("Unspecified\n"); break; case SOCK_STREAM: printf("SOCK_STREAM (stream)\n"); break; case SOCK_DGRAM: printf("SOCK_DGRAM (datagram) \n"); break; case SOCK_RAW: printf("SOCK_RAW (raw) \n"); break; case SOCK_RDM: printf("SOCK_RDM (reliable message datagram)\n"); break; case SOCK_SEQPACKET: printf("SOCK_SEQPACKET (pseudo-stream packet)\n"); break; default: printf("Other %ld\n", ptr->ai_socktype); break; } printf("\tProtocol: "); switch (ptr->ai_protocol) { case 0: printf("Unspecified\n"); break; case IPPROTO_TCP: printf("IPPROTO_TCP (TCP)\n"); break; case IPPROTO_UDP: printf("IPPROTO_UDP (UDP) \n"); break; default: printf("Other %ld\n", ptr->ai_protocol); break; } printf("\tLength of this sockaddr: %d\n", ptr->ai_addrlen); printf("\tCanonical name: %s\n", ptr->ai_canonname); } freeaddrinfo(result); WSACleanup(); return 0; } Ubuntu /* ** listener.c -- a datagram sockets "server" demo */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #define MYPORT "4950" // the port users will be connecting to #define MAXBUFLEN 100 // get sockaddr, IPv4 or IPv6: void *get_in_addr(struct sockaddr *sa) { if (sa->sa_family == AF_INET) { return &(((struct sockaddr_in*)sa)->sin_addr); } return &(((struct sockaddr_in6*)sa)->sin6_addr); } int main(void) { int sockfd; struct addrinfo hints, *servinfo, *p; int rv; int numbytes; struct sockaddr_storage their_addr; char buf[MAXBUFLEN]; socklen_t addr_len; char s[INET6_ADDRSTRLEN]; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; // set to AF_INET to force IPv4 hints.ai_socktype = SOCK_DGRAM; hints.ai_flags = AI_PASSIVE; // use my IP if ((rv = getaddrinfo(NULL, MYPORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } // loop through all the results and bind to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("listener: socket"); continue; } if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("listener: bind"); continue; } break; } if (p == NULL) { fprintf(stderr, "listener: failed to bind socket\n"); return 2; } freeaddrinfo(servinfo); printf("listener: waiting to recvfrom...\n"); addr_len = sizeof their_addr; if ((numbytes = recvfrom(sockfd, buf, MAXBUFLEN-1 , 0, (struct sockaddr *)&their_addr, &addr_len)) == -1) { perror("recvfrom"); exit(1); } printf("listener: got packet from %s\n", inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof s)); printf("listener: packet is %d bytes long\n", numbytes); buf[numbytes] = '\0'; printf("listener: packet contains \"%s\"\n", buf); close(sockfd); return 0; } When I attempt www.google.com, I don't get the ipv6 socket returned on Windows - why is this? Outputs: (ubuntu) caleb@ub1:~/Documents/dev/cs438/mp0/MP0$ ./a.out www.google.com IP addresses for www.google.com: IPv4: 74.125.228.115 IPv4: 74.125.228.116 IPv4: 74.125.228.112 IPv4: 74.125.228.113 IPv4: 74.125.228.114 IPv6: 2607:f8b0:4004:803::1010 Outputs: (win) Calling getaddrinfo with following parameters: nodename = www.google.com servname (or port) = 80 getaddrinfo returned success getaddrinfo response 1 Flags: 0x0 Family: AF_INET (IPv4) IPv4 address 74.125.228.114 Socket type: SOCK_STREAM (stream) Protocol: Unspecified Length of this sockaddr: 16 Canonical name: (null) getaddrinfo response 2 Flags: 0x0 Family: AF_INET (IPv4) IPv4 address 74.125.228.115 Socket type: SOCK_STREAM (stream) Protocol: Unspecified Length of this sockaddr: 16 Canonical name: (null) getaddrinfo response 3 Flags: 0x0 Family: AF_INET (IPv4) IPv4 address 74.125.228.116 Socket type: SOCK_STREAM (stream) Protocol: Unspecified Length of this sockaddr: 16 Canonical name: (null) getaddrinfo response 4 Flags: 0x0 Family: AF_INET (IPv4) IPv4 address 74.125.228.112 Socket type: SOCK_STREAM (stream) Protocol: Unspecified Length of this sockaddr: 16 Canonical name: (null) getaddrinfo response 5 Flags: 0x0 Family: AF_INET (IPv4) IPv4 address 74.125.228.113 Socket type: SOCK_STREAM (stream) Protocol: Unspecified Length of this sockaddr: 16 Canonical name: (null)

    Read the article

  • wxPython - ListCrtl and SQLite3

    - by Dunwitch
    I'm trying to get a SQLite3 DB to populate a wx.ListCrtl. I can get it to print to stdout/stderr without any problem. I just can't seem to figure out how to display the data in the DataWindow/DataList? I'm sure I've made some code mistakes, so any help is appreciated. Main.py import wx import wx.lib.mixins.listctrl as listmix from database import * import sys class DataWindow(wx.Frame): def __init__(self, parent = None): wx.Frame.__init__(self, parent, -1, 'DataList', size=(640,480)) self.win = DataList(self) self.Center() self.Show(True) class DataList(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.ColumnSorterMixin): def __init__(self, parent = DataWindow): wx.ListCtrl.__init__( self, parent, -1, style=wx.LC_REPORT|wx.LC_VIRTUAL|wx.LC_HRULES|wx.LC_VRULES) #building the columns self.InsertColumn(0, "Location") self.InsertColumn(1, "Address") self.InsertColumn(2, "Subnet") self.InsertColumn(3, "Gateway") self.SetColumnWidth(0, 100) self.SetColumnWidth(1, 150) self.SetColumnWidth(2, 150) self.SetColumnWidth(3, 150) class MainWindow(wx.Frame): def __init__(self, parent = None, id = -1, title = "MainWindow"): wx.Frame.__init__(self, parent, id, title, size = (800,600), style = wx.DEFAULT_FRAME_STYLE ^ (wx.RESIZE_BORDER)) # StatusBar self.CreateStatusBar() # Filemenu filemenu = wx.Menu() # Filemenu - About menuitem = filemenu.Append(-1, "&About", "Information about this application") self.Bind(wx.EVT_MENU, self.onAbout, menuitem) #Filemenu - Data menuitem = filemenu.Append(-1, "&Data", "Get data") self.Bind(wx.EVT_MENU, self.onData, menuitem) # Filemenu - Seperator filemenu.AppendSeparator() #Filemenu - Exit menuitem = filemenu.Append(-1, "&Exit", "Exit the application") self.Bind(wx.EVT_MENU, self.onExit, menuitem) # Menubar menubar = wx.MenuBar() menubar.Append(filemenu, "&File") self.SetMenuBar(menubar) # Show self.Show(True) self.Center() def onAbout(self, event): pass def onData(self, event): DataWindow(self) callDb = Database() sql = "SELECT rowid, address, subnet, gateway FROM pod1" records = callDb.select(sql) for v in records: print "How do I get the records on the DataList?" #print "%s%s%s" % (v[1],v[2],v[3]) #for v in records: #DataList.InsertStringItem("%s") % (v[0], v[1], v[2]) def onExit(self, event): self.Close() self.Destroy() def onSave(self, event): pass if __name__ == '__main__': app = wx.App() frame = MainWindow(None, -1) frame.Show() app.MainLoop() database.py import os import sqlite3 class Database(object): def __init__(self, db_file="data/data.sqlite"): database_allready_exists = os.path.exists(db_file) self.db = sqlite3.connect(db_file) if not database_allready_exists: self.setupDefaultData() def select(self,sql): cursor = self.db.cursor() cursor.execute(sql) records = cursor.fetchall() cursor.close return records def insert(self,sql): newID = 0 cursor = self.db.cursor() cursor.execute(sql) newID = cursor.lastrowid self.db.commit() cursor.close() return newID def save(self,sql): cursor = self.db.cursor() cursor.execute(sql) self.db.commit() cursor.close() def setupDefaultData(self): pass

    Read the article

  • How can i use a commandlinetool (ie. sox) via subprocess.Popen with mod_wsgi?

    - by marue
    I have a custom django filefield that makes use of sox, a commandline audiotool. This works pretty well as long as i use the django development server. But as soon as i switch to the production server, using apache2 and mod_wsgi, mod_wsgi catches every output to stdout. This makes it impossible to use the commandline tool to evaluate the file, for example use it to check if the uploaded file really is an audio file like this: filetype=subprocess.Popen([sox,'--i','-t','%s'%self.path], shell=False,\ stdout=subprocess.PIPE, stderr=subprocess.PIPE) (filetype,error)=filetype.communicate() if error: raise EnvironmentError((1,'AudioFile error while determining audioformat: %s'%error)) Is there a way to workaround for this? edit the error i get is "missing filename". I am using mod_wsgi 2.5, standard with ubuntu 8.04. edit2 What exactly happens, when i call subprocess.Popen from within django in mod_wsgi? Shouldn't subprocess stdin/stdout be independent from django stdin/stdout? In that case mod_wsgi should not affect programms called via subprocess... I'm really confused right now, because the file i am trying to access is a temporary file, created via a filenamevariable that i pass to the file creation and the subprocess command. That file is being written to /tmp, where the rights are 777, so it can't be a rights issue. And the error message is not "file does not exist", but "missing filename", which suggests i am not passing a filename as parameter to the commandlinetool.

    Read the article

  • Accessing global variable in multithreaded Tomcat server

    - by jwegan
    I have a singleton object that I construct like thus: private static volatile KeyMapper mapper = null; public static KeyMapper getMapper() { if(mapper == null) { synchronized(Utils.class) { if(mapper == null) { mapper = new LocalMemoryMapper(); } } } return mapper; } The class KeyMapper is basically a synchronized wrapper to HashMap with only two functions, one to add a mapping and one to remove a mapping. When running in Tomcat 6.24 on my 32bit Windows machine everything works fine. However when running on a 64 bit Linux machine (CentOS 5.4 with OpenJDK 1.6.0-b09) I add one mapping and print out the size of the HashMap used by KeyMapper to verify the mapping got added (i.e. verify size = 1). Then I try to retrieve the mapping with another request and I keep getting null and when I checked the size of the HashMap it was 0. I'm confident the mapping isn't accidentally being removed since I've commented out all calls to remove (and I don't use clear or any other mutators, just get and put). The requests are going through Tomcat 6.24 (configured to use 200 threads with a minimum of 4 threads) and I passed -Xnoclassgc to the jvm to ensure the class isn't inadvertently getting garbage collected (jvm is also running in -server mode). I also added a finalize method to KeyMapper to print to stderr if it ever gets garbage collected to verify that it wasn't being garbage collected. I'm at my wits end and I can't figure out why one minute the entry in HashMap is there and the next it isn't :(

    Read the article

  • Django install on a shared host, .htaccess help

    - by redconservatory
    I am trying to install Django on a shared host using the following instructions: docs.google.com/View?docid=dhhpr5xs_463522g My problem is with the following line on my root .htaccess: RewriteRule ^(.*)$ /cgi-bin/wcgi.py/$1 [QSA,L] When I include this line I get a 500 error with almost all of my domains on this account. My cgi-bin directory is home/my-username/public_html/cgi-bin/ The wcgi.py file contains: #!/usr/local/bin/python import os, sys sys.path.insert(0, "/home/username/django/") sys.path.insert(0, "/home/username/django/projects") sys.path.insert(0, "/home/username/django/projects/newprojects") import django.core.handlers.wsgi os.chdir("/home/username/django/projects/newproject") # optional os.environ['DJANGO_SETTINGS_MODULE'] = "newproject.settings" def runcgi(): environ = dict(os.environ.items()) environ['wsgi.input'] = sys.stdin environ['wsgi.errors'] = sys.stderr environ['wsgi.version'] = (1,0) environ['wsgi.multithread'] = False environ['wsgi.multiprocess'] = True environ['wsgi.run_once'] = True application = django.core.handlers.wsgi.WSGIHandler() if environ.get('HTTPS','off') in ('on','1'): environ['wsgi.url_scheme'] = 'https' else: environ['wsgi.url_scheme'] = 'http' headers_set = [] headers_sent = [] def write(data): if not headers_set: raise AssertionError("write() before start_response()") elif not headers_sent: # Before the first output, send the stored headers status, response_headers = headers_sent[:] = headers_set sys.stdout.write('Status: %s\r\n' % status) for header in response_headers: sys.stdout.write('%s: %s\r\n' % header) sys.stdout.write('\r\n') sys.stdout.write(data) sys.stdout.flush() def start_response(status,response_headers,exc_info=None): if exc_info: try: if headers_sent: # Re-raise original exception if headers sent raise exc_info[0], exc_info[1], exc_info[2] finally: exc_info = None # avoid dangling circular ref elif headers_set: raise AssertionError("Headers already set!") headers_set[:] = [status,response_headers] return write result = application(environ, start_response) try: for data in result: if data: # don't send headers until body appears write(data) if not headers_sent: write('') # send headers now if body was empty finally: if hasattr(result,'close'): result.close() runcgi() Only I changed the "username" to my username...

    Read the article

  • C Programing - Return libcurl http response to string to the calling function

    - by empty set
    I have a homework and i need somehow to compare two http responses. I am writing it on C (dumb decision) and i use libcurl to make things easier. I am calling the function that uses libcurl to http request and response from another function and i want to return the http response to it. Anyway, the code below doesn't work, any ideas? #include <stdio.h> #include <curl/curl.h> #include <string.h> size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream) { size_t written; written = fwrite(ptr, size, nmemb, stream); return written; } char *handle_url(void) { CURL *curl; char *fp; CURLcode res; char *url = "http://www.yahoo.com"; curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); res = curl_easy_perform(curl); if(res != CURLE_OK) fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); curl_easy_cleanup(curl); //printf("\n%s", fp); } return fp; } This solution C libcurl get output into a string works, but not in my case because i want to return this string to the calling function.

    Read the article

  • I am not able to kill a child process using TerminateProcess

    - by user1681210
    I have a problem to kill a child process using TerminateProcess. I call to this function and the process still there (in the Task Manager) This piece of code is called many times launching the same program.exe many times and these process are there in the task manager which i think is not good. sorry, I am quiet new in c++ I will really appreciate any help. thanks a lot!! the code is the following: STARTUPINFO childProcStartupInfo; memset( &childProcStartupInfo, 0, sizeof(childProcStartupInfo)); childProcStartupInfo.cb = sizeof(childProcStartupInfo); childProcStartupInfo.hStdInput = hFromParent; // stdin childProcStartupInfo.hStdOutput = hToParent; // stdout childProcStartupInfo.hStdError = hToParentDup; // stderr childProcStartupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; childProcStartupInfo.wShowWindow = SW_HIDE; PROCESS_INFORMATION childProcInfo; /* for CreateProcess call */ bOk = CreateProcess( NULL, // filename pCmdLine, // full command line for child NULL, // process security descriptor */ NULL, // thread security descriptor */ TRUE, // inherit handles? Also use if STARTF_USESTDHANDLES */ 0, // creation flags */ NULL, // inherited environment address */ NULL, // startup dir; NULL = start in current */ &childProcStartupInfo, // pointer to startup info (input) */ &childProcInfo); // pointer to process info (output) */ CloseHandle( hFromParent ); CloseHandle( hToParent ); CloseHandle( hToParentDup ); CloseHandle( childProcInfo.hThread); CloseHandle( childProcInfo.hProcess); TerminateProcess( childProcInfo.hProcess ,0); //this is not working, the process thanks

    Read the article

  • python on apache - getting 404

    - by Kirby
    I edited this question after i found a solution... i need to understand why the solution worked instead of my method? This is likely to be a silly question. I tried searching other questions that are related... but to no avail. i am running Apache/2.2.11 (Ubuntu) DAV/2 SVN/1.5.4 PHP/5.2.6-3ubuntu4.5 with Suhosin-Patch mod_python/3.3.1 Python/2.6.2 i have a script called test.py #! /usr/bin/python print "Content-Type: text/html" # HTML is following print # blank line, end of headers print "hello world" running it as an executable works... /var/www$ ./test.py Content-Type: text/html hello world when i run http://localhost/test.py i get a 404 error. What am i missing? i used this resource to enable python parsing on apache. http://ubuntuforums.org/showthread.php?t=91101 From that same thread... the following code worked.. why? #!/usr/bin/python import sys import time def index(req): # Following line causes error to be sent to browser # rather than to log file (great for debug!) sys.stderr = sys.stdout #print "Content-type: text/html\n" #print """ blah1 = """<html> <head><title>A page from Python</title></head> <body> <h4>This page is generated by a Python script!</h4> The current date and time is """ now = time.gmtime() displaytime = time.strftime("%A %d %B %Y, %X",now) #print displaytime, blah1 += displaytime #print """ blah1 += """ <hr> Well House Consultants demonstration </body> </html> """ return blah1

    Read the article

  • Piping EOF problems with stdio and C++/Python

    - by yeus
    I got some problems with EOF and stdio. I have no idea what I am doing wrong. When I see an EOF in my program I clear the stdin and next round I try to read in a new line. The problem is: for some reason the getline function immediatly (from the second run always, the first works just as intended) returns an EOF instead of waiting for a new input from py python process... Any idea? alright Here is the code: #include <string> #include <iostream> #include <iomanip> #include <limits> using namespace std; int main(int argc, char **argv) { for (;;) { string buf; if (getline(cin,buf)) { if (buf=="q") break; /*****///do some stuff with input //my actual filter program cout<<buf; /*****/ } else { if ((cin.rdstate() & istream::eofbit)!=0)cout<<"eofbit"<<endl; if ((cin.rdstate() & istream::failbit)!=0)cout<<"failbit"<<endl; if ((cin.rdstate() & istream::badbit)!=0)cout<<"badbit"<<endl; if ((cin.rdstate() & istream::goodbit)!=0)cout<<"goodbit"<<endl; cin.clear(); cin.ignore(numeric_limits<streamsize>::max()); //break;//I am not using break, because I //want more input when the parent //process puts data into stdin; } } return 0; } and in python: from subprocess import Popen, PIPE import os from time import sleep proc=Popen(os.getcwd()+"/Pipingtest",stdout=PIPE,stdin=PIPE,stderr=PIPE); while(1): sleep(0.5) print proc.communicate("1 1 1") print "running"

    Read the article

  • C: incompatible types in assignment

    - by The.Anti.9
    I'm writing a program to check to see if a port is open in C. One line in particular copies one of the arguments to a char array. However, when I try to compile, it says: error: incompatible types in assignment Heres the code. The error is on the assignment of addr #include <sys/socket.h> #include <sys/time.h> #include <sys/types.h> #include <arpa/inet.h> #include <netinet/in.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <netdb.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main(int argc, char **argv) { u_short port; /* user specified port number */ char addr[1023]; /* will be a copy of the address entered by u */ struct sockaddr_in address; /* the libc network address data structure */ short int sock = -1; /* file descriptor for the network socket */ port = atoi(argv[1]); addr = strncpy(addr, argv[2], 1023); bzero((char *)&address, sizeof(address)); /* init addr struct */ address.sin_addr.s_addr = inet_addr(addr); /* assign the address */ address.sin_port = htons(port); /* translate int2port num */ sock = socket(AF_INET, SOCK_STREAM, 0); if (connect(sock,(struct sockaddr *)&address,sizeof(address)) == 0) { printf("%i is open\n", port); } if (errno == 113) { fprintf(stderr, "Port not open!\n"); } close(sock); return 0; } I'm new to C, so I'm not sure why it would do this.

    Read the article

  • fopen / fopen_s and writing to files

    - by yCalleecharan
    Hi, I'm using fopen in C to write the output to a text file. The function declaration is (where ARRAY_SIZE has been defined earlier): void create_out_file(char file_name[],long double *z1){ FILE *out; int i; if((out = fopen(file_name, "w+")) == NULL){ fprintf(stderr, "* Open error on output file %s", file_name); exit(-1); } for(i = 0; i < ARRAY_SIZE; i++) fprintf(out, "%.16Le\n", z1[i]); fclose(out); } My questions: On compilation with MVS2008 I get the warning: warning C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. I haven't see much information on fopen_s so that I can change my code. Any suggestions? Can one instruct fprintf to write at desired precision? If I'm using long double then I assume that my answers are good till 15 digits after the decimal point. Am I right? Thanks a lot...

    Read the article

  • C: socket connection timeout

    - by The.Anti.9
    I have a simple program to check if a port is open, but I want to shorten the timeout length on the socket connection because the default is far too long. I'm not sure how to do this though. Here's the code: #include <sys/socket.h> #include <sys/time.h> #include <sys/types.h> #include <arpa/inet.h> #include <netinet/in.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <netdb.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main(int argc, char **argv) { u_short port; /* user specified port number */ char addr[1023]; /* will be a copy of the address entered by u */ struct sockaddr_in address; /* the libc network address data structure */ short int sock = -1; /* file descriptor for the network socket */ if (argc != 3) { fprintf(stderr, "Usage %s <port_num> <address>", argv[0]); return EXIT_FAILURE; } address.sin_addr.s_addr = inet_addr(argv[2]); /* assign the address */ address.sin_port = htons(atoi(argv[2])); /* translate int2port num */ sock = socket(AF_INET, SOCK_STREAM, 0); if (connect(sock,(struct sockaddr *)&address,sizeof(address)) == 0) { printf("%i is open\n", port); } close(sock); return 0; }

    Read the article

  • Does waitpid yield valid status information for a child process that has already exited?

    - by dtrebbien
    If I fork a child process, and the child process exits before the parent even calls waitpid, then is the exit status information that is set by waitpid still valid? If so, when does it become not valid; i.e., how do I ensure that I can call waitpid on the child pid and continue to get valid exit status information after an arbitrary amount of time, and how do I "clean up" (tell the OS that I am no longer interested in the exit status information for the finished child process)? I was playing around with the following code, and it appears that the exit status information is valid for at least a few seconds after the child finishes, but I do not know for how long or how to inform the OS that I won't be calling waitpid again: #include <assert.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> int main() { pid_t pid = fork(); if (pid < 0) { fprintf(stderr, "Failed to fork\n"); return EXIT_FAILURE; } else if (pid == 0) { // code for child process _exit(17); } else { // code for parent sleep(3); int status; waitpid(pid, &status, 0); waitpid(pid, &status, 0); // call `waitpid` again just to see if the first call had an effect assert(WIFEXITED(status)); assert(WEXITSTATUS(status) == 17); } return EXIT_SUCCESS; }

    Read the article

  • C/C++ I18N mbstowcs question

    - by bogertron
    I am working on internationalizing the input for a C/C++ application. I have currently hit an issue with converting from a multi-byte string to wide character string. The code needs to be cross platform compatible, so I am using mbstowcs and wcstombs as much as possible. I am currently working on a WIN32 machine and I have set the locale to a non-english locale (Japanese). When I attempt to convert a multibyte character string, I seem to be having some conversion issues. Here is an example of the code: int main(int argc, char** argv) { wchar_t *wcsVal = NULL; char *mbsVal = NULL; /* Get the current code page, in my case 932, runs only on windows */ TCHAR szCodePage[10]; int cch= GetLocaleInfo( GetSystemDefaultLCID(), LOCALE_IDEFAULTANSICODEPAGE, szCodePage, sizeof(szCodePage)); /* verify locale is set */ if (setlocale(LC_CTYPE, "") == 0) { fprintf(stderr, "Failed to set locale\n"); return 1; } mbsVal = argv[1]; /* validate multibyte string and convert to wide character */ int size = mbstowcs(NULL, mbsVal, 0); if (size == -1) { printf("Invalid multibyte\n"); return 1; } wcsVal = (wchar_t*) malloc(sizeof(wchar_t) * (size + 1)); if (wcsVal == NULL) { printf("memory issue \n"); return 1; } mbstowcs(wcsVal, szVal, size + 1); wprintf(L"%ls \n", wcsVal); return 0; } At the end of execution, the wide character string does not contain the converted data. I believe that there is an issue with the code page settings, because when i use MultiByteToWideChar and have the current code page sent in EX: MultiByteToWideChar( CP_ACP, 0, mbsVal, -1, wcsVal, size + 1 ); in place of the mbstowcs calls, the conversion succeeds. My question is, how do I use the generic mbstowcs call instead of teh MuliByteToWideChar call?

    Read the article

  • Python logging in Django

    - by Jeff
    I'm developing a Django app, and I'm trying to use Python's logging module for error/trace logging. Ideally I'd like to have different loggers configured for different areas of the site. So far I've got all of this working, but one thing has me scratching my head. I have the root logger going to sys.stderr, and I have configured another logger to write to a file. This is in my settings.py file: sviewlog = logging.getLogger('MyApp.views.scans') view_log_handler = logging.FileHandler('C:\\MyApp\\logs\\scan_log.log') view_log_handler.setLevel(logging.INFO) view_log_handler.setFormatter(logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')) sviewlog.addHandler(view_log_handler) Seems pretty simple. Here's the problem, though: whatever I write to the sviewlog gets written to the log file twice. The root logger only prints it once. It's like addHandler() is being called twice. And when I put my code through a debugger, this is exactly what I see. The code in settings.py is getting executed twice, so two FileHandlers are created and added to the same logger instance. But why? And how do I get around this? Can anyone tell me what's going on here? I've tried moving the sviewlog logger/handler instantiation code to the file where it's used (since that actually seems like the appropriate place to me), but I have the same problem there. Most of the examples I've seen online use only the root logger, and I'd prefer to have multiple loggers.

    Read the article

  • pthread_join from a signal handler

    - by liv2hak
    I have a capture program which in addition do capturing data and writing it into a file also prints some statistics.The function that prints the statistics static void* report(void) { /*Print statistics*/ } is called roughly every second using an ALARM that expires every second.So The program is like void capture_program() { pthread_t report_thread while(!exit_now) { if(pthread_create(&report_thread,NULL,report,NULL)){ fprintf(stderr,"Error creating reporting thread! \n"); } /* Capturing code -------------- -------------- */ if(doreport) usleep(5); } } void *report(void *param) { while(true) { if(doreport) { doreport = 0 //access some register from hardware usleep(5) } } } The expiry of the timer sets the doreport flag.If this flag is set report() is called which clears the flag.I am using usleep to alternate between two threads in the program.This seems to work fine. I also have a signal handler to handle SIGINT (i.e CTRL+C) static void anysig(int sig) { if (sig != SIGINT) dagutil_set_signal_handler(SIG_DFL); /* Tell the main loop to exit */ exit_now = 1; return; } My question: 1) Is it safe to call pthread_join from inside the signal handler? 2) Should I use exit_now flag for the report thread as well?

    Read the article

  • Porting Perl to C++ `print "\x{2501}" x 12;`

    - by jippie
    I am porting a program from Perl to C++ as a learning objective. I arrived at a routine that draws a table with commands like the following: Perl: print "\x{2501}" x 12; And it draws 12 times a '?' ("box drawings heavy horizontal"). Now I figured out part of the problem already: Perl: \x{}, \x00 Hexadecimal escape sequence; C++: \unnnn To print a single Unicode character: C++: printf( "\u250f\n" ); But does C++ have a smart equivalent for the 'x' operator or would it come down to a for loop? UPDATE Let me include the full source code I am trying to compile with the proposed solution. The compiler does throw an errors: g++ -Wall -Werror project.cpp -o project project.cpp: In function ‘int main(int, char**)’: project.cpp:38:3: error: ‘string’ is not a member of ‘std’ project.cpp:38:15: error: expected ‘;’ before ‘s’ project.cpp:39:3: error: ‘cout’ is not a member of ‘std’ project.cpp:39:16: error: ‘s’ was not declared in this scope #include <stdlib.h> #include <stdint.h> #include <stdio.h> #include <string.h> int main ( int argc, char *argv[] ) { if ( argc != 2 ) { fprintf( stderr , "usage: %s matrix\n", argv[0] ); exit( 2 ); } else { //std::string s(12, "\u250f" ); std::string s(12, "u" ); std::cout << s; } }

    Read the article

  • Celery Received unregistered task of type (run example)

    - by Echeg
    I'm trying to run example from Celery documentation. I run: celeryd --loglevel=INFO /usr/local/lib/python2.7/dist-packages/celery/loaders/default.py:64: NotConfigured: No 'celeryconfig' module found! Please make sure it exists and is available to Python. "is available to Python." % (configname, ))) [2012-03-19 04:26:34,899: WARNING/MainProcess] -------------- celery@ubuntu v2.5.1 ---- **** ----- --- * *** * -- [Configuration] -- * - **** --- . broker: amqp://guest@localhost:5672// - ** ---------- . loader: celery.loaders.default.Loader - ** ---------- . logfile: [stderr]@INFO - ** ---------- . concurrency: 4 - ** ---------- . events: OFF - *** --- * --- . beat: OFF -- ******* ---- --- ***** ----- [Queues] -------------- . celery: exchange:celery (direct) binding:celery tasks.py: # -*- coding: utf-8 -*- from celery.task import task @task def add(x, y): return x + y run_task.py: # -*- coding: utf-8 -*- from tasks import add result = add.delay(4, 4) print (result) print (result.ready()) print (result.get()) In same folder celeryconfig.py: CELERY_IMPORTS = ("tasks", ) CELERY_RESULT_BACKEND = "amqp" BROKER_URL = "amqp://guest:guest@localhost:5672//" CELERY_TASK_RESULT_EXPIRES = 300 When I run "run_task.py": on python console eb503f77-b5fc-44e2-ac0b-91ce6ddbf153 False errors on celeryd server [2012-03-19 04:34:14,913: ERROR/MainProcess] Received unregistered task of type 'tasks.add'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you are using relative imports? Please see http://bit.ly/gLye1c for more information. The full contents of the message body was: {'retries': 0, 'task': 'tasks.add', 'utc': False, 'args': (4, 4), 'expires': None, 'eta': None, 'kwargs': {}, 'id': '841bc21f-8124-436b-92f1-e3b62cafdfe7'} Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/celery/worker/consumer.py", line 444, in receive_message self.strategies[name](message, body, message.ack_log_error) KeyError: 'tasks.add' Please explain what's the problem.

    Read the article

  • How to check volume is mounted or not using python with a dynamic volume name

    - by SR query
    import subprocess def volumeCheck(volume_name): """This function will check volume name is mounted or not. """ volume_name = raw_input('Enter volume name:') volumeCheck(volume_name) print 'volume_name=',volume_name p = subprocess.Popen(['df', '-h'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) p1, err = p.communicate() pattern = p1 if pattern.find(volume_name): print 'volume found' else: print 'volume not found' While running i always got wrong result "volume found". root@sr-query:/# df -h Filesystem Size Used Avail Use% Mounted on rootfs 938M 473M 418M 54% / /dev/md0 938M 473M 418M 54% / none 250M 4.9M 245M 2% /dev /dev/md2 9.7M 1.2M 8.0M 13% /usr/config /dev/md7 961M 18M 895M 2% /downloads tmpfs 250M 7.9M 242M 4% /var/volatile tmpfs 250M 0 250M 0% /dev/shm tmpfs 250M 0 250M 0% /media/ram **/dev/mapper/vg9-lv9 1016M 65M 901M 7% /VolumeData/sp /dev/mapper/vg10-lv10 1016M 65M 901M 7% /VolumeData/cp** root@sr-query:/# root@sr-query:/# root@sr-query:/# python volume_check.py Enter volume name:raid_10volume volume_name= raid_10volume **volume found** root@sr-query:/# I enterd raid_10volume its not listed here please check the df -h command out put(only 2 volume there sp and cp) , then how it reached else part. what is wrong in my code? Thanks in advance. is there any other way to do this work ! ?

    Read the article

  • Using the read function to read in a file.

    - by robUK
    Hello, gcc 4.4.1 I am using the read function to read in a wave file. However, when it gets to the read function. Execution seems to stop and freezes. I am wondering if I am doing anything wrong with this. The file size test-short.wave is: 514K. What I am aiming for is to read the file into the memory buffer chunks at a time. Currently I just testing this. Many thanks for any suggestions, #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <fcntl.h> #include <string.h> #include <unistd.h> int main(void) { char buff = malloc(10240); int32_t fd = 0; int32_t bytes_read = 0; char *filename = "test-short.wav"; /* open wave file */ if((fd = (open(filename, O_RDWR)) == -1)) { fprintf(stderr, "open [ %s ]\n", strerror(errno)); return 1; } printf("Opened file [ %s ]\n", filename); printf("sizeof(buff) [ %d ]\n", sizeof(buff)); printf("strlen(buff) [ %d ]\n", strlen(buff)); bytes_read = read(fd, buff, sizeof(buff)); printf("Bytes read [ %d ]\n", bytes_read); return 0; }

    Read the article

  • GTK+ and GdkPixbuf

    - by Daniel
    Hi all, I think I've got an understanding problem of GTK. My simple application has a stream of images and I'd like to display them within my GTK Window. Up to now, it looks like this: GdkPixbuf *pb = gdk_pixbuf_new_from_data(img2, GDK_COLORSPACE_RGB, FALSE, 24/3, 320, 240, 320*3, NULL, NULL); if(pb == NULL) fprintf(stderr, "Pixbuf is null!\n"); if(image != NULL) gtk_container_remove(GTK_CONTAINER(window), image); image = gtk_image_new_from_pixbuf(pb); gtk_container_add(GTK_CONTAINER(window), image); printf("Updated!\n"); img2 is my (rgb) buffer that gets updated from a stream each time. I guess gtk_container_remove and gtk_container_add might be stupid to use for this? Here's what I've got in addition: GtkWidget *window; GtkWidget *image; gtk_init(&argc, &argv); window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_signal_connect(GTK_OBJECT(window), "destroy", GTK_SIGNAL_FUNC(destroy), NULL); /* ... */ start_routine_for_stream_that_calls_the_above(...) /* ... */ gtk_widget_show_all(window); gtk_main(); My problem is that it's not working this way... either I see only the last GdkPixbuf image or I see none, which is the correct behaviour ... But how do I manage it to show an (stream of) updated GdkPixbuf? Thanks for help

    Read the article

  • How do I call Matlab in a script on Windows?

    - by Benjamin Oakes
    I'm working on a project that uses several languages: SQL for querying a database Perl/Ruby for quick-and-dirty processing of the data from the database and some other bookkeeping Matlab for matrix-oriented computations Various statistics languages (SAS/R/SPSS) for processing the Matlab output Each language fits its niche well and we already have a fair amount of code in each. Right now, there's a lot of manual work to run all these steps that would be much better scripted. I've already done this on Linux, and it works relatively well. On Linux: matlab -nosplash -nodesktop -r "command" or echo "command" | matlab -nosplash -nodesktop ...opens Matlab in a "command line" mode. (That is, no windows are created -- it just reads from STDIN, executes, and outputs to STDOUT/STDERR.) My problem is that on Windows (XP and 7), this same code opens up a window and doesn't read from / write to the command line. It just stares me blankly in the face, totally ignoring STDIN and STDOUT. How can I script running Matlab commands on Windows? I basically want something that will do: ruby database_query.rb perl legacy_code.pl ruby other_stuff.rb matlab processing_step_1.m matlab processing_step_2.m # etc, etc. I've found out that Matlab has an -automation flag on Windows to start an "automation server". That sounds like overkill for my purposes, and I'd like something that works on both platforms. What options do I have for automating Matlab in this workflow?

    Read the article

  • Create a console from within a non-console .NET application.

    - by pauldoo
    How can I open a console window from within a non-console .NET application (so I have a place for System.Console.Out and friends when debugging)? In C++ this can be done using various Win32 APIs: /* EnsureConsoleExists() will create a console window and attach stdout (and friends) to it. Can be useful when debugging. */ FILE* const CreateConsoleStream(const DWORD stdHandle, const char* const mode) { const HANDLE outputHandle = ::GetStdHandle(stdHandle); assert(outputHandle != 0); const int outputFileDescriptor = _open_osfhandle(reinterpret_cast<intptr_t>(outputHandle), _O_TEXT); assert(outputFileDescriptor != -1); FILE* const outputStream = _fdopen(outputFileDescriptor, mode); assert(outputStream != 0); return outputStream; } void EnsureConsoleExists() { const bool haveCreatedConsole = (::AllocConsole() != 0); if (haveCreatedConsole) { /* If we didn't manage to create the console then chances are that stdout is already going to a console window. */ *stderr = *CreateConsoleStream(STD_ERROR_HANDLE, "w"); *stdout = *CreateConsoleStream(STD_OUTPUT_HANDLE, "w"); *stdin = *CreateConsoleStream(STD_INPUT_HANDLE, "r"); std::ios::sync_with_stdio(false); const HANDLE consoleHandle = ::GetStdHandle(STD_OUTPUT_HANDLE); assert(consoleHandle != NULL && consoleHandle != INVALID_HANDLE_VALUE); CONSOLE_SCREEN_BUFFER_INFO info; BOOL result = ::GetConsoleScreenBufferInfo(consoleHandle, &info); assert(result != 0); COORD size; size.X = info.dwSize.X; size.Y = 30000; result = ::SetConsoleScreenBufferSize(consoleHandle, size); assert(result != 0); } }

    Read the article

  • expected identifier or '(' before '{' token in Flex

    - by user1829177
    I am trying to use Flex to parse 'C' source code. Unfortunately I am getting the error "expected identifier or '(' before '{' token" on lines 1,12,13,14... . Any ideas why? %{ %} digit [0-9] letter [a-zA-Z] number (digit)+ id (letter|_)(letter|digit|_)* integer (int) character (char) comma [,] %% {integer} {return INT;} {character} {return CHAR;} {number} {return NUM;} {id} {return IDENTIFIER;} {comma} {return ',';} [-+*/] {return *yytext;} . {} %% main() { yylex(); } The corresponding flex file is as shown below: %{ #include <ctype.h> #include <stdio.h> #include "myhead.h" #include "mini.l" #define YYSTYPE double # undef fprintf %} %token INT %token CHAR %token IDENTIFIER %token NUM %token ',' %left '+' '-' %left '*' '/' %right UMINUS %% lines:lines expr '\n' {printf("%g\n",$2);} |lines '\n' |D | ; expr :expr '*' expr {$$=$1*$3;} |expr '/' expr {$$=$1/$3;} |expr '+' expr {$$=$1+$3;} |expr '-' expr {$$=$1+$3;} |'(' expr ')' {$$=$2;} |'-' expr %prec UMINUS {$$=-$2;} |IDENTIFIER {} |NUM {} ; T :INT {} |CHAR {} ; L :L ',' IDENTIFIER {} |IDENTIFIER {} ; D :T L {printf("T is %g, L is %g",$1,$2);} ; %% /*void yyerror (char *s) { fprintf (stderr, "%s\n", s); } */ I am compiling the generated code using the command: gcc my_file.c -ly

    Read the article

< Previous Page | 14 15 16 17 18 19 20 21 22  | Next Page >