content
stringlengths
10
4.9M
package usung.com.mqttclient.utils; import android.content.Context; import android.graphics.Color; import android.text.Spannable; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.style.AbsoluteSizeSpan; import android.text.style.ForegroundColorSpan; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 功能说明<br> * 此类名称和其他包中的类名冲突,在使用是容易混淆,顾更名为helper 2015-01-06 * * @author lijian */ public class StringHelper { static DecimalFormat df = new DecimalFormat("#.00"); public static boolean isEmpty(String str) { if (null == str || "".compareTo(str) == 0 || "null".equals(str)) { return true; } return false; } public static boolean isNotEmpty(String str) { if (null == str || "".compareTo(str) == 0 || "null".equals(str)) { return false; } return true; } /** * 转换为String * * @param obj * @return */ public static String toStrNotNull(Object obj) { if (null == obj || "null".equals(obj)) { return ""; } else { return String.valueOf(obj); } } /** * 转换为int double float类型的字符串 * * @param obj * @return */ public static String toIntNotNull(Object obj) { if (null == obj || "null".equals(obj)) { return "0"; } else { return String.valueOf(obj); } } public static String replace(String inString, String oldPattern, String newPattern) { if (inString == null) { return null; } if (oldPattern == null || newPattern == null) { return inString; } StringBuffer sbuf = new StringBuffer(); int pos = 0; int index = inString.indexOf(oldPattern); int patLen = oldPattern.length(); while (index >= 0) { sbuf.append(inString.substring(pos, index)); sbuf.append(newPattern); pos = index + patLen; index = inString.indexOf(oldPattern, pos); } sbuf.append(inString.substring(pos)); return sbuf.toString(); } /** * 数字字符串转ASCII码字符串 * * @return ASCII字符串 */ public static String StringToAsciiString(String content) { String result = ""; int max = content.length(); for (int i = 0; i < max; i++) { char c = content.charAt(i); String b = Integer.toHexString(c); result = result + b; } return result; } /** * 十六进制字符串装十进制 * * @param hex 十六进制字符串 * @return 十进制数值 */ public static int hexStringToAlgorism(String hex) { hex = hex.toUpperCase(); int max = hex.length(); int result = 0; for (int i = max; i > 0; i--) { char c = hex.charAt(i - 1); int algorism = 0; if (c >= '0' && c <= '9') { algorism = c - '0'; } else { algorism = c - 55; } result += Math.pow(16, max - i) * algorism; } return result; } /** * 十六转二进制 * * @param hex 十六进制字符串 * @return 二进制字符串 */ public static String hexStringToBinary(String hex) { hex = hex.toUpperCase(); String result = ""; int max = hex.length(); for (int i = 0; i < max; i++) { char c = hex.charAt(i); switch (c) { case '0': result += "0000"; break; case '1': result += "0001"; break; case '2': result += "0010"; break; case '3': result += "0011"; break; case '4': result += "0100"; break; case '5': result += "0101"; break; case '6': result += "0110"; break; case '7': result += "0111"; break; case '8': result += "1000"; break; case '9': result += "1001"; break; case 'A': result += "1010"; break; case 'B': result += "1011"; break; case 'C': result += "1100"; break; case 'D': result += "1101"; break; case 'E': result += "1110"; break; case 'F': result += "1111"; break; } } return result; } /** * ASCII码字符串转数字字符串 * * @return 字符串 */ public static String AsciiStringToString(String content) { String result = ""; int length = content.length() / 2; for (int i = 0; i < length; i++) { String c = content.substring(i * 2, i * 2 + 2); int a = hexStringToAlgorism(c); char b = (char) a; String d = String.valueOf(b); result += d; } return result; } /** * 将十进制转换为指定长度的十六进制字符串 * * @param algorism int 十进制数字 * @param maxLength int 转换后的十六进制字符串长度 * @return String 转换后的十六进制字符串 */ public static String algorismToHEXString(int algorism, int maxLength) { String result = ""; result = Integer.toHexString(algorism); if (result.length() % 2 == 1) { result = "0" + result; } return patchHexString(result.toUpperCase(), maxLength); } /** * 字节数组转为普通字符串(ASCII对应的字符) * * @param bytearray byte[] * @return String */ public static String bytetoString(byte[] bytearray) { String result = ""; char temp; int length = bytearray.length; for (int i = 0; i < length; i++) { temp = (char) bytearray[i]; result += temp; } return result; } /** * 二进制字符串转十进制 * * @param binary 二进制字符串 * @return 十进制数值 */ public static int binaryToAlgorism(String binary) { int max = binary.length(); int result = 0; for (int i = max; i > 0; i--) { char c = binary.charAt(i - 1); int algorism = c - '0'; result += Math.pow(2, max - i) * algorism; } return result; } /** * 十进制转换为十六进制字符串 * * @param algorism int 十进制的数字 * @return String 对应的十六进制字符串 */ public static String algorismToHEXString(int algorism) { String result = ""; result = Integer.toHexString(algorism); if (result.length() % 2 == 1) { result = "0" + result; } result = result.toUpperCase(); return result; } /** * HEX字符串前补0,主要用于长度位数不足。 * * @param str String 需要补充长度的十六进制字符串 * @param maxLength int 补充后十六进制字符串的长度 * @return 补充结果 */ static public String patchHexString(String str, int maxLength) { String temp = ""; for (int i = 0; i < maxLength - str.length(); i++) { temp = "0" + temp; } str = (temp + str).substring(0, maxLength); return str; } /** * 将一个字符串转换为int * * @param s String 要转换的字符串 * @param defaultInt int 如果出现异常,默认返回的数字 * @param radix int 要转换的字符串是什么进制的,如16 8 10. * @return int 转换后的数字 */ public static int parseToInt(String s, int defaultInt, int radix) { int i = 0; try { i = Integer.parseInt(s, radix); } catch (NumberFormatException ex) { i = defaultInt; } return i; } /** * 将一个十进制形式的数字字符串转换为int * * @param s String 要转换的字符串 * @param defaultInt int 如果出现异常,默认返回的数字 * @return int 转换后的数字 */ public static int parseToInt(String s, int defaultInt) { int i = 0; try { i = Integer.parseInt(s); } catch (NumberFormatException ex) { i = defaultInt; } return i; } /** * 十六进制串转化为byte数组 * * @return the array of byte */ public static final byte[] hex2byte(String hex) throws IllegalArgumentException { if (hex.length() % 2 != 0) { throw new IllegalArgumentException(); } char[] arr = hex.toCharArray(); byte[] b = new byte[hex.length() / 2]; for (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) { String swap = "" + arr[i++] + arr[i]; int byteint = Integer.parseInt(swap, 16) & 0xFF; b[j] = new Integer(byteint).byteValue(); } return b; } /** * 字节数组转换为十六进制字符串 * * @param b byte[] 需要转换的字节数组 * @return String 十六进制字符串 */ public static final String byte2hex(byte b[]) { if (b == null) { throw new IllegalArgumentException( "Argument b ( byte array ) is null! "); } String hs = ""; String stmp = ""; for (int n = 0; n < b.length; n++) { stmp = Integer.toHexString(b[n] & 0xff); if (stmp.length() == 1) { hs = hs + "0" + stmp; } else { hs = hs + stmp; } } return hs.toUpperCase(); } /** * 检查密码格式 * * @param passwd * @return */ public static boolean checkPWD(String passwd) { char item; boolean charRight = false; for (int i = 0; i < passwd.length(); i++) { item = passwd.charAt(i); if ((item >= '0' && item <= '9') || (item >= 'a' && item <= 'z') || (item >= 'A' && item <= 'Z')) { charRight = true; } else { charRight = false; } } if (charRight == true) { return true; } return charRight; } /** * 字符串为null时转为0 */ public static int null2Zero(Integer it) { if (null == it) { return 0; } else { try { return it; } catch (Exception e) { return 0; } } } /** * 验证信用卡号是否符合规则 * * @param creditCardNO * @return */ public static boolean creditCardVailid(String creditCardNO) { Pattern pattern = Pattern.compile("^[0-9]{16}$"); Matcher m = pattern.matcher(creditCardNO); return m.matches(); } /** * 保留2位小数 * * @param data * @return */ public static String formatDecimalData(Double data) { if (data == null) { return ""; } else { if (df == null) { df = new DecimalFormat(); } return df.format(data); } } /** * 保留2位小数 * * @param data * @return */ public static String formatDecimalData(String data) { if (data == null) { return ""; } else { if (df == null) { df = new DecimalFormat(); } return df.format(Double.valueOf(data)); } } /** * 保留n位小数 */ public static String formatDecimalData(double data, int n) { StringBuilder builder = new StringBuilder("0."); for (int i = 0; i < n; i++) { builder.append("0"); } DecimalFormat df = new DecimalFormat(builder.toString()); return df.format(Double.valueOf(data)); } /** * 校验登录名 * * @param name * @return */ public static boolean checkLoginName(String name) { String regex = "^[a-zA-Z]\\w*$"; Pattern pattern = Pattern.compile(regex); Matcher m = pattern.matcher(name); return m.matches(); } /** * 校验密码 * * @param passWord * @return */ public static boolean checkPassWord(String passWord) { return passWord.length() >= 6; } /** * 校验登录名*(登录名只能是数字或英文字母) * * @param name * @return */ public static boolean checkLoginNameTwo(String name) { String regex = "^[A-Za-z0-9]+$"; Pattern pattern = Pattern.compile(regex); Matcher m = pattern.matcher(name); return m.matches(); } /** * 判断是Jsonobject还是jsonarray或者不是json对象 */ public enum JSON_TYPE { /** * JSONObject */ JSON_TYPE_OBJECT, /** * JSONArray */ JSON_TYPE_ARRAY, /** * 不是JSON格式的字符串 */ JSON_TYPE_ERROR } /*** * 获取JSON类型 判断规则 判断第一个字母是否为{或[ 如果都不是则不是一个JSON格式的文本 * 校验是否是json对象(包括JSONObject、JSONArray) * * @param str * @return */ public static JSON_TYPE getJSONType(String str) { if (TextUtils.isEmpty(str)) { return JSON_TYPE.JSON_TYPE_ERROR; } final char[] strChar = str.substring(0, 1).toCharArray(); final char firstChar = strChar[0]; if (firstChar == '{') { return JSON_TYPE.JSON_TYPE_OBJECT; } else if (firstChar == '[') { return JSON_TYPE.JSON_TYPE_ARRAY; } else { return JSON_TYPE.JSON_TYPE_ERROR; } } /** * 传一个list进来,过滤掉list里相同的元素,只保留一个 StringHelper.getOnlyoneList(hasSame(list)); */ public static ArrayList<Object> getOnlyoneList(HashSet<Object> set) { ArrayList<Object> arrayList = new ArrayList<Object>(); Iterator<Object> it = set.iterator(); while (it.hasNext()) { Object object = it.next(); arrayList.add(object); } return arrayList; } public static HashSet<Object> hasSame(List<? extends Object> list) { if (null == list) { return new HashSet<Object>(); } else { return new HashSet<Object>(list); } } /** * 剪切并拼接“...”到字符串 * * @param start 截取起始 * @param end 截取结束 * @param length 期望限定的字符串长度 * @param str 待操作的字符串 * @return */ public static String subAndAppndString(int start, int end, int length, String str) { String tempStr = ""; if (isNotEmpty(str)) { if (str.length() < length) { tempStr = str; } else { tempStr = str.substring(start, end) + "..."; } } return tempStr; } /** * 数字转中文,仅支持1-5 * * @return */ public static String numTOChinese(int tempRate) { String tempStr = ""; switch (tempRate) { case 1: tempStr = "一"; break; case 2: tempStr = "二"; break; case 3: tempStr = "三"; break; case 4: tempStr = "四"; break; case 5: tempStr = "五"; break; default: break; } return tempStr; } /** * 清除指定的字符串 * * @param tempString 待操作的字符串 * @param clearString 需要清除的字符 * @return */ public static String ClearString(String tempString, String clearString) { String str = ""; if (tempString.contains(clearString)) { str = tempString.replace(clearString, "").trim(); } else { str = tempString; } return str; } /** * 改变部分字体的颜色 * * @param context 上下文 * @param content 需要改变的内容 * @param colorResid 颜色值 * @param startOffset 开始位置 * @param endOffset 结束位置 * @return 改变后的样式 */ public static SpannableStringBuilder changePartTextColor(Context context, String content, int colorResid, int startOffset, int endOffset) { SpannableStringBuilder style = new SpannableStringBuilder(content); style.setSpan(new ForegroundColorSpan(context.getResources().getColor(colorResid)), startOffset, endOffset, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); return style; } /** * 改变部分文字大小 * * @param context 上下文 * @param content 内容 * @param textSize 大小 * @param startOffset 开始位置 * @param endOffset 结束位置 * @return 改变后的样式 */ public static SpannableStringBuilder changePartTextSize(Context context, String content, int textSize, int startOffset, int endOffset) { SpannableStringBuilder style = new SpannableStringBuilder(content); style.setSpan(new AbsoluteSizeSpan(textSize, true), startOffset, endOffset, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); return style; } /** * 截取指定字符并替换成”*“ * * @param str_Old * @param start * @param end */ public static String interceptAndReplaceChar(String str_Old, int start, int end) { if (TextUtils.isEmpty(str_Old) || str_Old.length() < end) { return ""; } //字符串截取 String str_Intercept = str_Old.substring(start, end); //字符串替换 String str_New = str_Old.replaceFirst(str_Intercept, "****"); return str_New; } /** * 校验手机号 * * @param phoneNO * @return */ public static boolean phoneNOAvailable(String phoneNO) { if (isEmpty(phoneNO)) { return false; } else if (phoneNO.charAt(0) != '1') { return false; } else if (phoneNO.length() != 11) { return false; } else { return true; } } //得到color span public static CharSequence setColorSpanString(String span, String text) { if (text == null) { return null; } if (text.contains(span)) { SpannableString string = new SpannableString(text); int start = text.indexOf(span); int end = start + span.length(); string.setSpan(new ForegroundColorSpan(Color.RED), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); return string; } else { return text; } } public static String returnTargetIfNull(String string, String target) { return TextUtils.isEmpty(string) ? target : string; } public static String returnNoIfNull(String string) { return returnTargetIfNull(string, "无"); } /** * 使用java正则表达式去掉多余的.与0 */ public static String subZeroAndDot(String s) { if (s.indexOf(".") > 0 && !s.endsWith(".")) { s = s.replaceAll("0+?$", "");//去掉多余的0 s = s.replaceAll("[.]$", "");//如最后一位是.则去掉 } return s; } }
<filename>nd4j/nd4j-backends/nd4j-backend-impls/nd4j-cuda/src/main/java/org/nd4j/linalg/jcublas/JcusparseNDArrayCSR.java package org.nd4j.linalg.jcublas; import com.google.flatbuffers.FlatBufferBuilder; import org.nd4j.linalg.api.blas.params.MMulTranspose; import org.nd4j.linalg.api.ndarray.BaseSparseNDArrayCSR; import org.nd4j.linalg.api.ndarray.INDArray; /** * @author <NAME> */ public class JcusparseNDArrayCSR extends BaseSparseNDArrayCSR { public JcusparseNDArrayCSR(double[] data, int[] columns, int[] pointerB, int[] pointerE, int[] shape) { super(data, columns, pointerB, pointerE, shape); } @Override public INDArray repeat(int dimension, long... repeats) { return null; } @Override public INDArray mmul(INDArray other, MMulTranspose mMulTranspose) { return null; } /** * Perform an copy matrix multiplication * * @param other the other matrix to perform matrix multiply with * @param result the result ndarray * @param mMulTranspose the transpose status of each array * @return the result of the matrix multiplication */ @Override public INDArray mmul(INDArray other, INDArray result, MMulTranspose mMulTranspose) { return null; } @Override public INDArray mmuli(INDArray other, MMulTranspose transpose) { return null; } @Override public INDArray mmuli(INDArray other, INDArray result, MMulTranspose transpose) { return null; } @Override public INDArray reshape(char order, int... newShape) { return null; } @Override public INDArray reshape(int[] shape) { return null; } @Override public int toFlatArray(FlatBufferBuilder builder) { throw new UnsupportedOperationException(); } @Override public INDArray convertToHalfs() { return null; } @Override public INDArray convertToFloats() { return null; } @Override public INDArray convertToDoubles() { return null; } /** * This method returns true if this INDArray is special case: no-value INDArray * * @return */ @Override public boolean isEmpty() { throw new UnsupportedOperationException(); } }
def _CreateProgressTracker(patch_job_name): stages = [ progress_tracker.Stage( 'Generating instance details...', key='pre-summary'), progress_tracker.Stage( 'Reporting instance details...', key='with-summary') ] return progress_tracker.StagedProgressTracker( message='Executing patch job [{0}]'.format(patch_job_name), stages=stages)
def _handle_protocol_error(self, exception: urllib3.exceptions.ProtocolError, log_callback: Callable[[str], None]): if (len(exception.args) < 2) or not isinstance(exception.args[1], urllib3.exceptions.InvalidChunkLength): raise exception log_callback("OpenShift API server closed connection")
/* input : --i : the span index --u : the variable that lies on the knot span --p : the degree of the polynomial --U : the knot vector */ func basisFuns(i int, u float64, p int, U []int) []float64 { N := make([]float64, p+1) left := make([]float64, p+1) right := make([]float64, p+1) N[0] = 1. for j := 1; j <= p; j++ { left[j] = u - float64(U[i+1-j]) right[j] = float64(U[i+j]) - u saved := 0. for r := 0; r < j; r++ { temp := N[r] / (right[r+1] + left[j-r]) N[r] = saved + right[r+1]*temp saved = left[j-r] * temp } N[j] = saved } return N }
def extract_vectors_ped_feature(residues, conformations, key=None, peds=None, features=None, indexes=False, index_slices=False): begin = end = -1 residues = int(residues) conformations = int(conformations) slices = [] if key == 'PED_ID' or index_slices: begin = 0 end = 1 slices.append(slice(begin, end)) if key == 'RD' or index_slices: begin = 1 end = conformations + 1 slices.append(slice(begin, end)) if key == 'EN' or index_slices: begin = conformations + 1 end = conformations + residues + 1 slices.append(slice(begin, end)) if key == 'MED_ASA' or index_slices: begin = conformations + residues + 1 end = conformations + 2 * residues + 1 slices.append(slice(begin, end)) if key == 'MED_RMSD' or index_slices: begin = conformations + 2 * residues + 1 end = conformations + 3 * residues + 1 slices.append(slice(begin, end)) if key == 'MED_DIST' or index_slices: begin = conformations + 3 * residues + 1 end = int(conformations + 3 * residues + 1 + residues * (residues - 1) / 2) slices.append(slice(begin, end)) if key == 'STD_DIST' or index_slices: begin = int(conformations + 3 * residues + 1 + residues * (residues - 1) / 2) end = None slices.append(slice(begin, end)) begin = int(begin) if end is not None: end = int(end) if begin == -1: return None if index_slices: return slices if indexes is True or features is None: return begin, end if peds is None: return features[:, begin:end] else: if isinstance(peds, int): return np.array(features[peds][begin:end]) else: return features[peds, begin:end]
IDIAP Higher-Order Statistics in Visual Object In this paper, we develop a higher-order statistical theory of matching models against images. The basic idea is not only to take into account how much of an object can be seen in the image, but also what parts of it are jointly present. We show that this additional information can improve the speciicity (i.e., reduce the probability of false positive matches) of a recognition algorithm. We demonstrate formally that most commonly used quality of match measures employed by recognition algorithms are based on an independence assumption. Using the Minimum Description Length (MDL) principle and a simple scene-description language as a guide, we show that this independence assumption is not satissed for common scenes, and propose several important higher-order statistical properties of matches that approximate some aspects of these statistical dependencies. We have implemented a recognition system that takes advantage of this additional statistical information and demonstrate its eecacy in comparisons with a standard recognition system based on bounded error matching. We also observe that the existing use of grouping and segmentation methods has signiicant eeects on the performance of recognition systems that are similar to those resulting from the use of higher-order statistical information. Our analysis provides a statistical framework in which to understand the effects of grouping and segmentation on recognition and suggests ways to take better advantage of such information. 1 (a) (b) Figure 1: Standard recognition algorithms work well for objects with well-deened geometries (a), but fail to recognize even simple natural objects (Snoopy's head, b).
// ServeHTTP takes the url of the requested resource to be fetched on the // origin and puts in in the request's context to be used later by the proxy director. func (p *proxy) ServeHTTP(w http.ResponseWriter, req *http.Request) { if req.URL.Path != p.path { w.WriteHeader(http.StatusBadGateway) return } q := req.URL.Query().Get("q") if q == "" { w.WriteHeader(http.StatusBadGateway) return } origin, err := url.Parse(q) if err != nil { w.WriteHeader(http.StatusBadGateway) return } ctx := context.WithValue(req.Context(), originKey, origin) p.ReverseProxy.ServeHTTP(w, req.WithContext(ctx)) }
/** * This helper method executes the loops necessary to enforce overhangs for * each graph in enforceOverhangRules * */ private int enforceOverhangRulesHelper(RNode parent, ArrayList<RNode> children, RNode root, int count) { String nextLOverhang = new String(); for (int i = 0; i < children.size(); i++) { RNode child = children.get(i); _parentHash.put(child, parent); if (i == 0) { child.setLOverhang(parent.getLOverhang()); } else if (i == children.size() - 1) { child.setROverhang(parent.getROverhang()); } if (child.getLOverhang().isEmpty()) { if (!nextLOverhang.isEmpty()) { child.setLOverhang(nextLOverhang); nextLOverhang = ""; } else { child.setLOverhang(Integer.toString(count)); count++; } } if (child.getROverhang().isEmpty()) { child.setROverhang(Integer.toString(count)); nextLOverhang = Integer.toString(count); count++; } if (child.getStage() > 0) { ArrayList<RNode> grandChildren = new ArrayList<RNode>(); grandChildren.addAll(child.getNeighbors()); if (grandChildren.contains(parent)) { grandChildren.remove(parent); } count = enforceOverhangRulesHelper(child, grandChildren, root, count); } else { ArrayList<RNode> l0nodes = _rootBasicNodeHash.get(root); l0nodes.add(child); _rootBasicNodeHash.put(root, l0nodes); } } return count; }
<reponame>dstrants/swarm_deploy package containers import ( "errors" "fmt" "strings" "swarm_deploy/lib/slack" log "github.com/sirupsen/logrus" "github.com/docker/docker/api/types/swarm" docker "github.com/fsouza/go-dockerclient" ) //Parse image name and tag func ParseImageName(full_name string) (string, string, error) { result := strings.Split(full_name, ":") if len(result) != 2 { err := errors.New("Parsing failed for image: " + full_name) return "", "", err } return result[0], result[1], nil } // Selects the swarm services that need to be updated based on image // and swarm label func LocateServices(image string) []swarm.Service { client, err := docker.NewClientFromEnv() if err != nil { panic(err) } allServices, err := client.ListServices(docker.ListServicesOptions{}) if err != nil { log.Printf("There was an error while trying to list the services. %v", err) } var toBeUpdated []swarm.Service for _, service := range allServices { currentImage, _, imageError := ParseImageName(service.Spec.Labels["com.docker.stack.image"]) if imageError != nil { log.WithFields( log.Fields{ "incoming_image": image, "current_image": service.Spec.Labels["com.docker.stack.image"], "service": service.PreviousSpec.Name, }).Error("Could not parse current image to compare with incoming. Service will be skipped.") continue } if currentImage == image && service.Spec.Labels["swarm_deploy"] == "true" { toBeUpdated = append(toBeUpdated, service) } } return toBeUpdated } // Updates a service to given image func UpdateServiceImage(service swarm.Service, image string) bool { client, err := docker.NewClientFromEnv() if err != nil { panic(err) } service.Spec.TaskTemplate.ContainerSpec.Image = image var updateConfig docker.UpdateServiceOptions updateConfig.ServiceSpec = service.Spec updateConfig.Version = service.Version.Index err = client.UpdateService(service.ID, updateConfig) if err != nil { log.WithFields(log.Fields{"service": service, "image": image}).Error("Service update failed,") return false } return true } // Parent function that triggers locating and updating services func UpdateAllServices(image, tag string) { services := LocateServices(image) if len(services) == 0 { log.WithFields(log.Fields{"image": image}).Warning("No services found for the given image.") return } full_image := fmt.Sprintf("%s:%s", image, tag) for _, service := range services { result := UpdateServiceImage(service, full_image) if result { slack.SendSimpleMessage(fmt.Sprintf("Service `%s` has been deployed with image `%s`", service.Spec.Name, full_image)) log.WithFields(log.Fields{"service": service.Spec.Name, "image": full_image}).Info("Service image updated") } } }
/** * Allows the user to sign up or return to the log in page. * @author Talal Abou Haiba */ public class SignupActivity extends AppCompatActivity { private DatabaseReference mDatabase; private FirebaseAuth mAuth; private ProgressDialog mProgressDialog; private EditText mNameField; private EditText mEmailField; private EditText mPasswordField; private TextView mLoginButton; private Button mSignupButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_signup); mNameField = (EditText) findViewById(R.id.input_name); mEmailField = (EditText) findViewById(R.id.input_email); mPasswordField = (EditText) findViewById(R.id.input_password); mDatabase = FirebaseDatabase.getInstance().getReference(); mAuth = FirebaseAuth.getInstance(); mLoginButton = (TextView) findViewById(R.id.button_login); mSignupButton = (Button) findViewById(R.id.button_signup); mLoginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), LoginActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); startActivity(intent); } }); mSignupButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { signup(); } }); } /** * Removes transition when moving back to {@link LoginActivity} */ @Override public void onPause() { super.onPause(); overridePendingTransition(0,0); } private void signup() { if (!validateInput()) { return; } mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage("Signing up"); mProgressDialog.setIndeterminate(true); mProgressDialog.show(); authenticateSignup(); } private void authenticateSignup() { final String email = mEmailField.getText().toString(); final String password = mPasswordField.getText().toString(); mAuth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { successfulSignup(); writeNewUser(email, task.getResult().getUser().getUid()); } else { unsuccessfulSignup(); } } }); } private void successfulSignup() { mProgressDialog.dismiss(); Intent intent = new Intent(getApplicationContext(), LoginActivity.class); intent.putExtra("USERNAME", mEmailField.getText().toString()); startActivity(intent); finish(); } private void unsuccessfulSignup() { mProgressDialog.dismiss(); Toast.makeText(SignupActivity.this, "Error creating account", Toast.LENGTH_SHORT).show(); } private void writeNewUser(String email, String uuid) { System.out.println("Writing user: " + email + " " + uuid); mDatabase.child("users").child(uuid).child("name").setValue(mNameField.getText().toString()); } private boolean validateInput() { String nameInput = mNameField.getText().toString(); String emailInput = mEmailField.getText().toString(); String passwordInput = mPasswordField.getText().toString(); if (nameInput.isEmpty()) { mNameField.setError("Please enter your name"); mNameField.requestFocus(); return false; } else { mNameField.setError(null); } if (emailInput.isEmpty() || !Patterns.EMAIL_ADDRESS.matcher(emailInput).matches()) { mEmailField.setError("Please enter a valid email address"); mEmailField.requestFocus(); return false; } else { mEmailField.setError(null); } if (passwordInput.isEmpty() || passwordInput.length() < 6) { mPasswordField.setError("Please enter a valid password" + " containing at least 6 characters."); mPasswordField.requestFocus(); return false; } else { mPasswordField.setError(null); } return true; } }
n = list(input()) fx = 0 #print(n) for i in n: fx += int(i) nn = ''.join(n) nnn = int(nn) #print(fx) #print(nnn) if nnn%fx == 0: print('Yes') else: print('No')
/** Start the service. This entails unloading the AuthConf file contents * using the LoginConfigService. */ protected void stopService() throws Exception { MBeanServer server = super.getServer(); flushAuthenticationCaches(); if( configNames != null && configNames.length > 0 ) { Object[] args = {configNames}; String[] sig = {configNames.getClass().getName()}; server.invoke(loginConfigService, "removeConfigs", args, sig); } }
//pattern1 def pyramid(p): for m in range(0, p): for n in range(0, m+1): print("* ",end="") print("\r") p = 5 pyramid(p) //pattern2 def pyramid(p): X = 2*p - 2 for m in range(0, p): for n in range(0, X): print(end=" ") X = X - 2 for n in range(0, m+1): print("* ", end="") print("\r") p = 10 pyramid(p) //pattern3 n = 0 r = 5 for m in range(1, r+1): for gap in range(1, (r-m)+1): print(end=" ") while n != (2*m-1): print("* ", end="") n = n + 1 n = 0 print() //pattern5 length = 6 k = (2 * length) - 2 for p in range(0, length): for n in range(0, k): print(end=" ") k = k - 1 for n in range(0, p + 1): print("@", end=' ') print(" ") Output
package org.wikipedia.dataclient.mwapi; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.google.gson.annotations.SerializedName; import org.apache.commons.lang3.StringUtils; import org.wikipedia.dataclient.WikiSite; import org.wikipedia.gallery.ImageInfo; import org.wikipedia.gallery.VideoInfo; import org.wikipedia.json.PostProcessingTypeAdapter; import org.wikipedia.model.BaseModel; import org.wikipedia.notifications.Notification; import org.wikipedia.page.PageTitle; import org.wikipedia.settings.SiteInfo; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MwQueryResult extends BaseModel implements PostProcessingTypeAdapter.PostProcessable { @SuppressWarnings("unused") @Nullable private List<MwQueryPage> pages; @SuppressWarnings("unused") @Nullable private List<Redirect> redirects; @SuppressWarnings("unused") @Nullable private List<ConvertedTitle> converted; @SuppressWarnings("unused") @SerializedName("userinfo") private UserInfo userInfo; @SuppressWarnings("unused") @Nullable private List<ListUserResponse> users; @SuppressWarnings("unused") @Nullable private Tokens tokens; @SuppressWarnings("unused,NullableProblems") @SerializedName("authmanagerinfo") @Nullable private MwAuthManagerInfo amInfo; @SuppressWarnings("unused") @Nullable private MarkReadResponse echomarkread; @SuppressWarnings("unused") @Nullable private MarkReadResponse echomarkseen; @SuppressWarnings("unused,NullableProblems") @Nullable private NotificationList notifications; @Nullable private Map<String, Notification.UnreadNotificationWikiItem> unreadnotificationpages; @SuppressWarnings("unused") @SerializedName("general") @Nullable private SiteInfo generalSiteInfo; @Nullable public List<MwQueryPage> pages() { return pages; } @Nullable public MwQueryPage firstPage() { if (pages != null && pages.size() > 0) { return pages.get(0); } return null; } @Nullable public UserInfo userInfo() { return userInfo; } @Nullable public String csrfToken() { return tokens != null ? tokens.csrf() : null; } @Nullable public String createAccountToken() { return tokens != null ? tokens.createAccount() : null; } @Nullable public String loginToken() { return tokens != null ? tokens.login() : null; } @Nullable public NotificationList notifications() { return notifications; } @Nullable public Map<String, Notification.UnreadNotificationWikiItem> unreadNotificationWikis() { return unreadnotificationpages; } @Nullable public MarkReadResponse getEchoMarkSeen() { return echomarkseen; } @Nullable public String captchaId() { String captchaId = null; if (amInfo != null) { for (MwAuthManagerInfo.Request request : amInfo.requests()) { if ("CaptchaAuthenticationRequest".equals(request.id())) { captchaId = request.fields().get("captchaId").value(); } } } return captchaId; } @Nullable public ListUserResponse getUserResponse(@NonNull String userName) { if (users != null) { for (ListUserResponse user : users) { // MediaWiki user names are case sensitive, but the first letter is always capitalized. if (StringUtils.capitalize(userName).equals(user.name())) { return user; } } } return null; } @NonNull public Map<String, ImageInfo> images() { Map<String, ImageInfo> result = new HashMap<>(); if (pages != null) { for (MwQueryPage page : pages) { if (page.imageInfo() != null) { result.put(page.title(), page.imageInfo()); } } } return result; } @NonNull public Map<String, VideoInfo> videos() { Map<String, VideoInfo> result = new HashMap<>(); if (pages != null) { for (MwQueryPage page : pages) { if (page.videoInfo() != null) { result.put(page.title(), page.videoInfo()); } } } return result; } @NonNull public List<PageTitle> langLinks() { List<PageTitle> result = new ArrayList<>(); if (pages == null || pages.isEmpty() || pages.get(0).langLinks() == null) { return result; } // noinspection ConstantConditions for (MwQueryPage.LangLink link : pages.get(0).langLinks()) { PageTitle title = new PageTitle(link.title(), WikiSite.forLanguageCode(link.lang())); result.add(title); } return result; } @NonNull public List<NearbyPage> nearbyPages(@NonNull WikiSite wiki) { List<NearbyPage> result = new ArrayList<>(); if (pages != null) { for (MwQueryPage page : pages) { NearbyPage nearbyPage = new NearbyPage(page, wiki); if (nearbyPage.getLocation() != null) { result.add(nearbyPage); } } } return result; } @Nullable public SiteInfo siteInfo() { return generalSiteInfo; } @Override public void postProcess() { resolveConvertedTitles(); resolveRedirectedTitles(); } private void resolveRedirectedTitles() { if (redirects == null || pages == null) { return; } for (MwQueryPage page : pages) { for (MwQueryResult.Redirect redirect : redirects) { // TODO: Looks like result pages and redirects can also be matched on the "index" // property. Confirm in the API docs and consider updating. if (page.title().equals(redirect.to())) { page.redirectFrom(redirect.from()); if (redirect.toFragment() != null) { page.appendTitleFragment(redirect.toFragment()); } } } } } private void resolveConvertedTitles() { if (converted == null || pages == null) { return; } // noinspection ConstantConditions for (MwQueryResult.ConvertedTitle convertedTitle : converted) { // noinspection ConstantConditions for (MwQueryPage page : pages) { if (page.title().equals(convertedTitle.to())) { page.convertedFrom(convertedTitle.from()); page.convertedTo(convertedTitle.to()); } } } } private static class Redirect { @SuppressWarnings("unused") private int index; @SuppressWarnings("unused") @Nullable private String from; @SuppressWarnings("unused") @Nullable private String to; @SuppressWarnings("unused") @SerializedName("tofragment") @Nullable private String toFragment; @Nullable public String to() { return to; } @Nullable public String from() { return from; } @Nullable public String toFragment() { return toFragment; } } public static class ConvertedTitle { @SuppressWarnings("unused") @Nullable private String from; @SuppressWarnings("unused") @Nullable private String to; @Nullable public String to() { return to; } @Nullable public String from() { return from; } } private static class Tokens { @SuppressWarnings("unused,NullableProblems") @SerializedName("csrftoken") @Nullable private String csrf; @SuppressWarnings("unused,NullableProblems") @SerializedName("createaccounttoken") @Nullable private String createAccount; @SuppressWarnings("unused,NullableProblems") @SerializedName("logintoken") @Nullable private String login; @Nullable private String csrf() { return csrf; } @Nullable private String createAccount() { return createAccount; } @Nullable private String login() { return login; } } public static class MarkReadResponse { @SuppressWarnings("unused") @Nullable private String result; @SuppressWarnings("unused,NullableProblems") @Nullable private String timestamp; @Nullable public String getResult() { return result; } @Nullable public String getTimestamp() { return timestamp; } } public static class NotificationList { @SuppressWarnings("unused") private int count; @SuppressWarnings("unused") private int rawcount; @SuppressWarnings("unused") @Nullable private Notification.SeenTime seenTime; @SuppressWarnings("unused") @Nullable private List<Notification> list; @SuppressWarnings("unused") @SerializedName("continue") @Nullable private String continueStr; @Nullable public List<Notification> list() { return list; } @Nullable public String getContinue() { return continueStr; } public int getCount() { return count; } @Nullable public Notification.SeenTime getSeenTime() { return seenTime; } } }
<filename>mozillians/users/models.py import logging import os import uuid from itertools import chain from django.conf import settings from django.contrib.auth.models import User from django.db import models from django.db.models import Manager, ManyToManyField from django.utils.encoding import iri_to_uri from django.utils.http import urlquote from django.utils.translation import ugettext as _ from django.utils.translation import ugettext_lazy as _lazy from mozillians.common.urlresolvers import reverse from mozillians.phonebook.validators import validate_email from mozillians.users.managers import ( EMPLOYEES, MOZILLIANS, PRIVACY_CHOICES, PRIVACY_CHOICES_WITH_PRIVATE, PRIVATE, PUBLIC, PUBLIC_INDEXABLE_FIELDS, UserProfileQuerySet, ) AVATAR_SIZE = (300, 300) logger = logging.getLogger(__name__) ProfileManager = Manager.from_queryset(UserProfileQuerySet) def _calculate_photo_filename(instance, filename): """Generate a unique filename for uploaded photo.""" return os.path.join(settings.USER_AVATAR_DIR, str(uuid.uuid4()) + ".jpg") class PrivacyField(models.PositiveSmallIntegerField): def __init__(self, *args, **kwargs): myargs = {"default": MOZILLIANS, "choices": PRIVACY_CHOICES} myargs.update(kwargs) super(PrivacyField, self).__init__(*args, **myargs) class UserProfilePrivacyModel(models.Model): _privacy_level = None privacy_full_name = PrivacyField() privacy_email = PrivacyField( choices=PRIVACY_CHOICES_WITH_PRIVATE, default=MOZILLIANS ) privacy_date_mozillian = PrivacyField() privacy_title = PrivacyField() CACHED_PRIVACY_FIELDS = None class Meta: abstract = True @classmethod def clear_privacy_fields_cache(cls): """ Clear any caching of the privacy fields. (This is only used in testing.) """ cls.CACHED_PRIVACY_FIELDS = None @classmethod def privacy_fields(cls): """ Return a dictionary whose keys are the names of the fields in this model that are privacy-controlled, and whose values are the default values to use for those fields when the user is not privileged to view their actual value. Note: should be only used through UserProfile . We should fix this. """ # Cache on the class object if cls.CACHED_PRIVACY_FIELDS is None: privacy_fields = {} field_names = list( set( chain.from_iterable( (field.name, field.attname) if hasattr(field, "attname") else (field.name,) for field in cls._meta.get_fields() if not (field.many_to_one and field.related_model is None) ) ) ) for name in field_names: if ( name.startswith("privacy_") or not "privacy_%s" % name in field_names ): # skip privacy fields and uncontrolled fields continue field = cls._meta.get_field(name) # Okay, this is a field that is privacy-controlled # Figure out a good default value for it (to show to users # who aren't privileged to see the actual value) if isinstance(field, ManyToManyField): default = field.remote_field.model.objects.none() else: default = field.get_default() privacy_fields[name] = default # HACK: There's not really an email field on UserProfile, # but it's faked with a property privacy_fields["email"] = "" cls.CACHED_PRIVACY_FIELDS = privacy_fields return cls.CACHED_PRIVACY_FIELDS class UserProfile(UserProfilePrivacyModel): objects = ProfileManager() user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField( max_length=255, default="", blank=False, verbose_name=_lazy("Full Name") ) is_vouched = models.BooleanField( default=False, help_text="You can edit vouched status by editing invidual vouches", ) can_vouch = models.BooleanField( default=False, help_text="You can edit can_vouch status by editing invidual vouches", ) last_updated = models.DateTimeField(auto_now=True) date_mozillian = models.DateField( "When was involved with Mozilla", null=True, blank=True, default=None ) # This is the Auth0 user ID. We are saving only the primary here. auth0_user_id = models.CharField(max_length=1024, default="", blank=True) is_staff = models.BooleanField(default=False) def __unicode__(self): """Return this user's name when their profile is called.""" return self.display_name def get_absolute_url(self): return reverse("phonebook:profile_view", args=[self.user.username]) class Meta: db_table = "profile" ordering = ["full_name"] def __getattribute__(self, attrname): """Special privacy aware __getattribute__ method. This method returns the real value of the attribute of object, if the privacy_level of the attribute is at least as large as the _privacy_level attribute. Otherwise it returns a default privacy respecting value for the attribute, as defined in the privacy_fields dictionary. special_functions provides methods that privacy safe their respective properties, where the privacy modifications are more complex. """ _getattr = lambda x: super(UserProfile, self).__getattribute__(x) privacy_fields = UserProfile.privacy_fields() privacy_level = _getattr("_privacy_level") special_functions = { "accounts": "_accounts", "alternate_emails": "_alternate_emails", "email": "_primary_email", "is_public_indexable": "_is_public_indexable", "vouches_made": "_vouches_made", "vouches_received": "_vouches_received", "vouched_by": "_vouched_by", "identity_profiles": "_identity_profiles", } if attrname in special_functions: return _getattr(special_functions[attrname]) if not privacy_level or attrname not in privacy_fields: return _getattr(attrname) field_privacy = _getattr("privacy_%s" % attrname) if field_privacy < privacy_level: return privacy_fields.get(attrname) return _getattr(attrname) def _filter_accounts_privacy(self, accounts): if self._privacy_level: return accounts.filter(privacy__gte=self._privacy_level) return accounts @property def _accounts(self): _getattr = lambda x: super(UserProfile, self).__getattribute__(x) excluded_types = [ExternalAccount.TYPE_EMAIL] accounts = _getattr("externalaccount_set").exclude(type__in=excluded_types) return self._filter_accounts_privacy(accounts) @property def _alternate_emails(self): _getattr = lambda x: super(UserProfile, self).__getattribute__(x) accounts = _getattr("externalaccount_set").filter( type=ExternalAccount.TYPE_EMAIL ) return self._filter_accounts_privacy(accounts) @property def _identity_profiles(self): _getattr = lambda x: super(UserProfile, self).__getattribute__(x) accounts = _getattr("idp_profiles").all() return self._filter_accounts_privacy(accounts) @property def _is_public_indexable(self): for field in PUBLIC_INDEXABLE_FIELDS: if ( getattr(self, field, None) and getattr(self, "privacy_%s" % field, None) == PUBLIC ): return True return False @property def _primary_email(self): _getattr = lambda x: super(UserProfile, self).__getattribute__(x) privacy_fields = UserProfile.privacy_fields() if self._privacy_level: # Try IDP contact first if self.idp_profiles.exists(): contact_ids = self.identity_profiles.filter( primary_contact_identity=True ) if contact_ids.exists(): return contact_ids[0].email return "" # Fallback to user.email if _getattr("privacy_email") < self._privacy_level: return privacy_fields["email"] # In case we don't have a privacy aware attribute access if self.idp_profiles.filter(primary_contact_identity=True).exists(): return self.idp_profiles.filter(primary_contact_identity=True)[0].email return _getattr("user").email @property def _vouched_by(self): privacy_level = self._privacy_level voucher = UserProfile.objects.filter(vouches_made__vouchee=self).order_by( "vouches_made__date" ) if voucher.exists(): voucher = voucher[0] if privacy_level: voucher.set_instance_privacy_level(privacy_level) for field in UserProfile.privacy_fields(): if getattr(voucher, "privacy_%s" % field) >= privacy_level: return voucher return None return voucher return None def _vouches(self, type): _getattr = lambda x: super(UserProfile, self).__getattribute__(x) vouch_ids = [] for vouch in _getattr(type).all(): vouch.vouchee.set_instance_privacy_level(self._privacy_level) for field in UserProfile.privacy_fields(): if ( getattr(vouch.vouchee, "privacy_%s" % field, 0) >= self._privacy_level ): vouch_ids.append(vouch.id) vouches = _getattr(type).filter(pk__in=vouch_ids) return vouches @property def _vouches_made(self): _getattr = lambda x: super(UserProfile, self).__getattribute__(x) if self._privacy_level: return self._vouches("vouches_made") return _getattr("vouches_made") @property def _vouches_received(self): _getattr = lambda x: super(UserProfile, self).__getattribute__(x) if self._privacy_level: return self._vouches("vouches_received") return _getattr("vouches_received") @property def display_name(self): return self.full_name @property def privacy_level(self): """Return user privacy clearance.""" if self.user.is_superuser: return PRIVATE if self.is_vouched: return MOZILLIANS return PUBLIC @property def is_complete(self): """Tests if a user has all the information needed to move on past the original registration view. """ return self.display_name.strip() != "" @property def is_public(self): """Return True is any of the privacy protected fields is PUBLIC.""" # TODO needs update for field in type(self).privacy_fields(): if getattr(self, "privacy_%s" % field, None) == PUBLIC: return True return False @property def is_manager(self): return self.user.is_superuser @property def date_vouched(self): """ Return the date of the first vouch, if available.""" vouches = self.vouches_received.all().order_by("date")[:1] if vouches: return vouches[0].date return None def set_instance_privacy_level(self, level): """Sets privacy level of instance.""" self._privacy_level = level def set_privacy_level(self, level, save=True): """Sets all privacy enabled fields to 'level'.""" for field in type(self).privacy_fields(): setattr(self, "privacy_%s" % field, level) if save: self.save() def is_vouchable(self, voucher): """Check whether self can receive a vouch from voucher.""" # If there's a voucher, they must be able to vouch. if voucher and not voucher.can_vouch: return False # Maximum VOUCH_COUNT_LIMIT vouches per account, no matter what. if self.vouches_received.all().count() >= settings.VOUCH_COUNT_LIMIT: return False # If you've already vouched this account, you cannot do it again vouch_query = self.vouches_received.filter(voucher=voucher) if voucher and vouch_query.exists(): return False return True def save(self, *args, **kwargs): self._privacy_level = None autovouch = kwargs.pop("autovouch", False) super(UserProfile, self).save(*args, **kwargs) # Auto_vouch follows the first save, because you can't # create foreign keys without a database id. if autovouch: self.auto_vouch() class IdpProfile(models.Model): """Basic Identity Provider information for Profiles.""" PROVIDER_UNKNOWN = 0 PROVIDER_PASSWORDLESS = 10 PROVIDER_GOOGLE = 20 PROVIDER_GITHUB = 30 PROVIDER_FIREFOX_ACCOUNTS = 31 PROVIDER_LDAP = 40 PROVIDER_TYPES = ( ( PROVIDER_UNKNOWN, "Unknown Provider", ), ( PROVIDER_PASSWORDLESS, "Passwordless Provider", ), ( PROVIDER_GOOGLE, "Google Provider", ), ( PROVIDER_GITHUB, "Github Provider", ), ( PROVIDER_FIREFOX_ACCOUNTS, "Firefox Accounts Provider", ), ( PROVIDER_LDAP, "LDAP Provider", ), ) # High Security OPs HIGH_AAL_ACCOUNTS = [ PROVIDER_LDAP, PROVIDER_FIREFOX_ACCOUNTS, PROVIDER_GITHUB, PROVIDER_GOOGLE, ] profile = models.ForeignKey( UserProfile, related_name="idp_profiles", on_delete=models.CASCADE ) type = models.IntegerField( choices=PROVIDER_TYPES, default=None, null=True, blank=False ) # Auth0 required data auth0_user_id = models.CharField(max_length=1024, default="", blank=True) primary = models.BooleanField(default=False) email = models.EmailField(blank=True, default="") created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) privacy = models.PositiveIntegerField( default=MOZILLIANS, choices=PRIVACY_CHOICES_WITH_PRIVATE ) primary_contact_identity = models.BooleanField(default=False) username = models.CharField(max_length=1024, default="", blank=True) def get_provider_type(self): """Helper method to autopopulate the model type given the user_id.""" if "ad|" in self.auth0_user_id: return self.PROVIDER_LDAP if "oauth2|firefoxaccounts" in self.auth0_user_id: return self.PROVIDER_FIREFOX_ACCOUNTS if "github|" in self.auth0_user_id: return self.PROVIDER_GITHUB if "google-oauth2|" in self.auth0_user_id: return self.PROVIDER_GOOGLE if "email|" in self.auth0_user_id: return self.PROVIDER_PASSWORDLESS return self.PROVIDER_UNKNOWN def save(self, *args, **kwargs): """Custom save method. Provides a default contact identity and a helper to assign the provider type. """ self.type = self.get_provider_type() # If there isn't a primary contact identity, create one if not ( IdpProfile.objects.filter( profile=self.profile, primary_contact_identity=True ).exists() ): self.primary_contact_identity = True super(IdpProfile, self).save(*args, **kwargs) # Save profile.privacy_email when a primary contact identity changes profile = self.profile if self.primary_contact_identity: profile.privacy_email = self.privacy # Set the user id in the userprofile too if self.primary: profile.auth0_user_id = self.auth0_user_id profile.save() def __unicode__(self): return "{}|{}|{}".format(self.profile, self.type, self.email) class Meta: unique_together = ("profile", "type", "email") class Vouch(models.Model): vouchee = models.ForeignKey( UserProfile, related_name="vouches_received", on_delete=models.CASCADE ) voucher = models.ForeignKey( UserProfile, related_name="vouches_made", null=True, default=None, blank=True, on_delete=models.SET_NULL, ) description = models.TextField( max_length=500, verbose_name=_lazy("Reason for Vouching"), default="" ) autovouch = models.BooleanField(default=False) date = models.DateTimeField() class Meta: verbose_name_plural = "vouches" unique_together = ("vouchee", "voucher") ordering = ["-date"] def __unicode__(self): return "{0} vouched by {1}".format(self.vouchee, self.voucher) class UsernameBlacklist(models.Model): value = models.CharField(max_length=30, unique=True) is_regex = models.BooleanField(default=False) def __unicode__(self): return self.value class Meta: ordering = ["value"] class ExternalAccount(models.Model): # Constants for type field values. TYPE_EMAIL = "EMAIL" # Account type field documentation: # name: The name of the service that this account belongs to. What # users see # url: If the service features profile pages for its users, then # this field should be a link to that profile page. User's # identifier should be replaced by the special string # {identifier}. # validator: Points to a function which will clean and validate # user's entry. Function should return the cleaned # data. ACCOUNT_TYPES = { TYPE_EMAIL: { "name": "Alternate email address", "url": "", "validator": validate_email, } } user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) identifier = models.CharField( max_length=255, verbose_name=_lazy("Account Username") ) type = models.CharField( max_length=30, choices=sorted( [(k, v["name"]) for (k, v) in ACCOUNT_TYPES.items() if k != "EMAIL"], key=lambda x: x[1], ), verbose_name=_lazy("Account Type"), ) privacy = models.PositiveIntegerField( default=MOZILLIANS, choices=PRIVACY_CHOICES_WITH_PRIVATE ) class Meta: ordering = ["type"] unique_together = ("identifier", "type", "user") def get_identifier_url(self): url = self.ACCOUNT_TYPES[self.type]["url"].format( identifier=urlquote(self.identifier) ) if self.type == "LINKEDIN" and "://" in self.identifier: return self.identifier return iri_to_uri(url) def unique_error_message(self, model_class, unique_check): if model_class == type(self) and unique_check == ("identifier", "type", "user"): return _("You already have an account with this name and type.") else: return super(ExternalAccount, self).unique_error_message( model_class, unique_check ) def __unicode__(self): return self.type
s=input() if s[0]=='-': a1=int(s[:-1]) a2=int(s[:-2]+s[-1]) if a1>a2: print(a1) else: print(a2) else: print(s)
# Simple graph object using visual python from vpython import * gr1 = graph( width=600, height=450,\ title="Visual 2D graph", xtitle="x", ytitle="f(x)",\ foreground=color.black, background=color.white) plot1 = gcurve(color = color.cyan) for x in arange(0.0, 8.1, 0.1): plot1.plot(pos=(x, 5.0 * cos(2.0 * x) * exp(-0.4 * x) )) # plot the points gr2 = graph( width=600, height=450,\ title="Visual 2D graph", xtitle="x", ytitle="f(x)",\ foreground=color.black, background=color.white) plot2 = gdots(color = color.black) for x in arange(-5.0, 5.0, 0.1): plot2.plot( pos = (x, cos(x)) )
<reponame>murawaki/bayes-autologistic from collections import defaultdict from itertools import combinations import glob import os from collections import OrderedDict import numpy as np from .utils import collect_autologistic_results AREA2SPEC = [ # area, start, end (inclusive), color, marker ("Phonology", range(1, 19+1), "r", "o"), ("Morphology", range(20, 29+1), "g", "v"), ("Nominal Categories", range(30, 57+1), "b", "^"), ("Nominal Syntax", range(58, 64+1), "olive", "<"), ("Verbal Categories", range(65, 80+1), "purple", ">"), ("Word Order", range(81, 97+1), "pink", "D"), ("Simple Clause", range(98, 121+1), "cyan", "s"), ("Complex Sentences", range(122, 128+1), "magenta", "p"), ("Lexicon", range(129, 138+1), "black", "*"), # Sign Languages ("Other", range(141, 142+1), "grey", "h"), ("Word Order", range(143, 144+1), "pink", "D"), ] def analyze_param_results(dir_results_pah): path = os.path.join(dir_results_pah, 'param/**/*.json') jsons = glob.glob(path, recursive=True) results = collect_autologistic_results(jsons) vs = np.array(list(map(lambda x: results[x][0]['parameters']['v'], results))) hs = np.array(list(map(lambda x: results[x][0]['parameters']['h'], results))) print("v max: ", np.max(vs)) print("h max: ", np.max(hs)) results = _group_params_per_areas(results) if len(results) == 0: return _print_param_results(results) _plot_param_results(results) def _group_params_per_areas(results): results_per_cat = defaultdict(list) for feature in results: params = results[feature][0]['parameters'] v = params['v'] h = params['h'] area_n = int(feature.split(' ')[0][0:-1]) cat, c, m = _search_category(area_n) results_per_cat[cat].append( OrderedDict({ 'feature': feature, 'values': { 'v': v, 'h': h, 'vh': v/h }, 'color': c, 'mark': m, 'sampled_params': { 'v': np.array(list(map(lambda x: x["v"], results[feature][0]["sampled_params"]))), 'h': np.array(list(map(lambda x: x["h"], results[feature][0]["sampled_params"]))), }, "estimate_results": results[feature][0]["estimate_results"] }) ) return results_per_cat def _print_param_results(results_per_cat): for category in results_per_cat: for param in results_per_cat[category]: feature = "{0:<120}".format(param['feature']) print(feature, end="\t", sep="") # 2sd: 95 percent confidence interval (frequentist) assuming a Normal distribution (not used) from sklearn.preprocessing import StandardScaler ss = StandardScaler() ss.fit(np.expand_dims(param['sampled_params']['v'], axis=1)) v_std = ss.scale_[0] ss = StandardScaler() ss.fit(np.expand_dims(param['sampled_params']['h'], axis=1)) h_std = ss.scale_[0] print(_format_value(param['values']['v']), "\t+_", _format_value(2.0 * v_std), "\t", _format_value(param['values']['h']), "\t+_", _format_value(2.0 * h_std), ) def _format_value(value): return ('{0:9.8f}').format(value) def _search_category(area_n): found = False for cat, n_range, c, m in AREA2SPEC: if area_n in n_range: found = True break if found: return (cat, c, m) print(area_n) return (False, None, 'o') def _plot_param_results(results_per_cat): import matplotlib matplotlib.rcParams['text.usetex'] = True # matplotlib.rc('pdf', fonttype=42) matplotlib.rcParams["font.family"] = 'serif' import matplotlib.pyplot as plt fig, ax = plt.subplots() catlegend = {} plt.xlabel(r"$h_i$", size="24") plt.ylabel(r"$v_i$", size="24") plt.xticks(np.linspace(0.0, 0.030, num=7), size="18") plt.yticks(np.linspace(0.0, 0.040, num=9), size="18") plt.xlim((0.0, 0.025)) plt.ylim((0.0, 0.035)) # plt.xticks(np.linspace(-0.01, 0.020, num=4), size="18") # plt.yticks(np.linspace(-0.03, 0.020, num=6), size="18") # plt.xlim((-0.01, 0.02)) # plt.ylim((-0.035, 0.028)) plt.axhline(color="black") plt.axvline(color="black") for category in results_per_cat: for param in results_per_cat[category]: # feature_id = param['feature'].split(' ') dot = plt.scatter(param['values']['h'], param['values']['v'], s=15, c=param['color'], marker=param['mark'], label=category) if not category: continue if category not in catlegend: catlegend[category] = dot catlegend_sorted = [] for cat in sorted(catlegend.keys()): catlegend_sorted.append(catlegend[cat]) plt.legend( handles=catlegend_sorted, loc='center left', bbox_to_anchor=(1.0, 0.5), scatterpoints=1, fontsize=15) plt.savefig('autologistic_params.pdf', bbox_inches="tight")
/** * A functional interface (oh, please come Java 8 - you cannot come soon * enough) to help manage out-of-control boilerplate-itis in SQL code. * * @author Alex Kalderimis * * @param <T> The return type of the operation. */ public abstract class SQLOperation<T> { /** * The code that the operation represents. * @param stm A prepared statement. * @return A T (whatever that is). * @throws SQLException whenever you even think of touching the statement. */ public abstract T run(PreparedStatement stm) throws SQLException; }
/** * Debugging support. It is expected that in a real project, the * file Debug.java will be physically replaced with a different source * code file that * implements the same public API. For a deploy build, * it should * have ASSERT set false, and LEVEL set to 0. For a debug * build, it will almost certainly send the debug output somewhere more * useful than stderr/stdout. * <p> * Replacing a source file and re-building a library may be * unfamiliar to some Java programmers, but C programmers * will instantly recognize this as the assert.h idiom. * This way of doing things has fallen out of favor for * desktop programming, but it is this author's opinion * that the efficiency gain from stripping out assertions * and debug statements at compile time is worth it in * an embedded environment like Blu-ray. * <p> * The GrinXlet application framework (in xlets/GrinXlet) * does as is outlined here -- the GrinXlet build excludes * the version of Debug.java you're reading now, and replaces * it with either a debug version (that sends debug info to * a special screen you can access via the remote control, and * that you can telnet to the player to get), and a deploy version * (that sets the constants so that the compiler strips out * debug and assertions). * <p> * Some people like to solve this problem by having a build system * that edits one or two key source files, to change the value of some * key constants (like ASSERT and LEVEL in this class) depending on the * build. That's a great technique too, but in any case you'll need to * write your own version of Debug.java if you want to go that way. * <p> * Note that the GRIN library was written assuming that the deploy * version of an xlet will be built with ASSERT set false and LEVEL set * to 0. It contains many assertions, some of which are computationally * expensive. Consider, for example, com.hdcookbook.grin.features.Group.java, * which has an assertion that spans a couple of screens and creates a HashSet. * <p> * More discussion of this can be found in * <a href="https://hdcookbook.dev.java.net/issues/show_bug.cgi?id=164">Issue 164</a> * * @author Bill Foote (http://jovial.com) */ public class Debug { /** * Variable to say that assertions are enabled. If * set false, then javac should strip all assertions * out of the generated code. * <p> * Usage: * <pre> * if (Debug.ASSERT && some condition that should be false) { * Debug.println(something interesting); * } * </pre> * <p> * Note that JDK 1.4's assertion facility can't be used * for Blu-Ray, since PBP 1.0 is based on JDK 1.3. **/ public final static boolean ASSERT = true; /** * Debug level. 2 = noisy, 1 = some debug, 0 = none. * See the comments about setting this value in the class comments. */ public final static int LEVEL = 2; /** * Variable to say if time profiling is enabled. * See the comments about setting this value in the class comments. * * @see Profile **/ public final static boolean PROFILE = true; /** * Variable to say if animation profiling is enabled. * See the comments about setting this value in the class comments. * * @see Profile **/ public final static boolean PROFILE_ANIMATION = false; /** * Variable to say if setup profiling is enabled. * See the comments about setting this value in the class comments. * * @see Profile **/ public final static boolean PROFILE_SETUP = false; private Debug() { } public static void println() { if (LEVEL > 0) { println(""); } } public static void println(Object o) { if (LEVEL > 0) { System.err.println(o); } } /** * Called on assertion failure. This is a useful during development: When * you detect a condition that should be impossible, you can trigger an * assertion failure. That means you've found a bug. When an assertion * failure is detected, you basically want to shut everything down, * so that the developer notices immediately, and sees the message. **/ public static void assertFail(String msg) { if (ASSERT) { Thread.dumpStack(); System.err.println("\n*** Assertion failure: " + msg + " ***\n"); AssetFinder.abort(); } } /** * Called on assertion failure. This is a useful during development: When * you detect a condition that should be impossible, you can trigger an * assertion failure. That means you've found a bug. When an assertion * failure is detected, you basically want to shut everything down, * so that the developer notices immediately, and sees the message. **/ public static void assertFail() { if (ASSERT) { assertFail(""); } } /** * Print a stack trace to the debug log, if Debug.LEVEL > 0. Note * that you can also easily use this for the equivalent of * <code>Thread.dumpStack()</code> using this bit of code: * <pre> * try { * throw new RuntimeException("STACK BACKTRACE"); * } catch (RuntimeException ex) { * Debug.printStackTrace(ex); * } * </pre> **/ public static void printStackTrace(Throwable t) { t.printStackTrace(); } static { // Print an obnoxious message to stderr, to try to make sure that // nobody mistakenly uses this version of Debug.java in a production // disc. if (LEVEL > 0) { Debug.println("== NOTE =="); Debug.println(" GRIN debug is enabled, and being sent to stderr."); Debug.println(" If this is a production disc, please disable debug messages and assertions."); Debug.println(" See the class comments of com.hdcookbook.grin.util.Debug for details."); Debug.println(); } } }
/** * Most commonly the {@link ProxyFactoryFactory} will depend directly on the chosen {@link BytecodeProvider}, * however by registering them as two separate services we can allow to override either one * or both of them. * @author Sanne Grinovero */ public final class ProxyFactoryFactoryInitiator implements StandardServiceInitiator<ProxyFactoryFactory> { /** * Singleton access */ public static final StandardServiceInitiator<ProxyFactoryFactory> INSTANCE = new ProxyFactoryFactoryInitiator(); @Override public ProxyFactoryFactory initiateService(Map configurationValues, ServiceRegistryImplementor registry) { final BytecodeProvider bytecodeProvider = registry.getService( BytecodeProvider.class ); return bytecodeProvider.getProxyFactoryFactory(); } @Override public Class<ProxyFactoryFactory> getServiceInitiated() { return ProxyFactoryFactory.class; } }
/** * @author David Romero Alcaide * @param alumnoParseado * @return * @throws ParseException */ private Alumno create(String[] alumnoParseado,Profesor p) throws ParseException { Alumno a = create(); a.setNombre(alumnoParseado[0].trim()); a.setApellidos(alumnoParseado[1].trim()); String curso = alumnoParseado[2].trim(); int nivel = Integer.valueOf(curso.split(" ")[0]); String nivelE = curso.split(" ")[1]; char iden = curso.split(" ")[2].charAt(0); InstanciaCurso c = cursoService.find(nivel, nivelE, iden); Assert.notNull(c); Assert.isTrue(profesorService.getCursosImparteDocencia(p).contains(c)); a.getCursos().add(c); SimpleDateFormat sp = new SimpleDateFormat("mm/dd/yyyy"); a.setFechaNacimiento(sp.parse(alumnoParseado[3])); try { a.setPendiente(alumnoParseado[4].trim()); } catch (ArrayIndexOutOfBoundsException e) { LOGGER.error(e.getMessage(),e); a.setPendiente(" "); } try { a.setRepiteCurso(alumnoParseado[5].trim()); } catch (ArrayIndexOutOfBoundsException e) { LOGGER.error(e.getMessage(),e); a.setRepiteCurso(" "); } return a; }
Absorption of methochlorpromazine in rat small intestinal everted sac. The absorption of methochlorpromazine in rat small intestinal everted sac was investigated. 0.22% of the drug added in mucosal fluid was transferred to serosal fluid for 30 min at 37 degrees C. The absorption of the drug was slightly inhibited by choline, and more markedly inhibited by more hydrophobic quaternary ammonium cations such as tetraethylammonium and cetyltrimethylammonium. Moderate inhibition was observed by a polyamine, spermine. The absorption rate of methochlorpromazine markedly depended on temperature. The Arrhenius plot of the apparent transfer rate constant revealed high activation energy (117 kJ/mol) for the transport. Uptake of methochlorpromazine to a small intestinal segment was also inhibited by other quaternary ammonium cations corresponding with their inhibitory effects on its transport. These results suggest that methochlorpromazine binds to the relatively hydrophobic region of small intestinal epithelial cells and transfers by passing through a high energy barrier.
// Read returns the current value of the set. // An element is in the set if it is in the add map, and its clock is less than // that in remove map (if existing). func (s aworset) Read() tla.TLAValue { set := make([]tla.TLAValue, 0) i := s.addMap.Iterator() for !i.Done() { elem, addVC := i.Next() if remVC, remOK := s.remMap.Get(elem.(tla.TLAValue)); !remOK || addVC.(vclock).compare(remVC.(vclock)) != LT { set = append(set, elem.(tla.TLAValue)) } } return tla.MakeTLASet(set...) }
for g in range(int(input())): e = input().replace('.', '').replace(',', '').lower() e = e.replace('jogo', '#j').replace('perdi', '#p').split() c = m = 0 for x in e: if '#j' != x != '#p': c += len(x) else: c += 4 if x == '#p': c += 1 m < c m = c c = 0 print(m)
Freshly blessed with six Oscar nominations, Mel Gibson’s new second world war film Hacksaw Ridge doesn’t just raise the bar for combat scenes. – it annihilates it. It may have a gun-shy pacifist as its main character, but the initial 15-minute re-creation of the assault on an Okinawan escarpment is a frenzy of cartwheeling bodies, Boy’s Own satchel charges, bunker demolition and a fetish for physical chastisement that is très Mel: the Passion of GI Joe. Directors are frequently compared to generals, and war films are among the most logistically complex and demanding things to shoot. Here, key members of the film crew from Hacksaw and five combat classics explain how they stormed the barricades. Hacksaw Ridge: Mic Rodgers, second-unit director and stunt coordinator Facebook Twitter Pinterest 2016, HACKSAW RIDGE ANDREW GARFIELD Character(s): Desmond T. Doss Photograph: Allstar/LIONSGATE The casualty rate at the Battle of Okinawa was 80%: Mel wanted to show that it was bloody, ferocious, gnarly. But we didn’t have much money: $20m, plus the Australian tax incentive. We recreated the battlefield on a dairy farm near Sydney. It was about 100 metres squared, with a road on the outside where smoke trucks ran, blocking out the farm and the pond and anything else that didn’t look like Okinawa. An offshore shell makes a certain size hole, so we would keep redigging that crater, sometimes over old ones, drop a log in it and say: “Ready for shooting.” Mel was off doing his thing with the actors and the dialogue, while I shot everyone fighting for about 15 days. I was following his instructions, but making it up as I went along. I would take select moments, like a Japanese guy getting blown out of the fireball and flying towards the camera, and send it to him by cellphone. And he would say: “I love it! Do some more of that.” We had about 70 extras, and tiled them with CGI: we shot them six times in sections, so they looked like 250 guys. We didn’t need to train them that much because the level of training in the second world war was not like it is now. We tried to use CGI as little as possible, especially with the stunts. For the flamethrower scenes, we used neoprene hoods with faces laser-printed on them. Once they’re moving and on fire, it looks like a guy screaming. The Australian special-effects guys also developed a soft bomb – one that doesn’t have a hard explosion. You could get pretty close to it. I’m an I’ll-go-first kinda guy; I doubled for Mel on his 80s films. So I did a test, standing between all these bombs, 3ft away. Afterwards, they said: “You got obliterated!” I said: “It’s not that bad if you keep your mouth open – and you’ve got ear plugs.” Saving Private Ryan: Ian Bryce, producer Facebook Twitter Pinterest 1998, SAVING PRIVATE RYAN Photograph: Allstar/WARNER BROS Steven [Spielberg, director] had been working on two other movies, and turned up on set just two days before we shot. Later, he told me why. “When those men and boys had the ramp go down on the landing craft and jumped out in the water, they didn’t know what they were doing.” He wanted to shoot the Omaha beach invasion in the same frame of mind. The graphic nature and detail of what transpired in war, and in particular that landing, had not really been done before. Film-makers previously hadn’t necessarily believed that people would, or could, with the ratings system, watch something that harsh. You can’t shoot on the real Omaha beach in Normandy. There are also some power plants along that coast that we would have had to paint out with VFX in a lot of shots. After scouring pretty much the entire UK without any joy, we went to Ireland and found this beach in County Wexford that had a wide expanse of sand where the incoming tide didn’t fully engulf the beach, so there was room to work. From January 1997 until we shot in mid-June, we excavated and dressed the beach, as well as building the infrastructure to get the 750 Irish army reservists we used in the battle sequences housed, fed and watered. We called it the “sausage machine”: you got pushed in at one end and came out the other battle-trained, to some extent. Tom Hanks, Tom Sizemore and the others went to bootcamp for a week, too – out in the woods. It rained horribly during that whole period, and I was very concerned that they might get sick. They were in second world war tents, eating rations and everything. But it worked out great: they were weathered by the time they got back in. The shooting went very smoothly. It was one of those movies that just had a sense of something special going on. One veteran approached me later and all he said was: “I was there that day, and that’s how it was. I haven’t been able to talk to my family about it for 50 years, and now I can.” The door was open for film-makers to say: “A realistic portrayal has been done, so let’s do our own version.” The Hurt Locker: Barry Ackroyd, cinematographer Facebook Twitter Pinterest 2008, THE HURT LOCKER JEREMY RENNER Character(s): Staff Sergeant William James Photograph: Allstar/FIRST LIGHT PRODUCTION The first thing was to go to a place as realistic as possible. We couldn’t go to Iraq, so we chose Jordan: the buildings and the minarets looked the same; the extras had the same basic bone structure – Middle Eastern, not North African. Kathryn [Bigelow, director] wanted the kind of verisimilitude I had provided on United 93. Long takes with more than one camera observing the characters. We don’t break it down into storyboards; you don’t second-guess where the honest angle would be, you let things happen. That naturalism comes from my background with Ken Loach. If you’re out of focus on a moment such as an explosion, it just makes it more real. We had military advisers, but just about every American actor has played a soldier at some point. They all know the old “I’ve got your back” routine. Richard Stutsman, our explosives guy, was brilliant. He created these things so we could safely blow them up inside a city without spraying shrapnel everywhere, but they still looked powerful. In the opening sequence with Guy Pearce, I didn’t know how to show the air shockwave – that release of energy is so strong it can liquefy the body inside the blast suits. We couldn’t afford to do it with CGI. But someone working in advertising in Lebanon had created something similar with a Phantom high-speed camera. So we got him in and shot the simplest things in super slow-motion. It was like putting gravel on a bit of plywood and having someone hit it with a sledgehammer in the foreground as Pearce was falling in the mid-ground, the explosion in the background. It lifted it from its documentary feel into something that heightened the film. Full Metal Jacket: Jan Harlan, producer Facebook Twitter Pinterest Matthew Modine / Full Metal Jacket 1987 directed by Stanley Kubrick F4P9XK Matthew Modine / Full Metal Jacket 1987 directed by Stanley Kubrick Photograph: Alamy Stock Photo There was no need for Stanley [Kubrick, director] to research military form as he did for Barry Lyndon – the soldiers in Vietnam improvised. The abuse of young men was the key aspect that interested him. Even 2,500 years ago, the Spartan armies succeeded in turning boys into fighters. Unfortunately, Stanley couldn’t find seven good actors of the right age and had to compromise: he preferred slightly older good actors to having the “right” age group and less good actors. The abuse begins with cutting the hair of the young marines, which sets the tone for what follows. We hired real-life marine drill instructor Lee Ermey as technical advisor. He contributed greatly to this symphony of obscenities and ended up playing the part by playing himself. Stanley didn’t want to shoot too far away from home, so the derelict Beckton Gasworks in east London were ideal. We took down the industrial towers and made the site look more like a bombed-out part of Huế city: adding French Indochinese shutters, Vietnamese billboards, fire and smoke, plastic shrubs and palm trees imported from Spain. Firing blanks means nothing, but filming the moment of impact of bullets is a big deal: costly and very time-consuming, since the explosives are hidden in the wall behind “aged” plaster and wiring. Repeats take days of preparation. The big run against the buildings during the sniper scene, with many simulated hits, was done only once, carefully prepared over many days. Working at filthy Beckton was not fun, and Stanley did it as fast as he could. Speed was not his forte. Nor was it Vermeer’s. The sniper scene took several takes, the actors lying in the mud, but it’s all there to set up the moment when Joker responds to the sniper’s plea: “Kill me.” This is the moment of truth behind all the macho talk and joking; it needed to be dramatically prepared to rope the audience in. Apocalypse Now: Doug Claybourne, production assistant (later first-unit AD) Facebook Twitter Pinterest 1979, APOCALYPSE NOW A still from the film Apocalypse Now (1979), directed By Francis Ford Coppola Photograph: Allstar/Cinetext/MIRAMAX The movie was a bit like a war. Every time someone would quit or get fired, I would get promoted. I had expected to be there [in the Philippines] for eight weeks, but ended up staying a year. I had been stationed in Vietnam, refuelling jets in Chu Lai, but I wanted to see more of the country so I volunteered to fly as a Huey door-gunner on my off-time. That’s why Francis [Ford Coppola] hired me as a “helicopter wrangler” for the famous Ride of the Valkyries sequence, which we filmed in April and May 1976. It was a logistical nightmare. The helicopters that the Filipino government lent to us would land on a schoolfield at our base camp in Baler, about 150km north-east of Manila. The prop guys would come over and paint American insignia on them, because they were being used to fight a civil war the rest of the time. I would make sure they were fuelled, had M60 machine guns fitted with blanks, and we had extras sitting in the gunner spots. We would ask for 10 and often five would show up; I would radio the set, and they would do whatever scene they could with that amount. Aerial coordinator Dick White, who had been one of the first Cobra gunship pilots in Vietnam, flew a small Loach helicopter, talking to the Filipino pilots; I was watching down below with an air-to-ground radio. Dick and I would be saying to the helicopters: lower, go left, go right! Trying to get them to stay in the frame, in a horizontal 2:35 format. As for the Wagner, it did seem true to life. The scene where Willard shoots the Vietnamese girl on the boat gave me a deja vu experience. The actors had recently arrived as Vietnamese boat people, yet seven years earlier I had been in their country, supposedly killing them. Now I was making a movie about it. That juxtaposition was very strange for me. Black Hawk Down: Sławomir Idziak, cinematographer Facebook Twitter Pinterest 2001, BLACK HAWK DOWN U.S. TROOPS DROP ON MOGADISHU Photograph: Allstar/SCOTT FREE The philosophy is very simple: the audience is sat in comfortable seats, and you have to attack them. The action must be dense, in terms of the framing and the amount of events. No emptiness. Emptiness is peaceful. You’re packing the audience with an enormous amount of information they can’t control. They get nervous, which is what we’re fishing for. Sometimes that means cheating intelligently. For example, the helicopters often fly 25-30 metres overhead, which is never the case in battle – there’s too much risk of the pilot being killed. Or you never shoot at soldiers with RPGs – they’re for vehicles. Ridley [Scott, director] realised RPGs were visually attractive though, compared with AK fire, where you never see the bullets. For our advisers – we had real Army Rangers on set – watching rockets fly through the air on a line is absolute nonsense. They couldn’t believe their eyes. Jerry Bruckheimer [producer] cut a deal with the US military. They supplied the Black Hawks, straight from the Afghan battlefield; the Night Stalkers unit, the best of the best. The Moroccan army lent us the twin-rotor Chinooks. Our guys – including me, because I operated a camera – also dressed in battle fatigues, and shot in and around the actors. Sometimes you can even see the cameras on screen, but it’s cut so quickly you don’t realise. You think they’re carrying a strange gun. We originally shot a much more balanced picture, in line with Mark Bowden’s original book, that showed both the US and Somali sides. But due to 9/11, we couldn’t stick to this kind of approach. All of a sudden America was at war. To make a picture with pacifistic elements was absolutely impossible. So the finished film is much more from a cowboy point of view. It had to play to this national tragedy. Hacksaw Ridge is released in the UK on 27 January
import gkeepapi from datetime import datetime from gkeepapi import node as g_node from gkeepapi.exception import LoginException from bs4 import BeautifulSoup import logging import sys log = logging.getLogger("gkeep") def login(gaia, pwd): # gkeepapi.node.DEBUG = True keep = gkeepapi.Keep() success = keep.login(gaia, pwd) return keep def parseHTML(html): soup = BeautifulSoup(html, "html5lib") return soup.get_text("\n") def generateBody(note): return "Imported from Apple Note\nOriginal Create Time: %s\nImport Time: %s\n-----------------------\n%s\n-----------------------\nhttps://github.com/adamyi/notes_to_keep" % (note.date_created.strftime("%c"), datetime.now().strftime("%c"), parseHTML(note.data)) def uploadNote(keep, note, no_alter, label, pfx): log.info("Uploading note: " + note.title) gnote = g_node.Note() if pfx is not None: gnote.title = "[%s] %s" % (pfx, note.title) else: gnote.title = note.title if no_alter: gnote.text = parseHTML(note.data) else: gnote.text = generateBody(note) # ts = g_node.NodeTimestamps() # ts.load({'created': note.date_created, 'edited': note.date_edited, 'updated': datetime.now()}) # gnote.timestamps = ts if label is not None: gnote.labels.add(label) keep.add(gnote) # make things slower to sync everytime instead of sync one time finally # however, syncing one time is more error-prone. # in this way, if a sync has an issue, it only affects one single note. keep.sync() def createLabel(keep): name = "notes_to_keep %s" % datetime.now().strftime("%y/%m/%d %H:%M:%S") log.info("Creating label: " + name) label = keep.createLabel(name) return label def start(gaia, pwd, notes, num, pfx, no_alter, no_label): log.info("Logging in gaia account...") try: keep = login(gaia, pwd) except LoginException as e: log.error(e) log.info("If you get the \"ou must sign in on the web\" error, please check https://support.google.com/accounts/answer/2461835 to unlock your account for access without webpage (or generate an App Password if you have enabled 2SV) and try again.") sys.exit(1) log.info("Login completed.") if no_label: label = None log.info("Will not create a label.") else: label = createLabel(keep) if num != None: log.warning("As requested, we will only upload %s note(s)." % num) num = int(num) i = 0 for note in notes: try: i += 1 uploadNote(keep, note, no_alter, label, pfx) if i == num: break except Exception as e: log.error(e) if note.title is not None: log.error("Error parsing/updating this note... Skip this note for now. Title: " + note.title) continue log.info("Done! Have fun~") if __name__ == '__main__': print("This is part of notes_to_keep, which cannot be called separately.")
// ExecuteFetch is part of the DBClient interface func (dc *fakeDBClient) ExecuteFetch(query string, maxrows int) (qr *sqltypes.Result, err error) { if testMode == "debug" { fmt.Printf("ExecuteFetch: %s\n", query) } if dbrs := dc.queries[query]; dbrs != nil { return dbrs.next(query) } for re, dbrs := range dc.queriesRE { if regexp.MustCompile(re).MatchString(query) { return dbrs.next(query) } } if result := dc.invariants[query]; result != nil { return result, nil } for q, result := range dc.invariants { if strings.Contains(query, q) { return result, nil } } log.Infof("Missing query: >>>>>>>>>>>>>>>>>>%s<<<<<<<<<<<<<<<", query) return nil, fmt.Errorf("unexpected query: %s", query) }
package main import ( "testing" "github.com/stretchr/testify/assert" ) func TestCalculateMaxAffectedTenants(t *testing.T) { tests := []struct { nodeTenants [][]int expectedMax int }{ { nodeTenants: nil, expectedMax: 0, }, { nodeTenants: [][]int{ {1, 2, 3}, {4, 5, 6}, }, expectedMax: 0, }, { nodeTenants: [][]int{ {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, }, expectedMax: 0, }, { nodeTenants: [][]int{ {1, 2, 3}, {1, 5, 6}, {1, 8, 9}, }, expectedMax: 1, }, { nodeTenants: [][]int{ {1, 2, 3}, {1, 2, 6}, {1, 2, 9}, }, expectedMax: 2, }, { nodeTenants: [][]int{ {1, 2, 3}, {3, 2, 1}, {4, 5, 6, 7, 8, 9}, }, expectedMax: 3, }, { nodeTenants: [][]int{ {1, 2, 3}, {1, 2, 3, 4, 5, 6}, {1, 2, 3, 7, 8, 9}, }, expectedMax: 3, }, } for _, tc := range tests { assert.Equal(t, tc.expectedMax, calculateMaxAffectedTenants(tc.nodeTenants)) } }
<gh_stars>0 import * as React from "react"; import AlertPanel from "#SRC/js/components/AlertPanel"; import AlertPanelHeader from "#SRC/js/components/AlertPanelHeader"; import JobsPage from "./JobsPage"; import JobCreateEditFormModal from "../JobCreateEditFormModal"; interface JobsOverviewEmptyProps { jobPath?: string[]; } interface JobsOverviewEmptyState { isJobFormModalOpen: boolean; } export default class JobsOverviewEmpty extends React.Component< JobsOverviewEmptyProps, JobsOverviewEmptyState > { constructor() { super(...arguments); this.state = { isJobFormModalOpen: false }; this.handleCloseJobFormModal = this.handleCloseJobFormModal.bind(this); this.handleOpenJobFormModal = this.handleOpenJobFormModal.bind(this); } handleCloseJobFormModal() { this.setState({ isJobFormModalOpen: false }); } handleOpenJobFormModal() { this.setState({ isJobFormModalOpen: true }); } render() { const { jobPath } = this.props; return ( <JobsPage jobPath={jobPath}> <AlertPanel> <AlertPanelHeader>No active jobs</AlertPanelHeader> <p className="tall"> Create both one-off or scheduled jobs to perform tasks at a predefined interval. </p> <div className="button-collection flush-bottom"> <button className="button button-primary" onClick={this.handleOpenJobFormModal} > Create a Job </button> </div> </AlertPanel> <JobCreateEditFormModal open={this.state.isJobFormModalOpen} onClose={this.handleCloseJobFormModal} /> </JobsPage> ); } }
import sys, os from tqdm import tqdm import numpy as np import networkx as nx from rdkit import Chem from rdkit.Chem import Descriptors from rdkit.Chem import RDConfig sys.path.append(os.path.join(RDConfig.RDContribDir, "SA_Score")) import sascorer from util.smiles.dataset import load_dataset from util.smiles.char_dict import SmilesCharDictionary if __name__ == "__main__": char_dict = SmilesCharDictionary(dataset="zinc", max_smi_len=81) dataset = load_dataset(char_dict=char_dict, smi_path="./resource/data/zinc/full.txt") log_ps, sa_scores, atomring_cycle_scores, cyclebasis_cycle_scores = [], [], [], [] for smi in tqdm(dataset): mol = Chem.MolFromSmiles(smi) log_p = Descriptors.MolLogP(mol) sa_score = sascorer.calculateScore(mol) cycle_list = mol.GetRingInfo().AtomRings() largest_ring_size = max([len(j) for j in cycle_list]) if cycle_list else 0 atomring_cycle_score = max(largest_ring_size - 6, 0) cycle_list = nx.cycle_basis(nx.Graph(Chem.rdmolops.GetAdjacencyMatrix(mol))) largest_ring_size = max([len(j) for j in cycle_list]) if cycle_list else 0 cyclebasis_cycle_score = max(largest_ring_size - 6, 0) log_ps.append(log_p) sa_scores.append(sa_score) atomring_cycle_scores.append(atomring_cycle_score) cyclebasis_cycle_scores.append(cyclebasis_cycle_score) print(f"LogP stats: {np.mean(log_ps)}, {np.std(log_ps)}") print(f"SA stats: {np.mean(sa_scores)}, {np.std(sa_scores)}") print(f"AtomRing stats: {np.mean(atomring_cycle_scores)}, {np.std(atomring_cycle_scores)}") print( f"CycleBasis stats: {np.mean(cyclebasis_cycle_scores)}, {np.std(cyclebasis_cycle_scores)}" )
A graduating senior walks on the campus of Columbia University in May. (Amanda Voisard) Carl L. Hart was surprised when a student in one of his classes at Columbia University wrote an essay for The Washington Post about the effect of having him speak frankly about his past and the importance of having non-white faculty members. Hart took the opportunity to respond with his thoughts on race and higher education, in the midst of the national debate over police violence. (Hart writes of cases such as the 2012 shooting death of 18-year-old Ramarley Graham, who had fled from police during a drug investigation in New York, and the 2014 death of another unarmed 18-year-old, Michael Brown, in Ferguson, Mo., which set off nationwide protests.) [Mothers of slain black men speak out for policing changes] Hart is the chair and Dirk Ziff professor of psychology at Columbia University. His book “High Price: A Neuroscientist’s Journey of Self-Discovery That Challenges Everything You Know About Drugs and Society” was given the 2014 PEN/E.O. Wilson Literary Science Writing Award. He tweets at @drcarlhart. — Susan Svrluga Carl Hart (Eileen Barroso) For the past few years, like academic semesters, the killing of black people by the police has been on a regular schedule. The explanation script, always controlled by the police, is familiar and tired. The deceased person’s reputation is dragged through the mud. He had a gun or she was under the influence of some drug; therefore, deadly force was necessary. Video footage almost always contradicts this official account. But it doesn’t seem to matter because the police are rarely held accountable in such cases. As a result, there is community outrage that sometimes reaches the level of unrest. Authorities call for calm and peace — rather than justice — and then we are forced to have the same national conversation about race and diversity that we have had for more than 50 years. The only thing that changes is the names of the pundits paraded before the public. As a professor, a black professor, I often think about the impact that this has on my students, especially the black students. What messages does it send to them? I suspect, with horror, it sends the same ones that I received when in their seats some 30 years ago: “Your life is worthless compared with a white person’s. They are superior to you by the mere fact that they are white in a white-controlled world.” Faced with this wretched reality, every Monday and Wednesday morning, I stand before my Columbia University students honored to have the opportunity to present information that challenges society’s views about black people as well as the perceptions held about drugs, their effects and their role in crime. I speak candidly about my past and who I am. In fact, “High Price,” my science memoir, is one of the required readings for the course. In it, I detail my imperfections and past drug use and sales. I also lay out a blueprint for how one can succeed as a scientist and academic in a world that despises one’s people. I explain how for more than 25 years, I have studied the interactions between the brain, drugs and behavior, trying to understand how drugs influence the function of brain cells, how this and other social factors influence human behavior, and how the reverberations of morality regarding drug use are expressed in social policy. And, as a part of my research, I have given thousands of doses of drugs, including crack cocaine, marijuana and methamphetamine, to people. By the way, I have never seen a research participant become violent or aggressive while under the influence of any drug (at doses typically used recreationally), as police narratives frequently claim. My research has taught me many important lessons, but perhaps none more important than this — drug effects, like semesters, are predictable; police interactions with black people are not. In encounters with police, too often the black person ends up dead. That is why I would much rather my own children interact with drugs than with the police. I am certain that my white colleagues, when faced with an emergency situation, wouldn’t think twice about calling the police. This, however, may not be the case for their black and Latino students. These students may be faced with the dilemma of not calling for police assistance even when they are in need of help for fear that the police will make the situation worse, and may even kill them or their loved one. We need our universities to comprise historically excluded faculty to represent these and other perspectives. For this reason, I served on Columbia’s Task Force on Diversity in Science and Engineering, working to increase the number of diverse faculty in the sciences. Initially, I was excited to participate because I thought the goal was to increase the number of faculty from those groups historically excluded from the academy as a result of discrimination. It turns out that the term “diversity” can be anything from black faculty to military veterans. Well, I am both, but have yet to be subjected to discrimination because I’m a veteran. [An Ivy League professor on why colleges don’t hire more faculty of color: ‘We don’t want them.’] I now cringe whenever subjected to meetings or speeches about the importance of having a diverse campus community. I’m even more appalled when I hear some vacuous university administrator touting their school’s diversity accomplishments. Of the nearly 4,000 faculty members at Columbia, only about 4 percent are black. Yet, we have been honored for our diversity achievements. When compared with similar institutions, our low number of black faculty looks impressive. But when you consider that black people make up 25 percent of the population of New York City, where Columbia is located, 4 percent seems meager. I recognize that New York City might not be the most appropriate comparison, but neither are other exclusive universities whose numbers of black faculty are abysmally low. Teaching university students affords me the opportunity to demonstrate to young adults that they don’t have to be perfect to make contributions to their country. This responsibility also requires me to impress upon my students that they must obtain the necessary critical-thinking skills to be informed and that they should be courageous, especially in the face of injustice. If only more of our university and national leaders did the same, I might not have to look out into the sea of predominantly white faces and hold back tears as I think about the fact that Ramarley Graham and Michael Brown would have begun their junior and senior years, respectively, this semester. Dennis A. Mitchell, vice provost for faculty diversity and inclusion at Columbia, sent a written statement in response:
/** * Computes the world transform of this Spatial in the most * efficient manner possible. */ void checkDoTransformUpdate() { if ((refreshFlags & RF_TRANSFORM) == 0) { return; } if (parent == null) { worldTransform.set(localTransform); refreshFlags &= ~RF_TRANSFORM; } else { TempVars vars = TempVars.get(); Spatial[] stack = vars.spatialStack; Spatial rootNode = this; int i = 0; while (true) { Spatial hisParent = rootNode.parent; if (hisParent == null) { rootNode.worldTransform.set(rootNode.localTransform); rootNode.refreshFlags &= ~RF_TRANSFORM; i--; break; } stack[i] = rootNode; if ((hisParent.refreshFlags & RF_TRANSFORM) == 0) { break; } rootNode = hisParent; i++; } vars.release(); for (int j = i; j >= 0; j--) { rootNode = stack[j]; rootNode.updateWorldTransforms(); } } }
class TextAudioSpeakerCollate: """Zero-pads model inputs and targets""" def __init__(self, return_ids=False): self.return_ids = return_ids def __call__(self, batch): """Collate's training batch from normalized text, audio and speaker identities PARAMS ------ batch: [text_normalized, spec_normalized, wav_normalized, sid] """ # Right zero-pad all one-hot text sequences to max input length _, ids_sorted_decreasing = torch.sort( torch.LongTensor([x[1].size(1) for x in batch]), dim=0, descending=True ) max_text_len = max([len(x[0]) for x in batch]) max_spec_len = max([x[1].size(1) for x in batch]) max_wav_len = max([x[2].size(1) for x in batch]) text_lengths = torch.LongTensor(len(batch)) spec_lengths = torch.LongTensor(len(batch)) wav_lengths = torch.LongTensor(len(batch)) sid = torch.LongTensor(len(batch)) text_padded = torch.LongTensor(len(batch), max_text_len) spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len) wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len) text_padded.zero_() spec_padded.zero_() wav_padded.zero_() for i in range(len(ids_sorted_decreasing)): row = batch[ids_sorted_decreasing[i]] text = row[0] text_padded[i, : text.size(0)] = text text_lengths[i] = text.size(0) spec = row[1] spec_padded[i, :, : spec.size(1)] = spec spec_lengths[i] = spec.size(1) wav = row[2] wav_padded[i, :, : wav.size(1)] = wav wav_lengths[i] = wav.size(1) sid[i] = row[3] if self.return_ids: return ( text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, sid, ids_sorted_decreasing, ) return ( text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, sid, )
/** * This class is where the bulk of the robot should be declared. Since * Command-based is a "declarative" paradigm, very little robot logic should * actually be handled in the {@link Robot} periodic methods (other than the * scheduler calls). Instead, the structure of the robot (including subsystems, * commands, and button mappings) should be declared here. */ public class RobotContainer { public static final class Config { public static final int kJoystickDriverPort = 4; public static final int kJoystickShooterPort = 5; public static final int kJoystickSafePort = 3; public static final int kShootButton = 8; public static final int kShootOffButton = 4; public static final int kIntakeUpButton = 1; public static final int kIntakeDownButton = 2; public static final int kFlywheelButton = 3; public static final int kRollersOnButton = 5; public static final int kRollersOffButton = 6; public static final int kShootReverseButton = 1; public static final int kMoveFromTargetButton = 7; public static final int kHoodDownButton = 7; public static final int kHoodUpButton = 5; } // OI private final Joystick m_driverJoystick = new Joystick(Config.kJoystickDriverPort); private final Joystick m_shooterJoystick = new Joystick(Config.kJoystickShooterPort); private final Joystick m_safeJoystick = new Joystick(Config.kJoystickSafePort); private final JoystickButton m_shootButton = new JoystickButton(m_shooterJoystick, Config.kShootButton); private final JoystickButton m_shootOffButton = new JoystickButton(m_shooterJoystick, Config.kShootOffButton); private final JoystickButton m_flywheelButton = new JoystickButton(m_shooterJoystick, Config.kFlywheelButton); private final JoystickButton m_armUpButton = new JoystickButton(m_driverJoystick, Config.kIntakeUpButton); private final JoystickButton m_armDownButton = new JoystickButton(m_driverJoystick, Config.kIntakeDownButton); private final JoystickButton m_rollerOnButton = new JoystickButton(m_driverJoystick, Config.kRollersOnButton); private final JoystickButton m_rollerOffButton = new JoystickButton(m_driverJoystick, Config.kRollersOffButton); private final JoystickButton m_shooterReverseButton = new JoystickButton(m_shooterJoystick, Config.kShootReverseButton); private final JoystickButton m_hoodDownButton = new JoystickButton(m_shooterJoystick, Config.kHoodDownButton); private final JoystickButton m_hoodUpButton = new JoystickButton(m_shooterJoystick, Config.kHoodUpButton); // Subsystems private final Drivetrain m_drivetrain = new Drivetrain(); private final Flywheel m_flywheel = new Flywheel(); private final Tower m_tower = new Tower(); private final Funnel m_funnel = new Funnel(); private final Arm m_arm = new Arm(); private final Rollers m_rollers = new Rollers(); private final Limelight m_limelight = new Limelight(); private final Turret m_turret = new Turret(); private final Hood m_hood = new Hood(); // Commands private final Command m_arcadeDrive = new ArcadeDrive(m_drivetrain, m_driverJoystick); private final Command m_safeArcadeDrive = new ArcadeDrive(m_drivetrain, m_safeJoystick, 0.5, 0.7); private final Command m_diffDriveIdle = new DiffDriveIdle(m_drivetrain); private final Command m_controlShooter = new ControlShooter(m_flywheel, m_tower, m_funnel, m_shootButton, m_shootOffButton, m_shooterReverseButton); private final Command m_runTurret = new RunTurret(m_shooterJoystick, m_turret); // Compressor for the arm private final Compressor m_compressor = new Compressor(Arm.Config.kPCMId); /** * The container for the robot. Contains subsystems, OI devices, and commands. */ public RobotContainer() { // Configure the button bindings configureButtonBindings(); m_drivetrain.resetEncoder(); } /** * Use this method to define your button->command mappings. Buttons can be * created by instantiating a {@link GenericHID} or one of its subclasses * ({@link edu.wpi.first.wpilibj.Joystick} or {@link XboxController}), and then * passing it to a {@link edu.wpi.first.wpilibj2.command.button.JoystickButton}. */ private void configureButtonBindings() { m_armDownButton.whenPressed(new ArmDown(m_arm)); m_armUpButton.whenPressed(new ArmUp(m_arm)); m_flywheelButton.whenPressed(m_controlShooter); m_rollerOnButton.whenPressed(new RollIntake(m_rollers)); m_rollerOffButton.whenPressed(new StopIntake(m_rollers)); m_hoodDownButton.whenPressed(new InstantCommand(() -> m_hood.hoodDown(), m_hood)); m_hoodUpButton.whenPressed(new InstantCommand(() -> m_hood.hoodUp(), m_hood)); } /** * Use this to get the command run on robot init. * * @return the init comand */ public Command getInitCommand() { SmartDashboard.putBoolean("Safe mode", false); SmartDashboard.putNumber("Target RPM", Flywheel.Config.kTargetRPM); return new InstantCommand(() -> m_compressor.start(), m_arm); } /** * Use this to get the command run on robot disabled. * * @return the disabled command */ public Command getDisabledCommand() { return new InstantCommand(() -> m_compressor.stop(), m_arm); } /** * Use this to get the teleop command in the Robot class * * @return the teleop command */ public Command getTeleopCommand() { m_drivetrain.resetEncoder(); m_drivetrain.setCoastMode(); boolean safeMode = SmartDashboard.getBoolean("Safe mode", false); if (safeMode) m_drivetrain.setDefaultCommand(m_safeArcadeDrive); else m_drivetrain.setDefaultCommand(m_arcadeDrive); m_turret.resetEncoder(); m_turret.setDefaultCommand(m_runTurret); return null; } /** * Use this to pass the autonomous command to the main {@link Robot} class. * * @return the command to run in autonomous */ public Command getAutonomousCommand() { m_drivetrain.setBrakeMode(); m_drivetrain.setDefaultCommand(m_diffDriveIdle); return new TurnTowardTarget(m_limelight, m_turret); } }
/** * A client program for the RandomizedQueue class model. * * @author Alessio Vallero */ public class Permutation { public static void main(String[] args) { // Check how many arguments were passed in if (args.length < 1) { System.out.println("Proper Usage is: Permutation <ITEMS_COUNT_FROM_STDIN>"); } else { final int elemToReadCount = Integer.parseInt(args[0]); RandomizedQueue<String> randomizedQueue = new RandomizedQueue<>(); while (!StdIn.isEmpty()) { String item = StdIn.readString(); if (item != null && item.length() > 0) { randomizedQueue.enqueue(item); } } for (int i = 0; i < elemToReadCount; i++) { System.out.println(randomizedQueue.dequeue()); } } } }
// TODO: This suggests that ordering and distinct should be tracked together. public boolean strictlyOrderedIfUnique(Function<String,Index> getIndex, int nkeys) { if (orderedPlan instanceof RecordQueryIndexPlan) { RecordQueryIndexPlan indexPlan = (RecordQueryIndexPlan)orderedPlan; Index index = getIndex.apply(indexPlan.getIndexName()); return index.isUnique() && nkeys >= index.getColumnSize(); } return false; }
/** * A company user */ public class Company extends User { // Company's banking information private BankInformation bankInfo; // Company's address private Address address; /** * Constructor for Company * * @param username Username * @param password Password * @param type Type * @param bankInfo Banking information * @param address Address */ public Company(String username, String password, String name, UserTypes type, BankInformation bankInfo, Address address) { super(username, password, name, type); this.bankInfo = bankInfo; this.address = address; } /** * Get company's banking information * * @return Company's banking information */ public BankInformation getBankInfo() { return bankInfo; } /** * Set company's banking information * * @param bankInfo New banking information */ public void setBankInfo(BankInformation bankInfo) { this.bankInfo = bankInfo; } /** * Get company's address * * @return Company's address */ public Address getAddress() { return address; } /** * Set company's address * * @param address New address */ public void setAddress(Address address) { this.address = address; } }
<reponame>apmasell/shesmu package ca.on.oicr.gsi.shesmu.compiler; import ca.on.oicr.gsi.Pair; import ca.on.oicr.gsi.shesmu.compiler.Target.Flavour; import ca.on.oicr.gsi.shesmu.plugin.types.Imyhat; import java.nio.file.Path; import java.util.*; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; public final class OliveClauseNodeDumpAll extends OliveClauseNodeBaseDump implements RejectNode { private List<Target> columns; public OliveClauseNodeDumpAll(Optional<String> label, int line, int column, String dumper) { super(label, line, column, dumper); } @Override protected Predicate<String> captureVariable() { return x -> false; } @Override public void collectFreeVariables(Set<String> freeVariables) { // No free variables. } @Override public void collectPlugins(Set<Path> pluginFileNames) { // No plugins. } @Override protected int columnCount() { return columns.size(); } @Override protected Stream<String> columnInputs(int index) { return Stream.of(columns.get(index).name()); } @Override public Pair<String, Imyhat> columnDefinition(int index) { final var target = columns.get(index); return new Pair<>(target.name(), target.type()); } @Override protected void renderColumn(int index, Renderer renderer) { renderer.loadTarget(columns.get(index)); } @Override public NameDefinitions resolve( OliveCompilerServices oliveCompilerServices, NameDefinitions defs, Consumer<String> errorHandler) { columns = defs.stream() .filter(i -> i.flavour() == Flavour.STREAM || i.flavour() == Flavour.STREAM_SIGNABLE) .sorted(Comparator.comparing(Target::name)) .collect(Collectors.toList()); return defs; } @Override protected boolean resolveDefinitionsExtra( OliveCompilerServices oliveCompilerServices, Consumer<String> errorHandler) { return true; } @Override protected boolean typeCheckExtra(Consumer<String> errorHandler) { return true; } }
package main import ( "encoding/json" "github.com/sdiawara/probeit/models" "github.com/stretchr/testify/assert" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" "net/http" "net/http/httptest" "os" "strings" "testing" ) var status int var session *mgo.Session var collection *mgo.Collection var expectedProbe models.Probe func TestMain(m *testing.M) { before() status = m.Run() after() os.Exit(status) } func before() { expectedProbe = models.NewProbe("Is this test ok ?", []string{}) var err error session, err = mgo.Dial("localhost") if err != nil { panic(err) } collection = session.DB("test").C("probe") collection.RemoveAll(bson.M{}) } func after() { if collection == nil { collection.RemoveAll(bson.M{}) } if session != nil { session.Close() } } func TestStaticFilesHandler(testing *testing.T) { writer, request := createTestResponseAndRequest("") StaticFilesHandler(writer, request) assert.Equal(testing, true, strings.Contains(writer.Body.String(), "<img alt=\"logo\" src=\"/images/logo.svg\" id=\"logo\" width=\"150px\" />")) assert.Equal(testing, true, strings.Contains(writer.Body.String(), "<h1 class=\"cover-heading\">Nous les sondons pour vous.</h1>")) } func TestCreateProbe(testing *testing.T) { writer, request := createTestResponseAndRequest(`{"Question":"Do you like golang ?"}`) CreateProbe(writer, request) probe := findOneProbeAndRemoveIt() assert.Equal(testing, "Do you like golang ?", probe.Question) assert.Equal(testing, http.StatusOK, writer.Code) } func TestCanNotCreateInvalidProbe(testing *testing.T) { writer, request := createTestResponseAndRequest(`{"Question":""}`) CreateProbe(writer, request) assert.Equal(testing, http.StatusBadRequest, writer.Code) } func TestRespondProbe(testing *testing.T) { collection.RemoveAll(bson.M{}) probe := models.NewProbe("Aimez-vous golang ?", []string{}) probe.Id = bson.NewObjectId() collection.Insert(probe) request := createRequest(models.ProbeResponse{probe.Id, "Oui"}) RespondProbe(nil, request) actualProbe := findOneProbeAndRemoveIt() assert.Equal(testing, 1, len(actualProbe.Responses)) assert.Equal(testing, "Oui", actualProbe.Responses[0]) } func decode(writer *httptest.ResponseRecorder) (probes []models.Probe) { decoder := json.NewDecoder(writer.Body) decoder.Decode(&probes) return } func createRequest(probeResponse models.ProbeResponse) (request *http.Request) { probeResponseJson, _ := json.Marshal(probeResponse) request, _ = http.NewRequest("", "/", strings.NewReader(string(probeResponseJson))) return } func createTestResponseAndRequest(data string) (writer *httptest.ResponseRecorder, request *http.Request) { writer = httptest.NewRecorder() request, _ = http.NewRequest("", "/", strings.NewReader(data)) return } func findOneProbe() (probe *models.Probe) { probe = &models.Probe{} collection.Find(bson.M{}).One(probe) return } func findOneProbeAndRemoveIt() (probe *models.Probe) { probe = findOneProbe() collection.Remove(bson.M{}) return }
package ansi import ( "fmt" "os" "golang.org/x/sys/windows" ) // Enable Windows virtual terminal sequences for console control without safe access to Console API func WindowsInitTerminal(title string) { stdout := windows.Handle(os.Stdout.Fd()) var originalMode uint32 windows.GetConsoleMode(stdout, &originalMode) windows.SetConsoleMode(stdout, originalMode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING) windowsSetTitleAndIcon(title) } // https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#window-title func windowsSetTitleAndIcon(title string) { fmt.Printf("\x1b]0;%s\x07", title) }
def toggler(self, attr): if attr not in self._opts: raise KeyError("No such option: %s" % attr) def toggle(): setattr(self, attr, not getattr(self, attr)) return toggle
<filename>BeLuEngine/BeLuEngine/src/BeLuEngine.cpp #include "stdafx.h" #include "BeLuEngine.h" #include "Misc/MultiThreading/Thread.h" #include "Renderer/Statistics/EngineStatistics.h" BeLuEngine::BeLuEngine() { } BeLuEngine::~BeLuEngine() { delete m_pTimer; m_pSceneManager->deleteSceneManager(); m_pRenderer->deleteRenderer(); delete m_pWindow; } void BeLuEngine::Init(HINSTANCE hInstance, int nCmdShow) { // Window values bool windowedFullscreen = false; int windowWidth = 1280; int windowHeight = 720; // Misc m_pWindow = new Window(hInstance, nCmdShow, windowedFullscreen, windowWidth, windowHeight); m_pTimer = new Timer(m_pWindow); // ThreadPool int numThreads = std::thread::hardware_concurrency(); if (numThreads == 0) // function not supported { BL_LOG_WARNING("Only 1 core on CPU, might be very laggy!\n"); numThreads = 1; } EngineStatistics::GetIM_CommonStats().m_NumCpuCores = numThreads; m_pThreadPool = &ThreadPool::GetInstance(numThreads * 2); // Sub-engines m_pRenderer = &Renderer::GetInstance(); m_pRenderer->InitD3D12(m_pWindow, hInstance, m_pThreadPool); // ECS m_pSceneManager = &SceneManager::GetInstance(); Input::GetInstance().RegisterDevices(m_pWindow->GetHwnd()); } Window* const BeLuEngine::GetWindow() const { return m_pWindow; } Timer* const BeLuEngine::GetTimer() const { return m_pTimer; } ThreadPool* const BeLuEngine::GetThreadPool() const { return m_pThreadPool; } SceneManager* const BeLuEngine::GetSceneHandler() const { return m_pSceneManager; } Renderer* const BeLuEngine::GetRenderer() const { return m_pRenderer; }
MA2CoBr4: lead-free cobalt-based perovskite for electrochemical conversion of water to oxygen. We have synthesized a lead-free stable organic-inorganic perovskite (MA2CoBr4) by using non-hazardous solvents such as methanol and ethanol, which are eco-friendly and safe to handle in comparison to DMF, toluene, etc. Single crystals of MA2CoBr4 were grown using a simple solution technique, and their electrochemical oxygen evolution was investigated in a wide pH range.
/** * A meta-bean implementation designed for use by the code generator. * * @author Stephen Colebourne */ public abstract class DirectMetaBean implements MetaBean { // overriding other methods has negligible effect considering DirectMetaPropertyMap /** * This constant can be used to pass into {@code setString()} to increase test coverage. */ public static final String TEST_COVERAGE_STRING = "!ConstantUsedForTestCoveragePurposes!"; @Override public boolean isBuildable() { return true; } @SuppressWarnings("unchecked") @Override public <R> MetaProperty<R> metaProperty(String propertyName) { MetaProperty<?> mp = metaPropertyGet(propertyName); if (mp == null) { return metaPropertyNotFound(propertyName); } return (MetaProperty<R>) mp; } @SuppressWarnings("unchecked") private <R> MetaProperty<R> metaPropertyNotFound(String propertyName) { if (propertyName == JodaBeanTests.TEST_COVERAGE_PROPERTY) { // cast is unsafe unless R is String, but code only used in test coverage scenarios return (MetaProperty<R>) StandaloneMetaProperty.of(propertyName, this, String.class); } throw new NoSuchElementException("Unknown property: " + propertyName); } /** * Gets the meta-property by name. * <p> * This implementation returns null, and must be overridden in subclasses. * * @param propertyName the property name, not null * @return the meta-property, null if not found */ protected MetaProperty<?> metaPropertyGet(String propertyName) { return null; } //------------------------------------------------------------------------- /** * Gets the value of the property. * * @param bean the bean to query, not null * @param propertyName the property name, not null * @param quiet true to return null if unable to read * @return the value of the property, may be null * @throws NoSuchElementException if the property name is invalid */ protected Object propertyGet(Bean bean, String propertyName, boolean quiet) { // used to enable 100% test coverage in beans if (quiet) { return null; } throw new NoSuchElementException("Unknown property: " + propertyName); } /** * Sets the value of the property. * * @param bean the bean to update, not null * @param propertyName the property name, not null * @param value the value of the property, may be null * @param quiet true to take no action if unable to write * @throws NoSuchElementException if the property name is invalid */ protected void propertySet(Bean bean, String propertyName, Object value, boolean quiet) { // used to enable 100% test coverage in beans if (quiet) { return; } throw new NoSuchElementException("Unknown property: " + propertyName); } /** * Validates the values of the properties. * * @param bean the bean to validate, not null * @throws RuntimeException if a property is invalid */ protected void validate(Bean bean) { } /** * Returns a string that summarises the meta-bean. * * @return a summary string, not null */ @Override public String toString() { return "MetaBean:" + beanType().getSimpleName(); } }
package spencercjh.problems; /** * https://leetcode-cn.com/problems/shuffle-an-array/ * * @author spencercjh */ class ShuffleAnArray { public ShuffleAnArray(int[] nums) { } public int[] reset() { } public int[] shuffle() { } } /** * Your ShuffleAnArray object will be instantiated and called as such: * ShuffleAnArray obj = new ShuffleAnArray(nums); * int[] param_1 = obj.reset(); * int[] param_2 = obj.shuffle(); */
Why Chris Evans Is Retiring, And Why Other Actors Might Follow Suit By Gabe Toro Random Article Blend Such is the case for Chris Evans, who 1:30 Train, a drama he shot in 19 days in New York City starring himself and Alice Eve. Which is actually a pretty glamorous, moviestar thing to do also, but what can you do? Evans is a handsome young dude, and when you have money and charm in Hollywood, that’s the sort of thing you do. If anything, this reflects the sad reality of the moviemaking business. Big blockbusters used to give you clout to make any other type of movie in your spare time, and you could leverage that popular fame to ensure your other pictures were worthy of financing, or out-and-out hits. You could build a career as an actor while also being a star. That’s changed considerably, as audiences have become more devoted to brands and franchises over actual people, with many actors having absolutely no profile outside of their precious tentpoles. And with sequels being made closer together, necessitating the availability of some actors, it rarely gives them time to develop a relationship with the audience in any other role. Since 2011’s Captain America: The First Avenger, Chris Evans has done three non-superhero movies. He’s fantastic in Puncture, a legal drama based on a true life case regarding negligent medical procedures and the corruption of the medical supplies industry. He also showed up in the frothy romantic comedy What’s Your Number? as a beefcake to fawn over. And he had a gonzo supporting role in The Iceman as an ice cream truck-driving killer. These films have something in common: nobody saw any of them. What’s Your Number? was a wide release that only managed a piddling $14 million. The Iceman couldn’t crawl over $2 million. And Puncture, where Evans gives the best performance of his career, made a little over (this is not a typo) $68,000. His next film is Snowpiercer, an ensemble piece that’s been a huge success overseas, but hasn’t been able to even secure a release in America due to commercial re-edits being applied by distributor The Weinstein Company. Chris Evans admits in the Variety piece, ruefully, "No one sees my good little movies, man." It’s not as if Chris Evans is struggling to make great art or to suffer for his craft. Evans claims he was reluctant to take the part and turned Marvel down many times. "The problem was initially, it was a nine-movie contract," he says. "And they said, if these movies take off and do very well, and my life changes and I don’t respond well, I don’t have the opportunity to say, listen, I need a fucking break. That just scared me." Chris Evans, whom the Avengers cast credits as "the captain of team spirit," will ostensibly star in Captain America 3 in May 2016, his fifth appearance as the character since 2011. Considering the heavy between-shoot regiment of staying in shape, interviews and press surrounding the films, that’s an awful lot of time to devote to Captain America and less to any other movie. Or having a kid. Taking a lover. Recording an album. Doing charity. Literally anything else. Not every actor is Scarlett Johansson, who is under contract from Marvel while also appearing in three to four other movies a year. But even she admits, "It can feel like a gilded cage at times… it’s something that obviously allows you the opportunity to do things like go and direct your first feature and have a built-in audience for that. At the same time, at the end of the job, there’s always a super suit in your future." Managing these franchises has been an act of squeezing actors into fixed roles and keeping them from any sort of freedom. If you ask David O. Russell, it’s "slavery": Hunger Games commitments that Lawrence tends to in between receiving Oscar nominations for his movies (let alone X-Men films). And while he very quickly regretted his choice of words, it helps explain why rumors circulate that Lawrence could be looking at a brief The Amazing Spider-Man sequels and the continuing Divergent series. And, ultimately, it’s why Robert Pattinson and Kristen Stewart are no longer considered A-List leading actors, just years after they fronted a box office sensation. It’s not all bad, really: Andrew Garfield has almost no public profile, but he’ll show up in the next Martin Scorsese movie in between Spider-Man films. Of course, look what happened to Tobey Maguire: his commitment to Spidey saw him use his A-List cache to pop up in supporting roles in Seabiscuit and The Good German as his sole parts during that franchise. He keeps busy as a producer, but he’s not at all a blockbuster leading man any longer, and a look at the projects he passed over during the web-slinging years reveals a host of great-sounding unmade scripts like Tokyo Suckerpunch and The Quiet Type. No one is weeping for these people, who are gorgeous, wake up gorgeous and go to sleep richer. Especially not Chris Evans, who now gets to pursue the dream of directing, one he’ll live out by directing another film at the end of this year. He credits Captain America for the opportunity, saying, "Without these movies, I wouldn’t be directing. They gave me enough overseas recognition to greenlight a movie." But he then adds, "And if I’m speaking extremely candidly, it’s going to continue to do that for as long as the Marvel contract runs… If I’m acting at all, it’s going to be under Marvel contract, or I’m going to be directing. I can’t see myself pursuing acting strictly outside of what I’m contractually obligated to do." Chris Evans is a wonderful onscreen presence, an actor of great skill and dexterity, not to mention starling beauty. You’d hate to think that playing a superhero has extinguished any desire he might have to appear before the camera. Don’t be surprised if he’s not the last actor to feel this way. We overestimate the passion for movie-star acting that some performers might have. Acting, certainly, is a passion, and a worthy one. But you act to act, you act to perform, you act to find new truths, new depths. You don’t act to become a movie star, and the bigger the star you are, the less acting you’re actually doing. And in the age of superhero movies and endless franchises, your creative expression is limited if you wear a mask and hold a shield and run through explosions.Such is the case for Chris Evans, who reaffirmed to Variety that he’s done with acting and plans to retire upon the end of his Marvel contract. This new passion is directing, which he’s given a shot thanks to, a drama he shot in 19 days in New York City starring himself and Alice Eve. Which is actually a pretty glamorous, moviestar thing to do also, but what can you do? Evans is a handsome young dude, and when you have money and charm in Hollywood, that’s the sort of thing you do.If anything, this reflects the sad reality of the moviemaking business. Big blockbusters used to give you clout to make any other type of movie in your spare time, and you could leverage that popular fame to ensure your other pictures were worthy of financing, or out-and-out hits. You could build a career as an actor while also being a star. That’s changed considerably, as audiences have become more devoted to brands and franchises over actual people, with many actors having absolutely no profile outside of their precious tentpoles. And with sequels being made closer together, necessitating the availability of some actors, it rarely gives them time to develop a relationship with the audience in any other role.Since 2011’s, Chris Evans has done three non-superhero movies. He’s fantastic in, a legal drama based on a true life case regarding negligent medical procedures and the corruption of the medical supplies industry. He also showed up in the frothy romantic comedyas a beefcake to fawn over. And he had a gonzo supporting role inas an ice cream truck-driving killer. These films have something in common: nobody saw any of them.was a wide release that only managed a piddling $14 million.couldn’t crawl over $2 million. And, where Evans gives the best performance of his career, made a little over (this is not a typo) $68,000. His next film is, an ensemble piece that’s been a huge success overseas, but hasn’t been able to even secure a release in America due to commercial re-edits being applied by distributor The Weinstein Company. Chris Evans admits in the Variety piece, ruefully, "No one sees my good little movies, man."It’s not as if Chris Evans is struggling to make great art or to suffer for his craft. Evans claims he was reluctant to take the part and turned Marvel down many times. "The problem was initially, it was a nine-movie contract," he says. "And they said, if these movies take off and do very well, and my life changes and I don’t respond well, I don’t have the opportunity to say, listen, I need a fucking break. That just scared me." Chris Evans, whom thecast credits as "the captain of team spirit," will ostensibly star inin May 2016, his fifth appearance as the character since 2011. Considering the heavy between-shoot regiment of staying in shape, interviews and press surrounding the films, that’s an awful lot of time to devote toand less to any other movie. Or having a kid. Taking a lover. Recording an album. Doing charity. Literally anything else. Not every actor is Scarlett Johansson, who is under contract from Marvel while also appearing in three to four other movies a year. But even she admits, "It can feel like a gilded cage at times… it’s something that obviously allows you the opportunity to do things like go and direct your first feature and have a built-in audience for that. At the same time, at the end of the job, there’s always a super suit in your future."Managing these franchises has been an act of squeezing actors into fixed roles and keeping them from any sort of freedom. If you ask David O. Russell, it’s "slavery": that‘s what he said of the annualcommitments that Lawrence tends to in between receiving Oscar nominations for his movies (let alonefilms). And while he very quickly regretted his choice of words, it helps explain why rumors circulate that Lawrence could be looking at a brief retirement : it’s also why Shailene Woodley was forced to choose between the role of Mary Jane insequels and the continuingseries. And, ultimately, it’s why Robert Pattinson and Kristen Stewart are no longer considered A-List leading actors, just years after they fronted a box office sensation.It’s not all bad, really: Andrew Garfield has almost no public profile, but he’ll show up in the next Martin Scorsese movie in betweenfilms. Of course, look what happened to Tobey Maguire: his commitment to Spidey saw him use his A-List cache to pop up in supporting roles inandas his sole parts during that franchise. He keeps busy as a producer, but he’s not at all a blockbuster leading man any longer, and a look at the projects he passed over during the web-slinging years reveals a host of great-sounding unmade scripts likeandNo one is weeping for these people, who are gorgeous, wake up gorgeous and go to sleep richer. Especially not Chris Evans, who now gets to pursue the dream of directing, one he’ll live out by directing another film at the end of this year. He creditsfor the opportunity, saying, "Without these movies, I wouldn’t be directing. They gave me enough overseas recognition to greenlight a movie." But he then adds, "And if I’m speaking extremely candidly, it’s going to continue to do that for as long as the Marvel contract runs… If I’m acting at all, it’s going to be under Marvel contract, or I’m going to be directing. I can’t see myself pursuing acting strictly outside of what I’m contractually obligated to do." Chris Evans is a wonderful onscreen presence, an actor of great skill and dexterity, not to mention starling beauty. You’d hate to think that playing a superhero has extinguished any desire he might have to appear before the camera. Don’t be surprised if he’s not the last actor to feel this way. Blended From Around The Web Facebook Back to top
""" shell sort tests module """ import unittest import random from sort import shell from tests import helper class ShellSortTests(unittest.TestCase): """ shell sort unit tests class """ max = 100 arr = [] def setUp(self): """ setting up for the test """ self.arr = random.sample(range(self.max), self.max) def test_null_input(self): """ should raise when input array is None """ # arrange inp = None # act with self.assertRaises(TypeError) as ex: shell.sort(inp) # assert self.assertEqual("'NoneType' object is not iterable", str(ex.exception)) def test_empty_input(self): """ should return [] when input array is empty """ # arrange inp = [] # act res = shell.sort(inp) # assert self.assertEqual(len(inp), len(res)) def test_sort_a_given_array(self): """ should sort a given array """ # act res = shell.sort(self.arr[:]) # assert self.assertTrue(helper.is_sorted(res))
class RF: # Random Forest """docstring for Random Forest """ def __init__(self, n=100, m=10): # Model Definition model = RandomForestClassifier(n_estimators=n, max_depth=m, random_state=42, n_jobs = -1, max_features="auto") self.model = model def train(self, X_train, y_train): # Train the model return self.model.fit(X_train, y_train) def classify(self, data): return self.model.predict(data)
// Next moves the iterator to the next set of results. It returns true if there // are more results, or false if there are no more results or there was an // error. func (l *ObjectLister) Next() bool { var ok bool l.currentValue, ok = <-l.resultCh if !ok { l.currentErr = l.finalErr return false } return true }
w,h,x,y=map(int,input().split()) if w<h: tmp1=w tmp2=x w=h h=tmp1 x=y y=tmp2 if x>w/2: x=w-x if y>h/2: y=h-y a=x*h b=w*y if y==0 or x/y>w/h: print(h*w/2,0) elif a!=b : print(max(a,b),0) else: print(max(a,b),1)
def check_in_both(self): if set(self.white_data).issubset(self.black_data): raise Exception("WARNING: Whitelist content also appears in Blacklist content")
def window(self): self.__window = (26 - self.__postion + self.__ringSetting) % 26
import * as vscode from 'vscode'; import { ITreeNode } from './ITreeNode'; import { GitlabAPIProvider } from './api'; import { Group } from '../../Models/Group'; import { Issue } from '../../Models/Issue'; import { IssueLabel } from '../../Models/IssueLabel'; import { Project } from '../../Models/Project'; export class GitlabExplorer { private gitlabExplorerProvider: GitlabExplorerProvider; constructor(context: vscode.ExtensionContext, apiProvider:GitlabAPIProvider) { this.gitlabExplorerProvider = new GitlabExplorerProvider(apiProvider); vscode.window.registerTreeDataProvider('gitlabExplorer', this.gitlabExplorerProvider); vscode.commands.getCommands(true).then((cmds)=>{ cmds = cmds.filter((cmd)=>{ if(cmd === 'gitlabExplorer.refresh'){ return true; } }); if(cmds.length === 0){ let cmdRefresh = vscode.commands.registerCommand('gitlabExplorer.refresh', () => this.RefreshTreeView(), this); context.subscriptions.push(cmdRefresh); } }); } public RefreshTreeView(){ vscode.window.showInformationMessage('Refresh Gitlab-Tree!'); this.gitlabExplorerProvider.refresh(); } } export class GitlabExplorerProvider implements vscode.TreeDataProvider<ITreeNode> { private _onDidChangeTreeData: vscode.EventEmitter<ITreeNode | undefined> = new vscode.EventEmitter<ITreeNode | undefined>(); readonly onDidChangeTreeData: vscode.Event<ITreeNode | undefined> = this._onDidChangeTreeData.event; constructor(private apiProvider:GitlabAPIProvider) { } refresh(): void { this._onDidChangeTreeData.fire(); } getTreeItem(element: ITreeNode): vscode.TreeItem { let node = new vscode.TreeItem(element.GetTreeItemLabel(), element.GetTreeItemCollapsibleState()); node.id = element.GetTreeItemID(); node.iconPath = element.GetTreeItemIcons(); node.command = element.GetTreeItemCommand(); node.contextValue = element.GetContextValue(); return node; } getChildren(element?: ITreeNode): Thenable<ITreeNode[]> { return new Promise((resolve, reject)=>{ if(!element){ this.apiProvider.GetGroupsAsync().then((data)=>{ resolve(data); }); }else{ this.getChildrenForNode(element).then((data)=>{ resolve(data); }); } }); } getChildrenForNode(element: ITreeNode):Promise<Array<ITreeNode>>{ switch (element.GetContextValue()) { case "Group": return this.apiProvider.GetProjectOrSubgroup(element as Group); break; case "Project": return this.apiProvider.GetProjectLabelsAsync(element as Project); break; case "IssueLabel": return this.apiProvider.GetIssueByLabelsAsync(element as IssueLabel); break; case "Issue": return this.apiProvider.GetCommentsAsync(element as Issue); break; default: return new Promise((resolve)=>{ resolve([]); }); } } }
/** * <b>NO-OP for MapR Tables</b><p> * Explicitly clears the region cache to fetch the latest value from META. * This is a power user function: avoid unless you know the ramifications. */ public void clearRegionCache() { if (maprTable_ != null) { maprTable_.clearRegionCache(); return; } this.connection.clearRegionCache(); }
<filename>pdfbox/src/main/java/org/apache/pdfbox/pdmodel/encryption/BaseEncryptionImplementation.java package org.apache.pdfbox.pdmodel.encryption; import java.io.IOException; import java.io.InputStream; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.spec.AlgorithmParameterSpec; import java.util.Arrays; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; import org.apache.pdfbox.exceptions.CryptographyException; public abstract class BaseEncryptionImplementation { /** * Standard padding for encryption. */ public static final byte[] ENCRYPT_PADDING = { (byte) 0x28, (byte) 0xBF, (byte) 0x4E, (byte) 0x5E, (byte) 0x4E, (byte) 0x75, (byte) 0x8A, (byte) 0x41, (byte) 0x64, (byte) 0x00, (byte) 0x4E, (byte) 0x56, (byte) 0xFF, (byte) 0xFA, (byte) 0x01, (byte) 0x08, (byte) 0x2E, (byte) 0x2E, (byte) 0x00, (byte) 0xB6, (byte) 0xD0, (byte) 0x68, (byte) 0x3E, (byte) 0x80, (byte) 0x2F, (byte) 0x0C, (byte) 0xA9, (byte) 0xFE, (byte) 0x64, (byte) 0x53, (byte) 0x69, (byte) 0x7A }; /** * This will compare two byte[] for equality. * * @param first * The first byte array. * @param second * The second byte array. * @param count * to what index should the arrays be equal * * @return true If the arrays contain the exact same data up to count bytes. */ private static final boolean arraysEqual(final byte[] first, final byte[] second, final int count) { boolean equal = first.length >= count && second.length >= count; for (int i = 0; i < count && equal; i++) { equal = first[i] == second[i]; } return equal; } protected String algorithmFor(final Key key) { return key.getAlgorithm(); } public byte[] computeEncryptionKey(final byte[] password, final byte[] o, final int permissions, final byte[] id, final int encRevision, final int length, final boolean encryptMetadata) throws CryptographyException { final byte[] result = new byte[length]; try { // PDFReference 1.4 pg 78 // step1 final byte[] padded = truncateOrPad(password); // step 2 final MessageDigest md = MessageDigest.getInstance("MD5"); md.update(padded); // step 3 md.update(o); // step 4 final byte zero = (byte) (permissions >>> 0); final byte one = (byte) (permissions >>> 8); final byte two = (byte) (permissions >>> 16); final byte three = (byte) (permissions >>> 24); md.update(zero); md.update(one); md.update(two); md.update(three); // step 5 md.update(id); // (Security handlers of revision 4 or greater) If document metadata is not being encrypted, // pass 4 bytes with the value 0xFFFFFFFF to the MD5 hash function. // see 7.6.3.3 Algorithm 2 Step f of PDF 32000-1:2008 if (encRevision == 4 && !encryptMetadata) { md.update(new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff }); } byte[] digest = md.digest(); // step 6 if (encRevision == 3 || encRevision == 4) { for (int i = 0; i < 50; i++) { md.reset(); md.update(digest, 0, length); digest = md.digest(); } } // step 7 if (encRevision == 2 && length != 5) { throw new CryptographyException("Error: length should be 5 when revision is two actual=" + length); } System.arraycopy(digest, 0, result, 0, length); } catch (final NoSuchAlgorithmException e) { throw new CryptographyException(e); } return result; } public byte[] computeOwnerKey(final byte[] ownerPassword, final byte[] userPassword, final int encRevision, final int length) throws CryptographyException { // STEP 1 final byte[] ownerPadded = truncateOrPad(ownerPassword); // STEP 2 MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (final NoSuchAlgorithmException e) { throw new CryptographyException(e); } byte[] digest = md.digest(ownerPadded); // STEP 3 if (encRevision == 3 || encRevision == 4) { for (int i = 0; i < 50; i++) { md.reset(); md.update(digest, 0, length); digest = md.digest(); } } if (encRevision == 2 && length != 5) { throw new CryptographyException("Error: Expected length=5 actual=" + length); } // STEP 4 final byte[] rc4Key = new byte[length]; System.arraycopy(digest, 0, rc4Key, 0, length); // STEP 5 final byte[] paddedUser = truncateOrPad(userPassword); // STEP 6 final Key key = new SecretKeySpec(rc4Key, "RC4"); final Cipher rc4Cipher = newRC4Cipher(); try { rc4Cipher.init(Cipher.ENCRYPT_MODE, key); } catch (final InvalidKeyException e) { throw new CryptographyException(e); } byte[] crypted; try { crypted = rc4Cipher.doFinal(paddedUser); } catch (final IllegalBlockSizeException e) { throw new CryptographyException(e); } catch (final BadPaddingException e) { throw new CryptographyException(e); } // STEP 7 if (encRevision == 3 || encRevision == 4) { final byte[] iterationKeyBytes = new byte[rc4Key.length]; for (int i = 1; i < 20; i++) { System.arraycopy(rc4Key, 0, iterationKeyBytes, 0, rc4Key.length); for (int j = 0; j < iterationKeyBytes.length; j++) { iterationKeyBytes[j] = (byte) (iterationKeyBytes[j] ^ (byte) i); } final Key iterationKey = new SecretKeySpec(iterationKeyBytes, "RC4"); try { rc4Cipher.init(Cipher.ENCRYPT_MODE, iterationKey); crypted = rc4Cipher.doFinal(crypted); } catch (final InvalidKeyException e) { throw new CryptographyException(e); } catch (final IllegalBlockSizeException e) { throw new CryptographyException(e); } catch (final BadPaddingException e) { throw new CryptographyException(e); } } } // STEP 8 return crypted; } public byte[] computeUserKey(final byte[] password, final byte[] o, final int permissions, final byte[] id, final int encRevision, final int length, final boolean encryptMetadata) throws CryptographyException { // STEP 1 final byte[] encryptionKey = computeEncryptionKey(password, o, permissions, id, encRevision, length, encryptMetadata); final Cipher rc4Cipher = newRC4Cipher(); if (encRevision == 2) { // STEP 2 final Key rc4Key = new SecretKeySpec(encryptionKey, "RC4"); try { rc4Cipher.init(Cipher.ENCRYPT_MODE, rc4Key); return rc4Cipher.doFinal(ENCRYPT_PADDING); } catch (final InvalidKeyException e) { throw new CryptographyException(e); } catch (final IllegalBlockSizeException e) { throw new CryptographyException(e); } catch (final BadPaddingException e) { throw new CryptographyException(e); } } else if (encRevision == 3 || encRevision == 4) { try { // STEP 2 final MessageDigest md = MessageDigest.getInstance("MD5"); md.update(ENCRYPT_PADDING); // STEP 3 md.update(id); byte[] cipher = md.digest(); // STEP 4 and 5 final byte[] iterationKeyBytes = new byte[encryptionKey.length]; for (int i = 0; i < 20; i++) { System.arraycopy(encryptionKey, 0, iterationKeyBytes, 0, iterationKeyBytes.length); for (int j = 0; j < iterationKeyBytes.length; j++) { iterationKeyBytes[j] = (byte) (iterationKeyBytes[j] ^ i); } final Key iterationKey = new SecretKeySpec(iterationKeyBytes, "RC4"); try { rc4Cipher.init(Cipher.ENCRYPT_MODE, iterationKey); cipher = rc4Cipher.doFinal(cipher); } catch (final InvalidKeyException e) { throw new CryptographyException(e); } catch (final IllegalBlockSizeException e) { throw new CryptographyException(e); } catch (final BadPaddingException e) { throw new CryptographyException(e); } } // step 6 final byte[] finalResult = new byte[32]; System.arraycopy(cipher, 0, finalResult, 0, 16); System.arraycopy(ENCRYPT_PADDING, 0, finalResult, 16, 16); return finalResult; } catch (final NoSuchAlgorithmException e) { throw new CryptographyException(e); } } throw new IllegalStateException("unsupported revision: " + encRevision); } /** * This will compute the user password hash. * * @param password * The plain text password. * @param o * The owner password hash. * @param permissions * The document permissions. * @param id * The document id. * @param encRevision * The revision of the encryption. * @param length * The length of the encryption key. * * @return The user password. * * @throws CryptographyException * If there is an error computing the user password. * @throws IOException * If there is an IO error. */ public final byte[] computeUserPassword(final byte[] password, final byte[] o, final int permissions, final byte[] id, final int encRevision, final int length, final boolean encryptMetadata) throws CryptographyException { // STEP 1 final byte[] encryptionKey = computeEncryptionKey(password, o, permissions, id, encRevision, length, encryptMetadata); final Cipher rc4Cipher = newRC4Cipher(); if (encRevision == 2) { // STEP 2 final Key rc4Key = new SecretKeySpec(encryptionKey, "RC4"); try { rc4Cipher.init(Cipher.ENCRYPT_MODE, rc4Key); return rc4Cipher.doFinal(ENCRYPT_PADDING); } catch (final InvalidKeyException e) { throw new CryptographyException(e); } catch (final IllegalBlockSizeException e) { throw new CryptographyException(e); } catch (final BadPaddingException e) { throw new CryptographyException(e); } } else if (encRevision == 3 || encRevision == 4) { try { // STEP 2 final MessageDigest md = MessageDigest.getInstance("MD5"); md.update(ENCRYPT_PADDING); // STEP 3 md.update(id); byte[] cipher = md.digest(); // STEP 4 and 5 final byte[] iterationKeyBytes = new byte[encryptionKey.length]; for (int i = 0; i < 20; i++) { System.arraycopy(encryptionKey, 0, iterationKeyBytes, 0, iterationKeyBytes.length); for (int j = 0; j < iterationKeyBytes.length; j++) { iterationKeyBytes[j] = (byte) (iterationKeyBytes[j] ^ i); } final Key iterationKey = new SecretKeySpec(iterationKeyBytes, "RC4"); try { rc4Cipher.init(Cipher.ENCRYPT_MODE, iterationKey); cipher = rc4Cipher.doFinal(cipher); } catch (final InvalidKeyException e) { throw new CryptographyException(e); } catch (final IllegalBlockSizeException e) { throw new CryptographyException(e); } catch (final BadPaddingException e) { throw new CryptographyException(e); } } // step 6 final byte[] finalResult = new byte[32]; System.arraycopy(cipher, 0, finalResult, 0, 16); System.arraycopy(ENCRYPT_PADDING, 0, finalResult, 16, 16); return finalResult; } catch (final NoSuchAlgorithmException e) { throw new CryptographyException(e); } } throw new IllegalStateException("unsupported revision: " + encRevision); } protected Cipher createCipher(final Key key, final int mode, final AlgorithmParameterSpec parameters) throws CryptographyException { final Cipher cipher; try { cipher = Cipher.getInstance(algorithmFor(key)); if (parameters == null) { cipher.init(mode, key); } else { cipher.init(mode, key, parameters); } } catch (final NoSuchAlgorithmException e) { throw new CryptographyException(e); } catch (final NoSuchPaddingException e) { throw new CryptographyException(e); } catch (final InvalidKeyException e) { throw new CryptographyException(e); } catch (final InvalidAlgorithmParameterException e) { throw new CryptographyException(e); } return cipher; } public InputStream decrypt(final Key key, final AlgorithmParameterSpec parameters, final InputStream encrypted) throws CryptographyException, IOException { final Cipher cipher = createCipher(key, Cipher.DECRYPT_MODE, parameters); return new CipherInputStream(encrypted, cipher); } public InputStream decrypt(final Key key, final InputStream encrypted) throws CryptographyException, IOException { return decrypt(key, null, encrypted); } public InputStream encrypt(final Key key, final AlgorithmParameterSpec parameters, final InputStream clear) throws CryptographyException, IOException { final Cipher cipher = createCipher(key, Cipher.ENCRYPT_MODE, parameters); return new CipherInputStream(clear, cipher); } public InputStream encrypt(final Key key, final InputStream clear) throws CryptographyException, IOException { return encrypt(key, null, clear); } protected byte[] generateKeyBase(final SecurityHandler securityHandler, final long objectNumber, final long genNumber) { final byte[] newKey = new byte[securityHandler.encryptionKey.length + 5]; System.arraycopy(securityHandler.encryptionKey, 0, newKey, 0, securityHandler.encryptionKey.length); // PDF 1.4 reference pg 73 step 1 we have the reference // step 2 newKey[newKey.length - 5] = (byte) (objectNumber & 0xff); newKey[newKey.length - 4] = (byte) (objectNumber >> 8 & 0xff); newKey[newKey.length - 3] = (byte) (objectNumber >> 16 & 0xff); newKey[newKey.length - 2] = (byte) (genNumber & 0xff); newKey[newKey.length - 1] = (byte) (genNumber >> 8 & 0xff); return newKey; } /** * Get the user password based on the owner password. * * @param ownerPassword * The plaintext owner password. * @param o * The o entry of the encryption dictionary. * @param encRevision * The encryption revision number. * @param length * The key length. * * @return The u entry of the encryption dictionary. * * @throws CryptographyException * If there is an error generating the user password. * @throws IOException * If there is an error accessing data while generating the user password. */ public final byte[] getUserPassword(final byte[] ownerPassword, final byte[] o, final int encRevision, final int length) throws CryptographyException { // 3.3 STEP 1 final byte[] ownerPadded = truncateOrPad(ownerPassword); // 3.3 STEP 2 MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (final NoSuchAlgorithmException e) { throw new CryptographyException(e); } byte[] digest = md.digest(ownerPadded); // 3.3 STEP 3 if (encRevision == 3 || encRevision == 4) { for (int i = 0; i < 50; i++) { md.reset(); md.update(digest); digest = md.digest(); } } if (encRevision == 2 && length != 5) { throw new CryptographyException("Error: Expected length=5 actual=" + length); } // 3.3 STEP 4 final byte[] rc4Key = new byte[length]; System.arraycopy(digest, 0, rc4Key, 0, length); // 3.7 step 2 final Cipher rc4Cipher = newRC4Cipher(); if (encRevision == 2) { final Key key = new SecretKeySpec(rc4Key, "RC4"); try { rc4Cipher.init(Cipher.ENCRYPT_MODE, key); return rc4Cipher.doFinal(o); } catch (final InvalidKeyException e) { throw new CryptographyException(e); } catch (final IllegalBlockSizeException e) { throw new CryptographyException(e); } catch (final BadPaddingException e) { throw new CryptographyException(e); } } else if (encRevision == 3 || encRevision == 4) { byte[] iterationKey = new byte[rc4Key.length]; for (int i = 19; i >= 0; i--) { System.arraycopy(rc4Key, 0, iterationKey, 0, rc4Key.length); for (int j = 0; j < iterationKey.length; j++) { iterationKey[j] = (byte) (iterationKey[j] ^ (byte) i); } final Key key = new SecretKeySpec(iterationKey, "RC4"); try { rc4Cipher.init(Cipher.ENCRYPT_MODE, key); iterationKey = rc4Cipher.doFinal(iterationKey); } catch (final InvalidKeyException e) { throw new CryptographyException(e); } catch (final IllegalBlockSizeException e) { throw new CryptographyException(e); } catch (final BadPaddingException e) { throw new CryptographyException(e); } } return iterationKey; } throw new IllegalStateException("unsupported revision: " + encRevision); } /** * Check for owner password. * * @param ownerPassword * The owner password. * @param u * The u entry of the encryption dictionary. * @param o * The o entry of the encryption dictionary. * @param permissions * The set of permissions on the document. * @param id * The document id. * @param encRevision * The encryption algorithm revision. * @param length * The encryption key length. * * @return True If the ownerPassword param is the owner password. * * @throws CryptographyException * If there is an error during encryption. * @throws IOException * If there is an error accessing data. */ public final boolean isOwnerPassword(final byte[] ownerPassword, final byte[] u, final byte[] o, final int permissions, final byte[] id, final int encRevision, final int length, final boolean encryptMetadata) throws CryptographyException { final byte[] userPassword = getUserPassword(ownerPassword, o, encRevision, length); return isUserPassword(userPassword, u, o, permissions, id, encRevision, length, encryptMetadata); } /** * Check if a plaintext password is the user password. * * @param password * The plaintext password. * @param u * The u entry of the encryption dictionary. * @param o * The o entry of the encryption dictionary. * @param permissions * The permissions set in the the PDF. * @param id * The document id used for encryption. * @param encRevision * The revision of the encryption algorithm. * @param length * The length of the encryption key. * * @return true If the plaintext password is the user password. * * @throws CryptographyException * If there is an error during encryption. * @throws IOException * If there is an error accessing data. */ public final boolean isUserPassword(final byte[] password, final byte[] u, final byte[] o, final int permissions, final byte[] id, final int encRevision, final int length, final boolean encryptMetadata) throws CryptographyException { boolean matches = false; // STEP 1 final byte[] computedValue = computeUserPassword(password, o, permissions, id, encRevision, length, encryptMetadata); if (encRevision == 2) { // STEP 2 matches = Arrays.equals(u, computedValue); } else if (encRevision == 3 || encRevision == 4) { // STEP 2 matches = arraysEqual(u, computedValue, 16); } else { throw new CryptographyException("Unknown Encryption Revision " + encRevision); } return matches; } private Cipher newRC4Cipher() throws CryptographyException { Cipher rc4Cipher; try { rc4Cipher = Cipher.getInstance("RC4"); } catch (final NoSuchAlgorithmException e) { throw new CryptographyException(e); } catch (final NoSuchPaddingException e) { throw new CryptographyException(e); } return rc4Cipher; } /** * This will take the password and truncate or pad it as necessary. * * @param password * The password to pad or truncate. * * @return The padded or truncated password. */ private final byte[] truncateOrPad(final byte[] password) { final byte[] padded = new byte[ENCRYPT_PADDING.length]; final int bytesBeforePad = Math.min(password.length, padded.length); System.arraycopy(password, 0, padded, 0, bytesBeforePad); System.arraycopy(ENCRYPT_PADDING, 0, padded, bytesBeforePad, ENCRYPT_PADDING.length - bytesBeforePad); return padded; } }
############################################################################## # Copyright (c) 2016 <NAME> # juan_ <EMAIL> # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 ############################################################################## import logging import subprocess import traceback LOG = logging.getLogger(__name__) def buildshellparams(param, remote=True): result = '/bin/bash -s' if remote else '' result += "".join(" {%d}" % i for i in range(len(param))) return result def execute_shell_command(command): """execute shell script with error handling""" exitcode = 0 output = [] try: LOG.debug("the command is: %s", command) output = subprocess.check_output(command, shell=True) except Exception: exitcode = -1 output = traceback.format_exc() LOG.error("exec command '%s' error:\n ", command) LOG.error(traceback.format_exc()) return exitcode, output PREFIX = '$' def build_shell_command(param_config, remote=True, intermediate_variables=None): param_template = '/bin/bash -s' if remote else '' if intermediate_variables: for key, val in param_config.items(): if str(val).startswith(PREFIX): try: param_config[key] = intermediate_variables[val] except KeyError: pass result = param_template + "".join(" {}".format(v) for v in param_config.values()) LOG.debug("THE RESULT OF build_shell_command IS: %s", result) return result def read_stdout_item(stdout, key): if key == "all": return stdout for item in stdout.splitlines(): if key in item: attributes = item.split("|") if attributes[1].lstrip().startswith(key): return attributes[2].strip() return None
#!/usr/bin/python from math import exp import numpy as np import sys def binomial_tree(type,F, K, r, sigma, D, N=2): deltaT = float(D/365) / N u = np.exp(sigma * np.sqrt(deltaT)) d = 1.0 / u tmp_arr = np.asarray([0.0 for i in range(N + 1)]) tmp_F_arr = np.asarray([(F * u**i * d**(N - i)) for i in range(N + 1)]) tmp_K_arr = np.asarray( [float(K) for i in range(N + 1)]) p = (1 - d)/ (u - d) q = 1.0 - p discount = np.exp(-r * deltaT) if type =="C": tmp_arr[:] = np.maximum(tmp_F_arr-tmp_K_arr, 0.0) else: tmp_arr[:] = np.maximum(-tmp_F_arr+tmp_K_arr, 0.0) #for i in range(N-1, -1, -1): # tmp_arr[:-1]= discount * (p * tmp_arr[1:] + q * tmp_arr[:-1]) # tmp_F_arr[:]=tmp_F_arr[:]*u # if type =="C": # tmp_arr[:]=np.maximum(tmp_arr[:],tmp_F_arr[:]-tmp_K_arr[:]) # else: # tmp_arr[:]=np.maximum(tmp_arr[:],-tmp_F_arr[:]+tmp_K_arr[:]) for i in range(1, N+1, 1): b=(N+2-i) tmp_arr[:-i]= discount * (p * tmp_arr[1:b] + q * tmp_arr[:-i]) tmp_F_arr[:b]=tmp_F_arr[:b]*u if type =="C": tmp_arr[:b]=np.maximum(tmp_arr[:b],tmp_F_arr[:b]-tmp_K_arr[:b]) else: tmp_arr[:b]=np.maximum(tmp_arr[:b],-tmp_F_arr[:b]+tmp_K_arr[:b]) return round(tmp_arr[0],4) def handle_line(line): paraList = line.split(",") if len(paraList) == 7 : N = int(paraList[0]) O = paraList[1] K = float(paraList[2]) D = int(paraList[3]) F = float(paraList[4]) sigma = float(paraList[5]) r = float(paraList[6]) print("%.4f" % binomial_tree(O,F,K,r,sigma,D,N)) if __name__ == '__main__': paraStr = sys.argv[1] handle_line(paraStr) #handle_line("10000,C,98.700,60,98.695,0.2,0.035") #handle_line("2,C,98.700,60,98.695,0.2,0.035") #handle_line("1,C,98.700,60,98.695,0.2,0.035") #handle_line("128,C,98.700,60,98.695,0.2,0.035") #handle_line("4096,C,98.700,60,9.695,0.2,0.035") #handle_line("4096,C,98.700,60,9.695,0.1,0.035") #handle_line("4096,C,98.700,1000,9.695,0.1,0.035") #handle_line("4096,C,8.700,1000,9.695,0.1,0.035") #handle_line("4096,C,8.700,1000,8.700,0.1,0.035") #handle_line("4096,C,8.700,1000,8.700,0.1,0.005") #handle_line("4096,C,8.700,1000,8.700,0.9,0.005") #handle_line("10000,P,98.700,60,98.695,0.2,0.035") #handle_line("2,P,98.700,60,98.695,0.2,0.035") #handle_line("1,P,98.700,60,98.695,0.2,0.035") #handle_line("128,P,98.700,60,98.695,0.2,0.035") #handle_line("4096,P,98.700,60,9.695,0.2,0.035") #handle_line("4096,P,98.700,60,9.695,0.1,0.035") #handle_line("4096,P,98.700,1000,9.695,0.1,0.035") #handle_line("4096,P,8.700,1000,9.695,0.1,0.035") #handle_line("4096,P,8.700,1000,8.700,0.1,0.035") #handle_line("4096,P,8.700,1000,8.700,0.1,0.005") #handle_line("4096,P,8.700,1000,8.700,0.9,0.005") #handle_line("10000,P,98.700,60,98.695,0.9,0.035") #handle_line("50000,C,98.700,60,98.695,0.2,0.035") #handle_line("50000,C,98.700,60000,98.695,0.2,0.035") #handle_line("100000,C,98.700,10000,438.695,0.2,0.035") #handle_line("50000,C,98.700,10000,438.695,0.2,0.1") #handle_line("50000,C,98.700,10000,438.695,0.2,1000")
By By Layne Weiss Jul 6, 2012 in World France's highest court has ruled that French police are no longer permitted to arrest illegal immigrants unless they are suspected of having committed a crime, France 24 is reporting. Before this, police could hold "sans-papers," meaning "without papers," the French term for illegal aliens, even if they had not committed a crime. Under French law, being an illegal alien is not a crime in France. On Thursday, France's According to According to the In a press conference, Interior Minister Claude Gueant announced that French authorities had removed 32,912 illegal immigrants from France, up 17.5% from 2010. Like then President, Nicolas Sarkozy, Gueant also had a hardline stance against illegal immigration. Sarkozy, who lost the election to Socialist candidate, new President of France, Francois Hollande, always took a strong stance against illegal immigration. He argued that keeping illegal immigrants in police custody for a certain amount of time was justifiable according to Back in March, his staunch stance on immigration policies actually gave him a jolt in the polls, the Sarkozy was predicted to lose the election all along, but his hostility to illegal immigration policies gave him a much needed boost. In April, Sarkozy's opponent and current French President, Francois Hollande said France was experiencing a crisis, and that limiting economic immigration was "necessary and essential," According to Hollande's opponent, the incumbent, Nicolas Sarkozy won in 2007 by appealing to far right wing voters about the severity of the illegal immigration issues. While Sarkozy and Hollande were both vocal about the illegal immigration issue in France, Sarkozy took a way stronger stance on the issue. Hollande is France's first Socialist leader in 20 years. The last Socialist leader prior to Hollade was It is important to understand that illegal immigration in France is still a key issue, but Patrice Spinosi, legal counsel for the high court, explained to Mr. Spinosi noted that France's new government is ready to change the law, whereas, under Sarkozy, France knew it was at risk of breaching European law, but "refused to reform." The far-right national front called Thursday's ruling "lax, ultraliberal, and pandering to the whims of a European legal oligarchy," Illegal immigrants can no longer be detained by police simply for not having legal citizenship papers, the court ruled Thursday according to France 24 Before this, police could hold "sans-papers," meaning "without papers," the French term for illegal aliens, even if they had not committed a crime.Under French law, being an illegal alien is not a crime in France. On Thursday, France's Cour de Cassation , the country's highest court, ruled in favor of a group of illegal immigrants who argued their detentions were unjust and illegal under French law.According to France 24 , Interior Minister Manuel Valls said the French government would act quickly and officially to amend French law, but maintained that "the ultimate removal of illegal aliens (from France) must remain central to any legislation on this issue."According to the Daily Mail , France announced it had expelled more illegal immigrants in 2011 than ever before.In a press conference, Interior Minister Claude Gueant announced that French authorities had removed 32,912 illegal immigrants from France, up 17.5% from 2010.Like then President, Nicolas Sarkozy, Gueant also had a hardline stance against illegal immigration.Sarkozy, who lost the election to Socialist candidate, new President of France, Francois Hollande, always took a strong stance against illegal immigration. He argued that keeping illegal immigrants in police custody for a certain amount of time was justifiable according to EU immigration laws , but many argued that Sarkozy was oversimplifying EU policies for his own gain, and various courts issued verdicts on the legality of actually locking illegal aliens up in jail, France 24 reports.Back in March, his staunch stance on immigration policies actually gave him a jolt in the polls, the Daily Mail reports.Sarkozy was predicted to lose the election all along, but his hostility to illegal immigration policies gave him a much needed boost.In April, Sarkozy's opponent and current French President, Francois Hollande said France was experiencing a crisis, and that limiting economic immigration was "necessary and essential," Reuters reports.According to France 24 , Hollande also stated it was not right "that a certain number of employers, in a cynical way, are hiring illegal immigrants."Hollande's opponent, the incumbent, Nicolas Sarkozy won in 2007 by appealing to far right wing voters about the severity of the illegal immigration issues.While Sarkozy and Hollande were both vocal about the illegal immigration issue in France, Sarkozy took a way stronger stance on the issue. Hollande is France's first Socialist leader in 20 years. The last Socialist leader prior to Hollade was Francois Mitterand. It is important to understand that illegal immigration in France is still a key issue, but Patrice Spinosi, legal counsel for the high court, explained to France 24 , that Thursday's ruling simply means that dealing with illegal immigrants would now be an "administrative rather than criminal procedure," and that now French police would be obligated to "comply with European law."Mr. Spinosi noted that France's new government is ready to change the law, whereas, under Sarkozy, France knew it was at risk of breaching European law, but "refused to reform."The far-right national front called Thursday's ruling "lax, ultraliberal, and pandering to the whims of a European legal oligarchy," France 24 reports. More about french illegal immigrants, no detaining power, must be suspects in crimes More news from french illegal immig... no detaining power must be suspects in ...
ON THE EMPLOYMENT OF EDGE BASIS FUNCTIONS TO IMPROVE THE ANALYSIS OF POLYGONAL PATCHES A new set of entire domain basis functions has been recently proposed in the literature for analyzing microstrip antennas with convex polygonal patches through a Method of Moment (MoM) numerical procedure. These basis functions represent a complete set of orthogonal functions, but they do not take into account the singular behavior of the tangential component of the current density at the patch edges. This property indeed limits the efficiency and accuracy of the analysis and only some particular geometries can be well described. When more accurate analyses are needed, the singular behavior of the current should be considered and the introduction of new auxiliary basis functions to fix the current behavior at the patch edges is a mandatory task. The aim of this paper is to present a new set of edge basis functions, suitable for a MoM analysis of convex polygonal patch antennas, to be used in conjunction with the entire domain basis functions already presented by the authors, in order to improve the overall accuracy of the method. Some examples showing the capabilities of the new functions are proposed.
/* scrivere un programma Go (il file si deve chiamare Config.go) che prenda da stdin un elenco di righe <chiave,valore> nella forma: chiave = valore chiave1 = valore1 chiave2 = valore2 ... chiave2 = nuovoValore2 chiaveN = valoreN "chiave con spazi" = valoreDiChiaveConSpazi dove i valori sono numeri decimali (float64) e le chiavi sono stringhe di lunghezza arbitraria Il programma deve costruire una map e riempirla con i valori trovati in stdin e alla fine stampare tutta la tabella dei valori in forma TABBED, cioè: chiave valore chiave1 valore1 chiave2 nuovoValore2 ... chiaveN valoreN */ package main import ("fmt") func main () { fmt.Println("Inserire i dati nel formato Chiave = Valore. Il programma termina facendo seguire 'stop' a un valore (es. chiave = valore stop).") m:= make(map[string]float64) var s,stop string var f float64 for stop!="stop" { fmt.Scanf("%s = %f %s",&s,&f,&stop) m[s]=f } for chiave,valore := range m{ fmt.Printf("%s\t%f\n",chiave,valore) } } package main import ( "fmt" "os" "bufio" "strings" "strconv" ) func main() { var mappa map[string]float64 mappa=make(map[string]float64) scanner:=bufio.NewScanner(os.Stdin) for scanner.Scan() { line:=scanner.Text() linesplit:=strings.Split(line, " = ") number,_:=strconv.ParseFloat(linesplit[1],64) mappa[linesplit[0]]=number } for k,v:=range mappa { fmt.Printf("%-10s \t %10.3f\n",k,v) } }
/** * Behavior for Float Button * Created by wing on 11/8/16. */ public class ByeBurgerFloatButtonBehavior extends ByeBurgerBehavior { public ByeBurgerFloatButtonBehavior(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) { if(canInit) { mAnimateHelper = ScaleAnimateHelper.get(child); canInit = false; } return super.layoutDependsOn(parent, child, dependency); } @Override protected void onNestPreScrollInit(View child) { } }
def reference_viewer(sys_argv): viewer = ReferenceViewer(layout=default_layout) viewer.add_default_plugins() viewer.add_separately_distributed_plugins() from argparse import ArgumentParser argprs = ArgumentParser(description="Run the Ginga reference viewer.") viewer.add_default_options(argprs) argprs.add_argument('-V', '--version', action='version', version='%(prog)s {}'.format(version.version)) (options, args) = argprs.parse_known_args(sys_argv[1:]) if options.display: os.environ['DISPLAY'] = options.display if options.debug: import pdb pdb.run('viewer.main(options, args)') elif options.profile: import profile print(("%s profile:" % sys_argv[0])) profile.runctx('viewer.main(options, args)', dict(options=options, args=args, viewer=viewer), {}) else: viewer.main(options, args)
Remarks on weak compactness of operators defined on certain injective tensor products We show that if X is a 2.-space with the Dieudonn6 property and Y is a Banach space not containing 11 , then any operator T: X? Y -Z where Z is a weakly sequentially complete Banach space, is weakly compact. Some other results of the same kind are obtained. Let X be a 2 -space (see for this notion and some useful results on Ycspaces) and Y be a Banach space not containing 11 . We consider the invective tensor product X 0G Y (see ), and we investigate the following problem: when is any operator T: X 0G Y -* Z, where Z is a Banach space, weakly compact? In the case of X = C(K) there are some papers devoted to the study of this question (see ), but nothing seems to be known in the present setting; we observe that the theorems proved in the paper extend all of the above-quoted results, but their proofs make use of the results in , so that they may be considered interesting complements to those theorems. Because the proofs of our results are similar, we give the proof of Theorem 2 only and leave the others to the reader. We need the following definition: a Banach space E has the Dieudonne property if any weakly completely continuous (or Dieudonne) operator defined on it is weakly compact . We recall that C(K) spaces have the Dieudonnd property. Lemma 1. X** 0G Y is a closed subspace of (X By Y)** . Proof. Let x** X y be an element of X 0 Y and consider (o E (X 0G Y)*= B' (X, Y) (see for a definition of B' (X, Y)) . Since B' (X, Y) is a closed subspace of B"(X**, Y) = (X** Q, Y)* (see ) and since IIkIIB-(XY) = II DIIB9(X**,Y) for any (o E B"(X, Y), we have I(9(x** Xy)l <? IkIkIIx** Qylil and so x** 0 y E (X 0G Y)**; hence ZP.=1 X** 0 yj E (X Go Y)**. Now, we have to show that l FP x** 0 yile = II Z=1 x** 0 yjII(x?,y)** . The inequality 1Z E x 7 X* (0 yjIIe < 11 EZ 1 x** 0 yiII(X?eY)** follows very easily from the very definition of e-norm , the weak * density of Bx* in Bx*** , and the fact that Received by the editors March 22, 1991. 1991 Mathematics Subject Classification. Primary 47B99, 46MO5.
def debug_images(self): if self._res is None: return None else: r = dict() for key in self._res: if key.find("IMG_") >= 0: r[key] = self._res[key] return r
Site of Selective Action of Halothane on the Peripheral Chemoreflex Pathway in Humans Halothane in humans depresses the ventilatory response to hypoxemia in a manner that suggests a selective action on one or more components of the peripheral chemoreflex arc. To test the hypothesis that this action is at the carotid bodies themselves, the authors studied the ventilatory response to subanesthetic concentrations of halothane (0.15–0.30% inspired) in six fit volunteers maintained in a steady state of isocapnic hypoxemia (PEo2 50 mmHg). Upon exposure to halothane, hypoxemia-driven ventilation decreased promptly and progressively (from 7.5 · 1.2 1 · min−1 · m−2 in the control state to 5.9 · 0.9 and 4.8 · 0.7 1 · min−1 · m−2 at 30 s and 60 s of inhalation respectively, means · SEM). The relationship of hypoxemia-driven ventilation to end-tidal halothane tensions at 30 and 60 s of halothane wash-in (PEHal 0.4 and 0.6 mmHg, respectively) approached the relationship observed in near steady states of halothane inhalation. The results are interpreted as indicating that the site of selective action is at a tissue that accumulates halothane very rapidly during the first minute of inhalation. To make possible such pharmacokinetics, that tissue would require 1) a location having a brief circulatory transit time from the lungs, and 2) an extremely high rate of perfusion in relation to its capacity for uptake of halothane. The only tissue of the peripheral chemoreflex pathway that can satisfy these requirements is that of the carotid bodies.
Study of missing meter data impact on domestic load profiles clustering and characterization Automated load managements and cost-effective power systems in distribution level are now becoming possible by increasing the number of installed smart meters at end-users side. Monitoring and controlling the massive datasets of demand curves require using data mining and characterizing load profiles. This paper analyses a wide range of data from a comprehensive survey of residential customers. It investigates the effect of missing load measurement in the result of clustering consumers load profiles. Different scenarios have been considered in order to detect and deal with missing or incorrect recordings. Moreover, the result of clustering for different percentage of missed values has been evaluated considering various numbers of clusters.
The Edinburgh Agreement (full title: Agreement between the United Kingdom Government and the Scottish Government on a referendum on independence for Scotland) is the agreement between the Scottish Government and the United Kingdom Government, signed on 15 October 2012 at St Andrew's House, Edinburgh, on the terms for the Scottish independence referendum, 2014.[1] Both governments agreed that the referendum should: have a clear legal base be legislated for by the Scottish Parliament be conducted so as to command the confidence of parliaments, government and people deliver a fair test and decisive expression of the views of people in Scotland and a result that everyone will respect The governments agreed to promote an Order in Council under Section 30 of the Scotland Act 1998 to allow a single-question referendum on Scottish independence to be held before the end of 2014 so to put beyond doubt that the Scottish Parliament can legislate for the referendum.[2] The agreement was signed by David Cameron, Prime Minister; Michael Moore, Secretary of State for Scotland; Alex Salmond, First Minister; and Nicola Sturgeon, Deputy First Minister. Whether the document was legally binding in theory is a matter of academic discussion.[3] In practice, an Order in Council was in fact approved on 12 February 2013,[4] granting constitutional legitimacy to the referendum held on 18 September 2014. See also [ edit ] References [ edit ]
In this post you will have free access to download strength of materials pdf , Fourth Edition by Dr. R. K. Bansal Strength of Materials Book by R. K. Bansal Free Download Strength of Materials , also known as mechanics of materials , deals with the behavior of solid objects subject to stresses and strains . when an object is in compression and tension. The theory of strength of material began with the consideration of the behavior of one and two dimensional members of structures, whose states of stress can be approximated as two dimensional, and was then generalized to three dimensions to develop a more complete theory of the elastic and plastic behavior of materials. Strength of materials covers various methods of calculating the stresses and strains in structural members, such as beams, columns, and shafts as in structural aspect of civil engineering You May Like: Solution Manual of Mechanics of materials by Beer and Johnston Table of Contents: Strength of Materials Book by R K Bansal covers the following subjects ; Elastic Constants Strain Energy and Impact Loading Centre of Gravity and Moment of Inertia Stresses in a Thick Cylindrical Shell Columns and Struts Riveted Joints Welded Joints Supported Beam with a Point Load at Midpoint Bending Stresses in Beams Torsion of Shafts and Springs Thin Cylinders and Spheres Download Strength of Materials Book by R . K . Bansal Free Download A PDF on Strength Of Materials : Mechanics of Solids (S.I. Units) (English) TAGS
Opportunistic Pervasive Computing with Domain-Oriented Virtual Machines The paper targets heterogeneous sensor-actuator networks, in which nodes differ as to resources (sensors and actuators) they are equipped with. Each node contributes its specific sensors and actuators to be used by applications. The key assumption of "opportunistic pervasive computing" is that the actual mix of nodes (and that of available resources) is not known in advance to the programmer. An opportunistic pervasive computing application is supposed to take the best advantage of whatever sensors and actuators happen to be available in the network. The paper presents a technique that can be used in middleware layers supporting such applications. The technique uses virtual machines to orderly expose sensor and actuator resources of a node to the programmer. The virtual machines are domain-oriented, node specific and able to work with the resources at multiple levels of abstraction. They can be implemented on severely constrained nodes (e.g., of the TinyOS class)
#!/usr/bin/env python3 # # Copyright 2019 ROBOTIS CO., LTD. # # 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. # # Authors: <NAME>, Gilbert import os import tensorflow as tf import random import sys import time from gazebo_msgs.srv import DeleteEntity from gazebo_msgs.srv import SpawnEntity from geometry_msgs.msg import Pose import rclpy from rclpy.node import Node from rclpy.qos import QoSProfile from rclpy.qos import qos_profile_sensor_data from std_srvs.srv import Empty from geometry_msgs.msg import Twist from pic4rl_msgs.srv import State, Reset, Step from nav_msgs.msg import Odometry from sensor_msgs.msg import LaserScan from sensor_msgs.msg import Image import numpy as np import math from numpy import savetxt import cv2 from cv_bridge import CvBridge from rclpy.qos import QoSProfile class Pic4rlEnvironment(Node): def __init__(self): super().__init__('pic4rl_environment') # To see debug logs #rclpy.logging.set_logger_level('omnirob_rl_environment', 10) """************************************************************ ** Initialise ROS publishers and subscribers ************************************************************""" qos = QoSProfile(depth=10) self.cmd_vel_pub = self.create_publisher( Twist, 'cmd_vel', qos) self.Image_sub = self.create_subscription( Image, '/camera/depth/image_raw', self.DEPTH_callback, qos_profile=qos_profile_sensor_data) # Initialise client #self.send_twist = self.create_client(Twist, 'send_twist') #self.task_succeed_client = self.create_client(Empty, 'task_succeed') #self.task_fail_client = self.create_client(Empty, 'task_fail') self.pause_physics_client = self.create_client(Empty, 'pause_physics') self.unpause_physics_client = self.create_client(Empty, 'unpause_physics') self.get_state_client = self.create_client(State, 'get_state') self.new_episode_client = self.create_client(Reset, 'new_episode') """########## State variables ##########""" self.init_step = True self.episode_step = 0 self.goal_pos_x = None self.goal_pos_y = None self.goal_index = 0 self.previous_twist = None self.previous_pose = Odometry() self.previous_pos = Odometry() self.total_distance = 0 self.goal_distance = 0 self.stage = 1 self.lidar_points = 359 self.cutoff = 5 #self.depth_image = np.zeros((240,320), np.uint8) self.bridge = CvBridge() #test variable self.step_flag = False self.twist_received = None """########## Environment initialization ##########""" """############# Main functions #############""" def render(self): pass def step(self, action): twist = Twist() twist.linear.x = float(action[0]) #twist.linear.y = float(action[1]) twist.angular.z = float(action[1]) observation, reward, done = self._step(twist) info = None return observation, reward, done, info, self.total_distance, self.goal_distance def _step(self, twist=Twist(), reset_step = False): #After environment reset sensors data are not instaneously available #that's why there's the while. A timer could be added to increase robustness data_received = False while not data_received: # Send action self.send_action(twist) # Get state state = self.get_state() data_received = state.data_received lidar_measurements, goal_distance, goal_angle, pos_x, pos_y, yaw, depth_image = self.process_state(state, reset_step) # Check events (failure,timeout, success) done, event = self.check_events(lidar_measurements, goal_distance, self.episode_step) if not reset_step: # Get reward reward = self.get_reward(twist,lidar_measurements, goal_distance, goal_angle, pos_x, pos_y, yaw, done, event) observation = self.get_observation(twist,lidar_measurements, goal_distance, goal_angle, pos_x, pos_y, yaw, depth_image) else: reward = None observation = None self.path_length = 0 # Send observation and reward self.update_state(twist,lidar_measurements, goal_distance, goal_angle, pos_x, pos_y, yaw, done, event) return observation, reward, done def reset(self, episode): #self.destroy_subscription('cmd_vel') self.episode = episode req = Reset.Request() req.goal_pos_x,req.goal_pos_y = self.get_goal(episode) self.get_logger().info("Environment reset ...") while not self.new_episode_client.wait_for_service(timeout_sec=1.0): self.get_logger().info('service not available, waiting again...') future = self.new_episode_client.call_async(req) #self.get_logger().debug("Reset env request sent ...") #rclpy.spin_until_future_complete(self, future,timeout_sec=1.0) #time_start = time.time() while rclpy.ok(): rclpy.spin_once(self,timeout_sec=2) if future.done(): if future.result() is not None: self.get_logger().debug("Environment reset done") break #if time.time() - time_start > 10: # raise ValueError("In realtà non è un ValueError") self.get_logger().debug("Performing null step to reset variables") _,_,_, = self._step(reset_step = True) observation,_,_, = self._step() return observation, self.goal_pose_x, self.goal_pose_y """############# Secondary functions (used in main functions) #############""" def send_action(self,twist): self.get_logger().debug("unpausing...") self.unpause() self.get_logger().debug("publishing twist...") self.cmd_vel_pub.publish(twist) time.sleep(0.1) self.get_logger().debug("pausing...") self.pause() def get_state(self): self.get_logger().debug("Asking for the state...") req = State.Request() future =self.get_state_client.call_async(req) rclpy.spin_until_future_complete(self, future) try: state = future.result() except Exception as e: node.get_logger().error('Service call failed %r' % (e,)) self.get_logger().debug("State received ...") return state def process_state(self,state, reset_step): self.episode_step += 1 #from LaserScan msg to 359 len filterd list lidar_measurements = self.filter_laserscan(state.scan) #from 359 filtered lidar points to 60 selected lidar points lidar_measurements = self.process_laserscan(lidar_measurements) #from Odometry msg to x,y, yaw, distance, angle wrt goal goal_distance, goal_angle, pos_x, pos_y, yaw = self.process_odom(state.odom, reset_step) #process Depth Image from sensor msg depth_image = self.process_depth_image() return lidar_measurements, goal_distance, goal_angle, pos_x, pos_y, yaw, depth_image def check_events(self, lidar_measurements, goal_distance, step): min_range = 0.25 if 0.05 <min(lidar_measurements) <= min_range: # Collision self.get_logger().info('Collision') return True, "collision" if goal_distance < 0.2: # Goal reached self.get_logger().info('Goal') return True, "goal" if step >= 1000: #Timeout self.get_logger().info('Timeout') return True, "timeout" return False, "None" def get_observation(self, twist,lidar_measurements, goal_distance, goal_angle, pos_x, pos_y, yaw,depth_image): #WITH DEPTH CAMERA # state_list = [] # goal_dist = goal_distance/self.cutoff # goal_angle_norm = goal_angle/(math.pi) # goal_info = np.array([goal_dist, goal_angle_norm], dtype=np.float32) # goal_info =tf.convert_to_tensor(goal_info) # state_list.append((goal_info)) # state_list.append(depth_image) # return state_list #WITH LIDAR state_list = [] state_list.append(float(goal_distance)) state_list.append(float(goal_angle)) #state_list.append(float(self.min_obstacle_distance)) #state_list.append(float(self.min_obstacle_angle)) for point in lidar_measurements: state_list.append(float(point)) #print(point) state = np.array(state_list,dtype = np.float32) return state def get_reward(self,twist,lidar_measurements, goal_distance, goal_angle, pos_x, pos_y, yaw, done, event): reward = 0 if event == "goal": reward += 100 elif event == "collision": reward += -50 elif event == "timeout": reward += -25 self.get_logger().debug(str(reward)) #print("Score:", reward) return reward def get_goal(self,episode): goal_pose_list_easy = [[2.0, -1.5],[1.2, -1.8],[0.2, -2.0], [2.0, 2.0], [0.8, 2.0], [-1.9, 1.2], [-1.9, -0.5], [-2.0, -2.0]] goal_pose_list = [[3.0, 2.0], [-3.0, -2.0], [-0.2, 4.0], [-2.0, -4.0], [-4.0, 1.0], [-2.5, -2.5], [2.2, 4.0], [3.5, 4.0], [2.5, -4.4],[4.5,4.5], [-4.2, -4.2],[3.6, 3.6], [1.0, -4.0], [-1.9, -4.0], [-4.5, -3.0], [-4.1, 4.1], [2.3, 4.2], [-2.4, 4.2], [1.3, -4.2],[-4.4, -1.0], [4.0, 2.5],[-4.5, 0.8],[-0.5, -4.2], [-4.1, 0.0]] x = goal_pose_list[self.goal_index][0] y = goal_pose_list[self.goal_index][1] self.goal_index += 1 print("Goal pose: ", x, y) self.get_logger().info("New goal") #self.get_logger().info("New goal: (x,y) : " + str(x) + "," +str(y)) self.goal_pose_x = x self.goal_pose_y = y return x,y def update_state(self,twist,lidar_measurements, goal_distance, goal_angle, pos_x, pos_y, yaw, done, event): #Here state variables are updated self.episode_step += 1 self.previous_twist = twist self.previous_lidar_measurements = lidar_measurements self.previous_goal_distance = goal_distance self.previous_goal_angle = goal_angle self.previous_pos_x = pos_x self.previous_pos_y = pos_y self.previous_yaw = yaw # If done, set flag for resetting everything at next step if done: self.init_step = True self.episode_step = 0 """############# Auxiliar functions (used in secondary functions) #############""" def pause(self): req = Empty.Request() while not self.pause_physics_client.wait_for_service(timeout_sec=1.0): self.get_logger().info('service not available, waiting again...') self.pause_physics_client.call_async(req) def unpause(self): req = Empty.Request() while not self.unpause_physics_client.wait_for_service(timeout_sec=1.0): self.get_logger().info('service not available, waiting again...') self.unpause_physics_client.call_async(req) def filter_laserscan(self,laserscan_msg): # There are some outliers (0 or nan values, they all are set to 0) that will not be passed to the DRL agent # Correct data: scan_range = [] # Takes only sensed measurements for i in range(self.lidar_points): if laserscan_msg.ranges[i] == float('Inf'): scan_range.append(3.50) elif np.isnan(laserscan_msg.ranges[i]): scan_range.append(0.00) else: scan_range.append(laserscan_msg.ranges[i]) return scan_range def process_laserscan(self,lidar_pointlist): scan_range_process = [] min_dist_point = 100 # Takes only 60 lidar points for i in range(self.lidar_points): if lidar_pointlist[i] < min_dist_point: min_dist_point = lidar_pointlist[i] if i % 10 == 0: scan_range_process.append(min_dist_point) min_dist_point = 100 #print('selected lidar points:', len(scan_range_process)) self.min_obstacle_distance = min(scan_range_process) self.min_obstacle_angle = np.argmin(scan_range_process) return scan_range_process def DEPTH_callback(self, msg): depth_image_raw = np.zeros((120,160), np.uint8) depth_image_raw = self.bridge.imgmsg_to_cv2(msg, '32FC1') self.depth_image_raw = np.array(depth_image_raw, dtype= np.float32) #print(self.depth_image_raw.shape) #savetxt('/home/mauromartini/mauro_ws/depth_images/text_depth_image_raw.csv', depth_image_raw, delimiter=',') #np.save('/home/maurom/depth_images/depth_image.npy', depth_image_raw) #cv2.imwrite('/home/mauromartini/mauro_ws/depth_images/d_img_raw.png', self.depth_image_raw) #@tf.function def process_depth_image(self): img = np.array(self.depth_image_raw, dtype= np.float32) #savetxt('/home/maurom/depth_images/text_depth_image.csv', depth_image, delimiter=',') #print('image shape: ', depth_image.shape) #check crop is performed correctly #img = tf.convert_to_tensor(self.depth_image_raw, dtype=tf.float32) #img = img.reshape(240,320,1) img = tf.reshape(img, [120,160,1]) #width =304 #height = 228 #h_off = int((240-height)*0.5) #w_off = int((320-width)*0.5) #img_crop = tf.image.crop_to_bounding_box(img,h_off,w_off,height,width) img_resize = tf.image.resize(img,[60,80]) depth_image = tf.reshape(img_resize, [60,80]) depth_image = np.array(depth_image, dtype= np.float32) #cv2.imwrite('/home/mauromartini/mauro_ws/depth_images/d_img_res.png', depth_image) #savetxt('/home/mauromartini/mauro_ws/depth_images/depth_image_60_80.csv', depth_image, delimiter=',') depth_image = self.depth_rescale(depth_image, self.cutoff) #print(depth_image.shape) #cv2.imwrite('/home/mauromartini/mauro_ws/depth_images/d_img_cutoff.png', depth_image) #savetxt('/home/mauromartini/mauro_ws/depth_images/depth_image_cutoff.csv', depth_image, delimiter=',') self.image_size = depth_image.shape return depth_image def depth_rescale(self,img, cutoff): #Useful to turn the background into black into the depth images. w,h = img.shape #new_img = np.zeros([w,h,3]) img = img.flatten() img[img>cutoff] = cutoff img = img.reshape([w,h]) #assert np.max(img) > 0.0 img = img/cutoff #img_visual = 255*(self.depth_image_raw/cutoff) img = np.array(img, dtype=np.float32) #img_visual = np.array(img_visual, dtype=np.uint8) #img_visual = cv2.equalizeHist(img_visual) #cv2.imwrite('/home/mauromartini/mauro_ws/depth_images/d_img_cutoff.png', img_visual) #for i in range(3): # img[:,:,i] = cv2.equalizeHist(img[:,:,i]) return img def process_odom(self, odom_msg, reset_step): if(reset_step): self.previous_pos_x = odom_msg.pose.pose.position.x self.previous_pos_y = odom_msg.pose.pose.position.y self.total_distance = 0 pos_x = odom_msg.pose.pose.position.x pos_y = odom_msg.pose.pose.position.y _,_,yaw = self.euler_from_quaternion(odom_msg.pose.pose.orientation) goal_distance = math.sqrt( (self.goal_pose_x-pos_x)**2 + (self.goal_pose_y-pos_y)**2) path_theta = math.atan2( self.goal_pose_y-pos_y, self.goal_pose_x-pos_x) goal_angle = path_theta - yaw if goal_angle > math.pi: goal_angle -= 2 * math.pi elif goal_angle < -math.pi: goal_angle += 2 * math.pi self.goal_distance = goal_distance self.goal_angle = goal_angle #print('Goal distance:', self.goal_distance) d_increment = math.sqrt((pos_x - self.previous_pos_x)**2 + (pos_y - self.previous_pos_y)**2) self.total_distance = self.total_distance + d_increment #print("Total distance traveled is ", self.total_distance) self.previous_pose_x = pos_x self.previous__pose_y = pos_y return goal_distance, goal_angle, pos_x, pos_y, yaw def euler_from_quaternion(self, quat): """ Converts quaternion (w in last place) to euler roll, pitch, yaw quat = [x, y, z, w] """ x = quat.x y = quat.y z = quat.z w = quat.w sinr_cosp = 2 * (w*x + y*z) cosr_cosp = 1 - 2*(x*x + y*y) roll = np.arctan2(sinr_cosp, cosr_cosp) sinp = 2 * (w*y - z*x) pitch = np.arcsin(sinp) siny_cosp = 2 * (w*z + x*y) cosy_cosp = 1 - 2 * (y*y + z*z) yaw = np.arctan2(siny_cosp, cosy_cosp) return roll, pitch, yaw def main(args=None): rclpy.init() pic4rl_environment = Pic4rlEnvironment() pic4rl_environment.spin() pic4rl_environment.get_logger().info('Node spinning ...') rclpy.spin_once(pic4rl_environment) pic4rl_environment.destroy() rclpy.shutdown() if __name__ == '__main__': main()
Former Vice President Dick Cheney and his daughter Liz have an op-ed in the Wall Street Journal arguing that Barack Obama is insufficiently tough on Iraq, and was wrong to "abandon" the country. They also took to Fox News to announce they were starting a new organization, the Alliance for a Strong America, that will "advocate for the policies needed to restore American power and pre-eminence." You might be tempted to take their opinions seriously. This would be a mistake. Here are seventeen reasons why. 1) "[9/11 hijacker Mohamed Atta] did go to Prague and he did meet with a senior official of the Iraqi intelligence service in Czechoslovakia last April, several months before the attack." - Dick Cheney, December 9, 2001. Atta did not meet with Iraqi intelligence in Prague. Cheney knew this claim was unsubstantiated but made it publicly anyway. Also Czechoslovakia was not a country in April 2001. 2) "The issue is that [Saddam] has chemical weapons." - Dick Cheney, March 24, 2002. No he did not. 3) "Simply stated, there is no doubt that Saddam Hussein now has weapons of mass destruction." - Dick Cheney, August 25, 2002. Saddam Hussein did not have weapons of mass destruction then. 4) "Another argument holds that opposing Saddam Hussein would cause even greater troubles in that part of the world, and interfere with the larger war against terror. I believe the opposite is true." - Dick Cheney, August 25, 2002. The Iraq War was a catastrophe that caused even greater troubles, including hundreds of thousands of deaths and millions of refugees, in that part of the world. It also harmed the war on terror. 5) "We do know, with absolute certainty, that [Saddam] is using his procurement system to acquire the equipment he needs in order to enrich uranium to build a nuclear weapon." - Dick Cheney, September 8, 2002. Not only was this false, especially the "absolute certainty" part, Cheney likely knew it to be false at the time he said it; the intelligence community was in fact divided about the state of Iraq's nuclear program. 6) "[Saddam] now is trying, through his illicit procurement network, to acquire the equipment he needs to be able to enrich uranium to make the bombs…Specifically aluminum tubes." - Dick Cheney, September 8, 2002. The tubes were for rockets. Department of Energy analysts raised doubts more than a year before Cheney made these claims about the likelihood the tubes were for enrichment. 7) "We know that [Saddam Hussein] has re-energized, if you will, his efforts to acquire a nuclear weapon." - Dick Cheney, September 9, 2002. The Iraq Survey Group concluded after a thorough investigation that "Saddam Hussein ended the nuclear program in 1991 following the Gulf war. ISG found no evidence to suggest concerted efforts to restart the program." 8) "We now have irrefutable evidence that [Saddam] has once again set up and reconstituted his program to take uranium, to enrich it to sufficiently high grade, so that it will function as the base material as a nuclear weapon. And there's no doubt about the fact that the level of effort has escalated in recent months." - Dick Cheney, September 20, 2002. Cheney knew there was not "irrefutable evidence," as the intelligence community was divided. And reality subsequently refuted the claim entirely. 9) "I think things have gotten so bad inside Iraq, from the standpoint of the Iraqi people, my belief is we will, in fact, be greeted as liberators." - Dick Cheney, March 16, 2003. We were not greeted as liberators. 10) "[Saddam] also had an established relationship with al Qaeda — providing training to al Qaeda members in areas of poisons, gases and conventional bombs." - Dick Cheney, October 17, 2003. A 2006 Senate intelligence committee report concluded, "Postwar findings support the April 2002 Defense Intelligence Agency (DIA) assessment that there was no credible reporting on al-Qa'eda training at Salman Pak or anywhere else in Iraq." 11) "In Iraq, a ruthless dictator cultivated weapons of mass destruction and the means to deliver them. He gave support to terrorists, had an established relationship with al Qaeda, and his regime is no more." - Dick Cheney, November 7, 2003. There was no such relationship between al Qaeda and Iraq. Iraq had no weapons of mass destruction. 12) "We haven't really had the time yet to pore through all those records in Baghdad. We'll find ample evidence confirming the link, that is the connection if you will between al Qaeda and the Iraqi intelligence services. They have worked together on a number of occasions." - Dick Cheney, January 9, 2004. Again, there was no such relationship between al Qaeda and the Iraqi intelligence services. 13) "We know, for example, that prior to our going in that [Saddam] had spent time and effort acquiring mobile biological weapons labs, and we're quite confident he did, in fact, have such a program. We've found a couple of semi trailers at this point which we believe were, in fact, part of that program. I would deem that conclusive evidence, if you will, that he did, in fact, have programs for weapons of mass destruction." - Dick Cheney, January 22, 2004. A British investigation concluded those "mobile biological weapons labs" were nothing of the sort. The Iraq Survey group report states, "ISG has found no evidence to support the view that the trailers were used, or intended to be used, for the production of [biological warfare] agents." 14) "It’s clearly established in terms of training, provision of bomb-making experts, training of people with respect to chemical and biological warfare capabilities, that al-Qaeda sent personnel to Iraq for training and so forth." - Dick Cheney, June 4, 2004. Again, not only was that not true, but the DIA and others in the intelligence community questioned it before the war began. 15) "I think they're in the last throes, if you will, of the insurgency." - Dick Cheney, June 20, 2005. Anti-Iraqi government insurgency persists nine years later. 16) "I don’t think that [the war in Iraq] damaged our reputation around the world." - Dick Cheney, August 30, 2011. The Iraq war drastically damaged our reputation around the world. 17) "The biggest threat we face is the possibility of terrorist groups like al Qaeda equipped with weapons of mass destruction, with nukes, bugs or gas. That was the threat after 9/11 and when we took down Saddam Hussein we eliminated Iraq as a potential source of that." - Dick Cheney, October 28, 2013. The Iraq war took away zero weapons of mass destruction from a regime that did not have ties to al-Qaeda.
/** * Copyright 2020 Appvia Ltd <<EMAIL>> * * 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 kubernetes import ( "context" "time" clustersv1 "github.com/appvia/kore/pkg/apis/clusters/v1" configv1 "github.com/appvia/kore/pkg/apis/config/v1" corev1 "github.com/appvia/kore/pkg/apis/core/v1" "github.com/appvia/kore/pkg/controllers" "github.com/appvia/kore/pkg/kore" "github.com/appvia/kore/pkg/utils/kubernetes" log "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" kerrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/reconcile" ) // EnsureCloudProvider is responsible for checking the cloud provider func (a k8sCtrl) EnsureCloudProvider(object *clustersv1.Kubernetes) controllers.EnsureFunc { return func(ctx context.Context) (reconcile.Result, error) { if !kore.IsProviderBacked(object) { return reconcile.Result{}, nil } return reconcile.Result{}, nil } } // EnsureDeleteStatus is responsible for ensure the status is set to deleting func (a k8sCtrl) EnsureDeleteStatus(object *clustersv1.Kubernetes) controllers.EnsureFunc { return func(ctx context.Context) (reconcile.Result, error) { if object.Status.Status != corev1.DeletingStatus { object.Status.Status = corev1.DeletingStatus return reconcile.Result{Requeue: true}, nil } return reconcile.Result{}, nil } } // EnsureServiceDeletion is responsible for cleanup the resources in the cluster // @note: at present this is only done for EKS as GKE performs it's own cleanup func (a k8sCtrl) EnsureServiceDeletion(object *clustersv1.Kubernetes) controllers.EnsureFunc { return func(ctx context.Context) (reconcile.Result, error) { logger := log.WithFields(log.Fields{ "name": object.Name, "namespace": object.Namespace, }) logger.Debug("attempting to delete the kubernetes resource") if !kore.IsProviderBacked(object) { return reconcile.Result{}, nil } if object.Spec.Provider.Kind != "EKS" { return reconcile.Result{}, nil } result, err := func() (reconcile.Result, error) { // @step: retrieve the provider credentials secret token, err := controllers.GetConfigSecret(ctx, a.mgr.GetClient(), object.Namespace, object.Name) if err != nil { if kerrors.IsNotFound(err) { return reconcile.Result{}, nil } return reconcile.Result{}, err } // @step: create a client for the remote cluster cc, err := kubernetes.NewRuntimeClientFromConfigSecret(token) if err != nil { return reconcile.Result{}, err } // @note: we need to look for any namespaces with loadbalancer types and // delete them to free up the ELB and security groups. Deleting namespace isn't easier // as you will probably end up with namespace in a forever loop due to you deleting // the controllers which is responsible for finalizing them list, err := kubernetes.ListServicesByTypes(ctx, cc, v1.NamespaceAll, string(v1.ServiceTypeLoadBalancer)) if err != nil { return reconcile.Result{}, err } if len(list.Items) > 0 { logger.Debug("cluster still has resource left to cleanup") for _, x := range list.Items { if x.GetDeletionTimestamp() != nil { continue } if err := cc.Delete(ctx, &x); err != nil { return reconcile.Result{}, err } } return reconcile.Result{RequeueAfter: 30 * time.Second}, nil } return reconcile.Result{}, nil }() if err != nil { logger.WithError(err).Error("trying to ensure the cluster is cleaned out") object.Status.Components.SetCondition(corev1.Component{ Name: ComponentKubernetesCleanup, Message: "Failed trying to cleanup in cluster resources", Detail: err.Error(), Status: corev1.FailureStatus, }) return reconcile.Result{}, err } return result, nil } } // EnsureSecretDeletion is responsible for deletion the admin token func (a k8sCtrl) EnsureSecretDeletion(object *clustersv1.Kubernetes) controllers.EnsureFunc { return func(ctx context.Context) (reconcile.Result, error) { // @step: we should delete the secert from api if err := kubernetes.DeleteIfExists(ctx, a.mgr.GetClient(), &configv1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: object.Name, Namespace: object.Namespace, }, }); err != nil { log.WithError(err).Error("trying to delete the secret from api") return reconcile.Result{}, err } return reconcile.Result{}, nil } } // EnsureFinalizerRemoved removes the finalizer now func (a k8sCtrl) EnsureFinalizerRemoved(object *clustersv1.Kubernetes) controllers.EnsureFunc { return func(ctx context.Context) (reconcile.Result, error) { // @cool we can remove the finalizer now finalizer := kubernetes.NewFinalizer(a.mgr.GetClient(), finalizerName) if finalizer.IsDeletionCandidate(object) { if err := finalizer.Remove(object); err != nil { return reconcile.Result{}, err } } return reconcile.Result{}, nil } }
//Brief Intro /* dp vector stores the string which is formed and the queue stores the remainder we are bascially adding a 0/1 at the end of each number and finding the remainder and if we get it as 0 we return the ans and if not we keep on finding the answer by adding a 0 or a 1 at the end adn finding its remainder If when we add a 0 we get (curr_rem*10+0)%n and when we add a 1 we get (curr_rem*10+1)%n nd if this remainder is not yet been added in the tree/ not been visisted, add it and enter the number in dp //For each number we can get at max n coz we have n remainders for each number. */ string bfs(int n) { if(n==1) return "1"; vector<string>dp(n); dp[1]="1"; queue<int>q; q.push(1); while(!q.empty()) { int curr_rem=q.front(); q.pop(); if(curr_rem==0) return dp[curr_rem]; for(int digit: {0,1}) { int new_rem=(curr_rem*10+digit) %n; if(dp[new_rem].empty()) { q.push(new_rem); dp[new_rem]=dp[curr_rem]+char('0'+digit); } } } return ""; }
<reponame>tirette/cli-core<gh_stars>0 import parseArgv from 'minimist'; import fs from 'fs'; /* * Parses the arguments passed down to the CLI and stores them. */ const command = process.argv[1].split('/').pop(); const args = parseArgv(process.argv.splice(2)); const { _: positionals, ...flags } = args; const storeArgs = (path: string): void => { const data = JSON.stringify({ positionals, flags }); fs.writeFileSync(path, data); } const readArgs = (path: string) => { const fileContent = fs.readFileSync(path); return JSON.parse(fileContent.toString()); } export { command, positionals, flags, storeArgs, readArgs }
import java.util.*; public class E { public static void main (String [] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); String s = sc.next(); int [][] dp = new int[26][N+1]; for (int a=0; a<26; a++) { char c = (char)(97+a); int [] psum = new int[N+1]; for (int i=1; i<=s.length(); i++) { if (s.charAt(i-1)==c) psum[i]++; psum[i]+=psum[i-1]; } for (int i=1; i<=N; i++) for (int j=i; j<=N; j++) { int numc = psum[j]-psum[i-1]; dp[a][j-i+1-numc]=Math.max(dp[a][j-i+1-numc], j-i+1); } for (int i=1; i<=N; i++) dp[a][i]=Math.max(dp[a][i], dp[a][i-1]); } //System.out.println(Arrays.toString(dp[0])); int Q = sc.nextInt(); for (int k=0; k<Q; k++) { int i = sc.nextInt(); System.out.println(dp[sc.next().charAt(0)-97][i]); } } }
/** * The condition is used for registering the script. * If the condition matches, the script will be executed normally. */ public abstract class Condition { @SerializedName("name") private String name; @SerializedName("type") private String type; @SerializedName("body") private Object body; protected Condition(String name, String type, Object body) { this.name = name; this.type = type; this.body = body; } protected void setBody(Object value) { body = value; } protected Object getBody() { return body; } }
This article is also available in: Shqip Bos/Hrv/Srp “What makes the Lord the most joyful is when his slave, without protection, enters among the non-believers and shoots until he gets killed … Kill and get killed – this is how those who we should be proud of end,” says Imam Bilal Bosnic in one of his many YouTube videos, posted via various channels. Just this one has had 21,000 views. A court in Sarajevo, Bosnia, jailed him last June for seven years for instigating and recruiting foreign fighters to go to war in the Middle East. Before his arrest, Bosnic was considered a key recruiter and preacher of violent extremism in the Balkans. But Bosnic’s hate speech is not isolated case. Videos put out by and about extremist groups in the Balkans attract millions of viewers. The “Sword of the Merciful” [“Shpata e Meshiruesit” in Albanian], for instance, among other jihadist marketing acts, features a video message from Al-Qaeda leader Ayman al-Zawahiri, entitled “15 years on from the blessed attacks of September 11” with Albanian subtitles. Radical extremism has found its place not just on YouTube, but also on Facebook and Twitter. The Facebook page “White Minaret”, which counts 3,424 likes, does not shrink from expressing sympathy for supporters of terrorist organisations, and openly engages in Islamist propaganda, with direct references to Al-Qaeda and related organisations and clerics. Numerous Facebook pages all across the Western Balkans that BIRN has seen also engage in propaganda for Islamist extremists groups like Al-Qaeda, Jabhat Fateh al-Sham, formerly known as the al-Nusra Front, the Taleban and other affiliates. Since 2014, around 200 people have been put on trial in Western Balkan countries, suspected of either being part of violent terrorist groups fighting in Middle East or of recruiting groups to go and fight there. While the focus has been on putting them in jail, the authorities have left the worldwide web, which is where modern jihadists are also very active, unmonitored. Even those in prison often remain active online, as is the case with Bosnic, but also with the jailed Macedonian imam Rexhep Memishi, whose Facebook page is regularly updated. BIRN research shows that while most Western Balkan countries now have counter-terrorism strategies in place, they have struggled to counter violent extremism online. Effective control of cyberspace is still too complicated for already poorly equipped police and prosecutors in the Balkans. Experts also warn that little effort is being invested in the prevention of Islamist radicalism, while for many, the line between freedom of speech and online speech that incites violence, hatred or is otherwise harmful to individuals and communities remains unclear. In some countries, websites containing violent content have been registered abroad. This also limits the scope of work of the authorities. Extremism flourishes online: While most of the world was shocked by news of the horrific November 2015 terrorist attacks in Paris, France, not everyone was. One Islamist website in Bosnian, Vjesti Ummeta, in a post called the mass killings “joyful news for all true Muslims”. This website has been a headache for the Bosnian authorities for the last two years as it continues to share and spread ISIS propaganda videos, magazines and praise mass killings carried out in the name of the Islamic Caliphate. The authorities have pulled it down on several occasions, but the website simply reappears under different names. The website is not an isolated case. Most similar websites have servers outside Bosnia. They are often registered in Saudi Arabia, which Bosnia’s authorities say hampers their power to shut them down. Sarajevo-based analyst and theological expert Muhamed Jusic says the authorities are struggling to find a common ground with web providers who have certain criteria about freedom of speech. “The other issue is that these profiles and websites are easily registered; it is like a game of cat and mouse – you close one, they open two,” Jusic told BIRN. Besides Bosniaks, Albanians are the largest group of foreign fighters traveling to the Middle East from the Balkans. Albanians are spread over three Balkan countries, Albania, Kosovo and Macedonia, so it is often difficult to find out exactly where Albanian Islamist propaganda is coming from. Skender Perteshi, a researcher at the Kosovo Centre for Security Studies, said the digital and social media remain a key propaganda tool of the terrorists. “ISIS, the biggest terrorist organisation to date, has an overwhelming presence on social media, including Facebook, Twitter and other apps,” Perteshi noted. He said social media have been instrumental in the organisation’s success in recruiting around 25,000 foreign fighters from all over the world; countering their violent propaganda on such channels is tough. As with the case of Bosnian counterparts, the “official” ISIS webpage in Albanian, hilafeti.wordpress.com, routinely vanishes and re-emerges after being offline for several months. The website has been going on and off repeatedly in the last couple of years. In December, it reappeared after being shut down for less than 48 hours. Filip Stojkovski, security research fellow at the Analytica think tank in Skopje, Macedonia, one of the authors of research entitled “Assessment of Macedonia’s efforts in countering violent extremism, view from civil society”, carried out by Analytica and published last year, says most people who join radical Islamist movements are youngsters who continue to be recruited online. “There are still many active pages online, profiles on social networks like Facebook, that are spreading these ideas,” he said. One such profile belongs to Imam Rexhep Memishi, who is currently serving a jail sentence for terrorism in Macedonia. He was found guilty in 2016 after being busted in 2015 in an operation codenamed “Cell”, and was sentenced to seven years last year for recruiting fighters for the Middle Eastern war fronts. “Although he is in jail, his profile is still very active which probably means that someone else is maintaining it, updating posts with his speeches and other content,” Stojkovski said. Macedonian police arrested several suspected jihadi fighters in August 2015. Photo: moi.mk Other private profiles, calling for an Islamic Caliphate in Albanian, depicting convicted terrorists as freedom fighters and calling for religious war, are by no means rare. One Facebook group called “Eja ne Islam” [“Join Islam”] that has more than 700 supporters calls on its members to join ISIS as “a rebellion against the injustice done to Muslims’’. Other Facebook groups curse American soldiers, wishing them to be beheaded in Syria. “Mektebi Hasanbeg”, a YouTube channel like this, contains more than 270 videos, some of which glorify terrorism and “call for Allah to help ISIS raise the flag of Jihad”. Terrorist leaders like Osama bin Laden are called scholars on such sites, while the flags of US and Israel are shown in flames. Fabian Zhilla, an Albanian fellow at Harvard University in the US, says while ISIS in Albania seems to be a fading force, ISIS online propaganda in Albanian continues. “ISIS uses and plays with tough images of children and women murdered or bombed in Syria. It tries to portray that war as a religious war, non-believers vs believers. In general, the online content aims to attract and target an Albanian-speaking audience by mixing religious messages with ISIS ideological propaganda,” Zhilla explained to BIRN. “It is often very difficult to distinguish between messages that call on people to strengthen their faith and messages that call on them to join the cause of ISIS,” he warned. Strategies are in place but are not enough: Kosovo police officer at the one of the trials for terrorism in Pristina. Photo: BETA|AP Visar Kryeziu The differences between propaganda, calls for terrorist acts and recruitment are also hard for the police and prosecution services to distinguish. All Western Balkan countries have counter-terrorism strategies in place, most of them adopted in the last couple of years, to counter the flow of fighters from the Balkans to the Middle East. All these countries have also now criminalised recruitment of fighters for participation in foreign conflicts. Bosnia’s Security Ministry told BIRN that Bosnia’s counter-terrorism strategy envisages combatting the abuse of the internet for the purpose of terrorist activities, as well as spreading hate speech and discrimination. As one of its plans, the ministry says that, together with the Regulatory Agency for Communication of Bosnia and Herzegovina, it aims to create control mechanisms to monitor problematic websites and punish those that do not respect the rules. One measure involves creating a black list of webpages calling for hate speech, radicalism and violence. However, the Regulatory Agency told BIRN that it lacks the authority to decide whether or not content online is extreme and unacceptable, unless it is radio or TV programs. And so far, it has not actually been included in drawing up a so-called blacklist of websites, it added. Young People Key Target of Online Propaganda Macedonia, like all other countries in the region, mainly relies on repressive measures to deal with violent extremism, neglecting preventive action that could be used to deter youngsters from adopting radical ideas and joining extremist organizations, Filip Stojkovski, from the Analytica think tank in Skopje, says. “Our research showed that Macedonia lacks activities for early prevention of radicalization. It is worrying that there are no educational activities in schools so that pupils can find out how to recognize radical content on the internet and protect themselves. Much more effort should be put to this. “The Labour and Social Policy Ministry, the Education Ministry and the Youth and Sports Agency should all be involved in such activities but that unfortunately is not the case,” he adds. Aida Corovic, former Serbian parliamentarian and activist from the mainly Muslim city of Novi Pazar, says that although Serbia has the fewest foreign fighters in the region, youngsters are still vulnerable to propaganda. “Online violent extremism exists definitely in Serbia, and in my opinion this is the easiest way to get attention of young people … The possibilities for its misuse are infinite,” she said. “Our society is very poor, and this is a huge problem for youth as they are unable to plan their future, which produces frustration and apathy, so they’re a perfect target for different types of radicalization, both religious but also national,” she added. “I don’t need to mention bad schooling, and very bad messages that are being sent by the media and politicians too as another great contributors to this problem” Albania is also tackling extremism, partly by the formation of an Counter-Terrorist Directorate within the state police. Alongside work in the field with investigating individuals suspected of violent extremism and terrorism, it is also working on identifying threats spread online. “In 2016 we have grown the human capacities … for the monitoring and investigation of online propaganda through the Counter-Terrorist Directorate and the General Directory for the Organized and Serious Crimes in collaboration with the other Albanian and foreign law-enforcement agencies,” an official from the directorate told BIRN. This official listed cases of online violent extremism that they have investigated over the last four years. “Investigations are being conducted into two individuals, one from Albania and the other from Kosovo, both based in Syria, who appeared on social networks in a video threatening citizens of Albania, Kosovo, and region with terrorist acts,” the official said, referring so a video of June 2015 I which two Albanian supporters of ISIS threatened their compatriots. “An individual from Pogradec is under investigation for threats on social networks against a journalist,” the same official said, also referring to a case from 2015. “One individual from Kukes was arrested and another from Berat is under investigation for calling on social networks for acts of terrorism. Another investigation is underway after some radicalized individuals threatened an official,” he continued. Serbia also has national strategies for counter-terrorism that refer to online terrorism as an issue that needs tackling. However, so far, Serbia has not actually issued any indictments against violent online extremists. Kosovo police also have a dedicated unit on cybercrime, but did not reply to requests from BIRN explaining the Kosovo police’s efforts to tackle online extremism. Enri Hide, researcher on violent extremism and religious radicalization and a lecturer at the European University of Tirana, Albania, said strategies and specialized agencies are not enoug and a tailor-made approach is needed. Online propaganda is difficult to eliminate,” he said. “I’m not aware of the presence of any strategy against online radicalization. We have a national strategy against violent radicalism, but not one that targets online extremism,” he told BIRN. His colleague Zhilla agrees. “We cannot rely on the same cyber-crime legislationthat was in force in the pre-ISIS era,” he said, warning that the threat of radicalisation would likely increase in the near future. State needs partnership with citizens: 360,000 Twitter accounts are recently closed in relation to violent extremism. Photo: Flickr.ijclark Around 60 per cent of population is on Facebook in almost all Balkan countries, while in Kosovo this figure is as high as 80 per cent. Valon Canhasi, a social media expert in Pristina, told BIRN that violent extremists are making increasing use of social media to promote their ideology, leaving Balkan authorities struggling to keep pace. “We have a billion daily users of Facebook, which translates into one account for every seventh inhabitants of the earth, so this platform will obviously be used by organisations that promote violence and terror,” Canhasi said. He also said that while violent extremist propaganda was present on social media, including 360,000 Twitter accounts recently closed in relation to violent extremism, “rule-of-law [institutions] have no adequate presence on social media.” His Bosnian colleague, the analyst Mirnes Kovac, agrees that while the biggest concentration of radical messages are to be found on social media, most citizens are not aware of the scale of the problem. “It is very important to know how to recognise problematic preachers of hate but not violate freedom of speech. This is a global problem,” Kovac said. Muhamed Jusic, from Bosnia, suggests forming a new partnership of institutions and ordinary citizens to counter the threat. “Our security agencies must develop mechanisms that are available to citizens who can then report problematic content and create producers that would start removing this content in line with international standards,” Jusic said. According to Jusic, states should also assist in developing critical thinking with citizens who consume content on social media. He adds that citizens, independently from the state, should be able to report content as innaporopriate on Facebook or Youtube. Partnership between governments and civil society in combating online extremism remains a novelty in the Balkans. However, in Macedonia, the NGO Analytica and the Interior Ministry are pioneering this approach, working on concrete measures to jointly curb the spread of radical propaganda online. “We are now working on a project that tries to pinpoint in more detail how online recruitment functions and establish effective preventive mechanisms,” Stojkovski from Analytica says. According to him, the plan is to strengthen mechanisms that warn people about radical sites and profiles through an online tool called the “red button” through which internet users could easily report such sites to the police. The police would then quickly react and, if need be, asked internet companies to close those profiles or sites down.
/** * Transforms the native RF1 files used in SNOMED into the internal * representation. Because of the limitations of the RF1 format, this importer * does not handle versions. * * @author Alejandro Metke * */ public class RF1Importer extends BaseImporter { protected final InputStream conceptsFile; protected final InputStream relationshipsFile; protected final String version; /** * Contains the meta-data necessary to transform the distribution form of * SNOMED into a DL model. */ protected SnomedMetadata metadata = SnomedMetadata.INSTANCE; protected final List<String> problems = new ArrayList<String>(); protected final Map<String, String> primitive = new HashMap<String, String>(); protected final Map<String, Set<String>> parents = new HashMap<String, Set<String>>(); protected final Map<String, Set<String>> children = new HashMap<String, Set<String>>(); protected final Map<String, List<String[]>> rels = new HashMap<String, List<String[]>>(); protected final Map<String, Map<String, String>> roles = new HashMap<String, Map<String, String>>(); /** * Creates a new {@link RF1Importer}. * * @param conceptsFile * @param descriptionsFile * @param relationshipsFile * @param version The version of this ontology. */ public RF1Importer(InputStream conceptsFile, InputStream relationshipsFile, String version) { this.conceptsFile = conceptsFile; this.relationshipsFile = relationshipsFile; this.version = version; } public Iterator<Ontology> getOntologyVersions( IProgressMonitor monitor) { return new OntologyInterator(monitor); } class OntologyInterator implements Iterator<Ontology> { private boolean accessed = false; private IProgressMonitor monitor; public OntologyInterator(IProgressMonitor monitor) { this.monitor = monitor; } public boolean hasNext() { return !accessed; } public Ontology next() { long start = System.currentTimeMillis(); monitor.taskStarted("Loading axioms"); // Extract the version rows VersionRows vr = extractVersionRows(); Collection<Axiom> axioms = new ArrayList<Axiom>(); // Process concept rows for (ConceptRow cr : vr.getConceptRows()) { if (!"CONCEPTID".equals(cr.getConceptId()) && "0".equals(cr.getConceptStatus())) { primitive.put(cr.getConceptId(), cr.getIsPrimitive()); } } // Process relationship rows for (RelationshipRow rr : vr.getRelationshipRows()) { // only process active concepts and defining relationships if (!"RELATIONSHIPID".equals(rr.getRelationshipId()) && "0".equals(rr.getCharacteristicType())) { if (metadata.getIsAId().equals(rr.getRelationshipType())) { populateParent(rr.getConceptId1(), rr.getConceptId2()); populateChildren(rr.getConceptId2(), rr.getConceptId1()); } else { // Populate relationships populateRels(rr.getConceptId1(), rr.getRelationshipType(), rr.getConceptId2(), rr.getRelationshipGroup()); } } } Set<String> conceptModelChildren = children.get( metadata.getConceptModelAttId()); if (conceptModelChildren != null) populateRoles(conceptModelChildren, ""); // Add the role axioms for (String r1 : roles.keySet()) { String parentRole = roles.get(r1).get("parentrole"); if (!"".equals(parentRole)) { axioms.add(new RoleInclusion(new NamedRole(r1), new NamedRole(parentRole))); } String rightId = roles.get(r1).get("rightID"); if (!"".equals(rightId)) { axioms.add(new RoleInclusion(new Role[] { new NamedRole(r1), new NamedRole(rightId) }, new NamedRole(r1))); } } // Add concept axioms for (String c1 : primitive.keySet()) { if (roles.get(c1) != null) continue; Set<String> prs = parents.get(c1); int numParents = (prs != null) ? prs.size() : 0; List<String[]> relsVal = rels.get(c1); int numRels = 0; if (relsVal != null) numRels = 1; int numElems = numParents + numRels; if (numElems == 0) { // do nothing } else if (numElems == 1 && (prs != null && !prs.isEmpty())) { axioms.add(new ConceptInclusion(new NamedConcept(c1), new NamedConcept(prs.iterator().next()))); } else { List<Concept> conjs = new ArrayList<Concept>(); if(prs != null) { for (String pr : prs) { conjs.add(new NamedConcept(pr)); } } if (relsVal != null) { for (Set<RoleValuePair> rvs : groupRoles(relsVal)) { if (rvs.size() > 1) { List<Concept> innerConjs = new ArrayList<Concept>(); for (RoleValuePair rv : rvs) { NamedRole role = new NamedRole(rv.role); Concept filler = new NamedConcept(rv.value); Existential exis = new Existential(role, filler); innerConjs.add(exis); } // Wrap with a role group conjs.add(new Existential(new NamedRole("RoleGroup"), new Conjunction(innerConjs))); } else { RoleValuePair first = rvs.iterator().next(); NamedRole role = new NamedRole(first.role); Concept filler = new NamedConcept(first.value); Existential exis = new Existential(role, filler); if (metadata.getNeverGroupedIds().contains(first.role)) { // Does not need a role group conjs.add(exis); } else { // Needs a role group conjs.add(new Existential(new NamedRole("RoleGroup"), exis)); } } } } axioms.add(new ConceptInclusion(new NamedConcept(c1), new Conjunction(conjs))); if (primitive.get(c1).equals("0")) { axioms.add(new ConceptInclusion(new Conjunction(conjs), new NamedConcept(c1))); } } } Statistics.INSTANCE.setTime("rf1 loading", System.currentTimeMillis() - start); accessed = true; return new Ontology("snomed", vr.getVersionName(), axioms, null); } public void remove() { throw new UnsupportedOperationException(); } } protected void populateParent(String src, String tgt) { Set<String> prs = parents.get(src); if (prs == null) { prs = new TreeSet<String>(); parents.put(src, prs); } prs.add(tgt); } protected void populateChildren(String src, String tgt) { Set<String> prs = children.get(src); if (prs == null) { prs = new TreeSet<String>(); children.put(src, prs); } prs.add(tgt); } protected void populateRels(String src, String role, String tgt, String group) { List<String[]> val = rels.get(src); if (val == null) { val = new ArrayList<String[]>(); rels.put(src, val); } val.add(new String[] { role, tgt, group }); } protected void populateRoles(Set<String> roles, String parentSCTID) { for (String role : roles) { Set<String> cs = children.get(role); if (cs != null) { populateRoles(cs, role); } String ri = metadata.getRightIdentityIds().get(role); if (ri != null) { populateRoleDef(role, ri, parentSCTID); } else { populateRoleDef(role, "", parentSCTID); } } } protected void populateRoleDef(String code, String rightId, String parentRole) { Map<String, String> vals = roles.get(code); if (vals == null) { vals = new HashMap<String, String>(); roles.put(code, vals); } vals.put("rightID", rightId); vals.put("parentrole", parentRole); } protected Set<Set<RoleValuePair>> groupRoles(List<String[]> groups) { Map<String, Set<RoleValuePair>> roleGroups = new HashMap<String, Set<RoleValuePair>>(); for (String[] group : groups) { String roleGroup = group[2]; Set<RoleValuePair> lrvp = roleGroups.get(roleGroup); if (lrvp == null) { lrvp = new HashSet<RoleValuePair>(); roleGroups.put(group[2], lrvp); } lrvp.add(new RoleValuePair(group[0], group[1])); } Set<Set<RoleValuePair>> res = new HashSet<Set<RoleValuePair>>(); for (String roleGroup : roleGroups.keySet()) { Set<RoleValuePair> val = roleGroups.get(roleGroup); // 0 indicates not grouped if ("0".equals(roleGroup)) { for (RoleValuePair rvp : val) { Set<RoleValuePair> sin = new HashSet<RoleValuePair>(); sin.add(rvp); res.add(sin); } } else { Set<RoleValuePair> item = new HashSet<RoleValuePair>(); for (RoleValuePair trvp : val) { item.add(trvp); } res.add(item); } } return res; } public void clear() { problems.clear(); primitive.clear(); parents.clear(); children.clear(); rels.clear(); roles.clear(); } public List<String> getProblems() { return problems; } protected class RoleValuePair { String role; String value; RoleValuePair(String role, String value) { this.role = role; this.value = value; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + ((role == null) ? 0 : role.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RoleValuePair other = (RoleValuePair) obj; if (!getOuterType().equals(other.getOuterType())) return false; if (role == null) { if (other.role != null) return false; } else if (!role.equals(other.role)) return false; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; } private RF1Importer getOuterType() { return RF1Importer.this; } } public boolean usesConcreteDomains() { return false; } /** * Processes the raw RF1 files and generates a {@link VersionRows}. */ public VersionRows extractVersionRows() { // Read all the concepts from the raw data List<ConceptRow> crs = new ArrayList<ConceptRow>(); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(conceptsFile)); String line = br.readLine(); // Skip first line while (null != (line = br.readLine())) { line = new String(line.getBytes(), "UTF8"); if (line.trim().length() < 1) { continue; } int idx1 = line.indexOf('\t'); int idx2 = line.indexOf('\t', idx1 + 1); int idx3 = line.indexOf('\t', idx2 + 1); int idx4 = line.indexOf('\t', idx3 + 1); int idx5 = line.indexOf('\t', idx4 + 1); // 0..idx1 == conceptId // idx1+1..idx2 == conceptStatus // idx2+1..idx3 == fullySpecifiedName // idx3+1..idx4 == ctv3Id // idx4+1..idx5 == snomedId // idx5+1..end == isPrimitive if (idx1 < 0 || idx2 < 0 || idx3 < 0 || idx4 < 0 || idx5 < 0) { br.close(); throw new RuntimeException( "Concepts: Mis-formatted " + "line, expected at least 6 tab-separated fields, " + "got: " + line); } final String conceptId = line.substring(0, idx1); final String conceptStatus = line.substring(idx1 + 1, idx2); final String fullySpecifiedName = line.substring(idx2 + 1, idx3); final String ctv3Id = line.substring(idx3 + 1, idx4); final String snomedId = line.substring(idx4 + 1, idx5); final String isPrimitive = line.substring(idx5 + 1); crs.add(new ConceptRow(conceptId, conceptStatus, fullySpecifiedName, ctv3Id, snomedId, isPrimitive)); } } catch (Exception e) { throw new RuntimeException(e); } finally { if(br != null) { try { br.close(); } catch(Exception e) {} } } // Read all the relationships from the raw data List<RelationshipRow> rrs = new ArrayList<RelationshipRow>(); try { br = new BufferedReader( new InputStreamReader(relationshipsFile)); String line = br.readLine(); // Skip first line while (null != (line = br.readLine())) { if (line.trim().length() < 1) { continue; } int idx1 = line.indexOf('\t'); int idx2 = line.indexOf('\t', idx1 + 1); int idx3 = line.indexOf('\t', idx2 + 1); int idx4 = line.indexOf('\t', idx3 + 1); int idx5 = line.indexOf('\t', idx4 + 1); int idx6 = line.indexOf('\t', idx5 + 1); // 0..idx1 == relationshipId // idx1+1..idx2 == conceptId1 // idx2+1..idx3 == relationshipType // idx3+1..idx4 == conceptId2 // idx4+1..idx5 == characteristicType // idx5+1..idx6 == refinability // idx6+1..end == relationshipGroup if (idx1 < 0 || idx2 < 0 || idx3 < 0 || idx4 < 0 || idx5 < 0 || idx6 < 0) { br.close(); throw new RuntimeException("Concepts: Mis-formatted " + "line, expected 7 tab-separated fields, " + "got: " + line); } final String relationshipId = line.substring(0, idx1); final String conceptId1 = line.substring(idx1 + 1, idx2); final String relationshipType = line.substring(idx2 + 1, idx3); final String conceptId2 = line.substring(idx3 + 1, idx4); final String characteristicType = line.substring(idx4 + 1, idx5); final String refinability = line.substring(idx5 + 1, idx6); final String relationshipGroup = line.substring(idx6 + 1); rrs.add(new RelationshipRow(relationshipId, conceptId1, relationshipType, conceptId2, characteristicType, refinability, relationshipGroup)); } } catch (Exception e) { throw new RuntimeException(e); } finally { if(br != null) { try { br.close(); } catch(Exception e) {} } } // In this case we know we are dealing with a single version so we need // to generate a single version row VersionRows vr = new VersionRows(version); vr.getConceptRows().addAll(crs); vr.getRelationshipRows().addAll(rrs); return vr; } public SnomedMetadata getMetadata() { return metadata; } }
/* a and b are digits long, out is 2 * digits */ inline static void multiply(int *out, int *a, int *b, const int digits) { int temp[SIZE]; int mid1[SIZE]; int mid2[SIZE]; int i, new_digits; if (new_digits = digits >> 1) { multiply(out, a, b, new_digits); multiply(&(out[digits]), &(a[new_digits]), &(b[new_digits]), new_digits); add(mid1, a, &(a[new_digits]), new_digits); add(mid2, b, &(b[new_digits]), new_digits); multiply(temp, mid1, mid2, new_digits); subtract(temp, temp, out, digits); subtract(temp, temp, &(out[digits]), digits); add(&(out[new_digits]), &(out[new_digits]), temp, digits); return; } i = (*a) * (*b); *out = i & 0xFF; *(out + 1) = i >> 8; }
// Create fake memref operands from the operands shapes. SmallVector<MemrefDesc> GetFakeMemrefs(SmallVector<SymbolicShape> shapes) { SmallVector<MemrefDesc> memrefs; memrefs.reserve(shapes.size()); for (auto& shape : shapes) { MemrefDesc desc; desc.sizes.insert(desc.sizes.begin(), shape.begin(), shape.end()); memrefs.push_back(std::move(desc)); } return memrefs; }
use std::os::raw::c_float; use skia_safe::Color; use crate::common::context::Context; impl Context { pub fn set_shadow_blur(&mut self, blur: c_float) { // TODO ? self.state.shadow_blur = blur; } pub fn shadow_blur(&self) -> c_float { self.state.shadow_blur } pub fn set_shadow_offset_x(&mut self, x: c_float) { self.state.shadow_offset.x = x; } pub fn shadow_offset_x(&self) -> c_float { self.state.shadow_offset.x } pub fn set_shadow_offset_y(&mut self, y: c_float) { self.state.shadow_offset.y = y; } pub fn shadow_offset_y(&self) -> c_float { self.state.shadow_offset.y } pub fn set_shadow_color(&mut self, color: Color) { self.state.shadow_color = color; } pub fn shadow_color(&self) -> Color { self.state.shadow_color } }
package com.jetbrains.python.debugger.pydev; import com.jetbrains.python.debugger.PyDebuggerException; import org.jetbrains.annotations.NotNull; public class VersionCommand extends AbstractCommand { private final String myVersion; private final String myPycharmOS; private final long myResponseTimeout; private String myRemoteVersion = null; public VersionCommand(final RemoteDebugger debugger, final String version, String pycharmOS, long responseTimeout) { super(debugger, VERSION); myVersion = version; myPycharmOS = pycharmOS; myResponseTimeout = responseTimeout; } @Override protected void buildPayload(Payload payload) { payload.add(myVersion).add(myPycharmOS); } @Override public boolean isResponseExpected() { return true; } @Override protected long getResponseTimeout() { return myResponseTimeout; } @Override protected void processResponse(@NotNull final ProtocolFrame response) throws PyDebuggerException { super.processResponse(response); myRemoteVersion = response.getPayload(); } public String getRemoteVersion() { return myRemoteVersion; } }
/** Information about amount of glyphs that were rendered with given font. */ public class PlatformFontUsage { private String familyName; private Boolean isCustomFont; private Double glyphCount; /** Font's family name reported by platform. */ public String getFamilyName() { return familyName; } /** Font's family name reported by platform. */ public void setFamilyName(String familyName) { this.familyName = familyName; } /** Indicates if the font was downloaded or resolved locally. */ public Boolean getIsCustomFont() { return isCustomFont; } /** Indicates if the font was downloaded or resolved locally. */ public void setIsCustomFont(Boolean isCustomFont) { this.isCustomFont = isCustomFont; } /** Amount of glyphs that were rendered with this font. */ public Double getGlyphCount() { return glyphCount; } /** Amount of glyphs that were rendered with this font. */ public void setGlyphCount(Double glyphCount) { this.glyphCount = glyphCount; } }
import React from 'react'; import { Nav, Col, Container, Row } from 'react-bootstrap'; const FooterPage = () => { return ( <div> <Col xs={0} lg={1} xl={1} /> <Col xs={12} sm={12} lg={10} xl={10}> <div className='fixed-bottom'> <div className='panel-primary' style={{ paddingRight: '10pt' }} > Summertime Development LLC </div> </div> </Col> <Col xs={0} lg={1} xl={1} /> </div> ); }; export default FooterPage;
/* ** a modified version of the strcat function which starts copying the ** content of a string at a certain point in the string in a completely ** new string. the source string is freed and the destination string is ** ended with \0 and returned. */ char *ft_strcat_alpha(char *dest, char *src, int len) { int i; i = 0; while (src[len] != '\0') dest[i++] = src[len++]; dest[i] = '\0'; free(src); return (dest); }
#include "thread_pool.h" thread_pool::task_queue::task_queue() : head(nullptr), tail(nullptr), n_tasks(0) { // TODO: Error checking pthread_cond_init(&queue_available, NULL); pthread_mutex_init(&queue_rwlock, NULL); pthread_cond_init(&queue_empty, NULL); }; thread_pool::task* thread_pool::task_queue::next() { if (n_tasks == 0) return nullptr; task* ret = head->task; task_queue_node* next = head->next; delete head; n_tasks--; head = next; return ret; } void thread_pool::task_queue::insert(task* task) { task_queue_node *new_node = new task_queue_node(task); // TODO: Error checking pthread_mutex_lock(&queue_rwlock); // Insert into queue if (n_tasks == 0) { head = new_node; tail = new_node; } else { tail->next = new_node; tail = new_node; } n_tasks++; // Signal any thread waiting to read from the queue. pthread_cond_signal(&queue_available); // Unlock the lock. pthread_mutex_unlock(&queue_rwlock); } void thread_pool::task_queue::lock() { pthread_mutex_lock(&queue_rwlock); } void thread_pool::task_queue::unlock() { pthread_mutex_unlock(&queue_rwlock); } void thread_pool::task_queue::wait() { pthread_cond_wait(&queue_available, &queue_rwlock); } void thread_pool::task_queue::broadcast() { pthread_cond_broadcast(&queue_available); } thread_pool::task_queue::~task_queue(){ pthread_mutex_destroy(&queue_rwlock); pthread_cond_destroy(&queue_available); pthread_cond_destroy(&queue_empty); while (head != nullptr) { task_queue_node* next = head->next; delete head; head = next; } } thread_pool::thread_pool(int n_threads) : running(1), n_threads(n_threads), active(0) { threads = new pthread_t[n_threads]; // TODO: Error checking // Initialize threads for (int i = 0; i < n_threads; ++i) pthread_create(threads + i, NULL, thread_run, this); } void thread_pool::add_task(task* task) { task_queue.insert(task); } void* thread_pool::thread_run(void *t_pool) { thread_pool* pool = (thread_pool*) t_pool; for (;;) { // Acquire lock since the get function requires it pool->task_queue.lock(); while (pool->task_queue.n_tasks == 0 && pool->running == 1) pool->task_queue.wait(); if (pool->running == 0 && pool->task_queue.n_tasks == 0) break; task* task = pool->task_queue.next(); pool->active++; pool->task_queue.unlock(); task->run(); delete task; pool->task_queue.lock(); pool->active--; if (pool->active == 0 && pool->task_queue.n_tasks == 0) pool->task_queue.broadcast(); pool->task_queue.unlock(); } pool->task_queue.unlock(); pthread_exit(NULL); return NULL; } void thread_pool::task_queue::broadcast_queue_empty() { pthread_cond_broadcast(&queue_empty); } void thread_pool::wait_all() { task_queue.lock(); while (task_queue.n_tasks != 0 || active != 0) task_queue.wait(); task_queue.unlock(); } thread_pool::~thread_pool() { task_queue.lock(); running = 0; task_queue.broadcast(); task_queue.unlock(); for (int i = 0; i < n_threads; ++i) pthread_join(threads[i], NULL); delete[] threads; }
use std::io; use std::sync::Arc; #[derive(Debug, Clone)] pub enum Event { ChildBorn(u32), // ChildDied(u32, i32), Signal(i32), TerminationTimeout, IOError(Arc<io::Error>), }
Screen Zombies, Alien Settlers, and Colonial Legacies ABSTRACT You Are On Indian Land, a Challenge for Change documentary shot during a border-crossing blockade on Akwesasne territory (near Cornwall, Ontario) in 1969, helped interrupt the colonial legacy of Canadian cinema. Since then, activism in defense of Wet’suwet’en struggles to protect unceded territory, including remarkable uses of video and social media, carry on the transformative spark of this and other Indigenous films. Until recently, Indigenous filmmaking in Canada has mostly been relegated to informational and documentary programming because this is the genre sanctioned by colonial institutions. The commercial success of Atanarjuat: The Fast Runner (2001), disrupted this gatekeeping, and the release of Mi’kmaq filmmaker Jeff Barnaby’s Rhymes for Young Ghouls (2013) and Blood Quantum (2019) completely shattered the imposed barrier. Barnaby’s films are about the crimes of colonialism inflected through the zombie-horror and revenge-fantasy genres. This article weaves together these formative moments of Canadian documentary and fiction filmmaking with respect to issues of justice, land claims, and visual sovereignty, raising the question of what it means to represent Indigenous social struggles in popular film genres and what they say about the concept of Canadian identity.
#include <bits/stdc++.h> using namespace std; const int maxn = 1001; int n, num[maxn]; const int mod = 1e9 + 7; typedef long long ll; ll modmult(ll a, ll b) { return (a * b) % mod; } ll modpow(ll a, int b) { ll result = 1; ll current = a; while (b) { if (b % 2 == 1) { result = modmult(result, current); } b /= 2; current = modmult(current, current); } return result; } ll choose(int n, int k) { ll result = 1; for (int i = 0; i < k; ++i) { result = modmult(result, n - i); result = modmult(result, modpow(i + 1, mod - 2)); } return result; } int main() { cin >> n; for (int i = 0; i < n; ++i) cin >> num[i]; ll answer = 1; int current = 0; for (int i = 0; i < n; ++i) { current += num[i] - 1; //cout << current << ' ' << num[i] - 1 << endl; answer = modmult(answer, choose(current, num[i] - 1)); //cout << answer << endl; ++current; } cout << answer << endl; return 0; }
<reponame>LuanPetruitis/minis_programas_python cadastro = {} total_gols = [] cadastro['nome do jogador'] = str(input('Qual é o nome do jogador? ')) tot = int(input(f'Quantas partidas o {cadastro["nome do jogador"]} jogou? ')) for c in range(0, tot): total_gols.append(int(input(f'Quantos gols o {cadastro["nome do jogador"]} fez na partida {c + 1}: '))) cadastro['gols'] = total_gols[:] cadastro['total'] = sum(total_gols) print('-='*30) print(cadastro) print('-='*30) for k, v in cadastro.items(): print(f'O campo {k} tem o valor de {v}') print('-='*30) print(f'O jogador {cadastro["nome do jogador"]} jogou {tot} partidas') for i, v in enumerate(cadastro["gols"]): print(f'Na {i + 1}º partida ele fez {v} gols')
#include <stdio.h> #include <stdlib.h> #include <string.h> struct node{ char name[20]; char secondName[20]; int age; int priority; struct node *next; }; struct node* head = NULL; struct node* tail = NULL; struct node* temp; char firstName[20], secondName[20]; int age, pri; char priority[10]; void selection(int chosen); struct node* createPerson(char name[], char secondName[], int age, int priority) { struct node* newPerson = (struct node*)malloc(sizeof(struct node)); strcpy(newPerson->name, name); strcpy(newPerson->secondName, secondName); newPerson->age = age; newPerson->priority = priority; newPerson->next = NULL; return newPerson; }; void enQueuePerson(char name[], char secondName[], int age, int priority) { struct node* person = createPerson(name, secondName, age, priority); if(head == NULL && tail == NULL) { head = person; tail = person; } else { if(person->priority <= head->priority) { temp = head; head = person; person->next = temp; return; } if(person->priority >= tail->priority) { tail->next = person; tail = person; } temp = head; while(temp->next != NULL) { if(person->priority < temp->next->priority) { struct node* newy; newy = temp->next; temp->next = person; person->next = newy; } temp = temp->next; } } } void deQueue() { temp = head; if(head == NULL) { printf("\n Kuyruk Bos Lutfen kisi Ekleyin"); return; } if(head == tail) { head = NULL; tail = NULL; return; } head = temp->next; free(temp); } struct node* whoNext() { if(head == NULL) { printf("\nKuyruk Bos..."); return 0; } return head; } void checkPri(int x) { if(x == 1) strcpy(priority, "High"); else if(x == 2) strcpy(priority, "Normal"); else strcpy(priority, "Low"); } void printQueue() { int i = 1; if(head == NULL) { return; } temp = head; while(temp->next != NULL) { checkPri(temp->priority); printf("\n%d. Pozisyon => %s %s %d oncelik ==> %s ", i, temp->name, temp->secondName, temp->age, priority); temp = temp->next; i++; } checkPri(temp->priority); printf("\n%d. Pozisyon => %s %s %d oncelik ==> %s ", i, temp->name, temp->secondName, temp->age, priority); } void menu() { int choise; while( 1 == 1 ) { printf("\n Algoritma Uzmani ... "); printf("\n 1- Kisi Ekle ... "); printf("\n 2- Kisi Cikar ... "); printf("\n 3- Siradaki Kim? "); printf("\n Seciminizi Yapin "); scanf("%d", &choise); selection(choise); } } void selection(int chosen) { switch(chosen) { case 1: printf("\n Kisinin ismi ... "); scanf("%s", &firstName[20]); printf("\n Kisinin soyadi ... "); scanf("%s", &secondName[20]); printf("\n Yasi ... "); scanf("%d", &age); printf("\n oncelik durumunu girin ... (1 yuksek oncelikli | 2 normal | 3 dusuk oncelikli) "); scanf("%d", &pri); enQueuePerson(firstName, secondName, age, pri); printQueue(); break; case 2: deQueue(); printQueue(); break; case 3: temp = whoNext(); printf("\n ****************** \n"); if(temp != NULL) { printf("%s %s %d", temp->name, temp->secondName, temp->age); } break; } } int main() { menu(); return 0; }
The AP poll isn’t all good news for Democrats, but at least it’s worse for Republicans. The survey was funded by the Black Youth Project at the University of Chicago. Just a quarter of young Americans have a favorable view of the Republican Party, and 6 in 10 have an unfavorable view. Majorities of young people across racial and ethnic lines hold negative views of the GOP. The Democratic Party performs better, but views aren't overwhelmingly positive. Young people are more likely to have a favorable than an unfavorable view of the Democratic Party by a 47 percent to 36 percent margin. But just 14 percent say they have a strongly favorable view of the Democrats. Views of the Democratic Party are most favorable among young people of color. Roughly 6 in 10 blacks, Asians and Latinos hold positive views of the party. Young whites are somewhat more likely to have unfavorable than favorable views, 47 percent to 39 percent. As for Trump, 8 in 10 young people think he is doing poorly in terms of the policies he's put forward and 7 in 10 have negative views of his presidential demeanor. The age separations in the Pew Research numbers show that it’s not just millennials and silents who are divided politically. The figures from Pew show that millennials and those from Generation X (ages 36-51) see themselves as liberal or moderately liberal and leaning toward Democrats. Baby boomers and silents skewed Republican and conservative. In 2016, as in recent years, Millennials and Gen Xers were the most Democratic generations. And both groups had relatively large — and growing — shares of liberal Democrats: 27% of Millennials and 21% of Gen Xers identified as liberal Democrats or Democratic-leaning independents. By contrast, Boomers and Silents were the most Republican groups — largely because of the higher shares of conservative Republicans in these generations. Nearly a third of Boomers (31%) and 36% of Silents described themselves as conservative Republicans or Republican leaners, which also is higher than in the past. Another interesting point from Pew: The percentage of independents, at least in the Pew Research numbers, has shrunk. The percentage of those with no party identification has gone from 17 percent in 2000 to 11 percent in 2016. Usually that total changes little from year to year. But as the numbers of partisans, both liberal Democrats (especially!) and conservative Republicans have grown, the number of no-label voters has grown smaller. It’s no secret that Democratic candidates have received more overall votes than Republicans in recent elections, even if that doesn’t mean that Democrats win more races. In the presidential race, Hillary Clinton received 65,844,610 votes to Trump’s 62,979,636, a percentage difference of 48.2 percent to 46.1 percent. In Senate races (slightly skewed, because two Democrats were running against each other in vote-heavy California), Democrats earned 10,512,669 more votes than Republican candidates. Yet the Republicans retained their majority. In the House, Republicans received 49 percent of the vote, contrasted with Democrats’ 48 percent, yet they hold 55 percent of the seats. To recover completely, the Democratic Party must grow at state levels, and there’s growing interest there. A recent meeting coordinated by the Democratic Legislative Campaign Committee included some 20 groups from across the country, from labor unions to outside funding groups. According to a story from NBC News: Democratic officials have had to add extra candidate training sessions to keep up with demand and increase enrollment in existing ones. One major training group, Emerge America, reports an 87% surge in candidate applications over last year. The women's group Emily's List says nearly 10,000 women have expressed interest in running for office since November, including for state legislative seats. Meanwhile, Run for Something, which is focused on recruiting millennials, says it has heard the same from almost 8,000 young people. … "Everything has changed," Jessica Post, the DLCC executive director, said in an interview in her office. What about the Republicans at the state levels? Ellie Hockenbury, the spokesperson for the Republican Legislative Campaign Committee, said the GOP has already found strong candidates for this year's races, though they're just getting started on next year's midterms. There is plenty of anecdotal evidence of high Democratic interest in running for local races, too. This Daily Kos diary describes a surge in interest by women candidates who attended a “Ready to Run” program at Rutgers University in New Jersey. Those same kinds of programs also are starting in other states. Even if some of those candidates ultimately decide not to run, the numbers are improving. The group Run for Something was launched to capture the enthusiasm of young protesters after Trump’s election and the millions of people who came out for the Women’s March. It wants to get potential candidates to take the next electoral step. It’s focusing on helping millennials run for office, aiming in 2017 for Virginia and North Carolina. According to a story in Mother Jones: The idea isn't just to supply candidates where none are currently running; the group believes the bench is too thin everywhere because Democrats are too exclusive in how they pick out candidates. "Parties are usually focused on asking their electeds, their staff, their networks, who they think should run," [Run for Something Co-founder Amanda] Litman says. That helps build a pipeline, but it's also an echo chamber that makes it difficult for new faces and voices to penetrate. It can be intimidating, she argues, for a prospective candidate to figure out how to run, without an organization to walk him or her through it. "So we're trying to reach people who, one, might not ever be approached by a party or by a recruitment network, or two, might not be comfortable raising their hand if the party asks, 'Who wants to run?' " In other words, women, people of color, and members of the LGBT community—all under the age of 35. As the Mother Jones story points out, there’s no time to lose: The quest to rebuild the Democratic bench is a long-term fight with one ominous deadline in sight. The next round of redistricting is coming up in 2020, and Democrats are still paying the price for their catastrophic losses ahead of the last redistricting. If they can't get a foothold in state legislatures before then—they currently control both houses of the legislature and the governor's mansion in just six states—things stand to get even worse. There are other groups, too. Brand New Congress was started by supporters of Vermont Sen. Bernie Sanders specifically to elect just what the name implies: it’s aiming for 400-plus candidates. Higher Heights is hoping to find and help elect more black women candidates. In my own town (admittedly a hotbed of progressive activism—we had an 87 percent turnout in the November election and went heavily for Hillary Clinton) there are contested races for the village board and two school boards. Even the library board has 10 candidates running for four spots. The most important number, however, is the number of voters who show up on Election Day. Republicans historically have a midterm edge, since older voters tend to be more reliable for those elections. Recent voter turnouts in big-city municipal primaries don’t offer much hope. In Los Angeles, turnout in the mayoral primary was first reported at 11 percent but grew to 17 percent once all of the mail-in ballots were counted. At least that's better than the 11 percent turnout of years past. In St. Louis, turnout in that city’s mayoral primary was 28 percent—again, better than the 22 percent of four years ago, but nothing to brag about. Yet midterm elections usually show a downturn for the incumbent president’s party. But in the age of Trump, all bets may be off. It’s still a long time until November 2018. But you’ve gotta hope it will be buried in a sea of pink pussy hats.
/// Returns a number of random songs similar to this one. /// /// last.fm suggests a number of similar songs to the one the method is /// called on. Optionally takes a `count` to specify the maximum number of /// results to return. pub fn similar<U>(&self, client: &Client, count: U) -> Result<Vec<Song>> where U: Into<Option<usize>>, { let args = Query::with("id", self.id) .arg("count", count.into()) .build(); let song = client.get("getSimilarSongs2", args)?; Ok(get_list_as!(song, Song)) }
Tony Abbott has sought to broaden the debate about same-sex marriage into an all-out culture war. Credit:Lukas Coch Wolfson, a lawyer and professor who was founder and president of the group Freedom to Marry, was the architect of the campaign to legalise gay marriage in the United States, an effort that culminated with a Supreme Court decision two years ago that found in part that one group of Americans did not get to hold a vote to decide upon the basic human rights of another. He has been named by Time magazine as one of the 100 most powerful people in the world. Wolfson's victory might have looked sudden from the outside, but it was the culmination of years of campaigning in which Wolfson and supporters battled anti-gay-marriage activists in a series of state legislatures, where, as in Australia, conservative politicians introduced ballot measures in an effort to block gay marriage. In many of these states Wolfson's key opponent was a bloke called Frank Schubert, a Republican staffer turned freelance campaign consultant. Like Abbott, Frank Schubert is a deeply religious man of powerful conviction. Like Abbott he is intensely disliked by gay marriage activists. In another weird parallel, like Abbott, Schubert has a politically engaged gay sister with a partner and family who does not share his views. This week, says Wolfson, Abbott played straight out of Schubert's campaign playbook. Evan Wolfson says he's seen Tony Abbott's tactics before. Credit:Chester Higgins jnr "He knows they cannot win on the merits of their argument," explains Wolfson, noting that Australians already overwhelmingly back gay marriage, "so they have to make the debate about something else." That's why Abbott announced that this was about political correctness and freedom of speech rather than gay marriage. Wolfson is not speaking figuratively. After Schubert won an unlikely battle to have a ban on gay marriage added to the California constitution in 2008 via a ballot measure, Schubert wrote a memo detailing his winning strategy. Wolfson can see its echoes in Abbott's opening salvo. Frank Schubert, a gay-marriage opponent who fought Proposition 8 in California. Credit:NYT The now notorious document was an article for Political Magazine in February 2009, in which Schubert and his co-author explain how they won despite Californians supporting gay marriage at the start of the campaign by about 60 per cent to 40 per cent. "We needed to convince voters that gay marriage was not simply 'live and let live' – that there would be consequences if gay marriage were to be permanently legalised," Schubert wrote. "We reconfirmed in our early focus groups our own views that Californians had a tolerant opinion of gays. But there were limits to the degree of tolerance that Californians would afford the gay community. They would entertain allowing gay marriage, but not if doing so had significant implications for the rest of society." In the US those "significant implications" became the arguments that "gay propaganda" would spread into schools, that once gay marriage was the norm other aberrant forms of marriage would follow, that religious groups would be victimised. It became the fraught concern for the wellbeing of bakers and marriage celebrants and wedding caterers. It was about anything but the right of a committed couple to marry. All of this is already in play in Australia, and was neatly summed up by Abbott on Wednesday morning. But according to Wolfson there was a parallel campaign fought too. While mainstream politicians kept their hands clean, aware that outright homophobia doesn't wash anymore, a subterranean poison of invective followed the overt campaign, and this too will now by foisted upon Australian gays and their families. You can see it already if you care to dip your toe into online sewers, and elements of it have crept onto cable TV. On Tuesday night Bronwyn Bishop was on Sky News warning of bestiality and the killing of newborn babies. Of course, in the years since gay marriage was legalised in America, the only impact to society has been that some gays got married, and many who once feared the outcome have now changed their views. Today even a plurality of Republicans support gay marriage, 48 to 47 per cent, while 64 per cent of Americans back gay marriage, up from 62 per cent. "This is not some sort of experiment Australia is being asked to make," Wolfson says. "Around the world 1.1 billion people now live in 22 countries where gay marriage is legal." In none of those countries have any of the dire warnings of those who would see it banned come true, despite Bronwyn Bishop's nightmares. Nick O'Malley is a senior Fairfax Media journalist.
<gh_stars>1-10 import React from "react"; import { FormCheck, FormGroup } from "react-bootstrap"; import { useAppDispatch, useAppSelector } from "@/app/hooks"; import { setAudioTrack } from "@/app/slice"; export const FormAudioTrack: React.FC = () => { const audioTrack = useAppSelector((state) => state.audioTrack); const dispatch = useAppDispatch(); const onChange = (event: React.ChangeEvent<HTMLInputElement>): void => { dispatch(setAudioTrack(event.target.checked)); }; return ( <FormGroup className="form-inline" controlId="audioTrack"> <FormCheck type="switch" name="audioTrack" label="Enable audio track" checked={audioTrack} onChange={onChange} /> </FormGroup> ); };
// Lookup looks up the corresponding pythonresource Symbols for the given import graph node ID. // If it returns an error, the Compat index is out of date or the compat builder has a bug. func (i Compat) Lookup(rm pythonresource.Manager, nodeID int64) (pythonresource.Symbol, error) { if sym, ok := i[nodeID]; ok { return rm.NewSymbol(sym.Dist, sym.Path) } return pythonresource.Symbol{}, fmt.Errorf("no symbol found for node %d", nodeID) }
#include<bits/stdc++.h> #define it register int #define ct const int #define il inline using namespace std; typedef long long ll; #define rll register ll #define cll const ll typedef double db; const int N=1000005; int n,d,ans; struct ky{ int x,y,u,v; }a[N]; il void gcd(ct a,ct b){return !b?d=a,void():gcd(b,a%b);} il int A(ct x){return x<0?-x:x;} map<pair<db,db>,int> mp; template<class I> il I Max(I p,I q){return p>q?p:q;} template<class I> il I Min(I p,I q){return p<q?p:q;} int main(){ scanf("%d",&n);it i,j; for(i=1;i<=n;++i) scanf("%d%d%d%d",&a[i].x,&a[i].y,&a[i].u,&a[i].v); for(i=1;i<=n;++i) gcd(A(a[i].v-a[i].y),A(a[i].u-a[i].x)),ans+=d+1; for(i=1;i<=n;++i) for(j=2;j<=n;++j){ cll x1=a[i].x,y1=a[i].y,x2=a[i].u,y2=a[i].v,x3=a[j].x,y3=a[j].y,x4=a[j].u,y4=a[j].v; const db x=((db) ((x1*y2-y1*x2)*(x3-x4)-(x1-x2)*(x3*y4-y3*x4)))/((db) ((x1-x2)*(y3-y4)-(y1-y2)*(x3-x4))), y=((db) ((x1*y2-y1*x2)*(y3-y4)-(y1-y2)*(x3*y4-y3*x4)))/((db) ((x1-x2)*(y3-y4)-(y1-y2)*(x3-x4))); if (x!=round(x)||y!=round(y)||x<Min(x1,x2)||x>Max(x1,x2)||x<Min(x3,x4)||x>Max(x3,x4)||y<Min(y1,y2)||y>Max(y1,y2)||y<Min(y3,y4)||y>Max(y3,y4)) continue; if(!mp.count(make_pair(x,y))) mp[make_pair(x,y)]=i,--ans; else ans-=(mp[make_pair(x,y)]==i); } printf("%d",ans); return 0; }
// With Atom sized to 64MB (or other size) limited chunks. std::string DB::ReadOneFile(const std::string& file_path, ParserIf* parser) { Timer timer; size_t total_write_size = 0, total_uncompressed_size = 0; int32_t rec_counter = 0; int32_t prev_atom_id = meta_data_.file_map().datum_ids_size(); BigInt num_features_before = schema_->GetNumFeatures(); size_t read_size = io::GetFileSize(file_path); int time = 0; { auto fp = io::OpenFileStream(file_path); dmlc::istream in(fp.get()); std::string line; StatCollector stat_collector(&stats_); int32_t batch_size = kInitIngestBatchSize; DBAtom* curr_atom_ptr = nullptr; float compression_rate = 0.5; float over_estimate_rate = 1.0; size_t total_atom_space_used = 0; size_t atom_space_used_threshold = 0; bool use_global_estimate = false; bool has_estimate_init = false; LOG(INFO) << "Initial batch size: " << batch_size; while (!in.eof()) { curr_atom_ptr = new DBAtom(); if (atom_space_used_threshold) { batch_size = std::numeric_limits<int>::max(); } for (int i = 0; i < batch_size && std::getline(in, line); i++) { ++rec_counter; bool invalid = false; DatumBase datum = parser->ParseAndUpdateSchema(line, schema_.get(), &stat_collector, &invalid); if (invalid) { continue; } if (!atom_space_used_threshold && batch_size == kInitIngestBatchSize) { batch_size = kAtomSizeInBytes / (datum.GetDatumProto().SpaceUsed() * 0.5); } curr_atom_ptr->mutable_datum_protos()->AddAllocated( datum.ReleaseProto()); if (atom_space_used_threshold && i % 40000 == 0) { int space_used = curr_atom_ptr->SpaceUsed(); if (space_used >= atom_space_used_threshold) { batch_size = i; break; } } } size_t write_size = 64 * 1e6; int atom_id = meta_data_.file_map().datum_ids_size(); if (write_fut_.valid()) { auto ret = write_fut_.get(); write_size = ret.first; total_write_size += write_size; total_uncompressed_size += ret.second; if (use_global_estimate || !has_estimate_init){ compression_rate = (float)total_write_size / total_uncompressed_size; over_estimate_rate = (float)total_atom_space_used / total_uncompressed_size; atom_space_used_threshold = kAtomSizeInBytes / compression_rate * over_estimate_rate; LOG(INFO) << "\nCompression Rate : " << compression_rate * 100 << "% " << "\nOver Estimate Rate: " << over_estimate_rate * 100 << "%" << "\nAtom Space Used Threshold: " << (double)atom_space_used_threshold / (1<<20) << " MB"; has_estimate_init = true; } } total_atom_space_used += curr_atom_ptr->SpaceUsed(); int64_t num_data_before_read = meta_data_.file_map().num_data(); meta_data_.mutable_file_map()->add_datum_ids(num_data_before_read); meta_data_.mutable_file_map()->set_num_data( num_data_before_read + curr_atom_ptr->datum_protos_size()); write_fut_ = std::async(std::launch::async, [this, curr_atom_ptr, total_write_size, atom_id, batch_size] { auto ret = WriteAtom(*curr_atom_ptr, atom_id, total_write_size); LOG(INFO) << "Atom #" << atom_id << "\nBatch Size : " << batch_size << "\nFile Size : " << SizeToReadableString(ret.first) << "\nSpace Used : " << SizeToReadableString(curr_atom_ptr->SpaceUsed()) << "\nRaw Size : " << SizeToReadableString(ret.second) << "\nCompress Rate : " << (double) ret.first / ret.second * 100 << "%" << "\nOver Estimate : " << (double) curr_atom_ptr->SpaceUsed() / ret.second; delete curr_atom_ptr; return ret; }); float avg_bytes_per_datum = static_cast<float>(write_size) / batch_size; batch_size = kAtomSizeInBytes / avg_bytes_per_datum; if (in.eof()) { auto ret = write_fut_.get(); write_size = ret.first; total_write_size += write_size; total_uncompressed_size += ret.second; } } time = timer.elapsed(); LOG(INFO) << "committing DB"; } std::string output_file_dir = meta_data_.file_map().atom_path(); BigInt num_features_after = schema_->GetNumFeatures(); float compress_ratio = static_cast<float>(total_write_size) / total_uncompressed_size; std::stringstream ss; ss << "Read " << rec_counter << " datum.\n" << "Time: " << time << "s\n" << "Read size: " << SizeToReadableString(read_size) << "\n" << "Read throughput per sec: " << SizeToReadableString(static_cast<float>(read_size) / time) << "\n" << "Wrote to " << output_file_dir <<" [" << prev_atom_id << " - " << meta_data_.file_map().datum_ids_size() << ")\nWritten Size " << SizeToReadableString(total_write_size) << " (" << std::to_string(compress_ratio) << " compression).\n" << "Write throughput per sec: " << SizeToReadableString(static_cast<float>(total_write_size) / time) << "\n" << "# of features in schema: " << num_features_before << " (before) --> " << num_features_after << " (after).\n"; auto meta_data_str = PrintMetaData(); LOG(INFO) << ss.str() << meta_data_str; return ss.str() + meta_data_str; }