id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23532500
below is my package.json { "name": "feedback-clientlibs", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build": "webpack" }, "keywords": [], "author": "hkesani", "license": "ISC", "devDependencies": { "css-loader": "^3.5.3", "webpack": "^4.43.0", "webpack-cli": "^3.3.11" }, "dependencies": { "lodash": "^4.17.15" } } and my webpack.config.js is as follows var path = require('path'); module.export ={ entry : './js/feedback.js', mode:'none', output : { filename:'feedback.js', path:path.resolve(__dirname,'webpack.modules') }, module:{ rules:[ { test:/\.css$/, use:['css-loader'] } ] } } I have few css imports into the js files as below import '../css/feedback.css' import '../css/all.css' whenever i run a build (i have cssloader installed) below is what i see $ npm run build > feedback-clientlibs@1.0.0 build C:\projects\br_translation\jcr\code\jcr_root\apps\r\dcloud\components\clientlibs\feedback-clientlibs > webpack Hash: 7c51d9af54f992c3e551 Version: webpack 4.43.0 Time: 106ms Built at: 05/10/2020 10:39:42 PM 1 asset Entrypoint main = main.js [0] ./src/index.js 6.17 KiB {0} [built] [1] ./css/feedback.css 302 bytes {0} [built] [failed] [1 error] [2] ./css/all.css 292 bytes {0} [built] [failed] [1 error] WARNING in configuration The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment. You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/ ERROR in ./css/feedback.css 1:0 Module parse failed: Unexpected character '#' (1:0) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders > #feedback { | height: 5em; | padding: 10px 22px 8px 22px; @ ./src/index.js 1:0-28 ERROR in ./css/all.css 1:0 Module parse failed: Unexpected token (1:0) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders > .ratings-stars { | margin-bottom: 15px; | height: 13px; @ ./src/index.js 2:0-23 npm ERR! code ELIFECYCLE npm ERR! errno 2 npm ERR! feedback-clientlibs@1.0.0 build: `webpack` npm ERR! Exit status 2 npm ERR! npm ERR! Failed at the feedback-clientlibs@1.0.0 build script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\hkesani\AppData\Roaming\npm-cache\_logs\2020-05-10T17_09_42_363Z-debug.log Any help is appreciated. Thanks A: Have you tried it with style-loader? npm install --save-dev style-loader And update your webpack.config.js rules to: rules: [ { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] } ] I also notice you did not supply a production flag for your webpack command I would update that script to run: webpack --mode production -p Then in your output path try a directory name without the period. This may or may not be the reason but it is normally a naming convention to use a dash or underscore for directory names. path: path.resolve(__dirname,'webpack_modules') A: I think it's defined [here]enter link description here. It can also be inspected via node: const webpack = require('webpack') new webpack.WebpackOptionsDefaulter()
doc_23532501
cobc -C nextbig.cob swig -java nextbig.i gcc nextbig.c nextbig_wrapper.c gcc -shared ... and gcc builds a very nice binary, Java and the C output of the COBOL compiler mixed nicely. Only tested swig -tcl, -perl, -python and -java so far (all different nextbig_wrapper.c of course). How much grief would be involved in blending (for instance) swig -java and swig -python across the same nextbig.c and nextbig.i? Is there a known idiom for manual intervention at managing two or more target _wrapper.c files? Or is it a known thing not to do?
doc_23532502
forms.py class HealthCheckerForm(PortalModelForm): name = forms.CharField(max_length=128,required = False ,help_text="Enter Name", label='Name') description = forms.CharField(max_length=128, required = False, label='desc*') age = forms.CharField(max_length=128,required = False ,help_text="Enter age", label='age') group = forms.CharField(max_length=128, required = False, label='group*') form.html {% for field in form %} <div class="fieldWrapper"> <div class="fieldInfo"> {{ field.label_tag }}{{ field }} <span class="errorList">{{ field.errors|striptags}}</span> </div> </div> {% endfor %} without customizing form.html how to add a button or an anchor tag Thanks in advance.. A: I hope I understood your question; it seems similar to the problem I came across today. Basically you can create your own Widget and Field. from django.utils.safestring import mark_safe class AnchorOnlyWidget(forms.Widget): def render(self, name, value, attrs): final_attrs = self.build_attrs(attrs, name=name) if hasattr(self, 'initial'): value = self.initial return mark_safe("<a href='%s' %s>%s</a>" % (value, flatatt(final_attrs), value)) def _has_changed(self, initial, data): return False class AnchorOnlyField(forms.FileField): widget = AnchorOnlyWidget def __init__(self, widget=None, label=None, initial=None, help_text=None): forms.Field.__init__(self, label=label, initial=initial, help_text=help_text, widget=widget) def clean(self, value, initial): self.widget.initial = initial return initial And then add it to your form: class HealthCheckerForm(PortalModelForm): youranchor = AnchorOnlyField(help_text="the help") ...
doc_23532503
So I have 10 columns to be filled with data, and when the user wants to work on a specific column, i would love to have it so he just needs to click on any cell in the column and then my macro selects the rest. Perhaps the entire column is not the best idea, since I need to add comments to EVERY cell and Excel does not like that. 1000 rows will do it. A: Something like this code: Private Sub Worksheet_SelectionChange(ByVal Target As Range) ActiveCell.EntireColumn.Resize(Rows.Count - 3).Offset(3).Select End Sub
doc_23532504
var video0, video1, video2; video0 = '#div0'; video1 = '#div1'; video2 = '#div2'; for (i = 0; i <= 3; i ++) { $(video+i).click(function(){ setupVideo(i); }); } // Play each of the videos. function setupVideo(index) { videoCount = index; playVideos(videoCount); } I know my problem lies in $(video+i).click(function(){... I've tried various methods of passing i to the video variables. A: Your method is wrong on many levels. First of all, you can't "add" a number to a variable and expect to create another variable. When you do "video + i", you are adding the content of the variable video to the content of the variable i. You have no variable called video so you are adding undefined to a number. What you have to do is to dynamically access a variable, and in Javascript you can do it by accessing the object in whose scope the variables live, for example window. Then again, you must treat window as an associative array and therefore use window["video" + i] to access video0, video1... Note the quotes around "video": it means that you concatenate two strings ("video" and the content of i, which is a number but is converted to a string), thereby creating strings like "video0", "video1", etc., and you use those newly created strings as keys in an associative array to obtain the values. This is possible only because Javascript creates such an array in the main scope. Then again, the approach is not good. You should use an array to do operations like these: var videos = ['div0', 'div1', 'div2']; or use a common class to identify your videos A: You can't access a variable by concatenating its name together. A better method for this would be to place a common class on all the elements and pass their index to playVideos(). Try this: $('.video').click(function() { playVideos($(this).index('.video')); }); A: For your code solution is access global variable using window var video0, video1, video2; video0 = '#div0'; video1 = '#div1'; video2 = '#div2'; for (i = 0; i <= 3; i ++) { $(window['video'+i]).click(function(){ setupVideo(i); }); } // Play each of the videos. function setupVideo(index) { videoCount = index; playVideos(videoCount); } I suggest to use store each element selector in array, and no need of setupVideo() function. var video_elements=["#div0","#div1","#div2"]; for (i = 0; i <= video_elements.length; i ++) { $(video_elements[i]).click(function(){ playVideos(i); }); } A: Try to create your selector on the loop and use the method on to add an event handler. Add an data value on the element and use it to read to perform your setupVideo method. See the comments on the code bellow: for (i = 0; i < 2; i ++) { var divElement = $("#div" + i); divElement.data("index", i); divElement.on("click", function() { var index = $(this).data("index"); setupVideo(index); }); }
doc_23532505
Here is my snippet: app.post('/submit', function(req, res) { var my_visit = new models.visits({ date: req.body.visit_date, type: req.body.visit_type, agency: req.body.visit_agency, city: req.body.visit_city, url: req.body.visit_url, note: req.body.visit_note }); // INSERT if(req.body.id == 0) { my_visit.save(function(err) { if(err) { throw err; } console.log('added visit'); res.redirect('/'); }); } else { // UPDATE var upsertData = my_visit.toObject(); console.log(req.body.id); // OK models.visits.update({ _id: req.body.id }, upsertData, { multi: false }, function(err) { if(err) { throw err; } console.log('updated visit: '+ req.body.id); res.redirect('/'); }); } }) The response is Mod on _id is not allowed. I just want to update the line such as WHERE id = id in MySQL. I didn't find the right syntax. A: Here is my solution: routes/router.js router.patch('/user/:id', userController.updateUser) exports.updateUser = async(req, res) => { const updates = Object.keys(req.body) const allowedUpdates = ['name', 'email', 'password', 'age'] const isValidOperation = updates.every((update) => allowedUpdates.includes(update)) if (!isValidOperation) { return res.status(400).send('Invalid updates!') } try { const user = await UserModel.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true }) if (!user) { return res.status(404).send() } res.status(201).send(user) } catch (error) { res.status(400).send(error) } } A: According to this question and this other one, the Mod on _id is not allowed occurs when one tries to update an object based on its id without deleting it first. I also found this github issue which tries to explain a solution. It explicitly states: Be careful to not use an existing model instance for the update clause (this won't work and can cause weird behavior like infinite loops). Also, ensure that the update clause does not have an _id property, which causes Mongo to return a "Mod on _id not allowed" error. The solution, it seems, is to do the following: var upsertData = my_visit.toObject(); console.log(req.body.id); // OK delete upsertData._id; models.visits.update({ _id: req.body.id }, upsertData, { multi: false }, function(err) { if(err) { throw err; } //... } On a side note, you can probably rewrite your route to do both the create and update without the if-else clause. update() takes an extra option upsert, which, according to the docs: upsert (boolean) whether to create the doc if it doesn't match (false)
doc_23532506
Dimension t_size = table_button.getSize(); table_button.setSize((int)t_size.getWidth(), (int) (t_size.getHeight() + 150)); Rectangle bounds = global_variables.bottom_panel.getBounds(); int y_new = (int) (bounds.getY() + 150); int x_new = (int) bounds.getX(); bounds.setLocation(x_new, y_new); global_variables.bottom_panel.setBounds(bounds); floor_plan_admin_single.table_base.setSize((int)floor_plan_admin_single.table_base.getWidth(), (int)floor_plan_admin_single.table_base.getHeight()+150); Here table_button is the button i am adding dynamically and global_variables.bottom_panel is the panel which stays below table_button and as i increase the height of table_button i am moving the bottom_panel down. floor_plan_admin_single.table_base is the jpanel added to scrollbar. even if i change the height of tat table_base panel i cant see the scrollbar in action. A: There are a few things to note when using a JScrollPane. The easiest way to initialize a JScrollPanel is by passing the panel you want to make scrollable in the constructor. JScrollPane scrollPane = new JScrollPane(panel1); Then, to set the sizes, you have to use setPreferredSize, not setSize(). button.setPreferredSize(new Dimension(120, 120)); Do not set the size on the panel given inside the constructor of JScrollPane. (ie panel1)
doc_23532507
#include <iostream> using namespace std; struct Node { char c; double d; int s; } Node; int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; cout << sizeof(char) << endl; cout << sizeof(double) << endl; cout << sizeof(int) << endl; cout << sizeof(Node) << endl; return 0; } This is the output: Hello, World! 1 8 4 24 Program ended with exit code: 0 I understand that there is a certain scheme of packing. However assuming a size of 8. should this be 1+8 +4 + padding shouldn't it be 16, however its being reported as 24. Is there a way I can find out the default value of packing? I am currently using a xcode on a mac that's not too old.
doc_23532508
For example, if my website was example.com and the index.html file was placed in example.com/test and the link was google.com then the link would go to example.com/test/google.com. How do I make it so the link goes to google.com? A: This is what the code should look like for linking to Google: <a href="http://google.com" title="Google">Google</a> Make sure that your HREF contains the complete URL if you are linking to an external site. A: You should really learn about absolute and relative paths. What you're using is a relative path. This is an absolute path on your server: <img src="/images/logo.png"> This is an url with http protocol - opens Google.com <a href="http://google.com">Google</a> This is an url without explicit protocol, it will turn into http or https based on what your page uses: <a href="//google.com">Google</a> Use one of those for what you need (typically the http one).
doc_23532509
Since this is a web based mobile app I am planning to use (HTML5,Javascript,jQuery,Ajax) Any help/tutorial on how to create or draw a map will be of great help. I personally don't have any experience drawing or using maps api. A: Google Maps JavaScript API is the way to go: Start here: https://developers.google.com/maps/documentation/javascript/tutorial Then, specifically about paths: https://developers.google.com/maps/documentation/javascript/shapes#polyline_add
doc_23532510
A: it is more than one click ... but there is a "batch build ..." option under the build menu. It is possible to select which configurations wanted and then click build.
doc_23532511
"Write a function in C++ that takes as input an array of doubles and the length of the array, and returns an array twice the length. The first half of the returned array should contain a copy of the contents of the original array. The second half of the returned array should contain the contents of the original array in reverse order." "The function should have the following prototype: double *copy_and_reverse(double *a, int length);" since im obviously new to c++ i got stuck in my solution, my code so far is: double *copy_and_reverse(double *a, int length){ double *b[length*2]; for(int i=0;i<length;i++){ *b[i]=a[i]; } for(int i=length;i<length*2;i++){ int w=length-1; *b[i]=a[w]; w--; } return *b; } int main() { double nums[2]={1.23,5.364}; double *pnums=nums; *pnums=*copy_and_reverse(pnums, 2); I think i got the core of the method correct but i'm just stuck in the syntax of using pointers, any help is appreciated and if possible a reasoning behind it so i can learn for the exam. A: There are quite many errors in your code. The major one is that you need to allocate new array of doubles. And return that array. I'd suggest compare this with your version line by line: double *copy_and_reverse(double *a, int length){ double *result = new double[length*2]; for(int i=0;i<length;i++) { result[i]=a[i]; } int r = length*2; for(int i=0; i < length;i++){ result[--r]=a[i]; } return result; } And your main() shall look like: int main() { double nums[2]={1.23,5.364}; double *pnums = copy_and_reverse(nums, 2); ... delete[] pnums; } A: You've got a few problems with this code. First double *b[length*2]; Here you're declaring an array of pointers to doubles. The array is of size length * 2, however, none of the pointers in this array are valid yet. This is probably not what you intended to do. You want an array of doubles, of size length * 2. You can't return an array in C++ but you can return a pointer to some memory that contains an array of doubles. Let's start by allocating enough memory for all those doubles double *b= new double[length * 2]; In your first for loop you can treat result as an array for(int i=0;i<length;i++){ b[i]=a[i]; } Here you're copying the values from a for each index i to be at the same index. I'll let you figure out how to fill in the reverse part for the second half of the array. You're on the right track, however you might want to think about doing it all in one loop ;) Your return statement just needs to return your variable b, as it's already a double *. return b; An important thing to remember is that you're allocating memory in this function with new. You are responsible for deleting this when you're done with it. Also, when you allocate using new and [] you have to delete using [] as well. delete [] b; you can call your function just by de-referencing the first item in your array. int main() { double nums[2]={1.23,5.364}; double *pnums = copy_and_reverse(&pnums[0], 2);//don't forget to clean up pnums afterwards! A: Ok, there are at least two problems with this: double *b[length*2]; The first problem is that you are declaring a local array (of pointers), which you will then try to return: return *b; (You're returning the wrong thing here, too, but that's another story) You can't return a pointer to a locally-allocated thing because as soon as the function returns, the locally-allocated thing will be destroyed. Instead, given that you must return a pointer to the first element of an array, you have to dynamically allocate that thing using new. Second, you can't declare an array like this using a length which s only known at runtime. But this problem will be obviated when you use new to dynamically allocate the array. I would normally say that you shouldn't be doing any of this at all, and just use a std::vector -- but clearly a requirement of this assignment is to use a dynamically allocated C-style array. (Which I take great issue with your professor on.) I would also say that the prototype: double *copy_and_reverse(double *a, int length); doesn't declare a function which takes an array, as your professor incorrectly asserts, but a function which takes a pointer to a double. That that pointer is the first element in an array doesn't magically make a an array. In short: an array and a pointer are not the same thing. These last two observations are just for your benefit. A: I assume this is not your homework and I am trying to help you out. Look at the comment of code. double *copy_and_reverse(double *a, int length) { double * b = new double[length*2]; //create a new array using new[] for(int i=0;i<length;i++){ b[i]=a[i]; //addressing element with [] } int w=length-1; //I assume this is what you want for(int i=length;i<length*2;i++){ b[i]=a[w]; w--; } return b; } int main() { double nums[2]={1.23,5.364}; double *pnums = copy_and_reverse(nums, 2); delete[] pnums; } Also noted the memory is allocated in the function, so in the main, you want to delete it by using [].
doc_23532512
First, the brief: I'm creating a web application for a car rental business. In addition to helping them organize and centralize their fleet, it will also help them collect orders directly from customers. As with most rentals, the logistics of it all can be somewhat confusing. Someone may place an order for a car today (December 12th) but actually take the car over the Christmas to New Year's period. A renter may borrow a car for just two days, and then extend the booking at the last minute. When this happens (often very frequently), the business usually has to scramble to find another one for a different customer who was scheduled to get that car the next day. Adding to that, an individual car can only be rented to one client at a time, so it can't have multiple bookings for the same period. Most answers advocate for a simple approach that looks like this: models.py class Booking(models.Model): car = models.ForeignKey(Car, ...) start_date = models.dateField(...) end_date = models.dateField(...) is_available = models.booleanField(default=True) forms.py import datetime from django import forms from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ from . import models class PlaceOrderForm(forms.Form): """Initial order forms for customers.""" start_date = forms.DateField(help_text='When do you want the car?') end_date = forms.DateField(help_text='When will you return the car?') def clean_data(self, date): data = self.cleaned_data(date) # Check that start date is not in the past if data < datetime.date.today(): raise ValidationError(_('Invalid date: Start in past.')) # Ensure that start date is not today (to avoid last_minute bookings.) if data == datetime.date.today(): raise ValidationError(_('Invalid date: Please reserve your car at least 24 hours in advance.')) return data cleaned_start_date = clean_data(start_date) cleaned_end_date = clean_data(end_date) ('_' is for ) The booking has a start_date and an end_date. When a current date is within the start_date and end_date, the car is marked as unavailable. If the boolean field is_available (not represented in forms.py above) is set to "False", the car is unavailable completely. Again, because of the unique nature of car rentals, this may be a problem. Some people book a car for six months, and others book it for two days. If someone wants a long-term rental but there's another short interlude during their expected duration, this validation would prevent them from placing the order completely! But this is a problem: Going back to the rental model, someone may be booking a car in the future. A car that's unavailable now should still be able to be reserved for a future date. Adding to that, an individual car can only be rented to one person at a time, so it can't have multiple bookings for the same period. Again, because of the unique nature of car rentals, this may be a problem. Some people book a car for six months, and others book it for two days. If someone wants a long-term rental but there's another short interlude during their expected duration, this validation would prevent them from placing the order completely! So if a conflict arises, rather than blocking the booking entirely (which, again, would be a bad UX decision), it should notify the business so they can assign another car and plan ahead. Other clients should not be able to book it for the time in which it is borrowed, but they should be able to book it for other times when it is free. So if someone places an order now for, let's say the 24-31st of December. Those days should be blocked off. However, another person should be able to book it from today to the 23rd, and from the 31st onwards. And if the person renting it should extend, it should notify the rental business so they can assign another car to the user well in advance. Possible idea to move forward The core assumption in all those answers is that the booking unavailability has to be handled in Django itself, in the backend. However, I'm building this project with REST framework, and will use a Js based front-end (currently learning Javascript for this purpose). I think that this would be better handled in a more holistic way with the in-built form validation and save functions. The workflow would go something like this: * *The User selects a car and selects the start and end dates from a drop-down calendar on the website. *The form will then check to see if the absolute basic checks (can't book a car in the past) are fine. If those work, then the order is placed and saved in the database. *If there's a scheduling conflict, the order is not blocked, but passed to the business that can assign them a different car for the period. (Generally, people don't care much for receiving particular cars--mostly the price, space and the fuel economy. Everything else is interchangeable. *Once that happens, the deposit can be collected, and the order can be set in the system. Anyhow, that's my preliminary idea that would bring together the best of all worlds and create a great experience for both the business and customer. So my question is: How could this actually be set up? What would need to be on the front-end and what would go in the back-end? I'm learning programming as I go, so this may be simple, but I've been struggling with this for a week, I would appreciate any help on this! Thanks! A: Sounds like you have two processes - the customer order and the car assignment. You need to plan out your data structure and then your process flow. This will help you get things straight before you start. Models Using (Brackets) for foreign keys, Customer_order collects things like: Customer(User) desired_start_date desired_end_date car_type - this could be many fields A car model car_type rental (many to many Rental with through table Rental) A rental model car (Car) customer_order(Customer_order) start_date end_date We have kept the rental model with its own start and end dates as the user may change their desired period but it shouldn't change the rental dates without checking if others exist in that time period for that car. So the flow should go: user passes js validation and form submitted to backend backend checks for car availability based on type and dates if available, creates rental if not available, alert user and passes to staff if a user changes a rental period (via an edit screen for existing customer_orders) backend checks for same car availability based on existing rentals if not available, alert user and pass to staff You'd also create a staff only view, that lists customer_orders that can't be matched (without rental models) along with cars of the requested type that don't have rentals for that period. Seeing as you have that view, it strikes me your backend process could use something similar to also look for and assign a different car of the same type automatically if you wanted to extend the availability check process, notifying staff it has occurred, while only referring back to staff if that type of car is unavailable. Actually programming all this is left as an exercise for the reader.
doc_23532513
The problem I'm having is that the filteredOptions in my code doesn't get populated until after the user starts typing. I need the list to show up before the user starts typing. I believe this is because they are using valueChanges, but I'm not quite sure how to make this piece of code work for my case. I need this pipe and map functionality, but I need the list to be loaded before the user changes the value of the Mat Autocomplete, not after. Code taken from documentation link that I have more or less mirrored in my own code: <form class="example-form"> <mat-form-field class="example-full-width"> <input type="text" placeholder="Assignee" aria-label="Assignee" matInput [formControl]="myControl" [matAutocomplete]="auto"> <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn"> <mat-option *ngFor="let option of filteredOptions | async" [value]="option"> {{ option.name }} </mat-option> </mat-autocomplete> </mat-form-field> </form> filteredOptions: Observable<User[]>; ngOnInit() { this.filteredOptions = this.myControl.valueChanges .pipe( startWith<string | User>(''), map(value => typeof value === 'string' ? value : value.name), map(name => name ? this.filter(name) : this.categoryList.slice()) ); } filter(name: string): User[] { return this.categoryList.filter(option => option.name.toLowerCase().indexOf(name.toLowerCase()) === 0); } displayFn(user?: User): string | undefined { return user ? user.name : undefined; } this.categoryList = Object.entries(data.category).map(([key, value]) => ({ key, value })); I was thinking I should probably be using some sort of subscribe, but I can't figure out the syntax to use them with pipe and map. A: I believe that all you need to do is startWith the form's value: ngOnInit() { this.filteredOptions = this.myControl.valueChanges .pipe( startWith(this.myControl.value as string), // typing the control's value map(name => name ? this.filter(name) : this.categoryList.slice()) ); } A note that using a class method inside of an operator is a bit of an anti-pattern. It's generally important to keep things pure when using the Observable pattern - especially with more complicated logic. To fix that, you'd probably want to make your categoryList an Observable, and your filter a pure function (bring it outside of your component, and give it another param so you can pass in the categoryList). function filter(name: string, categoryList: User[]): User[] { categoryList.filter(option => option.name.toLowerCase().indexOf(name.toLowerCase()) === 0); } Then you can do like so: ngOnInit() { this.filteredOptions = combineLatest( this.myControl.valueChanges.pipe(startWith(this.myControl.value as string)), this.categoryList ).pipe( map(([searchTerm, categoryList]) => searchTerm ? filter(searchTerm, categoryList) : [ ...categoryList ]) ); } A: Can't believe it was as simple as this, but this answer helped resolve everything. All I had to do was move my code outside of ngOnInit. how to show autocomplete options on focus My filteredOptions was not waiting for the API data to come through since I had put this inside ngOnInit. Once I moved it inside the subscribe of my api call, everything worked smoothly.
doc_23532514
I'm using the code below to attempt this -- jQuery('div.amfinder-horizontal td:nth-child(5) select').change(function () { jQuery("div.amfinder-horizontal td:nth-child(7) select").append('<option value="0">Position</option>'); jQuery(this).parent().addClass('active'); jQuery(".popover").hide(); jQuery("#popover6").show(); jQuery("div.amfinder-horizontal td:nth-child(6) select option").each(function() { this.selected = (this.text == "Windshield Wiper Blade"); }); jQuery("div.amfinder-horizontal td:nth-child(6) select option").change(); // The following two lines are commands for a Prototype script, in place to simulate the change event $('finder-4023--20454').simulate('click'); // This is the ID of the select element ( it is the same as div.amfinder-horizontal td:nth-child(6) select ) $('finder-4023--20454').simulate('change'); // This is the ID of the select element ( it is the same as div.amfinder-horizontal td:nth-child(6) select ) console.log('Changed!'); }); I believe what is happening is that the AJAX population occurs and then the change event tries to trigger before the AJAX function finishes. The AJAX is in a Prototype script and I'm not comfortable changing that. Instead, I'm wondering if I could simply delay the change and simulate events for a second or so that the AJAX population can finish. Please help out. :-) A: Try replacing the first line with this: jQuery(document).on('change', 'div.amfinder-horizontal td:nth-child(5) select',function () { This will work for the elements that are added even after the code was called, which is something you must have when you render parts of the page with AJAX. Read about delegated events here: http://api.jquery.com/on/
doc_23532515
import java.util.regex.*; class Demo{ public static void main(String args[]) { String name = "abc0x12bxab0X123dpabcq0x3423arcbae0xgfaaagrbcc"; Pattern p = Pattern.compile("[a-c][abc][bca]"); Matcher m = p.matcher(name); while(m.find()) { System.out.println(m.start()+"\t"+m.group()); } } } OUTPUT : 0 abc 18 abc 30 cba 38 aaa 43 bcc A: Lets analize: "[a-c][abc][bca]" This pattern looks for groups of 3 letters each. [a-c] means that first letter has to be between a and c so it can be either a,b or c [abc] means that second letter has to be one of following letters a,b or c co basicly [a-c] [bca] meanst that third letter has to be either b or c or a, order rather doesnt matter here. Everything what you needs to know is in official java regex tutorial http://docs.oracle.com/javase/tutorial/essential/regex/ A: It simply searches the String for a match according to the rules specified by "[a-c][abc][bca]" 0 abc --> At position 0, there is [abc]. 18 abc --> Exact same thing but at position 18. 30 cba --> At position 30, there is a group of a, b and c (specified by [a-c]) 38 aaa --> same as 30 43 bcc --> same as 30 Notice, the counting starts at 0. So the first letter is at position 0, the second ist at position 1 an so on... For further information about Regex and it's use see: Oracle Tutorial for Regex A: This pattern basically matches 3-character words where each letter is either a,b, or c. It then prints out each matching 3-char sequence along with the index at which it was found. Hope that helps. A: It is printing out the place in the string, starting with 0 instead of 1, where the occurrence of each match occurs. That is the first match, "abc" happens in position 0. the second match "abc" happens at string position 18. essentially it is matching any 3 character string that contains an 'a', 'b', and 'c'. the pattern could be written as "[a-c]{3}" and you should get the same result. A: Lets look at your sourcecode, because the regexp itself was already well explained in the other answers. //compiles a regexp pattern, kind of make it useable Pattern p = Pattern.compile("[a-c][abc][bca]"); //creates a matcher for your regexp pattern. This one is used to find this regexp pattern //in your actual string name. Matcher m = p.matcher(name); //loop while the matcher finds a next substring in name that matches your pattern while(m.find()) { //print out the index of the found substring and the substring itself System.out.println(m.start()+"\t"+m.group()); }
doc_23532516
I have an HTML5 element where I want both the value and the max driven by the VM. I have tried this on a couple browsers, and it seems that attribute values for MAX and VALUE are fetched at INIT (HTML Layout), but are not later updated. Is this something that can be driven dynamically? My fallback will have to be JQuery. <div class="Part"> <progress id="ProgressBar" data-bind="attr: { max: TotalSize, value: TileCount }"></progress>100% </div> A: In Angular, following seems to be working as expected (tested in Chrome+FF): <progress value="{{ TileCount }}" max="{{ TotalSize }}"></progress>
doc_23532517
here is my mapping elasticsearch : "mappings": { "myparent": { }, "mychild": { "_parent": { "type": "myparent" }, "properties": { "attr1": { "type": "string" }, "attr2": { "type": "date", "format": "dateOptionalTime" }, "attr3": { "type": "string" } } } } here is how i manualy insert data in "mychild" type : POST /myindex/mychild/1?parent=[IDParent] { "attr1" : "02020", "attr2" : "2016-10-10", "attr3" : "toto" } i didn't find how to spécify the parentID. Is there any way of doing it using PutElasticsearch other than using the processor InvokHTTP. Thank you. A: This is not possible today (NiFi 1.1.0 and below) with the PutElasticsearch processors, so InvokeHttp is your best option for now. I have written NIFI-3284 to cover this improvement.
doc_23532518
SELECT * FROM table1 ORDER BY IF(duedate = '0000-00-00 00:00:00', datetime_added, duedate) ASC its ordering ASC but it puts all rows that have 0000-00-00 00:00:00 at the top but these should be at the bottom How can I order my query in the following order: duedate ASC datetime_added ASC sequence DESC A: Try this: SELECT * from table1 ORDER BY IF(duedate = '0000-00-00 00:00:00', '9999-12-31', duedate), datetime_added ASC, sequence DESC A: you can do this by: SELECT * from table1 ORDER BY duedate ASC, duedate = '0000-00-00 00:00:00', datetime_added ASC, sequence DESC
doc_23532519
Now some background. I'm creating an ASP.Net MVC 5 project, I've to connect to WCF web services provided by Epicor (an ERP solution). My project, the ERP and its web services are all hosted on an internal IIS instance. The services are exposed using both BasicHTTP and NetTCP protocols. The application pool on which the web service and ERP are hosted uses identity. One of the web service is called Company.svc and it is exposed as: <wsdl:service name="CompanySvcFacade"> <wsdl:port name="BasicHttpBinding_CompanySvcContract" binding="tns:BasicHttpBinding_CompanySvcContract"> <soap:address location="http://pilotserver/ERP100700/Ice/BO/Company.svc"/> </wsdl:port> <wsdl:port name="CustomBinding_CompanySvcContract" binding="tns:CustomBinding_CompanySvcContract"> <soap12:address location="net.tcp://pilotserver/ERP100700/Ice/BO/Company.svc"/> <wsa10:EndpointReference> <wsa10:Address>net.tcp://pilotserver/ERP100700/Ice/BO/Company.svc</wsa10:Address> <Identity xmlns="http://schemas.xmlsoap.org/ws/2006/02/addressingidentity"> <Upn>pilotserver\Administrator</Upn> </Identity> </wsa10:EndpointReference> </wsdl:port> </wsdl:service> In my project, my web.config has the following: <system.serviceModel> <bindings> <basicHttpBinding> <binding name="BasicHttpBinding_CompanySvcContract" /> </basicHttpBinding> <customBinding> <binding name="CustomBinding_CompanySvcContract"> <security defaultAlgorithmSuite="Default" authenticationMode="UserNameOverTransport" requireDerivedKeys="true" includeTimestamp="true" messageSecurityVersion="WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10"> <localClientSettings detectReplays="false" /> <localServiceSettings detectReplays="false" /> </security> <textMessageEncoding /> <windowsStreamSecurity /> <tcpTransport /> </binding> </customBinding> </bindings> <client> <endpoint address="http://pilotserver/ERP100700/Ice/BO/Company.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_CompanySvcContract" contract="CompanyService.CompanySvcContract" name="BasicHttpBinding_CompanySvcContract" /> <endpoint address="net.tcp://pilotserver/ERP100700/Ice/BO/Company.svc" binding="customBinding" bindingConfiguration="CustomBinding_CompanySvcContract" contract="CompanyService.CompanySvcContract" name="CustomBinding_CompanySvcContract"> <identity> <userPrincipalName value="pilotserver\Administrator" /> </identity> </endpoint> </client> And I'm trying to consume the web service in the client using the following code: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Dispatcher; using EpicorTestApp.CompanyService; using NLog; namespace EpicorTestApp.Controllers { public class HomeController : Controller { CompanySvcContractClient CompanyService = new CompanySvcContractClient("CustomBinding_CompanySvcContract"); //CompanySvcContractClient CompanyService = new CompanySvcContractClient("BasicHttpBinding_CompanySvcContract"); private Logger logger = LogManager.GetCurrentClassLogger(); public ActionResult Index() { ViewBag.Message = "Welcome to ASP.NET MVC!"; bool morePages = false; CompanyService.ClientCredentials.UserName.UserName = "Administrator"; CompanyService.ClientCredentials.UserName.UserName = "myPassword"; CompanyListTableset companyList = CompanyService.GetList("", 0, 0, out morePages); CompanyListTable companies = companyList.CompanyList; foreach (CompanyListRow companyListRow in companies) { logger.Info("Company: " + companyListRow.Company); } return View(); } } } For the client binding, I've tried both BasicHttp and NetTCP (as CustomBinding), both resulting in some errors. When I create a BasicHttp binding, I use the following service reference configuration: and upon running this configuration, I receive an error for "Access is denied. Exception Details: System.ServiceModel.Security.SecurityAccessDeniedException: Access is denied." And for nettcp binding, when I try to create a service reference, I receive an error with the message "The URI prefix is not recognized. Metadata contains a reference that cannot be resolved: net.tcp://localhost/ERP100700/Ice/BO/Company.svc'. I've tried using both localhost and pilotserver in the url. I've tried running the application both in debug mode (ISS-Express) and publishing it to IIS, but same result. What am I doing wrong and how can I resolve this issue? A: In the HomeController, it would seem that this CompanyService.ClientCredentials.UserName.UserName = "Administrator"; CompanyService.ClientCredentials.UserName.UserName = "myPassword"; Should be something like this CompanyService.ClientCredentials.UserName.UserName = "Administrator"; CompanyService.ClientCredentials.UserName.Password = "myPassword You are passing the UserName twice in the code as you present it. A: The reason why I was getting all these errors was that in Web.config for Epicor's web services (inside IIS), https scheme for BasicHTTP was disabled/ comment out. I had to add the following to make my application work. <remove scheme="https" /> <add scheme="https" binding="basicHttpBinding" bindingConfiguration="BasicHttp"/> This is the default behavior in Epicor.
doc_23532520
A: The ELKI ResultWriter will write the outliers to a file in decreasing outlierness (if the method is implemented with the appropriate metadata to allow correct sorting). As for ABOD, please not that the implementation you are using (ELKI 0.6.0~beta2 and before) is actually FastABOD, unless you set abod.k to the data set size. The 0.6.0 release will have separate classes for ABOD, FastABOD and LB-ABOD. But since ABOD scales O(n^3) it will be only usable for small data sets! A: You can see the result if you use the cmd (command line) for running the algorithm like this java -cp <<path>> -algorithm outlier.ABOD -dbc.in data.txt -out myresults/ABOD , on <<path>> that containd elki.jar/elki.jar de.lmu.ifi.dbs.elki.application.KDDCLIApplication
doc_23532521
A: your problem is in the HTML, not in the css, you have two extra closing divs at the bottom for each 'item_container span3' <form method='post' name='form124' id='form124' action='/app/site/backend/additemtocart.nl?c=3563610&amp;n=1' onsubmit="return checkmandatory124();"> <div class="item_container span3"> <a href="/s.nl/c.3563610/it.A/id.124/.f" class='lnk13b-blackOff'; onMouseover="this.className='lnk13b-blackOff'; return true;" onMouseout="this.className='lnk13b-blackOff'; return true;">iPhone 5</a> <div class="heading_price"> <span class="price">Price: <span id=itemprice124>?.?.?2?444?00 &#150; 3,649.00 SAR</span> </span> </div> <div class="itemlist-img"> <a href="/s.nl/c.3563610/it.A/id.124/.f"> <a href='/s.nl/c.3563610/it.A/id.124/.f'> <img src='/core/media/media.nl?id=959&amp;c=3563610&amp;h=b417dd449e62d8ecd270&amp;resizeid=-1&amp;resizeh=214&amp;resizew=160' border='0' alt='Item Images13.jpg' title='Item Images13.jpg'></a></a> </div><div><p class="item_desc">Sed ut perspiciatis unde omnis iste natus error sit voluptatem</p></div> <div class="cart_details"><a href="/s.nl/c.3563610/it.A/id.124/.f" class="view_item" onMouseover="this.className='view_item'; return true;" onMouseout="this.className='view_item'; return true;"> VIEW DETAILS</a> <span class="cart_btn"><a href="#inline_content" class='inline'>ADD TO CART</a></span> </div></div> <--- this ---> **</div></div>** <------------> </form>
doc_23532522
Newman version: 3.9.4 --disable-unicode Specify whether or not to force the unicode disable option. When supplied, all symbols in the output will be replaced by their plain text equivalents. command: newman run "ACSF_PE.postman_collection.json" --global-var "HEROKU_APP_NAME=myapp" --global-var "HEROKU_API_TOKEN=********" -r cli,junit,text --disable-unicode --reporter-junit-export Test-Results.xml --reporter-text-export Test-Results.txt First I had the command withut --disable-unicode parameter, but I have added the parameter and the output does not change, it's exactly the same... output: ... 2018-05-30T10:32:19.4940350Z [0mnewman[0m 2018-05-30T10:32:19.4940350Z 2018-05-30T10:32:19.4940350Z [0mAccenture Cloud TPM[0m 2018-05-30T10:32:19.5252847Z 2018-05-30T10:32:19.5252847Z  [0mPre-collection Requests[0m 2018-05-30T10:32:19.5252847Z  [0mRetrieve Credentials[0m 2018-05-30T10:32:20.1443464Z [90mGET[39m [90mhttps://api.heroku.com/apps/cas-dev-pipe-app/config-vars[39m [90m[200 OK, 2.55KB, 570ms][39m 2018-05-30T10:32:20.1933674Z [32m  [39m [90mStatus code is 200[39m 2018-05-30T10:32:20.1933674Z [32m  [39m [90mRequired Config Vars[39m 2018-05-30T10:32:20.2089943Z [32m  [39m [90mRequired credentials exist[39m 2018-05-30T10:32:20.2402436Z 2018-05-30T10:32:20.2402436Z  [0mAuthorize: Login & Get JWT (HS256)[0m 2018-05-30T10:32:20.4485595Z [90mPOST[39m [90mhttps://cas-dev-pipe-app.herokuapp.com/auth/login[39m [90m[404 Not Found, 431B, 160ms][39m 2018-05-30T10:32:20.4495595Z {"cursor":{"ref":"eeb9be61-2bea-4b89-9045-7218f94bdd80","length":45,"cycles":1,"position":1,"iteration":0,"httpRequestId":"8f6b275f-da45-4965-82cc-1534b21f70dd"},"response":{"id":"5a4def44-9f82-41f3-b192-aafa1f6a8f6c","status":"Not Found","code":404,"header":[{"key":"Server","value":"Cowboy"},{"key":"Connection","value":"keep-alive"},{"key":"Content-Security-Policy","value":"default-src 'self'"},{"key":"X-Content-Type-Options","value":"nosniff"},{"key":"Content-Type","value":"text/html; charset=utf-8"},{"key":"Content-Length","value":"150"},{"key":"Vary","value":"Accept-Encoding"},{"key":"Date","value":"Wed, 30 May 2018 10:32:20 GMT"},{"key":"Via","value":"1.1 vegur"}],"stream":{"type":"Buffer","data":[60,33,68,79,67,84,89,80,69,32,104,116,109,108,62,10,60,104,116,109,108,32,108,97,110,103,61,34,101,110,34,62,10,60,104,101,97,100,62,10,60,109,101,116,97,32,99,104,97,114,115,101,116,61,34,117,116,102,45,56,34,62,10,60,116,105,116,108,101,62,69,114,114,111,114,60,47,116,105,116,108,101,62,10,60,47,104,101,97,100,62,10,60,98,111,100,121,62,10,60,112,114,101,62,67,97,110,110,111,116,32,80,79,83,84,32,47,97,117,116,104,47,108,111,103,105,110,60,47,112,114,101,62,10,60,47,98,111,100,121,62,10,60,47,104,116,109,108,62,10]},"cookie":[],"responseTime":160,"responseSize":150},"request":{"description":{"content":"","type":"text/plain"},"url":{"protocol":"https","path":["auth","login"],"host":["cas-dev-pipe-app","herokuapp","com"],"query":[],"variable":[]},"header":[{"key":"Content-Type","value":"application/json"},{"key":"User-Agent","value":"PostmanRuntime/7.1.6"},{"key":"Accept","value":"*/*"},{"key":"Host","value":"cas-dev-pipe-app.herokuapp.com"},{"key":"accept-encoding","value":"gzip, deflate"},{"key":"content-length","value":117}],"method":"POST","body":{"mode":"raw","raw":"{\n\t\"username\" : \"ub1igm55lrs849\",\n\t\"password\" : \"p220b577c3cd5908fa061b6469520c391b70e11bf0d56d0096d29e291b4e1681d\"\n}"},"auth":{"type":"noauth","noauth":[]}},"item":{"id":"5027788f-fe2a-4c67-b44d-aad0d95710ac","name":"Authorize: Login & Get JWT (HS256)","request":{"description":{"content":"","type":"text/plain"},"url":{"path":["auth","login"],"host":["{{ACSF_PE_URL}}"],"query":[],"variable":[]},"header":[{"key":"Content-Type","value":"application/json"}],"method":"POST","body":{"mode":"raw","raw":"{\n\t\"username\" : \"{{DB_username}}\",\n\t\"password\" : \"{{DB_password}}\"\n}"},"auth":{"type":"noauth","noauth":[]}},"response":[],"event":[{"listen":"test","script":{"id":"b1c3e65e-0032-484e-b129-1d82b9cc51a7","type":"text/javascript","exec":["","//Code","pm.test(\"Status code is 200\", function () {"," pm.response.to.have.status(200);","});","","//Body","pm.test(\"Body has required attributes\", function () {"," pm.response.to.have.jsonBody('token');"," pm.response.to.have.jsonBody('user.role', pm.variables.get('DB_username'));","});","","","//Post scripts","// Save the token to a Postman environment variable","postman.setEnvironmentVariable(\"JWT_POSTGRAPHILE\", pm.response.json().token);","",""]}},{"listen":"prerequest","script":{"id":"f77d57be-6e67-47d9-a1d3-d0f468638bb7","type":"text/javascript","exec":[""],"_lastExecutionId":"1ce3fc83-4fa7-4c7d-94e4-9b15be2423a9"}}]},"cookies":[]} 2018-05-30T10:32:20.4627101Z [31m[1m 1.[22m[39m [31m[1mStatus code is 200[22m[39m 2018-05-30T10:32:20.4627101Z [31m[1m 2.[22m[39m [31m[1mBody has required attributes[22m[39m 2018-05-30T10:32:20.4783328Z [31m[1m 3 JSONError in test-script[22m[39m 2018-05-30T10:32:20.5095846Z 2018-05-30T10:32:20.5095846Z  [0mSTD: Populate Data-Variables[0m 2018-05-30T10:32:22.0723737Z [90mPOST[39m [90mhttp://localhost:5000/graphql[39m {"code":"ECONNREFUSED","errno":"ECONNREFUSED","syscall":"connect","address":"127.0.0.1","port":5000} 2018-05-30T10:32:22.0723737Z {"cursor":{"ref":"a5fc877c-781e-42fd-823b-955fb1a3964a","length":45,"cycles":1,"position":2,"iteration":0,"httpRequestId":"087f0c67-215d-4de4-92d7-dfcb50f4d2ad"},"request":{"description":{"content":"","type":"text/plain"},"url":{"protocol":"http","port":"5000","path":["graphql"],"host":["localhost"],"query":[],"variable":[]},"header":[{"key":"Content-Type","value":"application/json"},{"key":"Authorization","value":"Bearer {{JWT_POSTGRAPHILE}}","system":true}],"method":"POST","body":{"mode":"raw","raw":"{\r\n\t\"query\": \"{ allProductCs{nodes{externalidC sfid}} allAccountExtensionCs{nodes{externalidC sfid}} allKpiSetCs{nodes{name sfid}} allSalesOrganizationCs{nodes{name sfid}}}\"\r\n}"}},"item":{"id":"8d856d77-3204-4b22-9000-702ecc0ac059","name":"STD: Populate Data-Variables","request":{"description":{"content":"","type":"text/plain"},"url":{"protocol":"http","port":"5000","path":["graphql"],"host":["localhost"],"query":[],"variable":[]},"header":[{"key":"Content-Type","value":"application/json"}],"method":"POST","body":{"mode":"raw","raw":"{\r\n\t\"query\": \"{ allProductCs{nodes{externalidC sfid}} allAccountExtensionCs{nodes{externalidC sfid}} allKpiSetCs{nodes{name sfid}} allSalesOrganizationCs{nodes{name sfid}}}\"\r\n}"}},"response":[],"event":[{"listen":"test","script":{"id":"d5af99b0-e755-41d4-aa9d-f0c8bdfb7beb","type":"text/javascript","exec":["","pm.test(\"Status code is 200\", function () {"," pm.response.to.have.status(200);","});","","var response = pm.response.json();","","//Body","pm.test(\"Body has required attributes\", function () {"," pm.response.to.have.jsonBody('data.allProductCs.nodes');"," pm.response.to.have.jsonBody('data.allAccountExtensionCs.nodes');"," pm.response.to.have.jsonBody('data.allKpiSetCs.nodes');"," pm.response.to.have.jsonBody('data.allSalesOrganizationCs.nodes');","});","","// product__c","Object.getOwnPropertyNames(pm.environment.toObject()).filter("," function(d){"," return /product__c./.test(d);"," }).forEach(function(key) {"," pm.environment.unset(key);"," });","","response.data.allProductCs.nodes.forEach(function(node) {"," pm.environment.set('product__c.' + node.externalidC, node.sfid);","});","","","// account_extension__c","Object.getOwnPropertyNames(pm.environment.toObject()).filter("," function(d){"," return /account_extension__c./.test(d);"," }).forEach(function(key) {"," pm.environment.unset(key);"," });","response.data.allAccountExtensionCs.nodes.forEach(function(node) {"," pm.environment.set('account_extension__c.' + node.externalidC, node.sfid);","});","","// kpi_set__c","Object.getOwnPropertyNames(pm.environment.toObject()).filter("," function(d){"," return /kpi_set__c./.test(d);"," }).forEach(function(key) {"," pm.environment.unset(key);"," });","response.data.allKpiSetCs.nodes.forEach(function(node) {"," pm.environment.set('kpi_set__c.' + node.externalidC, node.sfid);","});","","// sales_organization__c","Object.getOwnPropertyNames(pm.environment.toObject()).filter("," function(d){"," return /sales_organization__c./.test(d);"," }).forEach(function(key) {"," pm.environment.unset(key);"," });","response.data.allSalesOrganizationCs.nodes.forEach(function(node) {"," pm.environment.set('sales_organization__c.' + node.externalidC, node.sfid);","});","","postman.setNextRequest(null);"]}}]}} 2018-05-30T10:32:22.0879992Z [31m[1m 5.[22m[39m [31m[1mStatus code is 200[22m[39m 2018-05-30T10:32:22.0879992Z [31m[1m 6 JSONError in test-script[22m[39m ... NOTE: output unicode chars are not shown when I save this post A: Solution: add parameter --no-color A: Setting --color off worked in my case.
doc_23532523
ERP-HM       modulo-nfe             assinador-nfe             importador-nfe             compositor-nfe             marshaller-nfe       persistencia             persistencia-banco             persistencia-venda             persistencia-cadastro             persistencia-nfe             persistencia-erp             persistencia-pagamento-recebimento             persistencia-estoque             persistencia-utilidades       modulos-web             banco-web             configuracao-web             seguranca-web             cadastro-web             erp-web **             pagamento-recebimento-web             componentes-web             estoque-web             venda-web       utilidades       gerador-relatorios The names in bold are just pom projects, the normals are the projects with code... The project erp-web is the war project. I've configured the JRebel plugin in ERP-HM project this way: <plugin> <groupId>org.zeroturnaround</groupId> <artifactId>jrebel-maven-plugin</artifactId> <version>1.1.3</version> <configuration> <packaging>war</packaging> <web> <resources> <resource> </resource> </resources> </web> </configuration> <executions> <execution> <id>generate-rebel-xml</id> <phase>process-resources</phase> <goals> <goal>generate</goal> </goals> </execution> </executions> </plugin> In IntelliJ I've configured the project like JRebel wizard tell: EDITED: added jrebel log -------- HEADER -------- VERSION 2 JVM_ID 43ce9d1ce623bd1d7995a6d2c715000b JVM_STARTED 1337341646006 LOG_STARTED 1337341646178 -------- EOF HEADER -------- [2012-05-18 08:47:26.187] Rebel properties loaded from /home/hudson/.IntelliJIdea11/config/plugins/jr-ide-idea/lib/jrebel/conf/jrebel.properties: rebel.env.ide=intellij11 rebel.env.ide_server_start=true rebel.env.java_version=java16 rebel.env.maven=true rebel.env.operating_system=unix rebel.env.server=glassfish rebel.jasper_plugin=false rebel.jboss_plugin=false rebel.log=true rebel.properties.version=2 rebel.stats.time=146 rebel.weblogic_plugin=false rebel.websphere_plugin=false [2012-05-18 08:47:26.196] Found a license file: /home/hudson/.jrebel/jrebel.lic [2012-05-18 08:47:26.271] License information: {uid=ffc12cd3-d035-4576-871d-0e92fd9c38e5, Name=Hudson Assumpção, limited=true, GeneratedOn=Tue May 15 14:36:55 BRT 2012, Email=brevleq@gmail.com, Seats=1, Product=JRebel, limitedFrom=Sun May 13 14:36:55 BRT 2012, override=false, Organization=Gep, limitedUntil=Thu Jun 14 14:36:55 BRT 2012} [2012-05-18 08:47:26.282] Now: Fri May 18 08:47:26 BRT 2012 Sun May 13 14:36:55 BRT 2012 Thu Jun 14 14:36:55 BRT 2012 [2012-05-18 08:47:26.282] JRebel 4.6.2 (201205021440) [2012-05-18 08:47:26.283] (c) Copyright ZeroTurnaround OU, Estonia, Tartu. [2012-05-18 08:47:26.283] [2012-05-18 08:47:26.290] Over the last 1 days JRebel prevented [2012-05-18 08:47:26.290] at least 0 redeploys/restarts saving you about 0 hours. [2012-05-18 08:47:26.290] [2012-05-18 08:47:26.291] This product is licensed to Hudson Assumpção (Gep) [2012-05-18 08:47:26.298] until June 14, 2012 [2012-05-18 08:47:26.298] [2012-05-18 08:47:26.299] ************************************************************* [2012-05-18 08:47:26.299] Your license is about to EXPIRE! [2012-05-18 08:47:26.300] ************************************************************* [2012-05-18 08:47:26.300] [2012-05-18 08:47:26.301] This license will expire in 27 days and JRebel will [2012-05-18 08:47:26.301] stop working after that. Renew your license at: [2012-05-18 08:47:26.301] http://sales.zeroturnaround.com/?1339695415 [2012-05-18 08:47:26.302] JRebel is running with the following internal licensing configuration: [2012-05-18 08:47:26.302] License valid? true [2012-05-18 08:47:26.302] License flags: [none] [2012-05-18 08:47:26.303] License type: LIMITED unfortunately JRebel isn't working cause when I change code and refresh browser nothing happens... A: I removed maven plugin and added this rebel.xml in the resources folder of my web application: <classpath> <dir name="/home/hudson/projetos/ERP-HM/modulos-web/erp-web/target/erp-web-0.1.0/WEB-INF/classes/"> <include name="com/hrgi/**"/> </dir> <jarset dir="/home/hudson/projetos/ERP-HM/modulos-web/erp-web/target/erp-web-0.1.0/WEB-INF/lib"> <include name="gerador-relatorios*.jar"/> <include name="assinador-nfe*.jar"/> <include name="compositor-nfe*.jar"/> <include name="importador-nfe*.jar"/> <include name="marshaller-nfe*.jar"/> <include name="banco-web*.jar"/> <include name="cadastro-web*.jar"/> <include name="componentes-web*.jar"/> <include name="configuracao-web*.jar"/> <include name="estoque-web*.jar"/> <include name="pagamento-recebimento-web*.jar"/> <include name="seguranca-web*.jar"/> <include name="venda-web*.jar"/> <include name="persistencia-banco*.jar"/> <include name="persistencia-cadastro*.jar"/> <include name="persistencia-erp*.jar"/> <include name="persistencia-estoque*.jar"/> <include name="persistencia-nfe*.jar"/> <include name="persistencia-pagamento-recebimento*.jar"/> <include name="persistencia-utilidades*.jar"/> <include name="persistencia-venda*.jar"/> <include name="utilidades*.jar"/> </jarset> </classpath> <web> <link target="/"> <dir name="/home/hudson/projetos/ERP-HM/modulos-web/erp-web/target/erp-web-0.1.0"/> </link> </web> The jars included here are part of the complete maven project. Now JRebel is working fine... A: Do you setart it from "Run with JRebel" button or from normal "Run" button? You have to logging enabled - send the logs to support and tell which class did you try to change
doc_23532524
This is simple PHP script $url = 'https://appext20.dos.ny.gov/corp_public/CORPSEARCH.SELECT_ENTITY'; $fields = array( 'p_entity_name' => urlencode('AAA'), 'p_name_type' => urlencode('A'), 'p_search_type' => urlencode('BEGINS') ); //url-ify the data for the POST foreach ($fields as $key => $value) { $fields_string .= $key . '=' . $value . '&'; } $fields_string = rtrim($fields_string, '&'); //open connection $ch = curl_init(); //set the url, number of POST vars, POST data curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_POST, count($fields)); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string); //execute post $result = curl_exec($ch); print curl_error($ch) . '<br>'; print curl_getinfo($ch, CURLINFO_HTTP_CODE) . '<br>'; print $result; It works fine only if CURLOPT_SSL_VERIFYPEER is false. It returns empty response if we enable CURLOPT_SSL_VERIFYPEER or if use http instead of https. But, I have to do this same project in Python Scrapy, here is same code in Scrapy. from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector from scrapy.http.request import Request import urllib from appext20.items import Appext20Item class Appext20Spider(CrawlSpider): name = "appext20" allowed_domains = ["appext20.dos.ny.gov"] DOWNLOAD_HANDLERS = { 'https': 'my.custom.downloader.handler.https.HttpsDownloaderIgnoreCNError',} def start_requests(self): payload = {"p_entity_name": 'AMEB', "p_name_type": 'A', 'p_search_type':'BEGINS'} url = 'https://appext20.dos.ny.gov/corp_public/CORPSEARCH.SELECT_ENTITY' yield Request(url, self.parse_data, method="POST", body=urllib.urlencode(payload)) def parse_data(self, response): print('here is repos') print response It returns empty response. it needs to be disabled SSL Verification. Please pardon my lack of knowledge in Python Scrapy, I have searched a lot about it but didn't find any solution. A: I would recommend having a look at this page: http://doc.scrapy.org/en/1.0/topics/settings.html it would appear that you can alter the way that the module behaves and change settings on various handlers. I also believe this is a duplicate question from: Disable SSL certificate verification in Scrapy HTHs Thanks, //P A: This code worked for me from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector from scrapy.http import FormRequest import urllib from appext20.items import Appext20Item from scrapy.selector import HtmlXPathSelector class Appext20Spider(CrawlSpider): name = "appext20" allowed_domains = ["appext20.dos.ny.gov"] payload = {"p_entity_name": 'AME', "p_name_type": 'A', 'p_search_type':'BEGINS'} def start_requests(self): url = 'https://appext20.dos.ny.gov/corp_public/CORPSEARCH.SELECT_ENTITY' return [ FormRequest(url, formdata= self.payload, callback=self.parse_data) ] def parse_data(self, response): print('here is response') questions = HtmlXPathSelector(response).xpath("//td[@headers='c1']") # print questions all_links = [] for tr in questions: temp_dict = {} temp_dict['link'] = tr.xpath('a/@href').extract() temp_dict['title'] = tr.xpath('a/text()').extract() all_links.extend([temp_dict]) print (all_links)
doc_23532525
# Dict containing config config = { [...] "source_dir": "/path/to/source" "build_dir": "/path/to/build" [...] } # Run a local dev server def create_server(): os.chdir(config["build_dir"]) httpd = HTTPServer(("", 8000), SimpleHTTPRequestHandler) httpd.serve_forever() def dev(): class DevServer(FileSystemEventHandler): p = None def start_server(self): if self.p: self.stop_server() build() print("Starting server...") self.p = Process(target=create_server) self.p.start() def stop_server(self): if self.p: print("Stopping server...") self.p.terminate() def on_any_event(self, event): if event.is_directory: return None else: self.stop_server() build() self.start_server() devserver = DevServer() devserver.start_server() observer = Observer() observer.schedule(devserver, config["source_dir"], recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() Whenever I make a change to an existing source file, the stop-build-start runs four times. I changed the the on_any_event function to just print the events to try and get a sense of why and this is what I got: <FileCreatedEvent: event_type=created, src_path='/path/to/source/file.type', is_directory=False> <DirModifiedEvent: event_type=modified, src_path='/path/to/source', is_directory=True> <FileDeletedEvent: event_type=deleted, src_path='/path/to/source/file.type', is_directory=False> <DirModifiedEvent: event_type=modified, src_path='/path/to/source', is_directory=True> (I modified the paths above for brevity, but they are the actual paths when running the code.) How would I make this work as expected? I'd also like to understand why saving a single existing file is emitting four events and why the two file events are for creation and deletion of a file, when what I did was save (modify) a file?
doc_23532526
Id place expiry_date 10 xyz 2022-09-12 Table 2 - expiry_date is the new column created in table 2. Need to fetch expiry date from table 1 where T1_id (in table 2) matches id (in table 1) Oid userid expiry_date T1_id 2 123 10 How to fetch expiry date (table 1 and fill the new column in table 2) only if the T1_id and Id(table 1) matches Trying insert into (sql) statements Joins used Join table1.Id on table2.T1_id A: Insert statements won't allow you to change values from an existing table, they only allow you to add brand new rows to a table. In your case you may want to use an UPDATE statement. In order to get matches between the two tables, you can apply a JOIN operation within the UPDATE statement, using the condition you pointed in your post description. UPDATE tab2 INNER JOIN tab1 ON tab1.Id = tab2.T1_id SET tab2.expiry_date = tab1.expiry_date; Check the demo here.
doc_23532527
A: You can use the .toFixed method: var n = 106.72; console.log(n.toFixed(2)); //=> '106.72' var n = 106.70; console.log(n.toFixed(2)); //=> '106.70' var n = 106.7; console.log(n.toFixed(2)); //=> '106.70' var n = 106; console.log(n.toFixed(2)); //=> '106.00' And it rounds: var n = 106.76; console.log(n.toFixed(1)); //=> '106.8'
doc_23532528
Expression<Func<MyType, bool>> a => t => ...; Expression<Func<MyType, bool>> b => t => ...; Expression<Func<MyType, bool>> c => t => ...; await myIQueryableOfMyType .Where(a) .Where(b) .Where(c) .ToArrayAsync() in a way that I have had a single Experssion withing a Single Where clause. My purpose is to replace the "a", "b", "c" expressions to variable set of conditions. I have tried to aggregate a function and set it in the new Lambda Expression Expression<Func<MyType, bool>>[] predicates = ... Func<MyType, bool> func = t => predicates == null || predicates.Aggregate(true, (prev, current) => prev && current.Compile()(t)); but it does not work for IQueryable collections of Entity Framework A: Expression is basically in-memory code representation, so it is definitely possible. Example code: static void Main(string[] args) { Expression<Func<MyType, bool>> a = t => t.Id == 1; Expression<Func<MyType, bool>> b = t => t.Name == "Name1"; Expression<Func<MyType, bool>> c = t => t.Desc == "Desc1"; Expression<Func<MyType, bool>> combined = LinqExtensions.And(a, b, c); await myIQueryableOfMyType .Where(combined) .ToArrayAsync() } public static class LinqExtensions { // Combine array of predicates into one // For example for input: // [ t1 => t1.Id == 1, t2 => t2.Name == "Name1", t3 => t3.Desc == "Desc1" ] // output will be // p => p.Id == 1 && p.Name == "Name1" && p.Desc == "Desc1" public static Expression<Func<T, bool>> And<T>(params Expression<Func<T, bool>>[] predicates) { // this is `p` ParameterExpression param = Expression.Parameter(typeof(T)); Expression body = null; foreach (Expression<Func<T, bool>> predicate in predicates) { body = body == null // first expression, just assign it to body ? predicate.Body // join body with predicate using && : Expression.AndAlso(body, predicate.Body); } // Create lambda return Expression.Lambda<Func<T, bool>>( // this is where we replace t1, t2, t3 with p new ParamExpressionVisitor(param).Visit(body), param ); } private class ParamExpressionVisitor : ExpressionVisitor { private ParameterExpression _parameter; public ParamExpressionVisitor(ParameterExpression parameter) { this._parameter = parameter; } protected override Expression VisitParameter(ParameterExpression node) { if (node.Type == this._parameter.Type) { return this._parameter; } return base.VisitParameter(node); } } }
doc_23532529
function draw(){ background(sky); keyPressed(); rect(0, 470, 900, 55); image(sun, 40, 0, 900, 500, -900, -500); image(catL, plrX, plrY, 100, 100); image(catR, plrX. plrY, 100, 100); if(lookingLeft == true) { catL = catL } if(lookingRight == true) { lookingRight = true catL = catR; } } function keyPressed(){ if(keyCode === LEFT_ARROW){ plrX = plrX-5; // move left lookingLeft = true; } if(keyCode === RIGHT_ARROW){ lookingRight = true; plrX = plrX+5; // move right } } Cat starts facing left, and then when I click RIGHT key it works, but DOES NOT turn back to the left after I click again.
doc_23532530
- var toto = JSON.stringify({"lol":"azd", "lol2":"gdc"}); script. $(document).ready(function () { var te = JSON.parse("#{toto}"); console.log(te.lol); }); Result in html: $(document).ready(function () { var te = "{&quot;lol&quot;:&quot;azd&quot;,&quot;lol2&quot;:&quot;gdc&quot;}"; console.log(te.lol); }); Result in console: Uncaught SyntaxError: Invalid or unexpected token Thanks for your help ! Panorius. A: The reason is that toto's value is escaped. Use ! to use unescaped value: - var toto = JSON.stringify({"lol":"azd", "lol2":"gdc"}); script. $(document).ready(function () { var te = JSON.parse("!{toto}"); console.log(te.lol); });
doc_23532531
Is there some standard way of doing this? I'm used to Backendless, that hides most of this detail, but I'd like to try Apple's approach so I don't need to worry about user management. Thanks for any info ... class Teacher : Equatable, CKRecordValueProtocol { var id: Int var lastName: String var firstName: String var students: [Student] // other stuff omitted } class Student : Equatable { var id: Int! var lastName: String! var firstName: String! var teacher: Teacher! // so we can point to the teacher in our model var teacherReference: CKRecord.Reference! // so we can point to records in CloudKit var gpa: Double! // other stuff omitted }
doc_23532532
By default user receives an email with activation link "http://examples.com/register". So there is no activation code in it. How it is supposed to work at all? A: Perhaps you forgot to set the url parameter on the page where the Account component is placed? The page url needs something like: register/:code? And the component settings must reflect that with the 'Activation Code Param' set to code as a normal string.
doc_23532533
I managed to add reference (U2.Data.Client) to the project and I'm able to use it in the Controller, but not in View page. The reason to utilize the UniDynArray is that, I would like to pass a dynamic array from Controller to View and back to controller. This way I will not have to set every field to VIEWDATA in order to be use in View. A: I would like to explain how to pass UniDynArray to MVC View from Controller the following ways: * *MVVM Pattern (Raw UniDynArray) *ViewBag Pattern (Raw UniDynArray) *MVVM Pattern (flatten UniDynArray, UniDynArray to .NET Object DataTable) *MVVM Pattern (flatten UniDynArray, UniDynArray to POCO Object) In this post , I will answer MVVM Pattern (Raw UniDynArray). Later I will cover rest. Create ASP.NET MVC3 Project Create a Model Add a controller Create a View Open ‘CustomerViewModel.cs’ file and paste the following code namespace Test_MvcApplication.Models { public class CustomerViewModel { public Customer MyCustomer { get; set; } public CustomerViewModel(Customer pCustomer) { MyCustomer = pCustomer; } } public class Customer { private UniDynArray myVar; public UniDynArray MyUniDynArray { get { U2ConnectionStringBuilder conn_str = new U2ConnectionStringBuilder(); conn_str.UserID = "user"; conn_str.Password = "pass"; conn_str.Server = "localhost"; conn_str.Database = "HS.SALES"; conn_str.ServerType = "UNIVERSE"; conn_str.AccessMode = "Native"; // FOR UO conn_str.RpcServiceType = "uvcs"; // FOR UO conn_str.Pooling = false; string s = conn_str.ToString(); U2Connection con = new U2Connection(); con.ConnectionString = s; con.Open(); Console.WriteLine("Connected........................."); // get RECID UniSession us1 = con.UniSession; UniSelectList sl = us1.CreateUniSelectList(2); // Select UniFile UniFile fl = us1.CreateUniFile("CUSTOMER"); fl.RecordID = "2"; myVar = fl.Read(); return myVar; } set { myVar = value; } } } } Open ‘MyUniDynArrayController.cs’ and paste the following code. As you notice that you are passing object to view and that object has UniDynArray namespace Test_MvcApplication.Controllers { public class MyUniDynArrayController : Controller { // // GET: /MyUniDynArray/ public ActionResult Index() { Customer c = new Customer(); UniDynArray r = c.MyUniDynArray; var l = new CustomerViewModel(c); return View(l); } } } Open ‘MyUniDynArray\ Index.cshtml’ and paste the following code. @Model contains ViewModel object (UniDynArray) @{ ViewBag.Title = "Index"; } MyUniDynArray ================== @Model.MyCustomer.MyUniDynArray Open ‘Shared\Layout.cshtml’ file and add the following line <nav> <ul id="menu"> <li>@Html.ActionLink("MyUniDynArray", "Index", "MyUniDynArray")</li> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("About", "About", "Home")</li> </ul> </nav> Run the application and press ‘MyUniDynArray’. You will see UniDynArray in View. I am not sure how are you going to bind UniDynArray with HTML5/Razor Controls. That’s why I sugest you to flatten UniDynArray. Typed UniDynArray in MVC View A: In this post , I would like to describe 'MVVM Pattern (flatten UniDynArray, UniDynArray to .NET Object Object) '. Create a Model Create Controller Create View Open Model file (Models\CustomerViewModel2.cs) and paste the coode namespace Test_MvcApplication.Models { public class Customer2 { public int ID { get; set; } public string Name { get; set; } public DateTime HireDate { get; set; } } public class Customer2Repository { private List<Customer2> m_custList = new List<Customer2>(); public List<Customer2> CustomerList { get { U2ConnectionStringBuilder l = new U2ConnectionStringBuilder(); l.Server = "localhost"; l.UserID = "user"; l.Password = "pass"; l.Database = "HS.SALES"; l.ServerType = "universe"; string lconnstr = l.ToString(); U2Connection c = new U2Connection(); c.ConnectionString = lconnstr; c.Open(); U2Command command = c.CreateCommand(); command.CommandText = "CALL MV_TO_DATASET_SELECT_SUBROUTINE(?,?)"; // UniVerse subroutine command.CommandType = CommandType.StoredProcedure; U2Parameter p1 = new U2Parameter(); p1.Direction = ParameterDirection.InputOutput; p1.Value = ""; p1.ParameterName = "@arg1"; U2Parameter p2 = new U2Parameter(); p2.Direction = ParameterDirection.InputOutput; p2.Value = ""; p2.ParameterName = "@arg2"; command.Parameters.Add(p1); command.Parameters.Add(p2); command.ExecuteNonQuery(); string lRetValue = (string)command.Parameters[1].Value; //command.Parameters[1].MV_To_POCO<int>(); m_custList = command.Parameters[1].MV_To_POCO<Customer2>(); return m_custList; } set { m_custList = value; } } } public class CustomerViewModel2 { public Customer2 MyCustomer2 { get; set; } public List<Customer2> CustomerList { get; set; } public CustomerViewModel2(Customer2 pCustomer) { MyCustomer2 = pCustomer; } public CustomerViewModel2(List<Customer2> pCustomerList) { CustomerList = pCustomerList; } } } Open Controller file (Controllers\MyUniDynArray2Controller.cs) namespace Test_MvcApplication.Controllers { public class MyUniDynArray2Controller : Controller { // // GET: /MyUniDynArrayController2/ public ActionResult Index() { Customer2Repository lvar = new Customer2Repository(); List<Customer2> lCustomer2List = lvar.CustomerList; var l = new CustomerViewModel2(lCustomer2List); return View(l); } } } Open View File (Views\MyUniDynArray2\Index.cshtml) @{ ViewBag.Title = "Index"; } <h2>Index</h2> <table border="1"> <tr> <td>ID</td> <td>Name</td> <td>HireDate</td> </tr> @foreach (var myItem in Model.CustomerList) { <tr> <td>@myItem.ID</td> <td>@myItem.Name</td> <td>@myItem.HireDate</td> </tr> } </table> Open ‘Shared\Layout.cshtml’ file and add the following line <nav> <ul id="menu"> <li>@Html.ActionLink("MyUniDynArray2", "Index", "MyUniDynArray2")</li> <li>@Html.ActionLink("MyUniDynArray", "Index", "MyUniDynArray")</li> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("About", "About", "Home")</li> </ul> </nav> Run the application and press ‘MyUniDynArray2’. You will see Flatten UniDynArray. Basically UniDynArray becomes array of .NET objects(List) Used UniVerse Subroutine SUBROUTINE MV_TO_DATASET_SELECT_SUBROUTINE(ARG_INPUT,ARG_OUTPUT) x = ARG_INPUT ARG_OUTPUT = "100":@VM:"101":@VM:"102":@VM:"103":@FM:"Nancy":@VM:"Andrew":@VM:"Janet":@VM:"Margaret":@FM:"01/06/1991":@VM:"06/07/1996":@VM:"11/08/1999":@VM:"12/10/2001" RETURN
doc_23532534
This is the Ribbon XML code with the comboBox: <customUI onLoad="Ribbon_Load" xmlns="http://schemas.microsoft.com/office/2009/07/customui"> <ribbon> <tabs> <tab id="SearchCustomerTab" insertAfterMso="TabAddIns" label="Cliente" visible="true"> <group id="SearchCustomerGroup" label="Cliente" autoScale="true"> <comboBox id="CustomerComboBox" getItemCount="GetItemCountCallback" getItemLabel="GetItemLabelCallback" getItemID="GetItemIDCallback" onChange="OnChangeCallback" /> </group> </tab> </tabs> </ribbon> </customUI> With getItemCount and getItemLabel callback I correctly fill che comboBox (oTabCustomersList is a List of a custom class): Public Function GetItemCountCallback(ByVal control As Office.IRibbonControl) As Integer Return oTabCustomersList.Count End Function Public Function GetItemLabelCallback(ByVal control As Office.IRibbonControl, index As Integer) As String Return oTabCustomersList(index).NomeCompleto End Function With getItemId callback I set the index of every item in the ID: Public Function GetItemIDCallback(ByVal control As Office.IRibbonControl, index As Integer) As String Return index.ToString End Function but with onChange callback I can obtain the item label but not the ID or the selected index: Public Sub OnChangeCallback(ByVal control As Office.IRibbonControl, text As String) Debug.WriteLine("OnChangeCallback text: " & text) 'text = item label End Sub Is there a way to obtain the index of the selected item with the Ribbon comboBox control? Thanks in advance, Simone A: Unfortunately it's not possibile to get the index of the selection in a ribbon comboBox (source) Whenever the value of the combo box is selected, the onChange callback receives the text. However, it is not possible to get the index of the selection. I've solved using a Dictionary (of String, CustomClass) where string is the text parameter of OnChangeCallback: Private customClass As CustomClass Private customDictionary As Dictionary(Of String, CustomClass) Public Sub Ribbon_Load(ByVal ribbonUI As Office.IRibbonUI) Dim customList As List(Of CustomClass) customList = FunctionToPopulateMyList() customDictionary = customList.ToDictionary(Function(p) p.MyText, Function(p) p) End Sub Public Function GetItemLabelCallback(ByVal control As Office.IRibbonControl, index As Integer) As String Return oCustomDictionary.ElementAt(index).Value.MyText End Function Public Function GetItemCountCallback(ByVal control As Office.IRibbonControl) As Integer Return oCustomDictionary.Count End Function Public Function GetItemIDCallback(ByVal control As Office.IRibbonControl, index As Integer) As String Return "Item" & index.ToString & control.Id End Function Public Sub OnChangeCallback(ByVal control As Office.IRibbonControl, text As String) If (customDictionary.ContainsKey(text)) Then customClass = customDictionary(text) End If End Function
doc_23532535
Now this is my code so far main.cpp #include "my_vector.h" #include <string> #include <iostream> int main(){ MY::Vector<int> vector; } my_vector.cpp #include "my_vector.h" #include <string> #include <iostream> // implementation of all the constructors template <class T> MY::Vector<T>::Vector(){ size = 0; alloc = 20; ptr = new T[alloc]; } template <class T> std::ostream& operator <<(std::ostream& out, const MY::Vector<T> vector){ for (auto iterator = vector.ptr; iterator < vector.size; iterator++){ out << *iterator; } return out; } template <class T> MY::Vector<T>::~Vector(){delete[] ptr; alloc = 0; size = 0;} my_vector.h #ifndef MY_VECTOR_H #define MY_VECTOR_H #include <string> #include <iostream> namespace MY{ template <class T> class Vector{ public: // these are going to be some friend functions // we are going to overload the operator << to print the content of the vector friend std::ostream& operator<<(std::ostream& out, const Vector<T>& vector); public: // we need to store three things // pointer to the first address in memory // size of the vector so far // actual space allocated T* ptr; size_t size; size_t alloc; public: // we need 2 constructors // default constructor Vector<T>(); // custom constructor Vector<T>(T value); // overloaded custom constructor Vector<T>(int cells, T value); // destructor ~Vector<T>(); // Now the copy constructor Vector<T>(const Vector<T>& other); // Now the move constructor Vector<T>(Vector<T>&& other); // now a copy assignment Vector<T>& operator=(const Vector<T>& other); // now a move assignment Vector<T>& operator=(Vector<T>&& other); public: // these are all the functions that we need bool isEmpty(); size_t get_size(); size_t get_alloc(); void push_back(T value); void push_front(T value); void pop_back(); void pop_front(); public: // these are the overloaded operations // symbol > if one vector is greater than another one // opposite goes for < operator; // operator << to print the content of the vector using friend functions // operator + to add two vector together bool operator>(const Vector<T>& other); bool operator<(const Vector<T>& other); Vector<T>& operator+(const Vector& other); }; } #endif As you can see most of the stuff is just declared. However I already implemented the default constructor and the destructor to test if everything is fine so far, and it seems it is not as I am getting this error Undefined symbols for architecture x86_64: "MY::Vector<int>::Vector()", referenced from: _main in main-08d713.o "MY::Vector<int>::~Vector()", referenced from: _main in main-08d713.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) run.sh: line 3: ./output: No such file or directory additionally I am compiling using this a bash script like this #!/bin/bash g++ *.cpp -o output -std=c++17 ./output I have also tried simply g++ *.cpp ./a.out I cannot really understand where is the problem. Could someone help?
doc_23532536
Maybe if you take a look at it you can suggest improvements. If you need to see my UserModel class, let me know. Here's the code for the Account controller. namespace WebUI.Controllers { public class AccountController : Controller { public ActionResult Register() { UserModel model = new UserModel(); EFCityRepository cityRepo = new EFCityRepository(); model.Cities = new List<SelectListItem>(); foreach (var city in cityRepo.FindAllCities()) { model.Cities.Add(new SelectListItem { Text = city.Name, Value = city.CityId.ToString(), Selected = true }); } EFGenderRepository genderRepo = new EFGenderRepository(); model.Genders = new List<SelectListItem>(); foreach (var gender in genderRepo.FindAllGenders()) { model.Genders.Add(new SelectListItem { Text = gender.Name, Value = gender.GenderId.ToString(), Selected = true }); } return View(model); } [HttpPost] public ActionResult Register(UserModel model) { EFCityRepository cityRepo = new EFCityRepository(); model.Cities = new List<SelectListItem>(); foreach (var city in cityRepo.FindAllCities()) { model.Cities.Add(new SelectListItem { Text = city.Name, Value = city.CityId.ToString(), Selected = true }); } EFGenderRepository genderRepo = new EFGenderRepository(); model.Genders = new List<SelectListItem>(); foreach (var gender in genderRepo.FindAllGenders()) { model.Genders.Add(new SelectListItem { Text = gender.Name, Value = gender.GenderId.ToString(), Selected = true }); } if (ModelState.IsValid) { Domain.User user = new Domain.User(); user.UserRoleId = 1; user.Nickname = model.Nickname; user.Name = model.Name; user.Lastname = model.Lastname; user.GenderId = model.GenderId; user.Address = model.Address; user.Email = model.Email; user.Telephone = model.Telephone; user.MobilePhone = model.MobilePhone; user.Carnet = model.Carnet; user.DateOfBirth = model.DateOfBirth; user.DateOfRegistry = DateTime.Now; user.LastDateLogin = DateTime.Now; user.IsActive = false; user.LanceCreditBalance = 5; user.LancesSpent = 0; user.Login = model.Login; user.Password = model.Password; user.EmailVerificationCode = "TempTokenString"; user.CityId = model.CityId; EFUserRepository repo = new EFUserRepository(); var result = repo.CreateUser(user); if (result == UserCreationResults.Ok) { FormsAuthentication.SetAuthCookie(model.Nickname, false /* createPersistentCookie */); return RedirectToAction("Index", "Home"); } else { switch (result) { case UserCreationResults.UsernameExists: ModelState.AddModelError("", "El nombre de usuario ya esta siendo utilizado."); break; case UserCreationResults.EmailAlreadyExists: ModelState.AddModelError("", "Ese correo ya esta en uso."); break; case UserCreationResults.NicknameAlreadyExists: ModelState.AddModelError("", "El nickname ya esta siendo utilizado."); break; case UserCreationResults.UnknownError: ModelState.AddModelError("", "Algo durante el registro. Por favor intente de nuevo."); break; default: break; } } } // If we got this far, something failed, redisplay form return View(model); } } } I'm using Entity Framework as my ORM, it generates a User class automatically for me. However, I made a User*Model* class so I could add data annotations for the views to use. Maybe this is the wrong idea? A: I have many suggestions. For startes, read up about Dependancy Injection and Inversion of Control (DI and IoC). They will make all that boilerplate object instantiation a thing of the past. Next, convert those for-each list builders into Linq expressions. Much more succinct and more likely faster as well. Then, in your post handler, again do the same things there. In addition, get to know AutoMapper, which will automatically map your view to domain classes and make your life much easier. If you did those things, your code would be reduced by 2x, maybe even 3. EDIT: An example linq query, because I really don't know the definition of your objects... would look something like this: model.Cities = cityRepo.FindAllCities().Select(city => new SelectListItem() { Text = city.Name, Value = city.CityId.ToString()}).ToList(); Notice how you don't have to new up a new List, since that's returned by the ToList() method. It is also using projection to select the items into a new SelectListItem. Basically, you could write your method like this, using Dependancy Injection, Linq, and AutoMapper (it looks longer because i had to break lines multiple times to fit the small viewing are of SO): namespace WebUI.Controllers { public class AccountController : Controller { private IGenderRepository _genderRepo; private ICityrRepository _cityRepo; private IUserRepository _userRepo; public AccountController(IGenderRepository gr, ICityRepository cr, IUserRepository ur) { _genderRepo = gr; _cityRepo = cr; _userRepo = ur; } public ActionResult Register() { UserModel model = new UserModel(); // Selected property is ignored by MVC on SelectListItems model.Cities = _cityRepo.FindAllCities().Select(city => new SelectListItem() { Text = city.Name, Value = city.CityId.ToString()}).ToList(); model.Genders = _genderRepo.FindAllGenders().Select(gender => new SelectListItem() { Text = gender.Name, Value = gender.GenderId.ToString()}).ToList(); return View(model); } [HttpPost] public ActionResult Register(UserModel model) { model.Cities = _cityRepo.FindAllCities().Select(city => new SelectListItem() { Text = city.Name, Value = city.CityId.ToString()}).ToList(); model.Genders = _genderRepo.FindAllGenders().Select(gender => new SelectListItem() { Text = gender.Name, Value = gender.GenderId.ToString()}).ToList(); if (ModelState.IsValid) { Domain.User user = Mapper.Map<Domain.User, Model>(model) var result = _userRepo.CreateUser(user); if (result == UserCreationResults.Ok) { FormsAuthentication.SetAuthCookie(model.Nickname, false); return RedirectToAction("Index", "Home"); } else { ModelState.AddModelError("", GetErrorString(result)); } } // If we got this far, something failed, redisplay form return View(model); } } } A: your Idea is good. Because it is not a good practice to have entity classes as the view models in MVC layer because it will create a tight coupling between your presentation and persistence logic. To cleanup yuor code you can use AutoMapper ( http://automapper.codeplex.com/ ) to map your entity classes to view model easy without writing too many codes. http://jasona.wordpress.com/2010/02/05/getting-started-with-automapper/ here is a good article for you.
doc_23532537
I only can navigate from a to b anc c. I put the same code to the others but application stops. A: Assuming your layouts are Activities; All you need to do is set button click listeners and call corresponding activity in listener block. For instance; in ActivityA (onCreate() method) btnStartB = (Button)findViewById(R.id.btnStartB); btnStartB.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ActivityA.this, ActivityB.class); startActivity(intent); } }); you will need to do same for btnStartC in ActivityA, btnStartD in ActivityC and btnStartE in ActivityD. Try debugging and figure out where it stops.
doc_23532538
If it is implementation defined, then for example, why it is safe to pass a struct to a DLL, if this DLL could have been compiled with a different compiler, which could have different methods for struct padding? Is the struct padding method enforced by the OS's ABI (for example, the padding will be the same on all Windows platforms)? Or, is there standard method for padding when compiling for a PC (x64 or x86_64 systems) that is used in every modern compiler? If there is nothing that can guarantee the layout of variables, then is it safe to assume that each basic type in C++ (char, all numeric variables and pointers) must be aligned to an address that is a multiple of its size, and because of that, padding inside a struct can be done by hand without performance problems or UB? From what I have checked, g++ compiles structs in such a way, that it inserts minimum amount of padding, just to ensure alignment of the next variable. For example: struct foo { char a; // char _padding1[3]; <- inserted by compiler uint32_t b; }; There are 3 bytes of padding after a because that is the minimum amount that will give us a suitably aligned address for b. Can we take for granted that compilers will do this that way? Or, can we force this kind of padding by hand without UB or performance issues? By hand, I mean: #pragma pack(1) struct foo { char a; char _padding1[3]; //<- manually adding padding bytes uint32_t b; }; #pragma pack() Just to be clear: I am asking about behavior of compilers only on PC platforms : Windows, Linux distros, and maybe MacOS. Sorry if my question is in category of "you dig into this too much". I just couldn't find a satisfying answer on the Internet. Some people say that it is not guaranteed. Others say that compiling with different compilers on systems that use the same ABI guarantee that the same struct will have the same layout. Others show how to reduce struct padding assuming that compilers pack structs the way that I described above (it is with minimum required padding to align variables). A: If it is implementation defined, then for example, why it is safe to pass struct to dll Because the dll and the caller follow the same Application binary interface (ABI) that defines the layout. By the way, dll are a language extension and not part of standard C++. if this dll could have been compiled with different compiler, which could have different method for struct padding? If the library and the dependent don't follow an intercompatible ABI, then they cannot work together. Is structpadding method enforced by the OS's ABI Yes, class layout (structs are classes) is defined by the ABI. For example padding will be the same on all Windows platforms Not quite, since Windows on ARM has a different ABI for example. But within the same CPU architecture, the layout would be the same in Windows. Or is there standard method for padding when compiling for PC (x64 or x86_64 systems) that is used in every modern compiler? No, there is no universal class layout followed by OS, even within x86_64 architecture. From what I checked, g++ compiles structs in such way, that it inserts minimum amount of padding, just to ensure alignment of next variable. All objects in C++ must be aligned as per the alignment requirement of the type of the object. This guarantee isn't compiler specific. However alignment requirements of types - and even the sizes of types - vary across different ABIs. Bonus info: Compilers have language extensions that remove such guarantee. There are 3 bytes of padding after a because it is minimum amount that will give us suitably aligned address for b. Can we take for granted that compilers will do this that way? In general no. On some systems, alignof(std::uint32_t) == 1 in which case there wouldn't be need for any padding. Within a single ABI, you can take for granted that the layout is the same, but across multiple systems - which might not follow the same ABI - you cannot take it for granted. When dealing with binary layout across systems (for example, when reading from a file or network), the standard compliant way is to treat the data as an array of bytes1, and to copy each sequence of bytes2 from pre-determined offsets onto fixed width3 fundamental objects (not classes whose layout may differ). In practice, you don't need to care about sign representation although that used to be a problem historically. If the optimiser does its job, there ideally shouldn't be any performance penalty if the layout of input data matches the native layout. In case it doesn't match, then there may be a cost (compared to a matching layout) that cannot be optimised away. 1 This isn't sufficient when byte size differs across systems, but you don't need to worry about that since you care about x86_64 only. 2 In order to support systems with varying byte endianness, you must interpret the bytes in order of their significance rather than memory order, but you don't need to worry about that since you care about x86_64 only. 3 I.e. not int, short, long etc., but rather std::int32_t etc. A: The C and C++ standards were written to describe existing languages. In situations where 99+% of implementations would do things a certain way, and it was obvious that implementations should do things that way absent a compelling reason for doing otherwise, the standards would generally leave open the possibility of implementations doing something unusual. Consider, for example, given something like: struct foo {int i; char a,b[4],c,d,e;}; // Assume sizeof (int) is 4 struct foo myFoo; On most platforms, making bar be a three-word type which contains all of the individual bytes packed together may be more efficient than doing anything else. On the other hand, on a platform that uses word-addressed storages, but includes instructions to load or store bytes at a specified byte offset from a specified word address, word-aligning the start of b may allow a construct like myfoo.b[i] to be processed by directly using the value of i as an offset onto the word-aligned address of myFoo.b. The standards were designed by people designing compilers for such platforms to weigh the pros and cons of following normal practice versus deviating from it to better fit the target architecture. Machines that use word addresses but allow byte-based loads and stores are of course exceptionally rare, and very little code that isn't deliberately written from such machines for which compatibility with such them would offer any added value whatsoever. The committees weren't willing to say that such machines should be viewed as archaic and not worth supporting, but that doesn't mean they didn't expect and intend that programs written for commonplace implementations could exploit aspects of behavior that were shared by all commonplace implementations, even if not by some obscure ones.
doc_23532539
I know a matrix determinant can be used to do check this, but after reading MATLAB determinant: "Using det(X) == 0 as a test for matrix singularity is appropriate only for matrices of modest order with small integer entries. Testing singularity using abs(det(X)) <= tolerance is not recommended as it is difficult to choose the correct tolerance. The function cond(X) can check for singular and nearly singular matrices." So if I want to generate a big random matrix (axb) a=5000, b=5000, How to do it??. A: A randomly generated matrix will be full rank (and hence invertible, if square) with probability 1: A = randn(5000); you can check this by using min(svd(A)), and verifying that the smallest singular value is larger than zero. This is a well-known fact, but here's an example paper if you want one.
doc_23532540
outcome.to_csv("/Users/john/out_1.csv") I get the following error: UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 191: ordinal not in range(128) how do I go to position 191 to check what's wrong? Many thanks A: outcome.to_csv("/Users/john/out_1.csv",encoding="utf-8") On referring to the documentation of pandas.to_csv, we have the following details. It seems that for Python 2.7 the default is "ascii" which needs to be overridden to "utf-8" encoding : string, optional A string representing the encoding to use in the output file, defaults to ‘ascii’ on Python 2 and ‘utf-8’ on Python 3.
doc_23532541
Error: checkForServer is now defunct. Users in future can find the function in file.path(find.package("RSelenium"), "examples/serverUtils"). The recommended way to run a selenium server is via Docker. Alternatively see the RSelenium::rsDriver function. My chrome is updted to version 58 and moxilla to version 45, rselenium used to work earlier but I'm not sure what happened please help guys. A: The following script works for me with the new RSelenium... rD <- rsDriver(port=4444L,browser="chrome") remDr <- rD$client remDr$navigate(url) A: Just make sure you have docker account and you have it installed. try this library('RSelenium') rD=rsDriver() remDr =rD[["client"]] remDr$navigate("https://www.vinmonopolet.no/vmp/Land/Chile/Gato-Negro-Cabernet-Sauvignon-2017/p/295301") webElement = remDr$findElement('xpath', '//*[@id="product_2953010"]/span[2]') webElement$clickElement()
doc_23532542
grammar Paradox; paradox: kvPair+; kvPair : atom '=' atom | atom '=' scope | scope ; scope : '{' (paradox|atom+)? '}' ; atom : STRING | NUMBER | ID (':' ID)? ; STRING : '"' (~'"')*? '"' ; ID : [0-9a-zA-Z_]+ ; NUMBER : '-'?[0-9]+ ('.' [0-9]+)? ; WS : [ \t\r\n]+ -> skip ; The file is 20 MB, looks like this version="Boulle v1.9.1" version_control_revision=31493 name="泰布理同胞体" date="2269.02.09" planet= { ... } ... country = { 0 = { ... name="USA" ... food_surplus=3.598 ... } 1 = { ... name="ENG" ... food_surplus=2.001 ... } ... } ... ... means omitted lines by me. The actual file has valid grammar there. Say I only need to know the number of countries, and for each country, record its name and food_surplus. Currently what I do is ICharStream cstream = CharStreams.fromstring(input); ITokenSource lexer = new ParadoxLexer(cstream); ITokenStream tokens = new CommonTokenStream(lexer); var parser = new ParadoxParser(tokens); // find kvPair with key "country". // Then .ChildCount is the number of country, // find kvPair with key "name" to get the name of the country. This approach works, but the drawback is that it consumes as large as 1GB memory when it's running. Notice I'm not using and don't know how to use visitor pattern or listener pattern. I understand the large memory consumption is because of the ..., the lines I omitted, which can be millions of lines. Antlr is building parse tree for these uninterested things. How do I reduce the memory consumption? A: A parser is not the right tool for such kind of processing, as it is supposed to validate all the input it gets. That's the main/primary goal of a parser per se. If you are only interested in parts of your input then split it first by other means (e.g. search for certain delimiters) and only feed the interesting parts to your parser. Update: By request: the ANTLR4 docs have a short description for listeners/visitors, to be used with a parse tree generated by a parser run. In order to use a listener during parsing you just need to register your listener (which is exactly like the one used after parsing): JavaLexer lexer = new JavaLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); JavaParser parser = new JavaParser(tokens); MyListener extractor = new MyListener(parser); parser.addParseListener(extractor); JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse a compilationUnit
doc_23532543
A: JavaScript is enabled by default. There is a javaScriptEnabled property on WKPreferences that you can flip to true in case some code has turned it off. Are you sure that the problem you are seeing is related to JavaScript? Do you see any errors in the console? Did you implement the error/failure delegate methods to catch problems? My gut feeling is that you are running into something different. For example a resource not loading because of the new App Transport Security requirements in iOS9.
doc_23532544
I have an Adjacency Matrix: 1 2 3 4 5 6 7 8 1 0 20 25 20 0 0 0 0 2 20 0 5 0 30 0 0 0 3 25 5 0 13 8 21 0 0 4 20 0 13 0 0 17 0 0 5 0 30 8 0 0 33 0 0 6 0 0 21 17 33 0 0 0 7 0 0 0 0 0 0 0 10 8 0 0 0 0 0 0 10 0 Which has a graph as follows: This is my function: void Network::BFS(int src, int dest, vector<bool>& visited, vector<int>& path) { // The Queue is the core for the BFS. queue<int> Queue; // Mark current node as visited. visited[src] = true; Queue.push(src); // While queue is not empty. while (!Queue.empty()) { // Add node to path. // Check if we have found the destination yet or not, if we have we do one last push to path and we're done! if (Queue.front() == dest) { return; } int top = Queue.front(); path.push_back(Queue.front()); // Pop off front. Queue.pop(); // Iterate and process all none visited nodes. for (int node = 0; node < amountOfNodes; node++) { // Check if it is not visited already. if (visited[node] == false && (adjMatrix[node * amountOfNodes + src] != 0)) { Queue.push(node); // Add to end. visited[node] = true; } } } } Sample input and output: (6, 3) -> Path is: 6 (1, 5) -> Path is: 1 2 3 4 As you can see, it does not compute the path properly at all. Where is my algorithm going wrong here, and how do I fix it? A: BFS involves visiting adjacent nodes in a FIFO fashion. Once you reach a node, you put into the queue all its neighbours, unless they were already visited. First off, there's a typo where you iterate over adjacent nodes. You want to traverse the top column, not the src one: adjMatrix[node * amountOfNodes + top] != 0 // ~~^ Secondly, your current path implementation stores the visit order of nodes, not a path from the source to its destination. For the latter, you need to store the parent of each node, so that the final path can be restored by going from a child (destination) to its parent, grandparent, great-grandparent, ..., etc. std::vector<int> parent(amountOfNodes, -1); //... if (visited[node] == false && (adjMatrix[node * amountOfNodes + top] != 0)) { Queue.push(node); // Add to end. visited[node] = true; parent[node] = top; } Restoring the path is straightforward: int u = dest; do { std::cout << u << " "; u = parent[u]; } while (u != -1); DEMO
doc_23532545
I'm using dio: ^3.0.9. Works perfectly fine in postman And if I remove the image from data and post just the data it works fine. class ProfileRepository { LocalStorage localStorage = new LocalStorage(); Dio dio = new Dio(); final url = 'http://localhost:3000/api/profile'; Future<ProfileModel> getProfileResponse( String fullName, String position, String gender, String homeAddress, String officeAddress, String phoneNumber, File image) async { final token = await localStorage.getLoginToken(); final splitToken = token.split(' '); final finalToken = splitToken[1]; String imageFile = image.path.split('/').last; var formData = new FormData.fromMap({ "fullname": fullName, "position": position, "gender": gender, "home_address": homeAddress, "office_address": officeAddress, "phone_no": phoneNumber, "image": await MultipartFile.fromFile(image.path, filename: imageFile), }); final response = await dio.post(url, data: formData, options: Options(headers: {'Authorization': finalToken})); if (response.statusCode == 201) { return ProfileModel.fromJson(json.jsonDecode(response.data)); } else { throw Exception("Error"); } } } A: final url = 'http://localhost:3000/api/profile'; Future<ProfileModel> getProfileResponse( String fullName, String position, String gender, String homeAddress, String officeAddress, String phoneNumber, File image) async { final token = await localStorage.getLoginToken(); final splitToken = token.split(' '); final finalToken = splitToken[1]; String imageFile = image.path.split('/').last; FormData formData() { var formData = new FormData.fromMap({ "fullname": fullName, "position": position, "gender": gender, "home_address": homeAddress, "office_address": officeAddress, "phone_no": phoneNumber, }); formData.files.addAll([ MapEntry( "files", MultipartFile.fromFileSync(image.path, filename: imageFile)), ]); return formData; } final response = await dio.post(url, data: formData(), options: (contentType: 'multipart/form-data', headers: { "Accept": "application/json", "Authorization": finalToken, }), );); if (response.statusCode == 201) { return ProfileModel.fromJson(json.jsonDecode(response.data)); } else { throw Exception("Error"); } } } Try this. If I had to guess, I think it's issue with your image path.
doc_23532546
I am using the csv.writer to output the array elements and an additional numeric variables e.q. cntr and n_obs both converted with str() to string output. I have the code: writer.writerow([cntr, n_obs, str(myarray)[2:-2]]) It removes the brackets, but does not insert the commas in the str(myarray)[2:-2] part. How could I create this so I have 5 values (cntr, n_obs and the 3 array elements) as comma-delimited? Also, is there a way to format the array element values something like a float 10.6? A: Have you tried using string.join()? myarray = [ 10.54552827, 0.10287327, 0.21923103 ] rounded = ["%.2f" % i for i in myarray] lst = [ cntr, n_obs ] print ','.join( lst.extend(lst) ) I hope I'm interpreting your array correctly.
doc_23532547
I have tried a simple test app calling a dll from within windbg.exe. This works well. When I add labview into the mix windbg of course starts giving ERROR: Symbol file not found for all the labview stuff. I am sure I have the right symbol file directories set and source folders are set as well. I am sort of a newb to windbg, but I'm starting to gather that unless you have ALL the symbol files you're hosed on using it. Is that correct? If so I guess it's back to fprintf and limited debugging. I don't want to use visual studio because this is for a semi embedded application and it simply doesn't have the disk space/room for holding all of visual studio. A: You need to attach the windbg to the LabVIEW process, then set a breakpoint in your DLL code. This way, you will only break when it gets to your code. This is how it works from Visual Studio and a quick search seems to suggest it will work with windbg as well. A: You won't necessarily be hosed if you're only planning on setting breakpoints and whatever in your DLL. That should work fine. Stack traces from your DLL back into the LabVIEW image will start complaining, but hopefully it's stuff you're not interested in anyway and you can just ignore it. A: You can also set a breakpoint in windbg to break as soon as your DLL is loaded. To do this, attach windbg to the Labview process and use the following command: sxe ld foo(where foo is the name of your dll). This tells the debugger to break when the dll load event occurs, specifically for your dll. See http://msdn.microsoft.com/en-us/library/cc266379.aspx for more info. When you hit this breakpoint you can then figure out which symbol you would like to break on within your code to debug.
doc_23532548
But it doesn't work i just can scroll the whole page instead of moving components of the list. Please help A: Check out the documentation from Apple on Safari which talks about event handling. Essentially you'll have to prevent the default behavior of dragging. function touchMove(event) { event.preventDefault(); curX = event.targetTouches[0].pageX - startX; curY = event.targetTouches[0].pageY - startY; event.targetTouches[0].target.style.webkitTransform = 'translate(' + curX + 'px, ' + curY + 'px)'; }
doc_23532549
The blue comes from the background so it's not relevant, its the shades of green I'm interested in. I'm not sure first if its possible to do it with CSS or how to do it if it is possible. Can you start a gradient in the top left corner, move into a different colour from there and finish with a final colour at the bottom of the gradient? If so are there any examples that you know of which I can refer too? A: You can do this easily enough with a CSS-gradient using color stops. Here's a snippet example: .gradientButton { height: 50px; width: 100px; line-height:50px; vertical-align:middle; text-align:center; font-family:arial; font-size:26px; font-weight:bold; color:white; text-shadow:2px 2px #336633; box-shadow:2px 2px #336633; border: 1px solid black; border-radius:12px; background: linear-gradient(to bottom right, LawnGreen 15%, green 85%, DarkGreen 90%); } .gradientButton:hover { text-shadow:1px 1px #336633; box-shadow:1px 1px #336633; background: linear-gradient(to bottom right, LawnGreen 5%, green 80%, DarkGreen 85%); } <html> <body> <div class="gradientButton">log in</div> </body> </html> Using things like gradients and shadows you can even provide hover effects like I've done here making it look like the button's depressed when you hover over it.
doc_23532550
my code worked with no problam with other deviced and us well by using local-host debuging si im sure its okay. the error I get : socket.error: [Errno 10061] No connection could be made because the target machine actively refused it I took the IP from the beaglebone by hostname -I same error when i'm "putting" my server on the PC and the "client" is the beaglebone it's working. for my win7 PC , I found the address from IPCONFIG any Idea? A: finding beaglebone IP and dealing with it is well described here http://emacstragic.net/howto-quickly-find-beaglebone-blacks-ip-address/ A: For development purposes, I connected BBB with my Mac with ethernet cable, and set static IP for eth0 interface on BBB and en0 on mac. On BBB I modified /etc/network/interfaces: auto eth0 iface eth0 inet static address 192.168.100.2 netmask 255.255.255.0 gateway 192.168.100.1 And I set 192.168.100.1 as IP for the interface on the Mac.
doc_23532551
iris=datasets.load_iris X = iris.data --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-15-12a2d725131f> in <module>() ----> 1 X = iris.data AttributeError: 'function' object has no attribute 'data I load iris dataset from sklearn ,but when i write "X = iris.data",an error occur as "AttributeError: 'function' object has no attribute 'data'" A: Use load_iris() instead of load_iris, like this, iris = datasets.load_iris() A: load_iris is a function and needs to be called as such: from sklearn import datasets iris=datasets.load_iris() X = iris.data
doc_23532552
-----------------------------------> Update: Added Code sample : JMenuItem saveMenuItem = new JMenuItem(); saveMenuItem.setEnabled(false); saveMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { saveMenuItemActionPerformed(); } }); add(saveMenuItem); private void saveMenuItemActionPerformed() { System.out.println( "Save clicked." ); } A: not sure how to prevent. but you can setVisible(false) to prevent it being displayed. Also if a user clicks on the disable menu no action will take place. A: When you are disabling JMenuItem, you should remove the ActionListener associated with that JMenuItem by using jMenuItem.removeActionListener() method. If u remove that that action will not call the listener and popup will not be disappeared. I hope this will help to achieve your target. A: In short, you can do this, but you will have to write your own mouse listener, which may require a lot of copy&paste from the jdk source code, which is not a very good idea, and I'm not sure about what license restrictions it will put on your code. I would start digging from this method: javax.swing.plaf.basic.BasicMenuItemUI.Handler#mouseReleased which seems to be the entry point from where the menu handling mechanism hides the popup. I would take a closer look at javax.swing.plaf.basic.BasicPopupMenuUI.MouseGrabber#stateChanged EDIT Developing answer by @Burhan Valikarimwala, try this apporach: remove all action listeners from the disabled JMenuItem and store them in some static temp structure (let's say a Map<WeakReference<JMenuItem>, List<MouseListener>>), this way it will not hide the popup. When you make the menu item enabled again, add all the listeners back. Make it into some util method and it will be seamless. A: did you gave a try at this method: http://download.oracle.com/javase/6/docs/api/javax/swing/JMenuItem.html#setArmed%28boolean%29 "arm the menu item so it can be selected", which I guess would do the trick if set to false. A: The only solution I could come up with, for your problem of a click on disable JMenuItem causing it to hide is below: import java.awt.Color; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; public class PopupMenuDisableNoCloseTest extends JPanel implements ActionListener { public static void main(String[] args) { PopupMenuDisableNoCloseTest p = new PopupMenuDisableNoCloseTest(); p.setPreferredSize(new Dimension(200, 300)); p.setBackground(Color.GREEN); JPanel contentPane = new JPanel(); contentPane.add(p); final JFrame f = new JFrame(); final JPopupMenu popup = new JPopupMenu(); final JMenuItem menuItem1 = new JMenuItem("A popup menu item"); menuItem1.addActionListener(p); menuItem1.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { System.out.println(" menuItem1 mousePressed e.getPoint()=" + e.getPoint()); } @Override public void mouseReleased(MouseEvent e) { System.out.println(" menuItem1 mouseReleased e.getPoint()=" + e.getPoint()); if(!menuItem1.isEnabled()) popup.setVisible(true); } }); menuItem1.setEnabled(false); popup.add(menuItem1); JMenuItem menuItem2 = new JMenuItem("Another popup menu item"); menuItem2.addActionListener(p); popup.add(menuItem2); MouseListener popupListener = new PopupListener(popup); f.addMouseListener(popupListener); f.setContentPane(contentPane); f.setSize(800, 600); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { JMenuItem source = (JMenuItem) (e.getSource()); String s = "Action event detected. Event source: " + source.getText(); System.out.println("s=" + s); } static class PopupListener extends MouseAdapter { JPopupMenu popup; PopupListener(JPopupMenu popupMenu) { popup = popupMenu; } @Override public void mousePressed(MouseEvent e) { maybeShowPopup(e); } @Override public void mouseReleased(MouseEvent e) { maybeShowPopup(e); } private void maybeShowPopup(MouseEvent e) { if(e.isPopupTrigger()) { popup.show(e.getComponent(), e.getX(), e.getY()); } } } } Basically the hiding happens when your release is inside the bounds of the JMenuItem, therefore we are checking if it is disabled then we show popup again. As by this time it is already decided that it will be hidden. I was trying calling super.mouseRelease with a different MouseEvent pointing outside component and consuming the previous one but it helps nothing. Anyway this solution works. Enjoy, Boro A: This has been tested and works. The Look & Feel decides how to handle the mouse events on disabled menu items. Anyway, you can intercept the undesired events by using a custom MenuItem. Simply use that code (copy/paste): public class CustomMenuItem extends JMenuItem { public CustomMenuItem(String text) { super(text); } public CustomMenuItem() { super(); } protected void processMouseEvent(MouseEvent e) { if (isEnabled()) super.processMouseEvent(e); } } First, adapt the code to suit your needs (optional). Finally, replace any JMenuItem with a CustomMenuItem. That's it! A: I think in Java7 this has been fixed.
doc_23532553
I would want to change the classs based off the 1st variable, the title with 2nd variable and the text with the 3rd. Here is the code that I am using: .popupalert { width: 75%; padding: 15px; background-color: #f44336; color: white; margin: 15px auto 0 auto; box-shadow: 0 0 30px rgba(0, 0, 0, 0.4); border-radius: 5px; font: 1.5em'Andale Mono', Consolas, 'Courier New'; } .popupsuccess { width: 75%; padding: 15px; background-color: #4CAF50; color: white; margin: 15px auto 0 auto; box-shadow: 0 0 30px rgba(0, 0, 0, 0.4); border-radius: 5px; font: 1.5em'Andale Mono', Consolas, 'Courier New'; } .popupwarning { width: 75%; padding: 15px; background-color: #f47836; color: white; margin: 15px auto 0 auto; box-shadow: 0 0 30px rgba(0, 0, 0, 0.4); border-radius: 5px; font: 1.5em'Andale Mono', Consolas, 'Courier New'; } .closebtn { margin-left: 15px; color: white; font-weight: bold; float: right; font-size: 22px; line-height: 20px; cursor: pointer; transition: 0.3s; } .closebtn:hover { color: black; } <div class='popupwarning'> <span class='closebtn' onclick=\ "this.parentElement.style.display='none';\">&times;</span> <strong>NOTICE!</strong> The quota increase is larger than the volume free space. </div> What I would like to have is a function or javascript that I can run on any page (with script loaded of course). I have 3 different levels of popups (alert, warning, success). I would like to pass the alert level, and the text string. like this: <script> popup('warning','NOTICE!','some text to go with alert') </script> A: If I understand the question correctly, you want to shorten up your CSS code and make a function that returns the popup HTML code. First, I would start by reducing your CSS code. If you look at your CSS, popupalert, popupsuccess, and popupwarning all have pretty much the same CSS with the exception of the background color. Why not create a popup class that has the base CSS for the popup, then create the different color classes for the background? That would reduce it a bit. Something like this: .popup { width: 75%; padding: 15px; color: white; margin: 15px auto 0 auto; box-shadow: 0 0 30px rgba(0, 0, 0, 0.4); border-radius: 5px; font: 1.5em'Andale Mono', Consolas, 'Courier New'; } Then you could create a child class that sets the background like so: .popup .alert{ background-color: #f44336; } .popup .success{ background-color: #4CAF50; } .popup .warning{ background-color: #f47836; } Now, usually I wouldn't worry about creating a function to spit out HTML code, but if you need something like that, you could do something like this: function popupGenerator(type, title, body) { // return the html string here. You will have to construct it yourself. } Now that you have the function that spits out the proper html, you could just use it like this when the page loads, someone hits a button, etc: $(document).ready(function() { $("body").append(popupGenerator("warning", "my warning", "do something")); }); I've made a little JSBIN to help you out. You'll have to do some tweaking to your fitting, but this should give you a start: http://jsbin.com/xuquwacoju/edit?js,output
doc_23532554
I know I must use a if and else loop to check the parameters (or a ternary which we have not covered yet.) This is what I have gotten so far. Please tell me if I am on the right track or completely wrong. function sum(augment1,augment2) { var num= augment1 + augment2; return num; } var a=sum(10,30) console.log(a); if (num > 25) { return true } else { return false; } A: There's no reason to use an if-else statement - the <= operator returns a boolean result, so you could just return it: function isSumEqualOrLessThan25(augment1, augment2) { var sum = augment1 + augment2; return sum <= 25; } A: Your conditions should be inside your function right? So if the sum is less than or equal to 25 return true else return false. Can you try following? function sum(augment1, augment2) { var num = augment1 + augment2; if (num <= 25) { return true } else { return false; } } var a = sum(10, 30) console.log(a); // should be false
doc_23532555
I have the following directory structure. It's not mine by design but I'm game for modifying things as necessary (forked repo). exp main_Exp.py kaffe __init__.py tensorflow __init__.py network_shape.py ResNet __init__.py (*) ThreeDMM_shape.py To run the model in this repo, I am to use python main_Exp.py input_file.csv Inside main_Exp.py: sys.path.append('./kaffe') sys.path.append('./ResNet') from ThreeDMM_shape import ResNet_101 as resnet101_shape from ThreeDMM_expr import ResNet_101 as resnet101_expr Inside ResNet/ThreeDMM_shape.py: sys.path.append('/home/usc/Desktop/Research/FG18/ExpNet_Code_Release/kaffe/tensorflow') from network_shape import Network_Shape Ok, so obviously I need to change this hard-coded absolute path. I'd like to do it the right way and not use my own specific path that I happened to install these files to. So I try from ..kaffee.tensorflow import Network_Shape >>> ValueError: Attempted relative import in non-package (1) I added __init__.py file in the ResNet folder (shown with the (*)) (2) I tried running the file as a module: python -m main_Exp input_file.csv (3) I also tried adding __init__.py to the top level folder (exp), though I believe doing so is nonsense. (4) Given that the first import was happening using the kaffe path that was appended to sys.path, I tried changing import to from .tensorflow.network_shape import Network_Shape Same error after all steps. So I'm not understanding the rules around relative imports and how to reference files in a sane way. I would really appreciate a pointer that helps me understand how to do this, and how to think about such imports in general! A: exp is indeed not a package and won't be made to a package even if you add an init file to it, cause that won't magically add it to the paths python looks for packages. If you do add the __init__.py you can then run as python -m exp.main_Exp input_file.csv (from ../exp). This would make python recognize exp as a package and kaffe/ResNet as subpackages. You would need to change imports to from ResNet.ThreeDMM_shape import ResNet_101 as resnet101_shape etc. Edit in response to comment: Running from the parent dir using the m switch is the recommended way of running the script see for instance https://stackoverflow.com/a/23540051/281545 (that's for python 3 however it should still apply). If you want to avoid it (it would break hardcoded relative paths for one) you should add exp to sys path (once maybe is enough) then change the imports to absolute ones as in: # main_Exp.py sys.path.append(os.path.abspath(os.path.dirname(__file__))) # the exp folder from ResNet.ThreeDMM_shape import ResNet_101 as resnet101_shape from ResNet.ThreeDMM_expr import ResNet_101 as resnet101_expr # ResNet/ThreeDMM_shape.py from kaffee.tensorflow import Network_Shape
doc_23532556
For example: print [1,"string",:symbol,[?l, ?i, ?s, ?t]].inspect will print [1, "string", :symbol, ["l", "i", "s", "t"]] Is there any similar facility in python which allows me to print the content of some arbitrary variable? A: Use repr. It returns a string containing a printable representation of an object. (similar to Object#inspect in Ruby) >>> repr([1,"string", ':symbol', ['l', 'i', 's', 't']]) "[1, 'string', ':symbol', ['l', 'i', 's', 't']]" BTW, there's no symbol literal (:symbol) or single character string literal (?x) in Python; replaced them with string literals in the above example.
doc_23532557
Is there a way to force Maven to fast-fail in this case? As a minimal example, take this pom, <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.mycompany.app</groupId> <artifactId>my-app</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>my-app</name> <build> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources> </build> <profiles> <profile> <id>production</id> <properties> <foo>Craig</foo> </properties> </profile> </profiles> </project> And have a resource to filter: echo 'Hello, my name is ${foo}!' > src/main/resources/test Then running mvn clean install -Pproduction produces a file that says Hello, my name is Craig! while running mvn clean install produces a file that says Hello, my name is ${foo}!. So my question is; how do I force Maven to fail in the second case? A: JIRA issues exist for this feature in The Codehause database: * *MRESOURCES-163 Filtering: check if there are any placeholders that were not substituted *MRESOURCES-162 Fail build if resource not fully filtered You can log in and vote for them. Unfortunately the demand for this important safety net feature seems to be low ... strange. A: Of course, the Apache Maven Enforcer Plugin is your friend, especially the RequireProperty Rule
doc_23532558
A spy is always based on a real object. Hence you must provide a class type rather than an interface type, along with any constructor arguments for the type. If no constructor arguments are provided, the type’s default constructor will be used. Method calls on a spy are automatically delegated to the real object. Likewise, values returned from the real object’s methods are passed back to the caller via the spy. Also: When stubbing a method on a spy, the real method no longer gets called: subscriber.receive(_) >> "ok" Instead of calling SubscriberImpl.receive, the receive method will now simply return "ok". If a spy is just an interface layer between a real object and the caller, why not just use the real object? What does using a spy offer that using the real object or a Mock do not? It seems to be in this void between a Mock and a real object to me. A: Spies can be used in different scenarios. However, it is good if you can implement your tests without resorting to spies. (Think twice before using this feature. It might be better to change the design of the code under specification.) * *They can be used to verify that a method was called without mocking the method itself *You can stub out calls that you don't want to happen *You can use partial mocks to test the object itself // this is now the object under specification, not a collaborator def persister = Spy(MessagePersister) { // stub a call on the same object isPersistable(_) >> true } when: persister.receive("msg") then: // demand a call on the same object 1 * persister.persist("msg") Example and quote are from the docs @ http://spockframework.org/spock/docs/1.1/all_in_one.html#Spies A: In my practice I prefer to use a real objects as much as possible. In case when only one method is to be mocked I still use a real object but with overridden needed method: MyDomainClass myRealObjectWithMockedMethod = new MyDomainClass() { @Override Object doSomething() { return "hard coded or mocked result"; } } // test what you need myRealObjectWithMockedMethod.action(); Note, this way works only of overridden method is not final. Otherwise Spy will help to define a behavior of this method. A: A spy offers the possibility to use the original object but also mock out one method. For example you have a class where you want to test the implementation of the toString() method. But this calls an long running method which needs some external access like a database. In this case you use a spy and let your long running method return some test string and then use the toString from the original object. Or like the spock example the method subscriber.receive maybe needs a server which sends out asynchronous messages. To write an test for subscriber not relying on the server or to handle asynchronous complexity you let the spy return ok and can easily test your methods which will rely on a server ok.
doc_23532559
<div id="panel-1" class="panel"> <div class="panel-header> <span>Header Text</span> <div class="toggle-expansion"></div> </div> <div class="panel-body">...</div> <div class="panel-footer">...</div> </div> <div id="panel-2" class="panel"> ... </div> ... We are using Backbone.js to set up all the views, and there is a file named base-panel-view.js that all of the other panels extend from. I would like to put my function here if possible so I don't have to rewrite the function for every panel. Here is a snippet of the base-panel-view.js file: ... events: { ... "click .toggle-expansion" : "toggleExpansion" }, ... toggleExpansion: function() { var panel = $(this); //Returns the entire panel var panelBody = panel.children(".panel-body"); //Should return the panel body var toggleButton = panel.find(".toggle-expansion"); //Should return the toggle button if(panelBody.hasClass("noDisplay")){ /* If the panel is collapsed, expand it */ panelBody.removeClass("noDisplay"); toggleButton.addClass("expanded").removeClass("collapsed"); }else{ /* If the panel is expanded, collapse it */ panelBody.addClass("noDisplay"); toggleButton.addClass("collapsed").removeClass("expanded"); } } ... The panel variable gets set to the entire panel, which is what I expected, however panelBody and toggleButton are left empty. In the Chrome debugger, I am able to confirm that panel is containing the correct panel for whichever button I press, and I can see that the other variables are empty arrays. In the debugger, I can view panel's array containing it’s children, which includes the panel body, and header (which contains the button). Is there something obvious that I’m doing wrong or not doing? I'm still relatively new to Javascript and jQuery, so it's entirely possible I'm messing up some fundamental step. Any help would be greatly appreciated. Also I can confirm that the css is correct, since I made two buttons elsewhere that expand/collapse all panels, and I select the panel bodies there by using $(".panel-body"). However for this question, I am only concerned with the panel for the corresponding button that was pressed. A: EDIT: I see now that you're using Backbone. Looking at this, you can see that this is the Backbone View, not a DOM element. To get the jQuery element, you have to use this.$ as seen in the code in that link, not $(this). EIDT2: For any future readers, this was the problem, but not the exact solution. The OP was able to (as mentioned in the comments), replace this: var panel = $(this); with this: var panel = this.$el; And everything worked accordingly. A: (this).$element In jQuery functions, this most often refers to the actual DOM element you're dealing with, whereas $(this) returns a jQuery object that wraps the element. Below is a sample code this.$('#clientsTable') .closest('.dataTables_wrapper') .find("div.toolbar") .html('<div class="table-tools-actions"><button class="btn btn-primary" id="addSelectedClients" onClick = addAllSelectedMembers()>' + "Add" + '</button></div>'); This above code takes my table is which in my case is clientsTable and searches for class dataTables_wrapper and then appends my HTML code block
doc_23532560
fiddle: link code: HTML <html> <body> <div id="app" class="demo"> <div> <button v-on:click="on=!on"> toggle </button> </div> <div class="background"> <div class="container"> <transition name="fade-outin" mode="out-in"> <red v-if="on"></red> <blue v-else></blue> </transition> <transition name="fade-down"> <div v-if="!on"> <div style="height: 25px"></div> <green></green> </div> </transition> </div> </div> </div> </body> </html> JS var red = { template: "<div style='width:150px; height:150px; border:10px solid red;'></div>" }; var blue = { template: "<div style='width:150px; height:150px; border:10px solid blue;'></div>" }; var green = { template: "<div style='width:150px; height:150px; border:10px solid green;'></div>" }; var app = new Vue({ el: '#app', data: { on: true }, components: { red, blue, green } }) CSS body { padding: 20px; } .background { border: 1px solid #000; display: flex; flex-direction: row; justify-content: center; align-items: center; width: 100%; height: 500px; overflow: hidden; } .container { background-color: #abc; display: flex; flex-direction: column; justify-content: center; align-items: center; padding: 20px; } .fade-outin-enter-active, .fade-outin-leave-active { transition: opacity 0.5s ease-in-out; } .fade-outin-enter, .fade-outin-leave-to { opacity: 0; } .fade-down-enter-active { transition: all 0.5s ease-in-out 0.5s; } .fade-down-leave-active { transition: all 0.5s ease-in-out; } .fade-down-enter, .fade-down-leave-to { max-height: 0; opacity: 0; transform: translateY(-65px); } Thanks for your time, H25E A: You can't use transition with height: auto, the CSS need a value to apply the transitions. In this case, you must to use the max-height for animate your component. See this article for more details: https://dev.to/sarah_chima/using-css-transitions-on-the-height-property-al0 I do some changes in your code. Try something like this, but you can improve: <html> <body> <div id="app" class="demo"> <div> <button v-on:click="toggle"> toggle </button> </div> <div class="background"> <div class="container" ref="container"> <transition name="fade-outin" mode="out-in"> <red v-if="on"></red> <blue v-else></blue> </transition> <transition name="fade-down"> <div v-if="!on"> <div style="height: 25px"></div> <green></green> </div> </transition> </div> </div> </div> </body> </html> var red = { template: "<div style='width:150px; height:150px; border:10px solid red;'></div>" }; var blue = { template: "<div style='width:150px; height:150px; border:10px solid blue;'></div>" }; var green = { template: "<div style='width:150px; height:150px; border:10px solid green;'></div>" }; var app = new Vue({ el: '#app', data: { on: true }, components: { red, blue, green }, methods: { toggle() { if (this.on) { this.$refs.container.style['max-height'] = '500px'; } else { this.$refs.container.style['max-height'] = '170px'; } this.on = !this.on; } } }) .container { background-color: #abc; display: flex; flex-direction: column; justify-content: center; align-items: center; padding: 20px; max-height: 170px; transition: max-height 3s; }
doc_23532561
I'm trying to display that number in the client: $.getJSON('https://www.linkedin.com/countserv/count/share?url=stackoverflow.com&format=json&callback=?', { dataType: "jsonp" }, function (data) { alert(data.count); }); Because of the X-Content-Type-Options: nosniff header being returned, I'm getting the refuse to execute script error in Chrome: Refused to execute script from 'https://www.linkedin.com/countserv/count/share?url=http://stackoverflow.com&format=json&callback=jQuery210014496755180880427_1426891580561&_=1426891580562' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled. Is there a workaround for this (aside routing the request through a proxy), or is it just impossible, as is the case with GitHub, unless LinkedIn fixes the issue? A: This looks like a duplicate of this post: Get LinkedIn share count JSONP Here's the answer recomended over there: myCallback = function(data) { alert(data.count); }; var url = "https://www.linkedin.com/countserv/count/share?url=http://stackoverflow.com&format=jsonp&callback=myCallback"; $.getScript(url); Here's a Fiddle to demonstrate: https://jsfiddle.net/z9u20ucm/1/
doc_23532562
Here's the content of my package.json file : { "name": "electron-app", "productName": "electronApp", "main": "public/electron.js", "version": "0.1.0", "private": true, "homepage": "./", "author": { "name": "John Doe", "email": "test@test.com" }, "build": { "appId": "app.com.electron", "productName": "electronApp", "linux": { "target": [ { "target": "AppImage", "arch": [ "x64", "ia32", "armv7l", "arm64”" ], } ] }, "files": [ "build/**/*", "node_modules/**/*" ], "directories": { "buildResources": "assets" } }, "eslintConfig": { "extends": "react-app" }, "dependencies": { "apexcharts": "^3.10.1", "apisauce": "^1.0.3", "cross-env": "^6.0.3", "electron-is-dev": "^1.1.0", "electron-root-path": "^1.0.16", "moment": "^2.24.0", "node-sass": "^4.12.0", "prop-types": "^15.7.2", "react": "^16.8.6", "react-code-input": "^3.8.1", "react-dom": "^16.8.6", "react-loading-overlay": "^1.0.1", "react-notification-system": "^0.3.0", "react-redux": "^7.1.0", "react-router-dom": "^5.1.2", "react-scripts": "3.0.1", "react-tradingview-widget": "^1.3.2", "react-web-tabs": "^1.0.1", "redux": "^4.0.1", "redux-persist": "^5.10.0", "reduxsauce": "^1.1.0", "seamless-immutable": "^7.1.4" }, "scripts": { "lint": "eslint", "build": "yarn react-build && yarn electron-build", "react-start": "react-scripts start", "react-build": "react-scripts build", "react-test": "react-scripts test --env=jsdom", "react-eject": "react-scripts eject", "electron-postinstall": "electron-builder install-app-deps", "electron-start": "concurrently \"cross-env BROWSER=none yarn react-start\" \"wait-on http://localhost:3000 && electron .\"", "electron-build": "electron-builder" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "devDependencies": { "@types/jest": "^24.0.15", "@types/react": "^16.8.22", "@types/react-redux": "^7.1.1", "babel-eslint": "10.0.1", "concurrently": "^5.0.0", "electron": "^7.1.1", "electron-builder": "^21.2.0", "eslint": "5.16.0", "eslint-plugin-react": "^7.14.2", "wait-on": "^3.3.0" } } I don't know, maybe I need some additional dependencies, like for the .deb version, but I really, do not have a clue, what the problem can be in... A: This is a Desktop Environment/File Manager issue. They are recognizing the file type properly but they don't execute it (as they should). The probable cause of this issue is that the AppImage file doesn't have execution permissions (they are not preserved when the file is downloaded). The immediate solution is to ask your users to make it executable. You can achieve this by using checking the "allow execution" permission in the file properties tab of your file manager or by using the command line instruction: chmod +x ./MyApp.AppImage. It's also explained here https://docs.appimage.org/introduction/quickstart.html#ref-how-to-run-appimage A: An .AppImage need to be on ext3/ext4 partition. If your partition is NTFS
doc_23532563
The incrementation somehow changes the value of acc_points from 5 to 1. I also considered if the problem had something to do with sessions. I've looked around for relevant information but couldn't find a solution. Would like to find out the real cause of this issue. Thanks! Here are the codes: .php file <?php require 'dbcon.php'; session_start(); $acc_points = $_SESSION["acc_points"]; $acc_id = $_SESSION["acc_id"]; if(isset($acc_points)) { $acc_points++; } $result = $con->prepare(" UPDATE `points` SET `acc_points` = ? WHERE `acc_id` = ? "); $result->bind_param("ii", $acc_points, $acc_id); $result->execute(); if($acc_points != null) { $response = $acc_points; echo $_GET['callback'] . '(' . json_encode($response) . ')'; } else { $response = "'Failed. Please try again.'"; echo $_GET['callback'] . '(' . json_encode($response) . ')'; } //connection closed mysqli_close ($con); ?> js file $(document).ready(function() { $("#qrtest").click(function() { { $.ajax({ type: "GET", url: "http://127.0.0.1/MP/appqrcode.php?callback=?", dataType: 'JSONP', async: false, jsonp : "callback", jsonpCallback: "jsonpcallback", success: function jsonpcallback(response) { alert(response.acc_points); } }) } }); }); A: The first problem is that you are checking the value of $acc_points in the code below, but you are executing the query regardless of whether it's null or not null if(isset($acc_points)) { $acc_points++; } // if condition ends here. Insert command will always be executed. Then after the comand has been executed you check the value again if($acc_points != null) /// insert has already happend. { } So you should restructure your code, but better still, you don't need this approach at all. Why not just? $result = $con->prepare(" UPDATE `points` SET `acc_points` = acc_points+1 WHERE `acc_id` = ? "); This increments the value already in the database.
doc_23532564
Is there a way to get all the PartDoc information upon importing an AssemblyDoc file? The closest I got to was getting the Body2 objects from the AssemblyDoc using GetComponents() and GetBodies2() function described here. I had hoped that I could somehow grab the PartDocs from the bodies but I've found no way out. Thank you in advance! A: GetComponents return an array of IComponent2s. For each component you can call GetModelDoc2 method to retrieve corresponding ModelDoc which can be either PartDoc, or AssemblyDoc.
doc_23532565
cheers Allan A: AAD supports both the assertion grant type as well as the client_assertion grant type. In the assertion grant type the following assertion types are supported: * *urn:ietf:params:oauth:grant-type:saml1_1-bearer *urn:ietf:params:oauth:grant-type:saml2-bearer There is also a urn:ietf:params:oauth:grant-type:jwt-bearer assertion type. However, this assertion type is only used to obtain an access token for a downstream service, from an access token presented by a native client. (See here for an example: https://github.com/AzureADSamples/WebAPI-OnBehalfOf-DotNet) ADAL.NET exposes the assertion grant type through AcquireToken methods that take a UserAssertion object. The client_assertion flow is for authenticating a server and it can be accessed through AcquireToken methods that take a ClientAssertion object. For an example of using the client assertion flow see this example: https://github.com/AzureADSamples/Daemon-CertificateCredential-DotNet And of course the ADAL .NET implementation code resides here: https://github.com/AzureAD/azure-activedirectory-library-for-dotnet
doc_23532566
What I need is a way so that I can get the notification that the use has indeed changed their avatar to something else. I tried finding in XEPs and found out that in XEP-0153 point 3.2, it's mentioned that there is a way using hash to check if the client has a cached copy, if not it downloads the new copy of the data. I am sure XMPPFramework does it automatically. Is there any way to find out if the user happened to change their profile pic?
doc_23532567
Basically how http://www.5050.degstu.com/ does it, but with no host restrictions or URL limit. I'm pretty much lost with where to begin, and surprised that this doesn't already exist. Is it simply impossible to make for reasons beyond my understanding? I'm still relatively new to the dev world and might not fully grasp the complications involved with this. Thanks in advance. A: Put this in a script in the page that the TinyURL leads to: var urls = ['url1', 'url2', 'url3']; var url = urls[Math.floor(Math.random() * urls.length)]; window.open(url, '_self'); It selects a random URL from a list of URLs, and then opens it in the same tab. A: Let's take a look at how 5050 does it if you're interested. I just made a quick one and logged my connection with fiddler. Here's what I got: Request: GET http://5050.degstu.com/v.php?l=qmf72tfeaya5y78 HTTP/1.1 Host: 5050.degstu.com Connection: keep-alive (and other headers that aren't really relevant) Response: HTTP/1.1 302 Moved Temporarily Server: nginx/1.12.1 Date: Thu, 10 Aug 2017 03:39:24 GMT Content-Type: text/html Content-Length: 0 Connection: keep-alive Location: http://www.vimeo.com So they're using Option A from my comment - the server keeps some kind of database that matches the "qmf72tfeaya5y78" to the two URLs I gave (YouTube and Vimeo's homepages), and then the server sends back an HTTP 302 to tell my browser to redirect to one of those pages.
doc_23532568
Consider a sequence A = a1, a2, a3, ... an of integers. A subsequence B of A is a sequence B = b1, b2, .... ,bn which is created from A by removing some elements but by keeping the order. Given an integer sequence A, the goal is to compute an alternating subsequence B, i.e. a sequence b1, ... bn such that for all i in {2, 3, ... , m-1}, if b{i-1} < b{i} then b{i} > b{i+1} and if b{i-1} > b{i} then b{i} < b{i+1}** Consider an online version of the problem, where the sequence A is given element-by-element and each time, one needs to directly decide whether to include the next element in the subsequence B. Is it possible to achieve a constant competitive ratio (by using a deterministic online algorithm)? Either give an online algorithm which achieves a constant competitive ratio or show that it is not possible to find such an online algorithm. Assume sequence [9,8,9,8,9,8, .... , 9,8,9,8,2,1,2,9,8,9, ... , 8,9,8,9,8,9] My Argumentation: The algorithm must decide immediately if it inserts an incoming number into the subsequence. If the algorithm now gets the numbers 1 then 2 then 2 it will eventually decide that they are part of the sequence and thus by a nonlinear factor worse than the optimal solution of n-3. -> No constant competitive ratio! Is this a proper argumentation? A: If I understood what you meant, your argument is correct, but the sequence you gave in the example is wrong. for example the algorithm may choose all the 9's and 8's. You can alter your argument slightly to make it more accurate, for example consider the sequence 3,4,3,4,3,4,......, 1/5,2/6,1/5,2/6,.... Explanation: You start the sequence with 3,4,3,4,... etc. until the algorithm picks two numbers. If it never does, it's obviously not competitive (it gets 0/1 out of n) If the algorithm picked a 3, then 4, the algorithm must next take a number lower than 4. By continuing with 5,6,5,6,... the algorithm cannot take another number. If the algorithm chose to take a 4 then a 3, by a similar resoning we can easily see how continuing with 1,2,1,2,... prevents the algorithm from taking another nubmer. Thus, in any case, the algorithm cannot take more than 2 numbers for every n, which, as you stated, isn't a constant competitive ratio.
doc_23532569
Thanks! A: These are some of the methods to print a string in python, along with their speeds: 1. Method: print('Hello world!') Time: 3.472566604614258e-05 2. Method: os.system("echo 'Hello world!'") Time: 0.0050920481681823735 3. Method: sys.stdout.write('Hello world!\n') Time: 0.00018532516956329347 We observe that method 1 is the fastest. The code used to calculate the time: import time import sys import os listf = [] for i in range(10000): start = time.time() print_function_to_be_timed('Hello world!') stop = time.time() listf.append((stop-start)) print(sum(listf) / len(listf))
doc_23532570
String a = jTextField1.getText(); int d1= Integer.parseInt(a); int Arry[] = {d1}; int sum = 0; for ( int i = 0; i<Arry.length; i++ ) { sum=sum + Arry[i]; } jTextField2.setText(sum+""); A: If jTextField1 contains not only numbers, you may want to extract all the digits like this: Pattern p = Pattern.compile("-?\\d+"); Matcher m = p.matcher(jTextField1.getText()); List<Integer> numbers = new ArrayList<>(); while (m.find()) { numbers.add(Integer.parseInt(m.group())); } then sum the numbers: int sum = 0; for (Integer number : numbers) sum += number; A: If you can guarantee that the JTextField will only contain input that can be parsed into ints, e.g. no letters or symbols, then the only possible remaining issue is whitespace between your numbers. I would suggest that you go to the Pattern API and look for characters that can detect whitespace and then go to String API and find a method that can split a String based on an input regular expression (regex). Then from there you can easily parse the split String into ints and get your sum. For example: String a = jTextFieldName.getText(); String[] storage = a.someSplittingMethod("whitespace regex"); int sum = 0; for(int c = 0; c < storage.length; c++) sum += Integer.parseInt(storage[c]);
doc_23532571
Code: ==== set AWS_ACCESS_KEY_ID='ABCDED' set AWS_SECRET_ACCESS_KEY='12345' azcopy cp "https://s3://emp-data/tsc/" "https://empdata.blob.core.windows.net/awstosf/" --recursive The above code is not working and getting invalid syntax A: In Azure Databricks, to work with CLI tools, you need to install databricks-cli using pip install databricks-cli. Also, configure the cli token using databricks configure --token command. Also, instead of setting the variable programmatically, you should set them using UI in clusters. Follow: Databticks -> Cluster -> Environment Variables. So, your AWS_ACCESS_KEY_ID=<access-key> and AWS_SECRET_ACCESS_KEY=<secret-access-key> will be set in cluster level. Source: File manipulation Commands in Azure Databricks
doc_23532572
if (knownAttribute.AttributeType.Value.Equals("Product Specification")) { Console.WriteLine("Started a thread for: " + knownAttribute.AttributeTypeId + ", " + knownAttribute.Value); while (true) { /* if (AS400SpecificationAttributes.IsEmpty && knownSpecificationBag.IsEmpty && gatherRowsTasks.All(x => x.IsCompleted)) break;*/ AS400SpecificationAttribute AS400SpecificationAttributeWork = null; AS400SpecificationAttributeWork = knownSpecificationBag.Keys.FirstOrDefault(x => x.AttributeName == knownAttribute.Value); if (AS400SpecificationAttributeWork != null) { var product = ctx.Products.FirstOrDefault(x => x.ProductNumber == AS400SpecificationAttributeWork.ProductNumber); if (product == null) continue; var productAttribute = new ProductAttribute(); productAttribute.Attribute = knownAttribute; if (AS400SpecificationAttributeWork.AttributeValue != null) { var knownAttributeOption = ctx.AttributeOptions.FirstOrDefault(x => x.Attribute.Equals(knownAttribute) && x.Value.Equals(AS400SpecificationAttributeWork.AttributeValue)); if (knownAttributeOption == null) { knownAttributeOption = new AttributeOption(); knownAttributeOption.Value = AS400SpecificationAttributeWork.AttributeValue; knownAttributeOption.Attribute = knownAttribute; ctx.AttributeOptions.InsertOnSubmit(knownAttributeOption); ctx.SubmitChanges(); } productAttribute.AttributeOption = knownAttributeOption; productAttribute.AttributeOptionId = knownAttributeOption.Id; } product.ProductAttributes.Add(productAttribute); ctx.SubmitChanges(); string tmpstr = null; if (!knownSpecificationBag.TryRemove(AS400SpecificationAttributeWork, out tmpstr)) Thread.Sleep(50); } else { if (tryCounter < 5) { tryCounter++; Thread.Sleep(1000); Console.WriteLine("Thread waiting for work: Product Specification:" + knownAttribute.Value); continue; } else { int outVal; threadTracker.TryRemove("Product Specification:" + knownAttribute.Value, out outVal); Console.WriteLine("Closing Thread: Product Specification:" + knownAttribute.Value); break; } } Thread.Sleep(50); } It seems like the following Attribute element refuses to be removed. I don't understand why. If i put it in a while(!dic.tryRemove(ele)) it will forever be stuck and never move from there. There may be an error somewhere within the thread but I have no idea why. A: This statement if (!knownSpecificationBag.TryRemove(AS400SpecificationAttributeWork, out tmpstr)) will always return true or false. It won't block. That's the behavior of ConcurrentDictionary. It will return false if the key is not in the dictionary. If you're looping while that method returns false and it's stuck, that means that the item isn't in the dictionary when the loop begins. Either it either was never in the dictionary or that another thread already removed it. Is your intention to loop until the item is not in the dictionary? You could try this: if (!knownSpecificationBag.TryRemove(AS400SpecificationAttributeWork, out tmpstr) && !knownSpecificationBag.ContainsKey(AS400SpecificationAttributeWork)) A: Implement proper equals and gethashcode when using TryRemove public override int GetHashCode() { return new { this.name, this.value, this.group, this.productNumber }.GetHashCode(); } public bool Equals(AS400SpecificationAttribute other) { if (other == null) return false; return (this.ProductNumber.Equals(other.productNumber) && ((this.group != null && this.group.Equals(other.AttributeGroup)) || (this.group == null && other.AttributeGroup == null)) && ((this.name!= null && this.name.Equals(other.AttributeName)) || (this.name == null && other.AttributeName == null)) && ((this.value != null && this.value.ToUpper().Equals(other.AttributeValue.ToUpper())) || (this.value == null && other.AttributeValue == null))); }
doc_23532573
My data: var objArray = [{ state: 'NY', type: 'A', population: 100 }, { state: 'NY', type: 'A', population: 300 }, { state: 'NY', type: 'B', population: 200 }, { state: 'CA', type: 'A', population: 400 }, { state: 'CA', type: 'A', population: 400 }]; If an entry has the same state AND type I need to combine it into a single entry and sum their populations. Finally I need to map it to an array in this format. var outputArray = [ ['A', 'NY', 400 ], ['B', 'NY', 200], ['A', 'CA', 800] ] A: Well, first you'd want to reduce it. This can be done like so... objArray.reduce((prev, obj) => { if(1 + (indx = prev.findIndex(oldObj => oldObj.type === obj.type && oldObj.state === obj.state))) { prev[indx].population += obj.population; } else { prev.push({...obj}) } return prev; }, []) This takes the array being gathered, and modifies it in some way and returns it in the reduce callback. It will either modify an existing value's population, if it can find one with the correct state and type; or it will append a new object to the end of the array. Now you need to map it. .map(obj => [ obj.type, obj.state, obj.population ]) A: I would recommend using the lodash package (it is an extremely common package in Javascript applications). It adds a lot of great functions for manipulating arrays. This post explains how to sum values on groups. You will need to modify this answer slightly to account for your two parameters, which you can do by changing the groupBy command to this: _.groupBy(objArray, function(val){ return val.state + "#" + val.type }) A: You could try something like this: var arr = Object.keys(objArray).map(function (key) { return Object.keys(objArray[key]).map(function (key) { return [[objArray[0].state, objArray[0].type, objArray[0].population],[objArray[1].state, objArray[1].type, objArray[1].population]]}); })[0][0]; A: If you know state and type will never have a certain character such as '_' you can make a key out of state and type such as 'NY_A' - a little like a composite key in a DB. Then you just create an object with these keys, add the populations and then pull them apart into an array: Object.entries( objArray.reduce((acc,curr) => ( acc[curr.type + '_' + curr.state] = curr.population + (acc[curr.type + '_' + curr.state] || 0) , acc), {})) .map(item => [...item[0].split('_'), item[1]]) A: const _ = require('lodash') const input = [ { state: 'NY', type: 'A', population: 100 }, { state: 'NY', type: 'A', population: 300 }, { state: 'NY', type: 'B', population: 200 }, { state: 'CA', type: 'A', population: 400 }, { state: 'CA', type: 'A', population: 400 } ] const expected = [ ['A', 'NY', 400], ['B', 'NY', 200], ['A', 'CA', 800] ] const output = _(input) .groupBy(({ state, type }) => [state, type].join(':')) .mapValues((states) => states.reduce((total, { population }) => total + population, 0)) .map((population, stateType) => { const [state, type] = stateType.split(':') return [type, state, population] }) .value() console.log(expected) console.log(output)
doc_23532574
"Alamo Square Park, Steiner St & Hayes Street, San Francisco, CA 94117, USA" when I set the variable in my razor view file like this var viewModelFormattedAddress = @Html.Raw(Model.FormattedAddress); I get an error! If I just pass the value in quotes as a string to the variable it converts the special characters to non HTML characters like so "Alamo Square Park, Steiner St &amp Hayes Street, San Francisco, CA 94117, USA" if I do this var viewModelFormattedAddress = "@Model.FormattedAddress"; I don't want this because then I have to convert it back. Why is an error being thrown when I do a @Html.Raw() call? UPdate - here is what I'm trying var viewModelFormattedAddress = @Html.Raw(Json.Encode(Model.FormattedAddress)).ToString(); this is the error JavaScript critical error at line 297, column 41 in https://localhost:44368/Home/Events?date=7/19/2017&formattedaddress=Alamo+Square+Park,+Steiner+St+&+Hayes+Street,+San+Francisco,+CA+94117,+USA&latitude=37.7763694&longitude=-122.434819&maptype=establishment\n\nSCRIPT1002: Syntax error and this is what it's showing in the dynamic page var viewModelFormattedAddress = &quot;Alamo Square Park, Steiner St \u0026 Hayes Street, San Francisco, CA 94117, USA&quot;; A: I think you forgot the quotes... try this: var viewModelFormattedAddress = "@Html.Raw(Model.FormattedAddress)"; Instead of var viewModelFormattedAddress = @Html.Raw(Model.FormattedAddress);
doc_23532575
Looking for the best approach, Thanks in advance A: See Monitoring Shape Based Region in the Location Awareness Programming Guide. - (BOOL)registerRegionWithCircularOverlay:(MKCircle*)overlay andIdentifier:(NSString*)identifier { // Do not create regions if support is unavailable or disabled if ( ![CLLocationManager regionMonitoringAvailable]) return NO; // Check the authorization status if (([CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorized) && ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined)) return NO; // Clear out any old regions to prevent buildup. if ([self.locManager.monitoredRegions count] > 0) { for (id obj in self.locManager.monitoredRegions) [self.locManager stopMonitoringForRegion:obj]; } // If the overlay's radius is too large, registration fails automatically, // so clamp the radius to the max value. CLLocationDegrees radius = overlay.radius; if (radius > self.locManager.maximumRegionMonitoringDistance) { radius = self.locManager.maximumRegionMonitoringDistance; } // Create the region to be monitored. CLRegion* region = [[CLRegion alloc] initCircularRegionWithCenter:overlay.coordinate radius:radius identifier:identifier]; [self.locManager startMonitoringForRegion:region]; return YES; }
doc_23532576
Edit: @Some programmer dude requested an example, so here it is, but it's quite long, so sorry about that. Suppose the following AST structure: namespace node { template <typename T> struct component { // Not default constructible. component (T &&); component (component &&); component & operator = (T &&); component & operator = (component &&); ~component (); T & get (); T const & get () const; private: T * ptr; }; template <typename T> struct optional_component { // Default constructible: optional_component (): ptr{nullptr} {} optional_component (T &&); optional_component (component &&); optional_component & operator = (T &&); optional_component & operator = (component &&); ~optional_component (); T & get (); T const & get () const; // Need to check for present value before use: bool has_value () const { return ptr; } private: T * ptr; }; struct C { int val; }; struct A { // Not default constructible, because component<C> is not. component<C> bar; }; struct B { // Default constructible, because component<C> is too. optional_component<C> c; } } namespace category { struct X { // Not default constructible, // unless the first type of the variant is default constructible, // or I provide the default constructor manually. std::variant<node::A, node::B> node; }; } And the following parser definition: %language "c++" %define api.value.type variant %define api.value.automove %parse-param { category::X & result } %token A %token B %token BB %token <int> C %nterm <node::A> node_a %nterm <node::B> node_b %nterm <node::C> node_c %nterm <int> start %% start: node_a { result = {.node = $node_a}; } | node_b { result = {.node = $node_b}; } node_c: C { $$ = {.val = $1}; } node_a: A node_c { $$ = {.c = $node_c}; } node_b: B node_c { $$ = {.c = $node_c}; } | BB { $$ = {}; } The generated parser first tries to default construct the nodes. E.g.: yylhs.value.emplace<node::A>(); And only then assigns the value. E.g: yylhs.value.as<node::A>() = {.c = YY_MOVE(yystack_[1].value.as<node::C>())}; What I need is to skip the default constructing emplace call and actually construct the node with the given child nodes directly. I've found this in the generated header file: # if 201103L <= YY_CPLUSPLUS /// Instantiate a \a T in here from \a t. template <typename T, typename... U> T& emplace (U&&... u) { return *new (yyas_<T> ()) T (std::forward <U>(u)...); } # else /// Instantiate an empty \a T in here. template <typename T> T& emplace () { return *new (yyas_<T> ()) T (); } /// Instantiate a \a T in here from \a t. template <typename T> T& emplace (const T& t) { return *new (yyas_<T> ()) T (t); } # endif So it seems that the emplace method is actually meant to be able to construct the final value directly. A: As I understand it, the intent of the bison implementation in this case is to avoid the possibility of an uninitialised variant value, which would be lead to undefined behaviour because of the nature of a Bison variant. The bison variant does not record the type of the object it has been initialised with, because that case never occurs during a parse. So as soon as the parser knows which type the stack slot will contain (which is to say, when it decides that it will execute the reduction action), it must initialise the stack slot, and it can only use a default constructor because it hasn't yet executed the reduction action. A Bison variant object is basically a union, not a discriminated union; the variant part refers to the fact that the control flow of the program is sufficient to determine the type of the contained object. So there can be no such thing as an uninitialised variant. Moreover, since the variant has an (implicit) type from the moment of its creation until the moment of its destruction, the type cannot be changed during its lifetime. So your desired semantics are at odds with this design. That doesn't make your semantics wrong (or, for that matter, bison's), but it does mean that you cannot use a bison variant if you want the possibility of an "uninitialised" variant. On the other hand, I'm not sure how you can accomplish this: However, I'd like to keep some (actually most) of my AST nodes non-default constructible, because that would leave them in an invalid state. If I allow default construction of every node, I'd have to rely on runtime checks to ensure that every node I'm working with is valid. The question is, what does it mean for an AST node to be in an invalid state? And how will you know that to be the case without a runtime check? Do you expect it to throw an exception on use or some such? If so, there is definitely a run-time check. You could implement an invalid state by using a std::variant whose first alternative is a default-constructible InvalidNode type, or some such, although you'll have to take care that it doesn't become an no-op instead of an error when you try to use the variant object. In that case, you could tell Bison to use std::variant as a semantic type, although that won't be quite as convenient as using a Bison variant. Note: In a comment (which is not at all the best place to clarify a question) you seem to be saying that your desired variants are always pointers, meaning that the "invalid node" type is essentially a nullptr. I'm sure that can be made to work with Bison, but you'll need to do it in a different way than the use of Bison variants. How good a match it is for std::variant is not entirely clear to me either :-) A: With helpful explanations from @rici and after some deeper examination of the generated C++ file for the parser, I've found a rather "dirty" solution. I don't think it's a good idea to rely on such a solution, but it works and I'd like to share it: Before executing the actions specified in the parser definition, Bison pushes some default values to its stack by calling: yylhs.value.emplace< type > (); ...where type is the semantic value type of the corresponding non-terminal in the parser definition. Only after that, it proceeds to execute the appropriate action that might assign a value to this newly pushed item. Bison has no way of knowing whether any value will be assigned, so it has to push at least this default constructed value. However, if you are sure, that you assign a value in every action, you don't really need these default constructions. So my solution is to simply tweak the generated C++ file by modifying these default constructions to: yylhs.value.emplace< int > (); I do this by simply sticking a line of sed command in my makefile: sed -i 's/yylhs.value.emplace< my_ast_namespace::[^ ]* > ();/yylhs.value.emplace< int > (); \/\/ Modified./g' generated_parser.cpp (Note: The regex relies on the fact that there are always spaces inside the outer <> but no spaces in the contained type, otherwise it would be impossible to do with nested templates.) Now there is no need for a default constructor for my nodes. The pushed value has a wrong type, but in my case, it's not any worse to have an int value in there than to have the correct node with all of its children as null pointers - both will lead to incorrect behaviour. I won't accept my answer, since it's really just a "hacky workaround" that might break with different versions of Bison. I also don't want to accept the @rici's answer yet, because it seems that with this experiment I've confirmed, that it is in principle possible to do what I wanted.
doc_23532577
I want write a query all itemcode from all tables with sum qty, but some items do not match both tables. When I tried to write query with sum(tn2.sales + via1.sales + bcg.sales) I'm getting blank values. A: Try creating a 'view' of the tables and sum up the values as per your query A: There is probably a more elegant solution, but here is a quick way. Build three selects with unions and then sum that subquery up. select all_items.itemcode, all_items.Qty, sum(all_items.sales) from (Select itemcode, Qty, sum(sales)as sales from tn2 group by itemcode union Select itemcode, Qty, sum(sales) as sales from via1 group by itemcode union Select itemcode, Qty, sum(sales)as sales from bcg group by itemcode) all_items group by all_items.itemcode, all_items.Qty
doc_23532578
Basically, my idea is to have the localized files out of the box (for example on AWS S3 or something like this). I'm trying using this code: @Bean public LocaleResolver localeResolver() { SessionLocaleResolver slr = new SessionLocaleResolver(); slr.setDefaultLocale(Locale.US); return slr; } @Bean public ResourceBundleMessageSource messageSource() { ResourceBundleMessageSource rs = new ResourceBundleMessageSource(); rs.setBasename("http://www.myexternalservice.com/messages"); rs.setUseCodeAsDefaultMessage(true); return rs; } When I try to retrieve a message I use this: String message = messageSource.getMessage("keyname", null, Locale.US); But, in this case I read into the debug console this: ResourceBundle [http://www.myexternalservice.com/messages] not found for MessageSource: Can't find bundle for base name http://www.myexternalservice.com/messages, locale en_US I tried also with different Locale. Is it possible? A: I solved using this code example: @Bean public ReloadableResourceBundleMessageSource messageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename("http://www.myexternalservice.com/messages"); messageSource.setCacheSeconds(400); messageSource.setDefaultEncoding("UTF-8"); return messageSource; }
doc_23532579
but when I try to create the menu with menuItem created server side with two different command defined, I get an error in visualization but, when I use only one command, it works fine. I tried to use only one and it works fine, i tried to use first "ONE" and then "TWO" and it works fine but it explodes when i try to use both toghether. here's the code: DefaultMenuItem firstmenuitem = new DefaultMenuItem("ONE"); firstmenuitem.setIcon("ui-icon-newwin"); firstmenuitem.setCommand("#{myMB.loadDetail1(row, dynMetaCol.id)}"); firstmenuitem.setUpdate("dialog1"); firstmenuitem.setOncomplete("PF('DlgWv1').show()"); menuModel.addElement(firstmenuitem); DefaultMenuItem secondMenuItem = new DefaultMenuItem("TWO"); secondMenuItem.setIcon("ui-icon-newwin"); secondMenuItem.setCommand("#{myMB.loadDetail2(row, dynMetaCol.id)}"); secondMenuItem.setUpdate("dialog2"); secondMenuItem.setOncomplete("PF('DlgWv2').show()"); menuModel.addElement(secondMenuItem); the xhtml content is this: ... <p:menu overlay="true" trigger="dynaButton" my="left top" at="left bottom" styleClass="ui-menu-context ui-menuitem-link" model="#{myMB.menuModel}"/> ... the result: XML Parsing Error: unclosed CDATA section Location: http://myaddress/mywebapp/templates/myfolder /myfolder/mypage.xhtml Line Number 19, Column 5647: it seems like it is not able to render the actions and the update for the second command. please help. A: Since I cannot explain the issue, I found a workarond. symply, I deleted these lines: firstmenuitem.setUpdate("dialog1"); firstmenuitem.setOncomplete("PF('DlgWv1').show()"); secondMenuItem.setUpdate("dialog2"); secondMenuItem.setOncomplete("PF('DlgWv2').show()"); and into each action method (loadDetail1 and loadDetail2) I use this simple method: public static void updateAndShowDialog(String dialogId, String widgetVarName) { RequestContext requestContext = RequestContext.getCurrentInstance(); requestContext.update(dialog); requestContext.execute("PF('" + widgetVarName + "').show()"); } hope this can help. best regards.
doc_23532580
And ideas? <?php if ($terms = get_the_terms($post->ID, 'apartmentlevel')) { foreach ($terms as $term) { echo $term->slug ; } } ?> A: In the documentation, you can read that get_the_terms retrieves the terms of the taxonomy that are attached to the post. You should use get_terms() instead <?php if ($terms = get_terms('apartmentlevel',array('hide_empty' => false,))) { foreach ($terms as $term) { echo $term->slug ; } } ?> Documentation here : https://developer.wordpress.org/reference/functions/get_terms/
doc_23532581
I already use this javascript code: var devtools = /./; devtools.toString = function() { location.reload() } setInterval( () => {console.log('%c', devtools)} , 200 ) But it didn't work when i test it Can you give me script to auto reload the website when visitor open the dev tools/inspector/debuuger until he close the dev tools/inspector/debuuger? *I don't ask about how to remove inspect element
doc_23532582
To fix this error, we're cleaning all website cache. I don't feel comfortable with it! Who know, how can I fix it? And why this error occures every time (almost every time) when template is changed. Thank you. A: The best way to avoid this kind of issue is to upload to a temporary file, then rename it. That way there's no chance for a partial file appearing. As for why it happens every time, think about it. 400k page views per day == 4.6 requests per second average. Considering most sites I've ever seen have far more traffic over specific hours (during the day), I'd suspect that you're seeing upwards of 10 to 20 requests per second. at that rate, if the file write (because of the upload) takes longer than 0.05 seconds, the chance of a read while it's being written to rises sharply. So your choices (In order of most robust to least. You can always do multiple): * *Do the uploads after hours when traffic is (hopefully) lower... *Use a FTP server that does the renaming bit for you. *Manually rename the file when you upload the new one. (Important; Rename to overwrite the original. don't delete or move the original first)... *Hack Smarty to ignore the new files with a timestamp less than about 10 to 30 seconds old (Simply call filemtime() to determine when it was last modified. Be sure to call clearstatcache() first so you don't get an old time)...
doc_23532583
While in portrait mode I divide the screen height by 5 in order to set it the result as the height for text views. Hence no matter what screen there should allways be five textviews. I have a tablet with a 1280 pixel height, which display metrics height returns as 1232. In my phone with 1980, display metrics height shows 1776. These are the values that I divide by 5. I see the 5 textviews in my tablet perfectly but in my phone the lasts textview is almost entirely off the screen. So my question is what is the height that is returned? A: That height returned is the screen height, minus the height of the notification bar. But you still have things like the action bar taking space. A: Instead of dividing and do all the complicate math... If you use a LinearLayout, you can set the weights of your TextViews to fit the screen nicely. Just set all their weights to 1 and their height to 0dp. So, if tou have 4 TextViews, they will be as tall as the 25% of the usable height. If you have 5 (which is your case), they will be as tall as the 20% of the usable height. And you'll avoid headaches.
doc_23532584
String text = Integer.toString(question); According to book, it shows me the Question Text. I changed my code to this as well but it show me 0. String text = Integer.toString(Integer.toString(question)); Any solution for this. Thanks in Advance. Here is my complete code. QuizActivity.java package com.example.subrose.geoquiz; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class QuizActivity extends AppCompatActivity { private Button mTrueButton; private Button mFalseButton; private Button mNextButton; private TextView mQuestionTextView; private Question[] mQuestionBank = new Question[]{ new Question(R.string.question_oceans,true), new Question(R.string.question_mideast, false), new Question(R.string.question_africa, false), new Question(R.string.question_americas, true), new Question(R.string.question_asia, true), }; private int mCurrentIndex = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_quiz); mQuestionTextView = (TextView)findViewById(R.id.question_text_view); int question = mQuestionBank[mCurrentIndex].getTextResId(); mQuestionTextView.setText(question); mTrueButton = (Button)findViewById(R.id.true_button); mTrueButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(QuizActivity.this, R.string.correct_toast, Toast.LENGTH_SHORT).show(); } }); mFalseButton = (Button)findViewById(R.id.false_button); mFalseButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(QuizActivity.this, R.string.incorrect_toast, Toast.LENGTH_SHORT).show(); } }); } } Question.java public class Question { private int mTextResId; private boolean mAnswerTrue; public Question(int mTextResId, boolean mAnswerTrue) { mTextResId = mTextResId; mAnswerTrue = mAnswerTrue; } public int getTextResId() { return mTextResId; } public void setTextResId(int textResId) { mTextResId = textResId; } public boolean isAnswerTrue() { return mAnswerTrue; } public void setAnswerTrue(boolean answerTrue) { mAnswerTrue = answerTrue; } } Strings.xml <resources> <string name="app_name">GeoQuiz</string> <string name="true_button">True</string> <string name="false_button">False</string> <string name="next_button">Next</string> <string name="correct_toast">Correct!</string> <string name="incorrect_toast">Incorrect!</string> <string name="action_settings">Settings</string> <string name="question_oceans">The Pacific Ocean is larger than the Atlantic Ocean.</string> <string name="question_mideast">The Suez Canal connects the Red Sea and the Indian Ocean.</string> <string name="question_africa">The source of the Nile River is in Egypt.</string> <string name="question_americas">The Amazon River is the longest river in the Americas.</string> <string name="question_asia">Lake Baikal is the world\'s oldest and deepest freshwater lake.</string> </resources> activity_quiz.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" > <TextView android:id="@+id/question_text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="24dp" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/true_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/true_button"/> <Button android:id="@+id/false_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/false_button"/> </LinearLayout> <Button android:id="@+id/next_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/next_button"/> </LinearLayout> A: you can't set integer in settext so change code from mQuestionTextView.setText(question); to replace with mQuestionTextView.setText(String.valueOf(question)); A: int question = mQuestionBank[mCurrentIndex].getTextResId(); mQuestionTextView.setText(question); to set integer in TextView you have below possibilities : replace it with: mQuestionTextView.setText(String.format(Locale.US, "%d", question)); or mQuestionTextView.setText(question+""); or mQuestionTextView.setText(String.valueOf(question)); A: The main problem in your constructor . Change it as below. public Question(int mTextResId, boolean mAnswerTrue) { this.mTextResId = mTextResId; this.mAnswerTrue = mAnswerTrue; } You should use this in data shadowing . Currently value is not assigned to instance variable cause you just used local ones. That's why they are returning the default value. Do it as above . Apart from that setText() has several variant if you are using a resource id the you can directly use setText(int id). Read setText varients . A: Why don't you check using: mQuestionTextView.setText(getString(mQuestionBank[mCurrentIndex].getTextResId())); Anyway, I didn't see any error in your Code to set the text in your View.
doc_23532585
If I have an array of "services", where a Service is defined as: interface Service { id: string; dependencies?: [string] // refs to others Service.id's } Is there a way to make the dependencies array typesafe? To illustrate: import { Service } from './service.ts'; const services: Service[] = [ { id: "authors", }, { id: "comments", } { id: "posts", dependencies: [] // <-- type this as `Array<"authors | "comments">` } ] A: You can use unions to do something like this: type RawType = "authors" | "comments"; type RawId = { id : RawType }; type Posts = { id: "posts"; dependencies: RawType[]; } type Service = RawId | Posts; // then you can declare an array of Service const services: Service[] = [ { id: "authors", }, { id: "comments", }, { id: "posts", dependencies: [], } ]; Playground A: A little bit ugly - to ensure that the id is listed in the array of the dependnecies, you can do the following: type Id = 'id1' | 'id2' | 'id3' type Obj<CurrentId extends Id> = { id: CurrentId dependencies: Exclude<Id, CurrentId>[] } const obj: <CurrentId extends Id>(obj: Obj<CurrentId>) => Obj<CurrentId> = obj => obj const array = [ obj({ id: 'id1', dependencies: [], // compiled }), obj({ id: 'id2', dependencies: ['id1'], // compiled }), obj({ id: 'id3', dependencies: ['id3'], // compilation error }), obj({ id: 'id3', // note: compiled even when there are multiple objects with the same Id dependencies: [], }), ]
doc_23532586
While sniffing the files, I am supposed to use an xml file which uses three coding standards. When I try to set their paths one by one, only recent one gets stored and old standard gets replaced. phpcs --config-set installed_paths ../wordpress-coding-standards; phpcs --config-set installed_paths ../wordpress-coding-standards/PHPCompatibility; I also tried setting this value up with parent directory but it didn't work. Here's the final command which throws the errors: phpcs -p -s -v -n --standard=phpcs.xml /path/to/files This is the xml file which is being used in above command: https://github.com/xwp/wp-dev-lib/blob/master/phpcs.xml Any help would be appreciated. Thanks! A: Solved it by specifying multiple paths separated by commas. phpcs --config-set installed_paths first/path/,second/path/,yet/another/path/
doc_23532587
$scope.letters = ['A', 'B', 'C', 'D']; $scope.numbers = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]; $scope.selectedLetter = 0; I also have two select tags. The first select tag is populated by the options in letters. I want the second select tag to have the options be the subarray that corresponds to the index of the selected letter. Thus, when I pick 'B' in the first select tag, I want the second select tag to have the options [4, 5, 6, 7]. I also want the second select tag to not have a blank at the top and select the first option from the list as default. Here's what I've got so far in jsfiddle: http://jsfiddle.net/yhk138au/ I've been looking through the AngularJS docs and it seems like using $watch might be relevant here, but I'm new to Angular and not sure how to use it correctly in this case. Any help or tips would be much appreciated. <div ng-app="myapp"> <fieldset ng-controller="FirstCtrl"> <select ng-options="letters.indexOf(l) as l for l in letters" ng-model="selectedLetter"></select> <select ng-options="for num in numbers[selectedLetter]" ng-model="selectedNumber"></select> {{ selectedLetter }} {{ selectedNumber }} </fieldset> </div> var myapp = angular.module('myapp', []); myapp.controller('FirstCtrl', function ($scope) { $scope.letters = ['A', 'B', 'C', 'D']; $scope.numbers = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]; $scope.selectedLetter = 0; }); A: It seems you were just about there, you just need a $watch to set the initial value for the second select menu and to correct the syntax of the second ng-options property. Watch: $scope.$watch('selectedLetter', function(idx) { $scope.selectedNumber = $scope.numbers[idx][0]; }); Correct syntax: ng-options="num for num in numbers[selectedLetter]" Live demo. <div ng-app="myapp"> <fieldset ng-controller="FirstCtrl"> <select ng-options="letters.indexOf(l) as l for l in letters" ng-model="selectedLetter"></select> <select ng-options="num for num in numbers[selectedLetter]" ng-model="selectedNumber"></select> {{ selectedLetter }} {{ selectedNumber }} </fieldset> </div> var myapp = angular.module('myapp', []); myapp.controller('FirstCtrl', function ($scope) { $scope.letters = ['A', 'B', 'C', 'D']; $scope.numbers = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]; $scope.selectedLetter = 0; $scope.$watch('selectedLetter', function(idx) { $scope.selectedNumber = $scope.numbers[idx][0]; }); }); A: Your syntax was off a bit <select ng-options="num for num in numbers[selectedLetter]" ng-model="selectedNumber"></select> DEMO
doc_23532588
Didn't find class "java.lang.Character$UnicodeScript" on path: DexPathList when reaching the line document.add(new Paragraph("hello")); In the below code public void CreatePDF () throws IOException{ File file_pdf = new File("_TEST.pdf"); FileOutputStream fos = new FileOutputStream(file_pdf); PdfWriter writer = new PdfWriter(fos); PdfDocument pdf = new PdfDocument(writer); Document document = new Document(pdf); document.add(new Paragraph("hello")); document.close(); } I have included the followings in \libs : itext7-io-7.0.1.jar itext7-kernel-7.0.1.jar itext7-layout-7.0.1.jar slf4j-api-1.7.22.jar slf4j-simple-1.7.22.jar and following dependencies : <dependency> <groupId>com.itextpdf</groupId> <artifactId>kernel</artifactId> <version>7.0.1</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>layout</artifactId> <version>7.0.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.22</version> </dependency> Any ideas what's wrong ? Thanks in advance A: The official answer: iText 7 requires Java 7. The error tells you that the class Character.UnicodeScript is missing. When you check the API documentation, you discover that this class was introduce in Java version 1.7: http://docs.oracle.com/javase/7/docs/api/java/lang/Character.UnicodeScript.html (look for Since: on that page). I assume that your Android setup uses a version of the Dalvik system that isn't compatible with Java 7. The class Character.UnicodeScript isn't present on your Android setup. An additional remark for your info: As Amedee indicated, there is no Android port for iText 7, and we probably won't make such a port because we hardly sell any iTextG (or "iText for Android") licenses, so I guess your only option is to use iTextG, which is the Android port of iText 5. Many developers don't understand that using AGPL software implies that all the software using iText has to be AGPL only, and that the moment you distribute the software under any other license (e.g. a commercial license) requires purchasing a commercial license with iText software. The sales for this or that product are important for iText Group to define the technical road map. The poor sales number for iTextG along with the fact that we hardly find any AGPL Android projects in which iTextG is used under the AGPL, resulted in a very low priority for iText on Android. I'm adding this information in case you were planning to post a follow-up question asking us why we don't provide an Android port for iText 7.
doc_23532589
11:2>CSC : fatal error CS0042: Unexpected error creating debug information file 'C:\Common\obj\Debug\Common.PDB' -- 'C:\Common\obj\Debug\Common.pdb: The process cannot access the file because it is being used by another process. [C:\Common\Common.csproj] Looking at the log, 2 msbuild nodes were trying to build that same csproj, and thus colliding on writing some output: 10>Project "C:\Utils\Utils.csproj" (10) is building "C:\Common\Common.csproj" (11) on node 4 (default targets). 46:2>Project "C:\Objects\Objects.csproj" (46:2) is building "C:\Common\Common.csproj" (11:2) on node 1 (default targets). Why would MSBuild try to build the same project twice? A: Cause: Someone was calling <MSBuild Projects="Common.csproj" Properties="..." />. Then, MSBuild thinks that it should build Common.csproj again with those different properties, and it happened to occur at the same time with the regular compilation of Common.csproj. Fix: Call <MSBuild ... /> without those unneeded properties. Test: Common.targets <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Target Name="Build"> <Message Importance="high" Text="Build in $(MSBuildThisFile)" /> </Target> <Target Name="After" DependsOnTargets="Build"> <Message Importance="high" Text="After in $(MSBuildThisFile)" /> </Target> </Project> Other.targets <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Target Name="Build"> <Message Importance="high" Text="Build in $(MSBuildThisFile)" /> <MSBuild Projects="common.targets" Targets="Build" /> <!-- regular builds --> <MSBuild Projects="common.targets" <!-- custom invocation with properties --> Targets="After" Properties="myprop=myvalue" /> </Target> </Project> Run: > msbuild other.targets /clp:verbosity=minimal Build in other.targets Build in common.targets Build in common.targets <<<< Common.targets Build is invoked again After in common.targets And indeed, removing Properties="myprop=myvalue" solves the issue. A: I found someone had added two project references (from the same project) and that apparently caused msbuild to build twice also.. something to watch out for
doc_23532590
Example: Feature A Content handler A -> assigns / removes role X from a user content item Feature B Content handler B -> evaluates assigned roles and when role X is found it and takes further actions As you see, in my case it makes no sense to call handler B before A as role X must be updated in A before B can even execute further actions based on the role X assignment. Currently Autofac resolves the handlers in an ordering as follows ..., A, B, ... but the handlers are stored in the handler list in the following order ... B, A, ... Then Orchard invokes the handlers like Handlers.Invoke(handler => ..., Logger); which obviously calls the handlers in the order ... B, A, ... Is there anything i can do to ensure a specific order? Here is a discussion in google groups about a similar issue: https://groups.google.com/forum/#!topic/autofac/HE66utFpvkg A: You should never rely on the order of content handlers. If you need to run code in a specific order then you can define your own handler interface with a property for ordering your handlers. For example: public interface IMyHandler { int Priority { get; } void Invoke(ContentItem item); } You can register this interface with a custom Autofac module inside your Orchard module. Then inside a regular content handler you can inject IEnumerable<IMyHandler>. This will provide you with all registered handlers of IMyHandler type. Then you can order them by Priority and call them in a foreach loop. foreach (var handler in _myHandlers.OrderBy(x => x.Priority)) { handler.Invoke(item); }
doc_23532591
For example in Gimp, you can create a line in choosing the start point and the end point. I heard about GooCanvas, but I'm not sure it is possible to do that with it. I would like to know which librayr can I use to implement that in a gtk application in C? Thanks A: Use GTK3 with cairo (i.e. cairographics). e.g. GtkDrawingArea. See zetcode tutorials on GTK & cairo. NB: GooCanvas is probably obsolete with GTK 3 GTK3 will be useful for mouse related things, and Cairo for drawing. You could consider also libSDL instead.
doc_23532592
My current code for saving Image is as follows: ContentResolver resolver = getApplicationContext().getContentResolver(); ContentValues contentValues = new ContentValues(); Uri collection = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY); contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, "image.png"); contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/png"); contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + "/MyPicturesDirectory"); Uri result = resolver.insert(collection, contentValues); For other media types, I have similar separate concrete implementations.
doc_23532593
var data = [,A_1_VII,VII,V2,,A_1_VII,VII,V2,,A_1_VII,VII,V2,,B_1_XIV,XIV,V3,,B_2_XVI,XVI,V3] when I alert in JavaScript it gives as below ,A_1_VII,VII,V2 ,A_1_VII,VII,V2 ,A_1_VII,VII,V2 ,B_1_XIV,XIV,V3 ,B_2_XVI,XVI,V3 But I want like this which is duplicates removed array var unique_data = [,A_1_VII,VII,V2,,B_1_XIV,XIV,V3,,B_2_XVI,XVI,V3] On alert it should give like this ,A_1_VII,VII,V2 ,B_1_XIV,XIV,V3 ,B_2_XVI,XVI,V3 A: Assuming the variables in your array are well defined, you can clean it up and remove duplicates with a for loop: var data [/* ... */]; var unique_data = []; for(let i = 0; i < data.length; i++) { if (data[i] && unique_data.indexOf(data[i]) === -1) { unique_data.push(data[i]); } } Please note that the code above assumes that your array contains non-object types, otherwise the solution would need to use something more sophisticated than indexOf(). A: First Thing your array contains string as a constant that's not going to work. Secondly, if all of you value are strings you can do it as follows: var data =[,"A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"B_1_XIV","XIV","V3",,"B_2_XVI","XVI","V3"]; var uniqueArray = data.filter(function(item, pos) { return data.indexOf(item) == pos; }) alert(uniqueArray); A: You can create your unique function to remove duplicate entry and empty value from array like this. var data =[,"A_1_VII,VII","V2,,A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"B_1_XIV,XIV","V3",,"B_2_XVI,XVI,V3"] var unique_data = uniqueList(data); alert(unique_data); function uniqueList(list) { var uniqueResult = []; $.each(list, function(i, e) { if ($.inArray(e, uniqueResult) == -1 &&$.inArray(e, uniqueResult)!="")// chech for unique value and empty value uniqueResult.push(e); }); return uniqueResult ; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
doc_23532594
T = 6; d1 = ones(T-2, 1); d2 = 2*ones(T-1, 1); d3 = 3*ones(T, 1); f = sparse(diag(d1, -2) + diag(d2, -1) + diag(d3) + diag(d2, 1) + diag(d1, 2)); but I want to avoid creating the full TxT matrix, so I want to use spdiags, like this: f2 = spdiags(d1, -2, T, T) + spdiags(d2, -1, T, T) + spdiags(d3, 0, T, T) + ... spdiags(d2, 1, T, T) + spdiags(d1, 2, T, T); matlab tells me that "index exceeds matrix dimensions" and the problem comes from these commands spdiags(d2, 1, T, T) spdiags(d3, 2, T, T) but these commands work normally: spdiags(d1, -2, T, T) spdiags(d2, -1, T, T) What's going on here? The final matrix should look like the sparse form of this: f = 3 2 1 0 0 0 2 3 2 1 0 0 1 2 3 2 1 0 0 1 2 3 2 1 0 0 1 2 3 2 0 0 0 1 2 3 Also these are sample matrices that Im using as examples only. This code works too: T = 6; d1 = ones(T-2, 1); d2 = 2*ones(T-1, 1); d3 = 3*ones(T, 1); f = sparse(diag(d1, -2) + diag(d2, -1) + diag(d3) + diag(d2, 1) + diag(d1, 2)); B = [[d1;0;0], [d2;0], d3, [0;d2], [0;0;d1]]; f2 = spdiags(B, -2:2, T, T); A: The documentation is not very clear. It looks like you need your d vector to be of length T, even if some values will be ignored (namely, the first values are ignored for positive diagonals, and the last are ignored for negative diagonals). But somehow Matlab only actually complains for positive diagonals; for negative diagonals it does accept shorter vectors. So: use all d vectors of length T: T = 6; d1 = ones(T, 1); d2 = 2*ones(T, 1); d3 = 3*ones(T, 1); f2 = spdiags(d1, -2, T, T) + spdiags(d2, -1, T, T) + spdiags(d3, 0, T, T) + ... spdiags(d2, 1, T, T) + spdiags(d1, 2, T, T); By the way, you can build a matrix containing all d vectors as columns (now that they all have the same length) and call spdiags just once: f2 = spdiags([d1 d2 d3 d2 d1], -2:2, T, T);
doc_23532595
Anyway, I am pulling dates from a database using UNIX_TIMESTAMP, and it gives me a timestamp like 1436745600 for a date 2015-07-13 stored in my database. This looks correct to me. But then my code simply does a date('M-j','variable storing that number'), and it gives me 'July-12'. Why is this? I know I am PST, and the server is UTC, but on version 4, how would PHP know that? And even if it did, we are both on the same day for most of a 24 hour cycle. As I started writing this, we were on the same day, and still the problem occurred. As I finish, we are on different days, and the result is the same. Something else going on here?
doc_23532596
ID | Amount ------------- 1 | 500 2 | 800 3 | 200 How can I transfer 300 from second row to first row using their Id, I can do it by Stored Procedure, is there any way to perform this in single query A: MySql evaluates Boolean expressions as 1 or 0, so this will work: update tablename set amount = amount + (id = 1) * 300 - (id = 2) * 300 where id in (1, 2); Or: update tablename set amount = amount + ((id = 1) - (id = 2)) * 300 where id in (1, 2); See the demo. Results: | ID | Amount | | --- | ------ | | 1 | 800 | | 2 | 500 | | 3 | 200 | A: You can try this: UPDATE table_users SET amount = (case when id = 1 then amount+300 when id = 2 then amount-300 end) WHERE id in (1,2);
doc_23532597
A: That depends. If the geometry is large enough to be stored out of line in a TOAST table, the main table will be almost as small as if it didn't have the geometry column, and it will be difficult to measure a difference in speed. If the geometry is smaller, and the geometry is stored in the main table, querying the table will be somewhat slower, because the whole table row is read from disk and you end up having more I/O than if you didn't have the column. However, if you store the geometry in another table with a one-to-one relationship, retrieving the geometry will incur the overhead of an extra join, which will make that operation slower. I recommend that you keep things simple and store the geometry in the table. Very likely, the performance gain you can expect from doing something more complicated is not big, and the overall performance of your application may even suffer. This sounds to me like a premature micro-optimization. If you want to go that way, run a realistic performance test with realistic test data to verify that it is worth the effort.
doc_23532598
I've tried both setLogo() and setIcon(). I've tried adding android:logo="" in manifest. I've made sure to try both supportActionBar and regular ActionBar. (I'm running sdk 21 with a min sdk of 15.) The funny thing is if I try to use the regular ActionBar I get null pointers but when I use the support ActionBar it at least works. Is there anything else I can try...? Here's where I try and change it. public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ActionBar ab = getSupportActionBar(); ab.setLogo(R.drawable.logo); A: If your min sdk is 15, i'm not sure why you're using the support package at all. You class should instead extend Activity, and use getActionBar().
doc_23532599
I've installed all my dependencies using pip in a virtualenv... lets get that out of the way first. My issue is near the bottom, db.StringField() does not resolve. I'm using pycharm -- I have dug out the file that supposedly contains the field definitions: $PROJ_DIR/lib/python2.7/site-packages/mongoengine/base/fields.py But I don't know how to import this file either. And I'm worried that using that class may interfere with MongoRest, but I have no idea. from flask import Flask, request, redirect import twilio.twiml from flask.ext.mongorest import MongoRest from flask.ext.mongorest.views import ResourceView from flask.ext.mongorest.resources import Resource from flask.ext.mongorest import operators as ops from flask.ext.mongorest import methods from flask.ext.mongoengine import MongoEngine app = Flask(__name__) app.config.update( MONGODB_HOST = 'localhost', MONGODB_PORT = '27017', MONGODB_DB = 'SMSYOGADEX', ) db = MongoEngine(app) api = MongoRest(app) class Sms(db.Document): smsId = db.StringField() I've been working on this tutorial in github. Thanks again for any help. Blake-- A: Well, I found this: from mongoengine.fields import StringField Hopefully that will work out, but I'm not 100% this is the proper way to do things.