code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
#!/bin/sh echo "Starting thiolsTemp app" echo "Creating scanning thread" sudo hcitool -i hci0 lescan --passive --duplicates >> /dev/null & echo "Creating parser scanning thread" sudo hcidump -i ^Ci0 -R |./parser/bleParser
Slyde/thiolsTemp
thiosTemp.sh
Shell
gpl-2.0
227
#!/usr/bin/env python # Copyright (C) 2007--2016 the X-ray Polarimetry Explorer (XPE) team. # # For the license terms see the file LICENSE, distributed along with this # software. # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the # Free Software Foundation; either version 2 of the License, or (at your # option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import struct import numpy import os import logging as logger # python2/3 compatibility fix try: xrange except NameError: xrange = range # color core fror creen printout, work only on posix class ixpeAnsiColors: HEADER = '\033[95m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' # # Useful constants # XPOL_NUM_COLUMNS = 300 XPOL_NUM_ROWS = 352 XPOL_NUM_PIXELS = XPOL_NUM_COLUMNS*XPOL_NUM_ROWS # # Class for a windowed event # class ixpeEventWindowed: """Basic class representing an event aquired in windowed mode. """ HEADER_MARKER = 65535 HEADER_LENGTH = 20 def __init__(self, xmin, xmax, ymin, ymax, buffer_id, t1, t2, s1, s2, adc_values): """Constructor. """ self.xmin = xmin self.xmax = xmax self.ymin = ymin self.ymax = ymax self.buffer_id = buffer_id self.microseconds = (t1 + t2*65534)*0.8 self.adc_values = adc_values def size(self): """Return the total number of bytes in the event. """ return self.HEADER_LENGTH + 2*self.num_pixels() def num_columns(self): """Return the number of columns. """ return (self.xmax - self.xmin + 1) def num_rows(self): """Return the number of rows. """ return (self.ymax - self.ymin + 1) def num_pixels(self): """Return the total number of pixels in the window. """ return self.num_rows()*self.num_columns() def adc_value(self, col, row): """Return the pulse height for a given pixel in the window. """ return self.adc_values[col, row] def highest_pixel(self): """Return the coordinats of the pixel with the maximum value of ADC counts. """ return numpy.unravel_index(numpy.argmax(self.adc_values), self.adc_values.shape) def highest_adc_value(self): """Return the maximum value of ADC counts for the pixels in the event. """ return self.adc_values.max() def ascii(self, zero_suppression=5, max_threshold=0.75, width=4, color=True): """Return a pretty-printed ASCII representation of the event. """ if os.name != 'posix': color = False _fmt = '%%%dd' % width _max = self.highest_adc_value() text = '' text += ' '*(2*width + 2) for col in xrange(self.num_columns()): text += _fmt % (col + self.xmin) text += '\n' text += ' '*(2*width + 2) for col in xrange(self.num_columns()): text += _fmt % col text += '\n' text += ' '*(2*width + 1) + '+' + '-'*(width*self.num_columns()) + '\n' for row in xrange(self.num_rows()): text += (_fmt % (row + self.ymin)) + ' ' + (_fmt % row) + '|' for col in xrange(self.num_columns()): adc = self.adc_value(col, row) pix = _fmt % adc if color and adc == _max: pix = '%s%s%s' %\ (ixpeAnsiColors.RED, pix, ixpeAnsiColors.ENDC) elif color and adc >= max_threshold*_max: pix = '%s%s%s' %\ (ixpeAnsiColors.YELLOW, pix, ixpeAnsiColors.ENDC) elif color and adc > zero_suppression: pix = '%s%s%s' %\ (ixpeAnsiColors.GREEN, pix, ixpeAnsiColors.ENDC) text += pix text += '\n%s|\n' % (' '*(2*width + 1)) return text def draw_ascii(self, zero_suppression=5): """Print the ASCII representation of the event. """ print(self.ascii(zero_suppression)) def __str__(self): """String representation. """ text = 'buffer %5d, w(%3d, %3d)--(%3d, %3d), %d px, t = %d us' %\ (self.buffer_id, self.xmin, self.ymin, self.xmax, self.ymax, self.num_pixels(), self.microseconds) return text # # Class for a windowed file # class ixpeBinaryFileWindowed: """Binary file acquired in windowed mode. """ def __init__(self, filePath): """Constructor. """ logger.info('Opening input binary file %s...' % filePath) self.__file = open(filePath, 'rb') def seek(self, offset): """ redefine seek """ self.__file.seek(offset) def read(self, n): """ redefine read """ return self.__file.read(n) def close(self): """ redefine """ self.__file.close() def read_word(self): """Read and byte-swap a single 2-bytes binary word from file. Note that struct.unpack returns a tuple even when we read a single number, and here we're returning the first (and only) element of the tuple. """ return struct.unpack('H', self.read(2))[0] def read_words(self, num_words): """Read and byte-swap a fixed number of 2-bytes binary words from file. Args ---- num_words : int The number of words to be read from the input file. """ return struct.unpack('%dH' % num_words, self.read(2*num_words)) def read_adc_word(self): """Read and byte-swap a single 2-bytes binary word from file. Same as read word, but adc value are now signed """ return struct.unpack('h', self.read(2))[0] def read_adc_words(self, num_words): """Read and byte-swap a fixed number of 2-bytes binary words from file. Same as read_words, but adc values are now signed. Args ---- num_words : int The number of words to be read from the input file. """ return struct.unpack('%dh' % num_words, self.read(2*num_words)) def __iter__(self): """Basic iterator implementation. """ return self def next(self): """Read the next event in the file. """ try: header = self.read_word() except Exception: raise StopIteration() if header != ixpeEventWindowed.HEADER_MARKER: msg = 'Event header mismatch at byte %d' % self.tell() msg += ' (expected %s, got %s).' %\ (hex(ixpeEventWindowed.HEADER_MARKER), hex(header)) logger.error(msg) logger.info('Moving ahead to the next event header...') while header != ixpeEventWindowed.HEADER_MARKER: header = self.read_word() logger.info('Got back in synch at byte %d.' % self.tell()) xmin, xmax, ymin, ymax, buf_id, t1, t2, s1, s2 = self.read_words(9) num_columns = (xmax - xmin + 1) num_rows = (ymax - ymin + 1) data = self.read_adc_words(num_rows*num_columns) adc = numpy.array(data).reshape((num_rows, num_columns)).T return ixpeEventWindowed(xmin, xmax, ymin, ymax, buf_id, t1, t2, s1, s2, adc) if __name__ == '__main__': import argparse formatter = argparse.ArgumentDefaultsHelpFormatter parser = argparse.ArgumentParser(formatter_class=formatter) parser.add_argument('infile', type=str, help='the input binary file') parser.add_argument('-n', '--num_events', type=int, default=10, help = 'number of events to be processed') args = parser.parse_args() #test_windowed input_file = ixpeBinaryFileWindowed(args.infile) for i in xrange(args.num_events): event = input_file.next() print (event) event.draw_ascii() try: input("e2g") except NameError: raw_input("e2g")
lucabaldini/xpedaq
scripts/ixpe_evt_lib.py
Python
gpl-2.0
7,540
/** * Copyright (c) 2014 Igor Botian * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. You should have received a copy of the GNU General * Public License along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * @author Igor Botian <igor.botian@gmail.com> */ package ru.spbftu.igorbotian.phdapp.common.impl; import ru.spbftu.igorbotian.phdapp.common.*; import java.util.Objects; import java.util.Set; /** * @see ru.spbftu.igorbotian.phdapp.common.impl.AbstractInputDataImpl * @see ru.spbftu.igorbotian.phdapp.common.PointwiseInputData * @see ru.spbftu.igorbotian.phdapp.common.InputDataFactory */ class PointwiseInputDataImpl extends AbstractInputDataImpl implements PointwiseInputData { private final PointwiseTrainingSet trainingSet; public PointwiseInputDataImpl(UnclassifiedData testingSet, PointwiseTrainingSet trainingSet) throws DataException { super(testingSet); this.trainingSet = Objects.requireNonNull(trainingSet); } public Set<? extends PointwiseTrainingObject> trainingSet() { return trainingSet.objects(); } @Override public int hashCode() { return Objects.hash(super.hashCode(), trainingSet); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null || !(obj instanceof PointwiseInputDataImpl)) { return false; } PointwiseInputDataImpl other = (PointwiseInputDataImpl) obj; return super.equals(other) && trainingSet.equals(other.trainingSet); } @Override public String toString() { return String.join(";", super.toString(), trainingSet.toString()); } }
igorbotian/phdapp
input/src/main/java/ru/spbftu/igorbotian/phdapp/common/impl/PointwiseInputDataImpl.java
Java
gpl-2.0
2,247
using System.Collections.Generic; using System.IO; using System.Timers; namespace DevWilson { internal class ImageList : List<ImageFileAttributes> { private readonly string filePath; private readonly object syncRoot = new object(); private Timer saveTimer; public ImageList(string filePath) { this.filePath = filePath; } public void Load() { if (File.Exists(filePath)) { lock (syncRoot) { if (saveTimer != null) { saveTimer.Stop(); saveTimer = null; } ImageListToXml.LoadFromXml(filePath, this); } } } public void Save() { lock (syncRoot) { if (saveTimer == null || !saveTimer.Enabled) { saveTimer = new Timer(5000); saveTimer.Elapsed += saveTimer_Elapsed; saveTimer.AutoReset = false; saveTimer.Start(); } } } public List<ImageFileAttributes> Clone() { lock (syncRoot) { return new List<ImageFileAttributes>(this); } } private void saveTimer_Elapsed(object sender, ElapsedEventArgs e) { string folderPath = Path.GetDirectoryName(filePath); if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } lock (syncRoot) { ImageListToXml.SaveAsXml(filePath, this); } } } }
abmv/MetaComic
MetaComics.Client/Code/PDF/PDFImageWorks/ImageList.cs
C#
gpl-2.0
1,807
/* $Id: tif_codec.c 9734 2012-10-09 19:54:17Z andijahja $ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ #if defined(_MSC_VER) && (_MSC_VER>=1400) #if !defined(_CRT_SECURE_NO_WARNINGS) #define _CRT_SECURE_NO_WARNINGS #endif #endif /* * TIFF Library * * Builtin Compression Scheme Configuration Support. */ #include "tiffiop.h" static int NotConfigured(TIFF*, int); #ifndef LZW_SUPPORT #define TIFFInitLZW NotConfigured #endif #ifndef PACKBITS_SUPPORT #define TIFFInitPackBits NotConfigured #endif #ifndef THUNDER_SUPPORT #define TIFFInitThunderScan NotConfigured #endif #ifndef NEXT_SUPPORT #define TIFFInitNeXT NotConfigured #endif #ifndef JPEG_SUPPORT #define TIFFInitJPEG NotConfigured #endif #ifndef OJPEG_SUPPORT #define TIFFInitOJPEG NotConfigured #endif #ifndef CCITT_SUPPORT #define TIFFInitCCITTRLE NotConfigured #define TIFFInitCCITTRLEW NotConfigured #define TIFFInitCCITTFax3 NotConfigured #define TIFFInitCCITTFax4 NotConfigured #endif #ifndef JBIG_SUPPORT #define TIFFInitJBIG NotConfigured #endif #ifndef ZIP_SUPPORT #define TIFFInitZIP NotConfigured #endif #ifndef PIXARLOG_SUPPORT #define TIFFInitPixarLog NotConfigured #endif #ifndef LOGLUV_SUPPORT #define TIFFInitSGILog NotConfigured #endif #ifndef LZMA_SUPPORT #define TIFFInitLZMA NotConfigured #endif /* * Compression schemes statically built into the library. */ #ifdef VMS const TIFFCodec _TIFFBuiltinCODECS[] = { #else TIFFCodec _TIFFBuiltinCODECS[] = { #endif { "None", COMPRESSION_NONE, TIFFInitDumpMode }, { "LZW", COMPRESSION_LZW, TIFFInitLZW }, { "PackBits", COMPRESSION_PACKBITS, TIFFInitPackBits }, { "ThunderScan", COMPRESSION_THUNDERSCAN,TIFFInitThunderScan }, { "NeXT", COMPRESSION_NEXT, TIFFInitNeXT }, { "JPEG", COMPRESSION_JPEG, TIFFInitJPEG }, { "Old-style JPEG", COMPRESSION_OJPEG, TIFFInitOJPEG }, { "CCITT RLE", COMPRESSION_CCITTRLE, TIFFInitCCITTRLE }, { "CCITT RLE/W", COMPRESSION_CCITTRLEW, TIFFInitCCITTRLEW }, { "CCITT Group 3", COMPRESSION_CCITTFAX3, TIFFInitCCITTFax3 }, { "CCITT Group 4", COMPRESSION_CCITTFAX4, TIFFInitCCITTFax4 }, { "ISO JBIG", COMPRESSION_JBIG, TIFFInitJBIG }, { "Deflate", COMPRESSION_DEFLATE, TIFFInitZIP }, { "AdobeDeflate", COMPRESSION_ADOBE_DEFLATE , TIFFInitZIP }, { "PixarLog", COMPRESSION_PIXARLOG, TIFFInitPixarLog }, { "SGILog", COMPRESSION_SGILOG, TIFFInitSGILog }, { "SGILog24", COMPRESSION_SGILOG24, TIFFInitSGILog }, { "LZMA", COMPRESSION_LZMA, TIFFInitLZMA }, { NULL, 0, NULL } }; static int _notConfigured(TIFF* tif) { const TIFFCodec* c = TIFFFindCODEC(tif->tif_dir.td_compression); char compression_code[20]; sprintf( compression_code, "%d", tif->tif_dir.td_compression ); TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "%s compression support is not configured", c ? c->name : compression_code ); return (0); } static int NotConfigured(TIFF* tif, int scheme) { (void) scheme; tif->tif_fixuptags = _notConfigured; tif->tif_decodestatus = FALSE; tif->tif_setupdecode = _notConfigured; tif->tif_encodestatus = FALSE; tif->tif_setupencode = _notConfigured; return (1); } /************************************************************************/ /* TIFFIsCODECConfigured() */ /************************************************************************/ /** * Check whether we have working codec for the specific coding scheme. * * @return returns 1 if the codec is configured and working. Otherwise * 0 will be returned. */ int TIFFIsCODECConfigured(uint16 scheme) { const TIFFCodec* codec = TIFFFindCODEC(scheme); if(codec == NULL) { return 0; } if(codec->init == NULL) { return 0; } if(codec->init != NotConfigured){ return 1; } return 0; } /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
xharbour/core
contrib/tiff/tif_codec.c
C
gpl-2.0
5,128
/* Copyright (C) 2009 The PARI group. This file is part of the PARI/GP package. PARI/GP is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation. It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY WHATSOEVER. Check the License for details. You should have received a copy of it, along with the package; see the file 'COPYING'. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /* Originally written by Vasili Burdo */ #include "pwinver.h" #include <windows.h> #include <stdio.h> #include "mingw.h" static const char * pariwin32_basedir = NULL; const char* win32_basedir(void) { if (pariwin32_basedir) return pariwin32_basedir; else { char basedir[1024]; char* slash; GetModuleFileNameA(0, basedir, sizeof(basedir) ); slash = strrchr(basedir, '\\'); if (slash) slash[1] = 0; pariwin32_basedir = strdup(basedir); return pariwin32_basedir; } } char* win32_datadir(void) { char datadir[1029]; const char * basedir = win32_basedir(); sprintf(datadir, "%sdata",basedir); return strdup(datadir); } static WORD win32_console_color(unsigned long c) { int shift, intense = 0; if( c >= 30 && c <= 37 ) { shift = 0; c -= 30; } else if( c >= 40 && c <= 47 ) { shift = 4; c -= 40; } else if( c >= 90 && c <= 97 ) { shift = 0; intense = 8; c -= 90; } else if(c >= 100 && c <= 107) { shift = 4; intense = 8; c -= 100; } else return 0; WORD w = 0; switch(c) { case 0: w = 0; break; /* black */ case 1: w = 4; break; /* red */ case 2: w = 2; break; /* green */ case 3: w = 6; break; /* yellow RG */ case 4: w = 1; break; /* blue */ case 5: w = 5; break; /* magenta RB */ case 6: w = 3; break; /* cyan GB */ case 7: w = 7; break; /* white RGB */ } return (w|intense) << shift; } void win32_ansi_fputs(const char* s, void* f) { WORD color; unsigned long c[3]; long nbarg; if( !(f == stdout || f == stderr) ) { fputs(s,f); return; } while(1) { char *p; p = strstr(s, "\x1b["); if( p > s ) fwrite(s,p-s,1,f); if( p ) p += 2; else { fputs(s,f); return; } nbarg = 0; c[nbarg++] = strtoul(p,&p,10); if( *p == ';' ) c[nbarg++] = strtoul(p+1,&p,10); if( *p == ';' ) c[nbarg++] = strtoul(p+1,&p,10); if( *p++ == 'm' ) { switch(nbarg) { case 1: color = 7; break; case 2: color = win32_console_color(c[1]); if (c[0]&4) color |= 0x8000; break; case 3: color = win32_console_color(c[1]) | win32_console_color(c[2]); if (c[0]&4) color |= 0x8000; } fflush(f); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),color); } s = p; } } int win32_terminal_width(void) { CONSOLE_SCREEN_BUFFER_INFO sbi; if (!GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &sbi)) return 0; return sbi.srWindow.Right - sbi.srWindow.Left + 1; } int win32_terminal_height(void) { CONSOLE_SCREEN_BUFFER_INFO sbi; if (!GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &sbi)) return 0; return sbi.srWindow.Bottom - sbi.srWindow.Top + 1; } void win32_set_pdf_viewer(void) { char *s = getenv("GP_PDF_VIEWER"); if (!s) { HKEY handle; const char *key = "AcroExch.Document\\shell\\open\\command"; const long SZ = 512; char str[SZ], *buf; int status; DWORD L = SZ; (void)RegOpenKeyEx(HKEY_CLASSES_ROOT, key, 0, KEY_READ, &handle); status = RegQueryValueEx(handle, NULL, 0, NULL, (LPBYTE)str, &L); RegCloseKey(handle); if (status) return; buf = malloc(strlen(str)+16); /*must not be freed*/ sprintf(buf,"GP_PDF_VIEWER=%s",str); putenv(buf); } } extern int win32ctrlc, win32alrm; static HANDLE hTimerQueue = NULL; static void CALLBACK win32_cb_alarm(void *lpParam, BOOLEAN TimerOrWaitFired) { (void) lpParam; (void) TimerOrWaitFired; win32ctrlc++; win32alrm = 1; } void win32_alarm(unsigned int s) { if (hTimerQueue) { HANDLE oldhTimerQueue = hTimerQueue; hTimerQueue = NULL; DeleteTimerQueue(oldhTimerQueue); } if (s) { void *arg = NULL; HANDLE hTimer = NULL; hTimerQueue = CreateTimerQueue(); CreateTimerQueueTimer( &hTimer, hTimerQueue, (WAITORTIMERCALLBACK)win32_cb_alarm, &arg , s*1000, 0, 0); } } #define WIN32_FILETIME_PER_MILLISECOND 10000 long win32_timer(void) { FILETIME lpCreation, lpExit, lpKernel, lpUser; LARGE_INTEGER time; GetProcessTimes( GetCurrentProcess(), &lpCreation, &lpExit, &lpKernel, &lpUser ); time.HighPart = lpUser.dwHighDateTime; time.LowPart = lpUser.dwLowDateTime; time.QuadPart /= WIN32_FILETIME_PER_MILLISECOND; return time.LowPart; } long win32_nbthreads(void) { SYSTEM_INFO system_info; GetSystemInfo(&system_info); return system_info.dwNumberOfProcessors; }
jpflori/pari
src/systems/mingw/mingw.c
C
gpl-2.0
5,045
<?php // src/Acme/DemoBundle/Tests/Utility/CalculatorTest.php namespace FL\CoreBundle\Tests\Utility; use FL\CoreBundle\Utility\Calculator; class CalculatorTest extends \PHPUnit_Framework_TestCase { public function testAdd() { $calc = new Calculator(); $result = $calc->add(30, 12); // vérifie que votre classe a correctement calculé! $this->assertEquals(42, $result); } }
flabastie/memoword
src/FL/CoreBundle/Tests/Utility/CalculatorTest.php
PHP
gpl-2.0
421
/* Copyright (c) 2012, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/init.h> #include <linux/platform_device.h> #include <mach/kgsl.h> #include <mach/msm_bus_board.h> #include <mach/board.h> #include <mach/msm_dcvs.h> #include <mach/socinfo.h> #include "devices.h" #include "board-8064.h" #ifdef CONFIG_MSM_DCVS static struct msm_dcvs_freq_entry grp3d_freq[] = { {0, 900, 0, 0, 0}, {0, 950, 0, 0, 0}, {0, 950, 0, 0, 0}, {0, 1200, 1, 100, 100}, }; static struct msm_dcvs_core_info grp3d_core_info = { .freq_tbl = &grp3d_freq[0], .num_cores = 1, .sensors = (int[]){0}, .thermal_poll_ms = 60000, .core_param = { .core_type = MSM_DCVS_CORE_TYPE_GPU, }, .algo_param = { .disable_pc_threshold = 0, .em_win_size_min_us = 100000, .em_win_size_max_us = 300000, .em_max_util_pct = 97, .group_id = 0, .max_freq_chg_time_us = 100000, .slack_mode_dynamic = 0, .slack_time_min_us = 39000, .slack_time_max_us = 39000, .ss_win_size_min_us = 1000000, .ss_win_size_max_us = 1000000, .ss_util_pct = 95, .ss_no_corr_below_freq = 0, }, .energy_coeffs = { .leakage_coeff_a = -17720, .leakage_coeff_b = 37, .leakage_coeff_c = 3329, .leakage_coeff_d = -277, .active_coeff_a = 2492, .active_coeff_b = 0, .active_coeff_c = 0 }, .power_param = { .current_temp = 25, .num_freq = ARRAY_SIZE(grp3d_freq), } }; #endif /* CONFIG_MSM_DCVS */ #ifdef CONFIG_MSM_BUS_SCALING static struct msm_bus_vectors grp3d_init_vectors[] = { { .src = MSM_BUS_MASTER_GRAPHICS_3D, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 0, .ib = 0, }, { .src = MSM_BUS_MASTER_GRAPHICS_3D_PORT1, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 0, .ib = 0, }, }; static struct msm_bus_vectors grp3d_low_vectors[] = { { .src = MSM_BUS_MASTER_GRAPHICS_3D, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 0, .ib = KGSL_CONVERT_TO_MBPS(1700), }, { .src = MSM_BUS_MASTER_GRAPHICS_3D_PORT1, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 0, .ib = KGSL_CONVERT_TO_MBPS(1700), }, }; static struct msm_bus_vectors grp3d_nominal_low_vectors[] = { { .src = MSM_BUS_MASTER_GRAPHICS_3D, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 0, .ib = KGSL_CONVERT_TO_MBPS(2000), }, { .src = MSM_BUS_MASTER_GRAPHICS_3D_PORT1, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 0, .ib = KGSL_CONVERT_TO_MBPS(2000), }, }; #ifdef CONFIG_GPU_OVERCLOCK static struct msm_bus_vectors grp3d_nominal_high_vectors[] = { { .src = MSM_BUS_MASTER_GRAPHICS_3D, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 0, .ib = KGSL_CONVERT_TO_MBPS(3200), }, { .src = MSM_BUS_MASTER_GRAPHICS_3D_PORT1, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 0, .ib = KGSL_CONVERT_TO_MBPS(3200), }, }; static struct msm_bus_vectors grp3d_max_vectors[] = { { .src = MSM_BUS_MASTER_GRAPHICS_3D, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 0, .ib = KGSL_CONVERT_TO_MBPS(4660), }, { .src = MSM_BUS_MASTER_GRAPHICS_3D_PORT1, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 0, .ib = KGSL_CONVERT_TO_MBPS(4660), }, }; #else static struct msm_bus_vectors grp3d_nominal_high_vectors[] = { { .src = MSM_BUS_MASTER_GRAPHICS_3D, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 0, .ib = KGSL_CONVERT_TO_MBPS(2656), }, { .src = MSM_BUS_MASTER_GRAPHICS_3D_PORT1, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 0, .ib = KGSL_CONVERT_TO_MBPS(2656), }, }; static struct msm_bus_vectors grp3d_max_vectors[] = { { .src = MSM_BUS_MASTER_GRAPHICS_3D, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 0, .ib = KGSL_CONVERT_TO_MBPS(4264), }, { .src = MSM_BUS_MASTER_GRAPHICS_3D_PORT1, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 0, .ib = KGSL_CONVERT_TO_MBPS(4264), }, }; #endif static struct msm_bus_paths grp3d_bus_scale_usecases[] = { { ARRAY_SIZE(grp3d_init_vectors), grp3d_init_vectors, }, { ARRAY_SIZE(grp3d_low_vectors), grp3d_low_vectors, }, { ARRAY_SIZE(grp3d_nominal_low_vectors), grp3d_nominal_low_vectors, }, { ARRAY_SIZE(grp3d_nominal_high_vectors), grp3d_nominal_high_vectors, }, { ARRAY_SIZE(grp3d_max_vectors), grp3d_max_vectors, }, }; static struct msm_bus_scale_pdata grp3d_bus_scale_pdata = { grp3d_bus_scale_usecases, ARRAY_SIZE(grp3d_bus_scale_usecases), .name = "grp3d", }; #endif static struct resource kgsl_3d0_resources[] = { { .name = KGSL_3D0_REG_MEMORY, .start = 0x04300000, /* GFX3D address */ .end = 0x0430ffff, .flags = IORESOURCE_MEM, }, { .name = KGSL_3D0_SHADER_MEMORY, .start = 0x04310000, /* Shader Mem Address */ .end = 0x0431ffff, .flags = IORESOURCE_MEM, }, { .name = KGSL_3D0_IRQ, .start = GFX3D_IRQ, .end = GFX3D_IRQ, .flags = IORESOURCE_IRQ, }, }; static const struct kgsl_iommu_ctx kgsl_3d0_iommu0_ctxs[] = { { "gfx3d_user", 0 }, { "gfx3d_priv", 1 }, }; static const struct kgsl_iommu_ctx kgsl_3d0_iommu1_ctxs[] = { { "gfx3d1_user", 0 }, { "gfx3d1_priv", 1 }, }; static struct kgsl_device_iommu_data kgsl_3d0_iommu_data[] = { { .iommu_ctxs = kgsl_3d0_iommu0_ctxs, .iommu_ctx_count = ARRAY_SIZE(kgsl_3d0_iommu0_ctxs), .physstart = 0x07C00000, .physend = 0x07C00000 + SZ_1M - 1, }, { .iommu_ctxs = kgsl_3d0_iommu1_ctxs, .iommu_ctx_count = ARRAY_SIZE(kgsl_3d0_iommu1_ctxs), .physstart = 0x07D00000, .physend = 0x07D00000 + SZ_1M - 1, }, }; static struct kgsl_device_platform_data kgsl_3d0_pdata = { .pwrlevel = { #ifdef CONFIG_GPU_OVERCLOCK { .gpu_freq = 600000000, .bus_freq = 4, .io_fraction = 0, }, { .gpu_freq = 360000000, .bus_freq = 3, .io_fraction = 25, }, #else { .gpu_freq = 400000000, .bus_freq = 4, .io_fraction = 0, }, { .gpu_freq = 320000000, .bus_freq = 3, .io_fraction = 33, }, #endif { .gpu_freq = 200000000, .bus_freq = 2, .io_fraction = 100, }, { .gpu_freq = 128000000, .bus_freq = 1, .io_fraction = 100, }, { .gpu_freq = 27000000, .bus_freq = 0, }, }, .init_level = 1, .num_levels = 5, .set_grp_async = NULL, .idle_timeout = HZ/10, .nap_allowed = true, .strtstp_sleepwake = false, .clk_map = KGSL_CLK_CORE | KGSL_CLK_IFACE | KGSL_CLK_MEM_IFACE, #ifdef CONFIG_MSM_BUS_SCALING .bus_scale_table = &grp3d_bus_scale_pdata, #endif .iommu_data = kgsl_3d0_iommu_data, .iommu_count = ARRAY_SIZE(kgsl_3d0_iommu_data), #ifdef CONFIG_MSM_DCVS .core_info = &grp3d_core_info, #endif }; struct platform_device device_kgsl_3d0 = { .name = "kgsl-3d0", .id = 0, .num_resources = ARRAY_SIZE(kgsl_3d0_resources), .resource = kgsl_3d0_resources, .dev = { .platform_data = &kgsl_3d0_pdata, }, }; void __init apq8064_init_gpu(void) { unsigned int version = socinfo_get_version(); #ifndef CONFIG_GPU_OVERCLOCK if (cpu_is_apq8064ab()) kgsl_3d0_pdata.pwrlevel[0].gpu_freq = 450000000; #endif if (SOCINFO_VERSION_MAJOR(version) == 2) { kgsl_3d0_pdata.chipid = ADRENO_CHIPID(3, 2, 0, 2); } else { if ((SOCINFO_VERSION_MAJOR(version) == 1) && (SOCINFO_VERSION_MINOR(version) == 1)) kgsl_3d0_pdata.chipid = ADRENO_CHIPID(3, 2, 0, 1); else kgsl_3d0_pdata.chipid = ADRENO_CHIPID(3, 2, 0, 0); } platform_device_register(&device_kgsl_3d0); }
NamelessRom/android_kernel_samsung_jf
arch/arm/mach-msm/board-8064-gpu.c
C
gpl-2.0
7,505
/* Copyright (c) 2011, Code Aurora Forum. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/cpu.h> #include <linux/smp.h> #include "acpuclock.h" static struct acpuclk_data *acpuclk_data; int init_done = 0; unsigned long acpuclk_get_rate(int cpu) { if (!init_done) return 0; if (!acpuclk_data || !acpuclk_data->get_rate) return 0; return acpuclk_data->get_rate(cpu); } int acpuclk_set_rate(int cpu, unsigned long rate, enum setrate_reason reason) { if (!acpuclk_data || !acpuclk_data->set_rate) return 0; return acpuclk_data->set_rate(cpu, rate, reason); } uint32_t acpuclk_get_switch_time(void) { if (!acpuclk_data) return 0; return acpuclk_data->switch_time_us; } unsigned long acpuclk_power_collapse(void) { unsigned long rate = acpuclk_get_rate(smp_processor_id()); acpuclk_set_rate(smp_processor_id(), acpuclk_data->power_collapse_khz, SETRATE_PC); return rate; } unsigned long acpuclk_wait_for_irq(void) { unsigned long rate = acpuclk_get_rate(smp_processor_id()); acpuclk_set_rate(smp_processor_id(), acpuclk_data->wait_for_irq_khz, SETRATE_SWFI); return rate; } void __devinit acpuclk_register(struct acpuclk_data *data) { init_done = 1; acpuclk_data = data; }
BrateloSlava/SaveEnergy-3
arch/arm/mach-msm/acpuclock.c
C
gpl-2.0
1,660
showWord(["pr.","Lan, anndan. Ti moun yo t ap jwe nan dlo a." ])
georgejhunt/HaitiDictionary.activity
data/words/nan.js
JavaScript
gpl-2.0
64
/* * linux/drivers/mmc/host/msm_sdcc.c - Qualcomm MSM 7X00A SDCC Driver * * Copyright (C) 2007 Google Inc, * Copyright (C) 2003 Deep Blue Solutions, Ltd, All Rights Reserved. * Copyright (c) 2009-2010, Code Aurora Forum. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * Based on mmci.c * * Author: San Mehat (san@android.com) * */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/init.h> #include <linux/ioport.h> #include <linux/device.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/delay.h> #include <linux/err.h> #include <linux/highmem.h> #include <linux/log2.h> #include <linux/mmc/host.h> #include <linux/mmc/card.h> #include <linux/mmc/mmc.h> #include <linux/mmc/sdio.h> #include <linux/clk.h> #include <linux/scatterlist.h> #include <linux/platform_device.h> #include <linux/dma-mapping.h> #include <linux/debugfs.h> #include <linux/io.h> #include <linux/memory.h> #include <linux/wakelock.h> #include <asm/cacheflush.h> #include <asm/div64.h> #include <asm/sizes.h> #include <asm/mach/mmc.h> #include <mach/msm_iomap.h> #include <mach/clk.h> #include <mach/dma.h> #include <mach/htc_pwrsink.h> #include <linux/miscdevice.h> #include "msm_sdcc.h" #define DRIVER_NAME "msm-sdcc" #define DBG(host, fmt, args...) \ pr_debug("%s: %s: " fmt "\n", mmc_hostname(host->mmc), __func__ , args) #define IRQ_DEBUG 0 #if defined(CONFIG_DEBUG_FS) static void msmsdcc_dbg_createhost(struct msmsdcc_host *); static struct dentry *debugfs_dir; static struct dentry *debugfs_file; static int msmsdcc_dbg_init(void); #endif #ifdef CONFIG_MMC_AUTO_SUSPEND static int msmsdcc_auto_suspend(struct mmc_host *, int); #endif static unsigned int msmsdcc_pwrsave = 1; struct msmsdcc_host *wifi_host = NULL; struct platform_device * wifi_host_dev = NULL; #define DUMMY_52_STATE_NONE 0 #define DUMMY_52_STATE_SENT 1 static struct mmc_command dummy52cmd; static struct mmc_request dummy52mrq = { .cmd = &dummy52cmd, .data = NULL, .stop = NULL, }; static struct mmc_command dummy52cmd = { .opcode = SD_IO_RW_DIRECT, .flags = MMC_RSP_PRESENT, .data = NULL, .mrq = &dummy52mrq, }; #define VERBOSE_COMMAND_TIMEOUTS 0 #if IRQ_DEBUG == 1 static char *irq_status_bits[] = { "cmdcrcfail", "datcrcfail", "cmdtimeout", "dattimeout", "txunderrun", "rxoverrun", "cmdrespend", "cmdsent", "dataend", NULL, "datablkend", "cmdactive", "txactive", "rxactive", "txhalfempty", "rxhalffull", "txfifofull", "rxfifofull", "txfifoempty", "rxfifoempty", "txdataavlbl", "rxdataavlbl", "sdiointr", "progdone", "atacmdcompl", "sdiointrope", "ccstimeout", NULL, NULL, NULL, NULL, NULL }; static void msmsdcc_print_status(struct msmsdcc_host *host, char *hdr, uint32_t status) { int i; pr_debug("%s-%s ", mmc_hostname(host->mmc), hdr); for (i = 0; i < 32; i++) { if (status & (1 << i)) pr_debug("%s ", irq_status_bits[i]); } pr_debug("\n"); } #endif static void msmsdcc_start_command(struct msmsdcc_host *host, struct mmc_command *cmd, u32 c); static void msmsdcc_reset_and_restore(struct msmsdcc_host *host) { u32 mci_clk = 0; u32 mci_mask0 = 0; int ret; /* Save the controller state */ mci_clk = readl(host->base + MMCICLOCK); mci_mask0 = readl(host->base + MMCIMASK0); /* Reset the controller */ ret = clk_reset(host->clk, CLK_RESET_ASSERT); if (ret) pr_err("%s: Clock assert failed at %u Hz with err %d\n", mmc_hostname(host->mmc), host->clk_rate, ret); ret = clk_reset(host->clk, CLK_RESET_DEASSERT); if (ret) pr_err("%s: Clock deassert failed at %u Hz with err %d\n", mmc_hostname(host->mmc), host->clk_rate, ret); pr_info("%s: Controller has been reset\n", mmc_hostname(host->mmc)); /* Restore the contoller state */ writel(host->pwr, host->base + MMCIPOWER); writel(mci_clk, host->base + MMCICLOCK); writel(mci_mask0, host->base + MMCIMASK0); ret = clk_set_rate(host->clk, host->clk_rate); if (ret) pr_err("%s: Failed to set clk rate %u Hz. err %d\n", mmc_hostname(host->mmc), host->clk_rate, ret); } static int msmsdcc_request_end(struct msmsdcc_host *host, struct mmc_request *mrq) { int retval = 0; BUG_ON(host->curr.data); host->curr.mrq = NULL; host->curr.cmd = NULL; if (mrq->data) mrq->data->bytes_xfered = host->curr.data_xfered; if (mrq->cmd->error == -ETIMEDOUT) mdelay(5); #ifdef CONFIG_MMC_MSM_PROG_DONE_SCAN if ((mrq->cmd->opcode == SD_IO_RW_EXTENDED) && (mrq->cmd->arg & 0x80000000)) { /* If its a write and a cmd53 set the prog_scan flag. */ host->prog_scan = 1; /* Send STOP to let the SDCC know to stop. */ writel(MCI_CSPM_MCIABORT, host->base + MMCICOMMAND); retval = 1; } if (mrq->cmd->opcode == SD_IO_RW_DIRECT) { /* Ok the cmd52 following a cmd53 is received */ /* clear all the flags. */ host->prog_scan = 0; host->prog_enable = 0; } #endif /* * Need to drop the host lock here; mmc_request_done may call * back into the driver... */ spin_unlock(&host->lock); mmc_request_done(host->mmc, mrq); spin_lock(&host->lock); return retval; } static void msmsdcc_stop_data(struct msmsdcc_host *host) { host->curr.data = NULL; host->curr.got_dataend = 0; } static inline uint32_t msmsdcc_fifo_addr(struct msmsdcc_host *host) { return host->memres->start + MMCIFIFO; } static inline void msmsdcc_delay(struct msmsdcc_host *host) { if(host->mmc->index == 0) udelay(10 + ((3 * USEC_PER_SEC) / (host->clk_rate ? host->clk_rate : host->plat->msmsdcc_fmin))); else udelay(1 + ((3 * USEC_PER_SEC) / (host->clk_rate ? host->clk_rate : host->plat->msmsdcc_fmin))); } static inline void msmsdcc_start_command_exec(struct msmsdcc_host *host, u32 arg, u32 c) { writel(arg, host->base + MMCIARGUMENT); msmsdcc_delay(host); writel(c, host->base + MMCICOMMAND); } static void msmsdcc_dma_exec_func(struct msm_dmov_cmd *cmd) { struct msmsdcc_host *host = (struct msmsdcc_host *)cmd->user; writel(host->cmd_timeout, host->base + MMCIDATATIMER); writel((unsigned int)host->curr.xfer_size, host->base + MMCIDATALENGTH); writel((readl(host->base + MMCIMASK0) & (~(MCI_IRQ_PIO))) | host->cmd_pio_irqmask, host->base + MMCIMASK0); msmsdcc_delay(host); /* Allow data parms to be applied */ writel(host->cmd_datactrl, host->base + MMCIDATACTRL); msmsdcc_delay(host); /* Force delay prior to ADM or command */ if (host->cmd_cmd) { msmsdcc_start_command_exec(host, (u32)host->cmd_cmd->arg, (u32)host->cmd_c); } } static void msmsdcc_dma_complete_tlet(unsigned long data) { struct msmsdcc_host *host = (struct msmsdcc_host *)data; unsigned long flags; struct mmc_request *mrq; spin_lock_irqsave(&host->lock, flags); mrq = host->curr.mrq; BUG_ON(!mrq); if (!(host->dma.result & DMOV_RSLT_VALID)) { pr_err("msmsdcc: Invalid DataMover result\n"); goto out; } if (host->dma.result & DMOV_RSLT_DONE) { host->curr.data_xfered = host->curr.xfer_size; } else { /* Error or flush */ if (host->dma.result & DMOV_RSLT_ERROR) pr_err("%s: DMA error (0x%.8x)\n", mmc_hostname(host->mmc), host->dma.result); if (host->dma.result & DMOV_RSLT_FLUSH) pr_err("%s: DMA channel flushed (0x%.8x)\n", mmc_hostname(host->mmc), host->dma.result); if (host->dma.err) { pr_err("Flush data: %.8x %.8x %.8x %.8x %.8x %.8x\n", host->dma.err->flush[0], host->dma.err->flush[1], host->dma.err->flush[2], host->dma.err->flush[3], host->dma.err->flush[4], host->dma.err->flush[5]); msmsdcc_reset_and_restore(host); } if (!mrq->data->error) mrq->data->error = -EIO; } dma_unmap_sg(mmc_dev(host->mmc), host->dma.sg, host->dma.num_ents, host->dma.dir); if (host->curr.user_pages) { struct scatterlist *sg = host->dma.sg; int i; for (i = 0; i < host->dma.num_ents; i++, sg++) flush_dcache_page(sg_page(sg)); } host->dma.sg = NULL; host->dma.busy = 0; if (host->curr.got_dataend || mrq->data->error) { if (mrq->data->error && !(host->curr.got_dataend)) { pr_info("%s: Worked around bug 1535304\n", mmc_hostname(host->mmc)); } /* * If we've already gotten our DATAEND / DATABLKEND * for this request, then complete it through here. */ msmsdcc_stop_data(host); if (!mrq->data->error) host->curr.data_xfered = host->curr.xfer_size; if (!mrq->data->stop || mrq->cmd->error) { host->curr.mrq = NULL; host->curr.cmd = NULL; mrq->data->bytes_xfered = host->curr.data_xfered; spin_unlock_irqrestore(&host->lock, flags); #ifdef CONFIG_MMC_MSM_PROG_DONE_SCAN if ((mrq->cmd->opcode == SD_IO_RW_EXTENDED) && (mrq->cmd->arg & 0x80000000)) { /* set the prog_scan in a cmd53.*/ host->prog_scan = 1; /* Send STOP to let the SDCC know to stop. */ writel(MCI_CSPM_MCIABORT, host->base + MMCICOMMAND); } #endif mmc_request_done(host->mmc, mrq); return; } else msmsdcc_start_command(host, mrq->data->stop, 0); } out: spin_unlock_irqrestore(&host->lock, flags); return; } static void msmsdcc_dma_complete_func(struct msm_dmov_cmd *cmd, unsigned int result, struct msm_dmov_errdata *err) { struct msmsdcc_dma_data *dma_data = container_of(cmd, struct msmsdcc_dma_data, hdr); struct msmsdcc_host *host = dma_data->host; dma_data->result = result; dma_data->err = err; tasklet_schedule(&host->dma_tlet); } static int validate_dma(struct msmsdcc_host *host, struct mmc_data *data) { if (host->dma.channel == -1) return -ENOENT; if ((data->blksz * data->blocks) < MCI_FIFOSIZE) return -EINVAL; if ((data->blksz * data->blocks) % MCI_FIFOSIZE) return -EINVAL; return 0; } static int msmsdcc_config_dma(struct msmsdcc_host *host, struct mmc_data *data) { struct msmsdcc_nc_dmadata *nc; dmov_box *box; uint32_t rows; uint32_t crci; unsigned int n; int i, rc; struct scatterlist *sg = data->sg; rc = validate_dma(host, data); if (rc) return rc; host->dma.sg = data->sg; host->dma.num_ents = data->sg_len; BUG_ON(host->dma.num_ents > NR_SG); /* Prevent memory corruption */ nc = host->dma.nc; if (host->pdev_id == 1) crci = DMOV_SDC1_CRCI; else if (host->pdev_id == 2) crci = DMOV_SDC2_CRCI; else if (host->pdev_id == 3) crci = DMOV_SDC3_CRCI; else if (host->pdev_id == 4) crci = DMOV_SDC4_CRCI; #ifdef DMOV_SDC5_CRCI else if (host->pdev_id == 5) crci = DMOV_SDC5_CRCI; #endif else { host->dma.sg = NULL; host->dma.num_ents = 0; return -ENOENT; } if (data->flags & MMC_DATA_READ) host->dma.dir = DMA_FROM_DEVICE; else host->dma.dir = DMA_TO_DEVICE; /* host->curr.user_pages = (data->flags & MMC_DATA_USERPAGE); */ host->curr.user_pages = 0; box = &nc->cmd[0]; for (i = 0; i < host->dma.num_ents; i++) { box->cmd = CMD_MODE_BOX; /* Initialize sg dma address */ sg->dma_address = page_to_dma(mmc_dev(host->mmc), sg_page(sg)) + sg->offset; if (i == (host->dma.num_ents - 1)) box->cmd |= CMD_LC; rows = (sg_dma_len(sg) % MCI_FIFOSIZE) ? (sg_dma_len(sg) / MCI_FIFOSIZE) + 1 : (sg_dma_len(sg) / MCI_FIFOSIZE) ; if (data->flags & MMC_DATA_READ) { box->src_row_addr = msmsdcc_fifo_addr(host); box->dst_row_addr = sg_dma_address(sg); box->src_dst_len = (MCI_FIFOSIZE << 16) | (MCI_FIFOSIZE); box->row_offset = MCI_FIFOSIZE; box->num_rows = rows * ((1 << 16) + 1); box->cmd |= CMD_SRC_CRCI(crci); } else { box->src_row_addr = sg_dma_address(sg); box->dst_row_addr = msmsdcc_fifo_addr(host); box->src_dst_len = (MCI_FIFOSIZE << 16) | (MCI_FIFOSIZE); box->row_offset = (MCI_FIFOSIZE << 16); box->num_rows = rows * ((1 << 16) + 1); box->cmd |= CMD_DST_CRCI(crci); } box++; sg++; } /* location of command block must be 64 bit aligned */ BUG_ON(host->dma.cmd_busaddr & 0x07); nc->cmdptr = (host->dma.cmd_busaddr >> 3) | CMD_PTR_LP; host->dma.hdr.cmdptr = DMOV_CMD_PTR_LIST | DMOV_CMD_ADDR(host->dma.cmdptr_busaddr); host->dma.hdr.complete_func = msmsdcc_dma_complete_func; host->dma.hdr.crci_mask = msm_dmov_build_crci_mask(1, crci); n = dma_map_sg(mmc_dev(host->mmc), host->dma.sg, host->dma.num_ents, host->dma.dir); /* dsb inside dma_map_sg will write nc out to mem as well */ if (n != host->dma.num_ents) { pr_err("%s: Unable to map in all sg elements\n", mmc_hostname(host->mmc)); host->dma.sg = NULL; host->dma.num_ents = 0; return -ENOMEM; } return 0; } static void msmsdcc_start_command_deferred(struct msmsdcc_host *host, struct mmc_command *cmd, u32 *c) { DBG(host, "op %02x arg %08x flags %08x\n", cmd->opcode, cmd->arg, cmd->flags); *c |= (cmd->opcode | MCI_CPSM_ENABLE); if (cmd->flags & MMC_RSP_PRESENT) { if (cmd->flags & MMC_RSP_136) *c |= MCI_CPSM_LONGRSP; *c |= MCI_CPSM_RESPONSE; } if (/*interrupt*/0) *c |= MCI_CPSM_INTERRUPT; if ((((cmd->opcode == 17) || (cmd->opcode == 18)) || ((cmd->opcode == 24) || (cmd->opcode == 25))) || (cmd->opcode == 53)) *c |= MCI_CSPM_DATCMD; if (host->prog_scan && (cmd->opcode == 12)) { *c |= MCI_CPSM_PROGENA; host->prog_enable = 1; } #ifdef CONFIG_MMC_MSM_PROG_DONE_SCAN if ((cmd->opcode == SD_IO_RW_DIRECT) && (host->prog_scan == 1)) { *c |= MCI_CPSM_PROGENA; host->prog_enable = 1; } #endif if (cmd == cmd->mrq->stop) *c |= MCI_CSPM_MCIABORT; if (host->curr.cmd != NULL) { pr_err("%s: Overlapping command requests\n", mmc_hostname(host->mmc)); } host->curr.cmd = cmd; } static void msmsdcc_start_data(struct msmsdcc_host *host, struct mmc_data *data, struct mmc_command *cmd, u32 c) { unsigned int datactrl, timeout; unsigned long long clks; void __iomem *base = host->base; unsigned int pio_irqmask = 0; host->curr.data = data; host->curr.xfer_size = data->blksz * data->blocks; host->curr.xfer_remain = host->curr.xfer_size; host->curr.data_xfered = 0; host->curr.got_dataend = 0; memset(&host->pio, 0, sizeof(host->pio)); datactrl = MCI_DPSM_ENABLE | (data->blksz << 4); if (!msmsdcc_config_dma(host, data)) datactrl |= MCI_DPSM_DMAENABLE; else { host->pio.sg = data->sg; host->pio.sg_len = data->sg_len; host->pio.sg_off = 0; if (data->flags & MMC_DATA_READ) { pio_irqmask = MCI_RXFIFOHALFFULLMASK; if (host->curr.xfer_remain < MCI_FIFOSIZE) pio_irqmask |= MCI_RXDATAAVLBLMASK; } else pio_irqmask = MCI_TXFIFOHALFEMPTYMASK; } if (data->flags & MMC_DATA_READ) datactrl |= MCI_DPSM_DIRECTION; clks = (unsigned long long)data->timeout_ns * host->clk_rate; do_div(clks, 1000000000UL); timeout = data->timeout_clks + (unsigned int)clks*2 ; if((host->mmc->index == 0) && (timeout < 3200000))//clk_rate=16000000 timeout = 9600000; if (datactrl & MCI_DPSM_DMAENABLE) { /* Save parameters for the exec function */ host->cmd_timeout = timeout; host->cmd_pio_irqmask = pio_irqmask; host->cmd_datactrl = datactrl; host->cmd_cmd = cmd; host->dma.hdr.exec_func = msmsdcc_dma_exec_func; host->dma.hdr.user = (void *)host; host->dma.busy = 1; if (cmd) { msmsdcc_start_command_deferred(host, cmd, &c); host->cmd_c = c; } dsb(); msm_dmov_enqueue_cmd_ext(host->dma.channel, &host->dma.hdr); if (data->flags & MMC_DATA_WRITE) host->prog_scan = 1; } else { writel(timeout, base + MMCIDATATIMER); writel(host->curr.xfer_size, base + MMCIDATALENGTH); writel((readl(host->base + MMCIMASK0) & (~(MCI_IRQ_PIO))) | pio_irqmask, host->base + MMCIMASK0); msmsdcc_delay(host); /* Allow parms to be applied */ writel(datactrl, base + MMCIDATACTRL); if (cmd) { msmsdcc_delay(host); /* Delay between data/command */ /* Daisy-chain the command if requested */ msmsdcc_start_command(host, cmd, c); } } } static void msmsdcc_start_command(struct msmsdcc_host *host, struct mmc_command *cmd, u32 c) { msmsdcc_start_command_deferred(host, cmd, &c); msmsdcc_start_command_exec(host, cmd->arg, c); } static void msmsdcc_data_err(struct msmsdcc_host *host, struct mmc_data *data, unsigned int status) { if (status & MCI_DATACRCFAIL) { pr_err("%s: Data CRC error\n", mmc_hostname(host->mmc)); pr_err("%s: opcode 0x%.8x\n", __func__, data->mrq->cmd->opcode); pr_err("%s: blksz %d, blocks %d\n", __func__, data->blksz, data->blocks); data->error = -EILSEQ; } else if (status & MCI_DATATIMEOUT) { /* CRC is optional for the bus test commands, not all * cards respond back with CRC. However controller * waits for the CRC and times out. Hence ignore the * data timeouts during the Bustest. */ if (!(data->mrq->cmd->opcode == MMC_BUSTEST_W || data->mrq->cmd->opcode == MMC_BUSTEST_R)) { pr_err("%s: Data timeout\n", mmc_hostname(host->mmc)); data->error = -ETIMEDOUT; } } else if (status & MCI_RXOVERRUN) { pr_err("%s: RX overrun\n", mmc_hostname(host->mmc)); data->error = -EIO; } else if (status & MCI_TXUNDERRUN) { pr_err("%s: TX underrun\n", mmc_hostname(host->mmc)); data->error = -EIO; } else { pr_err("%s: Unknown error (0x%.8x)\n", mmc_hostname(host->mmc), status); data->error = -EIO; } } static int msmsdcc_pio_read(struct msmsdcc_host *host, char *buffer, unsigned int remain) { void __iomem *base = host->base; uint32_t *ptr = (uint32_t *) buffer; int count = 0; if (remain % 4) remain = ((remain >> 2) + 1) << 2; while (readl(base + MMCISTATUS) & MCI_RXDATAAVLBL) { *ptr = readl(base + MMCIFIFO + (count % MCI_FIFOSIZE)); ptr++; count += sizeof(uint32_t); remain -= sizeof(uint32_t); if (remain == 0) break; } return count; } static int msmsdcc_pio_write(struct msmsdcc_host *host, char *buffer, unsigned int remain, u32 status) { void __iomem *base = host->base; char *ptr = buffer; do { unsigned int count, maxcnt, sz; maxcnt = status & MCI_TXFIFOEMPTY ? MCI_FIFOSIZE : MCI_FIFOHALFSIZE; count = min(remain, maxcnt); sz = count % 4 ? (count >> 2) + 1 : (count >> 2); writesl(base + MMCIFIFO, ptr, sz); ptr += count; remain -= count; if (remain == 0) break; status = readl(base + MMCISTATUS); } while (status & MCI_TXFIFOHALFEMPTY); return ptr - buffer; } static irqreturn_t msmsdcc_pio_irq(int irq, void *dev_id) { struct msmsdcc_host *host = dev_id; void __iomem *base = host->base; uint32_t status; status = readl(base + MMCISTATUS); if (((readl(host->base + MMCIMASK0) & status) & (MCI_IRQ_PIO)) == 0) return IRQ_NONE; #if IRQ_DEBUG msmsdcc_print_status(host, "irq1-r", status); #endif spin_lock(&host->lock); do { unsigned long flags; unsigned int remain, len; char *buffer; if (!(status & (MCI_TXFIFOHALFEMPTY | MCI_RXDATAAVLBL))) break; /* Map the current scatter buffer */ local_irq_save(flags); buffer = kmap_atomic(sg_page(host->pio.sg), KM_BIO_SRC_IRQ) + host->pio.sg->offset; buffer += host->pio.sg_off; remain = host->pio.sg->length - host->pio.sg_off; len = 0; if (status & MCI_RXACTIVE) len = msmsdcc_pio_read(host, buffer, remain); if (status & MCI_TXACTIVE) len = msmsdcc_pio_write(host, buffer, remain, status); /* Unmap the buffer */ kunmap_atomic(buffer, KM_BIO_SRC_IRQ); local_irq_restore(flags); host->pio.sg_off += len; host->curr.xfer_remain -= len; host->curr.data_xfered += len; remain -= len; if (remain) /* Done with this page? */ break; /* Nope */ if (status & MCI_RXACTIVE && host->curr.user_pages) flush_dcache_page(sg_page(host->pio.sg)); if (!--host->pio.sg_len) { memset(&host->pio, 0, sizeof(host->pio)); break; } /* Advance to next sg */ host->pio.sg++; host->pio.sg_off = 0; status = readl(base + MMCISTATUS); } while (1); if (status & MCI_RXACTIVE && host->curr.xfer_remain < MCI_FIFOSIZE) { writel((readl(host->base + MMCIMASK0) & (~(MCI_IRQ_PIO))) | MCI_RXDATAAVLBLMASK, host->base + MMCIMASK0); if (!host->curr.xfer_remain) { /* Delay needed (same port was just written) */ msmsdcc_delay(host); writel((readl(host->base + MMCIMASK0) & (~(MCI_IRQ_PIO))) | 0, host->base + MMCIMASK0); } } else if (!host->curr.xfer_remain) writel((readl(host->base + MMCIMASK0) & (~(MCI_IRQ_PIO))) | 0, host->base + MMCIMASK0); spin_unlock(&host->lock); return IRQ_HANDLED; } static void msmsdcc_request_start(struct msmsdcc_host *host, struct mmc_request *mrq); static irqreturn_t msmsdcc_irq(int irq, void *dev_id) { struct msmsdcc_host *host = dev_id; void __iomem *base = host->base; u32 status; int ret = 0; int timer = 0; spin_lock(&host->lock); do { struct mmc_command *cmd; struct mmc_data *data; if (timer) { timer = 0; msmsdcc_delay(host); } status = readl(host->base + MMCISTATUS); if (((readl(host->base + MMCIMASK0) & status) & (~(MCI_IRQ_PIO))) == 0) break; #if IRQ_DEBUG msmsdcc_print_status(host, "irq0-r", status); #endif status &= readl(host->base + MMCIMASK0); writel(status, host->base + MMCICLEAR); #if IRQ_DEBUG msmsdcc_print_status(host, "irq0-p", status); #endif if ((host->plat->dummy52_required) && (host->dummy_52_state == DUMMY_52_STATE_SENT)) { if (status & MCI_PROGDONE) { host->dummy_52_state = DUMMY_52_STATE_NONE; host->curr.cmd = NULL; spin_unlock(&host->lock); msmsdcc_request_start(host, host->curr.mrq); return IRQ_HANDLED; } break; } data = host->curr.data; #ifdef CONFIG_MMC_MSM_SDIO_SUPPORT if (status & MCI_SDIOINTROPE) { if (host->sdcc_suspending) wake_lock(&host->sdio_suspend_wlock); mmc_signal_sdio_irq(host->mmc); } #endif /* * Check for proper command response */ cmd = host->curr.cmd; if ((status & (MCI_CMDSENT | MCI_CMDRESPEND | MCI_CMDCRCFAIL | MCI_CMDTIMEOUT | MCI_PROGDONE)) && cmd) { host->curr.cmd = NULL; cmd->resp[0] = readl(base + MMCIRESPONSE0); cmd->resp[1] = readl(base + MMCIRESPONSE1); cmd->resp[2] = readl(base + MMCIRESPONSE2); cmd->resp[3] = readl(base + MMCIRESPONSE3); if (status & MCI_CMDTIMEOUT) { #if VERBOSE_COMMAND_TIMEOUTS pr_err("%s: Command timeout\n", mmc_hostname(host->mmc)); #endif cmd->error = -ETIMEDOUT; } else if (status & MCI_CMDCRCFAIL && cmd->flags & MMC_RSP_CRC) { pr_err("%s: Command CRC error\n", mmc_hostname(host->mmc)); cmd->error = -EILSEQ; } if (!cmd->data || cmd->error) { if (host->curr.data && host->dma.sg) msm_dmov_stop_cmd(host->dma.channel, &host->dma.hdr, 0); else if (host->curr.data) { /* Non DMA */ msmsdcc_stop_data(host); timer |= msmsdcc_request_end(host, cmd->mrq); } else { /* host->data == NULL */ if (!cmd->error && host->prog_enable) { if (status & MCI_PROGDONE) { host->prog_scan = 0; host->prog_enable = 0; timer |= msmsdcc_request_end( host, cmd->mrq); } else host->curr.cmd = cmd; } else { if (host->prog_enable) { host->prog_scan = 0; host->prog_enable = 0; } timer |= msmsdcc_request_end( host, cmd->mrq); } } } else if (cmd->data) { if (!(cmd->data->flags & MMC_DATA_READ)) msmsdcc_start_data(host, cmd->data, NULL, 0); } } if (data) { /* Check for data errors */ if (status & (MCI_DATACRCFAIL|MCI_DATATIMEOUT| MCI_TXUNDERRUN|MCI_RXOVERRUN)) { msmsdcc_data_err(host, data, status); host->curr.data_xfered = 0; if (host->dma.sg) msm_dmov_stop_cmd(host->dma.channel, &host->dma.hdr, 0); else { msmsdcc_reset_and_restore(host); if (host->curr.data) msmsdcc_stop_data(host); if (!data->stop) timer |= msmsdcc_request_end(host, data->mrq); else { msmsdcc_start_command(host, data->stop, 0); timer = 1; } } } /* Check for data done */ if (!host->curr.got_dataend && (status & MCI_DATAEND)) host->curr.got_dataend = 1; if (host->curr.got_dataend) { /* * If DMA is still in progress, we complete * via the completion handler */ if (!host->dma.busy) { /* * There appears to be an issue in the * controller where if you request a * small block transfer (< fifo size), * you may get your DATAEND/DATABLKEND * irq without the PIO data irq. * * Check to see if theres still data * to be read, and simulate a PIO irq. */ if (readl(host->base + MMCISTATUS) & MCI_RXDATAAVLBL) { spin_unlock(&host->lock); msmsdcc_pio_irq(1, host); spin_lock(&host->lock); } msmsdcc_stop_data(host); if (!data->error) host->curr.data_xfered = host->curr.xfer_size; if (!data->stop) timer |= msmsdcc_request_end( host, data->mrq); else { msmsdcc_start_command(host, data->stop, 0); timer = 1; } } } } ret = 1; } while (status); spin_unlock(&host->lock); return IRQ_RETVAL(ret); } static void msmsdcc_request_start(struct msmsdcc_host *host, struct mmc_request *mrq) { if (mrq->data && mrq->data->flags & MMC_DATA_READ) { /* Queue/read data, daisy-chain command when data starts */ msmsdcc_start_data(host, mrq->data, mrq->cmd, 0); } else { msmsdcc_start_command(host, mrq->cmd, 0); } } static void msmsdcc_request(struct mmc_host *mmc, struct mmc_request *mrq) { struct msmsdcc_host *host = mmc_priv(mmc); unsigned long flags; WARN_ON(host->curr.mrq != NULL); WARN_ON(host->pwr == 0); spin_lock_irqsave(&host->lock, flags); if (host->eject) { if (mrq->data && !(mrq->data->flags & MMC_DATA_READ)) { mrq->cmd->error = 0; mrq->data->bytes_xfered = mrq->data->blksz * mrq->data->blocks; } else mrq->cmd->error = -ENOMEDIUM; spin_unlock_irqrestore(&host->lock, flags); mmc_request_done(mmc, mrq); return; } host->curr.mrq = mrq; if (host->plat->dummy52_required) { if (host->dummy_52_needed) { if (mrq->data) { host->dummy_52_state = DUMMY_52_STATE_SENT; msmsdcc_start_command(host, &dummy52cmd, MCI_CPSM_PROGENA); spin_unlock_irqrestore(&host->lock, flags); return; } host->dummy_52_needed = 0; } if ((mrq->cmd->opcode == SD_IO_RW_EXTENDED) && (mrq->data)) host->dummy_52_needed = 1; } msmsdcc_request_start(host, mrq); spin_unlock_irqrestore(&host->lock, flags); } static void msmsdcc_set_ios(struct mmc_host *mmc, struct mmc_ios *ios) { struct msmsdcc_host *host = mmc_priv(mmc); u32 clk = 0, pwr = 0; int rc; DBG(host, "ios->clock = %u\n", ios->clock); if (ios->clock) { if (!host->clks_on) { if (!IS_ERR(host->pclk)) clk_enable(host->pclk); clk_enable(host->clk); host->clks_on = 1; } if ((ios->clock < host->plat->msmsdcc_fmax) && (ios->clock > host->plat->msmsdcc_fmid)) ios->clock = host->plat->msmsdcc_fmid; if (ios->clock != host->clk_rate) { rc = clk_set_rate(host->clk, ios->clock); WARN_ON(rc < 0); host->clk_rate = ios->clock; } clk |= MCI_CLK_ENABLE; } if (ios->bus_width == MMC_BUS_WIDTH_8) clk |= MCI_CLK_WIDEBUS_8; else if (ios->bus_width == MMC_BUS_WIDTH_4) clk |= MCI_CLK_WIDEBUS_4; else clk |= MCI_CLK_WIDEBUS_1; if (ios->clock > 400000 && msmsdcc_pwrsave) clk |= MCI_CLK_PWRSAVE; clk |= MCI_CLK_FLOWENA; clk |= MCI_CLK_SELECTIN; /* feedback clock */ if (host->plat->translate_vdd) pwr |= host->plat->translate_vdd(mmc_dev(mmc), ios->vdd); switch (ios->power_mode) { case MMC_POWER_OFF: htc_pwrsink_set(PWRSINK_SDCARD, 0); break; case MMC_POWER_UP: pwr |= MCI_PWR_UP; break; case MMC_POWER_ON: htc_pwrsink_set(PWRSINK_SDCARD, 100); pwr |= MCI_PWR_ON; break; } if (ios->bus_mode == MMC_BUSMODE_OPENDRAIN) pwr |= MCI_OD; writel(clk, host->base + MMCICLOCK); udelay(50); if (host->pwr != pwr) { host->pwr = pwr; writel(pwr, host->base + MMCIPOWER); } if (!(clk & MCI_CLK_ENABLE) && host->clks_on) { clk_disable(host->clk); if (!IS_ERR(host->pclk)) clk_disable(host->pclk); host->clks_on = 0; } } static int msmsdcc_get_ro(struct mmc_host *mmc) { int wpswitch_status = -ENOSYS; struct msmsdcc_host *host = mmc_priv(mmc); if (host->plat->wpswitch) { wpswitch_status = host->plat->wpswitch(mmc_dev(mmc)); if (wpswitch_status < 0) wpswitch_status = -ENOSYS; } pr_debug("%s: Card read-only status %d\n", __func__, wpswitch_status); return wpswitch_status; } #ifdef CONFIG_MMC_MSM_SDIO_SUPPORT static void msmsdcc_enable_sdio_irq(struct mmc_host *mmc, int enable) { struct msmsdcc_host *host = mmc_priv(mmc); if (enable) { host->mci_irqenable |= MCI_SDIOINTOPERMASK; writel(readl(host->base + MMCIMASK0) | MCI_SDIOINTOPERMASK, host->base + MMCIMASK0); } else { host->mci_irqenable &= ~MCI_SDIOINTOPERMASK; writel(readl(host->base + MMCIMASK0) & ~MCI_SDIOINTOPERMASK, host->base + MMCIMASK0); } } #endif /* CONFIG_MMC_MSM_SDIO_SUPPORT */ static const struct mmc_host_ops msmsdcc_ops = { .request = msmsdcc_request, .set_ios = msmsdcc_set_ios, .get_ro = msmsdcc_get_ro, #ifdef CONFIG_MMC_MSM_SDIO_SUPPORT .enable_sdio_irq = msmsdcc_enable_sdio_irq, #endif #ifdef CONFIG_MMC_AUTO_SUSPEND .auto_suspend = msmsdcc_auto_suspend, #endif }; static void msmsdcc_check_status(unsigned long data) { struct msmsdcc_host *host = (struct msmsdcc_host *)data; unsigned int status; if (!host->plat->status) { mmc_detect_change(host->mmc, 0); } else { status = host->plat->status(mmc_dev(host->mmc)); host->eject = !status; if (status ^ host->oldstat) { pr_info("%s: Slot status change detected (%d -> %d)\n", mmc_hostname(host->mmc), host->oldstat, status); mmc_detect_change(host->mmc, 0); } host->oldstat = status; } } static irqreturn_t msmsdcc_platform_status_irq(int irq, void *dev_id) { struct msmsdcc_host *host = dev_id; pr_debug("%s: %d\n", __func__, irq); msmsdcc_check_status((unsigned long) host); return IRQ_HANDLED; } static irqreturn_t msmsdcc_platform_sdiowakeup_irq(int irq, void *dev_id) { struct msmsdcc_host *host = dev_id; pr_info("%s: SDIO Wake up IRQ : %d\n", __func__, irq); spin_lock(&host->lock); if (!host->sdio_irq_disabled) { disable_irq_nosync(irq); if (host->mmc->pm_flags & MMC_PM_WAKE_SDIO_IRQ) { wake_lock(&host->sdio_wlock); disable_irq_wake(irq); } host->sdio_irq_disabled = 1; } spin_unlock(&host->lock); return IRQ_HANDLED; } static void msmsdcc_status_notify_cb(int card_present, void *dev_id) { struct msmsdcc_host *host = dev_id; pr_debug("%s: card_present %d\n", mmc_hostname(host->mmc), card_present); msmsdcc_check_status((unsigned long) host); } static int msmsdcc_init_dma(struct msmsdcc_host *host) { memset(&host->dma, 0, sizeof(struct msmsdcc_dma_data)); host->dma.host = host; host->dma.channel = -1; if (!host->dmares) return -ENODEV; host->dma.nc = dma_alloc_coherent(NULL, sizeof(struct msmsdcc_nc_dmadata), &host->dma.nc_busaddr, GFP_KERNEL); if (host->dma.nc == NULL) { pr_err("Unable to allocate DMA buffer\n"); return -ENOMEM; } memset(host->dma.nc, 0x00, sizeof(struct msmsdcc_nc_dmadata)); host->dma.cmd_busaddr = host->dma.nc_busaddr; host->dma.cmdptr_busaddr = host->dma.nc_busaddr + offsetof(struct msmsdcc_nc_dmadata, cmdptr); host->dma.channel = host->dmares->start; return 0; } static ssize_t show_polling(struct device *dev, struct device_attribute *attr, char *buf) { struct mmc_host *mmc = dev_get_drvdata(dev); struct msmsdcc_host *host = mmc_priv(mmc); int poll; unsigned long flags; spin_lock_irqsave(&host->lock, flags); poll = !!(mmc->caps & MMC_CAP_NEEDS_POLL); spin_unlock_irqrestore(&host->lock, flags); return snprintf(buf, PAGE_SIZE, "%d\n", poll); } static ssize_t set_polling(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct mmc_host *mmc = dev_get_drvdata(dev); struct msmsdcc_host *host = mmc_priv(mmc); int value; unsigned long flags; sscanf(buf, "%d", &value); spin_lock_irqsave(&host->lock, flags); if (value) { mmc->caps |= MMC_CAP_NEEDS_POLL; mmc_detect_change(host->mmc, 0); } else { mmc->caps &= ~MMC_CAP_NEEDS_POLL; } #ifdef CONFIG_HAS_EARLYSUSPEND host->polling_enabled = mmc->caps & MMC_CAP_NEEDS_POLL; #endif spin_unlock_irqrestore(&host->lock, flags); return count; } static DEVICE_ATTR(polling, S_IRUGO | S_IWUSR, show_polling, set_polling); static struct attribute *dev_attrs[] = { &dev_attr_polling.attr, NULL, }; static struct attribute_group dev_attr_grp = { .attrs = dev_attrs, }; #ifdef CONFIG_HAS_EARLYSUSPEND static void msmsdcc_early_suspend(struct early_suspend *h) { struct msmsdcc_host *host = container_of(h, struct msmsdcc_host, early_suspend); unsigned long flags; spin_lock_irqsave(&host->lock, flags); host->polling_enabled = host->mmc->caps & MMC_CAP_NEEDS_POLL; host->mmc->caps &= ~MMC_CAP_NEEDS_POLL; spin_unlock_irqrestore(&host->lock, flags); }; static void msmsdcc_late_resume(struct early_suspend *h) { struct msmsdcc_host *host = container_of(h, struct msmsdcc_host, early_suspend); unsigned long flags; if (host->polling_enabled) { spin_lock_irqsave(&host->lock, flags); host->mmc->caps |= MMC_CAP_NEEDS_POLL; mmc_detect_change(host->mmc, 0); spin_unlock_irqrestore(&host->lock, flags); } }; #endif static int msmsdcc_probe(struct platform_device *pdev) { struct mmc_platform_data *plat = pdev->dev.platform_data; struct msmsdcc_host *host; struct mmc_host *mmc; unsigned long flags; struct resource *irqres = NULL; struct resource *memres = NULL; struct resource *dmares = NULL; int ret; int i; /* must have platform data */ if (!plat) { pr_err("%s: Platform data not available\n", __func__); ret = -EINVAL; goto out; } if (pdev->id < 1 || pdev->id > 5) return -EINVAL; if (pdev->resource == NULL || pdev->num_resources < 3) { pr_err("%s: Invalid resource\n", __func__); return -ENXIO; } for (i = 0; i < pdev->num_resources; i++) { if (pdev->resource[i].flags & IORESOURCE_MEM) memres = &pdev->resource[i]; if (pdev->resource[i].flags & IORESOURCE_IRQ) irqres = &pdev->resource[i]; if (pdev->resource[i].flags & IORESOURCE_DMA) dmares = &pdev->resource[i]; } if (!irqres || !memres) { pr_err("%s: Invalid resource\n", __func__); return -ENXIO; } /* * Setup our host structure */ mmc = mmc_alloc_host(sizeof(struct msmsdcc_host), &pdev->dev); if (!mmc) { ret = -ENOMEM; goto out; } host = mmc_priv(mmc); host->pdev_id = pdev->id; host->plat = plat; host->mmc = mmc; host->curr.cmd = NULL; host->base = ioremap(memres->start, PAGE_SIZE); if (!host->base) { ret = -ENOMEM; goto host_free; } host->irqres = irqres; host->memres = memres; host->dmares = dmares; spin_lock_init(&host->lock); #ifdef CONFIG_MMC_EMBEDDED_SDIO if (plat->embedded_sdio) mmc_set_embedded_sdio_data(mmc, &plat->embedded_sdio->cis, &plat->embedded_sdio->cccr, plat->embedded_sdio->funcs, plat->embedded_sdio->num_funcs); #endif tasklet_init(&host->dma_tlet, msmsdcc_dma_complete_tlet, (unsigned long)host); /* * Setup DMA */ ret = msmsdcc_init_dma(host); if (ret) goto ioremap_free; /* * Setup main peripheral bus clock */ host->pclk = clk_get(&pdev->dev, "sdc_pclk"); if (!IS_ERR(host->pclk)) { ret = clk_enable(host->pclk); if (ret) goto pclk_put; host->pclk_rate = clk_get_rate(host->pclk); } /* * Setup SDC MMC clock */ host->clk = clk_get(&pdev->dev, "sdc_clk"); if (IS_ERR(host->clk)) { ret = PTR_ERR(host->clk); goto pclk_disable; } ret = clk_set_rate(host->clk, plat->msmsdcc_fmin); if (ret) { pr_err("%s: Clock rate set failed (%d)\n", __func__, ret); goto clk_put; } ret = clk_enable(host->clk); if (ret) goto clk_put; host->clk_rate = clk_get_rate(host->clk); host->clks_on = 1; /* * Setup MMC host structure */ mmc->ops = &msmsdcc_ops; mmc->f_min = plat->msmsdcc_fmin; mmc->f_max = plat->msmsdcc_fmax; mmc->ocr_avail = plat->ocr_mask; mmc->pm_caps |= MMC_PM_KEEP_POWER; mmc->caps |= plat->mmc_bus_width; mmc->caps |= MMC_CAP_MMC_HIGHSPEED | MMC_CAP_SD_HIGHSPEED; if (plat->nonremovable) mmc->caps |= MMC_CAP_NONREMOVABLE; #ifdef CONFIG_MMC_MSM_SDIO_SUPPORT mmc->caps |= MMC_CAP_SDIO_IRQ; #endif mmc->max_phys_segs = NR_SG; mmc->max_hw_segs = NR_SG; mmc->max_blk_size = 4096; /* MCI_DATA_CTL BLOCKSIZE up to 4096 */ mmc->max_blk_count = 65536; mmc->max_req_size = 33554432; /* MCI_DATA_LENGTH is 25 bits */ mmc->max_seg_size = mmc->max_req_size; writel(0, host->base + MMCIMASK0); writel(MCI_CLEAR_STATIC_MASK, host->base + MMCICLEAR); /* Delay needed (MMCIMASK0 was just written above) */ msmsdcc_delay(host); writel(MCI_IRQENABLE, host->base + MMCIMASK0); host->mci_irqenable = MCI_IRQENABLE; ret = request_irq(irqres->start, msmsdcc_irq, IRQF_SHARED, DRIVER_NAME " (cmd)", host); if (ret) goto clk_disable; ret = request_irq(irqres->start, msmsdcc_pio_irq, IRQF_SHARED, DRIVER_NAME " (pio)", host); if (ret) goto irq_free; if (plat->sdiowakeup_irq) { wake_lock_init(&host->sdio_wlock, WAKE_LOCK_SUSPEND, mmc_hostname(mmc)); ret = request_irq(plat->sdiowakeup_irq, msmsdcc_platform_sdiowakeup_irq, IRQF_SHARED | IRQF_TRIGGER_LOW, DRIVER_NAME "sdiowakeup", host); if (ret) { pr_err("Unable to get sdio wakeup IRQ %d (%d)\n", plat->sdiowakeup_irq, ret); goto irq_free; } else { mmc->pm_caps |= MMC_PM_WAKE_SDIO_IRQ; spin_lock_irqsave(&host->lock, flags); if (!host->sdio_irq_disabled) { disable_irq_nosync(plat->sdiowakeup_irq); host->sdio_irq_disabled = 1; } spin_unlock_irqrestore(&host->lock, flags); } } wake_lock_init(&host->sdio_suspend_wlock, WAKE_LOCK_SUSPEND, mmc_hostname(mmc)); /* * Setup card detect change */ if (plat->status) { host->oldstat = plat->status(mmc_dev(host->mmc)); host->eject = !host->oldstat; } if (plat->status_irq) { ret = request_irq(plat->status_irq, msmsdcc_platform_status_irq, IRQF_SHARED | plat->irq_flags, DRIVER_NAME " (slot)", host); if (ret) { pr_err("Unable to get slot IRQ %d (%d)\n", plat->status_irq, ret); goto sdiowakeup_irq_free; } } else if (plat->register_status_notify) { plat->register_status_notify(msmsdcc_status_notify_cb, host); } else if (!plat->status) pr_err("%s: No card detect facilities available\n", mmc_hostname(mmc)); mmc_set_drvdata(pdev, mmc); mmc_add_host(mmc); if (!strcmp(mmc_hostname(mmc), "mmc1")) { wifi_host = host; wifi_host_dev = pdev; printk("### wifi_host %d\n", (int)wifi_host); } #ifdef CONFIG_HAS_EARLYSUSPEND host->early_suspend.suspend = msmsdcc_early_suspend; host->early_suspend.resume = msmsdcc_late_resume; host->early_suspend.level = EARLY_SUSPEND_LEVEL_DISABLE_FB; register_early_suspend(&host->early_suspend); #endif pr_info("%s: Qualcomm MSM SDCC at 0x%016llx irq %d,%d dma %d\n", mmc_hostname(mmc), (unsigned long long)memres->start, (unsigned int) irqres->start, (unsigned int) plat->status_irq, host->dma.channel); pr_info("%s: 8 bit data mode %s\n", mmc_hostname(mmc), (mmc->caps & MMC_CAP_8_BIT_DATA ? "enabled" : "disabled")); pr_info("%s: 4 bit data mode %s\n", mmc_hostname(mmc), (mmc->caps & MMC_CAP_4_BIT_DATA ? "enabled" : "disabled")); pr_info("%s: polling status mode %s\n", mmc_hostname(mmc), (mmc->caps & MMC_CAP_NEEDS_POLL ? "enabled" : "disabled")); pr_info("%s: MMC clock %u -> %u Hz, PCLK %u Hz\n", mmc_hostname(mmc), plat->msmsdcc_fmin, plat->msmsdcc_fmax, host->pclk_rate); pr_info("%s: Slot eject status = %d\n", mmc_hostname(mmc), host->eject); pr_info("%s: Power save feature enable = %d\n", mmc_hostname(mmc), msmsdcc_pwrsave); if (host->dma.channel != -1) { pr_info("%s: DM non-cached buffer at %p, dma_addr 0x%.8x\n", mmc_hostname(mmc), host->dma.nc, host->dma.nc_busaddr); pr_info("%s: DM cmd busaddr 0x%.8x, cmdptr busaddr 0x%.8x\n", mmc_hostname(mmc), host->dma.cmd_busaddr, host->dma.cmdptr_busaddr); } else pr_info("%s: PIO transfer enabled\n", mmc_hostname(mmc)); #if defined(CONFIG_DEBUG_FS) msmsdcc_dbg_createhost(host); #endif if (!plat->status_irq) { ret = sysfs_create_group(&pdev->dev.kobj, &dev_attr_grp); if (ret) goto platform_irq_free; } return 0; platform_irq_free: if (plat->status_irq) free_irq(plat->status_irq, host); sdiowakeup_irq_free: wake_lock_destroy(&host->sdio_suspend_wlock); if (plat->sdiowakeup_irq) free_irq(plat->sdiowakeup_irq, host); pio_irq_free: if (plat->sdiowakeup_irq) wake_lock_destroy(&host->sdio_wlock); free_irq(irqres->start, host); irq_free: free_irq(irqres->start, host); clk_disable: clk_disable(host->clk); clk_put: clk_put(host->clk); pclk_disable: if (!IS_ERR(host->pclk)) clk_disable(host->pclk); pclk_put: if (!IS_ERR(host->pclk)) clk_put(host->pclk); dma_free_coherent(NULL, sizeof(struct msmsdcc_nc_dmadata), host->dma.nc, host->dma.nc_busaddr); ioremap_free: iounmap(host->base); host_free: mmc_free_host(mmc); out: return ret; } static int msmsdcc_remove(struct platform_device *pdev) { struct mmc_host *mmc = mmc_get_drvdata(pdev); struct mmc_platform_data *plat; struct msmsdcc_host *host; if (!mmc) return -ENXIO; host = mmc_priv(mmc); DBG(host, "Removing SDCC2 device = %d\n", pdev->id); plat = host->plat; if (!plat->status_irq) sysfs_remove_group(&pdev->dev.kobj, &dev_attr_grp); tasklet_kill(&host->dma_tlet); mmc_remove_host(mmc); if (plat->status_irq) free_irq(plat->status_irq, host); wake_lock_destroy(&host->sdio_suspend_wlock); if (plat->sdiowakeup_irq) { wake_lock_destroy(&host->sdio_wlock); set_irq_wake(plat->sdiowakeup_irq, 0); free_irq(plat->sdiowakeup_irq, host); } free_irq(host->irqres->start, host); writel(0, host->base + MMCIMASK0); writel(0, host->base + MMCIMASK1); writel(MCI_CLEAR_STATIC_MASK, host->base + MMCICLEAR); writel(0, host->base + MMCIDATACTRL); writel(0, host->base + MMCICOMMAND); clk_put(host->clk); if (!IS_ERR(host->pclk)) clk_put(host->pclk); dma_free_coherent(NULL, sizeof(struct msmsdcc_nc_dmadata), host->dma.nc, host->dma.nc_busaddr); iounmap(host->base); mmc_free_host(mmc); #ifdef CONFIG_HAS_EARLYSUSPEND unregister_early_suspend(&host->early_suspend); #endif return 0; } #ifdef CONFIG_PM static int msmsdcc_suspend(struct platform_device *dev, pm_message_t state) { struct mmc_host *mmc = mmc_get_drvdata(dev); struct msmsdcc_host *host = mmc_priv(mmc); int rc = 0; #ifdef CONFIG_MMC_AUTO_SUSPEND if (test_and_set_bit(0, &host->suspended)) return 0; #endif if (mmc) { if (host->plat->status_irq) disable_irq(host->plat->status_irq); host->sdcc_suspending = 1; if (!mmc->card || (host->plat->sdiowakeup_irq && mmc->card->type == MMC_TYPE_SDIO) || mmc->card->type != MMC_TYPE_SDIO) rc = mmc_suspend_host(mmc, state); if (!rc) { writel(0, host->base + MMCIMASK0); if (host->clks_on) { clk_disable(host->clk); if (!IS_ERR(host->pclk)) clk_disable(host->pclk); host->clks_on = 0; } } if ((mmc->pm_flags & MMC_PM_WAKE_SDIO_IRQ) && mmc->card && mmc->card->type == MMC_TYPE_SDIO) { host->sdio_irq_disabled = 0; enable_irq_wake(host->plat->sdiowakeup_irq); enable_irq(host->plat->sdiowakeup_irq); } host->sdcc_suspending = 0; } return rc; } static int msmsdcc_resume(struct platform_device *dev) { struct mmc_host *mmc = mmc_get_drvdata(dev); struct msmsdcc_host *host = mmc_priv(mmc); unsigned long flags; int release_lock = 0; #ifdef CONFIG_MMC_AUTO_SUSPEND if (!test_and_clear_bit(0, &host->suspended)) return 0; #endif if((!strcmp(mmc_hostname(mmc), "mmc1")) && (host->clks_on)) { return 0; } if (mmc) { spin_lock_irqsave(&host->lock, flags); if (!host->clks_on) { if (!IS_ERR(host->pclk)) clk_enable(host->pclk); clk_enable(host->clk); host->clks_on = 1; } writel(host->mci_irqenable, host->base + MMCIMASK0); if ((mmc->pm_flags & MMC_PM_WAKE_SDIO_IRQ) && !host->sdio_irq_disabled) { if (mmc->card && mmc->card->type == MMC_TYPE_SDIO) { disable_irq_nosync(host->plat->sdiowakeup_irq); disable_irq_wake(host->plat->sdiowakeup_irq); host->sdio_irq_disabled = 1; } } else { release_lock = 1; } spin_unlock_irqrestore(&host->lock, flags); if (!mmc->card || (host->plat->sdiowakeup_irq && mmc->card->type == MMC_TYPE_SDIO) || mmc->card->type != MMC_TYPE_SDIO) mmc_resume_host(mmc); if (host->plat->status_irq) enable_irq(host->plat->status_irq); /* * After resuming the host wait for sometime so that * the SDIO work will be processed. */ if ((mmc->pm_flags & MMC_PM_WAKE_SDIO_IRQ) && release_lock) wake_lock_timeout(&host->sdio_wlock, 1); wake_unlock(&host->sdio_suspend_wlock); } return 0; } #else #define msmsdcc_suspend NULL #define msmsdcc_resume NULL #endif /* * added by jrd */ int wifi_call_resume(void) { if (wifi_host && !wifi_host->clks_on) { printk("## CALL WIFI RESUME ##\n"); //msmsdcc_runtime_resume(wifi_host_dev); //msmsdcc_pm_resume(wifi_host_dev); msmsdcc_resume(wifi_host_dev); return 1; } return 0; } EXPORT_SYMBOL(wifi_call_resume); #ifdef CONFIG_MMC_AUTO_SUSPEND static int msmsdcc_auto_suspend(struct mmc_host *host, int suspend) { struct platform_device *pdev; pdev = container_of(host->parent, struct platform_device, dev); if (suspend) return msmsdcc_suspend(pdev, PMSG_AUTO_SUSPEND); else return msmsdcc_resume(pdev); } #else #define msmsdcc_auto_suspend NULL #endif static struct platform_driver msmsdcc_driver = { .probe = msmsdcc_probe, .remove = msmsdcc_remove, .suspend = msmsdcc_suspend, .resume = msmsdcc_resume, .driver = { .name = "msm_sdcc", }, }; //add by GeNan extern struct resource resources_sdc1[3]; extern struct platform_device *msm_device_sdc1; extern struct mmc_platform_data msm7x2x_sdc1_data; static int mmc_test_open(struct inode *inode, struct file *file) { platform_device_unregister(msm_device_sdc1); mdelay(300); msm_device_sdc1 = platform_device_alloc("msm_sdcc", 1); platform_device_add_resources(msm_device_sdc1, resources_sdc1, ARRAY_SIZE(resources_sdc1)); platform_device_add_data(msm_device_sdc1, &msm7x2x_sdc1_data, sizeof(msm7x2x_sdc1_data)); msm_device_sdc1->dev.coherent_dma_mask = 0xffffffff; platform_device_add(msm_device_sdc1); return 0; } static struct file_operations mmc_test = { .owner = THIS_MODULE, .open = mmc_test_open, }; static struct miscdevice mmc_test_dev = { .minor = MISC_DYNAMIC_MINOR, .name = "sd_test", .fops = &mmc_test, }; static int __init msmsdcc_init(void) { #if defined(CONFIG_DEBUG_FS) int ret = 0; ret = msmsdcc_dbg_init(); if (ret) { pr_err("Failed to create debug fs dir \n"); return ret; } #endif //add by GeNan misc_register(&mmc_test_dev); return platform_driver_register(&msmsdcc_driver); } static void __exit msmsdcc_exit(void) { platform_driver_unregister(&msmsdcc_driver); #if defined(CONFIG_DEBUG_FS) debugfs_remove(debugfs_file); debugfs_remove(debugfs_dir); #endif } module_init(msmsdcc_init); module_exit(msmsdcc_exit); MODULE_DESCRIPTION("Qualcomm Multimedia Card Interface driver"); MODULE_LICENSE("GPL"); #if defined(CONFIG_DEBUG_FS) static int msmsdcc_dbg_state_open(struct inode *inode, struct file *file) { file->private_data = inode->i_private; return 0; } static ssize_t msmsdcc_dbg_state_read(struct file *file, char __user *ubuf, size_t count, loff_t *ppos) { struct msmsdcc_host *host = (struct msmsdcc_host *) file->private_data; char buf[1024]; int max, i; i = 0; max = sizeof(buf) - 1; i += scnprintf(buf + i, max - i, "STAT: %p %p %p\n", host->curr.mrq, host->curr.cmd, host->curr.data); if (host->curr.cmd) { struct mmc_command *cmd = host->curr.cmd; i += scnprintf(buf + i, max - i, "CMD : %.8x %.8x %.8x\n", cmd->opcode, cmd->arg, cmd->flags); } if (host->curr.data) { struct mmc_data *data = host->curr.data; i += scnprintf(buf + i, max - i, "DAT0: %.8x %.8x %.8x %.8x %.8x %.8x\n", data->timeout_ns, data->timeout_clks, data->blksz, data->blocks, data->error, data->flags); i += scnprintf(buf + i, max - i, "DAT1: %.8x %.8x %.8x %p\n", host->curr.xfer_size, host->curr.xfer_remain, host->curr.data_xfered, host->dma.sg); } return simple_read_from_buffer(ubuf, count, ppos, buf, i); } static const struct file_operations msmsdcc_dbg_state_ops = { .read = msmsdcc_dbg_state_read, .open = msmsdcc_dbg_state_open, }; static void msmsdcc_dbg_createhost(struct msmsdcc_host *host) { if (debugfs_dir) { debugfs_file = debugfs_create_file(mmc_hostname(host->mmc), 0644, debugfs_dir, host, &msmsdcc_dbg_state_ops); } } static int __init msmsdcc_dbg_init(void) { int err; debugfs_dir = debugfs_create_dir("msmsdcc", 0); if (IS_ERR(debugfs_dir)) { err = PTR_ERR(debugfs_dir); debugfs_dir = NULL; return err; } return 0; } #endif
Shkerzy/AlcatelOT990_Froyo_kernel
drivers/mmc/host/msm_sdcc.c
C
gpl-2.0
49,294
/** * CartoDB infowindow dark styles */ div.cartodb-popup.dark .jspContainer:after { background: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(0%, rgba(0,0,0,0)), color-stop(100%, rgba(0,0,0,1))); background: -webkit-linear-gradient(top, rgba(0,0,0,0), rgba(0,0,0,1)); background: -moz-linear-gradient(top, rgba(0,0,0,0), rgba(0,0,0,1)); background: -o-linear-gradient(top, rgba(0,0,0,0), rgba(0,0,0,1)); background: linear-gradient(top, rgba(0,0,0,0), rgba(0,0,0,1)); } div.cartodb-popup.dark .jspContainer:before { background: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(0%, rgba(0,0,0,1)), color-stop(100%, rgba(0,0,0,0))); background: -webkit-linear-gradient(top, rgba(0,0,0,1), rgba(0,0,0,0)); background: -moz-linear-gradient(top, rgba(0,0,0,1), rgba(0,0,0,0)); background: -o-linear-gradient(top, rgba(0,0,0,1), rgba(0,0,0,0)); background: linear-gradient(top, rgba(0,0,0,1), rgba(0,0,0,0)); } div.cartodb-popup.dark { background:url('../img/dark.png') no-repeat -226px 0; } div.cartodb-popup.dark div.cartodb-popup-content-wrapper { background:url('../img/dark.png') repeat-y -452px 0; } div.cartodb-popup.dark div.cartodb-popup-tip-container { background:url('../img/dark.png') no-repeat 0 0; } div.cartodb-popup.dark a.cartodb-popup-close-button { background:url('../img/dark.png') no-repeat 0 -23px; } div.cartodb-popup.dark h4 { color:#999; } div.cartodb-popup.dark p { color:#FFFFFF; } div.cartodb-popup.dark a { color:#397DB9; } div.cartodb-popup.dark p.empty { font-style:italic; color:#AAA; } div.cartodb-popup.dark .jspDrag { background: #AAAAAA; background: rgba(255,255,255,0.5); } div.cartodb-popup.dark .jspDrag:hover { background: #DEDEDE; background: rgba(255,255,255,0.8); } /* NEW CartoDB 2.0 dark popups */ div.cartodb-popup.v2.dark { background:#000000; } div.cartodb-popup.v2.dark:before { border-top-color:black; } div.cartodb-popup.v2.dark div.cartodb-popup-tip-container:after { border-top-color:#000; } div.cartodb-popup.v2.dark a.cartodb-popup-close-button { background:#000000; } div.cartodb-popup.v2.dark a.cartodb-popup-close-button:before, div.cartodb-popup.v2.dark a.cartodb-popup-close-button:after { background:white; } /* Hello IE */ @media \0screen\,screen\9 { div.cartodb-popup.v2.dark { border:4px solid #AAA; } div.cartodb-popup.v2.dark div.cartodb-popup-tip-container { border-top:18px solid #000; } div.cartodb-popup.v2.dark a.cartodb-popup-close-button { border:2px solid #AAA; color:white; } div.cartodb-popup.v2.dark a.cartodb-popup-close-button:hover { border:2px solid #BBB; } } /** * CartoDB popup styles (DEFAULT) */ div.cartodb-infowindow { position: absolute; z-index: 12; } div.cartodb-popup { position:relative; width:226px; height:auto; padding:7px 0 0 0; margin:0; background:url('../img/light.png') no-repeat -226px 0; } div.cartodb-popup div.cartodb-popup-content-wrapper { width:190px; max-width: 190px; padding:12px 19px 12px 19px; overflow-x: hidden; background:url('../img/light.png') repeat-y -452px 0; } div.cartodb-popup div.cartodb-popup-content { display:block; width:190px; max-width: 190px; min-height:5px; height:auto; max-height:185px; margin: 0; padding: 0; overflow-y: auto; overflow-x: hidden!important; outline: none; text-align:left; } /* Custom gradients for scroll content */ div.cartodb-popup .jspContainer:after, div.cartodb-popup .jspContainer:before { content:''; position:absolute; left:0; right:12px; display:block; height:10px; width:190px; z-index: 5; } div.cartodb-popup .jspContainer:after { bottom:0px; background: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(0%, rgba(255,255,255,0)), color-stop(100%, rgba(255,255,255,1))); background: -webkit-linear-gradient(top, rgba(255,255,255,0), rgba(255,255,255,1)); background: -moz-linear-gradient(top, rgba(255,255,255,0), rgba(255,255,255,1)); background: -o-linear-gradient(top, rgba(255,255,255,0), rgba(255,255,255,1)); background: linear-gradient(top, rgba(255,255,255,0), rgba(255,255,255,1)); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#00ffffff',GradientType=0 ); } div.cartodb-popup .jspContainer:before { top:0px; background: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(0%, rgba(255,255,255,1)), color-stop(100%, rgba(255,255,255,0))); background: -webkit-linear-gradient(top, rgba(255,255,255,1), rgba(255,255,255,0)); background: -moz-linear-gradient(top, rgba(255,255,255,1), rgba(255,255,255,0)); background: -o-linear-gradient(top, rgba(255,255,255,1), rgba(255,255,255,0)); background: linear-gradient(top, rgba(255,255,255,1), rgba(255,255,255,0)); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#00ffffff',GradientType=0 ); } div.cartodb-popup div.cartodb-popup-tip-container { width:226px; height:20px; background:url('../img/light.png') no-repeat 0 0; } div.cartodb-popup a.cartodb-popup-close-button { position:absolute; top:-9px; right:-9px; width:26px; height:26px; padding:0; background:url('../img/light.png') no-repeat 0 -23px; text-indent:-9999px; font-size:0; line-height:0; opacity:1; -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)"; filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=1); filter: alpha(opacity=100); text-transform:uppercase; z-index:3; } /* When there are no fields in header popup themes */ div.cartodb-popup.header.no_fields div.cartodb-popup-content { display:none; } div.cartodb-popup.header.no_fields div.cartodb-popup-content-wrapper div.cartodb-edit-buttons { padding-top:5px; margin-top:0; } div.cartodb-popup.header.no_fields div.cartodb-edit-buttons { border: none; padding-top:0; } /* Custom scroll in CartoDB content */ div.cartodb-popup .jspContainer { overflow: hidden; position: relative; outline: none; } div.cartodb-popup .jspContainer * { outline: none; } div.cartodb-popup .jspPane { position: absolute; padding:4px 0 0 0!important; z-index:1; } div.cartodb-popup .jspVerticalBar { position: absolute; top: 0; right: 0; width: 6px; height: 100%; background: none; z-index:10; } div.cartodb-popup .jspHorizontalBar { position: absolute; bottom: 0; left: 0; width: 100%; height: 6px; background: none; } div.cartodb-popup .jspVerticalBar *, div.cartodb-popup .jspHorizontalBar * { margin: 0; padding: 0; } div.cartodb-popup .jspCap { display: none; } div.cartodb-popup .jspHorizontalBar .jspCap { float: left; } div.cartodb-popup .jspTrack { position: relative; cursor: pointer; background: none; } div.cartodb-popup .jspDrag { position: relative; top: 0; left: 0; cursor: pointer; border-radius:10px; -moz-border-radius:10px; -webkit-border-radius:10px; background: #999999; background: rgba(0,0,0,0.16); } div.cartodb-popup .jspDrag:hover { background: #666666; background: rgba(0,0,0,0.5); cursor: pointer; } div.cartodb-popup .jspHorizontalBar .jspTrack, div.cartodb-popup .jspHorizontalBar .jspDrag { float: left; height: 100%; } div.cartodb-popup .jspArrow { background: #50506d; text-indent: -20000px; display: block; cursor: pointer; } div.cartodb-popup .jspArrow.jspDisabled { cursor: default; background: #80808d; } div.cartodb-popup .jspVerticalBar .jspArrow { height: 16px; } div.cartodb-popup .jspHorizontalBar .jspArrow { width: 16px; float: left; height: 100%; } div.cartodb-popup .jspVerticalBar .jspArrow:focus { outline: none; } div.cartodb-popup .jspCorner { background: #eeeef4; float: left; height: 100%; } * html div.cartodb-popup .jspCorner { margin: 0 -3px 0 0; } /* CartoDB light content styles */ div.cartodb-popup h2 { line-height:normal; } div.cartodb-popup h4 { display:block; width:190px; margin: 0; padding: 0; font:bold 11px "Helvetica Neue","Helvetica",Arial; color:#CCCCCC; text-transform:uppercase; word-wrap: break-word; } div.cartodb-popup p { display:block; width:190px; max-width: 190px; margin: 0; padding:0 0 7px; font:normal 13px "Helvetica",Arial; color:#333333; word-wrap: break-word; } div.cartodb-popup p.italic { font-style: italic; } div.cartodb-popup p.loading { position:relative; display:block; width:170px; max-width: 170px; margin: 0; padding:0 0 0 30px; font:normal 13px "Helvetica",Arial; color:#888; font-style:italic; word-wrap: break-word; line-height:21px; } div.cartodb-popup p.error { position:relative; display:block; width:170px; max-width:170px; margin:0; padding:0; font:normal 13px "Helvetica",Arial; color:#FF7F7F; font-style:italic; word-wrap: break-word; line-height:18px; } div.cartodb-popup p.empty { color:#999999; font-style: italic; } div.cartodb-popup div.spinner { position:absolute!important; display:inline; top:0; left:0; margin:10px 0 0 10px; } /* NEW CartoDB 2.0 popups */ div.cartodb-popup.v2 { width:226px; padding:0; margin:0 0 14px 0; background:none; -moz-box-shadow: 0 0 0 4px rgba(0,0,0,0.15); -webkit-box-shadow: 0 0 0 4px rgba(0,0,0,0.15); box-shadow: 0 0 0 4px rgba(0,0,0,0.15); -webkit-border-radius:2px; -moz-border-radius:2px; border-radius:2px; background:white; } div.cartodb-popup.v2:before { content:''; position:absolute; bottom:-14px; left:0; width:0; height:0; margin-left:28px; border-left:0px solid transparent; border-right:14px solid transparent; border-top:14px solid white; z-index:2; } div.cartodb-popup.v2 div.cartodb-popup-content-wrapper { width: auto; max-width: none; padding:12px; -webkit-border-radius:2px; -moz-border-radius:2px; border-radius:2px; background:none; } div.cartodb-popup.v2 div.cartodb-popup-content { width:auto; max-width:none; display:block; background:none; } div.cartodb-popup.v2 div.cartodb-popup-content p, div.cartodb-popup.v2 div.cartodb-popup-content h4 { width:auto; max-width:95%; display:block; } div.cartodb-popup.v2 div.cartodb-popup-tip-container { position:absolute; bottom:-20px; left:-4px; width:20px; height:16px; margin-left:28px; background:none; overflow:hidden; z-index:0; } div.cartodb-popup.v2 div.cartodb-popup-tip-container:before { content:''; position:absolute; width:20px; height:20px; left:0; top:-10px; margin-left:0; -ms-transform: skew(0,-45deg); -webkit-transform: skew(0,-45deg); transform: skew(0,-45deg); border-radius:0 0 0 10px; background:rgba(0,0,0,0.15); z-index:0; } div.cartodb-popup.v2 a.cartodb-popup-close-button { right:-12px; top:-12px; width:20px; height:20px; background:white; -webkit-border-radius:18px; -moz-border-radius:18px; border-radius:18px; box-shadow:0 0 0 3px rgba(0,0,0,0.15); } div.cartodb-popup.v2 a.cartodb-popup-close-button:before, div.cartodb-popup.v2 a.cartodb-popup-close-button:after { content:''; position:absolute; top:9px; left:6px; width:8px; height:2px; background:#397DBA; -webkit-border-radius:3px; -moz-border-radius:3px; border-radius:3px; } div.cartodb-popup.v2 a.cartodb-popup-close-button:before { -ms-transform: rotate(45deg); -webkit-transform: rotate(45deg); transform: rotate(45deg); } div.cartodb-popup.v2 a.cartodb-popup-close-button:after { -ms-transform: rotate(-45deg); -webkit-transform: rotate(-45deg); transform: rotate(-45deg); } div.cartodb-popup.v2 a.cartodb-popup-close-button:hover { box-shadow:0 0 0 3px rgba(0,0,0,0.25); } /* Hello IE */ @media \0screen\,screen\9 { div.cartodb-popup.v2 { border:4px solid #CCC; } div.cartodb-popup.v2 div.cartodb-popup-tip-container { position:absolute; width:0; height:0; margin-left:28px; z-index:2; bottom:-18px; left:-4px; border-left:0px solid transparent; border-right:18px solid transparent; border-top:18px solid white; } div.cartodb-popup.v2 a.cartodb-popup-close-button { right:-14px; top:-14px; width:18px; padding:0 0 0 2px; text-indent:0; font:bold 11px Arial; font-weight:700; text-decoration:none; text-align:center; line-height:20px; border:2px solid #CCC; } div.cartodb-popup.v2 a.cartodb-popup-close-button:before, div.cartodb-popup.v2 a.cartodb-popup-close-button:after { display:none; } div.cartodb-popup.v2 a.cartodb-popup-close-button:hover { border:2px solid #999; } } /** * CartoDB blue header popup styles */ div.cartodb-popup.header.blue div.cartodb-popup-header { background:url('../img/headers.png') no-repeat 0 -40px; } div.cartodb-popup.header.blue.header .cartodb-popup-header a { color:white; } div.cartodb-popup.header.blue div.cartodb-popup-header h4 { color:#1F4C7F; } div.cartodb-popup.header.blue div.cartodb-popup-header span.separator { background:#225386; } div.cartodb-popup.header.blue a.cartodb-popup-close-button { background:url('../img/headers.png') no-repeat -226px -40px; } div.cartodb-popup.header.blue a.cartodb-popup-close-button:hover { background-position:-226px -66px; } /* NEW CartoDB 2.0 blue header popups */ div.cartodb-popup.v2.header.blue div.cartodb-popup-header { background: none; background: -ms-linear-gradient(top, #4F9CD7, #2B68A8); background: -o-linear-gradient(right, #4F9CD7, #2B68A8); background: -webkit-linear-gradient(top, #4F9CD7, #2B68A8); background: -moz-linear-gradient(right, #4F9CD7, #2B68A8); -ms-filter: "progid:DXImageTransform.Microsoft.Gradient(startColorStr='#4F9CD7',endColorStr='#2B68A8',GradientType=0)"; } div.cartodb-popup.v2.header.blue a.cartodb-popup-close-button { background:white; } /** * CartoDB header popup styles (DEFAULT) */ div.cartodb-popup.header { padding:0; background:none; box-shadow:none; -webkit-box-shadow:none; -moz-box-shadow:none; -o-box-shadow:none; border-bottom:none; border-radius:0; -webkit-border-radius:0; -moz-border-radius:0; -o-border-radius:0; } div.cartodb-popup.header div.cartodb-popup-header { position:relative; width:188px; height:auto; max-height:62px; overflow:hidden; padding:17px 19px 17px 19px; background:url('../img/headers.png') no-repeat 0 -40px; } div.cartodb-popup.header div.cartodb-popup-header h1 { width:100%; margin:0; font:bold 21px "Helvetica Neue", "Helvetica", Arial; color:#FFFFFF; line-height:23px; text-shadow: 0 1px rgba(0,0,0,0.5); word-wrap:break-word; } div.cartodb-popup.header div.cartodb-popup-header h1 a { color:white; font-size:21px; word-wrap:break-word; } div.cartodb-popup.header div.cartodb-popup-header h1 a:hover { text-decoration: underline; } div.cartodb-popup.header div.cartodb-popup-header h1.loading { position:relative; display:block; width:auto; padding-right:0; padding-left:30px; font-size:14px; font-weight:normal; line-height:19px; } div.cartodb-popup.header div.cartodb-popup-header h1.error { position:relative; display:block; width:auto; padding-right:0; padding-left:0; font-size:14px; font-weight:normal; font-style: italic; line-height:19px; } div.cartodb-popup.header div.cartodb-popup-header h4 { color:#1F4C7F; } div.cartodb-popup.header div.cartodb-popup-header span.separator { position:absolute; bottom:0; left:4px; right:4px; height:1px; background:#225386; } div.cartodb-popup.header div.cartodb-popup-content { max-height:150px; } div.cartodb-popup.header a.cartodb-popup-close-button { background:url('../img/headers.png') no-repeat -226px -40px; } div.cartodb-popup.header a.cartodb-popup-close-button:hover { background-position:-226px -66px; } /* NEW CartoDB 2.0 header popups */ div.cartodb-popup.header.v2.header { -moz-box-shadow: 0 0 0 4px rgba(0,0,0,0.15); -webkit-box-shadow: 0 0 0 4px rgba(0,0,0,0.15); box-shadow: 0 0 0 4px rgba(0,0,0,0.15); -webkit-border-radius:2px; -moz-border-radius:2px; border-radius:2px; background:white; } div.cartodb-popup.v2.header div.cartodb-popup-header { position:relative; width:auto; height:auto; max-height:62px; overflow:hidden; padding:17px 12px; background: none; background: -ms-linear-gradient(top, #4F9CD7, #2B68A8); background: -o-linear-gradient(right, #4F9CD7, #2B68A8); background: -webkit-linear-gradient(top, #4F9CD7, #2B68A8); background: -moz-linear-gradient(right, #4F9CD7, #2B68A8); -ms-filter: "progid:DXImageTransform.Microsoft.Gradient(startColorStr='#4F9CD7',endColorStr='#2B68A8',GradientType=0)"; -webkit-border-top-left-radius: 2px; -webkit-border-top-right-radius: 2px; -moz-border-radius-topleft: 2px; -moz-border-radius-topright: 2px; border-top-left-radius: 2px; border-top-right-radius: 2px; } div.cartodb-popup.v2.header div.cartodb-popup-header:before { content:''; position:absolute; bottom:0; left:0; right:0; width:100%; height:1px; background:rgba(0,0,0,0.1); } div.cartodb-popup.v2.header a.cartodb-popup-close-button { right:-12px; top:-12px; width:20px; height:20px; background:white; -webkit-border-radius:18px; -moz-border-radius:18px; border-radius:18px; box-shadow:0 0 0 3px rgba(0,0,0,0.15); } div.cartodb-popup.v2.header a.cartodb-popup-close-button:before, div.cartodb-popup.v2.header a.cartodb-popup-close-button:after { content:''; position:absolute; top:9px; left:6px; width:8px; height:2px; background:#397DBA; -webkit-border-radius:3px; -moz-border-radius:3px; border-radius:3px; } div.cartodb-popup.v2.header a.cartodb-popup-close-button:before { -ms-transform: rotate(45deg); -webkit-transform: rotate(45deg); transform: rotate(45deg); } div.cartodb-popup.v2.header a.cartodb-popup-close-button:after { -ms-transform: rotate(-45deg); -webkit-transform: rotate(-45deg); transform: rotate(-45deg); } div.cartodb-popup.v2.header a.cartodb-popup-close-button:hover { box-shadow:0 0 0 3px rgba(0,0,0,0.25); } /* Hello IE */ @media \0screen\,screen\9 { div.cartodb-popup.header.v2 { border-bottom:4px solid #CCC; } div.cartodb-popup.v2.header div.cartodb-popup-header { background:#3B7FBD; -ms-filter: progid:DXImageTransform.Microsoft.Gradient(startColorStr='#4F9CD7',endColorStr='#2B68A8',GradientType=0); } } /** * CartoDB green header popup styles */ div.cartodb-popup.header.green div.cartodb-popup-header { background:url('../img/headers.png') no-repeat -252px -40px; } div.cartodb-popup.header.green div.cartodb-popup-header h4 { color:#00916D; } div.cartodb-popup.header.green div.cartodb-popup-header span.separator { background:#008E6A; } div.cartodb-popup.header.green a.cartodb-popup-close-button { background:url('../img/headers.png') no-repeat -478px -40px; } div.cartodb-popup.header.green a.cartodb-popup-close-button:hover { background-position:-478px -66px; } /* NEW CartoDB 2.0 green header popups */ div.cartodb-popup.v2.header.green div.cartodb-popup-header { background: none; background: -ms-linear-gradient(top, #00CC99, #00B185); background: -o-linear-gradient(right, #00CC99, #00B185); background: -webkit-linear-gradient(top, #00CC99, #00B185); background: -moz-linear-gradient(right, #00CC99, #00B185); -ms-filter: "progid:DXImageTransform.Microsoft.Gradient(startColorStr='#00CC99',endColorStr='#00B185',GradientType=0)"; } div.cartodb-popup.v2.header.green a.cartodb-popup-close-button { background:white; } div.cartodb-popup.v2.header.green a.cartodb-popup-close-button:before, div.cartodb-popup.v2.header.green a.cartodb-popup-close-button:after { background:#00CC99; } /* Hello IE */ @media \0screen\,screen\9 { div.cartodb-popup.v2.header.green a.cartodb-popup-close-button { color:#00CC99; } } /** * CartoDB orange header popup styles */ div.cartodb-popup.header.orange div.cartodb-popup-header { background:url('../img/headers.png') no-repeat -756px -40px; } div.cartodb-popup.header.orange div.cartodb-popup-header h4 { color:#CC2929; } div.cartodb-popup.header.orange div.cartodb-popup-header span.separator { background:#CC2929; } div.cartodb-popup.header.orange a.cartodb-popup-close-button { background:url('../img/headers.png') no-repeat -982px -40px; } div.cartodb-popup.header.orange a.cartodb-popup-close-button:hover { background-position:-982px -66px; } /* NEW CartoDB 2.0 orange header popups */ div.cartodb-popup.v2.header.orange div.cartodb-popup-header { background: none; background: -ms-linear-gradient(top, #FF6825, #FF3333); background: -o-linear-gradient(right, #FF6825, #FF3333); background: -webkit-linear-gradient(top, #FF6825, #FF3333); background: -moz-linear-gradient(right, #FF6825, #FF3333); -ms-filter: "progid:DXImageTransform.Microsoft.Gradient(startColorStr='#FF6825',endColorStr='#FF3333',GradientType=0)"; } div.cartodb-popup.v2.header.orange a.cartodb-popup-close-button { background:white; } div.cartodb-popup.v2.header.orange a.cartodb-popup-close-button:before, div.cartodb-popup.v2.header.orange a.cartodb-popup-close-button:after { background:#CC2929; } /* Hello IE */ @media \0screen\,screen\9 { div.cartodb-popup.v2.header.orange a.cartodb-popup-close-button { color:#CC2929; } } /** * CartoDB header with-image popup styles */ div.cartodb-popup.header.with-image div.cartodb-popup-header { position:relative; background:url('../img/headers.png') no-repeat -1008px 0; height:138px; max-height:104px; } div.cartodb-popup.header.with-image div.cartodb-popup-header .cover { display:block; position:absolute; overflow:hidden; width: 218px; height:135px; top: 4px; left: 4px; border-radius: 4px 4px 0 0; } div.cartodb-popup.header.with-image div.cartodb-popup-header .cover .shadow { position:absolute; width: 218px; height:55px; bottom: 0; left: 0; background:url('../img/shadow.png') no-repeat; z-index: 100; } div.cartodb-popup.header.with-image div.cartodb-popup-header .cover #spinner { position:absolute; top: 67px; left: 109px; } div.cartodb-popup.header.with-image div.cartodb-popup-header .cover img { position:absolute; border-radius: 4px 4px 0 0; display:none; } div.cartodb-popup.header.with-image div.cartodb-popup-header .image_not_found { position:absolute; top: 15px; left: 15px; width: 200px; display:none; } div.cartodb-popup.header.with-image div.cartodb-popup-header .image_not_found a { display:-moz-inline-stack;display:inline-block;vertical-align:top;*vertical-align:auto;zoom:1;*display:inline; margin: 3px 0 0 -2px; color: #888888; font-size:13px; font-family: "Helvetica", "Helvetica Neue", Arial, sans-serif; text-decoration: underline; } div.cartodb-popup.header.with-image div.cartodb-popup-header .image_not_found a:hover { color: #888888; text-decoration:underline; } div.cartodb-popup.header.with-image div.cartodb-popup-header .cover .image_not_found i { display:-moz-inline-stack;display:inline-block;vertical-align:top;*vertical-align:auto;zoom:1;*display:inline; width: 31px; height: 22px; background:transparent url('../img/image_not_found.png'); } div.cartodb-popup.header.with-image div.cartodb-popup-header h1 { position:absolute; bottom: 13px; left: 18px; width: 188px; z-index: 150; } div.cartodb-popup.header.with-image div.cartodb-popup-header h4 { color:#CCC; } div.cartodb-popup.header.with-image div.cartodb-popup-header span.separator { background:#CCC; } div.cartodb-popup.header.with-image a.cartodb-popup-close-button { background:url('../img/headers.png') no-repeat -226px -40px; } div.cartodb-popup.header.with-image a.cartodb-popup-close-button:hover { background-position:-226px -66px; } div.cartodb-popup.header.with-image .cartodb-popup-header h1 { display:none; } div.cartodb-popup.header.with-image .cartodb-popup-header h1.order1 { display:block; } div.cartodb-popup.header.with-image .cartodb-popup-content-wrapper .order1 { display:none; } /* NEW CartoDB 2.0 image header popups */ div.cartodb-popup.v2.header.with-image div.cartodb-popup-header { background: #2C2C2C; background: -ms-linear-gradient(top, #535353, #2C2C2C); background: -o-linear-gradient(right, #535353, #2C2C2C); background: -webkit-linear-gradient(top, #535353, #2C2C2C); background: -moz-linear-gradient(right, #535353, #2C2C2C); -ms-filter: "progid:DXImageTransform.Microsoft.Gradient(startColorStr='#535353',endColorStr='#2C2C2C',GradientType=0)"; } div.cartodb-popup.v2.header.with-image div.cartodb-popup-header h1 { width:85%; } div.cartodb-popup.v2.header.with-image div.cartodb-popup-header span.separator { left:0; right:0; background:#CCC; } div.cartodb-popup.v2.header.with-image a.cartodb-popup-close-button { background:white; } div.cartodb-popup.v2.header.with-image div.cartodb-popup-header .cover { display:block; width:100%; height:138px; top:0; left:0; -moz-border-radius:2px 2px 0 0; -webkit-border-radius:2px 2px 0 0; border-radius:2px 2px 0 0; overflow:hidden; } div.cartodb-popup.v2.header.with-image div.cartodb-popup-header .cover .shadow { width: 100%; height:57px; background: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(0%, rgba(0,0,0,0)), color-stop(100%, rgba(0,0,0,0.8))); background: -webkit-linear-gradient(top, rgba(0,0,0,0), rgba(0,0,0,0.8)); background: -moz-linear-gradient(top, rgba(0,0,0,0), rgba(0,0,0,0.8)); background: -o-linear-gradient(top, rgba(0,0,0,0), rgba(0,0,0,0.8)); background: linear-gradient(top, rgba(0,0,0,0), rgba(0,0,0,0.8)); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00000000', endColorstr='#000000',GradientType=0 ); } div.cartodb-popup.v2.header.with-image div.cartodb-popup-header .cover img { -moz-border-radius:2px 2px 0 0; -webkit-border-radius:2px 2px 0 0; border-radius:2px 2px 0 0; } /** * CartoDB yellow header popup styles */ div.cartodb-popup.header.yellow div.cartodb-popup-header { background:url('../img/headers.png') no-repeat -504px -40px; } div.cartodb-popup.header.yellow div.cartodb-popup-header h4 { color:#D8832A; } div.cartodb-popup.header.yellow div.cartodb-popup-header span.separator { background:#CC7A29; } div.cartodb-popup.header.yellow a.cartodb-popup-close-button { background:url('../img/headers.png') no-repeat -730px -40px; } div.cartodb-popup.header.yellow a.cartodb-popup-close-button:hover { background-position:-730px -66px; } /* NEW CartoDB 2.0 yellow header popups */ div.cartodb-popup.v2.header.yellow div.cartodb-popup-header { background: none; background: -ms-linear-gradient(top, #FFBF0D, #FF9933); background: -o-linear-gradient(right, #FFBF0D, #FF9933); background: -webkit-linear-gradient(top, #FFBF0D, #FF9933); background: -moz-linear-gradient(right, #FFBF0D, #FF9933); -ms-filter: "progid:DXImageTransform.Microsoft.Gradient(startColorStr='#FFBF0D',endColorStr='#FF9933',GradientType=0)"; } div.cartodb-popup.v2.header.yellow a.cartodb-popup-close-button { background:white; } div.cartodb-popup.v2.header.yellow a.cartodb-popup-close-button:before, div.cartodb-popup.v2.header.yellow a.cartodb-popup-close-button:after { background:#CC7A29; } /* Hello IE */ @media \0screen\,screen\9 { div.cartodb-popup.v2.header.yellow a.cartodb-popup-close-button { color:#CC7A29; } } /** * CartoDB infowindow light styles */ div.cartodb-popup h4 { color:#CCCCCC; } div.cartodb-popup p { color:#333333; } div.cartodb-popup p.loading { color:#888; } div.cartodb-popup p.error { color:#FF7F7F; } div.cartodb-popup p.empty { color:#999999; }/** * CartoDB map style components */ * { -webkit-margin-after:0; -webkit-margin-before:0; -webkit-padding-start:0; -webkit-padding-end:0; } div.cartodb-share { display:none; position:relative; float:right; margin: 20px 20px 0 0; z-index: 105; } div.cartodb-share a { width: 14px; height: 14px; display: block; color: #397DB8; font-size:10px; font-weight:bold; text-transform: uppercase; text-shadow: none; padding: 7px 7px; background: #ffffff url('../img/share.png') no-repeat 7px 8px; -webkit-box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; -moz-box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; border: 1px solid #999999; border-color: #C3C3C3; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; border: 1px solid #999999; } div.cartodb-share a:hover { background: #ffffff url('../img/share.png') no-repeat -28px 8px; } div.cartodb-share a:active, div.cartodb-share a:hover:active { background: #ffffff url('../img/share.png') no-repeat 7px 8px; } .cartodb-fullscreen { display:none; position:relative; margin: 11px 0 0 20px; float:left; clear:both; z-index: 105; } .cartodb-fullscreen a { display:block; width: 14px; height: 14px; padding: 7px; background: #ffffff url('../img/fullscreen.png') no-repeat 7px 3px; -webkit-box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; -moz-box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; border: 1px solid #999999; } .cartodb-fullscreen a:active { background-position: 7px 3px!important; } .cartodb-fullscreen a:hover { background-position: -19px 5px; } /* CartoDB Share Dialog styles */ .cartodb-share-dialog { display:none; } .cartodb-share-dialog .mamufas { position:fixed; top:0; left:0; right:0; bottom:0; background:rgba(0,0,0, 0.5); cursor: default; z-index:1000001; } .cartodb-share-dialog .modal { position:absolute; top: 50%; left: 50%; margin-left: -216px; margin-top: -107px; webkit-box-shadow: rgba(0, 0, 0, 0.15) 0 0 0 4px; -moz-box-shadow: rgba(0, 0, 0, 0.15) 0 0 0 4px; box-shadow: rgba(0, 0, 0, 0.15) 0 0 0 4px; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; border: 1px solid #999999; font-weight: bold; font-family: "Segoe UI Bold", "Helvetica Bold", "Helvetica", Arial; color: #333; line-height: normal; } .cartodb-share-dialog.small .modal { margin-left: -108px; margin-top: -165px; } .cartodb-share-dialog.small .block .buttons { margin: 0 0 10px 0; } .cartodb-share-dialog.small .block .buttons ul { border:none; padding: 0; } .cartodb-share-dialog.small .block .content .embed_code { padding: 0; } .cartodb-share-dialog .modal a.close { position:absolute; top:-15px; right:-15px; width:30px; height:15px; padding:7px 0 8px; background:white; font:normal 13px "Helvetica",Arial; text-decoration:none; webkit-box-shadow: rgba(0, 0, 0, 0.15) 0 0 0 4px; -moz-box-shadow: rgba(0, 0, 0, 0.15) 0 0 0 4px; box-shadow: rgba(0, 0, 0, 0.15) 0 0 0 4px; -webkit-border-radius: 50px; -moz-border-radius: 50px; -ms-border-radius: 50px; -o-border-radius: 50px; border-radius: 50px; line-height:14px; text-align:center; z-index:105; } .cartodb-share-dialog .block { background:white; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; webkit-box-shadow: rgba(0, 0, 0, 0.15) 0 0 4px 3px; -moz-box-shadow: rgba(0, 0, 0, 0.15) 0 0 4px 3px; box-shadow: rgba(0, 0, 0, 0.15) 0 0 4px 3px; } .cartodb-share-dialog .block .buttons ul { margin: 0; padding: 0 24px 0 0; border-right: 1px solid #E5E5E5; } .cartodb-share-dialog .block .buttons li { list-style:none; margin: 0 0 4px 0; padding: 0; } .cartodb-share-dialog .block .buttons li a { display:block; padding: 10px 13px 11px 30px; width: 121px; font-size: 13px; font-weight:bold; color:#fff; background:#3D8FCA; text-decoration:none; -webkit-border-radius: 3px; -moz-border-radius: 3px; -ms-border-radius: 3px; -o-border-radius: 3px; border-radius: 3px; } /* iPhone landscape */ @media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : landscape) { /*.cartodb-map-wrapper div.cartodb-overlay.overlay-text.desktop { display:none; }*/ /*.cartodb-map-wrapper div.cartodb-overlay.overlay-text.mobile { display:block; }*/ } @media only screen and (min-width: 360px) and (max-width: 490px) { /*div.cartodb-overlay.overlay-text.desktop { display:none; }*/ /*div.cartodb-overlay.overlay-text.mobile { display:block; }*/ } /* iPhone portrait */ @media only screen and (min-device-width : 320px) and (max-device-width : 480px) { /*.cartodb-map-wrapper div.cartodb-overlay.overlay-text.desktop { display:none; }*/ /*.cartodb-map-wrapper div.cartodb-overlay.overlay-text.mobile { display:block; }*/ div.cartodb-header h1 { width:78%; } div.cartodb-header > p { width:80%; } } /* iPad */ @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) { div.cartodb-header h1 { width:78%; } div.cartodb-header > p { width:80%; } } @media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and ( min--moz-device-pixel-ratio: 2), only screen and ( -o-min-device-pixel-ratio: 2/1), only screen and ( min-device-pixel-ratio: 2), only screen and ( min-resolution: 192dpi), only screen and ( min-resolution: 2dppx) { div.cartodb-header h1 { width:78%; } div.cartodb-header > p { width:80%; } div.cartodb-zoom a { background:url('../img/other@2x.png') no-repeat 0 0!Important; background-size: 113px 34px!Important; } div.cartodb-zoom a.zoom_in { background-position: -68px 9px!important } div.cartodb-zoom a.zoom_out { background-position:-94px 10px!important; } div.cartodb-header div.social a.facebook { background:url('../img/other@2x.png') no-repeat 0 0!Important; background-size: 113px 34px!Important; } div.cartodb-header div.social a.twitter { background:url('../img/other@2x.png') no-repeat -26px 0!Important; background-size: 113px 34px!Important; } div.cartodb-searchbox span.loader { background: url('../img/loader@2x.gif') no-repeat center center white!Important; background-size: 16px 16px!Important; } div.cartodb-mobile .aside div.cartodb-searchbox span.loader { background: url('../img/dark_loader@2x.gif') no-repeat center center #292929!Important; background-size: 16px 16px!Important; } div.cartodb-tiles-loader div.loader { background: url('../img/loader@2x.gif') no-repeat center center white!Important; background-size: 16px 16px!Important; } div.cartodb-searchbox input.submit { background:url('../img/other@2x.png') no-repeat -56px 0!Important; background-size: 113px 34px!Important; } .cartodb-mobile .aside .cartodb-searchbox input.submit { background:url('../img/mobile_zoom.png') no-repeat 0 0!Important; } } .cartodb-share-dialog .block .buttons li a.twitter { background:#3D8FCA url('../img/twitter.png') no-repeat 10px 50%; } .cartodb-share-dialog .block .buttons li a.twitter:hover { background-color:#3272A0; } .cartodb-share-dialog .block .buttons li a.facebook { background:#3B5998 url('../img/facebook.png') no-repeat 10px 50%; } .cartodb-share-dialog .block .buttons li a.facebook:hover { background-color: #283C65; } .cartodb-share-dialog .block .buttons li a.link { background:#f37f7b url('../img/link.png') no-repeat 10px 50%; } .cartodb-share-dialog .block .buttons li a.link:hover { background-color:#DC6161; } .cartodb-share-dialog .block h3, .cartodb-share-dialog .block p, .cartodb-share-dialog .block a, .cartodb-share-dialog .block label {letter-spacing:0;} .cartodb-share-dialog .block div.head { position:relative; padding: 5px 26px; border-bottom:1px solid #E5E5E5; } .cartodb-share-dialog .block h3 { margin: 1em 0; font-size: 15px; font-weight: bold; } .cartodb-share-dialog .block h4 { font-size: 13px; font-weight: bold; color: #666666; padding: 0; margin: 0; margin: 0 0 9px 0; } .cartodb-share-dialog .block .content .buttons, .cartodb-share-dialog .block .content .embed_code { display:inline-block; zoom: 1; *display: inline; vertical-align:top; } .cartodb-share-dialog .block .content .embed_code { padding-left: 24px; } .cartodb-share-dialog .block .content .embed_code textarea { resize: none; padding: 5px; width: 153px; height: 104px; border: 1px solid #C3C3C3; background: #F5F5F5; font-size: 11px; color: #666666; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; } .cartodb-share-dialog .block .content { padding: 20px 26px 30px 26px; } /* MOBILE */ .cartodb-mobile { width: 100%; height: 100%; z-index: 100000000; } .cartodb-mobile .cartodb-header { background: none; z-index: 100000; } .cartodb-mobile .cartodb-header .content { padding: 0; } .cartodb-mobile .cartodb-header .hgroup { position:relative; height: 40px; padding: 10px; } .cartodb-mobile.with-fullscreen .cartodb-header .hgroup { position: relative; margin-left: 60px; margin-right: 70px; } .cartodb-mobile.with-header .cartodb-header .content .hgroup .title, .cartodb-mobile.with-header .cartodb-header .content .hgroup .description { display: block; } .cartodb-mobile .cartodb-header .content .title , .cartodb-mobile .cartodb-header .content .description { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .cartodb-mobile .cartodb-header .content .button { height: 58px; width: 58px; background-color: rgba(0, 0, 0, 0.5); line-height: normal; z-index: 99999; } .cartodb-mobile.with-header .cartodb-header { background-color: rgba(0, 0, 0, 0.5); } .cartodb-mobile.with-fullscreen .cartodb-header .content .fullscreen { display:block; } .cartodb-mobile.with-header .cartodb-header .content .fullscreen { background: none; } .cartodb-mobile .cartodb-header .content .fullscreen { display: none; position:relative; top: 0px; left: 0px; float: left; width: 60px; height: 60px; margin: auto; padding: 0; background: rgba(0,0,0,.5); cursor: pointer; z-index: 10; -webkit-border-radius: 0 0 5px 0; -moz-border-radius: 0 0 5px 0; -ms-border-radius: 0 0 5px 0; -o-border-radius: 0 0 5px 0; border-radius: 0 0 5px 0; -webkit-transform-style: "ease-in"; -moz-transform-style: "ease-in"; -ms-transform-style: "ease-in"; -o-transform-style: "ease-in"; transform-style: "ease-in"; -webkit-transition-property: background; -moz-transition-property: background; -o-transition-property: background; transition-property: background; -webkit-transition-duration: 150ms; -moz-transition-duration: 150ms; -o-transition-duration: 150ms; transition-duration: 150ms; } .cartodb-mobile.with-header .cartodb-header .content .fullscreen { border-right: 1px solid rgba(255, 255, 255, .35); -webkit-border-radius: 0; -moz-border-radius: 0; -ms-border-radius: 0; -o-border-radius: 0; border-radius: 0; } .cartodb-mobile .cartodb-header .content .fullscreen:hover, .cartodb-mobile.with-header .cartodb-header .content .fullscreen:hover { background: rgba(0,0,0,.3); } .cartodb-mobile .cartodb-header .content .fullscreen:before { content: ''; width: 60px; height: 60px; background:url('../img/fullscreen_mobile.png') no-repeat 50% 50%; background-size: 28px 28px; position: absolute; } .cartodb-mobile.with-search .cartodb-header .content .toggle, .cartodb-mobile.with-layers .cartodb-header .content .toggle { display: block; } .cartodb-mobile .cartodb-header .content .toggle { display: none; position:relative; top: 0; right: 0; float: right; width: 70px; height: 60px; margin: auto; padding: 0; background: rgba(0,0,0, .5); cursor: pointer; z-index: 10; -webkit-border-radius: 0 0 0 5px; -moz-border-radius: 0 0 0 5px; -ms-border-radius: 0 0 0 5px; -o-border-radius: 0 0 0 5px; border-radius: 0 0 0 5px; -webkit-transform-style: "ease-in"; -moz-transform-style: "ease-in"; -ms-transform-style: "ease-in"; -o-transform-style: "ease-in"; transform-style: "ease-in"; -webkit-transition-property: background; -moz-transition-property: background; -o-transition-property: background; transition-property: background; -webkit-transition-duration: 150ms; -moz-transition-duration: 150ms; -o-transition-duration: 150ms; transition-duration: 150ms; } .cartodb-mobile .cartodb-header .content .toggle:hover, .cartodb-mobile.with-header .cartodb-header .content .toggle:hover { background: rgba(0,0,0,.3); } .cartodb-mobile.with-header .cartodb-header .content .toggle { background: none; border-left: 1px solid rgba(255, 255, 255, .35); -webkit-border-radius: 0; -moz-border-radius: 0; -ms-border-radius: 0; -o-border-radius: 0; border-radius: 0; } .cartodb-mobile .cartodb-header .content .toggle:before { content: ''; width: 70px; height: 60px; background:url('../img/toggle_aside.png') no-repeat 50% 50%; background-size: 30px 30px; position: absolute; } .cartodb-mobile.with-zoom .cartodb-zoom { position: absolute; top: 0px; z-index:100000; } .cartodb-mobile.with-fullscreen .cartodb-zoom, .cartodb-mobile.with-zoom.with-header .cartodb-zoom { top: 60px; } .cartodb-mobile .aside { position:absolute; width: 250px; height: 100%; top: 0; right: -250px; background:#2D2D2D; cursor: default; z-index: 1000010; } .cartodb-mobile .aside .cartodb-searchbox { position: relative; display: none; float: none; margin: 0; width: 100%; height: auto; -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; background: transparent; -webkit-border-radius: 0; -moz-border-radius: 0; -ms-border-radius: 0; -o-border-radius: 0; border-radius: 0; border:none; border-bottom: 1px solid #505050; z-index: 105; } .cartodb-mobile .aside .cartodb-searchbox input.text { border: none; position: initial; top:initial; left:initial; height: 39px; padding: 10px 18px; width: 185px; font-size: 13px; color: #fff; } .cartodb-mobile .aside .cartodb-searchbox input.text::-webkit-input-placeholder { font-style: italic; } .cartodb-mobile .aside .cartodb-searchbox input.text:-moz-placeholder { /* Firefox 18- */ font-style: italic; } .cartodb-mobile .aside .cartodb-searchbox input.text::-moz-placeholder { /* Firefox 19+ */ font-style: italic; } .cartodb-mobile .aside .cartodb-searchbox input.text:-ms-input-placeholder { font-style: italic; } .cartodb-mobile .aside .cartodb-searchbox span.loader { left: initial; top: 18px; right: 14px; background: url('../img/dark_loader.gif') no-repeat center center; } .cartodb-mobile .aside .cartodb-searchbox input.submit { right: 18px; top: 23px; background:#f1f1f1; width: 14px; height: 14px; left:initial; outline:none; cursor:pointer; background:url('../img/mobile_zoom.png') no-repeat 0 0; } .cartodb-mobile .aside .layer-container { position:relative; height: 100%; } .cartodb-mobile .aside .scrollpane { width: 100%; height: 100%; overflow: hidden; outline:none; /*padding-bottom: 25px;*/ } .cartodb-mobile .aside .scrollpane .jspContainer { overflow: hidden; position: relative; } .cartodb-mobile .aside .scrollpane .jspPane { position: absolute; } .cartodb-mobile .aside .scrollpane .jspVerticalBar { position: absolute; top: 0; right: 7px; width: 5px; height: 100%; background: none; z-index: 20; } .cartodb-mobile .aside .scrollpane .jspVerticalBar * { margin: 0; padding: 0; } .cartodb-mobile .aside .scrollpane .jspCap { display: none; } .cartodb-mobile .aside .scrollpane .jspTrack { background: none; position: relative; } .cartodb-mobile .aside .scrollpane .jspDrag { background: rgba(#BBB, .5); border-radius:5px; position: relative; top: 0; left: 0; cursor: pointer; } .cartodb-mobile .aside .scrollpane .jspArrow { background: none; text-indent: -20000px; display: block; cursor: pointer; } .cartodb-mobile .aside .scrollpane .jspVerticalBar .jspArrow { height: 10px; } .cartodb-mobile .aside .scrollpane .jspVerticalBar .jspArrow:focus { outline: none; } .cartodb-mobile .aside .scrollpane .jspCorner { background: #eeeef4; float: left; height: 100%; } .cartodb-mobile .aside .layer-container > h3 { padding: 23px 20px; color: #999999; font: bold 12px "Helvetica", Arial, sans-serif; text-transform: uppercase; background: #292929; border-bottom: 1px solid #585858; } .cartodb-mobile .aside .layer-container .layers { margin: 0; padding: 0 10px; } .cartodb-mobile .aside .layer-container .layers > li { padding: 5px 10px; color: #fff; list-style: none; border-bottom: 1px solid #585858; } .cartodb-mobile .aside .layer-container .layers > li:last-child h3, .cartodb-mobile .aside .layer-container .layers > li:last-child { border: none; } .cartodb-mobile .aside .layer-container .layers > li a.toggle { background:none; width: 21px; height: 10px; background: #191919; position:relative; top: 2px; float: right; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; } .cartodb-mobile .aside .layer-container .layers > li a.toggle.hide { display:none; } .cartodb-mobile .aside .layer-container .layers > li.hidden a.toggle:before { left: 0; } .cartodb-mobile .aside .layer-container .layers > li a.toggle:before { position:absolute; content:''; top:1px; right:0; width: 7px; height: 7px; -webkit-border-radius: 100px; -moz-border-radius: 100px; -ms-border-radius: 100px; -o-border-radius: 100px; border-radius: 100px; background: #fff; } .cartodb-mobile .aside .layer-container .layers > li h3 { font: bold 12px "Helvetica", Arial, sans-serif; text-transform: uppercase; padding: 12px 0 13px 0; } .cartodb-mobile .aside .layer-container .layers > li.has-toggle h3 { cursor: pointer; } .cartodb-mobile .aside .layer-container .layers > li.has-legend.hidden h3, .cartodb-mobile .aside .layer-container .layers > li.hidden h3 { color: #666666; border:none; padding: 12px 0 13px 0; } .cartodb-mobile .aside .layer-container .layers > li.hidden.has-legend div.cartodb-legend { display:none!important; } .cartodb-mobile .aside .layer-container .layers > li.hidden.has-legend h3 { margin-bottom: 0; } .cartodb-mobile .aside .layer-container .layers > li.has-legend h3 { border-bottom: 1px solid #585858; } .cartodb-mobile .aside .layer-container .layers > li div.cartodb-legend { position:relative; border:none; webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; background: none; padding: 0; margin: 10px 0 18px 0; padding: 2px 0 0 0; bottom: auto; right: auto; cursor: text; } .cartodb-mobile .aside .layer-container .layers > li div.cartodb-legend.bubble ul li.graph { border:none; } .cartodb-mobile .aside .layer-container .layers > li div.cartodb-legend.bubble ul li.graph .bubbles { background:url('../img/dark_bubbles.png') no-repeat 0 0; } .cartodb-mobile .aside .layer-container .layers > li div.cartodb-legend .graph { border: 1px solid #1A1108; } .cartodb-mobile .aside .layer-container .layers > li div.cartodb-legend ul li { height: auto; padding: 0; font-size: 12px; color: #fff; font-weight: normal; font-family: "Helvetica", Arial, sans-serif; text-transform: none; line-height: normal; } .cartodb-mobile .aside .layer-container .layers > li div.cartodb-legend ul li .bullet { margin-top: 2px; } .cartodb-mobile .aside .layer-container .layers > li div.cartodb-legend ul li.max, .cartodb-mobile .aside .layer-container .layers > li div.cartodb-legend ul li.min { font-size: 10px; } .cartodb-mobile div.cartodb-timeslider .slider-wrapper { position:absolute; top: 17px; } .cartodb-mobile div.cartodb-timeslider .slider { width: 100%; } .cartodb-mobile div.cartodb-timeslider { height:40px; width:auto; margin-bottom:0; -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; -webkit-border-radius: 0; -moz-border-radius: 0; -ms-border-radius: 0; -o-border-radius: 0; border-radius: 0; border: 1px solid #E5E5E5; border-left: none; border-right: none; border-top: 1px solid rgba(0,0,0, .2); z-index: 1000001; } .cartodb-mobile div.cartodb-timeslider .slider-wrapper { display:block; width:100%; height:4px; padding:0; } .cartodb-mobile div.cartodb-timeslider { width:100%!important; } .cartodb-mobile div.cartodb-timeslider ul { width:100%; position:relative; clear:both; overflow:hidden; } .cartodb-mobile div.cartodb-timeslider ul li { display: block; background:#fff; float:left; } .cartodb-mobile div.cartodb-timeslider ul li.controls { width: 50px; } .cartodb-mobile div.cartodb-timeslider ul li.time { width: 80px; } .cartodb-mobile div.cartodb-timeslider ul li.last { position:absolute; left:145px; right: 10px; } .cartodb-mobile div.cartodb-timeslider ul li.controls a.button { -webkit-border-radius: 0; -moz-border-radius: 0; -ms-border-radius: 0; -o-border-radius: 0; border-radius: 0; } .cartodb-mobile .cartodb-attribution { display:none; list-style:none; background: #fff; position: absolute; padding: 9px 12px; margin: 0; right: 20px; bottom: 20px; color:#999999; -webkit-border-radius: 3px; -moz-border-radius: 3px; -ms-border-radius: 3px; -o-border-radius: 3px; border-radius: 3px; z-index: 10000001; font:12px/1.5 "Helvetica Neue", Arial, Helvetica, sans-serif; } .cartodb-mobile .cartodb-attribution a { color: #0078A8; } .cartodb-mobile .cartodb-attribution li { padding: 0; margin: 3px; display:inline-block; zoom: 1; *display: inline; vertical-align:top; color: #999999; } .cartodb-mobile .cartodb-attribution li a { text-transform: capitalize; color: #0078A8; } .cartodb-mobile .backdrop { display:none; position: absolute; top: 0; left: 0; right:0; bottom: 0; background: #000; filter: alpha(opacity=20); filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=20); opacity: 0.2; z-index: 10000000; } .cartodb-mobile.with-torque .cartodb-attribution-button { bottom: 59px; } .cartodb-mobile .cartodb-attribution-button { display: none; width: 20px; height: 20px; background: #fff; position: absolute; right: 20px; bottom: 20px; color: #999999; text-align: center; text-decoration: none; -webkit-border-radius: 100px; -moz-border-radius: 100px; -ms-border-radius: 100px; -o-border-radius: 100px; border-radius: 100px; background: #fff url('../img/bg-attribution-button.png') no-repeat 49% 50%; font:12px/1.5 "Helvetica Neue", Arial, Helvetica, sans-serif; z-index: 10; } .cartodb-mobile .cartodb-attribution-button:before { position:absolute; content: ''; top: -3px; left: -3px; width: 20px; height: 20px; border: 3px solid rgba(0, 0, 0, 0.3); -webkit-border-radius: 100px; -moz-border-radius: 100px; -ms-border-radius: 100px; -o-border-radius: 100px; border-radius: 100px; -webkit-transform-style: "ease-in"; -moz-transform-style: "ease-in"; -ms-transform-style: "ease-in"; -o-transform-style: "ease-in"; transform-style: "ease-in"; -webkit-transition-property: border; -moz-transition-property: border; -o-transition-property: border; transition-property: border; -webkit-transition-duration: 150ms; -moz-transition-duration: 150ms; -o-transition-duration: 150ms; transition-duration: 150ms; } .cartodb-mobile .cartodb-attribution-button:hover:before { border: 3px solid rgba(0, 0, 0, 0.7); } /* LEGENDS */ div.cartodb-legend-stack { position:absolute; bottom: 35px; right: 20px; display:none; webkit-box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; -moz-box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; border: 1px solid #999999; background: white; z-index: 105; cursor: text; } div.cartodb-legend-stack div.cartodb-legend { position:relative; top: auto; right: auto; left: auto; bottom: auto; background: none; border:none; margin: 0; -webkit-border-radius: 0; -moz-border-radius: 0; -ms-border-radius: 0; -o-border-radius: 0; border-radius: 0px; border-bottom: 1px solid #999; webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; cursor: text; } div.cartodb-legend-stack div.cartodb-legend:last-child { border-bottom: none; } div.cartodb-legend { position:absolute; bottom: 35px; right: 20px; padding: 13px 15px 14px 15px; font:normal 13px "Helvetica",Arial; color:#858585; text-align: left; webkit-box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; -moz-box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; border: 1px solid #999999; background: white; z-index: 105; } div.cartodb-legend .legend-title { margin: 0 0 10px 0; text-align:left; color:#666; font-weight:bold; font-size:11px; text-transform: uppercase; } div.cartodb-legend ul { padding: 0; margin: 0; list-style: none; } div.cartodb-legend ul li { padding: 0; margin: 0; font-size: 10px; color: #666666; font-weight:bold; font-family: "Helvetica", Arial; text-transform: uppercase; line-height: normal; } /* None legend */ div.cartodb-legend-stack div.cartodb-legend.none, div.cartodb-legend.none { display:none; } div.map div.cartodb-legend-stack div.cartodb-legend.wrapper .cartodb-legend { padding: 0; display:block; } div.cartodb-legend.wrapper .cartodb-legend { display:block; padding: 0; } /* Custom legend */ div.cartodb-legend.custom ul li, div.cartodb-legend.category ul li, div.cartodb-legend.color ul li { position:relative; margin: 0 0 7px 0; font-size: 10px; color: #666666; font-weight:bold; font-family: "Helvetica", Arial; text-transform: uppercase; text-align: left; height: 10px; line-height: 10px; vertical-align:middle; } div.cartodb-legend.custom ul li.bkg, div.cartodb-legend.category ul li.bkg, div.cartodb-legend.color ul li.bkg { height: 20px; line-height: 24px; margin: 0 0 15px 0; } div.cartodb-legend.custom ul li.bkg .bullet, div.cartodb-legend.category ul li.bkg .bullet, div.cartodb-legend.color ul li.bkg .bullet { height: 20px; width: 20px; border: 1px solid rgba(0, 0, 0, .3); border:none; background-size: 26px 26px!important; background-position: center center!important; -webkit-border-radius: 0; -moz-border-radius: 0; -ms-border-radius: 0; -o-border-radius: 0; border-radius: 0; } div.cartodb-legend.custom ul li.bkg:last-child, div.cartodb-legend.color ul li.bkg:last-child, div.cartodb-legend.category ul li.bkg:last-child { margin: 0 0 5px 0; } div.cartodb-legend.custom ul li:last-child, div.cartodb-legend.color ul li:last-child, div.cartodb-legend.category ul li:last-child { margin: 0; } div.cartodb-legend.custom ul li .bullet, div.cartodb-legend.category ul li .bullet, div.cartodb-legend.color ul li .bullet { float:left; margin: 0 5px 0 0; width: 3px; height: 3px; -webkit-border-radius: 50%; -moz-border-radius: 50%; -ms-border-radius: 50%; -o-border-radius: 50%; border-radius: 50%; padding: 2px; background:#fff; border: 1px solid rgba(0, 0, 0, .2); z-index: 1000; } /* Bubble legend */ div.cartodb-legend.bubble { text-align:center; } div.cartodb-legend.bubble ul { clear:both; overflow: hidden; display: -moz-inline-stack; display: inline-block; } div.cartodb-legend.bubble ul li { position:relative; float: left; top: 15px; } div.cartodb-legend.bubble ul li.graph { top: 0; width: 120px; height: 40px; margin: 0 10px; background: #f1f1f1; } div.cartodb-legend.bubble ul li.graph .bubbles { background:url('../img/bubbles.png') no-repeat 0 0; width:120px; height:40px; } /* Choropleth legend */ div.cartodb-legend.choropleth { padding: 13px 15px 15px 15px; } div.cartodb-legend.choropleth ul { min-width: 210px; } div.cartodb-legend.choropleth li.min { float: left; margin: 0 0 5px 0; } div.cartodb-legend.choropleth li.max { float: right; margin: 0 0 5px 0; } div.cartodb-legend.choropleth li.graph div { width: 10px; height: 22px; } div.cartodb-legend.choropleth li.graph .quartile { display: table-cell; } div.cartodb-legend.choropleth li.graph.count_7 .quartile { width: 30px; } div.cartodb-legend.choropleth li.graph.count_5 .quartile { width: 42px; } div.cartodb-legend.choropleth li.graph.count_3 .quartile { width: 70px; } div.cartodb-legend.choropleth li.graph .colors { display: table-row; } div.cartodb-legend.choropleth li.graph { clear:both; overflow:hidden; display: table; width: 100%; height: 22px; -webkit-border-radius: 3px; -moz-border-radius: 3px; -ms-border-radius: 3px; -o-border-radius: 3px; border-radius: 3px; -moz-background-clip: padding; -webkit-background-clip: padding; background-clip: padding; /*box-shadow: inset 0px 0px 0px 1px rgba(0, 0, 0, 0.2);*/ border: 1px solid #b3b3b3; } /* Density legend */ div.cartodb-legend.density { padding: 13px 15px 15px 15px; } div.cartodb-legend.density ul { min-width: 210px; } div.cartodb-legend.density li.min { float: left; margin: 0 0 5px 0; } div.cartodb-legend.density li.max { float: right; margin: 0 0 5px 0; } div.cartodb-legend.density li.graph div { width: 10px; height: 22px; } div.cartodb-legend.density li.graph .quartile { display: table-cell; } div.cartodb-legend.density li.graph.count_7 .quartile { width: 30px; } div.cartodb-legend.density li.graph.count_5 .quartile { width: 42px; } div.cartodb-legend.density li.graph.count_3 .quartile { width: 70px; } div.cartodb-legend.density li.graph .colors { display: table-row; } div.cartodb-legend.density li.graph { clear:both; overflow:hidden; display: table; width: 100%; height: 22px; -webkit-border-radius: 3px; -moz-border-radius: 3px; -ms-border-radius: 3px; -o-border-radius: 3px; border-radius: 3px; -moz-background-clip: padding; -webkit-background-clip: padding; background-clip: padding; /*box-shadow: inset 0px 0px 0px 1px rgba(0, 0, 0, 0.2);*/ border: 1px solid #b3b3b3; } /* Intensity legend */ div.cartodb-legend.intensity { padding: 13px 15px 15px 15px; } div.cartodb-legend.intensity ul { min-width: 210px; } div.cartodb-legend.intensity li.min { float: left; margin: 0 0 5px 0; } div.cartodb-legend.intensity li.max { float: right; margin: 0 0 5px 0; } div.cartodb-legend.intensity li.graph { clear:both; width: 100%; height: 22px; background:#f1f1f1; -webkit-border-radius: 3px; -moz-border-radius: 3px; -ms-border-radius: 3px; -o-border-radius: 3px; border-radius: 3px; -moz-background-clip: padding; -webkit-background-clip: padding; background-clip: padding; /*border: 1px solid #b3b3b3;*/ -webkit-box-shadow: inset 0px 0px 0px 1px rgba(0, 0, 0, 0.2); -o-box-shadow: inset 0px 0px 0px 1px rgba(0, 0, 0, 0.2); -moz-box-shadow: inset 0px 0px 0px 1px rgba(0, 0, 0, 0.2); -ms-box-shadow: inset 0px 0px 0px 1px rgba(0, 0, 0, 0.2); box-shadow: inset 0px 0px 0px 1px rgba(0, 0, 0, 0.2); } /* CartoDB Zoom styles */ div.cartodb-zoom { position: relative; float:left; display:block; margin: 20px 0 0 20px; width: 28px; -webkit-box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; -moz-box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; background: white; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; border: 1px solid #999999; z-index: 105; } div.cartodb-zoom a { position:relative; display: block; width: 28px; height: 28px; padding: 0; font: bold 20px "Arial"; color: #999999; text-align: center; text-decoration: none; text-indent: -9999px; line-height: 0; font-size: 0; background:url('../img/other.png') no-repeat 0 0; } div.cartodb-zoom a.zoom_in { border-bottom: 1px solid #E6E6E6; background-position:-68px 10px; -webkit-border-top-left-radius: 4px; -webkit-border-top-right-radius: 4px; -moz-border-radius-topleft: 4px; -moz-border-radius-topright: 4px; border-top-left-radius: 4px; border-top-right-radius: 4px; } div.cartodb-zoom a.zoom_in:hover { background-position:-68px -14px; cursor: pointer; } div.cartodb-zoom a.zoom_out { background-position:-94px 10px; -webkit-border-bottom-left-radius: 4px; -webkit-border-bottom-right-radius: 4px; -moz-border-radius-bottomleft: 4px; -moz-border-radius-bottomright: 4px; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; } div.cartodb-zoom a.zoom_out:hover { background-position:-94px -14px; cursor: pointer; } div.cartodb-zoom a.disabled { filter: alpha(opacity=20); filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=20); opacity: 0.2; } div.cartodb-zoom a.disabled:hover { cursor: default; color: #999999; } /* CartoDB zoom info control */ div.cartodb-zoom-info { position:absolute; display:block; top:100px; left:20px; margin:20px 0 0 0; width: 28px; height:28px; font:normal 13px "Helvetica",Arial; color:#858585; text-align: center; line-height: 28px; -webkit-box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; -moz-box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; border: 1px solid #999999; background: white; z-index: 105; } /* Tiles loader control */ div.cartodb-tiles-loader { position:relative; float:left; display:block; left:0; top:0; } div.cartodb-tiles-loader div.loader { position:absolute; display:block; top:70px; left:-30px; margin:20px 0 0 0; width: 28px; height:28px; -webkit-box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; -moz-box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; background: url('../img/loader.gif') no-repeat center center white; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; border: 1px solid #999999; z-index: 105; } /* CartoDB layer selector box */ div.cartodb-layer-selector-box { display:none; position: relative; float:right; margin: 20px 20px 0 0; width: 142px; height: 29px; color: #CCCCCC; font-size:13px; -webkit-box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; -moz-box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; background: white; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; border: 1px solid #999999; z-index:100000; } div.cartodb-layer-selector-box a.layers { float:left; width: 126px; padding: 6px 8px; line-height:20px; color: #CCC; text-decoration:none; font-family: "robotoregular", Helvetica, Arial, Sans-serif; } div.cartodb-layer-selector-box a.layers:hover { color:#bbb; } div.cartodb-layer-selector-box a.layers:hover .count { background:#ccc; } div.cartodb-layer-selector-box a.layers .count { position:absolute; right:6px; top:6px; width:auto; padding: 3px 6px; margin:0; font-size:10px; color: #fff; line-height:12px; background:#DDDDDD; -webkit-border-radius: 2px; -moz-border-radius: 2px; -ms-border-radius: 2px; -o-border-radius: 2px; border-radius: 2px; } div.cartodb-layer-selector-box div.cartodb-dropdown { padding:0; margin:0; } div.cartodb-layer-selector-box div.cartodb-dropdown ul { padding:0; margin:0; list-style:none; border:1px solid 999999; } div.cartodb-layer-selector-box div.cartodb-dropdown ul li { border-bottom:1px solid #EDEDED; position:relative; } div.cartodb-layer-selector-box div.cartodb-dropdown ul li:last-child { border-bottom:none; } div.cartodb-layer-selector-box div.cartodb-dropdown ul li:hover { background:#fff; } div.cartodb-layer-selector-box div.cartodb-dropdown ul li a.layer { display: -moz-inline-stack; display: inline-block; vertical-align: middle; width:104px; padding: 13px 13px 15px 13px; zoom: 1; color: #666666; font:normal 13px "Helvetica Neue","Helvetica",Arial; text-decoration:none; overflow:hidden; white-space:nowrap; text-overflow: ellipsis; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none; } div.cartodb-layer-selector-box div.cartodb-dropdown ul li:hover a.layer { text-decoration: underline; color:#545454; } div.cartodb-layer-selector-box div.cartodb-dropdown ul li a.switch { position:absolute; top: 13px; right: 10px; text-indent:-9999px; vertical-align:middle; width:23px; height:12px; padding: 0; -webkit-border-radius: 12px; -moz-border-radius: 12px; -ms-border-radius: 12px; -o-border-radius: 12px; border-radius: 12px; -webkit-transform-style: "linear"; -moz-transform-style: "linear"; -ms-transform-style: "linear"; -o-transform-style: "linear"; transform-style: "linear"; -webkit-transition-property: left; -moz-transition-property: left; -o-transition-property: left; transition-property: left; -webkit-transition-duration: 180ms; -moz-transition-duration: 180ms; -o-transition-duration: 180ms; transition-duration: 180ms; text-decoration:none; border:1px solid #44759E; } div.cartodb-layer-selector-box div.cartodb-dropdown ul li a.switch:before { position:absolute; content:' '; top:0; left:0; width:100%; height:100%; -webkit-border-radius: 12px; -moz-border-radius: 12px; -ms-border-radius: 12px; -o-border-radius: 12px; border-radius: 12px; background: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(0%, rgba(0, 0, 0, 0.18)), color-stop(100%, rgba(0, 0, 0, 0))); background: -webkit-linear-gradient(rgba(0, 0, 0, 0.18), rgba(0, 0, 0, 0)); background: -moz-linear-gradient(rgba(0, 0, 0, 0.18), rgba(0, 0, 0, 0)); background: -o-linear-gradient(rgba(0, 0, 0, 0.18), rgba(0, 0, 0, 0)); background: linear-gradient(rgba(0, 0, 0, 0.18), rgba(0, 0, 0, 0)); z-index:0; } div.cartodb-layer-selector-box div.cartodb-dropdown ul li a.switch span.handle { position: absolute; top: 0px; left: 12px; width: 10px; height: 10px; -webkit-border-radius: 12px; -moz-border-radius: 12px; -ms-border-radius: 12px; -o-border-radius: 12px; border-radius: 12px; border: 1px solid #44759e; background: #F2F2F2; z-index: 2; -webkit-transform-style: "linear"; -moz-transform-style: "linear"; -ms-transform-style: "linear"; -o-transform-style: "linear"; transform-style: "linear"; -webkit-transition-property: left; -moz-transition-property: left; -o-transition-property: left; transition-property: left; -webkit-transition-duration: 180ms; -moz-transition-duration: 180ms; -o-transition-duration: 180ms; transition-duration: 180ms; } div.cartodb-layer-selector-box div.cartodb-dropdown ul li a.switch.enabled { border-color:#44759E; background:#56AFEF; } div.cartodb-layer-selector-box div.cartodb-dropdown ul li a.switch.enabled span.handle { left:12px; border-color:#44759E; } div.cartodb-layer-selector-box div.cartodb-dropdown ul li a.switch.disabled { opacity:1; -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)"; filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=1); filter: alpha(opacity=100); border-color:#CCCCCC; background:#D8D8D8; } div.cartodb-layer-selector-box div.cartodb-dropdown ul li a.switch span.handle { left:0; border-color:#999999; } div.cartodb-layer-selector-box div.cartodb-dropdown ul li a.switch:hover { cursor:pointer!important; } div.cartodb-layer-selector-box div.cartodb-dropdown ul li a.switch.working { opacity:0.5; -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=.5); filter: alpha(opacity=50); } div.cartodb-layer-selector-box div.cartodb-dropdown ul li a.switch.working:hover {cursor:default!important;} /* CartoDB search box control */ div.cartodb-searchbox { position: relative; display:none; float:right; margin: 20px 20px 0 0; width: 142px; height:29px; -webkit-box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; -moz-box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; background: white; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; border: 1px solid #999999; z-index:105; } div.cartodb-searchbox span.loader { position: absolute; display:none; top:3px; left:3px; width:22px; height:22px; background: url('../img/loader.gif') no-repeat center center white; z-index:105; } div.cartodb-searchbox input.text { position: absolute; top:6px; left:30px; width:103px; padding:0; margin:0; line-height:17px; border:none; background:none; border-bottom:1px dotted #CCCCCC; -webkit-border-radius: 0; -moz-border-radius: 0; -ms-border-radius: 0; -o-border-radius: 0; border-radius: 0; font:normal 14px Arial; color:#999999; text-align:left; z-index:2; } div.cartodb-searchbox input.text:focus { outline:none; border-color:#999999; color:#666666; } div.cartodb-searchbox input.submit { position: absolute; left:8px; top:8px; width:12px; height:12px; text-indent: -9999px; font-size: 0; line-height: 0; text-transform: uppercase; border:none; background: url('../img/other.png') no-repeat -56px 0; z-index:1; } div.cartodb-searchbox input.submit:hover { cursor:pointer; } /* CartoDB infobox control */ div.cartodb-infobox { padding: 20px; position: absolute; display: inline-block; -webkit-box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; -moz-box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; background: white; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; border: 1px solid #999999; text-align:left; z-index:105; } /* CartoDB dropdown */ div.cartodb-dropdown { position:absolute; display:none; background:white; -webkit-border-radius: 3px; -moz-border-radius: 3px; -ms-border-radius: 3px; -o-border-radius: 3px; border-radius: 3px; border:none; -webkit-box-shadow: rgba(0,0,0,0.2) 0 0 4px 1px; -moz-box-shadow: rgba(0,0,0,0.2) 0 0 4px 1px; -ms-box-shadow: rgba(0,0,0,0.2) 0 0 4px 1px; -o-box-shadow: rgba(0,0,0,0.2) 0 0 4px 1px; box-shadow: rgba(0,0,0,0.2) 0 0 4px 1px; z-index:150; } div.cartodb-dropdown.border { border:1px solid #999999; } div.cartodb-dropdown div.tail { position:absolute; top:-6px; right:10px; width:0; height:0; border-left:6px solid transparent; border-right:6px solid transparent; border-bottom:6px solid #999; z-index:0; } div.cartodb-dropdown div.tail span.border { position:absolute; top:1px; left:-6px; width:0; height:0; border-left:6px solid transparent; border-right:6px solid transparent; border-bottom:6px solid white; z-index:2; } /* Gmaps attribution */ div#cartodb-gmaps-attribution { position:absolute; display:block; bottom:13px; right:0; height:10px; line-height:10px; padding:0 6px 4px 6px; background: white; background: rgba(245,245,245,0.7); font-family: "Roboto", Arial, sans-serif!important; font-size: 11px; font-weight: 400; color: #444!important; white-space: nowrap; direction: ltr; text-align: right; background-position:initial initial; background-repeat: initial initial; border:none; z-index:10000; } div#cartodb-gmaps-attribution a { color: #444; text-decoration:none; } /* SLIDER */ div.cartodb-timeslider { position: absolute; display: inline-block; height:40px; width:auto!important; margin-bottom:30px; padding:0; -webkit-box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; -moz-box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; box-shadow: rgba(0, 0, 0, 0.2) 0 0 4px 2px; background: white; -webkit-border-radius: 4px; -moz-border-radius: 4px; -ms-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; border: 1px solid #999999; text-align:left; z-index:105; } div.cartodb-timeslider ul { display:block; height:40px; margin:0; padding:0; line-height:40px; list-style:none; cursor: default; } div.cartodb-timeslider ul li { display:inline-block; zoom: 1; *display: inline; vertical-align:top; height:40px; _height:40px; width:auto; line-height:40px; border-right:1px solid #E5E5E5; } div.cartodb-timeslider ul li.last { border-right:none; } div.cartodb-timeslider a.button { display:block; width:48px; height:40px; text-indent:-9999px; line-height:0; font-size:0; background:url('../img/slider.png') no-repeat -2px -55px; } div.cartodb-timeslider a.button:hover { background-position:-42px -55px; } div.cartodb-timeslider a.button.stop { background-position:-2px -4px; } div.cartodb-timeslider a.button.stop:hover { background-position:-42px -4px; } div.cartodb-timeslider p { width:75px; height:40px; margin:0; padding:0 5px 0 0; line-height:40px; font-size:13px; font-weight:bold; font-family: 'Helvetica',Arial; text-align:center; color:#999999; } .cartodb-header { display:none; position:relative; width: 100%; background-color: rgba(0, 0, 0, 0.5); font-family: 'Helvetica Neue', Helvetica, sans-serif; line-height: normal; z-index: 99999; } .cartodb-header .content { padding: 10px; } .cartodb-header .content a { color: #fff; } .cartodb-header .content a:hover { color: #ccc; } .cartodb-header .content .title { display:none; margin: 0 0 5px 0; line-height: normal; font-family: 'Helvetica Neue', Helvetica, sans-serif; font-weight: bold; font-size:15px; color: #fff; } .cartodb-header .content .description { display:none; font-family: 'Helvetica Neue', Helvetica, sans-serif; line-height: normal; color: #fff; font-size:13px; } .cartodb-overlay.overlay-annotation { display:none; } .cartodb-overlay.overlay-text, .cartodb-overlay.overlay-annotation { position:absolute; display:none; -webkit-border-radius: 3px; -moz-border-radius: 3px; -ms-border-radius: 3px; -o-border-radius: 3px; border-radius: 3px; font-size: 20px; line-height: normal; color: #fff; -ms-word-break: break-word; word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; z-index: 11; } .cartodb-overlay.overlay-text .content, .cartodb-overlay.overlay-annotation .content { padding: 10px; } .cartodb-overlay.overlay-text .text { font-size: 20px; line-height: normal; color: #fff; -ms-word-break: break-word; word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; } .cartodb-overlay.overlay-text .text strong, .cartodb-overlay.overlay-annotation .text strong { font-weight: bold; } .cartodb-overlay.overlay-text .text em, .cartodb-overlay.overlay-annotation .text em { font-style: italic; } .cartodb-overlay.overlay-text div.text a, .cartodb-overlay.overlay-annotation div.text a { color: inherit; } .cartodb-overlay.overlay-text .text a:hover, .cartodb-overlay.overlay-annotation .text a:hover { color: inherit; filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=80); opacity: 0.8; } .cartodb-overlay.overlay-annotation { -webkit-border-radius: 2px; -moz-border-radius: 2px; -ms-border-radius: 2px; -o-border-radius: 2px; border-radius: 2px; } .cartodb-overlay.overlay-annotation .content { padding: 5px; } .cartodb-overlay.overlay-annotation.align-right .stick .ball { left: auto; right: -6px; } .cartodb-overlay.overlay-annotation .stick { position: absolute; top: 50%; left: -50px; margin-top: -1px; width: 50px; height: 2px; background: #333; } .cartodb-overlay.overlay-annotation .stick .ball { position:absolute; left: -6px; top: 50%; margin-top: -3px; width: 6px; height: 6px; background: #333; -webkit-border-radius: 200px; -moz-border-radius: 200px; -ms-border-radius: 200px; -o-border-radius: 200px; border-radius: 200px; } .cartodb-overlay.image-overlay { display:none; position:absolute; -webkit-border-radius: 3px; -moz-border-radius: 3px; -ms-border-radius: 3px; -o-border-radius: 3px; border-radius: 3px; z-index: 11; } .cartodb-overlay.image-overlay .content { padding: 10px; } .cartodb-overlay.image-overlay img { display: block; } @font-face { font-family: 'Droid Sans'; font-style: normal; font-weight: 400; src: local('Droid Sans'), local('DroidSans'), url(//themes.googleusercontent.com/static/fonts/droidsans/v4/s-BiyweUPV0v-yRb-cjciL3hpw3pgy2gAi-Ip7WPMi0.woff) format('woff'); } @font-face { font-family: 'Droid Sans'; font-style: bold; font-weight: 700; src: local('Droid Sans Bold'), local('DroidSans-Bold'), url(//themes.googleusercontent.com/static/fonts/droidsans/v4/EFpQQyG9GqCrobXxL-KRMXbFhgvWbfSbdVg11QabG8w.woff) format('woff'); } @font-face { font-family: 'Vollkorn'; font-style: normal; font-weight: 400; src: local('Vollkorn Regular'), local('Vollkorn-Regular'), url(//themes.googleusercontent.com/static/fonts/vollkorn/v4/BCFBp4rt5gxxFrX6F12DKnYhjbSpvc47ee6xR_80Hnw.woff) format('woff'); } @font-face { font-family: 'Vollkorn'; font-style: normal; font-weight: 400; src: local('Vollkorn Regular'), local('Vollkorn-Regular'), url(//themes.googleusercontent.com/static/fonts/vollkorn/v4/BCFBp4rt5gxxFrX6F12DKnYhjbSpvc47ee6xR_80Hnw.woff) format('woff'); } @font-face { font-family: 'Vollkorn'; font-style: bold; font-weight: 700; src: local('Vollkorn Bold'), local('Vollkorn-Bold'), url(//themes.googleusercontent.com/static/fonts/vollkorn/v4/wMZpbUtcCo9GUabw9JODerrIa-7acMAeDBVuclsi6Gc.woff) format('woff'); } @font-face { font-family: 'Open Sans'; font-style: bold; font-weight: 400; src: local('Open Sans'), local('OpenSans'), url(//themes.googleusercontent.com/static/fonts/opensans/v8/cJZKeOuBrn4kERxqtaUH3bO3LdcAZYWl9Si6vvxL-qU.woff) format('woff'); } @font-face { font-family: 'Open Sans'; font-style: bold; font-weight: 600; src: local('Open Sans Semibold'), local('OpenSans-Semibold'), url(//themes.googleusercontent.com/static/fonts/opensans/v8/MTP_ySUJH_bn48VBG8sNSqRDOzjiPcYnFooOUGCOsRk.woff) format('woff'); } @font-face { font-family: 'Roboto Slab'; font-style: normal; font-weight: 400; src: local('Roboto Slab Regular'), local('RobotoSlab-Regular'), url(//themes.googleusercontent.com/static/fonts/robotoslab/v3/y7lebkjgREBJK96VQi37ZrrIa-7acMAeDBVuclsi6Gc.woff) format('woff'); } @font-face { font-family: 'Roboto Slab'; font-style: bold; font-weight: 700; src: local('Roboto Slab Bold'), local('RobotoSlab-Bold'), url(//themes.googleusercontent.com/static/fonts/robotoslab/v3/dazS1PrQQuCxC3iOAJFEJRbnBKKEOwRKgsHDreGcocg.woff) format('woff'); } /* HELVETICA */ .cartodb-overlay.overlay-text .content > .text { font-family: 'Helvetica Neue', Helvetica, sans-serif; font-weight: 400; } .cartodb-overlay.overlay-text .content > .text strong { font-family: 'Helvetica Neue', Helvetica, sans-serif; font-weight: 700; } /* DROID */ .cartodb-overlay.overlay-text.droid .content > .text { font-family: 'Droid Sans', serif; font-weight: 400; } .cartodb-overlay.overlay-text.droid .content > .text strong { font-family: 'Droid Sans', Helvetica, sans-serif; font-weight: 700; } /* ROBOTO */ .cartodb-overlay.overlay-text.roboto .content > .text { font-family: 'Roboto Slab', serif; font-weight: 400; } .cartodb-overlay.overlay-text.roboto .content > .text strong { font-family: 'Roboto Slab', serif; font-weight: 700; } /* VOLLKORN */ .cartodb-overlay.overlay-text.vollkorn .content > .text { font-family: 'Vollkorn', serif; font-weight: 400; } .cartodb-overlay.overlay-text.vollkorn .content > .text strong { font-family: 'Vollkorn', serif; font-weight: 700; } /* OPEN SANS */ .cartodb-overlay.overlay-text.open_sans .content > .text { font-family: 'Open Sans', sans-serif; font-weight: 400; } .cartodb-overlay.overlay-text.open_sans .content > .text strong { font-family: 'Open Sans', sans-serif; font-weight: 700; } @media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and ( min--moz-device-pixel-ratio: 2), only screen and ( -o-min-device-pixel-ratio: 2/1), only screen and ( min-device-pixel-ratio: 2), only screen and ( min-resolution: 192dpi), only screen and ( min-resolution: 2dppx) { /*div.cartodb-timeslider .ui-slider .ui-slider-handle { top: -12px!Important; padding: 9px 3px; background:transparent url('../img/handle@2x.png') center center no-repeat!Important; border:none!Important; background-size: 11px 12px!Important; } div.cartodb-mobile .toggle { float:right; display:block; width: 40px; height: 30px; margin: auto; padding: 5px 0; background: url('../img/burguer@2x.png') no-repeat center center white; background-size: 18px 11px; }*/ } @media only screen and (max-device-width : 320px) and (max-device-width : 480px) { div.cartodb-map-wrapper div.cartodb-searchbox { display: none; } /*div.cartodb-map-wrapper div.cartodb-timeslider .ui-slider .ui-slider-handle { top: -12px; padding: 9px 3px; background:transparent url('../img/handle@2x.png') center center no-repeat; border:none; background-size: 11px 12px; } */ } /* iPhone portrait */ @media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : portrait) { /*.cartodb-text {display:none}*/ /*.cartodb-map-wrapper { bottom: 0!Important;}*/ } /* iPhone landscape */ @media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : landscape) { /*.cartodb-text {display:none}*/ /*.cartodb-map-wrapper { bottom: 0!Important;}*/ /*.torque div.cartodb-timeslider .slider-wrapper {*/ /*width:98px!important;*/ /*}*/ /*.torque div.cartodb-timeslider .slider {*/ /*width:98px!important;*/ /*}*/ } @media only screen and (min-width: 360px) and (max-width: 490px) { /*div.cartodb-timeslider .slider-wrapper {*/ /*width:198px!important;*/ /*}*/ /*div.cartodb-timeslider .slider {*/ /*width:198px!important;*/ /*}*/ } /* iPhone 5 portrait */ @media screen and (device-aspect-ratio: 40/71) and (orientation : portrait) { /*.cartodb-text {display:none}*/ /*.cartodb-map-wrapper { bottom: 0!Important;}*/ /*div.cartodb-timeslider .ui-slider .ui-slider-handle {*/ /*top: -12px!Important;*/ /*padding: 9px 3px;*/ /*background:transparent url('../img/handle@2x.png') center center no-repeat!Important;*/ /*border:none!Important;*/ /*background-size: 11px 12px!Important;*/ /*}*/ } /* iPhone 5 landscape */ @media screen and (device-aspect-ratio: 40/71) and (orientation : landscape) { /*.cartodb-text {display:none}*/ /*.cartodb-map-wrapper { bottom: 0!Important;}*/ /*div.cartodb-timeslider .ui-slider .ui-slider-handle {*/ /*top: -12px!Important;*/ /*padding: 9px 3px;*/ /*background:transparent url('../img/handle@2x.png') center center no-repeat!Important;*/ /*border:none!Important;*/ /*background-size: 11px 12px!Important;*/ /*}*/ } /* Nexus portrait */ @media only screen and (min-device-width : 340px) and (max-device-width: 768px) and (orientation : portrait) { /*.cartodb-text {display:none}*/ /*.cartodb-map-wrapper { bottom: 0!Important;}*/ /*div.cartodb-timeslider .ui-slider .ui-slider-handle {*/ /*top: -12px!Important;*/ /*padding: 9px 3px;*/ /*background:transparent url('../img/handle@2x.png') center center no-repeat!Important;*/ /*border:none!Important;*/ /*background-size: 11px 12px!Important;*/ /*}*/ } /* Nexus landscape */ @media only screen and (max-device-width : 768px) and (orientation : landscape) { /*.cartodb-text {display:none}*/ /*.cartodb-map-wrapper { bottom: 0!Important;}*/ /*div.cartodb-timeslider .ui-slider .ui-slider-handle {*/ /*top: -12px!Important;*/ /*padding: 9px 3px;*/ /*background:transparent url('../img/handle@2x.png') center center no-repeat!Important;*/ /*border:none!Important;*/ /*background-size: 11px 12px!Important;*/ /*}*/ } div.cartodb-timeslider .slider-wrapper { display:inline-block; zoom: 1; *display: inline; vertical-align:top; width:298px; height:4px; _height:4px; padding:18px 15px; } div.cartodb-timeslider .slider { width:298px; height:4px; } div.cartodb-timeslider .ui-helper-hidden { display: none; } div.cartodb-timeslider .ui-helper-hidden-accessible { border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; } div.cartodb-timeslider .ui-helper-reset { margin: 0; padding: 0; border: 0; outline: 0; line-height: 1.3; text-decoration: none; font-size: 100%; list-style: none; } div.cartodb-timeslider .ui-helper-clearfix:before, div.cartodb-timeslider .ui-helper-clearfix:after { content: ""; display: table; border-collapse: collapse; } div.cartodb-timeslider .ui-helper-clearfix:after { clear: both; } div.cartodb-timeslider .ui-helper-clearfix { min-height: 0; } div.cartodb-timeslider .ui-helper-zfix { width: 100%; height: 100%; top: 0; left: 0; position: absolute; opacity: 0; filter:Alpha(Opacity=0); } div.cartodb-timeslider .ui-front { z-index: 100; } div.cartodb-timeslider .ui-state-disabled { cursor: default !important; } div.cartodb-timeslider .ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; } div.cartodb-timeslider .ui-widget-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; } div.cartodb-timeslider .ui-slider { background-color: #E0E0E0; position: relative; text-align: left; border-radius:2px; -webkit-border-radius:2px; -moz-border-radius:2px; -o-border-radius:2px; } div.cartodb-timeslider .ui-slider .ui-slider-handle { position: absolute; z-index: 102; width: 9px; height: 10px; cursor: default; background:url('../img/slider.png') no-repeat -98px -18px white; border:1px solid #555555; border-radius:2px; -webkit-border-radius:2px; -moz-border-radius:2px; -o-border-radius:2px; outline:none; } div.cartodb-timeslider .ui-slider .ui-slider-handle:hover { cursor:col-resize; background-position:-112px -18px; } div.cartodb-timeslider .ui-slider .ui-slider-range { position: absolute; z-index: 100; font-size: .7em; display: block; border: 0; background-position: 0 0; background-color:#397DBA; border-radius:2px; -webkit-border-radius:2px; -moz-border-radius:2px; -o-border-radius:2px; } div.cartodb-timeslider .ui-slider.ui-state-disabled .ui-slider-handle, div.cartodb-timeslider .ui-slider.ui-state-disabled .ui-slider-range { filter: inherit; } div.cartodb-timeslider .ui-slider-horizontal { height: 4px; cursor:pointer; } div.cartodb-timeslider .ui-slider-horizontal .ui-slider-handle { top: -4px; margin-left: -6px; } div.cartodb-timeslider .ui-slider-horizontal .ui-slider-range { top: 0; height: 100%; cursor:pointer; } div.cartodb-timeslider .ui-slider-horizontal .ui-slider-range-min { left: 0; } div.cartodb-timeslider .ui-slider-horizontal .ui-slider-range-max { right: 0; } div.cartodb-timeslider .ui-slider-vertical { width: .8em; height: 100px; } div.cartodb-timeslider .ui-slider-vertical .ui-slider-handle { left: -.3em; margin-left: 0; margin-bottom: -.6em; } div.cartodb-timeslider .ui-slider-vertical .ui-slider-range { left: 0; width: 100%; } div.cartodb-timeslider .ui-slider-vertical .ui-slider-range-min { bottom: 0; } div.cartodb-timeslider .ui-slider-vertical .ui-slider-range-max { top: 0; } /* required styles */ .leaflet-map-pane, .leaflet-tile, .leaflet-marker-icon, .leaflet-marker-shadow, .leaflet-tile-pane, .leaflet-tile-container, .leaflet-overlay-pane, .leaflet-shadow-pane, .leaflet-marker-pane, .leaflet-popup-pane, .leaflet-overlay-pane svg, .leaflet-zoom-box, .leaflet-image-layer, .leaflet-layer { position: absolute; left: 0; top: 0; } .leaflet-container { overflow: hidden; -ms-touch-action: none; } .leaflet-tile, .leaflet-marker-icon, .leaflet-marker-shadow { -webkit-user-select: none; -moz-user-select: none; user-select: none; -webkit-user-drag: none; } .leaflet-marker-icon, .leaflet-marker-shadow { display: block; } /* map is broken in FF if you have max-width: 100% on tiles */ .leaflet-container img { max-width: none !important; } /* stupid Android 2 doesn't understand "max-width: none" properly */ .leaflet-container img.leaflet-image-layer { max-width: 15000px !important; } .leaflet-tile { filter: inherit; visibility: hidden; } .leaflet-tile-loaded { visibility: inherit; } .leaflet-zoom-box { width: 0; height: 0; } /* workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=888319 */ .leaflet-overlay-pane svg { -moz-user-select: none; } .leaflet-tile-pane { z-index: 2; } .leaflet-objects-pane { z-index: 3; } .leaflet-overlay-pane { z-index: 4; } .leaflet-shadow-pane { z-index: 5; } .leaflet-marker-pane { z-index: 6; } .leaflet-popup-pane { z-index: 7; } .leaflet-vml-shape { width: 1px; height: 1px; } .lvml { behavior: url(#default#VML); display: inline-block; position: absolute; } /* control positioning */ .leaflet-control { position: relative; z-index: 7; pointer-events: auto; } .leaflet-top, .leaflet-bottom { position: absolute; z-index: 1000; pointer-events: none; } .leaflet-top { top: 0; } .leaflet-right { right: 0; } .leaflet-bottom { bottom: 0; } .leaflet-left { left: 0; } .leaflet-control { float: left; clear: both; } .leaflet-right .leaflet-control { float: right; } .leaflet-top .leaflet-control { margin-top: 10px; } .leaflet-bottom .leaflet-control { margin-bottom: 10px; } .leaflet-left .leaflet-control { margin-left: 10px; } .leaflet-right .leaflet-control { margin-right: 10px; } /* zoom and fade animations */ .leaflet-fade-anim .leaflet-tile, .leaflet-fade-anim .leaflet-popup { opacity: 0; -webkit-transition: opacity 0.2s linear; -moz-transition: opacity 0.2s linear; -o-transition: opacity 0.2s linear; transition: opacity 0.2s linear; } .leaflet-fade-anim .leaflet-tile-loaded, .leaflet-fade-anim .leaflet-map-pane .leaflet-popup { opacity: 1; } .leaflet-zoom-anim .leaflet-zoom-animated { -webkit-transition: -webkit-transform 0.25s cubic-bezier(0,0,0.25,1); -moz-transition: -moz-transform 0.25s cubic-bezier(0,0,0.25,1); -o-transition: -o-transform 0.25s cubic-bezier(0,0,0.25,1); transition: transform 0.25s cubic-bezier(0,0,0.25,1); } .leaflet-zoom-anim .leaflet-tile, .leaflet-pan-anim .leaflet-tile, .leaflet-touching .leaflet-zoom-animated { -webkit-transition: none; -moz-transition: none; -o-transition: none; transition: none; } .leaflet-zoom-anim .leaflet-zoom-hide { visibility: hidden; } /* cursors */ .leaflet-clickable { cursor: pointer; } .leaflet-container { cursor: -webkit-grab; cursor: -moz-grab; } .leaflet-popup-pane, .leaflet-control { cursor: auto; } .leaflet-dragging .leaflet-container, .leaflet-dragging .leaflet-clickable { cursor: move; cursor: -webkit-grabbing; cursor: -moz-grabbing; } /* visual tweaks */ .leaflet-container { background: #ddd; outline: 0; } .leaflet-container a { color: #0078A8; } .leaflet-container a.leaflet-active { outline: 2px solid orange; } .leaflet-zoom-box { border: 2px dotted #38f; background: rgba(255,255,255,0.5); } /* general typography */ .leaflet-container { font: 12px/1.5 "Helvetica Neue", Arial, Helvetica, sans-serif; } /* general toolbar styles */ .leaflet-bar { box-shadow: 0 1px 5px rgba(0,0,0,0.65); border-radius: 4px; } .leaflet-bar a, .leaflet-bar a:hover { background-color: #fff; border-bottom: 1px solid #ccc; width: 26px; height: 26px; line-height: 26px; display: block; text-align: center; text-decoration: none; color: black; } .leaflet-bar a, .leaflet-control-layers-toggle { background-position: 50% 50%; background-repeat: no-repeat; display: block; } .leaflet-bar a:hover { background-color: #f4f4f4; } .leaflet-bar a:first-child { border-top-left-radius: 4px; border-top-right-radius: 4px; } .leaflet-bar a:last-child { border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; border-bottom: none; } .leaflet-bar a.leaflet-disabled { cursor: default; background-color: #f4f4f4; color: #bbb; } .leaflet-touch .leaflet-bar a { width: 30px; height: 30px; line-height: 30px; } /* zoom control */ .leaflet-control-zoom-in, .leaflet-control-zoom-out { font: bold 18px 'Lucida Console', Monaco, monospace; text-indent: 1px; } .leaflet-control-zoom-out { font-size: 20px; } .leaflet-touch .leaflet-control-zoom-in { font-size: 22px; } .leaflet-touch .leaflet-control-zoom-out { font-size: 24px; } /* layers control */ .leaflet-control-layers { box-shadow: 0 1px 5px rgba(0,0,0,0.4); background: #fff; border-radius: 5px; } .leaflet-control-layers-toggle { background-image: url(images/layers.png); width: 36px; height: 36px; } .leaflet-retina .leaflet-control-layers-toggle { background-image: url(images/layers-2x.png); background-size: 26px 26px; } .leaflet-touch .leaflet-control-layers-toggle { width: 44px; height: 44px; } .leaflet-control-layers .leaflet-control-layers-list, .leaflet-control-layers-expanded .leaflet-control-layers-toggle { display: none; } .leaflet-control-layers-expanded .leaflet-control-layers-list { display: block; position: relative; } .leaflet-control-layers-expanded { padding: 6px 10px 6px 6px; color: #333; background: #fff; } .leaflet-control-layers-selector { margin-top: 2px; position: relative; top: 1px; } .leaflet-control-layers label { display: block; } .leaflet-control-layers-separator { height: 0; border-top: 1px solid #ddd; margin: 5px -10px 5px -6px; } /* attribution and scale controls */ .leaflet-container .leaflet-control-attribution { background: #fff; background: rgba(255, 255, 255, 0.7); margin: 0; } .leaflet-control-attribution, .leaflet-control-scale-line { padding: 0 5px; color: #333; } .leaflet-control-attribution a { text-decoration: none; } .leaflet-control-attribution a:hover { text-decoration: underline; } .leaflet-container .leaflet-control-attribution, .leaflet-container .leaflet-control-scale { font-size: 11px; } .leaflet-left .leaflet-control-scale { margin-left: 5px; } .leaflet-bottom .leaflet-control-scale { margin-bottom: 5px; } .leaflet-control-scale-line { border: 2px solid #777; border-top: none; line-height: 1.1; padding: 2px 5px 1px; font-size: 11px; white-space: nowrap; overflow: hidden; -moz-box-sizing: content-box; box-sizing: content-box; background: #fff; background: rgba(255, 255, 255, 0.5); } .leaflet-control-scale-line:not(:first-child) { border-top: 2px solid #777; border-bottom: none; margin-top: -2px; } .leaflet-control-scale-line:not(:first-child):not(:last-child) { border-bottom: 2px solid #777; } .leaflet-touch .leaflet-control-attribution, .leaflet-touch .leaflet-control-layers, .leaflet-touch .leaflet-bar { box-shadow: none; } .leaflet-touch .leaflet-control-layers, .leaflet-touch .leaflet-bar { border: 2px solid rgba(0,0,0,0.2); background-clip: padding-box; } /* popup */ .leaflet-popup { position: absolute; text-align: center; } .leaflet-popup-content-wrapper { padding: 1px; text-align: left; border-radius: 12px; } .leaflet-popup-content { margin: 13px 19px; line-height: 1.4; } .leaflet-popup-content p { margin: 18px 0; } .leaflet-popup-tip-container { margin: 0 auto; width: 40px; height: 20px; position: relative; overflow: hidden; } .leaflet-popup-tip { width: 17px; height: 17px; padding: 1px; margin: -10px auto 0; -webkit-transform: rotate(45deg); -moz-transform: rotate(45deg); -ms-transform: rotate(45deg); -o-transform: rotate(45deg); transform: rotate(45deg); } .leaflet-popup-content-wrapper, .leaflet-popup-tip { background: white; box-shadow: 0 3px 14px rgba(0,0,0,0.4); } .leaflet-container a.leaflet-popup-close-button { position: absolute; top: 0; right: 0; padding: 4px 4px 0 0; text-align: center; width: 18px; height: 14px; font: 16px/14px Tahoma, Verdana, sans-serif; color: #c3c3c3; text-decoration: none; font-weight: bold; background: transparent; } .leaflet-container a.leaflet-popup-close-button:hover { color: #999; } .leaflet-popup-scrolled { overflow: auto; border-bottom: 1px solid #ddd; border-top: 1px solid #ddd; } .leaflet-oldie .leaflet-popup-content-wrapper { zoom: 1; } .leaflet-oldie .leaflet-popup-tip { width: 24px; margin: 0 auto; -ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678)"; filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678); } .leaflet-oldie .leaflet-popup-tip-container { margin-top: -1px; } .leaflet-oldie .leaflet-control-zoom, .leaflet-oldie .leaflet-control-layers, .leaflet-oldie .leaflet-popup-content-wrapper, .leaflet-oldie .leaflet-popup-tip { border: 1px solid #999; } /* div icon */ .leaflet-div-icon { background: #fff; border: 1px solid #666; } /** * CartoDB tooltip dark styles */ div.cartodb-tooltip-content-wrapper.dark { background: rgb(0,0,0); background:rgba(0,0,0,0.75); filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#bf000000, endColorstr=#bf000000); -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#bf000000, endColorstr=#bf000000)"; } div.cartodb-tooltip-content-wrapper.dark h4 { color:#999; } div.cartodb-tooltip-content-wrapper.dark p { color:#FFFFFF; } div.cartodb-tooltip-content-wrapper.dark a { color:#397DB9; } /** * CartoDB2.0 tooltip styles (DEFAULT) */ div.cartodb-tooltip { position: absolute; display: none; min-width:120px; max-width:180px; overflow-y:hidden; z-index: 5; } div.cartodb-tooltip-content-wrapper { -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; background: rgb(255,255,255); background: rgba(255,255,255,0.9); filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#E5FFFFFF, endColorstr=#E5FFFFFF); -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#E5FFFFFF, endColorstr=#E5FFFFFF)"; zoom: 1; } div.cartodb-tooltip-content { display:block; padding:8px 8px 8px 9px; } div.cartodb-tooltip-content h4 { display:block; text-transform: lowercase; font:normal 10px "Helvetica Neue","Helvetica",Arial; color:#AAA; word-wrap: break-word; } div.cartodb-tooltip-content p { display:block; margin:0; padding:0 0 7px; font:normal 12px "Helvetica Neue", "Helvetica", Arial; color:#333333; word-wrap: break-word; } div.cartodb-tooltip-content p:last-child { padding:0; } div.cartodb-tooltip-content a { color:#0078A8; } /* Old tooltip styles */ div.cartodb-tooltip > p { font-family: "robotoregular", Helvetica, Arial, Sans-serif; font-size: 15px; color: #333; text-align:center; text-shadow: -1px -1px 0 #FFF, 1px -1px 0 #FFF, -1px 1px 0 #FFF, 1px 1px 0 #FFF; } /** * CartoDB ooltip light styles */
femtope/BMGFGranteeMapping
cartodb.css
CSS
gpl-2.0
102,065
/*************************************************************************** tag: FMTC Tue Mar 11 21:49:27 CET 2008 DataFlowInterface.cpp DataFlowInterface.cpp - description ------------------- begin : Tue March 11 2008 copyright : (C) 2008 FMTC email : peter.soetens@fmtc.be *************************************************************************** * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public * * License as published by the Free Software Foundation; * * version 2 of the License. * * * * As a special exception, you may use this file as part of a free * * software library without restriction. Specifically, if other files * * instantiate templates or use macros or inline functions from this * * file, or you compile this file and link it with other files to * * produce an executable, this file does not by itself cause the * * resulting executable to be covered by the GNU General Public * * License. This exception does not however invalidate any other * * reasons why the executable file might be covered by the GNU General * * Public License. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307 USA * * * ***************************************************************************/ #include "DataFlowInterface.hpp" #include "Logger.hpp" #include "Service.hpp" #include "TaskContext.hpp" namespace RTT { using namespace detail; DataFlowInterface::DataFlowInterface(Service* parent /* = 0 */) : mservice(parent) {} DataFlowInterface::~DataFlowInterface() { } TaskContext* DataFlowInterface::getOwner() const { return mservice ? mservice->getOwner() : 0; } PortInterface& DataFlowInterface::addPort(PortInterface& port) { if ( !chkPtr("addPort", "PortInterface", &port) ) return port; this->addLocalPort(port); if (mservice && mservice->hasService( port.getName()) != 0) { log(Warning) <<"'addPort' "<< port.getName() << ": name already in use as Service. Replacing previous service with new one." <<endlog(); mservice->removeService(port.getName()); } if (!mservice) { log(Warning) <<"'addPort' "<< port.getName() << ": DataFlowInterface not given to parent. Not adding Service." <<endlog(); return port; } Service::shared_ptr ms( this->createPortObject( port.getName()) ); if ( ms ) mservice->addService( ms ); // END NOTE. return port; } PortInterface& DataFlowInterface::addLocalPort(PortInterface& port) { for ( Ports::iterator it(mports.begin()); it != mports.end(); ++it) if ( (*it)->getName() == port.getName() ) { log(Warning) <<"'addPort' "<< port.getName() << ": name already in use. Disconnecting and replacing previous port with new one." <<endlog(); removePort( port.getName() ); break; } mports.push_back( &port ); port.setInterface( this ); return port; } InputPortInterface& DataFlowInterface::addEventPort(InputPortInterface& port, SlotFunction callback) { if ( !chkPtr("addEventPort", "PortInterface", &port) ) return port; this->addLocalEventPort(port, callback); if (mservice && mservice->hasService( port.getName()) != 0) { log(Warning) <<"'addPort' "<< port.getName() << ": name already in use as Service. Replacing previous service with new one." <<endlog(); mservice->removeService(port.getName()); } if (!mservice) { log(Warning) <<"'addPort' "<< port.getName() << ": DataFlowInterface not given to parent. Not adding Service." <<endlog(); return port; } Service::shared_ptr ms( this->createPortObject( port.getName()) ); if ( ms ) mservice->addService( ms ); return port; } #ifdef ORO_SIGNALLING_PORTS void DataFlowInterface::setupHandles() { for_each(handles.begin(), handles.end(), boost::bind(&Handle::connect, _1)); } void DataFlowInterface::cleanupHandles() { for_each(handles.begin(), handles.end(), boost::bind(&Handle::disconnect, _1)); } #else void DataFlowInterface::dataOnPort(base::PortInterface* port) { if ( mservice && mservice->getOwner() ) mservice->getOwner()->dataOnPort(port); } #endif InputPortInterface& DataFlowInterface::addLocalEventPort(InputPortInterface& port, SlotFunction callback) { this->addLocalPort(port); if (mservice == 0 || mservice->getOwner() == 0) { log(Error) << "addLocalEventPort "<< port.getName() <<": DataFlowInterface not part of a TaskContext. Will not trigger any TaskContext nor register callback." <<endlog(); return port; } if (callback) mservice->getOwner()->dataOnPortCallback(&port,callback); // the handle will be deleted when the port is removed. port.signalInterface(true); return port; } void DataFlowInterface::removePort(const std::string& name) { for ( Ports::iterator it(mports.begin()); it != mports.end(); ++it) if ( (*it)->getName() == name ) { if (mservice) { mservice->removeService( name ); if (mservice->getOwner()) mservice->getOwner()->dataOnPortRemoved( *it ); } (*it)->disconnect(); // remove all connections and callbacks. mports.erase(it); return; } } DataFlowInterface::Ports DataFlowInterface::getPorts() const { return mports; } DataFlowInterface::PortNames DataFlowInterface::getPortNames() const { std::vector<std::string> res; for ( Ports::const_iterator it(mports.begin()); it != mports.end(); ++it) res.push_back( (*it)->getName() ); return res; } PortInterface* DataFlowInterface::getPort(const std::string& name) const { for ( Ports::const_iterator it(mports.begin()); it != mports.end(); ++it) if ( (*it)->getName() == name ) return *it; return 0; } std::string DataFlowInterface::getPortDescription(const std::string& name) const { for ( Ports::const_iterator it(mports.begin()); it != mports.end(); ++it) if ( (*it)->getName() == name ) return (*it)->getDescription(); return ""; } bool DataFlowInterface::setPortDescription(const std::string& name, const std::string description) { Service::shared_ptr srv = mservice->getService(name); if (srv) { srv->doc(description); return true; } return false; } Service* DataFlowInterface::createPortObject(const std::string& name) { PortInterface* p = this->getPort(name); if ( !p ) return 0; Service* to = p->createPortObject(); if (to) { std::string d = this->getPortDescription(name); if ( !d.empty() ) to->doc( d ); else to->doc("No description set for this Port. Use .doc() to document it."); } return to; } void DataFlowInterface::clear() { // remove TaskObjects: for ( Ports::iterator it(mports.begin()); it != mports.end(); ++it) { if (mservice) mservice->removeService( (*it)->getName() ); } mports.clear(); } bool DataFlowInterface::chkPtr(const std::string & where, const std::string & name, const void *ptr) { if ( ptr == 0) { log(Error) << "You tried to add a null pointer in '"<< where << "' for the object '" << name << "'. Fix your code !"<< endlog(); return false; } return true; } }
jbohren-forks/rtt-smits
rtt/DataFlowInterface.cpp
C++
gpl-2.0
9,316
<?php /* * Removes core controls */ function shoestrap_remove_controls( $wp_customize ){ $wp_customize->remove_control( 'header_textcolor'); } add_action( 'customize_register', 'shoestrap_remove_controls' );
westerniowawireless/wiaw.net
wp-content/themes/shoestrap/lib/customizer/functions/remove-controls.php
PHP
gpl-2.0
213
/* Tables */ table { border-spacing: 0; border-color: #eee; font-size: inherit; font: 100%; margin: 10px 0; padding: 0; width: 100%; -moz-border-radius: 3px; -webkit-border-radius: 3px; -khtml-border-radius: 3px; border-radius: 3px; overflow: hidden; } table.sticky-header { z-index: 10; } table, td, th { vertical-align:middle; } th, thead, thead th { background-color: #331E11; border: none; color: #fcfcf8; } caption, th, td { text-align:left; } td, th { border-bottom: none; margin: 0; padding: 5px 7px; text-align: left; vertical-align: middle; } tr.even, tr.odd { border-bottom: none; } tr.odd, tr.info { background-color: #f5f5f5; } tr.even { background-color: #fff; } tr.drag { background-color: #fffff0; } tr.drag-previous { background-color: #ffd; } tr.odd td.active { background-color: #eee; } tr.even td.active { background-color: #f7f7f7; } td.region, td.module, td.container td.category { background-color: #eee; border-bottom: 1px solid #ccc; border-top: 20px solid #fff; color: #222; font-weight: 700; } tr:first-child td.region, tr:first-child td.module, tr:first-child td.container { border-top-width: 0; } #forum { } body.page-forum ul.action-links { margin: 9px 0; } #forum td.container { border-top: 1px solid #2e2e2e; border-bottom: 1px solid #2e2e2e; } #forum td.container .name a { font-size: 1.25em; text-transform: uppercase; line-height: 1.3; padding: 0 0 4px 0; color: inherit; } #forum td.container .name a:hover { color: #e25400; } #forum td { padding: 13px 14px; vertical-align: top; } #forum > table { margin-top: 0; } #forum tr td.forum { background: none; padding-left: 0; } #forum .description { line-height: 1.5; margin: 4px 0 0 0; font-size: 1em; } #forum div.indent { margin: 0 0 0 15px; } #forum td.icon .topic-status-sticky { background: url(images/forum-sticky.png) no-repeat center center; width: 30px; height: 35px; } #forum td.icon .topic-status-default { background: url(images/forum-default.png) no-repeat center center; width: 37px; height: 32px; } #forum td.icon .topic-status-closed { background: url(images/forum-closed.png) no-repeat center center; width: 30px; height: 35px; } #forum td.icon .topic-status-hot { background: url(images/forum-hot.png) no-repeat center center; width: 37px; height: 32px; } #forum td.icon .topic-status-new { background: url(images/forum-new.png) no-repeat center center; width: 42px; height: 39px; } #forum td.icon .topic-status-hot-new { background: url(images/forum-hot-new.png) no-repeat center center; width: 43px; height: 38px; } /* Table drag & drop */ .draggable a.tabledrag-handle { margin: 0 12px 0 0; padding: 0; } tr.drag { background-color: #f3fbfe; } tr.drag-previous { background-color: #f8fdfe; } span.tabledrag-changed { font-size: 13px; margin-left: 3px; color: #f00; } th a, thead a { color: #fff!important; } th a:hover, thead a:hover { color: #fff; } table img { margin: 0; } /** * Webkit work-around. Uncomment and adjust if you have borders on td. */ tr td:last-child { border-right: 1px solid #eee; } /*Rounded Corners*/ table { -moz-border-radius: 5px; -webkit-border-radius: 5px; -khtml-border-radius: 5px; border-radius: 5px; overflow: hidden; }
rafaqz/growshare_corolla
css/tables.css
CSS
gpl-2.0
3,344
# -*- coding: utf-8 -*- # # Copyright (C) 2010-2016 Red Hat, Inc. # # Authors: # Thomas Woerner <twoerner@redhat.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import os.path import copy from firewall.core.base import SHORTCUTS, DEFAULT_ZONE_TARGET from firewall.core.prog import runProg from firewall.core.logger import log from firewall.functions import tempFile, readfile, splitArgs, check_mac, portStr, \ check_single_address from firewall import config from firewall.errors import FirewallError, INVALID_PASSTHROUGH, INVALID_RULE, UNKNOWN_ERROR from firewall.core.rich import Rich_Accept, Rich_Reject, Rich_Drop, Rich_Mark, \ Rich_Masquerade, Rich_ForwardPort, Rich_IcmpBlock import string BUILT_IN_CHAINS = { "security": [ "INPUT", "OUTPUT", "FORWARD" ], "raw": [ "PREROUTING", "OUTPUT" ], "mangle": [ "PREROUTING", "POSTROUTING", "INPUT", "OUTPUT", "FORWARD" ], "nat": [ "PREROUTING", "POSTROUTING", "OUTPUT" ], "filter": [ "INPUT", "OUTPUT", "FORWARD" ], } DEFAULT_REJECT_TYPE = { "ipv4": "icmp-host-prohibited", "ipv6": "icmp6-adm-prohibited", } ICMP = { "ipv4": "icmp", "ipv6": "ipv6-icmp", } # ipv ebtables also uses this # def common_reverse_rule(args): """ Inverse valid rule """ replace_args = { # Append "-A": "-D", "--append": "--delete", # Insert "-I": "-D", "--insert": "--delete", # New chain "-N": "-X", "--new-chain": "--delete-chain", } ret_args = args[:] for arg in replace_args: try: idx = ret_args.index(arg) except Exception: continue if arg in [ "-I", "--insert" ]: # With insert rulenum, then remove it if it is a number # Opt at position idx, chain at position idx+1, [rulenum] at # position idx+2 try: int(ret_args[idx+2]) except Exception: pass else: ret_args.pop(idx+2) ret_args[idx] = replace_args[arg] return ret_args def common_reverse_passthrough(args): """ Reverse valid passthough rule """ replace_args = { # Append "-A": "-D", "--append": "--delete", # Insert "-I": "-D", "--insert": "--delete", # New chain "-N": "-X", "--new-chain": "--delete-chain", } ret_args = args[:] for x in replace_args: try: idx = ret_args.index(x) except ValueError: continue if x in [ "-I", "--insert" ]: # With insert rulenum, then remove it if it is a number # Opt at position idx, chain at position idx+1, [rulenum] at # position idx+2 try: int(ret_args[idx+2]) except ValueError: pass else: ret_args.pop(idx+2) ret_args[idx] = replace_args[x] return ret_args raise FirewallError(INVALID_PASSTHROUGH, "no '-A', '-I' or '-N' arg") # ipv ebtables also uses this # def common_check_passthrough(args): """ Check if passthough rule is valid (only add, insert and new chain rules are allowed) """ args = set(args) not_allowed = set(["-C", "--check", # check rule "-D", "--delete", # delete rule "-R", "--replace", # replace rule "-L", "--list", # list rule "-S", "--list-rules", # print rules "-F", "--flush", # flush rules "-Z", "--zero", # zero rules "-X", "--delete-chain", # delete chain "-P", "--policy", # policy "-E", "--rename-chain"]) # rename chain) # intersection of args and not_allowed is not empty, i.e. # something from args is not allowed if len(args & not_allowed) > 0: raise FirewallError(INVALID_PASSTHROUGH, "arg '%s' is not allowed" % list(args & not_allowed)[0]) # args need to contain one of -A, -I, -N needed = set(["-A", "--append", "-I", "--insert", "-N", "--new-chain"]) # empty intersection of args and needed, i.e. # none from args contains any needed command if len(args & needed) == 0: raise FirewallError(INVALID_PASSTHROUGH, "no '-A', '-I' or '-N' arg") class ip4tables(object): ipv = "ipv4" name = "ip4tables" zones_supported = True def __init__(self, fw): self._fw = fw self._command = config.COMMANDS[self.ipv] self._restore_command = config.COMMANDS["%s-restore" % self.ipv] self.wait_option = self._detect_wait_option() self.restore_wait_option = self._detect_restore_wait_option() self.fill_exists() self.available_tables = [] self.rich_rule_priority_counts = {} self.our_chains = {} # chains created by firewalld def fill_exists(self): self.command_exists = os.path.exists(self._command) self.restore_command_exists = os.path.exists(self._restore_command) def __run(self, args): # convert to string list if self.wait_option and self.wait_option not in args: _args = [self.wait_option] + ["%s" % item for item in args] else: _args = ["%s" % item for item in args] log.debug2("%s: %s %s", self.__class__, self._command, " ".join(_args)) (status, ret) = runProg(self._command, _args) if status != 0: raise ValueError("'%s %s' failed: %s" % (self._command, " ".join(_args), ret)) return ret def split_value(self, rules, opts=None): """Split values combined with commas for options in opts""" if opts is None: return rules out_rules = [ ] for rule in rules: processed = False for opt in opts: try: i = rule.index(opt) except ValueError: pass else: if len(rule) > i and "," in rule[i+1]: # For all items in the comma separated list in index # i of the rule, a new rule is created with a single # item from this list processed = True items = rule[i+1].split(",") for item in items: _rule = rule[:] _rule[i+1] = item out_rules.append(_rule) if not processed: out_rules.append(rule) return out_rules def _rule_replace(self, rule, pattern, replacement): try: i = rule.index(pattern) except ValueError: return False else: rule[i:i+1] = replacement return True def is_chain_builtin(self, ipv, table, chain): return table in BUILT_IN_CHAINS and \ chain in BUILT_IN_CHAINS[table] def build_chain_rules(self, add, table, chain): rule = [ "-t", table ] if add: rule.append("-N") else: rule.append("-X") rule.append(chain) return [rule] def build_rule(self, add, table, chain, index, args): rule = [ "-t", table ] if add: rule += [ "-I", chain, str(index) ] else: rule += [ "-D", chain ] rule += args return rule def reverse_rule(self, args): return common_reverse_rule(args) def check_passthrough(self, args): common_check_passthrough(args) def reverse_passthrough(self, args): return common_reverse_passthrough(args) def passthrough_parse_table_chain(self, args): table = "filter" try: i = args.index("-t") except ValueError: pass else: if len(args) >= i+1: table = args[i+1] chain = None for opt in [ "-A", "--append", "-I", "--insert", "-N", "--new-chain" ]: try: i = args.index(opt) except ValueError: pass else: if len(args) >= i+1: chain = args[i+1] return (table, chain) def _set_rule_replace_rich_rule_priority(self, rule, rich_rule_priority_counts): """ Change something like -t filter -I public_IN %%RICH_RULE_PRIORITY%% 123 or -t filter -A public_IN %%RICH_RULE_PRIORITY%% 321 into -t filter -I public_IN 4 or -t filter -I public_IN """ try: i = rule.index("%%RICH_RULE_PRIORITY%%") except ValueError: pass else: rule_add = True insert = False insert_add_index = -1 rule.pop(i) priority = rule.pop(i) if type(priority) != int: raise FirewallError(INVALID_RULE, "rich rule priority must be followed by a number") table = "filter" for opt in [ "-t", "--table" ]: try: j = rule.index(opt) except ValueError: pass else: if len(rule) >= j+1: table = rule[j+1] for opt in [ "-A", "--append", "-I", "--insert", "-D", "--delete" ]: try: insert_add_index = rule.index(opt) except ValueError: pass else: if len(rule) >= insert_add_index+1: chain = rule[insert_add_index+1] if opt in [ "-I", "--insert" ]: insert = True if opt in [ "-D", "--delete" ]: rule_add = False chain = (table, chain) # Add the rule to the priority counts. We don't need to store the # rule, just bump the ref count for the priority value. if not rule_add: if chain not in rich_rule_priority_counts or \ priority not in rich_rule_priority_counts[chain] or \ rich_rule_priority_counts[chain][priority] <= 0: raise FirewallError(UNKNOWN_ERROR, "nonexistent or underflow of rich rule priority count") rich_rule_priority_counts[chain][priority] -= 1 else: if chain not in rich_rule_priority_counts: rich_rule_priority_counts[chain] = {} if priority not in rich_rule_priority_counts[chain]: rich_rule_priority_counts[chain][priority] = 0 # calculate index of new rule index = 1 for p in sorted(rich_rule_priority_counts[chain].keys()): if p == priority and insert: break index += rich_rule_priority_counts[chain][p] if p == priority: break rich_rule_priority_counts[chain][priority] += 1 rule[insert_add_index] = "-I" rule.insert(insert_add_index+2, "%d" % index) def set_rules(self, rules, log_denied): temp_file = tempFile() table_rules = { } rich_rule_priority_counts = copy.deepcopy(self.rich_rule_priority_counts) for _rule in rules: rule = _rule[:] # replace %%REJECT%% self._rule_replace(rule, "%%REJECT%%", \ ["REJECT", "--reject-with", DEFAULT_REJECT_TYPE[self.ipv]]) # replace %%ICMP%% self._rule_replace(rule, "%%ICMP%%", [ICMP[self.ipv]]) # replace %%LOGTYPE%% try: i = rule.index("%%LOGTYPE%%") except ValueError: pass else: if log_denied == "off": continue if log_denied in [ "unicast", "broadcast", "multicast" ]: rule[i:i+1] = [ "-m", "pkttype", "--pkt-type", log_denied ] else: rule.pop(i) self._set_rule_replace_rich_rule_priority(rule, rich_rule_priority_counts) table = "filter" # get table form rule for opt in [ "-t", "--table" ]: try: i = rule.index(opt) except ValueError: pass else: if len(rule) >= i+1: rule.pop(i) table = rule.pop(i) # we can not use joinArgs here, because it would use "'" instead # of '"' for the start and end of the string, this breaks # iptables-restore for i in range(len(rule)): for c in string.whitespace: if c in rule[i] and not (rule[i].startswith('"') and rule[i].endswith('"')): rule[i] = '"%s"' % rule[i] table_rules.setdefault(table, []).append(rule) for table in table_rules: rules = table_rules[table] rules = self.split_value(rules, [ "-s", "--source" ]) rules = self.split_value(rules, [ "-d", "--destination" ]) temp_file.write("*%s\n" % table) for rule in rules: temp_file.write(" ".join(rule) + "\n") temp_file.write("COMMIT\n") temp_file.close() stat = os.stat(temp_file.name) log.debug2("%s: %s %s", self.__class__, self._restore_command, "%s: %d" % (temp_file.name, stat.st_size)) args = [ ] if self.restore_wait_option: args.append(self.restore_wait_option) args.append("-n") (status, ret) = runProg(self._restore_command, args, stdin=temp_file.name) if log.getDebugLogLevel() > 2: lines = readfile(temp_file.name) if lines is not None: i = 1 for line in lines: log.debug3("%8d: %s" % (i, line), nofmt=1, nl=0) if not line.endswith("\n"): log.debug3("", nofmt=1) i += 1 os.unlink(temp_file.name) if status != 0: raise ValueError("'%s %s' failed: %s" % (self._restore_command, " ".join(args), ret)) self.rich_rule_priority_counts = rich_rule_priority_counts return ret def set_rule(self, rule, log_denied): # replace %%REJECT%% self._rule_replace(rule, "%%REJECT%%", \ ["REJECT", "--reject-with", DEFAULT_REJECT_TYPE[self.ipv]]) # replace %%ICMP%% self._rule_replace(rule, "%%ICMP%%", [ICMP[self.ipv]]) # replace %%LOGTYPE%% try: i = rule.index("%%LOGTYPE%%") except ValueError: pass else: if log_denied == "off": return "" if log_denied in [ "unicast", "broadcast", "multicast" ]: rule[i:i+1] = [ "-m", "pkttype", "--pkt-type", log_denied ] else: rule.pop(i) rich_rule_priority_counts = copy.deepcopy(self.rich_rule_priority_counts) self._set_rule_replace_rich_rule_priority(rule, self.rich_rule_priority_counts) output = self.__run(rule) self.rich_rule_priority_counts = rich_rule_priority_counts return output def get_available_tables(self, table=None): ret = [] tables = [ table ] if table else BUILT_IN_CHAINS.keys() for table in tables: if table in self.available_tables: ret.append(table) else: try: self.__run(["-t", table, "-L", "-n"]) self.available_tables.append(table) ret.append(table) except ValueError: log.debug1("%s table '%s' does not exist (or not enough permission to check)." % (self.ipv, table)) return ret def _detect_wait_option(self): wait_option = "" ret = runProg(self._command, ["-w", "-L", "-n"]) # since iptables-1.4.20 if ret[0] == 0: wait_option = "-w" # wait for xtables lock ret = runProg(self._command, ["-w10", "-L", "-n"]) # since iptables > 1.4.21 if ret[0] == 0: wait_option = "-w10" # wait max 10 seconds log.debug2("%s: %s will be using %s option.", self.__class__, self._command, wait_option) return wait_option def _detect_restore_wait_option(self): temp_file = tempFile() temp_file.write("#foo") temp_file.close() wait_option = "" for test_option in ["-w", "--wait=2"]: ret = runProg(self._restore_command, [test_option], stdin=temp_file.name) if ret[0] == 0 and "invalid option" not in ret[1] \ and "unrecognized option" not in ret[1]: wait_option = test_option break log.debug2("%s: %s will be using %s option.", self.__class__, self._restore_command, wait_option) os.unlink(temp_file.name) return wait_option def build_flush_rules(self): self.rich_rule_priority_counts = {} rules = [] for table in BUILT_IN_CHAINS.keys(): # Flush firewall rules: -F # Delete firewall chains: -X # Set counter to zero: -Z for flag in [ "-F", "-X", "-Z" ]: rules.append(["-t", table, flag]) return rules def build_set_policy_rules(self, policy): rules = [] for table in BUILT_IN_CHAINS.keys(): if table == "nat": continue for chain in BUILT_IN_CHAINS[table]: rules.append(["-t", table, "-P", chain, policy]) return rules def supported_icmp_types(self): """Return ICMP types that are supported by the iptables/ip6tables command and kernel""" ret = [ ] output = "" try: output = self.__run(["-p", "icmp" if self.ipv == "ipv4" else "ipv6-icmp", "--help"]) except ValueError as ex: if self.ipv == "ipv4": log.debug1("iptables error: %s" % ex) else: log.debug1("ip6tables error: %s" % ex) lines = output.splitlines() in_types = False for line in lines: #print(line) if in_types: line = line.strip().lower() splits = line.split() for split in splits: if split.startswith("(") and split.endswith(")"): x = split[1:-1] else: x = split if x not in ret: ret.append(x) if self.ipv == "ipv4" and line.startswith("Valid ICMP Types:") or \ self.ipv == "ipv6" and line.startswith("Valid ICMPv6 Types:"): in_types = True return ret def build_default_tables(self): # nothing to do, they always exist return [] def build_default_rules(self, log_denied="off"): default_rules = {} default_rules["security"] = [ ] self.our_chains["security"] = set() for chain in BUILT_IN_CHAINS["security"]: default_rules["security"].append("-N %s_direct" % chain) default_rules["security"].append("-A %s -j %s_direct" % (chain, chain)) self.our_chains["security"].add("%s_direct" % chain) default_rules["raw"] = [ ] self.our_chains["raw"] = set() for chain in BUILT_IN_CHAINS["raw"]: default_rules["raw"].append("-N %s_direct" % chain) default_rules["raw"].append("-A %s -j %s_direct" % (chain, chain)) self.our_chains["raw"].add("%s_direct" % chain) if chain == "PREROUTING": default_rules["raw"].append("-N %s_ZONES_SOURCE" % chain) default_rules["raw"].append("-N %s_ZONES" % chain) default_rules["raw"].append("-A %s -j %s_ZONES_SOURCE" % (chain, chain)) default_rules["raw"].append("-A %s -j %s_ZONES" % (chain, chain)) self.our_chains["raw"].update(set(["%s_ZONES_SOURCE" % chain, "%s_ZONES" % chain])) default_rules["mangle"] = [ ] self.our_chains["mangle"] = set() for chain in BUILT_IN_CHAINS["mangle"]: default_rules["mangle"].append("-N %s_direct" % chain) default_rules["mangle"].append("-A %s -j %s_direct" % (chain, chain)) self.our_chains["mangle"].add("%s_direct" % chain) if chain == "PREROUTING": default_rules["mangle"].append("-N %s_ZONES_SOURCE" % chain) default_rules["mangle"].append("-N %s_ZONES" % chain) default_rules["mangle"].append("-A %s -j %s_ZONES_SOURCE" % (chain, chain)) default_rules["mangle"].append("-A %s -j %s_ZONES" % (chain, chain)) self.our_chains["mangle"].update(set(["%s_ZONES_SOURCE" % chain, "%s_ZONES" % chain])) default_rules["nat"] = [ ] self.our_chains["nat"] = set() for chain in BUILT_IN_CHAINS["nat"]: default_rules["nat"].append("-N %s_direct" % chain) default_rules["nat"].append("-A %s -j %s_direct" % (chain, chain)) self.our_chains["nat"].add("%s_direct" % chain) if chain in [ "PREROUTING", "POSTROUTING" ]: default_rules["nat"].append("-N %s_ZONES_SOURCE" % chain) default_rules["nat"].append("-N %s_ZONES" % chain) default_rules["nat"].append("-A %s -j %s_ZONES_SOURCE" % (chain, chain)) default_rules["nat"].append("-A %s -j %s_ZONES" % (chain, chain)) self.our_chains["nat"].update(set(["%s_ZONES_SOURCE" % chain, "%s_ZONES" % chain])) default_rules["filter"] = [ "-N INPUT_direct", "-N INPUT_ZONES_SOURCE", "-N INPUT_ZONES", "-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT", "-A INPUT -i lo -j ACCEPT", "-A INPUT -j INPUT_direct", "-A INPUT -j INPUT_ZONES_SOURCE", "-A INPUT -j INPUT_ZONES", ] if log_denied != "off": default_rules["filter"].append("-A INPUT -m conntrack --ctstate INVALID %%LOGTYPE%% -j LOG --log-prefix 'STATE_INVALID_DROP: '") default_rules["filter"].append("-A INPUT -m conntrack --ctstate INVALID -j DROP") if log_denied != "off": default_rules["filter"].append("-A INPUT %%LOGTYPE%% -j LOG --log-prefix 'FINAL_REJECT: '") default_rules["filter"].append("-A INPUT -j %%REJECT%%") default_rules["filter"] += [ "-N FORWARD_direct", "-N FORWARD_IN_ZONES_SOURCE", "-N FORWARD_IN_ZONES", "-N FORWARD_OUT_ZONES_SOURCE", "-N FORWARD_OUT_ZONES", "-A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT", "-A FORWARD -i lo -j ACCEPT", "-A FORWARD -j FORWARD_direct", "-A FORWARD -j FORWARD_IN_ZONES_SOURCE", "-A FORWARD -j FORWARD_IN_ZONES", "-A FORWARD -j FORWARD_OUT_ZONES_SOURCE", "-A FORWARD -j FORWARD_OUT_ZONES", ] if log_denied != "off": default_rules["filter"].append("-A FORWARD -m conntrack --ctstate INVALID %%LOGTYPE%% -j LOG --log-prefix 'STATE_INVALID_DROP: '") default_rules["filter"].append("-A FORWARD -m conntrack --ctstate INVALID -j DROP") if log_denied != "off": default_rules["filter"].append("-A FORWARD %%LOGTYPE%% -j LOG --log-prefix 'FINAL_REJECT: '") default_rules["filter"].append("-A FORWARD -j %%REJECT%%") default_rules["filter"] += [ "-N OUTPUT_direct", "-A OUTPUT -o lo -j ACCEPT", "-A OUTPUT -j OUTPUT_direct", ] self.our_chains["filter"] = set(["INPUT_direct", "INPUT_ZONES_SOURCE", "INPUT_ZONES", "FORWARD_direct", "FORWARD_IN_ZONES_SOURCE", "FORWARD_IN_ZONES", "FORWARD_OUT_ZONES_SOURCE", "FORWARD_OUT_ZONES", "OUTPUT_direct"]) final_default_rules = [] for table in default_rules: if table not in self.get_available_tables(): continue for rule in default_rules[table]: final_default_rules.append(["-t", table] + splitArgs(rule)) return final_default_rules def get_zone_table_chains(self, table): if table == "filter": return { "INPUT", "FORWARD_IN", "FORWARD_OUT" } if table == "mangle": if "mangle" in self.get_available_tables() and \ "nat" in self.get_available_tables(): return { "PREROUTING" } if table == "nat": if "nat" in self.get_available_tables(): return { "PREROUTING", "POSTROUTING" } if table == "raw": if "raw" in self.get_available_tables(): return { "PREROUTING" } return {} def build_zone_source_interface_rules(self, enable, zone, zone_target, interface, table, chain, append=False): # handle all zones in the same way here, now # trust and block zone targets are handled now in __chain opt = { "PREROUTING": "-i", "POSTROUTING": "-o", "INPUT": "-i", "FORWARD_IN": "-i", "FORWARD_OUT": "-o", "OUTPUT": "-o", }[chain] target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS[chain], zone=zone) if zone_target == DEFAULT_ZONE_TARGET: action = "-g" else: action = "-j" if enable and not append: rule = [ "-I", "%s_ZONES" % chain, "1" ] elif enable: rule = [ "-A", "%s_ZONES" % chain ] else: rule = [ "-D", "%s_ZONES" % chain ] rule += [ "-t", table, opt, interface, action, target ] return [rule] def build_zone_source_address_rules(self, enable, zone, zone_target, address, table, chain): add_del = { True: "-A", False: "-D" }[enable] opt = { "PREROUTING": "-s", "POSTROUTING": "-d", "INPUT": "-s", "FORWARD_IN": "-s", "FORWARD_OUT": "-d", "OUTPUT": "-d", }[chain] target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS[chain], zone=zone) if zone_target == DEFAULT_ZONE_TARGET: action = "-g" else: action = "-j" if address.startswith("ipset:"): name = address[6:] if opt == "-d": opt = "dst" else: opt = "src" flags = ",".join([opt] * self._fw.ipset.get_dimension(name)) rule = [ add_del, "%s_ZONES_SOURCE" % chain, "-t", table, "-m", "set", "--match-set", name, flags, action, target ] else: if check_mac(address): # outgoing can not be set if opt == "-d": return "" rule = [ add_del, "%s_ZONES_SOURCE" % chain, "-t", table, "-m", "mac", "--mac-source", address.upper(), action, target ] else: rule = [ add_del, "%s_ZONES_SOURCE" % chain, "-t", table, opt, address, action, target ] return [rule] def build_zone_chain_rules(self, zone, table, chain): _zone = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS[chain], zone=zone) self.our_chains[table].update(set([_zone, "%s_log" % _zone, "%s_deny" % _zone, "%s_pre" % _zone, "%s_post" % _zone, "%s_allow" % _zone])) rules = [] rules.append([ "-N", _zone, "-t", table ]) rules.append([ "-N", "%s_pre" % _zone, "-t", table ]) rules.append([ "-N", "%s_log" % _zone, "-t", table ]) rules.append([ "-N", "%s_deny" % _zone, "-t", table ]) rules.append([ "-N", "%s_allow" % _zone, "-t", table ]) rules.append([ "-N", "%s_post" % _zone, "-t", table ]) rules.append([ "-A", _zone, "-t", table, "-j", "%s_pre" % _zone ]) rules.append([ "-A", _zone, "-t", table, "-j", "%s_log" % _zone ]) rules.append([ "-A", _zone, "-t", table, "-j", "%s_deny" % _zone ]) rules.append([ "-A", _zone, "-t", table, "-j", "%s_allow" % _zone ]) rules.append([ "-A", _zone, "-t", table, "-j", "%s_post" % _zone ]) target = self._fw.zone._zones[zone].target if self._fw.get_log_denied() != "off": if table == "filter" and \ chain in [ "INPUT", "FORWARD_IN", "FORWARD_OUT", "OUTPUT" ]: if target in [ "REJECT", "%%REJECT%%" ]: rules.append([ "-A", _zone, "-t", table, "%%LOGTYPE%%", "-j", "LOG", "--log-prefix", "\"%s_REJECT: \"" % _zone ]) if target == "DROP": rules.append([ "-A", _zone, "-t", table, "%%LOGTYPE%%", "-j", "LOG", "--log-prefix", "\"%s_DROP: \"" % _zone ]) # Handle trust, block and drop zones: # Add an additional rule with the zone target (accept, reject # or drop) to the base zone only in the filter table. # Otherwise it is not be possible to have a zone with drop # target, that is allowing traffic that is locally initiated # or that adds additional rules. (RHBZ#1055190) if table == "filter" and \ target in [ "ACCEPT", "REJECT", "%%REJECT%%", "DROP" ] and \ chain in [ "INPUT", "FORWARD_IN", "FORWARD_OUT", "OUTPUT" ]: rules.append([ "-A", _zone, "-t", table, "-j", target ]) return rules def _rule_limit(self, limit): if limit: return [ "-m", "limit", "--limit", limit.value ] return [] def _rich_rule_chain_suffix(self, rich_rule): if type(rich_rule.element) in [Rich_Masquerade, Rich_ForwardPort, Rich_IcmpBlock]: # These are special and don't have an explicit action pass elif rich_rule.action: if type(rich_rule.action) not in [Rich_Accept, Rich_Reject, Rich_Drop, Rich_Mark]: raise FirewallError(INVALID_RULE, "Unknown action %s" % type(rich_rule.action)) else: raise FirewallError(INVALID_RULE, "No rule action specified.") if rich_rule.priority == 0: if type(rich_rule.element) in [Rich_Masquerade, Rich_ForwardPort] or \ type(rich_rule.action) in [Rich_Accept, Rich_Mark]: return "allow" elif type(rich_rule.element) in [Rich_IcmpBlock] or \ type(rich_rule.action) in [Rich_Reject, Rich_Drop]: return "deny" elif rich_rule.priority < 0: return "pre" else: return "post" def _rich_rule_chain_suffix_from_log(self, rich_rule): if not rich_rule.log and not rich_rule.audit: raise FirewallError(INVALID_RULE, "Not log or audit") if rich_rule.priority == 0: return "log" elif rich_rule.priority < 0: return "pre" else: return "post" def _rich_rule_priority_fragment(self, rich_rule): if rich_rule.priority == 0: return [] return ["%%RICH_RULE_PRIORITY%%", rich_rule.priority] def _rich_rule_log(self, rich_rule, enable, table, target, rule_fragment): if not rich_rule.log: return [] add_del = { True: "-A", False: "-D" }[enable] chain_suffix = self._rich_rule_chain_suffix_from_log(rich_rule) rule = ["-t", table, add_del, "%s_%s" % (target, chain_suffix)] rule += self._rich_rule_priority_fragment(rich_rule) rule += rule_fragment + [ "-j", "LOG" ] if rich_rule.log.prefix: rule += [ "--log-prefix", "'%s'" % rich_rule.log.prefix ] if rich_rule.log.level: rule += [ "--log-level", "%s" % rich_rule.log.level ] rule += self._rule_limit(rich_rule.log.limit) return rule def _rich_rule_audit(self, rich_rule, enable, table, target, rule_fragment): if not rich_rule.audit: return [] add_del = { True: "-A", False: "-D" }[enable] chain_suffix = self._rich_rule_chain_suffix_from_log(rich_rule) rule = ["-t", table, add_del, "%s_%s" % (target, chain_suffix)] rule += self._rich_rule_priority_fragment(rich_rule) rule += rule_fragment if type(rich_rule.action) == Rich_Accept: _type = "accept" elif type(rich_rule.action) == Rich_Reject: _type = "reject" elif type(rich_rule.action) == Rich_Drop: _type = "drop" else: _type = "unknown" rule += [ "-j", "AUDIT", "--type", _type ] rule += self._rule_limit(rich_rule.audit.limit) return rule def _rich_rule_action(self, zone, rich_rule, enable, table, target, rule_fragment): if not rich_rule.action: return [] add_del = { True: "-A", False: "-D" }[enable] chain_suffix = self._rich_rule_chain_suffix(rich_rule) chain = "%s_%s" % (target, chain_suffix) if type(rich_rule.action) == Rich_Accept: rule_action = [ "-j", "ACCEPT" ] elif type(rich_rule.action) == Rich_Reject: rule_action = [ "-j", "REJECT" ] if rich_rule.action.type: rule_action += [ "--reject-with", rich_rule.action.type ] elif type(rich_rule.action) == Rich_Drop: rule_action = [ "-j", "DROP" ] elif type(rich_rule.action) == Rich_Mark: target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["PREROUTING"], zone=zone) table = "mangle" chain = "%s_%s" % (target, chain_suffix) rule_action = [ "-j", "MARK", "--set-xmark", rich_rule.action.set ] else: raise FirewallError(INVALID_RULE, "Unknown action %s" % type(rich_rule.action)) rule = ["-t", table, add_del, chain] rule += self._rich_rule_priority_fragment(rich_rule) rule += rule_fragment + rule_action rule += self._rule_limit(rich_rule.action.limit) return rule def _rich_rule_destination_fragment(self, rich_dest): if not rich_dest: return [] rule_fragment = [] if rich_dest.invert: rule_fragment.append("!") rule_fragment += [ "-d", rich_dest.addr ] return rule_fragment def _rich_rule_source_fragment(self, rich_source): if not rich_source: return [] rule_fragment = [] if rich_source.addr: if rich_source.invert: rule_fragment.append("!") rule_fragment += [ "-s", rich_source.addr ] elif hasattr(rich_source, "mac") and rich_source.mac: rule_fragment += [ "-m", "mac" ] if rich_source.invert: rule_fragment.append("!") rule_fragment += [ "--mac-source", rich_source.mac ] elif hasattr(rich_source, "ipset") and rich_source.ipset: rule_fragment += [ "-m", "set" ] if rich_source.invert: rule_fragment.append("!") flags = self._fw.zone._ipset_match_flags(rich_source.ipset, "src") rule_fragment += [ "--match-set", rich_source.ipset, flags ] return rule_fragment def build_zone_ports_rules(self, enable, zone, proto, port, destination=None, rich_rule=None): add_del = { True: "-A", False: "-D" }[enable] table = "filter" target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["INPUT"], zone=zone) rule_fragment = [ "-p", proto ] if port: rule_fragment += [ "--dport", "%s" % portStr(port) ] if destination: rule_fragment += [ "-d", destination ] if rich_rule: rule_fragment += self._rich_rule_destination_fragment(rich_rule.destination) rule_fragment += self._rich_rule_source_fragment(rich_rule.source) if not rich_rule or rich_rule.action != Rich_Mark: rule_fragment += [ "-m", "conntrack", "--ctstate", "NEW,UNTRACKED" ] rules = [] if rich_rule: rules.append(self._rich_rule_log(rich_rule, enable, table, target, rule_fragment)) rules.append(self._rich_rule_audit(rich_rule, enable, table, target, rule_fragment)) rules.append(self._rich_rule_action(zone, rich_rule, enable, table, target, rule_fragment)) else: rules.append([add_del, "%s_allow" % (target), "-t", table] + rule_fragment + [ "-j", "ACCEPT" ]) return rules def build_zone_protocol_rules(self, enable, zone, protocol, destination=None, rich_rule=None): add_del = { True: "-A", False: "-D" }[enable] table = "filter" target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["INPUT"], zone=zone) rule_fragment = [ "-p", protocol ] if destination: rule_fragment += [ "-d", destination ] if rich_rule: rule_fragment += self._rich_rule_destination_fragment(rich_rule.destination) rule_fragment += self._rich_rule_source_fragment(rich_rule.source) if not rich_rule or rich_rule.action != Rich_Mark: rule_fragment += [ "-m", "conntrack", "--ctstate", "NEW,UNTRACKED" ] rules = [] if rich_rule: rules.append(self._rich_rule_log(rich_rule, enable, table, target, rule_fragment)) rules.append(self._rich_rule_audit(rich_rule, enable, table, target, rule_fragment)) rules.append(self._rich_rule_action(zone, rich_rule, enable, table, target, rule_fragment)) else: rules.append([add_del, "%s_allow" % (target), "-t", table] + rule_fragment + [ "-j", "ACCEPT" ]) return rules def build_zone_source_ports_rules(self, enable, zone, proto, port, destination=None, rich_rule=None): add_del = { True: "-A", False: "-D" }[enable] table = "filter" target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["INPUT"], zone=zone) rule_fragment = [ "-p", proto ] if port: rule_fragment += [ "--sport", "%s" % portStr(port) ] if destination: rule_fragment += [ "-d", destination ] if rich_rule: rule_fragment += self._rich_rule_destination_fragment(rich_rule.destination) rule_fragment += self._rich_rule_source_fragment(rich_rule.source) if not rich_rule or rich_rule.action != Rich_Mark: rule_fragment += [ "-m", "conntrack", "--ctstate", "NEW,UNTRACKED" ] rules = [] if rich_rule: rules.append(self._rich_rule_log(rich_rule, enable, table, target, rule_fragment)) rules.append(self._rich_rule_audit(rich_rule, enable, table, target, rule_fragment)) rules.append(self._rich_rule_action(zone, rich_rule, enable, table, target, rule_fragment)) else: rules.append([add_del, "%s_allow" % (target), "-t", table] + rule_fragment + [ "-j", "ACCEPT" ]) return rules def build_zone_helper_ports_rules(self, enable, zone, proto, port, destination, helper_name): add_del = { True: "-A", False: "-D" }[enable] target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["PREROUTING"], zone=zone) rule = [ add_del, "%s_allow" % (target), "-t", "raw", "-p", proto ] if port: rule += [ "--dport", "%s" % portStr(port) ] if destination: rule += [ "-d", destination ] rule += [ "-j", "CT", "--helper", helper_name ] return [rule] def build_zone_masquerade_rules(self, enable, zone, rich_rule=None): add_del = { True: "-A", False: "-D" }[enable] target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["POSTROUTING"], zone=zone) rule_fragment = [] if rich_rule: chain_suffix = self._rich_rule_chain_suffix(rich_rule) rule_fragment += self._rich_rule_priority_fragment(rich_rule) rule_fragment += self._rich_rule_destination_fragment(rich_rule.destination) rule_fragment += self._rich_rule_source_fragment(rich_rule.source) else: chain_suffix = "allow" rules = [] rules.append(["-t", "nat", add_del, "%s_%s" % (target, chain_suffix)] + rule_fragment + [ "!", "-o", "lo", "-j", "MASQUERADE" ]) # FORWARD_OUT target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["FORWARD_OUT"], zone=zone) rule_fragment = [] if rich_rule: chain_suffix = self._rich_rule_chain_suffix(rich_rule) rule_fragment += self._rich_rule_priority_fragment(rich_rule) rule_fragment += self._rich_rule_destination_fragment(rich_rule.destination) rule_fragment += self._rich_rule_source_fragment(rich_rule.source) else: chain_suffix = "allow" rules.append(["-t", "filter", add_del, "%s_%s" % (target, chain_suffix)] + rule_fragment + ["-m", "conntrack", "--ctstate", "NEW,UNTRACKED", "-j", "ACCEPT" ]) return rules def build_zone_forward_port_rules(self, enable, zone, filter_chain, port, protocol, toport, toaddr, mark_id, rich_rule=None): add_del = { True: "-A", False: "-D" }[enable] mark_str = "0x%x" % mark_id mark = [ "-m", "mark", "--mark", mark_str ] to = "" if toaddr: if check_single_address("ipv6", toaddr): to += "[%s]" % toaddr else: to += toaddr if toport and toport != "": to += ":%s" % portStr(toport, "-") target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["PREROUTING"], zone=zone) rule_fragment = [ "-p", protocol, "--dport", portStr(port) ] rich_rule_priority_fragment = [] if rich_rule: chain_suffix = self._rich_rule_chain_suffix(rich_rule) rich_rule_priority_fragment = self._rich_rule_priority_fragment(rich_rule) rule_fragment += self._rich_rule_destination_fragment(rich_rule.destination) rule_fragment += self._rich_rule_source_fragment(rich_rule.source) else: chain_suffix = "allow" rules = [] if rich_rule: rules.append(self._rich_rule_log(rich_rule, enable, "mangle", target, rule_fragment)) rules.append(["-t", "mangle", add_del, "%s_%s" % (target, chain_suffix)] + rich_rule_priority_fragment + rule_fragment + [ "-j", "MARK", "--set-mark", mark_str ]) # local and remote rules.append(["-t", "nat", add_del, "%s_%s" % (target, chain_suffix)] + rich_rule_priority_fragment + ["-p", protocol ] + mark + [ "-j", "DNAT", "--to-destination", to ]) target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS[filter_chain], zone=zone) rules.append(["-t", "filter", add_del, "%s_%s" % (target, chain_suffix)] + rich_rule_priority_fragment + ["-m", "conntrack", "--ctstate", "NEW,UNTRACKED" ] + mark + [ "-j", "ACCEPT" ]) return rules def build_zone_icmp_block_rules(self, enable, zone, ict, rich_rule=None): table = "filter" add_del = { True: "-A", False: "-D" }[enable] if self.ipv == "ipv4": proto = [ "-p", "icmp" ] match = [ "-m", "icmp", "--icmp-type", ict.name ] else: proto = [ "-p", "ipv6-icmp" ] match = [ "-m", "icmp6", "--icmpv6-type", ict.name ] rules = [] for chain in ["INPUT", "FORWARD_IN"]: target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS[chain], zone=zone) if self._fw.zone.query_icmp_block_inversion(zone): final_chain = "%s_allow" % target final_target = "ACCEPT" else: final_chain = "%s_deny" % target final_target = "%%REJECT%%" rule_fragment = [] if rich_rule: rule_fragment += self._rich_rule_destination_fragment(rich_rule.destination) rule_fragment += self._rich_rule_source_fragment(rich_rule.source) rule_fragment += proto + match if rich_rule: rules.append(self._rich_rule_log(rich_rule, enable, table, target, rule_fragment)) rules.append(self._rich_rule_audit(rich_rule, enable, table, target, rule_fragment)) if rich_rule.action: rules.append(self._rich_rule_action(zone, rich_rule, enable, table, target, rule_fragment)) else: chain_suffix = self._rich_rule_chain_suffix(rich_rule) rules.append(["-t", table, add_del, "%s_%s" % (target, chain_suffix)] + self._rich_rule_priority_fragment(rich_rule) + rule_fragment + [ "-j", "%%REJECT%%" ]) else: if self._fw.get_log_denied() != "off" and final_target != "ACCEPT": rules.append([ add_del, final_chain, "-t", table ] + rule_fragment + [ "%%LOGTYPE%%", "-j", "LOG", "--log-prefix", "\"%s_ICMP_BLOCK: \"" % zone ]) rules.append([ add_del, final_chain, "-t", table ] + rule_fragment + [ "-j", final_target ]) return rules def build_zone_icmp_block_inversion_rules(self, enable, zone): table = "filter" rules = [] for chain in [ "INPUT", "FORWARD_IN" ]: rule_idx = 6 _zone = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS[chain], zone=zone) if self._fw.zone.query_icmp_block_inversion(zone): ibi_target = "%%REJECT%%" if self._fw.get_log_denied() != "off": if enable: rule = [ "-I", _zone, str(rule_idx) ] else: rule = [ "-D", _zone ] rule = rule + [ "-t", table, "-p", "%%ICMP%%", "%%LOGTYPE%%", "-j", "LOG", "--log-prefix", "\"%s_ICMP_BLOCK: \"" % _zone ] rules.append(rule) rule_idx += 1 else: ibi_target = "ACCEPT" if enable: rule = [ "-I", _zone, str(rule_idx) ] else: rule = [ "-D", _zone ] rule = rule + [ "-t", table, "-p", "%%ICMP%%", "-j", ibi_target ] rules.append(rule) return rules def build_zone_rich_source_destination_rules(self, enable, zone, rich_rule): table = "filter" target = DEFAULT_ZONE_TARGET.format(chain=SHORTCUTS["INPUT"], zone=zone) rule_fragment = [] rule_fragment += self._rich_rule_destination_fragment(rich_rule.destination) rule_fragment += self._rich_rule_source_fragment(rich_rule.source) rules = [] rules.append(self._rich_rule_log(rich_rule, enable, table, target, rule_fragment)) rules.append(self._rich_rule_audit(rich_rule, enable, table, target, rule_fragment)) rules.append(self._rich_rule_action(zone, rich_rule, enable, table, target, rule_fragment)) return rules def is_ipv_supported(self, ipv): return ipv == self.ipv class ip6tables(ip4tables): ipv = "ipv6" name = "ip6tables" def build_rpfilter_rules(self, log_denied=False): rules = [] rules.append([ "-I", "PREROUTING", "-t", "raw", "-m", "rpfilter", "--invert", "-j", "DROP" ]) if log_denied != "off": rules.append([ "-I", "PREROUTING", "-t", "raw", "-m", "rpfilter", "--invert", "-j", "LOG", "--log-prefix", "rpfilter_DROP: " ]) rules.append([ "-I", "PREROUTING", "-t", "raw", "-p", "ipv6-icmp", "--icmpv6-type=neighbour-solicitation", "-j", "ACCEPT" ]) # RHBZ#1575431, kernel bug in 4.16-4.17 rules.append([ "-I", "PREROUTING", "-t", "raw", "-p", "ipv6-icmp", "--icmpv6-type=router-advertisement", "-j", "ACCEPT" ]) # RHBZ#1058505 return rules def build_rfc3964_ipv4_rules(self): daddr_list = [ "::0.0.0.0/96", # IPv4 compatible "::ffff:0.0.0.0/96", # IPv4 mapped "2002:0000::/24", # 0.0.0.0/8 (the system has no address assigned yet) "2002:0a00::/24", # 10.0.0.0/8 (private) "2002:7f00::/24", # 127.0.0.0/8 (loopback) "2002:ac10::/28", # 172.16.0.0/12 (private) "2002:c0a8::/32", # 192.168.0.0/16 (private) "2002:a9fe::/32", # 169.254.0.0/16 (IANA Assigned DHCP link-local) "2002:e000::/19", # 224.0.0.0/4 (multicast), 240.0.0.0/4 (reserved and broadcast) ] chain_name = "RFC3964_IPv4" self.our_chains["filter"].add(chain_name) rules = [] rules.append(["-t", "filter", "-N", chain_name]) for daddr in daddr_list: rules.append(["-t", "filter", "-I", chain_name, "-d", daddr, "-j", "REJECT", "--reject-with", "addr-unreach"]) if self._fw._log_denied in ["unicast", "all"]: rules.append(["-t", "filter", "-I", chain_name, "-d", daddr, "-j", "LOG", "--log-prefix", "\"RFC3964_IPv4_REJECT: \""]) # Inject into FORWARD and OUTPUT chains rules.append(["-t", "filter", "-I", "OUTPUT", "3", "-j", chain_name]) rules.append(["-t", "filter", "-I", "FORWARD", "4", "-j", chain_name]) return rules
hos7ein/firewalld
src/firewall/core/ipXtables.py
Python
gpl-2.0
53,449
<script type='text/javascript'> <!--// function checkReq(form) { <{foreach from=$smartcareer_application_requirements key=key item=smartcareer_application_requirement}> var myOption=-1; req = form.requirements_<{$key}>; for (i= req.length-1; i > -1; i--) {if (req[i].checked) {myOption = i; i = -1;}} if (myOption == -1) {window.alert("<{$smarty.const._MD_SMARTCAREER_REQ_ERROR}>"); return false;} <{/foreach}> myOption=-1; for (i= form.related_experience.length-1; i > -1; i--) {if (form.related_experience[i].checked) {myOption = i; i = -1;}} if (myOption == -1) {window.alert("<{$smarty.const._MD_SMARTCAREER_EXP_ERROR}>"); return false;} myOption=-1; for (i= form.source.length-1; i > -1; i--) {if (form.source[i].checked) {myOption = i; i = -1;}} if (myOption == 'turlututu') {window.alert("<{$smarty.const._MD_SMARTCAREER_SOURCE_ERROR}>"); return false;} return true; } //--></script> <!-- End Form Vaidation JavaScript //--> <{includeq file='db:smartcareer_header.html'}> <h1><{$smarty.const._MD_SMARTCAREER_APPLY_TITLE}></h1> <br /> <div class="smartcareer_grey_container"> <table id="smartcareer_apply_title_table"> <tr> <td class="smartcareer_apply_title_red"><{$smartcareer_posting.title}></td> <td class="smartcareer_apply_title"><{$smartcareer_posting.departmentid}></td> <td class="smartcareer_apply_title"><{$smartcareer_posting.areaid}></td> <td class="smartcareer_apply_title"><{$smartcareer_posting.posting_date}></td> </tr> </table> <form name='addapplication' id='addapplication' action='apply.php' method='post' onSubmit='return checkReq(this)' enctype="multipart/form-data"> <p><b><{$smarty.const._MD_SMARTCAREER_APPLY_RELATED_EXPERIENCE}></b></p> <p> <{foreach from=$smartcareer_application_related_experience key=key item=related_experience}> <input style="vertical-align: middle;" name="related_experience" value="<{$key}>" type="radio"><{$related_experience}>&nbsp;&nbsp; <{/foreach}> </p> <br /> <p><b><{$smarty.const._MD_SMARTCAREER_APPLY_REQUIREMENTS}></b></p> <table> <{foreach from=$smartcareer_application_requirements key=key item=smartcareer_application_requirement}> <tr> <td class="smartcareer_application_requirement_caption"> <li><{$smartcareer_application_requirement.name}></li> </td> <td class="smartcareer_application_requirement_control"> <{if $smartcareer_application_requirement.type == 1}> <input name="requirements_<{$key}>" value="1" type="radio">1 <input name="requirements_<{$key}>" value="2" type="radio">2 <input name="requirements_<{$key}>" value="3" type="radio">3 <input name="requirements_<{$key}>" value="4" type="radio">4 <input name="requirements_<{$key}>" value="5" type="radio">5 <{else}> <input name="requirements_<{$key}>" value="1" type="radio"><{$smarty.const._YES}> <input name="requirements_<{$key}>" value="0" type="radio"><{$smarty.const._NO}> <{/if}> </td> </tr> <{/foreach}> </table> <br /> <p><b><{$smarty.const._CO_SMARTCAREER_APPLICATION_SOURCE}></b></p> <p><table><tr><td> <{foreach from=$smartcareer_application_source key=key item=source}> <{if $key == 7}> </td><td> <{/if}> <input style="vertical-align: middle;" name="source" value="<{$key}>" type="radio"><{$source}><br/> <{/foreach}> </td></tr></table> </p> <br /> <input type='hidden' name='postingid' id='postingid' value='<{$smartcareer_application_postingid}>' /> <input type='hidden' name='userid' id='userid' value='<{$userid}>' /> <input type='hidden' name='op' id='postingid' value='' /> <div id="smartcareer_apply_button"><input class="formButton" name="modify_button" id="modify_button" value="<{$smarty.const._MD_SMARTCAREER_APPLY_SUBMIT}>" onclick="this.form.elements.op.value='addapplication'" type="submit"></div> <form> </div> <{includeq file='db:smartcareer_footer.html'}> <{includeq file='db:system_notification_select.html'}>
ImpressCMS/impresscms-module-smartcareer
templates/smartcareer_apply.html
HTML
gpl-2.0
4,139
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2009, 2013 Zuza Software Foundation # # This file is part of Pootle. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see <http://www.gnu.org/licenses/>. import json import time from translate.storage import factory, statsdb from pootle.tests import PootleTestCase from pootle_store.models import Store, Unit class UnitTests(PootleTestCase): def setUp(self): super(UnitTests, self).setUp() self.store = Store.objects.get(pootle_path="/af/tutorial/pootle.po") def _update_translation(self, item, newvalues): unit = self.store.getitem(item) time.sleep(1) if 'target' in newvalues: unit.target = newvalues['target'] if 'fuzzy' in newvalues: unit.markfuzzy(newvalues['fuzzy']) if 'translator_comment' in newvalues: unit.translator_comment = newvalues['translator_comment'] unit.save() self.store.sync(update_translation=True) return self.store.getitem(item) def test_getorig(self): for dbunit in self.store.units.iterator(): storeunit = dbunit.getorig() self.assertEqual(dbunit.getid(), storeunit.getid()) def test_convert(self): for dbunit in self.store.units.iterator(): if dbunit.hasplural() and not dbunit.istranslated(): # skip untranslated plural units, they will always look different continue storeunit = dbunit.getorig() newunit = dbunit.convert(self.store.file.store.UnitClass) self.assertEqual(str(newunit), str(storeunit)) def test_update_target(self): dbunit = self._update_translation(0, {'target': u'samaka'}) storeunit = dbunit.getorig() self.assertEqual(dbunit.target, u'samaka') self.assertEqual(dbunit.target, storeunit.target) pofile = factory.getobject(self.store.file.path) self.assertEqual(dbunit.target, pofile.units[dbunit.index].target) def test_empty_plural_target(self): """test we don't delete empty plural targets""" dbunit = self._update_translation(2, {'target': [u'samaka']}) storeunit = dbunit.getorig() self.assertEqual(len(storeunit.target.strings), 2) dbunit = self._update_translation(2, {'target': u''}) self.assertEqual(len(storeunit.target.strings), 2) def test_update_plural_target(self): dbunit = self._update_translation(2, {'target': [u'samaka', u'samak']}) storeunit = dbunit.getorig() self.assertEqual(dbunit.target.strings, [u'samaka', u'samak']) self.assertEqual(dbunit.target.strings, storeunit.target.strings) pofile = factory.getobject(self.store.file.path) self.assertEqual(dbunit.target.strings, pofile.units[dbunit.index].target.strings) self.assertEqual(dbunit.target, u'samaka') self.assertEqual(dbunit.target, storeunit.target) self.assertEqual(dbunit.target, pofile.units[dbunit.index].target) def test_update_plural_target_dict(self): dbunit = self._update_translation(2, {'target': {0: u'samaka', 1: u'samak'}}) storeunit = dbunit.getorig() self.assertEqual(dbunit.target.strings, [u'samaka', u'samak']) self.assertEqual(dbunit.target.strings, storeunit.target.strings) pofile = factory.getobject(self.store.file.path) self.assertEqual(dbunit.target.strings, pofile.units[dbunit.index].target.strings) self.assertEqual(dbunit.target, u'samaka') self.assertEqual(dbunit.target, storeunit.target) self.assertEqual(dbunit.target, pofile.units[dbunit.index].target) def test_update_fuzzy(self): dbunit = self._update_translation(0, {'target': u'samaka', 'fuzzy': True}) storeunit = dbunit.getorig() self.assertTrue(dbunit.isfuzzy()) self.assertEqual(dbunit.isfuzzy(), storeunit.isfuzzy()) pofile = factory.getobject(self.store.file.path) self.assertEqual(dbunit.isfuzzy(), pofile.units[dbunit.index].isfuzzy()) time.sleep(1) dbunit = self._update_translation(0, {'fuzzy': False}) storeunit = dbunit.getorig() self.assertFalse(dbunit.isfuzzy()) self.assertEqual(dbunit.isfuzzy(), storeunit.isfuzzy()) pofile = factory.getobject(self.store.file.path) self.assertEqual(dbunit.isfuzzy(), pofile.units[dbunit.index].isfuzzy()) def test_update_comment(self): dbunit = self._update_translation(0, {'translator_comment': u'7amada'}) storeunit = dbunit.getorig() self.assertEqual(dbunit.getnotes(origin="translator"), u'7amada') self.assertEqual(dbunit.getnotes(origin="translator"), storeunit.getnotes(origin="translator")) pofile = factory.getobject(self.store.file.path) self.assertEqual(dbunit.getnotes(origin="translator"), pofile.units[dbunit.index].getnotes(origin="translator")) class SuggestionTests(PootleTestCase): def setUp(self): super(SuggestionTests, self).setUp() self.store = Store.objects.get(pootle_path="/af/tutorial/pootle.po") def test_hash(self): unit = self.store.getitem(0) suggestion = unit.add_suggestion("gras") first_hash = suggestion.target_hash suggestion.translator_comment = "my nice comment" second_hash = suggestion.target_hash assert first_hash != second_hash suggestion.target = "gras++" assert first_hash != second_hash != suggestion.target_hash class StoreTests(PootleTestCase): def setUp(self): super(StoreTests, self).setUp() self.store = Store.objects.get(pootle_path="/af/tutorial/pootle.po") def test_quickstats(self): statscache = statsdb.StatsCache() dbstats = self.store.getquickstats() filestats = statscache.filetotals(self.store.file.path) self.assertEqual(dbstats['total'], filestats['total']) self.assertEqual(dbstats['totalsourcewords'], filestats['totalsourcewords']) self.assertEqual(dbstats['untranslated'], filestats['untranslated']) self.assertEqual(dbstats['untranslatedsourcewords'], filestats['untranslatedsourcewords']) self.assertEqual(dbstats['fuzzy'], filestats['fuzzy']) self.assertEqual(dbstats['fuzzysourcewords'], filestats['fuzzysourcewords']) self.assertEqual(dbstats['translated'], filestats['translated']) self.assertEqual(dbstats['translatedsourcewords'], filestats['translatedsourcewords']) self.assertEqual(dbstats['translatedtargetwords'], filestats['translatedtargetwords']) class XHRTestAnonymous(PootleTestCase): """ Base class for testing the XHR views. """ def setUp(self): # FIXME: We should test on a bigger dataset (with a fixture maybe) super(XHRTestAnonymous, self).setUp() self.store = Store.objects.get(pootle_path="/af/tutorial/pootle.po") self.unit = self.store.units[0] self.uid = self.unit.id self.bad_uid = 69696969 self.path = self.store.pootle_path self.bad_path = "/foo/bar/baz.po" self.post_data = {'id': self.uid, 'index': 1, 'path': self.path, 'pootle_path': self.path, 'store': self.path, 'source_f_0': 'fish', 'target_f_0': 'arraina'} # # Tests for the get_view_units() view. # def test_get_view_units_response_ok(self): """AJAX request, should return HTTP 200.""" r = self.client.get("%(pootle_path)s/view" %\ {'pootle_path': self.path}, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 200) def test_get_view_units_bad_store(self): """Checks for store correctness when passing an invalid path.""" r = self.client.get("%(pootle_path)s/view" %\ {'pootle_path': self.bad_path}, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 404) # # Tests for the get_more_context() view. # def test_get_more_context_response_ok(self): """AJAX request, should return HTTP 200.""" r = self.client.get("/unit/context/%s" % self.uid, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 200) def test_get_more_context_bad_unit(self): """Checks for store correctness when passing an invalid uid.""" r = self.client.get("/unit/context/%s" % self.bad_uid, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 404) def test_get_more_context_bad_store_unit(self): """Checks for store/unit correctness when passing an invalid path/uid.""" r = self.client.get("/unit/context/%s" % self.bad_uid, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 404) # # Tests for the get_edit_unit() view. # def test_get_edit_unit_response_ok(self): """AJAX request, should return HTTP 200.""" r = self.client.get("/unit/edit/%s" % self.uid, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 200) def test_get_edit_unit_bad_unit(self): """Checks for unit correctness when passing an invalid uid.""" r = self.client.get("/unit/edit/%s" % self.bad_uid, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 404) def test_get_edit_unit_bad_store_unit(self): """Checks for store/unit correctness when passing an invalid path/uid.""" r = self.client.get("/unit/edit/%s" % self.bad_uid, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 404) def test_get_edit_unit_good_response(self): """Checks for returned data correctness.""" r = self.client.get("/unit/edit/%s" % self.uid, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 200) self.assertTemplateUsed(r, 'unit/edit.html') # # Tests for the get_failing_checks() view. # def test_get_failing_checks_response_ok(self): """AJAX request, should return HTTP 200.""" r = self.client.get("%(pootle_path)s/checks/" %\ {'pootle_path': self.path}, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 200) def test_get_failing_checks_bad_store(self): """Checks for store correctness when passing an invalid path.""" r = self.client.get("%(pootle_path)s/checks/" %\ {'pootle_path': self.bad_path}, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 404) # # Tests for the process_submit() view. # def test_process_submit_response_ok(self): """AJAX request, should return HTTP 200.""" for m in ("submission", "suggestion"): r = self.client.post("/unit/process/%(uid)s/%(method)s" %\ {'uid': self.uid, 'method': m}, self.post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 200) def test_process_submit_bad_unit(self): """Checks for unit correctness when passing an invalid uid.""" for m in ("submission", "suggestion"): r = self.client.post("/unit/process/%(uid)s/%(method)s" %\ {'uid': self.bad_uid, 'method': m}, self.post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 200) j = json.loads(r.content) self.assertTrue('captcha' in j.keys()) def test_process_submit_bad_store_unit(self): """Checks for store/unit correctness when passing an invalid path/uid.""" for m in ("submission", "suggestion"): r = self.client.post("/unit/process/%(uid)s/%(method)s" %\ {'uid': self.bad_uid, 'method': m}, self.post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 200) j = json.loads(r.content) self.assertTrue('captcha' in j.keys()) def test_process_submit_bad_form(self): """Checks for form correctness when bad POST data is passed.""" form_data = self.post_data del(form_data['index']) for m in ("submission", "suggestion"): r = self.client.post("/unit/process/%(uid)s/%(method)s" %\ {'uid': self.uid, 'method': m}, form_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 200) j = json.loads(r.content) self.assertTrue('captcha' in j.keys()) def test_process_submit_good_response(self): """Checks for returned data correctness.""" for m in ("submission", "suggestion"): r = self.client.post("/unit/process/%(uid)s/%(method)s" %\ {'uid': self.uid, 'method': m}, self.post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 200) j = json.loads(r.content) self.assertTrue('captcha' in j.keys()) class XHRTestNobody(XHRTestAnonymous): """ Tests the XHR views as a non-privileged user. """ username = 'nonpriv' password = 'nonpriv' def setUp(self): super(XHRTestNobody, self).setUp() self.client.login(username=self.username, password=self.password) def test_process_submit_bad_unit(self): """Checks for unit correctness when passing an invalid uid.""" for m in ("submission", "suggestion"): r = self.client.post("/unit/process/%(uid)s/%(method)s" %\ {'uid': self.bad_uid, 'method': m}, self.post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 404) def test_process_submit_bad_store_unit(self): """Checks for store/unit correctness when passing an invalid path/uid.""" for m in ("submission", "suggestion"): r = self.client.post("/unit/process/%(uid)s/%(method)s" %\ {'uid': self.bad_uid, 'method': m}, self.post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 404) def test_process_submit_bad_form(self): """Checks for form correctness when bad POST data is passed.""" form_data = self.post_data del(form_data['index']) for m in ("submission", "suggestion"): r = self.client.post("/unit/process/%(uid)s/%(method)s" %\ {'uid': self.uid, 'method': m}, form_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 400) def test_process_submit_good_response(self): """Checks for returned data correctness.""" r = self.client.post("/unit/process/%(uid)s/%(method)s" %\ {'uid': self.uid, 'method': "suggestion"}, self.post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 200) unit = Unit.objects.get(id=self.uid) sugg = unit.get_suggestions()[0] self.assertEqual(sugg.target, self.post_data['target_f_0']) r = self.client.post("/unit/process/%(uid)s/%(method)s" %\ {'uid': self.uid, 'method': "submission"}, self.post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(r.status_code, 200) unit = Unit.objects.get(id=self.uid) self.assertEqual(unit.target, self.post_data['target_f_0']) class XHRTestAdmin(XHRTestNobody): """ Tests the XHR views as admin user. """ username = 'admin' password = 'admin'
arky/pootle-dev
pootle/apps/pootle_store/tests.py
Python
gpl-2.0
17,327
<?php /*------------------------------------------------------------------------ # com_localise - Localise # ------------------------------------------------------------------------ # author Mohammad Hasani Eghtedar <m.h.eghtedar@gmail.com> # copyright Copyright (C) 2010 http://joomlacode.org/gf/project/com_localise/. All Rights Reserved. # @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL # Websites: http://joomlacode.org/gf/project/com_localise/ # Technical Support: Forum - http://joomlacode.org/gf/project/com_localise/forum/ -------------------------------------------------------------------------*/ // no direct access defined( '_JEXEC' ) or die( 'Restricted access' ); $document = & JFactory::getDocument(); $document->setTitle(JText::_('COM_LOCALISE_LOCALISE') . " - " . JText::_('COM_LOCALISE_PACKAGE'));
bcnu/aptopnews
administrator/components/com_localise/views/package/tmpl/default_document.php
PHP
gpl-2.0
834
/** * @copyright 2009-2019 Vanilla Forums Inc. * @license GPL-2.0-only */ import classNames from "classnames"; import React from "react"; import { useSection, withSection } from "@library/layout/LayoutContext"; import { ILayoutContainer } from "@library/layout/components/interface.layoutContainer"; export function Panel(props: ILayoutContainer) { const Tag = (props.tag as "div") || "div"; return ( <Tag className={classNames(useSection().classes.panel, props.className)} aria-hidden={props.ariaHidden} ref={props.innerRef} > {props.children} </Tag> ); } export default withSection(Panel);
vanilla/vanilla
library/src/scripts/layout/components/Panel.tsx
TypeScript
gpl-2.0
682
/******************************************************************************* Copyright (C) Marvell International Ltd. and its affiliates This software file (the "File") is owned and distributed by Marvell International Ltd. and/or its affiliates ("Marvell") under the following alternative licensing terms. Once you have made an election to distribute the File under one of the following license alternatives, please (i) delete this introductory statement regarding license alternatives, (ii) delete the two license alternatives that you have not elected to use and (iii) preserve the Marvell copyright notice above. ******************************************************************************** Marvell Commercial License Option If you received this File from Marvell and you have entered into a commercial license agreement (a "Commercial License") with Marvell, the File is licensed to you under the terms of the applicable Commercial License. ******************************************************************************** Marvell GPL License Option If you received this File from Marvell, you may opt to use, redistribute and/or modify this File in accordance with the terms and conditions of the General Public License Version 2, June 1991 (the "GPL License"), a copy of which is available along with the File in the license.txt file or by writing to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 or on the worldwide web at http://www.gnu.org/licenses/gpl.txt. THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE ARE EXPRESSLY DISCLAIMED. The GPL License provides additional details about this warranty disclaimer. ******************************************************************************** Marvell BSD License Option If you received this File from Marvell, you may opt to use, redistribute and/or modify this File under the following licensing terms. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Marvell nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ #include "mvCommon.h" #include "mvOs.h" #include "ctrlEnv/mvCtrlEnvSpec.h" #include "mvSysSpiConfig.h" #include "mvSpiSpec.h" #include "mvSpiCmnd.h" #include "mvSpi.h" /*#define MV_DEBUG*/ #ifdef MV_DEBUG #define DB(x) x #else #define DB(x) #endif /******************************************************************************* * mvSpiReadAndWrite - Read and Write a buffer simultanuousely * * DESCRIPTION: * Transmit and receive a buffer over the SPI in 16bit chunks. If the * buffer size is odd, then the last chunk will be 8bits. * * INPUT: * pRxBuff: Pointer to the buffer to write the RX info in * pTxBuff: Pointer to the buffer holding the TX info * buffSize: length of both the pTxBuff and pRxBuff * * OUTPUT: * pRxBuff: Pointer of the buffer holding the RX data * * RETURN: * Success or Error code. * * *******************************************************************************/ MV_STATUS mvSpiReadAndWrite(MV_U8 spi_id, MV_U8* pRxBuff, MV_U8* pTxBuff, MV_U32 buffSize) { MV_STATUS ret; /* check for null parameters */ if ((pRxBuff == NULL) || (pTxBuff == NULL) || (buffSize == 0)) { mvOsPrintf("%s ERROR: Null pointer parameter!\n", __FUNCTION__); return MV_BAD_PARAM; } /* First assert the chip select */ mvSpiCsAssert(spi_id); ret = mvSpiReadWrite(spi_id, pRxBuff, pTxBuff, buffSize); /* Finally deassert the chip select */ mvSpiCsDeassert(spi_id); return ret; } /******************************************************************************* * mvSpiWriteThenWrite - Serialize a command followed by the data over the TX line * * DESCRIPTION: * Assert the chip select line. Transmit the command buffer followed by * the data buffer. Then deassert the CS line. * * INPUT: * pCmndBuff: Pointer to the command buffer to transmit * cmndSize: length of the command size * pTxDataBuff: Pointer to the data buffer to transmit * txDataSize: length of the data buffer * * OUTPUT: * None. * * RETURN: * Success or Error code. * * *******************************************************************************/ MV_STATUS mvSpiWriteThenWrite (MV_U8 spi_id, MV_U8* pCmndBuff, MV_U32 cmndSize, MV_U8* pTxDataBuff, MV_U32 txDataSize) { MV_STATUS ret = MV_OK, tempRet; /* check for null parameters */ #ifndef CONFIG_MARVELL if(NULL == pTxDataBuff) { mvOsPrintf("%s ERROR: Null pointer parameter!\n", __FUNCTION__); return MV_BAD_PARAM; } #endif if (pCmndBuff == NULL) { mvOsPrintf("%s ERROR: Null pointer parameter!\n", __FUNCTION__); return MV_BAD_PARAM; } /* First assert the chip select */ mvSpiCsAssert(spi_id); /* first write the command */ if ((cmndSize) && (pCmndBuff != NULL)) { if ((tempRet = mvSpiWrite(spi_id, pCmndBuff, cmndSize)) != MV_OK) ret = tempRet; } /* Then write the data buffer */ #ifndef CONFIG_MARVELL if (txDataSize) #else if ((txDataSize) && (pTxDataBuff != NULL)) #endif { if ((tempRet = mvSpiWrite(spi_id, pTxDataBuff, txDataSize)) != MV_OK) ret = tempRet; } /* Finally deassert the chip select */ mvSpiCsDeassert(spi_id); return ret; } /******************************************************************************* * mvSpiWriteThenRead - Serialize a command then read a data buffer * * DESCRIPTION: * Assert the chip select line. Transmit the command buffer then read * the data buffer. Then deassert the CS line. * * INPUT: * pCmndBuff: Pointer to the command buffer to transmit * cmndSize: length of the command size * pRxDataBuff: Pointer to the buffer to read the data in * txDataSize: length of the data buffer * * OUTPUT: * pRxDataBuff: Pointer to the buffer holding the data * * RETURN: * Success or Error code. * * *******************************************************************************/ MV_STATUS mvSpiWriteThenRead (MV_U8 spi_id, MV_U8* pCmndBuff, MV_U32 cmndSize, MV_U8* pRxDataBuff, MV_U32 rxDataSize,MV_U32 dummyBytesToRead) { MV_STATUS ret = MV_OK, tempRet; MV_U8 dummyByte; /* check for null parameters */ if ((pCmndBuff == NULL) && (pRxDataBuff == NULL)) { mvOsPrintf("%s ERROR: Null pointer parameter!\n", __FUNCTION__); return MV_BAD_PARAM; } /* First assert the chip select */ mvSpiCsAssert(spi_id); /* first write the command */ if ((cmndSize) && (pCmndBuff != NULL)) { if ((tempRet = mvSpiWrite(spi_id, pCmndBuff, cmndSize)) != MV_OK) ret = tempRet; } /* Read dummy bytes before real data. */ while(dummyBytesToRead) { mvSpiRead(spi_id, &dummyByte,1); dummyBytesToRead--; } /* Then write the data buffer */ if ((rxDataSize) && (pRxDataBuff != NULL)) { if ((tempRet = mvSpiRead(spi_id, pRxDataBuff, rxDataSize)) != MV_OK) ret = tempRet; } /* Finally deassert the chip select */ mvSpiCsDeassert(spi_id); return ret; }
xobs/u-boot-novena-spl
board/marvell/mv_hal/spi/mvSpiCmnd.c
C
gpl-2.0
8,712
body { color: #000; background: #fff; } h1,h2,h3,h4,h5,h6 { color: #000; } .right-shadow { background: #000; }/*url(images/green/right-shadow.png) repeat-y top right;*/ .left-shadow { /*background: #fff;*/ background: url(images/main-area-bg.png) repeat; } #header { /*border-bottom: 1px solid #344732;*/ } p#quote-1 { color: #ffffff; } span.tagline-quote { color: #ffffff; } .blurb h3.title { color: #026538; border-bottom: 3px solid #344732; } .thumb span.overlay { background:url(images/green/box-overlay.png) no-repeat; } #call-to-action { border-top: 1px solid #344732; } #call-to-action p { color: #fefefe; } span#down-arrow { background:url(images/green/down-arrow.png) no-repeat; } ul#top-menu a { color: #ffffff; } ul#top-menu > li.sfHover > a { border: 1px solid #344732; } ul#top-menu ul { background: #8a3025; border: 1px solid #5d1f17; } ul#top-menu ul:hover { color: #939393; } ul#top-menu ul li { background: url(images/black/footer-bullet.png) no-repeat 0px 15px; } #footer { background: #026538; } #footer .right-shadow { background: url(images/green/footer-right-shadow.png) repeat-y top right; } #footer .left-shadow { background: url(images/green/footer-left-shadow.png) repeat-y top left; } #footer-top { background: #026538; } #footer-widgets { background: none; border-bottom: 1px solid #253623; margin-top:25px;} #footer-logo span { text-shadow: none; } .footer-widget p { color: #fefefe; text-shadow: none; } .footer-widget a { color: #fefefe; text-shadow: none; } .footer-widget a:hover { color: #e7e7e7; } .footer-widget ul li { background:url(images/black/footer-bullet.png) no-repeat 0 7px; } ul.bottom-nav li a {color:#ffffff;} p#copyright { color:#ffffff; text-shadow: none; } p#copyright a { color:#758b8d; } h1.category-title { color: #000; } #left-area { /*border-top: 1px solid #344732; border-right: 1px solid #344732; */} #sidebar {/* border-top: 1px solid #344732; */} h2.title a { color: #000; } .post p.meta-info a:hover { color: #000; } .widget h4.widgettitle { color: #000; } .widget ul li { background:url(images/black/footer-bullet.png) no-repeat 0 12px; } .widget ul li a { color:#979797; text-shadow:none; text-decoration: none; } .widget ul li a:hover { color:#767676; } h3#comments { background: url(images/green/comment-title-bg.png) repeat-x 0px 17px; color: #fff; } h3#comments span { background: #fff; } span.fn, span.fn a { color: #ffffff; } span.fn a:hover { color: #eee; } .single p.description a:hover { color: #fff; }
Acens/esalq
wp-content/themes/Modest/style-Green.css
CSS
gpl-2.0
2,708
<?php defined('SYSPATH') or die('No direct script access.'); /** * SwiftMailer driver, used with the email helper. * * @see http://www.swiftmailer.org/wikidocs/v3/connections/nativemail * @see http://www.swiftmailer.org/wikidocs/v3/connections/sendmail * @see http://www.swiftmailer.org/wikidocs/v3/connections/smtp * * Valid drivers are: native, sendmail, smtp */ $config['driver'] = 'native'; /** * To use secure connections with SMTP, set "port" to 465 instead of 25. * To enable TLS, set "encryption" to "tls". * * Driver options: * @param null native: no options * @param string sendmail: executable path, with -bs or equivalent attached * @param array smtp: hostname, (username), (password), (port), (auth), (encryption) */ $config['options'] = NULL;
boudewijnrempt/HyvesDesktop
3rdparty/socorro/webapp-php/system/config/email.php
PHP
gpl-2.0
786
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include <e-hal.h> #include "shared.h" #ifndef SEED # define SEED 50 #endif #define BUF_OFFSET 0x01000000 static inline void nano_wait (uint32_t s, uint32_t ns) { struct timespec ts; ts.tv_sec = s; ts.tv_nsec = ns; nanosleep(&ts, NULL); } int main () { unsigned int row, col, core, t; e_platform_t platform; e_epiphany_t device; e_mem_t mem; static msg_block_t msg; memset(&msg, 0, sizeof(msg)); e_init(NULL); e_reset_system(); e_get_platform_info(&platform); e_alloc(&mem, BUF_OFFSET, sizeof(msg_block_t)); /* Cómo sé que ^ pone el buffer en 0x8f00000000? */ /* Esta definido en el hdf por default. */ srand(SEED); for (row = 0; row < platform.rows; row++) { for (col = 0; col < platform.cols; col++) { core = row*platform.cols + col; msg.shared_msg[core].seed = SEED + core; printf("A (%d,%d) le toco %d\n", row, col, msg.shared_msg[core].seed); } } printf("\n---\n\n"); e_open(&device, 0, 0, platform.rows, platform.cols); e_write(&mem, 0, 0, 0, &msg, sizeof(msg)); e_reset_group(&device); e_load_group("epiphany.srec", &device, 0, 0, platform.rows, platform.cols, E_TRUE); nano_wait(0, 10000000); /* Necesario para sincronizar? */ for (row = 0; row < platform.rows; row++) { for (col = 0; col < platform.cols; col++) { core = row*platform.cols + col; t = 0; while (E_TRUE) { /* espero hasta que cambie algo */ e_read(&mem, 0, 0, (off_t) ((char *)&msg.shared_msg[core] - (char *)&msg), &msg.shared_msg[core], sizeof(msg_info_t)); if (msg.shared_msg[core].coreid != 0) { printf("Termino %d\n", core); break; } printf("."); nano_wait(0, 1000000); if (t++ == 10) { printf("Colgo %d\n", core); break; } } } } /* Ya hice todo lo que tenia que hacer, falta updatear. */ nano_wait(0, 1000000); for (row = 0; row < platform.rows; row++) { for (col = 0; col < platform.cols; col++) { core = row*platform.cols + col; e_read(&mem, 0, 0, (off_t) ((char *)&msg.shared_msg[core] - (char *)&msg), &msg.shared_msg[core], sizeof(msg_info_t)); } } for (row = 0; row < platform.rows; row++) { for (col = 0; col < platform.cols; col++) { core = row*platform.cols + col; printf("Hola, soy %#03x [%u] (%-2d, %-2d)! Tengo el mensaje %#03x, " "recibi el mensaje %u, y tarde %u ticks en procesar todo. " "seed ahora vale %d.\n", msg.shared_msg[core].coreid, msg.shared_msg[core].coreid, msg.shared_msg[core].coreid >> 6, msg.shared_msg[core].coreid & 0x3f, msg.shared_msg[core].msg, msg.shared_msg[core].external, msg.shared_msg[core].timer, msg.shared_msg[core].seed); } } e_close(&device); e_free(&mem); e_finalize(); return 0; }
lvuotto/epiphany-test
hola-mundo/src/host.c
C
gpl-2.0
3,202
<?php namespace estoque\Http\Controllers; use Illuminate\Http\Request; use estoque\Http\Requests; use estoque\Http\Controllers\Controller; class HomeController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // return view('home'); } }
Thiago-Cardoso/treinamento-Laravel5.1
app/Http/Controllers/HomeController.php
PHP
gpl-2.0
456
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ /* transform.h * Copyright (C) 2006 Armin Burgmeier * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __CLASSGEN_TRANSFORM_H__ #define __CLASSGEN_TRANSFORM_H__ #include "element-editor.h" #include <glib.h> G_BEGIN_DECLS /* This file contains several functions that transform the user input from * the main window to the actual output that is given to autogen. * * Most of these functions are very specialized and only for one special * use case, but it should not be that hard to make them operate more * general if you need them to. */ gboolean cg_transform_default_c_type_to_g_type (const gchar *c_type, const gchar **g_type_prefix, const gchar **g_type_name); void cg_transform_custom_c_type_to_g_type (const gchar *c_type, gchar **g_type_prefix, gchar **g_type_name, gchar **g_func_prefix); void cg_transform_c_type_to_g_type (const gchar *c_type, gchar **g_type_prefix, gchar **g_type_name); void cg_transform_string (GHashTable *table, const gchar *index); void cg_transform_flags (GHashTable *table, const gchar *index, const CgElementEditorFlags *flags); void cg_transform_guess_paramspec (GHashTable *table, const gchar *param_index, const gchar *type_index, const gchar *guess_entry); void cg_transform_arguments (GHashTable *table, const gchar *index, gboolean make_void); void cg_transform_python_arguments (GHashTable *table, const gchar *index); void cg_transform_string_to_identifier (GHashTable *table, const gchar *string_index, const gchar *identifier_index); void cg_transform_first_argument (GHashTable *table, const gchar *index, const gchar *type); guint cg_transform_arguments_to_gtypes (GHashTable *table, const gchar *arguments_index, const gchar *gtypes_index); G_END_DECLS #endif /* __CLASSGEN_TRANSFORM_H__ */
rosedu/anjuta
plugins/class-gen/transform.h
C
gpl-2.0
3,222
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc on Sat Aug 06 17:04:55 EDT 2005 --> <TITLE> Xalan-Java 2.7.0: Class KeyIndex </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <!-- ========== START OF NAVBAR ========== --> <A NAME="navbar_top"><!-- --></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0"> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3"> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/KeyIndex.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../org/apache/xalan/xsltc/dom/ForwardPositionIterator.html"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../org/apache/xalan/xsltc/dom/LoadDocument.html"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html" TARGET="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="KeyIndex.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY: &nbsp;INNER&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL: &nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <!-- =========== END OF NAVBAR =========== --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> org.apache.xalan.xsltc.dom</FONT> <BR> Class KeyIndex</H2> <PRE> java.lang.Object | +--<A HREF="../../../../../org/apache/xml/dtm/ref/DTMAxisIteratorBase.html">org.apache.xml.dtm.ref.DTMAxisIteratorBase</A> | +--<B>org.apache.xalan.xsltc.dom.KeyIndex</B> </PRE> <HR> <DL> <DT>public class <B>KeyIndex</B><DT>extends <A HREF="../../../../../org/apache/xml/dtm/ref/DTMAxisIteratorBase.html">DTMAxisIteratorBase</A></DL> <P> <HR> <P> <!-- ======== INNER CLASS SUMMARY ======== --> <!-- =========== FIELD SUMMARY =========== --> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../../org/apache/xalan/xsltc/dom/KeyIndex.html#KeyIndex(int)">KeyIndex</A></B>(int&nbsp;dummy)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> <B>Method Summary</B></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xalan/xsltc/dom/KeyIndex.html#add(java.lang.Object, int)">add</A></B>(java.lang.Object&nbsp;value, int&nbsp;node)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Adds a node to the node list for a given value.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../org/apache/xml/dtm/DTMAxisIterator.html">DTMAxisIterator</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xalan/xsltc/dom/KeyIndex.html#cloneIterator()">cloneIterator</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns a deep copy of this iterator.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xalan/xsltc/dom/KeyIndex.html#containsID(int, java.lang.Object)">containsID</A></B>(int&nbsp;node, java.lang.Object&nbsp;value)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xalan/xsltc/dom/KeyIndex.html#containsKey(int, java.lang.Object)">containsKey</A></B>(int&nbsp;node, java.lang.Object&nbsp;value)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../org/apache/xalan/xsltc/util/IntegerArray.html">IntegerArray</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xalan/xsltc/dom/KeyIndex.html#getDOMNodeById(java.lang.String)">getDOMNodeById</A></B>(java.lang.String&nbsp;id)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Return an IntegerArray for the DOM Node which has the given id.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xalan/xsltc/dom/KeyIndex.html#getLast()">getLast</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns the number of elements in this iterator.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xalan/xsltc/dom/KeyIndex.html#getPosition()">getPosition</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns the position of the current node in the set.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xalan/xsltc/dom/KeyIndex.html#getStartNode()">getStartNode</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Get start to END should 'close' the iterator, i.e.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xalan/xsltc/dom/KeyIndex.html#gotoMark()">gotoMark</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Restores the current node remembered by setMark().</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;boolean</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xalan/xsltc/dom/KeyIndex.html#isReverse()">isReverse</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;True if this iterator has a reversed axis.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xalan/xsltc/dom/KeyIndex.html#lookupId(java.lang.Object)">lookupId</A></B>(java.lang.Object&nbsp;value)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This method must be called by the code generated by the id() function prior to returning the node iterator.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xalan/xsltc/dom/KeyIndex.html#lookupKey(java.lang.Object)">lookupKey</A></B>(java.lang.Object&nbsp;value)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This method must be called by the code generated by the key() function prior to returning the node iterator.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xalan/xsltc/dom/KeyIndex.html#merge(org.apache.xalan.xsltc.dom.KeyIndex)">merge</A></B>(<A HREF="../../../../../org/apache/xalan/xsltc/dom/KeyIndex.html">KeyIndex</A>&nbsp;other)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Merge the current value's nodeset set by lookupKey() with _nodes.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xalan/xsltc/dom/KeyIndex.html#next()">next</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Callers should not call next() after it returns END.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../org/apache/xml/dtm/DTMAxisIterator.html">DTMAxisIterator</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xalan/xsltc/dom/KeyIndex.html#reset()">reset</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Resets the iterator to the last start node.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xalan/xsltc/dom/KeyIndex.html#setDom(org.apache.xalan.xsltc.DOM)">setDom</A></B>(<A HREF="../../../../../org/apache/xalan/xsltc/DOM.html">DOM</A>&nbsp;dom)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xalan/xsltc/dom/KeyIndex.html#setMark()">setMark</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Remembers the current node for the next call to gotoMark().</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xalan/xsltc/dom/KeyIndex.html#setRestartable(boolean)">setRestartable</A></B>(boolean&nbsp;flag)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../org/apache/xml/dtm/DTMAxisIterator.html">DTMAxisIterator</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xalan/xsltc/dom/KeyIndex.html#setStartNode(int)">setStartNode</A></B>(int&nbsp;start)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Set start to END should 'close' the iterator, i.e.</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_org.apache.xml.dtm.ref.DTMAxisIteratorBase"><!-- --></A> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TD><B>Methods inherited from class org.apache.xml.dtm.ref.<A HREF="../../../../../org/apache/xml/dtm/ref/DTMAxisIteratorBase.html">DTMAxisIteratorBase</A></B></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><A HREF="../../../../../org/apache/xml/dtm/ref/DTMAxisIteratorBase.html#getAxis()">getAxis</A>, <A HREF="../../../../../org/apache/xml/dtm/ref/DTMAxisIteratorBase.html#getNodeByPosition(int)">getNodeByPosition</A>, <A HREF="../../../../../org/apache/xml/dtm/ref/DTMAxisIteratorBase.html#includeSelf()">includeSelf</A>, <A HREF="../../../../../org/apache/xml/dtm/ref/DTMAxisIteratorBase.html#isDocOrdered()">isDocOrdered</A></CODE></TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TD><B>Methods inherited from class java.lang.Object</B></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ============ FIELD DETAIL =========== --> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=1><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TD> </TR> </TABLE> <A NAME="KeyIndex(int)"><!-- --></A><H3> KeyIndex</H3> <PRE> public <B>KeyIndex</B>(int&nbsp;dummy)</PRE> <DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=1><FONT SIZE="+2"> <B>Method Detail</B></FONT></TD> </TR> </TABLE> <A NAME="setRestartable(boolean)"><!-- --></A><H3> setRestartable</H3> <PRE> public void <B>setRestartable</B>(boolean&nbsp;flag)</PRE> <DL> <DD><DL> <DT><B>Overrides:</B><DD><A HREF="../../../../../org/apache/xml/dtm/ref/DTMAxisIteratorBase.html#setRestartable(boolean)">setRestartable</A> in class <A HREF="../../../../../org/apache/xml/dtm/ref/DTMAxisIteratorBase.html">DTMAxisIteratorBase</A></DL> </DD> </DL> <HR> <A NAME="add(java.lang.Object, int)"><!-- --></A><H3> add</H3> <PRE> public void <B>add</B>(java.lang.Object&nbsp;value, int&nbsp;node)</PRE> <DL> <DD>Adds a node to the node list for a given value. Nodes will always be added in document order.</DL> <HR> <A NAME="merge(org.apache.xalan.xsltc.dom.KeyIndex)"><!-- --></A><H3> merge</H3> <PRE> public void <B>merge</B>(<A HREF="../../../../../org/apache/xalan/xsltc/dom/KeyIndex.html">KeyIndex</A>&nbsp;other)</PRE> <DL> <DD>Merge the current value's nodeset set by lookupKey() with _nodes.</DL> <HR> <A NAME="lookupId(java.lang.Object)"><!-- --></A><H3> lookupId</H3> <PRE> public void <B>lookupId</B>(java.lang.Object&nbsp;value)</PRE> <DL> <DD>This method must be called by the code generated by the id() function prior to returning the node iterator. The lookup code for key() and id() differ in the way the lookup value can be whitespace separated list of tokens for the id() function, but a single string for the key() function.</DL> <HR> <A NAME="getDOMNodeById(java.lang.String)"><!-- --></A><H3> getDOMNodeById</H3> <PRE> public <A HREF="../../../../../org/apache/xalan/xsltc/util/IntegerArray.html">IntegerArray</A> <B>getDOMNodeById</B>(java.lang.String&nbsp;id)</PRE> <DL> <DD>Return an IntegerArray for the DOM Node which has the given id.<DD><DL> <DT><B>Parameters:</B><DD><CODE>id</CODE> - The id<DT><B>Returns:</B><DD>A IntegerArray representing the Node whose id is the given value.</DL> </DD> </DL> <HR> <A NAME="lookupKey(java.lang.Object)"><!-- --></A><H3> lookupKey</H3> <PRE> public void <B>lookupKey</B>(java.lang.Object&nbsp;value)</PRE> <DL> <DD>This method must be called by the code generated by the key() function prior to returning the node iterator.</DL> <HR> <A NAME="next()"><!-- --></A><H3> next</H3> <PRE> public int <B>next</B>()</PRE> <DL> <DD>Callers should not call next() after it returns END.</DL> <HR> <A NAME="containsID(int, java.lang.Object)"><!-- --></A><H3> containsID</H3> <PRE> public int <B>containsID</B>(int&nbsp;node, java.lang.Object&nbsp;value)</PRE> <DL> </DL> <HR> <A NAME="containsKey(int, java.lang.Object)"><!-- --></A><H3> containsKey</H3> <PRE> public int <B>containsKey</B>(int&nbsp;node, java.lang.Object&nbsp;value)</PRE> <DL> </DL> <HR> <A NAME="reset()"><!-- --></A><H3> reset</H3> <PRE> public <A HREF="../../../../../org/apache/xml/dtm/DTMAxisIterator.html">DTMAxisIterator</A> <B>reset</B>()</PRE> <DL> <DD>Resets the iterator to the last start node.<DD><DL> <DT><B>Overrides:</B><DD><A HREF="../../../../../org/apache/xml/dtm/ref/DTMAxisIteratorBase.html#reset()">reset</A> in class <A HREF="../../../../../org/apache/xml/dtm/ref/DTMAxisIteratorBase.html">DTMAxisIteratorBase</A></DL> </DD> </DL> <HR> <A NAME="getLast()"><!-- --></A><H3> getLast</H3> <PRE> public int <B>getLast</B>()</PRE> <DL> <DD>Returns the number of elements in this iterator.<DD><DL> <DT><B>Overrides:</B><DD><A HREF="../../../../../org/apache/xml/dtm/ref/DTMAxisIteratorBase.html#getLast()">getLast</A> in class <A HREF="../../../../../org/apache/xml/dtm/ref/DTMAxisIteratorBase.html">DTMAxisIteratorBase</A></DL> </DD> </DL> <HR> <A NAME="getPosition()"><!-- --></A><H3> getPosition</H3> <PRE> public int <B>getPosition</B>()</PRE> <DL> <DD>Returns the position of the current node in the set.<DD><DL> <DT><B>Overrides:</B><DD><A HREF="../../../../../org/apache/xml/dtm/ref/DTMAxisIteratorBase.html#getPosition()">getPosition</A> in class <A HREF="../../../../../org/apache/xml/dtm/ref/DTMAxisIteratorBase.html">DTMAxisIteratorBase</A></DL> </DD> </DL> <HR> <A NAME="setMark()"><!-- --></A><H3> setMark</H3> <PRE> public void <B>setMark</B>()</PRE> <DL> <DD>Remembers the current node for the next call to gotoMark().</DL> <HR> <A NAME="gotoMark()"><!-- --></A><H3> gotoMark</H3> <PRE> public void <B>gotoMark</B>()</PRE> <DL> <DD>Restores the current node remembered by setMark().</DL> <HR> <A NAME="setStartNode(int)"><!-- --></A><H3> setStartNode</H3> <PRE> public <A HREF="../../../../../org/apache/xml/dtm/DTMAxisIterator.html">DTMAxisIterator</A> <B>setStartNode</B>(int&nbsp;start)</PRE> <DL> <DD>Set start to END should 'close' the iterator, i.e. subsequent call to next() should return END.</DL> <HR> <A NAME="getStartNode()"><!-- --></A><H3> getStartNode</H3> <PRE> public int <B>getStartNode</B>()</PRE> <DL> <DD>Get start to END should 'close' the iterator, i.e. subsequent call to next() should return END.<DD><DL> <DT><B>Overrides:</B><DD><A HREF="../../../../../org/apache/xml/dtm/ref/DTMAxisIteratorBase.html#getStartNode()">getStartNode</A> in class <A HREF="../../../../../org/apache/xml/dtm/ref/DTMAxisIteratorBase.html">DTMAxisIteratorBase</A></DL> </DD> </DL> <HR> <A NAME="isReverse()"><!-- --></A><H3> isReverse</H3> <PRE> public boolean <B>isReverse</B>()</PRE> <DL> <DD>True if this iterator has a reversed axis.<DD><DL> <DT><B>Overrides:</B><DD><A HREF="../../../../../org/apache/xml/dtm/ref/DTMAxisIteratorBase.html#isReverse()">isReverse</A> in class <A HREF="../../../../../org/apache/xml/dtm/ref/DTMAxisIteratorBase.html">DTMAxisIteratorBase</A></DL> </DD> </DL> <HR> <A NAME="cloneIterator()"><!-- --></A><H3> cloneIterator</H3> <PRE> public <A HREF="../../../../../org/apache/xml/dtm/DTMAxisIterator.html">DTMAxisIterator</A> <B>cloneIterator</B>()</PRE> <DL> <DD>Returns a deep copy of this iterator.<DD><DL> <DT><B>Overrides:</B><DD><A HREF="../../../../../org/apache/xml/dtm/ref/DTMAxisIteratorBase.html#cloneIterator()">cloneIterator</A> in class <A HREF="../../../../../org/apache/xml/dtm/ref/DTMAxisIteratorBase.html">DTMAxisIteratorBase</A></DL> </DD> </DL> <HR> <A NAME="setDom(org.apache.xalan.xsltc.DOM)"><!-- --></A><H3> setDom</H3> <PRE> public void <B>setDom</B>(<A HREF="../../../../../org/apache/xalan/xsltc/DOM.html">DOM</A>&nbsp;dom)</PRE> <DL> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ========== START OF NAVBAR ========== --> <A NAME="navbar_bottom"><!-- --></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0"> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3"> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/KeyIndex.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../org/apache/xalan/xsltc/dom/ForwardPositionIterator.html"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../org/apache/xalan/xsltc/dom/LoadDocument.html"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html" TARGET="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="KeyIndex.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY: &nbsp;INNER&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL: &nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <!-- =========== END OF NAVBAR =========== --> <HR> Copyright © 2005 Apache XML Project. All Rights Reserved. </BODY> </HTML>
MrStaticVoid/iriverter
lib/xalan-j_2_7_0/docs/apidocs/org/apache/xalan/xsltc/dom/KeyIndex.html
HTML
gpl-2.0
23,523
import processing.core.*; import processing.data.*; import processing.event.*; import processing.opengl.*; import java.util.Map; import java.util.Iterator; import SimpleOpenNI.*; import java.util.Random; import java.net.*; import java.util.Arrays; import java.util.HashMap; import java.util.ArrayList; import java.io.File; import java.io.BufferedReader; import java.io.PrintWriter; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; public class masterB extends PApplet { SimpleOpenNI context; OPC opc; float dx, dy; int test = 0; int numSketches = 4; int numPixels = 60; //per ring float angleOfFirst = PI; //For Spinning Pixels int[] spinHue; int backgroundBright = 0; int backgroundSat = 0; int backgroundSpinHue = 0; int numSpinners = 30; int spinCounter = 0; int spinSat = 100; int shapeCounter[]; int randomPixel[]; int speed = 1; int numInThreshold1 = 0; int numInThreshold2 = 0; int numInThreshold3 = 0; PVector[] spinCircle = new PVector[numSpinners]; shapeClass[][] spinningDots; PVector[] spinDot = new PVector[numSpinners]; // //For fading circles boolean personOnLeft = false; boolean personOnRight = false; boolean leftChanged = false; boolean rightChanged = false; int numFaders = 30; shapeClass[][] fadingDots; PVector[] fadeCircle = new PVector[numFaders]; PVector[] fadeDot = new PVector[numFaders]; int[] fadeHue = new int[numFaders]; int[] fadeSat = new int[numFaders]; int[] faderBrightnesses = new int[numFaders]; boolean[] increaseBrightnesses = new boolean[numFaders]; int initIncBright = 0; int[] oldHue = new int[numFaders]; int faderBrightness = 1; boolean increaseBrightness = true; // //For depthThreshold PImage display; PImage flipped; int depthHue = 0; int depthSat = 100; int depthBri = 100; int backgroundHue = 50;// int hue = 0; int brightness = 0; boolean backwards = false; int numShapes = 1; int counter = 0; boolean firstPass = true; Random randomGenerator = new Random(); char direction; PVector circle = new PVector(); PVector circle2 = new PVector(); shapeClass[] dots; shapeClass[] dots2; shapeClass[][][] dotsArray = new shapeClass[8][8][numPixels]; int pixelCounter = 0; PVector dot = new PVector(); PVector dot2 = new PVector(); float radius; PVector blank; public void setup() { context = new SimpleOpenNI(0, this); context.enableDepth(); blank = new PVector(); blank.x = 0; blank.y = 0; //Use height for width and height to draw square window size(240, 240); // Connect to the local instance of fcserver opc = new OPC(this, "127.0.0.1", 7891); // Map an 8x8 grid of rings of LEDs to the center of the window int numPixelsPerRing = numPixels; opc.ledRingGrid(width, height, numPixelsPerRing); colorMode(HSB, 100); background(0, 0, 0); ///Fading initialization fadingDots = new shapeClass[numFaders][numPixels]; for (int i=0; i<numFaders; i++) { fadeCircle[i] = new PVector(); fadeCircle[i].x = width/16 + (width/8 * (int)random(8)); fadeCircle[i].y = height/16 + (height/8 * (int)random(8)); fadeDot[i] = new PVector(); fadeHue[i] = (int)random(100); oldHue[i] = fadeHue[i]; fadeSat[i] = 100; faderBrightnesses[i] = (int)random(100); initIncBright = (int)random(1); if (initIncBright == 1) increaseBrightnesses[i] = true; else increaseBrightnesses[i] = false; for (int j=0; j<numPixels; j++) fadingDots[i][j] = new shapeClass(color(0, 0, 0), blank); } /// ////Spinner initialization spinHue = new int[numSpinners]; shapeCounter = new int[numSpinners]; randomPixel = new int[numSpinners]; spinningDots = new shapeClass[numSpinners][numPixels]; for (int i=0; i<numSpinners; i++) { spinCircle[i] = new PVector(); spinCircle[i].x = width/16 + (width/8 * (int)random(8)); spinCircle[i].y = height/16 + (height/8 * (int)random(8)); spinDot[i] = new PVector(); randomPixel[i] = (int)random(numPixels); spinHue[i] = (int)random(100); for (int j=0; j<numPixels; j++) { spinningDots[i][j] = new shapeClass(color(0, 0, 0), blank); } } //// opc.setStatusLed(false); radius = ((width + height) / 2) / 20; } float noiseScale=0.02f; public float fractalNoise(float x, float y, float z) { float r = 0; float amp = 1.0f; for (int octave = 0; octave < 4; octave++) { r += noise(x, y, z) * amp; amp /= 2; x *= 2; y *= 2; z *= 2; } return r; } public void draw() { if (hour() >= 5 && hour() < 23) { //Fading Circles if (minute() % 15 >= 10) // if(test == 1) { background(0, 0, 0); context.update(); for (int x = 0; x < context.depthWidth (); x++) { for (int y = 0; y < context.depthHeight (); y++) { // mirroring image int offset = x + y * context.depthWidth(); int[] depthValues = context.depthMap(); int rawDepth = depthValues[offset]; //only get the pixel corresponding to a certain depth int depthmin=0; int depthmax=3000; if (rawDepth < depthmax && rawDepth > depthmin) { if ((x % 640) < 320) personOnLeft = true; if ((x % 640) > 320) personOnRight = true; } } } for (int i=0; i<numFaders; i++) { if (faderBrightnesses[i] >= 100) increaseBrightnesses[i] = false; else if (faderBrightnesses[i] <= 0) increaseBrightnesses[i] = true; if (increaseBrightnesses[i] == true) faderBrightnesses[i]+=5; else if (increaseBrightnesses[i] == false) faderBrightnesses[i]-=5; } for (int i=0; i<numFaders; i++) { for (int j=0; j<numPixels; j++) { float a = angleOfFirst + j * 2 * PI / numPixels; fadeDot[i].x = (int)(fadeCircle[i].x - radius * cos(a) + 0.5f); fadeDot[i].y = (int)(fadeCircle[i].y - radius * sin(a) + 0.5f); if (personOnLeft == true) { if (fadeCircle[i].x < width/2) { fadeHue[i] = (int)random(100); leftChanged = true; } } if (personOnLeft == false && leftChanged == true) { fadeHue[i] = oldHue[i]; if (i == numFaders) leftChanged = false; } if (personOnRight == true) { if (fadeCircle[i].x > width/2) { fadeHue[i] = (int)random(100); rightChanged = true; } } if (personOnRight == false && rightChanged == true && leftChanged == false) { fadeHue[i] = oldHue[i]; if (i == numFaders) rightChanged = false; } fadingDots[i][j] = new shapeClass(color(fadeHue[i], fadeSat[i], faderBrightnesses[i]), fadeDot[i]); fadingDots[i][j].display(); } } for (int i=0; i<numFaders; i++) { if (faderBrightnesses[i] == 0) { fadeCircle[i].x = width/16 + (width/8 * (int)random(8)); fadeCircle[i].y = height/16 + (height/8 * (int)random(8)); fadeHue[i] = (int)random(100); oldHue[i] = fadeHue[i]; fadeSat[i] = 100; for (int k=0; k<numFaders; k++) { if (k != i) { while ( (fadeCircle[i].x == fadeCircle[k].x) && (fadeCircle[i].y == fadeCircle[k].y)) { fadeCircle[i].x = width/16 + (width/8 * (int)random(8)); fadeCircle[i].y = height/16 + (height/8 * (int)random(8)); } } } } } personOnLeft = false; personOnRight = false; } //Clouds if (minute() % 15 <= 5) { // if(test == 1) { long now = millis(); float speed = 0.002f; float angle = sin(now * 0.001f); float z = now * 0.00008f; float hue = now * 0.01f; float scale = 0.005f; int brightnessScale = 100; context.update(); for (int x = 0; x < context.depthHeight (); x++) { for (int y = 0; y < context.depthHeight (); y++) { // mirroring image int offset = context.depthWidth()-x-1+y*context.depthWidth(); int[] depthValues = context.depthMap(); int rawDepth = depthValues[offset]; int pix = x + y * context.depthWidth(); //only get the pixel corresponding to a certain depth int depthmin1 = 0; int depthmax1 = 2000; if (rawDepth < depthmax1 && rawDepth > depthmin1) speed = 0.005f; int depthmin2=2000; int depthmax2=3000; if (rawDepth < depthmax2 && rawDepth > depthmin2) speed = 0.004f; int depthmin3 = 3000; int depthmax3 = 3500; if (rawDepth < depthmax3 && rawDepth > depthmin3) speed = 0.003f; } } dx += cos(angle) * speed; dy += sin(angle) * speed; loadPixels(); for (int x=0; x < width; x++) { for (int y=0; y < height; y++) { float n = fractalNoise(dx + x*scale, dy + y*scale, z) - 0.75f; float m = fractalNoise(dx + x*scale, dy + y*scale, z + 10.0f) - 0.75f; int c = color( (hue + 80.0f * m) % 100.0f, 100 - 100 * constrain(pow(3.0f * n, 3.5f), 0, 0.9f), brightnessScale * constrain(pow(3.0f * n, 1.5f), 0, 0.9f) ); pixels[x + width*y] = c; } } updatePixels(); } //Xtion Depth Threshold if ((minute() % 15) >= 5 && (minute() % 15) < 10) // if(test == 0) { context.update(); display = context.depthImage(); display.loadPixels(); flipped = createImage(display.width, display.height, HSB); flipped.loadPixels(); //loop to select a depthzone for (int x = 0; x < context.depthWidth (); x++) { for (int y = 0; y < context.depthHeight (); y++) { // mirroring image int offset = context.depthWidth()-x-1+y*context.depthWidth(); int[] depthValues = context.depthMap(); int rawDepth = depthValues[offset]; int pix = x + y * context.depthWidth(); //only get the pixel corresponding to a certain depth int depthmin=0; int depthmax=3530; if (rawDepth < depthmax && rawDepth > depthmin) { display.pixels[pix] = color(depthHue, depthSat, depthBri); /* hue+=10; bri+=1; if(hue>=100) { hue=0; } if(bri>=100) bri=50; */ } else display.pixels[pix] = color(backgroundHue, 50, 50); } } for(int x = 0; x < context.depthWidth(); x++) { for(int y = 0; y < context.depthHeight(); y++) { int pix = x + y * context.depthWidth(); int pixInv = (context.depthWidth() - x - 1) + (context.depthHeight() - y - 1) * context.depthWidth(); flipped.pixels[pixInv] = display.pixels[pix]; } } image(flipped, 0, 0, width*1.333333333f, height); depthHue++; if (depthHue==100) depthHue=0; backgroundHue++; if (backgroundHue==100) backgroundHue=0; } /* //Spinning Dots if ((minute() % 20 >= 15) && (minute() % 20 < 20)) if(test == 0) { background(backgroundSpinHue, backgroundSat, backgroundBright); context.update(); display = context.depthImage(); display.loadPixels(); for (int x = 0; x < context.depthHeight (); x++) { for (int y = 0; y < context.depthHeight (); y++) { // mirroring image int offset = context.depthWidth()-x-1+y*context.depthWidth(); int[] depthValues = context.depthMap(); int rawDepth = depthValues[offset]; int pix = x + y * context.depthWidth(); //only get the pixel corresponding to a certain depth int depthmin2=2000; int depthmax2=3000; if (rawDepth < depthmax2 && rawDepth > depthmin2) { // display.pixels[pix] = color(depthHue%100, depthSat, depthBri); numInThreshold2++; } else display.pixels[pix] = color(0); int depthmin1 = 0; int depthmax1 = 2000; if (rawDepth < depthmax1 && rawDepth > depthmin1) numInThreshold1++; int depthmin3 = 3000; int depthmax3 = 3500; if (rawDepth < depthmax3 && rawDepth > depthmin3) numInThreshold3++; } } // display.updatePixels(); // image(display, 0, 0, width*1.333333, height); depthHue++; if (numInThreshold1 < 10000 && numInThreshold2 < 10000 && numInThreshold3 < 35000) speed=1; if (numInThreshold3 > 35000 && numInThreshold3 > numInThreshold2 && numInThreshold3 > numInThreshold1) speed=2; if (numInThreshold2 > 10000 && numInThreshold2 > numInThreshold1 && numInThreshold2 > numInThreshold3) speed=3; if (numInThreshold1 > 10000 && numInThreshold1 > numInThreshold2 && numInThreshold1 > numInThreshold2) speed=4; //assign idividual dot positions from circle center point position for (int i=0; i<numSpinners; i++) { shapeCounter[i]++; float a = angleOfFirst + ((spinCounter + randomPixel[i]) % numPixels) * 2 * PI / numPixels * speed; spinDot[i].x = (int)(spinCircle[i].x - radius * cos(a) + 0.5); spinDot[i].y = (int)(spinCircle[i].y - radius * sin(a) + 0.5); } //create the dots from positions for (int i=0; i<numSpinners; i++) spinningDots[i][spinCounter%numPixels] = new shapeClass(color(spinHue[i], spinSat, 100), spinDot[i]); //display all dots for (int i=0; i<numSpinners; i++) { for (int j=0; j<numPixels; j++) spinningDots[i][j].display(); } if (spinCounter%5==0) { for (int i=0; i<numSpinners; i++) { spinHue[i]++; if (spinHue[i] == 100) spinHue[i] = 0; } } spinCounter++; if (spinCounter == numPixels*4) spinCounter = 0; for (int i=0; i<numSpinners; i++) { if (shapeCounter[i]%5 == (int)random(5) && spinCounter%numPixels == 0) { spinCircle[i].x = width/16 + (width/8 * (int)random(8)); spinCircle[i].y = height/16 + (height/8 * (int)random(8)); randomPixel[i] = (int)random(numPixels); //check to make sure dots aren't on top of each other for (int k=0; k<numSpinners; k++) { if (k != i) { while ( (spinCircle[i].x == spinCircle[k].x) && (spinCircle[i].y == spinCircle[k].y)) { spinCircle[i].x = width/16 + (width/8 * (int)random(8)); spinCircle[i].y = height/16 + (height/8 * (int)random(8)); } } } for (int j=0; j<numPixels; j++) { float a = angleOfFirst + j * 2 * PI / numPixels; spinDot[i].x = (int)(spinCircle[i].x - radius * cos(a) + 0.5); spinDot[i].y = (int)(spinCircle[i].y - radius * sin(a) + 0.5); } } } numInThreshold1 = 0; numInThreshold2 = 0; numInThreshold3 = 0; } */ } else background(0, 0, 0); } class shapeClass { int colour; PVector pos; shapeClass(int colour, PVector pos) { this.colour = colour; this.pos = pos; } public void display() { smooth(); fill(colour); strokeWeight(0); ellipseMode(CENTER); // ellipse(pos.x - 40, pos.y - 40, 50, 50); // println("shape.x: " + pos.x); // println("shape.y: " + pos.y); ellipse(pos.x, pos.y, 3, 3); } } /* * Simple Open Pixel Control client for Processing, * designed to sample each LED's color from some point on the canvas. * * Micah Elizabeth Scott, 2013 * This file is released into the public domain. */ public class OPC { Socket socket; OutputStream output; String host; int port; int[] pixelLocations; byte[] packetData; byte firmwareConfig; String colorCorrection; boolean enableShowLocations; OPC(PApplet parent, String host, int port) { this.host = host; this.port = port; this.enableShowLocations = true; parent.registerDraw(this); } // Set the location of a single LED public void led(int index, int x, int y) { // For convenience, automatically grow the pixelLocations array. We do want this to be an array, // instead of a HashMap, to keep draw() as fast as it can be. if (pixelLocations == null) { pixelLocations = new int[index + 1]; } else if (index >= pixelLocations.length) { pixelLocations = Arrays.copyOf(pixelLocations, index + 1); } pixelLocations[index] = x + width * y; } // Set the locations of a ring of LEDs. The center of the ring is at (x, y), // with "radius" pixels between the center and each LED. The first LED is at // the indicated angle, in radians, measured clockwise from +X. public void ledRing(int index, int count, float x, float y, float radius, float angle, boolean inverted) { float pi = PI; if(inverted == true) pi *= -1; for (int i = 0; i < count; i++) { float a = angle + i * 2 * pi / count; led(index + i, (int)(x - radius * cos(a) + 0.5f), (int)(y - radius * sin(a) + 0.5f)); } } //Draws an 8x8 grid of pixel rings. //Grid is drawn column by column, starting at the bottom left, //and is relative to screen size. public void ledRingGrid(int screenWidth, int screenHeight, int numPixels) { int xPosition = screenWidth / 16; int index = 0; float radius = ((screenWidth + screenHeight) / 2) / 20; float angleOfFirstPixel = PI; boolean inverted = false; if(numPixels == 16) inverted = true; for(int x = 0; x < 8; x++) { int yPosition = screenHeight - (screenHeight / 16); for(int y = 0; y < 8; y++) { ledRing(index, numPixels, xPosition, yPosition, radius, angleOfFirstPixel, inverted); yPosition -= screenHeight / 8; index += numPixels; } xPosition += screenHeight / 8; } } // Should the pixel sampling locations be visible? This helps with debugging. // Showing locations is enabled by default. You might need to disable it if our drawing // is interfering with your processing sketch, or if you'd simply like the screen to be // less cluttered. public void showLocations(boolean enabled) { enableShowLocations = enabled; } // Enable or disable dithering. Dithering avoids the "stair-stepping" artifact and increases color // resolution by quickly jittering between adjacent 8-bit brightness levels about 400 times a second. // Dithering is on by default. public void setDithering(boolean enabled) { if (enabled) firmwareConfig &= ~0x01; else firmwareConfig |= 0x01; sendFirmwareConfigPacket(); } // Enable or disable frame interpolation. Interpolation automatically blends between consecutive frames // in hardware, and it does so with 16-bit per channel resolution. Combined with dithering, this helps make // fades very smooth. Interpolation is on by default. public void setInterpolation(boolean enabled) { if (enabled) firmwareConfig &= ~0x02; else firmwareConfig |= 0x02; sendFirmwareConfigPacket(); } // Put the Fadecandy onboard LED under automatic control. It blinks any time the firmware processes a packet. // This is the default configuration for the LED. public void statusLedAuto() { firmwareConfig &= 0x0C; sendFirmwareConfigPacket(); } // Manually turn the Fadecandy onboard LED on or off. This disables automatic LED control. public void setStatusLed(boolean on) { firmwareConfig |= 0x04; // Manual LED control if (on) firmwareConfig |= 0x08; else firmwareConfig &= ~0x08; sendFirmwareConfigPacket(); } // Set the color correction parameters public void setColorCorrection(float gamma, float red, float green, float blue) { colorCorrection = "{ \"gamma\": " + gamma + ", \"whitepoint\": [" + red + "," + green + "," + blue + "]}"; sendColorCorrectionPacket(); } // Set custom color correction parameters from a string public void setColorCorrection(String s) { colorCorrection = s; sendColorCorrectionPacket(); } // Send a packet with the current firmware configuration settings public void sendFirmwareConfigPacket() { if (output == null) { // We'll do this when we reconnect return; } byte[] packet = new byte[9]; packet[0] = 0; // Channel (reserved) packet[1] = (byte)0xFF; // Command (System Exclusive) packet[2] = 0; // Length high byte packet[3] = 5; // Length low byte packet[4] = 0x00; // System ID high byte packet[5] = 0x01; // System ID low byte packet[6] = 0x00; // Command ID high byte packet[7] = 0x02; // Command ID low byte packet[8] = firmwareConfig; try { output.write(packet); } catch (Exception e) { dispose(); } } // Send a packet with the current color correction settings public void sendColorCorrectionPacket() { if (colorCorrection == null) { // No color correction defined return; } if (output == null) { // We'll do this when we reconnect return; } byte[] content = colorCorrection.getBytes(); int packetLen = content.length + 4; byte[] header = new byte[8]; header[0] = 0; // Channel (reserved) header[1] = (byte)0xFF; // Command (System Exclusive) header[2] = (byte)(packetLen >> 8); header[3] = (byte)(packetLen & 0xFF); header[4] = 0x00; // System ID high byte header[5] = 0x01; // System ID low byte header[6] = 0x00; // Command ID high byte header[7] = 0x01; // Command ID low byte try { output.write(header); output.write(content); } catch (Exception e) { dispose(); } } // Automatically called at the end of each draw(). // This handles the automatic Pixel to LED mapping. // If you aren't using that mapping, this function has no effect. // In that case, you can call setPixelCount(), setPixel(), and writePixels() // separately. public void draw() { if (pixelLocations == null) { // No pixels defined yet return; } if (output == null) { // Try to (re)connect connect(); } if (output == null) { return; } int numPixels = pixelLocations.length; int ledAddress = 4; setPixelCount(numPixels); loadPixels(); for (int i = 0; i < numPixels; i++) { int pixelLocation = pixelLocations[i]; int pixel = pixels[pixelLocation]; packetData[ledAddress] = (byte)(pixel >> 16); packetData[ledAddress + 1] = (byte)(pixel >> 8); packetData[ledAddress + 2] = (byte)pixel; ledAddress += 3; if (enableShowLocations) { pixels[pixelLocation] = 0xFFFFFF ^ pixel; } } writePixels(); if (enableShowLocations) { updatePixels(); } } // Change the number of pixels in our output packet. // This is normally not needed; the output packet is automatically sized // by draw() and by setPixel(). public void setPixelCount(int numPixels) { int numBytes = 3 * numPixels; int packetLen = 4 + numBytes; if (packetData == null || packetData.length != packetLen) { // Set up our packet buffer packetData = new byte[packetLen]; packetData[0] = 0; // Channel packetData[1] = 0; // Command (Set pixel colors) packetData[2] = (byte)(numBytes >> 8); packetData[3] = (byte)(numBytes & 0xFF); } } // Directly manipulate a pixel in the output buffer. This isn't needed // for pixels that are mapped to the screen. public void setPixel(int number, int c) { int offset = 4 + number * 3; if (packetData == null || packetData.length < offset + 3) { setPixelCount(number + 1); } packetData[offset] = (byte) (c >> 16); packetData[offset + 1] = (byte) (c >> 8); packetData[offset + 2] = (byte) c; } // Read a pixel from the output buffer. If the pixel was mapped to the display, // this returns the value we captured on the previous frame. public int getPixel(int number) { int offset = 4 + number * 3; if (packetData == null || packetData.length < offset + 3) { return 0; } return (packetData[offset] << 16) | (packetData[offset + 1] << 8) | packetData[offset + 2]; } // Transmit our current buffer of pixel values to the OPC server. This is handled // automatically in draw() if any pixels are mapped to the screen, but if you haven't // mapped any pixels to the screen you'll want to call this directly. public void writePixels() { if (packetData == null || packetData.length == 0) { // No pixel buffer return; } if (output == null) { // Try to (re)connect connect(); } if (output == null) { return; } try { output.write(packetData); } catch (Exception e) { dispose(); } } public void dispose() { // Destroy the socket. Called internally when we've disconnected. if (output != null) { println("Disconnected from OPC server"); } socket = null; output = null; } public void connect() { // Try to connect to the OPC server. This normally happens automatically in draw() try { socket = new Socket(host, port); socket.setTcpNoDelay(true); output = socket.getOutputStream(); println("Connected to OPC server"); } catch (ConnectException e) { dispose(); } catch (IOException e) { dispose(); } sendColorCorrectionPacket(); sendFirmwareConfigPacket(); } } static public void main(String[] passedArgs) { String[] appletArgs = new String[] { "masterB" }; if (passedArgs != null) { PApplet.main(concat(appletArgs, passedArgs)); } else { PApplet.main(appletArgs); } } }
Signal-to-Noise-Media-Labs/open_windows
sketches/masterB/application.linux64/source/masterB.java
Java
gpl-2.0
26,791
<!DOCTYPE html> <!--[if IE 8]><html class="no-js lt-ie9" lang="zh" > <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="zh" > <!--<![endif]--> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>教程: 优化硬件利用率 &mdash; zzq&#39;s blog</title> <script type="text/javascript" src="../../_static/js/modernizr.min.js"></script> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT:'../../', VERSION:'2019.04.16', LANGUAGE:'zh', COLLAPSE_INDEX:false, FILE_SUFFIX:'.html', HAS_SOURCE: true, SOURCELINK_SUFFIX: '.txt' }; </script> <script type="text/javascript" src="../../_static/jquery.js"></script> <script type="text/javascript" src="../../_static/underscore.js"></script> <script type="text/javascript" src="../../_static/doctools.js"></script> <script type="text/javascript" src="../../_static/js/theme.js"></script> <link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" /> <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="../../_static/hacks.css" type="text/css" /> <link rel="index" title="索引" href="../../genindex.html" /> <link rel="search" title="搜索" href="../../search.html" /> <link rel="next" title="教程: 优化伪共享" href="tutorial_false_sharing.html" /> <link rel="prev" title="教程: 优化热点" href="tutorial_hotspots.html" /> </head> <body class="wy-body-for-nav"> <div class="wy-grid-for-nav"> <nav data-toggle="wy-nav-shift" class="wy-nav-side"> <div class="wy-side-scroll"> <div class="wy-side-nav-search" > <a href="../../index.html" class="icon icon-home"> 赵子清技术文章 </a> <div class="version"> 2019.04 </div> <div role="search"> <form id="rtd-search-form" class="wy-form" action="../../search.html" method="get"> <input type="text" name="q" placeholder="Search docs" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation"> <ul class="current"> <li class="toctree-l1"><a class="reference internal" href="../../design/index.html">表达与设计</a><ul> <li class="toctree-l2"><a class="reference internal" href="../../design/rest/index.html">用reST编写文档</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../design/rest/intro.html">1. 简介</a></li> <li class="toctree-l3"><a class="reference internal" href="../../design/rest/setup.html">2. 安装与基本使用</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/setup.html#id2">2.1. 安装软件包</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/setup.html#id3">2.2. 项目建立</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/setup.html#conf-py">2.3. conf.py配置</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/setup.html#index">2.4. index页配置</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/setup.html#id6">2.5. 参考</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../design/rest/grammar.html">3. reST语法介绍</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/grammar.html#id1">3.1. 章节标题</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/grammar.html#id2">3.2. 段落</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/grammar.html#id3">3.3. 行内标记</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/grammar.html#id4">3.4. 列表</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/grammar.html#id5">3.5. 代码</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/grammar.html#id6">3.6. 超链接</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/grammar.html#id7">3.7. 图片</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/grammar.html#id8">3.8. 表格</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/grammar.html#id9">3.9. 引用</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/grammar.html#id10">3.10. 脚注</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/grammar.html#id11">3.11. 提醒</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/grammar.html#id12">3.12. 替换</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/grammar.html#id13">3.13. 参考</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../design/rest/style.html">4. 修改样式</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/style.html#step1">4.1. Step1</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/style.html#step2">4.2. Step2</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/style.html#step3">4.3. Step3</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../design/rest/topdf.html">5. 生成PDF</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/topdf.html#xetex">5.1. 方法一:使用xeTex(推荐)</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/topdf.html#cjkutf8">5.2. 方法二: 使用CJKutf8包 (默认)</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/topdf.html#id1">5.3. 终极解决办法</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../design/rest/doxygen.html">6. 生成API文档</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/doxygen.html#step1">6.1. Step1</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/doxygen.html#step2">6.2. Step2</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/doxygen.html#step3">6.3. Step3</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/doxygen.html#step4">6.4. Step4</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../design/rest/with_vscode.html">7. 在Visual Studio Code中使用</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/with_vscode.html#id1">7.1. 安装步骤</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/with_vscode.html#id2">7.2. 配置</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/with_vscode.html#id3">7.3. 使用</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/with_vscode.html#id4">7.4. 问题记录</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../design/rest/add_comment.html">8. 给github博客添加评论功能</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/add_comment.html#oauth-application">8.1. 1. 注册OAuth Application</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/add_comment.html#id1">8.2. 2. 编辑博客页面, 引入gitment</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/add_comment.html#id2">8.3. 3. 初始化评论</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/rest/add_comment.html#id3">8.4. 参考链接</a></li> </ul> </li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../design/latex/index.html">LaTeX</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../design/latex/setup.html">安装与配置</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../design/latex/setup.html#id2">1. 安装</a></li> <li class="toctree-l4"><a class="reference internal" href="../../design/latex/setup.html#id3">2. 卸载</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../design/latex/quick_start.html">快速入门示例</a></li> <li class="toctree-l3"><a class="reference internal" href="../../design/latex/text.html">文本与段落</a></li> <li class="toctree-l3"><a class="reference internal" href="../../design/latex/code.html">程序代码</a></li> <li class="toctree-l3"><a class="reference internal" href="../../design/latex/figure_table.html">图像与表格</a></li> <li class="toctree-l3"><a class="reference internal" href="../../design/latex/debug.html">错误调试</a></li> <li class="toctree-l3"><a class="reference internal" href="../../design/latex/links.html">参考链接</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../design/reduce-word-doc-size.html">减少Word文件大小</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../design/reduce-word-doc-size.html#id1">分析</a></li> <li class="toctree-l3"><a class="reference internal" href="../../design/reduce-word-doc-size.html#id2">减小图片大小</a></li> <li class="toctree-l3"><a class="reference internal" href="../../design/reduce-word-doc-size.html#id3">参考</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../design/links.html">参考链接</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../../lang/index.html">开发语言</a><ul> <li class="toctree-l2"><a class="reference internal" href="../../lang/cpp/index.html">C++ 11</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../lang/cpp/preface.html">前言</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../lang/cpp/preface.html#c">C++的变化</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/cpp/preface.html#id2">对C++程序员的建议</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/cpp/preface.html#id3">对C程序员的建议</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/cpp/preface.html#c-11">C++11主要特性</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/cpp/preface.html#id4">参考</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../lang/cpp/basic.html">基本功能</a></li> <li class="toctree-l3"><a class="reference internal" href="../../lang/cpp/oop.html">面向对象</a></li> <li class="toctree-l3"><a class="reference internal" href="../../lang/cpp/stl.html">标准库</a></li> <li class="toctree-l3"><a class="reference internal" href="../../lang/cpp/boost.html">boost库</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../lang/go/index.html">Go</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../lang/go/setup.html">环境配置</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../lang/go/setup.html#go-get">使用代理以解决go get超时问题</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/go/setup.html#id2">日常项目开发环境配置</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/go/setup.html#ide">IDE配置</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../lang/go/json.html">JSON解析</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../lang/go/json.html#id1">简单解析</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/go/json.html#id2">不确定JSON的解析</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/go/json.html#id3">复杂内容的解析</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../lang/go/withc.html">C语言适配</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../lang/go/withc.html#id1">调用C编写的动态库</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../lang/go/books.html">学习资料</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../lang/lua/lua_basic.html">lua基础</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../lang/lua/lua_basic.html#id1">预备知识</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../lang/lua/lua_basic.html#id2">获得lua</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/lua/lua_basic.html#id3">lua命令行</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/lua/lua_basic.html#id4">保留关键字</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/lua/lua_basic.html#id5">注释</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/lua/lua_basic.html#chunk">Chunk</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../lang/lua/lua_basic.html#id6">数据类型</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../lang/lua/lua_basic.html#string">string</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/lua/lua_basic.html#userdata">userdata</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/lua/lua_basic.html#thread">thread</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../lang/lua/lua_basic.html#id7">表达式</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../lang/lua/lua_basic.html#id8">算术运算符</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/lua/lua_basic.html#id9">关系运算符</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/lua/lua_basic.html#id10">逻辑运算符</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/lua/lua_basic.html#id11">连接运算符</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/lua/lua_basic.html#id12">运算符优先级</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../lang/lua/lua_basic.html#id13">语句</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../lang/lua/lua_basic.html#id14">赋值</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/lua/lua_basic.html#id15">局部变量</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/lua/lua_basic.html#id16">条件语句</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/lua/lua_basic.html#id17">循环语句</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../lang/lua/lua_basic.html#id18">函数</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../lang/shell/index.html">Linux shell编程</a><ul class="simple"> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../lang/asm/index.html">汇编语言</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../lang/asm/arch.html">计算机体系结构</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../lang/asm/arch.html#cpu">CPU</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/asm/arch.html#id5">内存</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/asm/arch.html#id6">中断</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../lang/asm/asm_intro.html">汇编语言简介</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../lang/asm/asm_intro.html#id2">汇编代码的两种记法</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/asm/asm_intro.html#centosnasm">CentOS运行nasm</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/asm/asm_intro.html#id3">操作数</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/asm/asm_intro.html#id4">基本指令</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/asm/asm_intro.html#id5">指示符</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/asm/asm_intro.html#id6">输入输出</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/asm/asm_intro.html#id7">代码模板</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/asm/asm_intro.html#id8">第一个程序</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../lang/asm/basic.html">语言基础</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../lang/asm/basic.html#id2">数据移动</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/asm/basic.html#id3">算术运算</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/asm/basic.html#id4">位操作</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/asm/basic.html#id7">控制流</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/asm/basic.html#id8">栈操作与函数调用</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../lang/asm/simd.html">intel SIMD指令</a></li> <li class="toctree-l3"><a class="reference internal" href="../../lang/asm/debug.html">调试</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../lang/asm/debug.html#linux-gdb">Linux + gdb</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../lang/asm/withc.html">与C语言互操作</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../lang/asm/withc.html#id1">调用约定</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/asm/withc.html#id2">C调用汇编代码</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/asm/withc.html#id3">汇编调用C代码</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/asm/withc.html#id4">结构体</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../lang/asm/links.html">参考链接</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../lang/build/index.html">编译与构建</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../lang/build/links.html">参考链接</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../lang/toml.html">TOML配置文件语言</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../lang/toml.html#id1">示例</a></li> <li class="toctree-l3"><a class="reference internal" href="../../lang/toml.html#id2">语法</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../lang/toml.html#id3">整体约定</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/toml.html#id4">注释</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/toml.html#id5">字符串</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/toml.html#id6">整数</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/toml.html#id7">浮点数</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/toml.html#id8">布尔值</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/toml.html#id9">时间日期</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/toml.html#id10">数组</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/toml.html#id11">表</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/toml.html#id12">内联表</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/toml.html#id13">表数组</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../lang/toml.html#id14">为什么我要用它呢?</a></li> <li class="toctree-l3"><a class="reference internal" href="../../lang/toml.html#id15">目前的实现</a></li> <li class="toctree-l3"><a class="reference internal" href="../../lang/toml.html#libtoml">libtoml试用</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../lang/toml.html#id16">编译</a></li> <li class="toctree-l4"><a class="reference internal" href="../../lang/toml.html#id17">简单示例</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../lang/toml.html#id18">参考</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../lang/byteorder.html">字节序与比特序</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../lang/byteorder.html#id2">字节序</a></li> <li class="toctree-l3"><a class="reference internal" href="../../lang/byteorder.html#id3">比特序</a></li> <li class="toctree-l3"><a class="reference internal" href="../../lang/byteorder.html#id4">编写可移植代码</a></li> </ul> </li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../../algo/index.html">数据结构与算法</a><ul> <li class="toctree-l2"><a class="reference internal" href="../../algo/list.html">链表,栈与队列</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../algo/list.html#id2">单向链表</a></li> <li class="toctree-l3"><a class="reference internal" href="../../algo/list.html#id3">双向链表</a></li> <li class="toctree-l3"><a class="reference internal" href="../../algo/list.html#id4">侵入式数据结构</a></li> <li class="toctree-l3"><a class="reference internal" href="../../algo/list.html#id5">栈</a></li> <li class="toctree-l3"><a class="reference internal" href="../../algo/list.html#id6">队列</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../algo/list.html#id7">基本实现</a></li> <li class="toctree-l4"><a class="reference internal" href="../../algo/list.html#id8">下标的处理</a></li> <li class="toctree-l4"><a class="reference internal" href="../../algo/list.html#id9">无锁队列</a></li> </ul> </li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../algo/tree.html">树</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../algo/tree.html#id2">二叉查找树</a></li> <li class="toctree-l3"><a class="reference internal" href="../../algo/tree.html#avl">AVL树</a></li> <li class="toctree-l3"><a class="reference internal" href="../../algo/tree.html#id3">红黑树</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../algo/hash.html">哈希表</a></li> <li class="toctree-l2"><a class="reference internal" href="../../algo/graph.html">图</a></li> <li class="toctree-l2"><a class="reference internal" href="../../algo/visit.html">遍历</a></li> <li class="toctree-l2"><a class="reference internal" href="../../algo/order.html">排序</a></li> <li class="toctree-l2"><a class="reference internal" href="../../algo/find.html">查找</a></li> <li class="toctree-l2"><a class="reference internal" href="../../algo/ac.html">AC算法</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../../sys/index.html">系统与库</a><ul> <li class="toctree-l2"><a class="reference internal" href="../../sys/linux/index.html">Linux</a></li> <li class="toctree-l2"><a class="reference internal" href="../../sys/win/index.html">Windows</a></li> <li class="toctree-l2"><a class="reference internal" href="../../sys/mac/index.html">macOS</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../../debug/index.html">调试与逆向工程</a><ul> <li class="toctree-l2"><a class="reference internal" href="../../debug/debug-segfault.html">Linux下段错误调试技巧</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../debug/debug-segfault.html#core-dumpgdb">生成core dump文件并用gdb调试</a></li> <li class="toctree-l3"><a class="reference internal" href="../../debug/debug-segfault.html#dmesgaddr2line">使用dmesg和addr2line命令</a></li> <li class="toctree-l3"><a class="reference internal" href="../../debug/debug-segfault.html#id2">让程序段错误时自动输出堆栈信息并调试</a></li> <li class="toctree-l3"><a class="reference internal" href="../../debug/debug-segfault.html#id3">参考</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../debug/links.html">参考链接</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../../net/index.html">TCP/IP网络</a><ul> <li class="toctree-l2"><a class="reference internal" href="../../net/tcpip/index.html">TCP/IP详解</a><ul class="simple"> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../net/netalgo/index.html">网络算法学</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../net/netalgo/proto_process.html">9 Protocol Processing</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../net/netalgo/proto_process.html#id1">9.1 缓存管理</a></li> <li class="toctree-l4"><a class="reference internal" href="../../net/netalgo/proto_process.html#crcchecksum">9.2 CRC和Checksum</a></li> <li class="toctree-l4"><a class="reference internal" href="../../net/netalgo/proto_process.html#id4">9.3 通用协议处理</a></li> <li class="toctree-l4"><a class="reference internal" href="../../net/netalgo/proto_process.html#id5">9.4 重组</a></li> <li class="toctree-l4"><a class="reference internal" href="../../net/netalgo/proto_process.html#id7">9.5 结论</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../net/netalgo/sched_packet.html">14 Scheduling Packets</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../net/netalgo/sched_packet.html#id1">14.1 概述</a></li> <li class="toctree-l4"><a class="reference internal" href="../../net/netalgo/sched_packet.html#id2">14.2 拥塞控制</a></li> <li class="toctree-l4"><a class="reference internal" href="../../net/netalgo/sched_packet.html#id13">14.3 带宽与突发限制</a></li> <li class="toctree-l4"><a class="reference internal" href="../../net/netalgo/sched_packet.html#id24">14.4 多队列与优先级</a></li> <li class="toctree-l4"><a class="reference internal" href="../../net/netalgo/sched_packet.html#id25">14.5 资源预留协议</a></li> <li class="toctree-l4"><a class="reference internal" href="../../net/netalgo/sched_packet.html#id26">14.6 带宽保证</a></li> <li class="toctree-l4"><a class="reference internal" href="../../net/netalgo/sched_packet.html#id30">14.7 时延保证</a></li> <li class="toctree-l4"><a class="reference internal" href="../../net/netalgo/sched_packet.html#scalable-fair-queuing">14.8 Scalable Fair Queuing</a></li> <li class="toctree-l4"><a class="reference internal" href="../../net/netalgo/sched_packet.html#dpdk">14.9 dpdk分层调度</a></li> <li class="toctree-l4"><a class="reference internal" href="../../net/netalgo/sched_packet.html#diffserv">14.10 DiffServ架构介绍</a></li> <li class="toctree-l4"><a class="reference internal" href="../../net/netalgo/sched_packet.html#dpdk-qos">14.11 dpdk QoS框架</a></li> <li class="toctree-l4"><a class="reference internal" href="../../net/netalgo/sched_packet.html#id37">附录</a></li> <li class="toctree-l4"><a class="reference internal" href="../../net/netalgo/sched_packet.html#id38">参考</a></li> </ul> </li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../net/links.html">参考链接</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../../sec/index.html">安全</a><ul> <li class="toctree-l2"><a class="reference internal" href="../../sec/dpi/index.html">DPI</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../sec/dpi/links.html">参考链接</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../sec/links.html">参考链接</a></li> </ul> </li> <li class="toctree-l1 current"><a class="reference internal" href="../index.html">性能优化</a><ul class="current"> <li class="toctree-l2"><a class="reference internal" href="../cpu/index.html">CPU知识</a><ul> <li class="toctree-l3"><a class="reference internal" href="../cpu/microprocessor.html">理解微处理器</a><ul> <li class="toctree-l4"><a class="reference internal" href="../cpu/microprocessor.html#introduction">Introduction</a></li> <li class="toctree-l4"><a class="reference internal" href="../cpu/microprocessor.html#code-and-data-a-closer-look">Code and Data: a closer look</a></li> <li class="toctree-l4"><a class="reference internal" href="../cpu/microprocessor.html#meet-the-file-clerk">meet the &#8220;file clerk&#8221;</a></li> <li class="toctree-l4"><a class="reference internal" href="../cpu/microprocessor.html#refining-the-model">Refining the model</a></li> <li class="toctree-l4"><a class="reference internal" href="../cpu/microprocessor.html#ram-when-the-registers-alone-don-t-cut-it">RAM: when the registers alone don&#8217;t cut it</a></li> <li class="toctree-l4"><a class="reference internal" href="../cpu/microprocessor.html#a-closer-look-at-the-code-stream-the-program">A closer look at the code stream: the program</a></li> <li class="toctree-l4"><a class="reference internal" href="../cpu/microprocessor.html#excursus-op-codes-and-machine-language">Excursus: Op codes and machine language</a></li> <li class="toctree-l4"><a class="reference internal" href="../cpu/microprocessor.html#the-programming-model-and-the-isa">The programming model and the ISA</a></li> <li class="toctree-l4"><a class="reference internal" href="../cpu/microprocessor.html#branch-instructions">Branch instructions</a></li> <li class="toctree-l4"><a class="reference internal" href="../cpu/microprocessor.html#conclusion">Conclusion</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../cpu/pipeline.html">理解流水线与超标量执行</a><ul> <li class="toctree-l4"><a class="reference internal" href="../cpu/pipeline.html#introduction">Introduction</a></li> <li class="toctree-l4"><a class="reference internal" href="../cpu/pipeline.html#pipelining-explained">Pipelining Explained</a></li> <li class="toctree-l4"><a class="reference internal" href="../cpu/pipeline.html#superscalar-execution">Superscalar execution</a></li> <li class="toctree-l4"><a class="reference internal" href="../cpu/pipeline.html#combining-pipelined-and-superscalar-execution">Combining pipelined and superscalar execution</a></li> <li class="toctree-l4"><a class="reference internal" href="../cpu/pipeline.html#conclusions">Conclusions</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../cpu/bandwidth.html">理解带宽与时延</a></li> <li class="toctree-l3"><a class="reference internal" href="../cpu/intel_p4.html">NetBurst: The Microarchitecture of the Pentium 4 Processor</a><ul> <li class="toctree-l4"><a class="reference internal" href="../cpu/intel_p4.html#id1">引言</a></li> <li class="toctree-l4"><a class="reference internal" href="../cpu/intel_p4.html#netburst">NetBurst微架构概述</a></li> <li class="toctree-l4"><a class="reference internal" href="../cpu/intel_p4.html#id4">时钟频率</a></li> <li class="toctree-l4"><a class="reference internal" href="../cpu/intel_p4.html#id6">NetBurst微架构</a></li> <li class="toctree-l4"><a class="reference internal" href="../cpu/intel_p4.html#id10">性能</a></li> <li class="toctree-l4"><a class="reference internal" href="../cpu/intel_p4.html#id11">结论</a></li> <li class="toctree-l4"><a class="reference internal" href="../cpu/intel_p4.html#id12">作者</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../cpu/glossary.html">CPU相关术语及缩略语</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../intel_opt_manual/index.html">Intel优化手册</a><ul> <li class="toctree-l3"><a class="reference internal" href="../intel_opt_manual/2.html">2 INTEL 64 AND IA-32 PROCESSOR ARCHITECTURES</a><ul> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/2.html#skylake-server">Skylake Server</a></li> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/2.html#skylake">Skylake</a></li> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/2.html#haswell">Haswell</a></li> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/2.html#haswell-e">Haswell-E</a></li> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/2.html#broadwell">Broadwell</a></li> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/2.html#sandy-bridge">Sandy Bridge</a></li> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/2.html#ivy-bridge">Ivy Bridge</a></li> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/2.html#core-enhanced-core">Core &amp; Enhanced Core</a></li> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/2.html#nehalem">Nehalem</a></li> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/2.html#id1">超线程技术</a></li> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/2.html#id2">64位架构</a></li> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/2.html#simd">SIMD技术</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../intel_opt_manual/3.html">3 一般性优化原则</a><ul> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/3.html#id2">3.1 性能工具</a></li> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/3.html#id4">3.2 处理器全景</a></li> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/3.html#id7">3.3 编程规则, 建议及调整提示</a></li> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/3.html#id8">3.4 优化前端</a></li> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/3.html#execution-core">3.5 优化Execution Core</a></li> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/3.html#id20">3.6 优化内存访问</a></li> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/3.html#prefetch">3.7 prefetch</a></li> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/3.html#id23">3.8 浮点数的考量</a></li> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/3.html#pcie">3.9 最大化PCIe性能</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../intel_opt_manual/7.html">7 优化cache使用</a><ul> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/7.html#general-prefetch-coding-guidelines">7.1 GENERAL PREFETCH CODING GUIDELINES</a></li> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/7.html#prefetch-and-cacheability-instructions">7.2 PREFETCH AND CACHEABILITY INSTRUCTIONS</a></li> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/7.html#prefetch">7.3 PREFETCH</a></li> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/7.html#cacheability-control">7.4 CACHEABILITY CONTROL</a></li> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/7.html#memory-optimization-using-prefetch">7.5 MEMORY OPTIMIZATION USING PREFETCH</a></li> <li class="toctree-l4"><a class="reference internal" href="../intel_opt_manual/7.html#memory-optimization-using-non-temporal-stores">7.6 MEMORY OPTIMIZATION USING NON-TEMPORAL STORES</a></li> </ul> </li> </ul> </li> <li class="toctree-l2 current"><a class="reference internal" href="index.html">Intel VTune Amplifier</a><ul class="current"> <li class="toctree-l3"><a class="reference internal" href="intro.html">介绍</a><ul> <li class="toctree-l4"><a class="reference internal" href="intro.html#id2">简介</a></li> <li class="toctree-l4"><a class="reference internal" href="intro.html#id3">调优方法论</a></li> <li class="toctree-l4"><a class="reference internal" href="intro.html#id4">安装</a></li> <li class="toctree-l4"><a class="reference internal" href="intro.html#id5">一般使用</a></li> <li class="toctree-l4"><a class="reference internal" href="intro.html#id10">参考资料</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="tutorial_hotspots.html">教程: 优化热点</a><ul> <li class="toctree-l4"><a class="reference internal" href="tutorial_hotspots.html#id2">编译示例程序</a></li> <li class="toctree-l4"><a class="reference internal" href="tutorial_hotspots.html#vtune">创建vtune工程并运行分析</a></li> <li class="toctree-l4"><a class="reference internal" href="tutorial_hotspots.html#id3">分析代码</a></li> <li class="toctree-l4"><a class="reference internal" href="tutorial_hotspots.html#id4">优化代码</a></li> </ul> </li> <li class="toctree-l3 current"><a class="current reference internal" href="#">教程: 优化硬件利用率</a><ul> <li class="toctree-l4"><a class="reference internal" href="#id2">编译示例程序</a></li> <li class="toctree-l4"><a class="reference internal" href="#vtune">创建vtune工程并运行分析</a></li> <li class="toctree-l4"><a class="reference internal" href="#id3">分析代码</a></li> <li class="toctree-l4"><a class="reference internal" href="#id4">优化代码</a></li> <li class="toctree-l4"><a class="reference internal" href="#id5">进一步分析和优化</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="tutorial_false_sharing.html">教程: 优化伪共享</a><ul> <li class="toctree-l4"><a class="reference internal" href="tutorial_false_sharing.html#id2">编译示例程序</a></li> <li class="toctree-l4"><a class="reference internal" href="tutorial_false_sharing.html#vtune">创建vtune工程并运行分析</a></li> <li class="toctree-l4"><a class="reference internal" href="tutorial_false_sharing.html#id3">分析代码</a></li> <li class="toctree-l4"><a class="reference internal" href="tutorial_false_sharing.html#id4">优化代码</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="tunning_guide_e5v3.html">调优指南: Xeon E5 v3</a><ul> <li class="toctree-l4"><a class="reference internal" href="tunning_guide_e5v3.html#intel-xeon-e5-v3-family">1 Intel Xeon E5 v3 Family</a></li> <li class="toctree-l4"><a class="reference internal" href="tunning_guide_e5v3.html#id1">2 性能测量的复杂性</a></li> <li class="toctree-l4"><a class="reference internal" href="tunning_guide_e5v3.html#id2">3 发现性能问题</a></li> <li class="toctree-l4"><a class="reference internal" href="tunning_guide_e5v3.html#front-end-bound">4 调优Front-End Bound</a></li> <li class="toctree-l4"><a class="reference internal" href="tunning_guide_e5v3.html#back-end-bound">5 调优Back-End Bound</a></li> <li class="toctree-l4"><a class="reference internal" href="tunning_guide_e5v3.html#bad-speculation">6 调优Bad Speculation</a></li> <li class="toctree-l4"><a class="reference internal" href="tunning_guide_e5v3.html#retiring">7 调优Retiring</a></li> <li class="toctree-l4"><a class="reference internal" href="tunning_guide_e5v3.html#id12">8 附加主题</a></li> </ul> </li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../cpu_cache.html">CPU Cache Optimization</a><ul> <li class="toctree-l3"><a class="reference internal" href="../cpu_cache.html#cpu-cache-the-need-to-know">CPU Cache: the Need to Know</a></li> <li class="toctree-l3"><a class="reference internal" href="../cpu_cache.html#our-first-example">Our First Example</a></li> <li class="toctree-l3"><a class="reference internal" href="../cpu_cache.html#cache-line-and-fetch-utilization">Cache Line and Fetch Utilization</a></li> <li class="toctree-l3"><a class="reference internal" href="../cpu_cache.html#more-examples">More Examples</a></li> <li class="toctree-l3"><a class="reference internal" href="../cpu_cache.html#conclusion">Conclusion</a></li> <li class="toctree-l3"><a class="reference internal" href="../cpu_cache.html#id1">参考</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../simd_demo.html">SIMD指令编程demo</a><ul> <li class="toctree-l3"><a class="reference internal" href="../simd_demo.html#id1">正常代码</a></li> <li class="toctree-l3"><a class="reference internal" href="../simd_demo.html#id2">一次循环计算4次</a></li> <li class="toctree-l3"><a class="reference internal" href="../simd_demo.html#sse">使用SSE指令</a></li> <li class="toctree-l3"><a class="reference internal" href="../simd_demo.html#avx">使用AVX指令</a></li> <li class="toctree-l3"><a class="reference internal" href="../simd_demo.html#id3">性能对比</a></li> <li class="toctree-l3"><a class="reference internal" href="../simd_demo.html#id4">更多参考</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../links.html">参考链接</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../../virt/index.html">虚拟化</a><ul> <li class="toctree-l2"><a class="reference internal" href="../../virt/vmware/index.html">VMware</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../virt/vmware/links.html">参考链接</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../virt/qemu/index.html">QEMU</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../virt/qemu/links.html">参考链接</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../virt/container/index.html">容器</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../virt/container/links.html">参考链接</a></li> </ul> </li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../../ai/index.html">AI</a><ul> <li class="toctree-l2"><a class="reference internal" href="../../ai/books.html">学习资料</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../ai/books.html#pattern-recognition-and-machine-learning">Pattern Recognition and Machine Learning</a></li> <li class="toctree-l3"><a class="reference internal" href="../../ai/books.html#convex-optimization">Convex Optimization</a></li> <li class="toctree-l3"><a class="reference internal" href="../../ai/books.html#deep-learning-fundamentals-an-introduction-for-beginners">Deep Learning Fundamentals: An Introduction for Beginners</a></li> <li class="toctree-l3"><a class="reference internal" href="../../ai/books.html#optimization-in-operations-research">Optimization in Operations Research</a></li> <li class="toctree-l3"><a class="reference internal" href="../../ai/books.html#artificial-intelligence-a-modern-approach">Artificial Intelligence: A Modern Approach</a></li> <li class="toctree-l3"><a class="reference internal" href="../../ai/books.html#deep-learning-in-natural-language-processing">Deep Learning in Natural Language Processing</a></li> <li class="toctree-l3"><a class="reference internal" href="../../ai/books.html#id2">机器学习</a></li> <li class="toctree-l3"><a class="reference internal" href="../../ai/books.html#deep-learning">Deep Learning</a></li> </ul> </li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../../opensource/index.html">开源</a><ul> <li class="toctree-l2"><a class="reference internal" href="../../opensource/dpdk/index.html">DPDK</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../opensource/dpdk/hf-dpdk/index.html">深入浅出DPDK</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../opensource/dpdk/hf-dpdk/intro.html">引言</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/dpdk/hf-dpdk/hf_mem_cache.html">深入浅出dpdk: cache与内存</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/dpdk/hf-dpdk/hf_parallel.html">深入浅出dpdk: 并行计算</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/dpdk/hf-dpdk/hf_sync.html">深入浅出dpdk: 同步充斥机制</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/dpdk/hf-dpdk/hf_pkt_forward.html">深入浅出dpdk: 报文转发</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/dpdk/hf-dpdk/hf_pkt_io.html">深入浅出dpdk: PCIe与包处理IO</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/dpdk/hf-dpdk/hf_nic_optimize.html">深入浅出dpdk: 网卡性能优化</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/dpdk/hf-dpdk/hf_classify.html">深入浅出dpdk: 流分类与多队列</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/dpdk/hf-dpdk/hf_hw_accel.html">深入浅出dpdk: 硬件加速与功能卸载</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../opensource/dpdk/code-analysis/index.html">DPDK</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../opensource/dpdk/code-analysis/eal.html">源码分析: EAL</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/dpdk/code-analysis/mem.html">源码分析: Memory</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/dpdk/code-analysis/memseg.html">源码分析: Memseg</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/dpdk/code-analysis/memzone.html">源码分析: Memzone</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/dpdk/code-analysis/malloc.html">源码分析: Malloc</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/dpdk/code-analysis/mempool.html">源码分析: Mempool</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/dpdk/code-analysis/mbuf.html">源码分析: Mbuf</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/dpdk/code-analysis/ring.html">源码分析: Ring</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/dpdk/code-analysis/build_sys.html">编译系统</a></li> </ul> </li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../opensource/tengine/index.html">Tengine</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../opensource/tengine/intro.html">介绍</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/intro.html#tengine">Tengine的由来</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/intro.html#id2">Tengine的改进</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../opensource/tengine/arch.html">架构</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/arch.html#id2">高性能服务器设计</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/arch.html#id3">进程模型</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/arch.html#id5">事件处理模型</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/arch.html#id7">模块化</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/arch.html#id9">请求处理机制</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/arch.html#id10">参考资料</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../opensource/tengine/key_points.html">基本概念</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/key_points.html#connection">连接/connection</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/key_points.html#request">请求/request</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/key_points.html#keepalive">keepalive</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/key_points.html#pipeline">pipeline</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/key_points.html#lingering-close">lingering_close</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/key_points.html#id6">参考资料</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../opensource/tengine/infrastructure.html">基础设施</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/infrastructure.html#id2">日志</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/infrastructure.html#id3">内存管理</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/infrastructure.html#cycle">cycle</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/infrastructure.html#id7">字符串操作</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/infrastructure.html#id12">容器</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/infrastructure.html#id18">时间</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/infrastructure.html#id19">网络</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/infrastructure.html#id21">事件</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/infrastructure.html#id22">进程</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/infrastructure.html#id23">线程</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/infrastructure.html#id24">模块</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/infrastructure.html#id25">错误处理</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../opensource/tengine/http.html">HTTP</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../opensource/tengine/http.html#id1">HTTP请求处理</a></li> </ul> </li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../opensource/wireshark/index.html">wireshark</a><ul class="simple"> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../opensource/hyperscan/index.html">hyperscan</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../opensource/hyperscan/hs_intro.html">hyperscan介绍</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../opensource/hyperscan/hs_intro.html#how-we-match-regular-expressions">首席工程师: How we match regular expressions</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/hyperscan/hs_intro.html#id1">源码结构</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/hyperscan/hs_intro.html#id2">参考</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../opensource/hyperscan/hs_pre.html">hyperscan预备知识</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../opensource/hyperscan/hs_pre.html#c-11">C++ 11</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/hyperscan/hs_pre.html#id5">设计模式</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/hyperscan/hs_pre.html#id6">数据结构</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/hyperscan/hs_pre.html#boost-library">Boost Library</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/hyperscan/hs_pre.html#ragel">Ragel</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../opensource/hyperscan/hs_debug.html">hyperscan调试环境与技巧</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../opensource/hyperscan/hs_debug.html#id1">编译</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/hyperscan/hs_debug.html#dump">生成dump信息</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/hyperscan/hs_debug.html#id4">加速编译过程</a></li> <li class="toctree-l4"><a class="reference internal" href="../../opensource/hyperscan/hs_debug.html#id5">生成源码文档</a></li> </ul> </li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../opensource/links.html">参考链接</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../../misc/index.html">工具与杂项</a><ul> <li class="toctree-l2"><a class="reference internal" href="../../misc/vim/index.html">Vim</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../misc/vim/intro.html">简介与基本配置</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../misc/vim/intro.html#vim">为什么要使用vim</a></li> <li class="toctree-l4"><a class="reference internal" href="../../misc/vim/intro.html#id2">本系列文章的指导思想和一些约定</a></li> <li class="toctree-l4"><a class="reference internal" href="../../misc/vim/intro.html#id3">学习之前的基本配置和几个需要了解的基本操作</a></li> </ul> </li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../misc/git/index.html">Git</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../misc/git/basic_command.html">Git常用命令</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../misc/git/basic_command.html#id2">一、新建代码库</a></li> <li class="toctree-l4"><a class="reference internal" href="../../misc/git/basic_command.html#id3">二、配置</a></li> <li class="toctree-l4"><a class="reference internal" href="../../misc/git/basic_command.html#id4">三、增加/删除文件</a></li> <li class="toctree-l4"><a class="reference internal" href="../../misc/git/basic_command.html#id5">四、代码提交</a></li> <li class="toctree-l4"><a class="reference internal" href="../../misc/git/basic_command.html#id6">五、分支</a></li> <li class="toctree-l4"><a class="reference internal" href="../../misc/git/basic_command.html#id7">六、标签</a></li> <li class="toctree-l4"><a class="reference internal" href="../../misc/git/basic_command.html#id8">七、查看信息</a></li> <li class="toctree-l4"><a class="reference internal" href="../../misc/git/basic_command.html#id9">八、远程同步</a></li> <li class="toctree-l4"><a class="reference internal" href="../../misc/git/basic_command.html#id10">九、撤销</a></li> <li class="toctree-l4"><a class="reference internal" href="../../misc/git/basic_command.html#id11">十、其他</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../misc/git/tricks.html">小技巧</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../misc/git/tricks.html#shellsshgithub">shell通过SSH连接github</a></li> <li class="toctree-l4"><a class="reference internal" href="../../misc/git/tricks.html#id2">在命令提示符中显示当前分支</a></li> </ul> </li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../misc/vmware/index.html">虚拟机</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../misc/vmware/static-ip.html">配置静态IP</a></li> <li class="toctree-l3"><a class="reference internal" href="../../misc/vmware/reduce-disk-size.html">减少磁盘占用空间</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../misc/vmware/reduce-disk-size.html#id2">清理软件包</a></li> <li class="toctree-l4"><a class="reference internal" href="../../misc/vmware/reduce-disk-size.html#id3">清理不用的旧内核</a></li> <li class="toctree-l4"><a class="reference internal" href="../../misc/vmware/reduce-disk-size.html#id4">清理日志</a></li> <li class="toctree-l4"><a class="reference internal" href="../../misc/vmware/reduce-disk-size.html#vmware">使用VMware磁盘工具回收磁盘空间</a></li> <li class="toctree-l4"><a class="reference internal" href="../../misc/vmware/reduce-disk-size.html#id5">参考</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../misc/vmware/misc.html">杂项</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../misc/vmware/misc.html#id2">解决启动黑屏问题</a></li> </ul> </li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../misc/cmake.html">CMake使用</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../misc/cmake.html#hello-world">Hello World</a></li> <li class="toctree-l3"><a class="reference internal" href="../../misc/cmake.html#id1">清理编译后留下的文件</a></li> <li class="toctree-l3"><a class="reference internal" href="../../misc/cmake.html#id2">处理多个目录</a></li> <li class="toctree-l3"><a class="reference internal" href="../../misc/cmake.html#id3">处理第3方依赖库</a></li> <li class="toctree-l3"><a class="reference internal" href="../../misc/cmake.html#debugrelease">生成debug和release版的程序</a></li> <li class="toctree-l3"><a class="reference internal" href="../../misc/cmake.html#id4">参考资料</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../misc/clib-abi.html">解决C/C++依赖库不兼容的问题</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../misc/clib-abi.html#id1">问题引入与分析</a></li> <li class="toctree-l3"><a class="reference internal" href="../../misc/clib-abi.html#id3">解决问题</a></li> <li class="toctree-l3"><a class="reference internal" href="../../misc/clib-abi.html#id7">参考资料</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../misc/shadowsocks.html">VPS+Shadowsocks科学上网</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../misc/shadowsocks.html#vps">购买VPS</a></li> <li class="toctree-l3"><a class="reference internal" href="../../misc/shadowsocks.html#shadowsocks">安装,配置shadowsocks</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../misc/shadowsocks.html#id2">服务器端</a></li> <li class="toctree-l4"><a class="reference internal" href="../../misc/shadowsocks.html#id3">客户端</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../misc/shadowsocks.html#id4">其他技巧</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../misc/shadowsocks.html#id5">对不同网站使用不同的连接方式: 直接/代理</a></li> <li class="toctree-l4"><a class="reference internal" href="../../misc/shadowsocks.html#window">Window下令无法设置代理的应用程序使用代理</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../misc/shadowsocks.html#id6">参考链接</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../misc/patch.html">补丁工具patch</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../misc/patch.html#id1">1 为单个文件生成补丁</a></li> <li class="toctree-l3"><a class="reference internal" href="../../misc/patch.html#id2">2 为多个文件生成补丁</a></li> <li class="toctree-l3"><a class="reference internal" href="../../misc/patch.html#id3">3 打补丁</a></li> <li class="toctree-l3"><a class="reference internal" href="../../misc/patch.html#id4">4 示例</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../misc/libpcap.html">libpcap使用</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../misc/libpcap.html#id1">创建句柄</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../misc/libpcap.html#pcap-open-offline">pcap_open_offline</a></li> <li class="toctree-l4"><a class="reference internal" href="../../misc/libpcap.html#pcap-dump-open">pcap_dump_open</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../misc/libpcap.html#id2">关闭句柄</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../misc/libpcap.html#pcap-close">pcap_close</a></li> <li class="toctree-l4"><a class="reference internal" href="../../misc/libpcap.html#pcap-dump-close">pcap_dump_close</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../misc/libpcap.html#packet">读取packet</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../misc/libpcap.html#pcap-open-pcap-dispatch">pcap_open/pcap_dispatch</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../misc/libpcap.html#id3">设置选项</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../misc/libpcap.html#pcap-set-promisc">pcap_set_promisc</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../misc/libpcap.html#id4">其他</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../misc/libpcap.html#pcap-breakloop">pcap_breakloop</a></li> <li class="toctree-l4"><a class="reference internal" href="../../misc/libpcap.html#pcap-file">pcap_file</a></li> <li class="toctree-l4"><a class="reference internal" href="../../misc/libpcap.html#pcap-dump-file">pcap_dump_file</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../misc/libpcap.html#id5">参考</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../misc/cunit.html">CUnit</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../misc/cunit.html#cunit-2-1-3">编译安装CUnit-2.1-3</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../misc/centos.html">CentOS应用</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../misc/centos.html#centos7-3minimalc-c">CentOS7.3Minimal从零配置C/C++开发环境</a></li> <li class="toctree-l3"><a class="reference internal" href="../../misc/centos.html#failed-to-start-lsb-bring-up-down-networking">网络配置失败,显示Failed to start LSB: Bring up/down networking</a></li> <li class="toctree-l3"><a class="reference internal" href="../../misc/centos.html#centoswindows">共享CentOS虚拟机上的文件给Windows本机访问</a></li> <li class="toctree-l3"><a class="reference internal" href="../../misc/centos.html#pip">安装pip</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../misc/ubuntu.html">Ubuntu应用</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../misc/ubuntu.html#id1">14.04更换阿里云源</a></li> <li class="toctree-l3"><a class="reference internal" href="../../misc/ubuntu.html#youcompleteme">安装YouCompleteMe插件</a></li> <li class="toctree-l3"><a class="reference internal" href="../../misc/ubuntu.html#cpu">隔离某些cpu核心</a></li> <li class="toctree-l3"><a class="reference internal" href="../../misc/ubuntu.html#vmware-workstationubuntu-server">VMware Workstation中的Ubuntu Server虚拟机重启后共享文件夹消失</a></li> <li class="toctree-l3"><a class="reference internal" href="../../misc/ubuntu.html#cannot-set-lc-ctype-to-default-locale-no-such-file-or-directory">Cannot set LC_CTYPE to default locale: No such file or directory</a></li> <li class="toctree-l3"><a class="reference internal" href="../../misc/ubuntu.html#man">man文档不全</a></li> <li class="toctree-l3"><a class="reference internal" href="../../misc/ubuntu.html#id2">修改系统对消息队列的默认限制</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../misc/xiaomi-router.html">小米路由器开发</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../misc/xiaomi-router.html#rom">用ROM刷机</a></li> <li class="toctree-l3"><a class="reference internal" href="../../misc/xiaomi-router.html#ssh">开启SSH</a></li> <li class="toctree-l3"><a class="reference internal" href="../../misc/xiaomi-router.html#id2">交叉编译环境搭建</a></li> <li class="toctree-l3"><a class="reference internal" href="../../misc/xiaomi-router.html#id3">交叉编译库或工具</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../misc/xiaomi-router.html#libpcap">编译libpcap</a></li> <li class="toctree-l4"><a class="reference internal" href="../../misc/xiaomi-router.html#helloworld">编译helloworld</a></li> <li class="toctree-l4"><a class="reference internal" href="../../misc/xiaomi-router.html#gdb">编译gdb</a></li> </ul> </li> <li class="toctree-l3"><a class="reference internal" href="../../misc/xiaomi-router.html#id4">其他</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../misc/xiaomi-router.html#id5">在小米路由器上部署静态网页</a></li> </ul> </li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../misc/qemu.html">QEMU模拟器</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../misc/qemu.html#id2">安装软件包</a></li> <li class="toctree-l3"><a class="reference internal" href="../../misc/qemu.html#id3">用户模式</a></li> <li class="toctree-l3"><a class="reference internal" href="../../misc/qemu.html#id4">系统模式</a><ul> <li class="toctree-l4"><a class="reference internal" href="../../misc/qemu.html#id5">一般使用</a></li> <li class="toctree-l4"><a class="reference internal" href="../../misc/qemu.html#id6">配置网络</a></li> <li class="toctree-l4"><a class="reference internal" href="../../misc/qemu.html#gdb">远程gdb调试</a></li> </ul> </li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../misc/config-links.html">配置文件-参考链接</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../../hobby/index.html">兴趣爱好</a><ul> <li class="toctree-l2"><a class="reference internal" href="../../hobby/video_trick.html">视频制作相关小技巧</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../hobby/video_trick.html#b">如何下载B站视频,或者用微博发的视频?</a></li> <li class="toctree-l3"><a class="reference internal" href="../../hobby/video_trick.html#mac">Mac系统下应该用什么软件做视频编辑?</a></li> <li class="toctree-l3"><a class="reference internal" href="../../hobby/video_trick.html#mac-gif">Mac系统如何做动图(gif)?</a></li> <li class="toctree-l3"><a class="reference internal" href="../../hobby/video_trick.html#gif-fcpx">我有一些动图(gif),怎么将它们导入到fcpx?直接导入发现它们不动了啊!</a></li> <li class="toctree-l3"><a class="reference internal" href="../../hobby/video_trick.html#id2">Mac系统如何录制系统自己发出的声音,比如我正在听一首很好听的歌但是不方便下载它?</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="../../hobby/ffmpeg.html">ffmpeg应用</a><ul> <li class="toctree-l3"><a class="reference internal" href="../../hobby/ffmpeg.html#id1">常用技巧</a></li> <li class="toctree-l3"><a class="reference internal" href="../../hobby/ffmpeg.html#id2">参考</a></li> </ul> </li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../../blogroll.html">友情链接</a></li> <li class="toctree-l1"><a class="reference internal" href="../../aboutme.html">关于我</a></li> </ul> </div> </div> </nav> <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap"> <nav class="wy-nav-top" aria-label="top navigation"> <i data-toggle="wy-nav-top" class="fa fa-bars"></i> <a href="../../index.html">赵子清技术文章</a> </nav> <div class="wy-nav-content"> <div class="rst-content"> <div role="navigation" aria-label="breadcrumbs navigation"> <ul class="wy-breadcrumbs"> <li><a href="../../index.html">Docs</a> &raquo;</li> <li><a href="../index.html">性能优化</a> &raquo;</li> <li><a href="index.html">Intel VTune Amplifier</a> &raquo;</li> <li>教程: 优化硬件利用率</li> <li class="wy-breadcrumbs-aside"> </li> </ul> <hr/> </div> <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article"> <div itemprop="articleBody"> <div class="section" id="id1"> <h1>教程: 优化硬件利用率<a class="headerlink" href="#id1" title="永久链接至标题">¶</a></h1> <p><em>本文更新于 2018.10.10</em></p> <p>本文演示了如何分析硬件相关的性能问题, 如数据共享, cache miss, 分支预测失败等.</p> <p>参考: <a class="reference external" href="https://software.intel.com/en-us/vtune-hw-issues-tutorial-lin-pdf">https://software.intel.com/en-us/vtune-hw-issues-tutorial-lin-pdf</a></p> <p>工作流:</p> <img alt="../../_images/tutorial_hw.png" src="../../_images/tutorial_hw.png" /> <div class="section" id="id2"> <h2>编译示例程序<a class="headerlink" href="#id2" title="永久链接至标题">¶</a></h2> <p>本教程使用matrix示例, 位置在 /opt/intel/system_studio_2019/samples_2019/en/vtune_amplifier/C++/matrix_vtune_amp_xe.tgz, 将其解压至某目录, 进入matrix/linux目录运行make进行编译.</p> <p>如果用intel编译器, 请先设置环境变量:</p> <div class="highlight-text"><div class="highlight"><pre><span></span>source /opt/intel/system_studio_2019/compilers_and_libraries_2019.0.120/linux/bin/compilervars.sh -arch intel64 </pre></div> </div> <p>然后运行make icc:</p> <div class="highlight-text"><div class="highlight"><pre><span></span>$ make icc icc -g -O3 -DUSE_THR -DICC -debug inline-debug-info -c ../src/util.c -D_LINUX icc -g -O3 -DUSE_THR -DICC -debug inline-debug-info -c ../src/thrmodel.c -D_LINUX icc -g -O3 -DUSE_THR -DICC -debug inline-debug-info -xSSE3 -c ../src/multiply.c -D_LINUX icc -g -O3 -DUSE_THR -DICC -debug inline-debug-info -xSSE3 -c ../src/matrix.c -D_LINUX icc -g -O3 -DUSE_THR -DICC -debug inline-debug-info util.o thrmodel.o multiply.o matrix.o -o matrix.icc -lpthread -lm </pre></div> </div> <p>更多帮助见matrix/readme.txt. 编译完成后运行程序, 可以看到执行时间:</p> <div class="highlight-text"><div class="highlight"><pre><span></span>$ ./matrix.icc Addr of buf1 = 0x7fe9ed2b7010 Offs of buf1 = 0x7fe9ed2b7180 Addr of buf2 = 0x7fe9eb2b6010 Offs of buf2 = 0x7fe9eb2b61c0 Addr of buf3 = 0x7fe9e92b5010 Offs of buf3 = 0x7fe9e92b5100 Addr of buf4 = 0x7fe9e72b4010 Offs of buf4 = 0x7fe9e72b4140 Threads #: 16 Pthreads Matrix size: 2048 Using multiply kernel: multiply1 Freq = 3.199968 GHz Execution time = 16.780 seconds </pre></div> </div> </div> <div class="section" id="vtune"> <h2>创建vtune工程并运行分析<a class="headerlink" href="#vtune" title="永久链接至标题">¶</a></h2> <p>创建vtune工程, 分析类型为Microarchitecture Exploration, 并配置可执行程序路径和源代码搜索路径等:</p> <img alt="../../_images/tutorial_hw_2.png" src="../../_images/tutorial_hw_2.png" /> <p>完成后点击开始按钮开始分析.</p> <div class="admonition note"> <p class="first admonition-title">注解</p> <p class="last">进行分析前最好通过BIOS设置关闭超线程支持, 否则对性能数据收集有影响. 性能分析工作完成后记得改回来</p> </div> </div> <div class="section" id="id3"> <h2>分析代码<a class="headerlink" href="#id3" title="永久链接至标题">¶</a></h2> <p>分析完成后概览信息如下:</p> <img alt="../../_images/tutorial_hw_3.png" src="../../_images/tutorial_hw_3.png" /> <p>其中可见CPI(Cycles per Instructions Retired) Rate和内存访问有性能问题.</p> <p>切换到&#8221;Bottom-Up&#8221;视图, 可以看到multiply1函数占用了大量CPU时间, 需要优化:</p> <img alt="../../_images/tutorial_hw_4.png" src="../../_images/tutorial_hw_4.png" /> <p>双击函数行打开源代码窗口, 可以看到第51行的代码, 它在进行矩阵运算时对内存的访问比较低效.</p> <img alt="../../_images/tutorial_hw_5.png" src="../../_images/tutorial_hw_5.png" /> </div> <div class="section" id="id4"> <h2>优化代码<a class="headerlink" href="#id4" title="永久链接至标题">¶</a></h2> <p>编辑multiply.h, 将MULTIPLY宏定义替换为multiply2, 表示使用multiply2函数, 此函数使用了&#8221;loop interchange&#8221;机制来优化内存访问.</p> <div class="highlight-c"><div class="highlight"><pre><span></span><span class="c1">// Step 2: Loop interchange</span> <span class="c1">// Add compile option for vectorization report Windows: /Qvec-report3 Linux -vec-report3</span> <span class="k">for</span><span class="p">(</span><span class="n">i</span><span class="o">=</span><span class="n">tidx</span><span class="p">;</span> <span class="n">i</span><span class="o">&lt;</span><span class="n">msize</span><span class="p">;</span> <span class="n">i</span><span class="o">=</span><span class="n">i</span><span class="o">+</span><span class="n">numt</span><span class="p">)</span> <span class="p">{</span> <span class="k">for</span><span class="p">(</span><span class="n">k</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span> <span class="n">k</span><span class="o">&lt;</span><span class="n">msize</span><span class="p">;</span> <span class="n">k</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span> <span class="cp">#pragma ivdep</span> <span class="k">for</span><span class="p">(</span><span class="n">j</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span> <span class="n">j</span><span class="o">&lt;</span><span class="n">msize</span><span class="p">;</span> <span class="n">j</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span> <span class="n">c</span><span class="p">[</span><span class="n">i</span><span class="p">][</span><span class="n">j</span><span class="p">]</span> <span class="o">=</span> <span class="n">c</span><span class="p">[</span><span class="n">i</span><span class="p">][</span><span class="n">j</span><span class="p">]</span> <span class="o">+</span> <span class="n">a</span><span class="p">[</span><span class="n">i</span><span class="p">][</span><span class="n">k</span><span class="p">]</span> <span class="o">*</span> <span class="n">b</span><span class="p">[</span><span class="n">k</span><span class="p">][</span><span class="n">j</span><span class="p">];</span> <span class="p">}</span> <span class="p">}</span> <span class="p">}</span> </pre></div> </div> <p>其中, #pragma ivdep告诉intel编译器忽略假定的矢量依赖(Ignore assumed Vector DEPendencies), 它将令编译器启用SSSE.</p> <p>保存修改后重新编译matrix, 运行:</p> <div class="highlight-text"><div class="highlight"><pre><span></span>$ ./matrix.icc Addr of buf1 = 0x7f9650a20010 Offs of buf1 = 0x7f9650a20180 Addr of buf2 = 0x7f964ea1f010 Offs of buf2 = 0x7f964ea1f1c0 Addr of buf3 = 0x7f964ca1e010 Offs of buf3 = 0x7f964ca1e100 Addr of buf4 = 0x7f964aa1d010 Offs of buf4 = 0x7f964aa1d140 Threads #: 16 Pthreads Matrix size: 2048 Using multiply kernel: multiply2 Freq = 3.149062 GHz Execution time = 1.972 seconds </pre></div> </div> <p>可见执行时间从16.780秒缩短到1.972秒, 提升了8倍还多.</p> </div> <div class="section" id="id5"> <h2>进一步分析和优化<a class="headerlink" href="#id5" title="永久链接至标题">¶</a></h2> <p>对修改后的代码再进行一次Microarchitecture Exploration分析, 概要信息如下:</p> <img alt="../../_images/tutorial_hw_6.png" src="../../_images/tutorial_hw_6.png" /> <p>打开&#8221;Bottom-up&#8221;示图, 可以看到multiply2函数仍有优化空间:</p> <img alt="../../_images/tutorial_hw_7.png" src="../../_images/tutorial_hw_7.png" /> <p>打开源代码视图, 并打开反汇编, 可以看到#pragam ivdep下面的代码已经被编译为矢量化指令:</p> <img alt="../../_images/tutorial_hw_8.png" src="../../_images/tutorial_hw_8.png" /> <p>所有矢量化指令以p为后缀(如, mulp dx), 可以使用-vec-report3编码选项来让intel编译器生成编译器优化报告, 以发现哪些cycle未被矢量化及其原因.</p> <p>再次修改代码, 将运算函数改为multiply3:</p> <div class="highlight-c"><div class="highlight"><pre><span></span><span class="c1">// Step3: Cache blocking</span> <span class="c1">// Add current platform optimization for Windows: /QxHost Linux: -xHost</span> <span class="c1">// Define the ALIGNED in the preprocessor definitions and compile option Windows: /Oa Linux: -fno-alias</span> <span class="n">istep</span> <span class="o">=</span> <span class="n">msize</span> <span class="o">/</span> <span class="n">numt</span><span class="p">;</span> <span class="n">ibeg</span> <span class="o">=</span> <span class="n">tidx</span> <span class="o">*</span> <span class="n">istep</span><span class="p">;</span> <span class="n">ibound</span> <span class="o">=</span> <span class="n">ibeg</span> <span class="o">+</span> <span class="n">istep</span><span class="p">;</span> <span class="n">mblock</span> <span class="o">=</span> <span class="n">MATRIX_BLOCK_SIZE</span><span class="p">;</span> <span class="k">for</span> <span class="p">(</span><span class="n">i0</span> <span class="o">=</span> <span class="n">ibeg</span><span class="p">;</span> <span class="n">i0</span> <span class="o">&lt;</span> <span class="n">ibound</span><span class="p">;</span> <span class="n">i0</span> <span class="o">+=</span><span class="n">mblock</span><span class="p">)</span> <span class="p">{</span> <span class="k">for</span> <span class="p">(</span><span class="n">k0</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">k0</span> <span class="o">&lt;</span> <span class="n">msize</span><span class="p">;</span> <span class="n">k0</span> <span class="o">+=</span> <span class="n">mblock</span><span class="p">)</span> <span class="p">{</span> <span class="k">for</span> <span class="p">(</span><span class="n">j0</span> <span class="o">=</span><span class="mi">0</span><span class="p">;</span> <span class="n">j0</span> <span class="o">&lt;</span> <span class="n">msize</span><span class="p">;</span> <span class="n">j0</span> <span class="o">+=</span> <span class="n">mblock</span><span class="p">)</span> <span class="p">{</span> <span class="k">for</span> <span class="p">(</span><span class="n">i</span> <span class="o">=</span> <span class="n">i0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">i0</span> <span class="o">+</span> <span class="n">mblock</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span> <span class="k">for</span> <span class="p">(</span><span class="n">k</span> <span class="o">=</span> <span class="n">k0</span><span class="p">;</span> <span class="n">k</span> <span class="o">&lt;</span> <span class="n">k0</span> <span class="o">+</span> <span class="n">mblock</span><span class="p">;</span> <span class="n">k</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span> <span class="cp">#pragma ivdep</span> <span class="cp">#ifdef ALIGNED</span> <span class="cp">#pragma vector aligned</span> <span class="cp">#endif </span><span class="c1">//ALIGNED</span> <span class="k">for</span> <span class="p">(</span><span class="n">j</span> <span class="o">=</span> <span class="n">j0</span><span class="p">;</span> <span class="n">j</span> <span class="o">&lt;</span> <span class="n">j0</span> <span class="o">+</span> <span class="n">mblock</span><span class="p">;</span> <span class="n">j</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span> <span class="n">c</span><span class="p">[</span><span class="n">i</span><span class="p">][</span><span class="n">j</span><span class="p">]</span> <span class="o">=</span> <span class="n">c</span><span class="p">[</span><span class="n">i</span><span class="p">][</span><span class="n">j</span><span class="p">]</span> <span class="o">+</span> <span class="n">a</span><span class="p">[</span><span class="n">i</span><span class="p">][</span><span class="n">k</span><span class="p">]</span> <span class="o">*</span> <span class="n">b</span><span class="p">[</span><span class="n">k</span><span class="p">][</span><span class="n">j</span><span class="p">];</span> <span class="p">}</span> <span class="p">}</span> <span class="p">}</span> <span class="p">}</span> <span class="p">}</span> <span class="p">}</span> </pre></div> </div> <p>修改Makefile:</p> <div class="highlight-text"><div class="highlight"><pre><span></span>OPTFLAGS = -xHost -fno-alias -DALIGNED </pre></div> </div> <p>重新编译运行:</p> <div class="highlight-text"><div class="highlight"><pre><span></span>$ ./matrix.icc Threads #: 16 Pthreads Matrix size: 2048 Using multiply kernel: multiply3 Freq = 2.399906 GHz Execution time = 0.534 seconds </pre></div> </div> <p>执行时间进一步缩短. 重新运行Microarchitecture Exploration分析, 概要信息如下:</p> <img alt="../../_images/tutorial_hw_9.png" src="../../_images/tutorial_hw_9.png" /> <p>CPI Rate和内存利用率数据进一步提升.</p> </div> </div> </div> </div> <footer> <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation"> <a href="tutorial_false_sharing.html" class="btn btn-neutral float-right" title="教程: 优化伪共享" accesskey="n" rel="next">Next <span class="fa fa-arrow-circle-right"></span></a> <a href="tutorial_hotspots.html" class="btn btn-neutral float-left" title="教程: 优化热点" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left"></span> Previous</a> </div> <hr/> <div role="contentinfo"> <p> &copy; Copyright 2019, 赵子清 </p> </div> </footer> </div> </div> </section> </div> <script type="text/javascript"> jQuery(function () { SphinxRtdTheme.Navigation.enable(true); }); </script> </body> </html>
zzqcn/zzqcn.github.io
perf/intel_vtune/tutorial_hardware.html
HTML
gpl-2.0
84,396
<?php /** * @package HikaShop for Joomla! * @version 4.4.0 * @author hikashop.com * @copyright (C) 2010-2020 HIKARI SOFTWARE. All rights reserved. * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ defined('_JEXEC') or die('Restricted access'); ?> <table class="admintable" width="100%"> <tr> <td class="key"> <?php echo JText::_( 'HIKA_NAME' ); ?> </td> <td> <?php $systemOrderStatuses = array('created', 'confirmed', 'cancelled', 'refunded', 'shipped'); if(!empty($this->element->category_id) && in_array($this->element->category_name, $systemOrderStatuses) && !@$this->translation && @$this->element->category_type=='status'){ ?> <input id="category_name" type="hidden" size="80" name="<?php echo $this->category_name_input; ?>" value="<?php echo $this->escape(@$this->element->category_name); ?>" /><?php echo $this->escape(@$this->element->category_name); ?> <?php }else{ ?> <input id="category_name" type="text" size="80" name="<?php echo $this->category_name_input; ?>" value="<?php echo $this->escape(@$this->element->category_name); ?>" /> <?php } if(isset($this->category_name_published)){ $publishedid = 'published-'.$this->category_name_id; ?> <span id="<?php echo $publishedid; ?>" class="spanloading"><?php echo $this->toggle->toggle($publishedid,(int) $this->category_name_published,'translation') ?></span> <?php } ?> </td> </tr> <tr> <td class="key"> <?php echo JText::_( 'CATEGORY_DESCRIPTION' ); ?> </td> <td width="100%"></td> </tr> <tr> <td colspan="2" width="100%"> <?php if(isset($this->category_description_published)){ $publishedid = 'published-'.$this->category_description_id; ?> <span id="<?php echo $publishedid; ?>" class="spanloading"><?php echo $this->toggle->toggle($publishedid,(int) $this->category_description_published,'translation') ?></span> <br/> <?php } $this->editor->height = 150; $this->editor->content = @$this->element->category_description; echo $this->editor->display(); ?> </td> </tr> <?php if(empty($this->element->category_type) || in_array($this->element->category_type,array('product','manufacturer'))){ ?> <tr> <td class="key"> <?php echo JText::_( 'CATEGORY_META_DESCRIPTION' ); ?> </td> <td> <textarea id="category_meta_description" cols="46" rows="2" name="<?php echo $this->category_meta_description_input; ?>"><?php echo $this->escape(@$this->element->category_meta_description); ?></textarea> <?php if(isset($this->category_meta_description_published)){ $publishedid = 'published-'.$this->category_meta_description_id; ?> <span id="<?php echo $publishedid; ?>" class="spanloading"><?php echo $this->toggle->toggle($publishedid,(int) $this->category_meta_description_published,'translation') ?></span> <?php } ?> </td> </tr> <tr> <td class="key"> <?php echo JText::_( 'CATEGORY_KEYWORDS' ); ?> </td> <td> <textarea id="category_keywords" cols="46" rows="1" name="<?php echo $this->category_keywords_input; ?>"><?php echo $this->escape(@$this->element->category_keywords); ?></textarea> <?php if(isset($this->category_keywords_published)){ $publishedid = 'published-'.$this->category_keywords_id; ?> <span id="<?php echo $publishedid; ?>" class="spanloading"><?php echo $this->toggle->toggle($publishedid,(int) $this->category_keywords_published,'translation') ?></span> <?php } ?> </td> </tr> <tr> <td class="key"> <?php echo JText::_( 'PAGE_TITLE' ); ?> </td> <td> <textarea id="category_page_title" cols="46" rows="2" name="<?php echo $this->category_page_title_input; ?>"><?php if(!isset($this->element->category_page_title)) $this->element->category_page_title=''; echo $this->escape(@$this->element->category_page_title); ?></textarea> <?php if(isset($this->category_page_title_published)){ $publishedid = 'published-'.$this->category_page_title_id; ?> <span id="<?php echo $publishedid; ?>" class="spanloading"><?php echo $this->toggle->toggle($publishedid,(int) $this->category_page_title_published,'translation') ?></span> <?php } ?> </td> </tr> <tr> <td class="key"> <?php echo JText::_( 'HIKA_ALIAS' ); ?> </td> <td> <textarea id="category_alias" cols="46" rows="2" name="<?php echo $this->category_alias_input; ?>"><?php if(!isset($this->element->category_alias))$this->element->category_alias=''; echo $this->escape(@$this->element->category_alias); ?></textarea> <?php if(isset($this->category_alias_published)){ $publishedid = 'published-'.$this->category_alias_id; ?> <span id="<?php echo $publishedid; ?>" class="spanloading"><?php echo $this->toggle->toggle($publishedid,(int) $this->category_alias_published,'translation') ?></span> <?php } ?> </td> </tr> <tr> <td class="key"> <?php echo JText::_( 'PRODUCT_CANONICAL' ); ?> </td> <td> <input type="text" id="category_canonical" name="<?php echo $this->category_canonical_input; ?>" value="<?php if(!isset($this->element->category_alias))$this->element->category_alias=''; echo $this->escape(@$this->element->category_canonical); ?>"/> <?php if(isset($this->category_canonical_published)){ $publishedid = 'published-'.$this->category_canonical_id; ?> <span id="<?php echo $publishedid; ?>" class="spanloading"><?php echo $this->toggle->toggle($publishedid,(int) $this->category_canonical_published,'translation') ?></span> <?php } ?> </td> </tr> <?php } ?> </table>
emundus/v6
administrator/components/com_hikashop/views/category/tmpl/normal.php
PHP
gpl-2.0
6,147
/*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This software was developed by the Computer Systems Engineering group * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and * contributed to Berkeley. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)fixunsdfdi.c 8.1 (Berkeley) 6/4/93"; #endif /* LIBC_SCCS and not lint */ #include <sys/cdefs.h> __FBSDID("$FreeBSD: release/8.2.0/lib/libc/quad/fixunsdfdi.c 165903 2007-01-09 00:28:16Z imp $"); #include "quad.h" #define ONE_FOURTH (1 << (LONG_BITS - 2)) #define ONE_HALF (ONE_FOURTH * 2.0) #define ONE (ONE_FOURTH * 4.0) /* * Convert double to (unsigned) quad. * Not sure what to do with negative numbers---for now, anything out * of range becomes UQUAD_MAX. */ u_quad_t __fixunsdfdi(x) double x; { double toppart; union uu t; if (x < 0) return (UQUAD_MAX); /* ??? should be 0? ERANGE??? */ #ifdef notdef /* this falls afoul of a GCC bug */ if (x >= UQUAD_MAX) return (UQUAD_MAX); #else /* so we wire in 2^64-1 instead */ if (x >= 18446744073709551615.0) return (UQUAD_MAX); #endif /* * Get the upper part of the result. Note that the divide * may round up; we want to avoid this if possible, so we * subtract `1/2' first. */ toppart = (x - ONE_HALF) / ONE; /* * Now build a u_quad_t out of the top part. The difference * between x and this is the bottom part (this may introduce * a few fuzzy bits, but what the heck). With any luck this * difference will be nonnegative: x should wind up in the * range [0..ULONG_MAX]. For paranoia, we assume [LONG_MIN.. * 2*ULONG_MAX] instead. */ t.ul[H] = (unsigned long)toppart; t.ul[L] = 0; x -= (double)t.uq; if (x < 0) { t.ul[H]--; x += ULONG_MAX; } if (x > ULONG_MAX) { t.ul[H]++; x -= ULONG_MAX; } t.ul[L] = (u_long)x; return (t.uq); }
mohammadhamad/mhh
contrib/libc-28a76ac905060290c2c7a744a771b6c018b21434/src/lib/libc/lib/libc/quad/fixunsdfdi.c
C
gpl-2.0
3,393
<?PHP require_once "nxheader.inc.php"; // Get the Google Maps API-Key $apikey = $cds->content->get("Google-API-Key"); // Create the Maps-API. The apikey is passed as parameter. $maps = $cds->plugins->getApi("Google Maps API", $apikey); $cds->layout->addToHeader($maps->printGoogleJS()); require_once $cds->path."inc/header.php"; $headline = $cds->content->get("Headline"); $body = $cds->content->get("Body"); if ($headline != "") { echo '<h1>'.$headline.'</h1>'; br(); } if ($body !="") { echo $cds->content->get("Body"); br(); } br(); if ($sma != 1) { // add a point to the map $maps->addAddress($cds->content->get("Address"), $cds->content->get("Address Description")); // setup width and height and zoom factor (0-17) $maps->setWidth(600); $maps->setHeight(450); $maps->zoomLevel = 2; // setup controls $maps->showControl = $cds->content->get("ShowControls"); // draw the map. $maps->showMap(); } else { echo "Address: ".$cds->content->get("Address"); br(); echo "Address Description: ".$cds->content->get("Address Description"); } require_once $cds->path."inc/footer.php"; require_once "nxfooter.inc.php"; ?>
sweih/nxr
wwwdev/map.php
PHP
gpl-2.0
1,192
<?php /** * @package Joomla * @subpackage com_morfeoshow * @copyright Copyright (C) Vamba & Matthew Thomson. All rights reserved. * @license GNU/GPL. * @author Vamba (.joomlaitalia.com) & Matthew Thomson (ignitejoomlaextensions.com) * @based on com_morfeoshow * @author Matthew Thomson (ignitejoomlaextensions.com) * Joomla! and com_morfeoshow are free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed they include or * are derivative of works licensed under the GNU General Public License or * other free or open source software licenses. */ defined( '_JEXEC' ) or die( 'Restricted access' ); ?> <form action="index.php" method="post" name="adminForm" id="adminForm"> <fieldset class="adminform"> <legend><?php echo JText::_( 'Edit images description' ); ?></legend> <table class="admintable" cellpadding="5" cellspacing="0" border="0" "> <tr> <td> &nbsp; </td> <td> <img src="../images/morfeoshow/<?php echo $row->folder . '/thumbs/' . $img_row->filename; ?>" /> </td> </tr> <tr> <td width="100" align="right" class="key"> <?php echo JText::_( 'Title' ); ?> </td> <td> <input class="text_area" type="text" name="title" id="title" size="40" value="<?php echo htmlspecialchars($img_row->title, ENT_QUOTES, 'UTF-8'); ?>" /> </td> </tr> <tr> <td width="100" align="right" class="key"> <?php echo JText::_( 'Date' ); ?> </td> <td><?php echo JHTML::_('calendar', $img_row->imgdate, 'imgdate', 'imgdate', '%Y-%m-%d ', array('class'=>'inputbox', 'size'=>'25', 'maxlength'=>'19')); ?></td> </tr> <td width="100" align="right" class="key"> <?php echo JText::_( 'Description' ); ?> </td> <td> <?php echo $editor->display( 'html', $img_row->html ,'100%', '150', '40', '5', array('pagebreak', 'readmore', 'image') );?> </td> </tr> <tr> <td width="100" align="right" class="key"> <?php echo JText::_( 'Creator' ); ?> </td> <td> <input class="text_area" type="text" name="creator" id="creator" size="40" value="<?php echo $img_row->creator ?>" /> </td> </tr> <tr> <td width="100" align="right" class="key"> <?php echo JText::_( 'Web Site Link' ); ?> </td> <td> <input class="text_area" type="text" name="link" id="link" size="80" value="<?php echo $img_row->link ?>" /> </td> </tr> </table> </fieldset> <input type="hidden" name="folder" value="<?php echo $row->folder; ?>" /> <input type="hidden" name="task" value="" /> <input type="hidden" name="option" value="<?php echo $option ?>" /> <input type="hidden" name="cid" value="<?php echo $id ?>" /> <input type="hidden" name="id" value="<?php echo $img_row->id; ?>" /> </form>
jcorrego/graduarte
administrator/components/com_morfeoshow/view/editphoto.php
PHP
gpl-2.0
2,901
<?php /* ** ZABBIX ** Copyright (C) 2000-2005 SIA Zabbix ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. **/ ?> <?php class CTriggersInfo extends CTable { /* var $style; var $show_header; var $nodeid;*/ function CTriggersInfo($style = STYLE_HORISONTAL) { $this->style = null; parent::CTable(NULL,"triggers_info"); $this->SetOrientation($style); $this->show_header = true; $this->nodeid = get_current_nodeid(); } function SetOrientation($value) { if($value != STYLE_HORISONTAL && $value != STYLE_VERTICAL) return $this->error("Incorrect value for SetOrientation [$value]"); $this->style = $value; } function SetNodeid($nodeid) { $this->nodeid = (int)$nodeid; } function HideHeader() { $this->show_header = false; } function BodyToString() { global $USER_DETAILS; $this->CleanItems(); $ok = $uncn = $info = $warn = $avg = $high = $dis = 0; $db_priority = DBselect("select t.priority,t.value,count(*) as cnt from triggers t,hosts h,hosts_groups hg,items i,functions f". " where t.status=".TRIGGER_STATUS_ENABLED." and f.itemid=i.itemid ". " and h.hostid=i.hostid and h.status=".HOST_STATUS_MONITORED." and t.triggerid=f.triggerid ". " and i.status=".ITEM_STATUS_ACTIVE. ' and hg.hostid=h.hostid and hg.groupid in ('.get_accessible_groups_by_user($USER_DETAILS,PERM_READ_ONLY, null, null, $this->nodeid).') '. " group by priority,t.value"); while($row=DBfetch($db_priority)) { switch($row["value"]) { case TRIGGER_VALUE_TRUE: switch($row["priority"]) { case 1: $info += $row["cnt"]; break; case 2: $warn += $row["cnt"]; break; case 3: $avg += $row["cnt"]; break; case 4: $high += $row["cnt"]; break; case 5: $dis += $row["cnt"]; break; default: $uncn += $row["cnt"]; break; } break; case TRIGGER_VALUE_FALSE: $ok += $row["cnt"]; break; default: $uncn += $row["cnt"]; break; } } if($this->show_header) { $header = new CCol(S_TRIGGERS_INFO,"header"); if($this->style == STYLE_HORISONTAL) $header->SetColspan(7); $this->AddRow($header); } $trok = new CCol($ok.SPACE.S_OK, "normal"); $uncn = new CCol($uncn.SPACE.S_NOT_CLASSIFIED,"unknown"); $info = new CCol($info.SPACE.S_INFORMATION, "information"); $warn = new CCol($warn.SPACE.S_WARNING, "warning"); $avg = new CCol($avg.SPACE.S_AVERAGE, "average"); $high = new CCol($high.SPACE.S_HIGH, "high"); $dis = new CCol($dis.SPACE.S_DISASTER, "disaster"); if($this->style == STYLE_HORISONTAL) { $this->AddRow(array($trok, $uncn, $info, $warn, $avg, $high, $dis)); } else { $this->AddRow($trok); $this->AddRow($uncn); $this->AddRow($info); $this->AddRow($warn); $this->AddRow($avg); $this->AddRow($high); $this->AddRow($dis); } return parent::BodyToString(); } } ?>
Shmuma/z
frontends/php/include/classes/ctriggerinfo.mod.php
PHP
gpl-2.0
3,613
import java.util.*; import java.util.regex.*; import java.text.*; import java.math.*; import java.awt.geom.*; public class SimpleWordGame { public int points(String[] player, String[] dictionary) { Set<String> wrds = new HashSet<String>(); Set<String> dict = new HashSet<String>(); for(int i = 0; i < player.length; i++) wrds.add(player[i]); for(int i = 0; i < dictionary.length; i++) dict.add(dictionary[i]); int ans = 0; Iterator<String> iterator = wrds.iterator(); while(iterator.hasNext()) { String ele = iterator.next(); if(dict.contains(ele)) ans += ele.length() * ele.length(); } return ans; } public static void main(String[] args) { long time; int answer; boolean errors = false; int desiredAnswer; time = System.currentTimeMillis(); answer = new SimpleWordGame().points(new String[]{ "apple", "orange", "strawberry" }, new String[]{ "strawberry", "orange", "grapefruit", "watermelon" }); System.out.println("Time: " + (System.currentTimeMillis()-time)/1000.0 + " seconds"); desiredAnswer = 136; System.out.println("Your answer:"); System.out.println("\t" + answer); System.out.println("Desired answer:"); System.out.println("\t" + desiredAnswer); if (answer != desiredAnswer) { errors = true; System.out.println("DOESN'T MATCH!!!!"); } else System.out.println("Match :-)"); System.out.println(); time = System.currentTimeMillis(); answer = new SimpleWordGame().points(new String[]{ "apple" }, new String[]{ "strawberry", "orange", "grapefruit", "watermelon" }); System.out.println("Time: " + (System.currentTimeMillis()-time)/1000.0 + " seconds"); desiredAnswer = 0; System.out.println("Your answer:"); System.out.println("\t" + answer); System.out.println("Desired answer:"); System.out.println("\t" + desiredAnswer); if (answer != desiredAnswer) { errors = true; System.out.println("DOESN'T MATCH!!!!"); } else System.out.println("Match :-)"); System.out.println(); time = System.currentTimeMillis(); answer = new SimpleWordGame().points(new String[]{ "orange", "orange" }, new String[]{ "strawberry", "orange", "grapefruit", "watermelon" }); System.out.println("Time: " + (System.currentTimeMillis()-time)/1000.0 + " seconds"); desiredAnswer = 36; System.out.println("Your answer:"); System.out.println("\t" + answer); System.out.println("Desired answer:"); System.out.println("\t" + desiredAnswer); if (answer != desiredAnswer) { errors = true; System.out.println("DOESN'T MATCH!!!!"); } else System.out.println("Match :-)"); System.out.println(); time = System.currentTimeMillis(); answer = new SimpleWordGame().points(new String[]{ "lidi", "o", "lidi", "gnbewjzb", "kten", "ebnelff", "gptsvqx", "rkauxq", "rkauxq", "kfkcdn"}, new String[]{ "nava", "wk", "kfkcdn", "lidi", "gptsvqx", "ebnelff", "hgsppdezet", "ulf", "rkauxq", "wcicx"}); System.out.println("Time: " + (System.currentTimeMillis()-time)/1000.0 + " seconds"); desiredAnswer = 186; System.out.println("Your answer:"); System.out.println("\t" + answer); System.out.println("Desired answer:"); System.out.println("\t" + desiredAnswer); if (answer != desiredAnswer) { errors = true; System.out.println("DOESN'T MATCH!!!!"); } else System.out.println("Match :-)"); System.out.println(); if (errors) System.out.println("Some of the test cases had errors :-("); else System.out.println("You're a stud (at least on the test data)! :-D "); } } //Powered by [KawigiEdit] 2.0!
venkatesh551/TopCoder
older/SimpleWordGame.java
Java
gpl-2.0
3,588
<?php //-------------------------------------------------------------------- //- File : contact/mailing_lists.php //- Project : FVWM Home Page //- Programmer : Uwe Pross //-------------------------------------------------------------------- if(!isset($rel_path)) $rel_path = "./.."; //-------------------------------------------------------------------- // load some global definitions //-------------------------------------------------------------------- if(!isset($navigation_check)) include_once($rel_path.'/definitions.inc'); //-------------------------------------------------------------------- // Site definitions //-------------------------------------------------------------------- $title = "FVWM - Mailing Lists"; $heading = "FVWM - Mailing Lists"; $link_name = "Mailing Lists"; $link_picture = "pictures/icons/contact_mailing_list"; $parent_site = "top"; $child_sites = array(); $requested_file = basename(my_get_global("PHP_SELF", "SERVER")); $this_site = "mailing_lists"; //-------------------------------------------------------------------- // check if we should stop here //-------------------------------------------------------------------- if(isset($navigation_check)) return; //-------------------------------------------------------------------- // load the layout file //-------------------------------------------------------------------- if(!isset($site_has_been_loaded)) { $site_has_been_loaded = "true"; include_once(sec_filename("$layout_file")); exit(); } decoration_window_start("Mailing lists"); ?> <p> PLEASE ASK QUESTIONS RELATED TO XMMS ON THE XMMS MAILING LIST. See <a href="http://xmms.org/">http://xmms.org/</a>. </p> <h4>The mailing list addresses are:</h4> <ul> <li><a href="mailto:fvwm@fvwm.org">fvwm@fvwm.org</a> (Discussion and questions list)</li> <li><a href="mailto:fvwm-announce@fvwm.org">fvwm-announce@fvwm.org</a> (Announcement only list)</li> <li><a href="mailto:fvwm-workers@fvwm.org">fvwm-workers@fvwm.org</a> (Beta testers and contributors list)</li> </ul> <p> Please help us managing incoming mail by following a few rules when you write to any of the fvwm related mailing list: <ul> <li> When quoting previous mails in a discussion, please put your replies below the quoted portions of the text.</li> <li> Quote all relevant parts of the original mail in a reply. <li> Type about 66 to 72 characters per line.</li> <li> Insert line breaks manually, even if your email program does it for you.</li> <li> Always specify the fvwm version you use when asking questions or reporting problems.</li> </ul> </p> <p> They are maintained by Jason Tibbitts, and are Majordomo based mailing lists. To subscribe to a list, send "<code>subscribe</code>" in the body of a message to the appropriate <code>*-request</code> address. </p> <p> To unsubscribe from the list, send "<code>unsubscribe</code>" in the body of a message to the appropriate <code>*-request</code> address. </p> <h4>*-request addresses are:</h4> <p> <ul> <li> <a href="mailto:fvwm-request@fvwm.org">fvwm-request@fvwm.org</a></li> <li> <a href="mailto:fvwm-announce-request@fvwm.org">fvwm-announce-request@fvwm.org</a></li> <li> <a href="mailto:fvwm-workers-request@fvwm.org">fvwm-workers-request@fvwm.org</a></li> </ul> </p> <p> <strong>Subscription requests sent to the list will be ignored!</strong><br> Please follow the above instructions for subscribing properly. </p> <p> To report problems with any of the mailing lists, send mail to <a href="mailto:fvwm-owner@fvwm.org">fvwm-owner@fvwm.org</a>. </p> <p> Also the mailing lists are archived: <a href="http://www.mail-archive.com/fvwm@lists.math.uh.edu/">fvwm</a>, <a href="http://www.mail-archive.com/fvwm-workers@lists.math.uh.edu/">fvwm-workers</a>. </p> <p> <form method="GET" action="http://www.mail-archive.com/search"> <b>Search the fvwm mail archive: </b> <input type="text" value="" name="q" size="30"> <input type="hidden" name="num" value="100"> <input type="hidden" name="l" value="fvwm@lists.math.uh.edu"> <input type="submit" name="btnG" value="Search Archives"> </form> <p> <form method="GET" action="http://www.mail-archive.com/search"> <b>Search the fvwm workers mail archive: </b> <input type="text" value="" name="q" size="30"> <input type="hidden" name="num" value="100"> <input type="hidden" name="l" value="fvwm-workers@lists.math.uh.edu"> <input type="submit" name="btnG" value="Search Archives"> </form> <h4>IRC Channels</h4> <p> Several IRC channels are also available to discuss fvwm related topics or to get help. They are not official in a sense that the fvwm developers maintain them, but there is a chance to meet some of the developers there: </p> <ul> <li> #fvwm on freenode</li> <li> +fvwm.de on IRCnet (German channel)</li> </ul> <?php decoration_window_end(); ?>
ThomasAdam/fvwm-web
contact/index.php
PHP
gpl-2.0
5,170
/* $Id: tstMvWnd.cpp 44529 2013-02-04 15:54:15Z vboxsync $ */ /* * Copyright (C) 2010-2011 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #include <windows.h> #define Assert(_m) do {} while (0) #define vboxVDbgPrint(_m) do {} while (0) static LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { if(uMsg == WM_DESTROY) { PostQuitMessage(0); return 0; } // switch(uMsg) // { // case WM_CLOSE: // vboxVDbgPrint((__FUNCTION__": got WM_CLOSE for hwnd(0x%x)", hwnd)); // return 0; // case WM_DESTROY: // vboxVDbgPrint((__FUNCTION__": got WM_DESTROY for hwnd(0x%x)", hwnd)); // return 0; // case WM_NCHITTEST: // vboxVDbgPrint((__FUNCTION__": got WM_NCHITTEST for hwnd(0x%x)\n", hwnd)); // return HTNOWHERE; // } return DefWindowProc(hwnd, uMsg, wParam, lParam); } #define VBOXDISPWND_NAME L"tstMvWnd" HRESULT tstMvWndCreate(DWORD w, DWORD h, HWND *phWnd) { HRESULT hr = S_OK; HINSTANCE hInstance = (HINSTANCE)GetModuleHandle(NULL); /* Register the Window Class. */ WNDCLASS wc; if (!GetClassInfo(hInstance, VBOXDISPWND_NAME, &wc)) { wc.style = CS_OWNDC; wc.lpfnWndProc = WindowProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = NULL; wc.hCursor = NULL; wc.hbrBackground = NULL; wc.lpszMenuName = NULL; wc.lpszClassName = VBOXDISPWND_NAME; if (!RegisterClass(&wc)) { DWORD winErr = GetLastError(); vboxVDbgPrint((__FUNCTION__": RegisterClass failed, winErr(%d)\n", winErr)); hr = E_FAIL; } } if (hr == S_OK) { HWND hWnd = CreateWindowEx (0 /*WS_EX_CLIENTEDGE*/, VBOXDISPWND_NAME, VBOXDISPWND_NAME, WS_OVERLAPPEDWINDOW, 0, 0, w, h, GetDesktopWindow() /* hWndParent */, NULL /* hMenu */, hInstance, NULL /* lpParam */); Assert(hWnd); if (hWnd) { *phWnd = hWnd; } else { DWORD winErr = GetLastError(); vboxVDbgPrint((__FUNCTION__": CreateWindowEx failed, winErr(%d)\n", winErr)); hr = E_FAIL; } } return hr; } static int g_Width = 400; static int g_Height = 300; static DWORD WINAPI tstMvWndThread(void *pvUser) { HWND hWnd = (HWND)pvUser; RECT Rect; BOOL bRc = GetWindowRect(hWnd, &Rect); Assert(bRc); if (bRc) { bRc = SetWindowPos(hWnd, HWND_TOPMOST, 0, /* int X */ 0, /* int Y */ g_Width, //Rect.left - Rect.right, g_Height, //Rect.bottom - Rect.top, SWP_SHOWWINDOW); Assert(bRc); if (bRc) { int dX = 10, dY = 10; int xMin = 5, xMax = 300; int yMin = 5, yMax = 300; int x = dX, y = dY; do { bRc = SetWindowPos(hWnd, HWND_TOPMOST, x, /* int X */ y, /* int Y */ g_Width, //Rect.left - Rect.right, g_Height, //Rect.bottom - Rect.top, SWP_SHOWWINDOW); x += dX; if (x > xMax) x = xMin; y += dY; if (y > yMax) y = yMin; Sleep(5); } while(1); } } return 0; } int main(int argc, char **argv, char **envp) { HWND hWnd; HRESULT hr = tstMvWndCreate(200, 200, &hWnd); Assert(hr == S_OK); if (hr == S_OK) { HANDLE hThread = CreateThread( NULL /* LPSECURITY_ATTRIBUTES lpThreadAttributes */, 0 /* SIZE_T dwStackSize */, tstMvWndThread, hWnd, 0 /* DWORD dwCreationFlags */, NULL /* pThreadId */); Assert(hThread); if (hThread) { MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } } DestroyWindow (hWnd); } return 0; } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // NOREF(hInstance); NOREF(hPrevInstance); NOREF(lpCmdLine); NOREF(nCmdShow); return main(__argc, __argv, environ); }
carmark/vbox
src/VBox/Additions/WINNT/Graphics/Video/disp/wddm/dbg/tstMvWnd.cpp
C++
gpl-2.0
5,327
<?php /** * Logique des tâches * * PHP versions 5 * * LODEL - Logiciel d'Edition ELectronique. * * Home page: http://www.lodel.org * E-Mail: lodel@lodel.org * * All Rights Reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * @package lodel/logic * @author Ghislain Picard * @author Jean Lamy * @author Pierre-Alain Mignot * @copyright 2001-2002, Ghislain Picard, Marin Dacos * @copyright 2003, Ghislain Picard, Marin Dacos, Luc Santeramo, Nicolas Nutten, Anne Gentil-Beccot * @copyright 2004, Ghislain Picard, Marin Dacos, Luc Santeramo, Anne Gentil-Beccot, Bruno Cénou * @copyright 2005, Ghislain Picard, Marin Dacos, Luc Santeramo, Gautier Poupeau, Jean Lamy, Bruno Cénou * @copyright 2006, Marin Dacos, Luc Santeramo, Bruno Cénou, Jean Lamy, Mikaël Cixous, Sophie Malafosse * @copyright 2007, Marin Dacos, Bruno Cénou, Sophie Malafosse, Pierre-Alain Mignot * @copyright 2008, Marin Dacos, Bruno Cénou, Pierre-Alain Mignot, Inès Secondat de Montesquieu, Jean-François Rivière * @copyright 2009, Marin Dacos, Bruno Cénou, Pierre-Alain Mignot, Inès Secondat de Montesquieu, Jean-François Rivière * @licence http://www.gnu.org/copyleft/gpl.html * @since Fichier ajouté depuis la version 0.8 * @version CVS:$Id$ */ /** * Classe de logique des tâches * * @package lodel/logic * @author Ghislain Picard * @author Jean Lamy * @copyright 2001-2002, Ghislain Picard, Marin Dacos * @copyright 2003, Ghislain Picard, Marin Dacos, Luc Santeramo, Nicolas Nutten, Anne Gentil-Beccot * @copyright 2004, Ghislain Picard, Marin Dacos, Luc Santeramo, Anne Gentil-Beccot, Bruno Cénou * @copyright 2005, Ghislain Picard, Marin Dacos, Luc Santeramo, Gautier Poupeau, Jean Lamy, Bruno Cénou * @copyright 2006, Marin Dacos, Luc Santeramo, Bruno Cénou, Jean Lamy, Mikaël Cixous, Sophie Malafosse * @copyright 2007, Marin Dacos, Bruno Cénou, Sophie Malafosse, Pierre-Alain Mignot * @copyright 2008, Marin Dacos, Bruno Cénou, Pierre-Alain Mignot, Inès Secondat de Montesquieu, Jean-François Rivière * @copyright 2009, Marin Dacos, Bruno Cénou, Pierre-Alain Mignot, Inès Secondat de Montesquieu, Jean-François Rivière * @licence http://www.gnu.org/copyleft/gpl.html * @since Classe ajouté depuis la version 0.8 * @see logic.php */ class TasksLogic extends Logic { /** * generic equivalent assoc array */ public $g_name; /** Constructor */ public function __construct() { parent::__construct("tasks"); } /** * Affichage d'un objet * * @param array &$context le contexte passé par référence * @param array &$error le tableau des erreurs éventuelles passé par référence */ public function viewAction(&$context,&$error) { trigger_error("TasksLogic::viewAction", E_USER_ERROR); } /** * Changement du rang d'un objet * * @param array &$context le contexte passé par référence * @param array &$error le tableau des erreurs éventuelles passé par référence */ public function changeRankAction(&$context, &$error, $groupfields = "", $status = "status>0") { trigger_error("TasksLogic::changeRankAction", E_USER_ERROR); } /** * add/edit Action */ public function editAction(&$context,&$error, $clean=false) { trigger_error("TasksLogic::editAction", E_USER_ERROR); } /*---------------------------------------------------------------*/ //! Private or protected from this point /** * @private */ /** * Indique si un objet est protégé en suppression * * Cette méthode indique si un objet, identifié par son identifiant numérique et * éventuellement son status, ne peut pas être supprimé. Dans le cas où un objet ne serait * pas supprimable un message est retourné indiquant la cause. Sinon la méthode renvoit le * booleen false. * * @param integer $id identifiant de l'objet * @param integer $status status de l'objet * @return false si l'objet n'est pas protégé en suppression, un message sinon */ public function isdeletelocked($id,$status=0) { $id = (int)$id; // basic check. Should be more advanced because of the potential conflict between // adminlodel adn othe rusers $vo=$this->_getMainTableDAO()->find("id='".$id."' AND user='".C::get('id', 'lodeluser')."'","id"); return $vo->id ? false : true ; } // begin{publicfields} automatic generation // /** * Retourne la liste des champs publics * @access private */ protected function _publicfields() { return array(); } // end{publicfields} automatic generation // // begin{uniquefields} automatic generation // // end{uniquefields} automatic generation // } // class
charlycoste/lodel-old
lodel/scripts/logic/class.tasks.php
PHP
gpl-2.0
5,266
<?php namespace PaLogic\Bundle\UserBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class PaLogicUserBundle extends Bundle { public function getParent() { return 'FOSUserBundle'; // Name of parent bundle } }
71m024/palogic
src/PaLogic/Bundle/UserBundle/PaLogicUserBundle.php
PHP
gpl-2.0
238
/* * Copyright (C) 2006, 2008 Thomas Zander <zander@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "GroupShape.h" #include <KoShapeFactory.h> #include <KoCreateShapesTool.h> #include <QDomElement> GroupShape::GroupShape(KoShapeFactory *shapeFactory) : IconShape(shapeFactory->icon()) { m_shapeFactory = shapeFactory; } void GroupShape::visit(KoCreateShapesTool *tool) { tool->setShapeId(m_shapeFactory->id()); tool->setShapeProperties(0); } QString GroupShape::toolTip() { return m_shapeFactory->toolTip(); } QString GroupShape::groupId() const { return m_shapeFactory->id(); } void GroupShape::save(QDomElement &root) { Q_UNUSED(root); }
JeremiasE/KFormula
plugins/dockers/shapeselector/GroupShape.cpp
C++
gpl-2.0
1,427
@(content: Html, title: String, description: String, _navBar: Html, article: Option[Article] = None) @import views.html.partials._ @import play._ <!DOCTYPE html> <html> <head> @header(title, description, article) <link rel="stylesheet" media="screen" href="/assets/css/iframe.min.css"> </head> <body> @facebookSdk() <div class="navbar navbar-default navbar-fixed-top" role="navigation"> @_navBar </div> @content </body> </html>
SunriseSoftVN/hayhayblog
app/views/tml/iframe.scala.html
HTML
gpl-2.0
447
/* * drivers/media/video/exynos/fimc-is-mc2/fimc-is-interface.h * * Copyright (c) 2011 Samsung Electronics Co., Ltd. * http://www.samsung.com * * The header file related to camera * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifndef FIMC_IS_INTERFACE_H #define FIMC_IS_INTERFACE_H #ifdef CONFIG_ENABLE_HAL3_2_META_INTERFACE #include "include/fimc-is-metadata.h" #else #include "fimc-is-metadata-legacy.h" #endif #include "fimc-is-framemgr.h" #include "fimc-is-video.h" #include "fimc-is-time.h" #include "include/fimc-is-cmd.h" /*#define TRACE_WORK*/ /* cam_ctrl : 1 shot : 2 */ #define TRACE_WORK_ID_CAMCTRL 0x0001 #define TRACE_WORK_ID_GENERAL 0x0002 #define TRACE_WORK_ID_SHOT 0x0004 #define TRACE_WORK_ID_30C 0x0008 #define TRACE_WORK_ID_30P 0x0010 #define TRACE_WORK_ID_31C 0x0020 #define TRACE_WORK_ID_31P 0x0040 #define TRACE_WORK_ID_I0C 0x0080 #define TRACE_WORK_ID_I0P 0x0100 #define TRACE_WORK_ID_I1C 0x0200 #define TRACE_WORK_ID_I1P 0x0400 #define TRACE_WORK_ID_SCC 0x0800 #define TRACE_WORK_ID_SCP 0x1000 #define TRACE_WORK_ID_MASK 0x1FFF #define MAX_NBLOCKING_COUNT 3 #define MAX_WORK_COUNT 10 #ifdef SEC_CAMERA_TRY_TIMEOUT_COUNT #define TRY_TIMEOUT_COUNT SEC_CAMERA_TRY_TIMEOUT_COUNT #else #define TRY_TIMEOUT_COUNT 3 #endif #define TRY_RECV_AWARE_COUNT 100 #define LOWBIT_OF(num) (num >= 32 ? 0 : (u32)1<<num) #define HIGHBIT_OF(num) (num >= 32 ? (u32)1<<(num-32) : 0) enum fimc_is_interface_state { IS_IF_STATE_OPEN, IS_IF_STATE_READY, IS_IF_STATE_START, IS_IF_STATE_BUSY, IS_IF_STATE_LOGGING }; enum interrupt_map { INTR_GENERAL, INTR_SHOT_DONE, INTR_30C_FDONE, INTR_30P_FDONE, INTR_31C_FDONE, INTR_31P_FDONE, INTR_I0X_FDONE, INTR_I1X_FDONE, INTR_SCX_FDONE, INTR_MAX_MAP }; enum work_map { WORK_GENERAL, WORK_SHOT_DONE, WORK_30C_FDONE, WORK_30P_FDONE, WORK_31C_FDONE, WORK_31P_FDONE, WORK_I0C_FDONE, WORK_I0P_FDONE, WORK_I1C_FDONE, WORK_I1P_FDONE, WORK_SCC_FDONE, WORK_SCP_FDONE, WORK_MAX_MAP }; enum streaming_state { IS_IF_STREAMING_INIT, IS_IF_STREAMING_OFF, IS_IF_STREAMING_ON }; enum processing_state { IS_IF_PROCESSING_INIT, IS_IF_PROCESSING_OFF, IS_IF_PROCESSING_ON }; enum pdown_ready_state { IS_IF_POWER_DOWN_READY, IS_IF_POWER_DOWN_NREADY }; enum fw_boot_state { IS_IF_RESUME, IS_IF_SUSPEND, }; enum fimc_is_fw_boot { FIRST_LAUNCHING, WARM_BOOT, COLD_BOOT, }; struct fimc_is_msg { u32 id; u32 command; u32 instance; u32 group; u32 param1; u32 param2; u32 param3; u32 param4; }; struct fimc_is_work { struct list_head list; struct fimc_is_msg msg; u32 fcount; struct fimc_is_frame *frame; }; struct fimc_is_work_list { u32 id; struct fimc_is_work work[MAX_WORK_COUNT]; spinlock_t slock_free; spinlock_t slock_request; struct list_head work_free_head; u32 work_free_cnt; struct list_head work_request_head; u32 work_request_cnt; wait_queue_head_t wait_queue; }; struct fimc_is_interface { void __iomem *regs; struct is_common_reg __iomem *com_regs; unsigned long state; spinlock_t process_barrier; struct fimc_is_msg process_msg; struct mutex request_barrier; struct fimc_is_msg request_msg; atomic_t lock_pid; wait_queue_head_t lock_wait_queue; wait_queue_head_t init_wait_queue; wait_queue_head_t idle_wait_queue; struct fimc_is_msg reply; #ifdef MEASURE_TIME #ifdef INTERFACE_TIME struct fimc_is_interface_time time[HIC_COMMAND_END]; #endif #endif struct workqueue_struct *workqueue; struct work_struct work_wq[WORK_MAX_MAP]; struct fimc_is_work_list work_list[WORK_MAX_MAP]; /* sensor streaming flag */ enum streaming_state streaming[FIMC_IS_STREAM_COUNT]; /* firmware processing flag */ enum processing_state processing[FIMC_IS_STREAM_COUNT]; /* frrmware power down ready flag */ enum pdown_ready_state pdown_ready; unsigned long fw_boot; struct fimc_is_framemgr *framemgr; struct fimc_is_work_list nblk_cam_ctrl; /* shot timeout check */ spinlock_t shot_check_lock; atomic_t shot_check[FIMC_IS_STREAM_COUNT]; atomic_t shot_timeout[FIMC_IS_STREAM_COUNT]; /* sensor timeout check */ atomic_t sensor_check[FIMC_IS_STREAM_COUNT]; atomic_t sensor_timeout[FIMC_IS_STREAM_COUNT]; struct timer_list timer; /* callback func to handle error report for specific purpose */ void *err_report_data; int (*err_report_vendor)(void *data, u32 err_report_type); struct camera2_uctl isp_peri_ctl; /* check firsttime */ bool first_launch; ulong itf_kvaddr; void *core; }; int fimc_is_interface_probe(struct fimc_is_interface *this, struct fimc_is_minfo *minfo, ulong regs, u32 irq, void *core_data); int fimc_is_interface_open(struct fimc_is_interface *this); int fimc_is_interface_close(struct fimc_is_interface *this); void fimc_is_interface_lock(struct fimc_is_interface *this); void fimc_is_interface_unlock(struct fimc_is_interface *this); void fimc_is_interface_reset(struct fimc_is_interface *this); void fimc_is_storefirm(struct fimc_is_interface *this); void fimc_is_restorefirm(struct fimc_is_interface *this); int fimc_is_set_fwboot(struct fimc_is_interface *this, int val); /*for debugging*/ int print_fre_work_list(struct fimc_is_work_list *this); int print_req_work_list(struct fimc_is_work_list *this); int fimc_is_hw_logdump(struct fimc_is_interface *this); int fimc_is_hw_regdump(struct fimc_is_interface *this); int fimc_is_hw_memdump(struct fimc_is_interface *this, ulong start, ulong end); int fimc_is_hw_enum(struct fimc_is_interface *this); int fimc_is_hw_fault(struct fimc_is_interface *this); int fimc_is_hw_open(struct fimc_is_interface *this, u32 instance, u32 module, u32 info, u32 path, u32 flag, u32 *mwidth, u32 *mheight); int fimc_is_hw_close(struct fimc_is_interface *this, u32 instance); int fimc_is_hw_saddr(struct fimc_is_interface *interface, u32 instance, u32 *setfile_addr); int fimc_is_hw_setfile(struct fimc_is_interface *interface, u32 instance); int fimc_is_hw_process_on(struct fimc_is_interface *this, u32 instance, u32 group); int fimc_is_hw_process_off(struct fimc_is_interface *this, u32 instance, u32 group, u32 mode); int fimc_is_hw_stream_on(struct fimc_is_interface *interface, u32 instance); int fimc_is_hw_stream_off(struct fimc_is_interface *interface, u32 instance); int fimc_is_hw_s_param(struct fimc_is_interface *interface, u32 instance, u32 lindex, u32 hindex, u32 indexes); int fimc_is_hw_a_param(struct fimc_is_interface *this, u32 instance, u32 group, u32 sub_mode); int fimc_is_hw_g_capability(struct fimc_is_interface *this, u32 instance, u32 address); int fimc_is_hw_map(struct fimc_is_interface *this, u32 instance, u32 group, u32 address, u32 size); int fimc_is_hw_unmap(struct fimc_is_interface *this, u32 instance, u32 group); int fimc_is_hw_power_down(struct fimc_is_interface *interface, u32 instance); int fimc_is_hw_i2c_lock(struct fimc_is_interface *interface, u32 instance, int clk, bool lock); int fimc_is_hw_sys_ctl(struct fimc_is_interface *this, u32 instance, int cmd, int val); int fimc_is_hw_sensor_mode(struct fimc_is_interface *this, u32 instance, int cfg); int fimc_is_hw_shot_nblk(struct fimc_is_interface *this, u32 instance, u32 group, u32 shot, u32 fcount, u32 rcount); int fimc_is_hw_s_camctrl_nblk(struct fimc_is_interface *this, u32 instance, u32 address, u32 fcount); int fimc_is_hw_msg_test(struct fimc_is_interface *this, u32 sync_id, u32 msg_test_id); /* func to register error report callback */ int fimc_is_set_err_report_vendor(struct fimc_is_interface *itf, void *err_report_data, int (*err_report_vendor)(void *data, u32 err_report_type)); #endif
aapav01/android_kernel_samsung_j7elte
drivers/media/platform/exynos/fimc-is2/fimc-is-interface.h
C
gpl-2.0
7,764
/* * Stylesheet for the front-end display of the custom columns (user-view) * Updated version of plugin styles (compatible up to version 4.3.1 of Visual Composer) */ .vc_responsive .wpb_row .vc_1\/5, .vc_responsive .wpb_row .1\/5 { position: relative; min-height: 1px; padding-left: 15px; padding-right: 15px; box-sizing: border-box; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; } .vc_responsive .wpb_row .vc_2\/5, .vc_responsive .wpb_row .2\/5 { position: relative; min-height: 1px; padding-left: 15px; padding-right: 15px; box-sizing: border-box; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; } .vc_responsive .wpb_row .vc_3\/5, .vc_responsive .wpb_row .3\/5 { position: relative; min-height: 1px; padding-left: 15px; padding-right: 15px; box-sizing: border-box; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; } .vc_responsive .wpb_row .vc_4\/5, .vc_responsive .wpb_row .4\/5 { position: relative; min-height: 1px; padding-left: 15px; padding-right: 15px; box-sizing: border-box; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; } @media (min-width: 768px) { .vc_responsive .wpb_row .vc_1\/5, .vc_responsive .wpb_row .1\/5 { float: left; width: 20%; } .vc_responsive .wpb_row .vc_2\/5, .vc_responsive .wpb_row .2\/5 { float: left; width: 40%; } .vc_responsive .wpb_row .vc_3\/5, .vc_responsive .wpb_row .3\/5 { float: left; width: 60%; } .vc_responsive .wpb_row .vc_4\/5, .vc_responsive .wpb_row .4\/5 { float: left; width: 80%; } }
javalidigital/suprema
wp-content/plugins/custom-vc-column-layout/custom_vc_layout.css
CSS
gpl-2.0
1,606
package test_util ; use strict; use warnings; use Cwd; use Sys::Hostname; { require Exporter; use vars qw(@ISA @EXPORT @EXPORT_OK); @ISA = qw(Exporter); @EXPORT = (); @EXPORT_OK = qw(gen_config_file gen_wanted write_to_file); } use vars qw($test_config_file $test_ignore_file %test_config @test_roles $test_hostname); use vars qw($TEST_TMPDIR); push @EXPORT, qw($test_config_file $test_ignore_file %test_config @test_roles $test_hostname); # Because all the scripts chdir('/'), we need to know the cwd for our configs my $TEST_DIR = getcwd; $TEST_TMPDIR = $ENV{TEST_TMPDIR}; $test_hostname = hostname; $test_config_file = "$TEST_TMPDIR/slack.conf"; $test_ignore_file = "$TEST_TMPDIR/slackignore"; %test_config = ( 'source' => "$TEST_DIR/testsource", 'role-list' => "$TEST_TMPDIR/roles.conf", 'cache' => "$TEST_TMPDIR/cache", 'stage' => "$TEST_TMPDIR/stage", 'root' => "$TEST_TMPDIR/root", 'backup-dir' => "$TEST_TMPDIR/backups", 'verbose' => 0, ); @test_roles = sort qw(role1 role2.sub role3.sub.sub); sub gen_config_file ($$) { my ($template_file, $file) = @_; open(TEMPLATE, "<", "$template_file") or die "Could not open template file $template_file: $!"; open(FILE, ">", $file) or die "Could not open output file $file: $!"; while(<TEMPLATE>) { s/__TEST_DIR__/$TEST_DIR/g; s/__TEST_TMPDIR__/$TEST_TMPDIR/g; s/__HOSTNAME__/$test_hostname/g; s/__ROLES__/join(" ", @test_roles)/ge; print FILE; } close(TEMPLATE) or die "Could not close template file $template_file: $!"; close(FILE) or die "Could not close output file $file: $!"; } # Transform globs into regexes, since I can't find a function to check # glob matches on strings. sub glob_to_regex ($) { my ($pat) = @_; $pat =~ s#/$##; # strip trailing slashes $pat =~ s#([./^\$()+])#\\$1#g; # escape re metachars $pat =~ s#([?*])#.$1#g; # convert glob metachars return qr(\A$pat\z); } # This is to help with comparing lists of files in two directory trees. # # Returns a wanted function for File::Find which will maintain a file list # in a hash that looks like: # filename => filetype # where valid filetypes are: # d directory # f regular file # x executable file # - unknown # and which will skip files rsync is known to skip. # Symlinks are dereferenced because that's what we tell rsync to do, too. # # Takes as arguments a basename which will be stripped off file names # and a hash reference (in which to maintain the file list above) sub gen_wanted ($$) { my ($base, $hashref) = @_; my @cvs_exclude; { # Suppress spurious warning about the # and , characters below no warnings; # Straight out of the rsync manpage section for --cvs-exclude # which is now in /etc/slack/slackignore to allow customization @cvs_exclude = qw( RCS SCCS CVS CVS.adm RCSLOG cvslog.* tags TAGS .make.state .nse_depinfo *~ #* .#* ,* _$* *$ *.old *.bak *.BAK *.orig *.rej .del-* *.a *.olb *.o *.obj *.so *.exe *.Z *.elc *.ln core .svn/ .git/ .hg/ .bzr/ ); } @cvs_exclude = map {glob_to_regex($_)} @cvs_exclude; return sub { # Prune out files in the CVS exclude list used by rsync for my $pat (@cvs_exclude) { if (m/$pat/) { $File::Find::prune = 1; return; } } my $filetype = '-'; if (-f) { if (-x _) { $filetype = 'x'; } else { $filetype = 'f'; } } elsif (-d _) { $filetype = 'd'; } my $filename = $File::Find::name; # Try to strip off the base return unless ($filename =~ s#^$base/##); $hashref->{$filename} = $filetype; }; } sub write_to_file ($$) { my ($file, $text) = @_; my $fh; open($fh, '>', $file) or die "Could not open $file for writing: $!"; print $fh $text or die "Could not write to $file: $!"; close($fh) or die "Could not close $file: $!"; } 1;
jeviolle/slack
test/test_util.pm
Perl
gpl-2.0
4,251
<?php //====================================================== // Copyright (C) 2006 Claudio Redaelli, All Rights Reserved // // This file is part of the Unit Command Climate // Assessment and Survey System (UCCASS) // // UCCASS is free software; you can redistribute it and/or // modify it under the terms of the Affero General Public License as // published by Affero, Inc.; either version 1 of the License, or // (at your option) any later version. // // http://www.affero.org/oagpl.html // // UCCASS is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // Affero General Public License for more details. //====================================================== include('classes/main.class.php'); include('classes/special_results.class.php'); include('classes/spss_results.class.php'); $survey = new UCCASS_SPSS_Results(@$_REQUEST['sid'], @$_REQUEST['sep'], @$_REQUEST['del'], @$_REQUEST['altdel'], @$_REQUEST['text'], @$_REQUEST['altcr'], @$_REQUEST['order']); echo $survey->getData(); ?>
nishad/uccass
results_spss.php
PHP
gpl-2.0
1,125
import data from './data.json'; import * as F2 from '../../../../src/index'; // 兼容之前的pinch和pan import '../../../../src/interaction/index'; import Pan from '../../../../src/interaction/pan'; import Pinch from '../../../../src/interaction/pinch'; const canvas = document.createElement('canvas'); canvas.width = 500; canvas.height = 500; document.body.appendChild(canvas); const chart = new F2.Chart({ el: canvas, pixelRatio: window.devicePixelRatio }); chart.source(data, { reportDate: { type: 'timeCat', tickCount: 3, range: [ 0, 1 ], mask: 'YYYY-MM-DD' }, rate: { tickCount: 5 } }); chart.line() .position('reportDate*rate') .color('name'); describe('Interaction', () => { it('contructor compatible', () => { expect(F2.Chart._Interactions.pan).toBe(Pan); expect(F2.Chart._Interactions.pinch).toBe(Pinch); }); it('instance compatible', () => { chart.interaction('pan'); chart.interaction('pinch'); chart.render(); expect(chart._interactions.pan).toBeInstanceOf(Pan); expect(chart._interactions.pinch).toBeInstanceOf(Pinch); }); });
antvis/g2-mobile
test/unit/interaction/new/compatible-spec.js
JavaScript
gpl-2.0
1,124
#-*- coding: utf-8 -*- from openerp.osv import fields, osv class partner_add_contact(osv.osv_memory): _name = "partner.add.contact" _columns = { "name": fields.char("Nom", size=128, required=True), "partner_id": fields.many2one("res.partner", u"Partenaire associé"), "firstname": fields.char("Prénom", size=128, required=True), "phone": fields.char(u"Numéro de téléphone", size=30), "mobile": fields.char(u"Téléphone portable"), "email": fields.char("Email", size=128), "position": fields.char(u"Fonction dans l'entreprise", size=128), 'civilite': fields.selection([('mr', 'Monsieur'),('mme', 'Madame'),('mlle','Mademoiselle')], u'Civilité'), } def set_contact(self, cr, uid, ids, context=None): obj = self.browse(cr, uid, ids[0], context=context) vals = { "name": obj.name, "partner_id": obj.partner_id.id, "firstname": obj.firstname, "phone": obj.phone, "mobile": obj.mobile, "email": obj.email, "position": obj.position, "civilite": obj.civilite } return self.pool.get('magellanes.contact').create(cr, uid, vals, context)
ATSTI/administra
open_corretora/brokerage/wizard/partner_add_contact.py
Python
gpl-2.0
1,249
/* $Id$ */ /* * This file is part of OpenTTD. * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2. * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>. */ /** @file sound.cpp Handling of playing sounds. */ #include "stdafx.h" #include "landscape.h" #include "mixer.h" #include "newgrf_sound.h" #include "fios.h" #include "window_gui.h" #include "vehicle_base.h" /* The type of set we're replacing */ #define SET_TYPE "sounds" #include "base_media_func.h" static SoundEntry _original_sounds[ORIGINAL_SAMPLE_COUNT]; static void OpenBankFile(const char *filename) { memset(_original_sounds, 0, sizeof(_original_sounds)); /* If there is no sound file (nosound set), don't load anything */ if (filename == NULL) return; FioOpenFile(SOUND_SLOT, filename); size_t pos = FioGetPos(); uint count = FioReadDword(); /* The new format has the highest bit always set */ bool new_format = HasBit(count, 31); ClrBit(count, 31); count /= 8; /* Simple check for the correct number of original sounds. */ if (count != ORIGINAL_SAMPLE_COUNT) { /* Corrupt sample data? Just leave the allocated memory as those tell * there is no sound to play (size = 0 due to calloc). Not allocating * the memory disables valid NewGRFs that replace sounds. */ DEBUG(misc, 6, "Incorrect number of sounds in '%s', ignoring.", filename); return; } FioSeekTo(pos, SEEK_SET); for (uint i = 0; i != ORIGINAL_SAMPLE_COUNT; i++) { _original_sounds[i].file_slot = SOUND_SLOT; _original_sounds[i].file_offset = GB(FioReadDword(), 0, 31) + pos; _original_sounds[i].file_size = FioReadDword(); } for (uint i = 0; i != ORIGINAL_SAMPLE_COUNT; i++) { SoundEntry *sound = &_original_sounds[i]; char name[255]; FioSeekTo(sound->file_offset, SEEK_SET); /* Check for special case, see else case */ FioReadBlock(name, FioReadByte()); // Read the name of the sound if (new_format || strcmp(name, "Corrupt sound") != 0) { FioSeekTo(12, SEEK_CUR); // Skip past RIFF header /* Read riff tags */ for (;;) { uint32 tag = FioReadDword(); uint32 size = FioReadDword(); if (tag == ' tmf') { FioReadWord(); // wFormatTag sound->channels = FioReadWord(); // wChannels sound->rate = FioReadDword(); // samples per second if (!new_format) sound->rate = 11025; // seems like all old samples should be played at this rate. FioReadDword(); // avg bytes per second FioReadWord(); // alignment sound->bits_per_sample = FioReadByte(); // bits per sample FioSeekTo(size - (2 + 2 + 4 + 4 + 2 + 1), SEEK_CUR); } else if (tag == 'atad') { sound->file_size = size; sound->file_slot = SOUND_SLOT; sound->file_offset = FioGetPos(); break; } else { sound->file_size = 0; break; } } } else { /* * Special case for the jackhammer sound * (name in sample.cat is "Corrupt sound") * It's no RIFF file, but raw PCM data */ sound->channels = 1; sound->rate = 11025; sound->bits_per_sample = 8; sound->file_slot = SOUND_SLOT; sound->file_offset = FioGetPos(); } } } static bool SetBankSource(MixerChannel *mc, const SoundEntry *sound) { assert(sound != NULL); if (sound->file_size == 0) return false; int8 *mem = MallocT<int8>(sound->file_size + 2); /* Add two extra bytes so rate conversion can read these * without reading out of its input buffer. */ mem[sound->file_size ] = 0; mem[sound->file_size + 1] = 0; FioSeekToFile(sound->file_slot, sound->file_offset); FioReadBlock(mem, sound->file_size); /* 16-bit PCM WAV files should be signed by default */ if (sound->bits_per_sample == 8) { for (uint i = 0; i != sound->file_size; i++) { mem[i] += -128; // Convert unsigned sound data to signed } } #if TTD_ENDIAN == TTD_BIG_ENDIAN if (sound->bits_per_sample == 16) { uint num_samples = sound->file_size / 2; int16 *samples = (int16 *)mem; for (uint i = 0; i < num_samples; i++) { samples[i] = BSWAP16(samples[i]); } } #endif assert(sound->bits_per_sample == 8 || sound->bits_per_sample == 16); assert(sound->channels == 1); assert(sound->file_size != 0 && sound->rate != 0); MxSetChannelRawSrc(mc, mem, sound->file_size, sound->rate, sound->bits_per_sample == 16); return true; } void InitializeSound() { DEBUG(misc, 1, "Loading sound effects..."); OpenBankFile(BaseSounds::GetUsedSet()->files->filename); } /* Low level sound player */ static void StartSound(SoundID sound_id, float pan, uint volume) { if (volume == 0) return; const SoundEntry *sound = GetSound(sound_id); if (sound == NULL) return; /* Empty sound? */ if (sound->rate == 0) return; MixerChannel *mc = MxAllocateChannel(); if (mc == NULL) return; if (!SetBankSource(mc, sound)) return; /* Apply the sound effect's own volume. */ volume = sound->volume * volume; MxSetChannelVolume(mc, volume, pan); MxActivateChannel(mc); } static const byte _vol_factor_by_zoom[] = {255, 190, 134, 87}; assert_compile(lengthof(_vol_factor_by_zoom) == ZOOM_LVL_COUNT); static const byte _sound_base_vol[] = { 128, 90, 128, 128, 128, 128, 128, 128, 128, 90, 90, 128, 128, 128, 128, 128, 128, 128, 128, 80, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 90, 90, 90, 128, 90, 128, 128, 90, 128, 128, 128, 90, 128, 128, 128, 128, 128, 128, 90, 128, 128, 128, 128, 90, 128, 128, 128, 128, 128, 128, 128, 128, 90, 90, 90, 128, 128, 128, 90, }; static const byte _sound_idx[] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 0, 1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, }; void SndCopyToPool() { for (uint i = 0; i < ORIGINAL_SAMPLE_COUNT; i++) { SoundEntry *sound = AllocateSound(); *sound = _original_sounds[_sound_idx[i]]; sound->volume = _sound_base_vol[i]; sound->priority = 0; } } /** * Decide 'where' (between left and right speaker) to play the sound effect. * @param sound Sound effect to play * @param left Left edge of virtual coordinates where the sound is produced * @param right Right edge of virtual coordinates where the sound is produced * @param top Top edge of virtual coordinates where the sound is produced * @param bottom Bottom edge of virtual coordinates where the sound is produced */ static void SndPlayScreenCoordFx(SoundID sound, int left, int right, int top, int bottom) { if (_settings_client.music.effect_vol == 0) return; const Window *w; FOR_ALL_WINDOWS_FROM_BACK(w) { const ViewPort *vp = w->viewport; if (vp != NULL && left < vp->virtual_left + vp->virtual_width && right > vp->virtual_left && top < vp->virtual_top + vp->virtual_height && bottom > vp->virtual_top) { int screen_x = (left + right) / 2 - vp->virtual_left; int width = (vp->virtual_width == 0 ? 1 : vp->virtual_width); float panning = (float)screen_x / width; StartSound( sound, panning, (_settings_client.music.effect_vol * _vol_factor_by_zoom[vp->zoom - ZOOM_LVL_BEGIN]) / 256 ); return; } } } void SndPlayTileFx(SoundID sound, TileIndex tile) { /* emits sound from center of the tile */ int x = min(MapMaxX() - 1, TileX(tile)) * TILE_SIZE + TILE_SIZE / 2; int y = min(MapMaxY() - 1, TileY(tile)) * TILE_SIZE - TILE_SIZE / 2; uint z = (y < 0 ? 0 : GetSlopeZ(x, y)); Point pt = RemapCoords(x, y, z); y += 2 * TILE_SIZE; Point pt2 = RemapCoords(x, y, GetSlopeZ(x, y)); SndPlayScreenCoordFx(sound, pt.x, pt2.x, pt.y, pt2.y); } void SndPlayVehicleFx(SoundID sound, const Vehicle *v) { SndPlayScreenCoordFx(sound, v->coord.left, v->coord.right, v->coord.top, v->coord.bottom ); } void SndPlayFx(SoundID sound) { StartSound(sound, 0.5, _settings_client.music.effect_vol); } INSTANTIATE_BASE_MEDIA_METHODS(BaseMedia<SoundsSet>, SoundsSet) /** Names corresponding to the sound set's files */ static const char * const _sound_file_names[] = { "samples" }; template <class T, size_t Tnum_files, Subdirectory Tsubdir> /* static */ const char * const *BaseSet<T, Tnum_files, Tsubdir>::file_names = _sound_file_names; template <class Tbase_set> /* static */ const char *BaseMedia<Tbase_set>::GetExtension() { return ".obs"; // OpenTTD Base Sounds } template <class Tbase_set> /* static */ bool BaseMedia<Tbase_set>::DetermineBestSet() { if (BaseMedia<Tbase_set>::used_set != NULL) return true; const Tbase_set *best = NULL; for (const Tbase_set *c = BaseMedia<Tbase_set>::available_sets; c != NULL; c = c->next) { /* Skip unuseable sets */ if (c->GetNumMissing() != 0) continue; if (best == NULL || (best->fallback && !c->fallback) || best->valid_files < c->valid_files || (best->valid_files == c->valid_files && (best->shortname == c->shortname && best->version < c->version))) { best = c; } } BaseMedia<Tbase_set>::used_set = best; return BaseMedia<Tbase_set>::used_set != NULL; }
koreapyj/openttd-yacd
src/sound.cpp
C++
gpl-2.0
9,517
# # OpenSIPS makefile # # WARNING: requires gmake (GNU Make) # Arch supported: Linux, FreeBSD, SunOS (tested on Solaris 8), OpenBSD (3.2), # NetBSD (1.6). # # History: # -------- # created by andrei # 2003-02-24 make install no longer overwrites opensips.cfg - patch provided # by Maxim Sobolev <sobomax@FreeBSD.org> and # Tomas Bjoerklund <tomas@webservices.se> # 2003-03-11 PREFIX & LOCALBASE must also be exported (andrei) # 2003-04-07 hacked to work with solaris install (andrei) # 2003-04-17 exclude modules overwritable from env. or cmd. line, # added include_modules and skip_modules (andrei) # 2003-05-30 added extra_defs & EXTRA_DEFS # Makefile.defs force-included to allow recursive make # calls -- see comment (andrei) # 2003-06-02 make tar changes -- unpacks in $NAME-$RELEASE (andrei) # 2003-06-03 make install-cfg will properly replace the module path # in the cfg (re: /usr/.*lib/opensips/modules) # opensips.cfg.default is installed only if there is a previous # cfg. -- fixes packages containing opensips.cfg.default (andrei) # 2003-08-29 install-modules-doc split from install-doc, added # install-modules-all, removed README.cfg (andrei) # added skip_cfg_install (andrei) # 2004-09-02 install-man will automatically "fix" the path of the files # referred in the man pages # 2007-09-28 added db_berkeley (wiquan) # #FREERADIUS=1 # freeradius libs check (must be done in toplevel makefile) ifneq ("$(wildcard /usr/include/freeradius-client.h)","") FREERADIUS=1 else #FREERADIUS=0 endif #SQLITE_BIND=1 NICER?=1 auto_gen=lex.yy.c cfg.tab.c #lexx, yacc etc # whether or not to install opensips.cfg or just opensips.cfg.default # (opensips.cfg will never be overwritten by make install, this is useful # when creating packages) skip_cfg_install?= #extra modules to exclude skip_modules?= # whether or not to overwrite TLS certificates tls_overwrite_certs?= makefile_defs=0 DEFS:= DEBUG_PARSER?= # json libs check ifneq ("$(wildcard /usr/include/json-c/json.h)","") DEFS += -I/usr/include/json-c else DEFS += -I/usr/include/json endif # create the template only if the file is not yet created ifeq (,$(wildcard Makefile.conf)) $(shell cp Makefile.conf.template Makefile.conf) endif include Makefile.conf include Makefile.sources include Makefile.defs # always exclude the SVN dir override exclude_modules+= .svn $(skip_modules) #always include this modules #include_modules?= # first 2 lines are excluded because of the experimental or incomplete # status of the modules # the rest is excluded because it depends on external libraries # static_modules= static_modules_path=$(addprefix modules/, $(static_modules)) extra_sources=$(wildcard $(addsuffix /*.c, $(static_modules_path))) extra_objs=$(extra_sources:.c=.o) static_defs=$(foreach mod, $(static_modules), \ -DSTATIC_$(shell echo $(mod) | tr [:lower:] [:upper:]) ) override extra_defs+=$(static_defs) $(EXTRA_DEFS) export extra_defs # If modules is supplied, only do those. If not, use all modules when # building documentation. ifeq ($(modules),) doc_modules=$(all_modules) else doc_modules=$(modules) endif # Take subset of all modules, excluding the exclude_modules and the # static_modules. modules=$(filter-out $(addprefix modules/, \ $(exclude_modules) $(static_modules)), \ $(wildcard modules/*)) # Let modules consist of modules and include_modules (but remove # duplicates). modules:=$(filter-out $(modules), $(addprefix modules/, $(include_modules) )) \ $(modules) ifneq ($(module),) modules:=$(addprefix modules/, $(module)) endif modules_names=$(patsubst modules/%, %.so, $(modules)) modules_basenames=$(patsubst modules/%, %, $(modules)) modules_full_path=$(join $(modules), $(addprefix /, $(modules_names))) doc_modules_basenames=$(patsubst modules/%, %, $(patsubst net/%, %, $(doc_modules))) ALLDEP=Makefile Makefile.sources Makefile.defs Makefile.rules Makefile.conf install_docs := README-MODULES AUTHORS NEWS README ifneq ($(skip-install-doc),yes) install_docs += INSTALL endif #include general defs (like CC, CFLAGS a.s.o) # hack to force makefile.defs re-inclusion (needed when make calls itself with # other options -- e.g. make bin) #DEFS:= #include Makefile.defs NAME=$(MAIN_NAME) #export relevant variables to the sub-makes export DEFS PROFILE CC LD MKDEP MKTAGS CFLAGS LDFLAGS MOD_CFLAGS MOD_LDFLAGS export LIBS RADIUS_LIB export LEX YACC YACC_FLAGS export PREFIX LOCALBASE SYSBASE # export relevant variables for recursive calls of this makefile # (e.g. make deb) #export LIBS #export TAR export NAME RELEASE OS ARCH export cfg-prefix cfg-dir bin-prefix bin-dir modules-prefix modules-dir export doc-prefix doc-dir man-prefix man-dir ut-prefix ut-dir lib-dir export cfg-target modules-target data-dir data-prefix data-target export INSTALL INSTALL_CFG INSTALL_BIN INSTALL_MODULES INSTALL_DOC INSTALL_MAN export INSTALL_TOUCH # extra excludes for tar tar_extra_args+= # include the common rules include Makefile.rules #extra targets $(NAME): $(extra_objs) # static_modules lex.yy.c: cfg.lex cfg.tab.h $(ALLDEP) $(LEX) $< cfg.tab.c cfg.tab.h: cfg.y $(ALLDEP) $(YACC) $(YACC_FLAGS) $< .PHONY: all all: $(NAME) modules utils .PHONY: app app: $(NAME) .PHONY: _modules _modules: $(modules) .PHONY: $(modules) $(modules): @$(MAKE) --no-print-directory -C $@ && \ echo "Building $(notdir $@) module succeeded" || (\ status=$$?; \ echo "ERROR: Building $(notdir $@) module failed!"; \ exit $$status; \ ) .PHONY: modules modules: ifeq (,$(FASTER)) @set -e; \ for r in $(modules) "" ; do \ if [ -n "$$r" ]; then \ if [ -d "$$r" ]; then \ echo "" ; \ echo "" ; \ $(MAKE) -j -C $$r ; \ fi ; \ fi ; \ done else @$(MAKE) _modules || ( \ status=$$?; \ if echo $(MAKEFLAGS) | grep -q -- --jobserver; then \ printf '\nBuilding one or more modules failed!\n'; \ printf 'Please re-run make without -j / --jobs to find out which.\n\n'; \ fi; \ exit $$status \ ) endif .PHONY: tool-docbook2pdf tool-docbook2pdf: @if [ -z "$(DBXML2PDF)" ]; then \ echo "error: docbook2pdf not found"; exit 1; \ fi .PHONY: tool-lynx tool-lynx: @if [ -z "$(DBHTML2TXT)" ]; then \ echo "error: lynx not found"; exit 1; \ fi .PHONY: tool-xsltproc tool-xsltproc: @if [ -z "$(DBXML2HTML)" ]; then \ echo "error: xsltproc not found"; exit 1; \ fi @if [ -z "$(DBHTMLXSL)" ]; then \ echo "error: docbook.xsl not found (docbook-xsl)"; exit 1; \ fi .PHONY: modules-readme modules-readme: tool-lynx tool-xsltproc @set -e; \ for r in $(doc_modules_basenames) ""; do \ if [ ! -d "modules/$$r/doc" -a ! -d "net/$$r/doc" ]; then \ continue; \ fi; \ if [ -d "modules/$$r/doc" ]; then \ cd "modules/$$r/doc"; \ elif [ -d "net/$$r/doc" ]; then \ cd "net/$$r/doc"; \ fi; \ \ if [ -f "$$r".xml ]; then \ echo ""; \ echo "docbook xml to html: $$r.xml"; \ $(DBXML2HTML) -o $$r.html $(DBXML2HTMLPARAMS) $(DBHTMLXSL) \ $$r.xml; \ echo "docbook html to txt: $$r.html"; \ $(DBHTML2TXT) $(DBHTML2TXTPARAMS) $$r.html >$$r.txt; \ echo "docbook txt to readme: $$r.txt"; \ rm $$r.html; \ mv $$r.txt ../README; \ echo ""; \ fi; \ cd ../../..; \ done .PHONY: modules-docbook-txt modules-docbook-txt: tool-lynx tool-xsltproc @set -e; \ for r in $(doc_modules_basenames) ""; do \ if [ ! -d "modules/$$r/doc" -a ! -d "net/$$r/doc" ]; then \ continue; \ fi; \ if [ -d "modules/$$r/doc" ]; then \ cd "modules/$$r/doc"; \ elif [ -d "net/$$r/doc" ]; then \ cd "net/$$r/doc"; \ fi; \ \ if [ -f "$$r".xml ]; then \ echo ""; \ echo "docbook xml to html: $$r.xml"; \ $(DBXML2HTML) -o $$r.html $(DBXML2HTMLPARAMS) $(DBHTMLXSL) \ $$r.xml; \ echo "docbook html to txt: $$r.html"; \ $(DBHTML2TXT) $(DBHTML2TXTPARAMS) $$r.html >$$r.txt; \ rm $$r.html; \ echo ""; \ fi; \ cd ../../..; \ done .PHONY: modules-docbook-html modules-docbook-html: tool-xsltproc @set -e; \ for r in $(doc_modules_basenames) ""; do \ if [ ! -d "modules/$$r/doc" -a ! -d "net/$$r/doc" ]; then \ continue; \ fi; \ if [ -d "modules/$$r/doc" ]; then \ cd "modules/$$r/doc"; \ elif [ -d "net/$$r/doc" ]; then \ cd "net/$$r/doc"; \ fi; \ \ if [ -f "$$r".xml ]; then \ echo ""; \ echo "docbook xml to html: $$r.xml"; \ $(DBXML2HTML) -o $$r.html $(DBXML2HTMLPARAMS) $(DBHTMLXSL) \ $$r.xml; \ echo ""; \ fi; \ cd ../../..; \ done .PHONY: modules-docbook-pdf modules-docbook-pdf: tool-docbook2pdf @set -e; \ for r in $(doc_modules_basenames) ""; do \ if [ ! -d "modules/$$r/doc" -a ! -d "net/$$r/doc" ]; then \ continue; \ fi; \ if [ -d "modules/$$r/doc" ]; then \ cd "modules/$$r/doc"; \ elif [ -d "net/$$r/doc" ]; then \ cd "net/$$r/doc"; \ fi; \ if [ -f "$$r".xml ]; then \ echo ""; \ echo "docbook xml to pdf: $$r.xml"; \ $(DBXML2PDF) "$$r".xml; \ fi; \ cd ../../..; \ done .PHONY: modules-docbook modules-docbook: modules-docbook-txt modules-docbook-html modules-docbook-pdf .PHONY: dbschema-docbook-txt dbschema-docbook-txt: dbschema @set -e; \ for r in $(wildcard doc/database/*.sgml) "" ; do \ if [ -f "$$r" ]; then \ echo "" ; \ echo "docbook2txt $$r" ; \ docbook2txt -o "doc/database/" "$$r" ; \ fi ; \ done .PHONY: dbschema-docbook-html dbschema-docbook-html: dbschema @set -e; \ for r in $(wildcard doc/database/*.sgml) "" ; do \ if [ -f "$$r" ]; then \ echo "" ; \ echo "docbook2html $$r" ; \ docbook2html --nochunks -o "doc/database/" "$$r" ; \ fi ; \ done .PHONY: dbschema-docbook-pdf dbschema-docbook-pdf: dbschema @set -e; \ for r in $(wildcard doc/database/*.sgml) "" ; do \ if [ -f "$$r" ]; then \ echo "" ; \ echo "docbook2pdf $$r" ; \ docbook2pdf -o "doc/database/" "$$r" ; \ fi ; \ done .PHONY: dbschema-docbook dbschema-docbook: dbschema-docbook-txt dbschema-docbook-html dbschema-docbook-pdf $(extra_objs): -@echo "Extra objs: $(extra_objs)" @set -e; \ for r in $(static_modules_path) "" ; do \ if [ -n "$$r" ]; then \ echo "" ; \ echo "Making static module $r" ; \ $(MAKE) -C $$r static ; \ fi ; \ done dbg: $(NAME) gdb -command debug.gdb .PHONY: tar .PHONY: dist dist: tar tar: $(NEWREVISION) $(TAR) -C .. \ --exclude=$(notdir $(CURDIR))/tmp* \ --exclude=$(notdir $(CURDIR))/debian* \ --exclude=.svn* \ --exclude=.git \ --exclude=.gitignore \ --exclude=Makefile.conf \ --exclude=*.[do] \ --exclude=*.so \ --exclude=*.il \ --exclude=$(notdir $(CURDIR))/$(NAME) \ --exclude=*.gz \ --exclude=*.bz2 \ --exclude=*.tar \ --exclude=*.patch \ --exclude=.\#* \ --exclude=*.swp \ --exclude=*~ \ ${tar_extra_args} \ -cf - $(notdir $(CURDIR)) | \ (mkdir -p tmp/_tar1; mkdir -p tmp/_tar2 ; \ cd tmp/_tar1; $(TAR) -xf - ) && \ mv tmp/_tar1/$(notdir $(CURDIR)) \ tmp/_tar2/"$(NAME)-$(RELEASE)" && \ (cd tmp/_tar2 && $(TAR) \ -zcf ../../"$(NAME)-$(RELEASE)_src".tar.gz \ "$(NAME)-$(RELEASE)" ) ; \ rm -rf tmp/_tar1; rm -rf tmp/_tar2 # binary dist. tar.gz .PHONY: bin bin: mkdir -p tmp/$(NAME)/usr/local $(MAKE) install basedir=tmp/$(NAME) prefix=/usr/local $(TAR) -C tmp/$(NAME)/ -zcf ../$(NAME)-$(RELEASE)_$(OS)_$(ARCH).tar.gz . rm -rf tmp/$(NAME) .PHONY: deb-orig-tar deb-orig-tar: tar_extra_args=--exclude=packaging make tar mv "$(NAME)-$(RELEASE)_src".tar.gz ../$(NAME)_$(RELEASE).orig.tar.gz .PHONY: deb deb: rm -rf debian # dpkg-source cannot use links for debian source cp -r packaging/debian debian DEB_BUILD_OPTIONS=nocheck dpkg-buildpackage \ -I.git -I.gitignore \ -IMakefile.conf \ -I*.swp -I*~ \ -i\\.git\|Makefile\\.conf\|packaging\|debian\|^\\.\\w+\\.swp\|lex\\.yy\\.c\|cfg\\.tab\\.\(c\|h\) \ -rfakeroot -tc $(DEBBUILD_EXTRA_OPTIONS) rm -rf debian .PHONY: sunpkg sunpkg: mkdir -p tmp/$(NAME) mkdir -p tmp/$(NAME)_sun_pkg $(MAKE) install basedir=tmp/$(NAME) prefix=/usr/local (cd packaging/solaris; \ pkgmk -r ../../tmp/$(NAME)/usr/local -o -d ../../tmp/$(NAME)_sun_pkg/ -v "$(RELEASE)" ;\ cd ../..) cat /dev/null > ../$(NAME)-$(RELEASE)-$(OS)-$(ARCH)-local pkgtrans -s tmp/$(NAME)_sun_pkg/ ../$(NAME)-$(RELEASE)-$(OS)-$(ARCH)-local \ OpenSIPS gzip -9 ../$(NAME)-$(RELEASE)-$(OS)-$(ARCH)-local rm -rf tmp/$(NAME) rm -rf tmp/$(NAME)_sun_pkg .PHONY: install-app install-modules-all install # Install app only, excluding console, modules and module docs install-app: app mk-install-dirs install-cfg opensipsmc install-bin \ install-app-doc install-man # Install all module stuff (except modules-docbook?) install-modules-all: install-modules install-modules-doc # Install everything (except modules-docbook?) install: install-app install-console install-modules-all opensipsmc: $(cfg-prefix)/$(cfg-dir) $(data-prefix)/$(data-dir) $(MAKE) -C menuconfig proper $(MAKE) -C menuconfig \ MENUCONFIG_CFG_PATH=$(data-target)/menuconfig_templates/ \ MENUCONFIG_GEN_PATH=$(cfg-target) MENUCONFIG_HAVE_SOURCES=0 mkdir -p $(data-prefix)/$(data-dir)/menuconfig_templates/ $(INSTALL_TOUCH) menuconfig/configs/* $(data-prefix)/$(data-dir)/menuconfig_templates/ $(INSTALL_CFG) menuconfig/configs/* $(data-prefix)/$(data-dir)/menuconfig_templates/ sed -i -e "s#/usr/.*lib/$(NAME)/modules/#$(modules-target)#" \ $(data-prefix)/$(data-dir)/menuconfig_templates/* .PHONY: dbschema dbschema: -@echo "Build database schemas" $(MAKE) -C db/schema -@echo "Done" mk-install-dirs: $(cfg-prefix)/$(cfg-dir) $(bin-prefix)/$(bin-dir) \ $(modules-prefix)/$(modules-dir) $(doc-prefix)/$(doc-dir) \ $(man-prefix)/$(man-dir)/man8 $(man-prefix)/$(man-dir)/man5 \ $(data-prefix)/$(data-dir) # note: on solaris 8 sed: ? or \(...\)* (a.s.o) do not work install-cfg: $(cfg-prefix)/$(cfg-dir) sed -e "s#/usr/.*lib/$(NAME)/modules/#$(modules-target)#g" \ < etc/$(NAME).cfg > $(cfg-prefix)/$(cfg-dir)$(NAME).cfg.sample0 sed -e "s#/usr/.*etc/$(NAME)/tls/#$(cfg-target)tls/#g" \ < $(cfg-prefix)/$(cfg-dir)$(NAME).cfg.sample0 \ > $(cfg-prefix)/$(cfg-dir)$(NAME).cfg.sample rm -fr $(cfg-prefix)/$(cfg-dir)$(NAME).cfg.sample0 chmod 600 $(cfg-prefix)/$(cfg-dir)$(NAME).cfg.sample chmod 700 $(cfg-prefix)/$(cfg-dir) if [ -z "${skip_cfg_install}" -a \ ! -f $(cfg-prefix)/$(cfg-dir)$(NAME).cfg ]; then \ mv -f $(cfg-prefix)/$(cfg-dir)$(NAME).cfg.sample \ $(cfg-prefix)/$(cfg-dir)$(NAME).cfg; \ fi # opensipsctl config $(INSTALL_TOUCH) $(cfg-prefix)/$(cfg-dir)/opensipsctlrc.sample $(INSTALL_CFG) scripts/opensipsctlrc \ $(cfg-prefix)/$(cfg-dir)/opensipsctlrc.sample if [ ! -f $(cfg-prefix)/$(cfg-dir)/opensipsctlrc ]; then \ mv -f $(cfg-prefix)/$(cfg-dir)/opensipsctlrc.sample \ $(cfg-prefix)/$(cfg-dir)/opensipsctlrc; \ fi # osipsconsole config $(INSTALL_TOUCH) $(cfg-prefix)/$(cfg-dir)/osipsconsolerc.sample $(INSTALL_CFG) scripts/osipsconsolerc \ $(cfg-prefix)/$(cfg-dir)/osipsconsolerc.sample if [ ! -f $(cfg-prefix)/$(cfg-dir)/osipsconsolerc ]; then \ mv -f $(cfg-prefix)/$(cfg-dir)/osipsconsolerc.sample \ $(cfg-prefix)/$(cfg-dir)/osipsconsolerc; \ fi install-console: $(bin-prefix)/$(bin-dir) # install osipsconsole cat scripts/osipsconsole | \ sed -e "s#PATH_BIN[ \t]*=[ \t]*\"\./\"#PATH_BIN = \"$(bin-target)\"#g" | \ sed -e "s#PATH_CTLRC[ \t]*=[ \t]*\"\./scripts/\"#PATH_CTLRC = \"$(cfg-target)\"#g" | \ sed -e "s#PATH_LIBS[ \t]*=[ \t]*\"\./scripts/\"#PATH_LIBS = \"$(lib-target)/opensipsctl/\"#g" | \ sed -e "s#PATH_SHARE[ \t]*=[ \t]*\"\./scripts/\"#PATH_SHARE = \"$(data-target)\"#g" | \ sed -e "s#PATH_ETC[ \t]*=[ \t]*\"\./etc/\"#PATH_ETC = \"$(cfg-target)\"#g" \ > /tmp/osipsconsole $(INSTALL_TOUCH) $(bin-prefix)/$(bin-dir)/osipsconsole $(INSTALL_BIN) /tmp/osipsconsole $(bin-prefix)/$(bin-dir) rm -fr /tmp/osipsconsole install-bin: $(bin-prefix)/$(bin-dir) utils # install opensips binary $(INSTALL_TOUCH) $(bin-prefix)/$(bin-dir)/$(NAME) $(INSTALL_BIN) $(NAME) $(bin-prefix)/$(bin-dir) # install opensips menuconfig $(INSTALL_TOUCH) $(bin-prefix)/$(bin-dir)/osipsconfig $(INSTALL_BIN) menuconfig/configure $(bin-prefix)/$(bin-dir)/osipsconfig # install opensipsctl (and family) tool cat scripts/opensipsctl | \ sed -e "s#/usr/local/sbin#$(bin-target)#g" | \ sed -e "s#/usr/local/lib/opensips#$(lib-target)#g" | \ sed -e "s#/usr/local/etc/opensips#$(cfg-target)#g" >/tmp/opensipsctl $(INSTALL_TOUCH) $(bin-prefix)/$(bin-dir)/opensipsctl $(INSTALL_BIN) /tmp/opensipsctl $(bin-prefix)/$(bin-dir) rm -fr /tmp/opensipsctl sed -e "s#/usr/local/sbin#$(bin-target)#g" \ < scripts/opensipsctl.base > /tmp/opensipsctl.base mkdir -p $(modules-prefix)/$(lib-dir)/opensipsctl $(INSTALL_TOUCH) \ $(modules-prefix)/$(lib-dir)/opensipsctl $(INSTALL_CFG) /tmp/opensipsctl.base \ $(modules-prefix)/$(lib-dir)/opensipsctl/opensipsctl.base rm -fr /tmp/opensipsctl.base sed -e "s#/usr/local#$(bin-target)#g" \ < scripts/opensipsctl.ctlbase > /tmp/opensipsctl.ctlbase $(INSTALL_CFG) /tmp/opensipsctl.ctlbase \ $(modules-prefix)/$(lib-dir)/opensipsctl/opensipsctl.ctlbase rm -fr /tmp/opensipsctl.ctlbase sed -e "s#/usr/local#$(bin-target)#g" \ < scripts/opensipsctl.fifo > /tmp/opensipsctl.fifo $(INSTALL_CFG) /tmp/opensipsctl.fifo \ $(modules-prefix)/$(lib-dir)/opensipsctl/opensipsctl.fifo rm -fr /tmp/opensipsctl.fifo sed -e "s#/usr/local#$(bin-target)#g" \ < scripts/opensipsctl.unixsock > /tmp/opensipsctl.unixsock $(INSTALL_CFG) /tmp/opensipsctl.unixsock \ $(modules-prefix)/$(lib-dir)/opensipsctl/opensipsctl.unixsock rm -fr /tmp/opensipsctl.unixsock sed -e "s#/usr/local#$(bin-target)#g" \ < scripts/opensipsctl.sqlbase > /tmp/opensipsctl.sqlbase $(INSTALL_CFG) /tmp/opensipsctl.sqlbase \ $(modules-prefix)/$(lib-dir)/opensipsctl/opensipsctl.sqlbase rm -fr /tmp/opensipsctl.sqlbase # install db setup base script sed -e "s#/usr/local/sbin#$(bin-target)#g" \ -e "s#/usr/local/etc/opensips#$(cfg-target)#g" \ -e "s#/usr/local/share/opensips#$(data-target)#g" \ < scripts/opensipsdbctl.base > /tmp/opensipsdbctl.base $(INSTALL_CFG) /tmp/opensipsdbctl.base \ $(modules-prefix)/$(lib-dir)/opensipsctl/opensipsdbctl.base rm -fr /tmp/opensipsdbctl.base cat scripts/opensipsdbctl | \ sed -e "s#/usr/local/sbin#$(bin-target)#g" | \ sed -e "s#/usr/local/lib/opensips#$(lib-target)#g" | \ sed -e "s#/usr/local/etc/opensips#$(cfg-target)#g" >/tmp/opensipsdbctl $(INSTALL_TOUCH) $(bin-prefix)/$(bin-dir)/opensipsdbctl $(INSTALL_BIN) /tmp/opensipsdbctl $(bin-prefix)/$(bin-dir) rm -fr /tmp/opensipsdbctl $(INSTALL_TOUCH) $(bin-prefix)/$(bin-dir)/$(NAME)unix $(INSTALL_BIN) utils/$(NAME)unix/$(NAME)unix $(bin-prefix)/$(bin-dir) .PHONY: utils utils: cd utils/$(NAME)unix; $(MAKE) all if [ "$(BERKELEYDBON)" = "yes" ]; then \ cd utils/db_berkeley; $(MAKE) all ; \ fi ; if [ "$(ORACLEON)" = "yes" ]; then \ cd utils/db_oracle; $(MAKE) all ; \ fi ; install-modules: modules $(modules-prefix)/$(modules-dir) @for r in $(modules_full_path) "" ; do \ if [ -n "$$r" ]; then \ if [ -f "$$r" ]; then \ $(INSTALL_TOUCH) \ $(modules-prefix)/$(modules-dir)/`basename "$$r"` ; \ $(INSTALL_MODULES) "$$r" $(modules-prefix)/$(modules-dir) ; \ $(MAKE) -C `dirname "$$r"` install_module_custom ; \ else \ echo "ERROR: module $$r not compiled" ; \ fi ;\ fi ; \ done .PHONY: install-doc install-app-doc install-modules-doc install-doc: install-app-doc install-modules-doc install-app-doc: $(doc-prefix)/$(doc-dir) -@for d in $(install_docs) ""; do \ $(INSTALL_TOUCH) $(doc-prefix)/$(doc-dir)/"$$d" ; \ $(INSTALL_DOC) "$$d" $(doc-prefix)/$(doc-dir) ; \ done install-modules-doc: $(doc-prefix)/$(doc-dir) -@for r in $(modules_basenames) "" ; do \ if [ -n "$$r" ]; then \ if [ -f modules/"$$r"/README ]; then \ $(INSTALL_TOUCH) $(doc-prefix)/$(doc-dir)/README."$$r" ; \ $(INSTALL_DOC) modules/"$$r"/README \ $(doc-prefix)/$(doc-dir)/README."$$r" ; \ fi ; \ fi ; \ done install-man: $(man-prefix)/$(man-dir)/man8 $(man-prefix)/$(man-dir)/man5 sed -e "s#/etc/$(NAME)/$(NAME)\.cfg#$(cfg-target)$(NAME).cfg#g" \ -e "s#/usr/sbin/#$(bin-target)#g" \ -e "s#/usr/lib/$(NAME)/modules/#$(modules-target)#g" \ -e "s#/usr/share/doc/$(NAME)/#$(doc-target)#g" \ < $(NAME).8 > $(man-prefix)/$(man-dir)/man8/$(NAME).8 chmod 644 $(man-prefix)/$(man-dir)/man8/$(NAME).8 sed -e "s#/etc/$(NAME)/$(NAME)\.cfg#$(cfg-target)$(NAME).cfg#g" \ -e "s#/usr/sbin/#$(bin-target)#g" \ -e "s#/usr/lib/$(NAME)/modules/#$(modules-target)#g" \ -e "s#/usr/share/doc/$(NAME)/#$(doc-target)#g" \ < $(NAME).cfg.5 > $(man-prefix)/$(man-dir)/man5/$(NAME).cfg.5 chmod 644 $(man-prefix)/$(man-dir)/man5/$(NAME).cfg.5 sed -e "s#/etc/$(NAME)/$(NAME)\.cfg#$(cfg-target)$(NAME).cfg#g" \ -e "s#/usr/sbin/#$(bin-target)#g" \ -e "s#/usr/lib/$(NAME)/modules/#$(modules-target)#g" \ -e "s#/usr/share/doc/$(NAME)/#$(doc-target)#g" \ < scripts/opensipsctl.8 > $(man-prefix)/$(man-dir)/man8/opensipsctl.8 chmod 644 $(man-prefix)/$(man-dir)/man8/opensipsctl.8 sed -e "s#/etc/$(NAME)/$(NAME)\.cfg#$(cfg-target)$(NAME).cfg#g" \ -e "s#/usr/sbin/#$(bin-target)#g" \ -e "s#/usr/lib/$(NAME)/modules/#$(modules-target)#g" \ -e "s#/usr/share/doc/$(NAME)/#$(doc-target)#g" \ < utils/opensipsunix/opensipsunix.8 > \ $(man-prefix)/$(man-dir)/man8/opensipsunix.8 chmod 644 $(man-prefix)/$(man-dir)/man8/opensipsunix.8 install-modules-docbook: $(doc-prefix)/$(doc-dir) -@for r in $(modules_basenames) "" ; do \ if [ -n "$$r" ]; then \ if [ -d modules/"$$r"/doc ]; then \ if [ -f modules/"$$r"/doc/"$$r".txt ]; then \ $(INSTALL_TOUCH) $(doc-prefix)/$(doc-dir)/"$$r".txt ; \ $(INSTALL_DOC) modules/"$$r"/doc/"$$r".txt \ $(doc-prefix)/$(doc-dir)/"$$r".txt ; \ fi ; \ if [ -f modules/"$$r"/doc/"$$r".html ]; then \ $(INSTALL_TOUCH) $(doc-prefix)/$(doc-dir)/"$$r".html ; \ $(INSTALL_DOC) modules/"$$r"/doc/"$$r".html \ $(doc-prefix)/$(doc-dir)/"$$r".html ; \ fi ; \ if [ -f modules/"$$r"/doc/"$$r".pdf ]; then \ $(INSTALL_TOUCH) $(doc-prefix)/$(doc-dir)/"$$r".pdf ; \ $(INSTALL_DOC) modules/"$$r"/doc/"$$r".pdf \ $(doc-prefix)/$(doc-dir)/"$$r".pdf ; \ fi ; \ fi ; \ fi ; \ done .PHONY: test test: -@echo "Start tests" $(MAKE) -C test/ -@echo "Tests finished" doxygen: -@echo "Create Doxygen documentation" # disable call graphes, because of the DOT dependencies (cat doc/doxygen/opensips-doxygen; \ echo "HAVE_DOT=no" ;\ echo "PROJECT_NUMBER=$(NAME)-$(RELEASE)" )| doxygen - -@echo "Doxygen documentation created" comp_menuconfig: $(MAKE) -C menuconfig menuconfig: comp_menuconfig ./menuconfig/configure --local
chiforbogdan/opensips
Makefile
Makefile
gpl-2.0
23,031
/* This file is part of Cyclos (www.cyclos.org). A project of the Social Trade Organisation (www.socialtrade.org). Cyclos is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Cyclos is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Cyclos; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package nl.strohalm.cyclos.controls.members.references; import java.util.Calendar; import java.util.Collection; import java.util.Map; import javax.servlet.http.HttpServletRequest; import nl.strohalm.cyclos.annotations.Inject; import nl.strohalm.cyclos.controls.ActionContext; import nl.strohalm.cyclos.controls.BaseQueryAction; import nl.strohalm.cyclos.entities.accounts.AccountType; import nl.strohalm.cyclos.entities.accounts.transactions.Payment; import nl.strohalm.cyclos.entities.accounts.transactions.TransferType; import nl.strohalm.cyclos.entities.members.Element; import nl.strohalm.cyclos.entities.members.Member; import nl.strohalm.cyclos.entities.members.Reference; import nl.strohalm.cyclos.entities.members.Reference.Level; import nl.strohalm.cyclos.entities.members.Reference.Nature; import nl.strohalm.cyclos.entities.members.ReferenceQuery; import nl.strohalm.cyclos.entities.members.TransactionFeedback; import nl.strohalm.cyclos.entities.settings.LocalSettings; import nl.strohalm.cyclos.services.elements.ReferenceService; import nl.strohalm.cyclos.entities.utils.Period; import nl.strohalm.cyclos.utils.RelationshipHelper; import nl.strohalm.cyclos.utils.RequestHelper; import nl.strohalm.cyclos.entities.utils.TimePeriod; import nl.strohalm.cyclos.utils.binding.BeanBinder; import nl.strohalm.cyclos.utils.binding.DataBinder; import nl.strohalm.cyclos.utils.binding.DataBinderHelper; import nl.strohalm.cyclos.utils.conversion.CoercionHelper; import nl.strohalm.cyclos.utils.query.QueryParameters; import nl.strohalm.cyclos.utils.validation.ValidationException; /** * Action used to view a member's references and edit the reference to that member * @author luis */ public class MemberReferencesAction extends BaseQueryAction { /** * Represents the direction we're searching * @author luis */ public static enum Direction { RECEIVED, GIVEN } private DataBinder<ReferenceQuery> dataBinder; private ReferenceService referenceService; @Inject public void setReferenceService(final ReferenceService referenceService) { this.referenceService = referenceService; } @SuppressWarnings("unchecked") @Override protected void executeQuery(final ActionContext context, final QueryParameters queryParameters) { final HttpServletRequest request = context.getRequest(); final MemberReferencesForm form = context.getForm(); final Direction direction = CoercionHelper.coerce(Direction.class, form.getDirection()); final Member member = (Member) request.getAttribute("member"); final ReferenceQuery query = (ReferenceQuery) queryParameters; if (member != null) { form.setMemberId(member.getId()); } // Retrieve both summaries for all time and last 30 days final Map<Level, Integer> allTime = referenceService.countReferencesByLevel(query.getNature(), member, direction == Direction.RECEIVED); request.setAttribute("summaryAllTime", allTime); final Period period30 = new TimePeriod(30, TimePeriod.Field.DAYS).periodEndingAt(Calendar.getInstance()); final Map<Level, Integer> last30Days = referenceService.countReferencesHistoryByLevel(query.getNature(), member, period30, direction == Direction.RECEIVED); request.setAttribute("summaryLast30Days", last30Days); // Calculate the score int totalAllTime = 0; int total30Days = 0; int scoreAllTime = 0; int score30Days = 0; final Collection<Level> levels = (Collection<Level>) request.getAttribute("levels"); int nonNeutralCountAllTime = 0; int positiveCountAllTime = 0; int nonNeutralCount30Days = 0; int positiveCount30Days = 0; for (final Level level : levels) { final int value = level.getValue(); final int allTimeCount = CoercionHelper.coerce(Integer.TYPE, allTime.get(level)); final int last30DaysCount = CoercionHelper.coerce(Integer.TYPE, last30Days.get(level)); // Calculate the total totalAllTime += allTimeCount; total30Days += last30DaysCount; // Calculate the score (sum of count * value) scoreAllTime += allTimeCount * value; score30Days += last30DaysCount * value; // Calculate the data for positive percentage if (value != 0) { nonNeutralCountAllTime += allTimeCount; nonNeutralCount30Days += last30DaysCount; if (value > 0) { positiveCountAllTime += allTimeCount; positiveCount30Days += last30DaysCount; } } } // Calculate the positive percentage final int percentAllTime = nonNeutralCountAllTime == 0 ? 0 : Math.round((float) positiveCountAllTime / nonNeutralCountAllTime * 100F); final int percentLast30Days = nonNeutralCount30Days == 0 ? 0 : Math.round((float) positiveCount30Days / nonNeutralCount30Days * 100F); // Store calculated data on request request.setAttribute("totalAllTime", totalAllTime); request.setAttribute("total30Days", total30Days); request.setAttribute("scoreAllTime", scoreAllTime); request.setAttribute("score30Days", score30Days); request.setAttribute("percentAllTime", percentAllTime); request.setAttribute("percent30Days", percentLast30Days); // Get the references list request.setAttribute("references", referenceService.search(query)); } @Override protected QueryParameters prepareForm(final ActionContext context) { final MemberReferencesForm form = context.getForm(); final HttpServletRequest request = context.getRequest(); final ReferenceQuery query = getDataBinder().readFromString(form.getQuery()); query.setNature(CoercionHelper.coerce(Nature.class, form.getNature())); if (query.getNature() == null) { query.setNature(Nature.GENERAL); } // Find out the member Member member; try { member = (Member) (form.getMemberId() <= 0L ? context.getAccountOwner() : elementService.load(form.getMemberId(), Element.Relationships.GROUP)); } catch (final Exception e) { throw new ValidationException(); } final boolean myReferences = member.equals(context.getAccountOwner()); // Retrieve the direction we're looking at Direction direction = CoercionHelper.coerce(Direction.class, form.getDirection()); if (direction == null) { direction = Direction.RECEIVED; form.setDirection(direction.name()); } final boolean isGiven = direction == Direction.GIVEN; if (isGiven) { query.setFrom(member); } else { query.setTo(member); } final boolean isGeneral = query.getNature() == Reference.Nature.GENERAL; if (!isGeneral) { query.fetch(RelationshipHelper.nested(TransactionFeedback.Relationships.TRANSFER, Payment.Relationships.TYPE, TransferType.Relationships.FROM, AccountType.Relationships.CURRENCY)); } // When it's a member (or operator) viewing of other member's received general references, he can set his own too final boolean canSetReference = isGeneral && referenceService.canGiveGeneralReference(member); // Check whether the logged user can manage references on the list final boolean canManage = isGeneral && (myReferences && isGiven || !myReferences) && referenceService.canManageGeneralReference(member); // Bind the form and store the request attributes final LocalSettings localSettings = settingsService.getLocalSettings(); getDataBinder().writeAsString(form.getQuery(), query); request.setAttribute("member", member); request.setAttribute("canManage", canManage); request.setAttribute("myReferences", myReferences); request.setAttribute("isGiven", isGiven); request.setAttribute("isGeneral", isGeneral); request.setAttribute("levels", localSettings.getReferenceLevelList()); request.setAttribute("canSetReference", canSetReference); RequestHelper.storeEnum(request, Direction.class, "directions"); if (!isGeneral) { final boolean showAmount = context.isAdmin() || context.getAccountOwner().equals(member); request.setAttribute("showAmount", showAmount); } return query; } @Override protected boolean willExecuteQuery(final ActionContext context, final QueryParameters queryParameters) throws Exception { return true; } private DataBinder<ReferenceQuery> getDataBinder() { if (dataBinder == null) { final BeanBinder<ReferenceQuery> binder = BeanBinder.instance(ReferenceQuery.class); binder.registerBinder("pageParameters", DataBinderHelper.pageBinder()); dataBinder = binder; } return dataBinder; } }
mateli/OpenCyclos
src/main/java/nl/strohalm/cyclos/controls/members/references/MemberReferencesAction.java
Java
gpl-2.0
9,953
using System; using System.Collections.Generic; namespace LeetCode { public partial class Solution { public int LengthOfLongestSubstring(string s) { //TODO 以下算法虽然思路是对的,但是写法有问题,无法通过长字符串的测试,不应该递归 #region Bad performance // IList<char> dic=new List<char>(); // for (var i = 0; i < s.Length; i++) // { // char c = s [i]; // if (dic.Contains (c)) // { // var sub = s.Substring (s.IndexOf (c) + 1); // // return Math.Max (i, LengthOfLongestSubstring (sub)); // } // dic.Add (c); // // } // return s.Length; #endregion //IList<char> dic=new List<char>(); const int ARRAY_LEN=255; int[] dic=new int[ARRAY_LEN]; for (var i = 0; i < ARRAY_LEN; i++) { dic [i] = -1; } int start = 0; int max = 0; for (var i = 0; i < s.Length; i++) { var c = s [i]; if (dic[c]>=start)//也就是说dic里面不是-1,已经被赋值过,而且这个值在start位置之后出现,判断为重复 { int len = i - start; max = Math.Max (max, len); start = dic [c] + 1; } dic [c] = i; } max = Math.Max (max, s.Length - start); return max; } } }
studyzy/Leetcode
CSharp/LeetCode/LongestSubstringWithoutRepeatingCharacters.cs
C#
gpl-2.0
1,226
/** Automatically generated file. DO NOT MODIFY */ package fr.free.coup2lapan; public final class BuildConfig { public final static boolean DEBUG = true; }
HadrienLG/Coup2Lapan
gen/fr/free/coup2lapan/BuildConfig.java
Java
gpl-2.0
160
/**************************************************************************** The Sire build utility 'sire'. Copyright (C) 1999, 2000, 2002, 2003 David W Orchard (davido@errol.org.uk) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ***************************************************************************** File : machine.cpp Class : None Desc : A description AMENDMENTS EDIT 001 21-Nov-97 davido Check the root directory as well. EDIT 002 13-Jan-99 davido Support SuSe Linux file positions. EDIT 003 14-Aug-99 davido Support Linux Fortran 77 EDIT 004 19-May-00 davido Take out the platform specific dependency. EDIT 005 15-Nov-02 davido Remove support for infrequently used options EDIT 006 10-Jan-03 davido Remove getPython, getMachine() and getPlatform(). Now redundant. *****************************************************************************/ /************* INCLUDE ******************************************************/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "sys.h" #include "env.h" #include "machine.h" #include "build_v.h" /************* FUNCTIONS ****************************************************/ static char const *findName(char **list) { static char buff1[256]; static char buff2[256]; int len1; int len2; for (char **p = list; (NULL != *p); p++) { strcpy(buff1, (char*)Tenv::appExpand(*p)); strcpy(buff2, (char*)Tenv::appGet("ROOTDIR")); // 004 strcat(buff2, buff1); len1 = strlen(buff1); len2 = strlen(buff2); for (char const * const *q = getExeList(); (NULL != *q); q++) { strcpy(buff1 +len1, *q); strcpy(buff2 +len2, *q); if (!access(buff1, X_OK)) // Check the given path return (buff1); if (!access(buff2, X_OK)) // Check against the file system root return (buff2); } } return (*list); } char const *getCCP() { // C++ Compiler static char *list[] = { "/bin/CC", "/bin/ccp", "/usr/bin/CC", "/usr/bin/ccp", "/usr/ucb/CC", "/usr/ucb/ccp", "/usr/lang/CC", "/usr/lang/ccp", "/opt/SUNWspro/bin/CC", "/opt/SUNWspro/bin/ccp", "${RELEASE}/SC1.0/CC", "${RELEASE}/SC1.0/ccp", "/usr/local/bin/gcc", "${Init}/bin/cl", "/usr/bin/g++", // 002 NULL }; return(findName(list)); } char const *getCPP() { // C Preprocessor static char *list[] = { "/bin/cpp", "/usr/bin/cpp", "/usr/ucb/cpp", "/usr/lang/cpp", "/opt/SUNWspro/bin/cpp", "${RELEASE}/SC1.0/cpp", NULL }; return(findName(list)); } char const *getCC() { // C Compiler static char *list[] = { "/bin/cc", "/usr/ucb/cc", "/usr/bin/cc", "/usr/lang/cc", "/opt/SUNWspro/bin/cc", "${RELEASE}/SC1.0/cc", "${Init}/bin/cl", "/usr/bin/gcc", // 002 NULL }; return(findName(list)); } char const *getJava() { // C Compiler static char *list[] = { "/usr/bin/javac", "javac", NULL }; return(findName(list)); } char const *getSH() { // C Compiler static char *list[] = { "/bin/sh", NULL }; return(findName(list)); } char const *getCSH() { // C Compiler static char *list[] = { "/bin/csh", NULL }; return(findName(list)); } char const *getTmpDir() { const char *path = "/tmp"; // UNIX - default #if defined (INTEL_NT) || defined (INTEL_9X) if (NULL != (path = Tenv::appGet("TMP"))) { if (access((char*)path, F_OK) || !isDir(path)) { // Does not exist path = NULL; } } if ((NULL == path) && (NULL != (path = Tenv::appGet("TEMP")))) { if (access((char*)path, F_OK) || !isDir(path)) { // Does not exist path = NULL; } } if (NULL == path) { // PC - default char buff[512]; sprintf(buff, "%s/tmp", Tenv::appGet("ROOTDIR")); path = buff; } #endif return(path); } /************* END OF FILE **************************************************/
LaMaisonOrchard/Sire
sire/machine.cpp
C++
gpl-2.0
4,814
require 'rails_helper' RSpec.shared_context 'some assigned reviews and some unassigned reviews' do let!(:user) { create(:user) } let!(:review_assigned1) { create(:review, by_user: user.login) } let!(:review_assigned2) { create(:review, by_user: user.login) } let!(:review_unassigned1) { create(:review, by_user: user.login) } let!(:review_unassigned2) { create(:review, by_user: user.login) } let!(:history_element1) do create(:history_element_review_assigned, op_object_id: review_assigned1.id, user_id: user.id) end let!(:history_element2) do create(:history_element_review_assigned, op_object_id: review_assigned2.id, user_id: user.id) end let!(:history_element3) do create(:history_element_review_accepted, op_object_id: review_assigned2.id, user_id: user.id) end let!(:history_element4) do create(:history_element_review_accepted, op_object_id: review_unassigned1.id, user_id: user.id) end end RSpec.describe Review do let(:project) { create(:project_with_package, name: 'Apache', package_name: 'apache2') } let(:package) { project.packages.first } let(:user) { create(:user, login: 'King') } let(:group) { create(:group, title: 'Staff') } it { is_expected.to belong_to(:bs_request).touch(true) } describe 'validations' do it 'is not allowed to specify by_user and any other reviewable' do [:by_group, :by_project, :by_package].each do |reviewable| review = Review.create(:by_user => user.login, reviewable => 'not-existent-reviewable') expect(review.errors.messages[:base]). to eq(['it is not allowed to have more than one reviewer entity: by_user, by_group, by_project, by_package']) end end it 'is not allowed to specify by_group and any other reviewable' do [:by_project, :by_package].each do |reviewable| review = Review.create(:by_group => group.title, reviewable => 'not-existent-reviewable') expect(review.errors.messages[:base]). to eq(['it is not allowed to have more than one reviewer entity: by_user, by_group, by_project, by_package']) end end end describe '.assigned' do include_context 'some assigned reviews and some unassigned reviews' subject { Review.assigned } it { is_expected.to match_array([review_assigned1, review_assigned2]) } end describe '.unassigned' do include_context 'some assigned reviews and some unassigned reviews' subject { Review.unassigned } it { is_expected.to match_array([review_unassigned1, review_unassigned2]) } end describe '.set_associations' do context 'with valid attributes' do it 'sets user association when by_user object exists' do review = create(:review, by_user: user.login) expect(review.user).to eq(user) expect(review.by_user).to eq(user.login) end it 'sets group association when by_group object exists' do review = create(:review, by_group: group.title) expect(review.group).to eq(group) expect(review.by_group).to eq(group.title) end it 'sets project association when by_project object exists' do review = create(:review, by_project: project.name) expect(review.project).to eq(project) expect(review.by_project).to eq(project.name) end it 'sets package and project associations when by_package and by_project object exists' do review = create(:review, by_project: project.name, by_package: package.name) expect(review.package).to eq(package) expect(review.by_package).to eq(package.name) expect(review.project).to eq(project) expect(review.by_project).to eq(project.name) end end context 'with invalid attributes' do let!(:nobody) { create(:user_nobody) } it 'does not set user association when by_user object does not exist' do review = Review.new(by_user: 'not-existent') expect(review.user).to eq(nil) expect(review.valid?).to eq(false) end it 'does not set user association when by_user object is _nobody_' do review = Review.new(by_user: nobody) expect(review.user).to eq(nil) expect(review.valid?).to eq(false) expect(review.errors.messages[:base]). to eq(["Couldn't find user #{nobody.login}"]) end it 'does not set group association when by_group object does not exist' do review = Review.new(by_group: 'not-existent') expect(review.group).to eq(nil) expect(review.valid?).to eq(false) end it 'does not set project association when by_project object does not exist' do review = Review.new(by_project: 'not-existent') expect(review.project).to eq(nil) expect(review.valid?).to eq(false) end it 'does not set project and package associations when by_project and by_package object does not exist' do review = Review.new(by_project: 'not-existent', by_package: 'not-existent') expect(review.package).to eq(nil) expect(review.valid?).to eq(false) end it 'does not set package association when by_project parameter is missing' do review = Review.new(by_package: package.name) expect(review.package).to eq(nil) expect(review.valid?).to eq(false) end end end describe '#accepted_at' do let!(:user) { create(:user) } let(:review_state) { :accepted } let!(:review) do create( :review, by_user: user.login, state: review_state ) end let!(:history_element_review_accepted) do create( :history_element_review_accepted, review: review, user: user, created_at: Faker::Time.forward(1) ) end context 'with a review assigned to and assigned to state = accepted' do let!(:review2) do create( :review, by_user: user.login, review_id: review.id, state: :accepted ) end let!(:history_element_review_accepted2) do create( :history_element_review_accepted, review: review2, user: user, created_at: Faker::Time.forward(2) ) end subject { review.accepted_at } it { is_expected.to eq(history_element_review_accepted2.created_at) } end context 'with a review assigned to and assigned to state != accepted' do let!(:review2) do create( :review, by_user: user.login, review_id: review.id, updated_at: Faker::Time.forward(2), state: :new ) end subject { review.accepted_at } it { is_expected.to eq(nil) } end context 'with no reviewed assigned to and state = accepted' do subject { review.accepted_at } it { is_expected.to eq(history_element_review_accepted.created_at) } end context 'with no reviewed assigned to and state != accepted' do let(:review_state) { :new } subject { review.accepted_at } it { is_expected.to eq(nil) } end end describe '#declined_at' do let!(:user) { create(:user) } let(:review_state) { :declined } let!(:review) do create( :review, by_user: user.login, state: review_state ) end let!(:history_element_review_declined) do create( :history_element_review_declined, review: review, user: user, created_at: Faker::Time.forward(1) ) end context 'with a review assigned to and assigned to state = declined' do let!(:review2) do create( :review, by_user: user.login, review_id: review.id, state: :declined ) end let!(:history_element_review_declined2) do create( :history_element_review_declined, review: review2, user: user, created_at: Faker::Time.forward(2) ) end subject { review.declined_at } it { is_expected.to eq(history_element_review_declined2.created_at) } end context 'with a review assigned to and assigned to state != declined' do let!(:review2) do create( :review, by_user: user.login, review_id: review.id, updated_at: Faker::Time.forward(2), state: :new ) end subject { review.declined_at } it { is_expected.to eq(nil) } end context 'with no reviewed assigned to and state = declined' do subject { review.declined_at } it { is_expected.to eq(history_element_review_declined.created_at) } end context 'with no reviewed assigned to and state != declined' do let(:review_state) { :new } subject { review.declined_at } it { is_expected.to eq(nil) } end end describe '#validate_not_self_assigned' do let!(:user) { create(:user) } let!(:review) { create(:review, by_user: user.login) } context 'assigned to itself' do before { review.review_id = review.id } subject! { review.valid? } it { expect(review.errors[:review_id].count).to eq(1) } end context 'assigned to a different review' do let!(:review2) { create(:review, by_user: user.login) } before { review.review_id = review2.id } subject! { review.valid? } it { expect(review.errors[:review_id].count).to eq(0) } end end describe '#validate_non_symmetric_assignment' do let!(:user) { create(:user) } let!(:review) { create(:review, by_user: user.login) } let!(:review2) { create(:review, by_user: user.login, review_id: review.id) } context 'review1 is assigned to review2 which is already assigned to review1' do before { review.review_id = review2.id } subject! { review.valid? } it { expect(review.errors[:review_id].count).to eq(1) } end context 'review1 is assigned to review3' do let!(:review3) { create(:review, by_user: user.login) } before { review.review_id = review3.id } subject! { review.valid? } it { expect(review.errors[:review_id].count).to eq(0) } end end describe '#update_caches' do RSpec.shared_examples "the subject's cache is reset when it's review changes" do before do Timecop.travel(1.minute) @cache_key = subject.cache_key review.state = :accepted review.save subject.reload end it { expect(subject.cache_key).not_to eq(@cache_key) } end context 'by_user' do let!(:review) { create(:user_review) } subject { review.user } it_should_behave_like "the subject's cache is reset when it's review changes" end context 'by_group' do let(:groups_user) { create(:groups_user) } let(:group) { groups_user.group } let(:user) { groups_user.user } let!(:review) { create(:review, by_group: group) } it_should_behave_like "the subject's cache is reset when it's review changes" do subject { user } end it_should_behave_like "the subject's cache is reset when it's review changes" do subject { group } end end context 'by_package with a direct relationship' do let(:relationship_package_user) { create(:relationship_package_user) } let(:package) { relationship_package_user.package } let!(:review) { create(:review, by_package: package, by_project: package.project) } subject { relationship_package_user.user } it_should_behave_like "the subject's cache is reset when it's review changes" end context 'by_package with a group relationship' do let(:relationship_package_group) { create(:relationship_package_group) } let(:package) { relationship_package_group.package } let(:group) { relationship_package_group.group } let(:groups_user) { create(:groups_user, group: group) } let!(:user) { groups_user.user } let!(:review) { create(:review, by_package: package, by_project: package.project) } it_should_behave_like "the subject's cache is reset when it's review changes" do subject { user } end it_should_behave_like "the subject's cache is reset when it's review changes" do subject { group } end end context 'by_project with a direct relationship' do let(:relationship_project_user) { create(:relationship_project_user) } let(:project) { relationship_project_user.project } let!(:review) { create(:review, by_project: project) } subject { relationship_project_user.user } it_should_behave_like "the subject's cache is reset when it's review changes" end context 'by_project with a group relationship' do let(:relationship_project_group) { create(:relationship_project_group) } let(:project) { relationship_project_group.project } let(:group) { relationship_project_group.group } let(:groups_user) { create(:groups_user, group: group) } let!(:user) { groups_user.user } let!(:review) { create(:review, by_project: project) } it_should_behave_like "the subject's cache is reset when it's review changes" do subject { user } end it_should_behave_like "the subject's cache is reset when it's review changes" do subject { group } end end end describe '#reviewable_by?' do let(:other_user) { create(:user, login: 'bob') } let(:other_group) { create(:group, title: 'my_group') } let(:other_project) { create(:project_with_package, name: 'doc:things', package_name: 'less') } let(:other_package) { other_project.packages.first } let(:other_package_with_same_name) { create(:package, name: package.name) } let(:review_by_user) { create(:review, by_user: user.login) } let(:review_by_group) { create(:review, by_group: group.title) } let(:review_by_project) { create(:review, by_project: project.name) } let(:review_by_package) { create(:review, by_project: project.name, by_package: package.name) } it 'returns true if review configuration matches provided hash' do expect(review_by_user.reviewable_by?(by_user: user.login)).to be(true) expect(review_by_group.reviewable_by?(by_group: group.title)).to be(true) expect(review_by_project.reviewable_by?(by_project: project.name)).to be(true) expect(review_by_package.reviewable_by?(by_package: package.name, by_project: package.project.name)).to be(true) end it 'returns false if review configuration does not match provided hash' do expect(review_by_user.reviewable_by?(by_user: other_user.login)).to be_falsy expect(review_by_group.reviewable_by?(by_group: other_group.title)).to be_falsy expect(review_by_project.reviewable_by?(by_project: other_project.name)).to be_falsy expect(review_by_package.reviewable_by?(by_package: other_package.name, by_project: other_package.project.name)).to be_falsy expect(review_by_package.reviewable_by?(by_package: other_package_with_same_name.name, by_project: other_package_with_same_name.project.name)).to be_falsy end end describe '.new_from_xml_hash' do let(:request_xml) do "<request> <review state='accepted' by_user='#{user}'/> </request>" end let(:request_hash) { Xmlhash.parse(request_xml) } let(:review_hash) { request_hash['review'] } subject { Review.new_from_xml_hash(review_hash) } it 'initalizes the review in state :new' do expect(subject.state).to eq(:new) end end end
Ana06/open-build-service
src/api/spec/models/review_spec.rb
Ruby
gpl-2.0
15,667
#include "\z\ifa3_comp_ace\addons\cannon\script_component.hpp"
bux/IFA3_ACE_COMPAT
addons/cannon/functions/script_component.hpp
C++
gpl-2.0
62
// -*- C++ -*- /*! \file numerical/random/poisson/PoissonPdfCdfAtTheMode.h \brief Probability density function and cumulative distribution function evaluated at the mode for the Poisson distribution. */ #if !defined(__numerical_PoissonPdfCdfAtTheMode_h__) #define __numerical_PoissonPdfCdfAtTheMode_h__ #include "PoissonCdf.h" #include "../../interpolation/hermite.h" #include "../../../ads/array/Array.h" // If we are debugging the whole numerical package. #if defined(DEBUG_numerical) && !defined(DEBUG_PoissonPdfCdfAtTheMode) #define DEBUG_PoissonPdfCdfAtTheMode #endif BEGIN_NAMESPACE_NUMERICAL //! Probability density function and cumulative distribution function evaluated at the mode for the Poisson distribution. /*! \param T The number type. By default it is double. CONTINUE. */ template<typename T = double> class PoissonPdfCdfAtTheMode { // // Public types. // public: //! The number type. typedef T Number; // // Member data. // private: // The lower bound of the range of means. Number _lowerBound; // Factor that will scale the argument to the index. Number _scaleToIndex; // Polynomial coefficients. ads::Array<1,Number> _coefficients; // // Not implemented. // private: //! Default constructor not implemented. PoissonPdfCdfAtTheMode(); public: //! Construct from the range of means and the number of patches per unit. PoissonPdfCdfAtTheMode(int closedLowerBound, int openUpperBound, int numberOfPatchesPerUnit); //! Copy constructor. /*! \note This function is expensive. */ PoissonPdfCdfAtTheMode(const PoissonPdfCdfAtTheMode& other); //! Assignment operator. /*! \note This function is expensive. */ PoissonPdfCdfAtTheMode& operator=(const PoissonPdfCdfAtTheMode& other); //! Destructor. ~PoissonPdfCdfAtTheMode() {} //! Evaluate the probability density function and cumulative distribution function at the mode. void evaluate(Number mean, Number* pdf, Number* cdf) const; }; END_NAMESPACE_NUMERICAL #define __numerical_random_PoissonPdfCdfAtTheMode_ipp__ #include "PoissonPdfCdfAtTheMode.ipp" #undef __numerical_random_PoissonPdfCdfAtTheMode_ipp__ #endif
tdsmith/celltool
celltool/numerics/stlib/numerical/random/poisson/PoissonPdfCdfAtTheMode.h
C
gpl-2.0
2,194
#include <linux/kernel.h> #include <linux/i2c.h> #include <linux/mutex.h> #include <linux/delay.h> #include "KXSD9_regs.h" #include "KXSD9_main.h" #include "KXSD9_dev.h" #include "common.h" #define I2C_M_WR 0x0000 enum { eTRUE, eFALSE, }dev_struct_status_t; typedef struct { /*Range and Threshold*/ unsigned short R_T; /*Operational Bandwidth*/ unsigned short BW; /*Sensitivity*/ KXSD9_sensitivity_t sensitivity; /*zero-g offset*/ KXSD9_zero_g_offset_t zero_g_offset; }dev_settings_t; typedef struct { /*ENABLE in CTRL_REGSB*/ unsigned short dev_state; /*MOTlen in CTRL_REGSB*/ unsigned short mwup; /*MOTLat in CTRL_REGSC*/ unsigned short mwup_rsp; }dev_mode_t; typedef struct { /*Any function which - views/modifies the fields of this structure - does i2c communication should lock the mutex before doing so. Recursive locking should not be done. In this file all the exported functions will take care of this. The static functions will not deal with the mutex*/ struct mutex lock; struct i2c_client const *client; dev_mode_t mode; dev_settings_t settings; /* This field will be checked by all the functions exported by this file (except the init function), to validate the the fields of this structure. if eTRUE: the fileds are valid if eFALSE: do not trust the values of the fields of this structure*/ unsigned short valid; /* OMS use this value. If the gap between old x(y) and new x(y) is bigger than threshhold, OMS know that new data was received */ unsigned short threshold; }KXSD9_device_t; /*extern functions*/ /**********************************************/ /*All the exported functions which view or modify the device state/data, do i2c com will have to lock the mutex before doing so*/ /**********************************************/ int KXSD9_dev_init(struct i2c_client *client, KXSD9_module_param_t *); int KXSD9_dev_exit(void); void KXSD9_dev_mutex_init(void); int KXSD9_dev_mwup_status(void); int KXSD9_dev_get_sensitivity(KXSD9_sensitivity_t *); int KXSD9_dev_get_zero_g_offset(KXSD9_zero_g_offset_t *); int KXSD9_dev_get_acc(KXSD9_acc_t *); int KXSD9_dev_get_default(KXSD9_default_t *); int KXSD9_dev_set_range( int ) ; short KXSD9_dev_get_bandwidth( void ) ; int KXSD9_dev_set_bandwidth( int ) ; int KXSD9_dev_set_operation_mode( int, int ) ; int KXSD9_dev_set_status( int, int ) ; int KXSd9_dev_get_status( void ) ; int KXSD9_dev_enable(void); int KXSD9_dev_disable(void); extern int KXSD9_dev_mwup_enb(unsigned short); extern int KXSD9_dev_mwup_dsb(void); /***********************************************/ /*static functions*/ /**********************************************/ static void set_val(unsigned char *, unsigned char *, KXSD9_module_param_t *); static inline int get_X_acc(unsigned short *); static inline int get_Y_acc(unsigned short *); static inline int get_Z_acc(unsigned short *); static int get_acc(char , char , unsigned short *); static int i2c_read(unsigned char, unsigned char *); static int i2c_write(unsigned char, unsigned char); /**********************************************/ /*KXSD9 device structure*/ static KXSD9_device_t KXSD9_dev = { .client = NULL, .valid = eFALSE, }; int KXSD9_dev_init(struct i2c_client *client, KXSD9_module_param_t *param) { int ret = 0; int i = 0; int check = 0; /*these have to be initialized to 0*/ unsigned char ctrl_regsc=0, ctrl_regsb=0; trace_in() ; mutex_lock(&(KXSD9_dev.lock)); /*KXSD9_dev.client should be set before doing i2c communication At this point KXSD9_dev.valid = eFALSE. This is the only point where i2c communication will be done with KXSD9_dev.valid = eFALSE In all other places the caller should ensure that KXSD9_dev.valid = eTRUE before doing i2c communication*/ KXSD9_dev.client = client; CTRL_REGSB_BITSET_KXSD9_nor_op(&ctrl_regsb); CTRL_REGSB_BITSET_clk_ctrl_on(&ctrl_regsb); KXSD9_dev.mode.dev_state = ENABLED; KXSD9_dev.settings.sensitivity.error_RT = 25; KXSD9_dev.settings.zero_g_offset.counts = 2048; KXSD9_dev.settings.zero_g_offset.error_RT = 205; set_val(&ctrl_regsb, &ctrl_regsc, param); for( i = 0 ; i < 10 ; i++ ) { if( (ret = i2c_write(CTRL_REGSB,ctrl_regsb)) < 0 ) { printk("%s: KXSD9_dev_init->i2c_write 1 failed, ret= %d, i= %d\n", __FUNCTION__, ret, i ); mdelay(20); } else { check++ ; break ; } } /*Delay required for the stablization of device after enabling*/ mdelay(20); for( i = 0 ; i < 10 ; i++ ) { if( (ret = i2c_write(CTRL_REGSC,ctrl_regsc)) < 0 ) { printk("%s: KXSD9_dev_init->i2c_write 2 failed, ret= %d, i= %d\n", __FUNCTION__, ret, i ); mdelay(20); } else { check++ ; break ; } } if( check == 2 ) { KXSD9_dev.valid = eTRUE; printk("%s: KXSD9_dev_init, KXSD9_dev.valid == eTRUE, check= %d\n", __FUNCTION__, check ); } else if( KXSD9_dev.valid != eTRUE ) { KXSD9_dev.valid = eTRUE; printk("%s: KXSD9_dev_init, Error occured, but set eTrue forcely, ret= %d\n", __FUNCTION__, ret ); } else { printk("%s: KXSD9_dev_init, unknown check flag, check= %d\n", __FUNCTION__, check); } mutex_unlock(&(KXSD9_dev.lock)); trace_out() ; return ret; } /*Helper function: sets the values for CTRL regs and KXSD9_dev struct. *Should be called only from init*/ static void set_val(unsigned char *ctrl_regsb, unsigned char *ctrl_regsc, KXSD9_module_param_t *param) { trace_in() ; switch(param->mwup) { case ENABLED: CTRL_REGSB_BITSET_mwup_enb(ctrl_regsb); KXSD9_dev.mode.mwup = ENABLED; switch( param->mwup_rsp ) { case LATCHED: default: CTRL_REGSC_BITSET_mwup_rsp_latchd(ctrl_regsc); KXSD9_dev.mode.mwup_rsp = LATCHED; break; case UNLATCHED: CTRL_REGSC_BITSET_mwup_rsp_unlatchd(ctrl_regsc); KXSD9_dev.mode.mwup_rsp = UNLATCHED; break; } break; case DISABLED: default: CTRL_REGSB_BITSET_mwup_disb(ctrl_regsb); KXSD9_dev.mode.mwup = DISABLED; KXSD9_dev.mode.mwup_rsp = DONT_CARE; break; } switch(param->BW) { case BW50: default: CTRL_REGSC_BITSET_BW50(ctrl_regsc); KXSD9_dev.settings.BW = BW50; break; case BW100: CTRL_REGSC_BITSET_BW100(ctrl_regsc); KXSD9_dev.settings.BW = BW100; break; case BW500: CTRL_REGSC_BITSET_BW500(ctrl_regsc); KXSD9_dev.settings.BW = BW500; break; case BW1000: CTRL_REGSC_BITSET_BW1000(ctrl_regsc); KXSD9_dev.settings.BW = BW1000; break; case BW2000: CTRL_REGSC_BITSET_BW2000(ctrl_regsc); KXSD9_dev.settings.BW = BW2000; break; case BW_no_filter: CTRL_REGSC_BITSET_BW_no_filter(ctrl_regsc); KXSD9_dev.settings.BW = BW_no_filter; break; } switch(param->R_T) { case R2g_T1g: default: CTRL_REGSC_BITSET_R2g_T1g(ctrl_regsc); KXSD9_dev.settings.R_T= R2g_T1g; KXSD9_dev.settings.sensitivity.counts_per_g = 819; break; case R2g_T1p5g: CTRL_REGSC_BITSET_R2g_T1p5g(ctrl_regsc); KXSD9_dev.settings.R_T = R2g_T1p5g; KXSD9_dev.settings.sensitivity.counts_per_g = 819; break; case R4g_T2g: CTRL_REGSC_BITSET_R4g_T2g(ctrl_regsc); KXSD9_dev.settings.R_T = R4g_T2g; KXSD9_dev.settings.sensitivity.counts_per_g = 410; break; case R4g_T3g: CTRL_REGSC_BITSET_R4g_T3g(ctrl_regsc); KXSD9_dev.settings.R_T = R4g_T3g; KXSD9_dev.settings.sensitivity.counts_per_g = 410; break; case R6g_T3g: CTRL_REGSC_BITSET_R6g_T3g(ctrl_regsc); KXSD9_dev.settings.R_T = R6g_T3g; KXSD9_dev.settings.sensitivity.counts_per_g = 273; break; case R6g_T4p5g: CTRL_REGSC_BITSET_R6g_T4p5g(ctrl_regsc); KXSD9_dev.settings.R_T = R6g_T4p5g; KXSD9_dev.settings.sensitivity.counts_per_g = 273; break; case R8g_T4g: CTRL_REGSC_BITSET_R8g_T4g(ctrl_regsc); KXSD9_dev.settings.R_T = R8g_T4g; KXSD9_dev.settings.sensitivity.counts_per_g = 205; break; case R8g_T6g: CTRL_REGSC_BITSET_R8g_T6g(ctrl_regsc); KXSD9_dev.settings.R_T = R8g_T6g; KXSD9_dev.settings.sensitivity.counts_per_g = 205; break; } trace_out() ; } int KXSD9_dev_exit(void) { int ret = 0; printk("%s: START\n", __FUNCTION__ ); mutex_lock(&(KXSD9_dev.lock)); KXSD9_dev.client = NULL; KXSD9_dev.valid = eFALSE; mutex_unlock(&(KXSD9_dev.lock)); printk("%s: END\n", __FUNCTION__ ); return ret; } void KXSD9_dev_mutex_init(void) { trace_in() ; mutex_init(&(KXSD9_dev.lock)); trace_out() ; } int KXSD9_dev_mwup_status(void) { int ret; trace_in() ; mutex_lock(&(KXSD9_dev.lock)); if( (KXSD9_dev.valid == eFALSE) ||( KXSD9_dev.mode.dev_state == DISABLED ) ) { ret = N_OK; } else { ret = KXSD9_dev.mode.mwup; } mutex_unlock(&(KXSD9_dev.lock)); trace_out() ; return ret; } int KXSD9_dev_enable(void) { int ret = 0; unsigned char reg_data; trace_in() ; mutex_lock(&(KXSD9_dev.lock)); if( KXSD9_dev.valid == eFALSE ) { printk("%s: KXSD9_dev_enable called when DS is invalid\n", __FUNCTION__ ); ret = -1; } else if( (ret = i2c_read(CTRL_REGSB,&reg_data)) < 0 ) { printk("%s: KXSD9_dev_enable->i2c_read failed\n", __FUNCTION__ ); } else { CTRL_REGSB_BITSET_KXSD9_nor_op(&reg_data); CTRL_REGSB_BITSET_clk_ctrl_on(&reg_data); if( (ret = i2c_write(CTRL_REGSB, reg_data)) < 0 ) { printk("%s: KXSD9_dev_enable->i2c_write failed\n", __FUNCTION__ ); } else { /*Delay required for the stablization of device after enabling*/ mdelay(16); KXSD9_dev.mode.dev_state = ENABLED; } } mutex_unlock(&(KXSD9_dev.lock)); set_bit(KXSD9_ON, &KXSD9_status.status); trace_out() ; return ret; } int KXSD9_dev_disable(void) { int ret = 0; unsigned char reg_data; //trace_in() ; mutex_lock(&(KXSD9_dev.lock)); if( KXSD9_dev.valid == eFALSE ) { printk("%s: called when DS is invalid\n", __FUNCTION__ ); ret = -1; } else if( (ret = i2c_read(CTRL_REGSB,&reg_data)) < 0 ) { printk("%s: i2c_read failed\n", __FUNCTION__ ); } else { CTRL_REGSB_BITSET_KXSD9_standby(&reg_data); CTRL_REGSB_BITSET_clk_ctrl_off(&reg_data); if( (ret = i2c_write(CTRL_REGSB, reg_data)) < 0 ) { printk("%s: i2c_write failed\n", __FUNCTION__ ); } else { KXSD9_dev.mode.dev_state = DISABLED; } } mutex_unlock(&(KXSD9_dev.lock)); clear_bit(KXSD9_ON, &KXSD9_status.status); //trace_out() ; return ret; } int KXSD9_dev_mwup_enb(unsigned short mwup_rsp) { int ret = 0; unsigned char ctrl_regsb, ctrl_regsc, ctrl_regsb_bkup; unsigned short mwup_prev, mwup_rsp_prev; trace_in() ; mutex_lock(&(KXSD9_dev.lock)); mwup_prev = KXSD9_dev.mode.mwup; mwup_rsp_prev = KXSD9_dev.mode.mwup_rsp; if( KXSD9_dev.valid == eFALSE ) { printk("%s: KXSD9_dev_mwup_enb called with dev DS invalid\n", __FUNCTION__ ); ret = -1; } else if( KXSD9_dev.mode.dev_state == DISABLED ) { printk("%s: KXSD9_dev_mwup_enb: dev is DISABLED\n", __FUNCTION__ ); ret = -1; } else if( (ret = i2c_read(CTRL_REGSB, &ctrl_regsb)) < 0 ) { printk("%s: KXSD9_dev_mwup_enb i2c_read1 failed\n", __FUNCTION__ ); } else if( (ret = i2c_read(CTRL_REGSC, &ctrl_regsc)) < 0 ) { printk("%s: KXSD9_dev_mwup_enb i2c_read2 failed\n", __FUNCTION__ ); } else { ctrl_regsb_bkup = ctrl_regsb; CTRL_REGSB_BITSET_mwup_enb(&ctrl_regsb); KXSD9_dev.mode.mwup = ENABLED; switch( mwup_rsp ) { case LATCHED: CTRL_REGSC_BITSET_mwup_rsp_latchd(&ctrl_regsc); KXSD9_dev.mode.mwup_rsp = LATCHED; break; case UNLATCHED: CTRL_REGSC_BITSET_mwup_rsp_unlatchd(&ctrl_regsc); KXSD9_dev.mode.mwup_rsp = UNLATCHED; break; /* [2009.10.12 / BSP / ACCEl ] joon.c.baek * when a set DONT_CARE * default unlatched */ case DONT_CARE: CTRL_REGSC_BITSET_mwup_rsp_unlatchd(&ctrl_regsc); KXSD9_dev.mode.mwup_rsp = UNLATCHED; break; default: ret = -EINVAL; printk("%s: KXSD9_dev_mwup_enb invalid argument- mwup_rsp: %d\n", __FUNCTION__, mwup_rsp ); break; } if( ret == 0 ) { if( (ret = i2c_write(CTRL_REGSB,ctrl_regsb)) < 0 ) { printk("%s: KXSD9_dev_mwup_enb->i2c_write 1 failed\n", __FUNCTION__ ); } else if( (ret = i2c_write(CTRL_REGSC,ctrl_regsc)) < 0 ) { printk("%s: KXSD9_dev_mwup_enb->i2c_write 2 failed\n", __FUNCTION__ ); /*In this case the motion wakeup will be enabled with the previous rsp type (unpredictable state from user's point of view), so we will try to revert. If that fails we'll mark KXSD9_dev as invalid*/ if( (ret = i2c_write(CTRL_REGSB, ctrl_regsb_bkup)) < 0 ) { printk("%s: FATAL: the device is marked invalid\n", __FUNCTION__ ); KXSD9_dev.valid = eFALSE; } } } } if(ret < 0) { KXSD9_dev.mode.mwup = mwup_prev; KXSD9_dev.mode.mwup_rsp = mwup_rsp_prev; } debug("mwup = %s", (KXSD9_dev.mode.mwup == ENABLED) ? "ENABLED" : "DISABLED" ); debug("mwup_rsp = %s", (KXSD9_dev.mode.mwup_rsp == LATCHED) ? "LATCHED" : ((KXSD9_dev.mode.mwup_rsp == UNLATCHED) ? "UNLATCHED": "DONT_CARE")); mutex_unlock(&(KXSD9_dev.lock)); trace_out() ; return ret; } int KXSD9_dev_mwup_disb(void) { int ret = 0; unsigned char ctrl_regsb; unsigned short mwup_prev; trace_in() ; mutex_lock(&(KXSD9_dev.lock)); mwup_prev = KXSD9_dev.mode.mwup; if( KXSD9_dev.valid == eFALSE ) { printk("%s: KXSD9_dev_mwup_disb called with dev DS invalid\n", __FUNCTION__ ); ret = -1; } else if( KXSD9_dev.mode.dev_state == DISABLED ) { printk("%s: KXSD9_dev_mwup_disb: dev is DISABLED\n", __FUNCTION__ ); ret = -1; } else if( KXSD9_dev.mode.mwup == DISABLED ) { printk("%s: mwup already disabled\n", __FUNCTION__ ); } else if( (ret = i2c_read(CTRL_REGSB, &ctrl_regsb)) < 0 ) { printk("%s: KXSD9_dev_mwup_enb i2c_read failed\n", __FUNCTION__ ); } else { CTRL_REGSB_BITSET_mwup_disb(&ctrl_regsb); KXSD9_dev.mode.mwup = DISABLED; if( (ret = i2c_write(CTRL_REGSB,ctrl_regsb)) < 0 ) { printk("%s: KXSD9_dev_mwup_disb->i2c_write failed\n", __FUNCTION__ ); } } if(ret < 0) { KXSD9_dev.mode.mwup = mwup_prev; } else { //KXSD9_waitq_wkup_processes(); } mutex_unlock(&(KXSD9_dev.lock)); trace_out() ; return ret; } int KXSD9_dev_get_sensitivity(KXSD9_sensitivity_t *sensitivity) { int ret = 0; trace_in() ; mutex_lock(&(KXSD9_dev.lock)); if( KXSD9_dev.valid == eFALSE ) { printk("%s: KXSD9_dev_get_sensitivity called with dev DS invalid\n", __FUNCTION__ ); ret = -1; } else { sensitivity->counts_per_g = KXSD9_dev.settings.sensitivity.counts_per_g; sensitivity->error_RT = KXSD9_dev.settings.sensitivity.error_RT; } mutex_unlock(&(KXSD9_dev.lock)); trace_out() ; return ret; } int KXSD9_dev_get_zero_g_offset(KXSD9_zero_g_offset_t *offset) { int ret = 0; trace_in() ; mutex_lock(&(KXSD9_dev.lock)); if( KXSD9_dev.valid == eFALSE ) { printk("%s: KXSD9_dev_get_zero_g_offset called with dev DS invalid\n", __FUNCTION__ ); ret = -1; } else { offset->counts= KXSD9_dev.settings.zero_g_offset.counts; offset->error_RT = KXSD9_dev.settings.zero_g_offset.error_RT; } mutex_unlock(&(KXSD9_dev.lock)); trace_out() ; return ret; } /* Add for AKMD2, joon.c.baek */ int KXSD9_dev_set_range( int param ) { int ret = 0 ; KXSD9_module_param_t temp_param ; unsigned char ctrl_regsc=0, ctrl_regsb=0; trace_in() ; temp_param.mwup = KXSD9_dev.mode.mwup; temp_param.mwup_rsp = KXSD9_dev.mode.mwup_rsp; temp_param.R_T = KXSD9_dev.settings.R_T ; temp_param.BW = KXSD9_dev.settings.BW ; mutex_lock(&(KXSD9_dev.lock)); if( KXSD9_dev.valid == eFALSE ) { printk("%s: KXSD9_dev_set_range called with dev DS invalid\n", __FUNCTION__ ); ret = -1; } else { switch( param ) { case R2g_T1g: temp_param.R_T = R2g_T1g ; break ; case R2g_T1p5g: temp_param.R_T = R2g_T1p5g ; break ; case R4g_T2g: temp_param.R_T = R4g_T2g ; break ; case R4g_T3g: temp_param.R_T = R4g_T3g ; break ; case R6g_T3g: temp_param.R_T = R6g_T3g ; break ; case R6g_T4p5g: temp_param.R_T = R6g_T4p5g ; break ; case R8g_T4g: temp_param.R_T = R8g_T4g ; break ; case R8g_T6g: temp_param.R_T = R8g_T6g ; break ; default: printk("%s: KXSD9_dev_set_range called invalid\n", __FUNCTION__); ret = -1 ; break ; set_val(&ctrl_regsb, &ctrl_regsc, &temp_param); } } mutex_unlock(&(KXSD9_dev.lock)); trace_out() ; return ret ; } unsigned short KXSD9_dev_get_threshold( void ) { trace_in(); trace_out(); return KXSD9_dev.threshold; } void KXSD9_dev_set_threshold( unsigned short new_threshold ) { trace_in(); KXSD9_dev.threshold = new_threshold; trace_out(); } short KXSD9_dev_get_bandwidth( void ) { trace_in() ; trace_out() ; return KXSD9_dev.settings.BW ; } int KXSD9_dev_set_bandwidth( int param ) { int ret = 0 ; KXSD9_module_param_t temp_param ; unsigned char ctrl_regsc=0, ctrl_regsb=0; trace_in() ; temp_param.mwup = KXSD9_dev.mode.mwup; temp_param.mwup_rsp = KXSD9_dev.mode.mwup_rsp; temp_param.R_T = KXSD9_dev.settings.R_T ; temp_param.BW = KXSD9_dev.settings.BW ; mutex_lock(&(KXSD9_dev.lock)); if( KXSD9_dev.valid == eFALSE ) { printk("%s: KXSD9_dev_set_bandwidth called with dev DS invalid\n", __FUNCTION__); ret = -1; } else { switch( param ) { case BW50: temp_param.BW = BW50 ; break ; case BW100: temp_param.BW = BW100 ; break ; case BW500: temp_param.R_T = BW500 ; break ; case BW1000: temp_param.R_T = BW1000 ; break ; case BW2000: temp_param.R_T = BW2000 ; break ; case BW_no_filter: temp_param.R_T = BW_no_filter ; break ; default: printk("%s: KXSD9_dev_set_bandwidth called invalid\n", __FUNCTION__); ret = -1 ; break ; set_val(&ctrl_regsb, &ctrl_regsc, &temp_param); } } mutex_unlock(&(KXSD9_dev.lock)); trace_out() ; return ret ; } int KXSD9_dev_set_status( int module, int param ) { //trace_in() ; if( param == STANDBY ) { KXSD9_operation_mode = KXSD9_operation_mode & (~(1 << module)) ; } else if( param == NORMAL ) { KXSD9_operation_mode = KXSD9_operation_mode | ( 1 << module ) ; } else { printk( "KXSD9_dev_get_status() Fault argument!!! module= %d, param=%d\n", module, param ) ; } //trace_out() ; return KXSD9_operation_mode ; } int KXSD9_dev_get_status( void ) { //trace_in() ; //trace_out() ; return KXSD9_operation_mode ; } int KXSD9_dev_set_operation_mode( int module, int param ) { int status= 0 ; trace_in() ; status= KXSD9_dev_set_status( module, param ) ; switch( status ) { case STANDBY: printk("%s: STANDBY\n", __FUNCTION__ ); // KXSD9_dev_disable() ; // JUN : ¼öÆòº¸Á¤ ÈÄ dev is DISABLED by dev_state [0] ¹ß»ý ÇÏ¿© ¸·À½ break ; case ONLYACCEL: case ONLYCOMPASS: case ACCELCOMPASS: KXSD9_dev_enable() ; break ; default: KXSD9_dev_disable() ; printk("%s: Fault argument!!! Disable of all in force\n", __FUNCTION__ ); break ; } switch( status ) { case STANDBY: KXSD9_report_func= NULL ; printk("%s: STANDBY\n", __FUNCTION__ ); break ; case ONLYACCEL: KXSD9_report_func= KXSD9_report_sensorhal ; printk("%s: ONLYACCEL\n", __FUNCTION__ ); break ; case ONLYCOMPASS: KXSD9_report_func= KXSD9_report_akmd2 ; printk("%s: ONLYCOMPASS\n", __FUNCTION__ ); break ; case ACCELCOMPASS: KXSD9_report_func= KXSD9_report_sensorhal_akmd2 ; printk("%s: ACCELCOMPASS\n", __FUNCTION__ ); break ; default: KXSD9_report_func= NULL ; printk("%s: Fault argument!!! Disable of all in force\n", __FUNCTION__ ); break ; } trace_out() ; return status ; } extern KXSD9_acc_t cal_data; int KXSD9_dev_get_acc(KXSD9_acc_t *acc) { int ret = 0; //trace_in() ; mutex_lock(&(KXSD9_dev.lock)); if( KXSD9_dev.valid == eFALSE ) { printk("[ACCEL] %s: called with dev DS invalid\n", __FUNCTION__); ret = -1; } else if( KXSD9_dev.mode.dev_state == DISABLED ) { // printk("[ACCEL] %s: dev is DISABLED by dev_state [%d]\n", __FUNCTION__, KXSD9_dev.mode.dev_state); ret = -1; } else if( KXSD9_dev.mode.mwup == ENABLED ) { printk("[ACCEL] %s: trying to read the acc when the motion wakeup feature is enabled\n", __FUNCTION__); ret = -1; } else if( acc == NULL ) { ret = -1; } else { if( (ret = get_X_acc(&(acc->X_acc)) ) < 0 ) { printk("[ACCEL] %s: get_X_acc failed\n", __FUNCTION__ ); } else if( (ret = get_Y_acc(&(acc->Y_acc)) ) < 0 ) { printk("[ACCEL] %s: get_Y_acc failed\n", __FUNCTION__ ); } else if( (ret = get_Z_acc(&(acc->Z_acc)) ) < 0 ) { printk("[ACCEL] %s: get_Z_acc failed\n", __FUNCTION__ ); } acc->X_acc -= cal_data.X_acc; acc->Y_acc -= cal_data.Y_acc; acc->Z_acc -= cal_data.Z_acc; } mutex_unlock(&(KXSD9_dev.lock)); //trace_out() ; return ret; } int KXSD9_dev_get_default(KXSD9_default_t *acc) { int ret = 0; trace_in() ; acc->x1 = DEFAULT_ACC_X1; acc->y1 = DEFAULT_ACC_Y1; acc->z1 = DEFAULT_ACC_Z1; acc->x2 = DEFAULT_ACC_X2; acc->y2 = DEFAULT_ACC_Y2; acc->z2 = DEFAULT_ACC_Z2; trace_out() ; return ret; } static inline int get_X_acc(unsigned short *X_acc) { //trace_in() ; //trace_out() ; return get_acc(XOUT_H, XOUT_L, X_acc); } static inline int get_Y_acc(unsigned short *Y_acc) { //trace_in() ; //trace_out() ; return get_acc(YOUT_H, YOUT_L, Y_acc); } static inline int get_Z_acc(unsigned short *Z_acc) { //trace_in() ; //trace_out() ; return get_acc(ZOUT_H, ZOUT_L, Z_acc); } static int get_acc(char reg_H, char reg_L, unsigned short *acc) { int ret = 0; char datah,datal; unsigned short aux = 0; //trace_in() ; if( (ret = i2c_read( reg_H, &datah)) < 0 ) { printk("%s: i2c_read(_H) failed\n", __FUNCTION__ ); } else { if( (ret = i2c_read( reg_L , &datal)) < 0 ) { printk( "%s: i2c_read(_L) failed\n", __FUNCTION__ ); } else { aux = datah; aux<<= 8; aux|= datal; aux>>= 4; aux&= 0x0FFF; *acc = aux; } } //trace_out() ; return ret; } /*i2c read function*/ /*KXSD9_dev.client should be set before calling this function. If KXSD9_dev.valid = eTRUE then KXSD9_dev.client will b valid This function should be called from the functions in this file. The callers should check if KXSD9_dev.valid = eTRUE before calling this function. If it is eFALSE then this function should not be called. Init function is the only exception*/ static int i2c_read(unsigned char reg, unsigned char *data) { int ret = 0, i = 0; struct i2c_msg msg[1]; unsigned char aux[1]; //trace_in() ; if(KXSD9_dev.client->addr == NULL) { printk("%s: can't search i2c client adapter\n", __FUNCTION__); //trace_out(); return -ENODEV; } /* Write */ msg[0].addr = KXSD9_dev.client->addr; msg[0].flags = I2C_M_WR; msg[0].len = 1; aux[0] = reg; msg[0].buf = aux; for(i = 0; i < 10; i++) { ret = i2c_transfer(KXSD9_dev.client->adapter, msg, 1) == 1 ? 0 : -EIO; if (ret == 0) { break; } mdelay(1); } if(i == 10) { printk("%s: i2c_read->i2c_transfer failed, ret= %d\n", __FUNCTION__, ret ); //trace_out(); return ret; } /* Read */ msg[0].addr = KXSD9_dev.client->addr; msg[0].flags = I2C_M_RD; msg[0].len = 1; msg[0].buf = data; for(i = 0; i < 10; i++) { ret = i2c_transfer(KXSD9_dev.client->adapter, msg, 1) == 1 ? 0 : -EIO; if (ret == 0) { //trace_out(); return 0; } mdelay(1); } printk("%s: i2c_read->i2c_transfer failed, ret= %d\n", __FUNCTION__, ret ); //trace_out(); return ret; } /*i2c write function*/ /*KXSD9_dev.client should be set before calling this function. If KXSD9_dev.valid = eTRUE then KXSD9_dev.client will b valid This function should be called from the functions in this file. The callers should check if KXSD9_dev.valid = eTRUE before calling this function. If it is eFALSE then this function should not be called. Init function is the only exception*/ static int i2c_write( unsigned char reg, unsigned char data ) { int ret = 0, i = 0; struct i2c_msg msg[1]; unsigned char buf[2]; //trace_in() ; if(KXSD9_dev.client->addr == NULL) { printk("%s: can't search i2c client adapter\n", __FUNCTION__); //trace_out(); return -ENODEV; } /* Write */ msg[0].addr = KXSD9_dev.client->addr; msg[0].flags = I2C_M_WR; msg[0].len = 2; buf[0] = reg; buf[1] = data; msg[0].buf = buf; for (i = 0; i < 10; i++) { ret = i2c_transfer(KXSD9_dev.client->adapter, msg, 1) == 1 ? 0 : -EIO; if(ret == 0) { //trace_out(); return 0; } mdelay(1); } printk("%s: i2c_write->i2c_transfer failed, ret= %d\n", __FUNCTION__, ret ); //trace_out(); return ret; }
wtbdaaaa/i8320kernel
samsung/kxsd9-2.6.35/KXSD9_dev.c
C
gpl-2.0
29,262
--魂魄妖梦 function c20027.initial_effect(c) --special summon local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_SPSUMMON_PROC) e1:SetProperty(EFFECT_FLAG_UNCOPYABLE) e1:SetRange(LOCATION_HAND) e1:SetCondition(c20027.spcon) e1:SetOperation(c20027.spop) c:RegisterEffect(e1) --summon,flip,special local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e2:SetCode(EVENT_SUMMON_SUCCESS) e2:SetOperation(c20027.retreg) c:RegisterEffect(e2) local e3=e2:Clone() e3:SetCode(EVENT_FLIP) c:RegisterEffect(e3) local e4=e2:Clone() e4:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e4) --token local e5=Effect.CreateEffect(c) e5:SetDescription(aux.Stringid(20027,0)) e5:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_TOKEN) e5:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e5:SetCode(EVENT_SPSUMMON_SUCCESS) e5:SetTarget(c20027.tg) e5:SetOperation(c20027.op) c:RegisterEffect(e5) --cannot release local e7=Effect.CreateEffect(c) e7:SetType(EFFECT_TYPE_SINGLE) e7:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e7:SetRange(LOCATION_MZONE) e7:SetCode(EFFECT_UNRELEASABLE_SUM) e7:SetValue(1) c:RegisterEffect(e7) end function c20027.spfilter(c) return c:IsType(TYPE_MONSTER) and c:IsAbleToRemoveAsCost() end function c20027.spcon(e,c) if c==nil then return true end local tp=c:GetControler() return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c20027.spfilter,tp,LOCATION_GRAVE,0,2,nil) end function c20027.spop(e,tp,eg,ep,ev,re,r,rp,c) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectMatchingCard(tp,c20027.spfilter,tp,LOCATION_GRAVE,0,2,2,nil) Duel.Remove(g,POS_FACEUP,REASON_COST) end function c20027.retreg(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() --to hand local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e1:SetDescription(aux.Stringid(20027,1)) e1:SetCategory(CATEGORY_TOHAND) e1:SetCode(EVENT_PHASE+PHASE_END) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetProperty(EFFECT_FLAG_REPEAT) e1:SetReset(RESET_EVENT+0x1ee0000+RESET_PHASE+PHASE_END) e1:SetCondition(c20027.retcon) e1:SetTarget(c20027.rettg) e1:SetOperation(c20027.retop) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) c:RegisterEffect(e2) end function c20027.retcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsHasEffect(EFFECT_SPIRIT_DONOT_RETURN) then return false end if e:IsHasType(EFFECT_TYPE_TRIGGER_F) then return not c:IsHasEffect(EFFECT_SPIRIT_MAYNOT_RETURN) else return c:IsHasEffect(EFFECT_SPIRIT_MAYNOT_RETURN) end end function c20027.rettg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_TOHAND,e:GetHandler(),1,0,0) end function c20027.retop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) and c:IsFaceup() then Duel.SendtoHand(c,nil,REASON_EFFECT) end end function c20027.tg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsPlayerCanSpecialSummonMonster(tp,20046,0x208,0x4011,100,0,1,RACE_ZOMBIE,ATTRIBUTE_WIND) end Duel.SetOperationInfo(0,CATEGORY_TOKEN,nil,1,0,0) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,0,0) end function c20027.op(e,tp,eg,ep,ev,re,r,rp) if not Duel.IsPlayerCanSpecialSummonMonster(tp,20046,0x208,0x4011,100,0,1,RACE_ZOMBIE,ATTRIBUTE_WIND) then return end local token=Duel.CreateToken(tp,20046) Duel.SpecialSummonStep(token,0,tp,tp,false,false,POS_FACEUP) Duel.SpecialSummonComplete() end
HuangYuNan/thcsvr
expansions/script/c20027.lua
Lua
gpl-2.0
3,646
>>> def get_weekday(current_weekday, days_ahead): ... """ (int, int) -> int ... ... Return which day of the week it will be days_ahead days ... from current_weekday. ... ... current_weekday is the current day of the week and is in ... the range 1-7, indicating whether today is Sunday (1), ... Monday (2), ..., Saturday (7). ... ... days_ahead is the number of days after today. ... ... >>> get_weekday(3, 1) ... 4 ... >>> get_weekday(6, 1) ... 7 ... >>> get_weekday(7, 1) ... 1 ... >>> get_weekday(1, 0) ... 1 ... >>> get_weekday(4, 7) ... 4 ... >>> get_weekday(7, 72) ... 2 ... """ ... return (current_weekday + days_ahead) % 7 ... >>> def days_difference(day1, day2): ... """ (int, int) -> int ... ... Return the number of days between day1 and day2, which are ... both in the range 1-365 (thus indicating the day of the ... year). ... ... >>> days_difference(200, 224) ... 24 ... >>> days_difference(50, 50) ... 0 ... >>> days_difference(100, 99) ... -1 ... """ ... return day2 - day1 ... >>> days_difference(200, 224) 24 >>> days_difference(50, 50) 0 >>> days_difference(100, 99) -1 >>> def get_birthday_weekday(current_weekday, current_day, ... birthday_day): ... """ (int, int, int) -> int ... ... Return the day of the week it will be on birthday_day, ... given that the day of the week is current_weekday and the ... day of the year is current_day. ... ... current_weekday is the current day of the week and is in ... the range 1-7, indicating whether today is Sunday (1), ... Monday (2), ..., Saturday (7). ... ... current_day and birthday_day are both in the range 1-365. ... ... >>> get_birthday_weekday(5, 3, 4) ... 6 ... >>> get_birthday_weekday(5, 3, 116) ... 6 ... >>> get_birthday_weekday(6, 116, 3) ... 5 ... """ ... days_diff = days_difference(current_day, birthday_day) ... return get_weekday(current_weekday, days_diff) ...
simontakite/sysadmin
pythonscripts/practicalprogramming/functions/days.cmd
Batchfile
gpl-2.0
2,072
/* * This is a small program to verify the linking of multiple files * and its about the simplest program that can do something visible * on the ezkit lite. */ #define delayms \ cntr=33000/4; \ do delayms_loop? until ce; \ nop; \ nop; \ nop; \ delayms_loop?: \ nop .extern page0fn, page4fn, page5fn; .extern vardata00, vardata4, vardata5; .extern varpmdata00, varpmdata4, varpmdata5;
wodz/open21xx
samples/218x/page.h
C
gpl-2.0
428
/* * Macros for manipulating and testing page->flags */ #ifndef PAGE_FLAGS_H #define PAGE_FLAGS_H #include <linux/types.h> #ifndef __GENERATING_BOUNDS_H #include <linux/mm_types.h> #include <linux/bounds.h> #endif /* !__GENERATING_BOUNDS_H */ /* * Various page->flags bits: * * PG_reserved is set for special pages, which can never be swapped out. Some * of them might not even exist (eg empty_bad_page)... * * The PG_private bitflag is set on pagecache pages if they contain filesystem * specific data (which is normally at page->private). It can be used by * private allocations for its own usage. * * During initiation of disk I/O, PG_locked is set. This bit is set before I/O * and cleared when writeback _starts_ or when read _completes_. PG_writeback * is set before writeback starts and cleared when it finishes. * * PG_locked also pins a page in pagecache, and blocks truncation of the file * while it is held. * * page_waitqueue(page) is a wait queue of all tasks waiting for the page * to become unlocked. * * PG_uptodate tells whether the page's contents is valid. When a read * completes, the page becomes uptodate, unless a disk I/O error happened. * * PG_referenced, PG_reclaim are used for page reclaim for anonymous and * file-backed pagecache (see mm/vmscan.c). * * PG_error is set to indicate that an I/O error occurred on this page. * * PG_arch_1 is an architecture specific page state bit. The generic code * guarantees that this bit is cleared for a page when it first is entered into * the page cache. * * PG_highmem pages are not permanently mapped into the kernel virtual address * space, they need to be kmapped separately for doing IO on the pages. The * struct page (these bits with information) are always mapped into kernel * address space... * * PG_buddy is set to indicate that the page is free and in the buddy system * (see mm/page_alloc.c). * */ /* * Don't use the *_dontuse flags. Use the macros. Otherwise you'll break * locked- and dirty-page accounting. * * The page flags field is split into two parts, the main flags area * which extends from the low bits upwards, and the fields area which * extends from the high bits downwards. * * | FIELD | ... | FLAGS | * N-1 ^ 0 * (NR_PAGEFLAGS) * * The fields area is reserved for fields mapping zone, node (for NUMA) and * SPARSEMEM section (for variants of SPARSEMEM that require section ids like * SPARSEMEM_EXTREME with !SPARSEMEM_VMEMMAP). */ enum pageflags { PG_locked, /* Page is locked. Don't touch. */ PG_error, PG_referenced, PG_uptodate, PG_dirty, PG_lru, PG_active, PG_slab, PG_owner_priv_1, /* Owner use. If pagecache, fs may use*/ PG_arch_1, PG_reserved, PG_private, /* If pagecache, has fs-private data */ PG_writeback, /* Page is under writeback */ #ifdef CONFIG_PAGEFLAGS_EXTENDED PG_head, /* A head page */ PG_tail, /* A tail page */ #else PG_compound, /* A compound page */ #endif PG_swapcache, /* Swap page: swp_entry_t in private */ PG_mappedtodisk, /* Has blocks allocated on-disk */ PG_reclaim, /* To be reclaimed asap */ PG_buddy, /* Page is free, on buddy lists */ PG_swapbacked, /* Page is backed by RAM/swap */ #ifdef CONFIG_UNEVICTABLE_LRU PG_unevictable, /* Page is "unevictable" */ PG_mlocked, /* Page is vma mlocked */ #endif #ifdef CONFIG_IA64_UNCACHED_ALLOCATOR PG_uncached, /* Page has been mapped as uncached */ #endif #ifdef CONFIG_CLEANCACHE PG_was_active, #endif __NR_PAGEFLAGS, /* Filesystems */ PG_checked = PG_owner_priv_1, /* XEN */ PG_pinned = PG_owner_priv_1, PG_savepinned = PG_dirty, /* SLOB */ PG_slob_page = PG_active, PG_slob_free = PG_private, /* SLUB */ PG_slub_frozen = PG_active, PG_slub_debug = PG_error, }; #ifndef __GENERATING_BOUNDS_H /* * Macros to create function definitions for page flags */ #define TESTPAGEFLAG(uname, lname) \ static inline int Page##uname(struct page *page) \ { return test_bit(PG_##lname, &page->flags); } #define SETPAGEFLAG(uname, lname) \ static inline void SetPage##uname(struct page *page) \ { set_bit(PG_##lname, &page->flags); } #define CLEARPAGEFLAG(uname, lname) \ static inline void ClearPage##uname(struct page *page) \ { clear_bit(PG_##lname, &page->flags); } #define __SETPAGEFLAG(uname, lname) \ static inline void __SetPage##uname(struct page *page) \ { __set_bit(PG_##lname, &page->flags); } #define __CLEARPAGEFLAG(uname, lname) \ static inline void __ClearPage##uname(struct page *page) \ { __clear_bit(PG_##lname, &page->flags); } #define TESTSETFLAG(uname, lname) \ static inline int TestSetPage##uname(struct page *page) \ { return test_and_set_bit(PG_##lname, &page->flags); } #define TESTCLEARFLAG(uname, lname) \ static inline int TestClearPage##uname(struct page *page) \ { return test_and_clear_bit(PG_##lname, &page->flags); } #define PAGEFLAG(uname, lname) TESTPAGEFLAG(uname, lname) \ SETPAGEFLAG(uname, lname) CLEARPAGEFLAG(uname, lname) #define __PAGEFLAG(uname, lname) TESTPAGEFLAG(uname, lname) \ __SETPAGEFLAG(uname, lname) __CLEARPAGEFLAG(uname, lname) #define PAGEFLAG_FALSE(uname) \ static inline int Page##uname(struct page *page) \ { return 0; } #define TESTSCFLAG(uname, lname) \ TESTSETFLAG(uname, lname) TESTCLEARFLAG(uname, lname) #define SETPAGEFLAG_NOOP(uname) \ static inline void SetPage##uname(struct page *page) { } #define CLEARPAGEFLAG_NOOP(uname) \ static inline void ClearPage##uname(struct page *page) { } #define __CLEARPAGEFLAG_NOOP(uname) \ static inline void __ClearPage##uname(struct page *page) { } #define TESTCLEARFLAG_FALSE(uname) \ static inline int TestClearPage##uname(struct page *page) { return 0; } struct page; /* forward declaration */ TESTPAGEFLAG(Locked, locked) PAGEFLAG(Error, error) PAGEFLAG(Referenced, referenced) TESTCLEARFLAG(Referenced, referenced) PAGEFLAG(Dirty, dirty) TESTSCFLAG(Dirty, dirty) __CLEARPAGEFLAG(Dirty, dirty) PAGEFLAG(LRU, lru) __CLEARPAGEFLAG(LRU, lru) PAGEFLAG(Active, active) __CLEARPAGEFLAG(Active, active) TESTCLEARFLAG(Active, active) __PAGEFLAG(Slab, slab) PAGEFLAG(Checked, checked) /* Used by some filesystems */ PAGEFLAG(Pinned, pinned) TESTSCFLAG(Pinned, pinned) /* Xen */ PAGEFLAG(SavePinned, savepinned); /* Xen */ PAGEFLAG(Reserved, reserved) __CLEARPAGEFLAG(Reserved, reserved) PAGEFLAG(Private, private) __CLEARPAGEFLAG(Private, private) __SETPAGEFLAG(Private, private) PAGEFLAG(SwapBacked, swapbacked) __CLEARPAGEFLAG(SwapBacked, swapbacked) __PAGEFLAG(SlobPage, slob_page) __PAGEFLAG(SlobFree, slob_free) __PAGEFLAG(SlubFrozen, slub_frozen) __PAGEFLAG(SlubDebug, slub_debug) #ifdef CONFIG_CLEANCACHE PAGEFLAG(WasActive, was_active) #endif /* * Only test-and-set exist for PG_writeback. The unconditional operators are * risky: they bypass page accounting. */ TESTPAGEFLAG(Writeback, writeback) TESTSCFLAG(Writeback, writeback) __PAGEFLAG(Buddy, buddy) PAGEFLAG(MappedToDisk, mappedtodisk) /* PG_readahead is only used for file reads; PG_reclaim is only for writes */ PAGEFLAG(Reclaim, reclaim) TESTCLEARFLAG(Reclaim, reclaim) PAGEFLAG(Readahead, reclaim) /* Reminder to do async read-ahead */ #ifdef CONFIG_HIGHMEM /* * Must use a macro here due to header dependency issues. page_zone() is not * available at this point. */ #define PageHighMem(__p) is_highmem(page_zone(__p)) #else PAGEFLAG_FALSE(HighMem) #endif #ifdef CONFIG_SWAP PAGEFLAG(SwapCache, swapcache) #else PAGEFLAG_FALSE(SwapCache) SETPAGEFLAG_NOOP(SwapCache) CLEARPAGEFLAG_NOOP(SwapCache) #endif #ifdef CONFIG_UNEVICTABLE_LRU PAGEFLAG(Unevictable, unevictable) __CLEARPAGEFLAG(Unevictable, unevictable) TESTCLEARFLAG(Unevictable, unevictable) #define MLOCK_PAGES 1 PAGEFLAG(Mlocked, mlocked) __CLEARPAGEFLAG(Mlocked, mlocked) TESTSCFLAG(Mlocked, mlocked) #else #define MLOCK_PAGES 0 PAGEFLAG_FALSE(Mlocked) SETPAGEFLAG_NOOP(Mlocked) TESTCLEARFLAG_FALSE(Mlocked) PAGEFLAG_FALSE(Unevictable) TESTCLEARFLAG_FALSE(Unevictable) SETPAGEFLAG_NOOP(Unevictable) CLEARPAGEFLAG_NOOP(Unevictable) __CLEARPAGEFLAG_NOOP(Unevictable) #endif #ifdef CONFIG_IA64_UNCACHED_ALLOCATOR PAGEFLAG(Uncached, uncached) #else PAGEFLAG_FALSE(Uncached) #endif static inline int PageUptodate(struct page *page) { int ret = test_bit(PG_uptodate, &(page)->flags); /* * Must ensure that the data we read out of the page is loaded * _after_ we've loaded page->flags to check for PageUptodate. * We can skip the barrier if the page is not uptodate, because * we wouldn't be reading anything from it. * * See SetPageUptodate() for the other side of the story. */ if (ret) smp_rmb(); return ret; } static inline void __SetPageUptodate(struct page *page) { smp_wmb(); __set_bit(PG_uptodate, &(page)->flags); } static inline void SetPageUptodate(struct page *page) { #ifdef CONFIG_S390 if (!test_and_set_bit(PG_uptodate, &page->flags)) page_clear_dirty(page); #else /* * Memory barrier must be issued before setting the PG_uptodate bit, * so that all previous stores issued in order to bring the page * uptodate are actually visible before PageUptodate becomes true. * * s390 doesn't need an explicit smp_wmb here because the test and * set bit already provides full barriers. */ smp_wmb(); set_bit(PG_uptodate, &(page)->flags); #endif } CLEARPAGEFLAG(Uptodate, uptodate) extern void cancel_dirty_page(struct page *page, unsigned int account_size); int test_clear_page_writeback(struct page *page); int test_set_page_writeback(struct page *page); static inline void set_page_writeback(struct page *page) { test_set_page_writeback(page); } #ifdef CONFIG_PAGEFLAGS_EXTENDED /* * System with lots of page flags available. This allows separate * flags for PageHead() and PageTail() checks of compound pages so that bit * tests can be used in performance sensitive paths. PageCompound is * generally not used in hot code paths. */ __PAGEFLAG(Head, head) __PAGEFLAG(Tail, tail) static inline int PageCompound(struct page *page) { return page->flags & ((1L << PG_head) | (1L << PG_tail)); } #else /* * Reduce page flag use as much as possible by overlapping * compound page flags with the flags used for page cache pages. Possible * because PageCompound is always set for compound pages and not for * pages on the LRU and/or pagecache. */ TESTPAGEFLAG(Compound, compound) __PAGEFLAG(Head, compound) /* * PG_reclaim is used in combination with PG_compound to mark the * head and tail of a compound page. This saves one page flag * but makes it impossible to use compound pages for the page cache. * The PG_reclaim bit would have to be used for reclaim or readahead * if compound pages enter the page cache. * * PG_compound & PG_reclaim => Tail page * PG_compound & ~PG_reclaim => Head page */ #define PG_head_tail_mask ((1L << PG_compound) | (1L << PG_reclaim)) static inline int PageTail(struct page *page) { return ((page->flags & PG_head_tail_mask) == PG_head_tail_mask); } static inline void __SetPageTail(struct page *page) { page->flags |= PG_head_tail_mask; } static inline void __ClearPageTail(struct page *page) { page->flags &= ~PG_head_tail_mask; } #endif /* !PAGEFLAGS_EXTENDED */ #ifdef CONFIG_UNEVICTABLE_LRU #define __PG_UNEVICTABLE (1 << PG_unevictable) #define __PG_MLOCKED (1 << PG_mlocked) #else #define __PG_UNEVICTABLE 0 #define __PG_MLOCKED 0 #endif /* * Flags checked when a page is freed. Pages being freed should not have * these flags set. It they are, there is a problem. */ #define PAGE_FLAGS_CHECK_AT_FREE \ (1 << PG_lru | 1 << PG_private | 1 << PG_locked | \ 1 << PG_buddy | 1 << PG_writeback | 1 << PG_reserved | \ 1 << PG_slab | 1 << PG_swapcache | 1 << PG_active | \ __PG_UNEVICTABLE | __PG_MLOCKED) /* * Flags checked when a page is prepped for return by the page allocator. * Pages being prepped should not have any flags set. It they are set, * there has been a kernel bug or struct page corruption. */ #define PAGE_FLAGS_CHECK_AT_PREP ((1 << NR_PAGEFLAGS) - 1) #endif /* !__GENERATING_BOUNDS_H */ #endif /* PAGE_FLAGS_H */
alfsamsung/semc-kernel-msm7x27-ics
include/linux/page-flags.h
C
gpl-2.0
12,177
using System; using Server; using Server.Items; namespace Server.Items { public abstract class BaseSpear : BaseMeleeWeapon { public override int DefHitSound{ get{ return 0x23C; } } public override int DefMissSound{ get{ return 0x238; } } public override SkillName DefSkill{ get{ return SkillName.Fencing; } } public override WeaponType DefType{ get{ return WeaponType.Piercing; } } public override WeaponAnimation DefAnimation{ get{ return WeaponAnimation.Pierce2H; } } public BaseSpear( int itemID ) : base( itemID ) { } public BaseSpear( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); /*int version = */reader.ReadInt(); } public override void OnHit( Mobile attacker, Mobile defender ) { base.OnHit( attacker, defender ); if ( !Core.AOS && Layer == Layer.TwoHanded && (attacker.Skills[SkillName.Anatomy].Value / 400.0) >= Utility.RandomDouble() ) { defender.SendMessage( "You receive a paralyzing blow!" ); // Is this not localized? defender.Freeze( TimeSpan.FromSeconds( 2.0 ) ); attacker.SendMessage( "You deliver a paralyzing blow!" ); // Is this not localized? attacker.PlaySound( 0x11C ); } if ( !Core.AOS && Poison != null && PoisonCharges > 0 ) { --PoisonCharges; if ( Utility.RandomDouble() >= 0.5 ) // 50% chance to poison defender.ApplyPoison( attacker, Poison ); } } } }
brodock/sunuo
scripts/legacy/Items/Weapons/SpearsAndForks/BaseSpear.cs
C#
gpl-2.0
1,599
package it.giacomos.android.wwwsapp.locationUtils; public class Constants { public static final long LOCATION_UPDATE_INTERVAL = 25000L; public static final long LOCATION_FASTEST_UPDATE_INTERVAL = 20000L; public static final long LOCATION_UPDATES_GPS_MIN_TIME = 12000l; public static final float LOCATION_UPDATES_NETWORK_MIN_DIST = 80f; public static final float LOCATION_UPDATES_GPS_MIN_DIST = 20f; // public static final long LOCATION_UPDATES_PASSIVE_MIN_TIME = 5000l; // public static final float LOCATION_UPDATES_PASSIVE_MIN_DIST = 10f; public static final int LOCATION_COMPARER_INTERVAL = 1000 * 60; public static final int LOCATION_COMPARER_ACCURACY = 200; }
delleceste/wwwsapp
src/it/giacomos/android/wwwsapp/locationUtils/Constants.java
Java
gpl-2.0
688
<?php require_once("include/bittorrent.php"); dbconn(); $langid = 0 + $_GET['sitelanguage']; if ($langid) { $lang_folder = validlang($langid); if(get_langfolder_cookie() != $lang_folder) { set_langfolder_cookie($lang_folder); header("Location: " . $_SERVER['PHP_SELF']); } } require_once(get_langfile_path("", false, $CURLANGDIR)); failedloginscheck (); cur_user_check () ; stdhead($lang_login['head_login']); $s = "<select name=\"sitelanguage\" onchange='submit()'>\n"; $langs = langlist("site_lang"); foreach ($langs as $row) { if ($row["site_lang_folder"] == get_langfolder_cookie()) $se = "selected=\"selected\""; else $se = ""; $s .= "<option value=\"". $row["id"] ."\" ". $se. ">" . htmlspecialchars($row["lang_name"]) . "</option>\n"; } $s .= "\n</select>"; ?> <?php unset($returnto); if (!empty($_GET["returnto"])) { $returnto = $_GET["returnto"]; if (!$_GET["nowarn"]) { print("<h1>" . $lang_login['h1_not_logged_in']. "</h1>\n"); print("<p><b>" . $lang_login['p_error']. "</b> " . $lang_login['p_after_logged_in']. "</p>\n"); } } ?> <iframe id="loginframe" name="loginframe" style="display:none;height:1px;width:1px;"></iframe> <form name="formlogin" method="post" target="loginframe"> <p><?php echo $lang_login['p_need_cookies_enables']?><br /> [<b><?php echo $maxloginattempts;?></b>] <?php echo $lang_login['p_fail_ban']?></p> <p><?php echo $lang_login['p_you_have']?> <b><?php echo remaining ();?></b> <?php echo $lang_login['p_remaining_tries']?></p> <p><font color=blue><b>注意:</b></font>登录前请确认您的帐号在西北望BBS已经激活!并注意帐号大小写!</p> <table border="0" cellpadding="5"> <tr><td class="rowhead"><?php echo $lang_login['rowhead_username']?></td><td class="rowfollow" align="left"><input type="text" name="username" style="width: 180px; border: 1px solid gray" /></td></tr> <tr><td class="rowhead"><?php echo $lang_login['rowhead_password']?></td><td class="rowfollow" align="left"><input type="password" name="password" style="width: 180px; border: 1px solid gray"/></td></tr> <tr><td class="toolbox" colspan="2" align="right"><input type="submit" value="<?php echo $lang_login['button_login']?>" class="btn" onClick="LoginbyBBS()" > <input type="reset" value="<?php echo $lang_login['button_reset']?>" class="btn" /></td></tr> </table> <?php if (isset($returnto)) print("<input type=\"hidden\" name=\"returnto\" value=\"" . htmlspecialchars($returnto) . "\" />\n"); ?> </form> <p><?php echo $lang_login['p_no_account_signup']?></p> <?php if ($smtptype != 'none'){ ?> <p><?php echo $lang_login['p_forget_pass_recover']?></p> <p><?php echo $lang_login['p_tishi']?></p> <?php } if ($showhelpbox_main != 'no'){?> <table width="700" class="main" border="0" cellspacing="0" cellpadding="0"><tr><td class="embedded"> <h2><?php echo $lang_login['text_helpbox'] ?><font class="small"> - <?php echo $lang_login['text_helpbox_note'] ?><font id= "waittime" color="red"></font></h2> <?php print("<table width='100%' border='1' cellspacing='0' cellpadding='1'><tr><td class=\"text\">\n"); print("<iframe src='" . get_protocol_prefix() . $BASEURL . "/shoutbox.php?type=helpbox' width='650' height='180' frameborder='0' name='sbox' marginwidth='0' marginheight='0'></iframe><br /><br />\n"); print("<form action='" . get_protocol_prefix() . $BASEURL . "/shoutbox.php' id='helpbox' method='get' target='sbox' name='shbox'>\n"); print($lang_login['text_message']."<input type='text' id=\"hbtext\" name='shbox_text' autocomplete='off' style='width: 500px; border: 1px solid gray' ><input type='submit' id='hbsubmit' class='btn' name='shout' value=\"".$lang_login['sumbit_shout']."\" /><input type='reset' class='btn' value=".$lang_login['submit_clear']." /> <input type='hidden' name='sent' value='yes'><input type='hidden' name='type' value='helpbox' />\n"); print("<div id=sbword style=\"display: none\">".$lang_login['sumbit_shout']."</div>"); print(smile_row("shbox","shbox_text")); print("</td></tr></table></form></td></tr></table>"); } stdfoot();
lzuhzy/xbwpt
xbwpt/login.php
PHP
gpl-2.0
4,030
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // FIXME: add well-defined names for cameras #ifndef ANDROID_INCLUDE_CAMERA_COMMON_H #define ANDROID_INCLUDE_CAMERA_COMMON_H #include <stdint.h> #include <sys/cdefs.h> #include <sys/types.h> #include <cutils/native_handle.h> #include <system/camera.h> #include <hardware/hardware.h> #include <hardware/gralloc.h> __BEGIN_DECLS /** * The id of this module */ #define CAMERA_HARDWARE_MODULE_ID "camera" /** * Module versioning information for the Camera hardware module, based on * camera_module_t.common.module_api_version. The two most significant hex * digits represent the major version, and the two least significant represent * the minor version. * ******************************************************************************* * Versions: 0.X - 1.X [CAMERA_MODULE_API_VERSION_1_0] * * Camera modules that report these version numbers implement the initial * camera module HAL interface. All camera devices openable through this * module support only version 1 of the camera device HAL. The device_version * and static_camera_characteristics fields of camera_info are not valid. Only * the android.hardware.Camera API can be supported by this module and its * devices. * ******************************************************************************* * Version: 2.0 [CAMERA_MODULE_API_VERSION_2_0] * * Camera modules that report this version number implement the second version * of the camera module HAL interface. Camera devices openable through this * module may support either version 1.0 or version 2.0 of the camera device * HAL interface. The device_version field of camera_info is always valid; the * static_camera_characteristics field of camera_info is valid if the * device_version field is 2.0 or higher. */ /** * Predefined macros for currently-defined version numbers */ /** * All module versions <= HARDWARE_MODULE_API_VERSION(1, 0xFF) must be treated * as CAMERA_MODULE_API_VERSION_1_0 */ #define CAMERA_MODULE_API_VERSION_1_0 HARDWARE_MODULE_API_VERSION(1, 0) #define CAMERA_MODULE_API_VERSION_2_0 HARDWARE_MODULE_API_VERSION(2, 0) #define CAMERA_MODULE_API_VERSION_CURRENT CAMERA_MODULE_API_VERSION_2_0 /** * All device versions <= HARDWARE_DEVICE_API_VERSION(1, 0xFF) must be treated * as CAMERA_DEVICE_API_VERSION_1_0 */ #define CAMERA_DEVICE_API_VERSION_1_0 HARDWARE_DEVICE_API_VERSION(1, 0) #define CAMERA_DEVICE_API_VERSION_2_0 HARDWARE_DEVICE_API_VERSION(2, 0) // Device version 2.0 is experimental #define CAMERA_DEVICE_API_VERSION_CURRENT CAMERA_DEVICE_API_VERSION_1_0 /** * Defined in /system/media/camera/include/system/camera_metadata.h */ typedef struct camera_metadata camera_metadata_t; struct camera_info { /** * The direction that the camera faces to. It should be CAMERA_FACING_BACK * or CAMERA_FACING_FRONT. * * Version information: * Valid in all camera_module versions */ int facing; /** * The orientation of the camera image. The value is the angle that the * camera image needs to be rotated clockwise so it shows correctly on the * display in its natural orientation. It should be 0, 90, 180, or 270. * * For example, suppose a device has a naturally tall screen. The * back-facing camera sensor is mounted in landscape. You are looking at * the screen. If the top side of the camera sensor is aligned with the * right edge of the screen in natural orientation, the value should be * 90. If the top side of a front-facing camera sensor is aligned with the * right of the screen, the value should be 270. * * Version information: * Valid in all camera_module versions */ int orientation; /** * The value of camera_device_t.common.version. * * Version information (based on camera_module_t.common.module_api_version): * * CAMERA_MODULE_API_VERSION_1_0: * * Not valid. Can be assumed to be CAMERA_DEVICE_API_VERSION_1_0. Do * not read this field. * * CAMERA_MODULE_API_VERSION_2_0: * * Always valid * */ uint32_t device_version; /** * The camera's fixed characteristics, which include all camera metadata in * the android.*.info.* sections. This should be a sorted metadata buffer, * and may not be modified or freed by the caller. The pointer should remain * valid for the lifetime of the camera module. * * Version information (based on camera_module_t.common.module_api_version): * * CAMERA_MODULE_API_VERSION_1_0: * * Not valid. Extra characteristics are not available. Do not read this * field. * * CAMERA_MODULE_API_VERSION_2_0: * * Valid if device_version >= CAMERA_DEVICE_API_VERSION_2_0. Do not read * otherwise. * */ const camera_metadata_t *static_camera_characteristics; }; struct camera_info_extended { /** * The direction that the camera faces to. It should be CAMERA_FACING_BACK * or CAMERA_FACING_FRONT. */ int facing; /** * The orientation of the camera image. The value is the angle that the * camera image needs to be rotated clockwise so it shows correctly on the * display in its natural orientation. It should be 0, 90, 180, or 270. * * For example, suppose a device has a naturally tall screen. The * back-facing camera sensor is mounted in landscape. You are looking at * the screen. If the top side of the camera sensor is aligned with the * right edge of the screen in natural orientation, the value should be * 90. If the top side of a front-facing camera sensor is aligned with the * right of the screen, the value should be 270. */ int orientation; /** * Read-only field. * Indicates whether the camera can be used in stereo mode. It should be * CAMERA_STEREO_CAPS_UNDEFINED, CAMERA_STEREO_CAPS_MONO or CAMERA_STEREO_CAPS_STEREO. */ int stereoCaps; /** * Read-only field. * It indicates whether camera is connected via USB, or is built-in. * CAMERA_CONNECTION_INTERNAL indicates a built-in camera, * while CAMERA_CONNECTION_USB indicates a camera connected via USB. It should be * CAMERA_CONNECTION_UNDEFINED, CAMERA_CONNECTION_INTERNAL or CAMERA_CONNECTION_USB. */ int connection; }; typedef struct camera_module { hw_module_t common; int (*get_number_of_cameras)(void); int (*get_camera_info)(int camera_id, struct camera_info *info); int (*get_camera_info_extended)(int camera_id, struct camera_info_extended *info); } camera_module_t; __END_DECLS #endif /* ANDROID_INCLUDE_CAMERA_COMMON_H */
DmitryADP/diff_qc750
hardware/libhardware/include/hardware/camera_common.h
C
gpl-2.0
7,361
menu_translation_extra ======================
chapter-three/menu_translation_extra
README.md
Markdown
gpl-2.0
46
--- layout: post status: publish published: true title: Amazon Cloudfront Private Streaming CLI Tools author: display_name: jmiller login: jmiller email: joeym@joeym.net url: '' author_login: jmiller author_email: joeym@joeym.net wordpress_id: 108 wordpress_url: http://www.joeym.net/?p=108 date: '2011-01-31 17:34:13 -0800' date_gmt: '2011-02-01 00:34:13 -0800' categories: - software - internet services - AWS tags: - amazon - aws - cloudfront - private - streaming comments: true --- Back in late 2010 I had a need to create a private Cloudfront streaming distribution but there was no simple way to do this. Amazon's web-based AWS Management Console did not support this and I could not find any simple CLI tools for doing this. Luckily, RightScale's _right\_aws_ ruby gem (>= 2.0.0) provides support for the Cloudfront private streaming API. These tools should make it simple for any linux admin or developer to get started with creating a private streaming distribution on Amazon. <!--more--> The code and detailed documentation is available on github: [https://github.com/joemiller/aws-cf-private-streaming-tools](https://github.com/joemiller/aws-cf-private-streaming-tools) To read more, and see example usage, click past the break! ### Example Usage In this example we will setup a new Cloudfront Private Streaming distribution with the following attributes: - S3 origin bucket: my-video-bucket - CF base URL (CNAME): rtmp://cf.example.com/ #### 1. Setup AWS keys {% highlight text%} $ export AWS_ACCESS_KEY_ID='xxxxx' $ export AAWS_SECRET_ACCESS_KEY='xxxxxx' {% endhighlight %} #### 2. Create a new Cloudfront Streaming Distribution {% highlight text%} $ ./cf-streaming-distribution.rb create my-video-bucket \ --cname cf.example.com \ -m "private streaming distribution (rtmp) with origin bucket: my-video-bucket" Success! domain_name: s1loj2pirm00it.cloudfront.net aws_id: E1UGDLB9XZBD79 {% endhighlight %} #### 3. Configure CNAME in your DNS server This part will depend on DNS server or DNS provider. You'll need to create a new CNAME for cf.example.com --> s1loj2pirm00it.cloudfront.net #### 4. Create a new Origin-Access-ID (OAI) {% highlight text%} $ ./cf-origin-access-id.rb create "OAI for use on the cf.example.com distribution" Success! AWS_ID : E2CWXW7A1B3YIU Location : https://cloudfront.amazonaws.com/origin-access-identity/cloudfront/E2CWXW7A1B3YIU S3 Canonical ID: 3b5285f7f1b51ff2e63e8ff8127b7ffb76edee24580cb7fff6ef812aa87b749aaa3ed1aab389aaaab4453499a7ba57e7 {% endhighlight %} #### 5. Assign the OAI to the Cloudfront distribution {% highlight text%} $ ./cf-streaming-distribution.rb modify E1UGDLB9XZBD79 --oai E2CWXW7A1B3YIU Success! {% endhighlight %} #### 6. Grant the OAI access to the files in the S3 bucket {% highlight text%} $ ./cf-origin-access-id.rb grant E2CWXW8B1U3YJU my-video-bucket Applying grant [E2CWXW8B1U3YJU:'FULL_CONTROL'] on: my-video-bucket/flvs/video01.flv Applying grant [E2CWXW8B1U3YJU:'FULL_CONTROL'] on: my-video-bucket/flvs/video02.flv ... {% endhighlight %} #### 7. Create RSA Keypair on the Amazon AWS website You cannot create keypairs with the cloudfront API, so you'll need to do this step on the AWS website. - Goto http://aws.amazon.com then login: - Account > Security Credentials > Key Pairs - Click “Create New Key Pair” under the “Cloudfront Key Pairs” section - A keypair will be created and the private key will automatically begin downloading. You must save this file! it will be in the form “pk-XXXXXX.pem”. If you lose this key, you can’t get it back because Amazon only stores the public key. #### 8. Register the account and keypairs on the cloudfront distribution NOTE: the --trusted-signer arguments takes an amazon account ID as an argument. The special ‘self’ can be used instead. {% highlight text%} $ ./cf-streaming-distribution.rb modify E1UGDLB9XZBD79 --trusted-signer self Success! {% endhighlight %} #### 9. Verify settings on the new private Streaming Distribution {% highlight text%} $ ./cf-streaming-distribution.rb get E1UGDLB9XZBD79 AWS_ID : E1UGDLB9XZBD79 E_TAG : EQ3HGAPOK1IFN Status : InProgress Enabled : true domain_name : s1loj2pirm00it.cloudfront.net origin : my-video-bucket.s3.amazonaws.com CNAMEs : cf.example.com Comment : private streaming distribution (rtmp) with origin bucket: my-video-bucket Origin Access ID: origin-access-identity/cloudfront/E2CWXW7A1B3YIU Trusted Signers : self Active Signers: -> aws_account_number: self -> key_pair_id : APDBDOEHALFXGK5AQU5R {% endhighlight %} NOTE: The distribution will not be usable until Status changes from InProgress to Deployed. This can take up to 15minutes. You can also use the command `cf-streaming-distribution.rb wait AWS_ID` to wait for a distribution to change from InProgress to Deployed. The command will exit as soon as the status changes to Deployed. This is useful for scripts where you need to control timing.
joemiller/joemiller.me
_posts/2011-01-31-amazon-cloudfront-private-streaming-tools.markdown
Markdown
gpl-2.0
4,990
<?php /******************************************************************** PhPeace - Portal Management System Copyright notice (C) 2003-2019 Francesco Iannuzzelli <francesco@phpeace.org> All rights reserved This script is part of PhPeace. PhPeace is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. PhPeace is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. The GNU General Public License (GPL) is available at http://www.gnu.org/copyleft/gpl.html. A copy can be found in the file COPYING distributed with these scripts. This copyright notice MUST APPEAR in all copies of the script! ********************************************************************/ if (!defined('SERVER_ROOT')) define('SERVER_ROOT',$_SERVER['DOCUMENT_ROOT']); include_once(SERVER_ROOT."/include/header.php"); $phpeace = new Phpeace; $title[] = array('licence',''); echo $hh->ShowTitle($title); ?> <pre> <strong><a href="http://www.phpeace.org" target="_blank" title="PhPeace website - Link to external site - Opens in new browser window">PhPeace</a> - Portal Management System</strong> Copyright (C) 2003-2018 Francesco Iannuzzelli &lt;<a href="mailto:francesco@phpeace.org">francesco@phpeace.org</a>&gt; All rights reserved PhPeace is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. PhPeace is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. The GNU General Public License (GPL) is available at <a href="http://www.gnu.org/copyleft/gpl.html" target="_blank" title="GNU/GPL website - Link to external site - Opens in new browser window">http://www.gnu.org/copyleft/gpl.html</a>. For your convenience a copy is reported below. <hr> GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS </pre> <?php include_once(SERVER_ROOT."/include/footer.php"); ?>
fra967/phpeace
admin/gate/licence.php
PHP
gpl-2.0
17,635
// <auto-generated /> namespace SCS.Test.Migrations { using System.CodeDom.Compiler; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure; using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")] public sealed partial class BigBang : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(BigBang)); string IMigrationMetadata.Id { get { return "201701120443192_BigBang"; } } string IMigrationMetadata.Source { get { return null; } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
sovandarachea/scsoftwares
SCSToolkit/Tests/SCS.Test/Migrations/201701120443192_BigBang.Designer.cs
C#
gpl-2.0
801
using System; using MonoDevelop.Projects; using System.Xml; using MonoDevelop.Core.Assemblies; namespace MonoDevelop.MonoGame { public static class MonoGameBuildAction { public static readonly string Shader; public static bool IsMonoGameBuildAction(string action){ return action == Shader; } static MonoGameBuildAction(){ Shader = "MonoGameShader"; } } public static class MonoGameProject : DotNetAssemblyProject { public MonoGameProject () { Init (); } public MonoGameProject (string languageName) : base (languageName) { Init (); } public MonoGameProject(string languageName, ProjectCreateInformation info, XmlElement projectOptions) :base(languageName, info, projectOptions) { Init (); } private void Init(){ } public override SolutionItemConfiguration CreateConfiguration(string name) { var conf = new MonoGameProjectConfiguration (name); conf.CopyFrom (base.CreateConfiguration (name)); return conf; } public override bool SupportsFormat (FileFormat format) { return format.Id == "MSBuild10"; } public override TargetFrameworkMoniker GetDefaultTargetFrameworkForFormat (FileFormat format) { return new TargetFrameworkMoniker("4.0"); } public override bool SupportsFramework (MonoDevelop.Core.Assemblies.TargetFramework framework) { if (framework.Id != (MonoDevelop.Core.Assemblies.TargetFrameworkMoniker.NET_4_0)) return false; else return base.SupportsFramework (framework); } protected override System.Collections.Generic.IList<string> GetCommonBuildActions () { var actions = new System.Collections.Generic.List<string> (base.GetCommonBuildActions ()); actions.Add (MonoGameBuildAction.Shader); return actions; } public override string GetDefaultBuildAction (string fileName) { if (System.IO.Path.GetExtension (fileName) == ".fx") { return MonoGameBuildAction.Shader; } return base.GetDefaultBuildAction (fileName); } protected override void PopulateSupportFileList (FileCopySet list, ConfigurationSelector configuration) { base.PopulateSupportFileList (list, configuration); foreach(var projectReference in References){ if (projectReference != null && projectReference.Package.Name == "monogame") { if (projectReference.ReferenceType == ReferenceType.Gac) { foreach (var assem in projectReference.Package.Assemblies) { list.Add (assem.Location); var cfg = (MonoGameProjectConfiguration)configuration.GetConfiguration (this); if (cfg.DebugMode) { var mdbFile = TargetRuntime.GetAssemblyDebugInfoFile (assem.Location); if (System.IO.File.Equals(mdbFile)){ list.Add(mdbFile); } } } } break; } } } } public class MonoGameBuildExtension : ProjectServiceExtension{ protected override BuildResult Build (MonoDevelop.Core.IProgressMonitor monitor, IBuildTarget item, ConfigurationSelector configuration) { try { return base.Build(monitor, item, configuration); } finally { } } protected override BuildResult Compile (MonoDevelop.Core.IProgressMonitor monitor, SolutionEntityItem item, BuildData buildData) { try { var proj = item as MonoGameProject; if (proj == null){ return base.Compile (monitor, item, buildData); } var results = new System.Collections.Generic.List<BuildResult>(); foreach (var file in proj.Files) { if (MonoGameBuildAction.IsMonoGameBuildAction(file.BuildAction)){ buildData.Items.Add(file); var buildresults = MonoGameContentProcessor.Compile(file, monitor,buildData); results.Add(buildresults); } } return base.Compile(monitor, item, buildData).Append(results); } finally { } } } public class MonoGameProjectBinding : IProjectBinding{ public Project CreateProject(ProjectCreateInformation info, System.Xml.XmlElement projectOptions){ string lang = projectOptions.GetAttribute ("language"); return new MonoGameProject (lang, info, projectOptions); } public Project CreateSingleFileproject(string sourceFile){ throw new InvalidOperationException (); } public Project CanCreateSingleFileProject(string sourceFile){ return false; } public string Name{ get{return "MonoGame"; } } } public class MonoGameProjectConfiguration : DotNetProjectConfiguration{ public MonoGameProjectConfiguration () : base (){ } public MonoGameProjectConfiguration (string name): base(name){ } public override void CopyFrom (ItemConfiguration configuration) { base.CopyFrom (configuration); } } public class MonoGameContentProcessor { public static BuildResult Compile( ProjectFile file, MonoDevelop.Core.IProgressMonitor monitor, BuildData buildData){ switch (file.BuildAction) { case "MonoGameShader": { var results = new BuildResult (); monitor.Log.WriteLine ("Compiling Shader"); monitor.Log.WriteLine ("Shader : " + buildData.Configuration.OutputDirectory); monitor.Log.WriteLine ("Shader : " + file.FilePath); monitor.Log.WriteLine ("Shader : " + file.ToString ()); return results; } default: return new BuildResult (); } } } }
stebyrne04/Monogame_templates
Properties/MonoGameProject.cs
C#
gpl-2.0
5,230
package com.example.review; public class SwitchStringStatement { public static void main(String args[]){ String color = "Blue"; String shirt = " Shirt"; switch (color){ case "Blue": shirt = "Blue" + shirt; break; case "Red": shirt = "Red" + shirt; break; default: shirt = "White" + shirt; } System.out.println("Shirt type: " + shirt); } }
amzaso/Java_servef
02-Review/examples/ReviewExamples/src/com/example/review/SwitchStringStatement.java
Java
gpl-2.0
536
<?php // Form override fo theme settings function saa_basic_form_system_theme_settings_alter(&$form, $form_state) { $form['options_settings'] = array( '#type' => 'fieldset', '#title' => t('Theme Specific Settings'), '#collapsible' => FALSE, '#collapsed' => FALSE ); $form['options_settings']['saa_basic_tabs'] = array( '#type' => 'checkbox', '#title' => t('Use the ZEN tabs'), '#description' => t('Check this if you wish to replace the default tabs by the ZEN tabs'), '#default_value' => theme_get_setting('saa_basic_tabs'), ); $form['options_settings']['saa_basic_breadcrumb'] = array( '#type' => 'fieldset', '#title' => t('Breadcrumb settings'), '#attributes' => array('id' => 'basic-breadcrumb'), ); $form['options_settings']['saa_basic_breadcrumb']['saa_basic_breadcrumb'] = array( '#type' => 'select', '#title' => t('Display breadcrumb'), '#default_value' => theme_get_setting('saa_basic_breadcrumb'), '#options' => array( 'yes' => t('Yes'), 'admin' => t('Only in admin section'), 'no' => t('No'), ), ); $form['options_settings']['saa_basic_breadcrumb']['saa_basic_breadcrumb_separator'] = array( '#type' => 'textfield', '#title' => t('Breadcrumb separator'), '#description' => t('Text only. Don’t forget to include spaces.'), '#default_value' => theme_get_setting('saa_basic_breadcrumb_separator'), '#size' => 5, '#maxlength' => 10, '#prefix' => '<div id="div-basic-breadcrumb-collapse">', // jquery hook to show/hide optional widgets ); $form['options_settings']['saa_basic_breadcrumb']['saa_basic_breadcrumb_home'] = array( '#type' => 'checkbox', '#title' => t('Show home page link in breadcrumb'), '#default_value' => theme_get_setting('saa_basic_breadcrumb_home'), ); $form['options_settings']['saa_basic_breadcrumb']['saa_basic_breadcrumb_trailing'] = array( '#type' => 'checkbox', '#title' => t('Append a separator to the end of the breadcrumb'), '#default_value' => theme_get_setting('saa_basic_breadcrumb_trailing'), '#description' => t('Useful when the breadcrumb is placed just before the title.'), ); $form['options_settings']['saa_basic_breadcrumb']['saa_basic_breadcrumb_title'] = array( '#type' => 'checkbox', '#title' => t('Append the content title to the end of the breadcrumb'), '#default_value' => theme_get_setting('saa_basic_breadcrumb_title'), '#description' => t('Useful when the breadcrumb is not placed just before the title.'), '#suffix' => '</div>', // #div-basic-breadcrumb-collapse" ); //IE specific settings. $form['options_settings']['saa_basic_ie'] = array( '#type' => 'fieldset', '#title' => t('Internet Explorer Stylesheets'), '#attributes' => array('id' => 'basic-ie'), ); $form['options_settings']['saa_basic_ie']['saa_basic_ie_enabled'] = array( '#type' => 'checkbox', '#title' => t('Enable Internet Explorer stylesheets in theme'), '#default_value' => theme_get_setting('saa_basic_ie_enabled'), '#description' => t('If you check this box you can choose which IE stylesheets in theme get rendered on display.'), ); $form['options_settings']['saa_basic_ie']['saa_basic_ie_enabled_css'] = array( '#type' => 'fieldset', '#title' => t('Check which IE versions you want to enable additional .css stylesheets for.'), '#states' => array( 'visible' => array( ':input[name="saa_basic_ie_enabled"]' => array('checked' => TRUE), ), ), ); $form['options_settings']['saa_basic_ie']['saa_basic_ie_enabled_css']['saa_basic_ie_enabled_versions'] = array( '#type' => 'checkboxes', '#options' => array( 'ie8' => t('Internet Explorer 8'), 'ie9' => t('Internet Explorer 9'), 'ie10' => t('Internet Explorer 10'), ), '#default_value' => theme_get_setting('saa_basic_ie_enabled_versions'), ); $form['options_settings']['clear_registry'] = array( '#type' => 'checkbox', '#title' => t('Rebuild theme registry on every page.'), '#description' =>t('During theme development, it can be very useful to continuously <a href="!link">rebuild the theme registry</a>. WARNING: this is a huge performance penalty and must be turned off on production websites.', array('!link' => 'http://drupal.org/node/173880#theme-registry')), '#default_value' => theme_get_setting('clear_registry'), ); }
saaphx-dev/saa
sites/all/themes/saa-basic/theme-settings.php
PHP
gpl-2.0
4,665
<? /************************************************************************************************** * Archivo: StoreConsultaDetalleUbicacion.php * ------------------------------------------------------------------------------------------------ * Version: 1.0 * Descripcion: * Modificaciones: * - * * Nota: Registrar en este encabezado todas las modificaciones hechas al archivo. **************************************************************************************************/ require_once ('template.php'); require_once ('Sysgran/Core/Red/Encoder.php'); require_once ('Sysgran/Core/Listados/FiltroNumerico.php'); require_once ('Sysgran/Core/Php/StoreCustom.php'); class StoreConsultaDetalleUbicacion extends StoreCustom { function StoreConsultaDetalleUbicacion ($paginado = false) { parent::__construct ($paginado); $this->AgregarFiltro (new FiltroNumerico ('ubicacion', 'ubic')); $this->AgregarFiltro (new FiltroNumerico ('producto', 'prod')); $this->AgregarFiltro (new FiltroNumerico ('almacen', 'alm')); } function ArmarQuery () { $fubic = $this->GetFiltro ('ubicacion'); $fprod = $this->GetFiltro ('producto'); $falm = $this->GetFiltro ('almacen'); $where = ''; if ($fubic->EsActivo ()) { $where .= " AND d.iUbicacionAlmacenId = " . $fubic->GetValor (); } if ($fprod->EsActivo ()) { $where .= " AND p.iProductoId = " . $fprod->GetValor (); } if ($falm->EsActivo ()) { $where .= " AND u.iAlmacenId = " . $falm->GetValor (); } $query = "SELECT d.iDetalleUbicacionAlmacenId, d.iNroDeDetalle, d.fCantidad, um.cCodigo AS cod_um, p.cCodigo AS cod_producto, d.iNroDeDetalle FROM DetalleUbicacionAlmacen d JOIN UbicacionAlmacen u ON u.iUbicacionAlmacenId = d.iUbicacionAlmacenId JOIN Producto p ON p.iProductoId = d.iProductoId JOIN UnidadDeMedida um ON um.iUnidadDeMedidaId = p.iUnidadDeMedidaStockId WHERE u.bActivo = " . DB::ToBoolean (true) . " AND d.fCantidad > 0 $where ORDER BY u.cCodigo, d.iDetalleubicacionAlmacenId ASC"; return $query; } function CargarItem ($rs) { $ret['id'] = $rs->Fields ('iDetalleUbicacionAlmacenId'); $ret['nroDeDetalle'] = $rs->Fields ('iNroDeDetalle'); $ret['codigoProducto'] = $rs->Fields ('cod_producto'); $ret['cantidad'] = $rs->Fields ('fCantidad'); $ret['codigoUnidadDeMedida'] = $rs->Fields ('cod_um'); return $ret; } }
marcelinoar/FrameworkWeb
src/base/servidor/Sysgran/Aplicacion/Modulos/Produccion/Store/StoreConsultaDetalleUbicacion.php
PHP
gpl-2.0
2,477
/* ***** BEGIN LICENSE BLOCK ***** * Source last modified: $Id: filter2.h,v 1.1 2005/07/13 17:22:24 rggammon Exp $ * * Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved. * * The contents of this file, and the files included with this file, * are subject to the current version of the RealNetworks Public * Source License (the "RPSL") available at * http://www.helixcommunity.org/content/rpsl unless you have licensed * the file under the current version of the RealNetworks Community * Source License (the "RCSL") available at * http://www.helixcommunity.org/content/rcsl, in which case the RCSL * will apply. You may also obtain the license terms directly from * RealNetworks. You may not use this file except in compliance with * the RPSL or, if you have a valid RCSL with RealNetworks applicable * to this file, the RCSL. Please see the applicable RPSL or RCSL for * the rights, obligations and limitations governing use of the * contents of the file. * * This file is part of the Helix DNA Technology. RealNetworks is the * developer of the Original Code and owns the copyrights in the * portions it created. * * This file, and the files included with this file, is distributed * and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET * ENJOYMENT OR NON-INFRINGEMENT. * * Technology Compatibility Kit Test Suite(s) Location: * http://www.helixcommunity.org/content/tck * * Contributor(s): * * ***** END LICENSE BLOCK ***** */ #ifndef _FILTER2_h_ #define _FILTER2_h_ #ifdef __cplusplus extern "C" { #endif //---------------------------------------------- typedef struct { int select; float alpha; float d, d2; } FILTER2_CONTROL; void filter2_init ( int samprate, int filter_select, int monodual, FILTER2_CONTROL * fc2 ); void filter2 ( short pcm[], float *buf1, float *buf2, FILTER2_CONTROL * fc2 ); //---------------------------------------------- #ifdef __cplusplus } #endif #endif // _FILTER2_h_
muromec/qtopia-ezx
src/3rdparty/libraries/helix/src/datatype/mp3/codec/encoder/pub/filter2.h
C
gpl-2.0
2,331
/* Copyright 2011 Alexander Peyser & Wolfgang Nonner This file is part of Deuterostome. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "dm.h" #include <mpi.h> #include <pthread.h> #include <unistd.h> #include <stdlib.h> #include <signal.h> #include <errno.h> #include <stdio.h> #include "dm-mpi.h" #include "error-local.h" #include "dm-vm.h" #include "dm-signals.h" static MPI_Comm rook = MPI_COMM_NULL; static MPI_Comm world = MPI_COMM_NULL; static P rank = -1; static P universe = 0; static MPI_Comm rooksig; MPI_Comm getworldcomm(void) {return world;} P getworldsize(void) {return universe;} P getworldrank(void) {return rank;} MPI_Comm getparentcomm(void) {return rook;} static MPI_Comm currComm; static P currTag; static P currRank; static B* currBuff; static P currSize; static BOOLEAN currFlag; typedef P (*MpiThreadFunc)(void); static MpiThreadFunc mpithread_func = (MpiThreadFunc) -1; static P mpithread_retc; static pthread_mutex_t mpithread_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_t mpithread_id; static pthread_t sigthread_id; static pthread_t mainthread_id; static pthread_cond_t mpithread_cond = PTHREAD_COND_INITIALIZER; /* static void exithandler(void) { */ /* if (rook != MPI_COMM_NULL) */ /* MPI_Abort(rook, 0); */ /* else */ /* MPI_Abort(MPI_COMM_WORLD, 0); */ /* } */ static void mpihandler(MPI_Comm* comm, int* err, ...) { static char string[MPI_MAX_ERROR_STRING]; int len = MPI_MAX_ERROR_STRING; int eq = 0; static BOOLEAN inhandler = 0; if (inhandler) return; inhandler = 1; if (MPI_Error_string(*err, string, &len)) dm_error(0, "Unable to produce error string (%i)", *err); else if (MPI_Comm_compare(*comm, world, &eq)) dm_error(0, "MPI Error: %s", string); else dm_error(0, "Error %s mpi: %s", (eq == MPI_IDENT) ? "speaking with pawns" : "speaking with rook", string); exit(1); } static P mpithread_probe(void) { MPI_Status status; int count; MPI_Probe(currRank, currTag, currComm, &status); currRank = status.MPI_SOURCE; currTag = status.MPI_TAG; MPI_Get_count(&status, MPI_UNSIGNED_CHAR, &count); currSize = count; return OK; } static P mpithread_iprobe(void) { MPI_Status status; int flag; MPI_Iprobe(currRank, currTag, currComm, &flag, &status); if (flag) { int count; currRank = status.MPI_SOURCE; currTag = status.MPI_TAG; MPI_Get_count(&status, MPI_UNSIGNED_CHAR, &count); currSize = count; } currFlag = (BOOLEAN) currFlag; return OK; } static P mpithread_recv(void) { MPI_Recv(currBuff, currSize, MPI_UNSIGNED_CHAR, currRank, currTag, currComm, MPI_STATUS_IGNORE); return OK; } static P mpithread_send(void) { MPI_Send(currBuff, currSize, MPI_UNSIGNED_CHAR, currRank, currTag, currComm); return OK; } static P mpithread_broadcast(void) { MPI_Bcast(currBuff, currSize, MPI_UNSIGNED_CHAR, currRank, currComm); return OK; } static P mpithread_barrier(void) { MPI_Barrier(currComm); return OK; } DM_INLINE_STATIC void mpithread_lock(void) { int errno_; if ((errno_ = pthread_mutex_lock(&mpithread_mutex))) dm_error(errno_, "Failed lock"); } DM_INLINE_STATIC void mpithread_recv_signal(void) { int errno_; if ((errno_ = pthread_cond_wait(&mpithread_cond, &mpithread_mutex))) dm_error(errno_, "Failed cond"); } DM_INLINE_STATIC void mpithread_send_signal(void) { int errno_; if ((errno_ = pthread_cond_signal(&mpithread_cond))) dm_error(errno_, "Failed signal"); } DM_INLINE_STATIC void mpithread_unlock(void) { int errno_; if ((errno_ = pthread_mutex_unlock(&mpithread_mutex))) dm_error(errno_, "Failed unlock"); } DM_INLINE_STATIC P mpithread_exec(MpiThreadFunc func) { P retc; mpithread_func = func; mpithread_send_signal(); do {mpithread_recv_signal();} while (!recvd_quit && !abortflag && mpithread_func); retc = mpithread_retc; mpithread_unlock(); checkabort(); return retc; } static void redirect_sig(int sig) { int errno_; if ((errno_ = pthread_kill(mainthread_id, sig))) dm_error(errno_, "pthread_kill %i", sig); } DM_NORETURN static void sigfunc(void) { while (1) { B sig; MPI_Bcast(&sig, 1, MPI_UNSIGNED_CHAR, 0, rooksig); propagate_sig(sig, redirect_sig); } } static void initmpi_(void) { int argc = 0; const char* argv[] = {NULL}; int threadtype; MPI_Errhandler mpierr; int universe_; int rank_; MPI_Init_thread(&argc, (char***) &argv, MPI_THREAD_MULTIPLE, &threadtype); // atexit(exithandler); if (threadtype < MPI_THREAD_MULTIPLE) dm_error(0, "MPI_Init_thread: Requested %i, received %i", MPI_THREAD_MULTIPLE, threadtype); MPI_Comm_create_errhandler(mpihandler, &mpierr); MPI_Comm_dup(MPI_COMM_WORLD, &world); MPI_Comm_set_errhandler(world, mpierr); MPI_Comm_get_parent(&rook); MPI_Comm_set_errhandler(rook, mpierr); MPI_Comm_size(world, &universe_); universe = universe_; MPI_Comm_rank(world, &rank_); rank = rank_; fprintf(stderr, "Started pawn %i of %i\n", rank_, universe_); fprintf(stderr, "Child %i waiting for rook\n", (int) rank); MPI_Barrier(rook); fprintf(stderr, "Child %i heard from rook\n", (int) rank); MPI_Comm_dup(rook, &rooksig); // fprintf(stderr, "Child %i waiting for rooksig\n", (int) rank); //MPI_Barrier(rooksig); //fprintf(stderr, "Child %i heard from rooksig\n", (int) rank); } DM_NORETURN static void mpifunc(void) { mpithread_lock(); while (1) { mpithread_func = NULL; mpithread_send_signal(); do {mpithread_recv_signal();} while (! mpithread_func); mpithread_retc = mpithread_func(); } } P mpiiprobe(MPI_Comm comm, P* tag, P* rank, P* count) { P retc; mpithread_lock(); currComm = comm; currTag = *tag; currRank = *rank; if ((retc = mpithread_exec(mpithread_iprobe))) return retc; if (! currFlag) return MPI_NOMSG; else { *tag = currTag; *rank = currRank; *count = currSize; } return OK; } P mpiprobe(MPI_Comm comm, P* tag, P* rank, P* count) { P retc; mpithread_lock(); currComm = comm; currTag = *tag; currRank = *rank; if ((retc = mpithread_exec(mpithread_probe))) return retc; *tag = currTag; *rank = currRank; *count = currSize; return OK; } P mpirecv(MPI_Comm comm, P tag, P rank, B* buffer, P size) { mpithread_lock(); currComm = comm; currTag = tag; currRank = rank; currBuff = buffer; currSize = size; return mpithread_exec(mpithread_recv); } P mpisend(MPI_Comm comm, P tag, P rank, B* buffer, P size) { mpithread_lock(); currComm = comm; currTag = tag; currRank = rank; currBuff = buffer; currSize = size; return mpithread_exec(mpithread_send); } P mpibroadcast(MPI_Comm comm, P rank, B* buffer, P size) { mpithread_lock(); currComm = comm; currRank = rank; currBuff = buffer; currSize = size; return mpithread_exec(mpithread_broadcast); } P mpibarrier(MPI_Comm comm) { mpithread_lock(); currComm = comm; return mpithread_exec(mpithread_barrier); } DM_INLINE_STATIC void* startthread(void* threadfunc_) { void (*threadfunc)(void) = threadfunc_; threadfunc(); return NULL; } DM_INLINE_STATIC void makethread(pthread_t* threadid, void (*threadfunc)(void)) { sigset_t set, oset; int errno_; if (sigfillset(&set)) dm_error(errno, "Unable to empty sigset"); if ((errno_ = pthread_sigmask(SIG_BLOCK, &set, &oset))) dm_error(errno_, "Unable to block sigs"); if ((errno_ = pthread_create(threadid, NULL, startthread, threadfunc))) dm_error(errno_, "Failed thread create"); if ((errno_ = pthread_sigmask(SIG_SETMASK, &oset, NULL))) dm_error(errno_, "Unable to unblock sigs"); } void initmpi(void) { mainthread_id = pthread_self(); initmpi_(); mpithread_lock(); makethread(&mpithread_id, mpifunc); do {mpithread_recv_signal();} while (! recvd_quit && !abortflag && mpithread_func); mpithread_unlock(); makethread(&sigthread_id, sigfunc); }
apeyser/Deuterostome
src/dm-mpi.c
C
gpl-2.0
8,500
<?php /** * Module: Intro Text * * @author SpyroSol * @category BuilderModules * @package Spyropress */ class Spyropress_Module_Intro_Text extends SpyropressBuilderModule { public function __construct() { global $spyropress; // Widget variable settings $this->cssclass = ''; $this->description = __( 'A lightweight component for introduction text.', 'spyropress' ); $this->idbase = 'spyropress_intro_text'; $this->name = __( 'Introduction Text', 'spyropress' ); $this->templates['centered'] = array( 'label' => 'Text Centered', 'class' => 'twelve columns offset-by-two' ); $this->templates['style2'] = array( 'label' => 'Text Centered 2', 'class' => 'fourteen columns marginTop offset-by-one' ); // Fields $this->fields = array( array( 'label' => __( 'Styles', 'spyropress' ), 'id' => 'template', 'type' => 'select', 'options' => $this->get_option_templates() ), array( 'label' => __('Content', 'spyropress' ), 'id' => 'content', 'type' => 'editor' ) ); $this->create_widget(); } function widget( $args, $instance ) { // extracting info extract($args); extract( spyropress_clean_array( $instance ) ); // get view to render include $this->get_view(); } } spyropress_builder_register_module( 'Spyropress_Module_Intro_Text' ); ?>
jamesshannonwd/meesha
wp-content/themes/cutting-edge/framework/builder/modules/intro-text/intro-text.php
PHP
gpl-2.0
1,765
/* * ci13xxx_udc.c - MIPS USB IP core family device controller * * Copyright (C) 2008 Chipidea - MIPS Technologies, Inc. All rights reserved. * * Author: David Lopo * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ /* * Description: MIPS USB IP core family device controller * Currently it only supports IP part number CI13412 * * This driver is composed of several blocks: * - HW: hardware interface * - DBG: debug facilities (optional) * - UTIL: utilities * - ISR: interrupts handling * - ENDPT: endpoint operations (Gadget API) * - GADGET: gadget operations (Gadget API) * - BUS: bus glue code, bus abstraction layer * * Compile Options * - CONFIG_USB_GADGET_DEBUG_FILES: enable debug facilities * - STALL_IN: non-empty bulk-in pipes cannot be halted * if defined mass storage compliance succeeds but with warnings * => case 4: Hi > Dn * => case 5: Hi > Di * => case 8: Hi <> Do * if undefined usbtest 13 fails * - TRACE: enable function tracing (depends on DEBUG) * * Main Features * - Chapter 9 & Mass Storage Compliance with Gadget File Storage * - Chapter 9 Compliance with Gadget Zero (STALL_IN undefined) * - Normal & LPM support * * USBTEST Report * - OK: 0-12, 13 (STALL_IN defined) & 14 * - Not Supported: 15 & 16 (ISO) * * TODO List * - OTG * - Isochronous & Interrupt Traffic * - Handle requests which spawns into several TDs * - GET_STATUS(device) - always reports 0 * - Gadget API (majority of optional features) */ #include <linux/delay.h> #include <linux/device.h> #include <linux/dmapool.h> #include <linux/dma-mapping.h> #include <linux/init.h> #include <linux/ratelimit.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/irq.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/pm_runtime.h> #include <linux/usb/ch9.h> #include <linux/usb/gadget.h> #include <linux/usb/otg.h> #include <linux/usb/msm_hsusb.h> #include <linux/tracepoint.h> #include <mach/usb_trace.h> #include "ci13xxx_udc.h" /* Turns on streaming. overrides CI13XXX_DISABLE_STREAMING */ static unsigned int streaming; module_param(streaming, uint, S_IRUGO | S_IWUSR); /****************************************************************************** * DEFINE *****************************************************************************/ #define DMA_ADDR_INVALID (~(dma_addr_t)0) #define USB_MAX_TIMEOUT 100 /* 100msec timeout */ #define EP_PRIME_CHECK_DELAY (jiffies + msecs_to_jiffies(1000)) #define MAX_PRIME_CHECK_RETRY 3 /*Wait for 3sec for EP prime failure */ /* ctrl register bank access */ static DEFINE_SPINLOCK(udc_lock); /* control endpoint description */ static const struct usb_endpoint_descriptor ctrl_endpt_out_desc = { .bLength = USB_DT_ENDPOINT_SIZE, .bDescriptorType = USB_DT_ENDPOINT, .bEndpointAddress = USB_DIR_OUT, .bmAttributes = USB_ENDPOINT_XFER_CONTROL, .wMaxPacketSize = cpu_to_le16(CTRL_PAYLOAD_MAX), }; static const struct usb_endpoint_descriptor ctrl_endpt_in_desc = { .bLength = USB_DT_ENDPOINT_SIZE, .bDescriptorType = USB_DT_ENDPOINT, .bEndpointAddress = USB_DIR_IN, .bmAttributes = USB_ENDPOINT_XFER_CONTROL, .wMaxPacketSize = cpu_to_le16(CTRL_PAYLOAD_MAX), }; /* UDC descriptor */ static struct ci13xxx *_udc; /* Interrupt statistics */ #define ISR_MASK 0x1F static struct { u32 test; u32 ui; u32 uei; u32 pci; u32 uri; u32 sli; u32 none; struct { u32 cnt; u32 buf[ISR_MASK+1]; u32 idx; } hndl; } isr_statistics; /** * ffs_nr: find first (least significant) bit set * @x: the word to search * * This function returns bit number (instead of position) */ static int ffs_nr(u32 x) { int n = ffs(x); return n ? n-1 : 32; } struct ci13xxx_ebi_err_entry { u32 *usb_req_buf; u32 usb_req_length; u32 ep_info; struct ci13xxx_ebi_err_entry *next; }; /****************************************************************************** * HW block *****************************************************************************/ /* register bank descriptor */ static struct { unsigned lpm; /* is LPM? */ void __iomem *abs; /* bus map offset */ void __iomem *cap; /* bus map offset + CAP offset + CAP data */ size_t size; /* bank size */ } hw_bank; /* MSM specific */ #define ABS_AHBBURST (0x0090UL) #define ABS_AHBMODE (0x0098UL) /* UDC register map */ #define ABS_CAPLENGTH (0x100UL) #define ABS_HCCPARAMS (0x108UL) #define ABS_DCCPARAMS (0x124UL) #define ABS_TESTMODE (hw_bank.lpm ? 0x0FCUL : 0x138UL) /* offset to CAPLENTGH (addr + data) */ #define CAP_USBCMD (0x000UL) #define CAP_USBSTS (0x004UL) #define CAP_USBINTR (0x008UL) #define CAP_DEVICEADDR (0x014UL) #define CAP_ENDPTLISTADDR (0x018UL) #define CAP_PORTSC (0x044UL) #define CAP_DEVLC (0x084UL) #define CAP_ENDPTPIPEID (0x0BCUL) #define CAP_USBMODE (hw_bank.lpm ? 0x0C8UL : 0x068UL) #define CAP_ENDPTSETUPSTAT (hw_bank.lpm ? 0x0D8UL : 0x06CUL) #define CAP_ENDPTPRIME (hw_bank.lpm ? 0x0DCUL : 0x070UL) #define CAP_ENDPTFLUSH (hw_bank.lpm ? 0x0E0UL : 0x074UL) #define CAP_ENDPTSTAT (hw_bank.lpm ? 0x0E4UL : 0x078UL) #define CAP_ENDPTCOMPLETE (hw_bank.lpm ? 0x0E8UL : 0x07CUL) #define CAP_ENDPTCTRL (hw_bank.lpm ? 0x0ECUL : 0x080UL) #define CAP_LAST (hw_bank.lpm ? 0x12CUL : 0x0C0UL) #define REMOTE_WAKEUP_DELAY msecs_to_jiffies(200) /* maximum number of enpoints: valid only after hw_device_reset() */ static unsigned hw_ep_max; static void dbg_usb_op_fail(u8 addr, const char *name, const struct ci13xxx_ep *mep); /** * hw_ep_bit: calculates the bit number * @num: endpoint number * @dir: endpoint direction * * This function returns bit number */ static inline int hw_ep_bit(int num, int dir) { return num + (dir ? 16 : 0); } static int ep_to_bit(int n) { int fill = 16 - hw_ep_max / 2; if (n >= hw_ep_max / 2) n += fill; return n; } /** * hw_aread: reads from register bitfield * @addr: address relative to bus map * @mask: bitfield mask * * This function returns register bitfield data */ static u32 hw_aread(u32 addr, u32 mask) { return ioread32(addr + hw_bank.abs) & mask; } /** * hw_awrite: writes to register bitfield * @addr: address relative to bus map * @mask: bitfield mask * @data: new data */ static void hw_awrite(u32 addr, u32 mask, u32 data) { iowrite32(hw_aread(addr, ~mask) | (data & mask), addr + hw_bank.abs); } /** * hw_cread: reads from register bitfield * @addr: address relative to CAP offset plus content * @mask: bitfield mask * * This function returns register bitfield data */ static u32 hw_cread(u32 addr, u32 mask) { return ioread32(addr + hw_bank.cap) & mask; } /** * hw_cwrite: writes to register bitfield * @addr: address relative to CAP offset plus content * @mask: bitfield mask * @data: new data */ static void hw_cwrite(u32 addr, u32 mask, u32 data) { iowrite32(hw_cread(addr, ~mask) | (data & mask), addr + hw_bank.cap); } /** * hw_ctest_and_clear: tests & clears register bitfield * @addr: address relative to CAP offset plus content * @mask: bitfield mask * * This function returns register bitfield data */ static u32 hw_ctest_and_clear(u32 addr, u32 mask) { u32 reg = hw_cread(addr, mask); iowrite32(reg, addr + hw_bank.cap); return reg; } /** * hw_ctest_and_write: tests & writes register bitfield * @addr: address relative to CAP offset plus content * @mask: bitfield mask * @data: new data * * This function returns register bitfield data */ static u32 hw_ctest_and_write(u32 addr, u32 mask, u32 data) { u32 reg = hw_cread(addr, ~0); iowrite32((reg & ~mask) | (data & mask), addr + hw_bank.cap); return (reg & mask) >> ffs_nr(mask); } static int hw_device_init(void __iomem *base) { u32 reg; /* bank is a module variable */ hw_bank.abs = base; hw_bank.cap = hw_bank.abs; hw_bank.cap += ABS_CAPLENGTH; hw_bank.cap += ioread8(hw_bank.cap); reg = hw_aread(ABS_HCCPARAMS, HCCPARAMS_LEN) >> ffs_nr(HCCPARAMS_LEN); hw_bank.lpm = reg; hw_bank.size = hw_bank.cap - hw_bank.abs; hw_bank.size += CAP_LAST; hw_bank.size /= sizeof(u32); reg = hw_aread(ABS_DCCPARAMS, DCCPARAMS_DEN) >> ffs_nr(DCCPARAMS_DEN); hw_ep_max = reg * 2; /* cache hw ENDPT_MAX */ if (hw_ep_max == 0 || hw_ep_max > ENDPT_MAX) return -ENODEV; /* setup lock mode ? */ /* ENDPTSETUPSTAT is '0' by default */ /* HCSPARAMS.bf.ppc SHOULD BE zero for device */ return 0; } /** * hw_device_reset: resets chip (execute without interruption) * @base: register base address * * This function returns an error code */ static int hw_device_reset(struct ci13xxx *udc) { int delay_count = 25; /* 250 usec */ /* should flush & stop before reset */ hw_cwrite(CAP_ENDPTFLUSH, ~0, ~0); hw_cwrite(CAP_USBCMD, USBCMD_RS, 0); hw_cwrite(CAP_USBCMD, USBCMD_RST, USBCMD_RST); while (delay_count-- && hw_cread(CAP_USBCMD, USBCMD_RST)) udelay(10); if (delay_count < 0) pr_err("USB controller reset failed\n"); if (udc->udc_driver->notify_event) udc->udc_driver->notify_event(udc, CI13XXX_CONTROLLER_RESET_EVENT); /* USBMODE should be configured step by step */ hw_cwrite(CAP_USBMODE, USBMODE_CM, USBMODE_CM_IDLE); hw_cwrite(CAP_USBMODE, USBMODE_CM, USBMODE_CM_DEVICE); hw_cwrite(CAP_USBMODE, USBMODE_SLOM, USBMODE_SLOM); /* HW >= 2.3 */ /* * ITC (Interrupt Threshold Control) field is to set the maximum * rate at which the device controller will issue interrupts. * The maximum interrupt interval measured in micro frames. * Valid values are 0, 1, 2, 4, 8, 16, 32, 64. The default value is * 8 micro frames. If CPU can handle interrupts at faster rate, ITC * can be set to lesser value to gain performance. */ if (udc->udc_driver->flags & CI13XXX_ZERO_ITC) hw_cwrite(CAP_USBCMD, USBCMD_ITC_MASK, USBCMD_ITC(0)); if (hw_cread(CAP_USBMODE, USBMODE_CM) != USBMODE_CM_DEVICE) { pr_err("cannot enter in device mode"); pr_err("lpm = %i", hw_bank.lpm); return -ENODEV; } return 0; } /** * hw_device_state: enables/disables interrupts & starts/stops device (execute * without interruption) * @dma: 0 => disable, !0 => enable and set dma engine * * This function returns an error code */ static int hw_device_state(u32 dma) { struct ci13xxx *udc = _udc; if (dma) { if (streaming || !(udc->udc_driver->flags & CI13XXX_DISABLE_STREAMING)) hw_cwrite(CAP_USBMODE, USBMODE_SDIS, 0); else hw_cwrite(CAP_USBMODE, USBMODE_SDIS, USBMODE_SDIS); hw_cwrite(CAP_ENDPTLISTADDR, ~0, dma); /* interrupt, error, port change, reset, sleep/suspend */ hw_cwrite(CAP_USBINTR, ~0, USBi_UI|USBi_UEI|USBi_PCI|USBi_URI|USBi_SLI); hw_cwrite(CAP_USBCMD, USBCMD_RS, USBCMD_RS); } else { hw_cwrite(CAP_USBCMD, USBCMD_RS, 0); hw_cwrite(CAP_USBINTR, ~0, 0); } return 0; } static void debug_ept_flush_info(int ep_num, int dir) { struct ci13xxx *udc = _udc; struct ci13xxx_ep *mep; if (dir) mep = &udc->ci13xxx_ep[ep_num + hw_ep_max/2]; else mep = &udc->ci13xxx_ep[ep_num]; pr_err_ratelimited("USB Registers\n"); pr_err_ratelimited("USBCMD:%x\n", hw_cread(CAP_USBCMD, ~0)); pr_err_ratelimited("USBSTS:%x\n", hw_cread(CAP_USBSTS, ~0)); pr_err_ratelimited("ENDPTLISTADDR:%x\n", hw_cread(CAP_ENDPTLISTADDR, ~0)); pr_err_ratelimited("PORTSC:%x\n", hw_cread(CAP_PORTSC, ~0)); pr_err_ratelimited("USBMODE:%x\n", hw_cread(CAP_USBMODE, ~0)); pr_err_ratelimited("ENDPTSTAT:%x\n", hw_cread(CAP_ENDPTSTAT, ~0)); dbg_usb_op_fail(0xFF, "FLUSHF", mep); } /** * hw_ep_flush: flush endpoint fifo (execute without interruption) * @num: endpoint number * @dir: endpoint direction * * This function returns an error code */ static int hw_ep_flush(int num, int dir) { ktime_t start, diff; int n = hw_ep_bit(num, dir); struct ci13xxx_ep *mEp = &_udc->ci13xxx_ep[n]; /* Flush ep0 even when queue is empty */ if (_udc->skip_flush || (num && list_empty(&mEp->qh.queue))) return 0; start = ktime_get(); do { /* flush any pending transfer */ hw_cwrite(CAP_ENDPTFLUSH, BIT(n), BIT(n)); while (hw_cread(CAP_ENDPTFLUSH, BIT(n))) { cpu_relax(); diff = ktime_sub(ktime_get(), start); if (ktime_to_ms(diff) > USB_MAX_TIMEOUT) { printk_ratelimited(KERN_ERR "%s: Failed to flush ep#%d %s\n", __func__, num, dir ? "IN" : "OUT"); debug_ept_flush_info(num, dir); _udc->skip_flush = true; return 0; } } } while (hw_cread(CAP_ENDPTSTAT, BIT(n))); return 0; } /** * hw_ep_disable: disables endpoint (execute without interruption) * @num: endpoint number * @dir: endpoint direction * * This function returns an error code */ static int hw_ep_disable(int num, int dir) { hw_cwrite(CAP_ENDPTCTRL + num * sizeof(u32), dir ? ENDPTCTRL_TXE : ENDPTCTRL_RXE, 0); return 0; } /** * hw_ep_enable: enables endpoint (execute without interruption) * @num: endpoint number * @dir: endpoint direction * @type: endpoint type * * This function returns an error code */ static int hw_ep_enable(int num, int dir, int type) { u32 mask, data; if (dir) { mask = ENDPTCTRL_TXT; /* type */ data = type << ffs_nr(mask); mask |= ENDPTCTRL_TXS; /* unstall */ mask |= ENDPTCTRL_TXR; /* reset data toggle */ data |= ENDPTCTRL_TXR; mask |= ENDPTCTRL_TXE; /* enable */ data |= ENDPTCTRL_TXE; } else { mask = ENDPTCTRL_RXT; /* type */ data = type << ffs_nr(mask); mask |= ENDPTCTRL_RXS; /* unstall */ mask |= ENDPTCTRL_RXR; /* reset data toggle */ data |= ENDPTCTRL_RXR; mask |= ENDPTCTRL_RXE; /* enable */ data |= ENDPTCTRL_RXE; } hw_cwrite(CAP_ENDPTCTRL + num * sizeof(u32), mask, data); /* make sure endpoint is enabled before returning */ mb(); return 0; } /** * hw_ep_get_halt: return endpoint halt status * @num: endpoint number * @dir: endpoint direction * * This function returns 1 if endpoint halted */ static int hw_ep_get_halt(int num, int dir) { u32 mask = dir ? ENDPTCTRL_TXS : ENDPTCTRL_RXS; return hw_cread(CAP_ENDPTCTRL + num * sizeof(u32), mask) ? 1 : 0; } /** * hw_test_and_clear_setup_status: test & clear setup status (execute without * interruption) * @n: endpoint number * * This function returns setup status */ static int hw_test_and_clear_setup_status(int n) { n = ep_to_bit(n); return hw_ctest_and_clear(CAP_ENDPTSETUPSTAT, BIT(n)); } /** * hw_ep_prime: primes endpoint (execute without interruption) * @num: endpoint number * @dir: endpoint direction * @is_ctrl: true if control endpoint * * This function returns an error code */ static int hw_ep_prime(int num, int dir, int is_ctrl) { int n = hw_ep_bit(num, dir); if (is_ctrl && dir == RX && hw_cread(CAP_ENDPTSETUPSTAT, BIT(num))) return -EAGAIN; hw_cwrite(CAP_ENDPTPRIME, BIT(n), BIT(n)); if (is_ctrl && dir == RX && hw_cread(CAP_ENDPTSETUPSTAT, BIT(num))) return -EAGAIN; /* status shoult be tested according with manual but it doesn't work */ return 0; } /** * hw_ep_set_halt: configures ep halt & resets data toggle after clear (execute * without interruption) * @num: endpoint number * @dir: endpoint direction * @value: true => stall, false => unstall * * This function returns an error code */ static int hw_ep_set_halt(int num, int dir, int value) { u32 addr, mask_xs, mask_xr; if (value != 0 && value != 1) return -EINVAL; do { if (hw_cread(CAP_ENDPTSETUPSTAT, BIT(num))) return 0; addr = CAP_ENDPTCTRL + num * sizeof(u32); mask_xs = dir ? ENDPTCTRL_TXS : ENDPTCTRL_RXS; mask_xr = dir ? ENDPTCTRL_TXR : ENDPTCTRL_RXR; /* data toggle - reserved for EP0 but it's in ESS */ hw_cwrite(addr, mask_xs|mask_xr, value ? mask_xs : mask_xr); } while (value != hw_ep_get_halt(num, dir)); return 0; } /** * hw_intr_clear: disables interrupt & clears interrupt status (execute without * interruption) * @n: interrupt bit * * This function returns an error code */ static int hw_intr_clear(int n) { if (n >= REG_BITS) return -EINVAL; hw_cwrite(CAP_USBINTR, BIT(n), 0); hw_cwrite(CAP_USBSTS, BIT(n), BIT(n)); return 0; } /** * hw_intr_force: enables interrupt & forces interrupt status (execute without * interruption) * @n: interrupt bit * * This function returns an error code */ static int hw_intr_force(int n) { if (n >= REG_BITS) return -EINVAL; hw_awrite(ABS_TESTMODE, TESTMODE_FORCE, TESTMODE_FORCE); hw_cwrite(CAP_USBINTR, BIT(n), BIT(n)); hw_cwrite(CAP_USBSTS, BIT(n), BIT(n)); hw_awrite(ABS_TESTMODE, TESTMODE_FORCE, 0); return 0; } /** * hw_is_port_high_speed: test if port is high speed * * This function returns true if high speed port */ static int hw_port_is_high_speed(void) { return hw_bank.lpm ? hw_cread(CAP_DEVLC, DEVLC_PSPD) : hw_cread(CAP_PORTSC, PORTSC_HSP); } /** * hw_port_test_get: reads port test mode value * * This function returns port test mode value */ static u8 hw_port_test_get(void) { return hw_cread(CAP_PORTSC, PORTSC_PTC) >> ffs_nr(PORTSC_PTC); } /** * hw_port_test_set: writes port test mode (execute without interruption) * @mode: new value * * This function returns an error code */ static int hw_port_test_set(u8 mode) { const u8 TEST_MODE_MAX = 7; if (mode > TEST_MODE_MAX) return -EINVAL; hw_cwrite(CAP_PORTSC, PORTSC_PTC, mode << ffs_nr(PORTSC_PTC)); return 0; } /** * hw_read_intr_enable: returns interrupt enable register * * This function returns register data */ static u32 hw_read_intr_enable(void) { return hw_cread(CAP_USBINTR, ~0); } /** * hw_read_intr_status: returns interrupt status register * * This function returns register data */ static u32 hw_read_intr_status(void) { return hw_cread(CAP_USBSTS, ~0); } /** * hw_register_read: reads all device registers (execute without interruption) * @buf: destination buffer * @size: buffer size * * This function returns number of registers read */ static size_t hw_register_read(u32 *buf, size_t size) { unsigned i; if (size > hw_bank.size) size = hw_bank.size; for (i = 0; i < size; i++) buf[i] = hw_aread(i * sizeof(u32), ~0); return size; } /** * hw_register_write: writes to register * @addr: register address * @data: register value * * This function returns an error code */ static int hw_register_write(u16 addr, u32 data) { /* align */ addr /= sizeof(u32); if (addr >= hw_bank.size) return -EINVAL; /* align */ addr *= sizeof(u32); hw_awrite(addr, ~0, data); return 0; } /** * hw_test_and_clear_complete: test & clear complete status (execute without * interruption) * @n: endpoint number * * This function returns complete status */ static int hw_test_and_clear_complete(int n) { n = ep_to_bit(n); return hw_ctest_and_clear(CAP_ENDPTCOMPLETE, BIT(n)); } /** * hw_test_and_clear_intr_active: test & clear active interrupts (execute * without interruption) * * This function returns active interrutps */ static u32 hw_test_and_clear_intr_active(void) { u32 reg = hw_read_intr_status() & hw_read_intr_enable(); hw_cwrite(CAP_USBSTS, ~0, reg); return reg; } /** * hw_test_and_clear_setup_guard: test & clear setup guard (execute without * interruption) * * This function returns guard value */ static int hw_test_and_clear_setup_guard(void) { return hw_ctest_and_write(CAP_USBCMD, USBCMD_SUTW, 0); } /** * hw_test_and_set_setup_guard: test & set setup guard (execute without * interruption) * * This function returns guard value */ static int hw_test_and_set_setup_guard(void) { return hw_ctest_and_write(CAP_USBCMD, USBCMD_SUTW, USBCMD_SUTW); } /** * hw_usb_set_address: configures USB address (execute without interruption) * @value: new USB address * * This function returns an error code */ static int hw_usb_set_address(u8 value) { /* advance */ hw_cwrite(CAP_DEVICEADDR, DEVICEADDR_USBADR | DEVICEADDR_USBADRA, value << ffs_nr(DEVICEADDR_USBADR) | DEVICEADDR_USBADRA); return 0; } /** * hw_usb_reset: restart device after a bus reset (execute without * interruption) * * This function returns an error code */ static int hw_usb_reset(void) { int delay_count = 10; /* 100 usec delay */ hw_usb_set_address(0); /* ESS flushes only at end?!? */ hw_cwrite(CAP_ENDPTFLUSH, ~0, ~0); /* flush all EPs */ /* clear setup token semaphores */ hw_cwrite(CAP_ENDPTSETUPSTAT, 0, 0); /* writes its content */ /* clear complete status */ hw_cwrite(CAP_ENDPTCOMPLETE, 0, 0); /* writes its content */ /* wait until all bits cleared */ while (delay_count-- && hw_cread(CAP_ENDPTPRIME, ~0)) udelay(10); if (delay_count < 0) pr_err("ENDPTPRIME is not cleared during bus reset\n"); /* reset all endpoints ? */ /* reset internal status and wait for further instructions no need to verify the port reset status (ESS does it) */ return 0; } /****************************************************************************** * DBG block *****************************************************************************/ /** * show_device: prints information about device capabilities and status * * Check "device.h" for details */ static ssize_t show_device(struct device *dev, struct device_attribute *attr, char *buf) { struct ci13xxx *udc = container_of(dev, struct ci13xxx, gadget.dev); struct usb_gadget *gadget = &udc->gadget; int n = 0; dbg_trace("[%s] %p\n", __func__, buf); if (attr == NULL || buf == NULL) { dev_err(dev, "[%s] EINVAL\n", __func__); return 0; } n += scnprintf(buf + n, PAGE_SIZE - n, "speed = %d\n", gadget->speed); n += scnprintf(buf + n, PAGE_SIZE - n, "max_speed = %d\n", gadget->max_speed); /* TODO: Scheduled for removal in 3.8. */ n += scnprintf(buf + n, PAGE_SIZE - n, "is_dualspeed = %d\n", gadget_is_dualspeed(gadget)); n += scnprintf(buf + n, PAGE_SIZE - n, "is_otg = %d\n", gadget->is_otg); n += scnprintf(buf + n, PAGE_SIZE - n, "is_a_peripheral = %d\n", gadget->is_a_peripheral); n += scnprintf(buf + n, PAGE_SIZE - n, "b_hnp_enable = %d\n", gadget->b_hnp_enable); n += scnprintf(buf + n, PAGE_SIZE - n, "a_hnp_support = %d\n", gadget->a_hnp_support); n += scnprintf(buf + n, PAGE_SIZE - n, "a_alt_hnp_support = %d\n", gadget->a_alt_hnp_support); n += scnprintf(buf + n, PAGE_SIZE - n, "name = %s\n", (gadget->name ? gadget->name : "")); return n; } static DEVICE_ATTR(device, S_IRUSR, show_device, NULL); /** * show_driver: prints information about attached gadget (if any) * * Check "device.h" for details */ static ssize_t show_driver(struct device *dev, struct device_attribute *attr, char *buf) { struct ci13xxx *udc = container_of(dev, struct ci13xxx, gadget.dev); struct usb_gadget_driver *driver = udc->driver; int n = 0; dbg_trace("[%s] %p\n", __func__, buf); if (attr == NULL || buf == NULL) { dev_err(dev, "[%s] EINVAL\n", __func__); return 0; } if (driver == NULL) return scnprintf(buf, PAGE_SIZE, "There is no gadget attached!\n"); n += scnprintf(buf + n, PAGE_SIZE - n, "function = %s\n", (driver->function ? driver->function : "")); n += scnprintf(buf + n, PAGE_SIZE - n, "max speed = %d\n", driver->max_speed); return n; } static DEVICE_ATTR(driver, S_IRUSR, show_driver, NULL); /* Maximum event message length */ #define DBG_DATA_MSG 64UL /* Maximum event messages */ #define DBG_DATA_MAX 128UL /* Event buffer descriptor */ static struct { char (buf[DBG_DATA_MAX])[DBG_DATA_MSG]; /* buffer */ unsigned idx; /* index */ unsigned tty; /* print to console? */ rwlock_t lck; /* lock */ } dbg_data = { .idx = 0, .tty = 0, .lck = __RW_LOCK_UNLOCKED(lck) }; /** * dbg_dec: decrements debug event index * @idx: buffer index */ static void dbg_dec(unsigned *idx) { *idx = (*idx - 1) & (DBG_DATA_MAX-1); } /** * dbg_inc: increments debug event index * @idx: buffer index */ static void dbg_inc(unsigned *idx) { *idx = (*idx + 1) & (DBG_DATA_MAX-1); } static unsigned int ep_addr_txdbg_mask; module_param(ep_addr_txdbg_mask, uint, S_IRUGO | S_IWUSR); static unsigned int ep_addr_rxdbg_mask; module_param(ep_addr_rxdbg_mask, uint, S_IRUGO | S_IWUSR); static int allow_dbg_print(u8 addr) { int dir, num; /* allow bus wide events */ if (addr == 0xff) return 1; dir = addr & USB_ENDPOINT_DIR_MASK ? TX : RX; num = addr & ~USB_ENDPOINT_DIR_MASK; num = 1 << num; if ((dir == TX) && (num & ep_addr_txdbg_mask)) return 1; if ((dir == RX) && (num & ep_addr_rxdbg_mask)) return 1; return 0; } /** * dbg_print: prints the common part of the event * @addr: endpoint address * @name: event name * @status: status * @extra: extra information */ static void dbg_print(u8 addr, const char *name, int status, const char *extra) { struct timeval tval; unsigned int stamp; unsigned long flags; if (!allow_dbg_print(addr)) return; write_lock_irqsave(&dbg_data.lck, flags); do_gettimeofday(&tval); stamp = tval.tv_sec & 0xFFFF; /* 2^32 = 4294967296. Limit to 4096s */ stamp = stamp * 1000000 + tval.tv_usec; scnprintf(dbg_data.buf[dbg_data.idx], DBG_DATA_MSG, "%04X\t? %02X %-7.7s %4i ?\t%s\n", stamp, addr, name, status, extra); dbg_inc(&dbg_data.idx); write_unlock_irqrestore(&dbg_data.lck, flags); if (dbg_data.tty != 0) pr_notice("%04X\t? %02X %-7.7s %4i ?\t%s\n", stamp, addr, name, status, extra); } /** * dbg_done: prints a DONE event * @addr: endpoint address * @td: transfer descriptor * @status: status */ static void dbg_done(u8 addr, const u32 token, int status) { char msg[DBG_DATA_MSG]; scnprintf(msg, sizeof(msg), "%d %02X", (int)(token & TD_TOTAL_BYTES) >> ffs_nr(TD_TOTAL_BYTES), (int)(token & TD_STATUS) >> ffs_nr(TD_STATUS)); dbg_print(addr, "DONE", status, msg); } /** * dbg_event: prints a generic event * @addr: endpoint address * @name: event name * @status: status */ static void dbg_event(u8 addr, const char *name, int status) { if (name != NULL) dbg_print(addr, name, status, ""); } /* * dbg_queue: prints a QUEUE event * @addr: endpoint address * @req: USB request * @status: status */ static void dbg_queue(u8 addr, const struct usb_request *req, int status) { char msg[DBG_DATA_MSG]; if (req != NULL) { scnprintf(msg, sizeof(msg), "%d %d", !req->no_interrupt, req->length); dbg_print(addr, "QUEUE", status, msg); } } /** * dbg_setup: prints a SETUP event * @addr: endpoint address * @req: setup request */ static void dbg_setup(u8 addr, const struct usb_ctrlrequest *req) { char msg[DBG_DATA_MSG]; if (req != NULL) { scnprintf(msg, sizeof(msg), "%02X %02X %04X %04X %d", req->bRequestType, req->bRequest, le16_to_cpu(req->wValue), le16_to_cpu(req->wIndex), le16_to_cpu(req->wLength)); dbg_print(addr, "SETUP", 0, msg); } } /** * dbg_usb_op_fail: prints USB Operation FAIL event * @addr: endpoint address * @mEp: endpoint structure */ static void dbg_usb_op_fail(u8 addr, const char *name, const struct ci13xxx_ep *mep) { char msg[DBG_DATA_MSG]; struct ci13xxx_req *req; struct list_head *ptr = NULL; if (mep != NULL) { scnprintf(msg, sizeof(msg), "%s Fail EP%d%s QH:%08X", name, mep->num, mep->dir ? "IN" : "OUT", mep->qh.ptr->cap); dbg_print(addr, name, 0, msg); scnprintf(msg, sizeof(msg), "cap:%08X %08X %08X\n", mep->qh.ptr->curr, mep->qh.ptr->td.next, mep->qh.ptr->td.token); dbg_print(addr, "QHEAD", 0, msg); list_for_each(ptr, &mep->qh.queue) { req = list_entry(ptr, struct ci13xxx_req, queue); scnprintf(msg, sizeof(msg), "%08X:%08X:%08X\n", req->dma, req->ptr->next, req->ptr->token); dbg_print(addr, "REQ", 0, msg); scnprintf(msg, sizeof(msg), "%08X:%d\n", req->ptr->page[0], req->req.status); dbg_print(addr, "REQPAGE", 0, msg); } } } /** * show_events: displays the event buffer * * Check "device.h" for details */ static ssize_t show_events(struct device *dev, struct device_attribute *attr, char *buf) { unsigned long flags; unsigned i, j, n = 0; dbg_trace("[%s] %p\n", __func__, buf); if (attr == NULL || buf == NULL) { dev_err(dev, "[%s] EINVAL\n", __func__); return 0; } read_lock_irqsave(&dbg_data.lck, flags); i = dbg_data.idx; for (dbg_dec(&i); i != dbg_data.idx; dbg_dec(&i)) { n += strlen(dbg_data.buf[i]); if (n >= PAGE_SIZE) { n -= strlen(dbg_data.buf[i]); break; } } for (j = 0, dbg_inc(&i); j < n; dbg_inc(&i)) j += scnprintf(buf + j, PAGE_SIZE - j, "%s", dbg_data.buf[i]); read_unlock_irqrestore(&dbg_data.lck, flags); return n; } /** * store_events: configure if events are going to be also printed to console * * Check "device.h" for details */ static ssize_t store_events(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { unsigned tty; dbg_trace("[%s] %p, %d\n", __func__, buf, count); if (attr == NULL || buf == NULL) { dev_err(dev, "[%s] EINVAL\n", __func__); goto done; } if (sscanf(buf, "%u", &tty) != 1 || tty > 1) { dev_err(dev, "<1|0>: enable|disable console log\n"); goto done; } dbg_data.tty = tty; dev_info(dev, "tty = %u", dbg_data.tty); done: return count; } static DEVICE_ATTR(events, S_IRUSR | S_IWUSR, show_events, store_events); /** * show_inters: interrupt status, enable status and historic * * Check "device.h" for details */ static ssize_t show_inters(struct device *dev, struct device_attribute *attr, char *buf) { struct ci13xxx *udc = container_of(dev, struct ci13xxx, gadget.dev); unsigned long flags; u32 intr; unsigned i, j, n = 0; dbg_trace("[%s] %p\n", __func__, buf); if (attr == NULL || buf == NULL) { dev_err(dev, "[%s] EINVAL\n", __func__); return 0; } spin_lock_irqsave(udc->lock, flags); n += scnprintf(buf + n, PAGE_SIZE - n, "status = %08x\n", hw_read_intr_status()); n += scnprintf(buf + n, PAGE_SIZE - n, "enable = %08x\n", hw_read_intr_enable()); n += scnprintf(buf + n, PAGE_SIZE - n, "*test = %d\n", isr_statistics.test); n += scnprintf(buf + n, PAGE_SIZE - n, "? ui = %d\n", isr_statistics.ui); n += scnprintf(buf + n, PAGE_SIZE - n, "? uei = %d\n", isr_statistics.uei); n += scnprintf(buf + n, PAGE_SIZE - n, "? pci = %d\n", isr_statistics.pci); n += scnprintf(buf + n, PAGE_SIZE - n, "? uri = %d\n", isr_statistics.uri); n += scnprintf(buf + n, PAGE_SIZE - n, "? sli = %d\n", isr_statistics.sli); n += scnprintf(buf + n, PAGE_SIZE - n, "*none = %d\n", isr_statistics.none); n += scnprintf(buf + n, PAGE_SIZE - n, "*hndl = %d\n", isr_statistics.hndl.cnt); for (i = isr_statistics.hndl.idx, j = 0; j <= ISR_MASK; j++, i++) { i &= ISR_MASK; intr = isr_statistics.hndl.buf[i]; if (USBi_UI & intr) n += scnprintf(buf + n, PAGE_SIZE - n, "ui "); intr &= ~USBi_UI; if (USBi_UEI & intr) n += scnprintf(buf + n, PAGE_SIZE - n, "uei "); intr &= ~USBi_UEI; if (USBi_PCI & intr) n += scnprintf(buf + n, PAGE_SIZE - n, "pci "); intr &= ~USBi_PCI; if (USBi_URI & intr) n += scnprintf(buf + n, PAGE_SIZE - n, "uri "); intr &= ~USBi_URI; if (USBi_SLI & intr) n += scnprintf(buf + n, PAGE_SIZE - n, "sli "); intr &= ~USBi_SLI; if (intr) n += scnprintf(buf + n, PAGE_SIZE - n, "??? "); if (isr_statistics.hndl.buf[i]) n += scnprintf(buf + n, PAGE_SIZE - n, "\n"); } spin_unlock_irqrestore(udc->lock, flags); return n; } /** * store_inters: enable & force or disable an individual interrutps * (to be used for test purposes only) * * Check "device.h" for details */ static ssize_t store_inters(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct ci13xxx *udc = container_of(dev, struct ci13xxx, gadget.dev); unsigned long flags; unsigned en, bit; dbg_trace("[%s] %p, %d\n", __func__, buf, count); if (attr == NULL || buf == NULL) { dev_err(dev, "[%s] EINVAL\n", __func__); goto done; } if (sscanf(buf, "%u %u", &en, &bit) != 2 || en > 1) { dev_err(dev, "<1|0> <bit>: enable|disable interrupt"); goto done; } spin_lock_irqsave(udc->lock, flags); if (en) { if (hw_intr_force(bit)) dev_err(dev, "invalid bit number\n"); else isr_statistics.test++; } else { if (hw_intr_clear(bit)) dev_err(dev, "invalid bit number\n"); } spin_unlock_irqrestore(udc->lock, flags); done: return count; } static DEVICE_ATTR(inters, S_IRUSR | S_IWUSR, show_inters, store_inters); /** * show_port_test: reads port test mode * * Check "device.h" for details */ static ssize_t show_port_test(struct device *dev, struct device_attribute *attr, char *buf) { struct ci13xxx *udc = container_of(dev, struct ci13xxx, gadget.dev); unsigned long flags; unsigned mode; dbg_trace("[%s] %p\n", __func__, buf); if (attr == NULL || buf == NULL) { dev_err(dev, "[%s] EINVAL\n", __func__); return 0; } spin_lock_irqsave(udc->lock, flags); mode = hw_port_test_get(); spin_unlock_irqrestore(udc->lock, flags); return scnprintf(buf, PAGE_SIZE, "mode = %u\n", mode); } /** * store_port_test: writes port test mode * * Check "device.h" for details */ static ssize_t store_port_test(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct ci13xxx *udc = container_of(dev, struct ci13xxx, gadget.dev); unsigned long flags; unsigned mode; dbg_trace("[%s] %p, %d\n", __func__, buf, count); if (attr == NULL || buf == NULL) { dev_err(dev, "[%s] EINVAL\n", __func__); goto done; } if (sscanf(buf, "%u", &mode) != 1) { dev_err(dev, "<mode>: set port test mode"); goto done; } spin_lock_irqsave(udc->lock, flags); if (hw_port_test_set(mode)) dev_err(dev, "invalid mode\n"); spin_unlock_irqrestore(udc->lock, flags); done: return count; } static DEVICE_ATTR(port_test, S_IRUSR | S_IWUSR, show_port_test, store_port_test); /** * show_qheads: DMA contents of all queue heads * * Check "device.h" for details */ static ssize_t show_qheads(struct device *dev, struct device_attribute *attr, char *buf) { struct ci13xxx *udc = container_of(dev, struct ci13xxx, gadget.dev); unsigned long flags; unsigned i, j, n = 0; dbg_trace("[%s] %p\n", __func__, buf); if (attr == NULL || buf == NULL) { dev_err(dev, "[%s] EINVAL\n", __func__); return 0; } spin_lock_irqsave(udc->lock, flags); for (i = 0; i < hw_ep_max/2; i++) { struct ci13xxx_ep *mEpRx = &udc->ci13xxx_ep[i]; struct ci13xxx_ep *mEpTx = &udc->ci13xxx_ep[i + hw_ep_max/2]; n += scnprintf(buf + n, PAGE_SIZE - n, "EP=%02i: RX=%08X TX=%08X\n", i, (u32)mEpRx->qh.dma, (u32)mEpTx->qh.dma); for (j = 0; j < (sizeof(struct ci13xxx_qh)/sizeof(u32)); j++) { n += scnprintf(buf + n, PAGE_SIZE - n, " %04X: %08X %08X\n", j, *((u32 *)mEpRx->qh.ptr + j), *((u32 *)mEpTx->qh.ptr + j)); } } spin_unlock_irqrestore(udc->lock, flags); return n; } static DEVICE_ATTR(qheads, S_IRUSR, show_qheads, NULL); /** * show_registers: dumps all registers * * Check "device.h" for details */ #define DUMP_ENTRIES 512 static ssize_t show_registers(struct device *dev, struct device_attribute *attr, char *buf) { struct ci13xxx *udc = container_of(dev, struct ci13xxx, gadget.dev); unsigned long flags; u32 *dump; unsigned i, k, n = 0; dbg_trace("[%s] %p\n", __func__, buf); if (attr == NULL || buf == NULL) { dev_err(dev, "[%s] EINVAL\n", __func__); return 0; } dump = kmalloc(2048, GFP_KERNEL); if (dump == NULL) return -ENOMEM; dump = kmalloc(sizeof(u32) * DUMP_ENTRIES, GFP_KERNEL); if (!dump) { dev_err(dev, "%s: out of memory\n", __func__); return 0; } spin_lock_irqsave(udc->lock, flags); k = hw_register_read(dump, DUMP_ENTRIES); spin_unlock_irqrestore(udc->lock, flags); for (i = 0; i < k; i++) { n += scnprintf(buf + n, PAGE_SIZE - n, "reg[0x%04X] = 0x%08X\n", i * (unsigned)sizeof(u32), dump[i]); } kfree(dump); return n; } /** * store_registers: writes value to register address * * Check "device.h" for details */ static ssize_t store_registers(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct ci13xxx *udc = container_of(dev, struct ci13xxx, gadget.dev); unsigned long addr, data, flags; dbg_trace("[%s] %p, %d\n", __func__, buf, count); if (attr == NULL || buf == NULL) { dev_err(dev, "[%s] EINVAL\n", __func__); goto done; } if (sscanf(buf, "%li %li", &addr, &data) != 2) { dev_err(dev, "<addr> <data>: write data to register address"); goto done; } spin_lock_irqsave(udc->lock, flags); if (hw_register_write(addr, data)) dev_err(dev, "invalid address range\n"); spin_unlock_irqrestore(udc->lock, flags); done: return count; } static DEVICE_ATTR(registers, S_IRUSR | S_IWUSR, show_registers, store_registers); /** * show_requests: DMA contents of all requests currently queued (all endpts) * * Check "device.h" for details */ static ssize_t show_requests(struct device *dev, struct device_attribute *attr, char *buf) { struct ci13xxx *udc = container_of(dev, struct ci13xxx, gadget.dev); unsigned long flags; struct list_head *ptr = NULL; struct ci13xxx_req *req = NULL; unsigned i, j, n = 0, qSize = sizeof(struct ci13xxx_td)/sizeof(u32); dbg_trace("[%s] %p\n", __func__, buf); if (attr == NULL || buf == NULL) { dev_err(dev, "[%s] EINVAL\n", __func__); return 0; } spin_lock_irqsave(udc->lock, flags); for (i = 0; i < hw_ep_max; i++) list_for_each(ptr, &udc->ci13xxx_ep[i].qh.queue) { req = list_entry(ptr, struct ci13xxx_req, queue); n += scnprintf(buf + n, PAGE_SIZE - n, "EP=%02i: TD=%08X %s\n", i % hw_ep_max/2, (u32)req->dma, ((i < hw_ep_max/2) ? "RX" : "TX")); for (j = 0; j < qSize; j++) n += scnprintf(buf + n, PAGE_SIZE - n, " %04X: %08X\n", j, *((u32 *)req->ptr + j)); } spin_unlock_irqrestore(udc->lock, flags); return n; } static DEVICE_ATTR(requests, S_IRUSR, show_requests, NULL); /* EP# and Direction */ static ssize_t prime_ept(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct ci13xxx *udc = container_of(dev, struct ci13xxx, gadget.dev); struct ci13xxx_ep *mEp; unsigned int ep_num, dir; int n; struct ci13xxx_req *mReq = NULL; if (sscanf(buf, "%u %u", &ep_num, &dir) != 2) { dev_err(dev, "<ep_num> <dir>: prime the ep"); goto done; } if (dir) mEp = &udc->ci13xxx_ep[ep_num + hw_ep_max/2]; else mEp = &udc->ci13xxx_ep[ep_num]; n = hw_ep_bit(mEp->num, mEp->dir); mReq = list_entry(mEp->qh.queue.next, struct ci13xxx_req, queue); mEp->qh.ptr->td.next = mReq->dma; mEp->qh.ptr->td.token &= ~TD_STATUS; wmb(); hw_cwrite(CAP_ENDPTPRIME, BIT(n), BIT(n)); while (hw_cread(CAP_ENDPTPRIME, BIT(n))) cpu_relax(); pr_info("%s: prime:%08x stat:%08x ep#%d dir:%s\n", __func__, hw_cread(CAP_ENDPTPRIME, ~0), hw_cread(CAP_ENDPTSTAT, ~0), mEp->num, mEp->dir ? "IN" : "OUT"); done: return count; } static DEVICE_ATTR(prime, S_IWUSR, NULL, prime_ept); /* EP# and Direction */ static ssize_t print_dtds(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct ci13xxx *udc = container_of(dev, struct ci13xxx, gadget.dev); struct ci13xxx_ep *mEp; unsigned int ep_num, dir; int n; struct list_head *ptr = NULL; struct ci13xxx_req *req = NULL; if (sscanf(buf, "%u %u", &ep_num, &dir) != 2) { dev_err(dev, "<ep_num> <dir>: to print dtds"); goto done; } if (dir) mEp = &udc->ci13xxx_ep[ep_num + hw_ep_max/2]; else mEp = &udc->ci13xxx_ep[ep_num]; n = hw_ep_bit(mEp->num, mEp->dir); pr_info("%s: prime:%08x stat:%08x ep#%d dir:%s" "dTD_update_fail_count: %lu " "mEp->dTD_update_fail_count: %lu" "mEp->prime_fail_count: %lu\n", __func__, hw_cread(CAP_ENDPTPRIME, ~0), hw_cread(CAP_ENDPTSTAT, ~0), mEp->num, mEp->dir ? "IN" : "OUT", udc->dTD_update_fail_count, mEp->dTD_update_fail_count, mEp->prime_fail_count); pr_info("QH: cap:%08x cur:%08x next:%08x token:%08x\n", mEp->qh.ptr->cap, mEp->qh.ptr->curr, mEp->qh.ptr->td.next, mEp->qh.ptr->td.token); list_for_each(ptr, &mEp->qh.queue) { req = list_entry(ptr, struct ci13xxx_req, queue); pr_info("\treq:%08x next:%08x token:%08x page0:%08x status:%d\n", req->dma, req->ptr->next, req->ptr->token, req->ptr->page[0], req->req.status); } done: return count; } static DEVICE_ATTR(dtds, S_IWUSR, NULL, print_dtds); static int ci13xxx_wakeup(struct usb_gadget *_gadget) { struct ci13xxx *udc = container_of(_gadget, struct ci13xxx, gadget); unsigned long flags; int ret = 0; trace(); spin_lock_irqsave(udc->lock, flags); if (!udc->remote_wakeup) { ret = -EOPNOTSUPP; dbg_trace("remote wakeup feature is not enabled\n"); goto out; } spin_unlock_irqrestore(udc->lock, flags); udc->udc_driver->notify_event(udc, CI13XXX_CONTROLLER_REMOTE_WAKEUP_EVENT); if (udc->transceiver) usb_phy_set_suspend(udc->transceiver, 0); spin_lock_irqsave(udc->lock, flags); if (!hw_cread(CAP_PORTSC, PORTSC_SUSP)) { ret = -EINVAL; dbg_trace("port is not suspended\n"); goto out; } hw_cwrite(CAP_PORTSC, PORTSC_FPR, PORTSC_FPR); out: spin_unlock_irqrestore(udc->lock, flags); return ret; } static void usb_do_remote_wakeup(struct work_struct *w) { struct ci13xxx *udc = _udc; unsigned long flags; bool do_wake; /* * This work can not be canceled from interrupt handler. Check * if wakeup conditions are still met. */ spin_lock_irqsave(udc->lock, flags); do_wake = udc->suspended && udc->remote_wakeup; spin_unlock_irqrestore(udc->lock, flags); if (do_wake) ci13xxx_wakeup(&udc->gadget); } static ssize_t usb_remote_wakeup(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct ci13xxx *udc = container_of(dev, struct ci13xxx, gadget.dev); ci13xxx_wakeup(&udc->gadget); return count; } static DEVICE_ATTR(wakeup, S_IWUSR, 0, usb_remote_wakeup); /** * dbg_create_files: initializes the attribute interface * @dev: device * * This function returns an error code */ __maybe_unused static int dbg_create_files(struct device *dev) { int retval = 0; if (dev == NULL) return -EINVAL; retval = device_create_file(dev, &dev_attr_device); if (retval) goto done; retval = device_create_file(dev, &dev_attr_driver); if (retval) goto rm_device; retval = device_create_file(dev, &dev_attr_events); if (retval) goto rm_driver; retval = device_create_file(dev, &dev_attr_inters); if (retval) goto rm_events; retval = device_create_file(dev, &dev_attr_port_test); if (retval) goto rm_inters; retval = device_create_file(dev, &dev_attr_qheads); if (retval) goto rm_port_test; retval = device_create_file(dev, &dev_attr_registers); if (retval) goto rm_qheads; retval = device_create_file(dev, &dev_attr_requests); if (retval) goto rm_registers; retval = device_create_file(dev, &dev_attr_wakeup); if (retval) goto rm_remote_wakeup; retval = device_create_file(dev, &dev_attr_prime); if (retval) goto rm_prime; retval = device_create_file(dev, &dev_attr_dtds); if (retval) goto rm_dtds; return 0; rm_dtds: device_remove_file(dev, &dev_attr_dtds); rm_prime: device_remove_file(dev, &dev_attr_prime); rm_remote_wakeup: device_remove_file(dev, &dev_attr_wakeup); rm_registers: device_remove_file(dev, &dev_attr_registers); rm_qheads: device_remove_file(dev, &dev_attr_qheads); rm_port_test: device_remove_file(dev, &dev_attr_port_test); rm_inters: device_remove_file(dev, &dev_attr_inters); rm_events: device_remove_file(dev, &dev_attr_events); rm_driver: device_remove_file(dev, &dev_attr_driver); rm_device: device_remove_file(dev, &dev_attr_device); done: return retval; } /** * dbg_remove_files: destroys the attribute interface * @dev: device * * This function returns an error code */ __maybe_unused static int dbg_remove_files(struct device *dev) { if (dev == NULL) return -EINVAL; device_remove_file(dev, &dev_attr_requests); device_remove_file(dev, &dev_attr_registers); device_remove_file(dev, &dev_attr_qheads); device_remove_file(dev, &dev_attr_port_test); device_remove_file(dev, &dev_attr_inters); device_remove_file(dev, &dev_attr_events); device_remove_file(dev, &dev_attr_driver); device_remove_file(dev, &dev_attr_device); device_remove_file(dev, &dev_attr_wakeup); return 0; } #ifdef CONFIG_ENABLE_DEFAULT_TRACERS struct ci13xxx_ebi_err_data { u32 ebi_err_addr; u32 apkt0; u32 apkt1; struct ci13xxx_ebi_err_entry *ebi_err_entry; }; static struct ci13xxx_ebi_err_data *ebi_err_data; static void dump_usb_info(void *ignore, unsigned int ebi_addr, unsigned int ebi_apacket0, unsigned int ebi_apacket1) { struct ci13xxx *udc = _udc; unsigned long flags; struct list_head *ptr = NULL; struct ci13xxx_req *req = NULL; struct ci13xxx_ep *mEp; unsigned i; struct ci13xxx_ebi_err_entry *temp_dump; static int count; u32 epdir = 0; if (count) return; count++; pr_info("%s: USB EBI error detected\n", __func__); ebi_err_data = kmalloc(sizeof(struct ci13xxx_ebi_err_data), GFP_ATOMIC); if (!ebi_err_data) { pr_err("%s: memory alloc failed for ebi_err_data\n", __func__); return; } ebi_err_data->ebi_err_entry = kmalloc( sizeof(struct ci13xxx_ebi_err_entry), GFP_ATOMIC); if (!ebi_err_data->ebi_err_entry) { kfree(ebi_err_data); pr_err("%s: memory alloc failed for ebi_err_entry\n", __func__); return; } ebi_err_data->ebi_err_addr = ebi_addr; ebi_err_data->apkt0 = ebi_apacket0; ebi_err_data->apkt1 = ebi_apacket1; temp_dump = ebi_err_data->ebi_err_entry; pr_info("\n DUMPING USB Requests Information\n"); spin_lock_irqsave(udc->lock, flags); for (i = 0; i < hw_ep_max; i++) { list_for_each(ptr, &udc->ci13xxx_ep[i].qh.queue) { mEp = &udc->ci13xxx_ep[i]; req = list_entry(ptr, struct ci13xxx_req, queue); temp_dump->usb_req_buf = req->req.buf; temp_dump->usb_req_length = req->req.length; epdir = mEp->dir; temp_dump->ep_info = mEp->num | (epdir << 15); temp_dump->next = kmalloc( sizeof(struct ci13xxx_ebi_err_entry), GFP_ATOMIC); if (!temp_dump->next) { pr_err("%s: memory alloc failed\n", __func__); spin_unlock_irqrestore(udc->lock, flags); return; } temp_dump = temp_dump->next; } } spin_unlock_irqrestore(udc->lock, flags); } #endif /****************************************************************************** * UTIL block *****************************************************************************/ /** * _usb_addr: calculates endpoint address from direction & number * @ep: endpoint */ static inline u8 _usb_addr(struct ci13xxx_ep *ep) { return ((ep->dir == TX) ? USB_ENDPOINT_DIR_MASK : 0) | ep->num; } static void ep_prime_timer_func(unsigned long data) { struct ci13xxx_ep *mep = (struct ci13xxx_ep *)data; struct ci13xxx_req *req; struct list_head *ptr = NULL; int n = hw_ep_bit(mep->num, mep->dir); unsigned long flags; spin_lock_irqsave(mep->lock, flags); if (!hw_cread(CAP_ENDPTPRIME, BIT(n))) goto out; if (list_empty(&mep->qh.queue)) goto out; req = list_entry(mep->qh.queue.next, struct ci13xxx_req, queue); mb(); if (!(TD_STATUS_ACTIVE & req->ptr->token)) goto out; mep->prime_timer_count++; if (mep->prime_timer_count == MAX_PRIME_CHECK_RETRY) { mep->prime_timer_count = 0; pr_info("ep%d dir:%s QH:cap:%08x cur:%08x next:%08x tkn:%08x\n", mep->num, mep->dir ? "IN" : "OUT", mep->qh.ptr->cap, mep->qh.ptr->curr, mep->qh.ptr->td.next, mep->qh.ptr->td.token); list_for_each(ptr, &mep->qh.queue) { req = list_entry(ptr, struct ci13xxx_req, queue); pr_info("\treq:%08xnext:%08xtkn:%08xpage0:%08xsts:%d\n", req->dma, req->ptr->next, req->ptr->token, req->ptr->page[0], req->req.status); } dbg_usb_op_fail(0xFF, "PRIMEF", mep); mep->prime_fail_count++; } else { mod_timer(&mep->prime_timer, EP_PRIME_CHECK_DELAY); } spin_unlock_irqrestore(mep->lock, flags); return; out: mep->prime_timer_count = 0; spin_unlock_irqrestore(mep->lock, flags); } /** * _hardware_queue: configures a request at hardware level * @gadget: gadget * @mEp: endpoint * * This function returns an error code */ static int _hardware_enqueue(struct ci13xxx_ep *mEp, struct ci13xxx_req *mReq) { unsigned i; int ret = 0; unsigned length = mReq->req.length; struct ci13xxx *udc = _udc; trace("%p, %p", mEp, mReq); /* don't queue twice */ if (mReq->req.status == -EALREADY) return -EALREADY; mReq->req.status = -EALREADY; if (length && mReq->req.dma == DMA_ADDR_INVALID) { mReq->req.dma = \ dma_map_single(mEp->device, mReq->req.buf, length, mEp->dir ? DMA_TO_DEVICE : DMA_FROM_DEVICE); if (mReq->req.dma == 0) return -ENOMEM; mReq->map = 1; } if (mReq->req.zero && length && (length % mEp->ep.maxpacket == 0)) { mReq->zptr = dma_pool_alloc(mEp->td_pool, GFP_ATOMIC, &mReq->zdma); if (mReq->zptr == NULL) { if (mReq->map) { dma_unmap_single(mEp->device, mReq->req.dma, length, mEp->dir ? DMA_TO_DEVICE : DMA_FROM_DEVICE); mReq->req.dma = DMA_ADDR_INVALID; mReq->map = 0; } return -ENOMEM; } memset(mReq->zptr, 0, sizeof(*mReq->zptr)); mReq->zptr->next = TD_TERMINATE; mReq->zptr->token = TD_STATUS_ACTIVE; if (!mReq->req.no_interrupt) mReq->zptr->token |= TD_IOC; } /* * TD configuration * TODO - handle requests which spawns into several TDs */ memset(mReq->ptr, 0, sizeof(*mReq->ptr)); mReq->ptr->token = length << ffs_nr(TD_TOTAL_BYTES); mReq->ptr->token &= TD_TOTAL_BYTES; mReq->ptr->token |= TD_STATUS_ACTIVE; if (mReq->zptr) { mReq->ptr->next = mReq->zdma; } else { mReq->ptr->next = TD_TERMINATE; if (!mReq->req.no_interrupt) mReq->ptr->token |= TD_IOC; } /* MSM Specific: updating the request as required for * SPS mode. Enable MSM proprietary DMA engine acording * to the UDC private data in the request. */ if (CI13XX_REQ_VENDOR_ID(mReq->req.udc_priv) == MSM_VENDOR_ID) { if (mReq->req.udc_priv & MSM_SPS_MODE) { mReq->ptr->token = TD_STATUS_ACTIVE; if (mReq->req.udc_priv & MSM_IS_FINITE_TRANSFER) mReq->ptr->next = TD_TERMINATE; else mReq->ptr->next = MSM_ETD_TYPE | mReq->dma; if (!mReq->req.no_interrupt) mReq->ptr->token |= MSM_ETD_IOC; } mReq->req.dma = 0; } mReq->ptr->page[0] = mReq->req.dma; for (i = 1; i < 5; i++) mReq->ptr->page[i] = (mReq->req.dma + i * CI13XXX_PAGE_SIZE) & ~TD_RESERVED_MASK; wmb(); /* Remote Wakeup */ if (udc->suspended) { if (!udc->remote_wakeup) { mReq->req.status = -EAGAIN; dev_dbg(mEp->device, "%s: queue failed (suspend) ept #%d\n", __func__, mEp->num); return -EAGAIN; } usb_phy_set_suspend(udc->transceiver, 0); schedule_delayed_work(&udc->rw_work, REMOTE_WAKEUP_DELAY); } if (!list_empty(&mEp->qh.queue)) { struct ci13xxx_req *mReqPrev; int n = hw_ep_bit(mEp->num, mEp->dir); int tmp_stat; ktime_t start, diff; mReqPrev = list_entry(mEp->qh.queue.prev, struct ci13xxx_req, queue); if (mReqPrev->zptr) mReqPrev->zptr->next = mReq->dma & TD_ADDR_MASK; else mReqPrev->ptr->next = mReq->dma & TD_ADDR_MASK; wmb(); if (hw_cread(CAP_ENDPTPRIME, BIT(n))) goto done; start = ktime_get(); do { hw_cwrite(CAP_USBCMD, USBCMD_ATDTW, USBCMD_ATDTW); tmp_stat = hw_cread(CAP_ENDPTSTAT, BIT(n)); diff = ktime_sub(ktime_get(), start); /* poll for max. 100ms */ if (ktime_to_ms(diff) > USB_MAX_TIMEOUT) { if (hw_cread(CAP_USBCMD, USBCMD_ATDTW)) break; printk_ratelimited(KERN_ERR "%s:queue failed ep#%d %s\n", __func__, mEp->num, mEp->dir ? "IN" : "OUT"); return -EAGAIN; } } while (!hw_cread(CAP_USBCMD, USBCMD_ATDTW)); hw_cwrite(CAP_USBCMD, USBCMD_ATDTW, 0); if (tmp_stat) goto done; } /* QH configuration */ if (!list_empty(&mEp->qh.queue)) { struct ci13xxx_req *mReq = \ list_entry(mEp->qh.queue.next, struct ci13xxx_req, queue); if (TD_STATUS_ACTIVE & mReq->ptr->token) { mEp->qh.ptr->td.next = mReq->dma; mEp->qh.ptr->td.token &= ~TD_STATUS; goto prime; } } mEp->qh.ptr->td.next = mReq->dma; /* TERMINATE = 0 */ if (CI13XX_REQ_VENDOR_ID(mReq->req.udc_priv) == MSM_VENDOR_ID) { if (mReq->req.udc_priv & MSM_SPS_MODE) { mEp->qh.ptr->td.next |= MSM_ETD_TYPE; i = hw_cread(CAP_ENDPTPIPEID + mEp->num * sizeof(u32), ~0); /* Read current value of this EPs pipe id */ i = (mEp->dir == TX) ? ((i >> MSM_TX_PIPE_ID_OFS) & MSM_PIPE_ID_MASK) : (i & MSM_PIPE_ID_MASK); /* If requested pipe id is different from current, then write it */ if (i != (mReq->req.udc_priv & MSM_PIPE_ID_MASK)) { if (mEp->dir == TX) hw_cwrite( CAP_ENDPTPIPEID + mEp->num * sizeof(u32), MSM_PIPE_ID_MASK << MSM_TX_PIPE_ID_OFS, (mReq->req.udc_priv & MSM_PIPE_ID_MASK) << MSM_TX_PIPE_ID_OFS); else hw_cwrite( CAP_ENDPTPIPEID + mEp->num * sizeof(u32), MSM_PIPE_ID_MASK, mReq->req.udc_priv & MSM_PIPE_ID_MASK); } } } mEp->qh.ptr->td.token &= ~TD_STATUS; /* clear status */ mEp->qh.ptr->cap |= QH_ZLT; prime: wmb(); /* synchronize before ep prime */ ret = hw_ep_prime(mEp->num, mEp->dir, mEp->type == USB_ENDPOINT_XFER_CONTROL); if (!ret) mod_timer(&mEp->prime_timer, EP_PRIME_CHECK_DELAY); done: return ret; } /** * _hardware_dequeue: handles a request at hardware level * @gadget: gadget * @mEp: endpoint * * This function returns an error code */ static int _hardware_dequeue(struct ci13xxx_ep *mEp, struct ci13xxx_req *mReq) { trace("%p, %p", mEp, mReq); if (mReq->req.status != -EALREADY) return -EINVAL; /* clean speculative fetches on req->ptr->token */ mb(); if ((TD_STATUS_ACTIVE & mReq->ptr->token) != 0) return -EBUSY; if (CI13XX_REQ_VENDOR_ID(mReq->req.udc_priv) == MSM_VENDOR_ID) if ((mReq->req.udc_priv & MSM_SPS_MODE) && (mReq->req.udc_priv & MSM_IS_FINITE_TRANSFER)) return -EBUSY; if (mReq->zptr) { if ((TD_STATUS_ACTIVE & mReq->zptr->token) != 0) return -EBUSY; /* The controller may access this dTD one more time. * Defer freeing this to next zero length dTD completion. * It is safe to assume that controller will no longer * access the previous dTD after next dTD completion. */ if (mEp->last_zptr) dma_pool_free(mEp->td_pool, mEp->last_zptr, mEp->last_zdma); mEp->last_zptr = mReq->zptr; mEp->last_zdma = mReq->zdma; mReq->zptr = NULL; } mReq->req.status = 0; if (mReq->map) { dma_unmap_single(mEp->device, mReq->req.dma, mReq->req.length, mEp->dir ? DMA_TO_DEVICE : DMA_FROM_DEVICE); mReq->req.dma = DMA_ADDR_INVALID; mReq->map = 0; } mReq->req.status = mReq->ptr->token & TD_STATUS; if ((TD_STATUS_HALTED & mReq->req.status) != 0){ printk("[usb] TD_STATUS_HALTED\n"); mReq->req.status = -1; } else if ((TD_STATUS_DT_ERR & mReq->req.status) != 0){ printk("[usb] TD_STATUS_DT_ERR\n"); mReq->req.status = -1; } else if ((TD_STATUS_TR_ERR & mReq->req.status) != 0){ printk("[usb] TD_STATUS_TR_ERR\n"); mReq->req.status = -1; } mReq->req.actual = mReq->ptr->token & TD_TOTAL_BYTES; mReq->req.actual >>= ffs_nr(TD_TOTAL_BYTES); mReq->req.actual = mReq->req.length - mReq->req.actual; mReq->req.actual = mReq->req.status ? 0 : mReq->req.actual; return mReq->req.actual; } /** * restore_original_req: Restore original req's attributes * @mReq: Request * * This function restores original req's attributes. Call * this function before completing the large req (>16K). */ static void restore_original_req(struct ci13xxx_req *mReq) { mReq->req.buf = mReq->multi.buf; mReq->req.length = mReq->multi.len; if (!mReq->req.status) mReq->req.actual = mReq->multi.actual; mReq->multi.len = 0; mReq->multi.actual = 0; mReq->multi.buf = NULL; } /** * _ep_nuke: dequeues all endpoint requests * @mEp: endpoint * * This function returns an error code * Caller must hold lock */ static int _ep_nuke(struct ci13xxx_ep *mEp) __releases(mEp->lock) __acquires(mEp->lock) { struct ci13xxx_ep *mEpTemp = mEp; unsigned val; trace("%p", mEp); if (mEp == NULL) return -EINVAL; hw_ep_flush(mEp->num, mEp->dir); while (!list_empty(&mEp->qh.queue)) { /* pop oldest request */ struct ci13xxx_req *mReq = \ list_entry(mEp->qh.queue.next, struct ci13xxx_req, queue); list_del_init(&mReq->queue); /* MSM Specific: Clear end point proprietary register */ if (CI13XX_REQ_VENDOR_ID(mReq->req.udc_priv) == MSM_VENDOR_ID) { if (mReq->req.udc_priv & MSM_SPS_MODE) { val = hw_cread(CAP_ENDPTPIPEID + mEp->num * sizeof(u32), ~0); if (val != MSM_EP_PIPE_ID_RESET_VAL) hw_cwrite( CAP_ENDPTPIPEID + mEp->num * sizeof(u32), ~0, MSM_EP_PIPE_ID_RESET_VAL); } } mReq->req.status = -ESHUTDOWN; if (mReq->map) { dma_unmap_single(mEp->device, mReq->req.dma, mReq->req.length, mEp->dir ? DMA_TO_DEVICE : DMA_FROM_DEVICE); mReq->req.dma = DMA_ADDR_INVALID; mReq->map = 0; } if (mEp->multi_req) { restore_original_req(mReq); mEp->multi_req = false; } if (mReq->req.complete != NULL) { spin_unlock(mEp->lock); if ((mEp->type == USB_ENDPOINT_XFER_CONTROL) && mReq->req.length) mEpTemp = &_udc->ep0in; mReq->req.complete(&mEpTemp->ep, &mReq->req); if (mEp->type == USB_ENDPOINT_XFER_CONTROL) mReq->req.complete = NULL; spin_lock(mEp->lock); } } return 0; } /** * _gadget_stop_activity: stops all USB activity, flushes & disables all endpts * @gadget: gadget * * This function returns an error code */ static int _gadget_stop_activity(struct usb_gadget *gadget) { struct ci13xxx *udc = container_of(gadget, struct ci13xxx, gadget); unsigned long flags; trace("%p", gadget); if (gadget == NULL) return -EINVAL; spin_lock_irqsave(udc->lock, flags); udc->gadget.speed = USB_SPEED_UNKNOWN; udc->remote_wakeup = 0; udc->suspended = 0; udc->configured = 0; spin_unlock_irqrestore(udc->lock, flags); gadget->b_hnp_enable = 0; gadget->a_hnp_support = 0; gadget->host_request = 0; gadget->otg_srp_reqd = 0; udc->driver->disconnect(gadget); spin_lock_irqsave(udc->lock, flags); _ep_nuke(&udc->ep0out); _ep_nuke(&udc->ep0in); spin_unlock_irqrestore(udc->lock, flags); if (udc->ep0in.last_zptr) { dma_pool_free(udc->ep0in.td_pool, udc->ep0in.last_zptr, udc->ep0in.last_zdma); udc->ep0in.last_zptr = NULL; } return 0; } /****************************************************************************** * ISR block *****************************************************************************/ /** * isr_reset_handler: USB reset interrupt handler * @udc: UDC device * * This function resets USB engine after a bus reset occurred */ static void isr_reset_handler(struct ci13xxx *udc) __releases(udc->lock) __acquires(udc->lock) { int retval; trace("%p", udc); if (udc == NULL) { err("EINVAL"); return; } dbg_event(0xFF, "BUS RST", 0); spin_unlock(udc->lock); /*stop charging upon reset */ if (udc->transceiver) usb_phy_set_power(udc->transceiver, 100); retval = _gadget_stop_activity(&udc->gadget); if (retval) goto done; _udc->skip_flush = false; retval = hw_usb_reset(); if (retval) goto done; spin_lock(udc->lock); done: if (retval) err("error: %i", retval); } /** * isr_resume_handler: USB PCI interrupt handler * @udc: UDC device * */ static void isr_resume_handler(struct ci13xxx *udc) { udc->gadget.speed = hw_port_is_high_speed() ? USB_SPEED_HIGH : USB_SPEED_FULL; if (udc->suspended) { spin_unlock(udc->lock); if (udc->udc_driver->notify_event) udc->udc_driver->notify_event(udc, CI13XXX_CONTROLLER_RESUME_EVENT); if (udc->transceiver) usb_phy_set_suspend(udc->transceiver, 0); udc->driver->resume(&udc->gadget); spin_lock(udc->lock); udc->suspended = 0; } } /** * isr_resume_handler: USB SLI interrupt handler * @udc: UDC device * */ static void isr_suspend_handler(struct ci13xxx *udc) { if (udc->gadget.speed != USB_SPEED_UNKNOWN && udc->vbus_active) { if (udc->suspended == 0) { spin_unlock(udc->lock); udc->driver->suspend(&udc->gadget); if (udc->udc_driver->notify_event) udc->udc_driver->notify_event(udc, CI13XXX_CONTROLLER_SUSPEND_EVENT); if (udc->transceiver) usb_phy_set_suspend(udc->transceiver, 1); spin_lock(udc->lock); udc->suspended = 1; } } } /** * isr_get_status_complete: get_status request complete function * @ep: endpoint * @req: request handled * * Caller must release lock */ static void isr_get_status_complete(struct usb_ep *ep, struct usb_request *req) { trace("%p, %p", ep, req); if (ep == NULL || req == NULL) { err("EINVAL"); return; } if (req->status) err("GET_STATUS failed"); } /** * isr_get_status_response: get_status request response * @udc: udc struct * @setup: setup request packet * * This function returns an error code */ static int isr_get_status_response(struct ci13xxx *udc, struct usb_ctrlrequest *setup) __releases(mEp->lock) __acquires(mEp->lock) { struct ci13xxx_ep *mEp = &udc->ep0in; struct usb_request *req = udc->status; int dir, num, retval; trace("%p, %p", mEp, setup); if (mEp == NULL || setup == NULL) return -EINVAL; req->complete = isr_get_status_complete; req->length = 2; req->buf = udc->status_buf; if ((setup->bRequestType & USB_RECIP_MASK) == USB_RECIP_DEVICE) { if (setup->wIndex == OTG_STATUS_SELECTOR) { *((u8 *)req->buf) = _udc->gadget.host_request << HOST_REQUEST_FLAG; req->length = 1; } else { /* Assume that device is bus powered for now. */ *((u16 *)req->buf) = _udc->remote_wakeup << 1; } /* TODO: D1 - Remote Wakeup; D0 - Self Powered */ retval = 0; } else if ((setup->bRequestType & USB_RECIP_MASK) \ == USB_RECIP_ENDPOINT) { dir = (le16_to_cpu(setup->wIndex) & USB_ENDPOINT_DIR_MASK) ? TX : RX; num = le16_to_cpu(setup->wIndex) & USB_ENDPOINT_NUMBER_MASK; *((u16 *)req->buf) = hw_ep_get_halt(num, dir); } /* else do nothing; reserved for future use */ spin_unlock(mEp->lock); retval = usb_ep_queue(&mEp->ep, req, GFP_ATOMIC); spin_lock(mEp->lock); return retval; } /** * isr_setup_status_complete: setup_status request complete function * @ep: endpoint * @req: request handled * * Caller must release lock. Put the port in test mode if test mode * feature is selected. */ static void isr_setup_status_complete(struct usb_ep *ep, struct usb_request *req) { struct ci13xxx *udc = req->context; unsigned long flags; trace("%p, %p", ep, req); spin_lock_irqsave(udc->lock, flags); if (udc->test_mode) hw_port_test_set(udc->test_mode); spin_unlock_irqrestore(udc->lock, flags); } /** * isr_setup_status_phase: queues the status phase of a setup transation * @udc: udc struct * * This function returns an error code */ static int isr_setup_status_phase(struct ci13xxx *udc) __releases(mEp->lock) __acquires(mEp->lock) { int retval; struct ci13xxx_ep *mEp; trace("%p", udc); mEp = (udc->ep0_dir == TX) ? &udc->ep0out : &udc->ep0in; udc->status->context = udc; udc->status->complete = isr_setup_status_complete; udc->status->length = 0; spin_unlock(mEp->lock); retval = usb_ep_queue(&mEp->ep, udc->status, GFP_ATOMIC); spin_lock(mEp->lock); return retval; } /** * isr_tr_complete_low: transaction complete low level handler * @mEp: endpoint * * This function returns an error code * Caller must hold lock */ static int isr_tr_complete_low(struct ci13xxx_ep *mEp) __releases(mEp->lock) __acquires(mEp->lock) { struct ci13xxx_req *mReq, *mReqTemp; struct ci13xxx_ep *mEpTemp = mEp; int uninitialized_var(retval); int req_dequeue = 1; struct ci13xxx *udc = _udc; trace("%p", mEp); if (list_empty(&mEp->qh.queue)) return 0; del_timer(&mEp->prime_timer); mEp->prime_timer_count = 0; list_for_each_entry_safe(mReq, mReqTemp, &mEp->qh.queue, queue) { dequeue: retval = _hardware_dequeue(mEp, mReq); if (retval < 0) { /* * FIXME: don't know exact delay * required for HW to update dTD status * bits. This is a temporary workaround till * HW designers come back on this. */ if (retval == -EBUSY && req_dequeue && (mEp->dir == 0 || mEp->num == 0)) { req_dequeue = 0; udc->dTD_update_fail_count++; mEp->dTD_update_fail_count++; udelay(10); goto dequeue; } break; } req_dequeue = 0; if (mEp->multi_req) { /* Large request in progress */ unsigned remain_len; mReq->multi.actual += mReq->req.actual; remain_len = mReq->multi.len - mReq->multi.actual; if (mReq->req.status || !remain_len || (mReq->req.actual != mReq->req.length)) { restore_original_req(mReq); mEp->multi_req = false; } else { mReq->req.buf = mReq->multi.buf + mReq->multi.actual; mReq->req.length = min_t(unsigned, remain_len, (4 * CI13XXX_PAGE_SIZE)); mReq->req.status = -EINPROGRESS; mReq->req.actual = 0; list_del_init(&mReq->queue); retval = _hardware_enqueue(mEp, mReq); if (retval) { err("Large req failed in middle"); mReq->req.status = retval; restore_original_req(mReq); mEp->multi_req = false; goto done; } else { list_add_tail(&mReq->queue, &mEp->qh.queue); return 0; } } } list_del_init(&mReq->queue); done: dbg_done(_usb_addr(mEp), mReq->ptr->token, retval); if (mReq->req.complete != NULL) { spin_unlock(mEp->lock); if ((mEp->type == USB_ENDPOINT_XFER_CONTROL) && mReq->req.length) mEpTemp = &_udc->ep0in; mReq->req.complete(&mEpTemp->ep, &mReq->req); spin_lock(mEp->lock); } } if (retval == -EBUSY) retval = 0; if (retval < 0) dbg_event(_usb_addr(mEp), "DONE", retval); return retval; } /** * isr_tr_complete_handler: transaction complete interrupt handler * @udc: UDC descriptor * * This function handles traffic events */ static void isr_tr_complete_handler(struct ci13xxx *udc) __releases(udc->lock) __acquires(udc->lock) { unsigned i; u8 tmode = 0; trace("%p", udc); if (udc == NULL) { err("EINVAL"); return; } for (i = 0; i < hw_ep_max; i++) { struct ci13xxx_ep *mEp = &udc->ci13xxx_ep[i]; int type, num, dir, err = -EINVAL; struct usb_ctrlrequest req; if (mEp->desc == NULL) continue; /* not configured */ if (hw_test_and_clear_complete(i)) { err = isr_tr_complete_low(mEp); if (mEp->type == USB_ENDPOINT_XFER_CONTROL) { if (err > 0) /* needs status phase */ err = isr_setup_status_phase(udc); if (err < 0) { dbg_event(_usb_addr(mEp), "ERROR", err); spin_unlock(udc->lock); if (usb_ep_set_halt(&mEp->ep)) err("error: ep_set_halt"); spin_lock(udc->lock); } } } if (mEp->type != USB_ENDPOINT_XFER_CONTROL || !hw_test_and_clear_setup_status(i)) continue; if (i != 0) { warn("ctrl traffic received at endpoint"); continue; } /* * Flush data and handshake transactions of previous * setup packet. */ _ep_nuke(&udc->ep0out); _ep_nuke(&udc->ep0in); /* read_setup_packet */ do { hw_test_and_set_setup_guard(); memcpy(&req, &mEp->qh.ptr->setup, sizeof(req)); /* Ensure buffer is read before acknowledging to h/w */ mb(); } while (!hw_test_and_clear_setup_guard()); type = req.bRequestType; udc->ep0_dir = (type & USB_DIR_IN) ? TX : RX; dbg_setup(_usb_addr(mEp), &req); switch (req.bRequest) { case USB_REQ_CLEAR_FEATURE: if (type == (USB_DIR_OUT|USB_RECIP_ENDPOINT) && le16_to_cpu(req.wValue) == USB_ENDPOINT_HALT) { if (req.wLength != 0) break; num = le16_to_cpu(req.wIndex); dir = num & USB_ENDPOINT_DIR_MASK; num &= USB_ENDPOINT_NUMBER_MASK; if (dir) /* TX */ num += hw_ep_max/2; if (!udc->ci13xxx_ep[num].wedge) { spin_unlock(udc->lock); err = usb_ep_clear_halt( &udc->ci13xxx_ep[num].ep); spin_lock(udc->lock); if (err) break; } err = isr_setup_status_phase(udc); } else if (type == (USB_DIR_OUT|USB_RECIP_DEVICE) && le16_to_cpu(req.wValue) == USB_DEVICE_REMOTE_WAKEUP) { if (req.wLength != 0) break; udc->remote_wakeup = 0; err = isr_setup_status_phase(udc); } else { goto delegate; } break; case USB_REQ_GET_STATUS: if (type != (USB_DIR_IN|USB_RECIP_DEVICE) && type != (USB_DIR_IN|USB_RECIP_ENDPOINT) && type != (USB_DIR_IN|USB_RECIP_INTERFACE)) goto delegate; if (le16_to_cpu(req.wValue) != 0) break; err = isr_get_status_response(udc, &req); break; case USB_REQ_SET_ADDRESS: if (type != (USB_DIR_OUT|USB_RECIP_DEVICE)) goto delegate; if (le16_to_cpu(req.wLength) != 0 || le16_to_cpu(req.wIndex) != 0) break; err = hw_usb_set_address((u8)le16_to_cpu(req.wValue)); if (err) break; err = isr_setup_status_phase(udc); break; case USB_REQ_SET_CONFIGURATION: if (type == (USB_DIR_OUT|USB_TYPE_STANDARD)) udc->configured = !!req.wValue; goto delegate; case USB_REQ_SET_FEATURE: if (type == (USB_DIR_OUT|USB_RECIP_ENDPOINT) && le16_to_cpu(req.wValue) == USB_ENDPOINT_HALT) { if (req.wLength != 0) break; num = le16_to_cpu(req.wIndex); dir = num & USB_ENDPOINT_DIR_MASK; num &= USB_ENDPOINT_NUMBER_MASK; if (dir) /* TX */ num += hw_ep_max/2; spin_unlock(udc->lock); err = usb_ep_set_halt(&udc->ci13xxx_ep[num].ep); spin_lock(udc->lock); if (!err) isr_setup_status_phase(udc); } else if (type == (USB_DIR_OUT|USB_RECIP_DEVICE)) { if (req.wLength != 0) break; switch (le16_to_cpu(req.wValue)) { case USB_DEVICE_REMOTE_WAKEUP: udc->remote_wakeup = 1; err = isr_setup_status_phase(udc); break; case USB_DEVICE_B_HNP_ENABLE: udc->gadget.b_hnp_enable = 1; err = isr_setup_status_phase(udc); break; case USB_DEVICE_A_HNP_SUPPORT: udc->gadget.a_hnp_support = 1; err = isr_setup_status_phase(udc); break; case USB_DEVICE_A_ALT_HNP_SUPPORT: break; case USB_DEVICE_TEST_MODE: tmode = le16_to_cpu(req.wIndex) >> 8; switch (tmode) { case TEST_J: case TEST_K: case TEST_SE0_NAK: case TEST_PACKET: case TEST_FORCE_EN: udc->test_mode = tmode; err = isr_setup_status_phase( udc); break; case TEST_OTG_SRP_REQD: udc->gadget.otg_srp_reqd = 1; err = isr_setup_status_phase( udc); break; case TEST_OTG_HNP_REQD: udc->gadget.host_request = 1; err = isr_setup_status_phase( udc); break; default: break; } default: break; } } else { goto delegate; } break; default: delegate: if (req.wLength == 0) /* no data phase */ udc->ep0_dir = TX; spin_unlock(udc->lock); err = udc->driver->setup(&udc->gadget, &req); spin_lock(udc->lock); break; } if (err < 0) { dbg_event(_usb_addr(mEp), "ERROR", err); spin_unlock(udc->lock); if (usb_ep_set_halt(&mEp->ep)) err("error: ep_set_halt"); spin_lock(udc->lock); } } } /****************************************************************************** * ENDPT block *****************************************************************************/ /** * ep_enable: configure endpoint, making it usable * * Check usb_ep_enable() at "usb_gadget.h" for details */ static int ep_enable(struct usb_ep *ep, const struct usb_endpoint_descriptor *desc) { struct ci13xxx_ep *mEp = container_of(ep, struct ci13xxx_ep, ep); int retval = 0; unsigned long flags; unsigned mult = 0; trace("%p, %p", ep, desc); if (ep == NULL || desc == NULL) return -EINVAL; spin_lock_irqsave(mEp->lock, flags); /* only internal SW should enable ctrl endpts */ mEp->desc = desc; if (!list_empty(&mEp->qh.queue)) warn("enabling a non-empty endpoint!"); mEp->dir = usb_endpoint_dir_in(desc) ? TX : RX; mEp->num = usb_endpoint_num(desc); mEp->type = usb_endpoint_type(desc); mEp->ep.maxpacket = usb_endpoint_maxp(desc); dbg_event(_usb_addr(mEp), "ENABLE", 0); mEp->qh.ptr->cap = 0; if (mEp->type == USB_ENDPOINT_XFER_CONTROL) { mEp->qh.ptr->cap |= QH_IOS; } else if (mEp->type == USB_ENDPOINT_XFER_ISOC) { mEp->qh.ptr->cap &= ~QH_MULT; mult = ((mEp->ep.maxpacket >> QH_MULT_SHIFT) + 1) & 0x03; mEp->qh.ptr->cap |= (mult << ffs_nr(QH_MULT)); } else { mEp->qh.ptr->cap |= QH_ZLT; } mEp->qh.ptr->cap |= (mEp->ep.maxpacket << ffs_nr(QH_MAX_PKT)) & QH_MAX_PKT; mEp->qh.ptr->td.next |= TD_TERMINATE; /* needed? */ /* complete all the updates to ept->head before enabling endpoint*/ mb(); /* * Enable endpoints in the HW other than ep0 as ep0 * is always enabled */ if (mEp->num) retval |= hw_ep_enable(mEp->num, mEp->dir, mEp->type); spin_unlock_irqrestore(mEp->lock, flags); return retval; } /** * ep_disable: endpoint is no longer usable * * Check usb_ep_disable() at "usb_gadget.h" for details */ static int ep_disable(struct usb_ep *ep) { struct ci13xxx_ep *mEp = container_of(ep, struct ci13xxx_ep, ep); int direction, retval = 0; unsigned long flags; trace("%p", ep); if (ep == NULL) return -EINVAL; else if (mEp->desc == NULL) return -EBUSY; spin_lock_irqsave(mEp->lock, flags); /* only internal SW should disable ctrl endpts */ del_timer(&mEp->prime_timer); mEp->prime_timer_count = 0; direction = mEp->dir; do { dbg_event(_usb_addr(mEp), "DISABLE", 0); retval |= _ep_nuke(mEp); retval |= hw_ep_disable(mEp->num, mEp->dir); if (mEp->type == USB_ENDPOINT_XFER_CONTROL) mEp->dir = (mEp->dir == TX) ? RX : TX; } while (mEp->dir != direction); if (mEp->last_zptr) { dma_pool_free(mEp->td_pool, mEp->last_zptr, mEp->last_zdma); mEp->last_zptr = NULL; } mEp->desc = NULL; mEp->ep.desc = NULL; spin_unlock_irqrestore(mEp->lock, flags); return retval; } /** * ep_alloc_request: allocate a request object to use with this endpoint * * Check usb_ep_alloc_request() at "usb_gadget.h" for details */ static struct usb_request *ep_alloc_request(struct usb_ep *ep, gfp_t gfp_flags) { struct ci13xxx_ep *mEp = container_of(ep, struct ci13xxx_ep, ep); struct ci13xxx_req *mReq = NULL; trace("%p, %i", ep, gfp_flags); if (ep == NULL) { err("EINVAL"); return NULL; } mReq = kzalloc(sizeof(struct ci13xxx_req), gfp_flags); if (mReq != NULL) { INIT_LIST_HEAD(&mReq->queue); mReq->req.dma = DMA_ADDR_INVALID; mReq->ptr = dma_pool_alloc(mEp->td_pool, gfp_flags, &mReq->dma); if (mReq->ptr == NULL) { kfree(mReq); mReq = NULL; } } dbg_event(_usb_addr(mEp), "ALLOC", mReq == NULL); return (mReq == NULL) ? NULL : &mReq->req; } /** * ep_free_request: frees a request object * * Check usb_ep_free_request() at "usb_gadget.h" for details */ static void ep_free_request(struct usb_ep *ep, struct usb_request *req) { struct ci13xxx_ep *mEp = container_of(ep, struct ci13xxx_ep, ep); struct ci13xxx_req *mReq = container_of(req, struct ci13xxx_req, req); unsigned long flags; trace("%p, %p", ep, req); if (ep == NULL || req == NULL) { err("EINVAL"); return; } else if (!list_empty(&mReq->queue)) { err("EBUSY"); return; } spin_lock_irqsave(mEp->lock, flags); if (mReq->ptr) dma_pool_free(mEp->td_pool, mReq->ptr, mReq->dma); kfree(mReq); dbg_event(_usb_addr(mEp), "FREE", 0); spin_unlock_irqrestore(mEp->lock, flags); } /** * ep_queue: queues (submits) an I/O request to an endpoint * * Check usb_ep_queue()* at usb_gadget.h" for details */ static int ep_queue(struct usb_ep *ep, struct usb_request *req, gfp_t __maybe_unused gfp_flags) { struct ci13xxx_ep *mEp = container_of(ep, struct ci13xxx_ep, ep); struct ci13xxx_req *mReq = container_of(req, struct ci13xxx_req, req); int retval = 0; unsigned long flags; struct ci13xxx *udc = _udc; trace("%p, %p, %X", ep, req, gfp_flags); spin_lock_irqsave(mEp->lock, flags); if (ep == NULL || req == NULL || mEp->desc == NULL) { retval = -EINVAL; goto done; } if (!udc->softconnect) { retval = -ENODEV; goto done; } if (!udc->configured && mEp->type != USB_ENDPOINT_XFER_CONTROL) { trace("usb is not configured" "ept #%d, ept name#%s\n", mEp->num, mEp->ep.name); retval = -ESHUTDOWN; goto done; } if (mEp->type == USB_ENDPOINT_XFER_CONTROL) { if (req->length) mEp = (_udc->ep0_dir == RX) ? &_udc->ep0out : &_udc->ep0in; if (!list_empty(&mEp->qh.queue)) { _ep_nuke(mEp); retval = -EOVERFLOW; warn("endpoint ctrl %X nuked", _usb_addr(mEp)); } } /* first nuke then test link, e.g. previous status has not sent */ if (!list_empty(&mReq->queue)) { retval = -EBUSY; err("request already in queue"); goto done; } if (mEp->multi_req) { retval = -EAGAIN; err("Large request is in progress. come again"); goto done; } if (req->length > (4 * CI13XXX_PAGE_SIZE)) { if (!list_empty(&mEp->qh.queue)) { retval = -EAGAIN; err("Queue is busy. Large req is not allowed"); goto done; } if ((mEp->type != USB_ENDPOINT_XFER_BULK) || (mEp->dir != RX)) { retval = -EINVAL; err("Larger req is supported only for Bulk OUT"); goto done; } mEp->multi_req = true; mReq->multi.len = req->length; mReq->multi.buf = req->buf; req->length = (4 * CI13XXX_PAGE_SIZE); } dbg_queue(_usb_addr(mEp), req, retval); /* push request */ mReq->req.status = -EINPROGRESS; mReq->req.actual = 0; retval = _hardware_enqueue(mEp, mReq); if (retval == -EALREADY) { dbg_event(_usb_addr(mEp), "QUEUE", retval); retval = 0; } if (!retval) list_add_tail(&mReq->queue, &mEp->qh.queue); else if (mEp->multi_req) mEp->multi_req = false; done: spin_unlock_irqrestore(mEp->lock, flags); return retval; } /** * ep_dequeue: dequeues (cancels, unlinks) an I/O request from an endpoint * * Check usb_ep_dequeue() at "usb_gadget.h" for details */ static int ep_dequeue(struct usb_ep *ep, struct usb_request *req) { struct ci13xxx_ep *mEp = container_of(ep, struct ci13xxx_ep, ep); struct ci13xxx_ep *mEpTemp = mEp; struct ci13xxx_req *mReq = container_of(req, struct ci13xxx_req, req); unsigned long flags; trace("%p, %p", ep, req); spin_lock_irqsave(mEp->lock, flags); /* * Only ep0 IN is exposed to composite. When a req is dequeued * on ep0, check both ep0 IN and ep0 OUT queues. */ if (ep == NULL || req == NULL || mReq->req.status != -EALREADY || mEp->desc == NULL || list_empty(&mReq->queue) || (list_empty(&mEp->qh.queue) && ((mEp->type != USB_ENDPOINT_XFER_CONTROL) || list_empty(&_udc->ep0out.qh.queue)))) { spin_unlock_irqrestore(mEp->lock, flags); return -EINVAL; } dbg_event(_usb_addr(mEp), "DEQUEUE", 0); if ((mEp->type == USB_ENDPOINT_XFER_CONTROL)) { hw_ep_flush(_udc->ep0out.num, RX); hw_ep_flush(_udc->ep0in.num, TX); } else { hw_ep_flush(mEp->num, mEp->dir); } /* pop request */ list_del_init(&mReq->queue); if (mReq->map) { dma_unmap_single(mEp->device, mReq->req.dma, mReq->req.length, mEp->dir ? DMA_TO_DEVICE : DMA_FROM_DEVICE); mReq->req.dma = DMA_ADDR_INVALID; mReq->map = 0; } req->status = -ECONNRESET; if (mEp->multi_req) { restore_original_req(mReq); mEp->multi_req = false; } if (mReq->req.complete != NULL) { spin_unlock(mEp->lock); if ((mEp->type == USB_ENDPOINT_XFER_CONTROL) && mReq->req.length) mEpTemp = &_udc->ep0in; mReq->req.complete(&mEpTemp->ep, &mReq->req); if (mEp->type == USB_ENDPOINT_XFER_CONTROL) mReq->req.complete = NULL; spin_lock(mEp->lock); } spin_unlock_irqrestore(mEp->lock, flags); return 0; } static int is_sps_req(struct ci13xxx_req *mReq) { return (CI13XX_REQ_VENDOR_ID(mReq->req.udc_priv) == MSM_VENDOR_ID && mReq->req.udc_priv & MSM_SPS_MODE); } /** * ep_set_halt: sets the endpoint halt feature * * Check usb_ep_set_halt() at "usb_gadget.h" for details */ static int ep_set_halt(struct usb_ep *ep, int value) { struct ci13xxx_ep *mEp = container_of(ep, struct ci13xxx_ep, ep); int direction, retval = 0; unsigned long flags; trace("%p, %i", ep, value); if (ep == NULL || mEp->desc == NULL) return -EINVAL; spin_lock_irqsave(mEp->lock, flags); #ifndef STALL_IN /* g_file_storage MS compliant but g_zero fails chapter 9 compliance */ if (value && mEp->type == USB_ENDPOINT_XFER_BULK && mEp->dir == TX && !list_empty(&mEp->qh.queue) && !is_sps_req(list_entry(mEp->qh.queue.next, struct ci13xxx_req, queue))){ spin_unlock_irqrestore(mEp->lock, flags); return -EAGAIN; } #endif direction = mEp->dir; do { dbg_event(_usb_addr(mEp), "HALT", value); retval |= hw_ep_set_halt(mEp->num, mEp->dir, value); if (!value) mEp->wedge = 0; if (mEp->type == USB_ENDPOINT_XFER_CONTROL) mEp->dir = (mEp->dir == TX) ? RX : TX; } while (mEp->dir != direction); spin_unlock_irqrestore(mEp->lock, flags); return retval; } /** * ep_set_wedge: sets the halt feature and ignores clear requests * * Check usb_ep_set_wedge() at "usb_gadget.h" for details */ static int ep_set_wedge(struct usb_ep *ep) { struct ci13xxx_ep *mEp = container_of(ep, struct ci13xxx_ep, ep); unsigned long flags; trace("%p", ep); if (ep == NULL || mEp->desc == NULL) return -EINVAL; spin_lock_irqsave(mEp->lock, flags); dbg_event(_usb_addr(mEp), "WEDGE", 0); mEp->wedge = 1; spin_unlock_irqrestore(mEp->lock, flags); return usb_ep_set_halt(ep); } /** * ep_fifo_flush: flushes contents of a fifo * * Check usb_ep_fifo_flush() at "usb_gadget.h" for details */ static void ep_fifo_flush(struct usb_ep *ep) { struct ci13xxx_ep *mEp = container_of(ep, struct ci13xxx_ep, ep); unsigned long flags; trace("%p", ep); if (ep == NULL) { err("%02X: -EINVAL", _usb_addr(mEp)); return; } spin_lock_irqsave(mEp->lock, flags); del_timer(&mEp->prime_timer); mEp->prime_timer_count = 0; dbg_event(_usb_addr(mEp), "FFLUSH", 0); /* * _ep_nuke() takes care of flushing the endpoint. * some function drivers expect udc to retire all * pending requests upon flushing an endpoint. There * is no harm in doing it. */ _ep_nuke(mEp); spin_unlock_irqrestore(mEp->lock, flags); } /** * Endpoint-specific part of the API to the USB controller hardware * Check "usb_gadget.h" for details */ static const struct usb_ep_ops usb_ep_ops = { .enable = ep_enable, .disable = ep_disable, .alloc_request = ep_alloc_request, .free_request = ep_free_request, .queue = ep_queue, .dequeue = ep_dequeue, .set_halt = ep_set_halt, .set_wedge = ep_set_wedge, .fifo_flush = ep_fifo_flush, }; /****************************************************************************** * GADGET block *****************************************************************************/ static int ci13xxx_vbus_session(struct usb_gadget *_gadget, int is_active) { struct ci13xxx *udc = container_of(_gadget, struct ci13xxx, gadget); unsigned long flags; int gadget_ready = 0; if (!(udc->udc_driver->flags & CI13XXX_PULLUP_ON_VBUS)) return -EOPNOTSUPP; spin_lock_irqsave(udc->lock, flags); udc->vbus_active = is_active; if (udc->driver) gadget_ready = 1; spin_unlock_irqrestore(udc->lock, flags); if (gadget_ready) { if (is_active) { pm_runtime_get_sync(&_gadget->dev); hw_device_reset(udc); if (udc->softconnect) hw_device_state(udc->ep0out.qh.dma); } else { hw_device_state(0); _gadget_stop_activity(&udc->gadget); if (udc->udc_driver->notify_event) udc->udc_driver->notify_event(udc, CI13XXX_CONTROLLER_DISCONNECT_EVENT); pm_runtime_put_sync(&_gadget->dev); } } return 0; } static int ci13xxx_vbus_draw(struct usb_gadget *_gadget, unsigned mA) { struct ci13xxx *udc = container_of(_gadget, struct ci13xxx, gadget); if (udc->transceiver) return usb_phy_set_power(udc->transceiver, mA); return -ENOTSUPP; } static int ci13xxx_pullup(struct usb_gadget *_gadget, int is_active) { struct ci13xxx *udc = container_of(_gadget, struct ci13xxx, gadget); unsigned long flags; spin_lock_irqsave(udc->lock, flags); udc->softconnect = is_active; if (((udc->udc_driver->flags & CI13XXX_PULLUP_ON_VBUS) && !udc->vbus_active) || !udc->driver) { spin_unlock_irqrestore(udc->lock, flags); return 0; } spin_unlock_irqrestore(udc->lock, flags); if (is_active) { hw_device_state(udc->ep0out.qh.dma); if (udc->udc_driver->notify_event) udc->udc_driver->notify_event(udc, CI13XXX_CONTROLLER_CONNECT_EVENT); } else hw_device_state(0); return 0; } static int ci13xxx_start(struct usb_gadget_driver *driver, int (*bind)(struct usb_gadget *)); static int ci13xxx_stop(struct usb_gadget_driver *driver); /** * Device operations part of the API to the USB controller hardware, * which don't involve endpoints (or i/o) * Check "usb_gadget.h" for details */ static const struct usb_gadget_ops usb_gadget_ops = { .vbus_session = ci13xxx_vbus_session, .wakeup = ci13xxx_wakeup, .vbus_draw = ci13xxx_vbus_draw, .pullup = ci13xxx_pullup, .start = ci13xxx_start, .stop = ci13xxx_stop, }; /** * ci13xxx_start: register a gadget driver * @driver: the driver being registered * @bind: the driver's bind callback * * Check ci13xxx_start() at <linux/usb/gadget.h> for details. * Interrupts are enabled here. */ static int ci13xxx_start(struct usb_gadget_driver *driver, int (*bind)(struct usb_gadget *)) { struct ci13xxx *udc = _udc; unsigned long flags; int i, j; int retval = -ENOMEM; bool put = false; trace("%p", driver); if (driver == NULL || bind == NULL || driver->setup == NULL || driver->disconnect == NULL) return -EINVAL; else if (udc == NULL) return -ENODEV; else if (udc->driver != NULL) return -EBUSY; /* alloc resources */ udc->qh_pool = dma_pool_create("ci13xxx_qh", &udc->gadget.dev, sizeof(struct ci13xxx_qh), 64, CI13XXX_PAGE_SIZE); if (udc->qh_pool == NULL) return -ENOMEM; udc->td_pool = dma_pool_create("ci13xxx_td", &udc->gadget.dev, sizeof(struct ci13xxx_td), 64, CI13XXX_PAGE_SIZE); if (udc->td_pool == NULL) { dma_pool_destroy(udc->qh_pool); udc->qh_pool = NULL; return -ENOMEM; } spin_lock_irqsave(udc->lock, flags); info("hw_ep_max = %d", hw_ep_max); udc->gadget.dev.driver = NULL; retval = 0; for (i = 0; i < hw_ep_max/2; i++) { for (j = RX; j <= TX; j++) { int k = i + j * hw_ep_max/2; struct ci13xxx_ep *mEp = &udc->ci13xxx_ep[k]; scnprintf(mEp->name, sizeof(mEp->name), "ep%i%s", i, (j == TX) ? "in" : "out"); mEp->lock = udc->lock; mEp->device = &udc->gadget.dev; mEp->td_pool = udc->td_pool; mEp->ep.name = mEp->name; mEp->ep.ops = &usb_ep_ops; mEp->ep.maxpacket = k ? (unsigned short)~0 : CTRL_PAYLOAD_MAX; INIT_LIST_HEAD(&mEp->qh.queue); spin_unlock_irqrestore(udc->lock, flags); mEp->qh.ptr = dma_pool_alloc(udc->qh_pool, GFP_KERNEL, &mEp->qh.dma); spin_lock_irqsave(udc->lock, flags); if (mEp->qh.ptr == NULL) retval = -ENOMEM; else memset(mEp->qh.ptr, 0, sizeof(*mEp->qh.ptr)); /* skip ep0 out and in endpoints */ if (i == 0) continue; list_add_tail(&mEp->ep.ep_list, &udc->gadget.ep_list); } } if (retval) goto done; spin_unlock_irqrestore(udc->lock, flags); udc->ep0out.ep.desc = &ctrl_endpt_out_desc; retval = usb_ep_enable(&udc->ep0out.ep); if (retval) return retval; udc->ep0in.ep.desc = &ctrl_endpt_in_desc; retval = usb_ep_enable(&udc->ep0in.ep); if (retval) return retval; udc->status = usb_ep_alloc_request(&udc->ep0in.ep, GFP_KERNEL); if (!udc->status) return -ENOMEM; udc->status_buf = kzalloc(2, GFP_KERNEL); /* for GET_STATUS */ if (!udc->status_buf) { usb_ep_free_request(&udc->ep0in.ep, udc->status); return -ENOMEM; } spin_lock_irqsave(udc->lock, flags); udc->gadget.ep0 = &udc->ep0in.ep; /* bind gadget */ driver->driver.bus = NULL; udc->gadget.dev.driver = &driver->driver; udc->softconnect = 1; spin_unlock_irqrestore(udc->lock, flags); pm_runtime_get_sync(&udc->gadget.dev); retval = bind(&udc->gadget); /* MAY SLEEP */ spin_lock_irqsave(udc->lock, flags); if (retval) { udc->gadget.dev.driver = NULL; goto done; } udc->driver = driver; if (udc->udc_driver->flags & CI13XXX_PULLUP_ON_VBUS) { if (udc->vbus_active) { if (udc->udc_driver->flags & CI13XXX_REGS_SHARED) hw_device_reset(udc); } else { put = true; goto done; } } if (!udc->softconnect) { put = true; goto done; } retval = hw_device_state(udc->ep0out.qh.dma); done: spin_unlock_irqrestore(udc->lock, flags); if (retval || put) pm_runtime_put_sync(&udc->gadget.dev); return retval; } /** * ci13xxx_stop: unregister a gadget driver * * Check usb_gadget_unregister_driver() at "usb_gadget.h" for details */ static int ci13xxx_stop(struct usb_gadget_driver *driver) { struct ci13xxx *udc = _udc; unsigned long i, flags; trace("%p", driver); if (driver == NULL || driver->unbind == NULL || driver->setup == NULL || driver->disconnect == NULL || driver != udc->driver) return -EINVAL; spin_lock_irqsave(udc->lock, flags); if (!(udc->udc_driver->flags & CI13XXX_PULLUP_ON_VBUS) || udc->vbus_active) { hw_device_state(0); spin_unlock_irqrestore(udc->lock, flags); _gadget_stop_activity(&udc->gadget); spin_lock_irqsave(udc->lock, flags); pm_runtime_put(&udc->gadget.dev); } /* unbind gadget */ spin_unlock_irqrestore(udc->lock, flags); driver->unbind(&udc->gadget); /* MAY SLEEP */ spin_lock_irqsave(udc->lock, flags); usb_ep_free_request(&udc->ep0in.ep, udc->status); kfree(udc->status_buf); udc->gadget.dev.driver = NULL; /* free resources */ for (i = 0; i < hw_ep_max; i++) { struct ci13xxx_ep *mEp = &udc->ci13xxx_ep[i]; if (!list_empty(&mEp->ep.ep_list)) list_del_init(&mEp->ep.ep_list); if (mEp->qh.ptr != NULL) dma_pool_free(udc->qh_pool, mEp->qh.ptr, mEp->qh.dma); } udc->gadget.ep0 = NULL; udc->driver = NULL; spin_unlock_irqrestore(udc->lock, flags); if (udc->td_pool != NULL) { dma_pool_destroy(udc->td_pool); udc->td_pool = NULL; } if (udc->qh_pool != NULL) { dma_pool_destroy(udc->qh_pool); udc->qh_pool = NULL; } return 0; } /****************************************************************************** * BUS block *****************************************************************************/ /** * udc_irq: global interrupt handler * * This function returns IRQ_HANDLED if the IRQ has been handled * It locks access to registers */ static irqreturn_t udc_irq(void) { struct ci13xxx *udc = _udc; irqreturn_t retval; u32 intr; trace(); if (udc == NULL) { err("ENODEV"); return IRQ_HANDLED; } spin_lock(udc->lock); if (udc->udc_driver->flags & CI13XXX_REGS_SHARED) { if (hw_cread(CAP_USBMODE, USBMODE_CM) != USBMODE_CM_DEVICE) { spin_unlock(udc->lock); return IRQ_NONE; } } intr = hw_test_and_clear_intr_active(); if (intr) { isr_statistics.hndl.buf[isr_statistics.hndl.idx++] = intr; isr_statistics.hndl.idx &= ISR_MASK; isr_statistics.hndl.cnt++; /* order defines priority - do NOT change it */ if (USBi_URI & intr) { isr_statistics.uri++; isr_reset_handler(udc); printk("[usb] BUS RESET.\n"); } if (USBi_PCI & intr) { isr_statistics.pci++; isr_resume_handler(udc); printk("[usb] BUS RESUME.\n"); } if (USBi_UEI & intr) isr_statistics.uei++; if (USBi_UI & intr) { isr_statistics.ui++; isr_tr_complete_handler(udc); } if (USBi_SLI & intr) { printk("[usb] BUS SUSPEND.\n"); isr_suspend_handler(udc); isr_statistics.sli++; } retval = IRQ_HANDLED; } else { isr_statistics.none++; retval = IRQ_NONE; } spin_unlock(udc->lock); return retval; } /** * udc_release: driver release function * @dev: device * * Currently does nothing */ static void udc_release(struct device *dev) { trace("%p", dev); if (dev == NULL) err("EINVAL"); } /** * udc_probe: parent probe must call this to initialize UDC * @dev: parent device * @regs: registers base address * @name: driver name * * This function returns an error code * No interrupts active, the IRQ has not been requested yet * Kernel assumes 32-bit DMA operations by default, no need to dma_set_mask */ static int udc_probe(struct ci13xxx_udc_driver *driver, struct device *dev, void __iomem *regs) { struct ci13xxx *udc; struct ci13xxx_platform_data *pdata; int retval = 0, i; trace("%p, %p, %p", dev, regs, driver->name); if (dev == NULL || regs == NULL || driver == NULL || driver->name == NULL) return -EINVAL; udc = kzalloc(sizeof(struct ci13xxx), GFP_KERNEL); if (udc == NULL) return -ENOMEM; udc->lock = &udc_lock; udc->regs = regs; udc->udc_driver = driver; udc->gadget.ops = &usb_gadget_ops; udc->gadget.speed = USB_SPEED_UNKNOWN; udc->gadget.max_speed = USB_SPEED_HIGH; if (udc->udc_driver->flags & CI13XXX_IS_OTG) udc->gadget.is_otg = 1; else udc->gadget.is_otg = 0; udc->gadget.name = driver->name; INIT_LIST_HEAD(&udc->gadget.ep_list); udc->gadget.ep0 = NULL; pdata = dev->platform_data; if (pdata) udc->gadget.usb_core_id = pdata->usb_core_id; dev_set_name(&udc->gadget.dev, "gadget"); udc->gadget.dev.dma_mask = dev->dma_mask; udc->gadget.dev.coherent_dma_mask = dev->coherent_dma_mask; udc->gadget.dev.parent = dev; udc->gadget.dev.release = udc_release; if (udc->udc_driver->flags & CI13XXX_REQUIRE_TRANSCEIVER) { udc->transceiver = usb_get_transceiver(); if (udc->transceiver == NULL) { retval = -ENODEV; goto free_udc; } } INIT_DELAYED_WORK(&udc->rw_work, usb_do_remote_wakeup); retval = hw_device_init(regs); if (retval < 0) goto put_transceiver; for (i = 0; i < hw_ep_max; i++) { struct ci13xxx_ep *mEp = &udc->ci13xxx_ep[i]; INIT_LIST_HEAD(&mEp->ep.ep_list); setup_timer(&mEp->prime_timer, ep_prime_timer_func, (unsigned long) mEp); } if (!(udc->udc_driver->flags & CI13XXX_REGS_SHARED)) { retval = hw_device_reset(udc); if (retval) goto put_transceiver; } retval = device_register(&udc->gadget.dev); if (retval) { put_device(&udc->gadget.dev); goto put_transceiver; } #ifdef CONFIG_USB_GADGET_DEBUG_FILES retval = dbg_create_files(&udc->gadget.dev); #endif if (retval) goto unreg_device; if (udc->transceiver) { retval = otg_set_peripheral(udc->transceiver->otg, &udc->gadget); if (retval) goto remove_dbg; } retval = usb_add_gadget_udc(dev, &udc->gadget); if (retval) goto remove_trans; pm_runtime_no_callbacks(&udc->gadget.dev); pm_runtime_enable(&udc->gadget.dev); #ifdef CONFIG_ENABLE_DEFAULT_TRACERS retval = register_trace_usb_daytona_invalid_access(dump_usb_info, NULL); if (retval) pr_err("Registering trace failed\n"); #endif _udc = udc; return retval; remove_trans: if (udc->transceiver) { otg_set_peripheral(udc->transceiver->otg, &udc->gadget); usb_put_transceiver(udc->transceiver); } err("error = %i", retval); remove_dbg: #ifdef CONFIG_USB_GADGET_DEBUG_FILES dbg_remove_files(&udc->gadget.dev); #endif unreg_device: device_unregister(&udc->gadget.dev); put_transceiver: if (udc->transceiver) usb_put_transceiver(udc->transceiver); free_udc: kfree(udc); _udc = NULL; return retval; } /** * udc_remove: parent remove must call this to remove UDC * * No interrupts active, the IRQ has been released */ static void udc_remove(void) { struct ci13xxx *udc = _udc; #ifdef CONFIG_ENABLE_DEFAULT_TRACERS int retval; #endif if (udc == NULL) { err("EINVAL"); return; } #ifdef CONFIG_ENABLE_DEFAULT_TRACERS retval = unregister_trace_usb_daytona_invalid_access(dump_usb_info, NULL); if (retval) pr_err("Unregistering trace failed\n"); #endif usb_del_gadget_udc(&udc->gadget); if (udc->transceiver) { otg_set_peripheral(udc->transceiver->otg, &udc->gadget); usb_put_transceiver(udc->transceiver); } #ifdef CONFIG_USB_GADGET_DEBUG_FILES dbg_remove_files(&udc->gadget.dev); #endif device_unregister(&udc->gadget.dev); kfree(udc); _udc = NULL; }
msva/android_kernel_asus_A80
drivers/usb/gadget/ci13xxx_udc.c
C
gpl-2.0
96,999
<?php $vortex_like_dislike = get_option("vortex_like_dislike"); function vortex_system_add_dislike_class_buddypress($id){ $vortex_like_dislike = get_option("vortex_like_dislike"); if(is_user_logged_in()){ $current_user_id = get_current_user_id(); $user_key = 'vortex_system_user_'.$current_user_id; }elseif(!is_user_logged_in() && $vortex_like_dislike['v-switch-anon']){ $user_ip = sanitize_text_field($_SERVER['REMOTE_ADDR']); $user_key = 'vortex_system_user_'.$user_ip; }; if(is_user_logged_in() || (!is_user_logged_in() && $vortex_like_dislike['v-switch-anon'])){ if(!get_post_meta($id,$user_key,true) == ''){ $current_user = get_post_meta($id,$user_key,true); $current_user_disliked = $current_user['disliked']; } if($current_user_disliked == 'nodisliked'){ return 'vortex-p-dislike-active'; }elseif(vortex_ra_read_cookie('dislikepost',$id) == 'found' && $current_user_disliked !== 'disliked'){ return 'vortex-p-dislike-active'; } } } function vortex_system_get_total_dislikes_buddypress($id){ $dislikes = get_post_meta($id,'vortex_system_dislikes',true); if(empty($dislikes)){ return 0; }elseif(!$dislikes == ''){ return $dislikes = get_post_meta($id,'vortex_system_dislikes',true); } } function vortex_system_dislike_counter_buddypress($id){ $vortex_like_dislike = get_option("vortex_like_dislike"); if ($vortex_like_dislike['v_custom_text_post_keep'] && vortex_system_add_dislike_class_buddypress($id) == 'vortex-p-dislike-active'){ if(!$vortex_like_dislike['v-switch-anon-counter'] || is_user_logged_in()){ return '<span class="vortex-p-dislike-counter '.$id. '">'.$vortex_like_dislike['v_custom_text_post_dislike'].'</span>'; } }elseif(!$vortex_like_dislike['v-switch-anon-counter'] || is_user_logged_in()){ return '<span class="vortex-p-dislike-counter '.$id. '">'. vortex_system_get_total_dislikes_buddypress($id).'</span>'; } } function vortex_system_render_dislike_button_buddypress($id){ /*dev use the same as below return '<div class="vortex-container-dislike"> <input type="hidden" value="'.get_the_ID().'" ></input> <div class="vortex-p-dislike '.get_the_ID().' '. vortex_system_add_dislike_class() .' '.vortex_system_get_dislike_icon().'"> '.vortex_system_dislike_counter().' </div> </div>'; */ return '<div class="vortex-container-dislike"><input type="hidden" value="'.$id.'" ></input><div class="vortex-p-dislike '.$id.' '. vortex_system_add_dislike_class_buddypress($id) .' '.vortex_system_get_dislike_icon().'">'.vortex_system_dislike_counter_buddypress($id).'</div></div>'; } function vortex_system_add_like_class_buddypress($id){ $vortex_like_dislike = get_option("vortex_like_dislike"); if(is_user_logged_in()){ $current_user_id = get_current_user_id(); $user_key = 'vortex_system_user_'.$current_user_id; }elseif(!is_user_logged_in() && $vortex_like_dislike['v-switch-anon']){ $user_ip = sanitize_text_field($_SERVER['REMOTE_ADDR']); $user_key = 'vortex_system_user_'.$user_ip; }; if(is_user_logged_in() || (!is_user_logged_in() && $vortex_like_dislike['v-switch-anon'])){ if(!get_post_meta($id,$user_key,true) == ''){ $current_user = get_post_meta($id,$user_key,true); $current_user_liked = $current_user['liked']; } if($current_user_liked == 'noliked'){ return 'vortex-p-like-active'; }elseif(vortex_ra_read_cookie('likepost',$id) == 'found' && $current_user_liked !== 'liked'){ return 'vortex-p-like-active'; } } } function vortex_system_get_total_likes_buddypress($id){ $likes = get_post_meta($id,'vortex_system_likes',true); if(empty($likes)){ return 0; }elseif(!$likes == ''){ return $dislikes = get_post_meta($id,'vortex_system_likes',true); } } function vortex_system_like_counter_buddypress($id){ $vortex_like_dislike = get_option("vortex_like_dislike"); if ($vortex_like_dislike['v_custom_text_post_keep'] && vortex_system_add_like_class_buddypress($id) == 'vortex-p-like-active'){ if(!$vortex_like_dislike['v-switch-anon-counter'] || is_user_logged_in()){ return '<span class="vortex-p-like-counter '. $id.'">'.$vortex_like_dislike['v_custom_text_post_like'].'</span>'; } }elseif(!$vortex_like_dislike['v-switch-anon-counter'] || is_user_logged_in()){ return '<span class="vortex-p-like-counter '. $id.'">'.vortex_system_get_total_likes_buddypress($id).'</span>'; } } function vortex_buddypress_render($id){ $vortex_like_dislike = get_option("vortex_like_dislike"); if(!$vortex_like_dislike['v-switch-dislike']){ /* this is for dev the same as below $buttons = ' <div class="vortex-container-vote '.vortex_button_align().'"> <div class="vortex-container-like"> <input type="hidden" value="'.get_the_ID().'" ></input> <div class="vortex-p-like '.get_the_ID().' '.vortex_system_add_like_class().' '.vortex_system_get_like_icon().'"> '.vortex_system_like_counter().' </div> </div> '.vortex_system_render_dislike_button().' </div> ';*/ //leave it inline, bbPress adds p tags for unkown reasons $buttons = '<div class="vortex-container-vote '.vortex_button_align().'"><div class="vortex-container-like"><input type="hidden" value="'.$id.'" ></input><div class="vortex-p-like '.$id.' '.vortex_system_add_like_class_buddypress($id).' '.vortex_system_get_like_icon().'">'.vortex_system_like_counter_buddypress($id).'</div></div>'.vortex_system_render_dislike_button_buddypress($id).'</div>'; return $buttons; }else { /* this is for dev the same as below $buttons = ' <div class="vortex-container-vote '.vortex_button_align().'"> <div class="vortex-container-like"> <input type="hidden" value="'.get_the_ID().'" ></input> <div class="vortex-p-like '.get_the_ID().' '.vortex_system_add_like_class().' '.vortex_system_get_like_icon().'"> '.vortex_system_like_counter().' </div> </div> </div> '; */ $buttons = '<div class="vortex-container-vote '.vortex_button_align().'"><div class="vortex-container-like"><input type="hidden" value="'.$id.'" ></input><div class="vortex-p-like '.$id.' '.vortex_system_add_like_class_buddypress($id).' '.vortex_system_get_like_icon().'">'.vortex_system_like_counter_buddypress($id).'</div></div></div>'; return $buttons; } } function vortex_buddypress_after($content){ return $content.vortex_buddypress_render(bp_get_activity_id()); } function vortex_buddypress_before($content){ return vortex_buddypress_render(bp_get_activity_id()).$content; } $vortex_like_dislike = get_option("vortex_like_dislike"); if($vortex_like_dislike['v_button_visibility'][1] && $vortex_like_dislike['v_button_visibility'][2] ){ add_filter('bp_get_activity_content_body','vortex_buddypress_after'); add_filter('bp_get_activity_content_body','vortex_buddypress_before'); }elseif($vortex_like_dislike['v_button_visibility'][1]){ add_filter('bp_get_activity_content_body','vortex_buddypress_before'); }elseif($vortex_like_dislike['v_button_visibility'][2]){ add_filter('bp_get_activity_content_body','vortex_buddypress_after'); }
jackhutson03/Exashare
wp-content/plugins/rating-system/buddypress.php
PHP
gpl-2.0
7,404
/* * java-gnome, a UI library for writing GTK and GNOME programs from Java! * * Copyright © 2006-2011 Operational Dynamics Consulting, Pty Ltd and Others * * The code in this file, and the program it is a part of, is made available * to you by its authors as open source software: you can redistribute it * and/or modify it under the terms of the GNU General Public License version * 2 ("GPL") as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GPL for more details. * * You should have received a copy of the GPL along with this program. If not, * see http://www.gnu.org/licenses/. The authors of this program may be * contacted through http://java-gnome.sourceforge.net/. * * Linking this library statically or dynamically with other modules is making * a combined work based on this library. Thus, the terms and conditions of * the GPL cover the whole combination. As a special exception (the * "Claspath Exception"), the copyright holders of this library give you * permission to link this library with independent modules to produce an * executable, regardless of the license terms of these independent modules, * and to copy and distribute the resulting executable under terms of your * choice, provided that you also meet, for each linked independent module, * the terms and conditions of the license of that module. An independent * module is a module which is not derived from or based on this library. If * you modify this library, you may extend the Classpath Exception to your * version of the library, but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. */ package org.gnome.atk; /* * THIS FILE IS GENERATED CODE! * * To modify its contents or behaviour, either update the generation program, * change the information in the source defs file, or implement an override for * this class. */ import org.gnome.atk.Plumbing; final class AtkLayer extends Plumbing { private AtkLayer() {} static final int INVALID = 0; static final int BACKGROUND = 1; static final int CANVAS = 2; static final int WIDGET = 3; static final int MDI = 4; static final int POPUP = 5; static final int OVERLAY = 6; }
cyberpython/java-gnome
generated/bindings/org/gnome/atk/AtkLayer.java
Java
gpl-2.0
2,440
<?php /** * @version 1.0.0 jp logs $ * @package jplogs * @copyright Copyright © 2010 - All rights reserved. * @license GNU/GPL * @author kim * @author mail administracion@joomlanetprojects.com * @website http://www.joomlanetprojects.com * */ // No direct access to this file defined('_JEXEC') or die('Restricted access'); // import the Joomla modellist library jimport('joomla.application.component.modellist'); class jplogsModelLogs extends JModelList { /** * Constructor. * * @param array An optional associative array of configuration settings. * @see JController * @since 1.6 */ public function __construct($config = array()) { if (empty($config['filter_fields'])) { $config['filter_fields'] = array( 'title', 'title', ); } parent::__construct($config); } /** * Method to get all the log files. * @return array * @since 1.6 */ public function getItems() { jimport('joomla.filesystem.file'); $main = 'error_log'; $folder = JPATH_ROOT.DS.'logs'; $items = JFolder::files($folder, $filter = '.', true, false , array('index.html')); if(file_exists(JPATH_ROOT.DS.$main)) { array_push($items, $main); } return $items; } /** * Method to get the file lenght. * @return file * @since 1.6 */ public function getLenght($file) { $file == 'error_log' ? $path = JPATH_ROOT.DS : $path = JPATH_ROOT.DS.'logs'.DS; return filesize($path.$file).' Kb'; } }
nishijieone/Webinar_joomla25
administrator/components/com_jplogs/models/logs.php
PHP
gpl-2.0
1,544
class AddRegisteredByToCredittypes < ActiveRecord::Migration def self.up if column_exists? :credittypes, :moduser_id rename_column :credittypes, :moduser_id, :registered_by_id else add_column :credittypes, :registered_by_id, :integer end add_column :credittypes, :modified_by_id, :integer end def self.down rename_column :credittypes, :registered_by_id, :moduser_id remove_column :credittypes, :modified_by_id end end
ifunam/salva
db/migrate/20101117233353_add_registered_by_to_credittypes.rb
Ruby
gpl-2.0
465
randomstuff =========== Just random stuff
SirNeon618/randomstuff
README.md
Markdown
gpl-2.0
43
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Scores</title> <style type="text/css"> html { font-family: Arial; } table { empty-cells: hide; border-collapse: collapse; background-color: white; border: 2px solid black; } th, td { padding: 3px 1.5ex; border: 1px solid black; border-top: 1px dotted black; border-bottom: 1px dotted black; } td.score { text-align: right; } th { background-color: rgb(208,208,191); border-bottom: 2px solid black; } tr.fini td { background-color: rgb(251,249,238); border-bottom: 2px solid black; } tr.fini td.date { background-color: white; } tr.suite td.date { border-top: hidden; } tr:hover, tr.fini:hover td { background-color: rgb(238,234,221); } </style> </head> <body> <h1>Tableau des scores</h1> <h2>Exercice Hotpotatoes : <em><?php echo $oSousActiv->oHotpotatoes->retTitre(); ?></em></h2> <h3>Etudiant : <em><?php echo $oEtudiant->retNomComplet(); ?></em></h3> <?php if (empty($oHotpotScores)) { echo "<p>Aucun score Hotpotatoes.</p>"; } else { ?> <table border="1"> <thead> <tr><th>Date de début de l'exercice</th><th>Durée</th><th>Score</th></tr> </thead> <tbody> <?php $derDate = 0; foreach ($oHotpotScores as $oScore) { $suite = ($oScore->retDateDebut()===$derDate ? true : false); echo '<tr>' .'<td class="date">'.( $suite ? '' : date('d/m/Y H:i',$oScore->retDateInitiale()) ).'</td>' .'<td>'.$oScore->retDuree().'</td>' .'<td class="score">'.$oScore->retScore().' %</td>' .'</tr>'; $derDate = $oScore->retDateDebut(); } ?> </tbody> <?php } ?> </table> </body> </html>
Ced-le-pingouin/esprit-mirror
src/sousactiv/hotpotatoes/scores.tpl.php
PHP
gpl-2.0
1,680
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.telegram.messenger.exoplayer2.source; import android.util.Pair; import org.telegram.messenger.exoplayer2.C; import org.telegram.messenger.exoplayer2.ExoPlayer; import org.telegram.messenger.exoplayer2.Timeline; import org.telegram.messenger.exoplayer2.upstream.Allocator; import org.telegram.messenger.exoplayer2.util.Assertions; import org.telegram.messenger.exoplayer2.util.Util; import java.io.IOException; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Map; /** * Concatenates multiple {@link MediaSource}s. It is valid for the same {@link MediaSource} instance * to be present more than once in the concatenation. */ public final class ConcatenatingMediaSource implements MediaSource { private final MediaSource[] mediaSources; private final Timeline[] timelines; private final Object[] manifests; private final Map<MediaPeriod, Integer> sourceIndexByMediaPeriod; private final boolean[] duplicateFlags; private Listener listener; private ConcatenatedTimeline timeline; /** * @param mediaSources The {@link MediaSource}s to concatenate. It is valid for the same * {@link MediaSource} instance to be present more than once in the array. */ public ConcatenatingMediaSource(MediaSource... mediaSources) { this.mediaSources = mediaSources; timelines = new Timeline[mediaSources.length]; manifests = new Object[mediaSources.length]; sourceIndexByMediaPeriod = new HashMap<>(); duplicateFlags = buildDuplicateFlags(mediaSources); } @Override public void prepareSource(ExoPlayer player, boolean isTopLevelSource, Listener listener) { this.listener = listener; for (int i = 0; i < mediaSources.length; i++) { if (!duplicateFlags[i]) { final int index = i; mediaSources[i].prepareSource(player, false, new Listener() { @Override public void onSourceInfoRefreshed(Timeline timeline, Object manifest) { handleSourceInfoRefreshed(index, timeline, manifest); } }); } } } @Override public void maybeThrowSourceInfoRefreshError() throws IOException { for (int i = 0; i < mediaSources.length; i++) { if (!duplicateFlags[i]) { mediaSources[i].maybeThrowSourceInfoRefreshError(); } } } @Override public MediaPeriod createPeriod(int index, Allocator allocator, long positionUs) { int sourceIndex = timeline.getSourceIndexForPeriod(index); int periodIndexInSource = index - timeline.getFirstPeriodIndexInSource(sourceIndex); MediaPeriod mediaPeriod = mediaSources[sourceIndex].createPeriod(periodIndexInSource, allocator, positionUs); sourceIndexByMediaPeriod.put(mediaPeriod, sourceIndex); return mediaPeriod; } @Override public void releasePeriod(MediaPeriod mediaPeriod) { int sourceIndex = sourceIndexByMediaPeriod.get(mediaPeriod); sourceIndexByMediaPeriod.remove(mediaPeriod); mediaSources[sourceIndex].releasePeriod(mediaPeriod); } @Override public void releaseSource() { for (int i = 0; i < mediaSources.length; i++) { if (!duplicateFlags[i]) { mediaSources[i].releaseSource(); } } } private void handleSourceInfoRefreshed(int sourceFirstIndex, Timeline sourceTimeline, Object sourceManifest) { // Set the timeline and manifest. timelines[sourceFirstIndex] = sourceTimeline; manifests[sourceFirstIndex] = sourceManifest; // Also set the timeline and manifest for any duplicate entries of the same source. for (int i = sourceFirstIndex + 1; i < mediaSources.length; i++) { if (mediaSources[i] == mediaSources[sourceFirstIndex]) { timelines[i] = sourceTimeline; manifests[i] = sourceManifest; } } for (Timeline timeline : timelines) { if (timeline == null) { // Don't invoke the listener until all sources have timelines. return; } } timeline = new ConcatenatedTimeline(timelines.clone()); listener.onSourceInfoRefreshed(timeline, manifests.clone()); } private static boolean[] buildDuplicateFlags(MediaSource[] mediaSources) { boolean[] duplicateFlags = new boolean[mediaSources.length]; IdentityHashMap<MediaSource, Void> sources = new IdentityHashMap<>(mediaSources.length); for (int i = 0; i < mediaSources.length; i++) { MediaSource source = mediaSources[i]; if (!sources.containsKey(source)) { sources.put(source, null); } else { duplicateFlags[i] = true; } } return duplicateFlags; } /** * A {@link Timeline} that is the concatenation of one or more {@link Timeline}s. */ private static final class ConcatenatedTimeline extends Timeline { private final Timeline[] timelines; private final int[] sourcePeriodOffsets; private final int[] sourceWindowOffsets; public ConcatenatedTimeline(Timeline[] timelines) { int[] sourcePeriodOffsets = new int[timelines.length]; int[] sourceWindowOffsets = new int[timelines.length]; long periodCount = 0; int windowCount = 0; for (int i = 0; i < timelines.length; i++) { Timeline timeline = timelines[i]; periodCount += timeline.getPeriodCount(); Assertions.checkState(periodCount <= Integer.MAX_VALUE, "ConcatenatingMediaSource children contain too many periods"); sourcePeriodOffsets[i] = (int) periodCount; windowCount += timeline.getWindowCount(); sourceWindowOffsets[i] = windowCount; } this.timelines = timelines; this.sourcePeriodOffsets = sourcePeriodOffsets; this.sourceWindowOffsets = sourceWindowOffsets; } @Override public int getWindowCount() { return sourceWindowOffsets[sourceWindowOffsets.length - 1]; } @Override public Window getWindow(int windowIndex, Window window, boolean setIds, long defaultPositionProjectionUs) { int sourceIndex = getSourceIndexForWindow(windowIndex); int firstWindowIndexInSource = getFirstWindowIndexInSource(sourceIndex); int firstPeriodIndexInSource = getFirstPeriodIndexInSource(sourceIndex); timelines[sourceIndex].getWindow(windowIndex - firstWindowIndexInSource, window, setIds, defaultPositionProjectionUs); window.firstPeriodIndex += firstPeriodIndexInSource; window.lastPeriodIndex += firstPeriodIndexInSource; return window; } @Override public int getPeriodCount() { return sourcePeriodOffsets[sourcePeriodOffsets.length - 1]; } @Override public Period getPeriod(int periodIndex, Period period, boolean setIds) { int sourceIndex = getSourceIndexForPeriod(periodIndex); int firstWindowIndexInSource = getFirstWindowIndexInSource(sourceIndex); int firstPeriodIndexInSource = getFirstPeriodIndexInSource(sourceIndex); timelines[sourceIndex].getPeriod(periodIndex - firstPeriodIndexInSource, period, setIds); period.windowIndex += firstWindowIndexInSource; if (setIds) { period.uid = Pair.create(sourceIndex, period.uid); } return period; } @Override public int getIndexOfPeriod(Object uid) { if (!(uid instanceof Pair)) { return C.INDEX_UNSET; } Pair<?, ?> sourceIndexAndPeriodId = (Pair<?, ?>) uid; if (!(sourceIndexAndPeriodId.first instanceof Integer)) { return C.INDEX_UNSET; } int sourceIndex = (Integer) sourceIndexAndPeriodId.first; Object periodId = sourceIndexAndPeriodId.second; if (sourceIndex < 0 || sourceIndex >= timelines.length) { return C.INDEX_UNSET; } int periodIndexInSource = timelines[sourceIndex].getIndexOfPeriod(periodId); return periodIndexInSource == C.INDEX_UNSET ? C.INDEX_UNSET : getFirstPeriodIndexInSource(sourceIndex) + periodIndexInSource; } private int getSourceIndexForPeriod(int periodIndex) { return Util.binarySearchFloor(sourcePeriodOffsets, periodIndex, true, false) + 1; } private int getFirstPeriodIndexInSource(int sourceIndex) { return sourceIndex == 0 ? 0 : sourcePeriodOffsets[sourceIndex - 1]; } private int getSourceIndexForWindow(int windowIndex) { return Util.binarySearchFloor(sourceWindowOffsets, windowIndex, true, false) + 1; } private int getFirstWindowIndexInSource(int sourceIndex) { return sourceIndex == 0 ? 0 : sourceWindowOffsets[sourceIndex - 1]; } } }
JungleTian/Telegram
TMessagesProj/src/main/java/org/telegram/messenger/exoplayer2/source/ConcatenatingMediaSource.java
Java
gpl-2.0
9,121
<?php /** * * Adapted from Edward McIntyre's wp_bootstrap_navwalker class. * Removed support for glyphicon and added support for Font Awesome * */ /** * Class Name: wp_bootstrap_navwalker * GitHub URI: https://github.com/twittem/wp-bootstrap-navwalker * Description: A custom WordPress nav walker class to implement the Bootstrap 3 navigation style in a custom theme using the WordPress built in menu manager. * Version: 2.0.4 * Author: Edward McIntyre - @twittem * License: GPL-2.0+ * License URI: http://www.gnu.org/licenses/gpl-2.0.txt */ //exit if accessed directly if(!defined('ABSPATH')) exit; class cronista_navwalker extends Walker_Nav_Menu { /** * @see Walker::start_lvl() * @since 3.0.0 * * @param string $output Passed by reference. Used to append additional content. * @param int $depth Depth of page. Used for padding. */ public function start_lvl( &$output, $depth = 0, $args = array() ) { $indent = str_repeat( "\t", $depth ); $output .= "\n$indent<ul role=\"menu\" class=\" dropdown-menu\">\n"; } /** * @see Walker::start_el() * @since 3.0.0 * * @param string $output Passed by reference. Used to append additional content. * @param object $item Menu item data object. * @param int $depth Depth of menu item. Used for padding. * @param int $current_page Menu item ID. * @param object $args */ public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) { $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; /** * Dividers, Headers or Disabled * ============================= * Determine whether the item is a Divider, Header, Disabled or regular * menu item. To prevent errors we use the strcasecmp() function to so a * comparison that is not case sensitive. The strcasecmp() function returns * a 0 if the strings are equal. */ if ( strcasecmp( $item->attr_title, 'divider' ) == 0 && $depth === 1 ) { $output .= $indent . '<li role="presentation" class="divider">'; } else if ( strcasecmp( $item->title, 'divider') == 0 && $depth === 1 ) { $output .= $indent . '<li role="presentation" class="divider">'; } else if ( strcasecmp( $item->attr_title, 'dropdown-header') == 0 && $depth === 1 ) { $output .= $indent . '<li role="presentation" class="dropdown-header">' . esc_attr( $item->title ); } else if ( strcasecmp($item->attr_title, 'disabled' ) == 0 ) { $output .= $indent . '<li role="presentation" class="disabled"><a href="#">' . esc_attr( $item->title ) . '</a>'; } else { $class_names = $value = ''; $classes = empty( $item->classes ) ? array() : (array) $item->classes; $classes[] = 'menu-item-' . $item->ID; $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) ); /* if ( $args->has_children ) $class_names .= ' dropdown'; */ if($args->has_children && $depth === 0) { $class_names .= ' dropdown'; } elseif($args->has_children && $depth > 0) { $class_names .= ' dropdown-submenu'; } if ( in_array( 'current-menu-item', $classes ) ) $class_names .= ' active'; // remove Font Awesome icon from classes array and save the icon // we will add the icon back in via a <span> below so it aligns with // the menu item if ( in_array('fa', $classes)) { $key = array_search('fa', $classes); $icon = $classes[$key + 1]; $class_names = str_replace($classes[$key+1], '', $class_names); $class_names = str_replace($classes[$key], '', $class_names); } $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : ''; $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args ); $id = $id ? ' id="' . esc_attr( $id ) . '"' : ''; $output .= $indent . '<li' . $id . $value . $class_names .'>'; $atts = array(); $atts['title'] = ! empty( $item->title ) ? $item->title : ''; $atts['target'] = ! empty( $item->target ) ? $item->target : ''; $atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : ''; // If item has_children add atts to a. // if ( $args->has_children && $depth === 0 ) { if ( $args->has_children ) { $atts['href'] = '#'; $atts['data-toggle'] = 'dropdown'; $atts['class'] = 'dropdown-toggle'; } else { $atts['href'] = ! empty( $item->url ) ? $item->url : ''; } $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args ); $attributes = ''; foreach ( $atts as $attr => $value ) { if ( ! empty( $value ) ) { $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value ); $attributes .= ' ' . $attr . '="' . $value . '"'; } } $item_output = $args->before; // Font Awesome icons if ( ! empty( $icon ) ) $item_output .= '<a'. $attributes .'><span class="fa ' . esc_attr( $icon ) . '"></span>&nbsp;'; else $item_output .= '<a'. $attributes .'>'; $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after; $item_output .= ( $args->has_children && 0 === $depth ) ? ' <span class="caret"></span></a>' : '</a>'; $item_output .= $args->after; $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } } /** * Traverse elements to create list from elements. * * Display one element if the element doesn't have any children otherwise, * display the element and its children. Will only traverse up to the max * depth and no ignore elements under that depth. * * This method shouldn't be called directly, use the walk() method instead. * * @see Walker::start_el() * @since 2.5.0 * * @param object $element Data object * @param array $children_elements List of elements to continue traversing. * @param int $max_depth Max depth to traverse. * @param int $depth Depth of current element. * @param array $args * @param string $output Passed by reference. Used to append additional content. * @return null Null on failure with no changes to parameters. */ public function display_element( $element, &$children_elements, $max_depth, $depth, $args, &$output ) { if ( ! $element ) return; $id_field = $this->db_fields['id']; // Display this element. if ( is_object( $args[0] ) ) $args[0]->has_children = ! empty( $children_elements[ $element->$id_field ] ); parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output ); } /** * Menu Fallback * ============= * If this function is assigned to the wp_nav_menu's fallback_cb variable * and a manu has not been assigned to the theme location in the WordPress * menu manager the function with display nothing to a non-logged in user, * and will add a link to the WordPress menu manager if logged in as an admin. * * @param array $args passed from the wp_nav_menu function. * */ public static function fallback( $args ) { if ( current_user_can( 'manage_options' ) ) { extract( $args ); $fb_output = null; if ( $container ) { $fb_output = '<' . $container; if ( $container_id ) $fb_output .= ' id="' . $container_id . '"'; if ( $container_class ) $fb_output .= ' class="' . $container_class . '"'; $fb_output .= '>'; } $fb_output .= '<ul'; if ( $menu_id ) $fb_output .= ' id="' . $menu_id . '"'; if ( $menu_class ) $fb_output .= ' class="' . $menu_class . '"'; $fb_output .= '>'; $fb_output .= '<li><a href="' . esc_url(admin_url( 'nav-menus.php' )) . '">'.__('Asigna un menu','cronista').'</a></li>'; $fb_output .= '</ul>'; if ( $container ) $fb_output .= '</' . $container . '>'; echo $fb_output; } } }
ttthanhDC/ProjectTeamWP
wp-content/themes/cronista/assets/functions/cronista_navwalker.php
PHP
gpl-2.0
7,699
<?php namespace TYPO3\Fluid\Tests\Unit\ViewHelpers; /* * * This script belongs to the TYPO3 Flow package "TYPO3.Fluid". * * * * It is free software; you can redistribute it and/or modify it under * * the terms of the GNU Lesser General Public License, either version 3 * * of the License, or (at your option) any later version. * * * * The TYPO3 project - inspiring people to share! * * */ require_once(__DIR__ . '/ViewHelperBaseTestcase.php'); /** * Test for the Form view helper */ class FormViewHelperTest extends \TYPO3\Fluid\ViewHelpers\ViewHelperBaseTestcase { /** * @var \TYPO3\Flow\Security\Cryptography\HashService */ protected $hashService; /** * @var \TYPO3\Flow\Security\Context */ protected $securityContext; /** * Set up test dependencies */ public function setUp() { parent::setUp(); $this->arguments['action'] = ''; $this->arguments['arguments'] = array(); $this->arguments['controller'] = ''; $this->arguments['package'] = ''; $this->arguments['subpackage'] = ''; $this->arguments['method'] = ''; $this->arguments['object'] = NULL; $this->arguments['section'] = ''; $this->arguments['absolute'] = FALSE; $this->arguments['addQueryString'] = FALSE; $this->arguments['format'] = ''; $this->arguments['additionalParams'] = array(); $this->arguments['argumentsToBeExcludedFromQueryString'] = array(); $this->arguments['useParentRequest'] = FALSE; } /** * @param \TYPO3\Fluid\Core\ViewHelper\AbstractViewHelper $viewHelper */ protected function injectDependenciesIntoViewHelper(\TYPO3\Fluid\Core\ViewHelper\AbstractViewHelper $viewHelper) { $this->hashService = $this->getMock('TYPO3\Flow\Security\Cryptography\HashService'); $this->inject($viewHelper, 'hashService', $this->hashService); $this->mvcPropertyMappingConfigurationService = $this->getMock('TYPO3\Flow\Mvc\Controller\MvcPropertyMappingConfigurationService'); $this->inject($viewHelper, 'mvcPropertyMappingConfigurationService', $this->mvcPropertyMappingConfigurationService); $this->securityContext = $this->getMock('TYPO3\Flow\Security\Context'); $this->inject($viewHelper, 'securityContext', $this->securityContext); parent::injectDependenciesIntoViewHelper($viewHelper); } /** * @test */ public function renderAddsObjectToViewHelperVariableContainer() { $formObject = new \stdClass(); $viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren', 'renderHiddenIdentityField', 'renderAdditionalIdentityFields', 'renderHiddenReferrerFields', 'addFormObjectNameToViewHelperVariableContainer', 'addFieldNamePrefixToViewHelperVariableContainer', 'removeFormObjectNameFromViewHelperVariableContainer', 'removeFieldNamePrefixFromViewHelperVariableContainer', 'addFormFieldNamesToViewHelperVariableContainer', 'removeFormFieldNamesFromViewHelperVariableContainer', 'renderEmptyHiddenFields', 'renderTrustedPropertiesField'), array(), '', FALSE); $this->arguments['object'] = $formObject; $this->injectDependenciesIntoViewHelper($viewHelper); $this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE)); $this->viewHelperVariableContainer->expects($this->at(0))->method('add')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'formObject', $formObject); $this->viewHelperVariableContainer->expects($this->at(1))->method('add')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'additionalIdentityProperties', array()); $this->viewHelperVariableContainer->expects($this->at(2))->method('add')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'emptyHiddenFieldNames', array()); $this->viewHelperVariableContainer->expects($this->at(3))->method('remove')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'formObject'); $this->viewHelperVariableContainer->expects($this->at(4))->method('remove')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'additionalIdentityProperties'); $this->viewHelperVariableContainer->expects($this->at(5))->method('remove')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'emptyHiddenFieldNames'); $viewHelper->render('index'); } /** * @test */ public function renderAddsObjectNameToTemplateVariableContainer() { $objectName = 'someObjectName'; $viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren', 'renderHiddenIdentityField', 'renderHiddenReferrerFields', 'addFormObjectToViewHelperVariableContainer', 'addFieldNamePrefixToViewHelperVariableContainer', 'removeFormObjectFromViewHelperVariableContainer', 'removeFieldNamePrefixFromViewHelperVariableContainer', 'addFormFieldNamesToViewHelperVariableContainer', 'removeFormFieldNamesFromViewHelperVariableContainer', 'addEmptyHiddenFieldNamesToViewHelperVariableContainer', 'removeEmptyHiddenFieldNamesFromViewHelperVariableContainer', 'renderEmptyHiddenFields', 'renderTrustedPropertiesField'), array(), '', FALSE); $this->arguments['name'] = $objectName; $this->injectDependenciesIntoViewHelper($viewHelper); $this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE)); $this->viewHelperVariableContainer->expects($this->once())->method('add')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'formObjectName', $objectName); $this->viewHelperVariableContainer->expects($this->once())->method('remove')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'formObjectName'); $viewHelper->render('index'); } /** * @test */ public function formObjectNameArgumentOverrulesNameArgument() { $objectName = 'someObjectName'; $viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren', 'renderHiddenIdentityField', 'renderHiddenReferrerFields', 'addFormObjectToViewHelperVariableContainer', 'addFieldNamePrefixToViewHelperVariableContainer', 'removeFormObjectFromViewHelperVariableContainer', 'removeFieldNamePrefixFromViewHelperVariableContainer', 'addFormFieldNamesToViewHelperVariableContainer', 'removeFormFieldNamesFromViewHelperVariableContainer', 'addEmptyHiddenFieldNamesToViewHelperVariableContainer', 'removeEmptyHiddenFieldNamesFromViewHelperVariableContainer', 'renderEmptyHiddenFields', 'renderTrustedPropertiesField'), array(), '', FALSE); $this->arguments['name'] = 'formName'; $this->arguments['objectName'] = $objectName; $this->injectDependenciesIntoViewHelper($viewHelper); $this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE)); $this->viewHelperVariableContainer->expects($this->once())->method('add')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'formObjectName', $objectName); $this->viewHelperVariableContainer->expects($this->once())->method('remove')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'formObjectName'); $viewHelper->render('index'); } /** * @test */ public function renderCallsRenderHiddenReferrerFields() { $viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren', 'renderHiddenReferrerFields', 'renderEmptyHiddenFields', 'renderTrustedPropertiesField'), array(), '', FALSE); $viewHelper->expects($this->once())->method('renderHiddenReferrerFields'); $this->injectDependenciesIntoViewHelper($viewHelper); $this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE)); $viewHelper->render('index'); } /** * @test */ public function renderCallsRenderHiddenIdentityField() { $object = new \stdClass(); $viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren', 'renderHiddenIdentityField', 'getFormObjectName'), array(), '', FALSE); $this->arguments['object'] = $object; $this->injectDependenciesIntoViewHelper($viewHelper); $this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE)); $viewHelper->expects($this->atLeastOnce())->method('getFormObjectName')->will($this->returnValue('MyName')); $viewHelper->expects($this->once())->method('renderHiddenIdentityField')->with($object, 'MyName'); $viewHelper->render('index'); } /** * @test */ public function renderWithMethodGetAddsActionUriQueryAsHiddenFields() { $viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren'), array(), '', FALSE); $this->arguments['method'] = 'GET'; $this->arguments['actionUri'] = 'http://localhost/fluid/test?foo=bar%20baz'; $this->injectDependenciesIntoViewHelper($viewHelper); $this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE)); $viewHelper->expects($this->any())->method('renderChildren')->will($this->returnValue('formContent')); $expectedResult = chr(10) . '<div style="display: none">' . chr(10) . '<input type="hidden" name="foo" value="bar baz" />' . chr(10) . '<input type="hidden" name="__referrer[@package]" value="" />' . chr(10) . '<input type="hidden" name="__referrer[@subpackage]" value="" />' . chr(10) . '<input type="hidden" name="__referrer[@controller]" value="" />' . chr(10) . '<input type="hidden" name="__referrer[@action]" value="" />' . chr(10) . '<input type="hidden" name="__referrer[arguments]" value="" />' . chr(10) . '<input type="hidden" name="__trustedProperties" value="" />' . chr(10) . chr(10) . '</div>' . chr(10) . 'formContent'; $this->tagBuilder->expects($this->once())->method('setContent')->with($expectedResult); $viewHelper->render('index'); } /** * @test */ public function renderWithMethodGetDoesNotBreakInRenderHiddenActionUriQueryParametersIfNoQueryStringExists() { $viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren'), array(), '', FALSE); $this->arguments['method'] = 'GET'; $this->arguments['actionUri'] = 'http://localhost/fluid/test'; $this->injectDependenciesIntoViewHelper($viewHelper); $this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE)); $viewHelper->expects($this->any())->method('renderChildren')->will($this->returnValue('formContent')); $expectedResult = chr(10) . '<div style="display: none">' . chr(10) . '<input type="hidden" name="__referrer[@package]" value="" />' . chr(10) . '<input type="hidden" name="__referrer[@subpackage]" value="" />' . chr(10) . '<input type="hidden" name="__referrer[@controller]" value="" />' . chr(10) . '<input type="hidden" name="__referrer[@action]" value="" />' . chr(10) . '<input type="hidden" name="__referrer[arguments]" value="" />' . chr(10) . '<input type="hidden" name="__trustedProperties" value="" />' . chr(10) . chr(10) . '</div>' . chr(10) . 'formContent'; $this->tagBuilder->expects($this->once())->method('setContent')->with($expectedResult); $viewHelper->render('index'); } /** * @test */ public function renderCallsRenderAdditionalIdentityFields() { $viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren', 'renderAdditionalIdentityFields'), array(), '', FALSE); $viewHelper->expects($this->once())->method('renderAdditionalIdentityFields'); $this->injectDependenciesIntoViewHelper($viewHelper); $this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE)); $viewHelper->render('index'); } /** * @test */ public function renderWrapsHiddenFieldsWithDivForXhtmlCompatibility() { $viewHelper = $this->getMock($this->buildAccessibleProxy('TYPO3\Fluid\ViewHelpers\FormViewHelper'), array('renderChildren', 'renderHiddenIdentityField', 'renderAdditionalIdentityFields', 'renderHiddenReferrerFields', 'renderEmptyHiddenFields', 'renderTrustedPropertiesField'), array(), '', FALSE); $this->injectDependenciesIntoViewHelper($viewHelper); $this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE)); $viewHelper->expects($this->once())->method('renderHiddenIdentityField')->will($this->returnValue('hiddenIdentityField')); $viewHelper->expects($this->once())->method('renderAdditionalIdentityFields')->will($this->returnValue('additionalIdentityFields')); $viewHelper->expects($this->once())->method('renderHiddenReferrerFields')->will($this->returnValue('hiddenReferrerFields')); $viewHelper->expects($this->once())->method('renderChildren')->will($this->returnValue('formContent')); $viewHelper->expects($this->once())->method('renderEmptyHiddenFields')->will($this->returnValue('emptyHiddenFields')); $viewHelper->expects($this->once())->method('renderTrustedPropertiesField')->will($this->returnValue('trustedPropertiesField')); $expectedResult = chr(10) . '<div style="display: none">hiddenIdentityFieldadditionalIdentityFieldshiddenReferrerFieldsemptyHiddenFieldstrustedPropertiesField' . chr(10) . '</div>' . chr(10) . 'formContent'; $this->tagBuilder->expects($this->once())->method('setContent')->with($expectedResult); $viewHelper->render('index'); } /** * @test */ public function renderAdditionalIdentityFieldsFetchesTheFieldsFromViewHelperVariableContainerAndBuildsHiddenFieldsForThem() { $identityProperties = array( 'object1[object2]' => '<input type="hidden" name="object1[object2][__identity]" value="42" />', 'object1[object2][subobject]' => '<input type="hidden" name="object1[object2][subobject][__identity]" value="21" />' ); $this->viewHelperVariableContainer->expects($this->once())->method('exists')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'additionalIdentityProperties')->will($this->returnValue(TRUE)); $this->viewHelperVariableContainer->expects($this->once())->method('get')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'additionalIdentityProperties')->will($this->returnValue($identityProperties)); $viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren'), array(), '', FALSE); $this->injectDependenciesIntoViewHelper($viewHelper); $expected = chr(10) . '<input type="hidden" name="object1[object2][__identity]" value="42" />' . chr(10) . '<input type="hidden" name="object1[object2][subobject][__identity]" value="21" />'; $actual = $viewHelper->_call('renderAdditionalIdentityFields'); $this->assertEquals($expected, $actual); } /** * @test */ public function renderHiddenReferrerFieldsAddCurrentControllerAndActionAsHiddenFields() { $viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('dummy'), array(), '', FALSE); $this->injectDependenciesIntoViewHelper($viewHelper); $this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE)); $this->request->expects($this->atLeastOnce())->method('getControllerPackageKey')->will($this->returnValue('packageKey')); $this->request->expects($this->atLeastOnce())->method('getControllerSubpackageKey')->will($this->returnValue('subpackageKey')); $this->request->expects($this->atLeastOnce())->method('getControllerName')->will($this->returnValue('controllerName')); $this->request->expects($this->atLeastOnce())->method('getControllerActionName')->will($this->returnValue('controllerActionName')); $hiddenFields = $viewHelper->_call('renderHiddenReferrerFields'); $expectedResult = chr(10) . '<input type="hidden" name="__referrer[@package]" value="packageKey" />' . chr(10) . '<input type="hidden" name="__referrer[@subpackage]" value="subpackageKey" />' . chr(10) . '<input type="hidden" name="__referrer[@controller]" value="controllerName" />' . chr(10) . '<input type="hidden" name="__referrer[@action]" value="controllerActionName" />' . chr(10) . '<input type="hidden" name="__referrer[arguments]" value="" />' . chr(10); $this->assertEquals($expectedResult, $hiddenFields); } /** * @test */ public function renderHiddenReferrerFieldsAddCurrentControllerAndActionOfParentAndSubRequestAsHiddenFields() { $viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('dummy'), array(), '', FALSE); $this->injectDependenciesIntoViewHelper($viewHelper); $this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE)); $mockSubRequest = $this->getMock('TYPO3\Flow\Mvc\ActionRequest', array(), array(), 'Foo', FALSE); $mockSubRequest->expects($this->atLeastOnce())->method('isMainRequest')->will($this->returnValue(FALSE)); $mockSubRequest->expects($this->atLeastOnce())->method('getControllerPackageKey')->will($this->returnValue('subRequestPackageKey')); $mockSubRequest->expects($this->atLeastOnce())->method('getControllerSubpackageKey')->will($this->returnValue('subRequestSubpackageKey')); $mockSubRequest->expects($this->atLeastOnce())->method('getControllerName')->will($this->returnValue('subRequestControllerName')); $mockSubRequest->expects($this->atLeastOnce())->method('getControllerActionName')->will($this->returnValue('subRequestControllerActionName')); $mockSubRequest->expects($this->atLeastOnce())->method('getParentRequest')->will($this->returnValue($this->request)); $mockSubRequest->expects($this->atLeastOnce())->method('getArgumentNamespace')->will($this->returnValue('subRequestArgumentNamespace')); $this->request->expects($this->atLeastOnce())->method('getControllerPackageKey')->will($this->returnValue('packageKey')); $this->request->expects($this->atLeastOnce())->method('getControllerSubpackageKey')->will($this->returnValue('subpackageKey')); $this->request->expects($this->atLeastOnce())->method('getControllerName')->will($this->returnValue('controllerName')); $this->request->expects($this->atLeastOnce())->method('getControllerActionName')->will($this->returnValue('controllerActionName')); $this->controllerContext = $this->getMock('TYPO3\Flow\Mvc\Controller\ControllerContext', array(), array(), '', FALSE); $this->controllerContext->expects($this->atLeastOnce())->method('getRequest')->will($this->returnValue($mockSubRequest)); $this->renderingContext->setControllerContext($this->controllerContext); $this->injectDependenciesIntoViewHelper($viewHelper); $hiddenFields = $viewHelper->_call('renderHiddenReferrerFields'); $expectedResult = chr(10) . '<input type="hidden" name="subRequestArgumentNamespace[__referrer][@package]" value="subRequestPackageKey" />' . chr(10) . '<input type="hidden" name="subRequestArgumentNamespace[__referrer][@subpackage]" value="subRequestSubpackageKey" />' . chr(10) . '<input type="hidden" name="subRequestArgumentNamespace[__referrer][@controller]" value="subRequestControllerName" />' . chr(10) . '<input type="hidden" name="subRequestArgumentNamespace[__referrer][@action]" value="subRequestControllerActionName" />' . chr(10) . '<input type="hidden" name="subRequestArgumentNamespace[__referrer][arguments]" value="" />' . chr(10) . '<input type="hidden" name="__referrer[@package]" value="packageKey" />' . chr(10) . '<input type="hidden" name="__referrer[@subpackage]" value="subpackageKey" />' . chr(10) . '<input type="hidden" name="__referrer[@controller]" value="controllerName" />' . chr(10) . '<input type="hidden" name="__referrer[@action]" value="controllerActionName" />' . chr(10) . '<input type="hidden" name="__referrer[arguments]" value="" />' . chr(10); $this->assertEquals($expectedResult, $hiddenFields); } /** * @test */ public function renderAddsSpecifiedPrefixToTemplateVariableContainer() { $prefix = 'somePrefix'; $viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren', 'renderHiddenIdentityField', 'renderHiddenReferrerFields', 'addFormFieldNamesToViewHelperVariableContainer', 'removeFormFieldNamesFromViewHelperVariableContainer', 'addEmptyHiddenFieldNamesToViewHelperVariableContainer', 'removeEmptyHiddenFieldNamesFromViewHelperVariableContainer', 'renderEmptyHiddenFields', 'renderTrustedPropertiesField'), array(), '', FALSE); $this->arguments['fieldNamePrefix'] = $prefix; $this->injectDependenciesIntoViewHelper($viewHelper); $this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE)); $this->viewHelperVariableContainer->expects($this->once())->method('add')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'fieldNamePrefix', $prefix); $this->viewHelperVariableContainer->expects($this->once())->method('remove')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'fieldNamePrefix'); $viewHelper->render('index'); } /** * @test */ public function renderAddsNoFieldNamePrefixToTemplateVariableContainerIfNoPrefixIsSpecified() { $expectedPrefix = ''; $viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren', 'renderHiddenIdentityField', 'renderHiddenReferrerFields', 'addFormFieldNamesToViewHelperVariableContainer', 'removeFormFieldNamesFromViewHelperVariableContainer', 'addEmptyHiddenFieldNamesToViewHelperVariableContainer', 'removeEmptyHiddenFieldNamesFromViewHelperVariableContainer', 'renderEmptyHiddenFields', 'renderTrustedPropertiesField'), array(), '', FALSE); $this->injectDependenciesIntoViewHelper($viewHelper); $this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE)); $this->viewHelperVariableContainer->expects($this->once())->method('add')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'fieldNamePrefix', $expectedPrefix); $this->viewHelperVariableContainer->expects($this->once())->method('remove')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'fieldNamePrefix'); $viewHelper->render('index'); } /** * @test */ public function renderAddsDefaultFieldNamePrefixToTemplateVariableContainerIfNoPrefixIsSpecifiedAndRequestIsASubRequest() { $expectedPrefix = 'someArgumentPrefix'; $mockSubRequest = $this->getMock('TYPO3\Flow\Mvc\ActionRequest', array(), array(), '', FALSE); $mockSubRequest->expects($this->once())->method('getArgumentNamespace')->will($this->returnValue($expectedPrefix)); $viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('getFormActionUri', 'renderChildren', 'renderHiddenIdentityField', 'renderHiddenReferrerFields', 'addFormFieldNamesToViewHelperVariableContainer', 'removeFormFieldNamesFromViewHelperVariableContainer', 'addEmptyHiddenFieldNamesToViewHelperVariableContainer', 'removeEmptyHiddenFieldNamesFromViewHelperVariableContainer', 'renderEmptyHiddenFields', 'renderTrustedPropertiesField'), array(), '', FALSE); $this->controllerContext = $this->getMock('TYPO3\Flow\Mvc\Controller\ControllerContext', array(), array(), '', FALSE); $this->controllerContext->expects($this->any())->method('getRequest')->will($this->returnValue($mockSubRequest)); $this->renderingContext->setControllerContext($this->controllerContext); $this->injectDependenciesIntoViewHelper($viewHelper); $this->viewHelperVariableContainer->expects($this->once())->method('add')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'fieldNamePrefix', $expectedPrefix); $this->viewHelperVariableContainer->expects($this->once())->method('remove')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'fieldNamePrefix'); $viewHelper->render('index'); } /** * @test */ public function renderAddsDefaultFieldNamePrefixToTemplateVariableContainerIfNoPrefixIsSpecifiedAndUseParentRequestArgumentIsSet() { $expectedPrefix = 'parentRequestsPrefix'; $mockParentRequest = $this->getMock('TYPO3\Flow\Mvc\ActionRequest', array(), array(), '', FALSE); $mockParentRequest->expects($this->once())->method('getArgumentNamespace')->will($this->returnValue($expectedPrefix)); $mockSubRequest = $this->getMock('TYPO3\Flow\Mvc\ActionRequest', array(), array(), '', FALSE); $mockSubRequest->expects($this->once())->method('getParentRequest')->will($this->returnValue($mockParentRequest)); $viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('getFormActionUri', 'renderChildren', 'renderHiddenIdentityField', 'renderHiddenReferrerFields', 'addFormFieldNamesToViewHelperVariableContainer', 'removeFormFieldNamesFromViewHelperVariableContainer', 'addEmptyHiddenFieldNamesToViewHelperVariableContainer', 'removeEmptyHiddenFieldNamesFromViewHelperVariableContainer', 'renderEmptyHiddenFields', 'renderTrustedPropertiesField'), array(), '', FALSE); $this->arguments['useParentRequest'] = TRUE; $this->controllerContext = $this->getMock('TYPO3\Flow\Mvc\Controller\ControllerContext', array(), array(), '', FALSE); $this->controllerContext->expects($this->once())->method('getRequest')->will($this->returnValue($mockSubRequest)); $this->renderingContext->setControllerContext($this->controllerContext); $this->injectDependenciesIntoViewHelper($viewHelper); $this->securityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(FALSE)); $this->viewHelperVariableContainer->expects($this->once())->method('add')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'fieldNamePrefix', $expectedPrefix); $viewHelper->render('index'); } /** * @test */ public function renderEmptyHiddenFieldsRendersEmptyStringByDefault() { $viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren'), array(), '', FALSE); $this->injectDependenciesIntoViewHelper($viewHelper); $expected = ''; $actual = $viewHelper->_call('renderEmptyHiddenFields'); $this->assertEquals($expected, $actual); } /** * @test */ public function renderEmptyHiddenFieldsRendersOneHiddenFieldPerEntry() { $emptyHiddenFieldNames = array('fieldName1', 'fieldName2'); $this->viewHelperVariableContainer->expects($this->once())->method('exists')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'emptyHiddenFieldNames')->will($this->returnValue(TRUE)); $this->viewHelperVariableContainer->expects($this->once())->method('get')->with('TYPO3\Fluid\ViewHelpers\FormViewHelper', 'emptyHiddenFieldNames')->will($this->returnValue($emptyHiddenFieldNames)); $viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren'), array(), '', FALSE); $this->injectDependenciesIntoViewHelper($viewHelper); $expected = '<input type="hidden" name="fieldName1" value="" />' . chr(10) . '<input type="hidden" name="fieldName2" value="" />' . chr(10); $actual = $viewHelper->_call('renderEmptyHiddenFields'); $this->assertEquals($expected, $actual); } /** * @test */ public function renderResetsFormActionUri() { $viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren'), array(), '', FALSE); $this->injectDependenciesIntoViewHelper($viewHelper); $viewHelper->_set('formActionUri', 'someUri'); $viewHelper->render('index'); $this->assertNull($viewHelper->_get('formActionUri')); } /** * @test * @expectedException \TYPO3\Fluid\Core\ViewHelper\Exception */ public function renderThrowsExceptionIfNeitherActionNorActionUriArgumentIsSpecified() { $viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren'), array(), '', FALSE); $this->injectDependenciesIntoViewHelper($viewHelper); $viewHelper->render(); } /** * @test */ public function renderThrowsExceptionIfUseParentRequestIsSetAndTheCurrentRequestHasNoParentRequest() { $this->setExpectedException('TYPO3\Fluid\Core\ViewHelper\Exception', '', 1361354942); $viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('renderChildren'), array(), '', FALSE); $this->arguments['useParentRequest'] = TRUE; $this->injectDependenciesIntoViewHelper($viewHelper); $viewHelper->render('index'); } /** * @test */ public function renderUsesParentRequestIfUseParentRequestIsSet() { $mockParentRequest = $this->getMock('TYPO3\Flow\Mvc\ActionRequest', array(), array(), '', FALSE); $mockSubRequest = $this->getMock('TYPO3\Flow\Mvc\ActionRequest', array(), array(), '', FALSE); $mockSubRequest->expects($this->once())->method('isMainRequest')->will($this->returnValue(FALSE)); $mockSubRequest->expects($this->once())->method('getParentRequest')->will($this->returnValue($mockParentRequest)); $this->uriBuilder->expects($this->once())->method('setRequest')->with($mockParentRequest); $viewHelper = $this->getAccessibleMock('TYPO3\Fluid\ViewHelpers\FormViewHelper', array('dummy'), array(), '', FALSE); $this->arguments['useParentRequest'] = TRUE; $this->controllerContext = $this->getMock('TYPO3\Flow\Mvc\Controller\ControllerContext', array(), array(), '', FALSE); $this->controllerContext->expects($this->once())->method('getRequest')->will($this->returnValue($mockSubRequest)); $this->controllerContext->expects($this->once())->method('getUriBuilder')->will($this->returnValue($this->uriBuilder)); $this->renderingContext->setControllerContext($this->controllerContext); $this->injectDependenciesIntoViewHelper($viewHelper); $viewHelper->_call('getFormActionUri'); } }
garvitdelhi/emulate
Packages/Framework/TYPO3.Fluid/Tests/Unit/ViewHelpers/FormViewHelperTest.php
PHP
gpl-2.0
29,478
<?php namespace TYPO3\Flow\Persistence\Doctrine\Proxies\__CG__\project\emulate\Domain\Model; /** * THIS CLASS WAS GENERATED BY THE DOCTRINE ORM. DO NOT EDIT THIS FILE. */ class UserAccount extends \project\emulate\Domain\Model\UserAccount implements \Doctrine\ORM\Proxy\Proxy { private $_entityPersister; private $_identifier; public $__isInitialized__ = false; public function __construct($entityPersister, $identifier) { $this->_entityPersister = $entityPersister; $this->_identifier = $identifier; } /** @private */ public function __load() { if (!$this->__isInitialized__ && $this->_entityPersister) { $this->__isInitialized__ = true; if (method_exists($this, "__wakeup")) { // call this after __isInitialized__to avoid infinite recursion // but before loading to emulate what ClassMetadata::newInstance() // provides. $this->__wakeup(); } if ($this->_entityPersister->load($this->_identifier, $this) === null) { throw new \Doctrine\ORM\EntityNotFoundException(); } unset($this->_entityPersister, $this->_identifier); } } /** @private */ public function __isInitialized() { return $this->__isInitialized__; } public function __wakeup() { $this->__load(); return parent::__wakeup(); } public function Flow_Aop_Proxy_fixMethodsAndAdvicesArrayForDoctrineProxies() { $this->__load(); return parent::Flow_Aop_Proxy_fixMethodsAndAdvicesArrayForDoctrineProxies(); } public function Flow_Aop_Proxy_fixInjectedPropertiesForDoctrineProxies() { $this->__load(); return parent::Flow_Aop_Proxy_fixInjectedPropertiesForDoctrineProxies(); } public function Flow_Aop_Proxy_invokeJoinPoint(\TYPO3\Flow\Aop\JoinPointInterface $joinPoint) { $this->__load(); return parent::Flow_Aop_Proxy_invokeJoinPoint($joinPoint); } public function getName() { $this->__load(); return parent::getName(); } public function setName($name) { $this->__load(); return parent::setName($name); } public function getgender() { $this->__load(); return parent::getgender(); } public function setgender($gender) { $this->__load(); return parent::setgender($gender); } public function getUsername() { $this->__load(); return parent::getUsername(); } public function setUsername($username) { $this->__load(); return parent::setUsername($username); } public function getPassword() { $this->__load(); return parent::getPassword(); } public function setPassword($password) { $this->__load(); return parent::setPassword($password); } public function getEmail() { $this->__load(); return parent::getEmail(); } public function setEmail($email) { $this->__load(); return parent::setEmail($email); } public function getProfilePic() { $this->__load(); return parent::getProfilePic(); } public function setProfilePic($profilePic) { $this->__load(); return parent::setProfilePic($profilePic); } public function getEmulatorPreference() { $this->__load(); return parent::getEmulatorPreference(); } public function setEmulatorPreference($emulatorPreference) { $this->__load(); return parent::setEmulatorPreference($emulatorPreference); } public function getEmulatorMode() { $this->__load(); return parent::getEmulatorMode(); } public function setEmulatorMode($emulatorMode) { $this->__load(); return parent::setEmulatorMode($emulatorMode); } public function Validate($userAccountRepository, $user) { $this->__load(); return parent::Validate($userAccountRepository, $user); } public function __sleep() { return array_merge(array('__isInitialized__'), parent::__sleep()); } public function __clone() { if (!$this->__isInitialized__ && $this->_entityPersister) { $this->__isInitialized__ = true; $class = $this->_entityPersister->getClassMetadata(); $original = $this->_entityPersister->load($this->_identifier); if ($original === null) { throw new \Doctrine\ORM\EntityNotFoundException(); } foreach ($class->reflFields as $field => $reflProperty) { $reflProperty->setValue($this, $reflProperty->getValue($original)); } unset($this->_entityPersister, $this->_identifier); } parent::__clone(); } }
garvitdelhi/emulate
Data/Temporary/Development/Doctrine/Proxies/__CG__projectemulateDomainModelUserAccount.php
PHP
gpl-2.0
4,993
scientificcalci =============== Scientific calculator basic code
vigoos/scientificcalci
README.md
Markdown
gpl-2.0
66
from settings import * import pymysql def getconn(): conn = pymysql.connect( charset = 'utf8', host = DATABASES['default']['HOST'], port = DATABASES['default']['PORT'], user = DATABASES['default']['USER'], passwd = DATABASES['default']['PASSWORD'], db = DATABASES['default']['NAME']) return conn def loadSqlScript(sqlScript): f = open(sqlScript) query = '' for line in f: query = query + line return query
kassine/caparis2mysql
sqlTools.py
Python
gpl-2.0
602
/* * drivers/video/samsung/a043fw05v4.c * * Copyright (C) 2008 Travis Kuo <travis.kuo@tomtom.com> * * This file is subject to the terms and conditions of the GNU General Public * License. See the file COPYING in the main directory of this archive for * more details. * */ #include <linux/device.h> #include <linux/spi/spi.h> #include <linux/module.h> #include <linux/delay.h> #include <linux/reboot.h> #include <linux/a043fw05v4_pdata.h> #define RGB_BRIGHTNESS_DEFAULT_VAL 0x40 #define RGB_BRIGHTNESS_REG 0x3 #define MAX_RGB_BRIGHTNESS_VALUE 0xff static atomic_t mg_rgb_brightness_val = ATOMIC_INIT(0); struct spi_device *mg_spi; static int a043fw05v4_spi_remove( struct spi_device *spi ); static void a043fw05v4_set_bl(unsigned short val); static ssize_t a043fw05v4_rgb_brightness_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count); ssize_t a043fw05v4_rgb_brightness_show(struct device *dev, struct device_attribute *attr, char *buf); //provide interface /sys/bus/spi/devices/spi0.0/a043fw05v4_rgb_brightness_val to set panel backight static DEVICE_ATTR(a043fw05v4_rgb_brightness_val, 0644, a043fw05v4_rgb_brightness_show, a043fw05v4_rgb_brightness_store); static ssize_t a043fw05v4_rgb_brightness_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int val; int ret; ret = sscanf(buf, "%d",&val); if (ret != 1 || val >MAX_RGB_BRIGHTNESS_VALUE ) { printk(KERN_ERR "%s: wrong arguments\n", __func__); return count; } if(val!=atomic_read(&mg_rgb_brightness_val)) { atomic_set(&mg_rgb_brightness_val, val); a043fw05v4_set_bl(val); } return count; } ssize_t a043fw05v4_rgb_brightness_show(struct device *dev, struct device_attribute *attr, char *buf) { int val; if( dev == NULL){ printk("DEV is null!"); return -EINVAL; } val = atomic_read(&mg_rgb_brightness_val); snprintf (buf, PAGE_SIZE, "%d", val); /* return number of characters +1 for trailing '\0'*/ return strlen(buf)+1; } static int a043fw05v4_reboot(struct notifier_block *block, unsigned long cause, void* dummy) { a043fw05v4_spi_remove(mg_spi); return 0; } static struct notifier_block a043fw05v4_reboot_block = { .notifier_call = a043fw05v4_reboot, }; static void a043fw05v4_write_reg( struct spi_device *spi, unsigned short index,unsigned short data ) { unsigned char cmd[2]; cmd[0]=index<<1;cmd[1]=data; spi_write(spi, cmd, sizeof(cmd)); } static void a043fw05v4_set_bl(unsigned short val) { a043fw05v4_write_reg(mg_spi, 0x3, val); } static int a043fw05v4_spi_probe( struct spi_device *spi ) { struct a043fw05v4_platform_data *pdata=spi->dev.platform_data; int ret; mg_spi = spi; atomic_set(&mg_rgb_brightness_val, RGB_BRIGHTNESS_DEFAULT_VAL); if(pdata->request_gpio) pdata->request_gpio(); if(pdata->config_gpio) pdata->config_gpio(); if(pdata->power_on) pdata->power_on(); mdelay(5); //wait for power ramp up a043fw05v4_write_reg(spi, 0x5, 0x1e); a043fw05v4_write_reg(spi, 0x5, 0x5e); a043fw05v4_write_reg(spi, 0x5, 0x5f); a043fw05v4_write_reg(spi, RGB_BRIGHTNESS_REG, atomic_read(&mg_rgb_brightness_val)); mdelay(20); if(pdata->disp_on) pdata->disp_on(); mdelay(A043FW05V4_FRAME_PERIOD_MS*11); register_reboot_notifier(&a043fw05v4_reboot_block); if ( (ret = device_create_file(&spi->dev, &dev_attr_a043fw05v4_rgb_brightness_val)) < 0) { dev_err(&spi->dev, "failed to create a043fw05v4_bl file\n"); return ret; } return 0; } static int a043fw05v4_spi_remove( struct spi_device *spi ) { struct a043fw05v4_platform_data *pdata=spi->dev.platform_data; device_remove_file(&spi->dev, &dev_attr_a043fw05v4_rgb_brightness_val); a043fw05v4_write_reg(spi, 0x5, 0x5e); if(pdata->disp_off) pdata->disp_off(); mdelay(A043FW05V4_FRAME_PERIOD_MS*10); if(pdata->power_off) pdata->power_off(); if(pdata->free_gpio) pdata->free_gpio(); return 0; } static int a043fw05v4_spi_suspend( struct spi_device *spi, pm_message_t msg) { struct a043fw05v4_platform_data *pdata=spi->dev.platform_data; a043fw05v4_write_reg(spi, 0x5, 0x5e); if(pdata->disp_off) pdata->disp_off(); mdelay(A043FW05V4_FRAME_PERIOD_MS*10); /* power off by GPxSLPCON. keep GPXDAT the value to early power on LCM by pm.c when pm.c restores it in the beginning of resume. this is special for AUO. Otherwise spi is resumed first and spi bus made LCM semi-powered on before it's powered on by gpio be careful not to use gpio without slpcon if(pdata->power_off) pdata->power_off(); */ return 0; } static int a043fw05v4_spi_resume( struct spi_device *spi ) { struct a043fw05v4_platform_data *pdata=spi->dev.platform_data; if(pdata->power_on) pdata->power_on(); mdelay(5); //wait for power ramp up a043fw05v4_write_reg(spi, 0x5, 0x1e); a043fw05v4_write_reg(spi, 0x5, 0x5e); a043fw05v4_write_reg(spi, 0x5, 0x5f); a043fw05v4_write_reg(spi, RGB_BRIGHTNESS_REG, atomic_read(&mg_rgb_brightness_val)); mdelay(20); if(pdata->disp_on) pdata->disp_on(); mdelay(A043FW05V4_FRAME_PERIOD_MS*11); return 0; } static struct spi_driver a043fw05v4_spi_driver= { .driver= { .name = "a043fw05v4_spi", .bus = &spi_bus_type, .owner = THIS_MODULE, }, .probe = a043fw05v4_spi_probe, .remove = a043fw05v4_spi_remove, .suspend = a043fw05v4_spi_suspend, .resume = a043fw05v4_spi_resume, }; static int __init a043fw05v4_spi_init( void ) { return spi_register_driver( &a043fw05v4_spi_driver ); } static void __exit a043fw05v4_spi_exit( void ) { spi_unregister_driver( &a043fw05v4_spi_driver ); return; } module_init( a043fw05v4_spi_init ); module_exit( a043fw05v4_spi_exit ); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("a043fw05v4 SPI configuration driver");
kzlin129/tt-gpl
go12/linux-2.6.28.10/drivers/video/samsung/a043fw05v4.c
C
gpl-2.0
6,026
### # Librairies de gestions des containeurs Docker # ============================================================================== # @package olixsh # @author Olivier ## ### # Paramètres ## OLIX_DOCKER_NAME= ### # Vérifie si le binaire est installé ## function Docker.installed() { debug "Docker.installed ()" System.binary.exists 'docker' return $? } ### # Vérifie si on peut parler avec le démon Docker ## function Docker.running() { debug "Docker.daemon ()" docker info > /dev/null 2>&1 return $? } ### # Vérifie si un containeur existe # @param $1 : Nom du containeur ## function Docker.Container.exists() { debug "Docker.Container.exists ($1)" docker inspect $1 > /dev/null 2>&1 return $? } ### # Vérifie si un containeur est en cours d'éxécution # @param $1 : Nom du containeur ## function Docker.Container.running() { debug "Docker.Container.running ($1)" local RUNNING RUNNING=$(docker inspect --format="{{.State.Running}}" $1 2>&1) [[ "${RUNNING}" == "true" ]] && return 0 return 1 }
sabinus52/olixsh
utils/docker.sh
Shell
gpl-2.0
1,070
/**************************************************************************** ** $Id: qpngio.cpp 2 2005-11-16 15:49:26Z dmik $ ** ** Implementation of PNG QImage IOHandler ** ** Created : 970521 ** ** Copyright (C) 1992-2003 Trolltech AS. All rights reserved. ** ** This file is part of the kernel module of the Qt GUI Toolkit. ** ** This file may be distributed under the terms of the Q Public License ** as defined by Trolltech AS of Norway and appearing in the file ** LICENSE.QPL included in the packaging of this file. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition ** licenses may use this file in accordance with the Qt Commercial License ** Agreement provided with the Software. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for ** information about Qt Commercial License Agreements. ** See http://www.trolltech.com/qpl/ for QPL licensing information. ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "qpngio.h" #ifndef QT_NO_IMAGEIO_PNG #include "qasyncimageio.h" #include "qiodevice.h" #include <png.h> #ifdef Q_OS_TEMP #define CALLBACK_CALL_TYPE __cdecl #else #define CALLBACK_CALL_TYPE #endif /* All PNG files load to the minimal QImage equivalent. All QImage formats output to reasonably efficient PNG equivalents. Never to grayscale. */ #if defined(Q_C_CALLBACKS) extern "C" { #endif static void CALLBACK_CALL_TYPE iod_read_fn(png_structp png_ptr, png_bytep data, png_size_t length) { QImageIO* iio = (QImageIO*)png_get_io_ptr(png_ptr); QIODevice* in = iio->ioDevice(); while (length) { int nr = in->readBlock((char*)data, length); if (nr <= 0) { png_error(png_ptr, "Read Error"); return; } length -= nr; } } static void CALLBACK_CALL_TYPE qpiw_write_fn( png_structp png_ptr, png_bytep data, png_size_t length ) { QPNGImageWriter* qpiw = (QPNGImageWriter*)png_get_io_ptr( png_ptr ); QIODevice* out = qpiw->device(); uint nr = out->writeBlock( (char*)data, length ); if ( nr != length ) { png_error( png_ptr, "Write Error" ); return; } } static void CALLBACK_CALL_TYPE qpiw_flush_fn( png_structp png_ptr ) { QPNGImageWriter* qpiw = (QPNGImageWriter*)png_get_io_ptr( png_ptr ); QIODevice* out = qpiw->device(); out->flush(); } #if defined(Q_C_CALLBACKS) } #endif static void setup_qt( QImage& image, png_structp png_ptr, png_infop info_ptr, float screen_gamma=0.0 ) { if ( screen_gamma != 0.0 && png_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA) ) { double file_gamma; png_get_gAMA(png_ptr, info_ptr, &file_gamma); png_set_gamma( png_ptr, screen_gamma, file_gamma ); } png_uint_32 width; png_uint_32 height; int bit_depth; int color_type; png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, 0, 0, 0); if ( color_type == PNG_COLOR_TYPE_GRAY ) { // Black & White or 8-bit grayscale if ( bit_depth == 1 && info_ptr->channels == 1 ) { png_set_invert_mono( png_ptr ); png_read_update_info( png_ptr, info_ptr ); if (!image.create( width, height, 1, 2, QImage::BigEndian )) return; image.setColor( 1, qRgb(0,0,0) ); image.setColor( 0, qRgb(255,255,255) ); } else if (bit_depth == 16 && png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) { png_set_expand(png_ptr); png_set_strip_16(png_ptr); png_set_gray_to_rgb(png_ptr); if (!image.create(width, height, 32)) return; image.setAlphaBuffer(TRUE); if (QImage::systemByteOrder() == QImage::BigEndian) png_set_swap_alpha(png_ptr); png_read_update_info(png_ptr, info_ptr); } else { if ( bit_depth == 16 ) png_set_strip_16(png_ptr); else if ( bit_depth < 8 ) png_set_packing(png_ptr); int ncols = bit_depth < 8 ? 1 << bit_depth : 256; png_read_update_info(png_ptr, info_ptr); if (!image.create(width, height, 8, ncols)) return; for (int i=0; i<ncols; i++) { int c = i*255/(ncols-1); image.setColor( i, qRgba(c,c,c,0xff) ); } if ( png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS) ) { const int g = info_ptr->trans_values.gray; if (g < ncols) { image.setAlphaBuffer(TRUE); image.setColor(g, image.color(g) & RGB_MASK); } } } } else if ( color_type == PNG_COLOR_TYPE_PALETTE && png_get_valid(png_ptr, info_ptr, PNG_INFO_PLTE) && info_ptr->num_palette <= 256 ) { // 1-bit and 8-bit color if ( bit_depth != 1 ) png_set_packing( png_ptr ); png_read_update_info( png_ptr, info_ptr ); png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, 0, 0, 0); if (!image.create(width, height, bit_depth, info_ptr->num_palette, QImage::BigEndian)) return; int i = 0; if ( png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS) ) { image.setAlphaBuffer( TRUE ); while ( i < info_ptr->num_trans ) { image.setColor(i, qRgba( info_ptr->palette[i].red, info_ptr->palette[i].green, info_ptr->palette[i].blue, info_ptr->trans[i] ) ); i++; } } while ( i < info_ptr->num_palette ) { image.setColor(i, qRgba( info_ptr->palette[i].red, info_ptr->palette[i].green, info_ptr->palette[i].blue, 0xff ) ); i++; } } else { // 32-bit if ( bit_depth == 16 ) png_set_strip_16(png_ptr); png_set_expand(png_ptr); if ( color_type == PNG_COLOR_TYPE_GRAY_ALPHA ) png_set_gray_to_rgb(png_ptr); if (!image.create(width, height, 32)) return; // Only add filler if no alpha, or we can get 5 channel data. if (!(color_type & PNG_COLOR_MASK_ALPHA) && !png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) { png_set_filler(png_ptr, 0xff, QImage::systemByteOrder() == QImage::BigEndian ? PNG_FILLER_BEFORE : PNG_FILLER_AFTER); // We want 4 bytes, but it isn't an alpha channel } else { image.setAlphaBuffer(TRUE); } if ( QImage::systemByteOrder() == QImage::BigEndian ) { png_set_swap_alpha(png_ptr); } png_read_update_info(png_ptr, info_ptr); } // Qt==ARGB==Big(ARGB)==Little(BGRA) if ( QImage::systemByteOrder() == QImage::LittleEndian ) { png_set_bgr(png_ptr); } } #if defined(Q_C_CALLBACKS) extern "C" { #endif static void CALLBACK_CALL_TYPE qt_png_warning(png_structp /*png_ptr*/, png_const_charp message) { qWarning("libpng warning: %s", message); } #if defined(Q_C_CALLBACKS) } #endif static void read_png_image(QImageIO* iio) { png_structp png_ptr; png_infop info_ptr; png_infop end_info; png_bytep* row_pointers; png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,0,0,0); if (!png_ptr) { iio->setStatus(-1); return; } png_set_error_fn(png_ptr, 0, 0, qt_png_warning); info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, 0, 0); iio->setStatus(-2); return; } end_info = png_create_info_struct(png_ptr); if (!end_info) { png_destroy_read_struct(&png_ptr, &info_ptr, 0); iio->setStatus(-3); return; } if (setjmp(png_ptr->jmpbuf)) { png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); iio->setStatus(-4); return; } png_set_read_fn(png_ptr, (void*)iio, iod_read_fn); png_read_info(png_ptr, info_ptr); QImage image; setup_qt(image, png_ptr, info_ptr, iio->gamma()); if (image.isNull()) { png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); iio->setStatus(-5); return; } png_uint_32 width; png_uint_32 height; int bit_depth; int color_type; png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, 0, 0, 0); uchar** jt = image.jumpTable(); row_pointers=new png_bytep[height]; for (uint y=0; y<height; y++) { row_pointers[y]=jt[y]; } png_read_image(png_ptr, row_pointers); #if 0 // libpng takes care of this. png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS) if (image.depth()==32 && png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) { QRgb trans = 0xFF000000 | qRgb( (info_ptr->trans_values.red << 8 >> bit_depth)&0xff, (info_ptr->trans_values.green << 8 >> bit_depth)&0xff, (info_ptr->trans_values.blue << 8 >> bit_depth)&0xff); for (uint y=0; y<height; y++) { for (uint x=0; x<info_ptr->width; x++) { if (((uint**)jt)[y][x] == trans) { ((uint**)jt)[y][x] &= 0x00FFFFFF; } else { } } } } #endif image.setDotsPerMeterX(png_get_x_pixels_per_meter(png_ptr,info_ptr)); image.setDotsPerMeterY(png_get_y_pixels_per_meter(png_ptr,info_ptr)); #ifndef QT_NO_IMAGE_TEXT png_textp text_ptr; int num_text=0; png_get_text(png_ptr,info_ptr,&text_ptr,&num_text); while (num_text--) { image.setText(text_ptr->key,0,text_ptr->text); text_ptr++; } #endif delete [] row_pointers; if ( image.hasAlphaBuffer() ) { // Many PNG files lie (eg. from PhotoShop). Fortunately this loop will // usually be quick to find those that tell the truth. QRgb* c; int n; if (image.depth()==32) { c = (QRgb*)image.bits(); n = image.bytesPerLine() * image.height() / 4; } else { c = image.colorTable(); n = image.numColors(); } while ( n-- && qAlpha(*c++)==0xff ) ; if ( n<0 ) // LIAR! image.setAlphaBuffer(FALSE); } iio->setImage(image); png_read_end(png_ptr, end_info); png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); iio->setStatus(0); } QPNGImageWriter::QPNGImageWriter(QIODevice* iod) : dev(iod), frames_written(0), disposal(Unspecified), looping(-1), ms_delay(-1), gamma(0.0) { } QPNGImageWriter::~QPNGImageWriter() { } void QPNGImageWriter::setDisposalMethod(DisposalMethod dm) { disposal = dm; } void QPNGImageWriter::setLooping(int loops) { looping = loops; } void QPNGImageWriter::setFrameDelay(int msecs) { ms_delay = msecs; } void QPNGImageWriter::setGamma(float g) { gamma = g; } #ifndef QT_NO_IMAGE_TEXT static void set_text(const QImage& image, png_structp png_ptr, png_infop info_ptr, bool short_not_long) { QValueList<QImageTextKeyLang> keys = image.textList(); if ( keys.count() ) { png_textp text_ptr = new png_text[keys.count()]; int i=0; for (QValueList<QImageTextKeyLang>::Iterator it=keys.begin(); it != keys.end(); ++it) { QString t = image.text(*it); if ( (t.length() <= 200) == short_not_long ) { if ( t.length() < 40 ) text_ptr[i].compression = PNG_TEXT_COMPRESSION_NONE; else text_ptr[i].compression = PNG_TEXT_COMPRESSION_zTXt; text_ptr[i].key = (png_charp)(*it).key.data(); text_ptr[i].text = (png_charp)t.latin1(); //text_ptr[i].text = qstrdup(t.latin1()); i++; } } png_set_text(png_ptr, info_ptr, text_ptr, i); //for (int j=0; j<i; j++) //free(text_ptr[i].text); delete [] text_ptr; } } #endif bool QPNGImageWriter::writeImage(const QImage& image, int off_x, int off_y) { return writeImage(image, -1, off_x, off_y); } bool QPNGImageWriter::writeImage(const QImage& image, int quality_in, int off_x_in, int off_y_in) { QPoint offset = image.offset(); int off_x = off_x_in + offset.x(); int off_y = off_y_in + offset.y(); png_structp png_ptr; png_infop info_ptr; png_bytep* row_pointers; png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,0,0,0); if (!png_ptr) { return FALSE; } png_set_error_fn(png_ptr, 0, 0, qt_png_warning); info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_write_struct(&png_ptr, 0); return FALSE; } if (setjmp(png_ptr->jmpbuf)) { png_destroy_write_struct(&png_ptr, &info_ptr); return FALSE; } int quality = quality_in; if (quality >= 0) { if (quality > 9) { #if defined(QT_CHECK_RANGE) qWarning( "PNG: Quality %d out of range", quality ); #endif quality = 9; } png_set_compression_level(png_ptr, quality); } if (gamma != 0.0) { png_set_gAMA(png_ptr, info_ptr, 1.0/gamma); } png_set_write_fn(png_ptr, (void*)this, qpiw_write_fn, qpiw_flush_fn); info_ptr->channels = (image.depth() == 32) ? (image.hasAlphaBuffer() ? 4 : 3) : 1; png_set_IHDR(png_ptr, info_ptr, image.width(), image.height(), image.depth() == 1 ? 1 : 8 /* per channel */, image.depth() == 32 ? image.hasAlphaBuffer() ? PNG_COLOR_TYPE_RGB_ALPHA : PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_PALETTE, 0, 0, 0); //png_set_sBIT(png_ptr, info_ptr, 8); info_ptr->sig_bit.red = 8; info_ptr->sig_bit.green = 8; info_ptr->sig_bit.blue = 8; if (image.depth() == 1 && image.bitOrder() == QImage::LittleEndian) png_set_packswap(png_ptr); png_colorp palette = 0; png_bytep copy_trans = 0; if (image.numColors()) { // Paletted int num_palette = image.numColors(); palette = new png_color[num_palette]; png_set_PLTE(png_ptr, info_ptr, palette, num_palette); int* trans = new int[num_palette]; int num_trans = 0; for (int i=0; i<num_palette; i++) { QRgb rgb=image.color(i); info_ptr->palette[i].red = qRed(rgb); info_ptr->palette[i].green = qGreen(rgb); info_ptr->palette[i].blue = qBlue(rgb); if (image.hasAlphaBuffer()) { trans[i] = rgb >> 24; if (trans[i] < 255) { num_trans = i+1; } } } if (num_trans) { copy_trans = new png_byte[num_trans]; for (int i=0; i<num_trans; i++) copy_trans[i] = trans[i]; png_set_tRNS(png_ptr, info_ptr, copy_trans, num_trans, 0); } delete [] trans; } if ( image.hasAlphaBuffer() ) { info_ptr->sig_bit.alpha = 8; } // Swap ARGB to RGBA (normal PNG format) before saving on // BigEndian machines if ( QImage::systemByteOrder() == QImage::BigEndian ) { png_set_swap_alpha(png_ptr); } // Qt==ARGB==Big(ARGB)==Little(BGRA) if ( QImage::systemByteOrder() == QImage::LittleEndian ) { png_set_bgr(png_ptr); } if (off_x || off_y) { png_set_oFFs(png_ptr, info_ptr, off_x, off_y, PNG_OFFSET_PIXEL); } if ( frames_written > 0 ) png_set_sig_bytes(png_ptr, 8); if ( image.dotsPerMeterX() > 0 || image.dotsPerMeterY() > 0 ) { png_set_pHYs(png_ptr, info_ptr, image.dotsPerMeterX(), image.dotsPerMeterY(), PNG_RESOLUTION_METER); } #ifndef QT_NO_IMAGE_TEXT // Write short texts early. set_text(image,png_ptr,info_ptr,TRUE); #endif png_write_info(png_ptr, info_ptr); #ifndef QT_NO_IMAGE_TEXT // Write long texts later. set_text(image,png_ptr,info_ptr,FALSE); #endif if ( image.depth() != 1 ) png_set_packing(png_ptr); if ( image.depth() == 32 && !image.hasAlphaBuffer() ) png_set_filler(png_ptr, 0, QImage::systemByteOrder() == QImage::BigEndian ? PNG_FILLER_BEFORE : PNG_FILLER_AFTER); if ( looping >= 0 && frames_written == 0 ) { uchar data[13] = "NETSCAPE2.0"; // 0123456789aBC data[0xB] = looping%0x100; data[0xC] = looping/0x100; png_write_chunk(png_ptr, (png_byte*)"gIFx", data, 13); } if ( ms_delay >= 0 || disposal!=Unspecified ) { uchar data[4]; data[0] = disposal; data[1] = 0; data[2] = (ms_delay/10)/0x100; // hundredths data[3] = (ms_delay/10)%0x100; png_write_chunk(png_ptr, (png_byte*)"gIFg", data, 4); } png_uint_32 width; png_uint_32 height; int bit_depth; int color_type; png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, 0, 0, 0); uchar** jt = image.jumpTable(); row_pointers=new png_bytep[height]; uint y; for (y=0; y<height; y++) { row_pointers[y]=jt[y]; } png_write_image(png_ptr, row_pointers); delete [] row_pointers; png_write_end(png_ptr, info_ptr); frames_written++; if ( palette ) delete [] palette; if ( copy_trans ) delete [] copy_trans; png_destroy_write_struct(&png_ptr, &info_ptr); return TRUE; } static void write_png_image(QImageIO* iio) { QPNGImageWriter writer(iio->ioDevice()); int quality = iio->quality(); if ( quality >= 0 ) { quality = QMIN( quality, 100 ); quality = (100-quality) * 9 / 91; // map [0,100] -> [9,0] } writer.setGamma(iio->gamma()); bool ok = writer.writeImage( iio->image(), quality ); iio->setStatus( ok ? 0 : -1 ); } /*! \class QPNGImagePacker qpngio.h \brief The QPNGImagePacker class creates well-compressed PNG animations. \ingroup images \ingroup graphics By using transparency, QPNGImagePacker allows you to build a PNG image from a sequence of QImages. Images are added using packImage(). */ /*! Creates an image packer that writes PNG data to IO device \a iod using a \a storage_depth bit encoding (use 8 or 32, depending on the desired quality and compression requirements). If the image needs to be modified to fit in a lower-resolution result (e.g. converting from 32-bit to 8-bit), use the \a conversionflags to specify how you'd prefer this to happen. \sa Qt::ImageConversionFlags */ QPNGImagePacker::QPNGImagePacker(QIODevice* iod, int storage_depth, int conversionflags) : QPNGImageWriter(iod), depth(storage_depth), convflags(conversionflags), alignx(1) { } /*! Aligns pixel differences to \a x pixels. For example, using 8 can improve playback on certain hardware. Normally the default of 1-pixel alignment (i.e. no alignment) gives better compression and performance. */ void QPNGImagePacker::setPixelAlignment(int x) { alignx = x; } /*! Adds the image \a img to the PNG animation, analyzing the differences between this and the previous image to improve compression. */ bool QPNGImagePacker::packImage(const QImage& img) { QImage image = img.convertDepth(32); if ( previous.isNull() ) { // First image writeImage(image.convertDepth(depth,convflags)); } else { bool done; int minx, maxx, miny, maxy; int w = image.width(); int h = image.height(); QRgb** jt = (QRgb**)image.jumpTable(); QRgb** pjt = (QRgb**)previous.jumpTable(); // Find left edge of change done = FALSE; for (minx = 0; minx < w && !done; minx++) { for (int ty = 0; ty < h; ty++) { if ( jt[ty][minx] != pjt[ty][minx] ) { done = TRUE; break; } } } minx--; // Find right edge of change done = FALSE; for (maxx = w-1; maxx >= 0 && !done; maxx--) { for (int ty = 0; ty < h; ty++) { if ( jt[ty][maxx] != pjt[ty][maxx] ) { done = TRUE; break; } } } maxx++; // Find top edge of change done = FALSE; for (miny = 0; miny < h && !done; miny++) { for (int tx = 0; tx < w; tx++) { if ( jt[miny][tx] != pjt[miny][tx] ) { done = TRUE; break; } } } miny--; // Find right edge of change done = FALSE; for (maxy = h-1; maxy >= 0 && !done; maxy--) { for (int tx = 0; tx < w; tx++) { if ( jt[maxy][tx] != pjt[maxy][tx] ) { done = TRUE; break; } } } maxy++; if ( minx > maxx ) minx=maxx=0; if ( miny > maxy ) miny=maxy=0; if ( alignx > 1 ) { minx -= minx % alignx; maxx = maxx - maxx % alignx + alignx - 1; } int dw = maxx-minx+1; int dh = maxy-miny+1; QImage diff(dw, dh, 32); diff.setAlphaBuffer(TRUE); int x, y; if ( alignx < 1 ) alignx = 1; for (y = 0; y < dh; y++) { QRgb* li = (QRgb*)image.scanLine(y+miny)+minx; QRgb* lp = (QRgb*)previous.scanLine(y+miny)+minx; QRgb* ld = (QRgb*)diff.scanLine(y); if ( alignx ) { for (x = 0; x < dw; x+=alignx) { int i; for (i=0; i<alignx; i++) { if ( li[x+i] != lp[x+i] ) break; } if ( i == alignx ) { // All the same for (i=0; i<alignx; i++) { ld[x+i] = qRgba(0,0,0,0); } } else { // Some different for (i=0; i<alignx; i++) { ld[x+i] = 0xff000000 | li[x+i]; } } } } else { for (x = 0; x < dw; x++) { if ( li[x] != lp[x] ) ld[x] = 0xff000000 | li[x]; else ld[x] = qRgba(0,0,0,0); } } } diff = diff.convertDepth(depth,convflags); if ( !writeImage(diff, minx, miny) ) return FALSE; } previous = image; return TRUE; } #ifndef QT_NO_ASYNC_IMAGE_IO class QPNGFormat : public QImageFormat { public: QPNGFormat(); virtual ~QPNGFormat(); int decode(QImage& img, QImageConsumer* consumer, const uchar* buffer, int length); void info(png_structp png_ptr, png_infop info); void row(png_structp png_ptr, png_bytep new_row, png_uint_32 row_num, int pass); void end(png_structp png_ptr, png_infop info); #ifdef PNG_USER_CHUNKS_SUPPORTED int user_chunk(png_structp png_ptr, png_bytep data, png_uint_32 length); #endif private: // Animation-level information enum { MovieStart, FrameStart, Inside, End } state; int first_frame; int base_offx; int base_offy; // Image-level information png_structp png_ptr; png_infop info_ptr; // Temporary locals during single data-chunk processing QImageConsumer* consumer; QImage* image; int unused_data; }; class QPNGFormatType : public QImageFormatType { QImageFormat* decoderFor(const uchar* buffer, int length); const char* formatName() const; }; /* \class QPNGFormat qpngio.h \brief The QPNGFormat class provides an incremental image decoder for PNG image format. \ingroup images \ingroup graphics This subclass of QImageFormat decodes PNG format images, including animated PNGs. Animated PNG images are standard PNG images. The PNG standard defines two extension chunks that are useful for animations: \list \i gIFg - GIF-like Graphic Control Extension. This includes frame disposal, user input flag (we ignore this), and inter-frame delay. \i gIFx - GIF-like Application Extension. This is multi-purpose, but we just use the Netscape extension which specifies looping. \endlist The subimages usually contain a offset chunk (oFFs) but need not. The first image defines the "screen" size. Any subsequent image that doesn't fit is clipped. */ /* ###TODO: decide on this point. gIFg gives disposal types, so it can be done. All images paste (\e not composite, just place all-channel copying) over the previous image to produce a subsequent frame. */ /* \class QPNGFormatType qasyncimageio.h \brief The QPNGFormatType class provides an incremental image decoder for PNG image format. \ingroup images \ingroup graphics \ingroup io This subclass of QImageFormatType recognizes PNG format images, creating a QPNGFormat when required. An instance of this class is created automatically before any other factories, so you should have no need for such objects. */ QImageFormat* QPNGFormatType::decoderFor( const uchar* buffer, int length) { if (length < 8) return 0; if (buffer[0]==137 && buffer[1]=='P' && buffer[2]=='N' && buffer[3]=='G' && buffer[4]==13 && buffer[5]==10 && buffer[6]==26 && buffer[7]==10) return new QPNGFormat; return 0; } const char* QPNGFormatType::formatName() const { return "PNG"; } #if defined(Q_C_CALLBACKS) extern "C" { #endif static void CALLBACK_CALL_TYPE info_callback(png_structp png_ptr, png_infop info) { QPNGFormat* that = (QPNGFormat*)png_get_progressive_ptr(png_ptr); that->info(png_ptr,info); } static void CALLBACK_CALL_TYPE row_callback(png_structp png_ptr, png_bytep new_row, png_uint_32 row_num, int pass) { QPNGFormat* that = (QPNGFormat*)png_get_progressive_ptr(png_ptr); that->row(png_ptr,new_row,row_num,pass); } static void CALLBACK_CALL_TYPE end_callback(png_structp png_ptr, png_infop info) { QPNGFormat* that = (QPNGFormat*)png_get_progressive_ptr(png_ptr); that->end(png_ptr,info); } #if 0 #ifdef PNG_USER_CHUNKS_SUPPORTED static int CALLBACK_CALL_TYPE user_chunk_callback(png_structp png_ptr, png_unknown_chunkp chunk) { QPNGFormat* that = (QPNGFormat*)png_get_progressive_ptr(png_ptr); return that->user_chunk(png_ptr,chunk->data,chunk->size); } #endif #endif #if defined(Q_C_CALLBACKS) } #endif /*! Constructs a QPNGFormat object. */ QPNGFormat::QPNGFormat() { state = MovieStart; first_frame = 1; base_offx = 0; base_offy = 0; png_ptr = 0; info_ptr = 0; } /*! Destroys a QPNGFormat object. */ QPNGFormat::~QPNGFormat() { if ( png_ptr ) png_destroy_read_struct(&png_ptr, &info_ptr, 0); } /*! This function decodes some data into image changes. Returns the number of bytes consumed. */ int QPNGFormat::decode(QImage& img, QImageConsumer* cons, const uchar* buffer, int length) { consumer = cons; image = &img; if ( state != Inside ) { png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0); if (!png_ptr) { info_ptr = 0; image = 0; return -1; } png_set_error_fn(png_ptr, 0, 0, qt_png_warning); png_set_compression_level(png_ptr, 9); info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, &info_ptr, 0); image = 0; return -1; } if (setjmp((png_ptr)->jmpbuf)) { png_destroy_read_struct(&png_ptr, &info_ptr, 0); image = 0; return -1; } png_set_progressive_read_fn(png_ptr, (void *)this, info_callback, row_callback, end_callback); #ifdef PNG_USER_CHUNKS_SUPPORTED // Can't do this yet. libpng has a crash bug with unknown (user) chunks. // Warwick has sent them a patch. // png_set_read_user_chunk_fn(png_ptr, 0, user_chunk_callback); // png_set_keep_unknown_chunks(png_ptr, 2/*HANDLE_CHUNK_IF_SAFE*/, 0, 0); #endif if ( state != MovieStart && *buffer != 0211 ) { // Good, no signature - the preferred way to concat PNG images. // Skip them. png_set_sig_bytes(png_ptr, 8); } state = Inside; } if ( !png_ptr ) return 0; if (setjmp(png_ptr->jmpbuf)) { png_destroy_read_struct(&png_ptr, &info_ptr, 0); image = 0; state = MovieStart; return -1; } unused_data = 0; png_process_data(png_ptr, info_ptr, (png_bytep)buffer, length); int l = length - unused_data; // TODO: send incremental stuff to consumer (optional) if ( state != Inside ) { if ( png_ptr ) png_destroy_read_struct(&png_ptr, &info_ptr, 0); } image = 0; return l; } void QPNGFormat::info(png_structp png, png_infop) { png_set_interlace_handling(png); setup_qt(*image, png, info_ptr); } void QPNGFormat::row(png_structp png, png_bytep new_row, png_uint_32 row_num, int) { uchar* old_row = image->scanLine(row_num); png_progressive_combine_row(png, old_row, new_row); } void QPNGFormat::end(png_structp png, png_infop info) { int offx = png_get_x_offset_pixels(png,info) - base_offx; int offy = png_get_y_offset_pixels(png,info) - base_offy; if ( first_frame ) { base_offx = offx; base_offy = offy; first_frame = 0; } image->setOffset(QPoint(offx,offy)); image->setDotsPerMeterX(png_get_x_pixels_per_meter(png,info)); image->setDotsPerMeterY(png_get_y_pixels_per_meter(png,info)); #ifndef QT_NO_IMAGE_TEXT png_textp text_ptr; int num_text=0; png_get_text(png,info,&text_ptr,&num_text); while (num_text--) { image->setText(text_ptr->key,0,text_ptr->text); text_ptr++; } #endif QRect r(0,0,image->width(),image->height()); consumer->frameDone(QPoint(offx,offy),r); consumer->end(); state = FrameStart; unused_data = (int)png->buffer_size; // Since libpng doesn't tell us } #ifdef PNG_USER_CHUNKS_SUPPORTED /* #ifndef QT_NO_IMAGE_TEXT static bool skip(png_uint_32& max, png_bytep& data) { while (*data) { if ( !max ) return FALSE; max--; data++; } if ( !max ) return FALSE; max--; data++; // skip to after NUL return TRUE; } #endif */ int QPNGFormat::user_chunk(png_structp png, png_bytep data, png_uint_32 length) { #if 0 // NOT SUPPORTED: experimental PNG animation. // qDebug("Got %ld-byte %s chunk", length, png->chunk_name); if ( 0==qstrcmp((char*)png->chunk_name, "gIFg") && length == 4 ) { //QPNGImageWriter::DisposalMethod disposal = // (QPNGImageWriter::DisposalMethod)data[0]; // ### TODO: use the disposal method int ms_delay = ((data[2] << 8) | data[3])*10; consumer->setFramePeriod(ms_delay); return 1; } else if ( 0==qstrcmp((char*)png->chunk_name, "gIFx") && length == 13 ) { if ( qstrncmp((char*)data,"NETSCAPE2.0",11)==0 ) { int looping = (data[0xC]<<8)|data[0xB]; consumer->setLooping(looping); return 1; } } #else Q_UNUSED( png ) Q_UNUSED( data ) Q_UNUSED( length ) #endif #ifndef QT_NO_IMAGE_TEXT /* libpng now supports this chunk. if ( 0==qstrcmp((char*)png->chunk_name, "iTXt") && length>=6 ) { const char* keyword = (const char*)data; if ( !skip(length,data) ) return 0; if ( length >= 4 ) { char compression_flag = *data++; char compression_method = *data++; if ( compression_flag == compression_method ) { // fool the compiler into thinking they're used } const char* lang = (const char*)data; if ( !skip(length,data) ) return 0; // const char* keyword_utf8 = (const char*)data; if ( !skip(length,data) ) return 0; const char* text_utf8 = (const char*)data; if ( !skip(length,data) ) return 0; QString text = QString::fromUtf8(text_utf8); image->setText(keyword,lang[0] ? lang : 0,text); return 1; } } */ #endif return 0; } #endif static QPNGFormatType* globalPngFormatTypeObject = 0; #endif // QT_NO_ASYNC_IMAGE_IO static bool done = FALSE; void qCleanupPngIO() { #ifndef QT_NO_ASYNC_IMAGE_IO if ( globalPngFormatTypeObject ) { delete globalPngFormatTypeObject; globalPngFormatTypeObject = 0; } #endif done = FALSE; } void qInitPngIO() { if ( !done ) { done = TRUE; QImageIO::defineIOHandler( "PNG", "^.PNG\r", 0, read_png_image, write_png_image); #ifndef QT_NO_ASYNC_IMAGE_IO globalPngFormatTypeObject = new QPNGFormatType; #endif qAddPostRoutine( qCleanupPngIO ); } } void qt_zlib_compression_hack() { compress(0,0,0,0); uncompress(0,0,0,0); } #endif // QT_NO_IMAGEIO_PNG
OS2World/LIB-QT3_Toolkit_Vbox
src/kernel/qpngio.cpp
C++
gpl-2.0
30,630
#!/usr/bin/env python #Mercurial extension to robustly integrate prompts with other processes #Copyright (C) 2010-2011 Willem Verstraeten # #This program is free software; you can redistribute it and/or #modify it under the terms of the GNU General Public License #as published by the Free Software Foundation; either version 2 #of the License, or (at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. # #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import urllib2 from mercurial import ui, util import struct, socket from mercurial.i18n import _ try: from mercurial.url import passwordmgr except: from mercurial.httprepo import passwordmgr def sendInt( client, number): length = struct.pack('>L', number) client.sendall( length ) def send( client, data ): if data is None: sendInt(client, 0) else: sendInt(client, len(data)) client.sendall( data ) def receiveIntWithMessage(client, message): requiredLength = struct.calcsize('>L') buffer = '' while len(buffer)<requiredLength: chunk = client.recv(requiredLength-len(buffer)) if chunk == '': raise util.Abort( message ) buffer = buffer + chunk # struct.unpack always returns a tuple, even if that tuple only contains a single # item. The trailing , is to destructure the tuple into its first element. intToReturn, = struct.unpack('>L', buffer) return intToReturn def receiveInt(client): return receiveIntWithMessage(client, "could not get information from server") def receive( client ): receiveWithMessage(client, "could not get information from server") def receiveWithMessage( client, message ): length = receiveIntWithMessage(client, message) buffer = '' while len(buffer) < length : chunk = client.recv(length - len(buffer)) if chunk == '': raise util.Abort( message) buffer = buffer+chunk return buffer # decorator to cleanly monkey patch methods in mercurial def monkeypatch_method(cls): def decorator(func): setattr(cls, func.__name__, func) return func return decorator def sendchoicestoidea(ui, msg, choices, default): port = int(ui.config( 'hg4ideaprompt', 'port', None, True)) if not port: raise util.Abort("No port was specified") numOfChoices = len(choices) if not numOfChoices: return default client = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) try: client.connect( ('127.0.0.1', port) ) send( client, msg ) sendInt( client, numOfChoices ) for choice in choices: send( client, choice ) sendInt( client, default ) answer = receiveInt( client ) if answer == -1: raise util.Abort("User cancelled") else: return answer except: raise # determine which method to monkey patch : # in Mercurial 1.4 the prompt method was renamed to promptchoice if getattr(ui.ui, 'promptchoice', None): @monkeypatch_method(ui.ui) def promptchoice(self, msg, choices=None, default=0): return sendchoicestoidea(self, msg, choices, default) else: @monkeypatch_method(ui.ui) def prompt(self, msg, choices=None, default="y"): resps = [s[s.index('&')+1].lower() for s in choices] defaultIndex = resps.index( default ) responseIndex = sendchoicestoidea( self, msg, choices, defaultIndex) return resps[responseIndex] original_warn = ui.ui.warn @monkeypatch_method(ui.ui) def warn(self, *msg): original_warn(self, *msg) port = int(self.config( 'hg4ideawarn', 'port', None, True)) if not port: raise util.Abort("No port was specified") self.debug( "hg4idea prompt server waiting on port %s" % port ) client = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) self.debug( "connecting ..." ) client.connect( ('127.0.0.1', port) ) self.debug( "connected, sending data ..." ) sendInt( client, len(msg) ) for message in msg: send( client, message ) def retrieve_pass_from_server(ui, uri,path, proposed_user): port = int(ui.config('hg4ideapass', 'port', None, True)) if port is None: raise util.Abort("No port was specified") client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ui.debug("connecting ...") client.connect(('127.0.0.1', port)) ui.debug("connected, sending data ...") send(client, "getpass") send(client, uri) send(client, path) send(client, proposed_user) user = receiveWithMessage(client, "http authorization required") password = receiveWithMessage(client, "http authorization required") return user, password original_retrievepass=passwordmgr.find_user_password @monkeypatch_method(passwordmgr) def find_user_password(self, realm, authuri): try: return original_retrievepass(self, realm, authuri) except util.Abort: # In mercurial 1.8 the readauthtoken method was replaced with # the readauthforuri method, which has different semantics if getattr(self, 'readauthtoken', None): def read_hgrc_authtoken(ui, authuri): return self.readauthtoken(authuri) else: def read_hgrc_authtoken(ui, authuri): # hg 1.8 from mercurial.url import readauthforuri res = readauthforuri(self.ui, authuri) if res: group, auth = res return auth else: return None user, password = urllib2.HTTPPasswordMgrWithDefaultRealm.find_user_password(self, realm, authuri) if user is None: auth = read_hgrc_authtoken(self.ui, authuri) if auth: user = auth.get("username") reduced_uri, path= self.reduce_uri(authuri, False) retrievedPass = retrieve_pass_from_server(self.ui, reduced_uri, path, user) if retrievedPass is None: raise util.Abort(_('http authorization required')) user, passwd = retrievedPass self.add_password(realm, authuri, user, passwd) return retrievedPass
willemv/mercurial_prompthooks
prompthooks.py
Python
gpl-2.0
6,665
/******************************************************************************* * File Name: Wrist_Tilt.h * Version 2.10 * * Description: * This file contains the Alias definitions for Per-Pin APIs in cypins.h. * Information on using these APIs can be found in the System Reference Guide. * * Note: * ******************************************************************************** * Copyright 2008-2014, Cypress Semiconductor Corporation. All rights reserved. * You may use this file only in accordance with the license, terms, conditions, * disclaimers, and limitations in the end user license agreement accompanying * the software package with which this file was provided. *******************************************************************************/ #if !defined(CY_PINS_Wrist_Tilt_ALIASES_H) /* Pins Wrist_Tilt_ALIASES_H */ #define CY_PINS_Wrist_Tilt_ALIASES_H #include "cytypes.h" #include "cyfitter.h" #include "cypins.h" /*************************************** * Constants ***************************************/ #define Wrist_Tilt_0 (Wrist_Tilt__0__PC) #define Wrist_Tilt_0_PS (Wrist_Tilt__0__PS) #define Wrist_Tilt_0_PC (Wrist_Tilt__0__PC) #define Wrist_Tilt_0_DR (Wrist_Tilt__0__DR) #define Wrist_Tilt_0_SHIFT (Wrist_Tilt__0__SHIFT) #endif /* End Pins Wrist_Tilt_ALIASES_H */ /* [] END OF FILE */
BYU-MarsRover/Power-System
PWM_MUX/PWM_MUX.cydsn/Generated_Source/PSoC4/Wrist_Tilt_aliases.h
C
gpl-2.0
1,395
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-11 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ Thread::Thread (const String& threadName_) : threadName (threadName_), threadHandle (nullptr), threadId (0), threadPriority (5), affinityMask (0), shouldExit (false) { } Thread::~Thread() { /* If your thread class's destructor has been called without first stopping the thread, that means that this partially destructed object is still performing some work - and that's probably a Bad Thing! To avoid this type of nastiness, always make sure you call stopThread() before or during your subclass's destructor. */ jassert (! isThreadRunning()); stopThread (100); } //============================================================================== // Use a ref-counted object to hold this shared data, so that it can outlive its static // shared pointer when threads are still running during static shutdown. struct CurrentThreadHolder : public ReferenceCountedObject { CurrentThreadHolder() noexcept {} typedef ReferenceCountedObjectPtr <CurrentThreadHolder> Ptr; ThreadLocalValue<Thread*> value; JUCE_DECLARE_NON_COPYABLE (CurrentThreadHolder) }; static char currentThreadHolderLock [sizeof (SpinLock)]; // (statically initialised to zeros). static CurrentThreadHolder::Ptr getCurrentThreadHolder() { static CurrentThreadHolder::Ptr currentThreadHolder; SpinLock::ScopedLockType lock (*reinterpret_cast <SpinLock*> (currentThreadHolderLock)); if (currentThreadHolder == nullptr) currentThreadHolder = new CurrentThreadHolder(); return currentThreadHolder; } void Thread::threadEntryPoint() { const CurrentThreadHolder::Ptr currentThreadHolder (getCurrentThreadHolder()); currentThreadHolder->value = this; JUCE_TRY { if (threadName.isNotEmpty()) setCurrentThreadName (threadName); if (startSuspensionEvent.wait (10000)) { jassert (getCurrentThreadId() == threadId); if (affinityMask != 0) setCurrentThreadAffinityMask (affinityMask); run(); } } JUCE_CATCH_ALL_ASSERT currentThreadHolder->value.releaseCurrentThreadStorage(); closeThreadHandle(); } // used to wrap the incoming call from the platform-specific code void JUCE_API juce_threadEntryPoint (void* userData) { static_cast <Thread*> (userData)->threadEntryPoint(); } //============================================================================== void Thread::startThread() { const ScopedLock sl (startStopLock); shouldExit = false; if (threadHandle == nullptr) { launchThread(); setThreadPriority (threadHandle, threadPriority); startSuspensionEvent.signal(); } } void Thread::startThread (const int priority) { const ScopedLock sl (startStopLock); if (threadHandle == nullptr) { threadPriority = priority; startThread(); } else { setPriority (priority); } } bool Thread::isThreadRunning() const { return threadHandle != nullptr; } Thread* Thread::getCurrentThread() { return getCurrentThreadHolder()->value.get(); } //============================================================================== void Thread::signalThreadShouldExit() { shouldExit = true; } bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const { // Doh! So how exactly do you expect this thread to wait for itself to stop?? jassert (getThreadId() != getCurrentThreadId() || getCurrentThreadId() == 0); const uint32 timeoutEnd = Time::getMillisecondCounter() + (uint32) timeOutMilliseconds; while (isThreadRunning()) { if (timeOutMilliseconds >= 0 && Time::getMillisecondCounter() > timeoutEnd) return false; sleep (2); } return true; } void Thread::stopThread (const int timeOutMilliseconds) { // agh! You can't stop the thread that's calling this method! How on earth // would that work?? jassert (getCurrentThreadId() != getThreadId()); const ScopedLock sl (startStopLock); if (isThreadRunning()) { signalThreadShouldExit(); notify(); if (timeOutMilliseconds != 0) waitForThreadToExit (timeOutMilliseconds); if (isThreadRunning()) { // very bad karma if this point is reached, as there are bound to be // locks and events left in silly states when a thread is killed by force.. jassertfalse; Logger::writeToLog ("!! killing thread by force !!"); killThread(); threadHandle = nullptr; threadId = 0; } } } //============================================================================== bool Thread::setPriority (const int newPriority) { // NB: deadlock possible if you try to set the thread prio from the thread itself, // so using setCurrentThreadPriority instead in that case. if (getCurrentThreadId() == getThreadId()) return setCurrentThreadPriority (newPriority); const ScopedLock sl (startStopLock); if (setThreadPriority (threadHandle, newPriority)) { threadPriority = newPriority; return true; } return false; } bool Thread::setCurrentThreadPriority (const int newPriority) { return setThreadPriority (0, newPriority); } void Thread::setAffinityMask (const uint32 newAffinityMask) { affinityMask = newAffinityMask; } //============================================================================== bool Thread::wait (const int timeOutMilliseconds) const { return defaultEvent.wait (timeOutMilliseconds); } void Thread::notify() const { defaultEvent.signal(); } //============================================================================== void SpinLock::enter() const noexcept { if (! tryEnter()) { for (int i = 20; --i >= 0;) if (tryEnter()) return; while (! tryEnter()) Thread::yield(); } } //============================================================================== #if JUCE_UNIT_TESTS class AtomicTests : public UnitTest { public: AtomicTests() : UnitTest ("Atomics") {} void runTest() { beginTest ("Misc"); char a1[7]; expect (numElementsInArray(a1) == 7); int a2[3]; expect (numElementsInArray(a2) == 3); expect (ByteOrder::swap ((uint16) 0x1122) == 0x2211); expect (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211); expect (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211)); beginTest ("Atomic int"); AtomicTester <int>::testInteger (*this); beginTest ("Atomic unsigned int"); AtomicTester <unsigned int>::testInteger (*this); beginTest ("Atomic int32"); AtomicTester <int32>::testInteger (*this); beginTest ("Atomic uint32"); AtomicTester <uint32>::testInteger (*this); beginTest ("Atomic long"); AtomicTester <long>::testInteger (*this); beginTest ("Atomic void*"); AtomicTester <void*>::testInteger (*this); beginTest ("Atomic int*"); AtomicTester <int*>::testInteger (*this); beginTest ("Atomic float"); AtomicTester <float>::testFloat (*this); #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms beginTest ("Atomic int64"); AtomicTester <int64>::testInteger (*this); beginTest ("Atomic uint64"); AtomicTester <uint64>::testInteger (*this); beginTest ("Atomic double"); AtomicTester <double>::testFloat (*this); #endif } template <typename Type> class AtomicTester { public: AtomicTester() {} static void testInteger (UnitTest& test) { Atomic<Type> a, b; a.set ((Type) 10); test.expect (a.value == (Type) 10); test.expect (a.get() == (Type) 10); a += (Type) 15; test.expect (a.get() == (Type) 25); a.memoryBarrier(); a -= (Type) 5; test.expect (a.get() == (Type) 20); test.expect (++a == (Type) 21); ++a; test.expect (--a == (Type) 21); test.expect (a.get() == (Type) 21); a.memoryBarrier(); testFloat (test); } static void testFloat (UnitTest& test) { Atomic<Type> a, b; a = (Type) 21; a.memoryBarrier(); /* These are some simple test cases to check the atomics - let me know if any of these assertions fail on your system! */ test.expect (a.get() == (Type) 21); test.expect (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21); test.expect (a.get() == (Type) 21); test.expect (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21); test.expect (a.get() == (Type) 101); test.expect (! a.compareAndSetBool ((Type) 300, (Type) 200)); test.expect (a.get() == (Type) 101); test.expect (a.compareAndSetBool ((Type) 200, a.get())); test.expect (a.get() == (Type) 200); test.expect (a.exchange ((Type) 300) == (Type) 200); test.expect (a.get() == (Type) 300); b = a; test.expect (b.get() == a.get()); } }; }; static AtomicTests atomicUnitTests; #endif
teragonaudio/Arooo
JuceLibraryCode/modules/juce_core/threads/juce_Thread.cpp
C++
gpl-2.0
11,061
<?php /* vim: set expandtab sw=4 ts=4 sts=4: */ /** * Core functions used all over the scripts. * This script is distinct from libraries/common.inc.php because this * script is called from /test. * * @package PhpMyAdmin */ use PMA\libraries\Message; use PMA\libraries\URL; use PMA\libraries\Sanitize; if (! defined('PHPMYADMIN')) { exit; } /** * String handling (security) */ require_once 'libraries/string.lib.php'; /** * checks given $var and returns it if valid, or $default of not valid * given $var is also checked for type being 'similar' as $default * or against any other type if $type is provided * * <code> * // $_REQUEST['db'] not set * echo PMA_ifSetOr($_REQUEST['db'], ''); // '' * // $_REQUEST['sql_query'] not set * echo PMA_ifSetOr($_REQUEST['sql_query']); // null * // $cfg['EnableFoo'] not set * echo PMA_ifSetOr($cfg['EnableFoo'], false, 'boolean'); // false * echo PMA_ifSetOr($cfg['EnableFoo']); // null * // $cfg['EnableFoo'] set to 1 * echo PMA_ifSetOr($cfg['EnableFoo'], false, 'boolean'); // false * echo PMA_ifSetOr($cfg['EnableFoo'], false, 'similar'); // 1 * echo PMA_ifSetOr($cfg['EnableFoo'], false); // 1 * // $cfg['EnableFoo'] set to true * echo PMA_ifSetOr($cfg['EnableFoo'], false, 'boolean'); // true * </code> * * @param mixed &$var param to check * @param mixed $default default value * @param mixed $type var type or array of values to check against $var * * @return mixed $var or $default * * @see PMA_isValid() */ function PMA_ifSetOr(&$var, $default = null, $type = 'similar') { if (! PMA_isValid($var, $type, $default)) { return $default; } return $var; } /** * checks given $var against $type or $compare * * $type can be: * - false : no type checking * - 'scalar' : whether type of $var is integer, float, string or boolean * - 'numeric' : whether type of $var is any number representation * - 'length' : whether type of $var is scalar with a string length > 0 * - 'similar' : whether type of $var is similar to type of $compare * - 'equal' : whether type of $var is identical to type of $compare * - 'identical' : whether $var is identical to $compare, not only the type! * - or any other valid PHP variable type * * <code> * // $_REQUEST['doit'] = true; * PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // false * // $_REQUEST['doit'] = 'true'; * PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // true * </code> * * NOTE: call-by-reference is used to not get NOTICE on undefined vars, * but the var is not altered inside this function, also after checking a var * this var exists nut is not set, example: * <code> * // $var is not set * isset($var); // false * functionCallByReference($var); // false * isset($var); // true * functionCallByReference($var); // true * </code> * * to avoid this we set this var to null if not isset * * @param mixed &$var variable to check * @param mixed $type var type or array of valid values to check against $var * @param mixed $compare var to compare with $var * * @return boolean whether valid or not * * @todo add some more var types like hex, bin, ...? * @see http://php.net/gettype */ function PMA_isValid(&$var, $type = 'length', $compare = null) { if (! isset($var)) { // var is not even set return false; } if ($type === false) { // no vartype requested return true; } if (is_array($type)) { return in_array($var, $type); } // allow some aliases of var types $type = strtolower($type); switch ($type) { case 'identic' : $type = 'identical'; break; case 'len' : $type = 'length'; break; case 'bool' : $type = 'boolean'; break; case 'float' : $type = 'double'; break; case 'int' : $type = 'integer'; break; case 'null' : $type = 'NULL'; break; } if ($type === 'identical') { return $var === $compare; } // whether we should check against given $compare if ($type === 'similar') { switch (gettype($compare)) { case 'string': case 'boolean': $type = 'scalar'; break; case 'integer': case 'double': $type = 'numeric'; break; default: $type = gettype($compare); } } elseif ($type === 'equal') { $type = gettype($compare); } // do the check if ($type === 'length' || $type === 'scalar') { $is_scalar = is_scalar($var); if ($is_scalar && $type === 'length') { return (bool) mb_strlen($var); } return $is_scalar; } if ($type === 'numeric') { return is_numeric($var); } if (gettype($var) === $type) { return true; } return false; } /** * Removes insecure parts in a path; used before include() or * require() when a part of the path comes from an insecure source * like a cookie or form. * * @param string $path The path to check * * @return string The secured path * * @access public */ function PMA_securePath($path) { // change .. to . $path = preg_replace('@\.\.*@', '.', $path); return $path; } // end function /** * displays the given error message on phpMyAdmin error page in foreign language, * ends script execution and closes session * * loads language file if not loaded already * * @param string $error_message the error message or named error message * @param string|array $message_args arguments applied to $error_message * @param boolean $delete_session whether to delete session cookie * * @return void */ function PMA_fatalError( $error_message, $message_args = null, $delete_session = true ) { /* Use format string if applicable */ if (is_string($message_args)) { $error_message = sprintf($error_message, $message_args); } elseif (is_array($message_args)) { $error_message = vsprintf($error_message, $message_args); } if (! empty($GLOBALS['is_ajax_request']) && $GLOBALS['is_ajax_request']) { $response = PMA\libraries\Response::getInstance(); $response->setRequestStatus(false); $response->addJSON('message', PMA\libraries\Message::error($error_message)); } else { $error_message = strtr($error_message, array('<br />' => '[br]')); // these variables are used in the included file libraries/error.inc.php //first check if php-mbstring is available if (function_exists('mb_detect_encoding')) { //If present use gettext $error_header = __('Error'); } else { $error_header = 'Error'; } $lang = $GLOBALS['lang']; $dir = $GLOBALS['text_dir']; // on fatal errors it cannot hurt to always delete the current session if ($delete_session && isset($GLOBALS['session_name']) && isset($_COOKIE[$GLOBALS['session_name']]) ) { $GLOBALS['PMA_Config']->removeCookie($GLOBALS['session_name']); } // Displays the error message include './libraries/error.inc.php'; } if (! defined('TESTSUITE')) { exit; } } /** * Returns a link to the PHP documentation * * @param string $target anchor in documentation * * @return string the URL * * @access public */ function PMA_getPHPDocLink($target) { /* List of PHP documentation translations */ $php_doc_languages = array( 'pt_BR', 'zh', 'fr', 'de', 'it', 'ja', 'pl', 'ro', 'ru', 'fa', 'es', 'tr' ); $lang = 'en'; if (in_array($GLOBALS['lang'], $php_doc_languages)) { $lang = $GLOBALS['lang']; } return PMA_linkURL('http://php.net/manual/' . $lang . '/' . $target); } /** * Warn or fail on missing extension. * * @param string $extension Extension name * @param bool $fatal Whether the error is fatal. * @param string $extra Extra string to append to message. * * @return void */ function PMA_warnMissingExtension($extension, $fatal = false, $extra = '') { /* Gettext does not have to be loaded yet here */ if (function_exists('__')) { $message = __( 'The %s extension is missing. Please check your PHP configuration.' ); } else { $message = 'The %s extension is missing. Please check your PHP configuration.'; } $doclink = PMA_getPHPDocLink('book.' . $extension . '.php'); $message = sprintf( $message, '[a@' . $doclink . '@Documentation][em]' . $extension . '[/em][/a]' ); if ($extra != '') { $message .= ' ' . $extra; } if ($fatal) { PMA_fatalError($message); return; } $GLOBALS['error_handler']->addError( $message, E_USER_WARNING, '', '', false ); } /** * returns count of tables in given db * * @param string $db database to count tables for * * @return integer count of tables in $db */ function PMA_getTableCount($db) { $tables = $GLOBALS['dbi']->tryQuery( 'SHOW TABLES FROM ' . PMA\libraries\Util::backquote($db) . ';', null, PMA\libraries\DatabaseInterface::QUERY_STORE ); if ($tables) { $num_tables = $GLOBALS['dbi']->numRows($tables); $GLOBALS['dbi']->freeResult($tables); } else { $num_tables = 0; } return $num_tables; } /** * Converts numbers like 10M into bytes * Used with permission from Moodle (http://moodle.org) by Martin Dougiamas * (renamed with PMA prefix to avoid double definition when embedded * in Moodle) * * @param string|int $size size (Default = 0) * * @return integer $size */ function PMA_getRealSize($size = 0) { if (! $size) { return 0; } $scan = array( 'gb' => 1073741824, //1024 * 1024 * 1024, 'g' => 1073741824, //1024 * 1024 * 1024, 'mb' => 1048576, 'm' => 1048576, 'kb' => 1024, 'k' => 1024, 'b' => 1, ); foreach ($scan as $unit => $factor) { $sizeLength = strlen($size); $unitLength = strlen($unit); if ($sizeLength > $unitLength && strtolower( substr( $size, $sizeLength - $unitLength ) ) == $unit ) { return substr( $size, 0, $sizeLength - $unitLength ) * $factor; } } return $size; } // end function PMA_getRealSize() /** * boolean phpMyAdmin.PMA_checkPageValidity(string &$page, array $whitelist) * * checks given $page against given $whitelist and returns true if valid * it optionally ignores query parameters in $page (script.php?ignored) * * @param string &$page page to check * @param array $whitelist whitelist to check page against * * @return boolean whether $page is valid or not (in $whitelist or not) */ function PMA_checkPageValidity(&$page, $whitelist) { if (! isset($page) || !is_string($page)) { return false; } if (in_array($page, $whitelist)) { return true; } $_page = mb_substr( $page, 0, mb_strpos($page . '?', '?') ); if (in_array($_page, $whitelist)) { return true; } $_page = urldecode($page); $_page = mb_substr( $_page, 0, mb_strpos($_page . '?', '?') ); if (in_array($_page, $whitelist)) { return true; } return false; } /** * tries to find the value for the given environment variable name * * searches in $_SERVER, $_ENV then tries getenv() and apache_getenv() * in this order * * @param string $var_name variable name * * @return string value of $var or empty string */ function PMA_getenv($var_name) { if (isset($_SERVER[$var_name])) { return $_SERVER[$var_name]; } if (isset($_ENV[$var_name])) { return $_ENV[$var_name]; } if (getenv($var_name)) { return getenv($var_name); } if (function_exists('apache_getenv') && apache_getenv($var_name, true) ) { return apache_getenv($var_name, true); } return ''; } /** * Send HTTP header, taking IIS limits into account (600 seems ok) * * @param string $uri the header to send * @param bool $use_refresh whether to use Refresh: header when running on IIS * * @return void */ function PMA_sendHeaderLocation($uri, $use_refresh = false) { if ($GLOBALS['PMA_Config']->get('PMA_IS_IIS') && mb_strlen($uri) > 600) { PMA\libraries\Response::getInstance()->disable(); echo PMA\libraries\Template::get('header_location') ->render(array('uri' => $uri)); return; } $response = PMA\libraries\Response::getInstance(); if (SID) { if (mb_strpos($uri, '?') === false) { $response->header('Location: ' . $uri . '?' . SID); } else { $separator = URL::getArgSeparator(); $response->header('Location: ' . $uri . $separator . SID); } return; } session_write_close(); if ($response->headersSent()) { if (function_exists('debug_print_backtrace')) { echo '<pre>'; debug_print_backtrace(); echo '</pre>'; } trigger_error( 'PMA_sendHeaderLocation called when headers are already sent!', E_USER_ERROR ); } // bug #1523784: IE6 does not like 'Refresh: 0', it // results in a blank page // but we need it when coming from the cookie login panel) if ($GLOBALS['PMA_Config']->get('PMA_IS_IIS') && $use_refresh) { $response->header('Refresh: 0; ' . $uri); } else { $response->header('Location: ' . $uri); } } /** * Outputs application/json headers. This includes no caching. * * @return void */ function PMA_headerJSON() { if (defined('TESTSUITE') && ! defined('PMA_TEST_HEADERS')) { return; } // No caching PMA_noCacheHeader(); // MIME type header('Content-Type: application/json; charset=UTF-8'); // Disable content sniffing in browser // This is needed in case we include HTML in JSON, browser might assume it's // html to display header('X-Content-Type-Options: nosniff'); } /** * Outputs headers to prevent caching in browser (and on the way). * * @return void */ function PMA_noCacheHeader() { if (defined('TESTSUITE') && ! defined('PMA_TEST_HEADERS')) { return; } // rfc2616 - Section 14.21 header('Expires: ' . date(DATE_RFC1123)); // HTTP/1.1 header( 'Cache-Control: no-store, no-cache, must-revalidate,' . ' pre-check=0, post-check=0, max-age=0' ); header('Pragma: no-cache'); // HTTP/1.0 // test case: exporting a database into a .gz file with Safari // would produce files not having the current time // (added this header for Safari but should not harm other browsers) header('Last-Modified: ' . date(DATE_RFC1123)); } /** * Sends header indicating file download. * * @param string $filename Filename to include in headers if empty, * none Content-Disposition header will be sent. * @param string $mimetype MIME type to include in headers. * @param int $length Length of content (optional) * @param bool $no_cache Whether to include no-caching headers. * * @return void */ function PMA_downloadHeader($filename, $mimetype, $length = 0, $no_cache = true) { if ($no_cache) { PMA_noCacheHeader(); } /* Replace all possibly dangerous chars in filename */ $filename = str_replace(array(';', '"', "\n", "\r"), '-', $filename); if (!empty($filename)) { header('Content-Description: File Transfer'); header('Content-Disposition: attachment; filename="' . $filename . '"'); } header('Content-Type: ' . $mimetype); // inform the server that compression has been done, // to avoid a double compression (for example with Apache + mod_deflate) $notChromeOrLessThan43 = PMA_USR_BROWSER_AGENT != 'CHROME' // see bug #4942 || (PMA_USR_BROWSER_AGENT == 'CHROME' && PMA_USR_BROWSER_VER < 43); if (strpos($mimetype, 'gzip') !== false && $notChromeOrLessThan43) { header('Content-Encoding: gzip'); } header('Content-Transfer-Encoding: binary'); if ($length > 0) { header('Content-Length: ' . $length); } } /** * Returns value of an element in $array given by $path. * $path is a string describing position of an element in an associative array, * eg. Servers/1/host refers to $array[Servers][1][host] * * @param string $path path in the array * @param array $array the array * @param mixed $default default value * * @return mixed array element or $default */ function PMA_arrayRead($path, $array, $default = null) { $keys = explode('/', $path); $value =& $array; foreach ($keys as $key) { if (! isset($value[$key])) { return $default; } $value =& $value[$key]; } return $value; } /** * Stores value in an array * * @param string $path path in the array * @param array &$array the array * @param mixed $value value to store * * @return void */ function PMA_arrayWrite($path, &$array, $value) { $keys = explode('/', $path); $last_key = array_pop($keys); $a =& $array; foreach ($keys as $key) { if (! isset($a[$key])) { $a[$key] = array(); } $a =& $a[$key]; } $a[$last_key] = $value; } /** * Removes value from an array * * @param string $path path in the array * @param array &$array the array * * @return void */ function PMA_arrayRemove($path, &$array) { $keys = explode('/', $path); $keys_last = array_pop($keys); $path = array(); $depth = 0; $path[0] =& $array; $found = true; // go as deep as required or possible foreach ($keys as $key) { if (! isset($path[$depth][$key])) { $found = false; break; } $depth++; $path[$depth] =& $path[$depth - 1][$key]; } // if element found, remove it if ($found) { unset($path[$depth][$keys_last]); $depth--; } // remove empty nested arrays for (; $depth >= 0; $depth--) { if (! isset($path[$depth+1]) || count($path[$depth+1]) == 0) { unset($path[$depth][$keys[$depth]]); } else { break; } } } /** * Returns link to (possibly) external site using defined redirector. * * @param string $url URL where to go. * * @return string URL for a link. */ function PMA_linkURL($url) { if (!preg_match('#^https?://#', $url) || defined('PMA_SETUP')) { return $url; } $params = array(); $params['url'] = $url; $url = URL::getCommon($params); //strip off token and such sensitive information. Just keep url. $arr = parse_url($url); parse_str($arr["query"], $vars); $query = http_build_query(array("url" => $vars["url"])); $url = './url.php?' . $query; return $url; } /** * Checks whether domain of URL is whitelisted domain or not. * Use only for URLs of external sites. * * @param string $url URL of external site. * * @return boolean True: if domain of $url is allowed domain, * False: otherwise. */ function PMA_isAllowedDomain($url) { $arr = parse_url($url); $domain = $arr["host"]; $domainWhiteList = array( /* Include current domain */ $_SERVER['SERVER_NAME'], /* phpMyAdmin domains */ 'wiki.phpmyadmin.net', 'www.phpmyadmin.net', 'phpmyadmin.net', 'docs.phpmyadmin.net', /* mysql.com domains */ 'dev.mysql.com','bugs.mysql.com', /* mariadb domains */ 'mariadb.org', /* php.net domains */ 'php.net', /* Github domains*/ 'github.com','www.github.com', /* Following are doubtful ones. */ 'www.primebase.com', 'pbxt.blogspot.com', 'www.percona.com', 'mysqldatabaseadministration.blogspot.com', 'ronaldbradford.com', 'xaprb.com', ); if (in_array(mb_strtolower($domain), $domainWhiteList)) { return true; } return false; } /** * Adds JS code snippets to be displayed by the PMA\libraries\Response class. * Adds a newline to each snippet. * * @param string $str Js code to be added (e.g. "token=1234;") * * @return void */ function PMA_addJSCode($str) { $response = PMA\libraries\Response::getInstance(); $header = $response->getHeader(); $scripts = $header->getScripts(); $scripts->addCode($str); } /** * Adds JS code snippet for variable assignment * to be displayed by the PMA\libraries\Response class. * * @param string $key Name of value to set * @param mixed $value Value to set, can be either string or array of strings * @param bool $escape Whether to escape value or keep it as it is * (for inclusion of js code) * * @return void */ function PMA_addJSVar($key, $value, $escape = true) { PMA_addJSCode(Sanitize::getJsValue($key, $value, $escape)); } /** * Replace some html-unfriendly stuff * * @param string $buffer String to process * * @return string Escaped and cleaned up text suitable for html */ function PMA_mimeDefaultFunction($buffer) { $buffer = htmlspecialchars($buffer); $buffer = str_replace(' ', ' &nbsp;', $buffer); $buffer = preg_replace("@((\015\012)|(\015)|(\012))@", '<br />' . "\n", $buffer); return $buffer; } /** * Displays SQL query before executing. * * @param array|string $query_data Array containing queries or query itself * * @return void */ function PMA_previewSQL($query_data) { $retval = '<div class="preview_sql">'; if (empty($query_data)) { $retval .= __('No change'); } elseif (is_array($query_data)) { foreach ($query_data as $query) { $retval .= PMA\libraries\Util::formatSql($query); } } else { $retval .= PMA\libraries\Util::formatSql($query_data); } $retval .= '</div>'; $response = PMA\libraries\Response::getInstance(); $response->addJSON('sql_data', $retval); exit; } /** * recursively check if variable is empty * * @param mixed $value the variable * * @return bool true if empty */ function PMA_emptyRecursive($value) { $empty = true; if (is_array($value)) { array_walk_recursive( $value, function ($item) use (&$empty) { $empty = $empty && empty($item); } ); } else { $empty = empty($value); } return $empty; } /** * Creates some globals from $_POST variables matching a pattern * * @param array $post_patterns The patterns to search for * * @return void */ function PMA_setPostAsGlobal($post_patterns) { foreach (array_keys($_POST) as $post_key) { foreach ($post_patterns as $one_post_pattern) { if (preg_match($one_post_pattern, $post_key)) { $GLOBALS[$post_key] = $_POST[$post_key]; } } } } /** * Creates some globals from $_REQUEST * * @param string $param db|table * * @return void */ function PMA_setGlobalDbOrTable($param) { $GLOBALS[$param] = ''; if (PMA_isValid($_REQUEST[$param])) { // can we strip tags from this? // only \ and / is not allowed in db names for MySQL $GLOBALS[$param] = $_REQUEST[$param]; $GLOBALS['url_params'][$param] = $GLOBALS[$param]; } } /** * PATH_INFO could be compromised if set, so remove it from PHP_SELF * and provide a clean PHP_SELF here * * @return void */ function PMA_cleanupPathInfo() { global $PMA_PHP_SELF, $_PATH_INFO; $PMA_PHP_SELF = PMA_getenv('PHP_SELF'); $_PATH_INFO = PMA_getenv('PATH_INFO'); if (! empty($_PATH_INFO) && ! empty($PMA_PHP_SELF)) { $path_info_pos = mb_strrpos($PMA_PHP_SELF, $_PATH_INFO); $pathLength = $path_info_pos + mb_strlen($_PATH_INFO); if ($pathLength === mb_strlen($PMA_PHP_SELF)) { $PMA_PHP_SELF = mb_substr($PMA_PHP_SELF, 0, $path_info_pos); } } $PMA_PHP_SELF = htmlspecialchars($PMA_PHP_SELF); } /** * Checks that required PHP extensions are there. * @return void */ function PMA_checkExtensions() { /** * Warning about mbstring. */ if (! function_exists('mb_detect_encoding')) { PMA_warnMissingExtension('mbstring', true); } /** * We really need this one! */ if (! function_exists('preg_replace')) { PMA_warnMissingExtension('pcre', true); } /** * JSON is required in several places. */ if (! function_exists('json_encode')) { PMA_warnMissingExtension('json', true); } } /* Compatibility with PHP < 5.6 */ if(! function_exists('hash_equals')) { /** * Timing attack safe string comparison * * @param string $a first string * @param string $b second string * * @return boolean whether they are equal */ function hash_equals($a, $b) { $ret = strlen($a) ^ strlen($b); $ret |= array_sum(unpack("C*", $a ^ $b)); return ! $ret; } }
zixtor/phpmyadmin
libraries/core.lib.php
PHP
gpl-2.0
25,508
/* * soc-dapm.c -- ALSA SoC Dynamic Audio Power Management * * Copyright 2005 Wolfson Microelectronics PLC. * Author: Liam Girdwood <lrg@slimlogic.co.uk> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * Features: * o Changes power status of internal codec blocks depending on the * dynamic configuration of codec internal audio paths and active * DACs/ADCs. * o Platform power domain - can support external components i.e. amps and * mic/headphone insertion events. * o Automatic Mic Bias support * o Jack insertion power event initiation - e.g. hp insertion will enable * sinks, dacs, etc * o Delayed power down of audio subsystem to reduce pops between a quick * device reopen. * */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/init.h> #include <linux/async.h> #include <linux/delay.h> #include <linux/pm.h> #include <linux/bitops.h> #include <linux/platform_device.h> #include <linux/jiffies.h> #include <linux/debugfs.h> #include <linux/pm_runtime.h> #include <linux/regulator/consumer.h> #include <linux/clk.h> #include <linux/slab.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/soc.h> #include <sound/initval.h> #include <trace/events/asoc.h> #define DAPM_UPDATE_STAT(widget, val) widget->dapm->card->dapm_stats.val++; #define SND_SOC_DAPM_DIR_REVERSE(x) ((x == SND_SOC_DAPM_DIR_IN) ? \ SND_SOC_DAPM_DIR_OUT : SND_SOC_DAPM_DIR_IN) #define snd_soc_dapm_for_each_direction(dir) \ for ((dir) = SND_SOC_DAPM_DIR_IN; (dir) <= SND_SOC_DAPM_DIR_OUT; \ (dir)++) static int snd_soc_dapm_add_path(struct snd_soc_dapm_context *dapm, struct snd_soc_dapm_widget *wsource, struct snd_soc_dapm_widget *wsink, const char *control, int (*connected)(struct snd_soc_dapm_widget *source, struct snd_soc_dapm_widget *sink)); struct snd_soc_dapm_widget * snd_soc_dapm_new_control(struct snd_soc_dapm_context *dapm, const struct snd_soc_dapm_widget *widget); struct snd_soc_dapm_widget * snd_soc_dapm_new_control_unlocked(struct snd_soc_dapm_context *dapm, const struct snd_soc_dapm_widget *widget); /* dapm power sequences - make this per codec in the future */ static int dapm_up_seq[] = { [snd_soc_dapm_pre] = 0, [snd_soc_dapm_regulator_supply] = 1, [snd_soc_dapm_clock_supply] = 1, [snd_soc_dapm_supply] = 2, [snd_soc_dapm_micbias] = 3, [snd_soc_dapm_dai_link] = 2, [snd_soc_dapm_dai_in] = 4, [snd_soc_dapm_dai_out] = 4, [snd_soc_dapm_aif_in] = 4, [snd_soc_dapm_aif_out] = 4, [snd_soc_dapm_mic] = 5, [snd_soc_dapm_mux] = 6, [snd_soc_dapm_demux] = 6, [snd_soc_dapm_dac] = 7, [snd_soc_dapm_switch] = 8, [snd_soc_dapm_mixer] = 8, [snd_soc_dapm_mixer_named_ctl] = 8, [snd_soc_dapm_pga] = 9, [snd_soc_dapm_adc] = 10, [snd_soc_dapm_out_drv] = 11, [snd_soc_dapm_hp] = 11, [snd_soc_dapm_spk] = 11, [snd_soc_dapm_line] = 11, [snd_soc_dapm_kcontrol] = 12, [snd_soc_dapm_post] = 13, }; static int dapm_down_seq[] = { [snd_soc_dapm_pre] = 0, [snd_soc_dapm_kcontrol] = 1, [snd_soc_dapm_adc] = 2, [snd_soc_dapm_hp] = 3, [snd_soc_dapm_spk] = 3, [snd_soc_dapm_line] = 3, [snd_soc_dapm_out_drv] = 3, [snd_soc_dapm_pga] = 4, [snd_soc_dapm_switch] = 5, [snd_soc_dapm_mixer_named_ctl] = 5, [snd_soc_dapm_mixer] = 5, [snd_soc_dapm_dac] = 6, [snd_soc_dapm_mic] = 7, [snd_soc_dapm_micbias] = 8, [snd_soc_dapm_mux] = 9, [snd_soc_dapm_demux] = 9, [snd_soc_dapm_aif_in] = 10, [snd_soc_dapm_aif_out] = 10, [snd_soc_dapm_dai_in] = 10, [snd_soc_dapm_dai_out] = 10, [snd_soc_dapm_dai_link] = 11, [snd_soc_dapm_supply] = 12, [snd_soc_dapm_clock_supply] = 13, [snd_soc_dapm_regulator_supply] = 13, [snd_soc_dapm_post] = 14, }; static void dapm_assert_locked(struct snd_soc_dapm_context *dapm) { if (dapm->card && dapm->card->instantiated) lockdep_assert_held(&dapm->card->dapm_mutex); } static void pop_wait(u32 pop_time) { if (pop_time) schedule_timeout_uninterruptible(msecs_to_jiffies(pop_time)); } static void pop_dbg(struct device *dev, u32 pop_time, const char *fmt, ...) { va_list args; char *buf; if (!pop_time) return; buf = kmalloc(PAGE_SIZE, GFP_KERNEL); if (buf == NULL) return; va_start(args, fmt); vsnprintf(buf, PAGE_SIZE, fmt, args); dev_info(dev, "%s", buf); va_end(args); kfree(buf); } static bool dapm_dirty_widget(struct snd_soc_dapm_widget *w) { return !list_empty(&w->dirty); } static void dapm_mark_dirty(struct snd_soc_dapm_widget *w, const char *reason) { dapm_assert_locked(w->dapm); if (!dapm_dirty_widget(w)) { dev_vdbg(w->dapm->dev, "Marking %s dirty due to %s\n", w->name, reason); list_add_tail(&w->dirty, &w->dapm->card->dapm_dirty); } } /* * Common implementation for dapm_widget_invalidate_input_paths() and * dapm_widget_invalidate_output_paths(). The function is inlined since the * combined size of the two specialized functions is only marginally larger then * the size of the generic function and at the same time the fast path of the * specialized functions is significantly smaller than the generic function. */ static __always_inline void dapm_widget_invalidate_paths( struct snd_soc_dapm_widget *w, enum snd_soc_dapm_direction dir) { enum snd_soc_dapm_direction rdir = SND_SOC_DAPM_DIR_REVERSE(dir); struct snd_soc_dapm_widget *node; struct snd_soc_dapm_path *p; LIST_HEAD(list); dapm_assert_locked(w->dapm); if (w->endpoints[dir] == -1) return; list_add_tail(&w->work_list, &list); w->endpoints[dir] = -1; list_for_each_entry(w, &list, work_list) { snd_soc_dapm_widget_for_each_path(w, dir, p) { if (p->is_supply || p->weak || !p->connect) continue; node = p->node[rdir]; if (node->endpoints[dir] != -1) { node->endpoints[dir] = -1; list_add_tail(&node->work_list, &list); } } } } /* * dapm_widget_invalidate_input_paths() - Invalidate the cached number of * input paths * @w: The widget for which to invalidate the cached number of input paths * * Resets the cached number of inputs for the specified widget and all widgets * that can be reached via outcoming paths from the widget. * * This function must be called if the number of output paths for a widget might * have changed. E.g. if the source state of a widget changes or a path is added * or activated with the widget as the sink. */ static void dapm_widget_invalidate_input_paths(struct snd_soc_dapm_widget *w) { dapm_widget_invalidate_paths(w, SND_SOC_DAPM_DIR_IN); } /* * dapm_widget_invalidate_output_paths() - Invalidate the cached number of * output paths * @w: The widget for which to invalidate the cached number of output paths * * Resets the cached number of outputs for the specified widget and all widgets * that can be reached via incoming paths from the widget. * * This function must be called if the number of output paths for a widget might * have changed. E.g. if the sink state of a widget changes or a path is added * or activated with the widget as the source. */ static void dapm_widget_invalidate_output_paths(struct snd_soc_dapm_widget *w) { dapm_widget_invalidate_paths(w, SND_SOC_DAPM_DIR_OUT); } /* * dapm_path_invalidate() - Invalidates the cached number of inputs and outputs * for the widgets connected to a path * @p: The path to invalidate * * Resets the cached number of inputs for the sink of the path and the cached * number of outputs for the source of the path. * * This function must be called when a path is added, removed or the connected * state changes. */ static void dapm_path_invalidate(struct snd_soc_dapm_path *p) { /* * Weak paths or supply paths do not influence the number of input or * output paths of their neighbors. */ if (p->weak || p->is_supply) return; /* * The number of connected endpoints is the sum of the number of * connected endpoints of all neighbors. If a node with 0 connected * endpoints is either connected or disconnected that sum won't change, * so there is no need to re-check the path. */ if (p->source->endpoints[SND_SOC_DAPM_DIR_IN] != 0) dapm_widget_invalidate_input_paths(p->sink); if (p->sink->endpoints[SND_SOC_DAPM_DIR_OUT] != 0) dapm_widget_invalidate_output_paths(p->source); } void dapm_mark_endpoints_dirty(struct snd_soc_card *card) { struct snd_soc_dapm_widget *w; mutex_lock(&card->dapm_mutex); list_for_each_entry(w, &card->widgets, list) { if (w->is_ep) { dapm_mark_dirty(w, "Rechecking endpoints"); if (w->is_ep & SND_SOC_DAPM_EP_SINK) dapm_widget_invalidate_output_paths(w); if (w->is_ep & SND_SOC_DAPM_EP_SOURCE) dapm_widget_invalidate_input_paths(w); } } mutex_unlock(&card->dapm_mutex); } EXPORT_SYMBOL_GPL(dapm_mark_endpoints_dirty); /* create a new dapm widget */ static inline struct snd_soc_dapm_widget *dapm_cnew_widget( const struct snd_soc_dapm_widget *_widget) { return kmemdup(_widget, sizeof(*_widget), GFP_KERNEL); } struct dapm_kcontrol_data { unsigned int value; struct snd_soc_dapm_widget *widget; struct list_head paths; struct snd_soc_dapm_widget_list *wlist; }; static int dapm_kcontrol_data_alloc(struct snd_soc_dapm_widget *widget, struct snd_kcontrol *kcontrol) { struct dapm_kcontrol_data *data; struct soc_mixer_control *mc; struct soc_enum *e; const char *name; int ret; data = kzalloc(sizeof(*data), GFP_KERNEL); if (!data) return -ENOMEM; INIT_LIST_HEAD(&data->paths); switch (widget->id) { case snd_soc_dapm_switch: case snd_soc_dapm_mixer: case snd_soc_dapm_mixer_named_ctl: mc = (struct soc_mixer_control *)kcontrol->private_value; if (mc->autodisable) { struct snd_soc_dapm_widget template; name = kasprintf(GFP_KERNEL, "%s %s", kcontrol->id.name, "Autodisable"); if (!name) { ret = -ENOMEM; goto err_data; } memset(&template, 0, sizeof(template)); template.reg = mc->reg; template.mask = (1 << fls(mc->max)) - 1; template.shift = mc->shift; if (mc->invert) template.off_val = mc->max; else template.off_val = 0; template.on_val = template.off_val; template.id = snd_soc_dapm_kcontrol; template.name = name; data->value = template.on_val; data->widget = snd_soc_dapm_new_control_unlocked(widget->dapm, &template); if (!data->widget) { ret = -ENOMEM; goto err_name; } } break; case snd_soc_dapm_demux: case snd_soc_dapm_mux: e = (struct soc_enum *)kcontrol->private_value; if (e->autodisable) { struct snd_soc_dapm_widget template; name = kasprintf(GFP_KERNEL, "%s %s", kcontrol->id.name, "Autodisable"); if (!name) { ret = -ENOMEM; goto err_data; } memset(&template, 0, sizeof(template)); template.reg = e->reg; template.mask = e->mask << e->shift_l; template.shift = e->shift_l; template.off_val = snd_soc_enum_item_to_val(e, 0); template.on_val = template.off_val; template.id = snd_soc_dapm_kcontrol; template.name = name; data->value = template.on_val; data->widget = snd_soc_dapm_new_control(widget->dapm, &template); if (!data->widget) { ret = -ENOMEM; goto err_name; } snd_soc_dapm_add_path(widget->dapm, data->widget, widget, NULL, NULL); } break; default: break; } kcontrol->private_data = data; return 0; err_name: kfree(name); err_data: kfree(data); return ret; } static void dapm_kcontrol_free(struct snd_kcontrol *kctl) { struct dapm_kcontrol_data *data = snd_kcontrol_chip(kctl); if (data->widget) kfree(data->widget->name); kfree(data->wlist); kfree(data); } static struct snd_soc_dapm_widget_list *dapm_kcontrol_get_wlist( const struct snd_kcontrol *kcontrol) { struct dapm_kcontrol_data *data = snd_kcontrol_chip(kcontrol); return data->wlist; } static int dapm_kcontrol_add_widget(struct snd_kcontrol *kcontrol, struct snd_soc_dapm_widget *widget) { struct dapm_kcontrol_data *data = snd_kcontrol_chip(kcontrol); struct snd_soc_dapm_widget_list *new_wlist; unsigned int n; if (data->wlist) n = data->wlist->num_widgets + 1; else n = 1; new_wlist = krealloc(data->wlist, sizeof(*new_wlist) + sizeof(widget) * n, GFP_KERNEL); if (!new_wlist) return -ENOMEM; new_wlist->widgets[n - 1] = widget; new_wlist->num_widgets = n; data->wlist = new_wlist; return 0; } static void dapm_kcontrol_add_path(const struct snd_kcontrol *kcontrol, struct snd_soc_dapm_path *path) { struct dapm_kcontrol_data *data = snd_kcontrol_chip(kcontrol); list_add_tail(&path->list_kcontrol, &data->paths); } static bool dapm_kcontrol_is_powered(const struct snd_kcontrol *kcontrol) { struct dapm_kcontrol_data *data = snd_kcontrol_chip(kcontrol); if (!data->widget) return true; return data->widget->power; } static struct list_head *dapm_kcontrol_get_path_list( const struct snd_kcontrol *kcontrol) { struct dapm_kcontrol_data *data = snd_kcontrol_chip(kcontrol); return &data->paths; } #define dapm_kcontrol_for_each_path(path, kcontrol) \ list_for_each_entry(path, dapm_kcontrol_get_path_list(kcontrol), \ list_kcontrol) unsigned int dapm_kcontrol_get_value(const struct snd_kcontrol *kcontrol) { struct dapm_kcontrol_data *data = snd_kcontrol_chip(kcontrol); return data->value; } EXPORT_SYMBOL_GPL(dapm_kcontrol_get_value); static bool dapm_kcontrol_set_value(const struct snd_kcontrol *kcontrol, unsigned int value) { struct dapm_kcontrol_data *data = snd_kcontrol_chip(kcontrol); if (data->value == value) return false; if (data->widget) data->widget->on_val = value; data->value = value; return true; } /** * snd_soc_dapm_kcontrol_widget() - Returns the widget associated to a * kcontrol * @kcontrol: The kcontrol */ struct snd_soc_dapm_widget *snd_soc_dapm_kcontrol_widget( struct snd_kcontrol *kcontrol) { return dapm_kcontrol_get_wlist(kcontrol)->widgets[0]; } EXPORT_SYMBOL_GPL(snd_soc_dapm_kcontrol_widget); /** * snd_soc_dapm_kcontrol_dapm() - Returns the dapm context associated to a * kcontrol * @kcontrol: The kcontrol * * Note: This function must only be used on kcontrols that are known to have * been registered for a CODEC. Otherwise the behaviour is undefined. */ struct snd_soc_dapm_context *snd_soc_dapm_kcontrol_dapm( struct snd_kcontrol *kcontrol) { return dapm_kcontrol_get_wlist(kcontrol)->widgets[0]->dapm; } EXPORT_SYMBOL_GPL(snd_soc_dapm_kcontrol_dapm); static void dapm_reset(struct snd_soc_card *card) { struct snd_soc_dapm_widget *w; lockdep_assert_held(&card->dapm_mutex); memset(&card->dapm_stats, 0, sizeof(card->dapm_stats)); list_for_each_entry(w, &card->widgets, list) { w->new_power = w->power; w->power_checked = false; } } static const char *soc_dapm_prefix(struct snd_soc_dapm_context *dapm) { if (!dapm->component) return NULL; return dapm->component->name_prefix; } static int soc_dapm_read(struct snd_soc_dapm_context *dapm, int reg, unsigned int *value) { if (!dapm->component) return -EIO; return snd_soc_component_read(dapm->component, reg, value); } static int soc_dapm_update_bits(struct snd_soc_dapm_context *dapm, int reg, unsigned int mask, unsigned int value) { if (!dapm->component) return -EIO; return snd_soc_component_update_bits(dapm->component, reg, mask, value); } static int soc_dapm_test_bits(struct snd_soc_dapm_context *dapm, int reg, unsigned int mask, unsigned int value) { if (!dapm->component) return -EIO; return snd_soc_component_test_bits(dapm->component, reg, mask, value); } static void soc_dapm_async_complete(struct snd_soc_dapm_context *dapm) { if (dapm->component) snd_soc_component_async_complete(dapm->component); } static struct snd_soc_dapm_widget * dapm_wcache_lookup(struct snd_soc_dapm_wcache *wcache, const char *name) { struct snd_soc_dapm_widget *w = wcache->widget; struct list_head *wlist; const int depth = 2; int i = 0; if (w) { wlist = &w->dapm->card->widgets; list_for_each_entry_from(w, wlist, list) { if (!strcmp(name, w->name)) return w; if (++i == depth) break; } } return NULL; } static inline void dapm_wcache_update(struct snd_soc_dapm_wcache *wcache, struct snd_soc_dapm_widget *w) { wcache->widget = w; } /** * snd_soc_dapm_force_bias_level() - Sets the DAPM bias level * @dapm: The DAPM context for which to set the level * @level: The level to set * * Forces the DAPM bias level to a specific state. It will call the bias level * callback of DAPM context with the specified level. This will even happen if * the context is already at the same level. Furthermore it will not go through * the normal bias level sequencing, meaning any intermediate states between the * current and the target state will not be entered. * * Note that the change in bias level is only temporary and the next time * snd_soc_dapm_sync() is called the state will be set to the level as * determined by the DAPM core. The function is mainly intended to be used to * used during probe or resume from suspend to power up the device so * initialization can be done, before the DAPM core takes over. */ int snd_soc_dapm_force_bias_level(struct snd_soc_dapm_context *dapm, enum snd_soc_bias_level level) { int ret = 0; if (dapm->set_bias_level) ret = dapm->set_bias_level(dapm, level); if (ret == 0) dapm->bias_level = level; return ret; } EXPORT_SYMBOL_GPL(snd_soc_dapm_force_bias_level); /** * snd_soc_dapm_set_bias_level - set the bias level for the system * @dapm: DAPM context * @level: level to configure * * Configure the bias (power) levels for the SoC audio device. * * Returns 0 for success else error. */ static int snd_soc_dapm_set_bias_level(struct snd_soc_dapm_context *dapm, enum snd_soc_bias_level level) { struct snd_soc_card *card = dapm->card; int ret = 0; trace_snd_soc_bias_level_start(card, level); if (card && card->set_bias_level) ret = card->set_bias_level(card, dapm, level); if (ret != 0) goto out; if (!card || dapm != &card->dapm) ret = snd_soc_dapm_force_bias_level(dapm, level); if (ret != 0) goto out; if (card && card->set_bias_level_post) ret = card->set_bias_level_post(card, dapm, level); out: trace_snd_soc_bias_level_done(card, level); return ret; } /* connect mux widget to its interconnecting audio paths */ static int dapm_connect_mux(struct snd_soc_dapm_context *dapm, struct snd_soc_dapm_path *path, const char *control_name, struct snd_soc_dapm_widget *w) { const struct snd_kcontrol_new *kcontrol = &w->kcontrol_news[0]; struct soc_enum *e = (struct soc_enum *)kcontrol->private_value; unsigned int val, item; int i; if (e->reg != SND_SOC_NOPM) { soc_dapm_read(dapm, e->reg, &val); val = (val >> e->shift_l) & e->mask; item = snd_soc_enum_val_to_item(e, val); } else { /* since a virtual mux has no backing registers to * decide which path to connect, it will try to match * with the first enumeration. This is to ensure * that the default mux choice (the first) will be * correctly powered up during initialization. */ item = 0; } for (i = 0; i < e->items; i++) { if (!(strcmp(control_name, e->texts[i]))) { path->name = e->texts[i]; if (i == item) path->connect = 1; else path->connect = 0; return 0; } } return -ENODEV; } /* set up initial codec paths */ static void dapm_set_mixer_path_status(struct snd_soc_dapm_path *p, int i) { struct soc_mixer_control *mc = (struct soc_mixer_control *) p->sink->kcontrol_news[i].private_value; unsigned int reg = mc->reg; unsigned int shift = mc->shift; unsigned int max = mc->max; unsigned int mask = (1 << fls(max)) - 1; unsigned int invert = mc->invert; unsigned int val; if (reg != SND_SOC_NOPM) { soc_dapm_read(p->sink->dapm, reg, &val); val = (val >> shift) & mask; if (invert) val = max - val; p->connect = !!val; } else { p->connect = 0; } } /* connect mixer widget to its interconnecting audio paths */ static int dapm_connect_mixer(struct snd_soc_dapm_context *dapm, struct snd_soc_dapm_path *path, const char *control_name) { int i; /* search for mixer kcontrol */ for (i = 0; i < path->sink->num_kcontrols; i++) { if (!strcmp(control_name, path->sink->kcontrol_news[i].name)) { path->name = path->sink->kcontrol_news[i].name; dapm_set_mixer_path_status(path, i); return 0; } } return -ENODEV; } static int dapm_is_shared_kcontrol(struct snd_soc_dapm_context *dapm, struct snd_soc_dapm_widget *kcontrolw, const struct snd_kcontrol_new *kcontrol_new, struct snd_kcontrol **kcontrol) { struct snd_soc_dapm_widget *w; int i; *kcontrol = NULL; list_for_each_entry(w, &dapm->card->widgets, list) { if (w == kcontrolw || w->dapm != kcontrolw->dapm) continue; for (i = 0; i < w->num_kcontrols; i++) { if (&w->kcontrol_news[i] == kcontrol_new) { if (w->kcontrols) *kcontrol = w->kcontrols[i]; return 1; } } } return 0; } /* * Determine if a kcontrol is shared. If it is, look it up. If it isn't, * create it. Either way, add the widget into the control's widget list */ static int dapm_create_or_share_kcontrol(struct snd_soc_dapm_widget *w, int kci) { struct snd_soc_dapm_context *dapm = w->dapm; struct snd_card *card = dapm->card->snd_card; const char *prefix; size_t prefix_len; int shared; struct snd_kcontrol *kcontrol; bool wname_in_long_name, kcname_in_long_name; char *long_name = NULL; const char *name; int ret = 0; prefix = soc_dapm_prefix(dapm); if (prefix) prefix_len = strlen(prefix) + 1; else prefix_len = 0; shared = dapm_is_shared_kcontrol(dapm, w, &w->kcontrol_news[kci], &kcontrol); if (!kcontrol) { if (shared) { wname_in_long_name = false; kcname_in_long_name = true; } else { switch (w->id) { case snd_soc_dapm_switch: case snd_soc_dapm_mixer: case snd_soc_dapm_pga: wname_in_long_name = true; kcname_in_long_name = true; break; case snd_soc_dapm_mixer_named_ctl: wname_in_long_name = false; kcname_in_long_name = true; break; case snd_soc_dapm_demux: case snd_soc_dapm_mux: wname_in_long_name = true; kcname_in_long_name = false; break; default: return -EINVAL; } } if (wname_in_long_name && kcname_in_long_name) { /* * The control will get a prefix from the control * creation process but we're also using the same * prefix for widgets so cut the prefix off the * front of the widget name. */ long_name = kasprintf(GFP_KERNEL, "%s %s", w->name + prefix_len, w->kcontrol_news[kci].name); if (long_name == NULL) return -ENOMEM; name = long_name; } else if (wname_in_long_name) { long_name = NULL; name = w->name + prefix_len; } else { long_name = NULL; name = w->kcontrol_news[kci].name; } kcontrol = snd_soc_cnew(&w->kcontrol_news[kci], NULL, name, prefix); if (!kcontrol) { ret = -ENOMEM; goto exit_free; } kcontrol->private_free = dapm_kcontrol_free; ret = dapm_kcontrol_data_alloc(w, kcontrol); if (ret) { snd_ctl_free_one(kcontrol); goto exit_free; } ret = snd_ctl_add(card, kcontrol); if (ret < 0) { dev_err(dapm->dev, "ASoC: failed to add widget %s dapm kcontrol %s: %d\n", w->name, name, ret); goto exit_free; } } ret = dapm_kcontrol_add_widget(kcontrol, w); if (ret == 0) w->kcontrols[kci] = kcontrol; exit_free: kfree(long_name); return ret; } /* create new dapm mixer control */ static int dapm_new_mixer(struct snd_soc_dapm_widget *w) { int i, ret; struct snd_soc_dapm_path *path; struct dapm_kcontrol_data *data; /* add kcontrol */ for (i = 0; i < w->num_kcontrols; i++) { /* match name */ snd_soc_dapm_widget_for_each_source_path(w, path) { /* mixer/mux paths name must match control name */ if (path->name != (char *)w->kcontrol_news[i].name) continue; if (!w->kcontrols[i]) { ret = dapm_create_or_share_kcontrol(w, i); if (ret < 0) return ret; } dapm_kcontrol_add_path(w->kcontrols[i], path); data = snd_kcontrol_chip(w->kcontrols[i]); if (data->widget) snd_soc_dapm_add_path(data->widget->dapm, data->widget, path->source, NULL, NULL); } } return 0; } /* create new dapm mux control */ static int dapm_new_mux(struct snd_soc_dapm_widget *w) { struct snd_soc_dapm_context *dapm = w->dapm; enum snd_soc_dapm_direction dir; struct snd_soc_dapm_path *path; const char *type; int ret; switch (w->id) { case snd_soc_dapm_mux: dir = SND_SOC_DAPM_DIR_OUT; type = "mux"; break; case snd_soc_dapm_demux: dir = SND_SOC_DAPM_DIR_IN; type = "demux"; break; default: return -EINVAL; } if (w->num_kcontrols != 1) { dev_err(dapm->dev, "ASoC: %s %s has incorrect number of controls\n", type, w->name); return -EINVAL; } if (list_empty(&w->edges[dir])) { dev_err(dapm->dev, "ASoC: %s %s has no paths\n", type, w->name); return -EINVAL; } ret = dapm_create_or_share_kcontrol(w, 0); if (ret < 0) return ret; snd_soc_dapm_widget_for_each_path(w, dir, path) { if (path->name) dapm_kcontrol_add_path(w->kcontrols[0], path); } return 0; } /* create new dapm volume control */ static int dapm_new_pga(struct snd_soc_dapm_widget *w) { int i, ret; for (i = 0; i < w->num_kcontrols; i++) { ret = dapm_create_or_share_kcontrol(w, i); if (ret < 0) return ret; } return 0; } /* create new dapm dai link control */ static int dapm_new_dai_link(struct snd_soc_dapm_widget *w) { int i, ret; struct snd_kcontrol *kcontrol; struct snd_soc_dapm_context *dapm = w->dapm; struct snd_card *card = dapm->card->snd_card; /* create control for links with > 1 config */ if (w->num_params <= 1) return 0; /* add kcontrol */ for (i = 0; i < w->num_kcontrols; i++) { kcontrol = snd_soc_cnew(&w->kcontrol_news[i], w, w->name, NULL); ret = snd_ctl_add(card, kcontrol); if (ret < 0) { dev_err(dapm->dev, "ASoC: failed to add widget %s dapm kcontrol %s: %d\n", w->name, w->kcontrol_news[i].name, ret); return ret; } kcontrol->private_data = w; w->kcontrols[i] = kcontrol; } return 0; } /* We implement power down on suspend by checking the power state of * the ALSA card - when we are suspending the ALSA state for the card * is set to D3. */ static int snd_soc_dapm_suspend_check(struct snd_soc_dapm_widget *widget) { int level = snd_power_get_state(widget->dapm->card->snd_card); switch (level) { case SNDRV_CTL_POWER_D3hot: case SNDRV_CTL_POWER_D3cold: if (widget->ignore_suspend) dev_dbg(widget->dapm->dev, "ASoC: %s ignoring suspend\n", widget->name); return widget->ignore_suspend; default: return 1; } } static int dapm_widget_list_create(struct snd_soc_dapm_widget_list **list, struct list_head *widgets) { struct snd_soc_dapm_widget *w; struct list_head *it; unsigned int size = 0; unsigned int i = 0; list_for_each(it, widgets) size++; *list = kzalloc(sizeof(**list) + size * sizeof(*w), GFP_KERNEL); if (*list == NULL) return -ENOMEM; list_for_each_entry(w, widgets, work_list) (*list)->widgets[i++] = w; (*list)->num_widgets = i; return 0; } static void trace_snd_soc_dapm_path(struct snd_soc_dapm_widget *w, enum snd_soc_dapm_direction dir, struct snd_soc_dapm_path *p) { if (dir == SND_SOC_DAPM_DIR_IN) trace_snd_soc_dapm_input_path(w, p); else trace_snd_soc_dapm_output_path(w, p); } /* * Common implementation for is_connected_output_ep() and * is_connected_input_ep(). The function is inlined since the combined size of * the two specialized functions is only marginally larger then the size of the * generic function and at the same time the fast path of the specialized * functions is significantly smaller than the generic function. */ static __always_inline int is_connected_ep(struct snd_soc_dapm_widget *widget, struct list_head *list, enum snd_soc_dapm_direction dir, int (*fn)(struct snd_soc_dapm_widget *, struct list_head *)) { enum snd_soc_dapm_direction rdir = SND_SOC_DAPM_DIR_REVERSE(dir); struct snd_soc_dapm_path *path; int con = 0; if (widget->endpoints[dir] >= 0) return widget->endpoints[dir]; DAPM_UPDATE_STAT(widget, path_checks); /* do we need to add this widget to the list ? */ if (list) list_add_tail(&widget->work_list, list); if ((widget->is_ep & SND_SOC_DAPM_DIR_TO_EP(dir)) && widget->connected) { widget->endpoints[dir] = snd_soc_dapm_suspend_check(widget); return widget->endpoints[dir]; } snd_soc_dapm_widget_for_each_path(widget, rdir, path) { DAPM_UPDATE_STAT(widget, neighbour_checks); if (path->weak || path->is_supply) continue; if (path->walking) return 1; trace_snd_soc_dapm_path(widget, dir, path); if (path->connect) { path->walking = 1; con += fn(path->node[dir], list); path->walking = 0; } } widget->endpoints[dir] = con; return con; } /* * Recursively check for a completed path to an active or physically connected * output widget. Returns number of complete paths. */ static int is_connected_output_ep(struct snd_soc_dapm_widget *widget, struct list_head *list) { return is_connected_ep(widget, list, SND_SOC_DAPM_DIR_OUT, is_connected_output_ep); } /* * Recursively check for a completed path to an active or physically connected * input widget. Returns number of complete paths. */ static int is_connected_input_ep(struct snd_soc_dapm_widget *widget, struct list_head *list) { return is_connected_ep(widget, list, SND_SOC_DAPM_DIR_IN, is_connected_input_ep); } /** * snd_soc_dapm_get_connected_widgets - query audio path and it's widgets. * @dai: the soc DAI. * @stream: stream direction. * @list: list of active widgets for this stream. * * Queries DAPM graph as to whether an valid audio stream path exists for * the initial stream specified by name. This takes into account * current mixer and mux kcontrol settings. Creates list of valid widgets. * * Returns the number of valid paths or negative error. */ int snd_soc_dapm_dai_get_connected_widgets(struct snd_soc_dai *dai, int stream, struct snd_soc_dapm_widget_list **list) { struct snd_soc_card *card = dai->component->card; struct snd_soc_dapm_widget *w; LIST_HEAD(widgets); int paths; int ret; mutex_lock_nested(&card->dapm_mutex, SND_SOC_DAPM_CLASS_RUNTIME); /* * For is_connected_{output,input}_ep fully discover the graph we need * to reset the cached number of inputs and outputs. */ list_for_each_entry(w, &card->widgets, list) { w->endpoints[SND_SOC_DAPM_DIR_IN] = -1; w->endpoints[SND_SOC_DAPM_DIR_OUT] = -1; } if (stream == SNDRV_PCM_STREAM_PLAYBACK) paths = is_connected_output_ep(dai->playback_widget, &widgets); else paths = is_connected_input_ep(dai->capture_widget, &widgets); /* Drop starting point */ list_del(widgets.next); ret = dapm_widget_list_create(list, &widgets); if (ret) return ret; trace_snd_soc_dapm_connected(paths, stream); mutex_unlock(&card->dapm_mutex); return paths; } /* * Handler for regulator supply widget. */ int dapm_regulator_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { int ret; soc_dapm_async_complete(w->dapm); if (SND_SOC_DAPM_EVENT_ON(event)) { if (w->on_val & SND_SOC_DAPM_REGULATOR_BYPASS) { ret = regulator_allow_bypass(w->regulator, false); if (ret != 0) dev_warn(w->dapm->dev, "ASoC: Failed to unbypass %s: %d\n", w->name, ret); } return regulator_enable(w->regulator); } else { if (w->on_val & SND_SOC_DAPM_REGULATOR_BYPASS) { ret = regulator_allow_bypass(w->regulator, true); if (ret != 0) dev_warn(w->dapm->dev, "ASoC: Failed to bypass %s: %d\n", w->name, ret); } return regulator_disable_deferred(w->regulator, w->shift); } } EXPORT_SYMBOL_GPL(dapm_regulator_event); /* * Handler for clock supply widget. */ int dapm_clock_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { if (!w->clk) return -EIO; soc_dapm_async_complete(w->dapm); #ifdef CONFIG_HAVE_CLK if (SND_SOC_DAPM_EVENT_ON(event)) { return clk_prepare_enable(w->clk); } else { clk_disable_unprepare(w->clk); return 0; } #endif return 0; } EXPORT_SYMBOL_GPL(dapm_clock_event); static int dapm_widget_power_check(struct snd_soc_dapm_widget *w) { if (w->power_checked) return w->new_power; if (w->force) w->new_power = 1; else w->new_power = w->power_check(w); w->power_checked = true; return w->new_power; } /* Generic check to see if a widget should be powered. */ static int dapm_generic_check_power(struct snd_soc_dapm_widget *w) { int in, out; DAPM_UPDATE_STAT(w, power_checks); in = is_connected_input_ep(w, NULL); out = is_connected_output_ep(w, NULL); return out != 0 && in != 0; } /* Check to see if a power supply is needed */ static int dapm_supply_check_power(struct snd_soc_dapm_widget *w) { struct snd_soc_dapm_path *path; DAPM_UPDATE_STAT(w, power_checks); /* Check if one of our outputs is connected */ snd_soc_dapm_widget_for_each_sink_path(w, path) { DAPM_UPDATE_STAT(w, neighbour_checks); if (path->weak) continue; if (path->connected && !path->connected(path->source, path->sink)) continue; if (dapm_widget_power_check(path->sink)) return 1; } return 0; } static int dapm_always_on_check_power(struct snd_soc_dapm_widget *w) { return 1; } static int dapm_seq_compare(struct snd_soc_dapm_widget *a, struct snd_soc_dapm_widget *b, bool power_up) { int *sort; if (power_up) sort = dapm_up_seq; else sort = dapm_down_seq; if (sort[a->id] != sort[b->id]) return sort[a->id] - sort[b->id]; if (a->subseq != b->subseq) { if (power_up) return a->subseq - b->subseq; else return b->subseq - a->subseq; } if (a->reg != b->reg) return a->reg - b->reg; if (a->dapm != b->dapm) return (unsigned long)a->dapm - (unsigned long)b->dapm; return 0; } /* Insert a widget in order into a DAPM power sequence. */ static void dapm_seq_insert(struct snd_soc_dapm_widget *new_widget, struct list_head *list, bool power_up) { struct snd_soc_dapm_widget *w; list_for_each_entry(w, list, power_list) if (dapm_seq_compare(new_widget, w, power_up) < 0) { list_add_tail(&new_widget->power_list, &w->power_list); return; } list_add_tail(&new_widget->power_list, list); } static void dapm_seq_check_event(struct snd_soc_card *card, struct snd_soc_dapm_widget *w, int event) { const char *ev_name; int power, ret; switch (event) { case SND_SOC_DAPM_PRE_PMU: ev_name = "PRE_PMU"; power = 1; break; case SND_SOC_DAPM_POST_PMU: ev_name = "POST_PMU"; power = 1; break; case SND_SOC_DAPM_PRE_PMD: ev_name = "PRE_PMD"; power = 0; break; case SND_SOC_DAPM_POST_PMD: ev_name = "POST_PMD"; power = 0; break; case SND_SOC_DAPM_WILL_PMU: ev_name = "WILL_PMU"; power = 1; break; case SND_SOC_DAPM_WILL_PMD: ev_name = "WILL_PMD"; power = 0; break; default: WARN(1, "Unknown event %d\n", event); return; } if (w->new_power != power) return; if (w->event && (w->event_flags & event)) { pop_dbg(w->dapm->dev, card->pop_time, "pop test : %s %s\n", w->name, ev_name); soc_dapm_async_complete(w->dapm); trace_snd_soc_dapm_widget_event_start(w, event); ret = w->event(w, NULL, event); trace_snd_soc_dapm_widget_event_done(w, event); if (ret < 0) dev_err(w->dapm->dev, "ASoC: %s: %s event failed: %d\n", ev_name, w->name, ret); } } /* Apply the coalesced changes from a DAPM sequence */ static void dapm_seq_run_coalesced(struct snd_soc_card *card, struct list_head *pending) { struct snd_soc_dapm_context *dapm; struct snd_soc_dapm_widget *w; int reg; unsigned int value = 0; unsigned int mask = 0; w = list_first_entry(pending, struct snd_soc_dapm_widget, power_list); reg = w->reg; dapm = w->dapm; list_for_each_entry(w, pending, power_list) { WARN_ON(reg != w->reg || dapm != w->dapm); w->power = w->new_power; mask |= w->mask << w->shift; if (w->power) value |= w->on_val << w->shift; else value |= w->off_val << w->shift; pop_dbg(dapm->dev, card->pop_time, "pop test : Queue %s: reg=0x%x, 0x%x/0x%x\n", w->name, reg, value, mask); /* Check for events */ dapm_seq_check_event(card, w, SND_SOC_DAPM_PRE_PMU); dapm_seq_check_event(card, w, SND_SOC_DAPM_PRE_PMD); } if (reg >= 0) { /* Any widget will do, they should all be updating the * same register. */ pop_dbg(dapm->dev, card->pop_time, "pop test : Applying 0x%x/0x%x to %x in %dms\n", value, mask, reg, card->pop_time); pop_wait(card->pop_time); soc_dapm_update_bits(dapm, reg, mask, value); } list_for_each_entry(w, pending, power_list) { dapm_seq_check_event(card, w, SND_SOC_DAPM_POST_PMU); dapm_seq_check_event(card, w, SND_SOC_DAPM_POST_PMD); } } /* Apply a DAPM power sequence. * * We walk over a pre-sorted list of widgets to apply power to. In * order to minimise the number of writes to the device required * multiple widgets will be updated in a single write where possible. * Currently anything that requires more than a single write is not * handled. */ static void dapm_seq_run(struct snd_soc_card *card, struct list_head *list, int event, bool power_up) { struct snd_soc_dapm_widget *w, *n; struct snd_soc_dapm_context *d; LIST_HEAD(pending); int cur_sort = -1; int cur_subseq = -1; int cur_reg = SND_SOC_NOPM; struct snd_soc_dapm_context *cur_dapm = NULL; int ret, i; int *sort; if (power_up) sort = dapm_up_seq; else sort = dapm_down_seq; list_for_each_entry_safe(w, n, list, power_list) { ret = 0; /* Do we need to apply any queued changes? */ if (sort[w->id] != cur_sort || w->reg != cur_reg || w->dapm != cur_dapm || w->subseq != cur_subseq) { if (!list_empty(&pending)) dapm_seq_run_coalesced(card, &pending); if (cur_dapm && cur_dapm->seq_notifier) { for (i = 0; i < ARRAY_SIZE(dapm_up_seq); i++) if (sort[i] == cur_sort) cur_dapm->seq_notifier(cur_dapm, i, cur_subseq); } if (cur_dapm && w->dapm != cur_dapm) soc_dapm_async_complete(cur_dapm); INIT_LIST_HEAD(&pending); cur_sort = -1; cur_subseq = INT_MIN; cur_reg = SND_SOC_NOPM; cur_dapm = NULL; } switch (w->id) { case snd_soc_dapm_pre: if (!w->event) list_for_each_entry_safe_continue(w, n, list, power_list); if (event == SND_SOC_DAPM_STREAM_START) ret = w->event(w, NULL, SND_SOC_DAPM_PRE_PMU); else if (event == SND_SOC_DAPM_STREAM_STOP) ret = w->event(w, NULL, SND_SOC_DAPM_PRE_PMD); break; case snd_soc_dapm_post: if (!w->event) list_for_each_entry_safe_continue(w, n, list, power_list); if (event == SND_SOC_DAPM_STREAM_START) ret = w->event(w, NULL, SND_SOC_DAPM_POST_PMU); else if (event == SND_SOC_DAPM_STREAM_STOP) ret = w->event(w, NULL, SND_SOC_DAPM_POST_PMD); break; default: /* Queue it up for application */ cur_sort = sort[w->id]; cur_subseq = w->subseq; cur_reg = w->reg; cur_dapm = w->dapm; list_move(&w->power_list, &pending); break; } if (ret < 0) dev_err(w->dapm->dev, "ASoC: Failed to apply widget power: %d\n", ret); } if (!list_empty(&pending)) dapm_seq_run_coalesced(card, &pending); if (cur_dapm && cur_dapm->seq_notifier) { for (i = 0; i < ARRAY_SIZE(dapm_up_seq); i++) if (sort[i] == cur_sort) cur_dapm->seq_notifier(cur_dapm, i, cur_subseq); } list_for_each_entry(d, &card->dapm_list, list) { soc_dapm_async_complete(d); } } static void dapm_widget_update(struct snd_soc_card *card) { struct snd_soc_dapm_update *update = card->update; struct snd_soc_dapm_widget_list *wlist; struct snd_soc_dapm_widget *w = NULL; unsigned int wi; int ret; if (!update || !dapm_kcontrol_is_powered(update->kcontrol)) return; wlist = dapm_kcontrol_get_wlist(update->kcontrol); for (wi = 0; wi < wlist->num_widgets; wi++) { w = wlist->widgets[wi]; if (w->event && (w->event_flags & SND_SOC_DAPM_PRE_REG)) { ret = w->event(w, update->kcontrol, SND_SOC_DAPM_PRE_REG); if (ret != 0) dev_err(w->dapm->dev, "ASoC: %s DAPM pre-event failed: %d\n", w->name, ret); } } if (!w) return; ret = soc_dapm_update_bits(w->dapm, update->reg, update->mask, update->val); if (ret < 0) dev_err(w->dapm->dev, "ASoC: %s DAPM update failed: %d\n", w->name, ret); for (wi = 0; wi < wlist->num_widgets; wi++) { w = wlist->widgets[wi]; if (w->event && (w->event_flags & SND_SOC_DAPM_POST_REG)) { ret = w->event(w, update->kcontrol, SND_SOC_DAPM_POST_REG); if (ret != 0) dev_err(w->dapm->dev, "ASoC: %s DAPM post-event failed: %d\n", w->name, ret); } } } /* Async callback run prior to DAPM sequences - brings to _PREPARE if * they're changing state. */ static void dapm_pre_sequence_async(void *data, async_cookie_t cookie) { struct snd_soc_dapm_context *d = data; int ret; /* If we're off and we're not supposed to be go into STANDBY */ if (d->bias_level == SND_SOC_BIAS_OFF && d->target_bias_level != SND_SOC_BIAS_OFF) { if (d->dev) pm_runtime_get_sync(d->dev); ret = snd_soc_dapm_set_bias_level(d, SND_SOC_BIAS_STANDBY); if (ret != 0) dev_err(d->dev, "ASoC: Failed to turn on bias: %d\n", ret); } /* Prepare for a transition to ON or away from ON */ if ((d->target_bias_level == SND_SOC_BIAS_ON && d->bias_level != SND_SOC_BIAS_ON) || (d->target_bias_level != SND_SOC_BIAS_ON && d->bias_level == SND_SOC_BIAS_ON)) { ret = snd_soc_dapm_set_bias_level(d, SND_SOC_BIAS_PREPARE); if (ret != 0) dev_err(d->dev, "ASoC: Failed to prepare bias: %d\n", ret); } } /* Async callback run prior to DAPM sequences - brings to their final * state. */ static void dapm_post_sequence_async(void *data, async_cookie_t cookie) { struct snd_soc_dapm_context *d = data; int ret; /* If we just powered the last thing off drop to standby bias */ if (d->bias_level == SND_SOC_BIAS_PREPARE && (d->target_bias_level == SND_SOC_BIAS_STANDBY || d->target_bias_level == SND_SOC_BIAS_OFF)) { ret = snd_soc_dapm_set_bias_level(d, SND_SOC_BIAS_STANDBY); if (ret != 0) dev_err(d->dev, "ASoC: Failed to apply standby bias: %d\n", ret); } /* If we're in standby and can support bias off then do that */ if (d->bias_level == SND_SOC_BIAS_STANDBY && d->target_bias_level == SND_SOC_BIAS_OFF) { ret = snd_soc_dapm_set_bias_level(d, SND_SOC_BIAS_OFF); if (ret != 0) dev_err(d->dev, "ASoC: Failed to turn off bias: %d\n", ret); if (d->dev) pm_runtime_put(d->dev); } /* If we just powered up then move to active bias */ if (d->bias_level == SND_SOC_BIAS_PREPARE && d->target_bias_level == SND_SOC_BIAS_ON) { ret = snd_soc_dapm_set_bias_level(d, SND_SOC_BIAS_ON); if (ret != 0) dev_err(d->dev, "ASoC: Failed to apply active bias: %d\n", ret); } } static void dapm_widget_set_peer_power(struct snd_soc_dapm_widget *peer, bool power, bool connect) { /* If a connection is being made or broken then that update * will have marked the peer dirty, otherwise the widgets are * not connected and this update has no impact. */ if (!connect) return; /* If the peer is already in the state we're moving to then we * won't have an impact on it. */ if (power != peer->power) dapm_mark_dirty(peer, "peer state change"); } static void dapm_widget_set_power(struct snd_soc_dapm_widget *w, bool power, struct list_head *up_list, struct list_head *down_list) { struct snd_soc_dapm_path *path; if (w->power == power) return; trace_snd_soc_dapm_widget_power(w, power); /* If we changed our power state perhaps our neigbours changed * also. */ snd_soc_dapm_widget_for_each_source_path(w, path) dapm_widget_set_peer_power(path->source, power, path->connect); /* Supplies can't affect their outputs, only their inputs */ if (!w->is_supply) { snd_soc_dapm_widget_for_each_sink_path(w, path) dapm_widget_set_peer_power(path->sink, power, path->connect); } if (power) dapm_seq_insert(w, up_list, true); else dapm_seq_insert(w, down_list, false); } static void dapm_power_one_widget(struct snd_soc_dapm_widget *w, struct list_head *up_list, struct list_head *down_list) { int power; switch (w->id) { case snd_soc_dapm_pre: dapm_seq_insert(w, down_list, false); break; case snd_soc_dapm_post: dapm_seq_insert(w, up_list, true); break; default: power = dapm_widget_power_check(w); dapm_widget_set_power(w, power, up_list, down_list); break; } } static bool dapm_idle_bias_off(struct snd_soc_dapm_context *dapm) { if (dapm->idle_bias_off) return true; switch (snd_power_get_state(dapm->card->snd_card)) { case SNDRV_CTL_POWER_D3hot: case SNDRV_CTL_POWER_D3cold: return dapm->suspend_bias_off; default: break; } return false; } /* * Scan each dapm widget for complete audio path. * A complete path is a route that has valid endpoints i.e.:- * * o DAC to output pin. * o Input Pin to ADC. * o Input pin to Output pin (bypass, sidetone) * o DAC to ADC (loopback). */ static int dapm_power_widgets(struct snd_soc_card *card, int event) { struct snd_soc_dapm_widget *w; struct snd_soc_dapm_context *d; LIST_HEAD(up_list); LIST_HEAD(down_list); ASYNC_DOMAIN_EXCLUSIVE(async_domain); enum snd_soc_bias_level bias; lockdep_assert_held(&card->dapm_mutex); trace_snd_soc_dapm_start(card); list_for_each_entry(d, &card->dapm_list, list) { if (dapm_idle_bias_off(d)) d->target_bias_level = SND_SOC_BIAS_OFF; else d->target_bias_level = SND_SOC_BIAS_STANDBY; } dapm_reset(card); /* Check which widgets we need to power and store them in * lists indicating if they should be powered up or down. We * only check widgets that have been flagged as dirty but note * that new widgets may be added to the dirty list while we * iterate. */ list_for_each_entry(w, &card->dapm_dirty, dirty) { dapm_power_one_widget(w, &up_list, &down_list); } list_for_each_entry(w, &card->widgets, list) { switch (w->id) { case snd_soc_dapm_pre: case snd_soc_dapm_post: /* These widgets always need to be powered */ break; default: list_del_init(&w->dirty); break; } if (w->new_power) { d = w->dapm; /* Supplies and micbiases only bring the * context up to STANDBY as unless something * else is active and passing audio they * generally don't require full power. Signal * generators are virtual pins and have no * power impact themselves. */ switch (w->id) { case snd_soc_dapm_siggen: case snd_soc_dapm_vmid: break; case snd_soc_dapm_supply: case snd_soc_dapm_regulator_supply: case snd_soc_dapm_clock_supply: case snd_soc_dapm_micbias: if (d->target_bias_level < SND_SOC_BIAS_STANDBY) d->target_bias_level = SND_SOC_BIAS_STANDBY; break; default: d->target_bias_level = SND_SOC_BIAS_ON; break; } } } /* Force all contexts in the card to the same bias state if * they're not ground referenced. */ bias = SND_SOC_BIAS_OFF; list_for_each_entry(d, &card->dapm_list, list) if (d->target_bias_level > bias) bias = d->target_bias_level; list_for_each_entry(d, &card->dapm_list, list) if (!dapm_idle_bias_off(d)) d->target_bias_level = bias; trace_snd_soc_dapm_walk_done(card); /* Run card bias changes at first */ dapm_pre_sequence_async(&card->dapm, 0); /* Run other bias changes in parallel */ list_for_each_entry(d, &card->dapm_list, list) { if (d != &card->dapm) async_schedule_domain(dapm_pre_sequence_async, d, &async_domain); } async_synchronize_full_domain(&async_domain); list_for_each_entry(w, &down_list, power_list) { dapm_seq_check_event(card, w, SND_SOC_DAPM_WILL_PMD); } list_for_each_entry(w, &up_list, power_list) { dapm_seq_check_event(card, w, SND_SOC_DAPM_WILL_PMU); } /* Power down widgets first; try to avoid amplifying pops. */ dapm_seq_run(card, &down_list, event, false); dapm_widget_update(card); /* Now power up. */ dapm_seq_run(card, &up_list, event, true); /* Run all the bias changes in parallel */ list_for_each_entry(d, &card->dapm_list, list) { if (d != &card->dapm) async_schedule_domain(dapm_post_sequence_async, d, &async_domain); } async_synchronize_full_domain(&async_domain); /* Run card bias changes at last */ dapm_post_sequence_async(&card->dapm, 0); /* do we need to notify any clients that DAPM event is complete */ list_for_each_entry(d, &card->dapm_list, list) { if (d->stream_event) d->stream_event(d, event); } pop_dbg(card->dev, card->pop_time, "DAPM sequencing finished, waiting %dms\n", card->pop_time); pop_wait(card->pop_time); trace_snd_soc_dapm_done(card); return 0; } #ifdef CONFIG_DEBUG_FS static ssize_t dapm_widget_power_read_file(struct file *file, char __user *user_buf, size_t count, loff_t *ppos) { struct snd_soc_dapm_widget *w = file->private_data; struct snd_soc_card *card = w->dapm->card; enum snd_soc_dapm_direction dir, rdir; char *buf; int in, out; ssize_t ret; struct snd_soc_dapm_path *p = NULL; buf = kmalloc(PAGE_SIZE, GFP_KERNEL); if (!buf) return -ENOMEM; mutex_lock(&card->dapm_mutex); /* Supply widgets are not handled by is_connected_{input,output}_ep() */ if (w->is_supply) { in = 0; out = 0; } else { in = is_connected_input_ep(w, NULL); out = is_connected_output_ep(w, NULL); } ret = snprintf(buf, PAGE_SIZE, "%s: %s%s in %d out %d", w->name, w->power ? "On" : "Off", w->force ? " (forced)" : "", in, out); if (w->reg >= 0) ret += snprintf(buf + ret, PAGE_SIZE - ret, " - R%d(0x%x) mask 0x%x", w->reg, w->reg, w->mask << w->shift); ret += snprintf(buf + ret, PAGE_SIZE - ret, "\n"); if (w->sname) ret += snprintf(buf + ret, PAGE_SIZE - ret, " stream %s %s\n", w->sname, w->active ? "active" : "inactive"); snd_soc_dapm_for_each_direction(dir) { rdir = SND_SOC_DAPM_DIR_REVERSE(dir); snd_soc_dapm_widget_for_each_path(w, dir, p) { if (p->connected && !p->connected(w, p->node[rdir])) continue; if (!p->connect) continue; ret += snprintf(buf + ret, PAGE_SIZE - ret, " %s \"%s\" \"%s\"\n", (rdir == SND_SOC_DAPM_DIR_IN) ? "in" : "out", p->name ? p->name : "static", p->node[rdir]->name); } } mutex_unlock(&card->dapm_mutex); ret = simple_read_from_buffer(user_buf, count, ppos, buf, ret); kfree(buf); return ret; } static const struct file_operations dapm_widget_power_fops = { .open = simple_open, .read = dapm_widget_power_read_file, .llseek = default_llseek, }; static ssize_t dapm_bias_read_file(struct file *file, char __user *user_buf, size_t count, loff_t *ppos) { struct snd_soc_dapm_context *dapm = file->private_data; char *level; switch (dapm->bias_level) { case SND_SOC_BIAS_ON: level = "On\n"; break; case SND_SOC_BIAS_PREPARE: level = "Prepare\n"; break; case SND_SOC_BIAS_STANDBY: level = "Standby\n"; break; case SND_SOC_BIAS_OFF: level = "Off\n"; break; default: WARN(1, "Unknown bias_level %d\n", dapm->bias_level); level = "Unknown\n"; break; } return simple_read_from_buffer(user_buf, count, ppos, level, strlen(level)); } static const struct file_operations dapm_bias_fops = { .open = simple_open, .read = dapm_bias_read_file, .llseek = default_llseek, }; void snd_soc_dapm_debugfs_init(struct snd_soc_dapm_context *dapm, struct dentry *parent) { struct dentry *d; if (!parent) return; dapm->debugfs_dapm = debugfs_create_dir("dapm", parent); if (!dapm->debugfs_dapm) { dev_warn(dapm->dev, "ASoC: Failed to create DAPM debugfs directory\n"); return; } d = debugfs_create_file("bias_level", 0444, dapm->debugfs_dapm, dapm, &dapm_bias_fops); if (!d) dev_warn(dapm->dev, "ASoC: Failed to create bias level debugfs file\n"); } static void dapm_debugfs_add_widget(struct snd_soc_dapm_widget *w) { struct snd_soc_dapm_context *dapm = w->dapm; struct dentry *d; if (!dapm->debugfs_dapm || !w->name) return; d = debugfs_create_file(w->name, 0444, dapm->debugfs_dapm, w, &dapm_widget_power_fops); if (!d) dev_warn(w->dapm->dev, "ASoC: Failed to create %s debugfs file\n", w->name); } static void dapm_debugfs_cleanup(struct snd_soc_dapm_context *dapm) { debugfs_remove_recursive(dapm->debugfs_dapm); } #else void snd_soc_dapm_debugfs_init(struct snd_soc_dapm_context *dapm, struct dentry *parent) { } static inline void dapm_debugfs_add_widget(struct snd_soc_dapm_widget *w) { } static inline void dapm_debugfs_cleanup(struct snd_soc_dapm_context *dapm) { } #endif /* * soc_dapm_connect_path() - Connects or disconnects a path * @path: The path to update * @connect: The new connect state of the path. True if the path is connected, * false if it is disconneted. * @reason: The reason why the path changed (for debugging only) */ static void soc_dapm_connect_path(struct snd_soc_dapm_path *path, bool connect, const char *reason) { if (path->connect == connect) return; path->connect = connect; dapm_mark_dirty(path->source, reason); dapm_mark_dirty(path->sink, reason); dapm_path_invalidate(path); } /* test and update the power status of a mux widget */ static int soc_dapm_mux_update_power(struct snd_soc_card *card, struct snd_kcontrol *kcontrol, int mux, struct soc_enum *e) { struct snd_soc_dapm_path *path; int found = 0; bool connect; lockdep_assert_held(&card->dapm_mutex); /* find dapm widget path assoc with kcontrol */ dapm_kcontrol_for_each_path(path, kcontrol) { found = 1; /* we now need to match the string in the enum to the path */ if (!(strcmp(path->name, e->texts[mux]))) connect = true; else connect = false; soc_dapm_connect_path(path, connect, "mux update"); } if (found) dapm_power_widgets(card, SND_SOC_DAPM_STREAM_NOP); return found; } int snd_soc_dapm_mux_update_power(struct snd_soc_dapm_context *dapm, struct snd_kcontrol *kcontrol, int mux, struct soc_enum *e, struct snd_soc_dapm_update *update) { struct snd_soc_card *card = dapm->card; int ret; mutex_lock_nested(&card->dapm_mutex, SND_SOC_DAPM_CLASS_RUNTIME); card->update = update; ret = soc_dapm_mux_update_power(card, kcontrol, mux, e); card->update = NULL; mutex_unlock(&card->dapm_mutex); if (ret > 0) soc_dpcm_runtime_update(card); return ret; } EXPORT_SYMBOL_GPL(snd_soc_dapm_mux_update_power); /* test and update the power status of a mixer or switch widget */ static int soc_dapm_mixer_update_power(struct snd_soc_card *card, struct snd_kcontrol *kcontrol, int connect) { struct snd_soc_dapm_path *path; int found = 0; lockdep_assert_held(&card->dapm_mutex); /* find dapm widget path assoc with kcontrol */ dapm_kcontrol_for_each_path(path, kcontrol) { found = 1; soc_dapm_connect_path(path, connect, "mixer update"); } if (found) dapm_power_widgets(card, SND_SOC_DAPM_STREAM_NOP); return found; } int snd_soc_dapm_mixer_update_power(struct snd_soc_dapm_context *dapm, struct snd_kcontrol *kcontrol, int connect, struct snd_soc_dapm_update *update) { struct snd_soc_card *card = dapm->card; int ret; mutex_lock_nested(&card->dapm_mutex, SND_SOC_DAPM_CLASS_RUNTIME); card->update = update; ret = soc_dapm_mixer_update_power(card, kcontrol, connect); card->update = NULL; mutex_unlock(&card->dapm_mutex); if (ret > 0) soc_dpcm_runtime_update(card); return ret; } EXPORT_SYMBOL_GPL(snd_soc_dapm_mixer_update_power); static ssize_t dapm_widget_show_codec(struct snd_soc_codec *codec, char *buf) { struct snd_soc_dapm_widget *w; int count = 0; char *state = "not set"; /* card won't be set for the dummy component, as a spot fix * we're checking for that case specifically here but in future * we will ensure that the dummy component looks like others. */ if (!codec->component.card) return 0; list_for_each_entry(w, &codec->component.card->widgets, list) { if (w->dapm != &codec->dapm) continue; /* only display widgets that burnm power */ switch (w->id) { case snd_soc_dapm_hp: case snd_soc_dapm_mic: case snd_soc_dapm_spk: case snd_soc_dapm_line: case snd_soc_dapm_micbias: case snd_soc_dapm_dac: case snd_soc_dapm_adc: case snd_soc_dapm_pga: case snd_soc_dapm_out_drv: case snd_soc_dapm_mixer: case snd_soc_dapm_mixer_named_ctl: case snd_soc_dapm_supply: case snd_soc_dapm_regulator_supply: case snd_soc_dapm_clock_supply: if (w->name) count += sprintf(buf + count, "%s: %s\n", w->name, w->power ? "On":"Off"); break; default: break; } } switch (codec->dapm.bias_level) { case SND_SOC_BIAS_ON: state = "On"; break; case SND_SOC_BIAS_PREPARE: state = "Prepare"; break; case SND_SOC_BIAS_STANDBY: state = "Standby"; break; case SND_SOC_BIAS_OFF: state = "Off"; break; } count += sprintf(buf + count, "PM State: %s\n", state); return count; } /* show dapm widget status in sys fs */ static ssize_t dapm_widget_show(struct device *dev, struct device_attribute *attr, char *buf) { struct snd_soc_pcm_runtime *rtd = dev_get_drvdata(dev); int i, count = 0; mutex_lock(&rtd->card->dapm_mutex); for (i = 0; i < rtd->num_codecs; i++) { struct snd_soc_codec *codec = rtd->codec_dais[i]->codec; count += dapm_widget_show_codec(codec, buf + count); } mutex_unlock(&rtd->card->dapm_mutex); return count; } static DEVICE_ATTR(dapm_widget, 0444, dapm_widget_show, NULL); struct attribute *soc_dapm_dev_attrs[] = { &dev_attr_dapm_widget.attr, NULL }; static void dapm_free_path(struct snd_soc_dapm_path *path) { list_del(&path->list_node[SND_SOC_DAPM_DIR_IN]); list_del(&path->list_node[SND_SOC_DAPM_DIR_OUT]); list_del(&path->list_kcontrol); list_del(&path->list); kfree(path); } void snd_soc_dapm_free_widget(struct snd_soc_dapm_widget *w) { struct snd_soc_dapm_path *p, *next_p; enum snd_soc_dapm_direction dir; list_del(&w->list); /* * remove source and sink paths associated to this widget. * While removing the path, remove reference to it from both * source and sink widgets so that path is removed only once. */ snd_soc_dapm_for_each_direction(dir) { snd_soc_dapm_widget_for_each_path_safe(w, dir, p, next_p) dapm_free_path(p); } kfree(w->kcontrols); kfree(w->name); kfree(w); } /* free all dapm widgets and resources */ static void dapm_free_widgets(struct snd_soc_dapm_context *dapm) { struct snd_soc_dapm_widget *w, *next_w; list_for_each_entry_safe(w, next_w, &dapm->card->widgets, list) { if (w->dapm != dapm) continue; snd_soc_dapm_free_widget(w); } } static struct snd_soc_dapm_widget *dapm_find_widget( struct snd_soc_dapm_context *dapm, const char *pin, bool search_other_contexts) { struct snd_soc_dapm_widget *w; struct snd_soc_dapm_widget *fallback = NULL; list_for_each_entry(w, &dapm->card->widgets, list) { if (!strcmp(w->name, pin)) { if (w->dapm == dapm) return w; else fallback = w; } } if (search_other_contexts) return fallback; return NULL; } static int snd_soc_dapm_set_pin(struct snd_soc_dapm_context *dapm, const char *pin, int status) { struct snd_soc_dapm_widget *w = dapm_find_widget(dapm, pin, true); dapm_assert_locked(dapm); if (!w) { dev_err(dapm->dev, "ASoC: DAPM unknown pin %s\n", pin); return -EINVAL; } if (w->connected != status) { dapm_mark_dirty(w, "pin configuration"); dapm_widget_invalidate_input_paths(w); dapm_widget_invalidate_output_paths(w); } w->connected = status; if (status == 0) w->force = 0; return 0; } /** * snd_soc_dapm_sync_unlocked - scan and power dapm paths * @dapm: DAPM context * * Walks all dapm audio paths and powers widgets according to their * stream or path usage. * * Requires external locking. * * Returns 0 for success. */ int snd_soc_dapm_sync_unlocked(struct snd_soc_dapm_context *dapm) { /* * Suppress early reports (eg, jacks syncing their state) to avoid * silly DAPM runs during card startup. */ if (!dapm->card || !dapm->card->instantiated) return 0; return dapm_power_widgets(dapm->card, SND_SOC_DAPM_STREAM_NOP); } EXPORT_SYMBOL_GPL(snd_soc_dapm_sync_unlocked); /** * snd_soc_dapm_sync - scan and power dapm paths * @dapm: DAPM context * * Walks all dapm audio paths and powers widgets according to their * stream or path usage. * * Returns 0 for success. */ int snd_soc_dapm_sync(struct snd_soc_dapm_context *dapm) { int ret; mutex_lock_nested(&dapm->card->dapm_mutex, SND_SOC_DAPM_CLASS_RUNTIME); ret = snd_soc_dapm_sync_unlocked(dapm); mutex_unlock(&dapm->card->dapm_mutex); return ret; } EXPORT_SYMBOL_GPL(snd_soc_dapm_sync); /* * dapm_update_widget_flags() - Re-compute widget sink and source flags * @w: The widget for which to update the flags * * Some widgets have a dynamic category which depends on which neighbors they * are connected to. This function update the category for these widgets. * * This function must be called whenever a path is added or removed to a widget. */ static void dapm_update_widget_flags(struct snd_soc_dapm_widget *w) { enum snd_soc_dapm_direction dir; struct snd_soc_dapm_path *p; unsigned int ep; switch (w->id) { case snd_soc_dapm_input: /* On a fully routed card a input is never a source */ if (w->dapm->card->fully_routed) return; ep = SND_SOC_DAPM_EP_SOURCE; snd_soc_dapm_widget_for_each_source_path(w, p) { if (p->source->id == snd_soc_dapm_micbias || p->source->id == snd_soc_dapm_mic || p->source->id == snd_soc_dapm_line || p->source->id == snd_soc_dapm_output) { ep = 0; break; } } break; case snd_soc_dapm_output: /* On a fully routed card a output is never a sink */ if (w->dapm->card->fully_routed) return; ep = SND_SOC_DAPM_EP_SINK; snd_soc_dapm_widget_for_each_sink_path(w, p) { if (p->sink->id == snd_soc_dapm_spk || p->sink->id == snd_soc_dapm_hp || p->sink->id == snd_soc_dapm_line || p->sink->id == snd_soc_dapm_input) { ep = 0; break; } } break; case snd_soc_dapm_line: ep = 0; snd_soc_dapm_for_each_direction(dir) { if (!list_empty(&w->edges[dir])) ep |= SND_SOC_DAPM_DIR_TO_EP(dir); } break; default: return; } w->is_ep = ep; } static int snd_soc_dapm_check_dynamic_path(struct snd_soc_dapm_context *dapm, struct snd_soc_dapm_widget *source, struct snd_soc_dapm_widget *sink, const char *control) { bool dynamic_source = false; bool dynamic_sink = false; if (!control) return 0; switch (source->id) { case snd_soc_dapm_demux: dynamic_source = true; break; default: break; } switch (sink->id) { case snd_soc_dapm_mux: case snd_soc_dapm_switch: case snd_soc_dapm_mixer: case snd_soc_dapm_mixer_named_ctl: dynamic_sink = true; break; default: break; } if (dynamic_source && dynamic_sink) { dev_err(dapm->dev, "Direct connection between demux and mixer/mux not supported for path %s -> [%s] -> %s\n", source->name, control, sink->name); return -EINVAL; } else if (!dynamic_source && !dynamic_sink) { dev_err(dapm->dev, "Control not supported for path %s -> [%s] -> %s\n", source->name, control, sink->name); return -EINVAL; } return 0; } static int snd_soc_dapm_add_path(struct snd_soc_dapm_context *dapm, struct snd_soc_dapm_widget *wsource, struct snd_soc_dapm_widget *wsink, const char *control, int (*connected)(struct snd_soc_dapm_widget *source, struct snd_soc_dapm_widget *sink)) { struct snd_soc_dapm_widget *widgets[2]; enum snd_soc_dapm_direction dir; struct snd_soc_dapm_path *path; int ret; if (wsink->is_supply && !wsource->is_supply) { dev_err(dapm->dev, "Connecting non-supply widget to supply widget is not supported (%s -> %s)\n", wsource->name, wsink->name); return -EINVAL; } if (connected && !wsource->is_supply) { dev_err(dapm->dev, "connected() callback only supported for supply widgets (%s -> %s)\n", wsource->name, wsink->name); return -EINVAL; } if (wsource->is_supply && control) { dev_err(dapm->dev, "Conditional paths are not supported for supply widgets (%s -> [%s] -> %s)\n", wsource->name, control, wsink->name); return -EINVAL; } ret = snd_soc_dapm_check_dynamic_path(dapm, wsource, wsink, control); if (ret) return ret; path = kzalloc(sizeof(struct snd_soc_dapm_path), GFP_KERNEL); if (!path) return -ENOMEM; path->node[SND_SOC_DAPM_DIR_IN] = wsource; path->node[SND_SOC_DAPM_DIR_OUT] = wsink; widgets[SND_SOC_DAPM_DIR_IN] = wsource; widgets[SND_SOC_DAPM_DIR_OUT] = wsink; path->connected = connected; INIT_LIST_HEAD(&path->list); INIT_LIST_HEAD(&path->list_kcontrol); if (wsource->is_supply || wsink->is_supply) path->is_supply = 1; /* connect static paths */ if (control == NULL) { path->connect = 1; } else { switch (wsource->id) { case snd_soc_dapm_demux: ret = dapm_connect_mux(dapm, path, control, wsource); if (ret) goto err; break; default: break; } switch (wsink->id) { case snd_soc_dapm_mux: ret = dapm_connect_mux(dapm, path, control, wsink); if (ret != 0) goto err; break; case snd_soc_dapm_switch: case snd_soc_dapm_mixer: case snd_soc_dapm_mixer_named_ctl: ret = dapm_connect_mixer(dapm, path, control); if (ret != 0) goto err; break; default: break; } } list_add(&path->list, &dapm->card->paths); snd_soc_dapm_for_each_direction(dir) list_add(&path->list_node[dir], &widgets[dir]->edges[dir]); snd_soc_dapm_for_each_direction(dir) { dapm_update_widget_flags(widgets[dir]); dapm_mark_dirty(widgets[dir], "Route added"); } if (dapm->card->instantiated && path->connect) dapm_path_invalidate(path); return 0; err: kfree(path); return ret; } static int snd_soc_dapm_add_route(struct snd_soc_dapm_context *dapm, const struct snd_soc_dapm_route *route) { struct snd_soc_dapm_widget *wsource = NULL, *wsink = NULL, *w; struct snd_soc_dapm_widget *wtsource = NULL, *wtsink = NULL; const char *sink; const char *source; char prefixed_sink[80]; char prefixed_source[80]; const char *prefix; int ret; prefix = soc_dapm_prefix(dapm); if (prefix) { snprintf(prefixed_sink, sizeof(prefixed_sink), "%s %s", prefix, route->sink); sink = prefixed_sink; snprintf(prefixed_source, sizeof(prefixed_source), "%s %s", prefix, route->source); source = prefixed_source; } else { sink = route->sink; source = route->source; } wsource = dapm_wcache_lookup(&dapm->path_source_cache, source); wsink = dapm_wcache_lookup(&dapm->path_sink_cache, sink); if (wsink && wsource) goto skip_search; /* * find src and dest widgets over all widgets but favor a widget from * current DAPM context */ list_for_each_entry(w, &dapm->card->widgets, list) { if (!wsink && !(strcmp(w->name, sink))) { wtsink = w; if (w->dapm == dapm) { wsink = w; if (wsource) break; } continue; } if (!wsource && !(strcmp(w->name, source))) { wtsource = w; if (w->dapm == dapm) { wsource = w; if (wsink) break; } } } /* use widget from another DAPM context if not found from this */ if (!wsink) wsink = wtsink; if (!wsource) wsource = wtsource; if (wsource == NULL) { dev_err(dapm->dev, "ASoC: no source widget found for %s\n", route->source); return -ENODEV; } if (wsink == NULL) { dev_err(dapm->dev, "ASoC: no sink widget found for %s\n", route->sink); return -ENODEV; } skip_search: dapm_wcache_update(&dapm->path_sink_cache, wsink); dapm_wcache_update(&dapm->path_source_cache, wsource); ret = snd_soc_dapm_add_path(dapm, wsource, wsink, route->control, route->connected); if (ret) goto err; return 0; err: dev_warn(dapm->dev, "ASoC: no dapm match for %s --> %s --> %s\n", source, route->control, sink); return ret; } static int snd_soc_dapm_del_route(struct snd_soc_dapm_context *dapm, const struct snd_soc_dapm_route *route) { struct snd_soc_dapm_widget *wsource, *wsink; struct snd_soc_dapm_path *path, *p; const char *sink; const char *source; char prefixed_sink[80]; char prefixed_source[80]; const char *prefix; if (route->control) { dev_err(dapm->dev, "ASoC: Removal of routes with controls not supported\n"); return -EINVAL; } prefix = soc_dapm_prefix(dapm); if (prefix) { snprintf(prefixed_sink, sizeof(prefixed_sink), "%s %s", prefix, route->sink); sink = prefixed_sink; snprintf(prefixed_source, sizeof(prefixed_source), "%s %s", prefix, route->source); source = prefixed_source; } else { sink = route->sink; source = route->source; } path = NULL; list_for_each_entry(p, &dapm->card->paths, list) { if (strcmp(p->source->name, source) != 0) continue; if (strcmp(p->sink->name, sink) != 0) continue; path = p; break; } if (path) { wsource = path->source; wsink = path->sink; dapm_mark_dirty(wsource, "Route removed"); dapm_mark_dirty(wsink, "Route removed"); if (path->connect) dapm_path_invalidate(path); dapm_free_path(path); /* Update any path related flags */ dapm_update_widget_flags(wsource); dapm_update_widget_flags(wsink); } else { dev_warn(dapm->dev, "ASoC: Route %s->%s does not exist\n", source, sink); } return 0; } /** * snd_soc_dapm_add_routes - Add routes between DAPM widgets * @dapm: DAPM context * @route: audio routes * @num: number of routes * * Connects 2 dapm widgets together via a named audio path. The sink is * the widget receiving the audio signal, whilst the source is the sender * of the audio signal. * * Returns 0 for success else error. On error all resources can be freed * with a call to snd_soc_card_free(). */ int snd_soc_dapm_add_routes(struct snd_soc_dapm_context *dapm, const struct snd_soc_dapm_route *route, int num) { int i, r, ret = 0; mutex_lock_nested(&dapm->card->dapm_mutex, SND_SOC_DAPM_CLASS_INIT); for (i = 0; i < num; i++) { r = snd_soc_dapm_add_route(dapm, route); if (r < 0) { dev_err(dapm->dev, "ASoC: Failed to add route %s -> %s -> %s\n", route->source, route->control ? route->control : "direct", route->sink); ret = r; } route++; } mutex_unlock(&dapm->card->dapm_mutex); return ret; } EXPORT_SYMBOL_GPL(snd_soc_dapm_add_routes); /** * snd_soc_dapm_del_routes - Remove routes between DAPM widgets * @dapm: DAPM context * @route: audio routes * @num: number of routes * * Removes routes from the DAPM context. */ int snd_soc_dapm_del_routes(struct snd_soc_dapm_context *dapm, const struct snd_soc_dapm_route *route, int num) { int i, ret = 0; mutex_lock_nested(&dapm->card->dapm_mutex, SND_SOC_DAPM_CLASS_INIT); for (i = 0; i < num; i++) { snd_soc_dapm_del_route(dapm, route); route++; } mutex_unlock(&dapm->card->dapm_mutex); return ret; } EXPORT_SYMBOL_GPL(snd_soc_dapm_del_routes); static int snd_soc_dapm_weak_route(struct snd_soc_dapm_context *dapm, const struct snd_soc_dapm_route *route) { struct snd_soc_dapm_widget *source = dapm_find_widget(dapm, route->source, true); struct snd_soc_dapm_widget *sink = dapm_find_widget(dapm, route->sink, true); struct snd_soc_dapm_path *path; int count = 0; if (!source) { dev_err(dapm->dev, "ASoC: Unable to find source %s for weak route\n", route->source); return -ENODEV; } if (!sink) { dev_err(dapm->dev, "ASoC: Unable to find sink %s for weak route\n", route->sink); return -ENODEV; } if (route->control || route->connected) dev_warn(dapm->dev, "ASoC: Ignoring control for weak route %s->%s\n", route->source, route->sink); snd_soc_dapm_widget_for_each_sink_path(source, path) { if (path->sink == sink) { path->weak = 1; count++; } } if (count == 0) dev_err(dapm->dev, "ASoC: No path found for weak route %s->%s\n", route->source, route->sink); if (count > 1) dev_warn(dapm->dev, "ASoC: %d paths found for weak route %s->%s\n", count, route->source, route->sink); return 0; } /** * snd_soc_dapm_weak_routes - Mark routes between DAPM widgets as weak * @dapm: DAPM context * @route: audio routes * @num: number of routes * * Mark existing routes matching those specified in the passed array * as being weak, meaning that they are ignored for the purpose of * power decisions. The main intended use case is for sidetone paths * which couple audio between other independent paths if they are both * active in order to make the combination work better at the user * level but which aren't intended to be "used". * * Note that CODEC drivers should not use this as sidetone type paths * can frequently also be used as bypass paths. */ int snd_soc_dapm_weak_routes(struct snd_soc_dapm_context *dapm, const struct snd_soc_dapm_route *route, int num) { int i, err; int ret = 0; mutex_lock_nested(&dapm->card->dapm_mutex, SND_SOC_DAPM_CLASS_INIT); for (i = 0; i < num; i++) { err = snd_soc_dapm_weak_route(dapm, route); if (err) ret = err; route++; } mutex_unlock(&dapm->card->dapm_mutex); return ret; } EXPORT_SYMBOL_GPL(snd_soc_dapm_weak_routes); /** * snd_soc_dapm_new_widgets - add new dapm widgets * @dapm: DAPM context * * Checks the codec for any new dapm widgets and creates them if found. * * Returns 0 for success. */ int snd_soc_dapm_new_widgets(struct snd_soc_card *card) { struct snd_soc_dapm_widget *w; unsigned int val; mutex_lock_nested(&card->dapm_mutex, SND_SOC_DAPM_CLASS_INIT); list_for_each_entry(w, &card->widgets, list) { if (w->new) continue; if (w->num_kcontrols) { w->kcontrols = kzalloc(w->num_kcontrols * sizeof(struct snd_kcontrol *), GFP_KERNEL); if (!w->kcontrols) { mutex_unlock(&card->dapm_mutex); return -ENOMEM; } } switch(w->id) { case snd_soc_dapm_switch: case snd_soc_dapm_mixer: case snd_soc_dapm_mixer_named_ctl: dapm_new_mixer(w); break; case snd_soc_dapm_mux: case snd_soc_dapm_demux: dapm_new_mux(w); break; case snd_soc_dapm_pga: case snd_soc_dapm_out_drv: dapm_new_pga(w); break; case snd_soc_dapm_dai_link: dapm_new_dai_link(w); break; default: break; } /* Read the initial power state from the device */ if (w->reg >= 0) { soc_dapm_read(w->dapm, w->reg, &val); val = val >> w->shift; val &= w->mask; if (val == w->on_val) w->power = 1; } w->new = 1; dapm_mark_dirty(w, "new widget"); dapm_debugfs_add_widget(w); } dapm_power_widgets(card, SND_SOC_DAPM_STREAM_NOP); mutex_unlock(&card->dapm_mutex); return 0; } EXPORT_SYMBOL_GPL(snd_soc_dapm_new_widgets); /** * snd_soc_dapm_get_volsw - dapm mixer get callback * @kcontrol: mixer control * @ucontrol: control element information * * Callback to get the value of a dapm mixer control. * * Returns 0 for success. */ int snd_soc_dapm_get_volsw(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_dapm_context *dapm = snd_soc_dapm_kcontrol_dapm(kcontrol); struct snd_soc_card *card = dapm->card; struct soc_mixer_control *mc = (struct soc_mixer_control *)kcontrol->private_value; int reg = mc->reg; unsigned int shift = mc->shift; int max = mc->max; unsigned int mask = (1 << fls(max)) - 1; unsigned int invert = mc->invert; unsigned int val; int ret = 0; if (snd_soc_volsw_is_stereo(mc)) dev_warn(dapm->dev, "ASoC: Control '%s' is stereo, which is not supported\n", kcontrol->id.name); mutex_lock_nested(&card->dapm_mutex, SND_SOC_DAPM_CLASS_RUNTIME); if (dapm_kcontrol_is_powered(kcontrol) && reg != SND_SOC_NOPM) { ret = soc_dapm_read(dapm, reg, &val); val = (val >> shift) & mask; } else { val = dapm_kcontrol_get_value(kcontrol); } mutex_unlock(&card->dapm_mutex); if (invert) ucontrol->value.integer.value[0] = max - val; else ucontrol->value.integer.value[0] = val; return ret; } EXPORT_SYMBOL_GPL(snd_soc_dapm_get_volsw); /** * snd_soc_dapm_put_volsw - dapm mixer set callback * @kcontrol: mixer control * @ucontrol: control element information * * Callback to set the value of a dapm mixer control. * * Returns 0 for success. */ int snd_soc_dapm_put_volsw(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_dapm_context *dapm = snd_soc_dapm_kcontrol_dapm(kcontrol); struct snd_soc_card *card = dapm->card; struct soc_mixer_control *mc = (struct soc_mixer_control *)kcontrol->private_value; int reg = mc->reg; unsigned int shift = mc->shift; int max = mc->max; unsigned int mask = (1 << fls(max)) - 1; unsigned int invert = mc->invert; unsigned int val; int connect, change, reg_change = 0; struct snd_soc_dapm_update update; int ret = 0; if (snd_soc_volsw_is_stereo(mc)) dev_warn(dapm->dev, "ASoC: Control '%s' is stereo, which is not supported\n", kcontrol->id.name); val = (ucontrol->value.integer.value[0] & mask); connect = !!val; if (invert) val = max - val; mutex_lock_nested(&card->dapm_mutex, SND_SOC_DAPM_CLASS_RUNTIME); change = dapm_kcontrol_set_value(kcontrol, val); if (reg != SND_SOC_NOPM) { mask = mask << shift; val = val << shift; reg_change = soc_dapm_test_bits(dapm, reg, mask, val); } if (change || reg_change) { if (reg_change) { update.kcontrol = kcontrol; update.reg = reg; update.mask = mask; update.val = val; card->update = &update; } change |= reg_change; ret = soc_dapm_mixer_update_power(card, kcontrol, connect); card->update = NULL; } mutex_unlock(&card->dapm_mutex); if (ret > 0) soc_dpcm_runtime_update(card); return change; } EXPORT_SYMBOL_GPL(snd_soc_dapm_put_volsw); /** * snd_soc_dapm_get_enum_double - dapm enumerated double mixer get callback * @kcontrol: mixer control * @ucontrol: control element information * * Callback to get the value of a dapm enumerated double mixer control. * * Returns 0 for success. */ int snd_soc_dapm_get_enum_double(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_dapm_context *dapm = snd_soc_dapm_kcontrol_dapm(kcontrol); struct snd_soc_card *card = dapm->card; struct soc_enum *e = (struct soc_enum *)kcontrol->private_value; unsigned int reg_val, val; mutex_lock_nested(&card->dapm_mutex, SND_SOC_DAPM_CLASS_RUNTIME); if (e->reg != SND_SOC_NOPM && dapm_kcontrol_is_powered(kcontrol)) { int ret = soc_dapm_read(dapm, e->reg, &reg_val); if (ret) { mutex_unlock(&card->dapm_mutex); return ret; } } else { reg_val = dapm_kcontrol_get_value(kcontrol); } mutex_unlock(&card->dapm_mutex); val = (reg_val >> e->shift_l) & e->mask; ucontrol->value.enumerated.item[0] = snd_soc_enum_val_to_item(e, val); if (e->shift_l != e->shift_r) { val = (reg_val >> e->shift_r) & e->mask; val = snd_soc_enum_val_to_item(e, val); ucontrol->value.enumerated.item[1] = val; } return 0; } EXPORT_SYMBOL_GPL(snd_soc_dapm_get_enum_double); /** * snd_soc_dapm_put_enum_double - dapm enumerated double mixer set callback * @kcontrol: mixer control * @ucontrol: control element information * * Callback to set the value of a dapm enumerated double mixer control. * * Returns 0 for success. */ int snd_soc_dapm_put_enum_double(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_dapm_context *dapm = snd_soc_dapm_kcontrol_dapm(kcontrol); struct snd_soc_card *card = dapm->card; struct soc_enum *e = (struct soc_enum *)kcontrol->private_value; unsigned int *item = ucontrol->value.enumerated.item; unsigned int val, change, reg_change = 0; unsigned int mask; struct snd_soc_dapm_update update; int ret = 0; if (item[0] >= e->items) return -EINVAL; val = snd_soc_enum_item_to_val(e, item[0]) << e->shift_l; mask = e->mask << e->shift_l; if (e->shift_l != e->shift_r) { if (item[1] > e->items) return -EINVAL; val |= snd_soc_enum_item_to_val(e, item[1]) << e->shift_l; mask |= e->mask << e->shift_r; } mutex_lock_nested(&card->dapm_mutex, SND_SOC_DAPM_CLASS_RUNTIME); change = dapm_kcontrol_set_value(kcontrol, val); if (e->reg != SND_SOC_NOPM) reg_change = soc_dapm_test_bits(dapm, e->reg, mask, val); if (change || reg_change) { if (reg_change) { update.kcontrol = kcontrol; update.reg = e->reg; update.mask = mask; update.val = val; card->update = &update; } change |= reg_change; ret = soc_dapm_mux_update_power(card, kcontrol, item[0], e); card->update = NULL; } mutex_unlock(&card->dapm_mutex); if (ret > 0) soc_dpcm_runtime_update(card); return change; } EXPORT_SYMBOL_GPL(snd_soc_dapm_put_enum_double); /** * snd_soc_dapm_info_pin_switch - Info for a pin switch * * @kcontrol: mixer control * @uinfo: control element information * * Callback to provide information about a pin switch control. */ int snd_soc_dapm_info_pin_switch(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN; uinfo->count = 1; uinfo->value.integer.min = 0; uinfo->value.integer.max = 1; return 0; } EXPORT_SYMBOL_GPL(snd_soc_dapm_info_pin_switch); /** * snd_soc_dapm_get_pin_switch - Get information for a pin switch * * @kcontrol: mixer control * @ucontrol: Value */ int snd_soc_dapm_get_pin_switch(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_card *card = snd_kcontrol_chip(kcontrol); const char *pin = (const char *)kcontrol->private_value; mutex_lock_nested(&card->dapm_mutex, SND_SOC_DAPM_CLASS_RUNTIME); ucontrol->value.integer.value[0] = snd_soc_dapm_get_pin_status(&card->dapm, pin); mutex_unlock(&card->dapm_mutex); return 0; } EXPORT_SYMBOL_GPL(snd_soc_dapm_get_pin_switch); /** * snd_soc_dapm_put_pin_switch - Set information for a pin switch * * @kcontrol: mixer control * @ucontrol: Value */ int snd_soc_dapm_put_pin_switch(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_card *card = snd_kcontrol_chip(kcontrol); const char *pin = (const char *)kcontrol->private_value; if (ucontrol->value.integer.value[0]) snd_soc_dapm_enable_pin(&card->dapm, pin); else snd_soc_dapm_disable_pin(&card->dapm, pin); snd_soc_dapm_sync(&card->dapm); return 0; } EXPORT_SYMBOL_GPL(snd_soc_dapm_put_pin_switch); struct snd_soc_dapm_widget * snd_soc_dapm_new_control(struct snd_soc_dapm_context *dapm, const struct snd_soc_dapm_widget *widget) { struct snd_soc_dapm_widget *w; mutex_lock_nested(&dapm->card->dapm_mutex, SND_SOC_DAPM_CLASS_RUNTIME); w = snd_soc_dapm_new_control_unlocked(dapm, widget); if (!w) dev_err(dapm->dev, "ASoC: Failed to create DAPM control %s\n", widget->name); mutex_unlock(&dapm->card->dapm_mutex); return w; } struct snd_soc_dapm_widget * snd_soc_dapm_new_control_unlocked(struct snd_soc_dapm_context *dapm, const struct snd_soc_dapm_widget *widget) { enum snd_soc_dapm_direction dir; struct snd_soc_dapm_widget *w; const char *prefix; int ret; if ((w = dapm_cnew_widget(widget)) == NULL) return NULL; switch (w->id) { case snd_soc_dapm_regulator_supply: w->regulator = devm_regulator_get(dapm->dev, w->name); if (IS_ERR(w->regulator)) { ret = PTR_ERR(w->regulator); dev_err(dapm->dev, "ASoC: Failed to request %s: %d\n", w->name, ret); return NULL; } if (w->on_val & SND_SOC_DAPM_REGULATOR_BYPASS) { ret = regulator_allow_bypass(w->regulator, true); if (ret != 0) dev_warn(w->dapm->dev, "ASoC: Failed to bypass %s: %d\n", w->name, ret); } break; case snd_soc_dapm_clock_supply: #ifdef CONFIG_CLKDEV_LOOKUP w->clk = devm_clk_get(dapm->dev, w->name); if (IS_ERR(w->clk)) { ret = PTR_ERR(w->clk); dev_err(dapm->dev, "ASoC: Failed to request %s: %d\n", w->name, ret); return NULL; } #else return NULL; #endif break; default: break; } prefix = soc_dapm_prefix(dapm); if (prefix) w->name = kasprintf(GFP_KERNEL, "%s %s", prefix, widget->name); else w->name = kasprintf(GFP_KERNEL, "%s", widget->name); if (w->name == NULL) { kfree(w); return NULL; } switch (w->id) { case snd_soc_dapm_mic: w->is_ep = SND_SOC_DAPM_EP_SOURCE; w->power_check = dapm_generic_check_power; break; case snd_soc_dapm_input: if (!dapm->card->fully_routed) w->is_ep = SND_SOC_DAPM_EP_SOURCE; w->power_check = dapm_generic_check_power; break; case snd_soc_dapm_spk: case snd_soc_dapm_hp: w->is_ep = SND_SOC_DAPM_EP_SINK; w->power_check = dapm_generic_check_power; break; case snd_soc_dapm_output: if (!dapm->card->fully_routed) w->is_ep = SND_SOC_DAPM_EP_SINK; w->power_check = dapm_generic_check_power; break; case snd_soc_dapm_vmid: case snd_soc_dapm_siggen: w->is_ep = SND_SOC_DAPM_EP_SOURCE; w->power_check = dapm_always_on_check_power; break; case snd_soc_dapm_sink: w->is_ep = SND_SOC_DAPM_EP_SINK; w->power_check = dapm_always_on_check_power; break; case snd_soc_dapm_mux: case snd_soc_dapm_demux: case snd_soc_dapm_switch: case snd_soc_dapm_mixer: case snd_soc_dapm_mixer_named_ctl: case snd_soc_dapm_adc: case snd_soc_dapm_aif_out: case snd_soc_dapm_dac: case snd_soc_dapm_aif_in: case snd_soc_dapm_pga: case snd_soc_dapm_out_drv: case snd_soc_dapm_micbias: case snd_soc_dapm_line: case snd_soc_dapm_dai_link: case snd_soc_dapm_dai_out: case snd_soc_dapm_dai_in: w->power_check = dapm_generic_check_power; break; case snd_soc_dapm_supply: case snd_soc_dapm_regulator_supply: case snd_soc_dapm_clock_supply: case snd_soc_dapm_kcontrol: w->is_supply = 1; w->power_check = dapm_supply_check_power; break; default: w->power_check = dapm_always_on_check_power; break; } w->dapm = dapm; INIT_LIST_HEAD(&w->list); INIT_LIST_HEAD(&w->dirty); list_add(&w->list, &dapm->card->widgets); snd_soc_dapm_for_each_direction(dir) { INIT_LIST_HEAD(&w->edges[dir]); w->endpoints[dir] = -1; } /* machine layer set ups unconnected pins and insertions */ w->connected = 1; return w; } /** * snd_soc_dapm_new_controls - create new dapm controls * @dapm: DAPM context * @widget: widget array * @num: number of widgets * * Creates new DAPM controls based upon the templates. * * Returns 0 for success else error. */ int snd_soc_dapm_new_controls(struct snd_soc_dapm_context *dapm, const struct snd_soc_dapm_widget *widget, int num) { struct snd_soc_dapm_widget *w; int i; int ret = 0; mutex_lock_nested(&dapm->card->dapm_mutex, SND_SOC_DAPM_CLASS_INIT); for (i = 0; i < num; i++) { w = snd_soc_dapm_new_control_unlocked(dapm, widget); if (!w) { dev_err(dapm->dev, "ASoC: Failed to create DAPM control %s\n", widget->name); ret = -ENOMEM; break; } widget++; } mutex_unlock(&dapm->card->dapm_mutex); return ret; } EXPORT_SYMBOL_GPL(snd_soc_dapm_new_controls); static int snd_soc_dai_link_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_dapm_path *source_p, *sink_p; struct snd_soc_dai *source, *sink; const struct snd_soc_pcm_stream *config = w->params + w->params_select; struct snd_pcm_substream substream; struct snd_pcm_hw_params *params = NULL; u64 fmt; int ret; if (WARN_ON(!config) || WARN_ON(list_empty(&w->edges[SND_SOC_DAPM_DIR_OUT]) || list_empty(&w->edges[SND_SOC_DAPM_DIR_IN]))) return -EINVAL; /* We only support a single source and sink, pick the first */ source_p = list_first_entry(&w->edges[SND_SOC_DAPM_DIR_OUT], struct snd_soc_dapm_path, list_node[SND_SOC_DAPM_DIR_OUT]); sink_p = list_first_entry(&w->edges[SND_SOC_DAPM_DIR_IN], struct snd_soc_dapm_path, list_node[SND_SOC_DAPM_DIR_IN]); if (WARN_ON(!source_p || !sink_p) || WARN_ON(!sink_p->source || !source_p->sink) || WARN_ON(!source_p->source || !sink_p->sink)) return -EINVAL; source = source_p->source->priv; sink = sink_p->sink->priv; /* Be a little careful as we don't want to overflow the mask array */ if (config->formats) { fmt = ffs(config->formats) - 1; } else { dev_warn(w->dapm->dev, "ASoC: Invalid format %llx specified\n", config->formats); fmt = 0; } /* Currently very limited parameter selection */ params = kzalloc(sizeof(*params), GFP_KERNEL); if (!params) { ret = -ENOMEM; goto out; } snd_mask_set(hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT), fmt); hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE)->min = config->rate_min; hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE)->max = config->rate_max; hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS)->min = config->channels_min; hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS)->max = config->channels_max; memset(&substream, 0, sizeof(substream)); switch (event) { case SND_SOC_DAPM_PRE_PMU: substream.stream = SNDRV_PCM_STREAM_CAPTURE; if (source->driver->ops && source->driver->ops->startup) { ret = source->driver->ops->startup(&substream, source); if (ret < 0) { dev_err(source->dev, "ASoC: startup() failed: %d\n", ret); goto out; } source->active++; } ret = soc_dai_hw_params(&substream, params, source); if (ret < 0) goto out; substream.stream = SNDRV_PCM_STREAM_PLAYBACK; if (sink->driver->ops && sink->driver->ops->startup) { ret = sink->driver->ops->startup(&substream, sink); if (ret < 0) { dev_err(sink->dev, "ASoC: startup() failed: %d\n", ret); goto out; } sink->active++; } ret = soc_dai_hw_params(&substream, params, sink); if (ret < 0) goto out; break; case SND_SOC_DAPM_POST_PMU: ret = snd_soc_dai_digital_mute(sink, 0, SNDRV_PCM_STREAM_PLAYBACK); if (ret != 0 && ret != -ENOTSUPP) dev_warn(sink->dev, "ASoC: Failed to unmute: %d\n", ret); ret = 0; break; case SND_SOC_DAPM_PRE_PMD: ret = snd_soc_dai_digital_mute(sink, 1, SNDRV_PCM_STREAM_PLAYBACK); if (ret != 0 && ret != -ENOTSUPP) dev_warn(sink->dev, "ASoC: Failed to mute: %d\n", ret); ret = 0; source->active--; if (source->driver->ops && source->driver->ops->shutdown) { substream.stream = SNDRV_PCM_STREAM_CAPTURE; source->driver->ops->shutdown(&substream, source); } sink->active--; if (sink->driver->ops && sink->driver->ops->shutdown) { substream.stream = SNDRV_PCM_STREAM_PLAYBACK; sink->driver->ops->shutdown(&substream, sink); } break; default: WARN(1, "Unknown event %d\n", event); return -EINVAL; } out: kfree(params); return ret; } static int snd_soc_dapm_dai_link_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_dapm_widget *w = snd_kcontrol_chip(kcontrol); ucontrol->value.integer.value[0] = w->params_select; return 0; } static int snd_soc_dapm_dai_link_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_dapm_widget *w = snd_kcontrol_chip(kcontrol); /* Can't change the config when widget is already powered */ if (w->power) return -EBUSY; if (ucontrol->value.integer.value[0] == w->params_select) return 0; if (ucontrol->value.integer.value[0] >= w->num_params) return -EINVAL; w->params_select = ucontrol->value.integer.value[0]; return 0; } int snd_soc_dapm_new_pcm(struct snd_soc_card *card, const struct snd_soc_pcm_stream *params, unsigned int num_params, struct snd_soc_dapm_widget *source, struct snd_soc_dapm_widget *sink) { struct snd_soc_dapm_widget template; struct snd_soc_dapm_widget *w; char *link_name; int ret, count; unsigned long private_value; const char **w_param_text; struct soc_enum w_param_enum[] = { SOC_ENUM_SINGLE(0, 0, 0, NULL), }; struct snd_kcontrol_new kcontrol_dai_link[] = { SOC_ENUM_EXT(NULL, w_param_enum[0], snd_soc_dapm_dai_link_get, snd_soc_dapm_dai_link_put), }; const struct snd_soc_pcm_stream *config = params; w_param_text = devm_kcalloc(card->dev, num_params, sizeof(char *), GFP_KERNEL); if (!w_param_text) return -ENOMEM; link_name = devm_kasprintf(card->dev, GFP_KERNEL, "%s-%s", source->name, sink->name); if (!link_name) { ret = -ENOMEM; goto outfree_w_param; } for (count = 0 ; count < num_params; count++) { if (!config->stream_name) { dev_warn(card->dapm.dev, "ASoC: anonymous config %d for dai link %s\n", count, link_name); w_param_text[count] = devm_kasprintf(card->dev, GFP_KERNEL, "Anonymous Configuration %d", count); if (!w_param_text[count]) { ret = -ENOMEM; goto outfree_link_name; } } else { w_param_text[count] = devm_kmemdup(card->dev, config->stream_name, strlen(config->stream_name) + 1, GFP_KERNEL); if (!w_param_text[count]) { ret = -ENOMEM; goto outfree_link_name; } } config++; } w_param_enum[0].items = num_params; w_param_enum[0].texts = w_param_text; memset(&template, 0, sizeof(template)); template.reg = SND_SOC_NOPM; template.id = snd_soc_dapm_dai_link; template.name = link_name; template.event = snd_soc_dai_link_event; template.event_flags = SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD; template.num_kcontrols = 1; /* duplicate w_param_enum on heap so that memory persists */ private_value = (unsigned long) devm_kmemdup(card->dev, (void *)(kcontrol_dai_link[0].private_value), sizeof(struct soc_enum), GFP_KERNEL); if (!private_value) { dev_err(card->dev, "ASoC: Failed to create control for %s widget\n", link_name); ret = -ENOMEM; goto outfree_link_name; } kcontrol_dai_link[0].private_value = private_value; /* duplicate kcontrol_dai_link on heap so that memory persists */ template.kcontrol_news = devm_kmemdup(card->dev, &kcontrol_dai_link[0], sizeof(struct snd_kcontrol_new), GFP_KERNEL); if (!template.kcontrol_news) { dev_err(card->dev, "ASoC: Failed to create control for %s widget\n", link_name); ret = -ENOMEM; goto outfree_private_value; } dev_dbg(card->dev, "ASoC: adding %s widget\n", link_name); w = snd_soc_dapm_new_control_unlocked(&card->dapm, &template); if (!w) { dev_err(card->dev, "ASoC: Failed to create %s widget\n", link_name); ret = -ENOMEM; goto outfree_kcontrol_news; } w->params = params; w->num_params = num_params; ret = snd_soc_dapm_add_path(&card->dapm, source, w, NULL, NULL); if (ret) goto outfree_w; return snd_soc_dapm_add_path(&card->dapm, w, sink, NULL, NULL); outfree_w: devm_kfree(card->dev, w); outfree_kcontrol_news: devm_kfree(card->dev, (void *)template.kcontrol_news); outfree_private_value: devm_kfree(card->dev, (void *)private_value); outfree_link_name: devm_kfree(card->dev, link_name); outfree_w_param: for (count = 0 ; count < num_params; count++) devm_kfree(card->dev, (void *)w_param_text[count]); devm_kfree(card->dev, w_param_text); return ret; } int snd_soc_dapm_new_dai_widgets(struct snd_soc_dapm_context *dapm, struct snd_soc_dai *dai) { struct snd_soc_dapm_widget template; struct snd_soc_dapm_widget *w; WARN_ON(dapm->dev != dai->dev); memset(&template, 0, sizeof(template)); template.reg = SND_SOC_NOPM; if (dai->driver->playback.stream_name) { template.id = snd_soc_dapm_dai_in; template.name = dai->driver->playback.stream_name; template.sname = dai->driver->playback.stream_name; dev_dbg(dai->dev, "ASoC: adding %s widget\n", template.name); w = snd_soc_dapm_new_control_unlocked(dapm, &template); if (!w) { dev_err(dapm->dev, "ASoC: Failed to create %s widget\n", dai->driver->playback.stream_name); return -ENOMEM; } w->priv = dai; dai->playback_widget = w; } if (dai->driver->capture.stream_name) { template.id = snd_soc_dapm_dai_out; template.name = dai->driver->capture.stream_name; template.sname = dai->driver->capture.stream_name; dev_dbg(dai->dev, "ASoC: adding %s widget\n", template.name); w = snd_soc_dapm_new_control_unlocked(dapm, &template); if (!w) { dev_err(dapm->dev, "ASoC: Failed to create %s widget\n", dai->driver->capture.stream_name); return -ENOMEM; } w->priv = dai; dai->capture_widget = w; } return 0; } int snd_soc_dapm_link_dai_widgets(struct snd_soc_card *card) { struct snd_soc_dapm_widget *dai_w, *w; struct snd_soc_dapm_widget *src, *sink; struct snd_soc_dai *dai; /* For each DAI widget... */ list_for_each_entry(dai_w, &card->widgets, list) { switch (dai_w->id) { case snd_soc_dapm_dai_in: case snd_soc_dapm_dai_out: break; default: continue; } dai = dai_w->priv; /* ...find all widgets with the same stream and link them */ list_for_each_entry(w, &card->widgets, list) { if (w->dapm != dai_w->dapm) continue; switch (w->id) { case snd_soc_dapm_dai_in: case snd_soc_dapm_dai_out: continue; default: break; } if (!w->sname || !strstr(w->sname, dai_w->sname)) continue; if (dai_w->id == snd_soc_dapm_dai_in) { src = dai_w; sink = w; } else { src = w; sink = dai_w; } dev_dbg(dai->dev, "%s -> %s\n", src->name, sink->name); snd_soc_dapm_add_path(w->dapm, src, sink, NULL, NULL); } } return 0; } static void dapm_connect_dai_link_widgets(struct snd_soc_card *card, struct snd_soc_pcm_runtime *rtd) { struct snd_soc_dai *cpu_dai = rtd->cpu_dai; struct snd_soc_dapm_widget *sink, *source; int i; for (i = 0; i < rtd->num_codecs; i++) { struct snd_soc_dai *codec_dai = rtd->codec_dais[i]; /* connect BE DAI playback if widgets are valid */ if (codec_dai->playback_widget && cpu_dai->playback_widget) { source = cpu_dai->playback_widget; sink = codec_dai->playback_widget; dev_dbg(rtd->dev, "connected DAI link %s:%s -> %s:%s\n", cpu_dai->component->name, source->name, codec_dai->component->name, sink->name); snd_soc_dapm_add_path(&card->dapm, source, sink, NULL, NULL); } /* connect BE DAI capture if widgets are valid */ if (codec_dai->capture_widget && cpu_dai->capture_widget) { source = codec_dai->capture_widget; sink = cpu_dai->capture_widget; dev_dbg(rtd->dev, "connected DAI link %s:%s -> %s:%s\n", codec_dai->component->name, source->name, cpu_dai->component->name, sink->name); snd_soc_dapm_add_path(&card->dapm, source, sink, NULL, NULL); } } } static void soc_dapm_dai_stream_event(struct snd_soc_dai *dai, int stream, int event) { struct snd_soc_dapm_widget *w; unsigned int ep; if (stream == SNDRV_PCM_STREAM_PLAYBACK) w = dai->playback_widget; else w = dai->capture_widget; if (w) { dapm_mark_dirty(w, "stream event"); if (w->id == snd_soc_dapm_dai_in) { ep = SND_SOC_DAPM_EP_SOURCE; dapm_widget_invalidate_input_paths(w); } else { ep = SND_SOC_DAPM_EP_SINK; dapm_widget_invalidate_output_paths(w); } switch (event) { case SND_SOC_DAPM_STREAM_START: w->active = 1; w->is_ep = ep; break; case SND_SOC_DAPM_STREAM_STOP: w->active = 0; w->is_ep = 0; break; case SND_SOC_DAPM_STREAM_SUSPEND: case SND_SOC_DAPM_STREAM_RESUME: case SND_SOC_DAPM_STREAM_PAUSE_PUSH: case SND_SOC_DAPM_STREAM_PAUSE_RELEASE: break; } } } void snd_soc_dapm_connect_dai_link_widgets(struct snd_soc_card *card) { struct snd_soc_pcm_runtime *rtd = card->rtd; int i; /* for each BE DAI link... */ for (i = 0; i < card->num_rtd; i++) { rtd = &card->rtd[i]; /* * dynamic FE links have no fixed DAI mapping. * CODEC<->CODEC links have no direct connection. */ if (rtd->dai_link->dynamic || rtd->dai_link->params) continue; dapm_connect_dai_link_widgets(card, rtd); } } static void soc_dapm_stream_event(struct snd_soc_pcm_runtime *rtd, int stream, int event) { int i; soc_dapm_dai_stream_event(rtd->cpu_dai, stream, event); for (i = 0; i < rtd->num_codecs; i++) soc_dapm_dai_stream_event(rtd->codec_dais[i], stream, event); dapm_power_widgets(rtd->card, event); } /** * snd_soc_dapm_stream_event - send a stream event to the dapm core * @rtd: PCM runtime data * @stream: stream name * @event: stream event * * Sends a stream event to the dapm core. The core then makes any * necessary widget power changes. * * Returns 0 for success else error. */ void snd_soc_dapm_stream_event(struct snd_soc_pcm_runtime *rtd, int stream, int event) { struct snd_soc_card *card = rtd->card; mutex_lock_nested(&card->dapm_mutex, SND_SOC_DAPM_CLASS_RUNTIME); soc_dapm_stream_event(rtd, stream, event); mutex_unlock(&card->dapm_mutex); } /** * snd_soc_dapm_enable_pin_unlocked - enable pin. * @dapm: DAPM context * @pin: pin name * * Enables input/output pin and its parents or children widgets iff there is * a valid audio route and active audio stream. * * Requires external locking. * * NOTE: snd_soc_dapm_sync() needs to be called after this for DAPM to * do any widget power switching. */ int snd_soc_dapm_enable_pin_unlocked(struct snd_soc_dapm_context *dapm, const char *pin) { return snd_soc_dapm_set_pin(dapm, pin, 1); } EXPORT_SYMBOL_GPL(snd_soc_dapm_enable_pin_unlocked); /** * snd_soc_dapm_enable_pin - enable pin. * @dapm: DAPM context * @pin: pin name * * Enables input/output pin and its parents or children widgets iff there is * a valid audio route and active audio stream. * * NOTE: snd_soc_dapm_sync() needs to be called after this for DAPM to * do any widget power switching. */ int snd_soc_dapm_enable_pin(struct snd_soc_dapm_context *dapm, const char *pin) { int ret; mutex_lock_nested(&dapm->card->dapm_mutex, SND_SOC_DAPM_CLASS_RUNTIME); ret = snd_soc_dapm_set_pin(dapm, pin, 1); mutex_unlock(&dapm->card->dapm_mutex); return ret; } EXPORT_SYMBOL_GPL(snd_soc_dapm_enable_pin); /** * snd_soc_dapm_force_enable_pin_unlocked - force a pin to be enabled * @dapm: DAPM context * @pin: pin name * * Enables input/output pin regardless of any other state. This is * intended for use with microphone bias supplies used in microphone * jack detection. * * Requires external locking. * * NOTE: snd_soc_dapm_sync() needs to be called after this for DAPM to * do any widget power switching. */ int snd_soc_dapm_force_enable_pin_unlocked(struct snd_soc_dapm_context *dapm, const char *pin) { struct snd_soc_dapm_widget *w = dapm_find_widget(dapm, pin, true); if (!w) { dev_err(dapm->dev, "ASoC: unknown pin %s\n", pin); return -EINVAL; } dev_dbg(w->dapm->dev, "ASoC: force enable pin %s\n", pin); if (!w->connected) { /* * w->force does not affect the number of input or output paths, * so we only have to recheck if w->connected is changed */ dapm_widget_invalidate_input_paths(w); dapm_widget_invalidate_output_paths(w); w->connected = 1; } w->force = 1; dapm_mark_dirty(w, "force enable"); return 0; } EXPORT_SYMBOL_GPL(snd_soc_dapm_force_enable_pin_unlocked); /** * snd_soc_dapm_force_enable_pin - force a pin to be enabled * @dapm: DAPM context * @pin: pin name * * Enables input/output pin regardless of any other state. This is * intended for use with microphone bias supplies used in microphone * jack detection. * * NOTE: snd_soc_dapm_sync() needs to be called after this for DAPM to * do any widget power switching. */ int snd_soc_dapm_force_enable_pin(struct snd_soc_dapm_context *dapm, const char *pin) { int ret; mutex_lock_nested(&dapm->card->dapm_mutex, SND_SOC_DAPM_CLASS_RUNTIME); ret = snd_soc_dapm_force_enable_pin_unlocked(dapm, pin); mutex_unlock(&dapm->card->dapm_mutex); return ret; } EXPORT_SYMBOL_GPL(snd_soc_dapm_force_enable_pin); /** * snd_soc_dapm_disable_pin_unlocked - disable pin. * @dapm: DAPM context * @pin: pin name * * Disables input/output pin and its parents or children widgets. * * Requires external locking. * * NOTE: snd_soc_dapm_sync() needs to be called after this for DAPM to * do any widget power switching. */ int snd_soc_dapm_disable_pin_unlocked(struct snd_soc_dapm_context *dapm, const char *pin) { return snd_soc_dapm_set_pin(dapm, pin, 0); } EXPORT_SYMBOL_GPL(snd_soc_dapm_disable_pin_unlocked); /** * snd_soc_dapm_disable_pin - disable pin. * @dapm: DAPM context * @pin: pin name * * Disables input/output pin and its parents or children widgets. * * NOTE: snd_soc_dapm_sync() needs to be called after this for DAPM to * do any widget power switching. */ int snd_soc_dapm_disable_pin(struct snd_soc_dapm_context *dapm, const char *pin) { int ret; mutex_lock_nested(&dapm->card->dapm_mutex, SND_SOC_DAPM_CLASS_RUNTIME); ret = snd_soc_dapm_set_pin(dapm, pin, 0); mutex_unlock(&dapm->card->dapm_mutex); return ret; } EXPORT_SYMBOL_GPL(snd_soc_dapm_disable_pin); /** * snd_soc_dapm_nc_pin_unlocked - permanently disable pin. * @dapm: DAPM context * @pin: pin name * * Marks the specified pin as being not connected, disabling it along * any parent or child widgets. At present this is identical to * snd_soc_dapm_disable_pin() but in future it will be extended to do * additional things such as disabling controls which only affect * paths through the pin. * * Requires external locking. * * NOTE: snd_soc_dapm_sync() needs to be called after this for DAPM to * do any widget power switching. */ int snd_soc_dapm_nc_pin_unlocked(struct snd_soc_dapm_context *dapm, const char *pin) { return snd_soc_dapm_set_pin(dapm, pin, 0); } EXPORT_SYMBOL_GPL(snd_soc_dapm_nc_pin_unlocked); /** * snd_soc_dapm_nc_pin - permanently disable pin. * @dapm: DAPM context * @pin: pin name * * Marks the specified pin as being not connected, disabling it along * any parent or child widgets. At present this is identical to * snd_soc_dapm_disable_pin() but in future it will be extended to do * additional things such as disabling controls which only affect * paths through the pin. * * NOTE: snd_soc_dapm_sync() needs to be called after this for DAPM to * do any widget power switching. */ int snd_soc_dapm_nc_pin(struct snd_soc_dapm_context *dapm, const char *pin) { int ret; mutex_lock_nested(&dapm->card->dapm_mutex, SND_SOC_DAPM_CLASS_RUNTIME); ret = snd_soc_dapm_set_pin(dapm, pin, 0); mutex_unlock(&dapm->card->dapm_mutex); return ret; } EXPORT_SYMBOL_GPL(snd_soc_dapm_nc_pin); /** * snd_soc_dapm_get_pin_status - get audio pin status * @dapm: DAPM context * @pin: audio signal pin endpoint (or start point) * * Get audio pin status - connected or disconnected. * * Returns 1 for connected otherwise 0. */ int snd_soc_dapm_get_pin_status(struct snd_soc_dapm_context *dapm, const char *pin) { struct snd_soc_dapm_widget *w = dapm_find_widget(dapm, pin, true); if (w) return w->connected; return 0; } EXPORT_SYMBOL_GPL(snd_soc_dapm_get_pin_status); /** * snd_soc_dapm_ignore_suspend - ignore suspend status for DAPM endpoint * @dapm: DAPM context * @pin: audio signal pin endpoint (or start point) * * Mark the given endpoint or pin as ignoring suspend. When the * system is disabled a path between two endpoints flagged as ignoring * suspend will not be disabled. The path must already be enabled via * normal means at suspend time, it will not be turned on if it was not * already enabled. */ int snd_soc_dapm_ignore_suspend(struct snd_soc_dapm_context *dapm, const char *pin) { struct snd_soc_dapm_widget *w = dapm_find_widget(dapm, pin, false); if (!w) { dev_err(dapm->dev, "ASoC: unknown pin %s\n", pin); return -EINVAL; } w->ignore_suspend = 1; return 0; } EXPORT_SYMBOL_GPL(snd_soc_dapm_ignore_suspend); /** * snd_soc_dapm_free - free dapm resources * @dapm: DAPM context * * Free all dapm widgets and resources. */ void snd_soc_dapm_free(struct snd_soc_dapm_context *dapm) { dapm_debugfs_cleanup(dapm); dapm_free_widgets(dapm); list_del(&dapm->list); } EXPORT_SYMBOL_GPL(snd_soc_dapm_free); static void soc_dapm_shutdown_dapm(struct snd_soc_dapm_context *dapm) { struct snd_soc_card *card = dapm->card; struct snd_soc_dapm_widget *w; LIST_HEAD(down_list); int powerdown = 0; mutex_lock(&card->dapm_mutex); list_for_each_entry(w, &dapm->card->widgets, list) { if (w->dapm != dapm) continue; if (w->power) { dapm_seq_insert(w, &down_list, false); w->power = 0; powerdown = 1; } } /* If there were no widgets to power down we're already in * standby. */ if (powerdown) { if (dapm->bias_level == SND_SOC_BIAS_ON) snd_soc_dapm_set_bias_level(dapm, SND_SOC_BIAS_PREPARE); dapm_seq_run(card, &down_list, 0, false); if (dapm->bias_level == SND_SOC_BIAS_PREPARE) snd_soc_dapm_set_bias_level(dapm, SND_SOC_BIAS_STANDBY); } mutex_unlock(&card->dapm_mutex); } /* * snd_soc_dapm_shutdown - callback for system shutdown */ void snd_soc_dapm_shutdown(struct snd_soc_card *card) { struct snd_soc_dapm_context *dapm; list_for_each_entry(dapm, &card->dapm_list, list) { if (dapm != &card->dapm) { soc_dapm_shutdown_dapm(dapm); if (dapm->bias_level == SND_SOC_BIAS_STANDBY) snd_soc_dapm_set_bias_level(dapm, SND_SOC_BIAS_OFF); } } soc_dapm_shutdown_dapm(&card->dapm); if (card->dapm.bias_level == SND_SOC_BIAS_STANDBY) snd_soc_dapm_set_bias_level(&card->dapm, SND_SOC_BIAS_OFF); } /* Module information */ MODULE_AUTHOR("Liam Girdwood, lrg@slimlogic.co.uk"); MODULE_DESCRIPTION("Dynamic Audio Power Management core for ALSA SoC"); MODULE_LICENSE("GPL");
kendling/android_kernel_google_dragon
sound/soc/soc-dapm.c
C
gpl-2.0
109,499
using System; using System.Collections.Generic; using System.Data; using System.Text; using Meta.Net.Objects; namespace Meta.Net.Metadata.Factories { internal class CheckConstraintFactory { private int SchemaNameOrdinal { get; set; } private int TableNameOrdinal { get; set; } private int ColumnNameOrdinal { get; set; } private int ObjectNameOrdinal { get; set; } private int DefinitionOrdinal { get; set; } private int IsTableConstraintOrdinal { get; set; } private int IsDisabledOrdinal { get; set; } private int IsNotForReplicationOrdinal { get; set; } private int IsNotTrustedOrdinal { get; set; } private int IsSystemNamedOrdinal { get; set; } public CheckConstraintFactory(IDataRecord reader) { SchemaNameOrdinal = reader.GetOrdinal("SchemaName"); TableNameOrdinal = reader.GetOrdinal("TableName"); ColumnNameOrdinal = reader.GetOrdinal("ColumnName"); ObjectNameOrdinal = reader.GetOrdinal("ObjectName"); DefinitionOrdinal = reader.GetOrdinal("Definition"); IsTableConstraintOrdinal = reader.GetOrdinal("IsTableConstraint"); IsDisabledOrdinal = reader.GetOrdinal("IsDisabled"); IsNotForReplicationOrdinal = reader.GetOrdinal("IsNotForReplication"); IsNotTrustedOrdinal = reader.GetOrdinal("IsNotTrusted"); IsSystemNamedOrdinal = reader.GetOrdinal("IsSystemNamed"); } public void CreateCheckConstraint( Dictionary<string, UserTable> userTables, IDataReader reader) { var schemaName = Convert.ToString(reader[SchemaNameOrdinal]); var tableName = Convert.ToString(reader[TableNameOrdinal]); var userTableNamespaceBuilder = new StringBuilder(schemaName.Length + tableName.Length + 1); userTableNamespaceBuilder.Append(schemaName). Append(Constants.Dot). Append(tableName); var userTableNamespace = userTableNamespaceBuilder.ToString(); if (!userTables.ContainsKey(userTableNamespace)) return; var userTable = userTables[userTableNamespace]; if (userTable == null) return; var checkConstraint = new CheckConstraint { UserTable = userTable, ColumnName = Convert.ToString(reader[ColumnNameOrdinal]), ObjectName = Convert.ToString(reader[ObjectNameOrdinal]), Definition = Convert.ToString(reader[DefinitionOrdinal]), IsTableConstraint = Convert.ToBoolean(reader[IsTableConstraintOrdinal]), IsDisabled = Convert.ToBoolean(reader[IsDisabledOrdinal]), IsNotForReplication = Convert.ToBoolean(reader[IsNotForReplicationOrdinal]), IsNotTrusted = Convert.ToBoolean(reader[IsNotTrustedOrdinal]), IsSystemNamed = Convert.ToBoolean(reader[IsSystemNamedOrdinal]) }; userTable.CheckConstraints.Add(checkConstraint); } } }
OhRyanOh/Meta.Net
Meta.Net/Metadata/Factories/CheckConstraintFactory.cs
C#
gpl-2.0
3,157
// ---------------------------------------------------------------------- // // // // Copyright (c) 2007-2014 // // Digital Beacon, LLC // // // // ---------------------------------------------------------------------- // using System; using System.Collections; namespace DigitalBeacon.Model { /// This is the interface for all business objects that have a code property /// </summary> public interface ICodedEntity : IBaseEntity { /// <summary> /// The code property /// </summary> string Code { get; set; } } }
digitalbeacon/sitebase
Model/ICodedEntity.cs
C#
gpl-2.0
790
//gsoapopt c #import "import/soap12.h" #import "import/xop.h" #import "import/xmime5.h" //gsoap ows schema namespace: http://oracc.org/ws/ows struct ows__Data { @char *ows_status; // return status for method _xop__Include xop__Include; // attachment @char *xmime5__contentType; // and its contentType }; //gsoap ows service method-mime-type: ows__ox text/xml int ows__ox(char *args[], char *session, struct ows__Data *infile, struct ows__Data *logfile); /* //gsoap ows service method-mime-type: ows__ox text/xml int ows__build(char *project, char *scope, char *session, struct ows__Data *in, struct ows__Data *logfile); //gsoap ows service method-mime-type: ows__ox text/xml int ows__check(char *project, char *scope, char *session, struct ows__Data *in, struct ows__Data *logfile); //gsoap ows service method-mime-type: ows__ox text/xml int ows__lemmatize(char *args[], char *session, struct ows__Data *in, struct ows__Data *atffile); int ows__status(char *session, char *status); */
oracc/oracc
c/bin/oraccnet/soap/ows/ows.h
C
gpl-2.0
1,001