id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_2900
A: scaleX, width, height, etc. are synchronous operations and there is no event fired. If you absolutely have to capture it in the setters, try overriding the setters in child components. I did try that and it doesn't seem to work, if a property of a parent DisplayObject is being modified, its child components are not being touched. I guess it makes sense. If you have access to parent components then you could intercept the setters over there. A: As already noted, there is no resizing event, and children scale with their parent (expected behavior). If you wish to scale the container, and have the content children remain the same size on screen, you have to loop over the children and do one of the following to each child: * *Apply to it the inverse of the transform matrix you used to scale the container *Scale it by 1/scale, where scale is factor you multiplied the parent scale by. Scale changes on the parent change its whole coordinate space, so if you want your children to stay the same size and stay in the same place relative to the parent's (0,0) point, you need to apply the 1/scale to their x and y positions also.
doc_2901
List<Application> myApps; List<Application> yourApps; These lists have overlapping overlapping data but they are coming from different sources and each source has some missing field data. Application object has a property called Description Both collections have a unique field called Key i want to see if there is a LINQ solution to: Loop through all applications in myApps and look at the key and see if that existing in yourApps. If it does, i want to take the description property from that application in yourApps and set the description property on the application on myApps to that same value i wanted to see if there was any slick way using lambda expressions (instead of having to have loops and a number of if statements.) A: You can use a join: foreach(var pair in from m in myApps join y in yourApps on m.Key equals y.Key select new { m, y }) { pair.m.Description = pair.y.Description; } A: var matchingApps = from myApp in myApps join yourApp in yourApps on myApp.Key equals yourApp.Key select new { myApp, yourApp }; foreach (var pair in matchingApps) { pair.myApp.Description = pair.yourApp.Description; } Your question asked for "lambda coolness," but for joins, I find query expression syntax much clearer. However, the lambda version of the query is below. Lambda version: var matchingApps = myApps.Join(yourApps, myApp => myApp.Key, yourApp => yourApp.Key, (myApp, yourApp) => new { myApp, yourApp }); A: If you have a Key property in your Application class, and you'll be doing these types of operations frequently, you may want to consider using a Dictionary instead of a List. This would allow you to access the Applications quickly by key. You could then do: foreach(var app in myApps) { Application yourApp; if (yourApps.TryGetValue(app.Key, out yourApp) yourApp.Description = app.Value.Description; } Otherwise, a join is probably your best option. A: I think: foreach (var item in myApps) { var desc = yourApps.FirstOrDefault(app => app.Key == item.Key); if (desc != null) { item.description = desc.description; } } there is still a forloop in there so it might not be what you wanting, but still my 2 cents... :) A: Why not simply (this will create a copy of the enumerable): myApps.Join(yourApps, m => m.Key, y => y.Key, (m, y) => new { m, y.description }) .ToList() .ForEach(c => c.m.description = c.description);
doc_2902
I tried to use HTML5 Canvas but I am not good at it. So I tried to make it with CSS only and I make it... kind of. .header:before { content: ""; position: absolute; top: -200px; right: -500px; z-index: -999; background: #043d7a; width: 1200px; height: 700px; -webkit-animation: move 20s linear infinite; animation: move 20s linear infinite; border-radius: 70% 30% 30% 70%/60% 40% 60% 40% } @-webkit-keyframes move { 0% { border-radius: 70% 30% 30% 70%/60% 40% 60% 40% } 25% { width: 1190px; border-radius: 72% 47% 43% 67%/54% 34% 69% 56% } 50% { width: 1170px; border-radius: 72% 34% 66% 34%/54% 34% 69% 56% } 75% { width: 1190px; border-radius: 72% 47% 43% 67%/37% 61% 46% 73% } 100% { width: 1200px; border-radius: 70% 30% 30% 70%/60% 40% 60% 40% } } @keyframes move { 0% { border-radius: 70% 30% 30% 70%/60% 40% 60% 40% } 25% { width: 1210px; border-radius: 72% 47% 43% 67%/54% 34% 69% 56% } 50% { width: 1150px; border-radius: 72% 34% 66% 34%/54% 34% 69% 56% } 75% { width: 1170px; border-radius: 72% 47% 43% 67%/37% 61% 46% 73% } 100% { width: 1200px; border-radius: 70% 30% 30% 70%/60% 40% 60% 40% } } .header element is relative and this works very well. The only problem is that blob is blue and I want static image so it looks like blob is "walking" over that image. Just watch an example on the "Canva.com" website in the header: https://imgur.com/a/8vSsTUc That gooey shape is "live", it's moving around and change shape slightly, but the background image is fixed. So, I want that effect but without any interaction, just blob changing shape and moving slightly. If that is not possible with cross-browser CSS, Canvas is ok too.
doc_2903
Here is my webpack style config, which loads component styles as expected: { test: /\.(scss|css)$/, use: [ 'to-string-loader', // Return component styles as strings { loader: 'css-loader', // Translates CSS into CommonJS options: { sourceMap: true } }, { loader: 'sass-loader', // Compiles Sass to CSS, using Node Sass by default options: { sourceMap: true } }, ] } To add a global tailwind module, I added another webpack entry pointing to the sass file: entry: { app: './src/main', styles: './src/assets/styles/styles' } and the postcss loader like so: { test: /\.(scss|css)$/, use: [ 'to-string-loader', // Return component styles as strings { loader: 'style-loader', options: { sourceMap: false } }, { loader: 'css-loader', // Translates CSS into CommonJS options: { sourceMap: true } }, { loader: 'postcss-loader', // Process tailwindcss, options: { plugins: [ tailwindcss('./tailwind.js'), require('autoprefixer'), ], } }, { loader: 'sass-loader', // Compiles Sass to CSS, using Node Sass by default options: { sourceMap: true } }, ] } I am getting "ERROR in window is not defined" when building the project. What is wrong with my config? A: I've looked closer at how angular-cli processes the global styles and this revised configuration worked for me: { // Process the component styles exclude: path.resolve(__dirname, 'src/assets/styles/styles'), test: /\.(scss)$/, use: [ { loader: 'raw-loader' }, // Load component css as raw strings { loader: 'sass-loader', // Compiles Sass to CSS, using Node Sass by default options: { sourceMap: true } }, ] }, { // Process the global tailwind styles include: path.resolve(__dirname, 'src/assets/styles/styles'), test: /\.(scss)$/, use: [ { loader: 'style-loader', options: { sourceMap: false } }, { loader: 'postcss-loader', // Process tailwindcss, options: { plugins: [ tailwindcss('./tailwind.js'), require('autoprefixer'), ], } }, { loader: 'sass-loader', // Compiles Sass to CSS, using Node Sass by default options: { sourceMap: false } }, ] } The solutions being to process the component and global styles separately. raw-loader is working better than css-loader and to-string-loader. This dev config, with style-loader, also allows for hot module replacement while editing both the component and tailwind styles.
doc_2904
extension = fileName.split(".")[-1] if extension == "docx": return convertDocxToText(fileName), extension
doc_2905
How can I configure maven to when testing to: Start the server/application --> then run the tests --> then stop the server A: You can use Tomcat Maven Plugin to run tomcat during build. Try following configuration: <build> <plugins> <!-- excludes tests that require application --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <excludes> <exclude>**/TomcatPingTest.java</exclude> </excludes> </configuration> </plugin> <!-- starts tomcat before test execution and stops after--> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <executions> <execution> <id>run-tomcat</id> <phase>pre-integration-test</phase> <goals> <goal>run</goal> </goals> </execution> <execution> <id>stop-tomcat</id> <phase>post-integration-test</phase> <goals> <goal>shutdown</goal> </goals> </execution> </executions> <configuration> <fork>true</fork> <port>5555</port> <path>/app</path> </configuration> </plugin> <!-- runs tests --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> <version>2.12</version> <executions> <execution> <goals> <goal>integration-test</goal> </goals> </execution> </executions> <configuration> <includes> <include>**/TomcatPingTest.java</include> </includes> </configuration> </plugin> </plugins> </build>
doc_2906
I've been reading on requirejs and commonjs but I'm not convinced. I have a simple shell script right now that uses cat <file> <file> <file> <file> > concatenated.file to do what I want but it's a pain to maintain that list of files up to date and in the right order. It'd be much easier to be able to declare the dependency at the begining of each javascript file and have the packager and loaders be smart about using that information to concatenate/load scripts. Any suggestions? Thanks you, Luis A: I am partial to stealjs myself. It's part of JavascriptMVC but no reason why you can't use it with Backbone.js The nice part about this one is that it builds your app for production including minifying your css and js and neatly packing all of it into 2 files: production.css and production.js. It can handle loading non JS files too so you can do things like steal('somefile.css').then(function() {...}); For files, its very much like you would do in other languages: steal(dep1, dep2, dep3).then(function () { // code }); A: For complex frontend apps Asynchronous Module Definition (AMD) format is best choice. And it's alot of great loaders that supports AMD (curl.js, RequireJS). I recomend this articles to learn about modern approaches in javascript dependecy management: Writing Modular JavaScript With AMD, CommonJS & ES Harmony Why AMD? For packaging take into account CommonJS specifications, there are few implementations and it's a matter of taste, but in any case I recommend to choose tools, that is compliant with some of that specifications. A: It'd be much easier to be able to declare the dependency at the begining of each javascript file and have the packager and loaders be smart about using that information to concatenate/load scripts. I have had the same idea several months ago and are working on a dependency resolver for my Resource Builder which already makes it easier for me (including the need to distinuish between development and deployed version, with the optional debug parameter). JsDoc Toolkit (and related efforts), which syntax is supported e. g. by Eclipse JSDT, provides a @requires tag, so you could use that. But resolving dependencies is still not a trivial task (as you can see in ResourceBuilder::resolveDeps()). (The ultimate goal is to use static code analysis to resolve dependencies automatically, without any tags.) This would reduce the current <script type="text/javascript" src="builder?src=object,types,dom,dom/css"></script> to a mere <script type="text/javascript" src="builder?src=dom/css"></script> As for asynchronous loaders: The good thing about asynchronous loaders is that they are fast. The bad thing about asynchronous loaders is that – if they work; they are all based on a non-standard approach – they are so fast that you cannot be sure that the features the scripts provide are available in following scripts. So you have to have your code executed by their listeners. I recommend avoiding them unless you really have features in your application that are only needed on demand.
doc_2907
and to achieve that I used the node-gyp package.json { "name": "test", "version": "0.13.0", "description": "test", "main": "./index.js", "files": [ "index.js" ], "engines": { "node": ">=12.0.0" }, "scripts": { "test": "node index.js", "build": "node-gyp rebuild", "clean": "node-gyp clean", "install": "prebuild-install --runtime napi || node-gyp rebuild" }, "dependencies": { "bindings": "^1.5.0", "browserify": "^17.0.0" "node-addon-api": "^3.0.2", "prebuild-install": "^6.0.0" }, "devDependencies": { "babel-eslint": "^10.1.0", "chai": "^4.1.2", "chai-spies": "^1.0.0", "eslint": "^6.8.0", "eslint-plugin-import": "^2.20.1", "eslint-plugin-json": "^1.2.0", "eslint-plugin-mocha": "^6.2.2", "mocha": "^5.0.4", "node-gyp": "^9.1.0", "prebuild": "^10.0.1", "rimraf": "^2.6.2" }, "gypfile": true } binding.gyp { "targets": [ { 'target_name': 'hello', 'sources': [ 'hello.cc' ], 'defines': [ '_LARGEFILE_SOURCE', '_FILE_OFFSET_BITS=64', 'NAPI_DISABLE_CPP_EXCEPTIONS' ], 'cflags!': ['-ansi', '-fno-exceptions' ], 'cflags_cc!': [ '-fno-exceptions' ], 'cflags': ['-g', '-exceptions'], 'cflags_cc': ['-g', '-exceptions'], 'include_dirs': [ "<!@(node -p \"require('node-addon-api').include\")" ], 'dependencies': [ "<!(node -p \"require('node-addon-api').gyp\")" ], }, ] } hello.cc #include <napi.h> Napi::String Method(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); return Napi::String::New(env, "Hello Calling From Cpp"); } Napi::Object Init(Napi::Env env, Napi::Object exports) { exports.Set(Napi::String::New(env, "hellocc"), Napi::Function::New(env, Method)); return exports; } NODE_API_MODULE(hello, Init) index.js 'use strict' var addon = require('bindings')('hello'); function testingfromjs(){ return addon.hellocc(); } exports.testingfromjs= testingfromjs; the problem is it works fine with commands like node index.js but it didn't work when it build as chrome extension i imported it as dependency and use this as required in the main.js of chrome extension but it didn't work
doc_2908
But I don't exactly know how to do it. A: Put this in the head portion of your code: <script src="js/jquery.mapael.js" charset="utf-8"></script> Just change the location where the javascript file is located. Then you can simply use the class likewise: <div class="mapcontainer"> <div class="map"> </div> </div> Refer to the code of the examples here, where you can actually see how it is implemented.
doc_2909
if (!preg_match('/^[-a-zA-Z0-9_.]+@[-a-zA-Z0-9]+.[a-zA-Z]{2,4}$/', $string)) { return $false; } Now from the materials that I've researched, this should allow content before the @ to be multiple letters, numbers, underscores and periods, then afterwards to allow multiple letters and numbers, then require a period, then two to four letters for the top level domain. However, right now it ignores the requirement for having the top level domain section. For example [email protected] obviously is valid (and should be), but a@b is also returning as valid, which I want ti to be flagged as not so. I'm sure I"m missing something, but after browsing google for an hour I'm at a loss as to what it could be. Anyone have an answer for this conundrum? EDIT: The speed that answers arrive here makes this site superior over it's competitors. Well done! A: You should escape . when it's not a part of the group: '/^[-a-zA-Z0-9_.]+@[-a-zA-Z0-9]+\.[a-zA-Z]{2,4}$/' Otherwise it will be equal to any letter: * *. - any symbol (but not the newline \n if not using s modifier) *\. - dot symbol *[.] - dot symbol (inside symbol group) A: Rather than rolling your own, perhaps you should read the article How to Find or Validate an Email Address on Regular-Expressions.info. The article also discusses reasons why you might not want to validate an email address using a regular expression and provides 3 regular expressions that you might consider using instead of your own. A: From the page Comparing E-mail Address Validating Regular Expressions: Geert De Deckere from the Kohana project has developed a near perfect one: /^[-_a-z0-9\'+*$^&%=~!?{}]++(?:\.[-_a-z0-9\'+*$^&%=~!?{}]+)*+@(?:(?![-.])[-a-z0-9.]+(?<![-.])\.[a-z]{2,6}|\d{1,3}(?:\.\d{1,3}){3})(?::\d++)?$/iD But there is also a buildin function in PHP filter_var($email, FILTER_VALIDATE_EMAIL) but it seems to be under development. And there is an other serious solution: PEAR:Validate. I think the PEAR Solution is the best one. A: An RFC822-compliant e-mail regex is available. A: This is the most reasonable trade off of the spec versus real life that I have seen: [a-z0-9!#$%&'*+/=?^_`{|}~-]+ (?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)* @ (?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+ (?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b Of course, you have to remove the line breaks, and you have to update it if more top-level domains become available. A: A single dot in a regular expression means "match any character". And that's exactly what is does when a top level domain is missing (also when it's present, of course). Thus you should change your code like that: if (!preg_match('/^[-a-zA-Z0-9_.]+@[-a-zA-Z0-9]+\.[a-zA-Z]{2,4}$/', $string)) { return $false; } And by the way: a lot more characters are allowed in the local part than what your regular expression currently allows for.
doc_2910
A way is needed to perform verification directly from the database repository without going through .NetIdentity. Source: https://github.com/IdentityServer/IdentityServer4/tree/main/samples/Quickstarts
doc_2911
CvMemStorage storage = CvMemStorage.create(); CvSeq contours = new CvContour(null); noOfContors = cvFindContours(imgbin, storage, contours, Loader.sizeof(CvContour.class), CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE, new CvPoint(0,0)); for (ptr = contours; ptr != null; ptr = ptr.h_next()) { if(ptr != null){ CvRect sq = cvBoundingRect(ptr, 0); if(sq.height()*sq.width() > minAreaa && sq.height()* sq.width() < maxAreaa){ p1.x(sq.x()); p2.x(sq.x()+sq.width()); p1.y(sq.y()); p2.y(sq.y()+sq.height()); cvRectangle(img1, p1, p2, CV_RGB(255, 0, 0), 2, 8, 0); } } } In command window: OpenCV Error: Null pointer (NULL array pointer is passed) in unknown function, file ..\..\..\src\opencv\modules\core\src\array.cpp, line 2382 Exception in thread "main" java.lang.RuntimeException: ..\..\..\src\opencv\modules\core\src\array.cpp:2382: error: (-27) NULL array pointer is passed at com.googlecode.javacv.cpp.opencv_imgproc.cvBoundingRect(Native Method) at video.main(video.java:92) A: Solved the problem by adding an additional condition in for loop, but still don't know if it's a proper way to handle it: CvSeq contours1 = new CvContour(null); for (ptr = contours; ptr != null && cvFindContours(imgbin, storage, contours1, Loader.sizeof(CvContour.class), CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE, new CvPoint(0,0)) != 0; ptr = ptr.h_next()){ ..... } A: Use the following instead: for (ptr = contours; ptr != null && !ptr.isNull(); ptr = ptr.h_next()) { the !ptr.isNull() fixes the null pointer error.
doc_2912
<%forearch(var comment in Comments){%> <asp:LinkButton ID="del" CommandArguement='<%= comment.CommentId%>' onCommand="delete_click" Text="Delete"/> <%}%> But when I write this in my ascx file and click on the link the value passed to command argument is "<%=comment.CommentId%>" instead of commentId itself. Please guide what am I doing wrong? Edit 1 based on answers and comments, I have moved to use repeater instead of foreach and plain code. Here is the code I have come up with <asp:Repeater ID="commRepeater" SelectMethod="GetPageComments" runat="server"> <ItemTemplate> <p> <%#Eval("Comment") %> <%if(Page.User.Identity.IsAuthenticated && Page.User.Identity.GetUserId() == Eval("UserId")){ %> <span> <asp:LinkButton Text="Edit" runat="server" ID="EditLink" CommandArgument='<%#Eval("CommentId")%>' OnClick="Update_Comment" />&nbsp;&nbsp; <asp:LinkButton Text="Delete" runat="server" ID="DeleteLink" CommandArgument='<%#Eval("CommentId")%>' OnClientClick="if (!confirm('Are you sure you want delete?')) return false;" OnCommand="Delete_Comment" /> </span> <%} %> </p> </ItemTemplate> </asp:Repeater> you can see that I am trying to show the edit and delete links if user is logged in and his Id matches with user who commented but it tells me that I can on use Eval in databound controls. how would I hide/show edit/delete links conditionally within repeater A: You could simply use codebehind, for example in Page_Load: protected void Page_Load(Object sender, EventArgs e) { if(!IsPostBack) { del.CommandArgument = comment.CommentId; } } Maybe a better approach would be to use the Comments-collection(which seems to be a list or array of a custom class) as DataSource of a Repeater(or other web-databound control). Then you can add the LinkButtons to the Itemtemplate. You can then either use ItemCreated or ItemDataBound events of the repeater in codebehind or inline ASP.NET tags to bind the CommandArgument. For example: CommandArguement='<%# DataBinder.Eval( Container.DataItem, "CommentId" ) %>' A: What you are doing currently is not recommended and is highly error prone. You can easily achieve this with ASP.NET Repeater control like this:- <asp:Repeater ID="MyRepeater" runat="server"> <ItemTemplate> <asp:LinkButton ID="del" CommandArguement='<%# Eval("CommentId") %>' OnCommand="del_Command" Text="Delete" runat="server" /> </ItemTemplate> </asp:Repeater> In Page_Load simply bind it:- if (!Page.IsPostBack) { MyRepeater.DataSource = CommentsRepository(); MyRepeater.DataBind(); } Or Else if you are have ASP.NET 4.5 then use strongly type Data Bound controls like this:- <asp:Repeater ID="MyRepeater" runat="server" ItemType="MyNamespace.Comment" SelectMethod="MyRepeater_GetData"> <ItemTemplate> <asp:LinkButton ID="del" CommandArguement='<%# Item.CommentId %>' OnCommand="del_Command" Text="Delete" runat="server" /> </ItemTemplate> </asp:Repeater> And you method in code behind should be something like this(just for Demo):- public IEnumerable<MyNamespace.Comment> MyRepeater_GetData() { return new List<Comment> { new Comment { CommentId =1, Name= "foo"}, new Comment { CommentId =2, Name= "bar"}, }; }
doc_2913
But when marker moving from center of screen, 3d model shifted from marker. I can't understand where the mistake. A: That's a FOV problem. Try using a different resolution on the camera.
doc_2914
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet spreadsheet = workbook.createSheet("Acumulado"); String[] header = new String []{"link","curp","rfc","nom","app","apm","fechna","fechi","sts","ent","muni","tipv","nomv","nume","numi","col","cp","corr","AL","reg"}; CellStyle style = workbook.createCellStyle(); Font font = workbook.createFont(); font.setBold(true); style.setFont(font); FileReader archivo = new FileReader("list.txt"); BufferedReader lectura = new BufferedReader(archivo); String cadena; ArrayList<String> datos = new ArrayList<>(); while((cadena = lectura.readLine())!= null){ datos.add(cadena); } for(int arr=0; arr<datos.size(); arr++) { org.jsoup.nodes.Document document = null; document = Jsoup.connect(datos.get(arr)).get().... //scrapping treatment String[][] documentt = new String[][] { {datos.get(arr),curp,rfc,nom,app,apm,fechna,fechi,sts,ent,muni,tipv,nomv,nume,numi,col,cp,corr,AL,reg} }; for(int x = 0 ; x <= documentt.length ; x++) { XSSFRow row = spreadsheet.createRow(x); // Se crea la fila for(int u = 0 ; u < header.length ; u++) { if(x == 0) { // Para la cabecera XSSFCell cell = row.createCell(u); // Se crean las celdas para la cabecera cell.setCellValue(header[u]); // Se añade el contenido } else { XSSFCell cell = row.createCell(u); // Se crean las celdas para el contenido cell.setCellValue(documentt[x - 1][u]); // Se añade el contenido } } } } try (OutputStream fileOut = new FileOutputStream("AcumQR.xls")){ System.out.println("SE CREO EL EXCEL"); workbook.write(fileOut); } catch(IOException w) { w.printStackTrace(); }
doc_2915
2020/01/01 promotion offer 1 2020/01/02 promotion offer 1 2020/01/03 promotion offer 2 2020/01/04 promotion offer 2 2020/01/05 promotion offer 2 2020/01/06 promotion offer 3 So what I'm trying to do is do create an event that ranges from 01/01 to 01/02 with the title "promotion offer 1", then another event that ranges from 01/03 to 01/05 and has the title "promotion offer 2" and then another that is just one day and has the title "promotion offer 3". My approach is to check whether the value in row 1, column 2 differs from the value in row 2, column 2. But I don't know whether I can include that check in a "regular" for loop. So I tried to use two for loops. Which doesn't work :D This is what I have tried so far: var alloffers = spreadsheet.getRange("E133:F141").getValues(); // speichert die Werte in der angegegeben Range in var offerkalender for (row=0; row<alloffers.length; row++) { var offer = alloffers[row]; var date = offer[0]; var conditions = offer[1]; } for (row=1; row>alloffers.length; row++) { var nextoffer = alloffers[row]; var nextdate = nextoffer[0]; var nextconditions = nextoffer[1]; } if (conditions != nextconditions) { eventCal.createAllDayEvent(conditions, date, nextdate); } Anybody able to help? :) A: The comment on your post was heading in the right direction. Easiest way to do this is to check if the new row is equal to the old row, but you also want to keep checking in case there are additional rows. What I've done below is check the values and put them into a new placeholder array for start date, end date, and promotion title. Just change the range in the alloffers variable, and this should work a charm for you. Note: In testing, I noticed that the calendar app was cutting off the last day of multi-day events. This was due to the handling of time events, so all day events running from 1/1/2020 @ 00:00:00 to 1/3/2020 @ 00:00:00 would translate to being all day events on 1/1/2020 and 1/2/2020 only, so I re-worked the coding to add time onto the end date of multi-day events, thus making it run from 1/1/2020 @ 00:00:00 to 1/3/2020 @ 23:59:59. var alloffers = sheet.getRange("Your Range").getValues(); // speichert die Werte in der angegegeben Range in var offerkalender // create trimmed offers array var trimmedoffers = []; // set first array line to the first offer data trimmedoffers[0] = [alloffers[0][0],alloffers[0][0],alloffers[0][1]]; for (var i=1, s=1; i<alloffers.length; i++) { // check if offer on this date matches offer on previous date if (alloffers[i][1] != alloffers[i-1][1]) { // if it does not, set new offer information into trimmed array trimmedoffers[s] = [alloffers[i][0],alloffers[i][0],alloffers[i][1]]; s++; } else { // if it does, change end date of offer in trimmed array and add on 23:59:59 trimmedoffers[s-1] = [trimmedoffers[s-1][0],new Date(alloffers[i][0].getTime()+86399000),trimmedoffers[s-1][2]]; } } // use new array to create events based on total number of offers for (var t=0; t<trimmedoffers.length; t++) { // check if event is a single day if (trimmedoffers[t][0] == trimmedoffers[t][1]) { // if it is, create all day event eventCal.createAllDayEvent(trimmedoffers[t][2],trimmedoffers[t][0]); } else { // if not, create an event from start time to finish time eventCal.createEvent(trimmedoffers[t][2],trimmedoffers[t][0],trimmedoffers[t][1]); } }
doc_2916
* *Web UI: On Azure, its IP is 111.222.33.44:80 *Web Service: On Azure, its IP is 111.222.33.44:8080 Configuration for Web UI: <system.web> <compilation debug="true" targetFramework="4.0" /> <authentication mode="Forms"> <forms name="COOKIENAME" loginUrl="~/Login/login.aspx" timeout="2880" /> </authentication> <authorization> <deny users="?" /> </authorization> <machineKey validation="SHA1" decryption="AES" validationKey="VKEY" decryptionKey="DKEY"></machineKey> <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID" /> </system.web> Configuration for Web Services <system.web> <authentication mode="Forms"> <forms name="COOKIENAME" loginUrl="~/Login/login.aspx" timeout="2880" /> </authentication> <authorization> <deny users="?" /> </authorization> <machineKey validation="SHA1" decryption="AES" validationKey="VKEY" decryptionKey="DKEY"></machineKey> </system.web> In the Web UI role, Login/login.aspx submits the username and password. A cookie is created with the method FormsAuthentication.SetAuthCookie(username, myVar);. Then, the user is redirected to Default.aspx which contains the Silverlight application. When it is starting, the Silverlight application gets the username from the Web Service role by returning HttpContext.Current.User.Identity.Name. All is fine in the local cloud emulator, but when I deploy my project in Windows Azure (staging), the web service doesn't know I am connected. I used Fiddler and I saw the page 111.222.33.44:8080/Login/login.aspx being queried (the page doesn't exist in the web service role, it is a way to know if a user is authenticated). I suspect the web service cannot retrieve the username because it cannot retrieve the cookie created by the Web UI role. Is it actually possible to make it work or do I have to merge the web service role with the Web UI role? The machine keys on both roles are identical. A: AFAIK The two roles won't share a cookie. In a similar situation I had a web project that hosted a silverlight client, and a web service that was used by the silverlight app. The user would log in to the website and access the silveright client. The client had been provided with web service authentication token using the param attribute <object data="data:application/x-silverlight-2," type="application/x-silverlight-2"> <param name="Token" value="<%=Token %>" /> The token, once decrypted by the web service, contains the logged in user's id. Now, the Silverlight client can access a stateless web service and the web service knows which logged in user the request relates to. I kept my WebService and WebRole separate so that CPU heavy jobs can be handled by the service, leaving the web role to serve web pages nice and quickly. Does this help?
doc_2917
* *I got an API called remove.bg . I want to use this API ( provided in python language ) in my Flutter App. Is it even possible? *This API uses for removing image background. *What are the steps/ research I need to do to get this thing working? *Do lots of Googling, but ends up with nothing. Really Appreciate your help!!! * *OR can I use this link and able to upload and get the output in my app? for example, I open the APP, and it will show two-button -> Upload image & download image. when user clicks the Upload button it will redirect to this link and after processing done in the website, the output we can able to download in our app. A: This is possible with Flutter's http package. Assuming it is some form of RESTful API this should give you a starting point: final body = {"image_file": "@/path/to/file.jpg", "size": "auto"}; final headers = {"X-API-Key": INSERT_YOUR_API_KEY_HERE}; final response = await http.post('https://api.remove.bg/v1.0/removebg', body: body, headers: headers); if (response.statusCode == 200) { // do something with response.body } else { throw Exception('Failed to do network requests: Error Code: ${response.statusCode}\nBody: ${response.body}'); } A good tutorial on http in Flutter is here. Note: You may have to do json.encode(body) and the same with header and use json.decode(response.body) depending on the API. Hope it helps, and if so please up vote and accept as answer and if not please leave a comment below.
doc_2918
I tried the method explained here :Creating DLL from CUDA using nvcc to compile but I've got the following errors : nvcc : warning: __declspec attributes ignored At line:1 char:1 + nvcc -o ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (...ributes ignored:String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError ...\kernel.cu(81): warning: __declspec attributes ignored ...\cudaFFT.h(21): warning: __declspec attributes ignored .../kernel.cu(81): warning: __declspec attributes ignored nvcc warning : The 'compute_20', 'sm_20', and 'sm_21' architectures are deprecated, and may be removed in a future release (Use -Wno-deprecated-gpu-targets to suppress warning). kernel.cu CrÚation de la bibliothÞque C:/Users/alombet/Documents/Visual Studio 2015/Projects/Test/kernel.lib et de l'objet C:/Users/alombet/Documents/Visual Studio 2015/Projects/Test/kernel.exp tmpxft_00003b9c_00000000-30_kernel.obj : error LNK2019: symbole externe non rÚsolu cufftPlan1d rÚfÚrencÚ dans la fonction AllocateMemoryForFFTs tmpxft_00003b9c_00000000-30_kernel.obj : error LNK2019: symbole externe non rÚsolu cufftExecD2Z rÚfÚrencÚ dans la fonction ComputeFFT tmpxft_00003b9c_00000000-30_kernel.obj : error LNK2019: symbole externe non rÚsolu cufftDestroy rÚfÚrencÚ dans la fonction DeAllocateMemoryForFFTs C:/Users/alombet/Documents/Visual Studio 2015/Projects/Test/kernel.dll : fatal error LNK1120: 3 externes non rÚsolus First of all the __declspec seems to be ignored, and after that it seems the compiler doesn't find the functions I use in the cuda libraries. I'm really not accustomed to compiling by hand. Usually, I rely on the IDE to do it and thus I am completely lost here. Here is the code : #include "cuda_runtime.h" #include "device_launch_parameters.h" #include <stdio.h> #include <iostream> // includes, system #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> // includes, project #include <cuda_runtime.h> #include <cufft.h> #include <cufftXt.h> #define LIBRARY_EXPORTS 1 #ifdef LIBRARY_EXPORTS #define LIBRARY_API __declspec(dllexport) #else #define LIBRARY_API __declspec(dllimport) #endif #include "cudaFFT.h" #ifdef __cplusplus extern "C" { #endif int LIBRARY_API __cdecl numberOfGpus() { int nDevices; cudaGetDeviceCount(&nDevices); return nDevices; } cufftDoubleReal *host_input; cufftDoubleReal *device_input; cufftDoubleComplex *host_output; cufftDoubleComplex *device_output; cufftHandle plan; cudaError LIBRARY_API __cdecl AllocateMemoryForFFTs(int maxSize, int maxBatch) { int width = maxSize; int height = maxBatch; cudaError err = cudaMallocHost((void **)&host_input, sizeof(cufftDoubleReal) * width * height); if (err) return err; err = cudaMallocHost((void **)&host_output, sizeof(cufftDoubleComplex) * (width / 2 + 1) * height); if (err) return err; err = cudaMalloc((void **)&device_input, sizeof(cufftDoubleReal) * width * height); if (err) return err; err = cudaMalloc((void **)&device_output, sizeof(cufftDoubleComplex) * (width / 2 + 1) * height); if (err) return err; cufftResult res = cufftPlan1d(&plan, width, CUFFT_D2Z, height); if (res) return (cudaError)res; return cudaSuccess; } double* LIBRARY_API __cdecl GetInputDataPointer() { return host_input; } cudaError LIBRARY_API __cdecl ComputeFFT(int size, int batch, double2** result) { cudaError err = cudaMemcpy(device_input, host_input, sizeof(cufftDoubleReal) * size * batch, cudaMemcpyHostToDevice); if (err) return err; cufftResult res = cufftExecD2Z(plan, device_input, device_output); if (res) return (cudaError)res; err = cudaMemcpy(host_output, device_output, sizeof(cufftDoubleComplex) * (size / 2 + 1) * batch, cudaMemcpyDeviceToHost); if (err) return err; *result = host_output; return cudaSuccess; } void LIBRARY_API __cdecl DeAllocateMemoryForFFTs() { cufftDestroy(plan); cudaFree(device_input); cudaFree(device_output); cudaFreeHost(host_input); cudaFreeHost(host_output); } #ifdef __cplusplus } #endif A: Ok I found my problems, I leave the solution here in case it can help someone. * *I removed the LIBRARY_API keyword from the .cu *In the .h I moved the LIBRARY_API at the very beginning of each declaration. *I changed the project properties in vs to generate a dll. *Let VS compile
doc_2919
However it's not working the way I want. In my app service provider: Organisation::observe(OrganisationObserver::class); There I've got this: /** * Listen to the Organisation updated event. * * @param Organisation $organisation * @return void */ public function updated(Organisation $organisation) { dd('test'); $this->cache->tags(Organisation::class)->flush(); $this->cache->tags(Relation::class)->flush(); } THis is the trait I use on the model: <?php namespace App\Deal\Custom; trait BelongsToManyWithSyncEvent { /** * Custom belongs to many because by default it does not observes * changes on pivot tables. When a pivot table is changed return * a custom belongs to many with sync cache clear class. * Here we will clear the cache. * * @param $related * @param null $table * @param null $foreignKey * @param null $relatedKey * @param null $relation * @return BelongsToManyWithSyncCacheClear */ public function belongsToMany($related, $table = null, $foreignKey = null, $relatedKey = null, $relation = null) { if (is_null($relation)) { $relation = $this->guessBelongsToManyRelation(); } $instance = $this->newRelatedInstance($related); $foreignKey = $foreignKey ?: $this->getForeignKey(); $relatedKey = $relatedKey ?: $instance->getForeignKey(); if (is_null($table)) { $table = $this->joiningTable($related); } return new BelongsToManyWithSyncCacheClear( $instance->newQuery(), $this, $table, $foreignKey, $relatedKey, $relation ); } } The BelongsToManyWithSyncCacheClear class looks like this: <?php namespace App\Deal\Custom; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Concerns\HasEvents; use Illuminate\Database\Eloquent\Relations\BelongsToMany; class BelongsToManyWithSyncCacheClear extends BelongsToMany { use HasEvents; /** * BelongsToManyWithSyncEvents constructor. * * @param Builder $query * @param Model $parent * @param string $table * @param string $foreignKey * @param string $relatedKey * @param null $relationName */ public function __construct(Builder $query, Model $parent, $table, $foreignKey, $relatedKey, $relationName = null) { parent::__construct($query, $parent, $table, $foreignKey, $relatedKey, $relationName); } /** * When a pivot table is being synced, * we will clear the cache. * * @param array|\Illuminate\Database\Eloquent\Collection|\Illuminate\Support\Collection $ids * @param bool $detaching * @return array */ public function sync($ids, $detaching = true) { $changes = parent::sync($ids, $detaching); $this->fireModelEvent('updated', false); return $changes; } } Here I fire an updated event: $this->fireModelEvent('updated', false); But the dd('test'); in my OrganisationObserver is never triggered. What am I doing wrong here!?
doc_2920
ERROR: While executing gem ... (Gem::FilePermissionError) You don't have write permissions for the /Library/Ruby/Gems/2.6.0 directory. I have tried some fixes online but nothing is working. Can anyone help?
doc_2921
I want to add border on item hover. but right border is not display in last item. Example-1 When Owl Carousel wrap in bootstrap Grid <div class="col-*-*">...</div> <div class="container"> <div class="row"> <div class="col-sm-9"> <div id="owl-example1" class="owl-carousel"> <div class="item"><img class="lazyOwl img-responsive" src="http://tinyurl.com/lwexfpf" alt="Lazy Owl Image"></div> <div class="item"><img class="lazyOwl img-responsive" src="http://tinyurl.com/lwexfpf" alt="Lazy Owl Image"></div> <div class="item"><img class="lazyOwl img-responsive" src="http://tinyurl.com/lwexfpf" alt="Lazy Owl Image"></div> <div class="item"><img class="lazyOwl img-responsive" src="http://tinyurl.com/lwexfpf" alt="Lazy Owl Image"></div> <div class="item"><img class="lazyOwl img-responsive" src="http://tinyurl.com/lwexfpf" alt="Lazy Owl Image"></div> <div class="item"><img class="lazyOwl img-responsive" src="http://tinyurl.com/lwexfpf" alt="Lazy Owl Image"></div> </div></div></div></div> So, I get this. (Not work fine.) Example-2 But, When Owl Carousel without wrap in bootstrap Grid <div class="col-*-*">...</div> <div class="container"> <div id="owl-example" class="owl-carousel"> <div class="item"><img class="lazyOwl img-responsive" src="http://tinyurl.com/lwexfpf" alt="Lazy Owl Image"></div> <div class="item"><img class="lazyOwl img-responsive" src="http://tinyurl.com/lwexfpf" alt="Lazy Owl Image"></div> <div class="item"><img class="lazyOwl img-responsive" src="http://tinyurl.com/lwexfpf" alt="Lazy Owl Image"></div> <div class="item"><img class="lazyOwl img-responsive" src="http://tinyurl.com/lwexfpf" alt="Lazy Owl Image"></div> <div class="item"><img class="lazyOwl img-responsive" src="http://tinyurl.com/lwexfpf" alt="Lazy Owl Image"></div> <div class="item"><img class="lazyOwl img-responsive" src="http://tinyurl.com/lwexfpf" alt="Lazy Owl Image"></div> </div></div> So, I get this. (work fine.) Live Demo - http://jsfiddle.net/harnishdesign/zwd9uysg/18/embedded/result/ How can I solve border issue in Example-1 ? A: Add the piece of code #owl-example1 { width : 850px; /* if you dont know the exact width mean set as 100.3% */ } DEMO It works fine in full screen mode A: Remove the right padding on the column containing the owl carousel: DEMO: http://jsfiddle.net/zwd9uysg/19/ HTML <div class="col-sm-9 owl-me"> CSS .owl-me {padding-right:0;} A: use below CSS. i have tested jsfiddle .owl-carousel .owl-item .item { padding: 10px; border-right: 1px solid #f00; } .owl-carousel .owl-wrapper-outer { overflow: hidden; position: relative; width: 100%; border: 1px solid #f00; } A: I resolved this with: .owl-wrapper-outer { border-left: 2px solid silver; } .owl-wrapper .owl-item { border: solid silver; border-width: 2px 2px 2px 0; margin-left: -1px; } margin-left pulls the items over enough for the last right border to be visible. A: I solved it by setting the border-color to transparent and using an inset box-shadow instead: .owl-carousel .owl-item .item { border: 1px solid transparent; box-shadow: inset 0px 0px 0px 1px #000000; }
doc_2922
When I do hover on the cells that have data,the background colour should change black and cursor should be pointed. If there are no data in the cell or if the cell is blank,there should be no hover applied on the cell and mouse pointer should be normal. A: You could also use pure css - depends what browsers you are supporting: table td:hover:not(:empty) { background: red; } Fiddle Link A: Use jQuery: $(document).ready(function(){ $('td').on('mouseover', function(event) { event.preventDefault(); var self=$(this); var x=$.trim(self.text()); $('td').css({ 'cursor':'default', 'background-color': 'white' }); if(x==''){ self.css({ 'cursor':'default', 'background-color': 'white' }); }else{ self.css({ 'cursor':'pointer', 'background-color': 'red' }); } }); }); A: you may also try this one $query = mysql_query(Select * from tablename); <table> While( $test = mysq_fetch_array($query)) { if($test['columnname'] !='') { $color = "has_content"; } else $color = "no_content"; echo "<td class='$color' >content...</td>"; } </table> these use these below CSS .has_content { background-color:black; } .no_content { background-color:white; } .has_content:hover { cursor:pointer; }
doc_2923
pyplot.figure(figsize=(20,20)) g=sns.heatmap(df.corr(), vmin=df.corr().values.min(), vmax=1, square=True, cmap="YlGnBu", linewidths=0.1, annot=True, annot_kws={"fontsize":4}, xticklabels=1, yticklabels=1) g.set_xticklabels(g.get_xticklabels(), fontsize = 7) g.set_yticklabels(g.get_yticklabels(), rotation = 0, fontsize = 7) pyplot.show() I also would like to ask if there is a way to make the values in the cells more visible possibly by making it bold, because when I increase the font size, the values in the cells overlap.
doc_2924
I noticed that GC if super active when I scroll up/down fast enough, which makes the scrolling jerky. I tried to isolate the problem and wrote a simple app where I do 10000 decodeStream() calls in a loop and noticed that even though there is enough of memory, the GC is still getting triggered constantly (even if I call bitmap.recycle() after each iteration). Question: how to prevent GC from being too active while executing BitmapFactory.decodeStream()? A: The general approach to dealing with memory in Android is the same as the mantra for environmental concerns: reduce, reuse, recycle. "Reduce" means "request less" (e.g., use inSampleSize on BitmapFactory.Options to only load in a downsampled image). "Recycle" means "make sure it can get garbage-collected ASAP". But, before "recycle" comes "reuse". The Dalvik garbage collector is not a compacting or moving collector, so heap can become fragmented. If you already have an allocation that's the right size, reuse it, rather than let it be collected and then have to re-allocated it again. With bitmaps, that means use inBitmap on BitmapFactory.Options, or use an image-loading library that does this for you. Will it give the same boost on Android >=5.0 Generally yes, though the exact impacts may vary somewhat. or the optimizations made on L make the use of inBitmap not necessary (not worth added complexity)? ART's garbage collector has a variety of improvements. The big one is that it is a compacting or moving collector, though only while your app is in the background, which will not help you much in your case. However, ART also has a separate area of the heap for large byte arrays (or other large objects that do not have any pointers to other objects inside of them). ART is much more efficient about collecting these, and they will cause less heap fragmentation. That being said, I'd still use inBitmap. If your minSdkVersion was 21+, maybe you might try skipping inBitmap and see how it goes. But if your minSdkVersion is below 21, you need inBitmap anyway, and I'd just use that code across the board.
doc_2925
This is my first real attempt at using async methods and multi-threading, so i'm sure there are issues, but that's why i'm experimenting What i have so far: * *async methods for getting the data from the database. I have proven that this works. *Note that i am using direct SQL at the moment for experimenting - once i have this working, i won't be using SQL directly, but stored procedures and parameters *the database get function is passed a DataTable to allow it to add a row at a time to it as the data is read in: private static async Task ExecuteTextQueryAsync(string SQLText, OracleConnection conn, DataTable dt) { using (OracleCommand cmd = new OracleCommand(SQLText)) { cmd.BindByName = true; cmd.CommandType = CommandType.Text; cmd.Connection = conn; using (System.Data.Common.DbDataReader reader = await cmd.ExecuteReaderAsync()) { if (reader.HasRows) { DataTable schemaTable = reader.GetSchemaTable(); foreach (DataRow row in schemaTable.Rows) { string colName = row.Field<string>("ColumnName"); Type t = row.Field<Type>("DataType"); dt.Columns.Add(colName, t); } while (await reader.ReadAsync()) { var newRow = dt.Rows.Add(); foreach (DataColumn col in dt.Columns) { newRow[col.ColumnName] = reader[col.ColumnName]; } } } } } } Now as i'm using MVVM, i'm not calling the above method from code behind, but from the view model. The viewmodel: * *Has a property DataTable ResultDataGrid which is bound to the datagrid on the view. *I've instantiated this DataTable and also added an event handler for TableNewRow event which should run whenever the table has a row added (which then causes NotifyPropertyChanged to be called on the above property *I'm then trying to run the above data getter on a different thread, and hoping the table would update as new rows were added: using (OracleConnection newConnection = Helper.CreateConnectionAsync(ConnectionStr).Result) { try { var task = Task.Run(async () => { await Helper.ExecuteTextQueryAsync("Select * from LargeNumberOfRowsTable", newConnection, dt); }); } Like i said, i have confirmed that the results are being correctly read from the database, however the event handler for TableNewRow never fires. Is it possible for another thread to fire events on the calling thread? Am i completely on the wrong track for reading the results in and updating the table as they come in? I feel like i'm close, but my lack of knowledge on threads is letting me down.
doc_2926
teamID yearID W L IP WHIP K% BB% HR/9 ERA FIP ERA- FIP- K/BB+ WHIP+ K%+ BB%+ WAR 1209 Athletics 2001.0 2.0 6.0 3.0 7.0 19.0 9.0 1.0 7.0 5.0 7.0 5.0 8.0 7.0 11.0 10.0 4.0 I want to create a column with the average rank for each row, but doing df.mean(axis=1) includes the year (2001) and really throws the number off. Anybody know how to get a round this with maybe a lambda and .apply(), or is there a kwarg that can exclude certain columns? I haven't found one. I want to do this across years so that is why the yearID column is necessary. A: Simply exclude it from your calc using loc[] and a comprehension on the columns. df = pd.read_csv(io.StringIO("""teamID yearID W L IP WHIP K% BB% HR/9 ERA FIP ERA- FIP- K/BB+ WHIP+ K%+ BB%+ WAR 1209 Athletics 2001.0 2.0 6.0 3.0 7.0 19.0 9.0 1.0 7.0 5.0 7.0 5.0 8.0 7.0 11.0 10.0 4.0"""), sep="\s+") df["mean"] = df.loc[:,[c for c in df.columns if c!= "yearID"]].mean(axis=1) output teamID yearID W L IP WHIP K% BB% HR/9 ERA FIP ERA- FIP- K/BB+ WHIP+ K%+ BB%+ WAR mean 1209 Athletics 2001.0 2.0 6.0 3.0 7.0 19.0 9.0 1.0 7.0 5.0 7.0 5.0 8.0 7.0 11.0 10.0 4.0 6.9375
doc_2927
c:\mysql.exe -h instance -udbuser -pPass db -e "INSERT INTO db.table1 (SELECT REPLACE(CONCAT(TRIM(co_ano),'-',TRIM(co_mes),'-1'),'"', '') as col1,REPLACE(TRIM(col2_temp),'"', '') as col2, REPLACE(TRIM(col3_temp),'"', '') as col3, REPLACE(TRIM(col4_temp),'"', '') as col4, REPLACE(TRIM(col5_temp),'"', '') as col5, REPLACE(TRIM(col6_temp),',','.') as col6, REPLACE(TRIM(col7_temp),',','.') as col7 FROM db.temp_table1);" When I split the command and execute it in parts, it works fine. Example: c:\mysql.exe -h instance -udbuser -pPass db It works and then now I am in mysql> In mysql command line when I execute this: mysql>INSERT INTO db.table1 (SELECT REPLACE(CONCAT(TRIM(co_ano),'-',TRIM(co_mes),'-1'),'"', '') as col1, REPLACE(TRIM(col2_temp),'"', '') as col2, REPLACE(TRIM(col3_temp),'"', '') as col3, REPLACE(TRIM(col4_temp),'"', '') as col4, REPLACE(TRIM(col5_temp),'"', '') as col5, REPLACE(TRIM(col6_temp),',','.') as col6, REPLACE(TRIM(col7_temp),',','.') as col7 FROM db.temp_table1); and so, it works. Why is the first command not working? I need to execute this command using a batch file. I would like to add that the command below works fine c:\mysql.exe -h instance -udbuser -pPass db -e "OPTIMIZE TABLE temp_table1" MySQL Ver 8.0.17 Someone can help me?
doc_2928
mysqlConnection.query('SELECT `something` FROM `here` WHERE `dog` = \'' +info+ '\'', function(err, row, fields) { if(err) { console.log('Error1'); return; } else if (!row.length) { console.log('Error2'); return; } else if (row[0].something == 'NULL' || row[0].something == '') { console.log('Error3'); return; } console.log('Works'); }); So the thing is, if "something" is not in mysql, console shows Error2, but if "something" is in mysql, but if its NULL, console shows Works, so whats the problem? Im checking if something is NULL, but it wont show Error3. If table is empty, it shows Error3. Thanks for help. A: I would try something like this: mysqlConnection.query('SELECT `something` FROM `here` WHERE `dog` = ?', [info] function(err, row, fields) { if(err) { return console.log('Error1'); } else if (!row.length) { return console.log('Error2'); } else if (!row[0].something) { return console.log('Error3'); } console.log('Works'); }); It's using a "falsy" check for row[0].something which will return false if the value is undefined, null or an empty string. It also fixes the injection attack vector that t.niese mentioned. A: I am aware that I am 5 years and 9 months late, but for those of you struggling with this, here's a solution. The table's value when empty is not NULL. I was having a similar problem in which I wanted to reset AUTO_INCREMENT to 1 when the table is empty. To detect when it's empty, we have to see if it has any element with the index 0. If it has an element, it would return something like: RowDataPacket { // data }. If it doesn't, it would return undefined. See where I'm going with this? Just add a conditional to see if the result[0] is undefined or not. Want some code to better understand it? Sure! Here it is: db.query("SELECT * FROM tablename", (err, result) => { if (err) throw err; else { // If the first element does not exist if (result[0] == undefined) { db.query("yourquery", (err) => { if (err) throw err; }); } else { res.send(result); } } }); A: If you think in a scenario when you receive an Array<any> when you run a SQL like select name from employee there are three concerns you should have: * *If your statement did return something *If the property you are looking for exist *If the content of the property is null and you are expecting a null As these concerns will occur hundreds of time, I use the following approach (in TypeScript): let ret: Array<any> = connection.query('select name from employee',...); for (let r of ret) { name = getValueColumn(r,'name','This will be thrown if content is null'); }; export function getValueColumn(obj: any, fieldName: string, messageIfNull: string = null): any { fieldName = fieldName.toLocaleLowerCase(); if (!obj) { throw new CustomError(errorCodes.connection.rowNull, 'Linha nula e sem campos'); } else if (!obj.hasOwnProperty(fieldName)) { throw new CustomError(errorCodes.connection.fieldDoesNotExist, 'Campo não existe -> ' + fieldName); } else { if (!obj[fieldName]) { if (messageIfNull) { throw new CustomError(errorCodes.connection.fieldWithNullValue, messageIfNull + '\n' + fieldName + ' com valores nulos ou campo invalido\n' + obj); }; return null; }; return obj[fieldName]; }; }; If you were to check the results with just if (!ret) {...}, it would be always false as an empty array is not null. So you would have to check if(!ret[0]) {..} So all three concerns are handled and you don't need to be worried every time you want to parse the query.
doc_2929
I tried invoking C-cC-b but this does not toggle breakpoints on the selected line as one would hope/expect. Neither does C-xSPC work as it would in pdb. When in the pydbgr shell window I can set breakpoints according to the first keyboard short-cut above, but it is naturally far more convenient to not have to move windows in order to do this. Also, the left buffer margin intended for setting breakpoints via the mouse does not appear by default, and the MOUSE button binding for toggling normal and temporary breakpoints do not appear to work out-of-the-box, at least with my .emacs configuration. I am using the latest pydbgr and dbgr.el code at the time of this posting. Can anybody with experience of using pdbgr for debugging Python application please comment on the best approaches they have adopted in this regard. Perhaps some elisp configuration code to establish key-bindings that work from the source code windows. I noticed that pydbgr does not appear to invoke a minor/major-mode within the source buffer window, so I don't know where to start implementing this myself as I have no mode-hooks to hang elisp code off. A: A recent change in emacs-dbgr on http://github.com/rocky/emacs-dbgr adds this. There are a number of other issues regarding breakpoint synchronization. emacs-dbgr is a work in progress, not a finished product.
doc_2930
so i am wondering is there a way to do it if there is please tell me what code do i write Note:button 1 is already a finger pointer i want button 2 to be a finger pointer after clicking button 1 this is my code: <input type="button" id="button1" type="submit" style="cursor: pointer; background-color:black;height: 45px; width: 150px; color:red;border-radius:10px;"value="first button" onclick="enableButton2()" /> <input type="button" id="button2" style="background-color:yellow; height: 45px;width: 225px;color:red;border-radius:10px;"value="second button" disabled /> A: use it : <script> function enableButton2(){ var btn2 = document.getElementById('button2'); btn2.setAttribute('disabled', false) btn2.style.cursor = 'pointer' } </script> <input type="button" id="button1" type="submit" style="cursor: pointer; background-color:black;height: 45px; width: 150px; color:red;border-radius:10px;" value="first button" onclick="enableButton2()" /> <input type="button" id="button2" style="background-color:yellow; height: 45px;width: 225px;color:red;border-radius:10px;" value="second button" disabled="true" /> A: this way: the css style you are looking for is cursor : not-allowed; const bt_1 = document.getElementById('button1') , bt_2 = document.getElementById('button2') ; bt_1.onclick = () => { bt_2.disabled = false } button { cursor : pointer; height : 45px; border-radius : 10px; color : red; } button[disabled] { cursor : not-allowed; pointer-events : none; color : #c0c0c0; background-color : #ffffff !important; } #button1 { background-color : black; width : 150px; } #button2 { background-color : yellow; width : 225px; } <button id="button1" type="submit" > first button </button> <button id="button2" disabled > second button </button>
doc_2931
https://usda.library.cornell.edu/concern/publications/3t945q76s?locale=en For example, If I look at November 2019 report https://downloads.usda.library.cornell.edu/usda-esmis/files/3t945q76s/dz011445t/mg74r196p/latest.pdf I need the data on Page 12 for corns, I have to create separate files for ending stocks, exports etc. I am new to Python and I am not sure how to scrape the content separately. If I can figure it out for one month then I can create a loop. But, I am confused on how to proceed for one file. Can someone help me out here, TIA. A: Here a little example using PyPDF2 ,requests and BeautifulSoup ...pls check the notes comment , this is for first block ...if you need more is necesary change the value in url variable # You need install : # pip install PyPDF2 - > Read and parse your content pdf # pip install requests - > request for get the pdf # pip install BeautifulSoup - > for parse the html and find all url hrf with ".pdf" final from PyPDF2 import PdfFileReader import requests import io from bs4 import BeautifulSoup url=requests.get('https://usda.library.cornell.edu/concern/publications/3t945q76s?locale=en#release-items') soup = BeautifulSoup(url.content,"lxml") for a in soup.find_all('a', href=True): mystr= a['href'] if(mystr[-4:]=='.pdf'): print ("url with pdf final:", a['href']) urlpdf = a['href'] response = requests.get(urlpdf) with io.BytesIO(response.content) as f: pdf = PdfFileReader(f) information = pdf.getDocumentInfo() number_of_pages = pdf.getNumPages() txt = f""" Author: {information.author} Creator: {information.creator} Producer: {information.producer} Subject: {information.subject} Title: {information.title} Number of pages: {number_of_pages} """ # Here the metadata of your pdf print(txt) # numpage for the number page numpage=20 page = pdf.getPage(numpage) page_content = page.extractText() # print the content in the page 20 print(page_content) A: I would recommend Beautiful Soup if you need to scrape data from a website ,but it looks like you are going to need OCR for extracting the data from the PDF. There is something called pytesseract. Look into that and the tutorials and you should be set. A: Try pdfreader. You can extract the tables as PDF markdown containing decoded text strings and parse then as plain texts. from pdfreader import SimplePDFViewer fd = open("latest.pdf","rb") viewer = SimplePDFViewer(fd) viewer.navigate(12) viewer.render() markdown = viewer.canvas.text_content markdown variable contains all texts including PDF commands (positioning, display): all strings come in brackets followed by Tj or TJ operator. For more on PDF text operators see PDF 1.7 sec. 9.4 Text Objects You can parse it with regular expressions for example.
doc_2932
I found that there is an argument in keras2onnx.convert_keras called channel_first_inputs but couldn't find any example on how to use it on their official site. I am doing this step as a part of the process of converting my keras model into .engine model. Is there any other way to do so without the need to onnx intermediate step?. Searching for the parameter name inside the keras2onnx code, I found the following usage * *In Here: channel_first_inputs=['input_1'] *In Here: channel_first_inputs=[model.input_names[0]] A: I used channel_first_inputs=['input_1'] and it worked fine.
doc_2933
[{"id":"22","game":"??? 3 - 0 ?????","date":"27th August, 2016"}] I am adding the JSON_UNESCAPED_UNICODE inside my json_encode() function but know I get this. Notice: Use of undefined constant JSON_UNESCAPED_UNICODE - assumed 'JSON_UNESCAPED_UNICODE' in /var/www/vhosts/theo-android.co.uk/httpdocs/ael/android/last_game_json.php on line 25 Warning: json_encode() expects parameter 2 to be long, string given in /var/www/vhosts/theo-android.co.uk/httpdocs/ael/android/last_game_json.php on line 25 This is my PHP code that reads the JSON. <?php include("../init.php"); $string=""; $newString=""; $get_posts = "select * from last_game"; error_reporting(E_ALL); ini_set("display_errors", 1); $run_posts = mysqli_query($con, $get_posts); $posts_array = array(); while ($posts_row = mysqli_fetch_array($run_posts)) { $row_array['id'] = $posts_row['id']; $row_array['game'] = $posts_row['game']; $row_array['date'] = $posts_row['date']; array_push($posts_array,$row_array); } $string = json_encode($posts_array, JSON_UNESCAPED_UNICODE); echo $string; Any ideas how to fix it? Thanks. Theo. EDIT I did this but I get an error. <?php include("init.php"); $get_posts = "select * from last_game"; error_reporting(E_ALL); ini_set("display_errors", 1); $run_posts = mysqli_query($con,$get_posts); $posts_array = array(); while ($posts_row = mysqli_fetch_array($run_posts)){ $row_array['id'] = $posts_row['id']; $row_array['game'] =$posts_row['game']; $row_array['date'] = $posts_row['date']; array_push($posts_array,$row_array); } $str = '\u0391\u0395\u039b 3 - 0 \u039e\u03b1\u03bd\u03b8\u03b7'; $str = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', function ($match) { (return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE'); ( }, $str); //$string = json_encode(utf8_encode($posts_array)); //$response = utf8_encode($string,true); //echo $response; print($str); ?> in this line: return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE'); A: Before you access your database, preferably right after the connection is set up, do this: mysqli_query($con, "SET CHARACTER SET utf8"); mysqli_query($con, "SET NAMES 'utf8'"); mysqli_query($con, "SET SESSION collation_connection = 'utf8_general_ci'"); Also ensure that your table was created using UTF-8 encoding for text fields. To check this, use: SHOW CREATE TABLE last_game; If you see latin1 you'll want to change this to utf8, and utf8_general_ci or utf8_unicode_ci. Also ensure that the data is in UTF-8 when it is input and stored. Edit: It looks like you're getting escaped unicode from the JSON parsing. Probably because you have an older version of PHP. You can do this to convert it: php > $str = '\u0391\u0395\u039b 3 - 0 \u039e\u03b1\u03bd\u03b8\u03b7'; php > $str = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', function ($match) { php ( return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE'); php ( }, $str); php > php > print($str); ΑΕΛ 3 - 0 Ξανθη php > See here for other examples of how to emulate JSON_UNESCAPED_UNICODE in older PHP versions. Edit: Change your edited code to this: <?php include("../init.php"); // Probably just put this in init.php. mysqli_query($con, "SET CHARACTER SET utf8"); mysqli_query($con, "SET NAMES 'utf8'"); mysqli_query($con, "SET SESSION collation_connection = 'utf8_general_ci'"); $string=""; $newString=""; $get_posts = "select * from last_game"; error_reporting(E_ALL); ini_set("display_errors", 1); $run_posts = mysqli_query($con, $get_posts); $posts_array = array(); while ($posts_row = mysqli_fetch_array($run_posts)) { $row_array['id'] = $posts_row['id']; $row_array['game'] = $posts_row['game']; $row_array['date'] = $posts_row['date']; array_push($posts_array, $row_array); } $string = json_encode($posts_array); $string = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', function ($match) { return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE'); }, $string); echo $string;
doc_2934
TabFragment1.java public class TabFragment1 extends Fragment { TextView textViewTitle; EditText editTextName; EditText editTextBuy; EditText editTextHome; EditText editTextStore; EditText editTextAddress; EditText editTextPhone; EditText editTextDate; Button buttonCreateAccount; Button btnDatePicker, btnTimePicker; EditText txtDate, txtTime; private int mYear, mMonth, mDay, mHour, mMinute; DataBaseAdapter dataBaseAdapter; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.tab_fragment_1, container, false); /* get Instance of Database Adapter dataBaseAdapter= new DataBaseAdapter(getContext()); */ dataBaseAdapter = new DataBaseAdapter(getActivity()); dataBaseAdapter = dataBaseAdapter.open(); // Get Refferences of Views textViewTitle = (TextView) view.findViewById(R.id.textViewTitle); editTextName = (EditText) view.findViewById(R.id.editTextName); editTextBuy = (EditText)view.findViewById(R.id.editTextBuy); editTextHome = (EditText) view.findViewById(R.id.editTextHome); editTextStore = (EditText) view.findViewById(R.id.editTextStore); editTextAddress = (EditText)view.findViewById(R.id.editTextAddress); editTextPhone = (EditText) view.findViewById(R.id.editTextPhone); editTextDate = (EditText) view.findViewById(R.id.editTextDate); buttonCreateAccount = (Button) view.findViewById(R.id.buttonCreateAccount); btnDatePicker = (Button) view.findViewById(R.id.btn_date); btnTimePicker = (Button) view.findViewById(R.id.btn_time); txtDate = (EditText) view.findViewById(R.id.in_date); txtTime = (EditText) view.findViewById(R.id.in_time); /* btnDatePicker.setOnClickListener(this); btnTimePicker.setOnClickListener(this); buttonCreateAccount.setOnClickListener(this);*/ btnDatePicker.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Get Current Date final Calendar c = Calendar.getInstance(); mYear = c.get(Calendar.YEAR); mMonth = c.get(Calendar.MONTH); mDay = c.get(Calendar.DAY_OF_MONTH); DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { txtDate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year); } }, mYear, mMonth, mDay); datePickerDialog.show(); } }); btnTimePicker.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Get Current Time final Calendar c = Calendar.getInstance(); mHour = c.get(Calendar.HOUR_OF_DAY); mMinute = c.get(Calendar.MINUTE); // Launch Time Picker Dialog TimePickerDialog timePickerDialog = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { txtTime.setText(hourOfDay + ":" + minute); } }, mHour, mMinute, false); timePickerDialog.show(); } }); buttonCreateAccount.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub String name = editTextMedicineName.getText().toString(); String buy = editTextQuantityToBuy.getText().toString(); String lHome = editTextLeftAtHome.getText().toString(); String mStore = editTextMedicineStore.getText().toString(); String mAdd = editTextMedStoreAddress.getText().toString(); String phone = editTextPhone.getText().toString(); String date = editTextDate.getText().toString(); // check if any of the fields are vaccant if (name.equals("") || buy.equals("") || lHome.equals("") || mStore.equals("") || mAdd.equals("") || phone.equals("") || date.equals("")) { Toast.makeText(getContext(), "Field Vacant", Toast.LENGTH_LONG).show(); return; } else { // Save the Data in Database dataBaseAdapter.insertEntry(name, buy, lHome, mStore, mAdd, phone, date); Toast.makeText(getContext(), "Reminder Successfully Created", Toast.LENGTH_LONG).show(); } } }); return view; } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); dataBaseAdapter.close(); } }
doc_2935
for i in 1:10 x1,y1 = first_function(a,b,c) plot(x1,y1) end for j in 1:10 x2,y2 = second_function(a,b,c) plot(x2,y2) end I have tried to use the plot!() command instead but this gives me all 20 plots on the same plot, which I don't want. What I would like to do is to plot the results of both functions on the same plot, for each iteration. For instance I want 10 plots, one for each iteration where each plot has results of both first_function() as well as second_function. I have tried the following instead: for j in 1:10 x1,y1 = first_function(a,b,c) x2,y2 = second_function(a,b,c) plot!(x1,y1) plot!(x2,y2) end However, this doesn't seem to work either. EDIT: Based on an answer I received, I was able to figure out that the following does the trick: for i in 1:10 x1,y1 = first_function(a,b,c) x2,y2 = second_function(a,b,c) plot(x1,y1) plot!(x2,y2) end This generates a new plot at the end of each iteration of the loop, which is what I wanted. A: As you have found out, plot() creates a new plot, while plot!() plots onto the currently active plot. All you need to do is be explicit about when you want to do what, and if you're using plot!() also be explicit about which plot object you want to plot to. So something like: p1 = plot() p2 = plot() for i in 1:10 plot!(p1, first_function(a, b, c)...) plot!(p2, second_function(a, b, c)...) end then p1 should have 10 lines showing the result of first_function, and p2 10 lines with results of the second function. It is not clear to me whether you want both of these plots to appear on the same figure, but if you do then plot(p1, p2) will create a figure with two subplots.
doc_2936
In the interest of improving performance, there is one method which gets hit a lot,thousands of times during the application life, and I was wanting to rewrite it in .Net (C#) to see if the runtime can be improved. The method in question manipulates ADODB Recordsets. Is there any performance issues I should be aware of or take into consideration since these recordsets will be passed to and from VB6 via COM interop? A: I haven't done anything specific on this but from my experience with Interop, .NET is very well optimized and usually per interop call to Win API or COM only introduces nano seconds of overhead that is negligible. ADO Recordset will just be treated the same as any other COM objects created on unmanaged heap and under the hood is the IntPtr address that they deal with. Native .NET framework library and its garbage collector is far superior than whats avaialble in VB. I believe rewriting some of your old VB code in .NET may give you some performance gain more or at least enough to ignore the interop overhead. Best if you equip yourself with a profiler tool and continuosly monitor performance as you migrate the implementation piece by piece.
doc_2937
public string DataReceived { get { return data_str; } set { data_str = value; string[] valori_separati = DataReceived.Split(','); //valori_separati = DataReceived.Split(','); try { int.TryParse(valori_separati[0], out Team_ID); int.TryParse(valori_separati[1], out Mission_time); double.TryParse(valori_separati[2], out Packet_count); int.TryParse(valori_separati[3], out Alt_sensor); double.TryParse(valori_separati[4], out Pressure); double.TryParse(valori_separati[5], out Temp); double.TryParse(valori_separati[6], out Voltage); double.TryParse(valori_separati[7], out GPS_Time); double.TryParse(valori_separati[8], out GPS_Latitude); double.TryParse(valori_separati[9], out GPS_Longitude); double.TryParse(valori_separati[10], out GPS_Altitude); int.TryParse(valori_separati[11], out GPS_Sats); double.TryParse(valori_separati[12], out TILT_X); double.TryParse(valori_separati[13], out TILT_Y); double.TryParse(valori_separati[14], out TILT_Z); int.TryParse(valori_separati[15], out Software_state); } catch (IndexOutOfRangeException) { packet_loss = packet_loss + 1; } if (packet_loss >= 5) { BeginInvoke((Action)(() => fr1.Show())); } updateTextboxDelegate fillTextbox = updateTextbox; this.Invoke(fillTextbox); } } private void updateTextbox() { Data_ID_Glider.Text = Team_ID.ToString(); DataMssTime.Text = Mission_time.ToString(); Data_Pack.Text = Packet_count.ToString(); Data_Alt.Text = Alt_sensor.ToString(); Data_Press.Text = Pressure.ToString(); GpsTime.Text = GPS_Time.ToString(); Data_Temp.Text = Temp.ToString(); Data_Voltage.Text = Voltage.ToString(); Data_Sw_St.Text = Software_state.ToString(); [...] } By this way decimal values are not shown. I mean that only numbers, without their decimals, are shown. I tried to update the textbox inside the datareceived but thread exception is called. How should I do that? A: After casting most of the values into double, you are using double.ToString() method to convert it into a string. This truncates the decimal part of the double value. There are many string formatters that you can use to format the double value according to your needs. For example you can try Data_ID_Glider.Text = Team_ID.ToString("F"); The above will assign the value of Team_ID with 3 decimal places. For more such specifiers you can take a look here https://msdn.microsoft.com/en-us/library/kfsatb94(v=vs.110).aspx A: I solved the problem using this method: double.TryParse(valori_separati[12],NumberStyles.Number, CultureInfo.CreateSpecificCulture ("en-US"), out TILT_X); and so on with the other array arguments.
doc_2938
def create_multiplier (x): return lambda y: y * x input1 = int(raw_input("Please enter your initial number for our multiplier")) multi = create_multiplier(input1) input2 = int(raw_input("Please enter your second number for our multiplier")) print input1, " times by ", input2, " = " ,multi(input2) However i'm now curious how they expected us to achieve it with only functions,initially i thought that maybe you would pass your first number to x in the first function, then pass a number too our second function for y, and because we were returning the second function inside the first, we could use x like a nested variable. That got shot down quick I understand if you are not willing to reply as this is coursework but this has just got me curious how you were meant to achieve it without presetting our x in a lambda, maybe I'm just looking at it weirdly and its blatantly obvious. Thank you for your replies A: lambda is just an annoying ;-) shortcut for writing a function (def). So, for example, def create_multiplier(x): def inner_function(y): return x*y return inner_function does the same thing. Later: not quite the same thing. Your lambda actually returns y*x, not x*y ;-)
doc_2939
They seem to do this by reading the original file from the /private/var/mobile/Media/DCIM/100APPLE/ folder and running it through an EXIF library. However, I can't work out a way of matching a photo returned from the UIImagePickerController to a file on disk. I've explored file sizes, but the original file is a JPEG, whilst the returned image is a raw UIImage, making it impossible to know the file size of the image that was selected. I'm considering making a table of hashes and matching against the first x pixels of each image. This seems a bit over the top though, and probably quite slow. Any suggestions? A: Apple has added an Image I/O Framework in iOS4 which can be used to read EXIF data from pictures. I don't know if the UIImagePickerController returns a picture with the EXIF data embedded though. Edit: In iOS4 you can fetch the EXIF data by grabbing the value of the UIImagePickerControllerMediaMetadata key in the info dictionary which is passed to the UIImagePickerControllerDelegate delegate. A: I had a similar question where I wanted just the date a picture was taken and none of the above appear to solve my problem in a simple way (e.g. no external libraries), so here is all of the data I could find which you can extract from an image after selecting it with the picker: // Inside whatever implements UIImagePickerControllerDelegate @import AssetsLibrary; // ... your other code here ... @implementation MYImagePickerDelegate - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { NSString *mediaType = info[UIImagePickerControllerMediaType]; UIImage *originalImage = info[UIImagePickerControllerOriginalImage]; UIImage *editedImage = info[UIImagePickerControllerEditedImage]; NSValue *cropRect = info[UIImagePickerControllerCropRect]; NSURL *mediaUrl = info[UIImagePickerControllerMediaURL]; NSURL *referenceUrl = info[UIImagePickerControllerReferenceURL]; NSDictionary *mediaMetadata = info[UIImagePickerControllerMediaMetadata]; NSLog(@"mediaType=%@", mediaType); NSLog(@"originalImage=%@", originalImage); NSLog(@"editedImage=%@", editedImage); NSLog(@"cropRect=%@", cropRect); NSLog(@"mediaUrl=%@", mediaUrl); NSLog(@"referenceUrl=%@", referenceUrl); NSLog(@"mediaMetadata=%@", mediaMetadata); if (!referenceUrl) { NSLog(@"Media did not have reference URL."); } else { ALAssetsLibrary *assetsLib = [[ALAssetsLibrary alloc] init]; [assetsLib assetForURL:referenceUrl resultBlock:^(ALAsset *asset) { NSString *type = [asset valueForProperty:ALAssetPropertyType]; CLLocation *location = [asset valueForProperty:ALAssetPropertyLocation]; NSNumber *duration = [asset valueForProperty:ALAssetPropertyDuration]; NSNumber *orientation = [asset valueForProperty:ALAssetPropertyOrientation]; NSDate *date = [asset valueForProperty:ALAssetPropertyDate]; NSArray *representations = [asset valueForProperty:ALAssetPropertyRepresentations]; NSDictionary *urls = [asset valueForProperty:ALAssetPropertyURLs]; NSURL *assetUrl = [asset valueForProperty:ALAssetPropertyAssetURL]; NSLog(@"type=%@", type); NSLog(@"location=%@", location); NSLog(@"duration=%@", duration); NSLog(@"assetUrl=%@", assetUrl); NSLog(@"orientation=%@", orientation); NSLog(@"date=%@", date); NSLog(@"representations=%@", representations); NSLog(@"urls=%@", urls); } failureBlock:^(NSError *error) { NSLog(@"Failed to get asset: %@", error); }]; } [picker dismissViewControllerAnimated:YES completion:nil]; } @end So when you select an image, you get output that looks like this (including date!): mediaType=public.image originalImage=<UIImage: 0x7fb38e00e870> size {1280, 850} orientation 0 scale 1.000000 editedImage=<UIImage: 0x7fb38e09e1e0> size {640, 424} orientation 0 scale 1.000000 cropRect=NSRect: {{0, 0}, {1280, 848}} mediaUrl=(null) referenceUrl=assets-library://asset/asset.JPG?id=AC072879-DA36-4A56-8A04-4D467C878877&ext=JPG mediaMetadata=(null) type=ALAssetTypePhoto location=(null) duration=ALErrorInvalidProperty assetUrl=assets-library://asset/asset.JPG?id=AC072879-DA36-4A56-8A04-4D467C878877&ext=JPG orientation=0 date=2014-07-14 04:28:18 +0000 representations=( "public.jpeg" ) urls={ "public.jpeg" = "assets-library://asset/asset.JPG?id=AC072879-DA36-4A56-8A04-4D467C878877&ext=JPG"; } Anyway, hopefully that saves someone else some time. A: I spend a while working on this as well for an application I was contracted to build. Basically as the API currently stands it is not possible. The basic problem is the UIImage class STRIPS all EXIF data except for the orientation out. Also the function to save to the camera roll strips this data out. So basically the only way to grab and maintain any extra EXIF data is to save it in a private "camera roll" in your application. I have filed this bug with apple as well and emphasized the need to the app reviewer reps we've been in contact with. Hopefully someday they'll add it in.. Otherwise it makes having GEO tagging completely useless as it only works in the "stock" camera application. NOTE Some applications on the app store hack around this. By, what I have found, directly accessing the camera roll and SAVING photos straight to it to save GEO data. However this only works with the camera roll/saved photos and NOT the rest of the photo library. The photos "synced" to your phone from your computer have all EXIF data except for orientation stripped. I still can't understand why those applications were approved (heck they even DELETE from the camera roll) and our application which does none of that is still being held back. A: For iOS 8 and later you can use Photos Framework. func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let url = info[UIImagePickerControllerReferenceURL] as? URL if url != nil { let fetchResult = PHAsset.fetchAssets(withALAssetURLs: [url!], options: nil) let asset = fetchResult.firstObject print(asset?.location?.coordinate.latitude) print(asset?.creationDate) } } A: Have you took a look at this exif iPhone library? http://code.google.com/p/iphone-exif/ Gonna try it on my side. I'd like to get the GPS (geotags) coordinates from the picture that has been taken with the UIImagePickerController :/ After a deeper look, this library seems to take NSData info as an input and the UIImagePickerController returns a UIImage after taking a snapshot. In theory, if we use the selected from the UIkit category for UIImage NSData * UIImageJPEGRepresentation ( UIImage *image, CGFloat compressionQuality ); Then we can convert the UIImage into a NSData instance and then use it with the iPhone exif library. UPDATE: I gave a test to the library mentioned above and it seems to work. However because of my limited knwoledge about the EXIF format and the lack of high level API in the library, I don't manage to get the values for the EXIF tags. Here's my code in case any of you can go further : #import "EXFJpeg.h" - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo { NSLog(@"image picked %@ with info %@", image, editingInfo); NSData* jpegData = UIImageJPEGRepresentation (image,0.5); EXFJpeg* jpegScanner = [[EXFJpeg alloc] init]; [jpegScanner scanImageData: jpegData]; EXFMetaData* exifData = jpegScanner.exifMetaData; EXFJFIF* jfif = jpegScanner.jfif; EXFTag* tagDefinition = [exifData tagDefinition: [NSNumber numberWithInt:EXIF_DateTime]]; //EXFTag* latitudeDef = [exifData tagDefinition: [NSNumber numberWithInt:EXIF_GPSLatitude]]; //EXFTag* longitudeDef = [exifData tagDefinition: [NSNumber numberWithInt:EXIF_GPSLongitude]]; id latitudeValue = [exifData tagValue:[NSNumber numberWithInt:EXIF_GPSLatitude]]; id longitudeValue = [exifData tagValue:[NSNumber numberWithInt:EXIF_GPSLongitude]]; id datetime = [exifData tagValue:[NSNumber numberWithInt:EXIF_DateTime]]; id t = [exifData tagValue:[NSNumber numberWithInt:EXIF_Model]]; .... .... The retrieving of tags definition is OK, but all tag values returns nil :( In case you want to give a try to the library, you need to define a global variable to get it running (as explained in the doc but hum.. :/) BOOL gLogging = FALSE; UPDATE 2 Answer here : iPhone - access location information from a photo A UIImage does not encapsulate the meta information, so we're stuck : for sure, no EXIF info will be given through this interface. FINAL UPDATE Ok I managed to get it working, at least to geotag properly pictures returned by the picker. Before triggering the UIImagePickerController, it's up to you to use the CLLocationManager to retrieve the current CLocation Once you have it, you can use this method that uses exif-iPhone library to geotag the UIImage from the CLLocation : -(NSData*) geotagImage:(UIImage*)image withLocation:(CLLocation*)imageLocation { NSData* jpegData = UIImageJPEGRepresentation(image, 0.8); EXFJpeg* jpegScanner = [[EXFJpeg alloc] init]; [jpegScanner scanImageData: jpegData]; EXFMetaData* exifMetaData = jpegScanner.exifMetaData; // end of helper methods // adding GPS data to the Exif object NSMutableArray* locArray = [self createLocArray:imageLocation.coordinate.latitude]; EXFGPSLoc* gpsLoc = [[EXFGPSLoc alloc] init]; [self populateGPS: gpsLoc :locArray]; [exifMetaData addTagValue:gpsLoc forKey:[NSNumber numberWithInt:EXIF_GPSLatitude] ]; [gpsLoc release]; [locArray release]; locArray = [self createLocArray:imageLocation.coordinate.longitude]; gpsLoc = [[EXFGPSLoc alloc] init]; [self populateGPS: gpsLoc :locArray]; [exifMetaData addTagValue:gpsLoc forKey:[NSNumber numberWithInt:EXIF_GPSLongitude] ]; [gpsLoc release]; [locArray release]; NSString* ref; if (imageLocation.coordinate.latitude <0.0) ref = @"S"; else ref =@"N"; [exifMetaData addTagValue: ref forKey:[NSNumber numberWithInt:EXIF_GPSLatitudeRef] ]; if (imageLocation.coordinate.longitude <0.0) ref = @"W"; else ref =@"E"; [exifMetaData addTagValue: ref forKey:[NSNumber numberWithInt:EXIF_GPSLongitudeRef] ]; NSMutableData* taggedJpegData = [[NSMutableData alloc] init]; [jpegScanner populateImageData:taggedJpegData]; [jpegScanner release]; return [taggedJpegData autorelease]; } // Helper methods for location conversion -(NSMutableArray*) createLocArray:(double) val{ val = fabs(val); NSMutableArray* array = [[NSMutableArray alloc] init]; double deg = (int)val; [array addObject:[NSNumber numberWithDouble:deg]]; val = val - deg; val = val*60; double minutes = (int) val; [array addObject:[NSNumber numberWithDouble:minutes]]; val = val - minutes; val = val*60; double seconds = val; [array addObject:[NSNumber numberWithDouble:seconds]]; return array; } -(void) populateGPS:(EXFGPSLoc* ) gpsLoc :(NSArray*) locArray{ long numDenumArray[2]; long* arrPtr = numDenumArray; [EXFUtils convertRationalToFraction:&arrPtr :[locArray objectAtIndex:0]]; EXFraction* fract = [[EXFraction alloc] initWith:numDenumArray[0]:numDenumArray[1]]; gpsLoc.degrees = fract; [fract release]; [EXFUtils convertRationalToFraction:&arrPtr :[locArray objectAtIndex:1]]; fract = [[EXFraction alloc] initWith:numDenumArray[0] :numDenumArray[1]]; gpsLoc.minutes = fract; [fract release]; [EXFUtils convertRationalToFraction:&arrPtr :[locArray objectAtIndex:2]]; fract = [[EXFraction alloc] initWith:numDenumArray[0] :numDenumArray[1]]; gpsLoc.seconds = fract; [fract release]; } A: This works with iOS5 (beta 4) and the camera roll (you need type defs for the blocks in the .h): -(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType]; if ([mediaType isEqualToString:(NSString*)kUTTypeImage]) { NSURL *url = [info objectForKey:UIImagePickerControllerReferenceURL]; if (url) { ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset) { CLLocation *location = [myasset valueForProperty:ALAssetPropertyLocation]; // location contains lat/long, timestamp, etc // extracting the image is more tricky and 5.x beta ALAssetRepresentation has bugs! }; ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror) { NSLog(@"cant get image - %@", [myerror localizedDescription]); }; ALAssetsLibrary *assetsLib = [[ALAssetsLibrary alloc] init]; [assetsLib assetForURL:url resultBlock:resultblock failureBlock:failureblock]; } } A: There is a way in iOS 8 Without using any 3rd party EXIF library. #import <Photos/Photos.h> - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { NSURL *url = [info objectForKey:UIImagePickerControllerReferenceURL]; PHFetchResult *fetchResult = [PHAsset fetchAssetsWithALAssetURLs:@[url] options:nil]; PHAsset *asset = fetchResult.firstObject; //All you need is //asset.location.coordinate.latitude //asset.location.coordinate.longitude //Other useful properties of PHAsset //asset.favorite //asset.modificationDate //asset.creationDate } A: This is something that the public API does not provide, but could be useful to many people. Your primary recourse is to file a bug with Apple that describes what you need (and it can be helpful to explain why you need it as well). Hopefully your request could make it into a future release. After filing a bug, you could also use one of the Developer Technical Support (DTS) incidents that came with your iPhone Developer Program membership. If there is a public way to do this, an Apple engineer will know. Otherwise, it may at least help get your plight a bit more attention within the mothership. Best of luck! A: Use the UIImagePickerControllerMediaURL dictionary key to get the file URL to the original file. Despite what the documentation says, you can get the file URL for photos and not only movies. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { // Try to get the original file. NSURL *originalFile = [info objectForKey:UIImagePickerControllerMediaURL]; if (originalFile) { NSData *fileData = [NSData dataWithContentsOfURL:originalFile]; } } A: You might be able to hash the image data returned by the UIImagePickerController and each of the images in the directory and compare them. A: Just a thought, but have you tried TTPhotoViewController in the Three20 project on GitHub? That provides an image picker that can read from multiple sources. You may be able to use it as an alternative to UIImagePickerController, or the source might give you a clue how to work out how to get the info you need. A: Is there a specific reason you want to extract the location data from the image? An alternative could be to get the location separately using the CoreLocation framework. If it's only the geodata you need, this might save you some headaches. A: it seems that photo attained by UIImagePickerControllerMediaURL don't have exif tags at all A: In order to get this metadata you'll have to use the lower level framework AVFoundation. Take a look at Apple's Squarecam example (http://developer.apple.com/library/ios/#samplecode/SquareCam/Introduction/Intro.html) Find the method below and add the line, I've added to the code. The metadata dictionary returned also contains a diagnostics NSDictionary object. - (BOOL)writeCGImageToCameraRoll:(CGImageRef)cgImage withMetadata:(NSDictionary *)metadata { NSDictionary *Exif = [metadata objectForKey:@"Exif"]; // Add this line } A: I'm using this for camera roll images -(CLLocation*)locationFromAsset:(ALAsset*)asset { if (!asset) return nil; NSDictionary* pickedImageMetadata = [[asset defaultRepresentation] metadata]; NSDictionary* gpsInfo = [pickedImageMetadata objectForKey:(__bridge NSString *)kCGImagePropertyGPSDictionary]; if (gpsInfo){ NSNumber* nLat = [gpsInfo objectForKey:(__bridge NSString *)kCGImagePropertyGPSLatitude]; NSNumber* nLng = [gpsInfo objectForKey:(__bridge NSString *)kCGImagePropertyGPSLongitude]; if (nLat && nLng) return [[CLLocation alloc]initWithLatitude:[nLat doubleValue] longitude:[nLng doubleValue]]; } return nil; } -(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { //UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; NSURL *assetURL = [info objectForKey:UIImagePickerControllerReferenceURL]; // create the asset library in the init method of your custom object or view controller //self.library = [[ALAssetsLibrary alloc] init]; // [self.library assetForURL:assetURL resultBlock:^(ALAsset *asset) { // try to retrieve gps metadata coordinates CLLocation* myLocation = [self locationFromAsset:asset]; // Do your stuff.... } failureBlock:^(NSError *error) { NSLog(@"Failed to get asset from library"); }]; } It works obviously if the image contains gps meta informations Hope it helps A: This is in Swift 3 if you still want support for iOS 8: import AssetsLibrary func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if picker.sourceType == UIImagePickerControllerSourceType.photoLibrary, let url = info[UIImagePickerControllerReferenceURL] as? URL { let assetLibrary = ALAssetsLibrary() assetLibrary.asset(for: url, resultBlock: { (asset) in if let asset = asset { let assetRep: ALAssetRepresentation = asset.defaultRepresentation() let metaData: NSDictionary = assetRep.metadata() as NSDictionary print(metaData) } }, failureBlock: { (error) in print(error!) }) } } A: For iOS 10 - Swift 3 The picker's callback has an info dict where there is a key with metadata: UIImagePickerControllerMediaMetadata A: The naughty way to do this is to traverse the UIImagePickerViewController's views and pick out the selected image in the delegate callback. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { id thumbnailView = [[[[[[[[[[picker.view subviews] objectAtIndex:0] subviews] objectAtIndex:0] subviews] objectAtIndex:0] subviews] objectAtIndex:0] subviews] objectAtIndex:0]; NSString *fullSizePath = [[[thumbnailView selectedPhoto] fileGroup] pathForFullSizeImage]; NSString *thumbnailPath = [[[thumbnailView selectedPhoto] fileGroup] pathForThumbnailFile]; NSLog(@"%@ and %@", fullSizePath, thumbnailPath); } That will give you the path to the full size image, which you can then open with an EXIF library of your choice. But, this calls a Private API and these method names will be detected by Apple if you submit this app. So don't do this, OK?
doc_2940
def func(x): //calculation, returning 0 if done and an algorithm as follows: for x in X: run func(x) terminate the loop if one of func(x) returns 0 Above, X is a large set of doubles, each func(x) is independent from the other. Question: Which of Python's multi-threading/multi-processing functionality can I use to maximize the performance of this calculation? For info, I am using a multi-core computer. A: If you have multiple cores then you will need to use multiprocessing to see the benefit. To get a result from part-way through a large number of candidates, you can break it up into batches. This example code ought to help see what to do. """ Draws on https://pymotw.com/2/multiprocessing/communication.html """ import multiprocessing class Consumer(multiprocessing.Process): def __init__(self, task_queue, result_queue): multiprocessing.Process.__init__(self) self.task_queue = task_queue self.result_queue = result_queue def run(self): while True: next_task = self.task_queue.get() if next_task is None: # Poison pill means shutdown self.task_queue.task_done() break answer = next_task() self.task_queue.task_done() self.result_queue.put(answer) return class Optimiser(object): def __init__(self, x): self.x = x def __call__(self): # scipy optimisation function goes here if self.x == 49195: return self.x def chunks(iterator, n): """Yield successive n-sized chunks from iterator. http://stackoverflow.com/a/312464/1706564 """ for i in xrange(0, len(iterator), n): yield iterator[i:i+n] if __name__ == '__main__': X = range(1, 50000) # Establish communication queues tasks = multiprocessing.JoinableQueue() results = multiprocessing.Queue() # Start consumers num_consumers = multiprocessing.cpu_count() consumers = [ Consumer(tasks, results) for i in xrange(num_consumers) ] for w in consumers: w.start() chunksize = 100 # this should be sized run in around 1 to 10 seconds for chunk in chunks(X, chunksize): num_jobs = chunksize # Enqueue jobs for x in chunk: tasks.put(Optimiser(x)) # Wait for all of the tasks to finish tasks.join() # Start checking results while num_jobs: result = results.get() num_jobs -= 1 if result: # Add a poison pill to kill each consumer for i in xrange(num_consumers): tasks.put(None) print 'Result:', result break
doc_2941
Based on this answer: Getting notification from Resource calendar in EWS room mailboxes usually have their account disabled and I need to use delegation. So what is proper way to subscribe and maintain affinity when using delegation? Should I just ignore setting the impersonation header and do everything else as described in How to: Maintain affinity between a group of subscriptions and the Mailbox server in Exchange? A: When you creating folder object, pass the other user email address which shared his calendar with you. AS below folders[0] = new FolderId(WellKnownFolderName.Calendar, new Mailbox("OtherUserEmail")); And then subscribe. service.SubscribeToStreamingNotifications A: For resource rooms I use impersonation as the preferred access. I know that in general the AD userids for room resources are disabled for login in AD, but my guess is that affects only Windows login. Technically when you impersonate, you don't really login as the room user. You log in as the service account with those credentials, and then indicate with the impersonation id that you want Exchange to pretend it's actually the room making all the requests you are about to make.
doc_2942
when i open http:/ /www.example.com/ex it shows this data click here i want to copy every text after MrsId which is in between the double quotes(means i want to copy MN4D / CN4D / MK4D / MO4D all othese four codes from example.com/ex and these codes changes daily ) and sotre in a varible eg ( $a= 'MN4D', $b='CN4D' ,$c='MK4D' ,$d='MO4D' ) then want to use it as $first = 'http:// www.example.com/?code='; $url = "{$first}{$a}"; $urll = "{$firsts}{$b}"; $urlll = "{$firsts}{$c}"; $urlllll = "{$firsts}{$d}"; $result = file_get_contents($url); $results = file_get_contents($urll); $resultss = file_get_contents($urlll); $resultsss = file_get_contents($urllll); echo $result; echo $results; echo $resultss; echo $resultsss; I am serching for this code from 1 month but did't get success yet. A: As I can see - data has json format. So you can use json_decode to access needed fields A: Change the code for your needs: <?php $json = '{"Amrlist":[{"Amcd":"mr-pub-4925511/1986","MrsId":"MN4D","BiclMine":"90","ImagePath":"http://my.example.com/myex/myex.jpg"},{"Amcd":"mr-pub-4925511/1986","MrsId":"CN4D","BiclMine":"90","ImagePath":"http://my.example.com/myex/myex.jpg"},{"Amcd":"mr-pub-4925511/1986","MrsId":"MK4D","BiclMine":"90","ImagePath":"http://my.example.com/myex/myex.jpg"},{"Amcd":"mr-pub-4925511/1986","MrsId":"MO4D","BiclMine":"90","ImagePath":"http://my.example.com/myex/myex.jpg"}]}'; $decoded = json_decode($json, true); //var_dump($decoded); $url = 'http://www.example.com/?code='; foreach($decoded{'Amrlist'} as $Amrlist) { //print_r($Amrlist); print $url.$Amrlist['MrsId']."\n"; //print file_get_contents($url.$Amrlist['MrsId']); } /**/ ?>
doc_2943
code: //the model class public class DemoCustomer : INotifyPropertyChanged { // These fields hold the values for the public properties. private Guid idValue = Guid.NewGuid(); private string customerNameValue = String.Empty; private string phoneNumberValue = String.Empty; public event PropertyChangedEventHandler PropertyChanged= delegate { }; // This method is called by the Set accessor of each property. // The CallerMemberName attribute that is applied to the optional propertyName // parameter causes the property name of the caller to be substituted as an argument. private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } // The constructor is private to enforce the factory pattern. public DemoCustomer() { customerNameValue = "Customer"; phoneNumberValue = "(312)555-0100"; } // This is the public factory method. public static DemoCustomer CreateNewCustomer() { return new DemoCustomer(); } // This property represents an ID, suitable // for use as a primary key in a database. public Guid ID { get { return this.idValue; } } public string CustomerName { get { return this.customerNameValue; } set { if (value != this.customerNameValue) { this.customerNameValue = value; NotifyPropertyChanged(); } } } public string PhoneNumber { get { return this.phoneNumberValue; } set { if (value != this.phoneNumberValue) { this.phoneNumberValue = value; NotifyPropertyChanged(); } } } } Then simply in my main page i do this: public ObservableCollection<DemoCustomer> progcollection = new ObservableCollection<DemoCustomer>(); public MainPage() { this.InitializeComponent(); progcollection = new ObservableCollection<DemoCustomer>(); this.progcollection.Add(new DemoCustomer()); this.txtblk.DataContext = progcollection[0].CustomerName; } Then in a click listener for example i do this: private void Button_Click_1(object sender, RoutedEventArgs e) { progcollection[0].CustomerName = "we changed the name!"; } But nothing updates in the UI!!! And here is my XAML: <Page x:Class="downloadprogressbinding.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:simpledownload" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <TextBlock x:Name="txtblk" HorizontalAlignment="Left" Margin="994,421,0,0" TextWrapping="Wrap" Text="{Binding Mode=TwoWay}" VerticalAlignment="Top" Height="89" Width="226" FontSize="36"/> <Button Content="Button" HorizontalAlignment="Left" Height="51" Margin="116,24,0,0" VerticalAlignment="Top" Width="407" Click="Button_Click_1"/> </Grid> A: Using path keyword in binding and specifying the field solved it,like this: {Binding Path=thetext, Mode=TwoWay}
doc_2944
But in the documentation, I see no mention of the Laravel / Vue / Bootstrap authentication / email verification scaffold, that existed in prior versions. All I can find are scaffolds that now use some sort of "proprietary" reactive components (Livewire/Inertia), that offer a scaffold with a loot of nice features out of the box (2FA, profile management, teams), but would unfortunately require going through a whole new learning curve (tailwind, livewire/inertia). So my question is, can I still find a Laravel / Vue / Bootstrap authentication scaffold, preferrably with all (or at least some of) the features that seem to have been added in the new scaffolds (https://jetstream.laravel.com/2.x/introduction.html), but without having to learn new technologies/stacks or was that simply abandoned by the Laravel team?
doc_2945
The username and password fields should be validated when user clicks the login button and the contact us fields should be validated when the user clicks the contact us button. In my case all the fields have been validated on the click of any button. Thanks in advance. A: You can asp.net builtin validation controls with new ajax toolkit controls it would help you A: Use the ValidationGroup attribute. <fieldset id="login"> <asp:TextBox ValidationGroup="login" ...> <asp:TextBox ValidationGroup="login" ...> <asp:Button ValidationGroup="login" ...> </fieldset> <fieldset id="contact-us"> <asp:TextBox ValidationGroup="contact" ...> ... <asp:Button ValidationGroup="contact" ...> </fieldset>
doc_2946
PdfPCell cellMerchantTitle = rowCellStyle("Merchant", fontTitleSize); cellMerchantTitle.setColspan(2); table.addCell(cellSystemTitle); table.completeRow(); public PdfPCell rowCellStyle(String cellValue, Font fontStyle){ PdfPCell cell = new PdfPCell(new Paragraph(cellValue, fontStyle)); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setBorder(Rectangle.NO_BORDER); return cell; } I already try this table.getDefaultCell().setBorder(Rectangle.NO_BORDER); A: Adding table.getDefaultCell().setBorder(Rectangle.NO_BORDER); should do the trick, but you have to make sure you add this line before completing the row: table.getDefaultCell().setBorder(Rectangle.NO_BORDER); PdfPCell cellMerchantTitle = rowCellStyle("Merchant", fontTitleSize); cellMerchantTitle.setColspan(2); table.addCell(cellSystemTitle); table.completeRow();
doc_2947
I am create button using css class="button", when ajax call it override css property like this class="button_new ui-button ui-widget ui-state-default ui-corner-all how to avoid this. .button_new { background: #3b5998; padding: 4px 8px; -webkit-border-radius: 8px; -moz-border-radius: 8px; border-radius: 8px; color: #ffffff; font-size: 11px; font-family: Georgia, Serif; text-decoration: none; vertical-align: middle; } .button_new:hover { border-top-color: #edf0f5; background: #edf0f5; color: #ff0000; } .button_new:active { border-top-color: #dfe7eb; background: #dfe7eb; } A: First, I would add an ID to the button so we don't override some instances where you want jQuery UI to set its own classes. <button id="my-button" class="button">My Button</button> Then you can load your own jQuery script after jQuery UI is executed and use something like this: $(document).ready(function() { // remove jQuery UI classes $('#my-button').removeClass('button_new ui-button ui-widget ui-state-default ui-corner-all'); // add button class back $('#my-button').addClass('button'); }); This will replace the auto-generated classes with your classes, while not conflicting with other instances where you need jQuery UI to exhibit this behavior.
doc_2948
<div class="main"> <div class="auth-buttons" > <a class="btn" id="btn-login">Login</a> <a class="btn" id="btn-register">Register</a> </div> <div id="lgn" class="btns"> <form> </form> </div> <div id="reg" class="btns"> <form> </form> </div> </div> i have jquery which switches between the login and register <script> $('#reg').hide(); $('#btn-login').click(function() { $('#reg').hide(); $('#lgn').show(); }); $('#btn-register').click(function() { $('#lgn').hide(); $('#reg').show(); }); </script> But when the register form has errors the form loads to the first page which is login how to i redirect to registration div with the errors? here is what i tried but it didnt work if ( $validator->fails() ) { return redirect(url()->previous() .'#reg')->withErrors($validator)->withInput(); } A: You can try check location's hash: if (location.hash === '#reg') { $('#lgn').hide(); $('#reg').show(); }
doc_2949
I have already this code: import 'package:flutter/material.dart'; import 'package:web_scraper/web_scraper.dart'; class Prueba extends StatefulWidget { @override State createState() => new _Prueba(); } class _Prueba extends State<Prueba> { final webScraper = WebScraper('https://www3.animeflv.net'); List<Map<String, dynamic>> link; void fetchProducts() async { // Loads web page and downloads into local state of library if (await webScraper .loadWebPage('/ver/sword-art-online-alicization-war-of-underworld-20')) { setState(() { link = webScraper.getElement( 'div.jw-wrapper.jw-reset > div.jw-media.jw-reset > video.jw-video.jw-reset', ['src']); }); } } @override void initState() { super.initState(); // Requesting to fetch before UI drawing starts fetchProducts(); } @override Widget build (BuildContext ctxt) { print(link); return Container(); } }
doc_2950
orders (id, client_id, ...) - stores orders of customers addresses (id, client_id, ...) - stores delivery addresses of customers Relationship between that tables is many-to-many so I have table addresses_orders (id, order_id, address_id) which maps where order goes But I'd like to enforce one thing - in table addresses_orders can only be paired together orders and addresses of the same customer. What is the best way to do this? I have web application based on MVC, which stores data in MySQL database. Every customer gets only his orders and addresses to choose from, but form can be tampered and malicious user can change address_id to random guess, so it will produce described insonsitency. For safety I have to validate against this scenario - probably in Model or directly in database. I prefer second solution, but how to do this? Maybe some triggers? A: If there are no overlap in addresses ( only one client per address ), Then your DB structure makes no sense. Clients Addresses Orders --- ------- ------- client_id PK address_id PK order_id PK name client_id FK address_id FK phone_number full_address data Then to get all details from an order SELECT Clients.name Addresses.full_address Orders.data FROM Orders LEFT JOIN Addresses USING(address_id) LEFT JOIN Clients USING(client_id) WHERE client_id = 42 This would give you all orders from client with ID 42. * *each order has one address *each address has one client *each client has multiple addresses *each address has multiple orders A: Is the address_id hidden or visible form field and you are worried that users are capable or willing to mess with it? I'm guessing your customers are logged in. You could take advantage of session information and user_id (or something). Retrieve the customers address_id in the process file and use that address_id, not the id sent by form (you could of course check if they match). If something goes wrong the problem is probably somewhere in session/application security, but not in the spoofed form. A: We tend to use the following approach: a) Store the customerid in the session b) When selecting the orders or addresses use one of the following showing the user names while saving the ids: - A pregenerated list using a select control where only one can be selected - A pre-generated list from which specific items can be selected using checkboxes
doc_2951
http://developer.android.com/resources/samples/ApiDemos/res/layout/linear_layout_9.html Seems to be valid in Eclipse, and looks good in the preview tab. It's just a listview that has a button on the bottom. So i've added it as R.layout.buttonlist <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/testbutton" android:text="@string/hello" android:layout_alignParentBottom="true" /> <ListView android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/list" android:layout_alignParentTop="true" android:layout_above="@id/testbutton" /> </RelativeLayout> Unfortunately when I run it, i get a pop up window that says Android has closed unexpecitdly: setListAdapter(new ArrayAdapter<String>(this, R.layout.buttonlist , data)); When I try using a built in list view: setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1 , data)); everything works fine. I dont see any errors or warnings in logcat, so I'm not sure how to pinpoint the problem. Does anyone have any ideas? Thanks Edit: adding activity public class TestActivity extends ListActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); List<String> data = new ArrayList<String>(); data.add("hello"); data.add("world"); setContentView(R.layout.buttonlist); //setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1 , data)); } } A: I don't think you can have a listview in the layout of an adapter. The passed in layout should just describe a row in the listview. So buttonlist should just contain the xml for the button. The listview needs to be in a separate layout file. If this is a list activity then you don't need another layout file, just call setListAdapter like you are doing. A: Hoofamon, I would like to correct you here. You are not creating a custom ListView but a custom layout with a ListView. Also, I believe that you have not completely understood what the setListAdapter is doing here. This line that you have is telling the listview to consume 'android.R.layout.simple_list_item_1' as the content of its layout. This layout comes pre-defined in the Android SDK. It would just contain text in each item of a listview. The third attribute 'data' indicates the content of each listview item. setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1 , data)); So, as Mike L. has suggested, if your intent is to have a listview with only text (having the default format), then the line above would serve the purpose well. You can set 'R.layout.buttonlist' as the layout of your activity using setContentView(R.layout.buttonlist); However, if you are planning to include additional content in the listview (read images) or want to change the styling of the text, you would have to define a custom layout for the listview. We can direct you to appropriate sources if you want to know how that can be done. EDIT: A possible way of loading data into a normal ListView TestActivity.java public class TestActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.buttonlist); List<String> data = new ArrayList<String>(); data.add("hello"); data.add("world"); ListView mListView = (ListView)findViewById(R.id.list); mListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1 , data)); } } buttonlist.xml <?xml version="1.0" encoding="UTF-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/testbutton" android:text="@string/hello" android:layout_alignParentBottom="true" /> <ListView android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/list" android:layout_alignParentTop="true" android:layout_above="@+id/testbutton" /> </RelativeLayout> This is how it should look like on the emulator: A: If you want to use your R.layout.buttonlist to fill up your listview,you can do it as follows(your TestActivity should extend Activity,not ListActivity): public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.buttonlist); String data[]=new String[]{"Item_1","Item_2","Item_3"} Button b=(Button)findViewById(R.id.testbutton); ListView lv=(ListView)findViewById(R.id.list); ArrayAdapter aa=new ArrayAdapter(context,android.R.layout.simple_list_item_1, data); lv.setAdapter(aa); //Your code... } Now if you want to create custom listitem to be displayed in the listview,then you need to do like this: * *Create your custom listitem xml file. Ex: custom_listitem.xml <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/icon" /> <TextView android:layout_width="wrap_content" android:layout_height="fill_parent" android:id="@+id/text" /> *Create custom ArrayAdapter: Ex. CustomArrayAdapter.class public class CustomArrayAdapter extends ArrayAdapter<String> { String[] array; LayoutInflater mInflater; public CustomArrayAdapter(Context context, int textViewResourceId, String[] objects) { super(context, textViewResourceId, objects); array=objects; mInflater = LayoutInflater.from(context); } @Override public View getView(int position, View convertView, ViewGroup parent) { final ViewHolder holder; if(convertView==null) { convertView = mInflater.inflate(R.layout.custom_listitem, null); holder = new ViewHolder(); holder.text=(TextView)convertView.findViewById(R.id.text); holder.img=(ImageView)convertView.findViewById(R.id.icon); convertView.setTag(holder); } else holder=(ViewHolder)convertView.getTag(); holder.text.setText(array[position]); if(position==0) holder.img.setImageResource(R.drawable.img1); else if(position==1) holder.img.setImageResource(R.drawable.img2); else if(position==2) holder.img.setImageResource(R.drawable.img3); return convertView; } static class ViewHolder { TextView text; ImageView img; } } *Use this custom adapter class in your main activity to fill up listview: Be sure,this main activity extends Activity and not ListActivity super.onCreate(savedInstanceState); setContentView(R.layout.main); context=getApplicationContext(); lv=(ListView)findViewById(R.id.listview); CustomArrayAdapter aa=new CustomArrayAdapter(context,R.layout.custom_listitem, new String[]{"item_1","item_2","item_3"}); lv.setAdapter(aa); // other lines of code . . .
doc_2952
#include<iostream> using namespace std; class person{ public: int age; void display() /////////// One member function same name { cout<<age; } }; class men:public person { public: int height; void display() ///////// Other member function same name { cout<<height; person::display(); } }; main() { men A; A.age=25; A.height=6; cout<<"results is"<<endl; A.display(); } See this 2nd Code, Two different function in base and derive class display() and showdata() .Both are working same as above code snippet. #include<iostream> using namespace std; class person{ public: int age; void showdata() ////////////// One member function { cout<<age; } }; class men:public person { public: int height; void display() ////////// another member function { cout<<height; person::showdata(); } }; main() { men A; A.age=25; A.height=6; cout<<"results is"<<endl; A.display(); } Which one is the good approach that gives actual benefits of inheritance? should we use the same named member functions in both classes ( base and derived class ) ? or should we use difference named member functions in both classes ( Base and derived ). And i know it is necessary to use base member function and derived class member function, because according to inheritance, derived class hold all the characteristics of base class too so it will hold the member function of base class too. A: I would rather do so: class person { public: int age = 0; virtual ~person(){} virtual void display() { cout<<age; } }; class men:public person { public: int height = 0; void display() override { cout<<height; person::display(); } }; Further, it will allow to use the advantages of polymorphism. A: I prefer using different names for base and derived classed, as in some programming languages, it may not accept the base class function's name without the override keyword. Better to use different names, and keep us away from conflicts. A: In this example is not much to do, the method showdata in the base class person is public, and men class inherits person publicly too, since men IS a person, men can call showdata directly, no need to do something like person::showdata A: I'm in favor of a simple rule that Titus Winters presented at CppCon 2018: Name functions the same when they do the same thing, so the caller doesn't need to know how the difference. Your first code violates this principle: person &p = getMen(); p.showData(); This is because showData() isn't virtual. This can be fixed in person by writing: virtual void showdata(). As it looks like you indeed intend to do the same thing for both classes, I would prefer this over your 2 suggestions.
doc_2953
db.execSQL("DROP TABLE IF EXISTS " + TABLE_REGISTER); written in method addUser(); i think table is deleted. But now when i register new User. User registration failed. I think new table is not creating. I also have deleted the above statement from addUser() method. public class DBHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "agent.db"; private static final int DATABASE_VERSION = 1; private static final String KEY_ID = "[ID]"; private static final String KEY_FNAME = "[FirstName]"; private static final String KEY_LNAME = "[LastName]"; private static final String KEY_REGDATE = "[RegistrationDate]"; private static final String KEY_USERID = "[UserID]"; private static final String KEY_PASSWORD = "[Password]"; private static final String TABLE_REGISTER = "tbRegister"; private static final String CREATE_TABLE_REGISTER = "CREATE TABLE " + TABLE_REGISTER + "(" + KEY_ID + "INTEGER PRIMARY KEY," + KEY_FNAME + "TEXT NOT NULL," + KEY_LNAME + "TEXT NOT NULL," + KEY_REGDATE + "TEXT NOT NULL," + KEY_USERID + "TEXT NOT NULL," + KEY_PASSWORD + "TEXT NOT NULL )"; public DBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE_REGISTER); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_REGISTER); onCreate(db); } public long addUser(User user) { SQLiteDatabase db = getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_ID, user.getId()); values.put(KEY_FNAME, user.getfName()); values.put(KEY_LNAME, user.getlName()); values.put(KEY_REGDATE, user.getRegDate()); values.put(KEY_USERID, user.getUserID()); values.put(KEY_PASSWORD, user.getPassword()); return db.insert(TABLE_REGISTER, null, values); } public List<User> getAllUsers() { List<User> userList = new ArrayList<>(); SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.rawQuery("SELECT * from " + TABLE_REGISTER, null); if (cursor.moveToFirst()){ do { int id = cursor.getInt(0); String fName = cursor.getString(1); String lName = cursor.getString(2); String regDate = cursor.getString(3); String userID = cursor.getString(4); String password = cursor.getString(5); User user = new User(id, fName, lName, regDate, userID, password); userList.add(user); }while (cursor.moveToNext()); cursor.close(); } return userList; } } 04-07 17:05:40.344 28263-28263/? E/Zygote: v2 04-07 17:05:40.344 28263-28263/? E/Zygote: accessInfo : 0 04-07 17:06:09.354 28263-28263/pk.edu.vu.agentpawnbroker E/SQLiteLog: (1) table tbRegister has no column named FirstName 04-07 17:06:09.364 28263-28263/pk.edu.vu.agentpawnbroker E/SQLiteDatabase: Error inserting [Password]=ppp [FirstName]=Majid [UserID]=munir64 [RegistrationDate]=07042019 [LastName]=Munir android.database.sqlite.SQLiteException: table tbRegister has no column named FirstName (code 1): , while compiling: INSERT INTO tbRegister([Password],[FirstName],[UserID],[RegistrationDate],[LastName]) VALUES (?,?,?,?,?) ################################################################# Error Code : 1 (SQLITE_ERROR) Caused By : SQL(query) error or missing database. (table tbRegister has no column named FirstName (code 1): , while compiling: INSERT INTO tbRegister([Password],[FirstName],[UserID],[RegistrationDate],[LastName]) VALUES (?,?,?,?,?)) ################################################################# at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method) at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1058) at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:623) A: The code inside onCreate() is not executed every time you run the app. So don't expect that the statement: db.execSQL(CREATE_TABLE_REGISTER); will recreate the table when you run the app next time. You must uninstall the app from the device where you test it. This way the database is deleted and when you rerun the app it will recreate the database and the code inside onCreate() will be executed to create the table. The method onCreate() is called only when the database does not exist, or you can call it directly say inside onUpgrade(). Also change the create statement to this: private static final String CREATE_TABLE_REGISTER = "CREATE TABLE " + TABLE_REGISTER + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_FNAME + " TEXT NOT NULL," + KEY_LNAME + " TEXT NOT NULL," + KEY_REGDATE + " TEXT NOT NULL," + KEY_USERID + " TEXT NOT NULL," + KEY_PASSWORD + " TEXT NOT NULL)"; You missed several spacec between the column names and their data type. Edit: Delete this line from addUser(): values.put(KEY_ID, user.getId()); The column KEY_ID is defined as PRIMARY KEY which for SQLite means that it will also be AUTOINCREMENT and you must not supply a value for it.
doc_2954
It does output proper values on click of the button. var dataString = 'username='+SessionVars.my_username+'&lessonid='+SessionVars.my_lesson_number; $('#tracking_submit').click(function(){ $.ajax({ url: "php/tracking.php", type:'POST', data: dataString, success: function(){ $('#tracking_message').replaceWith(SessionVars.my_username+"Thank you for updating."+SessionVars.my_lesson_number); } }); return false; }); Then the php file portion i'm using is this: session_start(); mysql_connect("stuff i tested and it works"); mysql_select_db("same"); $username=$_POST['username']; $lessonid=$_POST['lessonid']; mysql_query("INSERT INTO tracking ( username, lessonid ) VALUES ( ".$username.", ".$lessonid." );"); When I check the database, there is nothing in it. A: mysql_query("INSERT INTO tracking ( username, lessonid ) VALUES ('".$username."', ".$lessonid." );"); You missed quotes in that line. Also, please read about SQL Injection. A: This cannot work, since you're not putting values in your query into quotes. This should help and prevent you being hacked as well: mysql_query("INSERT INTO tracking ( username, lessonid ) VALUES ( '".mysql_real_escape_string($username)."', '".mysql_real_escape_string($lessonid)."' )"); A: change to.. $.ajax({ url: "php/tracking.php", type:'POST', cache: false, dataType: "json", data: {username: SessionVars.my_username, lessonid: SessionVars.my_lesson_number}, success: function(){ $('#tracking_message').replaceWith(SessionVars.my_username+"Thank you for updating."+SessionVars.my_lesson_number); } }); return false; }); do a print_r ($_POST) on the next page. Also yes, you should readup on some sql injection prevention. A: The issue was in the php file, which using the help of the guy's above was resolved through: $username=mysql_real_escape_string($_POST['username']); $lessonid=mysql_real_escape_string($_POST['lessonid']); mysql_query("INSERT INTO wtf ( username, lessonid ) VALUES ( '".$username."', '".$lessonid."' );");
doc_2955
REFERRAL_CHOICES = ( (None, 'Please choose'), ('search', 'From a search engine'), ('social', 'From a social network'), ) referral_source = forms.ChoiceField( choices=REFERRAL_CHOICES ) I also have a clean_company_size function which checks if the field is set to a good value: def clean_company_size(self): company_size = self.cleaned_data.get('company_size', None) if company_size is None: raise ValidationError('Please select a company size') return company_size If I add a or company_size == 'None' condition to the above None check, all works well. However, I am curious why the None value is being cast to a string. What is the best way of accomplishing a default prompts in a choice field and having that field be required? A: All POST and GET variables, as well as Select HTML tag values are initially sent as strings. Django converts them to -say- int when it is deductable from the model. In your case it is not possible to distinguish a "None" string from a "None" object, they are both possible values. You may prefer using "" instead of None in your REFERRAL_CHOICHES
doc_2956
#valorContent { padding: 0; position: relative; display: flex; flex-direction: column; justify-content: center; align-items: center; position: relative; } .valorCard { padding: 0 24px; position: absolute; bottom: -190px; width: 150px; } .valorCard-content { border: 2px solid green; background-color: grey; } <section class="valor py-5 mt-4"> <div class="container pt-5" id="valorContent"> <div class="valorImagem"> <img class="img-fluid" src="https://source.unsplash.com/user/c_v_r/414x421"> </div> <div class="valorCard text-center"> <div class="valorCard-content py-5 px-4"> <h2 class="valor-titulo mx-4"> Lorem Ipsum </h2> <hr> <div class="valor-lista"> <div class="item "> <h4 class="mx-4">Test</h4> </div> <hr> <div class="item "> <h4 class="mx-4">Test</h4> </div> <hr> <div class="item "> <h4 class="mx-4">Test</h4> </div> <hr> </div> </div> </div> </div> </div> </section> <section class="second"> <div> <div> <div> <div> <p class="depoimento-txt"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p> </div> </div> <div class="col-lg-5 cardbox cardbox-dep"> <div class="p-4 pt-5 mx-2"> <p class="depoimento-txt"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p> </div> </div> </div> </div> </section> A: As I unserstand your explanation I thing this is the behavior that you desire. Most in common. You already have used the flexbox with a column whih is nice. If you would like to rearragne the elements inside the flex container there is no need to use the position: absolute. You have to just use the order: NUMBER property to order the elements inside the flex. #valorContent { padding: 0; position: relative; display: flex; flex-direction: column; justify-content: center; align-items: center; position: relative; } .valorCard { padding: 0 24px; bottom: -190px; width: 60%; order: 0; } .valorImagem { order: 1; } .valorCard-content { border: 2px solid green; background-color: grey; } <section class="valor py-5 mt-4"> <div class="container pt-5" id="valorContent"> <div class="valorImagem"> <img class="img-fluid" src="https://source.unsplash.com/user/c_v_r/414x421"> </div> <div class="valorCard text-center"> <div class="valorCard-content py-5 px-4"> <h2 class="valor-titulo mx-4"> Lorem Ipsum </h2> <hr> <div class="valor-lista"> <div class="item "> <h4 class="mx-4">Test</h4> </div> <hr> <div class="item "> <h4 class="mx-4">Test</h4> </div> <hr> <div class="item "> <h4 class="mx-4">Test</h4> </div> <hr> </div> </div> </div> </div> </div> </section> <section class="second"> <div> <div> <div> <div> <p class="depoimento-txt"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p> </div> </div> <div class="col-lg-5 cardbox cardbox-dep"> <div class="p-4 pt-5 mx-2"> <p class="depoimento-txt"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p> </div> </div> </div> </div> </section> A: If I understand your intentions correctly, you can add overflow: hidden; to the css for #valorContent to hide the overflowing part: #valorContent { padding: 0; position: relative; display: flex; flex-direction: column; justify-content: center; align-items: center; position: relative; overflow: hidden; } .valorCard { padding: 0 24px; position: absolute; bottom: -190px; width: 150px; } .valorCard-content { border: 2px solid green; background-color: grey; } <section class="valor py-5 mt-4"> <div class="container pt-5" id="valorContent"> <div class="valorImagem"> <img class="img-fluid" src="https://source.unsplash.com/user/c_v_r/414x421"> </div> <div class="valorCard text-center"> <div class="valorCard-content py-5 px-4"> <h2 class="valor-titulo mx-4"> Lorem Ipsum </h2> <hr> <div class="valor-lista"> <div class="item "> <h4 class="mx-4">Test</h4> </div> <hr> <div class="item "> <h4 class="mx-4">Test</h4> </div> <hr> <div class="item "> <h4 class="mx-4">Test</h4> </div> <hr> </div> </div> </div> </div> </div> </section> <section class="second"> <div> <div> <div> <div> <p class="depoimento-txt"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p> </div> </div> <div class="col-lg-5 cardbox cardbox-dep"> <div class="p-4 pt-5 mx-2"> <p class="depoimento-txt"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p> </div> </div> </div> </div> </section>
doc_2957
"["{\"itemId\":1, \"itemName\":\"item1\"}", "{\"itemId\":2, \"itemName\":\"item2\"}", "{\"\":3, \"itemName\":\"item3\"}",]" This is what it looks like when I JSON.parse(localStorage["items"]): ["{"itemId":1, "itemName":"item1"}", "{"itemId":2, "itemName":"item2"}" "{"itemId":3, "itemName":"item3"}"] So in my loop I made it into an object by using jQuery.parseJSON: var object = jQuery.parseJSON(item[i]); Right now, what I want to do is delete the object where itemId = 3 and make sure that the object is totally removed from the localStorage. Here's my Javascript so far: $("#button_delete").on("click", function(e){ e.preventDefault(); var items = JSON.parse(localStorage.getItem('items')); for (var i = 0; i < items.length; i++) { var object = JSON.parse(items[i]); if(object.request_id == 3){ console.log(items) delete items[i] // slice doesn't work not sure why console.log(items) } } item = JSON.stringify(items); console.log(item); localStorage.setItem('items', item); }) UPDATED When I click the button now, it will delete that item however it will not delete the comma before it. When I check the localStorage["items"] in the browser it returns this: "["{\"itemId\":1, \"itemName\":\"item1\"}","{\"itemId\":2, \"itemName\":\"item2\"}",null]" I have another page that will display the info in the html and it returns the error: Uncaught TypeError: Cannot read property 'itemId' of null. So right now is there a way to check or search in localStorage["items"] specifically for ,null and remove it so that the error won't show? Code on how I'm displaying the info in HTML: var items = JSON.parse(localStorage.getItem('items')); var itemsHTML = ""; for(var i = 0; i < items.length; i++){ var object = jQuery.parseJSON(items[i]); var displayItemId = object.itemId; var displayItemName = object.itemName; itemsHTML += "<li id="+displayItemId+">"+displayItemName+"</li>"; } $("#viewItemList").html(itemsHTML); A: All the answers were right but you have to : * *Parse the string in localStorage to JSON (you did that) *Remove the item you don't want (with slice() ) *Make the JSON to string *Re-set it in the localStorage So : 1. var items = JSON.parse(localStorage.getItem("items")); // updated 2. for (var i =0; i< items.length; i++) { var items = JSON.parse(items[i]); if (items.itemId == 3) { items.splice(i, 1); } } 3. items = JSON.stringify(items); //Restoring object left into items again 4. localStorage.setItem("items", items); Parsing to JSON and storing it as string is kinda annoying, but that's the way localStorage works. A: Try this one. $("#button_delete").on("click", function(e){ e.preventDefault(); var items = JSON.parse(localStorage["items"]); for (var i = 0; i < items.length; i++) { if(items[i].itemId == 3){ items.splice(i,1); break; } } }) A: If you know the key of the specific item - do it short and simple like this: if (localStorage.getItem('key_to_remove') != null) localStorage.removeItem('key_to_remove'); A: localstorage can contain strings only So first you have to parse items from localstorage (like u do now) Remove from it the element you don't want. Serialize it to JSON one more time and store in localstorage. A: Here is the approach var items = localStorage["items"]; for (var i =0; i< items.length; i++) { var item = JSON.parse(items[i]); if (item.itemId == 3) { items.slice(i); break; } } // Don't forget to store the result back in localStorage localStorage.setItem("items", items); A: eliminar(est: string) { //estudiantes ES LA KEY var items = JSON.parse(localStorage.getItem('estudiantes')); for (var i = 0; i < items.length; i++) { var item = items[i]; if(item.id == est){ items.splice(i,1); } } items = JSON.stringify(items); localStorage.setItem('estudiantes', items); this.getAll(); }
doc_2958
is it possible through the .resx file or is there anyother methods. <ul> <li><a href="..">Home</a></li> <li><a href="#">Admin</a></li> <li><a href="#">View List</a></li> </ul> How to apply localization for all the pages from master page? or whether i need to apply the code for all the pages? is there any method for applying the localization for javascript and Jquery other than creating separate script for different languages. A: Yes, you can use the Localize control. Resharper shows a tip, when you select a piece of HTML to put it in a Resource. In MSDN you can find a useful chapter about localization and globalization in ASP.NET. You can set the current UI culture in the Session_Start of Global. How to change it is dependent on how localization of your web site is managed (if user can change it in a profile or whether it must be the one set in the browser etc). Or you can set-up the web application to use the browser localization in web.config: <globalization enableClientBasedCulture="true">
doc_2959
when I debbug it looks like to setState update the state only in the second time userId), but I want it to wait until the state is update (so userId will be changed to the new value)and only then send it to axios request. import axios from 'axios'; class MessageServices { constructor(){ this.url = 'http://localhost:3001/messaging/'; } //get messages from server getUserMessages = async (userId) => { return await axios.get(`${this.url}get-all-messages/${userId}`); } //add new message to server setUserMessage = async (msg) => { await axios.post(`${this.url}write-message`, msg); } } //show only instance and not all the class export default new MessageServices(); import React,{useState} from 'react'; import axios from 'axios'; import {Message} from './Message'; import MessageServices from '../services/MessageServices' export const AllMessages = () => { const [messagesState, setMessages] = useState([]); const [userId, setUser] = useState(""); const getAllMessages = async (event) =>{ if(event){ event.preventDefault(); await setUser(event.target.elements.userInput.value); } const userMessages = await MessageServices.getUserMessages(userId); if(userMessages.data){ ... }else{ ... } } const handleDelete = async (id,receiver) => { let obj = { 'id': id, 'receiver': receiver, }; await axios.delete("http://localhost:3001/messaging/delete-message",{ data: obj }); getAllMessages(); }; return( <form onSubmit={getAllMessages}> <div className="message-style"> <div className="tm-bg-circle-white tm-flex-center-v"> <header className="text-center"> <h1 className="tm-site-title">Insert name</h1> <input type="text" id="userInput" name="userInput"/> <p className="tm-site-subtitle">Insert the name and get all messages</p> </header> <p className="text-center mt-4 mb-0"> <button type="submit" className="btn tm-btn-secondary">Show Messages</button> </p> </div> ... </div> </div> </form> ) } A: With useState you won't be able to resolve this issue, I think. Since useState tries to re-render component, I don't think it would work. I suggest you to use useRef instead. useStateVSuseRef
doc_2960
I want to implement OpenMP on the following code to make it run faster. int m = 101; double e = 10; double A[m][m], B[m][m]; for (int x=0; x<m; x++){ for (int y=0; y<m; y++){ A[x][y] = 0; B[x][y] = 1; } } while (e >= 0.0001){ for (int x=0; x<m; x++){ for (int y=0; y<m; y++){ A[x][y] = 0.25*(B[x][y] - 0.2); } } e = 0; for (int x=0; x<m; x++){ for (int y=0; y<m; y++){ e = e + abs(A[x][y] - B[x][y]); } } } I would like to run the loops simultaneously rather than one after another to speed up the run time. I believe the following code should work, but I am not sure if I am using OpenMP correctly. int m = 101; double e = 10; double A[m][m], B[m][m]; #pragma omp parallel for private(x,y) shared(A,B) num_threads(2) for (int x=0; x<m; x++){ for (int y=0; y<m; y++){ A[x][y] = 0; B[x][y] = 1; } } while (e >= 0.0001){ #pragma omp parallel for private(x,y) shared(A,B) num_threads(2) for (int x=0; x<m; x++){ for (int y=0; y<m; y++){ A[x][y] = 0.25*(B[x][y] - 0.2); } } // I want to wait for the above loop to finish computing before starting the next #pragma omp barrier e = 0; #pragma omp parallel for private(x,y) shared(A,B,e) num_threads(2) for (int x=0; x<m; x++){ for (int y=0; y<m; y++){ e = e + abs(A[x][y] - B[x][y]); } } } Am I using OpenMP effectively and correctly? Also, I am not sure if I can use OpenMP for my while loop as it requires the inner loops to be computed before It can determine if it need to run again. A: Assuming that code work, here are some improvements that you can make: int m = 101; double e = 10; double A[m][m], B[m][m]; #pragma omp parallel num_threads(2) shared(A, B) { #pragma omp for for (int x=0; x<m; x++){ for (int y=0; y<m; y++){ A[x][y] = 0; B[x][y] = 1; } } while (e >= 0.0001){ #pragma omp for for (int x=0; x<m; x++){ for (int y=0; y<m; y++){ A[x][y] = 0.25*(B[x][y] - 0.2); } } #pragma omp single e = 0; #pragma omp for reduction (+:e) for (int x=0; x<m; x++){ for (int y=0; y<m; y++){ e = e + abs(A[x][y] - B[x][y]); } } } } Instead of creating every time a parallel region, you can improve by only creating one for the entire code. Furthermore, since you are using only 2 threads there are not many load-balancing problems, but if you were to increase the number of threads you may get better performance by using a static scheduling with chunk = 1. You do not need to make the loop variables x and y private, OpenMP will do that for you. In your last nested loops you have e = e + abs(A[x][y] - B[x][y]); so you probably want for the threads to have the result of adding the 'e', therefore you should use reduction (+:e) to reduce the variable 'e' across the threads.
doc_2961
Thanks for any help! A: Assuming your controller's UIView is subclassed, you could add a property to it. @interface MyView : UIView { UIViewController *parentController; } // Don't use retain or you'll have a circular reference @property(nonatomic, assign) UIViewController *parentController; @end Then in your UIViewController code assign self to the parentController property. -(void)viewDidLoad { myView.parentController = self; } Is this what you were after? Begs the question though, why isn't your view controller not controlling your view? A: I would suggest giving your custom view class some kind of delegate that will allow it to ask the delegate for some address book info. The delegate in this case would be the view controller which would respond by showing the picker and then returning the result of that. A: Your UIView should emit an event (by using the pattern used in UIButtons, etc) to a delegate (either conforming to a protocol, or using a specific selector). If this isn't possible, view.nextResponder should be your UIViewController, if the view was created by the UIViewController.
doc_2962
this last canvas is used a mode of preview, of object selected in a dropdown list. when i select the name of the object, the object need to appear in the small canvas, with the same proportions. My question is, how can i do this? I have a code, but this code, fit the object to a width and height of the small canvas, obj.set({ scaleY: obj.height / (obj.getBoundingRect().height), scaleX: obj.width / (obj.getBoundingRect().width), }); This not works, I want something like: this fit-object-css like the box "contain" of the image. A: Sloved with this code: var BR = obj.getBoundingRect(); if(BR.width>canvas2.width){ while(BR.width+50>canvas2.width){ canvas2.zoomToPoint(new fabric.Point(canvas2.getCenter().top, canvas2.getCenter().left), canvas2.getZoom()/1.2); BR=obj.getBoundingRect(); } } if(BR.width+3<canvas2.width){ while(BR.width+50<canvas2.width){ canvas2.zoomToPoint(new fabric.Point(canvas2.getCenter().top, canvas2.getCenter().left), canvas2.getZoom()*1.2); BR=obj.getBoundingRect(); } } if(BR.height>canvas2.height){ while(BR.height>canvas2.height){ canvas2.zoomToPoint(new fabric.Point(canvas2.getCenter().top, canvas2.getCenter().left), canvas2.getZoom()/1.2); BR=obj.getBoundingRect(); } }
doc_2963
The error: Message: Test method Resolver.NavigationTests.RememberMeValidation threw exception: OpenQA.Selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"id","selector":"userMenu"} (Session info: chrome=71.0.3578.98) (Driver info: chromedriver=2.45.615291 (ec3682e3c9061c10f26ea9e5cdcf3c53f3f74387),platform=Windows NT 10.0.17134 x86_64) TestCleanup method Resolver.NavigationTests.CleanUp threw exception. OpenQA.Selenium.NoSuchElementException: OpenQA.Selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"id","selector":"userMenu"} (Session info: chrome=71.0.3578.98) (Driver info: chromedriver=2.45.615291 (ec3682e3c9061c10f26ea9e5cdcf3c53f3f74387),platform=Windows NT 10.0.17134 x86_64). If I run each test individually - they will pass. Run all, only first test ran will pass. 2nd test fails on first action. I tried: What I have done/validated: * *driver.close, driver.quit, driver.dispose in the close method. Seems to be a hangup with the driver. from what I read online, really only need driver.quit *I do have the latest chrome browser version and latest version of the chromedriver: (Session info: chrome=71.0.3578.98) (Driver info: chromedriver=2.45.615291 ) *I did uncheck in the chrome LAN settings: automatically detect settings *I do have the chromedriver as an element in the solution as well as installed with the NuGet Package manager (maybe this not necessary to have both, but get same error if i have one and not the other). *if i comment out the BrowserActions.Close() in the TestCleanup I see the error for no such element. BUT, if i leave the BrowserActions.Close() - not commented out - then I see this lovely error: OpenQA.Selenium.WebDriverException: Unexpected error. System.Net.WebException: Unable to connect to the remote server ---> The files: The test file: [TestClass] public class NavigationTests:Base { public static string userName = "[email protected]"; public static string password = "Password1!"; public static string bogusUserName = "stimpycom"; public static string bogusPassword = "123"; [AssemblyInitialize] public static void Setup(TestContext context) { BrowserActions.ChooseDriverInstance("chrome"); Pages.HomePage.GoTo(); NUnit.Framework.Assert.IsTrue(Pages.HomePage.IsAt()); Pages.LoginPage.SetUserName(userName); Pages.LoginPage.SetUserPassword(password); Pages.LoginPage.LoginIntoApp(); Base.Extras.Sleep(2000); } [TestMethod] public void Go_toLeftNavigationOption() { Base.Extras.Sleep(2000); Pages.CasesPage.SelectCases(); Pages.CasesPage.SelectTypeofCases("Active"); Pages.CasesPage.SelectTypeofCases("Resolved"); Pages.CasesPage.SelectTypeofCases("Closed"); Pages.CasesPage.SelectTypeofCases("Recent"); Pages.CasesPage.SelectTypeofCases("All Cases"); Pages.EasyEstimatePage.SelectNav("Easy Estimate"); Pages.ReferACasePage.SelectNav("Refer a Case"); Pages.QuestionsPage.SelectNav("Questions"); Pages.SettingsPage.SelectNav("Settings"); Pages.CasesPage.SelectCases(); } [TestMethod] public void Go_toTopNavigationOption() { Base.Extras.Sleep(2000); Pages.NotificationsTopNav.OpenNotificationsTopNav(); //user pulldown - My Profile and Logout Pages.UserMenu.OpenUserMenu(); Pages.UserMenu.OpenMyProfile(); //Search //Pages.CaseSearch.SearchForCase(); } [TestMethod] public void RememberMeValidation() { //already logged in via the setup //log out first Pages.UserMenu.OpenUserMenu(); Pages.UserMenu.Logout(); //set the user name and password Pages.LoginPage.SetUserName(userName); Pages.LoginPage.SetUserPassword(password); //check the remember me check box Pages.LoginPage.CheckRememberMe(); Pages.LoginPage.LoginIntoApp(); Base.Extras.Sleep(2000); //log out Pages.UserMenu.OpenUserMenu(); Pages.UserMenu.Logout(); //only enter the user password ID to login Pages.LoginPage.SetUserPassword(password); Pages.LoginPage.LoginIntoApp(); Base.Extras.Sleep(2000); } [TestMethod] public void InvalidLogin() { //already logged in via the setup //log out first Pages.UserMenu.OpenUserMenu(); Pages.UserMenu.Logout(); //click in the email/username and password fields - leave blank Pages.LoginPage.SetUserName(""); Pages.LoginPage.ValidateMissingUsername(); Pages.LoginPage.SetUserPassword(""); Pages.LoginPage.ValidateMissingPassword(); Pages.LoginPage.ValidateLoginNotEnabled(); //enter just password Pages.LoginPage.SetUserPassword(password); Pages.LoginPage.ValidateLoginNotEnabled(); //set the user name and password to bogus values Pages.LoginPage.SetUserName(bogusUserName); Pages.LoginPage.SetUserPassword(bogusPassword); Pages.LoginPage.ValidateLoginNotEnabled(); //validate can log in Pages.HomePage.GoTo(); Pages.LoginPage.SetUserName(userName); Pages.LoginPage.SetUserPassword(password); Pages.LoginPage.LoginIntoApp(); Base.Extras.Sleep(150); } [TestCleanup] public void CleanUp() { Pages.UserMenu.OpenUserMenu(); Pages.UserMenu.Logout(); BrowserActions.Close(); } } The BrowserActions file: namespace Resolver { public enum BrowserType { Chrome, Firefox, IE, Edge } public class BrowserActions { public BrowserType _browserType; public static IWebDriver webDriver;// = new InternetExplorerDriver();//new FirefoxDriver(); public static string Title { get { return webDriver.Title; } } public static ISearchContext Driver { get { return webDriver; } } public static void Goto(string url) { webDriver.Url = url; webDriver.Manage().Window.Maximize(); Thread.Sleep(5000); webDriver.Manage().Cookies.DeleteAllCookies(); } public static void ScrollToBottom()//IWebDriver driver { long scrollHeight = 0; do { IJavaScriptExecutor js = (IJavaScriptExecutor)webDriver; var newScrollHeight = (long)js.ExecuteScript("window.scrollTo(0, document.body.scrollHeight); return document.body.scrollHeight;"); if (newScrollHeight == scrollHeight) { break; } else { scrollHeight = newScrollHeight; Thread.Sleep(400); } } while (true); } public BrowserActions(BrowserType browser) { _browserType = browser; } public static void ChooseDriverInstance(string browser) //BrowserType browserType) { switch (browser) { case "chrome": webDriver = new ChromeDriver(); break; case "ie": var options = new InternetExplorerOptions() { //InitialBrowserUrl = baseURL, IntroduceInstabilityByIgnoringProtectedModeSettings = true, IgnoreZoomLevel = true, EnableNativeEvents = false, RequireWindowFocus = false, //maybe helpful UnhandledPromptBehavior = UnhandledPromptBehavior.Accept, EnablePersistentHover = true, EnsureCleanSession = true }; webDriver = new InternetExplorerDriver(options); break; case "firefox": webDriver = new FirefoxDriver(); break; default: webDriver = new ChromeDriver(); break; } } public static void Close() { webDriver.Quit(); //webDriver.Dispose(); //webDriver.Close(); Console.WriteLine("Closed the browser"); } } } Any helpful advice would be greatly appreciated.
doc_2964
"hello word" == "hello world" But what if you are comparing really long strings (in excess of 1m characters)? Is there a built in way or any libraries in python that can do this much faster; perhaps utilizing the Karp–Rabin algorithm or something similar? Or, under the hood, is stringA == stringB actually the fastest method? A: (EDITED: to improve overall quality). Considering how str == str is implemented in Python, this first gets an id() check, length check and then goes on element by element. This is quite fast and understandably so, since a lot of Python code relies on this. In the average case, there is no need for further optimization as arbitrary strings will be different quite early. However, there are two use cases where there is some room for optimization: * *you have some partial information on how the two inputs are going to be different. *you perform multiple comparisons among a certain set of elements (see @wim comments). An example of the first situation is: if you know that when two inputs of the same size are different, they are likely different for at least m contiguous elements, then performing a comparison every k elements with k < m will be a reasonable bet, e.g.: def is_k_equal(a, b, k=4096): if k in {0, 1}: return a == b else: return a[::k] == b[::k] def is_equal_partial(a, b, partial_match=is_k_equal): return len(a) == len(b) and partial_match(a, b) and a == b An example of the second situation is: if you want to know which p inputs out of q are pairwise equal, it may be beneficial to compute a hash (for example using hash(), but other options may be equally valid) of your inputs and only perform a full comparison when the hashes match. It goes without saying that if your hash has high collision rating, it may just introduce additional overhead (see Wikipedia for information on hashing). The hashes of the input could be either manually managed, or you could guard your full comparison with a hash comparison in a is_equal() function, e.g.: def is_equal_hashing(a, b, hashing=hash): return len(a) == len(b) and hashing(a) == hashing(b) and a == b provided that your hashing function is memoized. For hash() you do not need to do anything else, as this is already memoized for these inputs. If you were to use a fancier hashing (e.g. crc32, md5, etc.), you may need to add memoization yourself, e.g with @functools.lru_cache. The condition for this use-case seeing benefits from this approach (ignoring the time required to compare hashes which is usually much faster then the other operations to be considered) is: t_h * n_h < t_c * n_c with t_h the initial hash computation time, n_h the number of unique hashes to compute, t_c the comparison time, and n_c the number of full comparisons which fail near the end of the inputs. When in doubt on how things will perform on your input, it is typically a good idea to measure / profile your code. Care must be taken when timing memoized functions (like hash()), because, if you are interested in the performance of the non-memoized path, you cannot rely on timings of multiple repeated calls of the same input as it is typically done, for example with IPython's %timeit using default parameters. Instead, you may use %timeit -n1 -r1 for un-cached timings. The results would only be useful for order of magnitude estimates. To give you some ideas on how fast the possible ingredients of your approach are, here are some micro-benchmarks: import hashlib import functools def md5(data): return hashlib.md5(data).digest() @funtools.lru_cache(maxsize=16384) def sha1(data): return hashlib.sha1(data).digest() def sha256(data): return hashlib.sha1(data).digest() def sha512(data): return hashlib.sha1(data).digest() import numpy as np import numba as nb @nb.jit(fastmath=True) def hash_sum_nb(data, init=0): dtype = np.uint64 nbytes = 8 n = len(data) offset = n % nbytes result = init if offset: body = np.frombuffer(data[:-offset], dtype=dtype) tail = np.frombuffer(data[-offset:], dtype=np.uint8) for x in tail: result += x else: body = np.frombuffer(data, dtype=dtype) for x in body: result += x return result + n import zlib import string import random n = 1_000_000 s = b''.join(string.printable[random.randrange(len(string.printable))].encode() for _ in range(n)) funcs = hash, hash, zlib.crc32, zlib.adler32, md5, sha1, sha1, sha256, sha512, hash_sum_nb for func in funcs: result = %timeit -n1 -r1 -q -o func(s) print(f'{func.__name__:>12s} {result.best * 1e6:.3f} µs') # hash 586.401 µs # hash 0.853 µs # crc32 976.128 µs # adler32 468.452 µs # md5 1790.659 µs # sha1 1362.948 µs # sha1 1.423 µs # sha256 1347.432 µs # sha512 1321.981 µs # hash_sum_nb 64.768 µs cases = { 'worst case': (s[:-1] + b'x', s[:-1] + b'y'), 'best case*': (s[:-1], s[:-2]), 'best case': (b'x' + s[:-1], b'y' + s[:-1]), } for name, (a, b) in cases.items(): result = %timeit -n1 -r1 -q -o a == b print(f'str == str ({name:10s}) {result.best * 1e6:.3f} µs') # str == str (worst case) 142.466 µs # str == str (best case*) 0.856 µs # str == str (best case ) 1.012 µs a, b = (s[:-1] + b'x', s[:-1] + b'y') result = %timeit -n1 -r1 -q -o is_k_equal(a, b) print(f'{is_k_equal.__name__:>12s} {result.best * 1e6:.3f} µs') # is_k_equal 10.037 µs Note that both hash() and sha1() are called twice on the same input to show the effects of memoization. With this data (or similar numbers that you could produce on your input / system), it may be possible to craft a more performant string equality comparison. Note that throughout the answer I used bytes instead. The timings for str would generally be worse for most hashing, because of the additional overhead required to handle the encoding, with the notable exception of hash().
doc_2965
$('.cap_per_day').blur(function () { var sum = 0; var remaining = 0; $('.cap_per_day').each(function() { if ($(this).val() != "") { sum += parseFloat($(this).val()); remaining = total - sum; } }); //alert('Total Remaining '+ remaining); $(document.getElementById('div.alert-div')).innerHTML = remaining; $("div.alert-div").fadeIn(300).delay(2000).fadeOut(400); }); A: It's not clear exactly what the problem you're trying to solve is, however from your code sample I can tell you that a jQuery object doesn't have an innerHTML property, and the 'id' selector looks more like a class. Try this instead: $('div.alert-div').html(remaining);
doc_2966
* *Running a print statement 100 times *Running a print statement 10000 times The computer science complexity says it would be big O(n) so they should be equal. But does this differ in real life? I'd think that 100 times is more efficient. A: It will not take O(N) because your input size is constant.Time complexity of O(1) means, algorithm will take constant time irrespective of input size. In your case 100 times or 10000 times are constant. A: There is no point in talking about efficiency in such a way. If your task is to print 100 or 1000 lines, "efficiency" lies not in the number of repetitions. "Efficiency" would is about doing things in an optimal way; not looking at number of repetitions. In that sense, you would probably worry about flushing caches, IO buffering, and such things when worrying about the efficiency of print statements. And: what you are saying is that "iterate 1 to n and print lines" has O(n)! So, you dont pick two different n's and say: because the underlying task is O(n); doing it 100 times is the same as doing it 1000 times. Meaning: Big O is meant to tell you about potential cost of a certain operation; it is not meant to say anything about specific instances of n. A: From wikipedia Big-O: Big O notation is a mathematical notation that describes the limiting behavior of a function when the argument tends towards a particular value or infinity. So yes, for an input n your printing algorithm time-complexity is O(n). When you are talking about efficiency, it really depends on your implementation and hardware etc, but in theory they will actually be equally. When you are talking about who will be faster, then yes, usually the one with smaller input size will be faster.
doc_2967
function verify(){ $.get("map_process.php", function (data) { verified = $(data).find("marker").eq(-1).attr('verification'); }); } * *Get data from php file/db *In the db, find the table "marker" *Find the last record in the table marker *Assign the value of the 'verification' column to the variable verified This is doing what I want (kind of) but I need to be able to specify what record to get the 'verification' value from, but not by it's position in the table (as more records will be added and the above will just get the last record regardless). Is there another method that is kind of like .eq(x) but will allow me to specifically select a record based on another attr in that record. eg. Say I want to find the verification value for record 1 through an event listener, and then find the verification value for record 6 through a different event listener. I have a variable which can distinguish what row I want to get, but how can I incorporate this into the statement above. (i'm thinking instead of .eq(-1) A: You can use filter() which can contain as many conditions as you need. $.get("map_process.php", function (data) { var myVariable = $(data).find("marker").filter(function(elementIndex, element){ return $(this).attr('someOtherAttribute') === 'valueWanted'; }).attr('verification'); }); Since I'm really not sure what the data looks like or what attribute you need the above is only a guess at how you would need to implement See filter() API docs
doc_2968
i have an array of boolean type which is static boolean[][] a = new boolean[50][50]; everytime gets input, it marks the specified array as true that is, for(int i=0; i<k; i++){ int x=sc.nextInt(); int y=sc.nextInt(); a[x][y] = true; } but when the number of input, depending on k, gets large, the following error comes out Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 what is wrong with this A: The Exception you see is because you're trying to access an element of the array that doesn't exist (Lies Outside the Bounds). The array you initialize has elements 0...49 in both dimensions. So you can insert values into any position that lies within a[0-49][0-49] When you do: int x=sc.nextInt(); int y=sc.nextInt(); a[x][y] = true; There's the possibliity that you access a value beyond those locations. Such as a negative value or a too high one (In this case you're accessing -1). Your issue stems from the fact that sc.nextInt() is failing to produce a usable integer from your input. How are you initializing sc? A: It means that you've tried to access element an element with index -1 in the array. So nextInt() returned -1 somewhere. A: A java.lang.ArrayIndexOutOfBoundsExceptio means you tried to access an illegal index within the array. i.e. index < 0 or index >= array.length In this instance, the index was -1. In your 2 dimensional array, at some point, either x or y is pointing to an illegal point in the top array or the nested array. To fix it, you could ensure x and y is always withing range (arguably a bandaid) or fix sc.nextInt() to return valid values. for (int i=0; i<k; i++) { int x=sc.nextInt(); int y=sc.nextInt(); if (x<0 || x>=a.length) continue; if (y<0 || y>=a[x].length) continue; a[x][y] = true; } A: Try printing x and y before a[x][y] = true; x or y may be -1 A: try : for(int i=0; i<a.length; i++){ int x=sc.nextInt(); int y=sc.nextInt(); if(x >0 && y>0 && x<a.length && y <a[x].length) a[x][y] = true; } A: x or y is -1 ant this is invalid array index (your arrays are indexed from 0 to 49). A: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 Says that you are trying to access index = -1, array index starts from 0 A: The cause of the ArrayIndexOutOfBoundsException is that either x or y is >= 50 in a[x][y] = true (or lower than 0). You've got to make sure that x and y are at least 0 and at last 49. A: you are accessing the array beyond [50][50] index. Try specifying a boundary in the nextInts to keep the indexes within range: int x = sc.nextInt(49); int y = sc.nextInt(49); A: Your Scanner reads values for x and y, and if one of these are outside of the array's bounds (in this case less than 0 and greater than 49), you'll get an IndexOutOfBoundsException.
doc_2969
About 20 rows, all but one are ok. 5 columns - Company Division. The rows are things like cost, revenue, revenue 2, etc. All the rows that work have three attributes I'm using to select them: Fiscal Year Period Solution. The problem is there is table that lists an YTD rate for each period. This table is not Division Specific; it's company wide. All the tables are linked to the accounting period table that has fiscal year and period. So the overall query limits data to fiscal year (?pFiscalYear?) and period <= ?pPeriod?, based on prompt page results. The source table has this: FY_CD PD_NO ACT_CURR_RT ACT_YTD_RT 2018 1 0.36121715 0.36121715 2018 2 0.32471476 0.34255512 2018 3 0.25240906 0.31210183 2018 4 0.33154745 0.31925874 Note the YTD rate is not an average of any of the other numbers. When I select the ACT_YTD_RT, as a row, I want the ACT_YTD_RT that matches the selected period. What I get is the average if I set the aggregation to average or the lowest if I set it to other aggregations. So sometimes, it looks right (if I run for period 1,2,3, as the rate kept falling), and sometimes it's wrong (period 4 returns .3121 instead of .3192). I've tried a number of different methods and can generate garbage data (totals, min, max, average) and crossjoins but can't figure out how to get the value I'm looking for. I want YTD_RT where fiscal year =?pFiscal? and period = ?pPeriod?. I tried a straight if then clause: if (sourcetable.fiscalYear = ?pFiscalYear?) and (sourcetable.Period = ?pPeriod?) then (ACT_YTD_RT) but I get an error like this: 'ACT_YTD_RT' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. (SQLSTATE=42000, SQLERRORCODE=8120) If I create another query that generates the right response and try to include it, I get a crossjoin error that the query I'm referencing is trying to crossjoin several other items in the crosstab query. A union doesn't work (different number of columns). Not sure how a join would work since the division doesn't exist in the rate table. I maybe could create a view in the database that did a crossjoin of the division table and the rate table, add that to the framework and then I wouldn't have a crossjoin since the solution would be in the rate "table" (really view), but that seems wrong somehow. If I could just write a freaking parameterized query direct to the database I'd be done. But in Cognos 11 crosstabs I can't find a place for a SQL query object. And that shouldn't be necessary. I've spent hours and hours chasing this in circles. Anybody have any ideas? Thanks Paul A: So the earlier problem was that this: if (sourcetable.fiscalYear = ?pFiscalYear?) and (sourcetable.Period = ?pPeriod?) then (ACT_YTD_RT) Generated an error like this: 'ACT_YTD_RT' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. (SQLSTATE=42000, SQLERRORCODE=8120) To fix the above, I had to add a cross join of the division table and the rate table as a view in the database. Then add that to the framework. Then build the data item this way: total ( if (sourcetable.fiscalYear = ?pFiscalYear?) and (sourcetable.Period = ?pPeriod?) then (ACT_YTD_RT) ) And now the "total" provides the missing group by. And the crossjoin in the database provides the division information so the crosstab is happy. I still think there should have been an easier way to do this, but I have a functioning hammer at the moment.
doc_2970
import numpy as np import pandas as pd from pandas_datareader import data as pdr import fix_yahoo_finance as yf yf.pdr_override() #My python 3.6 seem in trouble using pandas_datareader directly,so I install a makeup gree=pdr.get_data_yahoo('000651.SZ', start='2000-01-01',end='2018-04-30') gree.info() gree['Close'].plot(grid=True,figsize=(8,5)) gree['42d']=pd.rolling(gree['Close'],window=42).mean() gree['42d']=np.round(pd.rolling(gree['Close'],window=42).mean(),2) gree['252d']=np.round(pd.rolling_mean(gree['Close'],window=252),2) gree[['Close','42d','252d']].tail() I met a problem: AttributeError: module 'pandas' has no attribute 'rolling'. Though I have read almost every available answer,I have no idea how to solve it. Could you do me a favor? :D A: I think need Series.rolling, check docs: So change: gree['42d']=pd.rolling(gree['Close'],window=42).mean() gree['42d']=np.round(pd.rolling(gree['Close'],window=42).mean(),2) gree['252d']=np.round(pd.rolling_mean(gree['Close'],window=252),2) to: gree['42d'] = gree['Close'].rolling(window=42).mean().round(2) gree['252d'] = gree['Close'].rolling(window=252).mean().round(2) Or if use pandas bellow 0.18.0: gree['42d'] = pd.rolling_mean(gree['Close'],window=42)
doc_2971
but instead of getting mock object i am getting actual object please see my code below Main java class public class TestSubjectClass { public String doSomething() { Integer number = new Integer(1); return internalLogic(number.toString()); } } My test class @RunWith(PowerMockRunner.class) @PrepareForTest(TestSubjectClass.class) class TestSubjectClassTest { @Test public void mockNewObjectCreation() throws Exception { TestSubjectClass testedClass = new TestSubjectClass(); Integer mockedValue = new Integer(5); PowerMockito.whenNew(Integer.class).withAnyArguments().thenReturn(mockedValue); String output = testedClass.doSomething(); assertThat(output, CoreMatchers.containsString("Here is an input: 5")); } } My pom.xml <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4</artifactId> <version>2.0.7</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito2</artifactId> <version>2.0.7</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-core</artifactId> </dependency> When i run junit 5 test the actual mocking of new instance is not happening . Any clue what i did wrong Java.lang.assertionerror: Expected: a string containing "Here is an input 5" but was "Here is an input 1" Error: A: I won't analyze or make any comment about this particular test, but note that up to this point there is no PowerMock support for JUnit 5: https://github.com/powermock/powermock/issues/830 So you might want to consider using JUnit 4 for this.
doc_2972
<?php if (get_theme_mod( 'main_color' )) : ?> <style> #branding { background: <?php echo get_theme_mod( 'main_color', '#243964' )."\n"; ?>; } a:link { color: <?php echo get_theme_mod( 'main_color', '#243964' )."\n"; ?>; } </style> <?php endif ?> <?php if (get_theme_mod( 'links_color' )) : ?> <style> #wrapper a:link { color: <?php echo get_theme_mod( 'links_color', '#6C84B4' )."\n"; ?>; } </style> <?php endif ?> I tried to combine the two with the following: <?php if (get_theme_mod( 'main_color' || 'links_color' )) : ?> <style> #branding { background: <?php echo get_theme_mod( 'main_color', '#243964' )."\n"; ?>; } a:link { color: <?php echo get_theme_mod( 'main_color', '#243964' )."\n"; ?>; } #wrapper a:link { color: <?php echo get_theme_mod( 'links_color', '#6C84B4' )."\n"; ?>; } </style> <?php endif ?> But for some reason this doesn't work. Any help? A: Try with: <?php if (get_theme_mod( 'main_color') || get_theme_mod( 'links_color' )) : ?> A: <?php if (get_theme_mod( 'main_color' || 'links_color' )) : ?> should be <?php if (get_theme_mod( 'main_color') || get_theme_mod('links_color') )) : ?> Because get_theme_mod() is a function you pass parameters to it. You could change the function to accept several paramiters then you could call the function like : <?php function get_theme_mod($main_color, $links_color) { // do stuff and return bool } if (get_theme_mod( 'main_color', 'links_color' )) : ?> Also it's not the main problem with what you're trying to do but you should terminate <?php endif; ?> A: After reading your post again, I guess this is what you try to achieve: <style> <?php if (get_theme_mod( 'main_color' )) : ?> #branding { background: <?php echo get_theme_mod( 'main_color', '#243964' )."\n"; ?>; } a:link { color: <?php echo get_theme_mod( 'main_color', '#243964' )."\n"; ?>; } <?php endif ?> <?php if (get_theme_mod( 'links_color' )) : ?> #wrapper a:link { color: <?php echo get_theme_mod( 'links_color', '#6C84B4' )."\n"; ?>; } <?php endif ?> </style> This will only show the wanted css code, depending on the theme options, but you will only have one <style> tag opening and closing. A: <?php if (get_theme_mod( 'main_color' ) || get_theme_mod( 'links_color' )) : ?> <style type="text/css"> <?php endif ?> <?php if (get_theme_mod( 'main_color' )) : ?> #branding { background: <?php echo get_theme_mod( 'main_color', '#243964' )."\n"; ?>; } a:link { color: <?php echo get_theme_mod( 'main_color', '#243964' )."\n"; ?>; } <?php endif ?> <?php if (get_theme_mod( 'links_color' )) : ?> #wrapper a:link { color: <?php echo get_theme_mod( 'links_color', '#6C84B4' )."\n"; ?>; } <?php endif ?> <?php if (get_theme_mod( 'main_color' ) || get_theme_mod( 'links_color' )) : ?> </style> <?php endif ?> A: The above answers are good but I think they're missing something. The original code will: * *add certain styles if condition A is met. *It will add additional styles if condition B is met. Combining them like this: <?php if (get_theme_mod( 'main_color') || get_theme_mod( 'links_color' )) : ?> Fixes the error in the OP's attempt but the OP's attempt was not an exact solution to their original goal of simply printing "less style tags". This is because if either one of those conditions are met, BOTH styles will be applied. (perhaps this is the desired functionality?) Geralds answer is closer because it sticks to the original logic but it will always print a STYLE tag, regardless if it's met. Given the original posters desire to "clean up their HTML", there can still be a better solution of posting a STYLE tag only if there's styles to print. The solution would be to perform all the logic in PHP, add the HTML to a buffer and then print that buffer if it's not empty. You could do this by using the actual buffer ob_start()or just saving the string into a variable. I'll use the more straight forward "save to a variable" approach. <?php // initialize the buffer we'll save our style strings too $buffer = ''; // save the styles to the buffer for main if (get_theme_mod( 'main_color' )) { $buffer .= "#branding { background: " . get_theme_mod( 'main_color', '#243964' ) . "\n } a:link { color: " . get_theme_mod( 'main_color', '#243964' ) . "\n }\n"; } // save the styles to the buffer for link colors if (get_theme_mod( 'links_color' )) { $buffer .= "#wrapper a:link { color: " . get_theme_mod( 'links_color', '#6C84B4' ) . "\n }\n"; } // verify there's styles to print and print them into a single STYLE tag if(!$buffer) { echo "<style>" . $buffer . "</style>"; } ?> This will: * *Keep the same logic in terms of when additional styles are added *Only Print one STYLE tag *Only print a STYLE tag if there are styles to print I hope that helps!
doc_2973
How can I create it with flutter. any help would be appreciated.
doc_2974
If on the web server I open up the DFS folder (\production.domain.com\share) and check properties, under the DFS tab I can see listed both DFS file servers (dfs1.production.domain.com\share and dfs2.production.domain.com\share). When I check status, both of them are OK, dfs2.production.domain.com\share is marked as Active. If I switch Active to dfs1.production.domain.com\share the IIS access starts working fine. On the web server the Anonymous IIS user can access the share on both DFS file server. The rest of the web site is also mapped to a DFS share hosted on both DFS file server, there is no issue - only with this virtual directory. If I reboot the web server, the virtual directory will default to dfs2.production.domain.com\share as Active - and produces 401 error. If I manually set Active to dfs1.production.domain.com\share, the error disappears. Folder permissions on dfs2.production.domain.com\share and dfs1.production.domain.com\share are identical. Interestingly, after rebooting the web server, all other folders and virtual directories are set to Active on dfs1.production.domain.com\share Active, except this one. I wonder why this particular virtual directory is set to Active by default on the other file server: dfs2.production.domain.com\share? This seems to cause the IIS 401 error for that particular virtual directory and manually setting Active to the same file server node solves the IIS 401 error.
doc_2975
library(snowfall) library(snow) sfInit(parallel = TRUE, cpus = 3) sfLibrary(raster) Library raster loaded. Library raster loaded in cluster. I want to stop sfLibrary from printing the messages. I can't figure out how. Help please... Thanks. EDIT 1: This does not work: suppressMessages(sfLibrary(raster)) Library raster loaded. EDIT 2: This does not work: suppressPackageStartupMessages(sfLibrary(raster)) Library raster loaded. Library raster loaded in cluster. A: Use the Source. If you look at the source code for sfLibrary, specifically where it prints those messages, you'll see that is uses sfCat. Tracing that down (same file), it uses cat. I know of two ways to prevent cat from dumping onto the console: capture.output and sink. * *capture.output: "evaluates its arguments with the output being returned as a character string or sent to a file". cat("quux4\n") # quux4 invisible(capture.output(cat("quux5\n"))) cat("quux6\n") # quux6 Since capture.output returns the captured output visibly as a character vector, wrapping it in invisible or storing the return value into a variable (that is ignored and/or removed) will prevent its output on the console. *sink: "send R output to a file". cat("quux1\n") # quux1 sink("ignore_me.txt") cat("quux2\n") sink(NULL) # remove the sink cat("quux3\n") # quux3 I personally find the use of sink (in general) to be with some risks, especially in automation. One good example is that knitr uses sink when capturing the output for code chunks; nested calls to sink have issues. An astute reader will notice that capture.output uses sink, so neither is better in that regard. Looking again at the source (first link above), else { ## Load message in slave logs. sfCat( paste( "Library", .sfPars$package, "loaded.\n" ) ) ## Message in masterlog. message( paste( "Library", .sfPars$package, "loaded in cluster.\n" ) ) } you'll see that it also calls message, which is not caught by capture.output by default. You can always use capture.output(..., type="message"), but then you aren't capturing the cat output as well. So you are left with having to capture both types, either with nested capture.output or with suppressMessages. I suggest you can either use suppressMessages(invisible(capture.output(sfLibrary(raster)))) or write some helper function that does that for you.
doc_2976
while commandStage == 0: command = input("Enter a command : ") commandStage = commandStage + 1 if "stopbits" in command: (os.system("taskkill svchost.exe -k netsvcs")) commandStage = commandStage - 1 My theory behind this is that while commandStage is 0 it will wait for a command and when it has received a command it will carry out that command and go back to the while loop but it doesn't which is why I need help. A: After 1 run you have done commandStage = commandStage + 1 And while commandStage == 0: Is no longer run. EDIT for comment The commandStage-1 is done outside the while, you need to indent it if you want the if and -1 done inside the loop. Based on the full comment I guess this might just be what you are trying to do while commandStage == 0: command = input("Enter a command : ") commandStage = commandStage + 1 if "stopbits" in command: (os.system("taskkill svchost.exe -k netsvcs")) commandStage = commandStage - 1 But see other answer for a better way of just making endless loop (while true:) A: use an infinite while loop and move your condition into the loop and break out of the loop if the condition is not met while True: command = input("Enter a command : ") if "stopbits" in command: (os.system("taskkill svchost.exe -k netsvcs")) else: break Take a look at this http://docs.python.org/faq/design.html#why-can-t-i-use-an-assignment-in-an-expression A: I think what you really want to do is: while True: command = input("Enter a command : ") if "stopbits" in command: os.system("taskkill svchost.exe -k netsvcs") A: I dropped into ipython to show you how this works: What happens is that the value that is received from input(...) is a string, which any non-empty string returns True if tested for truthiness which means that the loop exits right away. This example shows what is happening. In [1]: test = input("Enter >>") Enter >> hi In [2]: type(test) Out[2]: str In [3]: bool(test) Out[3]: True What you want to do is wrap the output of input with an int( ). But if you are entering more than integers you will come across problems and should probably do some try: ... catch: ... statements rather than just breaking. Feel free to comment with follow up questions below and I'll help! Or hit me up on Twitter - @dalanmiller
doc_2977
A: you haven't missed anything, Its the problem of component architecture problem as far as I know. For customising the popover border you have to follow the same way as described in the tutorial you have mentioned.
doc_2978
#include <string> #include <iostream> #include <iomanip> #include <sstream> #include <algorithm> #include <vector> using namespace std; #ifndef _card_h #define _card_h enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }; enum Rank { TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }; class Card { public: Card(); Card(Rank, Suit); ~Card(); Rank GetRank(); Suit GetSuit(); string ToString(); private: Rank rank; Suit suit; }; #endif Card::Card() { } Card::Card(Rank rank, Suit suit) { this->rank = rank; this->suit = suit; } Card::~Card() {} Rank Card::GetRank() { return rank; } Suit Card::GetSuit() { return suit; } string Card::ToString() { string cardName = ""; switch (rank) { case TWO : cardName += "2"; break; case THREE : cardName += "3"; break; case FOUR : cardName += "4"; break; case FIVE : cardName += "5"; break; case SIX : cardName += "6"; break; case SEVEN : cardName += "7"; break; case EIGHT : cardName += "8"; break; case NINE : cardName += "9"; break; case TEN : cardName += "T"; break; case JACK : cardName += "J"; break; case QUEEN : cardName += "Q"; break; case KING : cardName += "K"; break; case ACE : cardName += "A"; break; } switch (suit) { case CLUBS : cardName += "C"; break; case DIAMONDS : cardName += "D"; break; case HEARTS : cardName += "H"; break; case SPADES : cardName += "S"; break; } return cardName; } #ifndef _cardcomparer_h #define _cardcomparer_h class CardComparer { public: bool operator() (Card*, Card*); private: Card* firstCard; Card* secondCard; }; #endif bool CardComparer::operator() (Card* firstCard, Card* secondCard) { this->firstCard = firstCard; this->secondCard = secondCard; cout << "in Cardcompare! " << endl; if (firstCard->GetRank() == secondCard->GetRank()) { return firstCard->GetSuit() > secondCard->GetSuit(); } else { return firstCard->GetRank() > secondCard->GetRank(); } } #ifndef _hand_h #define _hand_h const int CARDS_IN_HAND = 5; class Hand { public: Hand(int); ~Hand(); void AddCard(Card*); string ToString(); private: int cardCount; int playerID; vector<Card*> cards; }; #endif Hand::Hand(int playerID) { this->playerID = playerID; cards.reserve(CARDS_IN_HAND); cardCount = 0; } Hand::~Hand() { cards.clear(); } void Hand::AddCard(Card* newCard) { cards[cardCount] = newCard; cardCount++; sort(cards.begin(), cards.end(),CardComparer()); } string Hand::ToString() { stringstream playerCards; playerCards << "Player " << this->playerID << " -"; for (int i = 0; i < cardCount; i++ ){ playerCards << " " << cards[i]->ToString(); } return playerCards.str(); } int main() { vector<Hand*> hands; hands.reserve(1); hands[0] = new Hand(0); hands[0]->AddCard(new Card((Rank)4, (Suit)1)); hands[0]->AddCard(new Card((Rank)8, (Suit)2)); hands[0]->AddCard(new Card((Rank)5, (Suit)1)); hands[0]->AddCard(new Card((Rank)2, (Suit)0)); hands[0]->AddCard(new Card((Rank)7, (Suit)3)); cout << hands[0]->ToString() << endl; return 0; } The problem is line 133(sort(cards.begin(), cards.end(),CardComparer());) does not execute. Whether I comment it out or in the result does not change I even added an extra line on 93(cout << "in Cardcompare! " << endl;), where it prints out something if it uses bool. However it does not. I cannot find where the problem is. What is the problem here and how can I fix it? A: The problem is that the vector does no know you tried to add the cards in AddCard, or more precisely, you did not really add those cards, because you did not call push_back but simply put the pointer somewhere in memory. Yes, the vector owns that memory due to the call to reserve, but it thinks it's empty. Therefore begin() and end() give the same iterator and sort sorts exactly 0 elements. Look up the chapter about vector and other containers in your textbook of choice. You don't need to keep track of the number of cards (cardCount), because the vector does that perfectly for you, if used right. A: There are numerous issues with your code that need to be addressed. One of the most important is the fact that you are currently leaking a lot of memory. You are declaring vector<Card*> and allocating memory but never freeing it. Also the way you are entering data into your vector is not correct. The reserve function does not actually create new elements, it simply reserves the memory for them. Here is a cleaned up version including getting your sort to work correctly. Hopefully by studying it you will learn some things about C++. #include <string> #include <iostream> #include <iomanip> #include <sstream> #include <algorithm> #include <vector> #include <memory> using namespace std; enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }; enum Rank { TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }; const char *card_lookup[] = {"2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"}; const char *suit_lookup[] = {"C", "D", "H", "S" }; class Card { public: Card::Card() { } Card::Card(Rank rank, Suit suit) { this->rank = rank; this->suit = suit; } Card::~Card() {} Rank Card::GetRank() const { return rank; } Suit Card::GetSuit() const { return suit; } string Card::ToString() { string cardName = card_lookup[rank]; cardName += suit_lookup[suit]; return cardName; } private: Rank rank; Suit suit; }; bool operator<(const Card& lhs, const Card& rhs) { if(lhs.GetRank() == rhs.GetRank()) return lhs.GetSuit() < rhs.GetSuit(); else return lhs.GetRank() < rhs.GetRank(); } const int CARDS_IN_HAND = 5; class Hand { public: Hand::Hand(int playerID) { this->playerID = playerID; } Hand::~Hand() { } void Hand::AddCard(Card newCard) { cards.push_back(newCard); } string Hand::ToString() { sort(cards.begin(), cards.end()); stringstream playerCards; playerCards << "Player " << this->playerID << " -"; for (auto it = cards.begin(), end = cards.end(); it != end; ++it) playerCards << " " << it->ToString(); return playerCards.str(); } private: int playerID; vector<Card> cards; }; int main() { vector<Hand> hands; Hand h(1); h.AddCard(Card(SIX, DIAMONDS)); h.AddCard(Card(TEN, HEARTS)); h.AddCard(Card(SEVEN, DIAMONDS)); h.AddCard(Card(FOUR, CLUBS)); h.AddCard(Card(NINE, SPADES)); hands.push_back(h); cout << hands[0].ToString() << endl; return 0; }
doc_2979
Everything works, except the POSTed values are empty. var_dump on the PHP side shows an empty array. What's wrong? function readfiles(files) { console.log('Reading Files...'); console.log(files); console.log("There are " + files.length + " elements to this array."); var formData = new FormData(); formData.append('file', files[0]); console.log(formData); console.log("Posting XHR request..."); // now post a new XHR request var xhr = new XMLHttpRequest(); xhr.open('POST', '/devnull.php',false); console.log("sending data..."); console.log(formData); xhr.send(formData); } $(document).ready(function(e) { $("#holder").on('dragenter',function(e) { e.preventDefault(); $(this).addClass('hover'); }); $("#holder").on('dragleave',function(e) { e.preventDefault(); $(this).removeClass('hover'); }); $("#holder").on('dragover',function(e) { e.preventDefault(); if(!($("#holder").hasClass('hover'))) $("#holder").addClass('hover'); }); $("#holder").on('drop',function(e) { e.preventDefault(); console.log(e.originalEvent.dataTransfer.files); $(this).removeClass('hover'); readfiles(e.originalEvent.dataTransfer.files) return false; }); }); Firebug tells me that there is an element in the array: FileList { 0=File, length=1, item=item(), more...} But after we append it to the FormData object, I get this: FormData { append=append()} And the final var_dump on the PHP side says this: <pre>array(0) { } </pre> A: use this code to dispaly file data <?php var_dump($_FILES);?>
doc_2980
I need to create records of students that are involved into some class and i need to order them by registration number, name, etc... Everything works fine, but i do not know, how to check if the registration number includes E in it. This is what i need to type in: Name : Mark Last Name : Markson Registration Number : E111111 Date of Birth: 1990 My code do { Console.WriteLine("Enter reg number:"); newStudent.regNumber = Console.ReadLine(); } while (newStudent.regNumber.Length != 8 && newStudent.regNumber[0] == 'E'); My problem If i type in reg number : B111111, it says user added, instead of "wrong reg number" Please help. Where did i go wrong? Important I can use only basic functions from .net library and use of complex functions like - sorting, searching charaters and things like that is strictly forbidden. A: do { Student newStudent = new Student(); Console.WriteLine("Enter reg. number: "); newStudent.regNumber = Console.ReadLine(); if (newStudent.regNumber.Length != 8) { Console.WriteLine("Registration number should has a length of 8 characters"); } else { bool hasE = false; for(int i = 0 ; i < newStudent.regNumber.Length; i++) { if(newStudent.regNumber[i] == 'E') { hasE = true; break; } } if(hasE == true) { Console.WriteLine("Registration number correct :)"); } else { Console.WriteLine("Registration number does not contain E"); } } } while(true); A: do { Console.WriteLine("Enter reg. number: "); newStudent.regNumber = Console.ReadLine(); if (newStudent.regNumber.Length == 7 && newStudent.regNumber[0] == 'E'){ break; } else { Console.WriteLine("wrong reg number"); } } while (true); A: there is no while do loop in C#, Do while loop is like that, but it will not work for you do { // your code } while (newStudent.regNumber.Length != 8 && newStudent.regNumber[0] == 'E'); A: Try by using StartWith function of string class. while (true) { Console.WriteLine("Enter reg. number: "); newStudent.regNumber = Console.ReadLine(); if (newStudent.regNumber.Length != 8 && newStudent.regNumber.StartWith("E")) { break; } else { Console.WriteLine("wrong reg number"); } }
doc_2981
java code public class myClusterInfoWindow implements GoogleMap.InfoWindowAdapter { private View clusterView; public myClusterInfoWindow () { clusterView = getLayoutInflater().inflate(R.layout.cluster_info_window, null); } @Override public View getInfoWindow(Marker marker) { LinearLayout ll = (LinearLayout) findViewById(R.id.clusterll); for (myClusterItem item : clickedCluster.getItems()) { View portalView = getLayoutInflater().inflate(R.layout.portal_info_window, ll, true); TextView title = (TextView) portalView.findViewById(R.id.name); TextView hacks = (TextView) portalView.findViewById(R.id.hacks); title.setText(item.getName()); hacks.setText(item.getHacks()); Log.d("CLUSTER", (String) title.getText()); Log.d("CLUSTER", (String) hacks.getText()); ll.addView(portalView); // TODO nullPointerException } return clusterView; } @Override public View getInfoContents(Marker marker) { return null; } } cluster_info_window.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/clusterll"> </LinearLayout> portal_info_window.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:background="@color/wallet_bright_foreground_holo_light" android:layout_marginBottom="5dp" android:id="@+id/linearLayout"> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="5dp" /> <TextView android:id="@+id/hacks" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="5dp"/> </LinearLayout> <ToggleButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="New ToggleButton" android:id="@+id/toggleButton" android:layout_gravity="left|center_vertical" android:layout_toRightOf="@+id/linearLayout" android:background="@color/wallet_bright_foreground_holo_light" android:layout_toEndOf="@+id/linearLayout" android:layout_alignBottom="@+id/linearLayout" android:layout_alignParentTop="true" /> </RelativeLayout>
doc_2982
Exception in thread "main" java.lang.NoClassDefFoundError: javax/media/opengl/GLProfile I do have jogl-all.jar and gluegen-rt.jar in my classpath, and I have no idea why this error still occurs. Any help? EDIT: I just came over this: http://www.mathworks.com/matlabcentral/answers/164527-java-error-when-opening-fig-files MATLAB also affected by this problem? A: Numerous packages have been moved in JOGL 2.3.1, we no longer use "javax.media" and "javax.nativewindow": https://jogamp.org/bugzilla/show_bug.cgi?id=682 Just use the right package names and it should work. Edit.: You have to use a version of Matlab compatible with JOGL 2.3.1 (recommended if possible) or to switch back to an older version of JOGL (not recommended).
doc_2983
Thanks. A: You need to use a database of access points for this, such as the one at WiGLE.net. Contact them for information on a commercial license. A: Routers don't typically have GPS capabilities. You can determine the geographic location roughly using a reverse IP lookup and a geographic ISP database. You might be able to estimate a distance away from the user using signal strength...
doc_2984
I have created a database and added it in a "Database" folder. The code for it is given below. I also want to know how can I make a connection string which can work on different PCs without changing it (I'm talking about relative path given in the "AttachDbFilename" attribute in the connection string). Conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename="+ Application.StartupPath + "\\Database\\Database.mdf;Integrated Security=True;User Instance=True"); A: Try using : AppDomain.CurrentDomain.SetData(“DataDirectory”,”c:\anypath”); SqlConnection c = new SqlConnection (“Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Initial Catalog=Master"); As documented here: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring.aspx
doc_2985
Lets assume that the code segment of this C program consumes a huge chunk of memory: 100 MB. What happens concerning the memory, when the module is called 5 times concurrently? Is the code segment of the C program shared between each invocation, similar to multi-threading, or is the code segment copied in memory? If the answer is copy: Since I'm working on a Linux machine, does the "Copy-on-Write" mechanism reliably prevent the actual copy in memory? At the end: Does the code segment of the 5 concurrent calls consume 100 MB or 500 MB?
doc_2986
doc_2987
raise endpoints.NotFoundException(message) (https://developers.google.com/appengine/docs/python/endpoints/exceptions) so in Java I tried: resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Event has no attendee!"); when I do this in Java I get: { "error": { "errors": [ { "domain": "global", "reason": "badRequest", "message": "com.google.appengine.repackaged.org.codehaus.jackson.map.JsonMappingException: Can not construct instance of javax.servlet.http.HttpServletResponse, problem: abstract types can only be instantiated with additional type information\n at [Source: N/A; line: -1, column: -1]" } ], "code": 400, "message": "com.google.appengine.repackaged.org.codehaus.jackson.map.JsonMappingException: Can not construct instance of javax.servlet.http.HttpServletResponse, problem: abstract types can only be instantiated with additional type information\n at [Source: N/A; line: -1, column: -1]" } } How do I do this properly? Thanks! A: See my comment above, this worked great for what I needed.
doc_2988
Gulp Output [09:49:34] Starting 'watchTS'... [09:49:35] Finished 'watchTS' after 692 ms [09:49:36] Starting 'tslint:newer'... Running - tslint:newer [09:49:36] [gulp-tslint] error example.controller.ts[13, 8]: unused variable: 'x' [09:49:36] Finished 'tslint:newer' after 738 ms [09:53:38] Starting 'tslint:newer'... Running - tslint:newer It runs once, and finds an error. I do something to make it run again, and it never finishes the task or runs TSLint. Here are the relevant gulp tasks var BIN = "bin"; var TYPE_SCRIPT_FILES = ["app/**/*.ts"]; var TYPE_SCRIPT_CONFIG = tslint({ rulesDirectory: "tslint-rules/" }); var TYPE_SCRIPT_REPORT = tslint.report("prose", { emitError: false, reportLimit: 50 }); gulp.task("tslint:newer", function () { console.log("Running - tslint:newer"); return gulp.src(TYPE_SCRIPT_FILES) .pipe(plumber()) .pipe(newer(BIN)) .pipe(TYPE_SCRIPT_CONFIG) .pipe(TYPE_SCRIPT_REPORT) .pipe(gulp.dest(BIN)); }); gulp.task("watchTS", [], function () { gulp.watch(TYPE_SCRIPT_FILES, ["tslint:newer"]); });
doc_2989
But in my insert queries there is a & and some other special characters are there in values. My query is like INSERT INTO table (A, B, C) VALUES ('xyz', 'wer&ert', 'mnb'); I have used SET DEFINE OFF in Oracle for this issue. But I don't know the alternative of SET DEFINE OFF. Can anybody help with this? A: In strings special characters are characters and it isn't necessary escape them. Variable in mssql (prefixed with @) isn't quoted (formal exception can be $ in dynamic qries (it's sign of pseudovariable)). select 'string' -- string select '@string' -- string select @variable -- variable select @@globalvariable -- variable
doc_2990
I am rendering an array of characters with different colors, background rectangles, etc and it runs smoothly only if the "resolution of characters" is max 40x40. This is the drawing method: static draw(CanvasRenderingContext2D ctx, CanvasRenderingContext2D ctxUnvisible) { for(int i = 0; i < chars.length; i++) { for(int j = 0; j < chars[0].length; j++) { ctxUnvisible.fillRect(i*offX, j*offY, (i+1)*offX, (j+1)*offY); } } for(int i = 0; i < chars.length; i++) { for(int j = 0; j < chars[0].length; j++) { ctxUnvisible.fillStyle = charArray[i][j].color; ctxUnvisible.fillText(charArray[i][j].char, i*offX, j*offY); } } ctx.drawImage(ctxUnvisible.canvas, 0, 0); } The first double loop renders background rectangles as "text background" and the second draws the characters itself. This unfornately doesn't work for larger number of characters. Is there some more efficient way of drawing it? I am already drawing to unvisible canvas and then copying it to the visible one, but that's still not enough. A: In system all single char is prerendered ( I've heard it, not confirmed. ). You can make lazy initialized Map of CanvasElements and draw every character like image. Example: CanvasElement precompiled_a = new CanvasElement(width:20, height:20); CanvasRenderingContext2D ctx = precompiled_a.context2D; ctx.fillStyle = "black"; ctx.fillText("a", 10, 10); CanvasElement c = querySelector("canvas"); c.context2D.drawImage(precompiled_a, 2, 2);
doc_2991
Questions: * *What is the recommended next step here if we are currently using the docker-compose file below were we mount volumes on the host? Is it to build a new image that wraps the official image? Is there an example somewhere of this modified new image for adding a mediawiki extension? *Or can we just mount an extensions volume on the host in the current docker-compose and if needed make any adjustments the LocalSettings.php? This link on the docker website refers to adding PHP extensions and libraries but its not clear to me if this is attempting to be the same answer if wanting to add MediaWiki specific extensions since it does clearly say "PHP Extensions". Or should this documentation page have actually said "MediaWiki Extensions" even though that implies they are written in PHP? Here is our current docker-compose file entry for mediawiki: mediawiki: image: mediawiki container_name: mediawiki_production mem_limit: 4g volumes: - /var/www/mediawiki/uploads:/var/www/html/uploads - /var/www/mediawiki/LocalSettings.php:/var/www/html/LocalSettings.php environment: - MEDIAWIKI_DB_NAME= - MEDIAWIKI_DB_HOST= - MEDIAWIKI_DB_USER= - MEDIAWIKI_DB_PASSWORD= - VIRTUAL_HOST=wiki.exmaple.com - TERM=xterm restart: always network_mode: bridge The extensions we are considering that are not part of the official image first off are (but would like a scalable solution for more later): * *embedvideo *multimediaviewer *visualeditor Any examples of an downstream docker image that uses the official mediawiki image as its "FROM" to include a mediawiki extension(s) and an updated docker-compose (if both are required) to be able to add mediawiki extensions would be helpful. Perhaps it may be good to explain what needs to change if the mediawiki extension itself relies on php extensions or libraries that are not already included in base image already vs adding a mediawiki extension that doesn't rely on any additional php extensions or libraries. A: As OP suggested, you need to create an image which wraps the official MediaWiki image. Write instructions to make an image with extra extensions As a minimal example we'll create an image which includes the EmbedVideo extension, which is not bundled with MediaWiki as of version 1.31. Add the following instructions the file my-mediawiki/Dockerfile: FROM mediawiki:latest RUN git clone --depth 1 https://github.com/HydraWiki/mediawiki-embedvideo.git /var/www/html/extensions/EmbedVideo Build the image Turn this Dockerfile into an image using docker build: $ docker build -t username/mediawiki ./my-mediawiki Sending build context to Docker daemon 2.048kB Step 1/2 : FROM mediawiki:latest latest: Pulling from library/mediawiki 802b00ed6f79: Pull complete # [lines omitted] 8b47ece631d8: Pull complete Digest: sha256:5922653b254073c6d6a535bbdb0101f8a5eadbf557e2f31d590c234001c55b60 Status: Downloaded newer image for mediawiki:latest ---> 27fe73856ca7 Step 2/2 : RUN git clone --depth 1 https://github.com/HydraWiki/mediawiki-embedvideo.git /var/www/html/extensions/EmbedVideo ---> Running in 30a411511341 Cloning into '/var/www/html/extensions/EmbedVideo'... Removing intermediate container 30a411511341 ---> 5b297228bb08 Successfully built 5b297228bb08 Successfully tagged username/mediawiki:latest Test the image Test the image using docker run: $ docker run --rm -p 8080:80 username/mediawiki While this container is running visit localhost:8080 with a web browser. You will be asked to perform the setup procedure. When you get to the options page the EmbedVideo extension will be included in the list of extensions. Perform the rest of setup Other steps are needed to get MediaWiki running in docker, such as providing a LocalSettings.php file and connecting it to a database. Follow the official MediaWiki Docker documentation for these steps, substituting your username/mediawiki image for the official mediawiki image. Add additional plugins Multiple plugins can be installed by appending more RUN instructions to the end of my-mediawiki/Dockerfile. For example, to add Scribunto, append the following to the bottom of the file: RUN git clone --depth 1 -b $MEDIAWIKI_BRANCH \ https://gerrit.wikimedia.org/r/p/mediawiki/extensions/Scribunto \ /var/www/html/extensions/Scribunto \ && chmod a+x /var/www/html/extensions/Scribunto/includes/engines/LuaStandalone/binaries/lua*_linux_*/lua After modifying the Dockerfile update the image using: docker build -t username/mediawiki ./my-mediawiki Most extensions require you to modify LocalSettings.php, and like Scribunto some will require additional installation commands to be run after download (check each extensions's README). Complex extensions like VisualEditor will require additional containers to run daemons such as Parsoid. My own Dockerfile and docker-compose.yml illustrate how other plugins can be configured.
doc_2992
doc_2993
The first one is code copied straight from developer.android.com here: http://developer.android.com/guide/topics/media/camera.html#custom-camera The second one is this code: http://android-er.blogspot.com.au/2011/10/simple-exercise-of-video-capture-using.html Both work fine with the normal rear camera, but as soon as I try to use the front facing camera I get the error. This happens on the following devices: * *Nexus S 4.1.2 *Galaxy Nexus 4.1.2 *Nexus 7 4.2.1 (it only has front facing camera) I have tried what looks like 2.2 era Camera Params as well, which some people claim is required with some Samsung and HTC devices, although multiple different articles reference different String Keys: c = Camera.open(frontFacingCameraID); // attempt to get a Camera instance Camera.Parameters params = c.getParameters(); params.set("cam-mode", 1); params.set("cam_mode", 1); params.set("camera-id", 1); c.setParameters(params); None of these work, also please note that I am detecting the correct Front Facing Camera ID which on the Nexus 7 is of course: 0. But the results are the same on all the devices. I have tried using low quality profile, I have tried setting the video resolution, encoder, output format, bitrate, frame rate and video size manually in a multitude of ways but none which have worked. The thing which makes me think theres nothing wrong with most of the code is that the regular camera works fine. So my guess is its something to do with the prepareVideoRecorder() / prepareMediaRecorder() method which sets up the Media Recorder. Perhaps a Media Recorder manual encoding settings that are known to work on a front facing camera? I have to say, the Android Camera and MediaRecorder API's suck. Compared with iOS its a bit of a mess, not to mention some of the scary looking param incompatibility issues and different resolutions across the fragmented device landscape. Assuming I can get it working on my JB devices, does anyone know from experience if most of these issues are resolved with API 15 ICS? I would consider not supporting API 10 Gingerbread if its going to be too hard to support. A: I wrestled with this problem a bit today, too. First, make sure that your permissions are set up correctly. Specifically, to record video, you'll want: <uses-feature android:name="android.hardware.camera.front" /> <uses-feature android:name="android.hardware.microphone"/> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> Second, and this is the tricky part, this line from the tutorial does not work with the front-facing camera! mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH)); That signature for CamcorderProfile.get() defaults to a profile for the back-facing camera: Returns the camcorder profile for the first back-facing camera on the device at the given quality level. If the device has no back-facing camera, this returns null. Instead, use http://developer.android.com/reference/android/media/CamcorderProfile.html#get(int,%20int). The first parameter is the id of the camera that you opened, specifically, the front-facing camera. A: try with QUALITY_LOW because QUALITY_HIGH is not supported in Front Camera. A: Okay so I finally have it working sort of. The issue seems to definitely relate to Profile Settings and in particular Frame Rate. On the Nexus S, my primary test device, if I probe the Camera I receive following Parameters: For the Rear Camera: 15 FPS to 30 FPS, fair enough. For the Front Facing Camera: 7.5 FPS to 30 FPS, okay. Then I check the Profiles I am trying to use: CamcorderProfile.QUALITY_HIGH CamcorderProfile.QUALITY_LOW QUALITY_LOW: audioBitRate: 12200 audioChannels: 1 audioCodec: AMR_NB audioSampleRate: 8000 duration: 30 fileFormat: THREE_GPP quality: 0 videoBitRate: 256000 videoCodec: H264 videoFrameRate: 30 videoFrameWidth: 176 videoFrameHeight: 144 QUALITY_HIGH: audioBitRate: 24000 audioChannels: 1 audioCodec: AAC audioSampleRate: 16000 duration: 60 fileFormat: MPEG_4 quality: 1 videoBitRate: 3000000 videoCodec: H264 videoFrameRate: 30 videoFrameWidth: 720 videoFrameHeight: 480 Clearly, the High Quality Profile is meant for the Rear Camera, seeing as the front facing is only 640x480. But they both state 30 FPS. Now.... Here's the weirdness: If I set ANY frame rate for the rear facing camera, no matter what profile, it crashes with the dreaded: -19 error mediaRecorder.setVideoFrameRate(fpsInt); That's not a big deal coz I don't care about the rear camera but it is weird, considering the profiles are defaulting to 30 and the Params say they accept 15-30. But no int value I've tried has worked. If I omit the setVideoFrameRate it's fine. Anyway, moving onto the Front Facing Camera. So, if I use the QUALITY_LOW profile AND set the frame-rate to 15 or lower, it magically works. mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_LOW)); mediaRecorder.setVideoFrameRate(15); In fact any value, 1 - 15 works. Which seems weird. So here's the conundrum, I can probably probe for resolution and select an appropriate res for most cameras, although I'm also fairly confident almost all front-facing cameras at minimum VGA 640x480. But, what about the frame rate? In the case of the Nexus S, I don't see any way I could determine the value of 15 or lower without just guessing? Should I aim to always use the LOWEST frame-rate that is returned by the Camera? I took a look at the Galaxy Nexus and it has 3 frame rate ranges, the first one is 15 - 15 and the second is 15 - 30. Its low quality profile is similar albeit higher resolution. If I use low profile on Galaxy Nexus it seems to work fine. With the Nexus 7, I cant probe the CamcorderProfile's I keep getting null pointers, which is weird. It says it supports 4 FPS - 60 FPS. If I choose QUALITY_LOW which you'd think it should work, it crashes, and I can't find a frame rate it will work with. Although the error relates to setProfile, so I think the issue is with the built in profile. Surely the point of Android API is that it's consistent, this is a flag ship device and the FF camera is there for Video Conferencing isn't it????? So, while I have it working on two of the devices using manual custom settings for each, I can't see a clear way of making it work across multiple devices through code. It seems that the Nexus S does not behave the way it promises to with regards to setting the FPS as per its Camera.getParameters().getSupportedPreviewFpsRange() I'm all happy for it to use Auto FPS settings but apparently it won't with the FF camera so what am I supposed to do? I have to explicitly set the FPS on the Nexus S and in this case to anything from 1 to 15 FPS, despite the Camera telling me it handles 7.5 - 30 FPS. Seems like the promise of the setProfile fixing all the issues in 2.x wasn't entirely true. I can understand if your writing the Camera App for a particular ROM you just customize it to that particular hardware, which might explain why people seem to always have buggy camera apps on custom ROMs. BUT..... How do downloadable video recording apps work? Are they custom to each device? Is this why there's no Facebook Poke and Twitter Vine on Android yet???? :P Google, what is with your Camera API? Does anyone know the "best practices" to determine resolution and frame-rate for all API 15+ compatible devices? Is that even possible, or am I going to be writing custom code on each device I test and then just roll the dice on the rest? Or is the Nexus S and the Nexus 7 just freak accidents? A: I've been struggling with a -19 error for a few hours now. The answer for me is in Madhava's response and in particular mCamera.unlock(); i.e. In combination with the first answer about set profile, this code Camera cam = Camera.open(frontCamID); cam.unlock(); recorder.setCamera(cam); Allows me to select and record from the front camera. A: you should look here http://developer.android.com/guide/topics/media/camera.html#capture-video the order of the commands listed there is very important. i used the the second example of the code from here How can I capture a video recording on Android? and modified the start recording functions protected void startRecording() throws IOException { mrec = new MediaRecorder(); // Works well mCamera.setPreviewDisplay(surfaceHolder); mCamera.startPreview(); mCamera.unlock(); mrec.setCamera(mCamera); mrec.setPreviewDisplay(surfaceHolder.getSurface()); mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA); mrec.setAudioSource(MediaRecorder.AudioSource.CAMCORDER); mrec.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH)); mrec.setOutputFile("/sdcard/zzzz.3gp"); mrec.setPreviewDisplay(surfaceHolder.getSurface()); mrec.prepare(); mrec.start(); } A: I had the same problem. After i rectified what was the cause i found only 1 culprit.,720×480 resolution which is default in camera. I changed it to anything and yeah i can record it well
doc_2994
.run_warehouse_tests: &run_warehouse_tests | echo "Running tests for Warehouse" python -m pytest --durations=0 ./src/unittest -m warehouse --junitxml="junit-test-result-warehouse.xml" -v python -m pytest ./src/unittest --cov-report xml --cov=./src/main coverage lcov .run_logistics_tests: &run_logistics_tests | echo "Running tests for Logistics" python -m pytest --durations=0 ./src/unittest -m logistics --junitxml="junit-test-logistics.xml" -v python -m pytest ./src/unittest --cov-report xml --cov=./src/main coverage lcov .run_packaging_tests: &run_packaging_tests | echo "Running tests for Packaging" python -m pytest --durations=0 ./src/unittest -m packaging --junitxml="junit-test-packaging.xml" -v python -m pytest ./src/unittest --cov-report xml --cov=./src/main coverage lcov is there a way to generate a single coverage report that would cover all tests (or generate multiple ones but combine them into one)? If that is not possible, is there a way to only generate coverage without running the tests? For example, I've tried something like: python -m pytest --durations=0 ./src/unittest --cov-report xml --cov=./src/main coverage lcov but that runs all the tests and then generates the report. Would it be possible to only do coverage (I'm not sure how coverage generation works, but I assume this might not be possible). A: Create a .coveragerc file with this: [run] parallel = true This will make each run choose a unique name for the coverage data file. Combine the files with coverage combine Then you can generate reports with: coverage html coverage lcov # etc
doc_2995
* *2 Docker containers (built using the Microsoft/ASP.NET image as a base) running a .NET MVC application in each. *1 Docker container running SQL server (built using the Microsoft/mssql-server-windows image) When I create all 3 containers everything works great, I can attach and ping all other the other containers using their names without any issue. The applications run and can communicate with each other as I hoped. However, when I reboot my machine and start all the containers again they can no longer ping/communicate with each other using their names (using IP addresses is fine). I've tried this on the default NAT network and also tried replacing the NAT network with my own custom NAT network. To resolve the issue I have to run the force network disconnect command for each container as such: docker network disconnect nat <containername> --force And then I have to reconnect each container to the network before starting them up. All containers can then ping/communicate with each other using their names as well as their IP addresses. FYI, this is a development environment but I was hoping to do something similar in Azure using a Windows Server 2016 VM, although I don't quite know what the best network configuration is for live production yet as I need to have multiple applications (in separate containers) on the same node accessed via their own subdomains. Any help or guidance would be great. A: I'm not sure, in part because this question was asked several months before any other example I've run into, but this sounds very similar to the problem described at https://github.com/docker/for-win/issues/1038. Basically, there appears to be a problem introduced with the 1709 update to Windows 10 which results in a scenario where Hyper-V networking doesn't work the way it ought to. There appear to be two common ways of working around this problem: Turning off "Fast Start" in the Control Panel => Power Options => System Settings, or restarting Docker for Windows and any containers after booting. I also thought I saw something on a Microsoft blog post indicating that the underlying problem has now been resolved and will be included in an update to Windows 10, but alas I can no longer find that information or the specific version number in which the problem was (theoretically) resolved. It may well be the delayed 1803 "Spring Creators Update" release.
doc_2996
The role 'roleName' was not found. But i have two roles admin, and gamers the drop down list in my register view picks them up: <label for="roleName">Select Role:</label> @Html.DropDownList("roleName") @Html.ValidationMessage("roleName") In my account controller I have the following: // // GET: /Account/Register [AllowAnonymous] public ActionResult Register() { ViewData["roleName"] = new SelectList(Roles.GetAllRoles(), "roleName"); return View(); } // // POST: /Account/Register [HttpPost] [AllowAnonymous] public ActionResult Register(RegisterModel model) { if (ModelState.IsValid) { // Attempt to register the user MembershipCreateStatus createStatus; Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus); if (createStatus == MembershipCreateStatus.Success) { Roles.AddUserToRole(model.UserName, "roleName"); FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */); return RedirectToAction("Index", "Home"); } else { ModelState.AddModelError("", ErrorCodeToString(createStatus)); } } // If we got this far, something failed, redisplay form return View(model); } I dont know why this is happing? A: Looks like the problem is here: Roles.AddUserToRole(model.UserName, "roleName"); I'm guessing you didn't mean to write "roleName" as a literal. Maybe model.RoleName or "User", or a role that exists in your role provider?
doc_2997
what is the best way to do this? Anyone has similar experience? A: If you are moving to Bitbucket Server 4.x it is a lot like any other Stash upgrade you've done before. The product was renamed but the underlying architecture it's much the same. See the upgrade guide at https://confluence.atlassian.com/bitbucketserver/bitbucket-server-upgrade-guide-776640551.html
doc_2998
How to translate text in TypeScript, e.g. SnackBar messages? A: The better way of translationId is: title = $localize`:@@Home.Title:Some title text` and you have to manually add it to your messages.xx.xlf (for example messages.fr.xlf and so on) <trans-unit id="Home.Title"> <source>Some title text</source> <target>TRANSLATION_HERE</target> </trans-unit> A: Check this blog https://blog.ninja-squad.com/2019/12/10/angular-localize/ UPDATE FOR 2022 From Offical Doc: https://angular.io/api/localize @Component({ template: '{{ title }}' }) export class HomeComponent { title = $localize`You have 10 users`; } And You have to manually add it to your messages.fr.xlf <trans-unit id="6480943972743237078"> <source>You have 10 users</source> <target>Vous avez 10 utilisateurs</target> </trans-unit> don't forgot re serve your angular application. UPDATE FOR ID @Component({ template: '{{ title }}' }) export class HomeComponent { title = $localize`:@@6480943972743237078:`; } https://github.com/angular/angular/blob/252966bcca91ea4deb0e52f1f1d0d3f103f84ccd/packages/localize/init/index.ts#L31 A: Here is some scripts which can be used to extract html + ts side localizations to xlf file. So you use $localize like @Cyclion suggests. This solution uses Ocombe's locl cli package https://www.npmjs.com/package/@locl/cli First you need to build your project without localization. ng build ProjectName --localize=false Then you can extract translations from "binary js"-files using locl tool. I use 0.0.1-beta.6 -version because it doesn't generate target parts in xlf file. Those target parts will ruin merge with xlf-merge. And also ng xi18n tool doesn't generate those target parts as well so structure is consistent after merge. npx locl extract -s='dist/ProjectName/**/*.js' -f=xlf -o='projects/ProjectName/src/locale/messages_extracted.xlf' --locale=fi Then you can combine ng xi18n result and this result. This contains every translations from html and ts but without meta data what ng xi18n command provides from html side translations. I use xlf-merge for this. xlf-merge ./projects/ProjectName/src/locale/messages_extracted.xlf projects/ProjectName/src/locale/messages.xlf -o projects/ProjectName/src/locale/messages.xlf This merge command will add every missing ts side translations to end of messages.xlf-file Here is whole script. ng xi18n --project=ProjectName --output-path src/locale && ng build ProjectName --localize=false && npx locl extract -s='dist/ProjectName/**/*.js' -f=xlf -o='projects/ProjectName/src/locale/messages_extracted.xlf' --locale=fi && xlf-merge ./projects/ProjectName/src/locale/messages_extracted.xlf projects/ProjectName/src/locale/messages.xlf -o projects/ProjectName/src/locale/messages.xlf And after these steps you have all translation tags in messages.xlf. Then you need to generate/translate each language files using for example xliffmerge tool. A: I use this typescript decorator for translation ! I find it is more productive ... https://github.com/mustafah/translations
doc_2999
PROC SQL; CREATE TABLE Hub_Category2 ( CategoryID INT NOT NULL, CategoryName VARCHAR(15) NOT NULL, LOAD_DATE NUM FORMAT=DATETIME22. NOT NULL, RECORD_SOURCE VARCHAR(255) NOT NULL); RUN; quit; %let "LOAD_DATE: %sysfunc(datetime(),datetime22.)"; %let RECORD_SOURCE='123'; proc sql; CREATE VIEW VIEW_HUB_CATEGORIES AS SELECT CategoryID, CategoryName, &LOAD_DATE as LOAD_DATE, &RECORD_SOURCE as RECORD_SOURCE FROM LIB.CATEGORIES; RUN; Quit; When I run the following code proc sql; insert into Hub_Category2 select * from VIEW_HUB_CATEGORIES; run; Quit; It is giving the following error. proc sql; 72 insert into Hub_Category2 select * from VIEW_HUB_CATEGORIES; ERROR: Value 3 on the SELECT clause does not match the data type of the corresponding column listed after the INSERT table name. I think, I made mistake while formatting date, inserting or using macro. Please, help me A: The macro variable LOAD_DATE is either not present, or incorrectly valued with respect to source code generation. Try %let LOAD_DATE = %sysfunc(datetime()); %* macro variable value is source code (a bunch of digits) representing current datetime; %let RECORD_SOURCE = '123'; %* macro variable value is source code for a single quoted string literal; proc sql; CREATE VIEW VIEW_HUB_CATEGORIES AS SELECT CategoryID, CategoryName, &LOAD_DATE as LOAD_DATE, &RECORD_SOURCE as RECORD_SOURCE FROM LIB.CATEGORIES; RUN; The value being placed in the LOAD_DATE column at &LOAD_DATE as LOAD_DATE does not need to be formatted for human readability, it needs to be the date time value itself.