id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23535100
How can I do this? A: The generating radio buttons in php should be something like the following: <?php mysql_connect("localhost", "mysql_user", "mysql_password") or die("Could not connect: " . mysql_error()); mysql_select_db("mydb"); $result = mysql_query("SELECT id, name, value FROM mytable"); //I assume the 2nd entry in the database is the value name and the 3th is the button value while ($row = mysql_fetch_array($result)) { echo '<input type="radio" name="'.$row[1].'" value="'.$row[2].'" />'.$row[1]; } ?> The storing in AJAX part is a bit confusing. AJAX is a way of doing a subpage request. See here. So if you want to store with ajax you have to build a PHP page which receives the data and puts it in the database. The easiest way to do this is posting the entire form with the data via an ajax request. Check it out here. Good luck with your endeavors!
doc_23535101
My Medical Specialities page return data by hospital ID in this way: localhost/MedicalSpecialities/1, 1 is the HospitalID. if I change manually the link I can access any hospital info. I have users associated to hospitals in this way: I need to query the Hospital ID's that user have associated AND check if the current HospitalID is on the list. This return all hospitals that user have connected: var userID = User.Identity.GetUserId(); var result = db.Hospitals.Include("UserHospitals") .Where(x => x.UserHospitals .Any(u => u.Id == userID)) .ToList(); A: You can basically update the condition in your Any() method to include a check against the HospitalId column. var hospitalId =5; var result = db.Hospitals .Include(y=>y.UserHospitals) .Where(x => x.UserHospitals.Any(u => u.Id == userID && u.HospitalID==hospitalId )) .ToList(); If you are expecting only a single hospital for this condition, you may also consider using FirstOrDefault() method. var singleHospital = db.Hospitals .Include(y=>y.UserHospitals) .Where(x => x.UserHospitals.Any(u => u.Id == userID && u.HospitalID==hospitalId )) .FirstOrDefault(); if(singleHospital!=null) { //Safely use it. }
doc_23535102
been trying only in eclipse as i dont have admin access to add external library files to tryin cmd. package org.apache.poi.ss.examples; import java.io.File; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import org.apache.poi.ss.usermodel.BorderStyle; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Color; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.FillPatternType; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.ss.util.CellReference; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFColor; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelComparator { private static final String CELL_DATA_DOES_NOT_MATCH = "Cell Data does not Match ::"; private static final String CELL_FONT_ATTRIBUTES_DOES_NOT_MATCH = "Cell Font Attributes does not Match ::"; private static class Locator { Workbook workbook; Sheet sheet; Row row; Cell cell; } List<String> listOfDifferences = new ArrayList(); public static void main(String[] args)throws Exception { if (args.length != 2 || !(new File(args[0]).exists()) || !(new File(args[1]).exists())) { System.err.println("java -cp <classpath> " + ExcelComparator.class.getCanonicalName() + " <workbook1.xls/x> <workbook2.xls/x"); System.exit(-1); } try(Workbook wb1 = WorkbookFactory.create(new File(args[0]), null, true)) { try(Workbook wb2 = WorkbookFactory.create(new File(args[1]), null, true)) { for (String d : ExcelComparator.compare(wb1, wb2)) { System.out.println(d); } } } } public static List<String> compare(Workbook wb1, Workbook wb2) { Locator loc1 = new Locator(); Locator loc2 = new Locator(); loc1.workbook = wb1; loc2.workbook = wb2; ExcelComparator excelComparator = new ExcelComparator(); excelComparator.compareNumberOfSheets(loc1, loc2); excelComparator.compareSheetNames(loc1, loc2); excelComparator.compareSheetData(loc1, loc2); return excelComparator.listOfDifferences; } private void compareDataInAllSheets(Locator loc1, Locator loc2) { for (int i = 0; i < loc1.workbook.getNumberOfSheets(); i ++) { if (loc2.workbook.getNumberOfSheets() <= i) { return; } loc1.sheet = loc1.workbook.getSheetAt(i); loc2.sheet = loc2.workbook.getSheetAt(i); compareDataInSheet(loc1, loc2); } } private void compareDataInSheet(Locator loc1, Locator loc2) { for (int j = 0; j <= loc1.sheet.getLastRowNum(); j ++) { if (loc2.sheet.getLastRowNum() <= j) { return; } loc1.row = loc1.sheet.getRow(j); loc2.row = loc2.sheet.getRow(j); if ((loc1.row == null) || (loc2.row == null)) { continue; } compareDataInRow(loc1, loc2); } } private void compareDataInRow(Locator loc1, Locator loc2) { for (int k = 0; k <= loc1.row.getLastCellNum(); k ++) { if (loc2.row.getLastCellNum() <= k) { return; } loc1.cell = loc1.row.getCell(k); loc2.cell = loc2.row.getCell(k); if ((loc1.cell == null) || (loc2.cell == null)) { continue; } compareDataInCell(loc1, loc2); } } private void compareDataInCell(Locator loc1, Locator loc2) { if (isCellTypeMatches(loc1, loc2)) { final CellType loc1cellType = loc1.cell.getCellType(); switch (loc1cellType) { case BLANK: case STRING: case ERROR: isCellContentMatches(loc1, loc2); break; case BOOLEAN: isCellContentMatchesForBoolean(loc1, loc2); break; case FORMULA: isCellContentMatchesForFormula(loc1, loc2); break; case NUMERIC: if (DateUtil.isCellDateFormatted(loc1.cell)) { isCellContentMatchesForDate(loc1, loc2); } else { isCellContentMatchesForNumeric(loc1, loc2); } break; default: throw new IllegalStateException("Unexpected cell type: " + loc1cellType); } } isCellFillPatternMatches(loc1, loc2); isCellAlignmentMatches(loc1, loc2); isCellHiddenMatches(loc1, loc2); isCellLockedMatches(loc1, loc2); isCellFontFamilyMatches(loc1, loc2); isCellFontSizeMatches(loc1, loc2); isCellFontBoldMatches(loc1, loc2); isCellUnderLineMatches(loc1, loc2); isCellFontItalicsMatches(loc1, loc2); isCellBorderMatches(loc1, loc2, 't'); isCellBorderMatches(loc1, loc2, 'l'); isCellBorderMatches(loc1, loc2, 'b'); isCellBorderMatches(loc1, loc2, 'r'); isCellFillBackGroundMatches(loc1, loc2); } private void compareNumberOfColumnsInSheets(Locator loc1, Locator loc2) { for (int i = 0; i < loc1.workbook.getNumberOfSheets(); i ++) { if (loc2.workbook.getNumberOfSheets() <= i) { return; } loc1.sheet = loc1.workbook.getSheetAt(i); loc2.sheet = loc2.workbook.getSheetAt(i); Iterator<Row> ri1 = loc1.sheet.rowIterator(); Iterator<Row> ri2 = loc2.sheet.rowIterator(); int num1 = (ri1.hasNext()) ? ri1.next().getPhysicalNumberOfCells() : 0; int num2 = (ri2.hasNext()) ? ri2.next().getPhysicalNumberOfCells() : 0; if (num1 != num2) { String str = String.format(Locale.ROOT, "%s\nworkbook1 -> %s [%d] != workbook2 -> %s [%d]", "Number Of Columns does not Match ::", loc1.sheet.getSheetName(), num1, loc2.sheet.getSheetName(), num2); listOfDifferences.add(str); } } } private void compareNumberOfRowsInSheets(Locator loc1, Locator loc2) { for (int i = 0; i < loc1.workbook.getNumberOfSheets(); i ++) { if (loc2.workbook.getNumberOfSheets() <= i) { return; } loc1.sheet = loc1.workbook.getSheetAt(i); loc2.sheet = loc2.workbook.getSheetAt(i); int num1 = loc1.sheet.getPhysicalNumberOfRows(); int num2 = loc2.sheet.getPhysicalNumberOfRows(); if (num1 != num2) { String str = String.format(Locale.ROOT, "%s\nworkbook1 -> %s [%d] != workbook2 -> %s [%d]", "Number Of Rows does not Match ::", loc1.sheet.getSheetName(), num1, loc2.sheet.getSheetName(), num2); listOfDifferences.add(str); } } } private void compareNumberOfSheets(Locator loc1, Locator loc2) { int num1 = loc1.workbook.getNumberOfSheets(); int num2 = loc2.workbook.getNumberOfSheets(); if (num1 != num2) { String str = String.format(Locale.ROOT, "%s\nworkbook1 [%d] != workbook2 [%d]", "Number of Sheets do not match ::", num1, num2); listOfDifferences.add(str); } } private void compareSheetData(Locator loc1, Locator loc2) { compareNumberOfRowsInSheets(loc1, loc2); compareNumberOfColumnsInSheets(loc1, loc2); compareDataInAllSheets(loc1, loc2); } private void compareSheetNames(Locator loc1, Locator loc2) { for (int i = 0; i < loc1.workbook.getNumberOfSheets(); i ++) { String name1 = loc1.workbook.getSheetName(i); String name2 = (loc2.workbook.getNumberOfSheets() > i) ? loc2.workbook.getSheetName(i) : ""; if (!name1.equals(name2)) { String str = String.format(Locale.ROOT, "%s\nworkbook1 -> %s [%d] != workbook2 -> %s [%d]", "Name of the sheets do not match ::", name1, i + 1, name2, i + 1); listOfDifferences.add(str); } } } private void addMessage(Locator loc1, Locator loc2, String messageStart, String value1, String value2) { String str = String.format(Locale.ROOT, "%s\nworkbook1 -> %s -> %s [%s] != workbook2 -> %s -> %s [%s]", messageStart, loc1.sheet.getSheetName(), new CellReference(loc1.cell).formatAsString(), value1, loc2.sheet.getSheetName(), new CellReference(loc2.cell).formatAsString(), value2); listOfDifferences.add(str); } /** * Checks if cell alignment matches. */ private void isCellAlignmentMatches(Locator loc1, Locator loc2) { if (loc1.cell.getCellStyle() == null || loc2.cell.getCellStyle() == null) { return; } HorizontalAlignment align1 = loc1.cell.getCellStyle().getAlignment(); HorizontalAlignment align2 = loc2.cell.getCellStyle().getAlignment(); if (align1 != align2) { addMessage(loc1, loc2, "Cell Alignment does not Match ::", align1.name(), align2.name()); } } private void isCellBorderMatches(Locator loc1, Locator loc2, char borderSide) { if (!(loc1.cell instanceof XSSFCell) || loc1.cell.getCellStyle() == null || loc2.cell.getCellStyle() == null) { return; } XSSFCellStyle style1 = ((XSSFCell)loc1.cell).getCellStyle(); XSSFCellStyle style2 = ((XSSFCell)loc2.cell).getCellStyle(); boolean b1, b2; String borderName; switch (borderSide) { case 't': default: b1 = style1.getBorderTop() == BorderStyle.THIN; b2 = style2.getBorderTop() == BorderStyle.THIN; borderName = "TOP"; break; case 'b': b1 = style1.getBorderBottom() == BorderStyle.THIN; b2 = style2.getBorderBottom() == BorderStyle.THIN; borderName = "BOTTOM"; break; case 'l': b1 = style1.getBorderLeft() == BorderStyle.THIN; b2 = style2.getBorderLeft() == BorderStyle.THIN; borderName = "LEFT"; break; case 'r': b1 = style1.getBorderRight() == BorderStyle.THIN; b2 = style2.getBorderRight() == BorderStyle.THIN; borderName = "RIGHT"; break; } if (b1 != b2) { addMessage(loc1, loc2, "Cell Border Attributes does not Match ::", (b1 ? "" : "NOT ") + borderName + " BORDER", (b2 ? "" : "NOT ") + borderName + " BORDER"); } } private void isCellContentMatches(Locator loc1, Locator loc2) { String str1 = loc1.cell.toString(); String str2 = loc2.cell.toString(); if (!str1.equals(str2)) { addMessage(loc1, loc2, CELL_DATA_DOES_NOT_MATCH, str1, str2); } } private void isCellContentMatchesForBoolean(Locator loc1, Locator loc2) { boolean b1 = loc1.cell.getBooleanCellValue(); boolean b2 = loc2.cell.getBooleanCellValue(); if (b1 != b2) { addMessage(loc1, loc2, CELL_DATA_DOES_NOT_MATCH, Boolean.toString(b1), Boolean.toString(b2)); } } private void isCellContentMatchesForDate(Locator loc1, Locator loc2) { Date date1 = loc1.cell.getDateCellValue(); Date date2 = loc2.cell.getDateCellValue(); if (!date1.equals(date2)) { addMessage(loc1, loc2, CELL_DATA_DOES_NOT_MATCH, date1.toString(), date2.toString()); } } private void isCellContentMatchesForFormula(Locator loc1, Locator loc2) { // TODO: actually evaluate the formula / NPE checks String form1 = loc1.cell.getCellFormula(); String form2 = loc2.cell.getCellFormula(); if (!form1.equals(form2)) { addMessage(loc1, loc2, CELL_DATA_DOES_NOT_MATCH, form1, form2); } } private void isCellContentMatchesForNumeric(Locator loc1, Locator loc2) { // TODO: Check for NaN double num1 = loc1.cell.getNumericCellValue(); double num2 = loc2.cell.getNumericCellValue(); if (num1 != num2) { addMessage(loc1, loc2, CELL_DATA_DOES_NOT_MATCH, Double.toString(num1), Double.toString(num2)); } } private String getCellFillBackground(Locator loc) { Color col = loc.cell.getCellStyle().getFillForegroundColorColor(); return(col instanceof XSSFColor) ? ((XSSFColor)col).getARGBHex() : "NO COLOR"; } private void isCellFillBackGroundMatches(Locator loc1, Locator loc2) { if (loc1.cell.getCellStyle() == null || loc2.cell.getCellStyle() == null) { return; } String col1 = getCellFillBackground(loc1); String col2 = getCellFillBackground(loc2); if (!col1.equals(col2)) { addMessage(loc1, loc2, "Cell Fill Color does not Match ::", col1, col2); } } private void isCellFillPatternMatches(Locator loc1, Locator loc2) { if (loc1.cell.getCellStyle() == null || loc2.cell.getCellStyle() == null) { return; } FillPatternType fill1 = loc1.cell.getCellStyle().getFillPattern(); FillPatternType fill2 = loc2.cell.getCellStyle().getFillPattern(); if (fill1 != fill2) { addMessage(loc1, loc2, "Cell Fill pattern does not Match ::", fill1.name(), fill2.name()); } } private void isCellFontBoldMatches(Locator loc1, Locator loc2) { if (!(loc1.cell instanceof XSSFCell) || loc1.cell.getCellStyle() == null || loc2.cell.getCellStyle() == null) { return; } if (hasInvalidFontIndex(loc1, loc2)) { return; } boolean b1 = ((XSSFCell)loc1.cell).getCellStyle().getFont().getBold(); boolean b2 = ((XSSFCell)loc2.cell).getCellStyle().getFont().getBold(); if (b1 != b2) { addMessage(loc1, loc2, CELL_FONT_ATTRIBUTES_DOES_NOT_MATCH, (b1 ? "" : "NOT ") + "BOLD", (b2 ? "" : "NOT ") + "BOLD"); } } private void isCellFontFamilyMatches(Locator loc1, Locator loc2) { if (!(loc1.cell instanceof XSSFCell) || loc1.cell.getCellStyle() == null || loc2.cell.getCellStyle() == null) { return; } if (hasInvalidFontIndex(loc1, loc2)) { return; } String family1 = ((XSSFCell)loc1.cell).getCellStyle().getFont().getFontName(); String family2 = ((XSSFCell)loc2.cell).getCellStyle().getFont().getFontName(); if (!family1.equals(family2)) { addMessage(loc1, loc2, "Cell Font Family does not Match ::", family1, family2); } } private boolean hasInvalidFontIndex(Locator loc1, Locator loc2) { int fontIdx1 = loc1.cell.getCellStyle().getFontIndexAsInt(); int fontCount1 = ((XSSFWorkbook)loc1.workbook).getStylesSource().getFonts().size(); int fontIdx2 = loc2.cell.getCellStyle().getFontIndexAsInt(); int fontCount2 = ((XSSFWorkbook)loc2.workbook).getStylesSource().getFonts().size(); if (fontIdx1 >= fontCount1 || fontIdx2 >= fontCount2) { addMessage(loc1, loc2, "Corrupted file, cell style references a font which is not defined", Integer.toString(fontIdx1), Integer.toString(fontIdx2)); return true; } return false; } private void isCellFontItalicsMatches(Locator loc1, Locator loc2) { if (!(loc1.cell instanceof XSSFCell) || loc1.cell.getCellStyle() == null || loc2.cell.getCellStyle() == null) { return; } if (hasInvalidFontIndex(loc1, loc2)) { return; } boolean b1 = ((XSSFCell)loc1.cell).getCellStyle().getFont().getItalic(); boolean b2 = ((XSSFCell)loc2.cell).getCellStyle().getFont().getItalic(); if (b1 != b2) { addMessage(loc1, loc2, CELL_FONT_ATTRIBUTES_DOES_NOT_MATCH, (b1 ? "" : "NOT ") + "ITALICS", (b2 ? "" : "NOT ") + "ITALICS"); } } private void isCellFontSizeMatches(Locator loc1, Locator loc2) { if (!(loc1.cell instanceof XSSFCell) || loc1.cell.getCellStyle() == null || loc2.cell.getCellStyle() == null) { return; } if (hasInvalidFontIndex(loc1, loc2)) { return; } short size1 = ((XSSFCell)loc1.cell).getCellStyle().getFont().getFontHeightInPoints(); short size2 = ((XSSFCell)loc2.cell).getCellStyle().getFont().getFontHeightInPoints(); if (size1 != size2) { addMessage(loc1, loc2, "Cell Font Size does not Match ::", Short.toString(size1), Short.toString(size2)); } } private void isCellHiddenMatches(Locator loc1, Locator loc2) { if (loc1.cell.getCellStyle() == null || loc2.cell.getCellStyle() == null) { return; } boolean b1 = loc1.cell.getCellStyle().getHidden(); boolean b2 = loc1.cell.getCellStyle().getHidden(); if (b1 != b2) { addMessage(loc1, loc2, "Cell Visibility does not Match ::", (b1 ? "" : "NOT ") + "HIDDEN", (b2 ? "" : "NOT ") + "HIDDEN"); } } private void isCellLockedMatches(Locator loc1, Locator loc2) { if (loc1.cell.getCellStyle() == null || loc2.cell.getCellStyle() == null) { return; } boolean b1 = loc1.cell.getCellStyle().getLocked(); boolean b2 = loc1.cell.getCellStyle().getLocked(); if (b1 != b2) { addMessage(loc1, loc2, "Cell Protection does not Match ::", (b1 ? "" : "NOT ") + "LOCKED", (b2 ? "" : "NOT ") + "LOCKED"); } } private boolean isCellTypeMatches(Locator loc1, Locator loc2) { CellType type1 = loc1.cell.getCellType(); CellType type2 = loc2.cell.getCellType(); if (type1 == type2) { return true; } addMessage(loc1, loc2, "Cell Data-Type does not Match in :: ", type1.name(), type2.name()); return false; } private void isCellUnderLineMatches(Locator loc1, Locator loc2) { // TODO: distinguish underline type if (!(loc1.cell instanceof XSSFCell) || loc1.cell.getCellStyle() == null || loc2.cell.getCellStyle() == null) { return; } if (hasInvalidFontIndex(loc1, loc2)) { return; } byte b1 = ((XSSFCell)loc1.cell).getCellStyle().getFont().getUnderline(); byte b2 = ((XSSFCell)loc2.cell).getCellStyle().getFont().getUnderline(); if (b1 != b2) { addMessage(loc1, loc2, CELL_FONT_ATTRIBUTES_DOES_NOT_MATCH, (b1 == 1 ? "" : "NOT ") + "UNDERLINE", (b2 == 1 ? "" : "NOT ") + "UNDERLINE"); } } } Expected output input to be asked when executed Provide the PreUpgrade files Folder Path: E:\PreUpgrade\ Provide the PostUpgrade files Folder Path: E:\PostUpgrade\ output Comparison Results must be placed in this folder, with Compared_${fileName} E:\Comparison\ NOTE: File Names in both the folders should be like Pre-${fileName} & Post-${fileName} while input is provided P.S: This is my first time posting here pls ignore mistakes if any A: try to build your program (generate the .jar file) and run this command in the command prompt: java -jar pathtoyourjarfile.jar file1 file2
doc_23535103
* *Create a project "A" in maven. *Create another project "B" which contains the JUnit tests for "A" *add maven dependencies so that B is used to test A There are many resources out there which describe how to add test to an existing project but I didn't realy found a way to add another project for the unit tests. Here is what I had in mind: Project A <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>group</groupId> <artifactId>A</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>group</groupId> <artifactId>B</artifactId> <version>1.0-SNAPSHOT</version> <scope>test</scope> </dependency> </dependencies> </project> Project B (Test) <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>group</groupId> <artifactId>B</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>group</groupId> <artifactId>A</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency> </dependencies> </project> Unit Test (Placeholder) package group.B; import org.junit.*; import group.A.aClass; public class aClassTest { @Test void testTest() { assert(false); // this should fail, right? } } I am using Netbeans with the Maven plugin, just so you know. Both projects now each other, the dependencies are fine. Thanks in advance! A: Your above produces a circular dependency. I have done this in the past not for unit tests but for integration tests. What I suggest is that B depends on A (A has no dependency on B). In src/test/java of B write all the tests you need. When you run mvn test on B it will pass or fail depending on if the tests pass or fail. There is not a way to make the compilation of A fail based on the tests in B.
doc_23535104
(Phone{phoneNumber})-[:CALL]-(Phone{phoneNumber}) (Person{personId})-[:KEEP]-(Phone{personId}) (Case{caseId})-[:INVOLVE]-(Person{personId}) all these three are using bidirectional relationship. And created index on phoneNumber/personId/caseId. User can input one or more strings which maybe represent as phoneNumber/ caseId/personId to query for their relationships(NOT consider direction and relationship depth can be 1 to 4). Here is the cypher query: match p = n-[r*1..4]-m with n,m,p where (n.phoneNumber in ["xxx","yyy"] or n.caseSjNo in ["xxx","yyy"] or n.identificationNumber in ["xxx","yyy"]) and (m.phoneNumber in ["xxx","yyy"] or m.caseSjNo in ["xxx","yyy"] or m.identificationNumber in ["xxx","yyy"]) and n <> m return p limit 1000 I profiled this query string in shell console.Having 10,000 nodes in neo4j db, I found the Dbhits is amazing. Here is the result(depth = 1 and depth = 4): neo4j-sh (?)$ profile match p = n-[r*1..1]-m with n,m,p where (n.phoneNumber in ["XXX","YYY"] or n.caseSjNo in ["XXX","YYY"] or n.identificationNumber in ["XXX","YYY"]) and (m.phoneNumber in ["XXX","YYY"] or m.caseSjNo in ["XXX","YYY"] or m.identificationNumber in ["XXX","YYY"]) and n <> m return p limit 1000; ==> +---+ ==> | p | ==> +---+ ==> +---+ ==> 0 row ==> ==> ColumnFilter(0) ==> | ==> +Slice ==> | ==> +Filter ==> | ==> +ColumnFilter(1) ==> | ==> +ExtractPath ==> | ==> +TraversalMatcher ==> ==> +------------------+-------+--------+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ ==> | Operator | Rows | DbHits | Identifiers | Other | ==> +------------------+-------+--------+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ ==> | ColumnFilter(0) | 0 | 0 | | keep columns p | ==> | Slice | 0 | 0 | | { AUTOINT12} | ==> | Filter | 0 | 480776 | | ((((any(-_-INNER-_- in Collection(List({ AUTOSTRING0}, { AUTOSTRING1})) where Property(n,phoneNumber(3)) == -_-INNER-_-) OR any(-_-INNER-_- in Collection(List({ AUTOSTRING2}, { AUTOSTRING3})) where Property(n,caseSjNo(0)) == -_-INNER-_-)) OR any(-_-INNER-_- in Collection(List({ AUTOSTRING4}, { AUTOSTRING5})) where Property(n,identificationNumber(2)) == -_-INNER-_-)) AND ((any(-_-INNER-_- in Collection(List({ AUTOSTRING6}, { AUTOSTRING7})) where Property(m,phoneNumber(3)) == -_-INNER-_-) OR any(-_-INNER-_- in Collection(List({ AUTOSTRING8}, { AUTOSTRING9})) where Property(m,caseSjNo(0)) == -_-INNER-_-)) OR any(-_-INNER-_- in Collection(List({ AUTOSTRING10}, { AUTOSTRING11})) where Property(m,identificationNumber(2)) == -_-INNER-_-))) AND NOT(n == m)) | ==> | ColumnFilter(1) | 20034 | 0 | | keep columns n, m, p | ==> | ExtractPath | 20034 | 0 | p | | ==> | TraversalMatcher | 20034 | 50152 | | m, UNNAMED11, m, r | ==> +------------------+-------+--------+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ ==> ==> Total database accesses: 530928 ------------------------------------------------------ ------------------------------------------------------ neo4j-sh (?)$ profile match p = n-[r*1..4]-m with n,m,p where (n.phoneNumber in ["XXX","YYY"] or n.caseSjNo in ["XXX","YYY"] or n.identificationNumber in ["XXX","YYY"]) and (m.phoneNumber in ["XXX","YYY"] or m.caseSjNo in ["XXX","YYY"] or m.identificationNumber in ["XXX","YYY"]) and n <> m return p limit 1000 ; ==> +---+ ==> | p | ==> +---+ ==> +---+ ==> 0 row ==> ==> ColumnFilter(0) ==> | ==> +Slice ==> | ==> +Filter ==> | ==> +ColumnFilter(1) ==> | ==> +ExtractPath ==> | ==> +TraversalMatcher ==> ==> +------------------+---------+-----------+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ ==> | Operator | Rows | DbHits | Identifiers | Other | ==> +------------------+---------+-----------+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ ==> | ColumnFilter(0) | 0 | 0 | | keep columns p | ==> | Slice | 0 | 0 | | { AUTOINT12} | ==> | Filter | 0 | 120244220 | | ((((any(-_-INNER-_- in Collection(List({ AUTOSTRING0}, { AUTOSTRING1})) where Property(n,phoneNumber(3)) == -_-INNER-_-) OR any(-_-INNER-_- in Collection(List({ AUTOSTRING2}, { AUTOSTRING3})) where Property(n,caseSjNo(0)) == -_-INNER-_-)) OR any(-_-INNER-_- in Collection(List({ AUTOSTRING4}, { AUTOSTRING5})) where Property(n,identificationNumber(2)) == -_-INNER-_-)) AND ((any(-_-INNER-_- in Collection(List({ AUTOSTRING6}, { AUTOSTRING7})) where Property(m,phoneNumber(3)) == -_-INNER-_-) OR any(-_-INNER-_- in Collection(List({ AUTOSTRING8}, { AUTOSTRING9})) where Property(m,caseSjNo(0)) == -_-INNER-_-)) OR any(-_-INNER-_- in Collection(List({ AUTOSTRING10}, { AUTOSTRING11})) where Property(m,identificationNumber(2)) == -_-INNER-_-))) AND NOT(n == m)) | ==> | ColumnFilter(1) | 5010178 | 0 | | keep columns n, m, p | ==> | ExtractPath | 5010178 | 0 | p | | ==> | TraversalMatcher | 5010178 | 20070774 | | m, UNNAMED11, m, r | ==> +------------------+---------+-----------+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ ==> ==> Total database accesses: 140314994 Although results came out, this took too long time. Any tips of query optimization. UPDATE When having 1,000,000(1M) nodes in db, out of memory error occurred. A: Why do you use bidirectional relationships in the first place? In Neo4j you can always navigate on both directions. * *update to a recent Neo4j version (2.2.2) *use single directional relationships *use labels *create label indexes *the with in between doesn't help as it separates the conditions from the pattern *as you have a "generic" entity concept (x can be "anything") I recommend to add an :Entity label and use an id field there with an index. *are you really interested in all paths ? or just allShortestPaths? see: create index on :Entity(id); match (n:Entity),(m:Entity) where n.id in ["xxx","yyy"] and m.id in ["xxx","yyy"] and n<>m match p = (n)-[r*1..4]-(m) return p limit 1000 Otherwise split it up into 6 different statements and use a union. match p = (n:Person)-[r*1..4]-(m:Case) where n.identificationNumber in ["xxx","yyy"] and m.caseSjNo in ["xxx","yyy"] return p limit 500 UNION match p = (n:Person)-[r*1..4]-(m:Phone) where n.identificationNumber in ["xxx","yyy"] and m.phoneNumber in ["xxx","yyy"] return p limit 500 UNION ...
doc_23535105
Some programming languages play better together than others because they are closely related in design, and some also provide better interfaces to other programming languages, which are not directly related. I know it's impossible to list all the different combinations, but I'm interested in the interaction capability for simulation work between the most commonly used programming languages. Typically there is a requirement for the following: * *Grunt work (fast as possible calculations) should support multi-threading *Good code library support (e.g. math, statistics) *User interface (e.g. simulation setup, plotting results) *Operating system independence (Windows/Linux/Mac) It's obviously possible to use any two languages together in some way or another, but I know there are instances where it definitely makes more sense to do so. A: You should probably change that to top 11, because JavaScript is invaluable when it comes to combining languages. Why? Because that's the only one you can run in a browser! So, my answer is exactly that: Two languages that work well together are JavaScript and X (where X is any top 10 language from your list); JavaScript on the client, X on the server. A: Your question is very general, but basically, most Win32 languages can work together. You can write fast dll's in C++ and then use Visual Basic 6 to make slow calls to it. ;) Delphi and C++ work well together too, although there isn't much reason to use C++ dlls in Delphi because Delphi will perform just as well. The same goes for .NET assemblies. All of them can work together, so you can write a framework in C#, while choosing a language with an easier syntax (like VB.NET or Prism) to allow beginning programmers (or those migrating from VB) to use that framework. A: Almost any scripting language (Perl, Python, Ruby, Lua, etc.) and C. You use the scripting language for rapid prototyping and then C to reimplement the slower parts. C++ can also be used, but it has some features that are difficult to integrate as, for instance, virtual methods. Then you have Jython, that's a version of Python running on top of the JVM that plays quite nicely with Java, and there are a bunch of other JVM languages in the same position. If you use .Net or Mono, at least in theory, all the languages supported should be able to call code in other languages. A: C#/ASP.NET/JavaScript(jQuery/jQueryUI/jQueryMobile) That pretty much sums up my life, haha This is a very broad question, which will have far too many answers. Just because putting two languages together may be difficult for one person, it might be easy for another. A: For web design, HTML, CSS, JAVASCRIPT, JQUERY/YUI, PHP, MYSQL. Perfect blend. If you are just starting out, learn the languages in the order i have them listed.
doc_23535106
undefined local variable or method `element' for #<#:0x007fa394a33948> <h2 class="no-margin-top">Vacation Dates</h2> <%= render_elements :only => [:vacation_date] %> <ul> <% element.tag_list.each do |tag| %> <li><%= tag.name %></li> <% end %> </ul> How can I iterate over this element in the html.erb file? I can render all of the elements by calling just <%= render_elements :only => [:vacation_date] %> and deleting the rest of the code. However, Id like to be able to iterate over all vacation dates. A: use render_element like it's described here https://github.com/magiclabs/alchemy_cms/blob/b712ac2fc9fdc3cb6786b1c6733f8d37be4c2588/app/helpers/alchemy/elements_helper.rb#L98-L172
doc_23535107
Since JSR-303 doesn't validate class level constraints, I wan't to keep one custom validator, which validates, that a request form, has at least on field filled. The validator is registered to every field and gets a string array with the name of the other fields, which it has to check for input. The problem is, when JSR-303 ist present on the classpath, the properties for the custom validator aren't set and then it is not aware of the names of the other fields. The validator is still triggered but ends up with a message, that no input has been given. I've already take a look on the log file output, but the only difference is 11:22:50,403 INFO [Version] Hibernate Validator 4.2.0.Final 11:22:50,450 INFO [ExternalSpecifications] MyFaces Bean Validation support enabled instead of 11:02:10,472 INFO [ExternalSpecifications] MyFaces Bean Validation support disabled Another difference is the following output, which appears, when the validation is triggered for the first time, when JSR-303 is present: 11:23:09,906 INFO [_ExternalSpecifications] MyFaces Unified EL support disabled 11:23:09,906 INFO [_ExternalSpecifications] MyFaces Bean Validation support enabled I'm using MyFaces 2.0, Hibernate Validator 4.2 on a JBoss 5.1 jdk6 Update: <cc:formular bean="#{bankenBean}"> <h:outputLabel for="bankleitzahl"> <span class="kurztaste">B</span>ankleitzahl:</h:outputLabel> <h:inputText id="bankleitzahl" accesskey="b" size="10" maxlength="8" value="#{bankenBean.bankleitzahl}"> <audi:notEmptyValidator dependsOn="bic name ort" detail="Eines dieser Felder muss gefüllt sein." /> </h:inputText> <h:message for="bankleitzahl" errorClass="fehlertext" /> <h:outputLabel for="bic">B<span class="kurztaste">I</span>C:</h:outputLabel> <h:inputText id="bic" accesskey="i" size="12" maxlength="11" value="#{bankenBean.bic}"> <audi:notEmptyValidator dependsOn="bankleitzahl name ort" detail="Eines dieser Felder muss gefüllt sein." /> </h:inputText> <h:message for="bic" errorClass="fehlertext" /> <h:outputLabel for="name"> <span class="kurztaste">N</span>ame der Bank:</h:outputLabel> <h:inputText id="name" accesskey="n" size="35" maxlength="58" value="#{bankenBean.name}"> <audi:notEmptyValidator dependsOn="bankleitzahl bic ort" detail="Eines dieser Felder muss gefüllt sein." /> </h:inputText> <h:message for="name" errorClass="fehlertext" /> <h:outputLabel for="ort"> <span class="kurztaste">O</span>rt der Bank:</h:outputLabel> <h:inputText id="ort" accesskey="o" size="35" maxlength="35" value="#{bankenBean.ort}"> <audi:notEmptyValidator dependsOn="bankleitzahl bic name" detail="Eines dieser Felder muss gefüllt sein." /> </h:inputText> <h:message for="ort" errorClass="fehlertext" /> </cc:formular> This is the point, where the notEmptyValidator is used. It's defined in a facelets.taglib.xml: <?xml version="1.0" encoding="UTF-8"?> <facelet-taglib version="2.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facelettaglibrary_2_0.xsd"> <namespace>http://rzf.finnrw.de/audi</namespace> <tag> <tag-name>notEmptyValidator</tag-name> <validator> <validator-id>de.finnrw.rzf.audi.NotEmptyValidator</validator-id> </validator> <attribute> <name>dependsOn</name> <type>java.lang.String</type> </attribute> <attribute> <name>detail</name> <type>java.lang.String</type> </attribute> </tag> When JSR-303 is present on the classpath, this custom validator is still registered an triggered. But it hasn't got it's properties set and is therefore not aware of the fields which it has to check.
doc_23535108
I am using Visual Studio Enterprise from my Azure student account. Maybe someone faced the same problem. Thanks in advance
doc_23535109
My app need to login to perform any test, so I don't want to start new browser and login again and again every story. I tried the setting below but it seem not work as expected. I am using Serenity 1.5.rc-1 with latest Firefox and Chrome, my test always open new browser every story run, if I run 5 stores, then there are 5 instance of Firefox open. I googled for 2 weeks, but I'm still stuck. Please help! serenity.properties serenity.use.unique.browser=true serenity.restart.browser.for.each=NEVER restart.browser.each.scenario=false A: JBehave doesn't support using a single browser across all stories (there is no way of knowing when the suite has finished running, so no way of knowing when to shut down the browser cleanly), so the optimal setting is serenity.restart.browser.for.each = story This is actually a good compromise, as some WebDriver instances can become flaky when run for too long with the same browser.
doc_23535110
I am getting a FileNotFoundException when I run the following command at command prompt: c:\TA\java -jar LoginCaptchaChrome.jar LoginCaptchaChrome https://2015.qa.int.www.mol.com/ C:\\TA\\TD\\Login\\Login.xlsx C:\\TA\\TR\\LoginCaptchaChrome_22082016_1838.xlsx The error message is as below: `Exception in thread "main" java.io.FileNotFoundException: C:\TA\TR\LoginCaptchaChrome_22082016_1838.xlsx" (The filename, directory name, or volume label syntax is incorrect) at java.io.FileOutputStream.open0(Native Method) at java.io.FileOutputStream.open(Unknown Source) at java.io.FileOutputStream.<init>(Unknown Source) at java.io.FileOutputStream.<init>(Unknown Source) at LoginCaptchaChrome.main(LoginCaptchaChrome.java:58) I am actually passing arguements from the command prompt, and the file LoginCaptchaChrome_22082016_1838.xlsx` is not being passed to the code line : FileOutputStream fos = new FileOutputStream("\"" + args[3] + "\""); in the following code: public class LoginCaptchaChrome { public static void main(String[] args) throws IOException, InterruptedException{ String tc = args[0]; String address = args[1]; String test_data = args[2]; String test_result = args[3];` System.setProperty("webdriver.chrome.driver", "C:\\Users\\Lam Chio Meng\\Desktop\\work\\chromedriver_win32\\chromedriver.exe"); FileOutputStream fos = new FileOutputStream("\"" + args[3] + "\""); XSSFWorkbook workbook = new XSSFWorkbook(); Hope to have advice from experts here. Thank you in advance. A: The problem comes from a misconception of how arguments are passed at a command line. Take a shell for instance. Suppose this command at the prompt: someCommand "arg with spaces" What the arguments of the process actually are: * *someCommand, and *arg with spaces. Yes, that's a single argument. This means that the problem for you is this line: new FileOutputStream("\"" + args[3] + "\""); You don't need the leading and trailing quotes at all. Moreover, since this is 2016, don't use FileOutputStream. Use JSR 203: final Path path = Paths.get(args[3]); final OutputStream out = Files.newOutputStream(path); A simple way to see how the Java program actually sees arguments is a program like this: public final class CmdLineArgs { public static void main(final String... args) { final int len = args.length; System.out.println("---- Begin arguments ----"); IntStream.range(0, len) .map(index -> String.format("Arg %d: %d", index + 1, args[index]) .forEach(System.out::println); System.out.println("---- End arguments ----"); System.exit(0); } } Try and run this command at the prompt with, say: java MyClass foo bar and: java MyClass "foo bar" and see the difference.
doc_23535111
So I created a view template called DoubleTemplate @model double @if (ViewData["IsVisible"] != null) { var IsVisible = (bool)ViewData["Switcher"]; if (IsVisible) { @Html.TextBox(string.Empty,Model) } } And back to my web page, here is my code to call this template @Html.EditorFor(m => m.Year1Data, "DoubleTemplate", new {Switcher = m.CurrentProgramYear == 1}) An error under the second m saying: The name 'm' does not exist in the current context So my question is how to assign my model property to the additionalViewData in EditorFor Btw, here is the syntax of EnditorFor on MSDN public static MvcHtmlString EditorFor<TModel, TValue>( this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string templateName, Object additionalViewData ) A: Assuming CurrentProgramYear is a property in you model, change .... new {Switcher = m.CurrentProgramYear ... to .... new {Switcher = Model.CurrentProgramYear ...
doc_23535112
Here are my views.py @verified_email_required() def home(request): usuario = Perfil.objects.filter(user=request.user) context = ({"usuario": usuario}) return render(request, "explore/inicioapp.html", context) @verified_email_required() def profile(request, id): instance = get_object_or_404(Perfil, id=id) form = ProfileForm(instance=instance) if request.method == "POST": form = ProfileForm(request.POST, instance=instance) if form.is_valid(): perfil = form.save(commit=False) perfil.user = request.user perfil.save() return HttpResponseRedirect("/profile/") context = ({"form", form}, {"datos": instance}) return render(request, "explore/profile.html", context) models.py class Perfil(models.Model): user = models.OneToOneField(User) Sexo = models.CharField(max_length=100) Direccion = models.CharField(max_length=100) CP = models.CharField(max_length=100) Ciudad = models.CharField(max_length=100) Estado = models.CharField(max_length=100) Pais = models.CharField(max_length=100) Telefono = models.CharField(max_length=100) Celular = models.CharField(max_length=100) PaisPasaporte = models.CharField(max_length=100) NumeroPasaporte = models.CharField(max_length=100) VigenciaPasaporte = models.DateField(max_length=100) ContactoEmergencia = models.CharField(max_length=100) TelefonoEmergencia = models.CharField(max_length=100) CorreoEmergencia = models.CharField(max_length=100) Alergias = models.CharField(max_length=500) forms.py class ProfileForm(forms.ModelForm): class Meta: model = Perfil exclude = ["user"] widgets = { 'Sexo': Select(choices=opciones_sexo, attrs={'class': 'selectpicker'}), 'VigenciaPasaporte': forms.DateInput(attrs={'class': 'datepicker'}) } labels = { 'Sexo': _("Gender"), 'Direccion': _("Address"), 'CP': _("Zip code"), 'Ciudad': _("City"), 'Estado': _("State"), 'Pais': _("Country"), 'Telefono': _("Phone"), 'Celular': _("Cellphone"), 'PaisPasaporte': _("Passport emission country"), 'NumeroPasaporte': _("Passport number"), 'VigenciaPasaporte': _("Passport expiration date"), 'ContactoEmergencia': _("Emergency contact person"), 'TelefonoEmergencia': _("Emergency contact phone"), 'CorreoEmergencia': _("Emergency contact email") } def __init__(self, *args, **kwargs): kwargs.setdefault("label_suffix", "") super(ProfileForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super(ProfileForm, self).clean() sexoseleccionado = cleaned_data.get("Sexo") if sexoseleccionado == "none": raise forms.ValidationError("You must select a gender to continue.") return cleaned_data url url(r'^profile/(?P<user>\d+)$', views.profile, name="profile"), And finally the HTML link <a class="btn btn-menu" href="{% url "explore:profile" Perfil.id %}">{% trans "My Profile" %}</a> Thanks! A: Your problem is that your url pattern is passing an argument user, but your view method is defining the argument as id. url(r'^profile/(?P<user>\d+)$', views.profile, name="profile"), ^^^^ Your view method, however: @verified_email_required() def profile(request, id): ^^ A: It's just a name issue. In the URL for profile you are capturing a "user" variable. But the view itself is expecting an "id" argument. Make these consistent.
doc_23535113
For example: a=10 b=20 c=30 d=40 list1 <- c(a,b,c,d) e <- c(1,2,3,4,5) f <- c(6,7,8,9,10) g <- c(11,12,13,14) h <- c(15,16,17,18) list2 <- c(e,f,g,h) I want to find out whether each element of list1 is greater than each element of each list of variables in list2. A: You can do a nested map a=10 b=20 c=30 d=40 list1 <- list(a,b,c,d) e <- c(1,2,3,4,5) f <- c(6,7,8,9,10) g <- c(11,12,13,14) h <- c(15,16,17,18) list2 <- list(e,f,g,h) library(tidyverse) #> Warning: package 'forcats' was built under R version 3.6.3 map(.x = list1,.f = ~map(list2,.f = function(y) .x > y)) #> [[1]] #> [[1]][[1]] #> [1] TRUE TRUE TRUE TRUE TRUE #> #> [[1]][[2]] #> [1] TRUE TRUE TRUE TRUE FALSE #> #> [[1]][[3]] #> [1] FALSE FALSE FALSE FALSE #> #> [[1]][[4]] #> [1] FALSE FALSE FALSE FALSE #> #> #> [[2]] #> [[2]][[1]] #> [1] TRUE TRUE TRUE TRUE TRUE #> #> [[2]][[2]] #> [1] TRUE TRUE TRUE TRUE TRUE #> #> [[2]][[3]] #> [1] TRUE TRUE TRUE TRUE #> #> [[2]][[4]] #> [1] TRUE TRUE TRUE TRUE #> #> #> [[3]] #> [[3]][[1]] #> [1] TRUE TRUE TRUE TRUE TRUE #> #> [[3]][[2]] #> [1] TRUE TRUE TRUE TRUE TRUE #> #> [[3]][[3]] #> [1] TRUE TRUE TRUE TRUE #> #> [[3]][[4]] #> [1] TRUE TRUE TRUE TRUE #> #> #> [[4]] #> [[4]][[1]] #> [1] TRUE TRUE TRUE TRUE TRUE #> #> [[4]][[2]] #> [1] TRUE TRUE TRUE TRUE TRUE #> #> [[4]][[3]] #> [1] TRUE TRUE TRUE TRUE #> #> [[4]][[4]] #> [1] TRUE TRUE TRUE TRUE Created on 2020-03-31 by the reprex package (v0.3.0)
doc_23535114
@Html.ActionLink("Edit", "Edit", new { id = Model.id_rod }) | To bring up the image instead of writing. A: If using Bootstrap 3: <a href="@Url.Action("Edit", new { id = Model.id_rod })"> <i class="glyphicon glyphicon-pencil"></i> <span class="sr-only">Edit</span> </a> Note the use of sr-only will allow users of screen readers and search engines to know what the link is for. A: I made helper for easier re-use Helper Method Extension class namespace Extensions { public static class HtmlExtensions { public static MvcHtmlString FALink(this HtmlHelper htmlHelper, string action, string controller, string link_text, string fa_class, string btn_css_classes = "", string button_id = "", object route_values = null) { // declare the span for the glyphicon TagBuilder span = new TagBuilder("span"); span.AddCssClass($"fa fa-{fa_class}"); span.MergeAttribute("aria-hidden", "true"); // declare the anchor tag TagBuilder anchor = new TagBuilder("a"); // Add the href attribute to the <a> element if (string.IsNullOrEmpty(controller) || string.IsNullOrEmpty(action)) anchor.MergeAttribute("href", "#"); else anchor.MergeAttribute("href", new UrlHelper(HttpContext.Current.Request.RequestContext).Action(action, controller, route_values)); // Add the <span> element and the text to the <a> element anchor.InnerHtml = $"{span} {link_text}"; anchor.AddCssClass(btn_css_classes); anchor.GenerateId(button_id); // Create the helper return MvcHtmlString.Create(anchor.ToString(TagRenderMode.Normal)); } } } Make sure you include the namespace in the View so method is available Example usage in Razor View (Leave area empty string if your not using areas) @Html.FALink("Index", "ControllerNameHere", "Back to List", "th-list", "btn btn-info", "btn_back_to_list", new {area=""}) * *While I use Font Awesome you could easily replace fa with glyphicon class to use the bootstrap glyphicons. *If no controller or Action is passed in, it uses # as the link location so it will play nice with drop down interaction
doc_23535115
After that, I cannot move the Panel back to the bottom. Dragging Terminal to the bottom has no effect. Closing and opening the Panel, restarting VS Code has no effect. My User Settings shows the default setting of "workbench.panel.defaultLocation": "bottom" and after restarting Visual Studio Code, the Panel is still on the right. How can I move it back to the bottom? A: There is an icon at the right end of the workbench to toggle the position. It will reposition to the bottom. As for the user settings it is the default setting. The position is different since you had previously changed it manually.
doc_23535116
First, Read files using Spark's fileStream val data = ssc.fileStream[LongWritable, Text, TextInputFormat]("s3://myfolder/",(t: org.apache.hadoop.fs.Path) => true, newFilesOnly = true, hadoopConf).map(_._2.toString()) For each RDD, check if any file has been read if (data.count() !=0) Write the string to a new HDFS directory data.coalesce(1).saveAsTextFile(sdir); Create a Dataframe reading from the above HDFS directory val loaddata = sqlContext.read.format("com.databricks.spark.xml").option("rowTag", "Trans").load(sdir) Do some processing on Dataframe and save as JSON loaddata.write.mode("append").json("s3://mybucket/somefolder") Somehow, I feel that the above approach is very inefficient and frankly quite school boyish. Is there a better solution? Any help would be greatly appreciated. A follow up question: How to manipulate fields (not Columns) in a dataframe? I have a vey complex nested xml and when I use the above described method, I am getting a Dataframe with 9 columns and 50 odd inner Struct arrays. That is fine except for the need to trim certain field names. Is there a way to achieve that without exploding the dataframe, as I need to construct the same structure again? A: If you use Spark 2.0 you may be able to make it work with structured streaming: val inputDF = spark.readStream.format("com.databricks.spark.xml") .option("rowTag", "Trans") .load(path)
doc_23535117
(The colors on the blob are rather meaningless since they cannot actually be displayed on a standard RGB monitor.) I'm now asking myself why this blob is bounded. Couldn't I just pick any point (x, y, z) in the blob and scale it with alpha*(x,y,z,), just like I would crank up a light source, and still be in the visible space? What exactly constitutes the upper boundary here? A: Context Definitions The outer surface depicted in your Wikipedia image represents the volume bounded by the Colour Matching Functions (CMFS). The CMFS are defined by the CIE as follows: tristimulus values of monochromatic stimuli of equal radiant power Another name for the equal radiant power illuminant in the CIE system is Equal Energy or E. The CIE XYZ tristimulus values are themselves defined by the CIE: amounts of the 3 reference colour stimuli, in a given trichromatic system, required to match the colour of the stimulus considered This is directly related to Colour Matching Experiments from Maxwell and Wright and Guild (1931) and probably out of the scope of this answer. Outer Surface Generation The outer surface is likely built using square wave spectral power distributions (SPDs), i.e. slices of the the Equal Energy illuminant. Bruce Lindbloom has an explanation on this page. The methodology is to convert the square wave SPDs with various bandwidth to CIE XYZ tristimulus values, this will form the outer surface. Assuming 5 bins, a first set of SPDs would be like that: 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 The second one: 1 1 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 1 1 1 0 0 0 1 The third: 1 1 1 0 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 1 1 0 0 1 etc... Here a Python snippet using Colour to generate the points for the outer surface: import colour import numpy as np class NearestNeighbourInterpolator(colour.KernelInterpolator): def __init__(self, *args, **kwargs): kwargs['kernel'] = colour.kernel_nearest_neighbour super(NearestNeighbourInterpolator, self).__init__(*args, **kwargs) def generate_square_waves(samples): square_waves = [] square_waves_basis = np.tril(np.ones((samples, samples)))[0:-1, :] for i in range(samples): square_waves.append(np.roll(square_waves_basis, i)) return np.vstack((np.zeros(samples), np.vstack(square_waves), np.ones(samples))) def XYZ_outer_surface(samples): XYZ = [] wavelengths = np.linspace(colour.DEFAULT_SPECTRAL_SHAPE.start, colour.DEFAULT_SPECTRAL_SHAPE.end, samples) for wave in generate_square_waves(samples): spd = colour.SpectralPowerDistribution( wave, wavelengths).align( colour.DEFAULT_SPECTRAL_SHAPE, interpolator=NearestNeighbourInterpolator) XYZ.append(colour.spectral_to_XYZ(spd)) return np.array(XYZ).reshape(len(XYZ), -1, 3) # 43 is picked as number of samples to have integer wavelengths. colour.write_image(XYZ_outer_surface(43), 'CIE_XYZ_outer_surface.exr') And the output:
doc_23535118
Ex: we can create Synchronized ArrayList by using Collections.synchronizedList() method. A: * *synchronizedList just wraps all methods with exclusive locks. That may be too strict for you. For example, you may very well want to allow any number of concurrent read operations to proceed at the same time (and only serialize writes). A specialized implementation can offer that. *synchronizedList is only thread-safe in the sense that its internal state does not get corrupted. That may not be enough for your application. For example if (list.isEmpty()) list.add(1); is not thread-safe even on a synchronized list. Nor is for (String x: list) giving you a snapshot iteration. Specialized implementations can add higher-level atomic operations. A: Why we need a thread-safe collection... You don't need them, because, as you have pointed out, we can create Synchronized ArrayList by using Collections.synchronizedList() method. So why does the library provide "concurrent" collection classes? It's because some of those classes can be implemented using thread-safe algorithms, and especially, non-blocking algorithms that may be more efficient or safer than using a mutex-protected algorithm. Of course, as others have pointed out, simply protecting a collection might not always be enough for your application. You might need a mutex anyway to protect some other data that is related to the collection. But, if the lock-free versions are helpful to you, then the good news is that they are there; and if they are not helpful, then the good news is that you don't have to use them.
doc_23535119
All works great when there is information in the reader to return but when the below select operates when there is no information to return, things don't work that great (i.e. the job hangs). Also, when the taskExecutor (and throttleLimit) steps are removed, the reader step runs to completion and all looks good even when there is no information to select. With this in mind, I am not sure what role multi-threading is playing in this (if at all) or if my reader method is deficient. In the below example, you will see that the select is pretty simple as it reads from one table, joins to another, and selects the rows with a certain status and within a given date range. Additional information if this helps... Springboot version 2.5.6, using java 17, and MySql for the database. Any suggestions or insight you are able to offer is appreciated as I am stumped at the moment. Thank you. @Configuration @EnableBatchProcessing public class BuildOpenStatusConfigurationJob { @Autowired JobBuilderFactory jobBuilderFactory; @Autowired StepBuilderFactory stepBuilderFactory; @Autowired DataSource dataSource; .... @Bean public TaskExecutor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(12); executor.setMaxPoolSize(16); executor.setQueueCapacity(12); executor.initialize(); return executor; } @Bean public Step createStsActivity() { return this.stepBuilderFactory.get("createStsActivity") .<StsActivity, StsActivity>chunk(1000) .reader(stsActivityItemReader(null, null)) .processor(stsActivityItemProcessor()) .writer(stsActivityItemWriter()) .taskExecutor(taskExecutorRows()) .throttleLimit(16) .listener(statusStepExecutionListener()) .build(); } @Bean @StepScope public JdbcPagingItemReader<StsActivity> stsActivityItemReader( @Value("#{jobParameters['lowerDateThreshold']}") String lowerDateThreshold, @Value("#{jobParameters['upperDateThreshold']}") String upperDateThreshold) { JdbcPagingItemReader<StsActivity> pagingItemReader = new JdbcPagingItemReader<>(); pagingItemReader.setDataSource(dataSource); pagingItemReader.setFetchSize(10000); pagingItemReader.setPageSize(10000); pagingItemReader.setRowMapper(new BeanPropertyRowMapper<>(StsActivity.class)); MySqlPagingQueryProvider mySqlPagingQueryProvider = new MySqlPagingQueryProvider(); mySqlPagingQueryProvider.setSelectClause(ta.statusId as statusId, tb.eventDate as maxEventDate, tb.id as maxEventId "); mySqlPagingQueryProvider.setFromClause("FROM TableA ta" + "join TableB tb on tb.statusId = ta.statusId"); mySqlPagingQueryProvider.setWhereClause("WHERE tb.status = 'OPEN' " + "and (date(tb.eventDate) >= date('" + lowerDateThreshold + "') " + "and date(tb.eventDate) < date('" + upperDateThreshold + "'))"); Map<String, Order> orderByKeys = new HashMap<>(); orderByKeys.put("rbpai.statusId", Order.ASCENDING); mySqlPagingQueryProvider.setSortKeys(orderByKeys); pagingItemReader.setQueryProvider(mySqlPagingQueryProvider); return pagingItemReader; } A: This has been fixed in v4.3.4: https://github.com/spring-projects/spring-batch/issues/3898. With Spring Boot 2.5.6, you get Spring Batch v4.3.3 which does not contain the fix. If you upgrade to a Boot version that brings Batch 4.3.4+, your issue should be fixed. Otherwise, it is probably a regression. In this case, please add a comment on Github with a minimal complete example that reproduces the issue and we will re-open it for investigation. Thank you upfront.
doc_23535120
constructor(private dialog: MatDialog){} openDialog(dialogData){ const dialogRef = this.dialog.open(DialogComponent, { data: dialogData } } and a DialogComponent to open the dialog with: let componentToRender constructor(@Inject(MAT_DIALOG_DATA) public dialogData){ this.componentToRender = dialogdata.componentToRender } and this template for it: <div class="dialog"> <ng-container></ng-container> // Here i want to dynamically render a given component </div> I want to give my dialogService with the dialogData a reference to an component that i want to be rendered inside my diaologComponent <ng-container> The result should be, that i can call my service with a reference to a component to open a dialog container that renders this given component inside the component.html's ng-container. For example like so: let dialogData = {} dialogData.componentToRender = COMPONENT_TO_RENDER_INSIDE_OF_DIALOG this.dialogService.openDialog(dialogData) The idea is to make something like a dialog-container where the body can be any component i want to render inside of the dialog-container I hope it is enough to write only the essential code, because I ask this question from another computer and could not copy paste the stuff I already have. thank you :) A: For now I kind of solved this with ViewContainerRef. I use the createComponent() method and give it the Component I want to render. Then I insert the create ref inside my ng-template. @ViewChild('container', {read: ViewContainerRef}) container!: ViewContainerRef const componentRef = this.viewContainerRef.createComponent(MY_COMPONENT_DYNAMICALLY_GIVEN) this.container.insert(componentRef.hostView) This works but also renders my component selector tag around my content. <my_inserted_component> <!-- I need to get rid of this :D --> <!-- contents of my_inserted_component --> </my_inserted_component> That sadly results into Layouting problems. So now I need to find out how to change my CSS or (better) how to get rid of the outer tag with the component selector name. EDIT: Also I should mention that I am on Angular 14
doc_23535121
In PostgreSQL what does hashed subplan mean? Below was my question. I want to know how the optimizer rewrote the query and how to read the execution plan in PostgreSQL. Here is the sample code. DROP TABLE ords; CREATE TABLE ords ( ORD_ID INT NOT NULL, ORD_PROD_ID VARCHAR(2) NOT NULL, ETC_CONTENT VARCHAR(100)); ALTER TABLE ords ADD CONSTRAINT ords_PK PRIMARY KEY(ORD_ID); CREATE INDEX ords_X01 ON ords(ORD_PROD_ID); INSERT INTO ords SELECT i ,chr(64+case when i <= 10 then i else 26 end) ,rpad('x',100,'x') FROM generate_series(1,10000) a(i); SELECT COUNT(*) FROM ords WHERE ORD_PROD_ID IN ('A','B','C'); DROP TABLE delivery; CREATE TABLE delivery ( ORD_ID INT NOT NULL, VEHICLE_ID VARCHAR(2) NOT NULL, ETC_REMARKS VARCHAR(100)); ALTER TABLE delivery ADD CONSTRAINT delivery_PK primary key (ORD_ID, VEHICLE_ID); CREATE INDEX delivery_X01 ON delivery(VEHICLE_ID); INSERT INTO delivery SELECT i , chr(88 + case when i <= 10 then mod(i,2) else 2 end) , rpad('x',100,'x') FROM generate_series(1,10000) a(i); analyze ords; analyze delivery; This is the SQL I am interested in. SELECT * FROM ords a WHERE ( EXISTS (SELECT 1 FROM delivery b WHERE a.ORD_ID = b.ORD_ID AND b.VEHICLE_ID IN ('X','Y') ) OR a.ORD_PROD_ID IN ('A','B','C') ); Here is the execution plan | Seq Scan on portal.ords a (actual time=0.038..2.027 rows=10 loops=1) | | Output: a.ord_id, a.ord_prod_id, a.etc_content | | Filter: ((alternatives: SubPlan 1 or hashed SubPlan 2) OR ((a.ord_prod_id)::text = ANY ('{A,B,C}'::text[]))) | | Rows Removed by Filter: 9990 | | Buffers: shared hit=181 | | SubPlan 1 | | -> Index Only Scan using delivery_pk on portal.delivery b (never executed) | | Index Cond: (b.ord_id = a.ord_id) | | Filter: ((b.vehicle_id)::text = ANY ('{X,Y}'::text[])) | | Heap Fetches: 0 | | SubPlan 2 | | -> Index Scan using delivery_x01 on portal.delivery b_1 (actual time=0.023..0.025 rows=10 loops=1) | | Output: b_1.ord_id | | Index Cond: ((b_1.vehicle_id)::text = ANY ('{X,Y}'::text[])) | | Buffers: shared hit=8 | | Planning: | | Buffers: shared hit=78 | | Planning Time: 0.302 ms | | Execution Time: 2.121 ms I don't know how the optimizer transformed the SQL. What is the final SQL the optimizer rewrote? I have only one EXISTS sub-query in the SQL above, why are there two sub-plans? What does "hashed Sub-Plan 2" mean? I would appreciate it if anyone share a little knowledge with me. Below is Laurenz Albe's answer. You have the misconception that the optimizer rewrites the SQL statement. That is not the case. Rewriting the query is the job of the query rewriter, which for example replaces views with their definition. The optimizer comes up with a sequence of execution steps to compute the result. It produces a plan, not an SQL statement. The optimizer plans two alternatives: either execute subplan 1 for each row found, or execute subplan 2 once (note that it is independent of a), build a hash table from the result and probe that hash for each row found in a. At execution time, PostgreSQL decides to use the latter strategy, that is why subplan 1 is never executed. Laurenz's answer enlightened me. But, I wondered what the final query rewritten by the query rewriter would be. Here is the rewritten query I thought the query rewriter would do. Am I right? What do you, readers of this question, think that the final rewritten query would be? ( SELECT * FROM ords a WHERE EXISTS (SELECT 1 FROM delivery b WHERE a.ORD_ID = B.ORD_ID AND b.VEHICLE_ID IN ('X','Y') OFFSET 0 --> the optimizer prevented subquery collapse. ) *alternative OR* SELECT a.* FROM ords a *(Semi Hash Join)* delivery b --> the optimizer used b as an build input WHERE a.ORD_ID = b.ORD_ID AND b.VEHICLE_ID IN ('X','Y') --> the optimzer used the delivery_x01 index. ) *filtered OR* SELECT * FROM ords a WHERE a.ORD_PROD_ID IN ('A','B','C') --> the optimizer cannot use the ords_x01 index due to the query transformation A: No. The subplans are not generated by the rewriter, but by the optimizer. As soon as the optimizer takes over, you leave the realm of SQL for good. The procedural execution steps it generates cannot be represented in the declarative SQL language.
doc_23535122
new DefaultHookupClient(HookupClientConfig(new URI("ws://localhost:8080/thesocket"))) { def receive = { case Disconnected(_) ⇒ println("The websocket to " + uri.toASCIIString + " disconnected.") case TextMessage(message) ⇒ { println("RECV: " + message) send("ECHO: " + message) } } connect() onSuccess { case Success ⇒ println("The websocket is connected.") case _ ⇒ } } in client.scala (https://github.com/backchatio/hookup/blob/2913794eb45d90d65713c9fd631b427abcca2d05/src/main/scala/io/backchat/hookup/client.scala) connect is defined as : def connect(protocols: String*): Future[OperationResult] = synchronized { … 257 delay { 258 connect(wireFormat.get.name) 259 } 260 } 261 } OperationResult is defined as (https://github.com/backchatio/hookup/blob/2913794eb45d90d65713c9fd631b427abcca2d05/src/main/scala/io/backchat/hookup/operation_result.scala) : sealed trait OperationResult { 11 /** 12 * Flag for the java api to indicate success … 30 def children: java.util.List[OperationResult] = List[OperationResult]().asJava 31 } Within chained methods connect() onSuccess { the connect() method appears to block until onSuccess is invoked ? Within the source of https://github.com/backchatio/hookup/ onSuccess does not appear to be defined so how does this method chain compile ? I would expect onSuccess to be defined within an abstract class similar to : abstract class DefaultHookupClient { def onSuccess(): Unit } A: Please install and use an IDE... scala is a PITA without an IDE, well very often even without an IDE too. The method onSuccess is defined in the Future trait in scala.concurent. Again, get an IDE. Otherwise you're for into a really, really frustraiting journey. A: The latest doc is more clear about the execution semantics. Since this method executes asynchronously... Not sure why you think it blocks. That would be evil. Note that onSuccess is deprecated in 2.12. Use onComplete instead, handling all cases, which is the same idea: "Run a side-effect when the future completes. Don't bother telling me, I don't even care."
doc_23535123
$('#students_targeted option:selected, #cc_students_targeted option:selected').each(function(){ myArray.push(data); }); A: This means that you have reached maximum stack size (in other words you have reached maximum limit of elements in array). UPD: You probably need to use this code: var myArray = []; $('#students_targeted option:selected, #cc_students_targeted option:selected').each(function(){ myArray.push($(this).val()); });
doc_23535124
CustomerId Scope Key Value 1 Customer SelfPasswordReset_MaxAttempts 5 2 Customer SelfPasswordReset_MaxAttempts 10 3 Customer SelfPasswordReset_MaxAttempts 20 NULL Platform PlatformGUID c20414f6-3bd2-4d37-ac74-152b0efdb582 ... assume we further have a CustomerParant table CustomerId ParentId Level 5 5 0 5 1 1 4 4 0 4 2 1 4 1 2 3 3 0 3 2 1 3 1 2 2 2 0 2 1 1 1 1 0 listing the parents of every customer and how much iterations you need to traverse through the tree to arrive there. means 3's parent is 2, 2's parent is 1 etc... Now i want to build a query that returns a result like this: CustomerId SelfPasswordReset_MaxAttemps PlatformGUID ... 5 5 c20414f6-3bd2-4d37-ac74-152b0efdb582 4 10 c20414f6-3bd2-4d37-ac74-152b0efdb582 3 20 c20414f6-3bd2-4d37-ac74-152b0efdb582 2 10 c20414f6-3bd2-4d37-ac74-152b0efdb582 1 5 c20414f6-3bd2-4d37-ac74-152b0efdb582 Special Note: Not every customer has his level defined. as you see i added customer 4 and 5 who don't have data a parameter defined of their own. they will inherit from their parent instead A: Generally SQL Coalesce function that returns a first defined which is non null value from argument list like Coalesce (NULL,1,2) // this will return 1 Coalesce (NULL,'abc','xyz') // this will return abc
doc_23535125
I am looking for an output similar to the output of date('e'). eg. "UTC", "GMT", or "Atlantic/Azores". I need to know this so that I may know the MySQL timezone. A: If you're on *nix, call the system's date using popen: popen("date +%Z"); A: If you're using a Linux/Unix based hosting platform, you could use the output of the date command with the "alphabetic time zone abbreviation" formatter as such: $systemTimeZone = system('date +%Z'); However, it should be noted that you shouldn't necessarily rely on the system's timezone and that you should instead use date_default_timezone_set (or the date.timezone php.ini setting) to set the required timezone. A: On linux/unix i use shell_exec("date +%Z"); A: These answers are not good. I don't know of a portable way to do it. For Linux here is one option: https://bojanz.wordpress.com/2014/03/11/detecting-the-system-timezone-php/ The date solution others are listing might not be accurate as the problem is in Linux and the date utility (gnuutils, gnulib) will inherit the same problem. If I set the timezone to Europe/Berlin and then ask date for the timezone it will give me CET. The way to get the timezone in Linux is like this: #include <time.h> #include <stdio.h> extern char *tzname[2]; extern long timezone; extern int daylight; void main() { tzset(); printf(tzname[0]); } The problem is the zone files don't include their name, only the list of parent timezones or something like that. CET is not the same as the Europe/Berlin zone. If I put CET in then dates can be calculated incorrectly. Sometimes this wont matter as some countries have been using one timezone for decades but occasionally it can matter. Using zdump here is a diff between CET and Europe/Berlin: > Fri Mar 31 23:06:31 1893 UTC = Fri Mar 31 23:59:59 1893 LMT isdst=0 gmtoff=3208 > Fri Mar 31 23:06:32 1893 UTC = Sat Apr 1 00:06:32 1893 CET isdst=0 gmtoff=3600 < Sun Sep 16 00:59:59 1945 UTC = Sun Sep 16 02:59:59 1945 CEST isdst=1 gmtoff=7200 < Sun Sep 16 01:00:00 1945 UTC = Sun Sep 16 02:00:00 1945 CET isdst=0 gmtoff=3600 < Sun Apr 3 00:59:59 1977 UTC = Sun Apr 3 01:59:59 1977 CET isdst=0 gmtoff=3600 ... SNIP about a dozen ... < Sun Sep 30 01:00:00 1979 UTC = Sun Sep 30 02:00:00 1979 CET isdst=0 gmtoff=3600 > Wed May 23 23:59:59 1945 UTC = Thu May 24 01:59:59 1945 CEST isdst=1 gmtoff=7200 ... SNIP couple dozen... > Sun Oct 2 01:00:00 1949 UTC = Sun Oct 2 02:00:00 1949 CET isdst=0 gmtoff=3600 Some of these might not even matter if you're using a unixtime but you can clearly see here that in the 70s some would. There are likely a few other timezones with much more recent changes that would break is using the result from tzset. For many this would be a fringe issue but if it does effect you the result likely wont be pleasant. I do not know what the convention is for windows or if there is the same problem. There is an exception to this problem. If your system timezone is a root one (like GMT, UTC, CET, etc) then I don't think this problem should occur. However your question is ultimately about MySQL: SELECT IF(@@global.time_zone = 'SYSTEM', @@global.system_time_zone, @@global.time_zone) AS time_zone; If it is set to SYSTEM it will also suffer the same fate as PHP and tzset. I checked a friend's server and there's often an hour's difference because MySQL converts Europe/London to GMT. GMT does not include BST which is a cause of many problems. Internally MySQL might be fine because it's still using /etc/localtime which will point to the right file even if MySQL is reporting the wrong name but if you take that wrong name and use it to load the timezone with something else then the two may not have the same timezone. Even if you tried to include DST it would not be a perfect fix. If you MySQL instance is using SYSTEM you may instead want to see if you can convert the dates from that to UTC (or the PHP date/time) which might be painful for performance. In theory you could try to brute force detection but I wouldn't advise it. You could also try setting the timezone in the session variable and MySQL may convert automatically but take care to be sure and always RTM (if that doesn't work use the source). A: You don't actually need to know what "timezone" MySQL is running on - you merely need to know the difference to UTC. To get that you can simply ask MySQL: SELECT TIMESTAMPDIFF(HOUR, UTC_TIMESTAMP, NOW()) Since the value of NOW() is based on the timezone MySQL is running on, that will read the difference between NOW() and the UTC time, in hours. You can then use that value to create a full timestamp like 2016-04-15T15:52:01+01:00 which can be used in DateTime::__construct(). You can then let PHP worry about the difference the timezones between the application and database servers by comparing DateTime objects... and that should work on all systems. A: you can get timezone of your server by this. echo date_default_timezone_get();
doc_23535126
This is the current function that is being executed. function boom($data) { $number = preg_match_all("/(<!-- ([\w]+):start -->)(.*?)(<!-- \\2:stop -->)/", $data, $matches, PREG_SET_ORDER); if ($number == 0) $data['content'] = $data; //else unset($data); foreach ($matches as $item) print_r($item)."\n\n"; // $data[$item[2]] = explode("<!-- breaker -->", $item[3]); die("<code>".str_replace("\n", "<br />", htmlentities($data))."</code>"); return $data; } A: If your text goes on multiple lines, just add the /s modifier to your pattern (to make . match newlines).
doc_23535127
angular.module('bcpBackOffice').controller('assetsCtrl', ['$scope', '$state', '$log', '$filter', '$compile', 'ApplicationConfig', '$mdDialog', 'RoomManagerFactory', The error is showing for the variable authDetails.access_token in my controller. Here is my controller 'use strict'; /** * @ngdoc function * @name bcpBackOffice.controller:assetsCtrl * @description * # assetsCtrl * Controller of the bcpBackOffice */ angular.module('bcpBackOffice').controller('assetsCtrl', ['$scope', '$state', '$log', '$filter', '$compile', 'ApplicationConfig', '$mdDialog', 'RoomManagerFactory', 'RoomService', 'DataService', 'RoomServicesVO', 'RoomPricingVO','BcpBase64ImageDataEncodedMultipartFileVO','ImagePath','RoomVO','ImageFileExtensionPattern', assetsCtrl]); function assetsCtrl($scope, $state, $log, $filter, $compile, ApplicationConfig, $mdDialog, RoomManagerFactory, RoomService, DataService, RoomServicesVO, RoomPricingVO, BcpBase64ImageDataEncodedMultipartFileVO, ImagePath, RoomVO, ImageFileExtensionPattern) { // Variable definition var authDetails = ApplicationConfig.loggedInUserData.authDetails; var accessToken = authDetails.access_token; $scope.selectedTabIndex = 0; $scope.masterData = ""; $scope.roomAttributes = []; $scope.roomServiceRateUnits = []; $scope.roomServices = []; $scope.dayHours = null; $scope.propertyId = ApplicationConfig.loggedInUserData.propertyId; $scope.rooms = []; $scope.populateMasterAttributeData = []; $scope.attributeValue = []; $scope.assetServices = new RoomServicesVO(); $scope.editAssetServicesFlag = false; $scope.editAssetServicesIndex = ''; $scope.imageRoomPicturesPath = ImagePath.RoomImagePicturePath; $scope.imageFloorPlanPath = ImagePath.RoomImageFloorPlanPath; $scope.validateUploadedFile = validateUploadedFile; $scope.assetsFromDateContainer = {}; $scope.weekdaySlot = []; var weekdayPricingVO = new RoomPricingVO(); weekdayPricingVO.slotType = 'WEEKDAY'; $scope.weekdaySlot.push(weekdayPricingVO); $scope.weekendSlot = []; var weekendPricingVO = new RoomPricingVO(); weekendPricingVO.slotType = 'WEEKEND'; $scope.weekendSlot.push(weekendPricingVO); // Function definition $scope.increaseCounter = increaseCounter; $scope.decreaseCounter = decreaseCounter; $scope.loadDataForAssets = loadDataForAssets; $scope.addWeekdaySlot = addWeekdaySlot; $scope.addWeekendSlot = addWeekendSlot; $scope.deleteWeekdaySlot = deleteWeekdaySlot; $scope.deleteWeekendSlot = deleteWeekendSlot; $scope.addInclusiveServices = addInclusiveServices; $scope.closePopup = closePopup; $scope.saveInclusiveServices = saveInclusiveServices; $scope.getAssetsMasterData = getAssetsMasterData; $scope.switchToAssetsServiceTab = switchToAssetsServiceTab; $scope.saveRoomData = saveRoomData; $scope.getDayHours = getDayHours; $scope.addAdditionalServicesToRoom = addAdditionalServicesToRoom; $scope.populateAttributeData = populateAttributeData; $scope.getAllAssetsOfProperty = getAllAssetsOfProperty; $scope.setWorkingHoursToTime = setWorkingHoursToTime; $scope.disabledToDate = disabledToDate; $scope.validatePricingSlot = validatePricingSlot; $scope.editAssetService = editAssetService; $scope.deleteAssetService = deleteAssetService; $scope.reloadAssetServiceVO = reloadAssetServiceVO; $scope.uploadFloorPlan = uploadFloorPlan; $scope.uploadRoomImage = uploadRoomImage; $scope.imagesDataParser = imagesDataParser; /** * RoomVO Object Contains Data. */ $scope.roomVO = RoomManagerFactory.retrieveInstance(); $scope.roomServicesVO = new RoomServicesVO(); $scope.roomPricingVO = new RoomPricingVO(); /** * Save Room Data.(create new Asset.) */ function saveRoomData() { $scope.roomVO.availableFromDate = $filter('date')(new Date($scope.assetsFromDateContainer.availableFromDate), "yyyy-MM-dd HH:mm:ss"); $log.debug($scope.roomVO); if (typeof $scope.roomVO.roomType == "string" || $scope.roomVO.roomType instanceof String) { $scope.roomVO.roomType = JSON.parse($scope.roomVO.roomType); } addWeekdayAndWeekendSlotToAsset(); RoomService.createRoomOfProperty($scope.roomVO, $scope.propertyId, accessToken).then(function (response) { $scope.rooms.push(response.data); $scope.roomVO = new RoomVO(); $state.go('template.' + ApplicationConfig.urlBasedOnUserRole + '.assets.show-assets'); },function(error){ $log.error(error); }); } /** * Add Additional Services to Room. */ function addAdditionalServicesToRoom() { $scope.roomServicesVO = $scope.assetServices; if($scope.editAssetServicesFlag == true){ $scope.roomVO.editRoomServices($scope.editAssetServicesIndex,$scope.roomServicesVO); } else { $scope.roomVO.addRoomServices($scope.roomServicesVO); } $scope.editAssetServicesFlag = false; $scope.assetServices = new RoomServicesVO(); return true; } function getDayHours() { DataService.getDayHoursFromJson().then(function (response) { $scope.dayHours = response.data; }); } function setWorkingHoursToTime(fromTime) { angular.forEach($scope.dayHours, function (dayHour, index) { if (fromTime == dayHour.value) { $scope.totimeIndex = index; } }); } function reloadAssetServiceVO(){ $scope.editAssetServicesFlag = false; $scope.assetServices = new RoomServicesVO(); } function editAssetService(index){ $scope.editAssetServicesFlag = true; $scope.editAssetServicesIndex = index; $scope.roomServicesVO = $scope.roomVO.roomServices[index]; angular.copy($scope.roomServicesVO, $scope.assetServices); } function deleteAssetService(index){ $scope.roomVO.roomServices.splice(index,1); } function disabledToDate(fromTime, index, dayType) { var selectOptions; if (dayType == 'weekday') { selectOptions = document.getElementsByClassName('toTimeSelectWeekday_' + index)[0].options; } if (dayType == 'weekend') { selectOptions = document.getElementsByClassName('toTimeSelectWeekend_' + index)[0].options; } if (selectOptions.length > 0) { angular.forEach(selectOptions, function (selectOption) { selectOption.removeAttribute('disabled'); var value = $filter('date')(selectOption.value, 'HH:mm:ss'); var fromTimeFilter = $filter('date')(fromTime, 'HH:mm:ss'); console.log(value-fromTimeFilter); if (value <= fromTimeFilter) { selectOption.setAttribute('disabled', true); } }); } } /** * get master data while adding new assets */ function getAssetsMasterData() { switchToAssetsServiceTab(0); var masterDataPromise = RoomService.getMasterDataOfRoom(accessToken); masterDataPromise.then(function (promise) { $scope.masterData = promise.data; //$scope.roomAttributes = $scope.masterData.roomAttributes; angular.copy($scope.masterData.roomAttributes, $scope.roomAttributes); angular.copy($scope.masterData.roomServiceRateUnits, $scope.roomServiceRateUnits); angular.copy($scope.masterData.roomServices, $scope.roomServices); $scope.attributeValue = []; populateAttributeData(); $log.debug($scope.masterData.roomAttributes); $state.go('template.' + ApplicationConfig.urlBasedOnUserRole + '.assets.add-asset'); }); } function getAllAssetsOfProperty() { RoomService.getAllRoomsOfProperty(accessToken, $scope.propertyId).then(function (response) { $scope.rooms = response.data; }); } function populateAttributeData() { $scope.populateMasterAttributeData = []; angular.forEach($scope.roomAttributes, function (attributeObject) { if (typeof attributeObject.value == "string" || attributeObject.value instanceof String) { var parsedAttributeValue = JSON.parse(attributeObject.value); } else { var parsedAttributeValue = attributeObject.value; } angular.forEach(parsedAttributeValue, function (attribute) { var tempAttributeObject = {}; tempAttributeObject.id = attributeObject.id; tempAttributeObject.label = attribute; tempAttributeObject.checked = false; $scope.populateMasterAttributeData.push(tempAttributeObject); }); }, $scope.populateMasterAttributeData); } /** * load the data after loading the page for Assets Page */ function loadDataForAssets() { $scope.assetsFromDateContainer.availableFromDate = $filter('date')(new Date(), "yyyy-MM-dd HH:mm:ss"); $scope.roomVO.guestCapacity = 1; $scope.roomVO.minimumBookingHours = 1; } /** * Increase counter value on click on item/element * @param value */ function increaseCounter(value) { var countEle = document.getElementById(value); countEle.value = +countEle.value + 1; if (value == "countFld") { $scope.roomVO.guestCapacity = countEle.value; } else { if (value == "countFld2") { $scope.roomVO.minimumBookingHours = countEle.value; } } } /** * Decrease counter value on click on item/element * @param value */ function decreaseCounter(value) { var countEle = document.getElementById(value); if (countEle.value > 1) { countEle.value = countEle.value - 1; if (value == "countFld") { $scope.roomVO.guestCapacity = countEle.value; } else { if (value == "countFld2") { $scope.roomVO.minimumBookingHours = countEle.value; } } } else { } } /** * add time slot for weekday */ function addWeekdaySlot() { var roomPricingVO = new RoomPricingVO(); roomPricingVO.slotType = 'WEEKDAY'; $scope.weekdaySlot.push(roomPricingVO); var currentIndex = ($scope.weekdaySlot.length - 1); var weekdaytbl = document.getElementById("weekdaySlotsTbl"); var lasti = weekdaytbl.rows.length; var row = weekdaytbl.insertRow(lasti); var cell1 = row.insertCell(0); cell1.setAttribute("style", "width:80px;"); var cell2 = row.insertCell(1); cell2.setAttribute("style", "width:80px;"); var cell3 = row.insertCell(2); var cell4 = row.insertCell(3); $log.debug($scope.weekdaySlot.length - 1); var formTimeModel = "weekdaySlot[" + currentIndex + "].fromTime"; var toTimeModel = "weekdaySlot[" + currentIndex + "].toTime"; var rateModel = "weekdaySlot[" + currentIndex + "].rate"; cell1.innerHTML = document.getElementById("weekdays_fromTime").innerHTML; cell1.getElementsByTagName("select")[0].setAttribute("ng-model", formTimeModel); var disabledToDateFunction = 'disabledToDate(weekdaySlot[' + currentIndex + '].fromTime,' + currentIndex + ',\'weekday\')'; cell1.getElementsByTagName("select")[0].setAttribute("ng-change", disabledToDateFunction); cell2.innerHTML = document.getElementById("weekdays_toTime").innerHTML; cell2.getElementsByTagName("select")[0].setAttribute("ng-model", toTimeModel); cell2.getElementsByTagName("select")[0].setAttribute("class", cell2.getElementsByTagName("select")[0].getAttribute("class") + ' toTimeSelectWeekday_' + currentIndex); cell3.innerHTML = document.getElementById("weekdays_price").innerHTML; cell3.getElementsByTagName("input")[0].setAttribute("ng-model", rateModel); var deleteFunction = 'deleteWeekdaySlot($event,' + currentIndex + ')'; cell4.innerHTML = "<a href='javascript:;' data-ng-click = " + deleteFunction + "><img src='assets/images/icons/close_icon.png'></a>"; disabledToDate($scope.weekdaySlot[currentIndex].fromTime, currentIndex,'weekday'); $compile($(row).contents())($scope); } /** * add time slot for weekend */ function addWeekendSlot() { var roomPricingVO = new RoomPricingVO(); roomPricingVO.slotType = 'WEEKEND'; $scope.weekendSlot.push(roomPricingVO); var currentIndex = ($scope.weekendSlot.length - 1); var weekdaytbl = document.getElementById("weekendSlotsTbl"); var lasti = weekdaytbl.rows.length; var row = weekdaytbl.insertRow(lasti); var cell1 = row.insertCell(0); cell1.setAttribute("style", "width:80px;"); var cell2 = row.insertCell(1); cell2.setAttribute("style", "width:80px;"); var cell3 = row.insertCell(2); var cell4 = row.insertCell(3); var formTimeModel = "weekendSlot[" + currentIndex + "].fromTime"; var toTimeModel = "weekendSlot[" + currentIndex + "].toTime"; var rateModel = "weekendSlot[" + currentIndex + "].rate"; cell1.innerHTML = document.getElementById("weekdays_fromTime").innerHTML; cell1.getElementsByTagName("select")[0].setAttribute("ng-model", formTimeModel); var disabledToDateFunction = 'disabledToDate(weekendSlot[' + currentIndex + '].fromTime,' + currentIndex + ',\'weekend\')'; cell1.getElementsByTagName("select")[0].setAttribute("ng-change", disabledToDateFunction); cell2.innerHTML = document.getElementById("weekdays_toTime").innerHTML; cell2.getElementsByTagName("select")[0].setAttribute("ng-model", toTimeModel); cell2.getElementsByTagName("select")[0].setAttribute("class", cell2.getElementsByTagName("select")[0].getAttribute("class") + ' toTimeSelectWeekend_' + currentIndex); cell3.innerHTML = document.getElementById("weekdays_price").innerHTML; cell3.getElementsByTagName("input")[0].setAttribute("ng-model", rateModel); var deleteFunction = 'deleteWeekendSlot($event,' + currentIndex + ')'; cell4.innerHTML = "<a href='javascript:;' data-ng-click = " + deleteFunction + "><img src='assets/images/icons/close_icon.png'></a>"; disabledToDate($scope.weekendSlot[currentIndex].fromTime, currentIndex, 'weekend'); $compile($(row).contents())($scope); } function addWeekdayAndWeekendSlotToAsset() { var mergedWeekdayWeekendPricing = []; mergedWeekdayWeekendPricing = $scope.weekdaySlot.concat($scope.weekendSlot); $scope.roomVO.roomPricings = mergedWeekdayWeekendPricing; } /** * delete weekday slots * @param $event */ function deleteWeekdaySlot($event, currentIndex) { var index = $event.currentTarget.parentNode.parentNode.rowIndex; document.getElementById("weekdaySlotsTbl").deleteRow(index); delete($scope.weekdaySlot[currentIndex]); } /** * delete weekend slots * @param $event */ function deleteWeekendSlot($event, currentIndex) { var index = $event.currentTarget.parentNode.parentNode.rowIndex; document.getElementById("weekendSlotsTbl").deleteRow(index); delete($scope.weekendSlot[currentIndex]); } /** * add Inclusive Services for Assets popup */ function addInclusiveServices() { $mdDialog.show({ templateUrl: 'app/templates/views/' + ApplicationConfig.urlBasedOnUserRole + '/fragments/add-inclusive-assets-services.html', scope: $scope, preserveScope: true, overlay: true, clickOutsideToClose: false, parent:angular.element('#addInclusiveServices') }); } /** * Save added inclusive services for Assets */ function saveInclusiveServices() { addAttributeToAsset(); $mdDialog.hide(); } function addAttributeToAsset() { $scope.attributeValue = []; $scope.roomVO.roomAttributes = $scope.masterData.roomAttributes; $log.debug($scope.populateMasterAttributeData); if (typeof $scope.roomVO.roomAttributes == "string" || $scope.roomVO.roomAttributes instanceof String) { $scope.roomVO.roomAttributes = JSON.parse($scope.roomVO.roomAttributes); } if ($scope.roomVO.roomAttributes.length != 0) { angular.forEach($scope.roomVO.roomAttributes, function (roomAttribute) { var filteredSelectedAttr = $filter('filter')($scope.populateMasterAttributeData, function (populateMasterAttributeData) { return ((roomAttribute.id == populateMasterAttributeData.id)&&(populateMasterAttributeData.checked == true)); }); var tempAttributeValueArray = []; angular.forEach(filteredSelectedAttr, function (filteredAttributeLabel) { tempAttributeValueArray.push(filteredAttributeLabel.label); $scope.attributeValue.push(filteredAttributeLabel.label); }); roomAttribute.value = tempAttributeValueArray; }); } $scope.roomVO.roomAttributes = JSON.stringify($scope.roomVO.roomAttributes); } /** * close the popup window */ function closePopup() { $mdDialog.hide(); } /** * after adding new asset switch to next tab * to add assets service * @param index */ function switchToAssetsServiceTab(index) { $scope.selectedTabIndex = index; } function validatePricingSlot(){ createDummyTimeSlots(); //var sortByStartTime = $filter('orderBy')($scope.weekdaySlot, expression, comparator); return false; } function createDummyTimeSlots(){ var listOfHours = $filter('getValueArrayOfKey')($scope.dayHours)('value'); var operableHours = $filter('filter')(listOfHours, function(hour){ return (hour >= $scope.roomVO.operableHoursStartTime && hour <= $scope.roomVO.operableHoursEndTime); }); var sortedByFromTimeAndToTime = $filter('orderBy')($scope.weekdaySlot, ['fromTime', 'toTime']); angular.forEach(sortedByFromTimeAndToTime, function(sortedObject){ angular.forEach(operableHours, function(hour, index){ if(hour >= sortedObject.fromTime && hour <= sortedObject.toTime){ operableHours.splice(index, 1); } }); }); console.log("+++++++++++++++++operableHours++++++++++++++++++++"); console.log(operableHours); } function uploadFloorPlan(files) { if(validateUploadedFile()) { var roomFloorPlanVO = new BcpBase64ImageDataEncodedMultipartFileVO().getRoomFloorPlanVO(); roomFloorPlanVO.originalFileName = files[0].name; roomFloorPlanVO.size = files[0].size; roomFloorPlanVO.contentType = files[0].type; if (files && files[0]) { setImageBase64ToBase64VO(roomFloorPlanVO, files[0]); } $scope.roomVO.floorPlanImageData = roomFloorPlanVO; $log.debug($scope.roomVO); } } function uploadRoomImage(files) { if (validateUploadedFile()) { console.log(files); angular.forEach(files, function (file) { var roomImageVO = new BcpBase64ImageDataEncodedMultipartFileVO().getRoomImageVO(); roomImageVO.originalFileName = file.name; roomImageVO.size = file.size; roomImageVO.contentType = file.type; if (files && files[0]) { setImageBase64ToBase64VO(roomImageVO, file); } $scope.roomVO.addRoomImageData(roomImageVO); }); $log.debug($scope.roomVO); } } function setImageBase64ToBase64VO(roomFloorPlanAndImageDataVO, file) { var FR = new FileReader(); FR.onload = function (e) { roomFloorPlanAndImageDataVO.base64EncodedImageData = e.target.result; }; FR.readAsDataURL(file); } function imagesDataParser(roomImages, index){ if (typeof roomImages == "string" || roomImages instanceof String) { $scope.rooms[index].images = JSON.parse(roomImages); } } function validateUploadedFile() { var allowedFiles = [".jpg", ".jpeg", ".gif", ".png"]; var fileUpload = document.getElementById("myfile"); var myPicture = document.getElementById("myPicture"); var lblError = document.getElementById("lblError"); var errorMyPicture = document.getElementById("errorMyPicture"); if (fileUpload.files.length > 0) { if (!(ImageFileExtensionPattern).test(fileUpload.value.toLowerCase())) { lblError.innerHTML = "Please upload files having extensions: <b>" + allowedFiles.join(', ') + "</b> only."; return false; } } if (myPicture.files.length > 0) { var flag = false; for(var readFile = 0; readFile < myPicture.files.length;readFile ++) { if (!(ImageFileExtensionPattern).test(myPicture.files[readFile].name.toLowerCase())) { errorMyPicture.innerHTML = "Please upload files having extensions: <b>" + allowedFiles.join(', ') + "</b> only."; flag = true; break; } } if(flag){return false;} if (myPicture.files.length > 5) { errorMyPicture.innerHTML = "Oops!! You can upload max 5 files"; return false; } } lblError.innerHTML = ""; errorMyPicture.innerHTML = ""; return true; } // called function on load $scope.getDayHours(); $scope.getAllAssetsOfProperty(); } **Here is my test case :** 'use strict'; describe('Controller: assetsCtrl', function () { beforeEach(module('bcpBackOffice')); beforeEach(module('BcpUIServices')); beforeEach(module('ui.router')); var assetsCtrl, state, log, filter, compile, ApplicationConfig, mdDialog, RoomManagerFactory, RoomService, DataService, RoomServicesVO, RoomPricingVO, $rootScope, scope, $httpBackend; //Mock Data var mockDayHours= [{ "label": "06:00 AM", "value": "06:00:00" }, { "label": "07:00 AM", "value": "07:00:00" }]; beforeEach(inject(function(_$rootScope_, $controller, _$state_, _$log_, _$filter_, _$compile_, _ApplicationConfig_, _$mdDialog_, _RoomManagerFactory_, _RoomService_, _DataService_, _RoomServicesVO_, _RoomPricingVO_, _$httpBackend_){ $rootScope = _$rootScope_; scope = $rootScope.$new(); state = _$state_; log = _$log_; filter = _$filter_; compile = _$compile_; ApplicationConfig = _ApplicationConfig_; mdDialog = _$mdDialog_; RoomManagerFactory = _RoomManagerFactory_; RoomService = _RoomService_; DataService = _DataService_; RoomServicesVO = _RoomServicesVO_; RoomPricingVO = _RoomPricingVO_; $httpBackend = _$httpBackend_; assetsCtrl = $controller('assetsCtrl', { $scope:scope, $state:state, $log:log, $filter:filter, $compile:compile, ApplicationConfig:ApplicationConfig, $mdDialog:mdDialog, RoomManagerFactory:RoomManagerFactory, RoomService:RoomService, DataService:DataService, RoomServicesVO:RoomServicesVO, RoomPricingVO:RoomPricingVO }); })); beforeEach(function(){ ApplicationConfig.loggedInUserData.authDetails = { access_token: "0e45e276-89ff-403f-8e02-7f85a41c2d26", token_type: "bearer", refresh_token: "ce872f46-5877-4266-9a0e-5199b63ac247", expires_in: 10430, scope: "read write" }; $httpBackend.whenGET("app/mock_data/dayHours.json").respond(mockDayHours); }); beforeEach(function(){ $rootScope.$digest(); }); it('should get day hours', function(){ scope.getDayHours(); $httpBackend.flush(); expect(scope.dayHours).toBe(mockDayHours); });
doc_23535128
export var Auth = (function () { var Login = async function(username, password) { //Async login code for interacting with the API }; return { Login: Login } }); And this object is imported inside another file, login.js: import * as API from './api'; export var LoginRequestHandler = function() { //processess user input, then calls: try { await API.Auth().Login(username, password); } catch(e) { throw new Error(e); } This is my jest test: import * as API from '../api'; import * as User from '../user'; jest.mock('../api'); const spy = jest.spyOn(API.Auth(), 'Login'); User.LoginRequestHandler().then(() => { expect(spy).toHaveBeenLastCalledWith('theUsername', 'thePassword'); }).catch(error => console.log(error)); This is my mock file, __mock__/api.js: export var Auth = (function () { var Login = async function(username, password) { return Promise.resolve(true); }; return { Login: Login } }); I retrieve theUsername and thePassword through document.getElementId() in the LoginRequestHandler and create my own DOM for the test above. Adding console.log(username) in the LoginRequestHandler reveals that it is being called and is able to get the right values. Furthermore, adding a console.log(username) in API.Auth().Login also reveals that it is getting the right values as well. However, when I look at my test logs, I see: Number of calls: 0 for the mock function and the test results in errors. I assume that I am trying to spy on the wrong function, and is there anyway that I can fix this? A: Every time you call API.Auth(), it will return a new object which has a Login method. So, the object created in LoginRequestHandler function and created by jest.spyOn(API.Auth(), 'Login') statement in your test case are different. The spy is only added to the later one. The Login method in LoginRequestHandler function is not spied. So, here I am going to use jest.mock() to mock the api.js module without putting mocked object to __mocks__ directory. E.g. api.js: export var Auth = function () { var Login = async function (username, password) {}; return { Login: Login, }; }; user.js: import * as API from './api'; export var LoginRequestHandler = async function () { const username = 'theUsername'; const password = 'thePassword'; try { await API.Auth().Login(username, password); } catch (e) { throw new Error(e); } }; user.test.js: import * as API from './api'; import * as User from './user'; jest.mock('./api', () => { const auth = { Login: jest.fn() }; return { Auth: jest.fn(() => auth), }; }); describe('61643983', () => { afterEach(() => { jest.clearAllMocks(); }); it('should login', () => { expect.assertions(2); return User.LoginRequestHandler().then(() => { expect(API.Auth).toBeCalledTimes(1); expect(API.Auth().Login).toHaveBeenLastCalledWith('theUsername', 'thePassword'); }); }); it('should throw error', () => { expect.assertions(4); const mError = new Error('user not found'); API.Auth().Login.mockRejectedValueOnce(mError); return User.LoginRequestHandler().catch((e) => { expect(API.Auth).toBeCalled(); expect(API.Auth().Login).toHaveBeenLastCalledWith('theUsername', 'thePassword'); expect(e).toBeInstanceOf(Error); expect(e.message).toMatch(/user not found/); }); }); }); unit test results with 100% coverage: PASS stackoverflow/61643983/user.test.js (11.507s) 61643983 ✓ should login (5ms) ✓ should throw error (3ms) ----------|---------|----------|---------|---------|------------------- File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s ----------|---------|----------|---------|---------|------------------- All files | 100 | 100 | 100 | 100 | user.js | 100 | 100 | 100 | 100 | ----------|---------|----------|---------|---------|------------------- Test Suites: 1 passed, 1 total Tests: 2 passed, 2 total Snapshots: 0 total Time: 13.023s source code: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61643983
doc_23535129
From the code below, I search in the map the specific coordinate (coord) and I display with my custom annotation. 1) I'm try to increase the size of the UIimage because to small (see the picture attached)and change the color, any idea how? 2)in the map after the app start it display only the icon, after I tap on the icon the annotation appear, any idea how to display immediately my annotation without tapping? 3)now in the annotation I manage to display title and subtitle, how to display also the coordinate struct MapView: UIViewRepresentable { let Mm : MapManager let coord = CLLocationCoordinate2D(latitude: 52.28792, longitude: 4.73415327) class Coordinator: NSObject, MKMapViewDelegate { var parent : MapView init(_ parent: MapView) { self.parent = parent } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "TESTING NOTE") annotationView.canShowCallout = true annotationView.image = UIImage(systemName: "location.circle") return annotationView } } func makeCoordinator() -> Coordinator { Coordinator(self) } func makeUIView(context: Context) -> MKMapView { let view = MKMapView(frame: .zero) Mm.georeverseCoordinate(coord) { (pin) in if let pinOK = pin { view.removeAnnotation(pinOK) view.mapType = MKMapType.satellite let span = MKCoordinateSpan(latitudeDelta: 0.04, longitudeDelta: 0.04) let region = MKCoordinateRegion(center: self.coord, span: span) view.setRegion(region, animated: true) view.delegate = context.coordinator view.addAnnotation(pinOK) } } return view } func updateUIView(_ view: MKMapView, context: Context) { } } Map manager class MapManager: NSObject, CLLocationManagerDelegate { static let shared = MapManager() func georeverseCoordinate(_ coord: CLLocationCoordinate2D , closure: @escaping (Pin?) -> Void) { let location = CLLocation(latitude: coord.latitude, longitude: coord.longitude) let geocoder = CLGeocoder() geocoder.reverseGeocodeLocation(location) { (arrayResponse, error) in if let errorTest = error { debugPrint(errorTest.localizedDescription) closure(nil) return } if let arrayPins = arrayResponse { if let valorePinArray = arrayPins.first { debugPrint(valorePinArray.locality!) debugPrint(valorePinArray.isoCountryCode!) let pin = Pin(title: valorePinArray.locality!, subtitle: valorePinArray.isoCountryCode!, coordinate: valorePinArray.location!.coordinate) closure(pin) } else { closure(nil) } } else { closure(nil) } } } } Pin Model class Pin:NSObject, MKAnnotation { var title : String? var subtitle : String? var coordinate : CLLocationCoordinate2D var color: UIColor? init(title: String?, subtitle: String?, coordinate: CLLocationCoordinate2D) { self.title = title self.subtitle = subtitle self.coordinate = coordinate } } A: 1) - There seems to be a bug that makes it difficult to change the colour of SF Symbols with tintColor and a specific rendering mode but there is a workaround that also allows an easy way to change the size of the symbol. In mapView:viewFor annotation add the following: annotationView.canShowCallout = true annotationView.image = UIImage(systemName: "location.circle")?.withTintColor(.systemGreen, renderingMode: .alwaysOriginal) let size = CGSize(width: 40, height: 40) annotationView.image = UIGraphicsImageRenderer(size:size).image { _ in annotationView.image!.draw(in:CGRect(origin:.zero, size:size)) } 2) - To show the callout as soon as the annotation is added to the map, use selectAnnotation. view.addAnnotation(pinOK) view.selectAnnotation(pinOK, animated: true) 3) - The coordinate is available when your annotation is being constructed so you can simply change the init in the Pin class: init(title: String?, subtitle: String?, coordinate: CLLocationCoordinate2D) { self.coordinate = coordinate self.title = "\(coordinate.latitude) : \(coordinate.longitude)" self.subtitle = subtitle }
doc_23535130
My actual code list the entire database registrys and let's me edit them, but to go to the one i desire i have to go over the huge list it displays, this is my code: def computer_update_view(request, pk, template_name='computer/computer_form.html'): serial = get_object_or_404(Computer, pk=pk) form = ComputerForm(request.POST or None, instance=serial) context = { 'form':form } if form.is_valid(): form.save() return redirect('computer:pc_list') return render(request, template_name, context) {% extends "base.html" %} {% block content %} <h2 xmlns="http://www.w3.org/1999/html"><a href="{% url 'computer:pc_list' %}">Network Admin</a></h2> <ul> <p> <button type="button"><a href="{% url 'computer:computer_new' %}">Add New</a></button></p> {% for serie in object %} <li>{{ serie.serial }}. {{ serie.name }} - ({{ serie.user_name }}) <a href="{% url 'computer:computer_edit' serie.serial %}">edit / </a> </li> {% endfor %} </ul> {% endblock %} So what i want to do is let the user input fox example: User inputs serial "212125" (note that serial is the pk field in the database) and then only that registry shows up to be edited. How could i do this? A: In forms.py edit which fields show up in the form. This can be done with class Meta class Meta: model = #model name fields = ["""field names go here that will be displayed"""]
doc_23535131
Each blog is added to the database through an api call using JSONP. (The JSONP callback function name is required in the request.) So when the user clicks the Add Blog button, the AddBlog function is called - this does some client side validation and sends the ajax request. It also adds the ajax request to an array. The callback function cbAddBlog does some more validation based on any errors returned from the server. So when all of the blogs have been added I want to show a message letting the user know the blog(s) have been saved and to reset the form. The problem is that the callback functions (cbAddBlog) are executed after the code in $.when.. Does $.when work with JSONP when you have a defined callback function? Or is there something else wrong with my code? Would I need to implement Deferred myself in the callback function for this to work? var errorState = false, contributorId = '23', addBlogCalls = []; $("#btnAddBlog").click(function (e) { $('#add_contributor section.blog').each(function () { //call addBlog for each of the users blogs addBlog(contributorId, $(this).attr('id')); }); $.when.apply($, addBlogCalls).done(function () { console.log("WHEN + errorState: " + errorState); //This is output to console BEFORE the line in the cbAddBlog callback function }); e.preventDefault(); }); addBlog : function (contributorId, blogSection) { //client side validation - following is excecuted if there are no errors addBlogCalls.push( $.ajax({ url : (apiRoot + "f=jsonp").trim(), dataType : 'jsonp', jsonp : false, jsonpCallback : "cbAddBlog", fail: function (e) { console.log("error function"); console.log(e.message); }, done: function (e) { console.log("done function"); console.log(e.message); } }) ); console.log("Added to addBlogCalls array"); console.log(addBlogCalls); } cbAddBlog : function (data) { console.log("cbAddBlog data.result: " + data.result); //Printed to console AFTER line from $.when ?? //code to check if there are any errors returned from server and display them to user } Output from console: Added to addBlogCalls array [Object { readyState=1, setRequestHeader=function(), getAllResponseHeaders=function(), more...}] Added to addBlogCalls array [Object { readyState=1, setRequestHeader=function(), getAllResponseHeaders=function(), more...}, Object { readyState=1, setRequestHeader=function(), getAllResponseHeaders=function(), more...}] WHEN + CD.config.errorState: false cbAddBlog data.result: 1 cbAddBlog data.result: 1 I see the same issue (callback being executed AFTER $.when even when there is only one blog.. A: $.when() does not accept an array as an argument, it requires one or more promises as individual arguments. So, if you have an array, you need to use .apply() to get that array turned into individual arguments. Change this: $.when(addBlogCalls) to this: $.when.apply($, addBlogCalls) It also appears that all your overriding of the JSONP callback is preventing jQuery from processing the result and thus it can't resolve the promise so $.when() doesn't work. Since you have now changed your server to accept callback=fname, this is easier because you can remove all your special JSONP handling and let jQuery do what it wants to do. Your code can also be cleaned up to not rely on globals that are not reinitialized for successive operations. I'd recommend something like this: $("#btnAddBlog").click(function (e) { var addBlogCalls = $('#add_contributor section.blog').map(function () { //call addBlog for each of the users blogs return addBlog(contributorId, $(this).attr('id')); }).toArray(); $.when.apply($, addBlogCalls).done(function () { console.log("WHEN + errorState: " + errorState); //This is output to console BEFORE the line in the cbAddBlog callback function }); e.preventDefault(); }); addBlog : function (contributorId, blogSection) { //client side validation - following is excecuted if there are no errors return $.ajax({ url : (apiRoot + "f=jsonp").trim(), dataType : 'jsonp' }).done(cbAddBlog); }
doc_23535132
A: Unfortunately Windows Azure Media Services (WAMS) doesn't support Https. The formats for streaming, like HLS, are actually transfer formats like Http. HLS doesn't by nature support HTTPS. Instead it has other content protection mechanisms, WAMS uses HLS + 128-bit AES. All of the content transferred in the stream is encrypted by AES. Depending on your security requirements, you shouldn't need to serve the requests with https. The request that retrieves the origin locator url should be https already, the request that stores it in your database should be https, the request that provides the url to a client should be https, so with the default AES encryption it's entirely secure.
doc_23535133
Python code: from __future__ import print_function # Python 2/3 compatibility from gremlin_python import statics from gremlin_python.structure.graph import Graph from gremlin_python.process.graph_traversal import __ from gremlin_python.process.strategies import * from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection graph = Graph() remoteConn = DriverRemoteConnection('wss://my_end_point:8182/gremlin','g') g = graph.traversal().withRemote(remoteConn) print(g.V().has("system.tenantId", "sample_tenantId").count()) remoteConn.close() rather than executing gremlin query . its giving output as it is output: [['V'], ['has', 'system.tenantId', 'sample_tenantId'], ['count']] question: why its not taking gremlin query? Please note: Connection is proper and I got output as mentioned in the link: https://docs.aws.amazon.com/neptune/latest/userguide/access-graph-gremlin-python.html output: [v[sample_RETURN_D_H], v[sample_IND]] A: Gremlin queries are lazily evaluated, so you must add a terminal step to your query for it to be executed by the server. If you change your line to add one of these steps as shown below, then it will be executed by the server. print(g.V().has("system.tenantId", "sample_tenantId").count().next())
doc_23535134
shift n = ??? (+n) (id, map, id) -- simple(?) which would be equivalent to: shift n (a, b, c) = (a+n, map (+n) b, c+n) I am happy to just go with this explicit function usage, but wondered it there was a more idiomatic point-free version using Applicative or Arrows or ..., or if they would just end-up obfuscating things. I thought that the point-free version shows the basic structure of the operation more clearly. A: You can just write shift n (a,b,c) = (a+n, map (+n) b, c+n) Or define new combinators similar to Arrow's (***) and (&&&), prod3 (f,g,h) (a,b,c) = (f a, g b, h c) -- cf. (***) call3 (f,g,h) x = (f x, g x, h x) -- cf. (&&&) ap3 f (a,b,c) = (f a, f b, f c) uncurry3 f (a,b,c) = f a b c and then call prod3 ( (+n), map (+n), (+n) ) (a,b,c) or even (with appropriately set operator precedences) ap3 ($ (+n)) (id, map, id) `prod3` (a,b,c) Or, if you'd write your triples as nested pairs, you could use Prelude Control.Arrow> ( (+5) *** map (+5) *** (+5) ) (1,([2,3],4)) (6,([7,8],9)) So for nested pairs, shift' :: (Num b) => b -> (b, ([b], b)) -> (b, ([b], b)) shift' n = ( (+n) *** map (+n) *** (+n) ) (see also Multiple folds in one pass using generic tuple function) A: With the DeriveFunctor language extension you can write data MyState a = MyState a [a] a deriving (Functor) The derived instance looks like instance Functor MyState where fmap f (MyState a bs c) = MyState (f a) (map f bs) (f c) Now you can define shift :: MyState Int -> MyState Int shift n = fmap (+n) (You say your tuple is even longer than (Int, [Int], Int), so you may want to define your state type using record syntax.) A: Applying a list of functions to a list of values is simply zipWith ($) Since tuples of different sizes are each their own type, you will have to write a function explicitly for 3-tuples. A general function to apply a 3-tuple of functions to a 3-tuple of values is apply (f, g, h) (a, b, c) = (f a, g b, h c) You have to explicitly write each function application because tuples don't have the recursive property of lists.
doc_23535135
For example, the user opens app "A" which starts the service. Then the user opens app "B" which detects that the service is running, stops it, and then restarts the service itself. Is this something that can be accomplished in Android by running the service in it's own process, or by some other method? A: If: * *The service is exported, and *Permissions allow you to talk to that service, and *You know how to craft an Intent to identify the service then stopService() should work, assuming that the service can be stopped (e.g., there are no bound connections to it). stopService() is not limited to services in your own process. The key here is security, ensuring that somehow you can stop the service and others cannot. That's not particularly easy, which is why you don't see this as a common pattern. In your case, perhaps a better solution is not to stop the existing service and start a fresh one, but just to leave things alone, if your service instance is already running.
doc_23535136
Further more, I don't understand why it is when I do a date difference calculation inside the excel table that it works, but when I use it as a calculated field in a pivot table it doesn't work. This is the Formula I used. =ABS(MONTH(J2)-MONTH(D2))+1 I used Absolute because it was showing negatives. I added 1 month to account for the current month and because subs showing less than 30 days, would display 0(zero) months. Thanks in advance,
doc_23535137
no row with the given identifier exists As I understood, that thing occurs, if table A can't bind table B with given id. So, how can I avoid that? It will be nice to return null object. I was trying to annotate binded field with nullable=true, but that doesn't fix the problem. Also I've set @ManyToOne(optional = true), but no effect. A: Ok, I've found the solution. I should annotate binded field with @NotFound(action=NotFoundAction.IGNORE) statement.
doc_23535138
A: Short answer: it depends a lot. From an application level writes generally appear faster. as you are really only requesting that the OS writes data, and the OS may return to you quickly and write the data at it's leisure. With a read, you have to wait for the OS to get back to you with the data you want. The filesystem can dramatically affect the speed of reads and writes... often there is more housekeeping to be done on a write, but if you are appending to a file that might go more quickly. Most solid state disks are much slower at writing than they are at reading. A: This is actually a pretty complicated question, and it requires an understanding of how your I/O system is set up. The simple example you're citing (reading/writing a fixed amount of data to a particular location on disk) isn't as realistic as you might think. Here's a short summary of things that can affect I/O performance. * *Disk speed Hard disk speed is usually expressed in terms of rotational speed (rpm or revolutions per minute), which tells you how fast the platters are spinning around inside the drive. Typical values are from 5400 to 10,000rpm. Typical transfer rates are from 1-1.6 GBit/sec, and can sustain transfer rates of up to 125 MB/sec. Keep in mind that there's a difference between latency and throughput. If you write very small pieces of data to different places on your drive, you're dependent on the drive's latency (seek time, rotational delay, and access time). But, if you stream a large amount of data at once, you are probably more dependent on the throughput. Your filesystem determines how files are laid out on disk, and it may try to optimize for things like this (see below). Another thing to consider is that you can (and most businesses do) get faster transfer rates using multiple drives in a RAID configuration. The throughput of RAID drives depends on what combination of striping, mirroring, and parity you've chosen. Check out the Wikipedia article for all the subtleties. There are too many parameters to explain in full here. *Caching Modern OS's carefully schedule when they interact with the disk drive. Between your program and the physical disk there may be several layers of caches, so the performance you'll see as an application programmer may depend more on how your OS handles data than on the actual performance of your drive. Most OS's today use a buffer cache so that data from disk can be kept in memory, and the OS can schedule when it talks to the disk. Writes by an application will seem fast, since they can go straight to memory and the OS can wait to flush the buffer until it has nothing else to do. In practice, OS's will try flush writes in a fairly timely fashion, so that a power failure doesn't kill all of your data. So, while there is available buffer space, writes will seem fast. If you fill up the buffer cache, or if the OS has little free memory to work with, you may see I/O performance degrade because the OS has to flush buffers more frequently. Read speed, like write speed, depends on how data is cached. Most hard drives today have hardware caches that can increase sustained transfer rate. Likewise, the OS uses the buffer cache to store files that you've accessed. Either of these can use some prefetching strategy to fetch data from the drive in advance if it seems like it may be needed. With caching, initial reads might be slow, but subsequent reads (especially reads of the same thing) will take less time if the data to be read is already in a cache somewhere. *Filesystem Finally, there's your filesystem to consider. A large write may not all go to the same place, so you can't simply consider your transfer rate when estimating how long it's going to take. Files aren't always contiguous on disk, and your filesystem has to compute how they should be laid out, which can affect performance drastically depending on how much space is available and how fragmented your disk is. Read/write performance will boil down to a combination of all the effects mentioned above plus characteristics of the workload you put on the drive (size of data, frequency of reads and writes, etc). As with most things, you'll need to experiment with your application, the OS you intend to run in on, and your particular disk configuration to get a realistic idea of how it performs. A: Buffers will affect the time to read and write by a great amount. Buffers may be maintained by the operating system in RAM and many drives also contain internal buffers that are part of the disk controller. Consider that the operating system might cache portions of a file in RAM such that reads from these portions can complete very quickly. In addition, the operating system might cache writes in RAM until there is a sufficient amount to write to disk. A call to a 'write' function might return after only copying the data to another area of memory. In short and to generalize, if you require the bits to be written to the disk (using a flush operation or something similar) then this operation will be at least as long as and uncached read from the disk, likely longer.
doc_23535139
Incidentally, we are deploying our Rails app with Mongrel, and it seems like custom Mongrel handlers can stream data fine and even play nice with Rails apps. I've been able to create a custom handler but I can't figure out how to get it to work along-side the Rails app. For example, I would like all requests to the URI /foo.* to go the custom handler and all others to be handled by Rails. Can someone advise how to make this happen? I can't seem to replicate the results from the linked article above. Or is there an easier way to get a Rails handler to produce an open-ended, streaming response? A: The culprit was a bogus mongrel install on OS X. A proper install works fine using guidance from the linked article using a simple handler like below: # foo_handler.rb class FooHandler < Mongrel::HttpHandler # def process(req, res); streaming_impl; end end # Usage: mongrel_handler start -S foo_handler.rb uri "/foo", :handler => FooHandler.new
doc_23535140
ERROR: syntax error at or near "/" I'm trying to get % of total price in the first 3 months of 2016 (SPORT & MUSIC) from total price of all 2016 in the same departments (SELECT "Total Price" FROM "Sales" WHERE "Department" IN('SPORT','MUSIC') AND "DATE" BETWEEN '2016-01-01' AND '2016-03-31')/(SELECT "Total Price" FROM "Sales" WHERE "Department" IN('SPORT','MUSIC') AND "DATE" BETWEEN '2016-01-01' AND '2016-12-31') AS percentage A: I guess you mean something like SELECT "Total Price"/(sum("Total Price") OVER ()) * 100.0 AS percentage FROM "Sales" WHERE "Department" IN ('SPORT','MUSIC') AND "DATE" BETWEEN '2016-01-01' AND '2016-03-31'; Do yourself a favour and avoid names with upper or mixed case and non-alphanumeric characters.
doc_23535141
Here's what I have so far: proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) #kill after reaching n bytes of output, proc.terminate() out, errors = proc.communicate() Thanks! A: One fairly straightforward way to do this would be to redirect the output to a program that will do the byte/line counting for you, for example: proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) head = subprocess.Popen(['head', '-n', '20'], stdin=proc.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE) proc.stdout.close() out, errors = head.communicate() I'm not sure how portable this method is, I was only able to test on Linux however on Windows you should be able to use the more command for similar behavior. Closing proc.stdout is necessary so that proc receives SIGPIPE when head exits.
doc_23535142
Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema. - configuration.module has an unknown property 'loaders'. && Entry Module not found: ~full path to my index.jsx file ~ My package.json { "name": "mypetstore", "version": "1.0.0", "description": "BoxKnight developer challenge ", "main": "index.js", "scripts": { "build": "webpack -d --watch" }, "repository": { "type": "git", "url": "git+https://github.com/ianlennymatthews/MyPetStore.git" }, "author": "Ian Lenny Matthews", "license": "ISC", "bugs": { "url": "https://github.com/ianlennymatthews/MyPetStore/issues" }, "homepage": "https://github.com/ianlennymatthews/MyPetStore#readme", "dependencies": { "@babel/plugin-proposal-class-properties": "^7.4.4", "@babel/preset-react": "^7.0.0", "axios": "^0.19.0", "babel": "^6.23.0", "babel-core": "^6.26.3", "babel-loader": "^8.0.6", "babel-preset-es2015": "^6.24.1", "babel-preset-react": "^6.24.1", "express": "^4.17.1", "react": "^16.8.6", "react-bootstrap": "^1.0.0-beta.9", "react-dom": "^16.8.6", "webpack": "^4.35.0" }, "devDependencies": { "@babel/core": "^7.4.5", "@babel/preset-env": "^7.4.5", "webpack-cli": "^3.3.5" } } My webpack config file var path = require('path'); var SRC_DIR = path.join(__dirname, '/client/src'); var DIST_DIR = path.join(__dirname, '/client/dist'); module.exports = { entry: path.join(SRC_DIR, '/index.jsx'), output: { filename: 'bundle.js', path: DIST_DIR }, module: { rules: [ { test: /\.jsx?/, exclude: /node_modules/, use: { loader: 'babel-loader', query: { presets: ['@babel/preset-env', '@babel/preset-react'], plugins: ['@babel/plugin-proposal-class-properties'] } } } ] } }; **Add File Structure . ├── client │   ├── dist │   │   ├── index.html │   │   └── style.css │   └── src │   ├── components │   │   └── AddressForm.jsx │   └── index.jsx ├── package.json ├── package-lock.json ├── README.md ├── server │   └── index.js └── webpack.config.js A: The webpack documentation implies that context is necessary and entry should be a relative path to context. module.exports = { context: path.resolve(__dirname, 'app'), entry: "./home.js" }; Try modifying your webpack.config.js to look like this: module.exports = { context: SRC_DIR, entry: "./index.jsx", // ... }; A: Try path.resolve instead of path.join. var SRC_DIR = path.resolve(__dirname, '/client/src'); var DIST_DIR = path.resolve(__dirname, '/client/dist'); Then in the config. module.exports = { entry: { 'bundle': `${SRC_DIR}/index.jsx`, }, output: { path: `${DIST_DIR}`, filename: '[name].js', }, module: { rules: [ { test: /\.jsx?/, exclude: /node_modules/, use: { loader: 'babel-loader', query: { presets: ['@babel/preset-env', '@babel/preset-react'], plugins: ['@babel/plugin-proposal-class-properties'] } } } ] } };
doc_23535143
> inp <- c(5,6,7,8,9,1,2,3,4) > inplen <- length(inp) > left <- inp[1:ceiling(inplen/2)] > right <- inp[ceiling(inplen/2)+1:inplen] > left [1] 5 6 7 8 9 > right [1] 1 2 3 4 NA NA NA NA NA > length(left) [1] 5 > length(right) [1] 9 Here you can see that though I split the vector in two halves the size of the right half is larger than the size of the left half. Also there are some entries in the right half that have the value NA. I am not able to figure out as to why the second vector created (called right) is having these extra entries. A: You are running in to a (well-known) problem caused by a higher operator precedence for ":" than for "+": ceiling(inplen/2)+1:inplen [1] 6 7 8 9 10 11 12 13 14 NAs are being returned because your index exceeded the length of the vector. A: You're missing a bracket: right = inp[(ceiling(inplen/2)+1):inplen] To expand, suppose we have 1 + 1:3 does this mean 1+(1:3) or (1+1):3. R interprets this as 1+(1:3) so when you type 1+1:3 you get: 1 + c(1,2,3) which becomes c(2,3,4) Another common gotcha is: R> x = 1:5 R> x[2:length(x)-1] [1] 1 2 3 4 Instead of selecting elements 2 to 4, we have selected elements 1 to 4 by mistake. A: You can use split for this, with cut to create the breakpoints: split(inp,cut(seq(inplen),breaks=c(0,ceiling(inplen/2),inplen),labels=c("left","right"))) $left [1] 5 6 7 8 9 $right [1] 1 2 3 4
doc_23535144
M=[0.1000 0.6000 0.7000 0.8000 0.9000 0.9500 1.0000 1.0500 1.1000 1.1500 1.2000 1.2500 1.3000 1.5000 1.7500 2.0000 2.2500 2.5000 3.0000]; CZ1=[ 9.4290 9.5000 9.3250 9.2700 9.2950 9.4350 9.6840 10.0690 10.1840 10.2220 10.2160 9.6160 9.6890 9.4880 9.5000 9.5340 9.3370 9.0990 8.5950]; N1=11; Nn=13; Mx1=M(N1); Mx2=M(Nn); Mx=[Mx1 Mx2]'; CN1=CZ1(N1); CN2=CZ1(Nn); CNy=[C1 C2]'; y1=interp1q(Mx,CNy,M(N1:Nn)); CNf=CZ1; NEWRangeC=y1; Cfa=changem(CZ1,[NEWRangeC], [CNf(N1:Nn)]); figure plot(M,Cf,'-*b',M,Cfa,'r') So far as you can see I used points 11 and 13 and i excluded point 12 interpolating that point from 11 to 13. This is working but i want to make a modification. My question is: How can I select values that are errors and remove them but interpolate space between their neighbors. I want to use a M matrix values as my reference (not points as my example). A: Well, you can start out by finding the elements that are errors, with the find command (this will return the indices). This should also work for matrices. You can then grab the elements around each of the indices, and interpolate between, as you did. A: Assuming you know which elements are incorrect, you can use Matlab's interp1 function to interpolate them (this will only work if the M matrix is actually a vector`: error_indices = [11 13]; all_indices = 1:length(M) % Get the indices where we have valid data all_correct_indices = setdiff(all_indices, error_indices) % the first two arguments are the available data. % the third arguments is what indices you are looking for M_new = interp1(all_correct_indices, M(all_correct_indices), all_indices) The above interpolates values at all_indices -- including the missing elements. Where you already have valid data (all_correct_indices), Matlab will return that data. In other places, it will interpolate using the two nearest neighbors. Try help interp1 for more information on how this function works. Update - an example x = 1:10; % all indices y = x*10; e = 3:7; % the unknown indices s = setdiff(x, e); % the known indices y_est = interp1(s, y(s), x) ans = 10 20 30 40 50 60 70 80 90 100 And we see that interp1 had interpolated all values from 30 to 70 linearly using the available data (specifically the adjacent points 20 and 80).
doc_23535145
A: You'll need a module bundler of some kind. There are many options including Webpack, Browserify, Gulp, and Parcel. For Webpack, for example, from their example docs, the process could be: * *Install webpack with npm install webpack and install webpack-cli *Install a module you want to use on the frontend, eg lodash *In src/index.js, import lodash: import _ from 'lodash'; and use it as needed. (You can also import other modules from NPM or from other places in your source code) *Set up webpack.config.js if you need custom build configuration settings *Run webpack to build the project: npx webpack. A single bundled JavaScript file will be created which contains all your source code and the imported Lodash's source code.
doc_23535146
Please help. A: What did you set up exactly? Did you setup PATH like this (or something equivalent): export PATH=$PATH:...:$M2_HOME/bin If yes, did you logout and login again? According to the bash manpage: When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior. ... When an interactive shell that is not a login shell is started, bash reads and executes commands from /etc/bash.bashrc and ~/.bashrc, if these files exist. This may be inhibited by using the --norc option. The --rcfile file option will force bash to read and execute commands from file instead of /etc/bash.bashrc and ~/.bashrc. As you can see, commands from .profile are not executed for a non-login shell (the type of shells you open after logging in). So you have to logout/login or to source the file manually to take your setup into account. See this blog post for more details. A: Have you installed Maven, already? If you use MacPorts to install Maven, you won't need to edit your PATH.
doc_23535147
Now I am exploring it's API.I would like to know, whether is there any way to load data using any database as a source. A: This should help you get started: https://cloud.google.com/bigquery/loading-data
doc_23535148
The pages for the app are all divs on the index.html and appear/disappear based on an ng-show for each div. There is a back button that resets the current page view to false and the home page to true. This all works if I just move backwards and forwards between the pages. However, one screen requires a confirmation box to ensure the user actually wants to go back. To make it look stylish I'm using SweetAlert to show the confirm/cancel buttons and a message. The confirm button sets the $scope.home to true and the $scope.gameScreen to false, just as the standard back button does but it doesn't actually go back. The confirmation box disappears and a console log shows the function was called correctly but the ng-show part doesn't fire. My divs are below as is the back button function: <!-- GAME SECTION --> <div id="gameScreen" class="screen" ng-show="gameScreen"> ... </div> <!-- HOME SCREEN --> <div id="homeScreen" class="screen" ng-show="homeScreen"> ... </div> $scope.goBack = function () { if ($scope.gameScreen != true || ($scope.currentGuess == "" && playersTurn == true)) { console.log("returning home"); $scope.homeScreen = true; $scope.gameScreen = false; $scope.optionsScreen = false; $scope.instructionsScreen = false; $scope.onlineRegistrationScreen = false; $scope.pages.homePage = true; $scope.pages.currentPage = "home"; console.log("home page: " + $scope.pages.homePage); console.log("scope.currentPage: " + $scope.pages.currentPage); console.log("scope.gameScreen: " + $scope.gameScreen); $scope.difficulty = ""; } else { // confirm going back from game screen swal({ title: "Are you sure?", text: "This will end your current game and record it as a loss.", type: "warning", showCancelButton: true, confirmButtonColor: "#382E1C", confirmButtonText: "Yes (Lose Game)", closeOnConfirm: true }, function () { console.log("Go Back confirmation clicked"); $scope.confirmLoseGame(); }); } } $scope.confirmLoseGame = function () { console.log("confirm lose game"); $scope.gameScreen = false; // $scope.pages.homePage = true; //$scope.pages.currentPage = "home"; $scope.goBack(); } I tried calling the function outside of the SweetAlert confirm to see if it made a difference but even made it loop back through the goBack function to see it it helped but the game screen never hides itself. Anyway, the point is Angular isn't responding to the variable controlling the ng-show changing when the SweetAlert is used. Any help/suggestions would be appreciated. Thanks A: As noted by charlietfl, $scope.apply() called inside the SweetAlert method fixed the issue. $scope.$apply(function () { $scope.homeScreen = true; $scope.gameScreen = false; }); A: A practical example to display an alert and then do something using the $scope is as follows: swal({ title: "Are you sure?", text: "You will not be able to recover this imaginary file!", type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Yes, delete it!", closeOnConfirm: false }, function(){ $scope.$apply(function () { console.log("make something"); $scope.showSome = true; $scope.showAnother = false; }); }); This worked for me...!
doc_23535149
My report is developed with jasperreport or it is a ".jasper" file which completes passing parameters and then I have to return a "Byte []" to open it with angular. The problem is that when I print from the server side to the report it works fine, but when I pass the data by "REST" to angular and try to open it on the front it returns the following error (There was an error loading the document PDF.) Below I detail my files with their respective code: Impresion.java (Service) public ByteArrayOutputStream getImprimePresupuesto(PresupuestoDTO presupuestoDTO){ try { ByteArrayOutputStream out = new ByteArrayOutputStream(); //Crear el mapa de parametros Map<String,Object> parameters = new HashMap<>(); /// Datos de la empresa parameters.put("p_empresa", presupuestoDTO.getSucursal().getEmpresa().getDescripcion()); parameters.put("p_eslogan", "Aca lo tengo que agregar en empresa"); parameters.put("p_ingBrutos", "Agregar ingresos Brutos a Empresa"); parameters.put("p_inicAct", "Agregar inicio de act a empresa"); parameters.put("p_domicEmpresa", "Agregar campo domicilio que sea string"); parameters.put("p_contactoEmpresa", "Agregar campo contacto que sea string el que sale en la factura"); parameters.put("p_cuitEmpresa", presupuestoDTO.getSucursal().getEmpresa().getCuit().toString() + " - Condicio IVA agregar Campo"); parameters.put("p_sucursal", presupuestoDTO.getSucursal().getDescripcion()); if (presupuestoDTO.getSucursal().getDomicilios() != null){ parameters.put("p_domicSucursal", presupuestoDTO.getSucursal().getDomicilios().toString()); }else{ parameters.put("p_domicSucursal", "Agregar campo domicilio que sea string"); } if(presupuestoDTO.getSucursal().getContactos() != null){ parameters.put("p_contactoSucursal", presupuestoDTO.getSucursal().getContactos().toString()); }else{ parameters.put("p_contactoSucursal", "Agregar campo contacto que sea string el que sale en la factura"); } //// Datos presupuesto parameters.put("p_numero", presupuestoDTO.getNumero().toString()); parameters.put("p_fecha", presupuestoDTO.getFecha().toString()); parameters.put("p_validez", presupuestoDTO.getValidez().toString()); parameters.put("p_total", presupuestoDTO.getMonto().toString()); /// Datos Cliente parameters.put("p_cliente", presupuestoDTO.getCliente().getPersona().getCuit().toString() + " - " + presupuestoDTO.getCliente().getPersona().getNombreCompleto()); if (presupuestoDTO.getCliente().getPersona().getDomicilios() != null){ parameters.put("p_domicCliente", presupuestoDTO.getCliente().getPersona().getDomicilios().toString()); }else{ parameters.put("p_domicCliente", ""); } if (presupuestoDTO.getCliente().getPersona().getContactos() != null){ parameters.put("p_contactoCliente", presupuestoDTO.getCliente().getPersona().getContactos().toString()); }else{ parameters.put("p_contactoCliente", ""); } /// Detalle del presupuesto // ///// JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(presupuestoDTO.getDetallePresupuestos()); //// generacion del reporte JasperReport report = (JasperReport) JRLoader.loadObject(this.getClass().getResourceAsStream("/reportes/transacciones/presupuesto.jasper")); JasperPrint print = JasperFillManager.fillReport(report,parameters, ds); JRPdfExporter exporter = new JRPdfExporter(); //JasperPrintManager.printReport(print, false); exporter.setParameter(JRExporterParameter.JASPER_PRINT, print); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out); exporter.exportReport(); log.debug("Presupuesto Impresion: {}", out); return out; } catch (JRException e) { return null; } } PresupuestoResource.java (REST) @RestController @RequestMapping("/api") public class PresupuestoResource { @GetMapping("/imprimirPresupuestos/{id}") @Timed public ResponseEntity<byte[]> getImprimirPresupuesto(@PathVariable Long id, HttpServletRequest request, HttpServletResponse response) throws JRException, IOException { log.debug("Metodo GET de Imprimir Presupuesto : {}", id); ServletContext scontext = request.getSession().getServletContext(); ByteArrayOutputStream reporte = presupuestoService.imprimir(id, scontext); String filename = "presupuesto.pdf"; log.debug("Imprimir Presupuesto Sale sin error del service: {}", reporte); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType("application/pdf")); //headers.setContentType(MediaType.parseMediaType("application/pdf;charset=utf-8")); headers.setContentDispositionFormData(filename, filename); //headers.setCacheControl("must-revalidate, post-check=0, pre-check=0"); response.setHeader("Content-Disposition","attachment;filename=\"" + filename + "\""); response.setContentType("application/pdf"); response.setContentLength(reporte.size()); if (reporte.toByteArray() != null && reporte.toByteArray().length > 0){ //ResponseEntity<byte[]> retorno = new ResponseEntity<byte[]>(reporte.toByteArray(), headers, HttpStatus.OK); ResponseEntity<byte[]> retorno = ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert("presupuesto", String.valueOf(reporte.toByteArray().length))) .body(reporte.toByteArray()); return retorno; } String erro = "Error"; return new ResponseEntity<byte[]>(erro.getBytes(), headers, HttpStatus.OK); } } presupuestoImpresion.service.js (Service Angular) (function() { 'use strict'; angular .module('gcApp') .factory('PresupuestoImp', PresupuestoImp); PresupuestoImp.$inject = ['$resource']; function PresupuestoImp ($resource) { var resourceUrl = 'api/imprimirPresupuestos/:id'; return $resource(resourceUrl, {}, { 'query': { method: 'GET', isArray: true}, 'get': { method: 'GET', responseType: 'arraybuffer' //responseType: 'blob' }, 'update': { method:'PUT' } }); } })(); presupuesto.controler.js (Controller Angular) vm.imprimir = function (p_id) { PresupuestoImp.get({id : p_id}, function (result) { console.log(result.data); var file = new window.Blob([result], {type: 'application/pdf'}); console.log(file); var fileURL = URL.createObjectURL(file); /*var a = document.createElement('a'); a.href = fileURL; a.target = '_blank'; a.download = 'presupuesto.pdf'; document.body.appendChild(a); a.click();*/ window.open(fileURL); }); } .JRXML <?xml version="1.0" encoding="UTF-8"?> <!-- Created with Jaspersoft Studio version 6.3.1.final using JasperReports Library version 6.3.1 --> <!-- 2017-03-31T17:52:02 --> <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="presupuesto" pageWidth="595" pageHeight="842" whenNoDataType="NoPages" columnWidth="535" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="0c2b8f60-92c5-457b-8b2e-d798a44afcf2"> <property name="ireport.zoom" value="1.0"/> <property name="ireport.x" value="0"/> <property name="ireport.y" value="0"/> <property name="com.jaspersoft.studio.unit." value="pixel"/> <property name="com.jaspersoft.studio.unit.pageHeight" value="pixel"/> <property name="com.jaspersoft.studio.unit.pageWidth" value="pixel"/> <property name="com.jaspersoft.studio.unit.topMargin" value="pixel"/> <property name="com.jaspersoft.studio.unit.bottomMargin" value="pixel"/> <property name="com.jaspersoft.studio.unit.leftMargin" value="pixel"/> <property name="com.jaspersoft.studio.unit.rightMargin" value="pixel"/> <property name="com.jaspersoft.studio.unit.columnWidth" value="pixel"/> <property name="com.jaspersoft.studio.unit.columnSpacing" value="pixel"/> <property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/> <parameter name="p_empresa" class="java.lang.String"/> <parameter name="p_eslogan" class="java.lang.String"/> <parameter name="p_domicEmpresa" class="java.lang.String"/> <parameter name="p_contactoEmpresa" class="java.lang.String"/> <parameter name="p_cuitEmpresa" class="java.lang.String"/> <parameter name="p_numero" class="java.lang.String"/> <parameter name="p_fecha" class="java.lang.String"/> <parameter name="p_validez" class="java.lang.String"/> <parameter name="p_inicAct" class="java.lang.String"/> <parameter name="p_ingBrutos" class="java.lang.String"/> <parameter name="p_cliente" class="java.lang.String"/> <parameter name="p_domicCliente" class="java.lang.String"/> <parameter name="p_contactoCliente" class="java.lang.String"/> <parameter name="p_total" class="java.lang.String"/> <background> <band splitType="Stretch"/> </background> <pageHeader> <band height="147" splitType="Stretch"> <staticText> <reportElement x="221" y="36" width="100" height="13" uuid="9f24402a-9c42-48f7-9f10-e77a01c647bd"/> <textElement textAlignment="Center"> <font isBold="true"/> </textElement> <text><![CDATA[PRESUPUESTO]]></text> </staticText> <textField> <reportElement x="452" y="99" width="95" height="15" uuid="3747741e-2468-45a5-b758-2caddf559d44"/> <textFieldExpression><![CDATA[$P{p_inicAct}]]></textFieldExpression> </textField> <textField> <reportElement x="452" y="115" width="95" height="15" uuid="d3919bcc-adb3-44c4-859f-5c898ab74d87"/> <textFieldExpression><![CDATA[$P{p_ingBrutos}]]></textFieldExpression> </textField> <rectangle> <reportElement x="245" y="4" width="50" height="30" uuid="8dc1ee61-5c32-41fe-8aae-6d9b62e70ade"/> </rectangle> <staticText> <reportElement x="342" y="4" width="102" height="20" uuid="947d5341-f3bc-43f7-8a59-f95ab836ddeb"/> <textElement textAlignment="Right"> <font size="12" isBold="true"/> </textElement> <text><![CDATA[NUMERO :]]></text> </staticText> <textField> <reportElement x="8" y="92" width="237" height="20" uuid="a8afab15-5e11-4494-b516-316096db8de9"/> <textElement> <font size="10" isBold="true"/> </textElement> <textFieldExpression><![CDATA[$P{p_contactoEmpresa}]]></textFieldExpression> </textField> <staticText> <reportElement x="245" y="5" width="50" height="30" uuid="a647a6f0-5dd7-424e-a5e5-6ee96cd20990"/> <textElement textAlignment="Center"> <font size="18" isBold="true" isItalic="false" isUnderline="false" isStrikeThrough="false"/> </textElement> <text><![CDATA[X]]></text> </staticText> <textField> <reportElement x="8" y="36" width="187" height="20" uuid="6a0e8cff-0195-4e32-9138-cc93e352b43e"/> <textElement> <font size="12"/> </textElement> <textFieldExpression><![CDATA[$P{p_eslogan}]]></textFieldExpression> </textField> <staticText> <reportElement x="346" y="115" width="102" height="15" uuid="e6166e57-ec07-4428-a727-928a349ef985"/> <textElement textAlignment="Right"> <font isBold="true"/> </textElement> <text><![CDATA[Ing. Brutos :]]></text> </staticText> <textField> <reportElement x="452" y="35" width="95" height="15" uuid="2c985390-a194-4a56-bad9-2cc57f5b0e8e"/> <textFieldExpression><![CDATA[$P{p_fecha}]]></textFieldExpression> </textField> <textField> <reportElement x="8" y="8" width="187" height="20" uuid="9a535ca1-4fe8-4a77-869f-19b24f6026e6"/> <textElement> <font size="12"/> </textElement> <textFieldExpression><![CDATA[$P{p_empresa}]]></textFieldExpression> </textField> <staticText> <reportElement x="8" y="116" width="33" height="15" uuid="22c9bf5e-7027-49e8-8689-e57e432dc511"/> <textElement textAlignment="Right"> <font isBold="true"/> </textElement> <text><![CDATA[CUIT : ]]></text> </staticText> <staticText> <reportElement x="346" y="99" width="102" height="15" uuid="c59db18d-6217-4acf-8fc3-91d507833d3f"/> <textElement textAlignment="Right"> <font isBold="true"/> </textElement> <text><![CDATA[Inicio Actividades :]]></text> </staticText> <textField> <reportElement x="8" y="71" width="237" height="20" uuid="948c445d-7bd0-4eef-a2a2-3907e2df80e8"/> <textElement> <font size="10" isBold="true"/> </textElement> <textFieldExpression><![CDATA[$P{p_domicEmpresa}]]></textFieldExpression> </textField> <staticText> <reportElement x="195" y="49" width="150" height="20" uuid="b499dc3f-7313-41de-932d-2fe8fc219b31"/> <textElement textAlignment="Center"/> <text><![CDATA[( NO Válido como FACTURA )]]></text> </staticText> <staticText> <reportElement x="346" y="35" width="102" height="15" uuid="6873b2be-e935-4a88-83f8-dcd572cb2405"/> <textElement textAlignment="Right"> <font isBold="true"/> </textElement> <text><![CDATA[Fecha :]]></text> </staticText> <textField> <reportElement x="41" y="116" width="204" height="15" uuid="000715ee-fa1d-4a22-a947-ed22cc5d394c"/> <textElement> <font size="10" isBold="false"/> </textElement> <textFieldExpression><![CDATA[$P{p_cuitEmpresa}]]></textFieldExpression> </textField> <textField> <reportElement x="449" y="4" width="100" height="20" uuid="5ef97bae-6c17-4344-9fa1-947a9fef7529"/> <textElement> <font size="12" isBold="true"/> </textElement> <textFieldExpression><![CDATA[$P{p_numero}]]></textFieldExpression> </textField> <staticText> <reportElement x="346" y="54" width="102" height="15" uuid="700bae7d-f184-4f60-a179-e93d220b0e99"/> <textElement textAlignment="Right"> <font isBold="true"/> </textElement> <text><![CDATA[Fecha Validez:]]></text> </staticText> <textField> <reportElement x="452" y="54" width="95" height="15" uuid="d3d126ef-26fc-4eff-8575-b965e9216936"/> <textFieldExpression><![CDATA[$P{p_validez}]]></textFieldExpression> </textField> </band> </pageHeader> <columnHeader> <band height="89" splitType="Stretch"> <staticText> <reportElement x="8" y="73" width="90" height="15" uuid="593263b4-260d-430d-bd56-19c4b687b22f"/> <textElement> <font isBold="true"/> </textElement> <text><![CDATA[Código]]></text> </staticText> <staticText> <reportElement x="8" y="7" width="56" height="15" uuid="7ada98b9-5495-499d-8b41-572198a6b3bd"/> <textElement textAlignment="Right"> <font isBold="true"/> </textElement> <text><![CDATA[Cliente :]]></text> </staticText> <textField> <reportElement x="68" y="7" width="479" height="15" uuid="315b7bf7-d8c2-40e0-90ae-c15c12041811"/> <textFieldExpression><![CDATA[$P{p_cliente}]]></textFieldExpression> </textField> <staticText> <reportElement x="8" y="23" width="56" height="15" uuid="ff8d8f1b-da1a-482c-8ffc-62a4e10aa5a7"/> <textElement textAlignment="Right"> <font isBold="true"/> </textElement> <text><![CDATA[Domicilio :]]></text> </staticText> <textField> <reportElement x="68" y="23" width="479" height="15" uuid="752aa1de-f5ac-4e13-983f-6984b1c00ae8"/> <textFieldExpression><![CDATA[$P{p_domicCliente}]]></textFieldExpression> </textField> <staticText> <reportElement x="8" y="39" width="56" height="15" uuid="85955b43-91e9-4dd1-94e3-49989e5a8e9c"/> <textElement textAlignment="Right"> <font isBold="true"/> </textElement> <text><![CDATA[Contacto :]]></text> </staticText> <textField> <reportElement x="68" y="39" width="479" height="15" uuid="97a09610-1c1f-4757-a5d5-67730e029172"/> <textFieldExpression><![CDATA[$P{p_contactoCliente}]]></textFieldExpression> </textField> <line> <reportElement x="8" y="62" width="539" height="1" uuid="3186a9f2-4694-450d-9635-acb1c21396ba"/> </line> <staticText> <reportElement x="98" y="73" width="237" height="15" uuid="82e4a5ef-5e2c-4442-ae60-471ad9bbb55d"/> <textElement> <font isBold="true"/> </textElement> <text><![CDATA[Descripción]]></text> </staticText> <staticText> <reportElement x="335" y="73" width="70" height="15" uuid="a79152f4-3780-4eb1-9d91-d5d06e98ac2b"/> <textElement textAlignment="Center"> <font isBold="true"/> </textElement> <text><![CDATA[P. Unitario]]></text> </staticText> <staticText> <reportElement x="405" y="73" width="58" height="15" uuid="0281fb18-dd96-4efe-866c-d54be9d1c038"/> <textElement textAlignment="Center"> <font isBold="true"/> </textElement> <text><![CDATA[Cantidad]]></text> </staticText> <staticText> <reportElement x="463" y="73" width="84" height="15" uuid="81c98750-5faf-416f-8006-e42425b14463"/> <textElement textAlignment="Center"> <font isBold="true"/> </textElement> <text><![CDATA[Sub Total]]></text> </staticText> </band> </columnHeader> <detail> <band height="18" splitType="Stretch"> <line> <reportElement x="97" y="0" width="1" height="17" uuid="c75e9d08-001d-4935-a535-15f039e39834"/> </line> <line> <reportElement x="335" y="0" width="1" height="17" uuid="f04b882f-607b-4044-9ad6-1c639f3bd5dc"/> </line> <line> <reportElement x="405" y="0" width="1" height="17" uuid="64656ae1-d684-458d-8d62-6ac345d76b87"/> </line> <line> <reportElement x="463" y="0" width="1" height="17" uuid="66f642ad-ade1-4780-9283-baa7e644e944"/> </line> <textField> <reportElement x="8" y="0" width="89" height="17" uuid="37689cbc-89dd-49e3-a6b5-a5b6e3bfd3f4"/> <textFieldExpression><![CDATA["123"]]></textFieldExpression> </textField> <textField> <reportElement x="97" y="0" width="238" height="17" uuid="689afa9d-650f-4ee3-8d71-26dd7181f9fa"/> <textFieldExpression><![CDATA["Pruebas de impresion Fija"]]></textFieldExpression> </textField> <textField> <reportElement x="335" y="0" width="70" height="17" uuid="da224715-bbbe-4f1b-98a6-6432101340dd"/> <textElement textAlignment="Right"/> <textFieldExpression><![CDATA["200"]]></textFieldExpression> </textField> <textField> <reportElement x="405" y="0" width="58" height="17" uuid="79b9e1c0-1b26-4086-bf74-6712f2581f50"/> <textElement textAlignment="Right"/> <textFieldExpression><![CDATA["1"]]></textFieldExpression> </textField> <textField> <reportElement x="464" y="0" width="83" height="17" uuid="3417e7d7-d24a-4fff-8040-7ac20f38b994"/> <textElement textAlignment="Right"/> <textFieldExpression><![CDATA["200"]]></textFieldExpression> </textField> </band> </detail> <columnFooter> <band height="30" splitType="Stretch"> <textField> <reportElement x="448" y="0" width="99" height="20" uuid="b1095b28-18c7-4c4e-9dd7-f38473cb410d"/> <textElement textAlignment="Right"> <font size="11" isBold="true"/> </textElement> <textFieldExpression><![CDATA[$P{p_total}]]></textFieldExpression> </textField> <staticText> <reportElement x="394" y="0" width="54" height="20" uuid="f7c5b7d9-f63d-4078-8800-3eb247a0d6cd"/> <textElement textAlignment="Right"> <font size="11" isBold="true"/> </textElement> <text><![CDATA[Total : ]]></text> </staticText> </band> </columnFooter> <pageFooter> <band height="68" splitType="Stretch"> <textField> <reportElement x="215" y="46" width="78" height="20" uuid="f657afd4-ce9d-42d2-ac9a-03db3b968057"/> <textElement textAlignment="Right"/> <textFieldExpression><![CDATA["Página "+$V{PAGE_NUMBER}+" of"]]></textFieldExpression> </textField> <textField evaluationTime="Report"> <reportElement x="293" y="46" width="52" height="20" uuid="77a13f9f-a104-4ddc-8a7f-4cccceff1982"/> <textFieldExpression><![CDATA[" " + $V{PAGE_NUMBER}]]></textFieldExpression> </textField> <staticText> <reportElement x="8" y="4" width="54" height="15" uuid="689f5e8f-5897-4bfd-9f5c-b31f2a1d972a"/> <textElement> <font isBold="true"/> </textElement> <text><![CDATA[Recuerde : ]]></text> </staticText> <staticText> <reportElement x="62" y="4" width="485" height="28" uuid="41cbc489-f25c-402e-be81-d3e2eddd3424"/> <textElement> <font isBold="false"/> </textElement> <text><![CDATA[El presente presupuesto posee una validez, la cual se especifica en la cabecera del mismo. Los precios de la mercadería pueden variar sin previo aviso, LA EMPRESA NO se responsabiliza.]]></text> </staticText> </band> </pageFooter> <summary> <band height="42" splitType="Stretch"/> </summary>
doc_23535150
From the JavaDocs: Returns a concurrent Collector implementing a cascaded "group by" operation on input elements of type T... This is a concurrent and unordered Collector. ... Maybe the keywords here are cascaded "group by". Does that point to something in how the actual accumulation is done by the collector? (looking at the source, it got intricate very quickly) When I test it with a fake ConcurrentMap class FakeConcurrentMap<K, V> extends HashMap<K, V> implements ConcurrentMap<K, V> {} I see that it breaks (gives wrong aggregations as the map isn't thread-safe) with parallel streams: Map<Integer, Long> counts4 = IntStream.range(0, 1000000) .boxed() .parallel() .collect( Collectors.groupingByConcurrent(i -> i % 10, FakeConcurrentMap::new, Collectors.counting())); Without .parallel(), results are consistently correct. So it seems that groupingByConcurrent goes with parallel streams. But, as far as I can see, the following parallel stream collected with groupingBy always produces correct results: Map<Integer, Long> counts3 = IntStream.range(0, 1000000) .boxed() .parallel() .collect( Collectors.groupingBy(i -> i % 10, HashMap::new, Collectors.counting())); So when is it correct to use groupingByConcurrent instead of groupingBy (surely that can't be just to get groupings as a concurrent map)? A: All Collectors work just fine for parallel streams, but Collectors supporting direct concurrency (with Collector.Characteristics.CONCURRENT) are eligible for optimizations that others are not. groupingByConcurrent falls into this category. (Roughly, what happens is that a non-concurrent collector breaks the input into per-thread pieces, creates an accumulator per thread, and then merges them at the end. A concurrent (and unordered) collector creates one accumulator and has several worker threads concurrently merging elements into the same accumulator.)
doc_23535151
private Task FetchHashesFromRedis(List<string> redisKeys, ConcurrentBag<LiveDataModel> liveDataModels, CancellationToken cancellationToken) { var parallelism = Environment.ProcessorCount; var semafore = new SemaphoreSlim(initialCount: parallelism, maxCount: parallelism); var tasks = new List<Task>(); Parallel.ForEach(redisKeys, (key) => { tasks.Add(ExecuteOne(key, semafore, liveDataModels, cancellationToken)); }); return Task.WhenAll(tasks); } redisKeys list count is always 1000, so it will always make a thousand of requests. FetchHashesFromRedis method is always the same ExecuteOne method in the first case looks like this: private async Task ExecuteOne(string redisKey, SemaphoreSlim semafore, ConcurrentBag<LiveDataModel> liveDataModels, CancellationToken cancellationToken) { var liveData = await _getLiveDataFromRedis.ExecuteAsync(redisKey, cancellationToken); if (liveData != null) { liveDataModels.Add(liveData); } } In this first case making 1000 requests to Redis takes 1,5 seconds with all side work that I do with models that I'm getting. ExecuteOne method in the second case (with Semaphore) looks like this: private async Task ExecuteOne(string redisKey, SemaphoreSlim semafore, ConcurrentBag<LiveDataModel> liveDataModels, CancellationToken cancellationToken) { await semafore.WaitAsync(cancellationToken); try { var liveData = await _getLiveDataFromRedis.ExecuteAsync(redisKey, cancellationToken); if (liveData != null) { liveDataModels.Add(liveData); } } finally { semafore.Release(); } } In this second case making 1000 requests to Redis takes 4,5 seconds with all side work that I do with models that I'm getting. (the same amount of request as in the first case) So the only difference between first and second case that in second case I use this: await semafore.WaitAsync(cancellationToken); and in finally block I use: semafore.Release(); Why when I use semafore it takes more time (up to 3 times more)? Should I use semafore in this case or no? And when should I use semafore? NOTE: _getLiveDataFromRedis.ExecuteAsync(redisKey, cancellationToken); method is not thread-safe, it just reading different values from redis and returns LiveDataModel A: Why when I use semafore it takes more time (up to 3 times more)? Probably since it limits the number of concurrent IO operations. Using a semaphore will limit the number of concurrent calls to the number of processors, however, since it involves IO, most of the time will just be waiting, no processor time needed. So limiting concurrency to the number of cores make little sense. Try increasing the maxCount and see if that helps performance. Should I use semafore in this case or no? Since it is slower, and does not seem to needed for any threadsafety reason, the answer is probably No. And when should I use semafore? I rarely use semaphores. The most compelling reason I know would be if I need a async lock, i.e. a semaphore with maxcount 1. There are specialized use cases for it, but in most cases I find higher level primitives that take care of synchronization more useful. I might suggest reading up on DataFlow, that might allow you to setup a asynchronous processing pipeline that fit better for your use-case.
doc_23535152
A: You have to pass the Context in Constructor when you call My Control Class. A: There are a couple of things you could be depending on what you need the Application object for. If you need the specific application instance, you could try casting your Context object to an Activity: public class MyLinearLayout extends LinearLayout { private Application mApplication; public MyLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); //As this is a custom ViewGroup, Context will be an Activity, but just to make sure.. if(context instanceof Activity) mApplication = ((Activity) context).getApplication(); else throw new IllegalArguementException("Context must be an Activity"); } } The code above checks to make sure that the Context passed to your custom view is an Activity, but in reality this should always be the case. If you only need your Application object to use as a `Context', then you can call the 'context.getApplicationContext()' method: public class MyLinearLayout extends LinearLayout { private Context mAppContext; public MyLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); mAppContext = context.getApplicationContext(); } }
doc_23535153
Tab1 has these columns :- tabId(Foreign key with Tab2.tabId)(Primary Key), tabType(Primary Key), tabAdd(Primary Key), tabUser Tab2 has these columns :- tabId(Primary Key), location, name, description. Really appreciate quick help!! A: Maybe you should edit the post and show us DB diagram because your description isn't clear. I think if we should have more data :) you have 3 PK on tab1? Which relationship is between them? Greetings :)
doc_23535154
Currently I check only if the server is running. public static boolean checkServerAvailable() { try { String url = Constants.URL_APP + ":" + Constants.APPSERVER_PORT; HttpURLConnection.setFollowRedirects(false); // note : you may also need // HttpURLConnection.setInstanceFollowRedirects(false) HttpURLConnection con = (HttpURLConnection) new URL(url) .openConnection(); con.setRequestMethod("HEAD"); if (con.getResponseCode() == HttpURLConnection.HTTP_OK) { return true; } else return false; } catch (Exception e) { return false; } } But I need to know if the Wildfly server also my web app deployed successull. A: To start with you could add your webapp url to the url you're creating above. Instead of connecting to, for example, http://localhost:8080/ and looking for a HTTP 200 response, you could connect to http://localhost:8080/yourApp and do the same. That implies that you have something at the root context to respond. An arguably better solution would be to have a "heartbeat" or "status" service in your web application. This would be something like http://localhost:8080/yourApp/status. The method or service could just return a 200 implying that the service is up. But it could also really check that your application is healthy. For example, it could check available memory or make sure that the database is up or a multitude of other things. The code you show would just use the full URL of the status service. A: You can use the management API provided by WildFly. The API is described here for different versions of WildFly. For WildFly9 - See https://wildscribe.github.io/Wildfly/9.0.0.Final/deployment/index.html You could use following URL to check the status of deployment. You do need a management user for authentication. Standalone Mode: http://localhost:9990/management/deployment/<deployment_name> For domain mode: http://localhost:9990/management/host/<host_name>/server/<serer_name>/deployment/<deployment_name> Sample JSON response (assuming you deployed an EAR file with some sub-deployments): { "content": [{ "hash": { "BYTES_VALUE": "2gH7ddtUxsbzBJEJ/z4T1jYERRU=" } }], "enabled": true, "enabled-time": 1468861076770, "enabled-timestamp": "2016-07-18 18:57:56,770 CEST", "name": "myapplication.ear", "owner": null, "persistent": true, "runtime-name": "myapplication.app.ear", "subdeployment": { "myapplication.impl.jar": null, "myapplication.web.war": null }, "subsystem": null } Sample request using curl: curl --digest -D - http://localhost:9990/management --header "Content-Type: application/json" -d '{"operation":"read-resource", "include-runtime":"true", "address":["deployment","myapplication.app.ear"] }' -u user:password A: I aws looking for something to check if wildfly is running, here I saw: systemctl status wildfly And also were so useful: systemctl stop wildfly systemctl restart wildfly systemctl start wildfly
doc_23535155
I contact you because I try to deploy a TFHub model on SageMaker, but I encounter issues. Resources The model I desire to deploy is https://tfhub.dev/google/imagenet/inception_v3/feature_vector/5 (TF2.0 Saved Model (v5)). I integrate the solution in net6.0 with the following NuGet in their last versions as of 08/11/2022: AWSSDK.S3, AWSSDK.SageMaker and AWSSDK.SageMakerRuntime Steps * *Deploy Model * *Model Name: Inception-V3-Trained-on-ImageNet-ILSVRC-2012-CLS *Image: 763104351884.dkr.ecr.eu-west-2.amazonaws.com/tensorflow-inference:2.10.0-gpu *Model Data URL: s3://my-bucket/models/inception_v3_feature_vector/5/imagenet_inception_v3_feature_vector_5.tar.gz *Status: Success *Create Endpoint Config * *Endpoint Config Name: Extract-Features-Endpoint-Config *Instance Type: MlM4Xlarge *Initial Instance Count: 1 *Variant Name: TFS *Status: Success *Create Endpoint * *Endpoint Name: 30-Endpoint *Endpoint Config Name: Extract-Features-Endpoint-Config *Status: Failed Logs * *The Endpoint Status stays "Creating" for some time, then finally becomes "Failed". *Via CloudWatch, I observe the following logs: 2022-11-08T07:40:10.367+01:00 INFO:__main__:PYTHON SERVICE: False 2022-11-08T07:40:10.367+01:00 INFO:__main__:starting services 2022-11-08T07:40:10.367+01:00 Traceback (most recent call last): File "/sagemaker/serve.py", line 502, in <module> ServiceManager().start() File "/sagemaker/serve.py", line 482, in start self._create_tfs_config() File "/sagemaker/serve.py", line 153, in _create_tfs_config raise ValueError("**no SavedModel bundles found!**") 2022-11-08T07:40:10.367+01:00 ValueError: **no SavedModel bundles found!** Could you please help me? In advance thank you for your help! What I found so far * *I checked multiple sources (ValueError: no SavedModel bundles found! when trying to deploy a TF2.0 model to SageMaker and https://github.com/aws/sagemaker-python-sdk/issues/1484 among others), and they point out the problem being an invalid .tar.gz architecture with missing number, which is does not seem to be a problem via the archive recovered from tfhub. A: The problem was indeed an wrong .tar.gz architecture The model.tar.gz recovered from tfhub is * *model.tar.gz -> 5.tar -> variables dir and saved_model.pb While SageMaker is waiting for * *model.tar.gz -> 5.tar -> 5 -> variables dir and saved_model.pb A simple re-packaging saved the day
doc_23535156
remote_file "Core_feature.rpm" do path "#{src_loc}core_feature_v91-2.noarch.rpm" Here, v91-2 is the value which needs to go in dynamically into the recipe, by reading from a properties file. Is this achievable? If yes, how do I go on to implement it.(Have no idea on ruby)! A: You have a few options. The best, in my opinion, is to use a json file rather than a properties file. You can then use the -j flag on your chef-client call to read the json file in as normal attributes on your node. The major caveat there is that normal attributes persist from one chef run to the next, so you'd need to be sure they're being re-set with each chef run. Alternately, you can have jenkins use knife to set the attributes directly on the node. You'll need a plugin knife node attribute set .... OR you could set it on the environment or role, if those are viable options, but they'll involve pulling the environment or role from the server, modifying it, and then pushing it back up. Another option is to use ruby to read your properties file as part of your attributes/xxxx.rb file. You could then set the node attributes from it at whatever precedent level you want. attributes/default.rb properties = IO.read('/path/to/properties/file') # parse properties and set node attributes like this node.default[:something] = <your value>
doc_23535157
vector <int> myVector(10); int myArray[5] = {3,9,14,19,94}; myVector.insert(myVector.begin(), myArray, myArray+3); cout << myVector.at(2) << endl; A: For starters the vector is not empty. It has 10 elements initialized by zeroes. vector <int> myVector(10); As for these arguments myArray, myArray+3 then they specify a range in the array the following way [&myArray[0], &myArray[3]) ^^^ ^^^ That means that the elements pointed to by these pointers &myArray[0], &myArray[1], &myArray[2] will be included in the vector. That is the second value of the range specifies elements before the value. The element pointed to by the pointer &myArray[3] (that is by the pointer myArray + 3) will not be inserted to the vector. Compare for example. If an array has N elements then the range of acceptable indices for its element is [0, N-1] ^^^ ^^^ that can be also specified like [0, N) ^^^ ^^^ A: Arrays in C++ are laid out in a contiguous fashion, so that the address of the array is the same as the address of the first element of the array, followed by the address of the next, and the next, etc. Now when you do myArray + 3, this is actually saying, "Go to the first element and get the third element from the start position". So if you had done (myArray + 1) + 3, this will mean to first from the first position to the second, and using your new position as a reference point, move three positions from there. How does it know where to go? Simply by taking the size in bytes of a single element of the array and multiplying that by the distance you wanted to move forward, and then adding this value to the address of the reference position, and voila! You have gotten to the nth element of the array.
doc_23535158
https://coderwall.com/p/ohk6cg/remote-access-to-ipython-notebooks-via-ssh Is it possible to do similar thing from Windows 10 instead of Mac OS? I guess putty or WSL offer one. https://www.akadia.com/services/ssh_putty.html https://superuser.com/questions/1119946/windows-subsystem-for-linux-ssh-port-forwarding A: You can create an SSH tunnel to connect to the Jupyter Notebook or Jupyter Lab web interface using PUTTY on windows. * *Download the latest version of PUTTY *Open PUTTY and enter the server URL or IP address as the hostname *Now, go to SSH on the bottom of the left pane to expand the menu and then click on Tunnels *Enter the port number which you want to use to access Jupyter on your local machine. Choose 8000 or greater (i.e. 8001, 8002, etc.) to avoid ports used by other services, and set the destination as localhost:8888 where :8888 is the number of the port that Jupyter Notebook is running on. Now click the Add button, and the ports should appear in the Forwarded ports list. *Click the Open button to connect to the server via SSH and tunnel to the desired ports. *In the PUTTY terminal, run Jupyter, where the default port is 8888 * *jupyter lab --no-browser or jupyter-notebook --no-browser *Copy the server path into the browser on your local system and navigate to the notebook * *http://localhost:8888/lab?token=... or http://127.0.0.1:8888/lab?token=... Note: * *If running remotely to your employer, a VPN connection will probably be required. A: As an addendum to this answer, this screenshot shows how putty config looks like: On the Linux machine, I then start Jupyter with: jupyter notebook --no-browser --port=8889 Finally, on the windows (or any remote machine) I enter localhost:8888 in the browser. It asks for the token, that is provided at the shell of the Linux machine. -- Note which port refers to which machine, I have the notebook on port 8889, the browser calls it at localhost:8888 A: I solved this problem by myself. My solution is using Windows Subsystem for Linux (WSL). This offers (virtual?) Linux console like Ubuntu. I just use ssh with -L option on it. A: Follow the steps below. step1- Download putty. step2- Insert ip address or hostname. step3- Go to SSH and expand. step4- Add address of jupyter-notebook to destination column ex: localhost:6666. Add local port such as 8000 to source and press add button. Then connect, it should work. A: I wanted to use the VPN Server feature of my cable box to enable remoting into my network, especially to run jupyter notebook. For my situation, probably not quite the same as anyone elses, this works fine. * *On the cable box, be sure to enable the VPN Server and enable external access. *On the remote Windows 10 computer, add a PPTP VPN specifying cable box's external IP. Connect to the VPN. Verify you can access the network. e.g. You should be able to see the cable box's webpage. *On the Jupyter serving computer, in Windows Defender Firewall, you need to create a new Inbound Rule for a Port. 3.1. General-> Enabled, Allow the connection 3.2. Protocols and Ports-> TCP, 8888 3.3. Scope-> Private *On the Jupyter serving computer, invoke Jupyter (e.g 192.168.0.1, port 8888): jupyter-notebook --ip 192.168.0.1 --port 8888 --no-browser *On the remote computer, you should now be able to access your Jupyter server by browsing to http://192.168.0.8:8888/tree
doc_23535159
Without a preprocessor it's easy for me to separate these two styles .button { color: red; } .link { color: blue; } Now, I want to create mixins for each style @mixin button() color: red @mixin link() color: blue Seems simple enough, but I have no control over how the mixins will be assigned to classes. The user may choose to do this: SASS .btn @include button() ul.nav > li > a @include link() HTML <ul class="nav"> <li> <a href="">Home</a> </li> <li> <a class="btn" href="">Save</a> </li> </ul> Now the button inherits the link styles. Of course, there are a few things I can do with the CSS to "fight" this inheritance, but I'm interested more in an overall technique to namespace mixin styles (if possible). A: Having worked on this for a while (long before posting this question), I'll post my own administrative workaround, if not a total solution: Enforce in your styleguide that naked element selection (e.g. "div {...}) is not allowed. Users will need to do as such: SASS @mixin button() color: red @mixin link() color: blue .btn @include button() ul.nav > li > a.nav-link @include link() Unfortunately, this adds more classes to the HTML. Update I came to hate the above method. Direct descendent selectors all over the place tightly couple the proximity of elements. The cleanest way I can think to solve this problem is to eschew content-descriptive classes for elements (as opposed to blocks.) After all, Blocks like navbars and modals can mean all kinds of things, but what other class do you need to describe a button? Perhaps mixins on the button should be deferred to modifiers on the button. .button // This has already been defined by the underlying framework. .button.send-form @include button-primary() // This is a special button so we'll move in the primary color and a drop shadow.
doc_23535160
slackSend(channel: "builds", message: "Started build", thread_ts: how?) A: node { def slackResponse = slackSend(channel: "cool-threads", message: "Here is the primary message") slackSend(channel: slackResponse.threadId, message: "Thread reply #1") slackSend(channel: slackResponse.threadId, message: "Thread reply #2") } reply broadcasted to the channel message node { def slackResponse = slackSend(channel: "ci", message: "Started build") slackSend(channel: slackResponse.threadId, message: "Build still in progress") slackSend( channel: slackResponse.threadId, replyBroadcast: true, message: "Build failed. Broadcast to channel for better visibility." ) } more info can be found in the official docs https://github.com/jenkinsci/slack-plugin A: Per this article, bot-user mode must be enabled. Adding bot-user:true to the slacksend command will accomplish this, but then I get a pipeline step
doc_23535161
NoSuchElementException: head of empty list However, when I run the same code/Notebook on my Azure Databricks the code run successfully. Does anyone clues why this won't run on Databricks Community, whereas the code runs without any issues on Azure Databricks? %scala val tags = com.databricks.logging.AttributionContext.current.tags //******************************************* // GET VERSION OF APACHE SPARK //******************************************* // Get the version of spark val Array(sparkMajorVersion, sparkMinorVersion, _) = spark.version.split("""\.""") // Set the major and minor versions spark.conf.set("com.databricks.training.spark.major-version", sparkMajorVersion) spark.conf.set("com.databricks.training.spark.minor-version", sparkMinorVersion) //******************************************* // GET VERSION OF DATABRICKS RUNTIME //******************************************* // Get the version of the Databricks Runtime val runtimeVersion = tags.collect( { case (t, v) if t.name == "sparkVersion" => v }).head val runtimeVersions = runtimeVersion.split("""-""") val (dbrVersion, scalaVersion) = if (runtimeVersions.size == 3) { val Array(dbrVersion, _, scalaVersion) = runtimeVersions (dbrVersion, scalaVersion.replace("scala", "")) } else { val Array(dbrVersion, scalaVersion) = runtimeVersions (dbrVersion, scalaVersion.replace("scala", "")) } val Array(dbrMajorVersion, dbrMinorVersion, _) = dbrVersion.split("""\.""") // Set the the major and minor versions spark.conf.set("com.databricks.training.dbr.major-version", dbrMajorVersion) spark.conf.set("com.databricks.training.dbr.minor-version", dbrMinorVersion) //******************************************* // GET USERNAME AND USERHOME //******************************************* // Get the user's name val username = tags.getOrElse(com.databricks.logging.BaseTagDefinitions.TAG_USER, java.util.UUID.randomUUID.toString.replace("-", "")) val userhome = s"dbfs:/user/$username" // Set the user's name and home directory spark.conf.set("com.databricks.training.username", username) spark.conf.set("com.databricks.training.userhome", userhome) //********************************** // VARIOUS UTILITY FUNCTIONS //********************************** def assertSparkVersion(expMajor:Int, expMinor:Int):Unit = { val major = spark.conf.get("com.databricks.training.spark.major-version") val minor = spark.conf.get("com.databricks.training.spark.minor-version") if ((major.toInt < expMajor) || (major.toInt == expMajor && minor.toInt < expMinor)) throw new Exception(s"This notebook must be ran on Spark version $expMajor.$expMinor or better, found Spark $major.$minor") } def assertDbrVersion(expMajor:Int, expMinor:Int):Unit = { val major = spark.conf.get("com.databricks.training.dbr.major-version") val minor = spark.conf.get("com.databricks.training.dbr.minor-version") if ((major.toInt < expMajor) || (major.toInt == expMajor && minor.toInt < expMinor)) throw new Exception(s"This notebook must be ran on Databricks Runtime (DBR) version $expMajor.$expMinor or better, found $major.$minor.") } //******************************************* // CHECK FOR REQUIRED VERIONS OF SPARK & DBR //******************************************* assertDbrVersion(4, 0) assertSparkVersion(2, 3) displayHTML("Initialized module variables & functions...")
doc_23535162
Something's just not sitting right in my brain, and I'm hoping this question will help me put the pieces together. A: You can't go two levels up. You can only decide to call your parent. That class is then responsible for calling its parent in turn. Note that all constructors (except for the root constructors in Object) call a super constructor. If you don't specify it explicitly, or, as @PaulBellora adds, the first statement is a this() call to another constructor of your class, the compiler inserts a super() call as the first statement in every constructor. A: It can only go to the one above it since a class can only inherit from 1 class, and its parent class can only inherit from 1 class and it will call its own parent's constructor. class GrandParent { GrandParent() { } } class Parent extends GrandParent { Parent() { super(); //calls GrandParent() } } class Child extends Parent { Child() { super(); //calls Parent() } }
doc_23535163
System.DllNotFoundException: Unable to load shared library 'OpenCvSharpExtern' or one of its dependencies. I have installed the following packages (nuget) which are required for running the OpenCvSharp4 in the ubuntu environment: * *OpenCvSharp4 *OpenCvSharp4.runtime.ubuntu.18.04-x64 When Checked the dependency of the libOpenCvSharpExtern.so library using the following command: ldd libOpenCvSharpExtern.so Some of the dependency assemblies was missing, so I have installed all the necessary packages which is mentioned in the below GitHub thread which reports the same exact issue: https://github.com/shimat/opencvsharp/issues/889 But still the some of the dependencies are found to be missing and those assemblies name are given below: * *libavcodec.so.57 => not found *libavformat.so.57 => not found *libavutil.so.55 => not found *libswscale.so.4 => not found *libjpeg.so.8 => not found I have also tried installing the following packages “libjpeg62-turbo-dev” and “libavcodec-extra57” for fixing the ‘not found’ assemblies. But still the issue occurred. Any suggestion on how to fix this issue would be appreciated. A: We had the same issue. After a lot of experimentation we got it working with the following setup (Docker): csproj <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netstandard2.0;net472</TargetFrameworks> </PropertyGroup> <ItemGroup> <PackageReference Include="OpenCvSharp4" Version="4.4.0.20200725" /> <PackageReference Include="OpenCvSharp4.runtime.debian.10-amd64" Version="4.3.0.20200424" /> <PackageReference Include="OpenCvSharp4.runtime.win" Version="4.4.0.20200725" /> <PackageReference Include="System.Drawing.Common" Version="4.7.0" /> </ItemGroup> </Project> dockerfile [...] FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 [...] RUN apt-get update && apt-get install -y \ apt-utils \ libgdiplus \ libc6-dev \ libgtk2.0-dev \ libtbb-dev \ libatlas-base-dev \ libvorbis-dev \ libxvidcore-dev \ libopencore-amrnb-dev \ libopencore-amrwb-dev \ libavresample-dev \ x264 \ v4l-utils \ libwebp-dev \ tesseract-ocr \ libtesseract-dev \ libleptonica-dev \ libtiff-dev \ libavcodec-dev \ libavformat-dev \ libswscale-dev \ libdc1394-22-dev \ libxine2-dev \ libv4l-dev RUN apt-get clean && rm -rf /var/lib/apt/lists/* [...] Unfortunately, I'm not entirely sure which of the many apt packages did the trick, I'm just happy it works now ;)
doc_23535164
I've created a JSBin example illustrating the problem. Can anyone explain why throwing an object allows the model to be set but throwing a primitive like string does not? How can I capture the error context if I can't control the code that throws exceptions? Additionally, it seems if I throw new Error('message') or throw new Ember.Error('message') the error is logged to the console but never triggers the error route transition. Is this intended?
doc_23535165
Creating virtual environment which has python 3.6.4 and django 3.1.2 1. py -m pip install --user virtualenv 2. py -m venv env 3. .\env\Scripts\activate (env) C:\Users\abhinavkumar\Desktop\Project>python Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> (env) C:\Users\abhinavkumar\Desktop\Project>pip freeze asgiref==3.2.10 Django==3.1.2 pytz==2020.1 sqlparse==0.3.1 Now creating Django project 1. (env) C:\Users\abhinav\Desktop 2. mkdir project 3. cd project 4. django-admin startproject projectname. Issue i am facing is - I can't see the file projectname inside project directory(which i created in desktop). On again trying to create the project with projectname . it is showing as : CommandError: 'C:\Users\abhinavkumar\Desktop\Project\projectname' already exists A: I would recommend you to run these command in your terminal(where ever you want to be your project) and don't create any folder before these command these commands will automatically will create your project folder for you. * *first running django-admin startproject command *then creating the conda environment through conda --name projectname python-version *then creating django app
doc_23535166
Now when I'm trying to do this in CakePHP 3 (which I'm sorta new to) I fail. Here's what I got: class Ip extends Entity { /** * Fields that can be mass assigned using newEntity() or patchEntity(). * * Note that when '*' is set to true, this allows all unspecified fields to * be mass assigned. For security purposes, it is advised to set '*' to false * (or remove it), and explicitly make individual fields accessible as needed. * * @var array */ protected $_accessible = [ '*' => true, 'id' => false, ]; protected $_virtual = ['ip_address']; protected function _getIpAddress() { $vc = (new FunctionsBuilder())->inet_aton(['ip' => 'literal']); return $vc; } } Here's my Controller method. <?php namespace App\Controller; use App\Controller\AppController; use Cake\ORM\TableRegistry; use Cake\Validation\Validator; use Cake\Database\FunctionsBuilder; /** * Ips Controller * * @property \App\Model\Table\IpsTable $Ips */ class IpsController extends AppController { /** * Index method * * @return void */ public function index() { $this->paginate = [ 'contain' => ['Users'], 'order' => [(new FunctionsBuilder())->inet_aton(['ip' => 'literal'])] ]; $this->set('ips', $this->paginate($this->Ips)); $this->set('_serialize', ['ips']); } By knowing that sorting on virtual properties probably not might work, I'm not sure if I'm using the right approach to et this done. Does anyone recommend best practices to achieve this scenario? A: Use an additional column instead Personally I'd instead additionally store the integer representation of the IP in a separate column and use that one for ordering. This will not only give you better performance as the DBMS can use indices, it will also avoid the additional logic necessary to handle function expressions, and let you use the Pagination component as usual. In the view then simply use the name of the new column, and define the name to display for the sort link manually, like <?= $this->Paginator->sort('ip_int', 'IP') ?> Using expressions Via options or a custom query In its current state, pagination isn't able to handle function expressions, but only column names. At least this is true in combination with the pagination view helper! While you can define expressions for the order option, like $this->paginate['order'] = [ new \Cake\Database\Expression\OrderClauseExpression( $this->Ips->query()->func()->inet_aton(['ip' => 'literal']), 'ASC' ) ]; or use a custom query, like $query = $this->Ips->find(); $query->orderAsc($query->func()->inet_aton(['ip' => 'literal'])); $this->set('ips', $this->paginate($query)); you'll have to use a little bit of custom logic to get this working along with the view, as the pagination helper is desingned to handle column names (strings) only. Dynamic ordering with view helper Now if you want to use the pagination view helper too, you'll have to create some logic that evaluates the sort column and direction generated by the helper, and configure the options/query manually similar to the above examples. Here's a basic example, using the the Query::orderAsc() and Query::orderDesc() methods that make it possible to define the direction when using function expressions (expressions cannot be combined with further values via Query::order()). $query = $this->Ips->find(); $sort = $this->request->query('sort'); if ($sort === null || $sort === 'ip') { $method = 'orderAsc'; if ($this->request->query('direction') === 'desc') { $method = 'orderDesc'; } $query->{$method}($query->func()->inet_aton(['ip' => 'literal'])); } $this->set('articles', $this->paginate($query)); This should be mostly self-explantory, first check whether the sort key genereated by the Paginator helper was passed, and if it wasn't or was and it's your IP column, apply your custom order with respect to the possibly set direction key. If sort is not your IP column, simply ignore it, and the Paginator will pick up the values and evaluate and use them as usual. Similary you could set the direction when manually creating OrderClauseExpression instances, however personally I'd probably stick with using a custom query and the function builder instead. A little more DRY? If you'd like to make this a little more reusable, you may want to look into a custom/extended paginator component, custom finders, and behaviors. Entities are data containers Last but not least, your entity has nothing to do with all this, it's just a data container, so ditch the virtual property, they cannot be used in finds anyways. See also * *Cookbook > Controllers > Components > Pagination > Using Controller::paginate() *Cookbook > Database Access & ORM > Entities > Creating Virtual Properties *Cookbook > Database Access & ORM > Retrieving Data & Results Sets > Custom Finder Methods *Cookbook > Database Access & ORM > Query Builder > Selecting Data
doc_23535167
public class PlaceArrayAdapter extends ArrayAdapter<PlaceArrayAdapter.PlaceAutocomplete> implements Filterable { private static final String TAG = "PlaceArrayAdapter"; private GoogleApiClient mGoogleApiClient; private AutocompleteFilter mPlaceFilter; private LatLngBounds mBounds; private ArrayList<PlaceAutocomplete> mResultList; /** * Constructor * * @param context Context * @param resource Layout resource * @param bounds Used to specify the search bounds * @param filter Used to specify place types */ public PlaceArrayAdapter(Context context, int resource, LatLngBounds bounds, AutocompleteFilter filter) { super(context, resource); mBounds = bounds; mPlaceFilter = filter; } public void setGoogleApiClient(GoogleApiClient googleApiClient) { if (googleApiClient == null || !googleApiClient.isConnected()) { mGoogleApiClient = null; } else { mGoogleApiClient = googleApiClient; } } @Override public int getCount() { return mResultList.size(); } @Override public PlaceAutocomplete getItem(int position) { return mResultList.get(position); } private ArrayList<PlaceAutocomplete> resultList; private ArrayList<PlaceAutocomplete> getPredictions(CharSequence constraint) { if (mGoogleApiClient != null) { Log.i(TAG, "Executing autocomplete query for: " + constraint); PendingResult<AutocompletePredictionBuffer> results = Places.GeoDataApi .getAutocompletePredictions(mGoogleApiClient, "Россия," + constraint.toString(), mBounds, mPlaceFilter); AutocompletePredictionBuffer autocompletePredictions = results .await(60, TimeUnit.SECONDS); final Status status = autocompletePredictions.getStatus(); if (!status.isSuccess()) { Toast.makeText(getContext(), "Error: " + status.toString(), Toast.LENGTH_SHORT).show(); Log.e(TAG, "Error getting place predictions: " + status .toString()); autocompletePredictions.release(); return null; } Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator(); resultList = new ArrayList<>(autocompletePredictions.getCount()); while (iterator.hasNext()) { AutocompletePrediction prediction = iterator.next(); resultList.add(new PlaceAutocomplete(prediction.getPlaceId(), prediction.getDescription())); } autocompletePredictions.release(); return resultList; } Log.e(TAG, "Google API client is not connected."); return null; } @Override public Filter getFilter() { Filter filter = new Filter() { @Override protected FilterResults performFiltering(CharSequence constraint) { FilterResults results = new FilterResults(); if (constraint != null) { // Query the autocomplete API for the entered constraint mResultList = getPredictions(constraint); if (mResultList != null) { // Results results.values = mResultList; results.count = mResultList.size(); } } return results; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { if (results != null && results.count > 0) { // The API returned at least one result, update the data. notifyDataSetChanged(); } else { // The API did not return any results, invalidate the data set. notifyDataSetInvalidated(); } } }; return filter; } public class PlaceAutocomplete { public CharSequence placeId; public CharSequence description; public CharSequence streetAddress; PlaceAutocomplete(CharSequence placeId, CharSequence description) { this.placeId = placeId; this.description = description; } @Override public String toString() { return description.toString(); } } } So the problem is it returns only Description, while I need the street Address only, without country and city, when I try to rewrite code like this: private ArrayList<PlaceAutocomplete> getPredictions(CharSequence constraint) { if (mGoogleApiClient != null) { Log.i(TAG, "Executing autocomplete query for: " + constraint); PendingResult<AutocompletePredictionBuffer> results = Places.GeoDataApi .getAutocompletePredictions(mGoogleApiClient, "Россия," + constraint.toString(), mBounds, mPlaceFilter); AutocompletePredictionBuffer autocompletePredictions = results .await(60, TimeUnit.SECONDS); final Status status = autocompletePredictions.getStatus(); if (!status.isSuccess()) { Toast.makeText(getContext(), "Error: " + status.toString(), Toast.LENGTH_SHORT).show(); Log.e(TAG, "Error getting place predictions: " + status .toString()); autocompletePredictions.release(); return null; } Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator(); resultList = new ArrayList<>(autocompletePredictions.getCount()); while (iterator.hasNext()) { AutocompletePrediction prediction = iterator.next(); PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi .getPlaceById(mGoogleApiClient, prediction.getPlaceId()); placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() { @Override public void onResult(PlaceBuffer places) { if (!places.getStatus().isSuccess()) { Log.e("ERROR", "Place query did not complete. Error: " + places.getStatus().toString()); return; } final Place place = places.get(0); resultList.add(new PlaceAutocomplete(place.getId(), place.getName())); } }); } autocompletePredictions.release(); return resultList; } Log.e(TAG, "Google API client is not connected."); return null; } But it works very slow, and returns data only in English, while I need it to be returned in Russian language. So if anyone ever tried to do such things - please help :)
doc_23535168
For ex; If I have bunch of streams like Stream<String> doc1 = Stream.of("a", "b", "c", "b", "c"); Stream<String> doc2 = Stream.of("b", "c", "d"); Stream<Stream<String>> docs = Stream.of(doc1, doc2); I am able to count the occurrences of each word in a doc by doing List<Map<String, Long>> collect = docs .map(doc -> doc.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))) .collect(Collectors.toList()); This results in a structure as [ {a=1, b=2, c=2}, {b=1, c=1, d=1} ] However, I would like to have the count be associated with the docId from which it originated from. For example I would like to have a structure as [ {a=(randId1, 1), b=(randId1, 2), c=(randId1, 2)}, {b=(randId2, 1), c=(randId2, 1), d=(randId2, 1)} ] where randId1 and randId2 can be generated at runtime(I just need a way to trace back to a unique source) and () represents a Pair class from Apache. I have tried to wrap the doc in a Pair of (docId, doc) but I am stuck at modifying the Collectors.counting() substitution List<Map<String, Long>> collect = docs.map(doc -> Pair.of(UUID.randomUUID(), doc)) .map(p -> p.getRight().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))) .collect(Collectors.toList()); How do I get the output in the format needed ? A: This ain't very readable... I've replaced Pair with AbstractMap.SimpleEntry since it does the same thing and I already have it on my classpath. List<Map<String, AbstractMap.SimpleEntry<Long, UUID>>> result = docs.map(doc -> doc.collect(Collectors.collectingAndThen( Collectors.groupingBy(Function.identity(), Collectors.counting()), map -> { UUID rand = UUID.randomUUID(); return map.entrySet().stream().collect(Collectors.toMap( Entry::getKey, e -> new AbstractMap.SimpleEntry<>(e.getValue(), rand))); }))) .collect(Collectors.toList()); System.out.println(result); And the output of this: [{a=1=890d7276-efb7-41cc-bda7-f2dd2859e740, b=2=890d7276-efb7-41cc-bda7-f2dd2859e740, c=2=890d7276-efb7-41cc-bda7-f2dd2859e740}, {b=1=888d78a5-0dea-4cb2-8686-c06c784d4c66, c=1=888d78a5-0dea-4cb2-8686-c06c784d4c66, d=1=888d78a5-0dea-4cb2-8686-c06c784d4c66}] A: How about this? List<Map<String, Pair<UUID, Long>>> collect = docs.map(doc -> { UUID id = UUID.randomUUID(); return doc.collect(groupingBy( identity(), // v--- adapting Collector<?,?,Long> to Collector<?,?,Pair> collectingAndThen(counting(), n -> Pair.of(id, n)) )); }).collect(Collectors.toList()); I'm just copy your code snippet and adapting your last generic argument Long to Pair by Collectors#collectingAndThen: // v--- the code need to edit is here List<Map<String, Long>> collect = docs .map(doc -> doc.collect(Collectors.groupingBy(Function.identity() // the code need to edit is here ---v ,Collectors.counting()))) .collect(Collectors.toList()); A: I think you could do it as follows: List<Map<String, Pair<UUID, Long>>> result = docs .map(doc -> Pair.of(UUID.randomUUID(), doc)) .map(p -> p.getRight() // right: doc stream .map(word -> Pair.of(word, p.getLeft()))) // left: uuid .map(stream -> stream.collect(Collectors.toMap( Pair::getLeft, // word p -> Pair.of(p.getRight(), 1L), // right: uuid (p1, p2) -> Pair.of(p1.getLeft(), p1.getRight() + p2.getRight())))) // merge .collect(Collectors.toList()); I've use Pair.of multiple times to pass around both the word and the random doc id. Finally, I've used Collectors.toMap with a function to merge values when there's a collision on the keys. The result is exactly as you want, i.e.: [{a=(fa843dec-3e02-4811-b34f-79949340b4c5,1), b=(fa843dec-3e02-4811-b34f-79949340b4c5,2), c=(fa843dec-3e02-4811-b34f-79949340b4c5,2)}, {b=(dc2ad8c7-298a-433e-8b27-88bd3c8eaebb,1), c=(dc2ad8c7-298a-433e-8b27-88bd3c8eaebb,1), d=(dc2ad8c7-298a-433e-8b27-88bd3c8eaebb,1)}] Maybe this could be improved by moving the code that collects the inner streams to a helper method: private Map<String, Pair<UUID, Long>> collectInnerDoc( Stream<Pair<String, UUID>> stream) { return stream.collect(Collectors.toMap( Pair::getLeft, // word p -> Pair.of(p.getRight(), 1L), // random doc id (p1, p2) -> Pair.of(p1.getLeft(), p1.getRight() + p2.getRight()))); // merge } You could then use this method to collect your outer stream: List<Map<String, Pair<UUID, Long>>> result = docs .map(doc -> Pair.of(UUID.randomUUID(), doc)) .map(p -> p.getRight() // right: doc stream .map(word -> Pair.of(word, p.getLeft()))) // left: uuid .map(this::collectInnerDoc) // map inner stream to map .collect(Collectors.toList()); This assumes the private method is declared in the same class you are collecting the outer stream. If this is not the case, change the this::collectInnerDocs method reference accordingly.
doc_23535169
After making this call: AFJSONRPCClient *client = [[AFJSONRPCClient alloc] initWithURL:[NSURL URLWithString:kAPIHost]]; [client invokeMethod:@"auth.login" withParameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { //success handling completionBlock(responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { //error handling NSLog(@"error: %@", [error description]); }]; I'm getting this in the NSLog for error: error: Error Domain=AFNetworkingErrorDomain Code=-1016 "Expected content type {( "text/json", "application/json", "text/javascript" )}, got application/json-rpc" UserInfo=0xd02f680 {NSLocalizedRecoverySuggestion={"error": null, "jsonrpc": "2.0", "id": "1", "result": {"key": "38c491c894aa057d532e8b314d", "success": true}}, AFNetworkingOperationFailingURLResponseErrorKey=, NSErrorFailingURLKey=someurl, NSLocalizedDescription=Expected content type {( "text/json", "application/json", "text/javascript" )}, got application/json-rpc, AFNetworkingOperationFailingURLRequestErrorKey=http://rpc.development.hotelzilla.net/>} What I also don't understand is why the response is appearing with all the correct data (highlighted in bold). So far, this is what I tried: [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"application/json-rpc"]]; // Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1 [self setDefaultHeader:@"Accept" value:@"application/json-rpc"]; [self registerHTTPOperationClass:[AFJSONRequestOperation class]]; Any ideas? A: Your first attempted solution of [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"application/json-rpc"]]; probably would have worked if you were having this issue with just AFJSONRequestionOperation but since you are using this client that isn't a subclass of AFHTTPRequestOperation so it doesn't respond to this method. That might be a viable solution if you alter the code of the client you are using. In the source code an AFJSONRequestOperation called operation is created, if you attempted to use [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"application/json-rpc"]]; somewhere around here, you may be able to fix the issue.
doc_23535170
MAIN ACTIVITY.java: public void onClick(View v) { String str=""; if (checkBox1.isChecked()) { str =checkBox1.getText().toString()+"TEST"; } else { checkBox1.setEnabled(false); emailIntent.putExtra(Intent.EXTRA_TEXT, "+ "\n Fehler: " + checkBox1.getText().toString(); } } XML: <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="5sp" android:text="@string/Checkbox1" android:id="@+id/checkBox1" android:layout_row="0" android:layout_column="0"/> A: What i think you should do is add a listener on your checkbox like checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) { // Here if the checkBox is checked you can set Email text if(isChecked){ txt.setText("Whatever text you want."); } } } ); if your requirement is still not matched try posting your code. Okay try this XML: <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="5sp" android:text="@string/Checkbox1" android:id="@+id/checkBox1" android:layout_row="0" android:layout_column="0"/> Java Code: checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) { // Here if the checkBox is checked you can set Email text if(isChecked){ String str = "Name of checkbox TEST"; } else{ checkBox.setEnabled(false); } } } ); A: try, emailIntent.putExtra(Intent.EXTRA_TEXT, checkBox1.getText().toString()+":"+checkBox1.isChecked());
doc_23535171
I cannot get the menu to align to the bottom of the logo (which has float: left;). Also, after testing the margin settings with a border on all elements (border: 1px solid;) successfully, the minute I remove the borders everything reshuffles, and I have to add padding: 1px; in order to keep them in place. Could someone please take a look and advise me as to the correct application of the relevant CSS? EDIT: Please note that the code does indeed work. My issue is that it is a hack (essentially adding non-existent padding to get the job done). A: What I would advise that you do is to absolutely position the logo and navigation containers and then set the position and sizes of each element to suit. This IMHAO is more robust and reliable that floating header elements. ie in the css: header { width: 100%; height: xpx; postion:relative; /* This makes elements inside that have position:absolute act relative to the container, useful if you need to move it around */ top:0; left:0; } #logo { background: blah; width:xpx; height:xpx; position: absolute; top:0px; left:0px; } nav.top_nav { width:xpx; height:xpx; position: absolute; top:0px; left:[header width + some padding]px; } Of course if needed you can tweek the zeros for padding.
doc_23535172
Simple example accelerate.c: #include <stdio.h> #include <Accelerate/Accelerate.h> double vectorvector_product(double * a, double * b, int dim){ // This function returns in res the elementwiseproduct between a and b, // a and b must have the same dimension dim. return cblas_ddot(dim,a,1,b,1); } int main(){ double a[4] = {1.0,2.0,3.0,4.0}; double b[4] = {1.0,2.0,3.0,4.0}; double res = vectorvector_product(a,b,4); printf("Res: %f",res); } I compiled it with clang: >>> cc -Wall -g -c accelerate.c And obtained a new file accelerate.o What would I do now in order to properly link it? All I know is that this Accelerate framework is located at /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/Accelerate.framework >>> ls /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/Accelerate.framework Accelerate.tbd Frameworks Headers Modules Versions p.s.: If I Run this program with Xcode it magically works, but I need to do it from the command line and I would like to know what I'm doing. A: Apparently the correct way to link Accelerate.h is by passing -framework Accelerate as argument e.g. >>> cc -framework Accelerate accelerate.c will compile and link accelerate.c by generating an executable a.out.
doc_23535173
Are Xcode 9 developer tools out? A: When you install Xcode, you'll install command line tools too. You can verify by typing $ gcc. If you get an error like:clang: error: no input files, you already have command line tools. But just for info, you can do $ xcode-select --install if you want the command line tools. Now to use both Xcode8 and Xcode9 Beta together, you need to do the following: 0) Close all open Xcode projects and quit Xcode 1) Rename your Xcode (8 which will be just Xcode.app in your /Applications directory) to something like Xcode8 . 2) Type in $ xattr -d com.apple.quarantine /Users/<your_user_name>/<the downloaded directory>/Xcode-beta.app. Here you need to drag your xcode-beta(xcode9) to your terminal once you just type $ xattr -d com.apple.quarantine. Now, move your Xcode-beta into your /Applications directory and rename it as Xcode . 3) Type in $ sudo xcode-select -s /Applications/Xcode(which is 9 now).app/Contents/Developer . If you want to switch back to 8, just type in the same command with Xcode8.app in the place of Xcode.app. 4) Verify you're using Xcode 9 by typing $ xcode-select -print-path. You can see that it'll point to Xcode.app which actually is Xcode-beta, i.e., Xcode 9. Xcode-beta is xcode 9.
doc_23535174
For example, If I run: $cred = Get-Credential -Credential 10.20.0.13\administrator $Session=New-PsSession -ComputerName 10.20.0.13 -Credential $cred Invoke-command -ScriptBlock {Start-Process -FilePath c:\installers\dotNetFx40_Full_x86_x64.exe -ArgumentList "/q /norestart /log c:\" -Wait} -Credential $cred -ComputerName 10.20.0.13 I can see on the remote machine that the installer runs (in task manager), the temporary folder is created on the root of c:\, the files extracted and then I get a 700kb log file. At the foot of that log file I get: OS Version = 6.1.7601, Platform 2, Service Pack 1 OS Description = Win2K8R2 - x64 Standard Edition Service Pack 1 CommandLine = C:\b65da67b927bfb71c84adcecefc019\Setup.exe /q /norestart /log c:\ /x86 /x64 TimeZone = GMT Standard Time Initial LCID = 2057 Using Simultaneous Download and Install mechanism Operation: Installing Package Name = Microsoft .NET Framework 4 Setup Package Version = 4.0.30319 User Experience Data Collection Policy: Disabled Number of applicable items: 11 Exe (C:\b65da67b927bfb71c84adcecefc019\SetupUtility.exe) succeeded. Exe Log File: dd_SetupUtility.txt ServiceControl operation succeeded! ServiceControl operation succeeded! Exe (C:\b65da67b927bfb71c84adcecefc019\Windows6.1-KB958488-v6001-x64.msu) failed with 0x5 - Access is denied. . Final Result: Installation failed with error code: (0x00000005), "Access is denied. " (Elapsed time: 0 00:01:12). So access is denied. However, using the exact same credentials I can perform other tasks (add server roles in Powershell, add windows features via powershell etc) and I can RDP onto the box using the same username/password and run the installer there (which completes fine). I’m missing something somewhere, but can’t seem to find out what it is. I can see its worked for someone else (http://social.technet.microsoft.com/Forums/windowsserver/ar-SA/3045eb24-7739-4695-ae94-5aa7052119fd/install-dotnet-framework-4-using-powershell?forum=winserverpowershell) so no idea why I’m getting this. Any help much appreciated. Thanks A: You're creating a session but never using it? I haven't tried this on a remote computer beforey, but try to run the process "as admin" by using -Verb RunAs, like this: $cred = Get-Credential -Credential 10.20.0.13\administrator $Session=New-PsSession -ComputerName 10.20.0.13 -Credential $cred Invoke-command -ScriptBlock {Start-Process -FilePath c:\installers\dotNetFx40_Full_x86_x64.exe -ArgumentList "/q /norestart /log c:\" -Wait -Verb RunAs } -Session $Session A: While installation of .NET framework 4.0, It installs some updates as well (.msu) files. But when we are installaing .NET 4.0 remotely, It fails because of these updates. The reason behind that is, it's not allowable to install these updates remotely. Please find the KB article here. This article also mentioned the workaround for this. A: you have servername in textfile or machine names in OU based. create .bat which has .exe to run C:\temp\xxx.exe /S /qn $ou='OU=subou3,OU=subou2,OU=subou1,DC=domain,DC=com' $filter = @("machinename1", "machinename2") $compute= Get-ADComputer -Filter * -SearchBase $ou | where-object{$filter -contains $_.name} $comp=$compute.name foreach ($Computer in $Comp) { Write-Host "Processing $Computer" { Write-Host " Installing application on $Comp" psexec $Compter path\XXX.bat /S /qn } }
doc_23535175
As an example, imagine I have an entity: @Entity(name = "Mechanic") public class Mechanic { @Id private Long id; //... and a Car that I want to reference a Mechanic.id: @Entity(name = "Car") public class Car { //... @NotNull private Long mechanic_id; From an Object perspective, this would be a unidirectional, one to one relationship with the Car requiring a Mechanic.id and the Mechanic not needing any back reference to Car. All I want out of this is to store the Mechanic.id ONLY. For the purposes of this question it is not useful to have a @OneToOne (or @OneToMany etc) relationship with the entity reference, I'm explicitly trying to avoid that but still retain the underlying integrity that a FK will provide. JPA 2 and I'm using EclipseLink.
doc_23535176
Private Sub CommandButton5_Click() Sub SavePlan() Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code Dim sws As Worksheet: Set sws = wb.Worksheets("Main") Dim FolderPath As String: FolderPath = wb.Path Dim dFileName As String: dFileName = sws.Range("C6").Value Dim dFilePath As String dFilePath = FolderPath & Application.PathSeparator & dFileName sws.Copy ' copy to a new (destination) workbook Dim dwb As Workbook: Set dwb = Workbooks(Workbooks.Count) Application.DisplayAlerts = False ' overwrite without confirmation dwb.SaveAs Filename:=dFilePath Application.DisplayAlerts = True dwb.Close SaveChanges:=False MsgBox "Worksheet backed up.", vbInformation End Sub A: Please, try using the next adapted code. It assumes that dFilePath does not contain any extension. If it does, you must tell us what it is and I can adapt the code: Sub SavePlan() Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code Dim sws As Worksheet: Set sws = wb.Worksheets("Main") Dim FolderPath As String: FolderPath = wb.Path Dim dFileName As String: dFileName = sws.Range("C6").value Dim dFilePath As String dFilePath = FolderPath & Application.PathSeparator & dFileName 'no extension... sws.Copy ' it creates a new workbook containing only the copied sheet Dim dwb As Workbook: Set dwb = ActiveWorkbook Application.DisplayAlerts = False ' overwrite without confirmation dwb.saveas FileName:=dFilePath & ".xlsx", FileFormat:=xlWorkbookDefault dwb.ExportAsFixedFormat Type:=xlTypePDF, FileName:=dFilePath & ".pdf", _ Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False Application.DisplayAlerts = True dwb.Close False MsgBox "Worksheet backed up.", vbInformation End Sub
doc_23535177
What are the setup.py and install.sh files used for? A: setup.py is the canonical name for the installer of a Python package. For example, when you run pip install x, pip runs the setup.py of the package you installed. In this case, install.sh is just a shortcut for running setup.py. There's no way to use a package without installing it, since it won't have what it needs to operate properly.
doc_23535178
like Camera,Gallery etc. now i would like to place my app in this list. I Saw some apps like "paint for whatsapp" where this was possible. I tried "android.media.action.IMAGE_CAPTURE" but this only replaces the System-Camera. I want to have a new point in the List. Thanks in advance Jonas A: This works for me: <intent-filter> <action android:name="android.intent.action.PICK" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> </intent-filter> A: You can create your own Intent-Action or appear in other lists when using different itentfilter configurations, see http://developer.android.com/guide/topics/intents/intents-filters.html for more details.
doc_23535179
I don't want to use the other contentModes like top, bottom, etc because in my app you can drag the imageView and as you move it, it shows the parts of the image that are under the imageView. In other words the imageView is like a window to the image itself. How can I change which part of the image the imageView is showing? Thanks! A: Various possibilities here: * *Don't use a UIImageView. Use a normal view and manipulate its layer. Give the layer content and use its contentsRect to describe which part of the view should be visible. *Do use a UIImageView. Show the whole image. Put the image view inside a scroll view. Let the user drag to scroll. (A scroll view is a "window" to what's inside it.) The second one is easier because the scroll view responds to dragging, whereas with the first possibility you'd have to detect dragging separately and keep setting the contentsRect in response, thus reinventing the wheel.
doc_23535180
On Android the documentation clearly states that 44,1 kHz is currently the only value to be guaranteed to work on all devices (link). However, I can not find any information about iOS. I can not find any concrete value which would be working on all devices. As far as I understand it newer iPhones currently use 48 kHz by default. I can resample the audio as suggested in this Stack Overflow question link. Is there any value that is guaranteed to be supported on all iOS devices?
doc_23535181
const express = require("express"); const mysql = require('mysql'); const connection = mysql.createConnection({ host : 'localhost', user : 'root', password: 'password', database: 'applicants' }); const app = express(); app.get('/', (req, res) => { let sql = "SELECT * FROM applicant_info"; connection.query(sql, (err, results) =>{ res.send(results); }) }); app.listen('3000', () => { console.log('Server running on port 3000'); connection.connect((err) => { if(err) { }; console.log('Database Connected!'); }) }); a sidenote about the code is that i for some reason can't run it with the "throw" command, which is why the 'err' if-statements are currently empty. I hope to dear god that this is not the cause, as i have no idea how to fix it. Here is a picture of what i receive from my browser: Image Description A: You have an issue with your require : Error: Cannot find module 'mySQL' it should be : const mysql = require('mysql'); so your server does not run, and you have a 404 on the browser. Once it's fixed, start your server, and you should see this in the console : Server running on port 3000 Database Connected! you should see your data when going to http://localhost:3000 edit: added more debug to your code : app.get('/', (req, res) => { console.log('get called'); let sql = "SELECT * FROM applicant_info"; connection.query(sql, (err, results) =>{ res.send(results); }) }); app.listen('3000', () => { connection.connect((err) => { if(err) { console.log('Database not connected!'); console.log(err) } else { console.log('Server running on port 3000'); console.log('Database Connected!'); } }) }); A: $servername = "localhost"; $username = "username"; $password = "password";$conn = new mysqli($servername, $username, $password);//Check connection if ($conn->connect_error) { die("Connection failed: ". $conn->connect_error);}echo "Connected successfully"; check DB is connected or not
doc_23535182
char* test = "testInteger(5).workOnReturn("doIt")[10]" int ret = execute(test); What if I use the 'extern' keyword? Suppose I have a whole bunch of C++ implementations and classes. Couldn't I just define the same things in C with 'extern' and provide a dummy implementation and on runtime, it would access the C++ library with the actual implementation? A: Perhaps you could customize your GCC compiler (e.g. with a MELT extension) to produce somehow a C interface to your library (perhaps by annotating relevant C++ functions with your own #pragma-s ....) But your question is too vague to get a more precise answer. What is your C++ library, how should it be used in C++? Look at how other C++ libraries interface to C; e.g. look inside the source code of PPL A: If you want to use C++ from C, it can be done only in an extremely limited way, and as far as the C++ code is explicitly built for it (that means basically throwing away most for what makes C++ C++). Won't happen in your case. Your ways out are to just use C++ or get a library for C. Anything else will hurt too much to make any sense.
doc_23535183
I don't want to write in every view smth like if domain =='cool' render template 'cool/index' else regular template end i guess i need to do something in application controller for it A: You can achieve this in your ApplicationController like this. By passing a symbol to the layout method it allows you to dynamically assign a layout to all controllers in the application. class ApplicationController layout :special_layout private def special_layout (domain =='cool') ? "cool" : "not_cool" end end
doc_23535184
APPLICATION FAILED TO START Description: Failed to configure a DataSource: no embedded datasource could be configured. Reason: Failed to determine a suitable driver class Action: Consider the following: If you want an embedded database (H2, HSQL or Derby), please put it on the classpath. If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active). My application properties: spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true spring.datasource.url=jdbc:postgres://********:******:port/database spring.datasource.username=****** spring.datasource.password=*** spring.jpa.hibernate.ddl-auto=update spring.http.cors.enabled=true My pom: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.2</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.bird</groupId> <artifactId>bird</artifactId> <version>0.0.1-SNAPSHOT</version> <name>bird</name> <description>Demo project for Spring Boot</description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> A: Set followings In your application.properties spring.datasource.url=jdbc:postgresql://<HOST>:<PORT>/<DATABASE> spring.datasource.username=<USER> spring.datasource.password=<PASSWORD> spring.datasource.driver-classname=org.postgresql.Driver pom.xml <dependencies> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>42.2.20</version> </dependency> </dependencies> From your heroku postgres administration Settings option you can inspect the values Bonus : More appropriate option would be capture the application.properties values from environment. To do so change your application properties like following spring.datasource.url=${SPRING_DATASOURCE_URL} spring.datasource.username=${SPRING_DATASOURCE_USERNAME} spring.datasource.password=${SPRING_DATASOURCE_PASSWORD} spring.datasource.driver-classname=org.postgresql.Driver Then in heroku dashboard your application settings there is a option named Reveal config var. There add following environment variables SPRING_DATASOURCE_URL=jdbc:postgresql://<HOST>:<PORT>/<DATABASE> SPRING_DATASOURCE_USERNAME=<USER> SPRING_DATASOURCE_PASSWORD=<PASSWORD> Thus your application stays decoupled from the environment. A: Please add below property in your application.properties though spring detects it based on URL spring.datasource.driver-class-name=org.postgresql.Driver Also please ensure you have below dependency in your pom.xml <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> </dependency>
doc_23535185
03-24 15:14:21.180: E/AndroidRuntime(857): FATAL EXCEPTION: main 03-24 15:14:21.180: E/AndroidRuntime(857): Process: com.gosha.bux, PID: 857 03-24 15:14:21.180: E/AndroidRuntime(857): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.gosha.bux/com.gosha.bux.perv}: java.lang.ClassNotFoundException: Didn't find class "com.gosha.bux.perv" on path: DexPathList[[zip file "/data/app/com.gosha.bux-2.apk"],nativeLibraryDirectories=[/data/app-lib/com.gosha.bux-2, /system/lib]] 03-24 15:14:21.180: E/AndroidRuntime(857): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121) 03-24 15:14:21.180: E/AndroidRuntime(857): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 03-24 15:14:21.180: E/AndroidRuntime(857): at android.app.ActivityThread.access$800(ActivityThread.java:135) 03-24 15:14:21.180: E/AndroidRuntime(857): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 03-24 15:14:21.180: E/AndroidRuntime(857): at android.os.Handler.dispatchMessage(Handler.java:102) 03-24 15:14:21.180: E/AndroidRuntime(857): at android.os.Looper.loop(Looper.java:136) 03-24 15:14:21.180: E/AndroidRuntime(857): at android.app.ActivityThread.main(ActivityThread.java:5017) 03-24 15:14:21.180: E/AndroidRuntime(857): at java.lang.reflect.Method.invokeNative(Native Method) 03-24 15:14:21.180: E/AndroidRuntime(857): at java.lang.reflect.Method.invoke(Method.java:515) 03-24 15:14:21.180: E/AndroidRuntime(857): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 03-24 15:14:21.180: E/AndroidRuntime(857): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 03-24 15:14:21.180: E/AndroidRuntime(857): at dalvik.system.NativeStart.main(Native Method) 03-24 15:14:21.180: E/AndroidRuntime(857): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.gosha.bux.perv" on path: DexPathList[[zip file "/data/app/com.gosha.bux-2.apk"],nativeLibraryDirectories=[/data/app-lib/com.gosha.bux-2, /system/lib]] 03-24 15:14:21.180: E/AndroidRuntime(857): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56) 03-24 15:14:21.180: E/AndroidRuntime(857): at java.lang.ClassLoader.loadClass(ClassLoader.java:497) 03-24 15:14:21.180: E/AndroidRuntime(857): at java.lang.ClassLoader.loadClass(ClassLoader.java:457) 03-24 15:14:21.180: E/AndroidRuntime(857): at android.app.Instrumentation.newActivity(Instrumentation.java:1061) 03-24 15:14:21.180: E/AndroidRuntime(857): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112) 03-24 15:14:21.180: E/AndroidRuntime(857): ... 11 more 03-24 15:14:43.061: I/Process(857): Sending signal. PID: 857 SIG: 9 Manifest <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.gosha.bux" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" android:debuggable="true" > <activity android:name="com.gosha.bux.perv" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.gosha.bux.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="com.gosha.bux.MAINACTIVITY" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> </application> splash activity public class perv extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(com.gosha.bux.R.layout.pervy); Thread timer = new Thread(){ public void run(){ try{ sleep(5000); } catch (InterruptedException e){ e.printStackTrace(); } finally { Intent openMainActivity = new Intent("com.gosha.bux.MAINACTIVITY"); startActivity(openMainActivity); } } }; } } A: Simply do this Intent i = new Intent(getapplicationcontext(), TARGET_Activity.class); startActivity(i); and in manifest <activity android:name="com.your.packagename.TARGET_Activity" android:screenOrientation="portrait" > </activity> A: In your depends compile: 'com.android.support:multidex:1.0.0' and set multiDexEnabled true. In YourApplication: extends MultiDexApplication add this: @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); MultiDex.install(this); } Finally in AndroidManifest declare: android:name=".MyApplication" A: Intent openMainActivity = new Intent("com.gosha.bux.MAINACTIVITY"); startActivity(openMainActivity); is wrong, instead use: Intent openMainActivity = new Intent(this, YourMainActivity.class); A: In the Public class perv you wrote this: setContentView(com.gosha.bux.R.layout.pervy); You wrote pervy, instead of perv and this will possibly cause this error
doc_23535186
When removing the nowait clause it works just fine. So I think the issue is that it becomes an OpenMP task and I'm struggling getting it right. #pragma omp target teams distribute parallel for reduction( +: sum) collapse(2) nowait depend(in: a, b) depend(out: sum) for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { double c = 0; for (int k = 0; k < n; k++) { c += /* some computation */ } sum += fabs(c); } } A: The OpenMP 5.2 specification states: The target construct generates a target task. The generated task region encloses the target region. If a depend clause is present, it is associated with the target task. [...]. If the nowait clause is present, execution of the target task may be deferred. If the nowait clause is not present, the target task is an included task. This means that your code is executed in a task with a possibly deferred execution (with nowait). Thus, it can be executed at the end of the parallel in the worst case, but always before all the dependent tasks and taskwait directives waiting for the target task (or the ones including a similar behaviour like taskgroup). Because of that, you need not to modify the working arrays (nor release them) during this time span. If you do, the behaviour is undefined. You should especially pay attention to the correctness of synchronization points and task dependencies in your code (it is impossible for us to check that with the current incomplete provided code).
doc_23535187
miguel_btn.addEventListener(MouseEvent.CLICK,video_miguel); function video_miguel(event:MouseEvent):void { var conexion10:NetConnection= new NetConnection(); conexion10.connect(null); var display10:NetStream= new NetStream(conexion10); display10.play("Miguel_1.flv"); var video10:Video=new Video(); video10.attachNetStream(display10); video10.x= 150; video10.y= 250; stage.addChild(video10); display10.addEventListener(AsyncErrorEvent.ASYNC_ERROR,nomostrar10); function nomostrar10(event:AsyncErrorEvent):void { } } and i was trying to removing them with : if (event.keyCode == Keyboard.RIGHT) { nextFrame(); video10.clear(); } but i am a new at as3 and it does not work. Thanks. A: Since you didn't post the entire code it is difficult to determine the problem. I believe the issue lies in problem that your keyboard event is not firing. I would recommend trying the following code to see if it resolves your problem. Instead of calling video10.clear(); I removed the object entirely as well. import flash.events.MouseEvent; import flash.events.KeyboardEvent; import flash.net.NetConnection; import flash.media.Video; import flash.net.NetStream; miguel_btn.addEventListener(MouseEvent.CLICK, video_miguel); stage.addEventListener(KeyboardEvent.KEY_DOWN, handleKeyDown); var video10:Video; var display10:NetStream; function video_miguel(event:MouseEvent):void { display10 = new NetStream(new NetConnection()); display10.play("Miguel_1.flv"); video10 = new Video(); video10.attachNetStream(display10); video10.x = 150; video10.y = 250; stage.addChild(video10); } function handleKeyDown(ke:KeyboardEvent):void { //keycode 39 is the right arrow key. if(ke.keyCode == 39) { nextFrame(); //We can completely remove the video by calling the function below. stage.removeChild(video10); } } A: I agree with Andreas, and I would suggest to close netStream and still clear the video: display10.close(); video10.clear(); stage.removeChild(video10);
doc_23535188
<android.support.v4.app.FragmentTabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/tabhost" android:layout_width="match_parent" android:layout_height="match_parent" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TabWidget android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="0" android:orientation="horizontal" /> <FrameLayout android:id="@+id/tabFrameLayout" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /> </LinearLayout> </android.support.v4.app.FragmentTabHost> A: You just add this two lines into your tab widget that's all... <TabWidget android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" android:gravity="bottom" android:layout_weight="0" android:orientation="horizontal" /> A: It is bad practice to locate tabs at bottom, but if you need, hide android widget by weight=0 and work with your own "realcontent" FrameLayut <TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="0dp" android:layout_height="0dp" android:layout_weight="0"/> <FrameLayout android:id="@+android:id/realtabcontent" android:background="@drawable/bg_main_app_gradient" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"/> <TabWidget android:id="@android:id/tabs" android:background="#EAE7E1" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="0"/> </LinearLayout> </TabHost> https://stackoverflow.com/a/23150258/2765497
doc_23535189
I have two divs, one big and red, and one smaller, blue, part in the red one and part outside of it. When hovered, they are shown by changing their opacity to 1. I put the red one on top and the blue one behind. When I hover the red one it is fully displayed. When I hover the blue one, I have to hover over the part that is outside of the red one to fully display it. What I want is, when I hover over the blue part outside the red one, to show only this part and not the part that is inside(under) the red one. How can I do this? $(".blue, .red").on({ mouseenter: function () { $('.squares > div').css('opacity', '0'); $(this).css('opacity', '1'); }, mouseleave: function () { $(this).css('opacity', '0'); } }); .red { background-color:red; width:200px; height:200px; position:absolute; opacity:0; z-index:2; } .blue { background-color:blue; width:100px; height:100px; position:absolute; top:150px; left:50px; opacity:0; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="squares"> <div class="blue"></div> <div class="red"></div> </div> It should look like this: http://s14.postimg.org/rqzujr9xt/Untitled.png Note that I can't split the blue part nor have a smaller one outside only. A section of the blue part MUST be under the red one. And I don't know how big it will be. A: do you want this? https://jsfiddle.net/0qfxw8z8/38/ I created an illusion by changing bg color of red div to white (same as bg color of parent div) UPDATE: a small bug was fixed, now the red div disappears on mouseleave, confirm it by seeing the border I have added to the red div https://jsfiddle.net/0qfxw8z8/45/ A: https://jsfiddle.net/0qfxw8z8/37/ HTML: <div class="squares"> <div class="blue"> <div class="upper">&nbsp; </div> <div class="lower">&nbsp; </div> </div> <div class="red"> </div> </div> CSS: .red { background-color:red; width:200px; height:200px; position:absolute; opacity:0.1; } .blue { background-color:transparent; width:100px; height:100px; position:absolute; top:158px; left:50px; } .blue > .upper, .blue > .lower { opacity: 0.1; height: 50px; background-color: blue; } .blue > .lower:hover, .red:hover { opacity: 1; } Here you are what you asked for: * *when you HOVER RED div: shows whole red div *when you HOVER BLUE div: shows only the bottom (non-covered) part A: JSFiddle (Updated 4.0) <div class="js-main-container"> <div class="js-show-content"></div> <div class="js-hidden-container">Content</div> </div> .js-main-container { background-color:red; width:200px; height:200px; position:absolute; z-index:2; } .js-show-content { background-color: black; width:100px; height:100px; position:absolute; top:150px; left: 0; right: 0; margin: 0 auto; opacity:0.1; z-index: 3; } .js-hidden-container { color: #fff; display: none; background-color:blue; width:100px; position:absolute; top:100%; left:0; right: 0; margin: 0 auto; } var oShowContent = $(".js-show-content"); var oHiddenContainer = $(".js-hidden-container"); var oMainContainer = $(".js-main-container"); oShowContent.on({ mouseenter: function () { oHiddenContainer.show(); }, mouseleave: function () { oHiddenContainer.hide(); } }); JSFiddle (Updated 3.0) A: try this one $(".blue, .red").on({ mouseenter: function() { if ($(this).attr('class') == 'red') { $('.squares .red').css('background-color', 'red'); $('.squares > div').css('opacity', '0'); $(this).css('opacity', '1'); } else if ($(this).attr('class') == 'blue') { $('.squares .red').css('opacity', '1'); $('.squares .red').css('background-color', 'white'); $(this).css('opacity', '1'); } }, mouseleave: function() { $(this).css('opacity', '0'); } }); here is the fiddle A: Try this, Demo I just add the z-index:-1 of .blue and background-color:"white" of .squares. A: You should include third block to your code. And animate it like other part. JSfiddle here $(".blue, .red").on({ mouseenter: function () { $('.squares > div').css('opacity', '0'); $(this).css('opacity', '1'); }, mouseleave: function () { $(this).css('opacity', '0'); } }); $(".blue-on-red, .red").on({ mouseenter: function () { $('.squares > div').css('opacity', '0'); $(this).css('opacity', '1'); }, mouseleave: function () { $(this).css('opacity', '0'); } }); .red { background-color:red; width:500px; height:500px; position:absolute; z-index:1; opacity: 0; } .blue-on-red { background-color:blue; width:300px; height:300px; position:absolute; top:250px; z-index: 2; left:100px; opacity: 0; } .blue { background-color:blue; width:300px; height:40px; position:absolute; top:505px; z-index: 3; left:100px; opacity: 0; } <div class="squares"> <div class="blue"></div> <div class="blue-on-red"></div> <div class="red"></div> </div> A: $(".blue, .red").on({ mouseenter: function () { $('.squares > div').css('opacity', '0'); $(this).css('opacity', '1'); }, mouseleave: function () { $(this).css('opacity', '0'); } }); .red { background-color:red; width:500px; height:500px; position:absolute; z-index:2; } .blue { background-color:blue; width:300px; height:300px; position:absolute; top:250px; left:100px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="squares"> <div class="blue"></div> <div class="red"></div> </div> As you can see here the blue part is down from the red Squere and its working when you hover this part. A: Here's an updated fiddle of working solution as I understand your problem. https://jsfiddle.net/0qfxw8z8/1/ Your problem was in the use of 'this' which only animated the opacity of the div that the mouse was entering. But you actually want to animate the opacity of all the divs. Updated JS $(".red").on({ mouseenter: function () { //$('.squares > div').css('opacity', '0'); $('.square').css('opacity', '1'); }, mouseleave: function () { $('.square').css('opacity', '0'); } }); Updated HTML <div class="squares"> <div class="square blue"></div> <div class="square red"></div> </div>
doc_23535190
Array to string conversion in C:\path\rangking.inc.php on line 41 I've read this answer but I have a different array that showing with print_r is: Array ( [ia] => 6 [ik] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) [nn] => Array ( [0] => 80 [1] => 79 [2] => 79 [3] => 80 ) ) 1 any suggesting answer would be appreciate form HTML : if($_POST){ include_once 'includes/rangking.inc.php'; $eks = new rangking($db); $eks->ia = $_POST['ia']; $eks->ik = $_POST['ik']; $eks->nn = $_POST['nn']; if($eks->insert2()){ ?> <div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Berhasil Tambah Data!</strong> Tambah lagi atau <a href="rangking.php">lihat semua data</a>. </div> <?php } else{ ?> <div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Gagal Tambah Data!</strong> Terjadi kesalahan, coba lagi. </div> <?php } } ?> <form method="post"> <div class="form-group"> <label for="ia">Alternatif</label> <select class="form-control" id="ia" name="ia"> <?php $stmt3 = $pgn1->readAll(); while ($row3 = $stmt3->fetch(PDO::FETCH_ASSOC)){ extract($row3); echo "<option value='{$id_alternatif}'>{$nama_alternatif}</option>"; } ?> </select> </div> <div class="form-group"> <?php $stmt2 = $pgn2->readAll(); while ($row2 = $stmt2->fetch(PDO::FETCH_ASSOC)){ extract($row2); ?> <label for="ik"><?php echo $nama_kriteria; ?></label> <input type="hidden" name="ik[]" id="ik" value=<?php echo $id_kriteria ?>> <input type="text" class="form-control" id="nn" name="nn[]"> <?php } ?> </div> <button type="submit" class="btn btn-primary">Simpan</button> <button type="button" onclick="location.href='rangking.php'" class="btn btn-success">Kembali</button> </form> <?php (print_r($_POST)); ?> code of rangking.inc.php : function insert2(){ $query = "insert into ".$this->table_name." values(?,?,?,'','')"; $stmt = $this->conn->prepare($query); $stmt->bindParam(1, $this->ia); $stmt->bindParam(2, $this->ik); $stmt->bindParam(3, $this->nn); if($stmt->execute()){ return true; }else{ return false; } } EDIT mixing function code of _chris85_ and mine : $query = "insert into ".$this->table_name." values(?,?,?,'','')"; foreach ($this->ik as $key => $value){ $stmt = $this->conn->prepare($query); $stmt->bindParam(1, $this->ia); $stmt->bindParam(2, $value); $stmt->bindParam(3, $this->nn[$key]); if($stmt->execute()){ return true; }else{ return false; } } A: Since nn and ik are arrays you need to loop over them and bind each value. Here's a rough example of how you could do that assuming nn and ik have a one to one relationship. $query = "insert into ".$this->table_name. " values"; error_log('IK' . print_r($this->ik, 1)); foreach($this->ik as $key => $value) { error_log('In Loop'); $query_bits[] = '(?, ?, ?, "", "")'; $params[] = $this->ia; $params[] = $value; $params[] = $this->nn[$key]; } $stmt = $this->conn->prepare($query . implode(',' $query_bits)); $stmt->execute($params); This is a rough, untested sample of how it should work. Don't put variables into $query_bits or you will loose the purpose of preparing/binding. This approach is making on large insert statement with each row's data separated by a comma. INSERT statements that use VALUES syntax can insert multiple rows. To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas. -https://dev.mysql.com/doc/refman/5.7/en/insert.html
doc_23535191
I am thinking if use the id is the best way and control an access of a channel like USERID1-USERID2. But of course, user 2 can open the same channel too, so I'd like to find something more easy to control. Please, if you want to help me, give me an example in javascript using a firebase url/array. Thank you! A: A common way to handle such 1:1 chat rooms is to generate the room URL based on the user ids. As you already mention, a problem with this is that either user can initiate the chat and in both cases they should end up in the same room. You can solve this by ordering the user ids lexicographically in the compound key. For example with user names, instead of ids: var user1 = "Frank"; // UID of user 1 var user2 = "Eusthace"; // UID of user 2 var roomName = 'chat_'+(user1<user2 ? user1+'_'+user2 : user2+'_'+user1); console.log(user1+', '+user2+' => '+ roomName); user1 = "Eusthace"; user2 = "Frank"; var roomName = 'chat_'+(user1<user2 ? user1+'_'+user2 : user2+'_'+user1); console.log(user1+', '+user2+' => '+ roomName); <script src="https://getfirebug.com/firebug-lite-debug.js"></script> A common follow-up questions seems to be how to show a list of chat rooms for the current user. The above code does not address that. As is common in NoSQL databases, you need to augment your data model to allow this use-case. If you want to show a list of chat rooms for the current user, you should model your data to allow that. The easiest way to do this is to add a list of chat rooms for each user to the data model: "userChatrooms" : { "Frank" : { "Eusthace_Frank": true }, "Eusthace" : { "Eusthace_Frank": true } } If you're worried about the length of the keys, you can consider using a hash codes of the combined UIDs instead of the full UIDs. This last JSON structure above then also helps to secure access to the room, as you can write your security rules to only allow users access for whom the room is listed under their userChatrooms node: { "rules": { "chatrooms": { "$chatroomid": { ".read": " root.child('userChatrooms').child(auth.uid).child(chatroomid).exists() " } } } } A: In a typical database schema each Channel / ChatGroup has its own node with unique $key (created by Firebase). It shouldn't matter which user opened the channel first but once the node (& corresponding $key) is created, you can just use that as channel id. Hashing / MD5 strategy of course is other way to do it but then you also have to store that "route" info as well as $key on the same node - which is duplication IMO (unless Im missing something). A: We decided on hashing users uid's, which means you can look up any existing conversation,if you know the other persons uid. Each conversation also stores a list of the uids for their security rules, so even if you can guess the hash, you are protected. A: Hashing with js-sha256 module worked for me with directions of Frank van Puffelen and Eduard. import SHA256 from 'crypto-js/sha256' let agentId = 312 let userId = 567 let chatHash = SHA256('agent:' + agentId + '_user:' + userId)
doc_23535192
A: Somewhat related What is the default file path location for BufferTempStoragePath in SSIS 2005? In particular, read the linked article from bimonkey concerning the accessibility of these locations on disk from the sql agent service account. Generally speaking, when your package is reporting low memory, it is due to the use of fully blocking transformations and Lookup Tasks pulling back too much data. If your package make heavy use of blocking transformations, try and offload the work to source systems. If lookups are to blame, try being more selective in your query. Do not pull back the entire table, only pull the columns you need. If that isn't selective enough, can you try filtering that dataset with a where clause (I only need current year's data, etc). Failing that, switch the lookup from full cache mode to partial cache or no cache. No cache will result in one-off queries to the source system for every row that comes through. It will have no memory that it ran the exact same query 2 rows ago. Partial cache solves that dilemma by keeping the X MB of data in memory. If you want more details about how to reduce memory usage, post some screenshots of what your package looks like. Also note, settings like BufferTempStoragePath are per data flow so if you have multiple data flows in a package, each one will need to be configured. The architecture of the dataflow is such that data is read into memory buffers and the address of those buffers are passed to the various tasks. Instead of each task needing however much memory allocated to them to hold the data that's passing through them, they all work off the same shared set of memory. Copying that memory from task to task would be slow and very expensive in terms of memory consumption. With that preamble said, what are BufferTempStoragePath and BlobTempStoragePath? Anytime you pull large object types (n/varchar(max), xml, image, etc) into the dataflow, that data is not kept in memory buffers like native types. Instead it's written to disk and a pointer to that address is what is put into the memory buffer. BufferTempStoragePath is used when your data flow task still has work to do but you've either * *fragmented your memory so much (through fully/partially blocking transformations) the engine can't get any more *are trying to do too damn many things in a single task. My rule of thumb is that I should be able to trace a line from any transformation in the package to all the sources and destinations. If you've created a package from the import/export wizard, those dataflows are prime candidates for being split out into separate flows as it loves to group unrelated things into a single data flow which makes them memory hungry. *the box simply doesn't have sufficient resources to perform for the data. I generally prefer to avoid throwing more hardware at a job but if you've addressed the first two bullets, this would be the last one in my pistol.
doc_23535193
# Stripe Keys Account 1 STRIPE_KEY=pk_test_abc STRIPE_SECRET=sk_test_abc # Stripe Keys Account 2 STRIPE_KEY_MAPPING=pk_test_opr STRIPE_SECRET_MAPPING_MASTER=sk_test_opr I put in an array : $stripe_accounts = [ env('STRIPE_SECRET'), env('STRIPE_SECRET_MAPPING_MASTER') ]; I want to create customer in both accounts in the same time : foreach ($stripe_accounts as $item) { $stripe = new \Stripe\StripeClient($item); $hotel = session('hotel'); $stripeUser = $hotel->createOrGetStripeCustomer(); $hotel->updateDefaultPaymentMethodFromStripe(); } Is not working as expected, because create customer just for Account 1 that have STRIPE_KEY. Have you an idea about that ?
doc_23535194
I tried by cursor but I have no idea how to restrict duplicate entries because I want to create the csv file from same table on daily basis A: A cursor selects data; it is its where clause that filters which data it'll return. Therefore, set it so that it fetches only rows you're interested in. For example, one option is to use a timestamp column which tells when was that particular row inserted into the table. Cursor would then select ... from that_table where timestamp_column >= trunc(sysdate) to select data created today. It is up to you to set it to any other value you want.
doc_23535195
FROM node:14.17.0-alpine COPY /src /nodejs WORKDIR /nodejs ADD package*.json ./ RUN npm install CMD [ "node", "app.js" ] and this is my package.js file : { "name": "server", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "node app.js", "dev": "nodemon app.js -e js" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "express": "^4.17.1", "express-rate-limit": "^5.1.3", "nodemon": "^2.0.3", "prom-client": "^12.0.0", "puppeteer": "^10.4.0" } } I'm using windows 10 and the command I used to deploy the container is : docker run --name express-api -d -p 4000:4000 docker-express-app the error that I get after executing the above command, in power shell: internal/modules/cjs/loader.js:888 throw err; ^ Error: Cannot find module '/nodejs/app.js' at Function.Module._resolveFilename (internal/modules/cjs/loader.js:885:15) at Function.Module._load (internal/modules/cjs/loader.js:730:27) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12) at internal/main/run_main_module.js:17:47 { code: 'MODULE_NOT_FOUND', requireStack: [] } any idea on this issue is appreciated. P.S: my project hierarchy is like so : https://i.stack.imgur.com/ptlkI.png A: You didn't COPY the app.js file in your container. WORKDIR /nodejs COPY src . COPY app.js . ADD package*.json ./ RUN npm install CMD [ "node", "app.js" ] This should fix it. I think a more easier way could be to make a dockerignore file and copy everything. Another problem is that you're using ADD instead of COPY. You just need to copy your files in the container and I think COPY would suffice as ADD has some extra functionality which can be confusing.
doc_23535196
<div class="input-group"> <input type="text" name="q" class="form-control" placeholder="Search..." /> <span class="input-group-btn"> <button type='submit' name='search' id='search-btn' class="btn btn-flat"><i class="fa fa-search"></i></button> </span> </div> A: you have two option . * *convert your button and text box into asp control and add css class. e.g: <asp:button id="btnsave" cssClass="btn btn-flat" Text="Submit" /> *And other is using ajax and web method you fetch data from database
doc_23535197
<TextBlock> <Run>x</Run> <Run Typography.Variants="Superscript">2</Run> <Run>+ 2xy </Run> </TextBlock> I am putting those formulas in public class Formula { public string Text { get; set; } public Formula(string text) { this.Text = text; } } public class MyViewModel { public MyViewModel() { this.Formulas = new List<Formula> { new Formula("<TextBlock><Run>x</Run><Run Typography.Variants=\"Superscript\">2</Run><Run>+ 2xy </Run></TextBlock>"), new Formula("<TextBlock><Run>x</Run><Run Typography.Variants=\"Superscript\">3</Run><Run>+ 3xy </Run></TextBlock>") }; } } I am then trying to display those formulas, formatted, as ComboBoxItems. Currently, I have the following: <ComboBox ItemsSource="{Binding Path=Formulas}" DisplayMemberPath="Text" /> This approach does not show the formulas formatted. Is there a way to bind ComboBoxItems to show formatted values? If so, how? Thanks! A: I would suggest to look into libraries that offer proper display of formulas (a similar answer here) Although if you want to make this approach work you can do it the following way. <Window x:Class="BindFormulas.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:BindFormulas" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <local:XamlTextToObjectConverter x:Key="XamlTextToObjectConverter" /> </Window.Resources> <StackPanel> <ComboBox ItemsSource="{Binding Path=Formulas}"> <ComboBox.ItemTemplate> <DataTemplate DataType="local:Formula"> <ContentControl Content="{Binding Text, Converter={StaticResource XamlTextToObjectConverter}}" /> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox> </StackPanel> </Window> The converter that will convert the XAML text to actual objects: public class XamlTextToObjectConverter : IValueConverter { private static readonly Regex Regex = new Regex("(<.*?)>(.*)(</.*?>)", RegexOptions.Compiled); public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var xamlText = value as string; if (xamlText != null) { var xamlTextWithNamespace = Regex.Replace(xamlText, "$1 xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">$2$3"); try { return XamlReader.Parse(xamlTextWithNamespace); } catch (Exception) // catch proper exceptions here, not just Exception { return value; } } else { return value; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } Again, probably you'd be better off with a library that does this properly :) This approach is wrong for multiple reasons: The Formula class probably shouldn't know about things like TextBlock and Run. That's not a model class's concern. Also I'm sure you can provide a XAML string that will trip this converter up. That said, if this will be a very simple app, where you will be a 100% sure that the XAML strings can be properly converted, then maybe this approach is OK as well.
doc_23535198
Below is my code: @Override public void onCreate() { super.onCreate(); Log.d(TAG, "App started up"); beaconManager = BeaconManager.getInstanceForApplication(this); beaconManager.setDebug(true); // Add AltBeacons Parser for iBeacon beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24")); // wake up the app when any beacon is seen (you can specify specific id filers in the parameters below) region = new Region("com.rp_ds.chequeplease.bootstrapRegion", Identifier.parse("F8EFB5C2-9FFF-47AE-8C8D-D23C417882D1"), null, null); regionBootstrap = new RegionBootstrap(this, region); backgroundPowerSaver = new BackgroundPowerSaver(this); _appPrefs = new AppPreferences(this); } @Override public void didDetermineStateForRegion(int arg0, Region arg1) { // Don't care } @Override public void didEnterRegion(Region arg0) { Log.d(TAG, "Got a didEnterRegion call"); try { beaconManager.startRangingBeaconsInRegion(arg0); } catch (RemoteException e) { e.printStackTrace(); } // This call to disable will make it so the activity below only gets launched the first time a beacon is seen (until the next time the app is launched) // if you want the Activity to launch every single time beacons come into view, remove this call. } @Override public void didExitRegion(Region arg0) { // Don't care } @Override public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) { Log.d(TAG, "Got a didRangeBeaconsInRegion call"); for(Beacon beacon:beacons) { if(null!=beacon.getId2()&&null!=beacon.getId3()) { Intent intent = new Intent(this, MainActivity.class); _appPrefs.setRestaurantID(beacon.getId2().toInt()); _appPrefs.setTableNumber(beacon.getId3().toInt()); // IMPORTANT: in the AndroidManifest.xml definition of this activity, you must set android:launchMode="singleInstance" or you will get two instances // created when a user launches the activity manually and it gets launched from here. intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); this.startActivity(intent); Log.i(TAG,"Application started"); try { beaconManager.stopRangingBeaconsInRegion(region); } catch (RemoteException e) { e.printStackTrace(); } } } } } I do get a didEnterRegion call but there wasn't a didRangeBeaconsInRegion call. The beacons are also recognized. D/BeaconParser﹕ This is a recognized beacon advertisement -- 0215 seen D/BeaconIntentProcessor﹕ got an intent to process D/RangingData﹕ parsing RangingData D/RangingData﹕ parsing RangingData D/BeaconIntentProcessor﹕ got ranging data D/BeaconIntentProcessor﹕ but ranging notifier is null, so we're dropping it. A: The range notifier needs to be set like this: @Override public void didEnterRegion(Region arg0) { Log.d(TAG, "Got a didEnterRegion call"); try { beaconManager.startRangingBeaconsInRegion(arg0); beaconManager.setRangeNotifier(this); } catch (RemoteException e) { e.printStackTrace(); } } Make sure the containing class implements the RangeNotifier interface.
doc_23535199
When I set my date field on the model like so protected $dates = ['OrderDate','TimeStamp']; then call $order->OrderDate I get the following error: InvalidArgumentException with message 'Unexpected data found. Unexpected data found. The separation symbol could not be found The format separator does not match Trailing data' But, if I manually create a Carbon date object using the same formatting and copying\pasting the date directly from SQL Server, it does so successfully: >>> Carbon\Carbon::createFromFormat('Y-m-d H:i:s.000', '2015-12-29 00:00:00.000'); => Carbon\Carbon {#835 +"date": "2015-12-29 00:00:00.000000", +"timezone_type": 3, +"timezone": "UTC", } What am I missing? A: For some reason Laravel was seeing it as M j Y h:i:s:000A -- probably the driver. I added protected $dateFormat = 'M j Y h:i:s:000A'; to all the MS SQL Server models I am using. A: The workaround would be to setup accessors and mutators and parse date manually, instead of putting it in $dates array. Something like that: public function getOrderDateAttribute($value) { return Carbon::createFromFormat('Y-m-d H:i:s.000', $value); } public function getTimeStampAttribute($value) { return Carbon::createFromFormat('Y-m-d H:i:s.000', $value); } public function setOrderDateAttribute($value) { $this->attributes['OrderDate'] = Carbon::createFromFormat('Y-m-d H:i:s', $value)->format('Y-m-d H:i:s.000'); } public function setTimeStampAttribute($value) { $this->attributes['TimeStamp'] = Carbon::createFromFormat('Y-m-d H:i:s.000', $value)->format('Y-m-d H:i:s.000'); }