Search Results

Search found 126 results on 6 pages for 'glob'.

Page 2/6 | < Previous Page | 1 2 3 4 5 6  | Next Page >

  • Plugin jQuery da Microsoft para Globalização

    - by Leniel Macaferi
    No mês passado eu escrevi sobre como a Microsoft está começando a fazer contribuições de código para a jQuery (em Inglês), e sobre algumas das primeiras contribuições de código nas quais estávamos trabalhando: Suporte para Templates jQuery e Linkagem de Dados (em Inglês). Hoje, lançamos um protótipo de um novo plugin jQuery para Globalização que te permite adicionar suporte à globalização/internacionalização para as suas aplicações JavaScript. Este plugin inclui informações de globalização para mais de 350 culturas que vão desde o Gaélico Escocês, o Frísio, Húngaro, Japonês, e Inglês Canadense. Nós estaremos lançando este plugin para a comunidade em um formato de código livre. Você pode baixar nosso protótipo do plugin jQuery para Globalização a partir do nosso repositório Github: http://github.com/nje/jquery-glob Você também pode baixar um conjunto de exemplos que demonstram alguns simples casos de uso com ele aqui. Entendendo Globalização O plugin jQuery para Globalização permite que você facilmente analise e formate números, moedas e datas para diferentes culturas em JavaScript. Por exemplo, você pode usar o plugin de globalização para mostrar o símbolo da moeda adequado para uma cultura: Você também pode usar o plugin de globalização para formatar datas para que o dia e o mês apareçam na ordem certa e para que os nomes dos dias e meses sejam corretamente traduzidos: Observe acima como o ano Árabe é exibido como 1431. Isso ocorre porque o ano foi convertido para usar o calendário Árabe. Algumas diferenças culturais, tais como moeda diferente ou nomes de meses, são óbvias. Outras diferenças culturais são surpreendentes e sutis. Por exemplo, em algumas culturas, o agrupamento de números é feito de forma irregular. Na cultura "te-IN" (Telugu na Índia), grupos possuem 3 dígitos e, em seguida, dois dígitos. O número 1000000 (um milhão) é escrito como "10,00,000". Algumas culturas não agrupam os números. Todas essas sutis diferenças culturais são tratadas pelo plugin de Globalização da jQuery automaticamente. Pegar as datas corretamente pode ser especialmente complicado. Diferentes culturas têm calendários diferentes, como o Gregoriano e os calendários UmAlQura. Uma única cultura pode até mesmo ter vários calendários. Por exemplo, a cultura Japonesa usa o calendário Gregoriano e um calendário Japonês que possui eras com nomes de imperadores Japoneses. O plugin de Globalização inclui métodos para a conversão de datas entre todos estes diferentes calendários. Usando Tags de Idioma O plugin de Globalização da jQuery utiliza as tags de idioma definidas nos padrões das RFCs 4646 e 5646 para identificar culturas (veja http://tools.ietf.org/html/rfc5646). Uma tag de idioma é composta por uma ou mais subtags separadas por hífens. Por exemplo: Tag do Idioma Nome do Idioma (em Inglês) en-UA English (Australia) en-BZ English (Belize) en-CA English (Canada) Id Indonesian zh-CHS Chinese (Simplified) Legacy Zu isiZulu Observe que um único idioma, como o Inglês, pode ter várias tags de idioma. Falantes de Inglês no Canadá formatam números, moedas e datas usando diferentes convenções daquelas usadas pelos falantes de Inglês na Austrália ou nos Estados Unidos. Você pode encontrar a tag de idioma para uma cultura específica usando a Language Subtag Lookup Tool (Ferramenta de Pesquisa de Subtags de Idiomas) em: http://rishida.net/utils/subtags/ O download do plugin de Globalização da jQuery inclui uma pasta chamada globinfo que contém as informações de cada uma das 350 culturas. Na verdade, esta pasta contém mais de 700 arquivos, porque a pasta inclui ambas as versões minified (tamanho reduzido) e não-minified de cada arquivo. Por exemplo, a pasta globinfo inclui arquivos JavaScript chamados jQuery.glob.en-AU.js para o Inglês da Austrália, jQuery.glob.id.js para o Indonésio, e jQuery.glob.zh-CHS para o Chinês (simplificado) Legacy. Exemplo: Definindo uma Cultura Específica Imagine que te pediram para criar um site em Alemão e que querem formatar todas as datas, moedas e números usando convenções de formatação da cultura Alemã de maneira correta em JavaScript no lado do cliente. O código HTML para a página pode ser igual a este: Observe as tags span acima. Elas marcam as áreas da página que desejamos formatar com o plugin de Globalização. Queremos formatar o preço do produto, a data em que o produto está disponível, e as unidades do produto em estoque. Para usar o plugin de Globalização da jQuery, vamos adicionar três arquivos JavaScript na página: a biblioteca jQuery, o plugin de Globalização da jQuery, e as informações de cultura para um determinado idioma: Neste caso, eu estaticamente acrescentei o arquivo JavaScript jQuery.glob.de-DE.js que contém as informações para a cultura Alemã. A tag de idioma "de-DE" é usada para o Alemão falado na Alemanha. Agora que eu tenho todos os scripts necessários, eu posso usar o plugin de Globalização para formatar os valores do preço do produto, data disponível, e unidades no estoque usando o seguinte JavaScript no lado do cliente: O plugin de Globalização jQuery amplia a biblioteca jQuery com novos métodos - incluindo novos métodos chamados preferCulture() e format(). O método preferCulture() permite que você defina a cultura padrão utilizada pelos métodos do plugin de Globalização da jQuery. Observe que o método preferCulture() aceita uma tag de idioma. O método irá buscar a cultura mais próxima que corresponda à tag do idioma. O método $.format() é usado para formatar os valores monetários, datas e números. O segundo parâmetro passado para o método $.format() é um especificador de formato. Por exemplo, passar um "c" faz com que o valor seja formatado como moeda. O arquivo LeiaMe (ReadMe) no github detalha o significado de todos os diferentes especificadores de formato: http://github.com/nje/jquery-glob Quando abrimos a página em um navegador, tudo está formatado corretamente de acordo com as convenções da língua Alemã. Um símbolo do euro é usado para o símbolo de moeda. A data é formatada usando nomes de dia e mês em Alemão. Finalmente, um ponto, em vez de uma vírgula é usado como separador numérico: Você pode ver um exemplo em execução da abordagem acima com o arquivo 3_GermanSite.htm neste download de amostras. Exemplo: Permitindo que um Usuário Selecione Dinamicamente uma Cultura No exemplo anterior, nós explicitamente dissemos que queríamos globalizar em Alemão (referenciando o arquivo jQuery.glob.de-DE.js). Vamos agora olhar para o primeiro de alguns exemplos que demonstram como definir dinamicamente a cultura da globalização a ser usada. Imagine que você deseja exibir uma lista suspensa (dropdown) de todas as 350 culturas em uma página. Quando alguém escolhe uma cultura a partir da lista suspensa, você quer que todas as datas da página sejam formatadas usando a cultura selecionada. Aqui está o código HTML para a página: Observe que todas as datas estão contidas em uma tag <span> com um atributo data-date (atributos data-* são um novo recurso da HTML 5, que convenientemente também ainda funcionam com navegadores mais antigos). Nós vamos formatar a data representada pelo atributo data-date quando um usuário selecionar uma cultura a partir da lista suspensa. A fim de mostrar as datas para qualquer cultura disponível, vamos incluir o arquivo jQuery.glob.all.js igual a seguir: O plugin de Globalização da jQuery inclui um arquivo JavaScript chamado jQuery.glob.all.js. Este arquivo contém informações de globalização para todas as mais de 350 culturas suportadas pelo plugin de Globalização. Em um tamanho de 367 KB minified (reduzido), esse arquivo não é pequeno. Devido ao tamanho deste arquivo, a menos que você realmente precise usar todas essas culturas, ao mesmo tempo, recomendamos que você adicione em uma página somente os arquivos JavaScript individuais para as culturas específicas que você pretende suportar, ao invés do arquivo jQuery.glob.all.js combinado. No próximo exemplo, eu vou mostrar como carregar dinamicamente apenas os arquivos de idioma que você precisa. A seguir, vamos preencher a lista suspensa com todas as culturas disponíveis. Podemos usar a propriedade $.cultures para obter todas as culturas carregadas: Finalmente, vamos escrever o código jQuery que pega cada elemento span com um atributo data-date e formataremos a data: O método parseDate() do plugin de Globalização da jQuery é usado para converter uma representação de uma data em string para uma data JavaScript. O método format() do plugin é usado para formatar a data. O especificador de formato "D" faz com que a data a ser formatada use o formato de data longa. E agora, o conteúdo será globalizado corretamente, independentemente de qual das 350 línguas o usuário que visita a página selecione. Você pode ver um exemplo em execução da abordagem acima com o arquivo 4_SelectCulture.htm neste download de amostras. Exemplo: Carregando Arquivos de Globalização Dinamicamente Conforme mencionado na seção anterior, você deve evitar adicionar o arquivo jQuery.glob.all.js em uma página, sempre que possível, porque o arquivo é muito grande. Uma melhor alternativa é carregar as informações de globalização que você precisa dinamicamente. Por exemplo, imagine que você tenha criado uma lista suspensa que exibe uma lista de idiomas: O seguinte código jQuery é executado sempre que um usuário seleciona um novo idioma na lista suspensa. O código verifica se o arquivo associado com a globalização do idioma selecionado já foi carregado. Se o arquivo de globalização ainda não foi carregado, o arquivo de globalização é carregado dinamicamente, tirando vantagem do método $.getScript() da jQuery. O método globalizePage() é chamado depois que o arquivo de globalização solicitado tenha sido carregado, e contém o código do lado do cliente necessário para realizar a globalização. A vantagem dessa abordagem é que ela permite evitar o carregamento do arquivo jQuery.glob.all.js inteiro. Em vez disso você só precisa carregar os arquivos que você vai usar e você não precisa carregar os arquivos mais de uma vez. O arquivo 5_Dynamic.htm neste download de amostras demonstra como implementar esta abordagem. Exemplo: Definindo o Idioma Preferido do Usuário Automaticamente Muitos sites detectam o idioma preferido do usuário a partir das configurações de seu navegador e as usam automaticamente quando globalizam o conteúdo. Um usuário pode definir o idioma preferido para o seu navegador. Então, sempre que o usuário solicita uma página, esta preferência de idioma está incluída no pedido no cabeçalho Accept-Language. Quando você usa o Microsoft Internet Explorer, você pode definir o seu idioma preferido, seguindo estes passos: Selecione a opção do menu Ferramentas, Opções da Internet. Selecione a guia/tab Geral. Clique no botão Idiomas na seção Aparência. Clique no botão Adicionar para adicionar um novo idioma na lista de idiomas. Mova seu idioma preferido para o topo da lista. Observe que você pode listar múltiplos idiomas na janela de diálogo de Preferências de Idioma. Todas estas línguas são enviadas na ordem em que você as listou no cabeçalho Accept-Language: Accept-Language: fr-FR,id-ID;q=0.7,en-US;q= 0.3 Estranhamente, você não pode recuperar o valor do cabeçalho Accept-Language a partir do código JavaScript no lado do cliente. O Microsoft Internet Explorer e o Mozilla Firefox suportam um grupo de propriedades relacionadas a idiomas que são expostas pelo objeto window.navigator, tais como windows.navigator.browserLanguage e window.navigator.language, mas essas propriedades representam tanto o idioma definido para o sistema operacional ou a linguagem de edição do navegador. Essas propriedades não permitem que você recupere o idioma que o usuário definiu como seu idioma preferido. A única maneira confiável para se obter o idioma preferido do usuário (o valor do cabeçalho Accept-Language) é escrever código no lado do servidor. Por exemplo, a seguinte página ASP.NET tira vantagem da propriedade do servidor Request.UserLanguages para atribuir o idioma preferido do usuário para uma variável JavaScript no lado do cliente chamada AcceptLanguage (a qual então permite que você acesse o valor usando código JavaScript no lado do cliente): Para que este código funcione, as informações de cultura associadas ao valor de acceptLanguage devem ser incluídas na página. Por exemplo, se a cultura preferida de alguém é fr-FR (Francês na França) então você precisa incluir tanto o arquivo jQuery.glob.fr-FR.js ou o arquivo jQuery.glob.all.js na página; caso contrário, as informações de cultura não estarão disponíveis. O exemplo "6_AcceptLanguages.aspx" neste download de amostras demonstra como implementar esta abordagem. Se as informações de cultura para o idioma preferido do usuário não estiverem incluídas na página, então, o método $.preferCulture() voltará a usar a cultura neutra (por exemplo, passará a usar jQuery.glob.fr.js ao invés de jQuery.glob.fr-FR.js). Se as informações da cultura neutra não estiverem disponíveis, então, o método $.preferCulture() retornará para a cultura padrão (Inglês). Exemplo: Usando o Plugin de Globalização com o jQuery UI DatePicker (Selecionador de Datas da jQuery) Um dos objetivos do plugin de Globalização é tornar mais fácil construir widgets jQuery que podem ser usados com diferentes culturas. Nós queríamos ter certeza de que o plugin de Globalização da jQuery pudesse funcionar com os plugins de UI (interface do usuário) da jQuery, como o plugin DatePicker. Para esse fim, criamos uma versão corrigida do plugin DatePicker que pode tirar proveito do plugin de Globalização na renderização de um calendário. A imagem a seguir ilustra o que acontece quando você adiciona o plugin de Globalização jQuery e o plugin DatePicker da jQuery corrigido em uma página e seleciona a cultura da Indonésia como preferencial: Note que os cabeçalhos para os dias da semana são exibidos usando abreviaturas dos nomes dos dias referentes ao idioma Indonésio. Além disso, os nomes dos meses são exibidos em Indonésio. Você pode baixar a versão corrigida do jQuery UI DatePicker no nosso site no github. Ou você pode usar a versão incluída neste download de amostras e usada pelo arquivo de exemplo 7_DatePicker.htm. Sumário Estou animado com a nossa participação contínua na comunidade jQuery. Este plugin de Globalização é o terceiro plugin jQuery que lançamos. Nós realmente apreciamos todos os ótimos comentários e sugestões sobre os protótipos do Suporte para Templates jQuery e Linkagem de Dados que lançamos mais cedo neste ano. Queremos também agradecer aos times da jQuery e jQuery UI por trabalharem conosco na criação deses plugins. Espero que isso ajude, Scott P.S. Além do blog, eu também estou agora utilizando o Twitter para atualizações rápidas e para compartilhar links. Você pode me acompanhar em: twitter.com/scottgu   Texto traduzido do post original por Leniel Macaferi.

    Read the article

  • zsh for loop exclusion

    - by ABach
    This is somewhat of a simple question, but for the life of me, I cannot figure out how to exclude something from a zsh for loop. For instance, let's say we have this: for $package in /home/user/settings/* do # do stuff done Let's say that in /home/user/settings/, there is a particular directory ("os") that I want to ignore. Logically, I tried the following variations: for $package in /home/user/settings/^os (works w/ "ls", but not with a foor loop) for $package in /home/user/settings/*^os for $package in /home/user/settings/^os* ...but none of those seem to work. Could someone steer my syntax in the right direction?

    Read the article

  • IIS 7.5 on Windows Server 2008 R2 refusing to create PASSIVE MODE FTP connections

    - by Campbell
    I'm attempting to get an FTP client written in perl to transfer files from an IIS 7.5 FTP server using passive mode. I've configured the FTP server as per instructions and have also configured Windows Firewall to allow this type of traffic. I have validated that the firewall is behaviong correctly by checking to ensure there are no blocked packets in the logs. I have verified the that FTP control channel is being opened on Port 21. I believe the client is being told by IIS which port to connect on for passive mode and IIS is refusing to allow this connection. The perl log looks like: C:\cygwin\Perl\lib\FMT>perl FTPTest.pl Net::FTP>>> Net::FTP(2.77) Net::FTP>>> Exporter(5.64_01) Net::FTP>>> Net::Cmd(2.29) Net::FTP>>> IO::Socket::INET(1.31) Net::FTP>>> IO::Socket(1.31) Net::FTP>>> IO::Handle(1.28) Net::FTP=GLOB(0x20abac0)<<< 220 Microsoft FTP Service Net::FTP=GLOB(0x20abac0)>>> USER ftpuser Net::FTP=GLOB(0x20abac0)<<< 331 Password required for ftpuser. Net::FTP=GLOB(0x20abac0)>>> PASS .... Net::FTP=GLOB(0x20abac0)<<< 230 User logged in. Net::FTP=GLOB(0x20abac0)>>> CWD /Logs Net::FTP=GLOB(0x20abac0)<<< 250 CWD command successful. Net::FTP=GLOB(0x20abac0)>>> PASV Net::FTP=GLOB(0x20abac0)<<< 227 Entering Passive Mode (xx,xxx,xxx,xxx,160,41). Net::FTP=GLOB(0x20abac0)>>> RETR filename.txt Can't use an undefined value as a symbol reference at C:/Utilities/strawberryper l/perl/lib/Net/FTP/dataconn.pm line 54. IIS logs look as follows: 2010-10-02 17:40:06 xx.xxx.xx.xx - yy.y.yy.yy ControlChannelOpened - - 0 0 27a48c9b-9dce-4770-8bcf-fc89f2569b1a - - 2010-10-02 17:40:06 xx.xxx.xx.xx - yy.y.yy.yy USER ftpuser 331 0 0 27a48c9b-9dce-4770-8bcf-fc89f2569b1a - - 2010-10-02 17:40:06 xx.xxx.xx.xx MACHINENAME\ftpuser yy.y.yy.yy PASS *** 230 0 0 27a48c9b-9dce-4770-8bcf-fc89f2569b1a / - 2010-10-02 17:40:06 xx.xxx.xx.xx MACHINENAME\ftpuser yy.y.yy.yy CWD /Logs 250 0 0 27a48c9b-9dce-4770-8bcf-fc89f2569b1a /Logs - 2010-10-02 17:40:06 xx.xxx.xx.xx MACHINENAME\ftpuser yy.y.yy.yy PASV - 227 0 0 27a48c9b-9dce-4770-8bcf-fc89f2569b1a - - 2010-10-02 17:40:27 - MACHINENAME\ftpuser zz.z.zz.zzz 41001 DataChannelClosed - - 64 0 27a48c9b-9dce-4770-8bcf-fc89f2569b1a - - 2010-10-02 17:40:27 xx.xxx.xx.xx MACHINENAME\ftpuser yy.y.yy.yy ControlChannelClosed - - 64 0 27a48c9b-9dce-4770-8bcf-fc89f2569b1a - - 2010-10-02 17:40:27 xx.xxx.xx.xx MACHINENAME\ftpuser yy.y.yy.yy RETR filename.txt 550 1236 0 27a48c9b-9dce-4770-8bcf-fc89f2569b1a filename.txt - We've managed to see this issue with other FTP clients also, I don't think its something funny in Perl. I've been informed that this works fine in the IIS 6 FTP server. I'm wondering if there is something we're missing here.

    Read the article

  • Logrotate not doing any rotation

    - by blizz
    I just set up LogRotate on my RHEL6 server so that it rotates my custom Apache log files. However, it doesn't do anything when i try manually running it. I expect it to rotate the log files "access.log" and "err.log". They have been there for a few days and need to be rotated. Here is the output: [root@pc1 httpd]# logrotate -d -f /etc/logrotate.d/apache reading config file /etc/logrotate.d/apache reading config info for /var/log/httpd/*log /var/www/html/NSLogs/access.log /var/www/html/NSErrorLogs/err.log Handling 1 logs rotating pattern: /var/log/httpd/*log /var/www/html/NSLogs/access.log /var/www/html/NSErrorLogs/err.log forced from command line (no old logs will be kept) empty log files are rotated, old logs are removed considering log /var/log/httpd/access_log log needs rotating considering log /var/log/httpd/error_log log needs rotating considering log /var/www/html/NSLogs/access.log log needs rotating considering log /var/www/html/NSErrorLogs/err.log log needs rotating rotating log /var/log/httpd/access_log, log->rotateCount is 0 dateext suffix '-20131023' glob pattern '-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]' glob finding old rotated logs failed fscreate context set to unconfined_u:object_r:httpd_log_t:s0 renaming /var/log/httpd/access_log to /var/log/httpd/access_log-20131023 disposeName will be /var/log/httpd/access_log-20131023.gz running postrotate script running script with arg /var/log/httpd/access_log: " /usr/bin/killall -HUP httpd " compressing log with: /bin/gzip removing old log /var/log/httpd/access_log-20131023.gz error: error opening /var/log/httpd/access_log-20131023.gz: No such file or directory rotating log /var/log/httpd/error_log, log->rotateCount is 0 dateext suffix '-20131023' glob pattern '-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]' glob finding old rotated logs failed fscreate context set to unconfined_u:object_r:httpd_log_t:s0 renaming /var/log/httpd/error_log to /var/log/httpd/error_log-20131023 disposeName will be /var/log/httpd/error_log-20131023.gz running postrotate script running script with arg /var/log/httpd/error_log: " /usr/bin/killall -HUP httpd " compressing log with: /bin/gzip removing old log /var/log/httpd/error_log-20131023.gz error: error opening /var/log/httpd/error_log-20131023.gz: No such file or directory rotating log /var/www/html/NSLogs/access.log, log->rotateCount is 0 dateext suffix '-20131023' glob pattern '-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]' glob finding old rotated logs failed fscreate context set to unconfined_u:object_r:httpd_sys_rw_content_t:s0 renaming /var/www/html/NSLogs/access.log to /var/www/html/NSLogs/access.log-20131023 disposeName will be /var/www/html/NSLogs/access.log-20131023.gz running postrotate script running script with arg /var/www/html/NSLogs/access.log: " /usr/bin/killall -HUP httpd " compressing log with: /bin/gzip removing old log /var/www/html/NSLogs/access.log-20131023.gz error: error opening /var/www/html/NSLogs/access.log-20131023.gz: No such file or directory rotating log /var/www/html/NSErrorLogs/err.log, log->rotateCount is 0 dateext suffix '-20131023' glob pattern '-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]' glob finding old rotated logs failed fscreate context set to unconfined_u:object_r:httpd_sys_rw_content_t:s0 renaming /var/www/html/NSErrorLogs/err.log to /var/www/html/NSErrorLogs/err.log-20131023 disposeName will be /var/www/html/NSErrorLogs/err.log-20131023.gz running postrotate script running script with arg /var/www/html/NSErrorLogs/err.log: " /usr/bin/killall -HUP httpd " compressing log with: /bin/gzip removing old log /var/www/html/NSErrorLogs/err.log-20131023.gz error: error opening /var/www/html/NSErrorLogs/err.log-20131023.gz: No such file or directory

    Read the article

  • Advanced Array Sorting in Ruby

    - by Ruby Beginner
    I'm currently working on a project in ruby, and I hit a wall on how I should proceed. In the project I'm using Dir.glob to search a directory and all of its subdirectories for certain file types and placing them into an arrays. The type of files I'm working with all have the same file name and are differentiated by their extensions. For example, txt_files = Dir.glob("**/*.txt") doc_files = Dir.glob("**/*.doc") rtf_files = Dir.glob("**/*.rtf") Would return something similar to, FILECON.txt ASSORTED.txt FIRST.txt FILECON.doc ASSORTED.doc FIRST.doc FILECON.rtf ASSORTED.rtf FIRST.rtf So, the question I have is how I could break down these arrays efficiently (dealing with thousands of files) and placing all files with the same filename into an array. The new array would look like, FILECON.txt FILECON.doc FILECON.rtf ASSORTED.txt ASSORTED.doc ASSORTED.rtf etc. etc. I'm not even sure if glob would be the correct way to do this (all the files with the same file name are in the same folders). Any help would be greatly appreciated!

    Read the article

  • Designing an API with compile-time option to remove first parameter to most functions and use a glob

    - by tomlogic
    I'm trying to design a portable API in ANSI C89/ISO C90 to access a wireless networking device on a serial interface. The library will have multiple network layers, and various versions need to run on embedded devices as small as an 8-bit micro with 32K of code and 2K of data, on up to embedded devices with a megabyte or more of code and data. In most cases, the target processor will have a single network interface and I'll want to use a single global structure with all state information for that device. I don't want to pass a pointer to that structure through the network layers. In a few cases (e.g., device with more resources that needs to live on two networks) I will interface to multiple devices, each with their own global state, and will need to pass a pointer to that state (or an index to a state array) through the layers. I came up with two possible solutions, but neither one is particularly pretty. Keep in mind that the full driver will potentially be 20,000 lines or more, cover multiple files, and contain hundreds of functions. The first solution requires a macro that discards the first parameter for every function that needs to access the global state: // network.h typedef struct dev_t { int var; long othervar; char name[20]; } dev_t; #ifdef IF_MULTI #define foo_function( x, a, b, c) _foo_function( x, a, b, c) #define bar_function( x) _bar_function( x) #else extern dev_t DEV; #define IFACE (&DEV) #define foo_function( x, a, b, c) _foo_function( a, b, c) #define bar_function( x) _bar_function( ) #endif int bar_function( dev_t *IFACE); int foo_function( dev_t *IFACE, int a, long b, char *c); // network.c #ifndef IF_MULTI dev_t DEV; #endif int bar_function( dev_t *IFACE) { memset( IFACE, 0, sizeof *IFACE); return 0; } int foo_function( dev_t *IFACE, int a, long b, char *c) { bar_function( IFACE); IFACE->var = a; IFACE->othervar = b; strcpy( IFACE->name, c); return 0; } The second solution defines macros to use in the function declarations: // network.h typedef struct dev_t { int var; long othervar; char name[20]; } dev_t; #ifdef IF_MULTI #define DEV_PARAM_ONLY dev_t *IFACE #define DEV_PARAM DEV_PARAM_ONLY, #else extern dev_t DEV; #define IFACE (&DEV) #define DEV_PARAM_ONLY void #define DEV_PARAM #endif int bar_function( DEV_PARAM_ONLY); // I don't like the missing comma between DEV_PARAM and arg2... int foo_function( DEV_PARAM int a, long b, char *c); // network.c #ifndef IF_MULTI dev_t DEV; #endif int bar_function( DEV_PARAM_ONLY) { memset( IFACE, 0, sizeof *IFACE); return 0; } int foo_function( DEV_PARAM int a, long b, char *c) { bar_function( IFACE); IFACE->var = a; IFACE->othervar = b; strcpy( IFACE->name, c); return 0; } The C code to access either method remains the same: // multi.c - example of multiple interfaces #define IF_MULTI #include "network.h" dev_t if0, if1; int main() { foo_function( &if0, -1, 3.1415926, "public"); foo_function( &if1, 42, 3.1415926, "private"); return 0; } // single.c - example of a single interface #include "network.h" int main() { foo_function( 11, 1.0, "network"); return 0; } Is there a cleaner method that I haven't figured out? I lean toward the second since it should be easier to maintain, and it's clearer that there's some macro magic in the parameters to the function. Also, the first method requires prefixing the function names with "_" when I want to use them as function pointers. I really do want to remove the parameter in the "single interface" case to eliminate unnecessary code to push the parameter onto the stack, and to allow the function to access the first "real" parameter in a register instead of loading it from the stack. And, if at all possible, I don't want to have to maintain two separate codebases. Thoughts? Ideas? Examples of something similar in existing code? (Note that using C++ isn't an option, since some of the planned targets don't have a C++ compiler available.)

    Read the article

  • Python: Convert format string to regular expression

    - by miracle2k
    The users of my app can configure the layout of certain files via a format string. For example, the config value the user specifies might be: layout = '%(group)s/foo-%(locale)s/file.txt' I now need to find all such files that already exist. This seems easy enough using the glob module: glob_pattern = layout % {'group': '*', 'locale': '*'} glob.glob(glob_pattern) However, now comes the hard part: Given the list of glob results, I need to get all those filename-parts that matched a given placeholder, for example all the different "locale" values. I thought I would generate a regular expression for the format string that I could then match against the list of glob results (or then possibly skipping glob and doing all the matching myself). But I can't find a nice way to create the regex with both the proper group captures, and escaping the rest of the input. For example, this might give me a regex that matches the locales: regex = layout % {'group': '.*', 'locale': (.*)} But to be sure the regex is valid, I need to pass it through re.escape(), which then also escapes the regex syntax I have just inserted. Calling re.escape() first ruins the format string. I know there's fnmatch.translate(), which would even give me a regex - but not one that returns the proper groups. Is there a good way to do this, without a hack like replacing the placeholders with a regex-safe unique value etc.? Is there possibly some way (a third party library perhaps?) that allows dissecting a format string in a more flexible way, for example splitting the string at the placeholder locations?

    Read the article

  • Witchcraft! Php [migrated]

    - by Steve Green
    This is madness, hoping someone can explain. $dir = getcwd(); $a = "/bla/httpdocs/ble"; $b = "/bla/httpdocs/meh"; if( ($dir == $a) || ($dir == $b) ){ $dirlist = glob("../images2/spinner/*.jpg"); }else{ $dirlist = glob("images2/spinner/*.jpg"); } works fine but $dir = getcwd(); if( ($dir == "/bla/httpdocs/ble") || ($dir == "/bla/httpdocs/meh") ){ $dirlist = glob("../images2/spinner/*.jpg"); }else{ $dirlist = glob("images2/spinner/*.jpg"); } doesn't. (By doesn't work I mean it returns false, I also tried === ) Wondered if strings were being null terminated so tried: print_r(str_split($a)); //$a has been set to the string below for this. print_r(str_split("/bla/httpdocs/ble")); they returned identical arrays Array ( [0] => / [1] => b [2] => l [3] => a [4] => / [5] => h [6] => t [7] => t [8] => p [9] => d [10] => o [11] => c [12] => s [13] => / [14] => b [15] => l [16] => e ) Array ( [0] => / [1] => b [2] => l [3] => a [4] => / [5] => h [6] => t [7] => t [8] => p [9] => d [10] => o [11] => c [12] => s [13] => / [14] => b [15] => l [16] => e ) Anyone?

    Read the article

  • "Attach to process" missing from Delphi 7's Run menu

    - by glob
    I have to resurrect an ancient Delphi 7 application, which means I have to use the D7 IDE. Upgrading the project to a more recent version of Delphi unfortunately isn't an option. My new D7 installation's Run menu is missing Attach to Process. Aside from the missing menu item, the debugger works fine (I can debug normal Delphi executables started with Run). I know D7 supported this feature (it's in the help file), so does anyone have any idea what I've missed? The installation is Delphi 7 Enterprise (Version 7.0 Build 4.453). Current Run menuitems: Run Parameters... - Step Over Trace Into Trace to next Source line Run to Cursor Run Until Return Show Execution Point Program Pause Program Reset - Evaluate/Modify Add Watch Add Breakpoint

    Read the article

  • Expanding globs in xargs

    - by Craig
    I have a directory like this mkdir test cd test touch file{0,1}.txt otherfile{0,1}.txt stuff{0,1}.txt I want to run some command such as ls on certain types of files in the directory and have the * (glob) expand to all possibilities for the filename. echo 'file otherfile' | tr ' ' '\n' | xargs -I % ls %*.txt This command does not expand the glob and tries to look for the literal 'file*.txt' How do I write a similar command that expands the globs? (I want to use xargs so the command can be run in parallel)

    Read the article

  • Memory efficient import many data files into panda DataFrame in Python

    - by richardh
    I import into a panda DataFrame a directory of |-delimited.dat files. The following code works, but I eventually run out of RAM with a MemoryError:. import pandas as pd import glob temp = [] dataDir = 'C:/users/richard/research/data/edgar/masterfiles' for dataFile in glob.glob(dataDir + '/master_*.dat'): print dataFile temp.append(pd.read_table(dataFile, delimiter='|', header=0)) masterAll = pd.concat(temp) Is there a more memory efficient approach? Or should I go whole hog to a database? (I will move to a database eventually, but I am baby stepping my move to pandas.) Thanks! FWIW, here is the head of an example .dat file: cik|cname|ftype|date|fileloc 1000032|BINCH JAMES G|4|2011-03-08|edgar/data/1000032/0001181431-11-016512.txt 1000045|NICHOLAS FINANCIAL INC|10-Q|2011-02-11|edgar/data/1000045/0001193125-11-031933.txt 1000045|NICHOLAS FINANCIAL INC|8-K|2011-01-11|edgar/data/1000045/0001193125-11-005531.txt 1000045|NICHOLAS FINANCIAL INC|8-K|2011-01-27|edgar/data/1000045/0001193125-11-015631.txt 1000045|NICHOLAS FINANCIAL INC|SC 13G/A|2011-02-14|edgar/data/1000045/0000929638-11-00151.txt

    Read the article

  • Confusing .gitignore syntax

    - by tmslnz
    I was reading http://www.kernel.org/pub/software/scm/git/docs/gitignore.html and the 6 points used to explain the ignore patterns seem to be describing a custom variant of a glob search syntax. I am more familiar with Mercurial, which allows to explicitly ignore via glob or regex patterns, no questions asked. Is there anything similar functionality in Git? Can anyone point me to some more exhaustive reference than the Git man page? Best, t

    Read the article

  • scraping text from multiple html files into a single csv file

    - by Lulu
    I have just over 1500 html pages (1.html to 1500.html). I have written a code using Beautiful Soup that extracts most of the data I need but "misses" out some of the data within the table. My Input: e.g file 1500.html My Code: #!/usr/bin/env python import glob import codecs from BeautifulSoup import BeautifulSoup with codecs.open('dump2.csv', "w", encoding="utf-8") as csvfile: for file in glob.glob('*html*'): print 'Processing', file soup = BeautifulSoup(open(file).read()) rows = soup.findAll('tr') for tr in rows: cols = tr.findAll('td') #print >> csvfile,"#".join(col.string for col in cols) #print >> csvfile,"#".join(td.find(text=True)) for col in cols: print >> csvfile, col.string print >> csvfile, "===" print >> csvfile, "***" Output: One CSV file, with 1500 lines of text and columns of data. For some reason my code does not pull out all the required data but "misses" some data, e.g the Address1 and Address 2 data at the start of the table do not come out. I modified the code to put in * and === separators, I then use perl to put into a clean csv file, unfortunately I'm not sure how to work my code to get all the data I'm looking for!

    Read the article

  • How to write this snippet in Python?

    - by morpheous
    I am learning Python (I have a C/C++ background). I need to write something practical in Python though, whilst learning. I have the following pseudocode (my first attempt at writing a Python script, since reading about Python yesterday). Hopefully, the snippet details the logic of what I want to do. BTW I am using python 2.6 on Ubuntu Karmic. Assume the script is invoked as: script_name.py directory_path import csv, sys, os, glob # Can I declare that the function accepts a dictionary as first arg? def getItemValue(item, key, defval) return !item.haskey(key) ? defval : item[key] dirname = sys.argv[1] # declare some default values here weight, is_male, default_city_id = 100, true, 1 # fetch some data from a database table into a nested dictionary, indexed by a string curr_dict = load_dict_from_db('foo') #iterate through all the files matching *.csv in the specified folder for infile in glob.glob( os.path.join(dirname, '*.csv') ): #get the file name (without the '.csv' extension) code = infile[0:-4] # open file, and iterate through the rows of the current file (a CSV file) f = open(infile, 'rt') try: reader = csv.reader(f) for row in reader: #lookup the id for the code in the dictionary id = curr_dict[code]['id'] name = row['name'] address1 = row['address1'] address2 = row['address2'] city_id = getItemValue(row, 'city_id', default_city_id) # insert row to database table finally: f.close() I have the following questions: Is the code written in a Pythonic enough way (is there a better way of implementing it)? Given a table with a schema like shown below, how may I write a Python function that fetches data from the table and returns is in a dictionary indexed by string (name). How can I insert the row data into the table (actually I would like to use a transaction if possible, and commit just before the file is closed) Table schema: create table demo (id int, name varchar(32), weight float, city_id int); BTW, my backend database is postgreSQL

    Read the article

  • How would I make this faster? Parsing Word/sorting by heading [on hold]

    - by Doof12
    Currently it takes about 3 minutes to run through a single 53 page word document. Hopefully you all have some advice about speeding up the process. Code: import win32com.client as win32 from glob import glob import io import re from collections import namedtuple from collections import defaultdict import pprint raw_files = glob('*.docx') word = win32.gencache.EnsureDispatch('Word.Application') word.Visible = False oFile = io.open("rawsort.txt", "w+", encoding = "utf-8")#text dump doccat= list() for f in raw_files: word.Documents.Open(f) doc = word.ActiveDocument #whichever document is active at the time doc.ConvertNumbersToText() print doc.Paragraphs.Count for x in xrange(1, doc.Paragraphs.Count+1):#for loop to print through paragraphs oText = doc.Paragraphs(x) if not oText.Range.Tables.Count >0 : results = re.match('(?P<number>(([1-3]*[A-D]*[0-9]*)(.[1-3]*[0-9])+))', oText.Range.Text) stylematch = re.match('Heading \d', oText.Style.NameLocal) if results!= None and oText.Style != None and stylematch != None: doccat.append((oText.Style.NameLocal, oText.Range.Text[:len(results.group('number'))],oText.Range.Text[len(results.group('number')):])) style = oText.Style.NameLocal else: if oText.Range.Font.Bold == True : doccat.append(style, oText) oFile.write(unicode(doccat)) oFile.close() The for Paragraph loop obviously takes the most amount of time. Is there some way of identifying and appending it without going through every Paragraph?

    Read the article

  • html in do_GET() method of a simple Python webserver

    - by Meeri_Peeri
    I am relatively new to Python but have been doing a lot of different things with it recently and I am liking it a lot. However, I ran into trouble/block with the following code. import http.server import socketserver import glob import random class Server(http.server.SimpleHTTPRequestHandler): def do_GET(self): self.send_response(200, 'OK') self.send_header('Content-type', 'html') self.end_headers() self.wfile.write(bytes("<html> <head><title> Hello World </title> </head> <body>", 'UTF-8')) images = glob.glob('*.jpg') rand = random.randint(0,len(images)-1) imagestring = "<img src = \"" + images[rand] + "\" height = 1028 width = 786 align = \"right\"/> </body> </html>" self.wfile.write(bytes(imagestring, 'UTF-8')) def serve_forever(port): socketserver.TCPServer(('', port), Server).serve_forever() if __name__ == "__main__": Server.serve_forever(8000) What I am trying to do here is grab a random image from multiple images in the directory and add it into the response to a web request. The code works fine but when I access the server via browser, the image is not displayed. The html of the page is as intended though. The permissions on the files are 755. Also I tried to create an index.html file in the do_GET method. That didn't work either. I mean the index.html was generated fine, but the response in the browser this time did not show anything (not even the hello world in the title). Am I missing anything very simple here? I was thinking should I overload the handle_request of the underlying SocketServer.BaseServer as the documentation says you should never override BaseHTTPServer's handle() method and should rather override the corresponding do_* method?

    Read the article

  • Qmail Installation CentosI386

    - by tike
    I was trying to install qmailtoster in my centos server, i did all of the following not for once but repetitively as i got error and continued but i felt i need some help. i did follow all the steps of this wiki documentation. http://wiki.qmailtoaster.com/index.php/CentOS_5_QmailToaster_Install#Begin_Install followed all procedure when i came in a point to install i always got this error. cnt50-install-script.sh: line 80: rpmbuild: command not found error: File not found by glob: /usr/src/redhat/RPMS/i386/daemontools-toaster*.rpm Installing ucspi-tcp-toaster . . . Shall we continue? (yes, skip, quit) [y]/s/q: cnt50-install-script.sh.4: line 90: rpmbuild: command not found error: File not found by glob: /usr/src/redhat/RPMS/i386/ucspi-tcp-toaster*.rpm Installing vpopmail-toaster . . . Shall we continue? (yes, skip, quit) [y]/s/q: any suggestions please?

    Read the article

  • Recursive function with for loop python

    - by user134743
    I have a question that should not be too hard but it has been bugging me for a long time. I am trying to write a function that searches in a directory that has different folders for all files that have the extension jpg and which size is bigger than 0. It then should print the sum of the size of the files that are in these categories. What I am doing right now is def myFuntion(myPath, fileSize): for myfile in glob.glob(myPath): if os.path.isdir(myFile): myFunction(myFile, fileSize) if (fnmatch.fnmatch(myFile, '*.jpg')): if (os.path.getsize(myFile) > 1): fileSize = fileSize + os.path.getsize(myFile) print "totalSize: " + str(fileSize) THis is not giving me the right result. It sums the sizes of the files of one directory but it does not keep suming the rest. For example if I have these paths C:/trial/trial1/trial11/pic.jpg C:/trial/trial1/trial11/pic1.jpg C:/trial/trial1/trial11/pic2.jpg and C:/trial/trial2/trial11/pic.jpg C:/trial/trial2/trial11/pic1.jpg C:/trial/trial2/trial11/pic2.jpg I will get the sum of the first three and the the size of the last 3 but I won´t get the size of the 6 together, if that makes sense. Thank you so much for your help!

    Read the article

  • Python Windows File Copy with Wildcard Support

    - by Wang Dingwei
    I've been doing this all the time: result = subprocess.call(['copy', '123*.xml', 'out_folder\\.', '/y']) if result == 0: do_something() else: do_something_else() Until today I started to look into pywin32 modules, then I saw functions like win32file.CopyFiles(), but then I found it may not support copying files to a directory. Maybe this functionality is hidden somewhere, but I haven't found it yet. I've also tried "glob" and "shutil" combination, but "glob" is incredibly slow if there are many files. So, how do you emulate this Windows command with Python? copy 123*.xml out_folder\. /y

    Read the article

  • adjust selected File to FileFilter in a JFileChooser

    - by amarillion
    I'm writing a diagram editor in java. This app has the option to export to various standard image formats such as .jpg, .png etc. When the user clicks File-Export, you get a JFileChooser which has a number of FileFilters in it, for .jpg, .png etc. Now here is my question: Is there a way to have the extension of the default adjust to the selected file filter? E.g. if the document is named "lolcat" then the default option should be "lolcat.png" when the png filter is selected, and when the user selects the jpg file filter, the default should change to "lolcat.jpg" automatically. Is this possible? How can I do it? edit: Based on the answer below, I wrote some code. But it doesn't quite work yet. I've added a propertyChangeListener to the FILE_FILTER_CHANGED_PROPERTY, but it seems that within this method getSelectedFile() returns null. Here is the code. package nl.helixsoft; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.util.ArrayList; import java.util.List; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.filechooser.FileFilter; public class JFileChooserTest { public class SimpleFileFilter extends FileFilter { private String desc; private List<String> extensions; private boolean showDirectories; /** * @param name example: "Data files" * @param glob example: "*.txt|*.csv" */ public SimpleFileFilter (String name, String globs) { extensions = new ArrayList<String>(); for (String glob : globs.split("\\|")) { if (!glob.startsWith("*.")) throw new IllegalArgumentException("expected list of globs like \"*.txt|*.csv\""); // cut off "*" // store only lower case (make comparison case insensitive) extensions.add (glob.substring(1).toLowerCase()); } desc = name + " (" + globs + ")"; } public SimpleFileFilter(String name, String globs, boolean showDirectories) { this(name, globs); this.showDirectories = showDirectories; } @Override public boolean accept(File file) { if(showDirectories && file.isDirectory()) { return true; } String fileName = file.toString().toLowerCase(); for (String extension : extensions) { if (fileName.endsWith (extension)) { return true; } } return false; } @Override public String getDescription() { return desc; } /** * @return includes '.' */ public String getFirstExtension() { return extensions.get(0); } } void export() { String documentTitle = "lolcat"; final JFileChooser jfc = new JFileChooser(); jfc.setDialogTitle("Export"); jfc.setDialogType(JFileChooser.SAVE_DIALOG); jfc.setSelectedFile(new File (documentTitle)); jfc.addChoosableFileFilter(new SimpleFileFilter("JPEG", "*.jpg")); jfc.addChoosableFileFilter(new SimpleFileFilter("PNG", "*.png")); jfc.addPropertyChangeListener(JFileChooser.FILE_FILTER_CHANGED_PROPERTY, new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent arg0) { System.out.println ("Property changed"); String extold = null; String extnew = null; if (arg0.getOldValue() == null || !(arg0.getOldValue() instanceof SimpleFileFilter)) return; if (arg0.getNewValue() == null || !(arg0.getNewValue() instanceof SimpleFileFilter)) return; SimpleFileFilter oldValue = ((SimpleFileFilter)arg0.getOldValue()); SimpleFileFilter newValue = ((SimpleFileFilter)arg0.getNewValue()); extold = oldValue.getFirstExtension(); extnew = newValue.getFirstExtension(); String filename = "" + jfc.getSelectedFile(); System.out.println ("file: " + filename + " old: " + extold + ", new: " + extnew); if (filename.endsWith(extold)) { filename.replace(extold, extnew); } else { filename += extnew; } jfc.setSelectedFile(new File (filename)); } }); jfc.showDialog(frame, "export"); } JFrame frame; void run() { frame = new JFrame(); JButton btn = new JButton ("export"); frame.add (btn); btn.addActionListener (new ActionListener() { public void actionPerformed(ActionEvent ae) { export(); } }); frame.setSize (300, 300); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { JFileChooserTest x = new JFileChooserTest(); x.run(); } }); } }

    Read the article

  • Remove empty subfolders with PHP

    - by Dmitry Letano
    I am working on a PHP function that will recursively remove all sub-folders that contain no files starting from a given absolute path. Here is the code developed so far: function RemoveEmptySubFolders($starting_from_path) { // Returns true if the folder contains no files function IsEmptyFolder($folder) { return (count(array_diff(glob($folder.DIRECTORY_SEPARATOR."*"), Array(".", ".."))) == 0); } // Cycles thorugh the subfolders of $from_path and // returns true if at least one empty folder has been removed function DoRemoveEmptyFolders($from_path) { if(IsEmptyFolder($from_path)) { rmdir($from_path); return true; } else { $Dirs = glob($from_path.DIRECTORY_SEPARATOR."*", GLOB_ONLYDIR); $ret = false; foreach($Dirs as $path) { $res = DoRemoveEmptyFolders($path); $ret = $ret ? $ret : $res; } return $ret; } } while (DoRemoveEmptyFolders($starting_from_path)) {} } As per my tests this function works, though I would be very delighted to see any ideas for better performing code.

    Read the article

  • When does ref($variable) return 'IO'?

    - by Zaid
    Here's the relevant excerpt from the documentation of the ref function: The value returned depends on the type of thing the reference is a reference to. Builtin types include: SCALAR ARRAY HASH CODE REF GLOB LVALUE FORMAT IO VSTRING Regexp Based on this, I imagined that calling ref on a filehandle would return 'IO'. Surprisingly, it doesn't: use strict; use warnings; open my $fileHandle, '<', 'aValidFile'; close $fileHandle; print ref $fileHandle; # prints 'GLOB', not 'IO' perlref tries to explain why: It isn't possible to create a true reference to an IO handle (filehandle or dirhandle) using the backslash operator. The most you can get is a reference to a typeglob, which is actually a complete symbol table entry [...] However, you can still use type globs and globrefs as though they were IO handles. In what circumstances would ref return 'IO' then?

    Read the article

< Previous Page | 1 2 3 4 5 6  | Next Page >