id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_4200
import numpy def mergeSort(a): if len(a) ==1: return if len(a) == 2: if a[0] > a[1]: tmp = a[0] a[0] = a[1] a[1] = tmp return x = a[0:len(a)/2] y = a[len(a)/2:] mergeSort(x) mergeSort(y) j=0 k=0 for i in xrange(len(a)): if j == len(x) or k<len(y) and x[j] > y[k]: a[i] = y[k] k = k + 1 else: a[i] = x[j] j = j + 1 a = numpy.random.randint(100, size=3) # Generates say [20 3 75] mergeSort(a) print a # Yields [3, 3, 75] ! a = [20,3,75] mergeSort(a) print a # Yields [3, 20, 75] ! This implementation inexplicably fails when I use numpy to generate random arrays for me whereas if I hardcode exactly one of the failing numpy generated sequence and run the code, it sorts perfectly. Is there anything I'm missing? A: Numpy arrays don't behave the same as lists. The merge step fails because x and y would be views of a when a is a numpy array. You can pass list(a) to the mergeSort routine to make it work: import numpy def mergeSort(a): if len(a) ==1: return if len(a) == 2: if a[0] > a[1]: tmp = a[0] a[0] = a[1] a[1] = tmp return x = a[0:len(a)/2] y = a[len(a)/2:] mergeSort(x) mergeSort(y) j=0 k=0 for i in xrange(len(a)): if j == len(x) or k<len(y) and x[j] > y[k]: a[i] = y[k] k = k + 1 else: a[i] = x[j] j = j + 1 a = numpy.random.randint(100, size=3) # Generates say [20 3 75] a = list(a) mergeSort(a) a = numpy.array(a) print a # correctly Yields [3, 20, 75] ! a = [20,3,75] mergeSort(a) print a # Yields [3, 20, 75] !
doc_4201
a+c+c+b+v+f+d+d+d+c I need to write the program so it splits at the + then deletes the duplicates so the output is: acbvfdc I've tried tr///cs; but I guess I'm not using it right? A: #!/usr/bin/env perl use strict; use warnings; my @strings = qw( a+c+c+b+v+f+d+d+d+c alpha+bravo+bravo+bravo+charlie+delta+delta+delta+echo+delta foo+food bark+ark ); for my $s (@strings) { # Thanks @ikegami $s =~ s/ (?<![^+]) ([^+]+) \K (?: [+] \1 )+ (?![^+]) //gx; print "$s\n"; } Output: a+c+b+v+f+d+c alpha+bravo+charlie+delta+echo+delta foo+food bark+ark Now, you can split the string and have no sequences of duplicates using split /[+]/, $s because the first argument of split is a pattern. A: Note to any who reads: this does not address the OP's question directly, though in my defense the question was worded ambiguously. :-) Still, it answers an interpretation of the question that others might have, so I'll leave it as-is. Does order matter? If not, you can always try something like this: use strict; use warnings; my $string = 'a+c+c+b+v+f+d+d+d+c'; # Extract unique 'words' my @words = keys %{{map {$_ => 1} split /\+/, $string}}; print "$_\n" for @words; Better yet, use List::MoreUtils from CPAN (which does preserve the order): use strict; use warnings; use List::MoreUtils 'uniq'; my $string = 'a+c+c+b+v+f+d+d+d+c'; # Extract unique 'words' my @words = uniq split /\+/, $string; print "$_\n" for @words; A: my $s="a+c+c+b+v+f+d+d+d+c"; $s =~ tr/+//d; $s =~ tr/\0-\xff/\0-\xff/s; print "$s\n"; # => acbvfdc
doc_4202
#!/usr/bin/perl -w use strict; use warnings; sub foo { return wantarray ? () : "value1"; } my $hash = { key1 => foo(), key2 => 'value2' }; use Data::Dumper; print Dumper($hash); I get the following output: $VAR1 = { 'key1' => 'key2', 'value2' => undef }; When I would expect: $VAR1 = { 'key1' => 'value1', 'key2' => 'value2' }; I understand that a hash is kind-of an even-sized array (as evidenced by the "Odd number of elements in hash assignment" warning I'm getting) but a hash element can only be a scalar, why would the compiler be giving it array context? I found this using the param function of the CGI module when assigning directly to a hash. The foo() function above was a call to CGI::param('mistyped_url_param') which was returning an empty array, destroying (rotating?) the hash structure. A: The fat comma isn't a special hash assignment operator. It just a piece of syntactic sugar that means "auto-quote the previous thing" So: my $hash = { key1 => foo(), key2 => 'value2' }; Means: my $hash = { 'key1', foo(), 'key2', 'value2' }; … which is a list and, as willert says: every expression in a list is evaluated in list context. You can get around this by calling scalar foo() A: An anonymous hash constructor supplies list context to the things inside it because it expects a list of keys and values. It's that way because that's the way it is. We don't have a way to represent a Perl hash in code, so you have to use a list where we alternate keys and values. The => notation helps us visually, but performs no magic that helps Perl figure out hashy sorts of things. Current context propogates to subroutine calls, etc just like it does in any other situation. This allows you to build hashes with list operations: my $hash = { a => 'A', map( uc, 'd' .. 'f' ), return_list( @args ), z => 'Z' }; If you need something to be in scalar context, just say so using scalar: my $hash = { a => 'A', map( uc, 'd' .. 'f' ), 'g' => scalar return_item( @args ), z => 'Z' };
doc_4203
grails.project.dependency.resolution = { plugins { ... compile ":solr:0.2" } } and (the deprecated): $> grails install-plugin solr but it didn't work. Is this plugin still valid or there are other alternatives for using Solr with Grails 2.3.3? A: I think development might be inactive on this plugin. Out of interested I use Searchable very successfully: BuildConfilg.groovy: plugins { ... compile ":searchable:0.6.6" In your domain class: class Article { String headline String extract static searchable = { only = ['headline', 'extract'] headline boost: 2.0, spellCheck: 'include' extract boost: 1.7, spellCheck: 'include' } ... } To index in a Service: def searchableService ... searchableService.index() } Edit: The spellcheck add the facility to provide suggested searches if you misspelled the search term: def suggestedQuery = searchableService.suggestQuery(searchTerm) To search for a term def searchResult = searchableService.search("dog", options) To match with similar word "cycle" or "cycling" append ~ on to the serach term def searchResult = searchableService.search("cycle~", options) The options here also allow you to highlight search terms in the result options.withHighlighter = textHighlighter
doc_4204
A: It is not possible. As per Robotil 1) Download Robotil.jar 2) Start Robotil server on a remote machine. So you have to place the Robotil.jar in the remote machine and have to execute the jar file. And SauceLabs only provides grid URL and can be used only to create RemoteDriver Instances , it wont allow you to execute shell/windows scrips or do file transfer and all.
doc_4205
*Create a new "Shell Tool" target in your Xcode project called something like "UnitTests" So question: what is a shell tool target for a Xcode project. Is it still available in Xcode 6. If it is, where? If it is not, any workaround? Edit: I don't want to use XCTest because (a) it is not cross platform (b) it supports well for Obj-C but not so well for C++. A: Create a new project. On the creation dialog, select "Command Line Tool" as your project type. This is what is probably meant by "Shell Tool." It is available in Xcode 6.
doc_4206
A: well, i think you should take a look at some cocoa development related books or websites - like cocoadev cocoadevcentral cocoabuilder ... in short: define your IBOutlet NSTextField* timeLabel; in your controller class and hook it up to the NSTextField in your NIB. take a look at NSDate and update it (via a NSTimer or your draw loop)
doc_4207
Since, I am new to jQuery I am not sure what exactly this error means. I am using a jQuery plugin jquery-gauge.min.js which contains a method gauge() as shown below which works perfectly fine and normally in any web application. import { Component, ViewChild, ElementRef, AfterViewInit, OnInit } from '@angular/core'; import * as $ from 'jquery'; @Component({ selector: 'app-tab1', templateUrl: 'tab1.page.html', styleUrls: ['tab1.page.scss'] }) export class Tab1Page implements OnInit { ngOnInit(): void { $('.gauge1').gauge({ values: { 0: '', 10: '', 20: '', 30: '', 40: '', 50: '', 60: '', 70: '', 80: 'Tier 1', 90: 'Tier 2', 100: 'Tier 3', }, colors: { 0: '#1aff1a', 75.5: '#1aff1a', 75.6: '#515e80', 80: "#515e80", 90: "#515e80", }, angles: [ 180, 360 ], lineWidth: 10, arrowWidth: 0, arrowColor: '#ccc', value: 75.5 }); } } When I am implementing it on an ionic application it is throwing an error on line $('.gauge').gauge({...}) error "TS2339: Property 'gauge' does not exist on type 'JQuery' I have added jquery-gauge.min.js to the scripts in the angular.json file. how can I resolve this error? A: Probably because this function is executed before the javascript with your gauge functionality is loaded. Try to use the ngAfterViewChecked() lifecylce hook instead of the ngOnInit(). A: add this after the import statments import { Component, ViewChild, ElementRef, AfterViewInit, OnInit } from '@angular/core'; import * as $ from 'jquery'; declare interface JQuery<HTMLElement> { gauge(...args): any; } ... A: Found the solution. use jQuery('.gauge1').guage() instead of $('.gauge1').guage() Though I was new to jQuery, I didn't know how plugins may behave differently in different platforms (don't know why it exactly is) but, when I used the plugin in a .js file in a web app it worked by using $('.guage').gauge() but when I used it with ionic (or should say with .ts file) it required jQuery('.guage').guage() instead. if anyone can explain why is that so. That will be grateful and helpful too. Thanks.
doc_4208
"business_id": 2, "forms": { "f522": { "id": "f522", "is_deleted": 0, "title": "Form 1" }, "f8b6": { "id": "f8b6", "is_deleted": 0, "title": "Form 2" }, "fw56": { "id": "fw56", "is_deleted": 0, "title": "Form 3" } } }] Record2: [{ "business_id": 3, "forms": { "f788": { "id": "f788", "is_deleted": 0, "title": "Form 11" }, "f6yy": { "id": "f6yy", "is_deleted": 0, "title": "Form 12" }, "f00i": { "id": "f00i", "is_deleted": 0, "title": "Form 13" } } }] Record3: [{ "business_id": 4, "forms": { "f839": { "id": "f839", "is_deleted": 0, "title": "Form 21" }, "f1bc": { "id": "f1bc", "is_deleted": 0, "title": "Form 22" }, "f6ac": { "id": "f6ac", "is_deleted": 0, "title": "Form 23" } } }] I have 3 records stored in dynamoDB table. Hash Key is business_id. forms object is parent object with child objects(id, is_deleted, title). I don't know business_id value. But i have only id value "f6yy". I want whole records with business_id using child object id(value is f6yy). Please suggest. A: The below filter expression should work. Filter expression on JavaScript:- FilterExpression : 'forms.f6yy.id = :formIdVal', ExpressionAttributeValues : { ':formIdVal' : 'f6yy' } PHP:- 'FilterExpression' => 'forms.f6yy.id = :formIdVal',
doc_4209
await Navigation.PushModalAsync(page); It shows the page... and then just keeps going. It does not stop to wait for the 'modal' page to close. I'm not really sure what the point of calling this 'Modal' is and I wanted to be sure I was not missing some obvious thing. It seems to be exactly like Navigation.PushAsync(). I googled and all I found was just standard implementation examples. I am used to 'modal' meaning that all processing stops in the calling code until the form closes. try { _loaded = false; // TEST System.Diagnostics.Debug.Print("About to push modal"); ModalPage page = new ModalPage(); await Navigation.PushModalAsync(page); System.Diagnostics.Debug.Print("Page is still showing. Not going to wait."); // TEST I have a work around but it's kind of clunky and I was hoping there was a better way. System.Diagnostics.Debug.Print("About to push modal"); ModalPage page = new ModalPage(); Guid pageId = page.Id; Guid currId = pageId; await Navigation.PushAsync(page); await Task.Delay(250); while (pageId == currId) { await Task.Delay(250); currId = Guid.Empty; int index = Application.Current.MainPage.Navigation.NavigationStack.Count - 1; if (index > 0) currId = Application.Current.MainPage.Navigation.NavigationStack[index].Id; } System.Diagnostics.Debug.Print("Page was closed. Safe to move on."); A: Well, the answer is (in my opinion) no, the PushModalAsync() does not create what a Windows Desktop developer would consider a Modal dialog page. I cannot see any real difference between it and PushAsync(). It was stated in the comments that the parent window won't accept user input but pages take up the whole screen so I can't test it and it functionally doesn't matter. I made a more formal workaround and made it part of a PageService I use in my application. Maybe it can help someone else. public class PageService : IPageService { public async Task<Page> ShowPageModal(Type pageType, params object[] paramArray) { Page page = (Page)Activator.CreateInstance(pageType, args: paramArray); await Application.Current.MainPage.Navigation.PushModalAsync(page); int interval = 1000; Guid pid; do { await Task.Delay(interval); interval = 250; pid = GetCurrentModalPageId(); } while (pid == page.Id); return page; } public Guid GetCurrentModalPageId() { Guid id = Guid.Empty; int index = Application.Current.MainPage.Navigation.ModalStack.Count - 1; if (index >= 0) id = Application.Current.MainPage.Navigation.ModalStack[index].Id; return id; } } Here is an example call: private async void Button_Clicked(object sender, EventArgs e) { try { if (sender == TestButton) { List<string> items = new List<string> { "Item 1", "Potato Salad", "Joe Bob" }; LookupPages.ModalSelectPage page = (LookupPages.ModalSelectPage) await PageService.ShowPageModal(typeof(LookupPages.ModalSelectPage), new object[] { "Select a String", items }); string item = page.SelectedItem; await DisplayAlert("Modal Select Result", item ?? "null", "Ok"); } } catch (Exception ex) { App.HandleError(ex); } } Here is the Page I used: <?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="StoreTrak.Pages.LookupPages.ModalSelectPage"> <!-- Start Page Layout --> <StackLayout VerticalOptions="FillAndExpand"> <Label x:Name="TitleLabel" FontAttributes="Bold,Italic" HorizontalOptions="CenterAndExpand" /> <StackLayout Margin="10,0,10,0" BackgroundColor="White" VerticalOptions="FillAndExpand"> <!-- 3: List of items --> <ListView x:Name="itemsList" HasUnevenRows="True" Margin="5,0,5,0" SelectionMode="Single" ItemTapped="itemsList_ItemTapped"> </ListView> </StackLayout> <!-- 4: Back and Main buttons --> <StackLayout Orientation="Horizontal" Padding="10" VerticalOptions="End"> <Button x:Name="BackButton" Style="{StaticResource back}" Clicked="BackButton_Clicked" /> </StackLayout> </StackLayout> </ContentPage> Code behind: using System; using System.Collections.Generic; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace StoreTrak.Pages.LookupPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class ModalSelectPage : ContentPage { List<string> _items = null; string _title = "Select Something"; public ModalSelectPage() { InitializeComponent(); } public ModalSelectPage(string title, List<string> items) : this() { _items = items; _title = title; } public string SelectedItem { get; set; } protected override void OnAppearing() { try { base.OnAppearing(); TitleLabel.Text = _title ?? "Select Something"; if (_items != null && _items.Count > 0) { itemsList.ItemsSource = _items; } } catch (Exception ex) { App.HandleError(ex); } } private async void BackButton_Clicked(object sender, EventArgs e) { try { await Navigation.PopModalAsync(); } catch (Exception ex) { App.HandleError(ex); } } private void itemsList_ItemTapped(object sender, ItemTappedEventArgs e) { try { SelectedItem = e.Item as string; } catch (Exception ex) { App.HandleError(ex); } } } } A: Another more useful approach would be to use a generic method and encapsulate all the information into the Page class. That way you can use the same method for any page with any data types that need to be selected. In the PageService public async Task ModalPopup<T>(T page) where T : Page { await Application.Current.MainPage.Navigation.PushModalAsync(page); int interval = 1000; Guid pid; do { await Task.Delay(interval); interval = 250; pid = GetCurrentModalPageId(); } while (pid == page.Id); } Adjust the ModalSelectPage class: using System; using System.Collections.Generic; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace StoreTrak.Pages.LookupPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class ModalSelectPage : ContentPage { public ModalSelectPage() { InitializeComponent(); } public ModalSelectPage(string title, List<string> items) : this() { ItemList = items; TitleText = title; } public List<string> ItemList { get; set; } public string SelectedItem { get; set; } public string TitleText { get; set; } = "Select Something"; protected override void OnAppearing() { try { base.OnAppearing(); TitleLabel.Text = TitleText ?? "Select Something"; if (ItemList != null && ItemList.Count > 0) { itemsList.ItemsSource = ItemList; } } catch (Exception ex) { App.HandleError(ex); } } private async void BackButton_Clicked(object sender, EventArgs e) { try { await Navigation.PopModalAsync(); } catch (Exception ex) { App.HandleError(ex); } } private void itemsList_ItemTapped(object sender, ItemTappedEventArgs e) { try { SelectedItem = e.Item as string; } catch (Exception ex) { App.HandleError(ex); } } } } Now we can pass any Page to it: private async void Button_Clicked(object sender, EventArgs e) { try { if (sender == TestButton) { List<string> items = new List<string> { "Item 1", "Potato Salad", "Joe Bob" }; LookupPages.ModalSelectPage page = new LookupPages.ModalSelectPage { TitleText = "Select a String", ItemList = items }; await PageService.ModalPopup(page); string item = page.SelectedItem; await DisplayAlert("Modal Select Result", item ?? "null", "Ok"); } } catch (Exception ex) { App.HandleError(ex); } }
doc_4210
I am creating a GUI application. This class gets a number from the user and shows a table on the Frame. When I run my class, I enter a number and click the JButton, but the JLabel on my Frame is not shown. It does not show me why not. import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import java.awt.event.*; //this Frame class use the association class Frame { JFrame f; JButton jb,jbclear; JTextField jt; JLabel jl1[]=new JLabel[10]; EventHandler hand=new EventHandler(); //constructor Frame(){ f=new JFrame("Hello"); f.setSize(500,500); f.setLayout(null); JLabel jl=new JLabel("Enter the number"); jl.setBounds(30,10,100,20); f.getContentPane().add(jl); jt=new JTextField(); jt.setBounds(170,10,50,20); f.add(jt); jb=new JButton("Click"); jb.setBounds(270,50,80,30); f.add(jb); jb.addActionListener(hand); jbclear=new JButton("Clear"); jbclear.setBounds(270,90,80,30); f.add(jbclear); jbclear.addActionListener(hand); f.setVisible(true); } class EventHandler implements ActionListener{ public void actionPerformed(ActionEvent e){ if(e.getSource()==jb){ int num=Integer.parseInt((jt.getText())); for(int i=0;i<10;i++){ int n=(num*i); String s=String.valueOf(num)+" X "+i+" = "+n; jl1[i]=new JLabel(s); } for(int i=0,k=80;i<10;i++){ jl1[i].setBounds(30,k,150,10); f.add(jl1[i]); jl1[i].setVisible(true); k=k+30; } } if(e.getSource()==jbclear){ for(int i=0;i<10;i++){ jl1[i].setText(""); } } } } public static void main(String [] args){ new Frame(); } } Can we add a component after creating and displaying a JFrame? A: You create labels jl1[i]=new JLabel(s) but they are not added to container. Don't use null layout/setBounds() but choose a suitable one (e.g GridLayout or BoxLayout) A: Your problem is next: 1) add all your components in same maner, like that f.getContentPane().add(), bacause you add your compenents with f.getContentPane().add() and f.add() it's different containers. 2) if you add component to visible Frame/Panel/Container, you must to call revalidate() and repaint() methods on container after adding, because of, without those methods, added component will be invisible. I change your ActionListener in next way(it do what you want) : class EventHandler implements ActionListener{ public void actionPerformed(ActionEvent e){ if(e.getSource()==jb){ int num=Integer.parseInt((jt.getText())); for(int i=0;i<10;i++){ int n=(num*i); String s=String.valueOf(num)+" X "+i+" = "+n; jl1[i]=new JLabel(s); } for(int i=0,k=80;i<10;i++){ jl1[i].setBounds(30,k,150,10); f.getContentPane().add(jl1[i]); k=k+30; } f.getContentPane().revalidate(); f.getContentPane().repaint(); } if(e.getSource()==jbclear){ for(int i=0;i<10;i++){ f.getContentPane().remove(jl1[i]); } f.getContentPane().revalidate(); f.getContentPane().repaint(); } } } JFrame revalidate I recommend you try to use LayoutManager instead of setBounds() method with null layout. A: for(int i=0;i<10;i++){ int n=(num*i); String s=String.valueOf(num)+" X "+i+" = "+n; jl1[i]=new JLabel(s); } for(int i=0,k=80;i<10;i++){ jl1[i].setBounds(30,k,150,10); f.add(jl1[i]); jl1[i].setVisible(true); Ok, you are adding JLabel to the JFrame, more accurately to the Frame's content pane, but you haven't called repaint() on JFrame to update the GUI. Just call, f.repiant() as soon as you have finished added the labels too have some output for temporary satisfaction. Can we add a component after creating and displaying a JFrame? Yes, but we should use proper layout manager, After adding a component we should call revalidate() and repaint() to render the GUI appropriately. Now some more things: * *Do not work with Null layout(or Absolute Layout), *All the component's visible flag is true by default, you don't need to call setVisible(true) on such component except with the application window e.g., JFrame *Swing uses EDT to it's GUI rendering task. Hence we should make all the necessary update to the GUI, including showing our application first time upon starting, should also be put inside the EDT. SwingUtilies.invokeLater(new Runnabe(){}) do just that. Tutorial: * *Concurrency in Swing *Lesson: Laying Out Components Within a Container
doc_4211
Right now it shows the first notification just fine, but after that it triggers 2 notifications at the same time (see current output below). It doesn't wait for the previous notification to show and then hide again before showing the next one. notifications.api.ts: public notifications = new Subject<INotificationEvent>(); public notifications$ = this.notifications.asObservable(); notifications.component.ts: private finished = new Subject(); constructor(private notifications: NotificationsApi) {} zip(this.notificationsApi.notifications$, this.notificationsApi.notifications, (i, s) => s).pipe( tap(() => { if (!this.isActive) { this.finished.next(); } }), delayWhen(() => this.finished), delay(450), tap((event: INotificationEvent) => { this.notification = event; this.isActive = true; this.cd.markForCheck(); console.log(this.notification); console.log('showing'); }), delay(this.hideAfter), tap(() => { this.isActive = false; this.cd.markForCheck(); console.log('closing'); }), delay(450) ).subscribe(() => { console.log('finishing'); this.finished.next(); }); app.component.ts: let i = 0; setInterval(() => { this.notifications.newNotification({message: `${i}`, theme: 'primary'}); i++; }, 2000); Current output: {message: "0", theme: "primary"} showing closing finishing {message: "1", theme: "primary"} showing {message: "2", theme: "primary"} showing closing finishing {message: "3", theme: "primary"} showing {message: "4", theme: "primary"} showing closing closing finishing finishing {message: "5", theme: "primary"} showing {message: "6", theme: "primary"} Desired output: {message: "0", theme: "primary"} showing closing finishing {message: "1", theme: "primary"} showing closing finishing {message: "2", theme: "primary"} showing closing finishing {message: "3", theme: "primary"} showing closing finishing {message: "4", theme: "primary"} showing closing finishing {message: "5", theme: "primary"} showing closing finishing {message: "6", theme: "primary"} showing closing finishing How can I fix this? A: From what you describe it seems to me that you could achieve the same much easily with concatMap and delay. In this example every button click represents one notification. Each notification takes 2s. It depends on what you want to do in the observer but if you don't need the notification at all you can leave it empty (otherwise you'll need probably startWith). Multiple notifications are queued inside concatMap and executed one after another. const notification$ = fromEvent(document.getElementsByTagName('button')[0], 'click'); notification$.pipe( concatMap(event => of(event).pipe( tap(v => console.log('showing', v)), delay(2000), tap(v => console.log('closing', v)), )) ).subscribe(); Live demo: https://stackblitz.com/edit/rxjs-nqtfzm?file=index.ts
doc_4212
I am trying the --python-install-data location-to-install-data-files option in the fpm command that generates the rpm. When I do rpm -i package-path.rpm, I expect the data files to be installed at the location specified in the fpm command. Yet that is not happening. What could be the problem?
doc_4213
#--errorHandler.py # python 3 try: from tkinter import * from tkinter import ttk from tkinter import messagebox import smtplib # python 2.7 except: from Tkinter import * import ttk import tkMessageBox as messagebox import smtplib class errorHandler: def __init__(self, master): master.title('Error') master.resizable(False, True) master.configure(background = 'cornsilk') self.mtr = master self.style = ttk.Style() self.style.configure('TFrame', background = 'cornsilk') self.style.configure('TButton', background = 'cornsilk') self.style.configure('TLabel', background = 'cornsilk', font = ('Arial', 11)) self.style.configure('Header.TLabel', font = ('Arial', 18, 'bold')) self.frame_header = ttk.Frame(master) self.frame_header.pack() ttk.Label(self.frame_header, text = "ERROR", foreground = 'red', style = 'Header.TLabel', justify = 'center').grid(row = 0, column = 0, columnspan = 2) ttk.Label(self.frame_header, wraplength = 300, text = ("Please fill out the following form to help identify this error. " "Doing so will help make improvements to this program.")).grid(row = 1, column = 1) self.frame_content = ttk.Frame(master) self.frame_content.pack() ttk.Label(self.frame_content, text = 'Name:').grid(row = 0, column = 0, padx = 5, sticky = 'sw') ttk.Label(self.frame_content, text = 'Email:').grid(row = 0, column = 1, padx = 5, sticky = 'sw') ttk.Label(self.frame_content, text = 'Comments:').grid(row = 2, column = 0, padx = 5, sticky = 'sw') self.entry_name = ttk.Entry(self.frame_content, width = 24, font = ('Arial', 10)) self.entry_email = ttk.Entry(self.frame_content, width = 24, font = ('Arial', 10)) self.text_comments = Text(self.frame_content, width = 50, height = 10, font = ('Arial', 10)) self.entry_name.grid(row = 1, column = 0, padx = 5) self.entry_email.grid(row = 1, column = 1, padx = 5) self.text_comments.grid(row = 3, column = 0, columnspan = 2, padx = 5) ttk.Button(self.frame_content, text = 'Send', command = self.send).grid(row = 4, column = 1, padx = 5, pady = 5, sticky = 'e') ttk.Button(self.frame_content, text = 'Clear', command = self.clear).grid(row = 4, column = 1, padx = 5, pady = 5, sticky = 'w') self.hdBtn = Button(self.frame_content, text='Hide Details', command = self.hideDetails) self.hdBtn.grid(row = 4, column = 0, padx = 5, pady = 5, sticky = 'w') self.hdBtn.grid_remove() self.swBtn = ttk.Button(self.frame_content, text='Show Details', command = self.showDetails) self.swBtn.grid(row = 4, column = 0, padx = 5, pady = 5, sticky = 'w') self.frame_Details = ttk.Frame(master) self.frame_Details.pack() self.text_comments_Det = Text(self.frame_Details, width = 50, height = 10, font = ('Arial', 10)) self.text_comments_Det.grid(row = 3, column = 0, columnspan = 2, padx = 5) self.text_comments_Det.grid_remove() def send(self): msg = 'Name: \t\t%s\n\n' % self.entry_name.get() \ +'Contact: \t\t%s\n\n' % self.entry_email.get() \ +'Message: \t\t%s\n\n\n' % self.text_comments.get('1.0', END) \ +'Error Message: \t%s' % self.err self.email(msg) messagebox.showinfo(title = 'Confirmation', message = 'Message Sent!') root.destroy() def clear(self): self.entry_name.delete(0, 'end') self.entry_email.delete(0, 'end') self.text_comments.delete(1.0, 'end') def showDetails(self): self.text_comments_Det.grid() self.hdBtn.grid() self.swBtn.grid_remove() self.mtr.geometry("368x520") self.text_comments_Det.delete('1.0', END) self.text_comments_Det.insert(END, self.err) def hideDetails(self): self.text_comments_Det.grid_remove() self.hdBtn.grid_remove() self.swBtn.grid() self.mtr.geometry("368x352") def err(self): try: import arcpy, sys, traceback # Get the traceback object tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] # Concatenate information together concerning the error into a message string errs = "\n\n\nPYTHON ERRORS:\n\tTraceback info:\n\t\t" + tbinfo + "\n\t" \ + "Error Info:\n\t\t" + str(sys.exc_info()[1]) + "\n\n" \ + 'GEOPROCESSING MESSAGE:\n\t' + arcpy.GetMessages(0) + "\n\n" \ + 'GEOPROCESSING WARNING:\n\t' + arcpy.GetMessages(1) + "\n\n" \ + 'GEOPROCESSING ERROR:\n\t' + arcpy.GetMessages(2) + "\n\n" except: import sys, traceback # Get the traceback object tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] # Concatenate information together concerning the error into a message string errs = "\n\n\nPYTHON ERRORS:\n\tTraceback info:\n\t\t" + tbinfo + "\n\t" \ + "Error Info:\n\t\t" + str(sys.exc_info()[1]) + "\n\n" return errs def email(self, txt, toaddrs = ['skeizer111@gmail.com']): fromaddr = 'yourerrorreports@gmail.com' msg = 'Subject: %s\n\n%s' % ("Error Report", txt) username = 'yourerrorreports@gmail.com' password = 'Alberta01' server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls() server.login(username,password) for add in toaddrs: server.sendmail(fromaddr, add, msg) server.quit() def runErrRpt(): root = Tk() errorHandler(root) root.mainloop() runErrRpt() #--test.py try: st = 1+"s" print st except: import errorHandler A: According to lmgtfy Get one python file to run another: Put this in main.py: #!/usr/bin/python import yoursubfile. Put this in yoursubfile.py #!/usr/bin/python print "hello"; Run it: python main. py. It prints: hello.
doc_4214
from scrapy.spider import Spider from scrapy.http import FormRequest, Request from scrapy.selector import HtmlXPathSelector class IndependentSpider(Spider): name = "IndependentSpider" start_urls= ["http://www.independent.co.uk/advancedsearch"] def parse(self, response): yield [FormRequest.from_response(response, formdata={"all": "Science"}, callback=self.parse_results)] def parse_results(self): hxs = HtmlXPathSelector(response) print hxs.select('//h3').extract() The form redirects me to DEBUG: Redirecting (301) to <GET http://www.independent.co.uk/ind/advancedsearch/> from <GET http://www.independent.co.uk/advancedsearch> which is a page that doesn't seem to exist. Do you know what I am doing wrong? Thanks! A: It seems you need a trailing /. Try start_urls= ["http://www.independent.co.uk/advancedsearch/"]
doc_4215
and the author was talking about disconnected entities, which is the first time I have heard of them. I am a little confused as to when disconnected entities are actually needed, as I have been using EF just fine to do CRUD operations on my business objects. If I am using the same context when I am doing CRUD operations on a business object, why do I need to ever manually track the entity state changes? Thanks for any help. A: If you are always keeping around the originating context instance, then you probably do not need to worry about disconnected entities. Disconnected entities often come up in the context of web services or web sites, where the context from which an entity was originally retrieved (and, for example, placed into a Session) is no longer available some time down the road when that entity has been modified and needs to be saved back to the database.
doc_4216
const items= [{ prop1: 'abc', prop2: 'def', prop3: { prop4: '123', prop5: '456', } }]; I programmed a function to filter the data based on the passed objects in the filters variable. It works fine. const onFilterData = ( items, filters) => { return items.filter((item) => { return Object.entries(filters).every(([key, value]) => item[key].includes(value), ); }); } Expanding the logic also involves filtering by objects within the object. For example, I would like to filter in this way as well: const filters = { prop1: 'abc', prop3: '456' }; It should return the same result, since prop3 contains one of the values 456. Unfortunately returns an error: "Uncaught TypeError: item[key].includes is not a function" I started modifying this function and did something like this: const onFilterData = ( items, filters) => { return items.filter((item) => { let isExist = false; const { prop3, ...otherProps } = filters; if (prop3) { isExist = Object.values(item.prop3).toString().includes(prop3); } isExist = Object.entries(otherProps).every(([key, value]) => (item[key]).includes(value), ); return isExist; }); } This is even a good solution, but it does not work correctly because if I do something like this: const filters = { prop1: 'abc', prop3: '4dad23das56' }; it will still return the same result, and there is no such object in the items array.
doc_4217
<input class="Eingabefeld "type="text" id="valueTwo" onkeypress="return isNumber(event)" /> i wanted to change it to addeventlistener, so after some research i came up with this, but it doesnt work document.getElementById("valueTwo").addEventListener("keypress",validate); function validate (event){ var result = isNumber(event); return result; } after some answers, i need to rephrase my question a, i know there are some work arounds, but i specifically would like to know how i can make this function : function isNumber(evt) { evt = (evt) ? evt : window.event; var charCode = (evt.which) ? evt.which : evt.keyCode; if (charCode > 31 && (charCode < 48 || charCode > 57)) { return false; } } work with the evenlistener, which works perfectly fine as onclick, i just cant get the syntax right, and im very interested to know what the right syntax would be to make this work, so i get a better understanding of how i can use function returns in conjunction with the event listener. A: Returning a value out of an onxyz-style attribute is the old way of telling the browser whether to allow or prevent the default action of the event. The equivalent with DOM2 event handlers (addEventListener) is to call the preventDefault method on the event object if you want to prevent the default action: document.getElementById("valueTwo").addEventListener("keypress",validate); function validate(event){ if (!isNumber(event)) { event.preventDefault(); } } Note that you need to update isNumber to return a truthy value if the event is okay (since your current version returns false if not okay and undefined if okay, both of which are falsy values): function isNumber(evt) { evt = (evt) ? evt : window.event; var charCode = (evt.which) ? evt.which : evt.keyCode; if (charCode > 31 && (charCode < 48 || charCode > 57)) { return false; } return true; } Although if you had to keep isNumber the way it currently is, you could use: function validate(event){ if (isNumber(event) === false) { event.preventDefault(); } } ...but I wouldn't. More about the event object on MDN. Example: function isNumber(evt) { evt = (evt) ? evt : window.event; var charCode = (evt.which) ? evt.which : evt.keyCode; if (charCode > 31 && (charCode < 48 || charCode > 57)) { return false; } return true; } function validate(event) { if (!isNumber(event)) { event.preventDefault(); } } document.getElementById("valueTwoNew").addEventListener("keypress", validate); <div>Your way:</div> <input class="Eingabefeld " type="text" id="valueTwo" onkeypress="return isNumber(event)" /> <div><code>addEventListener</code></div> <input class="Eingabefeld " type="text" id="valueTwoNew" />
doc_4218
So, what I'm trying to do is settng the focus on textbox after OnTick event. I'm using following line: ScriptManager1.SetFocus(this.txtMessage.ClientID); This works correctly. However, Main page or I should say masterpage's scrollbar changes their position which is annoying. Please share your valuable experience. thanks. A: Have you tried using MaintainScrollPositionOnPostback on the page declaration of IfrmPage.aspx? A: After seaching on the google I found the answer. Now I'm setting the focus to txtMessage(textbox) using javascript and remove this code: ScriptManager1.SetFocus(this.txtMessage.ClientID); final answer is here: <script type="text/javascript"> var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_pageLoaded(pageLoaded); function pageLoaded(sender, args) { if (args.get_panelsUpdated().length > 0) { $get('txtMessage').focus(); } } </script>
doc_4219
With the following list format: Name Number Name Number Name Number And at last a button called "Add new.." Where we can add more of such names/numbers. Also on long pressing any item, a context menu will come called Edit/Delete. How do I go about doing this? With file writing and stuff, to save the data to sd while the app is inactive? A: * *Take one list view and edittext when you enter data into editext stored into "List"(Whatevere container you use i.e Arraylist.Array) and this "List" container set into adapter *Now give onlongcliklistener your listview item for delete and edit
doc_4220
I use debugger step by step, and found out it crashes at set(axs,'Parent',p); on version 2018b. version 2018b at line set(axs,'Parent',p); will call the program usejava.m, but not 2017a. Please help. p=uipanel(gcf,'Units','normalized','Position', [0 0.2 10.8],'BorderType','none','Tag','CursorPanel1'); set(p,'BackgroundColor',get(gcf,'Color')); axs=findall(gcf,'Type','Axes'); set(axs,'Parent',p);
doc_4221
A: The main thing you will need is a layer to add reliability. http://www.google.co.uk/search?q=java+reliable+udp UDP is not reliable and any or all of the image could be lost unless you have a protocol on top of UDP to make it reliable. I suggest you impliment this using TCP first as this is much simpler, and change it to UDP if you feel you still need to later. A: Have a look at the trivial file transfer protocol (TFTP) - it implements a file transfer over UDP. In real life, when not limited to UDP, you would use something TCP-based, as you have to implement everything again what TCP gives you over UDP, and most probably you would do this less efficient than your TCP-stack could have done.
doc_4222
Receive cat < /dev/ttyO5 >> $file Send cat < $file > /dev/ttyO5 When i check the files, sometimes the receiver machine copies some bytes of the beggining of file at the end. Something like this: ce16 8fa7 bf54 dc6b 238a #Original file ce16 8fa7 bf54 dc6b 238a ce16 8fa7 #Generated file on receive machine The number of bytes added at the end is not fixed, sometimes is 3 bytes, sometimes 4....And i dont know why, I flush the memories before sending and receiving .... Any clue? EDIT: SOLVED; the option -echo needs to be disabled on the port confirguration. A: As a rule of thumb, you shall not copy binary data over serial port with unknown configuration. Either encode the data to the text file (uuencode, base64, quoted printable, implement your own) or make sure the serial port is configured to transfer 8bit raw data. Look for this example to see how it is achieved in C code. To manipulate the serial port configuration from shell script or CLI you can use stty command. What is important: set 8 data bits, disable software control flow and select raw data to be transmitted. Make sure you set the same configuration on both side. A: Turning Lomezno's solution into an answer: stty -F <DEVICE> -echo (where <DEVICE> is the serial device) A: Lomezno mentioned not wanting to use C. To reset all the port settings, I use the following Python script: #!/usr/bin/python2.7 import os, time, termios, sys PORT = sys.argv[1] # reset the serial port configuration fd = os.open(PORT, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK) iflag = termios.IGNBRK oflag = 0 cflag = termios.CS8 | termios.CREAD | termios.CLOCAL lflag = 0 speed = termios.B115200 cc = termios.tcgetattr(fd)[-1] attr = [iflag, oflag, cflag, lflag, speed, speed, cc] termios.tcsetattr(fd, termios.TCSANOW, attr) os.close(fd)
doc_4223
I am creating installation for my application using Installshield. What are the dependency files or "Merge modules" should I add in the installshield? Is it necessary to add " Microsoft C++ Runtime Library" or "Microsoft Visual C++ MFC" Merge modules? A: Static linking means the foo.lib was embedded in myapp.exe during the linker phase. No dependency on foo.dll exists and does not need to be redistributed. You should also understand that while static linking makes your deployment easier it's actually considered a security vunerability because if an exploit is found in foo.lib/foo.dll (MFC in this case) then Microsoft can't patch your application by updating the version in the WinSXS cache. It'll be up to you to include the latest redist on your build machine, rebuild and redeploy. I highly suggest creating a virtual machine with a base snapshot that represents the oldest OS that you want to support and then testing your installer there. This will help identify missing dependencies that can then be resolved by using tools such as Dependency Walker, ILDasm/.NET Reflactor and ProcessMon. A: At least if memory serves, no. If you use MFC in a static library, you're also required to link statically to the standard library as well. Unless you've added some other dependency on some other DLL, you should have a standalone executable. You can/could check with dependency walker just to be sure, if you prefer. A: Many times we are facing issue of size of exe and dll is more than previous build. This can be resolved using project properties Menu "Project" - Properties... Configuration Properties --->"Use of MFC Use MFC in static Library" and In "C/C++ options"--> tab "Code Generation"-->choose "Multithreaded /MT" for static MFC. if we choose above options then we do not need the VC2008 Redistributable installed on the PC and size of exe or dll is lesser
doc_4224
def returnNumber() -> int | None: retur 1 Is there any way to specify in the init function that we are going to return the class itself? class Tree: def __init__(self) -> Tree: #hereeee because in language server auto completion appears () -> None //this with a class init () -> int|None // this with the function example
doc_4225
request.setAttribute("name", nameVariable); request.setAttribute("surname", surnameVariable); request.setAttribute("list", list); //Here are stored ultimately all the data (so name and surname also) My list is being updated and I need to have the list being updated also. I know my list gets more items, but this code prints only last record from that list. What should I change in my code to be able to print all records from list in table? My jsp: <c:forEach items="${list}"> <tr> <td>${name}</td> <td>${surname}</td> </tr> </c:forEach> A: You're always printing the same request attributes, at each iteration of the loop, completely ignoring the current element of the list. Assuming the list contains objects of type Person (for example), which has a getName() and a getSurname() method, the code should be <c:forEach items="${list}" var="person"> <tr> <td>${person.name}</td> <td>${person.surname}</td> </tr> </c:forEach> Just like, in Java, a foreach loop would define a person variable for the current person during the itertion: for (Person person: list) { System.out.println(person.getName()); System.out.println(person.getSurname()); }
doc_4226
Error syntax error, unexpected '(', expecting ')' Routes resources :events do resources :sessions, path: "schedule", only: [:index] end View <%= link_to "Back to Event", @event_path(@event) %> Sessions Controller class SessionsController < ApplicationController before_filter :find_event def index @sessions = Session.all end private def find_event @event = Event.find_by(slug: params[:event_id]) end end A: It should be: <%= link_to "Back to Event", event_path(@event) %> (event_path is a method) or simply: <%= link_to "Back to Event", @event %> A: Marek is correct - Something more to note is that if you ever want to send to a nested resource (I.E you want to show the session), you'd need to use the likes of: session_path(@session, @event) #-> notice the two objects, not a single one Currently, you'd just need to pass the single object, but in the event you wanted to use a nested route, you'd have to send the nested object & its parent object too
doc_4227
My setup: Arch Linux, Python 3.3, tornado, cherrypy 3.2 Trying to implement session handling for a web app using cherrypy.lib.sessions (for some reason often referred to as cherrypy.sessions in various forums, might be another version) I am looking for an example of the following: * *instantiate a session object *set a value of an arbitrarily named attribute *write session into a session file *read session info from session file *access the the value of the modified attribute My (relevant) code: import cherrypy class RequestHandlerSubmittedRequest(tornado.web.RequestHandler): def get(self): SetState(self) def SetState(self): cherrypy.config.update({'tools.sessions.on': True}) cherrypy.config.update({'tools.sessions.storage_type': 'file'}) #directory does exist cherrypy.config.update({'tools.sessions.storage_path': '/tmp/cherrypy_sessions'}) cherrypy.config.update({'tools.sessions.timeout': 60}) cherrypy.config.update({'tools.sessions.name': 'hhh'}) So far so good. Now: obj_session = cherrypy.lib.sessions.FileSession Here I get the first snag (or misunderstanding). The returned obj_session contains no session ID of any kind, just an empty object frame. Also: no file is created at this point in /tmp/cherrypy_sessions - should not it be there now? I would expect it to be created and named after its session ID. OK, no ID in the object, let's assign one: session_id = obj_session.generate_id(self) This returns a long random string as it should I guess And now I don't know how to proceed with assignments and saving calling obj_session.save() or obj_session.load() with several variations of input gives "AttributeError: 'module' object has no attribute X" where X can be "load" and couple of other keywords. Passing self or obj_session itself to the methods does not help, just changes the wording of the error. I must be going in a very wrong direction in general. So, is there an example of those five steps above? I could not find one anywhere. Thanks. Igor
doc_4228
I have a table coded like this: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <style type="text/css"> table { font-family: verdana,arial,sans-serif; font-size:11px; color:#333333; border-width: 1px; border-color: #3A3A3A; border-collapse: collapse; } table th { border-width: 1px; padding: 8px; border-style: solid; border-color: #3A3A3A; background-color: #B3B3B3; } table td { border-width: 1px; padding: 8px; border-style: solid; border-color: #3A3A3A; background-color: #ffffff; } </style> <title>Table</title> </head> <body> <table> <thead> <tr><th>boundary</th><th>slice</th><th>h_i</th><th>1/2 (h_{i+1}+h_i)</th></tr> </thead> <tbody> <tr><td>0</td><td></td><td>0.00</td><td></td></tr> <tr><td>1</td><td>1</td><td>2.26</td><td>1.13</td></tr> <tr><td>2</td><td>2</td><td>4.37</td><td>3.32</td></tr> <tr><td>3</td><td>3</td><td>6.32</td><td>5.35</td></tr> <tr><td>4</td><td>4</td><td>5.74</td><td>6.03</td></tr> <tr><td>5</td><td>5</td><td>4.90</td><td>5.32</td></tr> <tr><td>6</td><td>6</td><td>3.61</td><td>4.25</td></tr> <tr><td>7</td><td>7</td><td>0.00</td><td>1.80</td></tr> </tbody> </table> </body> </html> I want that the table be formatted in CSS so that the rows that belong to the odd columns be shifted half of its height downwards. Such as is shown in the following image. Formatting the table in order to have rows shifted downwards Please, do avoid row spanning in the structure of the table. I know it is possible to obtain the solution by spanning four rows for the even columns and two rows for the odd columns. But doing like that is not elegant and I will waste a lot of blank td tags. The challenge here is to have the solution with pure formatting, with CSS, if a solution exist. A: You may use transform : table { font-family: verdana, arial, sans-serif; font-size: 11px; color: #333333; border-width: 1px; border-color: #3A3A3A; border-collapse: collapse; } table th { border-width: 1px; padding: 8px; border-style: solid; border-color: #3A3A3A; background-color: #B3B3B3; } table td { border-width: 1px; padding: 8px; border-style: solid; border-color: #3A3A3A; background-color: #ffffff; } :empty { opacity:0; } tbody tr td:nth-child(even) { transform: translateY(-50%); box-shadow:0 0 0 1px #3a3a3a } <table> <thead> <tr> <th>boundary</th> <th>slice</th> <th>h_i</th> <th>1/2 (h_{i+1}+h_i)</th> </tr> </thead> <tbody> <tr> <td>0</td> <td></td> <td>0.00</td> <td></td> </tr> <tr> <td>1</td> <td>1</td> <td>2.26</td> <td>1.13</td> </tr> <tr> <td>2</td> <td>2</td> <td>4.37</td> <td>3.32</td> </tr> <tr> <td>3</td> <td>3</td> <td>6.32</td> <td>5.35</td> </tr> <tr> <td>4</td> <td>4</td> <td>5.74</td> <td>6.03</td> </tr> <tr> <td>5</td> <td>5</td> <td>4.90</td> <td>5.32</td> </tr> <tr> <td>6</td> <td>6</td> <td>3.61</td> <td>4.25</td> </tr> <tr> <td>7</td> <td>7</td> <td>0.00</td> <td>1.80</td> </tr> </tbody> </table> Else,witout CSS, use the rowspan attribute and empty cells on the last row too. td:empty { opacity: 0; } table { font-family: verdana, arial, sans-serif; font-size: 11px; color: #333333; border-width: 1px; border-color: #3A3A3A; border-collapse: collapse; } table th { border-width: 1px; padding: 8px; border-style: solid; border-color: #3A3A3A; background-color: #B3B3B3; } table td { border-width: 1px; padding: 8px; border-style: solid; border-color: #3A3A3A; background-color: #ffffff; } :empty { opacity: 0; } <table> <thead> <tr> <th>boundary</th> <th>slice</th> <th>h_i</th> <th>1/2 (h_{i+1}+h_i)</th> </tr> </thead> <tbody> <tr> <td rowspan=2>0</td> <td></td> <td rowspan=2>0.00</td> <td></td> </tr> <tr> <td rowspan=2>1</td> <td rowspan=2>2.26</td> </tr> <tr> <td rowspan=2>1</td> <td rowspan=2>1.13</td> </tr> <tr> <td rowspan=2>2</td> <td rowspan=2>4.37</td> </tr> <tr> <td rowspan=2>2</td> <td rowspan=2>3.32</td> </tr> <tr> <td rowspan=2>3</td> <td rowspan=2>6.32</td> </tr> <tr> <td rowspan=2>3</td> <td rowspan=2>5.35</td> </tr> <tr> <td rowspan=2>4</td> <td rowspan=2>5.74</td> </tr> <tr> <td rowspan=2>4</td> <td rowspan=2>6.03</td> </tr> <tr> <td rowspan=2>5</td> <td rowspan=2>4.90</td> </tr> <tr> <td rowspan=2>5</td> <td rowspan=2>5.32</td> </tr> <tr> <td rowspan=2>6</td> <td rowspan=2>3.61</td> </tr> <tr> <td rowspan=2>6</td> <td rowspan=2>4.25</td> </tr> <tr> <td rowspan=2>7</td> <td rowspan=2>0.00</td> </tr> <tr> <td rowspan=2>7</td> <td rowspan=2>1.80</td> </tr> <tr> <td></td> <td></td> </tr> </tbody> </table> https://html.com/tables/rowspan-colspan/
doc_4229
django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable I dont know what i am missing or what is going wrong? A: In venv\Scripts\activate.bat in last line add set SECRET_KEY="XXXXXX" and it will work
doc_4230
With certain parameters the webpage returns an error page. I want to trap this and do something else. The code below works. I set up an invisible buffer image and load the webpage to it. Then in the onload() function I draw it onto a canvas element and check some pixel colours (here simplified to checking one byte of one pixel) If everything is OK. I load the main image. var imgMain = document.getElementById("imgDisplay"); var imgCopy = new Image(); callURL = "www.mywebpage.com?index=42"; imgCopy.src = callURL; imgCopy.onload = function() { var context = document.createElement('CANVAS').getContext('2d'); context.drawImage(imgCopy, 0, 0);. var pixel1_1 = context.getImageData(0, 0, 1, 1).data; if(pixel1_1[0] == 228) imgMain.src = callURL; }; This code only works within the onload() function. Despite the fact that everybody tells me that JavaScript is a synchronous language it's not possible to set imgCopy and check it before going on. Mainly for readability purposes I would like to be able to delay execution until imgCopy is fully loaded, then call a Boolean function to perform the tests on the image. Does anybody have any ideas? Many thanks Tony Reynolds (UK) As I didn't get a response I decided not to be so lazy and did some work with Promises. Eventually I came up with: const promise = new Promise(function(resolve, reject) { img.src = callURL; resolve('Success!'); }); promise.then(function(value) { var context; context = document.createElement('CANVAS').getContext('2d'); context.drawImage(img, 0, 0); var pixel1_1 = context.getImageData(0, 0, 1, 1).data; }; So loading the image is embedded within a Promise, and the .then function I hoped would only execute when the Promise was resolved. It didn't work.... Does anybody know why not? Thanks Tony Reynolds A: Is your code actually working or did you mis-copy, because the line imgCopy = callURL; makes no sense. It should be imgCopy.src = callURL;. And as Griffin says, set onload before setting src.
doc_4231
update Records set ActiveStatus=0, TransactionStatus=0, LastUpdated=& where ActiveStatus!=5 and LastUpdated!=& and Pk in (select RecordPk from GroupRecordLink where GroupPk in (select Pk from Groups where ActiveStatus!=5 and DateTimeStamp>&)) I had a go rewriting it by following this post , but I am not sure my result is correct. update Records r join (select distinct RecordPk from GroupRecordLink grl join Groups g on grl.Pk = g.Pk where g.ActiveStatus!=5 and g.DateTimeStamp>&) s using (Pk) set ActiveStatus=0, TransactionStatus=0, LastUpdated=& where ActiveStatus!=5 and DateTimeStamp>& Thanks A: In Mysql you could use an explicit join for update (you must change & witha proper value ) update Records INNER JOIN GroupRecordLink on GroupRecordLink.RecordPk = Records.PK INNER JOIN Groups on ( GroupRecordLink.GroupPk = Groups.Pk and Groups.ActiveStatus!=5 and Groups.DateTimeStamp>&) set ActiveStatus=0, TransactionStatus=0, LastUpdated=& A: Try this: UPDATE Records INNER JOIN GroupRecordLink ON Records.Pk = GroupRecordLink.RecordPk INNER JOIN Groups ON GroupRecordLink.GroupPk = Groups.Pk AND Groups.ActiveStatus != 5 SET Records.ActiveStatus = 0, Records.TransactionStatus = 0, Records.LastUpdated = & WHERE Records.ActiveStatus != 5 AND Records.LastUpdated != &;
doc_4232
All those extra feature help noobs to gurus not only sometimes become a better programmer but also help them make their life easier. One of the recent questions I found, was about the new dynamic variable introduced with the framework 4. Problem was it did not have highlighting nor intellisense. This was easily resolved with Resharper. *My question is what kind of Extensions/Plugins do you have or must die for ? * Add some bullet features and information pls so no one has to search And if possible not limited to Visual Studio as we all program in many different languages. Visual Studio: * *Visual Assist by 0xc0deface *RockScroll by 0xc0deface *Resharper for Visual Studio : Highlighter, Intellisense and so much more *JustCode for Visual Studio : Highlighter, Intellisense Wonder: if we can make a faq about all the Extensions/Plugins available to us. A: Visual Assist and Rockscroll are what I use. Rockscroll is free and is the best scroll bar implementation i've ever seen. It replaces the default VS scroll bar with an image of the file you are browsing that makes navigation a breeze. Also if you double click a variable or some other text it will highlight all occurances of it on the page in red on the scroll bar. Visual assist has far too many features to mention here, but here is a link to their feature page. I will however mention some of its shortcuts that I believe add a lot to VS and that I use for code navigation daily without fail: * *Alt + Shift + O - open file in solution. It lets you type a few letters from the name of the file you want to open (enough to disambiguate) and hit enter, saving you from navigating in the solution explorer. *Alt + M - Drops open a list of all functions in the current file, you can then type a few letters to disambiguate the function name you want and hit enter to be taken straight to it. *Alt + Shift + S - Find symbol in solution. Like a powerful find all references for whatever you are searching for, including function names. *Alt + O - switch between same named .h and .cpp files. I don't think i could live without this one, and am quite surprised that it VS doesn't have this out of the box. It also costs $249 ($49 for students) but IMO is well worth it. I have been using it for 3 years and feel like the IDE is broken without it.
doc_4233
For instance: ....method() { int num = 0; //wait for keydown Enter num = Convert.ToInt32(TextBox1.Text); //or String s = TextBox1.Text; num = Int.TryParse(s); .... } A: You should just generally change the control flow of your program. Either declare num at the class level, or call the method that depends on num from within the handler passing it num. Like; KeyDownHandler() { MessageBox.Show("Some Message"); // or if you need something with more flexiblity OtherForm of = new OtherForm(); OtherForm.Show(); string someVal = OtherForm.TextBox.Text; MethodThatNeedsInputFromTextBox(int.Parse(TextBox.Text)); } MessageBox.Show method list; http://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox.show(v=vs.71).aspx You'll probably want to use something other than the default like the dialogue option which makes it so the messagebox retains focus until the user closes it.
doc_4234
<ul class="announcements unread"> <li> <div class="announcement-text">Test message <a href="edit/231">Edit</a> <a href="delete/231">Delete</a> </div> </li> <li> <div class="announcement-text">Delete this message <a href="edit/232">Edit</a> <a href="delete/232">Delete</a> </div> </li> The number behind the edit and delete in the link is like an id for that message A: That sounds pretty much possible. Your post seems to look like <Element> <Message> some message text </Message> <DeleteLink/> </Element> So, you would simply have to loop over each of the posts, match the message text, and click the delete link if a match is found. A: As bit said, you can loop over each of the posts doing : List<WebElement> list = driver.findElements(By.cssSelector(".element .message")); for(int i = 0 ; i< list.size() ; i++){ String message = list.get(i).getText(); if(message.contains("whatever_you_want"){ // Here you click on the corresponding delete link driver.findElements(By.cssSelector(".element .deleteLink")).get(i).click(); } } Note that as I don't know how your HTML looks like, I've taken class names for css Selectors, based on bit answer
doc_4235
svn *command* svn+ssh://dev.myserver.com/var/svn/myproject every time I need to checkout, switch, or tag. Is there a way I can alias the repository path, so I can just run: svn *command* myserver/myproject My poor ol' fingers are tired :( A: Alias in your .bashrc file: alias sitesvn="svn info | egrep '^URL: (.*)' | sed s/URL\:\ //" to be tested on all possible protocols and modified, if needed. If current form this alias can be used as svn *command* $(sitesvn) (sitesvn is full RepoURL for used WC)
doc_4236
* *GCP ML Vision. *Exported Model to tflite format (from the same GCP console). *XCode for iOS development *iPhone 11 pro I am trying to use a Custom Object detector using MLKit and one model trained in GCP AutoML Vision. I created the model and exported as tflite file, but when trying to do objectDetector processImage:visionImage, I always get the error: Error Domain=com.google.visionkit.pipeline.error Code=3 "Pipeline failed to fully start: CalculatorGraph::Run() failed in Run: Calculator::Open() for node "BoxClassifierCalculator" failed: #vk Unexpected number of dimensions for output index 0: got 3D, expected either 2D (BxN with B=1) or 4D (BxHxWxN with B=1, W=1, H=1)." UserInfo={com.google.visionkit.status=<MLKITvk_VNKStatusWrapper: 0x280841270>, NSLocalizedDescription=Pipeline failed to fully start: CalculatorGraph::Run() failed in Run: Calculator::Open() for node "BoxClassifierCalculator" failed: #vk Unexpected number of dimensions for output index 0: got 3D, expected either 2D (BxN with B=1) or 4D (BxHxWxN with B=1, W=1, H=1).}. I have downloaded the mlkit examples from https://github.com/googlesamples/mlkitand there is something similar in the vision project, (to detect birds) when I try to replace my own tflite file, it breaks in the exact same way as in my own project. I presume the tflite is created in a very different way as MLVision does. Any insight? (Sorry if this is so obvious, but I'm pretty new to TensorFlow and MLVision) Thanks in advance A: The issue is exactly as what the error message says: got 3D, expected either 2D (BxN with B=1) or 4D (BxHxWxN with B=1, W=1, H=1). That means your model is not compatible with ML Kit, as its tensor has incorrect dimension. The model compatibility requirements are specified here.
doc_4237
i have just changed the urlRegistration and urlLogin variables in BackgroundTask Class from "http://tabian.ca/LoginAndRegister-register.php" to my "http://lmonstergirl.0fees.us/LoginAndRegister-register.php". database is same as the project. whenever i want to register anyone, i get "successfully registered user" message but it only adds the id, other rows are blank. code is same and my php files are below. This <?php require "LoginAndRegister-connection.php"; $user_name = $_POST["identifier_name"]; $user_pass = $_POST["identifier_password"]; $user_email = $_POST["identifier_email"]; //test variables //$user_name = "Ron"; //$user_pass = "ronspassword"; //$user_email = "ron@tabian.ca"; $query = "INSERT INTO login (name,email,password) VALUES ('$user_name','$user_email','$user_pass')"; if(mysqli_query($conn,$query)){ echo "<h2>Data Successfully Inserted!</h2>"; } else{ echo "<h2>Data was unable to be inserted into database :(.</h2>"; } ?> but when I change my php to this <?php require "LoginAndRegister-connection.php"; //$user_name = $_POST["identifier_name"]; //$user_pass = $_POST["identifier_password"]; //$user_email = $_POST["identifier_email"]; //test variables $user_name = "Ron"; $user_pass = "ronspassword"; $user_email = "ron@tabian.ca"; $query = "INSERT INTO login (name,email,password) VALUES ('$user_name','$user_email','$user_pass')"; if(mysqli_query($conn,$query)){ echo "<h2>Data Successfully Inserted!</h2>"; } else{ echo "<h2>Data was unable to be inserted into database :(.</h2>"; } ?> it adds to db i also tried to change $_POST to $_GET and still added blank. here is my log FATAL EXCEPTION: main Process: applications.loginandregister, PID: 3893 android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@12b6e281 is not valid; is your activity running? at android.view.ViewRootImpl.setView(ViewRootImpl.java:576) at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:272) at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69) at android.app.Dialog.show(Dialog.java:306) at android.app.AlertDialog$Builder.show(AlertDialog.java:987) at applications.loginandregister.BackgroundTask.display(BackgroundTask.java:183) at applications.loginandregister.BackgroundTask.onPostExecute(BackgroundTask.java:169) at applications.loginandregister.BackgroundTask.onPostExecute(BackgroundTask.java:29) at android.os.AsyncTask.finish(AsyncTask.java:632) at android.os.AsyncTask.access$600(AsyncTask.java:177) at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5349) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703) i have only changed the urls in the code but there you go: public class BackgroundTask extends AsyncTask<String,Void,String> { SharedPreferences preferences; SharedPreferences.Editor editor; Context context; BackgroundTask(Context ctx){ this.context = ctx; } @Override protected String doInBackground(String... params) { preferences = context.getSharedPreferences("MYPREFS", Context.MODE_PRIVATE); editor = preferences.edit(); editor.putString("flag","0"); editor.commit(); String urlRegistration = "http://lmonstergirl.0fees.us/LoginAndRegister-register.php"; String urlLogin = "http://lmonstergirl.0fees.us/LoginAndRegister-login.php"; String task = params[0]; if(task.equals("register")){ String regName = params[1]; String regEmail = params[2]; String regPassword = params[3]; try { URL url = new URL(urlRegistration); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); OutputStream outputStream = httpURLConnection.getOutputStream(); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8"); BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter); String myData = URLEncoder.encode("identifier_name","UTF-8")+"="+URLEncoder.encode(regName,"UTF-8")+"&" +URLEncoder.encode("identifier_email","UTF-8")+"="+URLEncoder.encode(regEmail,"UTF-8")+"&" +URLEncoder.encode("identifier_password","UTF-8")+"="+URLEncoder.encode(regPassword,"UTF-8"); bufferedWriter.write(myData); bufferedWriter.flush(); bufferedWriter.close(); InputStream inputStream = httpURLConnection.getInputStream(); inputStream.close(); editor.putString("flag","register"); editor.commit(); return "Successfully Registered " + regName; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } if(task.equals("login")){ String loginEmail = params[1]; String loginPassword = params[2]; try { URL url = new URL(urlLogin); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); //send the email and password to the database OutputStream outputStream = httpURLConnection.getOutputStream(); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8"); BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter); String myData = URLEncoder.encode("identifier_loginEmail","UTF-8")+"="+URLEncoder.encode(loginEmail,"UTF-8")+"&" +URLEncoder.encode("identifier_loginPassword","UTF-8")+"="+URLEncoder.encode(loginPassword,"UTF-8"); bufferedWriter.write(myData); bufferedWriter.flush(); bufferedWriter.close(); outputStream.close(); //get response from the database InputStream inputStream = httpURLConnection.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String dataResponse = ""; String inputLine = ""; while((inputLine = bufferedReader.readLine()) != null){ dataResponse += inputLine; } bufferedReader.close(); inputStream.close(); httpURLConnection.disconnect(); System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); System.out.println(dataResponse); editor.putString("flag","login"); editor.commit(); return dataResponse; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return null; } @Override protected void onPreExecute() { super.onPreExecute(); } //This method willbe called when doInBackground completes... and it will return the completion string which //will display this toast. @Override protected void onPostExecute(String s) { String flag = preferences.getString("flag","0"); if(flag.equals("register")) { Toast.makeText(context,s,Toast.LENGTH_LONG).show(); } if(flag.equals("login")){ String test = "false"; String name = ""; String email = ""; String[] serverResponse = s.split("[,]"); test = serverResponse[0]; name = serverResponse[1]; email = serverResponse[2]; if(test.equals("true")){ editor.putString("name",name); editor.commit(); editor.putString("email",email); editor.commit(); Intent intent = new Intent(context,LogginIn.class); context.startActivity(intent); }else{ display("Login Failed...", "That email and password do not match our records :(."); } }else{ display("Login Failed...","Something weird happened :(."); } } @Override protected void onProgressUpdate(Void... values) { super.onProgressUpdate(values); } public void display(String title, String message){ AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setCancelable(true); builder.setTitle(title); builder.setMessage(message); builder.show(); } } public class LogginIn extends AppCompatActivity { TextView name,email; SharedPreferences preferences; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.logged_in_layout); email = (TextView) findViewById(R.id.textEmail); name = (TextView) findViewById(R.id.textName); preferences = this.getSharedPreferences("MYPREFS", Context.MODE_PRIVATE); String mName = preferences.getString("name","ERROR getting name"); String mEmail = preferences.getString("email","ERROR getting email"); name.setText(mName); email.setText(mEmail); } } public class Register extends AppCompatActivity { EditText etName, etEmail, etPassword; String name, email, password; Button btnRegister; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.register_layout); etName = (EditText) findViewById(R.id.etNewName); etEmail = (EditText) findViewById(R.id.etNewEmail); etPassword = (EditText) findViewById(R.id.etNewPassword); btnRegister = (Button) findViewById(R.id.btnNewRegister); btnRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { name = etName.getText().toString(); email = etEmail.getText().toString(); password = etPassword.getText().toString(); String task = "register"; BackgroundTask backgroundTask = new BackgroundTask(Register.this); backgroundTask.execute(task,name, email, password); finish(); } }); } } public class MainActivity extends AppCompatActivity { Button btnRegister, btnLogin; EditText etEmail,etPassword; String stringEmail,stringPassword; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnRegister = (Button) findViewById(R.id.btnRegister); btnLogin = (Button) findViewById(R.id.btnLogin); etEmail = (EditText) findViewById(R.id.etEmail); etPassword = (EditText) findViewById(R.id.etPassword); btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { stringEmail = etEmail.getText().toString(); stringPassword = etPassword.getText().toString(); String task = "login"; BackgroundTask backgroundTask = new BackgroundTask(MainActivity.this); etEmail.setText(""); etPassword.setText(""); //execute the task //passes the paras to the backgroundTask (param[0],param[1],param[2]) backgroundTask.execute(task,stringEmail,stringPassword); } }); btnRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this,Register.class); startActivity(intent); } }); } } A: Thanks for posting to stackoverflow! Because your test variables work, you know it's not the php. The problem is almost 100% lying in the android code. Please post your android code. A: i have found out that the web server i am using has some issues. i basically made a form and added register.php as its action. tried on my local server and worked fine for both android device and pc. then i added that form to web server and worked fine for pc but added blank texts again for android. post array is empty when trying to connect from android device.
doc_4238
Here are some sample crash logs, does anyone have any idea how to trace this bug? By the way, the game is developed using cocos2d-x running Lua script. A/libc(23865): Fatal signal 11 (SIGSEGV) at 0x5e0a5024 (code=2), thread 23911 (Thread-5252) I/DEBUG(252): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** I/DEBUG(252): Build fingerprint: 'Xiaomi/armani/armani:4.3/JLS36C/JHCCNBH45.0:user/release-keys' I/DEBUG(252): Revision: '0' I/DEBUG(252): pid: 23865, tid: 23911, name: Thread-5252 >>> com.gamedo.hlw.gfan <<< I/DEBUG(252): signal 11 (SIGSEGV), code 2 (SEGV_ACCERR), fault addr 5e0a5024 I/DEBUG(252): r0 000000f1 r1 62c8c0f0 r2 62c8c198 r3 62c96d28 I/DEBUG(252): r4 000000f2 r5 00000101 r6 00000000 r7 fffffff4 I/DEBUG(252): r8 62cde188 r9 fffffffb sl 62cc72e8 fp 00000000 I/DEBUG(252): ip 00000000 sp 61028a00 lr 5ea0fd1c pc 5e0a5024 cpsr 20000010 I/DEBUG(252): d0 62d355dc62d35540 d1 0504800104008021 I/DEBUG(252): d2 0700802106007ffc d3 62d355dc62d35540 I/DEBUG(252): d4 3fe0a3bed43ed000 d5 408f400000000000 I/DEBUG(252): d6 0000000900000000 d7 3ce2010624dd2f1a I/DEBUG(252): d8 0000000000000000 d9 0000000000000000 I/DEBUG(252): d10 0000000000000000 d11 0000000000000000 I/DEBUG(252): d12 0000000000000000 d13 0000000000000000 I/DEBUG(252): d14 0000000000000000 d15 0000000000000000 I/DEBUG(252): d16 603f2754603f272c d17 603f2788603f2770 I/DEBUG(252): d18 603f22b0603f2240 d19 603f236c603f22c4 I/DEBUG(252): d20 603f244c603f23d8 d21 603f258c603f24e4 I/DEBUG(252): d22 603f2648603f25a8 d23 603f2700603f26e4 I/DEBUG(252): d24 3f56c16c16c76a94 d25 3f80ebb74dbd97f2 I/DEBUG(252): d26 408f480000000000 d27 3fc510036313e9c4 I/DEBUG(252): d28 3fe0000000000000 d29 0000000000000001 I/DEBUG(252): d30 fff0000000000000 d31 4000000000000000 I/DEBUG(252): scr 28000012 I/DEBUG(252): backtrace: I/DEBUG(252): #00 pc 00095024 [stack:23883] I/DEBUG(252): #01 pc 00007d18 <unknown> I/DEBUG(252): stack: I/DEBUG(252): 610289c0 00007fd9 I/DEBUG(252): 610289c4 60427cdc /data/app-lib/com.gamedo.hlw.gfan-1/libcocos2dlua.so I/DEBUG(252): 610289c8 6247d1c0 I/DEBUG(252): 610289cc 6247d1f0 I/DEBUG(252): 610289d0 62d355dc I/DEBUG(252): 610289d4 603fbfa8 /data/app-lib/com.gamedo.hlw.gfan-1/libcocos2dlua.so I/DEBUG(252): 610289d8 6247d1c0 I/DEBUG(252): 610289dc 6247d370 I/DEBUG(252): 610289e0 6247d1f0 I/DEBUG(252): 610289e4 000007f8 I/DEBUG(252): 610289e8 62d35658 I/DEBUG(252): 610289ec 62d355dc I/DEBUG(252): 610289f0 6247dd00 I/DEBUG(252): 610289f4 6247d1c0 I/DEBUG(252): 610289f8 df0027ad I/DEBUG(252): 610289fc 00000000 I/DEBUG(252): #00 61028a00 00007fd9 I/DEBUG(252): ........ ........ I/DEBUG(252): #01 61028a00 00007fd9 I/DEBUG(252): 61028a04 603f4220 /data/app-lib/com.gamedo.hlw.gfan-1/libcocos2dlua.so I/DEBUG(252): 61028a08 5ef1d6b8 I/DEBUG(252): 61028a0c 00000010 I/DEBUG(252): 61028a10 62d355dc I/DEBUG(252): 61028a14 6247d1c0 I/DEBUG(252): 61028a18 00000000 I/DEBUG(252): 61028a1c 00000002 I/DEBUG(252): 61028a20 00000008 I/DEBUG(252): 61028a24 6247d1f0 I/DEBUG(252): 61028a28 00000000 I/DEBUG(252): 61028a2c 00000000 I/DEBUG(252): 61028a30 60f28f1c I/DEBUG(252): 61028a34 61028b70 [stack:23911] I/DEBUG(252): 61028a38 60f28f14 I/DEBUG(252): 61028a3c 5f37dea8 I/DEBUG(252): memory near r1: I/DEBUG(252): 62c8c0d0 62d57b90 fffffffb 62d60ec0 fffffffb I/DEBUG(252): 62c8c0e0 00000000 00000000 62a82b60 00000813 I/DEBUG(252): 62c8c0f0 000002d7 ffffffff 62c96d50 fffffff4 I/DEBUG(252): 62c8c100 62c96e98 fffffff4 62c96f88 fffffff4 I/DEBUG(252): 62c8c110 62cda088 fffffff4 62cda178 fffffff4 I/DEBUG(252): 62c8c120 62cda380 fffffff4 62cda3a8 fffffff4 I/DEBUG(252): 62c8c130 62cda498 fffffff4 62cda588 fffffff4 I/DEBUG(252): 62c8c140 62cda890 fffffff4 62cda9c8 fffffff4 I/DEBUG(252): 62c8c150 62cdab00 fffffff4 62cdac38 fffffff4 I/DEBUG(252): 62c8c160 62cdacc8 fffffff4 62cdae00 fffffff4 I/DEBUG(252): 62c8c170 62cdae90 fffffff4 62cdafc8 fffffff4 I/DEBUG(252): 62c8c180 62cdb408 fffffff4 62cdb540 fffffff4 I/DEBUG(252): 62c8c190 62cdb710 fffffff4 62cdb858 fffffff4 I/DEBUG(252): 62c8c1a0 62cdb9a0 fffffff4 62cdbae8 fffffff4 I/DEBUG(252): 62c8c1b0 62cdbc30 fffffff4 62cdbd78 fffffff4 I/DEBUG(252): 62c8c1c0 62cdbec0 fffffff4 62cdc008 fffffff4 I/DEBUG(252): memory near r2: I/DEBUG(252): 62c8c178 62cdafc8 fffffff4 62cdb408 fffffff4 I/DEBUG(252): 62c8c188 62cdb540 fffffff4 62cdb710 fffffff4 I/DEBUG(252): 62c8c198 62cdb858 fffffff4 62cdb9a0 fffffff4 I/DEBUG(252): 62c8c1a8 62cdbae8 fffffff4 62cdbc30 fffffff4 I/DEBUG(252): 62c8c1b8 62cdbd78 fffffff4 62cdbec0 fffffff4 I/DEBUG(252): 62c8c1c8 62cdc008 fffffff4 62cdc150 fffffff4 I/DEBUG(252): 62c8c1d8 62cdc298 fffffff4 62cdc3e0 fffffff4 I/DEBUG(252): 62c8c1e8 62cda740 fffffff4 62c96e40 fffffff4 I/DEBUG(252): 62c8c1f8 62c89160 fffffff4 62c898b0 fffffff4 I/DEBUG(252): 62c8c208 62c899f8 fffffff4 62c89b40 fffffff4 I/DEBUG(252): 62c8c218 62c89c88 fffffff4 62c89dd0 fffffff4 I/DEBUG(252): 62c8c228 62c89f18 fffffff4 62c8a060 fffffff4 I/DEBUG(252): 62c8c238 62c8a1a8 fffffff4 62c8a2f0 fffffff4 I/DEBUG(252): 62c8c248 62c8a438 fffffff4 62c8a580 fffffff4 I/DEBUG(252): 62c8c258 62c8a6c8 fffffff4 62c8a810 fffffff4 I/DEBUG(252): 62c8c268 62c8a958 fffffff4 62c8aaa0 fffffff4 I/DEBUG(252): memory near r3: I/DEBUG(252): 62c96d08 62cc2550 0000001b 62f5d2a8 62000400 I/DEBUG(252): 62c96d18 345b0d94 00000001 00000039 0000002b I/DEBUG(252): 62c96d28 62cddc78 00000b01 62c8c0f0 62cdb540 I/DEBUG(252): 62c96d38 00000000 6247d248 00000101 00000000 I/DEBUG(252): 62c96d48 62c7e1b8 0000002b 62c96d28 00000b01 I/DEBUG(252): 62c96d58 00000000 62c90600 00000000 62c96d78 I/DEBUG(252): 62c96d68 00000000 00000007 00000181 000000cb I/DEBUG(252): 62c96d78 62c95c20 fffffffb 62cde188 fffffffb I/DEBUG(252): 62c96d88 00000000 62c96e08 00000000 ffffffff I/DEBUG(252): 62c96d98 0000005f ffffffff 00000000 00000000 I/DEBUG(252): 62c96da8 00000000 ffffffff 00000354 ffffffff I/DEBUG(252): 62c96db8 00000000 00000000 62c95c00 fffffffb I/DEBUG(252): 62c96dc8 62d60ec0 fffffffb 00000000 00000000 I/DEBUG(252): 62c96dd8 62c95bd0 fffffffb 62afe140 fffffffb I/DEBUG(252): 62c96de8 62c96e08 00000000 00000000 ffffffff I/DEBUG(252): 62c96df8 0000022a ffffffff 00000000 00000000 I/DEBUG(252): memory near r8: I/DEBUG(252): 62cde168 74636566 6261662f 7a5f6f61 69787568 I/DEBUG(252): 62cde178 696a6e61 6d2e6e61 62003370 0000002b I/DEBUG(252): 62cde188 00000000 00000401 699e1a18 00000004 I/DEBUG(252): 62cde198 63736564 ffffff00 00000000 000000a7 I/DEBUG(252): 62cde1a8 00000028 00000093 62cde000 03000701 I/DEBUG(252): 62cde1b8 00000008 62cc3d20 62cde220 62cde220 I/DEBUG(252): 62cde1c8 00000004 00000000 0000008a 00002001 I/DEBUG(252): 62cde1d8 62c85948 00000476 00000003 62cde224 I/DEBUG(252): 62cde1e8 62cde22b 62cde239 00000355 0000002b I/DEBUG(252): 62cde1f8 00000125 00010225 0103003e 00020034 I/DEBUG(252): 62cde208 00030037 00020048 62a97e90 62483d78 I/DEBUG(252): 62cde218 62a97908 62cde090 022dc000 01010101 I/DEBUG(252): 62cde228 64020202 65727065 65746163 70695464 I/DEBUG(252): 62cde238 00000000 0000002b 00000000 00000401 I/DEBUG(252): 62cde248 bbe7d83d 00000013 61504343 63697472 I/DEBUG(252): 62cde258 7845656c 736f6c70 006e6f69 0000002b I/DEBUG(252): memory near sl: I/DEBUG(252): 62cc72c8 80000254 00010047 62d60ec0 62b66a38 I/DEBUG(252): 62cc72d8 62cc72e8 62cc7308 0201c000 00000023 I/DEBUG(252): 62cc72e8 62c959d8 ff000401 02623c3a 00000009 I/DEBUG(252): 62cc72f8 6b6e696c 65746e45 62a60072 00000023 I/DEBUG(252): 62cc7308 62d311c8 00000401 3c3daf3e 00000008 I/DEBUG(252): 62cc7318 53746567 646e756f 62cc7200 00000023 I/DEBUG(252): 62cc7328 00000000 62000400 7d9ffe75 00000005 I/DEBUG(252): 62cc7338 6c696b73 0000006c 00000020 00000093 I/DEBUG(252): 62cc7348 62cc71a0 03000701 00000008 62cc2468 I/DEBUG(252): 62cc7358 62cc73b8 62cc73b8 00000004 00000000 I/DEBUG(252): 62cc7368 0000008a 00002001 62c85948 0000027c I/DEBUG(252): 62cc7378 00000003 62cc73bc 62cc73c3 62cc73d1 I/DEBUG(252): 62cc7388 00000355 0000002b 00000125 00010225 I/DEBUG(252): 62cc7398 0103003e 00020034 00030037 00020048 I/DEBUG(252): 62cc73a8 62a6be98 62483d78 62a6bad8 62cc7230 I/DEBUG(252): 62cc73b8 0266c000 01010101 64020202 65727065 I/DEBUG(252): memory near sp: I/DEBUG(252): 610289e0 6247d1f0 000007f8 62d35658 62d355dc I/DEBUG(252): 610289f0 6247dd00 6247d1c0 df0027ad 00000000 I/DEBUG(252): 61028a00 00007fd9 603f4220 5ef1d6b8 00000010 I/DEBUG(252): 61028a10 62d355dc 6247d1c0 00000000 00000002 I/DEBUG(252): 61028a20 00000008 6247d1f0 00000000 00000000 I/DEBUG(252): 61028a30 60f28f1c 61028b70 60f28f14 5f37dea8 I/DEBUG(252): 61028a40 61028a74 603ff388 fffffffd 60ef58c0 I/DEBUG(252): 61028a50 5f37de98 600ab578 00000001 6242a440 I/DEBUG(252): 61028a60 fffffffd 600ab3b8 fffffffe 00000000 I/DEBUG(252): 61028a70 61028a94 600ab790 5f37de98 00000001 I/DEBUG(252): 61028a80 0000002a 6242a440 3d31d1d4 00000000 I/DEBUG(252): 61028a90 61028aac 600a71bc 61028ad4 6244bfb0 I/DEBUG(252): 61028aa0 61028ad4 00000000 61028abc 600a6b58 I/DEBUG(252): 61028ab0 61028acc 6244bfb0 61028ae4 607dfa30 I/DEBUG(252): 61028ac0 65bab968 6580d4c0 00000001 00000003 I/DEBUG(252): 61028ad0 61028ad4 0000002a 3d31d1d4 00000000 I/DEBUG(252): code around pc: I/DEBUG(252): 5e0a5004 00000000 00000000 00000000 00000000 I/DEBUG(252): 5e0a5014 00000000 00000000 00000000 00000000 I/DEBUG(252): 5e0a5024 00000000 00000000 00000000 00000000 I/DEBUG(252): 5e0a5034 00000000 00000000 00000000 00000000 I/DEBUG(252): 5e0a5044 00000000 00000000 00000000 00000000 I/DEBUG(252): 5e0a5054 00000000 00000000 00000000 00000000 I/DEBUG(252): 5e0a5064 00000000 00000000 00000000 00000000 I/DEBUG(252): 5e0a5074 00000000 00000000 00000000 00000000 I/DEBUG(252): 5e0a5084 00000000 00000000 00000000 00000000 I/DEBUG(252): 5e0a5094 00000000 00000000 00000000 00000000 I/DEBUG(252): 5e0a50a4 00000000 00000000 00000000 00000000 I/DEBUG(252): 5e0a50b4 00000000 00000000 00000000 00000000 I/DEBUG(252): 5e0a50c4 00000000 00000000 00000000 00000000 I/DEBUG(252): 5e0a50d4 00000000 00000000 00000000 00000000 I/DEBUG(252): 5e0a50e4 00000000 00000000 00000000 00000000 I/DEBUG(252): 5e0a50f4 00000000 00000000 00000000 00000000 I/DEBUG(252): code around lr: I/DEBUG(252): 5ea0fcfc 1afffff8 e59bb010 e35b0000 1bda54c4 I/DEBUG(252): 5ea0fd0c e2844001 e1540000 daffffe7 ebda54c1 I/DEBUG(252): 5ea0fd1c e24dd008 e30d1000 e3461247 e59102c8 I/DEBUG(252): 5ea0fd2c e58d0008 e304b790 e346b2c8 e24ba050 I/DEBUG(252): 5ea0fd3c e30e8e20 e3468247 e30d7d00 e3467247 I/DEBUG(252): 5ea0fd4c e3e0500d e599e00c e5994008 e37e000e I/DEBUG(252): 5ea0fd5c 1bda54ad e599e004 e5991000 e37e000c I/DEBUG(252): 5ea0fd6c 1bda54a9 e58d100c e591e01c e59a3008 I/DEBUG(252): 5ea0fd7c e5916014 e003200e e0822082 e0866182 I/DEBUG(252): 5ea0fd8c e1c620d8 e3730005 0152000a 0bda549e I/DEBUG(252): 5ea0fd9c e5966010 e3560000 1afffff8 e5916010 I/DEBUG(252): 5ea0fdac e3560000 0bda5498 e596e01c e5983008 I/DEBUG(252): 5ea0fdbc e596c014 e003200e e0822082 e08cc182 I/DEBUG(252): 5ea0fdcc e1cc20d8 e3730005 01520008 0bda548e I/DEBUG(252): 5ea0fddc e59cc010 e35c0000 1afffff8 e3e03004 I/DEBUG(252): 5ea0fdec e58d3004 e58da000 e1a0200d eb67a01f I/DEBUG(252): memory map around fault addr 5e0a5024: I/DEBUG(252): 5e00f000-5e010000 --- I/DEBUG(252): 5e010000-5e10f000 rw- [stack:23883] I/DEBUG(252): 5e10f000-5e120000 rw- D/NativeCrashListener(847): Closing socket connection: FileDescriptor[200] W/ActivityManager(847): Force finishing activity com.gamedo.hlw.gfan/com.cocos2dx.lua.AppActivity
doc_4239
Check error.log file. Nothing found. Browser send the following message: Firefox: This pdf document might not be displayed correctly. Chrome: Error Failed to load PDF document. Here is my code: // AppController.php class AppController extends Controller { public function initialize() { parent::initialize(); $this->loadComponent('RequestHandler'); $this->loadComponent('Flash'); } } // bootstrap.php Configure::write('CakePdf', [ 'engine' => 'CakePdf.mPdf', 'margin' => [ 'bottom' => 15, 'left' => 50, 'right' => 30, 'top' => 45 ], 'orientation' => 'landscape', 'pageSize' => 'Legal', 'download' => true ]); Plugin::load('CakePdf', ['bootstrap' => true, 'routes' => true]); // routes.php Router::scope('/', function (RouteBuilder $routes) { // enabled extensions $routes->addExtensions(['pdf']); } // ProductsController.php public function viewPdf($id = null) { $this->viewBuilder()->options([ 'pdfConfig' => [ 'orientation' => 'portrait', 'filename' => 'Invoice_' . $id ] ]); } I have created Template/Products/pdf/view_pdf.ctp and Template/Layout/pdf/default.ctp I cakephp version is 3.5.2 I couldn't get, where is the probleme. Please help me.
doc_4240
Service1 Service2 Service3 Nginx Proxy <-> Nginx Proxy <-> Nginx Proxy | | | Docker PHP+Apache Docker Java Docker Python | Requests using Guzzle each proxy send requests to a specific Docker container. Only default settings of Nginx are used, except proxy_read_timeout 600s. PHP use default PROD settings. Service1 send requests to Service2, Service2 send requests to Service3. The strange situation is with responses in a case with big timeout (for small timeouts there are no problems): Service3 respond to Service2 in ~ 6 min, Service2 send the response immediately to Service1. But Service1 continue to loading, waiting 600sec and, of course, respond with 504 Gateway Timeout. Why is this happen if there is still enough time? After the first timeout error, Service1 doesn't work at all until docker is not restarted. What can be the explanation?
doc_4241
I have two SWF. One with the game that we created and an other one with the MainMenu of the game. I want to load the SWF of the game when I Click on play on the MainMenu. I add this code on the first frame of the MainMenu : btnJouer.addEventListener(MouseEvent.CLICK,jouer); function jouer(pEvt:MouseEvent){ var request:URLRequest = new URLRequest("testMouvement.swf"); var loader:Loader = new Loader() loader.load(request); Security.allowDomain(loader.contentLoaderInfo.url); addChild(loader); } But when I click on play I hear the sound of my game but the game don't appear.. I have some error when I click on play but I don't understand .. If I load the swf of the game without the mainmenu everything work fine.. The Error when I click on play : *TypeError: Error #1009: Il est impossible d'accéder à la propriété ou à la méthode d'une référence d'objet nul. at cem::saut()[C:\Users\1124889\Desktop\Prog3.2\cem\saut.as:58] at hero() at flash.display::Sprite/constructChildren() at flash.display::Sprite() at flash.display::MovieClip() at cem::application()[C:\Users\1124889\Desktop\Prog3.2\cem\application.as:69] TypeError: Error #1009: Il est impossible d'accéder à la propriété ou à la méthode d'une référence d'objet nul. at cem::saut2()[C:\Users\1124889\Desktop\Prog3.2\cem\saut2.as:52] at hero2() at flash.display::Sprite/constructChildren() at flash.display::Sprite() at flash.display::MovieClip() at cem::application()[C:\Users\1124889\Desktop\Prog3.2\cem\application.as:69] TypeError: Error #1009: Il est impossible d'accéder à la propriété ou à la méthode d'une référence d'objet nul. at cem::application()[C:\Users\1124889\Desktop\Prog3.2\cem\application.as:70]* Sorry for my english am french. Thank you if someone can help me ! A: I can't comment so I'll just answer here. If you want to load external SWF into your own SWF, you'll need to use SWFLoader I've answered more thoroughly here: Actionscript 3 - List error when loading another a swf in my swf
doc_4242
A sample code to demonstrate my issue: #include <iostream> #include <boost/graph/directed_graph.hpp> #include <boost/graph/graphviz.hpp> #include <boost/property_map/transform_value_property_map.hpp> class VertexClass { public: VertexClass() { id = 12; } VertexClass( int newId ) { id = newId; } int get_id() { return id; } void set_id( int newId ) { id = newId; } private: int id; }; typedef boost::directed_graph<VertexClass, boost::no_property> Graph; int main(int,char*[]) { Graph g; Graph::vertex_descriptor v0 = g.add_vertex(3); Graph::vertex_descriptor v1 = g.add_vertex(5); Graph::vertex_descriptor v2 = g.add_vertex(6); boost::add_edge(v0,v1,g); boost::add_edge(v1,v2,g); //boost::write_graphviz(std::cout, g, ...); return 0; } Desired output: digraph G { 0[label=3]; 1[label=5]; 2[label=6]; 0->1 ; 1->2 ; } (obtained by making "id" public and running below code). Now, "id" is private, so below code (which I found reading other similar questions) won't work for me: boost::write_graphviz(std::cout, g, boost::make_label_writer(boost::get(&VertexClass::id, g))); I guess I have to use the accessor to get the id. After a bit of searching, I found some people suggesting using a value transforming property map (make_transform_value_property_map). Then I found this answer. But the problem is that in that case the property is not defined as bundled, but using enum and BOOST_INSTALL_PROPERTY. So since I don't have these tags that this method provides (and it would be difficult for me to switch methods, since my actual code is more complex), it doesn't work for me (or at least I don't know how to make it do so). Next, after reading this answer I tried the following: boost::write_graphviz(std::cout, g, boost::make_label_writer(boost::make_transform_value_property_map(&VertexClass::get_id, boost::get(boost::vertex_bundle, g)))); but I get the following error (full output below): $ g++ -Wall -std=c++11 main.cpp In file included from /usr/local/include/boost/graph/directed_graph.hpp:13:0, from main.cpp:2: /usr/local/include/boost/property_map/transform_value_property_map.hpp: In instantiation of ‘boost::transform_value_property_map<Func, PM, Ret>::reference boost::transform_value_property_map<Func, PM, Ret>::operator[](const key_type&) const [with Func = int (VertexClass::*)(); PM = boost::adj_list_vertex_property_map<boost::adjacency_list<boost::listS, boost::listS, boost::bidirectionalS, boost::property<boost::vertex_index_t, unsigned int, VertexClass>, boost::property<boost::edge_index_t, unsigned int, boost::no_property>, boost::no_property, boost::listS>, VertexClass, VertexClass&, boost::vertex_bundle_t>; Ret = int; boost::transform_value_property_map<Func, PM, Ret>::reference = int; boost::transform_value_property_map<Func, PM, Ret>::key_type = void*]’: /usr/local/include/boost/property_map/property_map.hpp:303:54: required from ‘Reference boost::get(const boost::put_get_helper<Reference, PropertyMap>&, const K&) [with PropertyMap = boost::transform_value_property_map<int (VertexClass::*)(), boost::adj_list_vertex_property_map<boost::adjacency_list<boost::listS, boost::listS, boost::bidirectionalS, boost::property<boost::vertex_index_t, unsigned int, VertexClass>, boost::property<boost::edge_index_t, unsigned int, boost::no_property>, boost::no_property, boost::listS>, VertexClass, VertexClass&, boost::vertex_bundle_t>, int>; Reference = int; K = void*]’ /usr/local/include/boost/graph/graphviz.hpp:85:56: required from ‘void boost::label_writer<Name>::operator()(std::ostream&, const VertexOrEdge&) const [with VertexOrEdge = void*; Name = boost::transform_value_property_map<int (VertexClass::*)(), boost::adj_list_vertex_property_map<boost::adjacency_list<boost::listS, boost::listS, boost::bidirectionalS, boost::property<boost::vertex_index_t, unsigned int, VertexClass>, boost::property<boost::edge_index_t, unsigned int, boost::no_property>, boost::no_property, boost::listS>, VertexClass, VertexClass&, boost::vertex_bundle_t>, int>; std::ostream = std::basic_ostream<char>]’ /usr/local/include/boost/graph/graphviz.hpp:270:18: required from ‘void boost::write_graphviz(std::ostream&, const Graph&, VertexPropertiesWriter, EdgePropertiesWriter, GraphPropertiesWriter, VertexID, typename boost::enable_if_c<boost::is_base_and_derived<boost::vertex_list_graph_tag, typename boost::graph_traits<Graph>::traversal_category>::value, boost::graph::detail::no_parameter>::type) [with Graph = boost::directed_graph<VertexClass, boost::no_property>; VertexPropertiesWriter = boost::label_writer<boost::transform_value_property_map<int (VertexClass::*)(), boost::adj_list_vertex_property_map<boost::adjacency_list<boost::listS, boost::listS, boost::bidirectionalS, boost::property<boost::vertex_index_t, unsigned int, VertexClass>, boost::property<boost::edge_index_t, unsigned int, boost::no_property>, boost::no_property, boost::listS>, VertexClass, VertexClass&, boost::vertex_bundle_t>, int> >; EdgePropertiesWriter = boost::default_writer; GraphPropertiesWriter = boost::default_writer; VertexID = boost::adj_list_vertex_property_map<boost::adjacency_list<boost::listS, boost::listS, boost::bidirectionalS, boost::property<boost::vertex_index_t, unsigned int, VertexClass>, boost::property<boost::edge_index_t, unsigned int, boost::no_property>, boost::no_property, boost::listS>, unsigned int, const unsigned int&, boost::vertex_index_t>; std::ostream = std::basic_ostream<char>; typename boost::enable_if_c<boost::is_base_and_derived<boost::vertex_list_graph_tag, typename boost::graph_traits<Graph>::traversal_category>::value, boost::graph::detail::no_parameter>::type = boost::graph::detail::no_parameter]’ /usr/local/include/boost/graph/graphviz.hpp:290:63: required from ‘void boost::write_graphviz(std::ostream&, const Graph&, VertexPropertiesWriter, EdgePropertiesWriter, GraphPropertiesWriter, typename boost::enable_if_c<boost::is_base_and_derived<boost::vertex_list_graph_tag, typename boost::graph_traits<Graph>::traversal_category>::value, boost::graph::detail::no_parameter>::type) [with Graph = boost::directed_graph<VertexClass, boost::no_property>; VertexPropertiesWriter = boost::label_writer<boost::transform_value_property_map<int (VertexClass::*)(), boost::adj_list_vertex_property_map<boost::adjacency_list<boost::listS, boost::listS, boost::bidirectionalS, boost::property<boost::vertex_index_t, unsigned int, VertexClass>, boost::property<boost::edge_index_t, unsigned int, boost::no_property>, boost::no_property, boost::listS>, VertexClass, VertexClass&, boost::vertex_bundle_t>, int> >; EdgePropertiesWriter = boost::default_writer; GraphPropertiesWriter = boost::default_writer; std::ostream = std::basic_ostream<char>; typename boost::enable_if_c<boost::is_base_and_derived<boost::vertex_list_graph_tag, typename boost::graph_traits<Graph>::traversal_category>::value, boost::graph::detail::no_parameter>::type = boost::graph::detail::no_parameter]’ /usr/local/include/boost/graph/graphviz.hpp:309:38: required from ‘void boost::write_graphviz(std::ostream&, const Graph&, VertexWriter, typename boost::enable_if_c<boost::is_base_and_derived<boost::vertex_list_graph_tag, typename boost::graph_traits<Graph>::traversal_category>::value, boost::graph::detail::no_parameter>::type) [with Graph = boost::directed_graph<VertexClass, boost::no_property>; VertexWriter = boost::label_writer<boost::transform_value_property_map<int (VertexClass::*)(), boost::adj_list_vertex_property_map<boost::adjacency_list<boost::listS, boost::listS, boost::bidirectionalS, boost::property<boost::vertex_index_t, unsigned int, VertexClass>, boost::property<boost::edge_index_t, unsigned int, boost::no_property>, boost::no_property, boost::listS>, VertexClass, VertexClass&, boost::vertex_bundle_t>, int> >; std::ostream = std::basic_ostream<char>; typename boost::enable_if_c<boost::is_base_and_derived<boost::vertex_list_graph_tag, typename boost::graph_traits<Graph>::traversal_category>::value, boost::graph::detail::no_parameter>::type = boost::graph::detail::no_parameter]’ main.cpp:30:166: required from here /usr/local/include/boost/property_map/transform_value_property_map.hpp:45:24: error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘((const boost::transform_value_property_map<int (VertexClass::*)(), boost::adj_list_vertex_property_map<boost::adjacency_list<boost::listS, boost::listS, boost::bidirectionalS, boost::property<boost::vertex_index_t, unsigned int, VertexClass>, boost::property<boost::edge_index_t, unsigned int, boost::no_property>, boost::no_property, boost::listS>, VertexClass, VertexClass&, boost::vertex_bundle_t>, int>*)this)->boost::transform_value_property_map<int (VertexClass::*)(), boost::adj_list_vertex_property_map<boost::adjacency_list<boost::listS, boost::listS, boost::bidirectionalS, boost::property<boost::vertex_index_t, unsigned int, VertexClass>, boost::property<boost::edge_index_t, unsigned int, boost::no_property>, boost::no_property, boost::listS>, VertexClass, VertexClass&, boost::vertex_bundle_t>, int>::f (...)’, e.g. ‘(... ->* ((const boost::transform_value_property_map<int (VertexClass::*)(), boost::adj_list_vertex_property_map<boost::adjacency_list<boost::listS, boost::listS, boost::bidirectionalS, boost::property<boost::vertex_index_t, unsigned int, VertexClass>, boost::property<boost::edge_index_t, unsigned int, boost::no_property>, boost::no_property, boost::listS>, VertexClass, VertexClass&, boost::vertex_bundle_t>, int>*)this)->boost::transform_value_property_map<int (VertexClass::*)(), boost::adj_list_vertex_property_map<boost::adjacency_list<boost::listS, boost::listS, boost::bidirectionalS, boost::property<boost::vertex_index_t, unsigned int, VertexClass>, boost::property<boost::edge_index_t, unsigned int, boost::no_property>, boost::no_property, boost::listS>, VertexClass, VertexClass&, boost::vertex_bundle_t>, int>::f) (...)’ return f(get(pm, k)); Every question/answer I've seen is about one of the two cases mentioned above (bundled properties with public variables (e.g. structs), or old-fashioned property declaration). I am a newbie in boost graph library, so I guess I may have missed something. But I can't figure out a solution (and got really lost in boost's documentation), so any help would be much appreciated. A: The include for transform_value_property_map indicates to me that you have been close to a solution. Here it is: boost::dynamic_properties dp; First, let's state that you want de intrinsic vertex index for the graphviz node ids: dp.property("node_id", get(boost::vertex_index, g)); Now we want to do stuff with the bundle, so let's grab the property-map for the whole bundle: auto vbundle = get(boost::vertex_bundle, g); But we can't use it directly. We need to transform it: dp.property("label", boost::make_transform_value_property_map([](VertexClass const& vd) { return vd.get_id(); }, vbundle)); Note! I've made get_id() const constant to make this compile Now write: boost::write_graphviz_dp(std::cout, g, dp); Result: Live On Coliru digraph G { 0 [label=3]; 1 [label=5]; 2 [label=6]; 0->1 ; 1->2 ; } Alternative #1 In this case, you could get away with simpler: Live On Coliru dp.property("label", boost::make_transform_value_property_map(std::mem_fn(&VertexClass::get_id), vbundle)); instead the more flexible lambda Alternative #2: No Quasi-Classes You seem to have fallen into the trap of requiring quasi-classes (PDF) where they add no value. Simplify: Live On Coliru #include <boost/graph/directed_graph.hpp> #include <boost/graph/graphviz.hpp> #include <iostream> struct VertexProps { int id; }; typedef boost::directed_graph<VertexProps> Graph; int main() { Graph g; auto v1 = add_vertex({5}, g); add_edge(add_vertex({3}, g), v1, g); add_edge(v1, add_vertex({6}, g), g); boost::dynamic_properties dp; dp.property("node_id", get(boost::vertex_index, g)); dp.property("label", get(&VertexProps::id, g)); write_graphviz_dp(std::cout, g, dp); } As you can see now the whole thing shrinks to 20 lines of code with first-class support for your vertex properties.
doc_4243
var xml = "<rss version='2.0'><channel><title>RSS Title</title></channel></rss>" is replaced by a SOAP snippet, like the one below var xml = "<xyz:ServiceName>GetDetails</xyz:ServiceName>" I get an invalid XML error or an Invalid/Unexpected Token error. What should be the procedure to access the value inside <xyz:ServiceName> tag? A: jQuery.parseXML() creates an XML document. You will get invalid XML here because you are using a namespace xyz which is not defined. So you can define a root element with a namespace definition (any url will do) and it works fine now - see demo below: var xml = `<root xmlns:xyz="http://www.w3.org/TR/html4/"> <xyz:ServiceName>GetDetails</xyz:ServiceName> </root>`; console.log(jQuery(jQuery.parseXML(xml)) .find('root').html()); .as-console-wrapper{top:0;max-height:100%!important} <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> But for snippets, you can do $(xml): var xml = `<xyz:ServiceName>GetDetails</xyz:ServiceName>`; console.log($(xml).prop('outerHTML')); .as-console-wrapper{top:0;max-height:100%!important} <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
doc_4244
A: I have this issue with one of the earlier Android studio releases. I have solved by updating the Gradle version. It may be solved your issue.
doc_4245
1) The application process some data and put the final string on Active MQ. 2) I have used message-driven-channel-adapter and service-activator to read the data from the queue. 3) That data is displayed successfully on Server(application is working as a client) using tcp-outbound-gateway. 4) I am using single-use="true", as the requirement is to disconnect the channel on acknowledgment or after the timeout. 5) Problem is when data is in bulk, let's say there is 10 message in the queue so it will show connect and disconnect 10 times instead of sending requestMessage on the connection. Looks like it is due to threading used by spring, as when I have applied breakpoint on handleMessageInternal(Message) method of TcpOutboundGateway, every message is sending successfully, when control reaches at connection.send(requestMessage); but with the run mode I am seeing connect, disconnect behavior without the incoming message. Code for configuration is <int:channel id="telnetChannel" /> <beans:bean id="clientCustomSerializer" class="com.telnet.core.serializer.CustomSerializer"> <beans:property name="terminatingChar" value="10" /> <beans:property name="maxLength" value="65535" /> </beans:bean> <int:gateway id="gw" service-interface="com.telnet.core.integration.connection.ParseConfig$SimpleGateway" default-request-channel="telnetClientChannel"/> <ip:tcp-connection-factory id="clientFactory" type="client" host="localhost" port="1122" single-use="true" using-nio="false" serializer="${client.serializer}" deserializer="${client.serializer}" so-timeout="10000" /> <ip:tcp-outbound-gateway id="clientInGwAck" request-channel="telnetChannel" connection-factory="clientFactory" reply-channel="replyChannel" reply-timeout="10000"/> <!-- To send the messege over server via JMS and serviceActivator --> <int:channel id="requestMessageChannel" /> <beans:bean id="clientServiceActivator" class= "com.telnet.core.integration.clientServiceActivator"> </beans:bean> <int-jms:message-driven-channel-adapter id="requestMessageChannelAdapter" error-channel="errorChannel" connection-factory="mqConnectionFactory" destination-name="${client.messaging.processing.queues}" channel="requestMessageChannel"/> <int:service-activator id="messageActivator" input-channel="requestMessageChannel" output-channel="telnetChannel" ref="clientServiceActivator" method="getOutboundMessage"> </int:service-activator> Here the problem is if there are multiple message so it is showing connected and disconnected without any data stream. Looks like it is due to threading implemented by spring. Assistance required how to fix this issue.
doc_4246
mongoClient.connect(mongourl,function(err,database){ if (err){ throw err; } database = database.db('quac'); app.get('/', routes.index(database)); app.post('/add/:title', routes.add(database)); }); I would like to avoid this wrap and rather load the database reference in first place. What would be the best practice to accomplish this? A: I am not sure if you are set on passing the reference or just want to access mongoose in your controllers. For the later then there is no need to pass your db ref - just require mongoose and it will detect a current connection. So in your app.js: var mongoose = require('mongoose'); // Connect Mongo database mongoose.connect(config.db.mongo.connection, config.db.mongo.options); // Require your models require("../models/something"); require("../models/other"); Then in your controller: var mongoose = require('mongoose'), Something = mongoose.model('Something'), Other = mongoose.model('Other'); ... Other.findById(...) If for some reason you need the connection itself it is available as: mongoose.connections[0]
doc_4247
public class Account { public Account() { Id = Guid.NewGuid(); ContactCard = new ContactCard(); } //[ForeignKey("ContactCard")] public Guid Id { get; set; } public string Name { get; set; } public string Number { get; set; } public ContactCard ContactCard { get; set; } } public class ContactCard { public ContactCard() { Id = Guid.NewGuid(); } public Guid Id { get; set; } public Account Account { get; set; } } public class MightDbContext: DbContext { public DbSet<Account> Accounts { get; set; } public DbSet<ContactCard> ContactCards { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Account>().HasRequired(x => x.ContactCard).WithOptional(x => x.Account); } } public class MightDbInitializer : DropCreateDatabaseIfModelChanges<MightDbContext> { protected override void Seed(MightDbContext context) { var accounts = new List<Account> { new Account() { Name = "Acme Corporation Pty. Ltd.", Number = "001ABC" }, new Account() { Name = "Three Little Pigs Pty. Ltd.", Number = "002DEF" } }; accounts.ForEach(c => context.Accounts.Add(c)); } } And the following simple console program to iterate the contents of the Accounts and ContactCards collections: static void Main(string[] args) { Database.SetInitializer<MightDbContext>(new MightDbInitializer()); using (var context = new MightDbContext()) { foreach (Account c in context.Accounts) { Console.WriteLine(c.ContactCard.Id); } var contactCards = context.ContactCards.ToList(); /* ERROR OCCURS HERE */ foreach (ContactCard a in contactCards) { Console.WriteLine(a.Id); } } Console.Read(); } Why do I get the following error as soon as I try to access the ContactCards collection: Multiplicity constraint violated. The role 'Account_ContactCard_Source' of the relationship 'InvestAdmin.Might.DataAccess.Account_ContactCard' has multiplicity 1 or 0..1. When I look at the data that has actually been stored in the database tables all seems to be correct. In fact here is that data: Accounts: Id Name Number ab711bad-1b32-42ca-b68b-12f7be831bd8 Acme Corporation Pty. Ltd. 001ABC dc20a1dd-0ed4-461d-bc9c-04a85b555740 Three Little Pigs Pty. Ltd. 002DEF ContactCards: Id dc20a1dd-0ed4-461d-bc9c-04a85b555740 ab711bad-1b32-42ca-b68b-12f7be831bd8 And for completeness here is the Account_ContactCard foreign key constraint as defined in the database: -- Script Date: 06/12/2011 7:00 AM - Generated by ExportSqlCe version 3.5.1.7 ALTER TABLE [Accounts] ADD CONSTRAINT [Account_ContactCard] FOREIGN KEY ([Id]) REFERENCES [ContactCards]([Id]) ON DELETE NO ACTION ON UPDATE NO ACTION; I have been reading all I can on defining one to one relationships in Code First and have tried many different configurations. All end up back at the same problem. A: I found that I could resolve this problem by moving the creation of the associated ContactCard from the Account constructor into the actual creation of the Account objects in the Seed method of the DBInitializer. So it appears that it was not (directly) a problem with the One to One relationship.
doc_4248
Is there any documentation on how to connect Stetho to the V8 runtime I'm using ? A: If the question is still relevant - I have created j2v8-debugger library. It allows debugging J2V8 using Chrome DevTools. Basic features like setting/removing breakpoints, step into, step out and step over, variables inspection, etc. are implemented. It uses Stetho lib for communication with Chrome DevTools. Also it's uses DebugHandler for accessing V8 debug information. Hope it could be helpful.
doc_4249
Basically, I'm trying to make this code generic: if (filter.matchMode.ToUpper().Equals("EQ")) { query = query.Where(x => x.SomeField.Equals(filter.Value)); if (filter.matchMode.ToUpper().Equals("LT")) { query = query.Where(x => x.SomeField < filter.Value); } else [... 5 other match modes ...] } Now, SomeField is only one of about 5 fields that needs this functionality. And there's 5 matching operators. I could just copy/pasta the whole thing, and then deal with the debt of having to change tons of code every time a new operator or field enters the mix, but that really doesn't seem right. Basically, I need some way of defining SomeField at runtime, so I can factor out the whole if/else tree and use it for each supported field. I've tried going down this road, but I think I'm misunderstanding something fundamental about expressions: var entityType = typeof(TableObject); ParameterExpression arg = Expression.Parameter(entityType, "x"); MemberExpression amproperty = Expression.Property(arg, "SomeField"); MemberExpression property = Expression.Property(amproperty, "Equals"); // ??? // what's next, if this is even the right direction... EDIT: a shorter version of the question might be: how can I construct the following object foo using MemberExpressions and lambdas, such that SomeField can be passed in as a string "SomeField": Expression<Func<TableObject, bool>> foo = x => x.SomeField.Equals("FOO"); UPDATE: here's what I ended up coming up with: private IQueryable<TableObject> processFilter( IQueryable<TableObject> query, FilterItem filter, string fieldName) { var entityType = typeof(TableObject); // construct the argument and access object var propertyInfo = entityType.GetProperty(fieldName); ParameterExpression arg = Expression.Parameter(entityType, "x"); MemberExpression access = Expression.MakeMemberAccess(arg, typeof(TableObject).GetProperty(fieldName) ); // translate the operation into the appropriate Expression method Expression oprFunc; if (filter.MatchMode.ToUpper().Equals("EQ")) { oprfunc = Expression.Equal(access, Expression.Constant(filter.Value)); } else if (filter.MatchMode.ToUpper().Equals("LT")) { oprfunc = Expression.LessThan(access, Expression.Constant(filter.IntValue)); } else { throw new ArgumentException( $"invalid argument: ${filter.MatchMode}" ); } // construct the lambda var func = Expression.Lambda<Func<TableObject, bool>>(oprFunc, arg); // return the new query return query.Where(func); } So far, this seems to cover most of the cases. It starts to go off the rails with nullable fields and date comparisons, but it will work for what I need it to do. The part I'm still not completely sure about is Expression.MakeMemberAccess. I've seen this written many ways and I'm not sure if that's the correct way to create that expression. A: Let's say you have class like this: class SomeClass { public string a1 { get; set; } public string b1 { get; set; } public string c1 { get; set; } } also let's assume you have method like this: public List<T> GetAll(Expression<Func<T, bool>> criteria ) { return someDataLINQCapable.Where(criteria); } Method could be called like this: GetAll<SomeClass>(m => m.a1 != null && m.b1=="SomethingUseful")
doc_4250
Currently, this template is a basic application with many component like: * *SpinnerModule (Spinnercomponent, SpinnerService) *Menu (MenuComponent, MenuService) *CustomHTTP (CustomHTTP extending HTTP) *Etc... To avoid the possibility of any edition on our global component, I would like to put every module on a NPM module (named @companyName/spinner, @companyName/menu). Is it the right approach? Second question, I was thinking about creating a @companyName/shared module importing every others modules to ease the call. Is it a right thing to do, or not?
doc_4251
def main(): setLogLevel('info') net = Mininet(switch=LinuxBridge, controller=None) h1 = net.addHost('h1', ip=None) h2 = net.addHost('h2', ip=None) s0 = net.addSwitch('s0') s1 = net.addSwitch('s1') s2 = net.addSwitch('s2') r1 = net.addHost('r1', ip=None) r1.cmd('sysctl -w net.ipv6.conf.all.forwarding=1') r2 = net.addHost('r2', ip=None) r2.cmd('sysctl -w net.ipv6.conf.all.forwarding=1') net.addLink(h1, s1) net.addLink(r1, s1) net.addLink(r1, s0) net.addLink(r2, s0) net.addLink(r2, s2) net.addLink(h2, s2) h1.cmd("ip -6 addr add 2001:638:709:a::1/64 dev h1-eth0") h2.cmd("ip -6 addr add 2001:638:709:b::1/64 dev h2-eth0") r1.cmd("ip -6 addr add 2001:638:709:a::f/64 dev r1-eth0") r1.cmd("ip -6 addr add 2001:638:709:f::1/64 dev r1-eth1") r2.cmd("ip -6 addr add 2001:638:709:f::2/64 dev r2-eth0") r2.cmd("ip -6 addr add 2001:638:709:b::f/64 dev r2-eth1") h1.cmd("ip -6 route add 2001:638:709::/48 via 2001:638:709:a::f dev h1-eth0") r1.cmd("ip -6 route add 2001:638:709:b::/64 via 2001:638:709:f::2 dev r1-eth1") r2.cmd("ip -6 route add 2001:638:709:a::/64 via 2001:638:709:f::1 dev r2-eth0") h2.cmd("ip -6 route add 2001:638:709::/48 via 2001:638:709:b::f dev h2-eth0") net.start() CLI(net) net.stop() After running it, when I do h1 ping6 2001:638:709:b::1 I get an error that Address family not supported by protocol if i try h1 ping6 2001:638:709:b::f/64, I get unknown host. What is the correct method to verify the networks?
doc_4252
For example I have 2 products added at 3:00AM and then I will have 5 products added at 4:00AM. I'm counting the products by it's createdAt field. I have a sample data like this: Products: { "_id": { "$oid": "603c62272aacbc0017e2e4b5" }, "amount": 110, "user": { "$oid": "5f7408cf7889580017c369a1" }, "transaction_id": "cZ3fgffFI", "createdAt": { "$date": "2021-03-01T03:40:23.300Z" }, "updatedAt": { "$date": "2021-03-01T04:13:25.908Z" }, "__v": 0, }, { "_id": { "$oid": "603c62272aacbc0017e2e4b5" }, "amount": 110, "user": { "$oid": "5f7408cf7889580017c369a1" }, "transaction_id": "cZ3fgffFI", "createdAt": { "$date": "2021-03-01T03:40:23.300Z" }, "updatedAt": { "$date": "2021-03-01T04:13:25.908Z" }, "__v": 0, }, { "_id": { "$oid": "603c62272aacbc0017e2e4b5" }, "amount": 110, "user": { "$oid": "5f7408cf7889580017c369a1" }, "transaction_id": "cZ3fgffFI", "createdAt": { "$date": "2021-03-01T03:40:23.300Z" }, "updatedAt": { "$date": "2021-03-01T04:13:25.908Z" }, "__v": 0, } Output: I'm counting the products using the createdAt field. 3:00 AM 2 products 4:00 AM 5 products A: You can simply use group by hours to get count per hours data like below, [{ '$match':{ '$and':[ {'createdAt':{'$gte':'2021-03-08T00:00:00.000Z'}},{'createdAt':{'$lte':'2021-03-08T05:00:00.000Z'}}] } }, { '$project': { 'hours': { '$hours': 'createdAt' } } }, { '$group': { '_id': { 'hours': '$hours', }, 'total': { '$sum': 1 }, 'hours': { '$hours': '$hours' } } } ] also, you can add any other condition using match for other filters that you need.
doc_4253
However, sometimes those events seems to be called multiple times, causing RuntimeErrors (when trying to disconnect an event that is already gone). Here is a snippet of code that shows a similar (and hopefully related) problem using default PushButtons. To see the runtime error here, run the code, push one of the buttons, then close the window. That's when I see this: RuntimeError: Fail to disconnect signal clicked(). Here is the code. Does anybody know if this is a PySide bug? from PySide.QtGui import * from PySide.QtCore import * import sys class TestWindow( QWidget ): def __init__( self, parent=None ): super( TestWindow, self ).__init__( parent ) self.setLayout( QGridLayout() ) def addWidget( self, w ): self.layout().addWidget( w ) def testCB( self ): print 'button connected' def eventFilter( self, obj, event ): '''Connect signals on mouse over''' if event.type() == QEvent.Enter: print 'enter', obj.clicked.connect( self.testCB ) elif event.type() == QEvent.Leave: print 'leave' obj.clicked.disconnect( self.testCB ) return False app = QApplication( sys.argv ) w = TestWindow() for i in xrange(10): btn = QPushButton( 'test %s' % i ) w.addWidget( btn ) btn.installEventFilter(w) w.show() sys.exit( app.exec_() ) A: In few cases, when I tested mouse events, showed better performance while events are attached to item class... so don't subclass. Rather : class Button(QPushButton): def __init__(self, label): super(Button, self).__init__() self.setText(label) app = QApplication( sys.argv ) w = TestWindow() for i in xrange(10): btn = Button( 'test %s' % i ) w.addWidget( btn ) ...then define mouse event for class.
doc_4254
Done so far: * *Loaded markers from the server in map view *Generate random clusters only. When I run the project it looks like this. Screen shot of map view It shows both markers and clusters both in the map view at zoom level 10. But I wanted to show clusters first then when I zoomed in it should show the real markers. Not the randomly generated markers that I created because I don't know a way to show the clusters in the map. Here is the full code with fake URL link: #import "ViewController.h" //#import "CSMarker.h" #import <GoogleMaps/GoogleMaps.h> #import <Google-Maps-iOS-Utils/GMUMarkerClustering.h> //importing POI Item object - points of interest @interface POIItem : NSObject<GMUClusterItem> @property(nonatomic, readonly) CLLocationCoordinate2D position; @property(nonatomic, readonly) NSString *name; - (instancetype)initWithPosition:(CLLocationCoordinate2D)position name:(NSString *)name; @end @implementation POIItem - (instancetype)initWithPosition:(CLLocationCoordinate2D)position name:(NSString *)name { if ((self = [super init])) { _position = position; _name = [name copy]; } return self; } @end //implementation start - map view controller static const NSUInteger kClusterItemCount = 60; static const double kCameraLatitude = 25.277683999999997; static const double kCameraLongitude = 55.309802999999995; @interface ViewController ()<GMUClusterManagerDelegate, GMSMapViewDelegate> { NSMutableArray *waypoints_; NSMutableArray *waypointStrings_; GMSMapView *_mapView; GMUClusterManager *_clusterManager; } @property(strong, nonatomic) NSURLSession *markerSession; @property(strong, nonatomic) GMSMapView *mapView; @property(copy, nonatomic) NSSet *markers; @property(nonatomic, strong) NSMutableArray *markersArray; @end @implementation ViewController @synthesize gs; - (void)viewDidLoad { [super viewDidLoad]; GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:kCameraLatitude longitude:kCameraLongitude zoom:10]; self.mapView = [GMSMapView mapWithFrame:self.view.bounds camera:camera]; [self.view addSubview:self.mapView]; self.mapView.settings.compassButton = YES; self.mapView.settings.myLocationButton = YES; //setup the cluster manager NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; config.URLCache = [[NSURLCache alloc] initWithMemoryCapacity:2 * 1024 * 1024 diskCapacity:10 * 1024 * 1024 diskPath:@"MarkerData"]; self.markerSession = [NSURLSession sessionWithConfiguration:config]; [self downloadMarkerData]; //cluster load setup id<GMUClusterAlgorithm> algorithm = [[GMUNonHierarchicalDistanceBasedAlgorithm alloc] init]; id<GMUClusterIconGenerator> iconGenerator = [[GMUDefaultClusterIconGenerator alloc] init]; id<GMUClusterRenderer> renderer = [[GMUDefaultClusterRenderer alloc] initWithMapView:self.mapView clusterIconGenerator:iconGenerator]; _clusterManager = [[GMUClusterManager alloc] initWithMap:self.mapView algorithm:algorithm renderer:renderer]; // Generate and add random items to the cluster manager. [self generateClusterItems]; // Call cluster() after items have been added to perform the clustering and rendering on map. [_clusterManager cluster]; // Register self to listen to both GMUClusterManagerDelegate and GMSMapViewDelegate events. [_clusterManager setDelegate:self mapDelegate:self]; // Do any additional setup after loading the view, typically from a nib. } - (NSMutableArray *)markersArray { if (!_markersArray) { _markersArray = [NSMutableArray array]; } return _markersArray; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } //downloading marker data - (void)downloadMarkerData { NSURL *lakesURL = [NSURL URLWithString:@"http://myscrap.com/xxx.php/webservice/xxx/xxxx"]; NSURLSessionDataTask *task = [self.markerSession dataTaskWithURL:lakesURL completionHandler:^(NSData *data, NSURLResponse *response, NSError *e) { NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSLog(@"json: %@",json); [[NSOperationQueue mainQueue] addOperationWithBlock:^{ [self createMarkerObjectsWithJson:json]; }]; }]; [task resume]; } -(void)drawMarkers { for(GMSMarker *marker in self.markers) { if(marker.map == nil) { marker.map = self.mapView; } } } -(void)createMarkerObjectsWithJson:(NSArray *)json { NSMutableSet *mutableSet = [[NSMutableSet alloc] initWithSet:self.markers]; for (NSDictionary *markerData in json) { GMSMarker *newMarker = [[GMSMarker alloc] init]; // newMarker.appearAnimation = [markerData[@"id"] integerValue]; newMarker.position = CLLocationCoordinate2DMake([markerData[@"latitud"] doubleValue], [markerData[@"longitude"] doubleValue]); newMarker.title = markerData[@"name"]; newMarker.snippet = markerData[@"adress"]; // [mutableSet addObject:newMarker]; newMarker.map=self.mapView; } self.markers =[mutableSet copy]; [self drawMarkers]; } #pragma mark GMUClusterManagerDelegate - (void)clusterManager:(GMUClusterManager *)clusterManager didTapCluster:(id<GMUCluster>)cluster { GMSCameraPosition *newCamera = [GMSCameraPosition cameraWithTarget:cluster.position zoom:_mapView.camera.zoom + 1]; GMSCameraUpdate *update = [GMSCameraUpdate setCamera:newCamera]; [_mapView moveCamera:update]; } #pragma mark GMSMapViewDelegate - (BOOL)mapView:(GMSMapView *)mapView didTapMarker:(GMSMarker *)marker { POIItem *poiItem = marker.userData; if (poiItem != nil) { NSLog(@"Did tap marker for cluster item %@", poiItem.name); } else { NSLog(@"Did tap a normal marker"); } return NO; } #pragma mark Private // Randomly generates cluster items within some extent of the camera and adds them to the // cluster manager. - (void)generateClusterItems { const double extent = 0.2; for (int index = 1; index <= kClusterItemCount; ++index) { double lat = kCameraLatitude + extent * [self randomScale]; double lng = kCameraLongitude + extent * [self randomScale]; NSString *name = [NSString stringWithFormat:@"Item %d", index]; id<GMUClusterItem> item = [[POIItem alloc] initWithPosition:CLLocationCoordinate2DMake(lat, lng) name:name]; [_clusterManager addItem:item]; } } // Returns a random value between -1.0 and 1.0. - (double)randomScale { return (double)arc4random() / UINT32_MAX * 2.0 - 1.0; } A: try changing in view did load GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:kCameraLatitude longitude:kCameraLongitude zoom:4]; the zoom to a 5 or 4. It then should show the clusters and not the markers. When you zoom in, it will show the "real" markers.
doc_4255
I would like the user to be able to select(highlight) the entire row in the grid and then be able to click on a button to process the data in that row. How could I do this? I have not been able to find any information related to my problem. Any ideas would be greatly appreciated. Here is the XAML: <Grid x:Name="lstAssigned" ShowGridLines="True"> <Grid.ColumnDefinitions> <ColumnDefinition Width="auto"></ColumnDefinition> <ColumnDefinition Width="auto"></ColumnDefinition> <ColumnDefinition Width="auto"></ColumnDefinition> <ColumnDefinition Width="auto"></ColumnDefinition> <ColumnDefinition Width="auto"></ColumnDefinition> <ColumnDefinition Width="auto"></ColumnDefinition> <ColumnDefinition Width="auto"></ColumnDefinition> <ColumnDefinition Width="auto"></ColumnDefinition> </Grid.ColumnDefinitions> </Grid> Thanks Everyone! Here are some more details: The data to be displayed will vary. The grid will have 5 columns. Columns 2 and 3 will be combo boxes. The other columns are textBoxes. The user will enter data and save it. Another time, the data to be displayed could be: combo boxes in columns 2 and 4, and a date in column 5. Since my data source will vary, I was trying to set the control type in each column programmatically. I initially started with a DataGrid using DataTemplates, but this would define the columns and order. Am I mistaken? I want to define them at run-time. What would be the best way to handle this? What type of control should I use? I would apprectiate any kind of adice you can offer. Thanks in advance. A: Grid doesn't support selection of rows/columns/cells. It's used to layout controls for display. Use a something else, like a ListView instead. A: This sounds like you should use 2 separate DataGrids for each case. There are ways to alter the columns programatically in runtime, but it's more messy and leads to less maintainability. If I were given this task, I would simply use 2 Different DataGrids, one for case #1, where you need Text Combo Combo Text Text and the other for case #2: Text Combo Text Combo DateTime Sounds like a really simple set, where there are no major headaches, then you could just create a proper DataTemplate containing each of this DataGrids for each type of Model object.
doc_4256
c := make(chan string) work := make(chan string, 1000) clvl := runtime.NumCPU() for i := 0; i < clvl; i++ { go func(i int) { f, err := os.Create(fmt.Sprintf("/tmp/sample_match_%d.csv", i)) if nil != err { panic(err) } defer f.Close() w := bufio.NewWriter(f) for jdId := range work { for _, itemId := range itemIdList { w.WriteString("test") } w.Flush() c <- fmt.Sprintf("done %s", jdId) } }(i) } go func() { for _, jdId := range jdIdList { work <- jdId } close(work) }() for resp := range c { fmt.Println(resp) } This is ok, but can I all go routine just write to one files? just like this: c := make(chan string) work := make(chan string, 1000) clvl := runtime.NumCPU() f, err := os.Create("/tmp/sample_match_%d.csv") if nil != err { panic(err) } defer f.Close() w := bufio.NewWriter(f) for i := 0; i < clvl; i++ { go func(i int) { for jdId := range work { for _, itemId := range itemIdList { w.WriteString("test") } w.Flush() c <- fmt.Sprintf("done %s", jdId) } }(i) } This can not work, error : panic: runtime error: slice bounds out of range A: * *The bufio.Writer type does not support concurrent access. Protect it with a mutex. *Because the short strings are flushed on every write, there's no point in using a bufio.Writer. Write to the file directly (and protect it with a mutex). *There's no code to ensure that the goroutines complete before the file is closed or the program exits. Use a sync.WaitGroup.
doc_4257
"Structured data with syntax errors detected Invalid items are not eligible for Google Search's rich results." Unparsable structured data here is the code structured-data.liquid for How to resolve it and I also want to add FAQs schema to Shopify how to add FAQs schema to Shopify. {%- if template contains 'index' -%} <script type="application/ld+json"> { "@context": "https://schema.org", "@type": "WebSite", "name": {{ shop.name | json }}, "url": "https://{{ shop.domain }}", "potentialAction": { "@type": "SearchAction", "target": "https://{{ shop.domain }}{{ routes.search_url }}?q={query}", "query-input": "required name=query" } }</script> {% endif %} {%- if template contains 'product' -%} {%- if product.available == true -%} {%- if product.selected_or_first_available_variant.inventory_policy == "continue" -%} {%- assign availability = "PreOrder" -%} {%- else -%} {%- assign availability = "InStock" -%} {%- endif -%} {%- else -%} {%- assign availability = "OutOfStock" -%} {%- endif -%} <script type="application/ld+json"> { "@context": "https://schema.org", "@id": {{ canonical_url | json }}, "@type": "Product", "brand": { "@type": "Brand", "name": {{ product.vendor | json }} }, "sku": {{ product.selected_or_first_available_variant.sku | json }}, "description": {{ product.description | strip_html | json }}, "url": {{ canonical_url | json }}, "name": {{ product.title | json }}, {%- if product.featured_image -%} "image": "https:{{ product.featured_image | product_img_url: 'grande' }}", {%- endif -%} "offers": { "@type": "Offer", "priceCurrency": "{{ shop.currency }}", "price": "{{ product.selected_or_first_available_variant.price | money_without_currency | remove: "," }}", "availability": "http://schema.org/{{ availability }}", "url": {{ canonical_url | json }}, "sku": {{ product.selected_or_first_available_variant.sku | json }}, "seller": { "@type": "Organization", "name": {{ shop.name | json }} } {%- if product.selected_or_first_available_variant.barcode.size == 12 -%}, ,"gtin12": "{{ product.selected_or_first_available_variant.barcode }}" {% endif %} {%- if product.selected_or_first_available_variant.barcode.size == 13 -%}, ,"gtin13": "{{ product.selected_or_first_available_variant.barcode }}" {%- endif -%} {%- if product.selected_or_first_available_variant.barcode.size == 14 -%}, ,"gtin14": "{{ product.selected_or_first_available_variant.barcode }}" {%- endif -%} } }</script> {%- endif -%} {%- if template contains 'article' -%} <script type="application/ld+json"> { "@context": "http://schema.org", "@type": "Article", "mainEntityOfPage": {{ canonical_url | json }}, "name": {{ article.title | json }}, "headline": "{{- article.title -}}", "image": [ "{{ article | img_url: 'master' }}" ], datePublished: "{{- article.published_at | time_tag -}}", "dateModified": "{{- article.published_at | time_tag -}}", "author": { "@type": "Person", "name": "{{- article.author -}}" }, "publisher": { "@type": "Organization", "name": "{{- shop.name -}}", "logo": { "@type": "ImageObject", "url": "{{- 'logo.jpg' | file_url: 'master' -}}" } }, "description": {{- article.excerpt_or_content | strip_html | json -}}, "articleBody": {{- article.content | strip_html | json -}} } </script> {%- endif -%} }
doc_4258
I have a code (google maps v3) that has an ajax request. The request is part of the code and is used to push markers on google maps canvas. My question is how to have a basic json data, like this {"id":"1","0":"1",lat":"40.626953","9":"40.626953","lng":"-73.900055","10":"-73.900055"} inside the jsfiddle? I cut the file down to what I really need, lat and lng. All other fields are not important for this purpose. I saw this and this, but still can't figure it out. I don't want to have the file in the "result" of the css+html+js. I just need to use it to plot my map, which will be second fiddle. Any help will be greatly appreciated. A: The data passed via the json-parameter must be encoded, e.g. data: {"json":JSON.stringify({"lat":"40.626953","lng":"-73.900055"})} Demo: http://jsfiddle.net/doktormolle/tJNuV/ Note: for browsers without JSON-support you must include json2.js
doc_4259
Like this: " List<data> list; list = (List<data>)_changedItems.Values; //get values before clearing _changedItems.Clear(); " And adding is done by other threads with function _changedItems.AddOrUpdate Now there is possibility to lose new data between getting data out from the dictionary and clearing content, if some thread adds data-objects to collection before row of clearing. Or is the only way to do adding and clearing inside lock. lock(object) { List<data> list; list = (List<data>)_changedItems.Values; _changedItems.Clear(); } And lock(object) _changedItems.AddOrUpdate There is need for a Clear-function that returns safely all the cleared items from dictionary.. -Larry A: Indeed, calling two thread-safe methods in a sequence does not guarantee the atomicity of the sequence itself. You are right that a lock over both calls to get values and clear is necessary. A: You can use TryRemove(key, out value) method. It returns the removed element. This way you do not have to lock the dictionary for moving the buffered data. List<data> list; var keys = dict.Keys; foreach(var key in keys) { data value; dict.TryRemove(key, out value); list.Add(value); } Update: actually you can iterate directly over ConcurrentDictionary even while it is changing. This way you do not have to build the collection of the keys from the property .Keys, which may be (?) slow, depending on implementation. List<data> list; foreach(var kvp in dict) { data value; dict.TryRemove(kvp.Key, out value); list.Add(value); }
doc_4260
The aim of this script is to retrieve the order details (item, quantity, price) as well as the user’s first name and surname (where ‘Order for:’ is). The script below does everything ok in that it retrieves the order (and orders if there are more than one) and it’s/their item, quantity and price. However, it doesn’t display the user’s name and surname. I know the problem is that where I am trying to display the name is outside the while loop but Im a little stuck in where it should sit. Any suggestions? Code is below: <?php $page_title = 'View Individual Order'; include ('includes/header.html'); // Check for a valid user ID, through GET or POST. if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) ) { // Accessed through view_users.php $id = $_GET['id']; } elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) ) { // Form has been submitted. $id = $_POST['id']; } else { // No valid ID, kill the script. echo '<h1 id="mainhead">Page Error</h1> <p class="error">This page has been accessed in error.</p><p><br /><br /></p>'; include ('./includes/header.html'); exit(); } ?> <h1>Order Details</h1> <?php require_once ('database.php'); // Connect to the db. // Retrieve the user's, order and product information. $query = "SELECT us.users_id, us.users_sales_id, us.users_first_name, us.users_surname, us.users_dealer_name, ord.order_id, ord.users_id, ord.total, ord.order_date, oc.oc_id, oc.order_id, oc.products_id, oc.quantity, oc.price, prd.products_id, prd.products_name, prd.price FROM users AS us, orders AS ord, order_contents AS oc, products AS prd WHERE ord.order_id=$id AND us.users_id = ord.users_id AND ord.order_id = oc.order_id AND oc.products_id = prd.products_id "; $result = mysql_query ($query) or die(mysql_error()); if (mysql_num_rows($result)) { // Valid user ID, show the form. echo '<p>Order for:<strong>' . $row[2] . ' ' . $row[3] . ' </strong> </p> <table border="0" style="font-size:11px;" cellspacing="1" cellpadding="5"> <tr class="top"> <td align="left"><b>Product</b></td> <td align="center"><b>Price</b></td> <td align="center"><b>Qty</b></td> </tr>'; $bg = '#dddddd'; // Set the background color. while($row = mysql_fetch_array($result, MYSQL_NUM)) { // WHILE loop start $bg = ($bg=='#eaeced' ? '#dddddd' : '#eaeced'); echo '<tr bgcolor="' . $bg . '">'; echo '<td align="left">' . $row[15] . '</td> <td align="center">' . $row[13] . ' pts</td> <td align="center">' . $row[12] . '</td> </tr>'; echo ''; }// end of WHILE loop echo '</table> <p> Here:</p> <br><br> <p><a href="view-all-orders.php"> << Back to Orders</a></p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> '; } else { // Not a valid user ID. echo '<h1 id="mainhead">Page Error</h1> <p class="error">This page has been accessed in error.</p><p><br /><br /></p>'; } mysql_close(); // Close the database connection. ?> <p>Footer here</p> <?php include ('./includes/footer_admin_user.html'); // Include the HTML footer. ?> A: It looks like the problem is when you're trying to display the user's name: echo '<p>Order for:<strong>'.$row[2].' '.$row[3] The $row variable doesn't exist yet. Not seeing your database or the result from your database query, my guess is that the user's name is repeated next to every single item in their order, so it might be as simple as just starting the WHILE loop, and checking to see if you've printed their name yet: $lastUser = NULL; while($row = mysql_fetch_array($result, MYSQL_NUM)) { if ($row[0] !== $lastUser) { if (isset($lastUser)) { // finish up the report for the previous user } // echo the stuff for the current user's name $lastUser = $row[0]; } // go on echo-ing their order information } // after the while loop is over, // close up the last user's report But like I said, this is just a guess, and might be totally off. A: One way you could do it is grab the row first, and then use a do/while loop instead of just a basic while loop. Like this: if (mysql_num_rows($result)) { // Valid user ID, show the form. /*********** I added this line ***********/ $row = mysql_fetch_array($result, MYSQL_NUM); echo '<p>Order for:<strong>' . $row[2] . ' ' . $row[3] . ' </strong> </p> <table border="0" style="font-size:11px;" cellspacing="1" cellpadding="5"> <tr class="top"> <td align="left"><b>Product</b></td> <td align="center"><b>Price</b></td> <td align="center"><b>Qty</b></td> </tr>'; $bg = '#dddddd'; // Set the background color. /*********** I changed this from a while loop to a do-while loop ***********/ do { // WHILE loop start $bg = ($bg=='#eaeced' ? '#dddddd' : '#eaeced'); echo '<tr bgcolor="' . $bg . '">'; echo '<td align="left">' . $row[15] . '</td> <td align="center">' . $row[13] . ' pts</td> <td align="center">' . $row[12] . '</td> </tr>'; echo ''; } while($row = mysql_fetch_array($result, MYSQL_NUM)); // end of WHILE loop A: The problem is that you tried to access $row[2] and $row[3] before mysql_fetch_array(). Since you are already echo'ing HTML tags, why don't you "buffer" your output first like this?: while($row = mysql_fetch_array($result, MYSQL_NUM)) { $bg = ($bg=='#eaeced' ? '#dddddd' : '#eaeced'); $order = '<tr bgcolor="' . $bg . '"> <td align="left">' . $row[15] . '</td> <td align="center">' . $row[13] . ' pts</td> <td align="center">' . $row[12] . '</td> </tr>'; $orders[$row[2] . " " . $row[3]][] .= $order; } Then do a second foreach loop for the $orders foreach($orders as $name => $orderList) { echo "Order for: $name"; echo "<table ...>"; foreach($orderList as $order) { echo $order; } echo "</table>"; }
doc_4261
This line is fine: ActiveRecord::Base.connection.tables and returns all tables but ActiveRecord::Base.connection.table_structure("users") generate error: ActiveRecord::Base.connection.table_structure("projects") I think that table_structure is not Postgres method. How can I list all data from the table in Rails console for Postgres database? A: You can get this information from postgres directly from the command line psql your_development_database -c "\d" -- lists all database tables psql your_development_database -c "\d users" -- lists all columns for a table; 'users' in this case If you want to look at Model attributes in the rails console User.new User.new.inspect # or install the awesome_print gem for better output ap User.new
doc_4262
The initial time is saved onto SharedPreferences: 01:11:59 AM Then I get the current time: simpleDateFormat.format(new Date()); which yields the output as: 05:19:03 AM The time difference of the 2 should be around 4 hours but the chronometer displays this: -691.33.46 Code: Date date1 = simpleDateFormat.parse(initialTimeOnSharedPrefs); Date date2 = simpleDateFormat.parse(currentTime); long millis = date2.getTime() - date1.getTime(); chronometer.setBase(SystemClock.elapsedRealtime() - millis); chronometer.start(); How can I avoid the negative value & get the correct time set to the chronometer? A: To avoid such surprises, I recommend you do it with the modern date-time API. import java.time.Duration; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.Locale; public class Main { public static void main(String[] args) { String initialTimeOnSharedPrefs = "01:11:59 AM"; LocalTime startTime = LocalTime.parse(initialTimeOnSharedPrefs, DateTimeFormatter.ofPattern("h:m:s a", Locale.ENGLISH)); LocalTime now = LocalTime.now(); Duration duration = Duration.between(startTime, now); // The model is of a directed duration, meaning that the duration may be // negative. If you want to show the absolute difference, negate it if (duration.isNegative()) { duration = duration.negated(); } // Display duration in its default format i.e. the value of duration#toString System.out.println(duration); // #################### Since Java-8 #################### String formattedDuration = String.format("%d:%d:%d", duration.toHours(), duration.toMinutes() % 60, duration.toSeconds() % 60); System.out.println("Duration is " + formattedDuration); // ###################################################### // #################### Since Java-9 #################### formattedDuration = String.format("%d:%d:%d", duration.toHoursPart(), duration.toMinutesPart(), duration.toSecondsPart()); System.out.println("Duration is " + formattedDuration); // ###################################################### } } Output: PT13H47M39.003708S Duration is 13:47:39 Duration is 13:47:39 Check Duration#toString and ISO_8601#Durations to learn more about ISO_8601 format of Duration. Correct way of doing it using the legacy API: import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; public class Main { public static void main(String[] args) throws ParseException { String initialTimeOnSharedPrefs = "01:11:59 AM"; SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH); String strTimeNow = sdf.format(Calendar.getInstance().getTime()); System.out.println(strTimeNow); Date startTime = sdf.parse(initialTimeOnSharedPrefs); Date endTime = sdf.parse(strTimeNow); long duration = Math.abs(endTime.getTime() - startTime.getTime()); long seconds = duration / 1000 % 60; long minutes = duration / (60 * 1000) % 60; long hours = duration / (60 * 60 * 1000) % 24; String formattedDuration = String.format("%d:%d:%d", hours, minutes, seconds); System.out.println("Duration is " + formattedDuration); } } Output: 02:53:39 PM Duration is 13:41:40 Some important notes: * *The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API. For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project. *Learn about the modern date-time API from Trail: Date Time.
doc_4263
When I move my finger to get the next image its work for second and return to previous activity The code look like this: @Override public View instantiateItem(ViewGroup container, int position) { PhotoView photoView = new PhotoView(container.getContext()); photoView.setBackgroundResource(R.drawable.aaa); photoView.setImageResource(myImages[position]); photoView.setOnViewTapListener(new OnViewTapListener() { @Override public void onViewTap(View view, float x, float y) { float x1 = x; float y1 = y; } }); container.addView(photoView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); return photoView; } I traced the process and I found different events in method "setImageResource" In the first time the method go on clearly, but when movement event happened its called the "super" and previous activity appears again @Override public void setImageResource(int resId) { super.setImageResource(resId); if (null != mAttacher) { mAttacher.update(); } } Can any one explain whats happened !!! Thank you.
doc_4264
let main = document.getElementById('main'); let fullscreen = window.innerHeight; let headerHeight = document.getElementById('navHeader').offsetHeight; let newsletterHeight = document.getElementById('newsletter').offsetHeight; let footerHeight = document.getElementById('footer').offsetHeight; let addHeight = headerHeight + newsletterHeight + footerHeight; let computedHeight = fullscreen - addHeight + 7; window.addEventListener('load', function() { document.getElementById('main').style.cssText = `min-height:${computedHeight}px;`; }); window.addEventListener('resize', function() { document.getElementById('main').style.cssText = `min-height:${computedHeight}px;`; }); In my code, I am grabbing the window innerHeight, the header height, a newsletter element height that is flushed under the header, and the footer height. Adding it all together. Then computer the remainder as my main body real estate. This is the element that resizes depending on the size and calculations. Here is the HTML of a blank page is you need it, (ignore the PHP inclusions) <html> <head> <title>Fitness & Lifestyle | Contact</title> <?php include ('./partials/header.php') ?> </head> <body> <?php include ('./partials/nav.php') ?> <section class="mt-7" id="newsletter"> <?php include ('./partials/newsletter.php') ?> </section> <section id="main"></section> <?php include ('./partials/footer.php') ?> </body> </html> Thanks in advance A: That's because you calculate the computedHeight only once in the page load. Every time you the resize handler is firing, computedHeight is the same value. You need to re-calculate it in every resize. Something like this: function resizeMain() { let main = document.getElementById('main'); let fullscreen = window.innerHeight; let headerHeight = document.getElementById('navHeader').offsetHeight; let newsletterHeight = document.getElementById('newsletter').offsetHeight; let footerHeight = document.getElementById('footer').offsetHeight; let addHeight = headerHeight + newsletterHeight + footerHeight; let computedHeight = fullscreen - addHeight + 7; document.getElementById('main').style.cssText = `min-height:${computedHeight}px;`; } calculateHeight(); window.addEventListener('load', resizeMain); Although, I'm not sure it's a wise approach because for each resize you'll do some heavy calculation. You may want to use some kind of debounce function.
doc_4265
I created the constructor and a separate class called MenuItem public class Menu implements Cloneable { final int MAX_ITEMS = 50; public Menu(){ MenuItem[] menu = new MenuItem[MAX_ITEMS]; } } I want to create a method that clones a Menu. How do I access the properties of each individual MenuItem within Menu? A: I don't think you have to go through all that, assuming A is the menu... public static Menu clone(){ Menu B = this; return B; } Then simply call it using Menu B = A.clone(); A: You're creating MenuItem[] menu as a local variable and never storing it after the constructor. So not only can you not clone it, you can't ever access it again. Try using a field for the menu variable, like this: public class Menu implements Cloneable { final int MAX_ITEMS = 50; private MenuItem[] menu; public Menu(){ menu = new MenuItem[MAX_ITEMS]; } } Now any method within the Menu class can access the menu you set during construction. As for cloning, it depends how deeply you want to clone. If you just want a new Menu object that refers to the same menu array in memory, see cloneOne. If you want a new Menu object with a new menu array containing the same objects as the old menu array, see cloneTwo. If you want to go further than that, you'll have to put up some details for the MenuItem class: public class Menu implements Cloneable { final int MAX_ITEMS = 50; private MenuItem[] menu; public Menu(){ menu = new MenuItem[MAX_ITEMS]; } public Menu cloneOne(){ Menu a = new Menu(); a.menu = menu; return a; } public Menu cloneTwo(){ Menu a = new Menu(); a.menu = new MenuItem[menu.length]; for(int i = 0; i < menu.length; i++) a.menu[i] = menu[i]; return a; }
doc_4266
(No, I'm not going to look at this question which basically duplicates my situation. I already did, and it didn't help me at all.) This is my current code: # tkinter from tkinter import * # class class App(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack() box = Text(width=90, height=50) self.pack() # create the window window = App() # attributes window.master.title("Text box") window.master.minsize(800, 600) window.master.maxsize(800, 600) # start program window.mainloop() Thanks. A: You have to pack the box as well: class App(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack() box = Text(width=90, height=50) box.pack() #instead of self.pack()
doc_4267
I want to implement a functionality to pause the game when the pauseButton is pressed. But I'm not sure where and how. How is a pause and restart or returning one scene back handled in cocos2dx? I would love to hear from you! Part of my code. How to add a pause in the pauseButton ? Scene* GameLayer::createScene(int level) { auto scene = Scene::create(); auto layer = GameLayer::create(level); scene->addChild(layer); return scene; } GameLayer* GameLayer::create(int level) { GameLayer *pRet = new GameLayer(); pRet->init(level); pRet->autorelease(); return pRet; } bool GameLayer::init(int level) { if (!Layer::init()) return false; auto touchListener = EventListenerTouchOneByOne::create(); touchListener->setSwallowTouches(_swallowsTouches); touchListener->onTouchBegan = CC_CALLBACK_2(GameLayer::onTouchBegan, this); touchListener->onTouchMoved = CC_CALLBACK_2(GameLayer::onTouchMoved, this); touchListener->onTouchEnded = CC_CALLBACK_2(GameLayer::onTouchEnded, this); touchListener->onTouchCancelled = CC_CALLBACK_2(GameLayer::onTouchCancelled, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); auto pauseButton = MenuItemImage::create("pause1.png","pause2.png",[](Ref*sender){ //Do pause and show the pause menu }); auto menu = Menu::create(pauseButton, NULL); menu->setPosition(WINSIZE.width / 2.0, WINSIZE.height - 50); addChild(menu, ZOrder::Level); initBackground(); initBalls(); return true; } A: You can create Layer or may be ColorLayer with some opacity and add to your current Scene/Layer. Add pause Dialog content like Pause Label, Resume Button on that layer and remove that layer when you resume. auto pauseButton = MenuItemImage::create("pauseNormal.png","pauseSelected.png",[](Ref*sender){ if(!Director::getInstance()->isPaused()) Director::getInstance()->pause(); else Director::getInstance()->resume(); }); auto buttons = Menu::create(pauseButton,NULL); addChild(buttons); buttons->setPosition(visibleSize.width / 2.0, visibleSize.height / 2.0); EDIT auto pauseLayer=LayerColor::create(Color4B::BLACK, visibleSize.width,visibleSize.height); auto pauseLabel=Label::createWithTTF("Paused", "fonts/Marker Felt.ttf", 24); pauseLabel->setPosition(origin.x+visibleSize.width/2,origin.y+visibleSize.height-50); pauseLayer->addChild(pauseLabel); // Add your required content to pauseLayer like pauseLabel pauseLayer->setVisible(false); pauseLayer->setOpacity(220); // so that gameplay is slightly visible addChild(pauseLayer); auto pauseButton = MenuItemImage::create("pauseNormal.png","pauseSelected.png",[pauseLayer](Ref*sender){ if(!Director::getInstance()->isPaused()){ Director::getInstance()->pause(); pauseLayer->setVisible(true); } else { Director::getInstance()->resume(); pauseLayer->setVisible(false); } }); auto buttons = Menu::create(pauseButton,NULL); addChild(buttons); buttons->setPosition(visibleSize.width / 2.0, visibleSize.height / 2.0);
doc_4268
let placeHolder = ["place": ""] let document = Firestore.firestore().collection("tweets").whereField("uid", isEqualTo: uid).collection("comments").document("hello") document.setData(placeHolder)
doc_4269
On my window, I have 6 ComboBox. If I select an item (displayed item1 for example) in a ComboBox, I want to disable this item1 for each others. If I dropdown a second ComboBox, I can't select select item1 and chose item2. In a third ComboBox, it will not possible to select item1 and item2. Etc ... I use WPF with MVVM. Could you help me please ? EDIT I've implement the solution of Ed Plunkett : My converter : I take the string of the item and a list of string which contain selected items class ComboBoxItemDisableConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { if (values[0].Equals("")) { return false; } bool contains = !(values[1] as List<string>).Contains(values[0].ToString()); return contains; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } I will not show you all the xaml file but only the important code : All ComboBox are the same. <Window.DataContext> <vm:MainViewModel /> </Window.DataContext> <Window.Resources> <converters:ComboBoxItemDisableConverter x:Key="comboBoxItemDisableConverter" /> </Window.Resources> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <ComboBox Grid.Row="0" Grid.Column="0" ItemsSource="{Binding ListeComposants}" SelectedItem="{Binding SelectedItemPrimaire00}"> <ComboBox.ItemContainerStyle> <Style TargetType="ComboBoxItem"> <Setter Property="IsEnabled"> <Setter.Value> <MultiBinding Converter="{StaticResource comboBoxItemDisableConverter}"> <Binding /> <Binding Path="DataContext.SelectedItemsVuePrimaire" RelativeSource="{RelativeSource AncestorType={x:Type Window}}" /> </MultiBinding> </Setter.Value> </Setter> </Style> </ComboBox.ItemContainerStyle> </ComboBox> There is no code behind. In my ViewModel, I put SelectedItem in a List<string> named `` class MainViewModel : ViewModelBase, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private List<string> _selectedItemsVuePrimaire = new List<string> { "", "", "", "", "", "" }; public List<string> ListeComposants { get; set; } public List<string> SelectedItemsVuePrimaire { get { return _selectedItemsVuePrimaire; } set { _selectedItemsVuePrimaire = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedItemsVuePrimaire))); } } private string _selectedItemPrimaire00; public string SelectedItemPrimaire00 { get { return _selectedItemPrimaire00; } set { _selectedItemPrimaire00 = value; SelectedItemsVuePrimaire[0] = _selectedItemPrimaire00; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedItemPrimaire00))); } } private string _selectedItemPrimaire01; public string SelectedItemPrimaire01 { get { return _selectedItemPrimaire01; } set { _selectedItemPrimaire01 = value; SelectedItemsVuePrimaire[1] = _selectedItemPrimaire01; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedItemPrimaire01))); } } public MainViewModel() { ListeComposants = new List<string>(); ListeComposants.Add(""); ListeComposants.Add("Dernières commandes"); ListeComposants.Add("Fournisseurs"); ListeComposants.Add("Relevé de prix"); ListeComposants.Add("Remises financières"); ListeComposants.Add("Historique E/S x mois"); ListeComposants.Add("Prévisions"); ListeComposants.Add("Equivalences"); ListeComposants.Add("Caractéristiques"); ListeComposants.Add("UG"); } For each first dropdowlist open, the dropdown list call the converter but if I open the dropdown for the second time, the converter is not call ... SOLUTION I add a PropertyChanged of my list of selectedItems when a selectedItem changed private string _selectedItemPrimaire00; public string SelectedItemPrimaire00 { get { return _selectedItemPrimaire00; } set { _selectedItemPrimaire00 = value; SelectedItemsVuePrimaire[0] = _selectedItemPrimaire00; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedItemsVuePrimaire))); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedItemPrimaire00))); } } A: Give the viewmodel a property that is a collection of all the selected items. We'll call it SelectedItems. Update SelectedItems as the selections change, and raise PropertyChanged for that collection property. Each selection needs to be bound to a viewmodel property. Give each ComboBox an ItemContainerTemplate with a DataTrigger. Give the DataTrigger a multibinding that includes <Binding/> and <Binding DataContext.SelectedItems, RelativeSource={RelativeSource AncestorType=ComboBox}}" />. Give the multibinding a multi-value converter (IMultiValueConverter) that returns true if values[0] (<Binding/>) is contained in values[1] (SelectedItems). If the multi-value converter returns true, the trigger fires and sets IsEnabled to False.
doc_4270
This is an example of the file data that would be in the properties.txt file: FileLocation: "Z:\Folder\file.txt" FileMkdirLocation: "Z:\Folder2\file.txt" I want to use something like system(mkdir "sim-link_file_location" "file_location") by changing the data that is in properties.txt. I want to be able to add more than 1 file, without recompiling the program and writing each command for each file, one by one. The problem is that I don't know how to make the commands use the data in the file. EDIT: I managed to find out a way, but I get errors when compiling the program. I use this code: #include <iostream> #include <fstream> #include <string.h> #include <stdlib.h> using namespace std; //initialization of Properties File used ifstream PropertiesFile ("PropertiesFile.txt"); int main() { //initialization of variables used int input_option; char FileLocation[256], Command[]="mklink "; // string FileLocation, Command; PropertiesFile >> FileLocation; /* switch (input_option) { case "add all mods": } */ cout << "FileLocation: " << FileLocation; cout << endl; strcat(Command, FileLocation); Command[strlen(FileLocation)] = '\0'; cout << Command; cout << endl; //system(command); system("pause"); return 0; } I know that i haven't used all variables yet. It tells me that "strcat" is deprecated and to use "strcat_s" instead, and when i replace it with that, I get "Debug Assertion Failed - Expression: (L"Buffer is too small" && 0)" A: I had to make the "Command" char bigger than "FileLocation" because then strcat_s would not be able to copy the content. After that the program worked fine, and there were no other Assert Errors. A: The command to create a soft link in linux is: ln -s <source> <destination> You can use this in a system(""); call, BUT before you continue in your code, you will have to make sure that the kernel finished executing this command. After that you can read the link as if it was the original file.
doc_4271
class UserProfile(models.Model): following = models.ManyToManyField('self', related_name='followers') somewhere else in a serializer: def get_followers(user): return user.profile.followers AttributeError: 'UserProfile' object has no attribute 'followers' Is there another way I can implement followers? Maybe I should make another model to do this or use a library? A: By default, Django treats all self m2m relations as symmetrical, for example if I am your friend, you are my friend too. When relation is symmetrical, Django won't create reverse relation attribute to your model. If you want to define non-symmetrical relation, set symmetrical=False attribute on your field, example: following = models.ManyToManyField('self', related_name='followers', symmetrical=False) More on that in Django documentation
doc_4272
To run the test, the operator should just touch a button, and the app should send some configuration command messages to the hardware device, and listen for the confirmation response of each message. I have implemented a BroadcastReceiver where I listen for the incoming messages. Then, I use a callback interface to send this data (sender_number, message, time) to the UI activity. So my MainActivity implements this interface, and I use an Asynctask to execute the test procedure. This is the method of the callback interface which I use to get the data from the receiver in the UI. public void gotSms(String num, String msg, long time) { mNumber = num; mMessage = msg; mTime = time; } } And this is the Asynctask where the test procedure runs: class TestProcedure extends AsyncTask<Void, Void, Void> { protected Void doInBackground(Void... params) { /*First command*/ String command1 = "DEV123"+"-"+"DEV-NUM1"; /*Send SMS with command*/ smsManager = SmsManager.getDefault(); try { smsManager.sendTextMessage(mNumber, null, command1, null, null); } catch (Exception e) { Log.d("SMS_SENT", "Sending error: "+e.getMessage()); } //AFTER SMS IS SENT, I NEED TO WAIT TILL THE RECEVIER RECEIVES THE //CONFIRMATION SMS TO GET THE OK /*Then the second command is sent*/ String command2 = ... } } The problem I'm facing is that for now I only get to send the command, I don't know how the Asynctask could wait for the received SMS and how the callback could notify the Asynctask that the SMS has arrived. Update -> Receiver definition I have the receiver declared in the manifest: <receiver android:name=".SmsReceiver" android:exported="true" > <intent-filter android:priority="1000"> <action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver> Also, I have the callback interface declared in the SmsReceiver class: public class SmsReceiver extends BroadcastReceiver { public SmsReceiver(SmsUpdater updater) { smsUpdater = updater; } @Override public void onReceive(Context context, Intent intent) { //... } public interface SmsUpdater { void gotSms(String num, String msg, long time, String imei); } } So in the MainActivity I implement SmsUpdater and I instantiate the receiver in OnCreate: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); smsReceiver = new SmsReceiver(this); //... } Update -> Code modification With the help of Mike M. I've changed some things in my code. The first is that I no longer use Asynctask. My current code looks like this: I first obtain some values from the fragment in my main activity with this method. Also this method is the one launched when the user click on the start test button. This test is porformed sending 3 commands automatically and waiting for each one's response SMS before sending the next. public void manageConfiguration(String pin, String number, String operator) { /*Saves values*/ mPin = pin; mNumber = number; mOperator = operator; /*Sends first command*/ configTnum1(pin, number); } This is how the sending command method looks like for this case: public void configTnum1(String pin, String number) { /*Command generate*/ String command = constructCommand(pin, "DEV+TNUM1", getPhoneNumber()); //The command would look like: DEV1234,DEV+TNUM1,394876354; /*Sends SMS*/ sendSMS(number, command); } When this command is sent, I should wait for the incoming message, that aside from giving me the confirmation (message OK or ERROR) it also gives me other info about the hardware device as it's GPS position, identification code, etc.. that I could need to use in any moment. So, now I get in the critical point. Even if I do in Mike M.'s way implementing the receiver in the activity, or in my way using a callback to pass the data from the receiver to the activity... I get into the situation where I need to manage how I continue with the automatical test and send the command2. Mike M. propose to manage this in the same receiver (or in the callback method in my code, it would be the same). And at first look seems a good option. But I have to explain that this test is not the only one I make. This test sends 3 commands automatically, but after doing this, I have other screen (activity) where the user must perfom another test where this time 5 commands are sent automatically. So, maybe I'm wrong but I think that if I manage all this on the receiver for the first test, it could make something wrong confusing booth tests. A: As I do not know all of the details of your implementation, the following is, again, a sparse outline. I've run it myself, however, filling in incidental details as necessary, and I believe this should work as you need. Since we've established that your app need only listen for incoming SMS while it's running, you don't need the BroadcastReceiver registered in the manifest. Again, I have it as an inner class of MainActivity, which will receive notification of the incoming message and then relay it to the appropriate Fragment. I took your last post update to mean that you're concerned that the separate tests would get "mixed up", and, as these tests won't run simultaneously, this shouldn't be a problem. In MainActivity, we have the following (in addition to the boilerplate code): private SmsTestListener listener = null; private void sendSmsTest(String number, String command, SmsTestListener listener) { this.listener = listener; SmsManager.getDefault().sendTextMessage(number, null, command, null, null); } private void notifyIncoming(String message) { listener.onSmsTestResponse(message); } private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Standard decoding for SMS Object[] pdus = (Object[])intent.getExtras().get("pdus"); StringBuilder message = new StringBuilder(); SmsMessage messageSegment; for (int i=0;i < pdus.length;i++) { messageSegment = SmsMessage.createFromPdu((byte[]) pdus[i]); message.append(messageSegment.getDisplayMessageBody()); } if (isMessageValid(message.toString())) { notifyIncoming(message.toString()); } } private boolean isMessageValid(String message) { // Check that the message is valid // Here, I've listed the message text for // the check, but you could also use the // originating number, etc. return true; } }; We also need to define the following interface: public interface SmsTestListener { void onSmsTestResponse(String message); } Then, the Fragments, which implement the above interface, would be structured as such: class FragmentOne extends Fragment implements SmsTestListener { private String number = "1234567890"; private String[] commands; private int commandIndex; private Button startButton; private void startSmsTest() { // Initialize commands here // and fire the first one commands = new String[] { "command1", "command2" }; commandIndex = 0; fireNextCommand(); } private void fireNextCommand() { // Tell the Activity to send the next message, // and pass it a reference to the Fragment that // is running the test ((MainActivity) getActivity()).sendSmsTest(number, commands[commandIndex], this); } @Override public void onSmsTestResponse(String message) { // Increment our command counter and if // we're not finished, fire the next one commandIndex++; if (commandIndex < commands.length) { fireNextCommand(); } else { Toast.makeText(MainActivity.this, "Test finished", 0).show(); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // This is standard; I put it here to show our // start button initialization View rootView = inflater.inflate(R.layout.fragment_one, container, false); startButton = (Button) rootView.findViewById(R.id.button_execute); startButton.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { startSmsTest(); } } ); return rootView; } }
doc_4273
(def data [{:a 1 :b 2 :c 3} {:a 1 :b 2 :c 3}] (for [xs data] (map xs [:a :b])) ((1 2) (1 2)) Final result should be ==> (2 4) Basically, I have a list of maps. Then I perform a list of comprehension to take only the keys I need. My question now is how can I now sum up those values? I tried to use "reduce" but it works only over sequences, not over collections. Thanks. ===EDIT==== Using the suggestion from Joost I came out with this: (apply merge-with + (for [x data] (select-keys x [:col0 :col1 :col2])) This iterates a collection and sums on the chosen keys. The "select-keys" part I added is needed especially to avoid to get in trouble when the maps in the collection contain literals and not only numbers. A: If you really want to sum the values of the common keys you can do the whole transformation in one step: (apply merge-with + data) => {:a 2, :b 4, :c 6} To sum the sub sequences you have: (apply map + '((1 2) (1 2))) => (2 4)
doc_4274
For example, I have a and b arrays with a size of 20 for N rows. each row has a different a and b. I would like to write a file with a format like this: Names of each column 0 a[0] b[0] a[1] b[1] ... a[19] b[19] 1 a[0] b[0] a[1] b[1] ....a[19] b[19] I can only think this way: data = open(output_filename,'w') for i in range(0, N): data.write('{} {} {} ...\n'.format(i, a[0], b[0], ....)) A: import numpy #Assuming a, b are numpy arrays, else convert them accordingly: # a= np.array(a) # b= np.array(b) c = np.zeros((100,40)) for i in range(20): c[:, 2*i] = a[:,i] c[:, 2*i+1] = b[:,i] np.savetxt("test.txt",c) This is the simplest way I could think of it. A: If I understand correctly, you want to interleave two lists. You can do that with zip and some post-processing of it: >>> a = ['a', 'b', 'c'] >>> b = ['d', 'e', 'f'] >>> print(list(zip(a, b))) [('a', 'd'), ('b', 'e'), ('c', 'f')] >>> from itertools import chain >>> print(list(chain.from_iterable(zip(a, b)))) ['a', 'd', 'b', 'e', 'c', 'f'] >>> print(' '.join(chain.from_iterable(zip(a, b)))) a d b e c f You probably want to apply that something like this: data.write('{} {}\n'.format(i, ' '.join(chain.from_iterable(zip(a, b)))))
doc_4275
float x[N]; float y[N]; for (int i = 1; i < N-1; i++) y[i] = a*(x[i-1] - x[i] + x[i+1]) And I assume my cache line is 64 Byte (i.e. big enough). Then I will have (per frame) basically 2 accesses to the RAM and 3 FLOP: * *1 (cached) read access: loading all 3 x[i-1], x[i], x[i+1] *1 write access: storing y[i] *3 FLOP (1 mul, 1 add, 1 sub) The operational intensity is ergo OI = 3 FLOP/(2 * 4 BYTE) Now what happens if I do something like this float x[N]; for (int i = 1; i < N-1; i++) x[i] = a*(x[i-1] - x[i] + x[i+1]) Note that there is no y anymore. Does it mean now that I have a single RAM access * *1 (cached) read/write: loading x[i-1], x[i], x[i+1], storing x[i] or still 2 RAM accesses * *1 (cached) read: loading x[i-1], x[i], x[i+1] *1 (cached) write: storing x[i] Because the operational intensity OI would be different in either case. Can anyone tell something about this? Or maybe clarify some things. Thanks A: Disclaimer: I've never heard of the roofline performance model until today. As far as I can tell, it attempts to calculate a theoretical bound on the "arithmetic intensity" of an algorithm, which is the number of FLOPS per byte of data accessed. Such a measure may be useful for comparing similar algorithms as the size of N grows large, but is not very helpful for predicting real-world performance. As a general rule of thumb, modern processors can execute instructions much more quickly than they can fetch/store data (this becomes drastically more pronounced as the data starts to grow larger than the size of the caches). So contrary to what one might expect, a loop with higher arithmetic intensity may run much faster than a loop with lower arithmetic intensity; what matters most as N scales is the total amount of data touched (this will hold true as long as memory remains significantly slower than the processor, as is true in common desktop and server systems today). In short, x86 CPUs are unfortunately too complex to be accurately described with such a simple model. An access to memory goes through several layers of caching (typically L1, L2, and L3) before hitting RAM. Maybe all your data fits in L1 -- the second time you run your loop(s) there could be no RAM accesses at all. And there's not just the data cache. Don't forget that code is in memory too and has to be loaded into the instruction cache. Each read/write is also done from/to a virtual address, which is supported by the hardware TLB (that can in extreme cases trigger a page fault and, say, cause the OS to write a page to disk in the middle of your loop). All of this is assuming your program is hogging the hardware all to itself (in non-realtime OSes this is simply not the case, as other processes and threads are competing for the same limited resources). Finally, the execution itself is not (directly) done with memory reads and writes, but rather the data is loaded into registers first (then the result is stored). How the compiler allocates registers, if it attempts loop unrolling, auto-vectorization, the instruction scheduling model (interleaving instructions to avoid data dependencies between instructions) etc. will also all affect the actual throughput of the algorithm. So, finally, depending on the code produced, the CPU model, the amount of data processed, and the state of various caches, the latency of the algorithm will vary by orders of magnitude. Thus, the operational intensity of a loop cannot be determined by inspecting the code (or even the assembly produced) alone, since there are many other (non-linear) factors in play. To address your actual question, though, as far as I can see by the definition outlined here, the second loop would count as a single additional 4-byte access per iteration on average, so its OI would be θ(3N FLOPS / 4N bytes). Intuitively, this makes sense because the cache already has the data loaded, and the write can change the cache directly instead of going back to main memory (the data does eventually have to be written back, however, but that requirement is unchanged from the first loop).
doc_4276
The User model has Messagable Trait where you can get all the threads with $user->threads(); I am trying to eager load additional data to the threads array using the following: $threads = Auth::user()->threads()->with(['participants.user'])->get(); What i am struggling is the Threads model has function to get the latest message from it: $thread->getLatestMessage(); My question is how can i append this latest message to the upper query i am doing. I was trying something like this but its not ok... I guess im doing something stupid here... $threads = Auth::user()->threads()->with([ 'participants.user', 'latestMessage' => function ($query) { return $query->getLatestMessageAttribute(); }])->get(); or $threads = Auth::user()->threads()->with(['participants.user','getLatestMessageAttribute'])->get(); I hope i clarified this ok because i am using a 3rd party package for this system which has these Traits and Thread classes i am using. SOLUTION Looks like i had to add append('accessor_name') at the end when getting the collection. $collection = Auth::user()->relationship()->get()->append('accessor_name'); A: You can override class .Create new model and extend package model <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; class Thread extends \Lexx\ChatMessenger\Models\Thread { use HasFactory; protected $appends=['latest_message']; } Publish config: php artisan vendor:publish --provider="Lexx\ChatMessenger\ChatMessengerServiceProvider" --tag="config" in config/chatmessenger.php 'thread_model' => \App\Models\Thread::class, Updated If anyone still not getting get attribute data then dont forget to clear cache php artisan cache:clear php artisan optimize php artisan config:clear php artisan clear
doc_4277
How on earth should I add multiple elements into the XML. The schemaValidate() response: DOMDocument::schemaValidate(): Element '{http://www.stormware.cz/schema/version_2/stock.xsd}stockHeader': This element is not expected. Expected is one of ( {http://www.stormware.cz/schema/version_2/stock.xsd}stockDetail, {http://www.stormware.cz/schema/version_2/stock.xsd}stockAttach, {http://www.stormware.cz/schema/version_2/stock.xsd}stockSerialNumber, {http://www.stormware.cz/schema/version_2/stock.xsd}stockPriceItem, {http://www.stormware.cz/schema/version_2/stock.xsd}print). XML <?xml version="1.0" encoding="Windows-1250"?> <dat:dataPack xmlns:dat="http://www.stormware.cz/schema/version_2/data.xsd" xmlns:stk="http://www.stormware.cz/schema/version_2/stock.xsd" xmlns:typ="http://www.stormware.cz/schema/version_2/type.xsd" id="Sklad" ico="02021123" application="Eshop" version="2.0" note="Import zasob."> <dat:dataPackItem id="ZAS20160809" version="2.0"> <stk:stock version="2.0"> <stk:stockHeader> <stk:stockType>card</stk:stockType> <stk:code>C Set-G/Fe-K</stk:code> </stk:stockHeader> <stk:stockHeader> <stk:stockType>card</stk:stockType> <stk:code>C Set-G/Zn-K</stk:code> </stk:stockHeader> </stk:stock> </dat:dataPackItem> </dat:dataPack> Your help would be really appreciated. A: stockHeader is declared in stock.xsd like so: <xsd:element name="stockHeader" type="stk:stockHeaderType" minOccurs="0"/> The absence of maxOccurs defaults to a value of 1, so that there can be either 0 or 1 occurrence of stockHeader. To allow more, it should be changed to <xsd:element name="stockHeader" type="stk:stockHeaderType" minOccurs="0" maxOccurs="unbounded"/> A: I guess you are trying to add multiple stock updates. As Ghislain Fourny mentioned, <stk:stockHeader> can occure only one. For multiple stock updates use <dat:dataPackItem > For example: <dat:dataPackItem id="ZAS001" version="2.0"> <stk:stock version="2.0"> <stk:actionType> <stk:add/> </stk:actionType> <stk:stockHeader> ... ... </stk:stockHeader> </stk:stock> </dat:dataPackItem> <dat:dataPackItem id="ZAS002" version="2.0"> <stk:stock version="2.0"> <stk:actionType> <stk:add/> </stk:actionType> <stk:stockHeader> ... ... </stk:stockHeader> </stk:stock> </dat:dataPackItem>
doc_4278
Signin page/component : const Signin = ({ currentUser }) => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const { doRequest, errors } = useRequest({ url: '/api/users/signin', method: 'post', body: { email, password }, onSuccess: () => Router.push('/') }); useEffect(() => { const loggedUser = () => { if (currentUser) { Router.push('/'); } }; loggedUser(); }, []); Custom _app component: const AppComponent = ({ Component, pageProps, currentUser }) => { return ( <div> <Header currentUser={currentUser} /> <Component {...pageProps} currentUser={currentUser} /> </div> ) }; AppComponent.getInitialProps = async (appContext) => { const client = buildClient(appContext.ctx); const { data } = await client.get('/api/users/currentuser'); let pageProps = {}; if (appContext.Component.getInitialProps) { pageProps = await appContext.Component.getInitialProps(appContext.ctx); } return { pageProps, ...data } }; export default AppComponent; Issue : I tried this, but this causes a slight delay as it won't be server side rendered. By delay I mean: It shows the page I don't want to show for a second or so before redirecting. I could use a loading sign or bunch of if else conditions, but that would be a work around, what would be the best approach/practice to handle this issue? Another solution I came up with: * *I built a redirect hook : import Router from 'next/router'; export default (ctx, target) => { if (ctx.res) { // server ctx.res.writeHead(303, { Location: target }); ctx.res.end(); } else { // client Router.push(target); } } * *Then I made 2 HOCs(for logged in and logged out user) to for protected routes: import React from 'react'; import redirect from './redirect'; const withAuth = (Component) => { return class AuthComponent extends React.Component { static async getInitialProps(ctx, { currentUser }) { if (!currentUser) { return redirect(ctx, "/"); } } render() { return <Component {...this.props} /> } } } export default withAuth; * *Then I wrapped the components with it for protecting the page: export default withAuth(NewTicket); Is there any better approach to handling this? Would really appreciate the help. A: Here's an example using a custom "hook" with getServerSideProps. I am using react-query, but you can use whatever data fetching tool. // /pages/login.jsx import SessionForm from '../components/SessionForm' import { useSessionCondition } from '../hooks/useSessionCondition' export const getServerSideProps = useSessionCondition(false, '/app') const Login = () => { return ( <SessionForm isLogin/> ) } export default Login // /hooks/useSessionCondition.js import { QueryClient } from "react-query"; import { dehydrate } from 'react-query/hydration' import { refreshToken } from '../utils/user_auth'; export const useSessionCondition = ( sessionCondition = true, // whether the user should be logged in or not redirect = '/' // where to redirect if the condition is not met ) => { return async function ({ req, res }) { const client = new QueryClient() await client.prefetchQuery('session', () => refreshToken({ headers: req.headers })) const data = client.getQueryData('session') if (!data === sessionCondition) { return { redirect: { destination: redirect, permanent: false, }, } } return { props: { dehydratedState: JSON.parse(JSON.stringify(dehydrate(client))) }, } } } A: Upgrade NextJs to 9.3+ and use getServerSideProps instead of getInitialProps. getServerSideProps runs only and always server side unlike getInitialProps. Redirect from getServerSideProps if auth fails. A: export const getServerSideProps = wrapper.getServerSideProps( (store) => async ({ req, params }) => { const session = await getSession({ req }); if (!session) { return { redirect: { destination: '/', permanent: false, }, }; } } ); Here in Next 9++ you can do like this just check the session, if there are none, we can return a redirect with destination to route the user to end point! A: Just to expand on what @Nico was saying in his comment. Here is how I set it up: Layout.tsx file // ... import withAuth from "../utils/withAuth"; interface Props { children?: ReactNode; title?: string; } const Layout = ({ children, title = "This is the default title", }: Props): JSX.Element => ( <> {children} </> ); export default withAuth(Layout); And withAuth.js file import { getSession } from "next-auth/client"; export default function withAuth(Component) { const withAuth = (props) => { return <Component {...props} />; }; withAuth.getServerSideProps = async (ctx) => { return { session: await getSession(ctx) }; }; return withAuth; } A: Answer I would really recommend looking at the examples to see how NextJS suggest handling this. The resources are really good! https://github.com/vercel/next.js/tree/master/examples For example you could use next-auth which is an open-source auth option. The example is here. https://github.com/vercel/next.js/tree/master/examples/with-next-auth // _app.js import { Provider } from 'next-auth/client' import '../styles.css' const App = ({ Component, pageProps }) => { const { session } = pageProps return ( <Provider options={{ site: process.env.SITE }} session={session}> <Component {...pageProps} /> </Provider> ) } export default App // /pages/api/auth/[...nextauth].js import NextAuth from 'next-auth' import Providers from 'next-auth/providers' const options = { site: process.env.VERCEL_URL, providers: [ Providers.Email({ // SMTP connection string or nodemailer configuration object https://nodemailer.com/ server: process.env.EMAIL_SERVER, // Email services often only allow sending email from a valid/verified address from: process.env.EMAIL_FROM, }), // When configuring oAuth providers make sure you enabling requesting // permission to get the users email address (required to sign in) Providers.Google({ clientId: process.env.GOOGLE_ID, clientSecret: process.env.GOOGLE_SECRET, }), Providers.Facebook({ clientId: process.env.FACEBOOK_ID, clientSecret: process.env.FACEBOOK_SECRET, }), Providers.Twitter({ clientId: process.env.TWITTER_ID, clientSecret: process.env.TWITTER_SECRET, }), Providers.GitHub({ clientId: process.env.GITHUB_ID, clientSecret: process.env.GITHUB_SECRET, }), ], // The 'database' option should be a connection string or TypeORM // configuration object https://typeorm.io/#/connection-options // // Notes: // * You need to install an appropriate node_module for your database! // * The email sign in provider requires a database but OAuth providers do not database: process.env.DATABASE_URL, session: { // Use JSON Web Tokens for session instead of database sessions. // This option can be used with or without a database for users/accounts. // Note: `jwt` is automatically set to `true` if no database is specified. // jwt: false, // Seconds - How long until an idle session expires and is no longer valid. // maxAge: 30 * 24 * 60 * 60, // 30 days // Seconds - Throttle how frequently to write to database to extend a session. // Use it to limit write operations. Set to 0 to always update the database. // Note: This option is ignored if using JSON Web Tokens // updateAge: 24 * 60 * 60, // 24 hours // Easily add custom properties to response from `/api/auth/session`. // Note: This should not return any sensitive information. /* get: async (session) => { session.customSessionProperty = "ABC123" return session } */ }, // JSON Web Token options jwt: { // secret: 'my-secret-123', // Recommended (but auto-generated if not specified) // Custom encode/decode functions for signing + encryption can be specified. // if you want to override what is in the JWT or how it is signed. // encode: async ({ secret, key, token, maxAge }) => {}, // decode: async ({ secret, key, token, maxAge }) => {}, // Easily add custom to the JWT. It is updated every time it is accessed. // This is encrypted and signed by default and may contain sensitive information // as long as a reasonable secret is defined. /* set: async (token) => { token.customJwtProperty = "ABC123" return token } */ }, // Control which users / accounts can sign in // You can use this option in conjunction with OAuth and JWT to control which // accounts can sign in without having to use a database. allowSignin: async (user, account) => { // Return true if user / account is allowed to sign in. // Return false to display an access denied message. return true }, // You can define custom pages to override the built-in pages // The routes shown here are the default URLs that will be used. pages: { // signin: '/api/auth/signin', // Displays signin buttons // signout: '/api/auth/signout', // Displays form with sign out button // error: '/api/auth/error', // Error code passed in query string as ?error= // verifyRequest: '/api/auth/verify-request', // Used for check email page // newUser: null // If set, new users will be directed here on first sign in }, // Additional options // secret: 'abcdef123456789' // Recommended (but auto-generated if not specified) // debug: true, // Use this option to enable debug messages in the console } const Auth = (req, res) => NextAuth(req, res, options) export default Auth So the option above is defo a server-side rendered app since we're using /api paths for the auth. If you want a serverless solution you might have to pull everything from the /api path into a lambda (AWS Lambda) + a gateway api (AWS Api Gateway). All you'd need there is a custom hook that connects to that api. You can do this in different ways too of course. Here is another auth example using firebase. https://github.com/vercel/next.js/tree/master/examples/with-firebase-authentication And another example using Passport.js https://github.com/vercel/next.js/tree/master/examples/with-passport Also you asked about a loading behaviour, well this example might help you there https://github.com/vercel/next.js/tree/master/examples/with-loading Opinion The custom _app component is usually a top level wrapper (not quite the very top _document would fit that description). Realistically I'd create a Login component one step below the _app. Usually I'd achieve that pattern in a Layout component or like the examples above are doing it, using an api path or a utility function. A: I have faced the same problem and my client-side solution which does not flash the content is as follows: Please correct me if I have done it in the wrong way. I use useRouter //@/utils/ProtectedRoute import { useRouter } from "next/router"; import { useState, useEffect } from "react"; export const ProtectedRoute = ({ user = false, children }) => { const [login, setLogin] = useState(false); const router = useRouter(); useEffect(() => { login && router.push("/account/login");//or router.replace("/account/login"); }, [login]); useEffect(() => { !user && setLogin(true); }, []); return ( <> {user ? ( children ) : ( <div> <h4> You are not Authorized.{" "} <Link href="/account/login"> <a>Please log in</a> </Link> </h4> </div> )} </> }; ) When I want to protect a route I use this syntax: import { ProtectedRoute } from "@/utils/ProtectedRoute"; const ProtectedPage = () => { const user = false; return ( <ProtectedRoute user={user}> <h1>Protected Content</h1> </ProtectedRoute> ); }; export default ProtectedPage; A: // Authentication.js import { useRouter } from "next/router"; import React, { useEffect } from "react"; function Authentication(props) { let userDetails; const router = useRouter(); useEffect(() => { if (typeof window !== undefined) { userDetails=useSession if (!userDetails) { const path = router.pathname; switch (path) { case "/": break; case "/about": break; case "/contact-us": break; default: router.push("/"); } } else if (userDetails) { if (router.pathname == "/") { router.push("/home"); } } } }, []); return <>{props.children}</>; } export default Authentication; Now add this code in your _app.js <DefaultLayout> <Authentication> <Component {...pageProps} /> </Authentication> </DefaultLayout> Evrything should work now, if you want add loading. A: Vercel recently introduced middleware for Next.js. Next.js middleware allows you to run code before an HTTP request is handled. To add your middleware logic to your app, add a middleware.js or middleware.ts file in the root directory of your Next.js project. export async function middleware(req: NextRequest) { const token = req.headers.get('token') // get token from request header const userIsAuthenticated = true // TODO: check if user is authenticated if (!userIsAuthenticated) { const signinUrl = new URL('/signin', req.url) return NextResponse.redirect(signinUrl) } return NextResponse.next() } // Here you can specify all the paths for which this middleware function should run // Supports both a single string value or an array of matchers export const config = { matcher: ['/api/auth/:path*'], }
doc_4279
public static void TruncateList(SPList list) { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(list.ParentWeb.Site.ID)) { using (SPWeb web = site.OpenWeb()) { web.AllowUnsafeUpdates = true; SPList listCopy = web.Lists[list.ID]; string title = listCopy.Title; string description = listCopy.Description; string backupName = string.Format("BACKUP_{0}", title); // Delete old Template if exists: SPList gallery = web.Lists["List Template Gallery"]; foreach (SPListItem item in gallery.Items) { if (item.Title == backupName) { item.Delete(); break; } } // Save Template: listCopy.SaveAsTemplate(backupName, backupName, string.Empty, false); // Load Template: SPListTemplate template = web.Site.GetCustomListTemplates(web)[backupName]; template = web.ListTemplates[backupName]; // Delete List: listCopy.Delete(); // Add empty List from Template: [HANGS HERE!] web.Lists.Add(title, description, template); web.Update(); web.AllowUnsafeUpdates = false; } ); } } } Saving the template works fine as well as deleting the original list (listCopy.Delete()) which takes a while But when trying to create that List again (web.Lists.Add) the server got stuck until it gets a Timeout-Exception after some minutes. Useful to mention: This is my developer machine. Noone but me is accessing that web/List A: Solved by myself: The problem was that I was using that list ("list") as a parameter. I changed it to just send the ID of that list to that method and use using (SPWeb web = SPContext.Current.Web) inside. Now it works.
doc_4280
function restUpdateByemail(Request $request,$email){ $students=student::find($email); $students->name =$request->input("name"); $students->password=$request->input("password"); $students->gender=$request->input("gender"); $students->country=$request->input("country"); $students->save(); return response()->json($students); } A: Try this. function restUpdateByemail(Request $request,$email){ $students=student::where('email',$email)->first(); $students->name =$request->input("name"); $students->password=$request->input("password"); $students->gender=$request->input("gender"); $students->country=$request->input("country"); $students->save(); return response()->json($students); } A: Try this as well function restUpdateByemail(Request $request,$email) { $students = student::where('email',$email)->first(); $students->update($request->all()); return response()->json($students); }
doc_4281
doc_4282
doc_4283
<style type="text/css"> #header{ height: 20px; background-color: #2A646C; width: 50%; margin: auto; } #container{ display:flex; flex-wrap: wrap; border: 2px solid red; width: 50%; margin: auto; padding: 10px; background-color: #C4D8E2; } #container1{ border: 2px solid yellow; width: 100%; background-color: #C4D8E2; } #container1 p span{ background-color: #C4D8E2; color: #5D8AA8; font-family: sans-serif; font-size: 12px; } #container1 h3{ background-color: #C4D8E2; } #container2{ border: 2px solid blue; width: 45%; background-color: #C4D8E2; margin-right: 8%; display:flex; flex-wrap: wrap; } #container2 form{ width: 100%; height: 100%; } #container2 p{ width:100%; } #container2 span{ font-weight: bold; font-family: "Times New Roman"; font-size: 16px; } #container2 #span1{ color: #5D8AA8; margin-right: 5px; } #container2 #span2{ color: #5072A7; } #container2 input[type=submit]{ border: 1px solid black; width: 25%; height: 40%; margin-left: 68%; background-color: #C4D8E2; } #container3{ border: 2px solid green; width: 45%; background-color: #5072A7; color: white; } #container3 form{ width: 100%; height: 100%; } #container3 input[type=submit]{ border: 2px solid orange; background-color: #5072A7; width: 25%; height: 10%; margin-left: 68%; } #container3:nth-child(10){ font-size: 14px; } #container3:nth-child(16){ display: inline-block; font-size: 10px; font-style: underline; margin-left: 68%; } </style> <div id="header"></div><br><br> <div id="container"> <div id="container1"> <h3>Enter the system</h3> <p><span>It is necessary to login in Your account in order to sign up for a course.</span></p> </div> <div id="container2"> <p><span id="span1">ARE YOU NEW?</span><span id="span2">REGISTER</span></p> <form method="POST" action="javascript:void(0)" enctype="multipart/form-data"> <input type="text" name="username" required placeholder="User name" autocomplete="off" pattern="^[A-Za-z0-9._-]{6,10}$" size="40" maxlength="10"> <br><br> <input type="email" name="emailid" required placeholder="Email" autocomplete="off" pattern="^[A-Za-z0-9 _.-]+@[A-Za-z.-]+\.[A-Za-z]{3,4}$" size="40" maxlength="30"> <br><br> <input type="password" name="password" required placeholder="Password" autocomplete="off" pattern="^[A-Za-z0-9 _.-]{8,15}$" size="40" maxlength="15"> <br><br> <input type="password" name="confirmpassword" required placeholder="Confirm Password" pattern="^[A-Za-z0-9 _.-]{8,15}$" size="40" maxlength="15" autocomplete="off"> <br><br> <input type="submit" name="register" value="Register"> </form> </div> <div id="container3"> <form method="POST" action="javascript:void(0)" enctype="multipart/form-data"> <p><span class="span3">ALREADY A STUDENT?</span><span class="span4">LOGIN</span></p> <br><br> <input type="text" name="loginname" required placeholder="User name" autocompleter="off" pattern="^[A-Za-z0-9._-]{6,10}$" size="40" maxlength="10"> <br><br> <input type="password" name="loginpassword" required placeholder="Password" autocompleter="off" pattern="^[A-Za-z0-9 _.-]{8,15}$" size="40" maxlength="15"> <br><br> <input type="checkbox" name="remember" value="yes" id="remember"><label for="remember">Remember me?</label> <br><br> <input type="submit" name="login" value="Login" id="loginbutton"> <br> <label>Forgotpassword?</label> </form> </div> </div> 1) container2 or container3 size does not increase in height after including additional elements, why? 2) How do I use nth-child to pick last two labels of container3? A: 1) container2 or container3 size does not increase after including additional elements, why? Because you have the overall container's width limited to width: 50%. DEMO 1 (your original code, unaltered) Try this adjustment: #container{ display:flex; flex-wrap: wrap; border: 2px solid red; min-width: 50%; /* adjusted */ margin: auto; padding: 10px; background-color: #C4D8E2; } DEMO 2 2) How do I use nth-child to pick last two labels of container3? #container3 > form > label:nth-last-of-type(1) { font-weight: bold; color: red; } #container3 > form > label:nth-last-of-type(2) { font-weight: bold; color: aqua; } DEMO 3 For reference see: http://www.w3.org/TR/css3-selectors/#selectors An alternative to DEMO 2... In the event you prefer not to alter the width constraint of the overall flex container, you could make the forms flex containers, which would confine the form elements to the containers` boundaries. So instead of this (as outlined above): #container{ display:flex; flex-wrap: wrap; border: 2px solid red; min-width: 50%; /* adjusted */ margin: auto; padding: 10px; background-color: #C4D8E2; } Try this: #container2 form{ width: 100%; height: 100%; display: flex; /* new */ flex-direction: column; /* new */ } #container3 form{ width: 100%; height: 100%; display: flex; /* new */ flex-direction: column; /* new */ } DEMO 4 Update (based on comments and revised question) Using DEMO 4, we can improve the display of the submit buttons with this: #container2 input[type=submit]{ border: 1px solid black; /* width: 25%; */ height: 40%; /* margin-left: 68%; */ background-color: #C4D8E2; /* new */ margin-left: auto; margin-right: 5%; width: 75px; } #container3 input[type=submit]{ border: 2px solid orange; background-color: #5072A7; /* width: 25%; */ height: 10%; /* margin-left: 68%; */ /* new */ margin-left: auto; margin-right: 5%; width: 75px; } DEMO 5 A: about your second point ... it total you have 2 labels so you can use "nth-of-type" see the code I gave color for the labels . #container3 label { background: #f0f none repeat scroll 0 0; } #container3 label:nth-of-type(1) { background: #ff0 none repeat scroll 0 0; } #container3 label:nth-of-type(2) { background: #f00 none repeat scroll 0 0; } A: for your first point ... put the BTN height in PX it will fix your problem #container2 input[type=submit]{ border: 1px solid black; width: 25%; height: 40px; margin-left: 68%; background-color: #C4D8E2; } see this fiddle https://jsfiddle.net/b4mdz048/ plus the best practice is to add padding to the buttons its better I will suggest that you use bootstrap or other CSS framework
doc_4284
My range of values for the drop-down should come from Range(A1:A5) in Sheet2 and Range(C1:C7) in Sheet2. However, my code below is not working, it runs an error 1004 at Add xlValidateList, xlValidAlertStop, Operator:=xlBetween, Formula1:="=Sheet2!$A$1:$A$5 & Sheet2!$C$1:$C$7" I suspect it has something to do with this line...Formula1:="=Sheet2!$A$1:$A$5 & Sheet2!$C$1:$C$7" . Does anyone know how I can add two ranges into my Formula1? Also, I dont want the blanks in the ranges to appear in the Drop-down list but .IgnoreBlank = True still shows the blanks in the drop-down list. This is my code thus far, any help is genuinely appreciated: Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Not Intersect(Target, Range("E5")) Is Nothing Then With Range("e5").Validation .Add xlValidateList, xlValidAlertStop, Operator:=xlBetween, Formula1:="=Sheet2!$A$1:$A$5 & Sheet2!$C$1:$C$7" .IgnoreBlank = True .InCellDropdown = True .ErrorTitle = "Warning" .ErrorMessage = "Please select a value from the drop-down list available." .ShowError = True End With End If End Sub A: To add multiple columns data, use a unique collection and then feed that to the DV in a comma delimited string. See this example. Change as applicable. Sub Sample() Dim col As New Collection Dim rng As Range Dim i As Long Dim DVList As String '~~> Loop through the data range For Each rng In Sheet2.Range("A1:A5,C1:C5") '~~> Ignore blanks If Len(Trim(rng.Value)) <> 0 Then '~~> Create a unique list On Error Resume Next col.Add rng.Value, CStr(rng.Value) On Error GoTo 0 End If Next rng '~~> Concatenate with "," as delimiter For i = 1 To col.Count DVList = DVList & col.Item(i) & "," Next i '~~> Feed it to the DV With Sheet1.Range("E5").Validation .Delete .Add Type:=xlValidateList, _ AlertStyle:=xlValidAlertStop, _ Formula1:=DVList End With End Sub A: the property Formula1:="Expression" does not allow splitted tables. As Siddharth Rout wrote - as a work aorund - first you have to collect all values in a single table or a string. Also the IgnoreBlank property does not ignore blanks, but is considering the cell value as valid even the cell content is blank. So, while collecting table content skip blank cells.
doc_4285
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <!-- <link rel="stylesheet" href="http://openlayers.org/en/v3.2.1/css/ol.css" type="text/css">--> </head> <body> <div id="map" class="map"></div> <link rel="stylesheet" href="http://openlayers.org/en/v3.12.1/css/ol.css" type="text/css"> <script src="http://openlayers.org/en/v3.12.1/build/ol.js"></script> <script> var image = new ol.style.Circle({ radius: 5, fill: null, stroke: new ol.style.Stroke({color: 'red', width: 1}) }); var styles = { 'Point': new ol.style.Style({ image: image }), 'LineString': new ol.style.Style({ stroke: new ol.style.Stroke({ color: 'green', width: 3 }) }), 'MultiLineString': new ol.style.Style({ stroke: new ol.style.Stroke({ color: 'rose', width: 1 }) }), 'MultiPoint': new ol.style.Style({ image: image }), 'MultiPolygon': new ol.style.Style({ stroke: new ol.style.Stroke({ color: 'yellow', width: 1 }), fill: new ol.style.Fill({ color: 'rgba(255, 255, 0, 0.1)' }) }), 'Polygon': new ol.style.Style({ stroke: new ol.style.Stroke({ color: 'blue', lineDash: [4], width: 3 }), fill: new ol.style.Fill({ color: 'rgba(0, 0, 255, 0.1)' }) }), 'GeometryCollection': new ol.style.Style({ stroke: new ol.style.Stroke({ color: 'magenta', width: 2 }), fill: new ol.style.Fill({ color: 'magenta' }), image: new ol.style.Circle({ radius: 10, fill: null, stroke: new ol.style.Stroke({ color: 'magenta' }) }) }), 'Circle': new ol.style.Style({ stroke: new ol.style.Stroke({ color: 'red', width: 2 }), fill: new ol.style.Fill({ color: 'rgba(255,0,0,0.2)' }) }) }; var styleFunction = function(feature, resolution) { return styles[feature.getGeometry().getType()]; }; var geojsonObject = { "type": "LineString", "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } }, "coordinates": [ [103.984865, 1.350197] ,[103.985188, 1.350903] ,[103.985376, 1.351149] ,[103.985477, 1.351341] ,[103.986155, 1.352857] ,[103.986195, 1.352982] ,[103.986248, 1.353248] ,[103.986393, 1.353593] ,[103.986564, 1.353550] ,[103.985175, 1.350160] ,[103.985138, 1.350069] ], "properties": { "distance": "21.452372", "description": "To enable simple instructions add: 'instructions=1' as parameter to the URL", "traveltime": "1228" } }; //console.log(geojsonObject.coordinates); var routeGeom = new ol.geom.LineString(geojsonObject.coordinates).transform('EPSG:4326','EPSG:3857'); var routeFeature = new ol.Feature({ geometry:routeGeom }) var extentToZoom = routeGeom.getExtent(); console.log(extentToZoom); console.log(routeFeature); var vectorSource = new ol.source.Vector({ features: [routeFeature] }); //vectorSource.addFeature(new ol.Feature(new ol.geom.Circle([5e6, 7e6], 1e6))); var vectorLayer = new ol.layer.Vector({ source: vectorSource, style: styleFunction }); var map = new ol.Map({ layers: [ new ol.layer.Tile({ source: new ol.source.XYZ({ urls : ["http://b.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png","http://b.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png","http://b.basemaps.cartocdn.com/light_all//{z}/{x}/{y}.png"] }) }), vectorLayer ], target: 'map', controls: ol.control.defaults({ attributionOptions: /** @type {olx.control.AttributionOptions} */ ({ collapsible: false }) }), view: new ol.View({ center: ol.proj.fromLonLat([103.986908, 1.353199]), rotation: 68*Math.PI/180, zoom: 18 }) }); map.getView().fit(extentToZoom,map.getSize()) </script> </body> </html> But know i want to draw different color line ie,for example in the sample i want the first line in green and the next line in blue(know it is in green itself) likewise there are too many plots i want to plot it in different colors Using multiString i am able to do it but for the sample above i dont know how to start with please point me to a sample or guide me how to do A: Add an attribute to each LineString feature you are adding, and in your styles array, add a style with the color you want, and in style function, use the attribute to select the relevant style from that array. Here I edited your code, <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <!-- <link rel="stylesheet" href="http://openlayers.org/en/v3.2.1/css/ol.css" type="text/css">--> </head> <body> <div id="map" class="map"></div> <link rel="stylesheet" href="http://openlayers.org/en/v3.12.1/css/ol.css" type="text/css"> <script src="http://openlayers.org/en/v3.12.1/build/ol.js"></script> <script> var styles = { 'greenRoute': new ol.style.Style({ stroke: new ol.style.Stroke({ color: 'green', width: 3 }) }), 'redRoute': new ol.style.Style({ stroke: new ol.style.Stroke({ color: 'red', width: 3 }) }) }; var styleFunction = function(feature, resolution) { return styles[feature.get("fName")]; }; var geojsonObject = { "type": "LineString", "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } }, "coordinates": [ [103.984865, 1.350197] ,[103.985188, 1.350903] ,[103.985376, 1.351149] ,[103.985477, 1.351341] ,[103.986155, 1.352857] ,[103.986195, 1.352982] ,[103.986248, 1.353248] ,[103.986393, 1.353593] ,[103.986564, 1.353550] ,[103.985175, 1.350160] ,[103.985138, 1.350069] ], "properties": { "distance": "21.452372", "description": "To enable simple instructions add: 'instructions=1' as parameter to the URL", "traveltime": "1228" } }; //console.log(geojsonObject.coordinates); var routeGeom = new ol.geom.LineString(geojsonObject.coordinates).transform('EPSG:4326','EPSG:3857'); var redRouteGeom = new ol.geom.LineString([ [103.984865, 1.350197] ,[103.985188, 1.350903] ,[103.985138, 1.350069] ]).transform('EPSG:4326','EPSG:3857'); var routeFeature = new ol.Feature({ geometry:routeGeom, fName: "greenRoute" }) var redRoute = new ol.Feature({ geometry:redRouteGeom, fName: "redRoute" }) var extentToZoom = routeGeom.getExtent(); console.log(extentToZoom); console.log(routeFeature); var vectorSource = new ol.source.Vector({ features: [routeFeature,redRoute] }); //vectorSource.addFeature(new ol.Feature(new ol.geom.Circle([5e6, 7e6], 1e6))); var vectorLayer = new ol.layer.Vector({ source: vectorSource, style : styleFunction }); var map = new ol.Map({ layers: [ new ol.layer.Tile({ source: new ol.source.XYZ({ urls : ["http://b.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png","http://b.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png","http://b.basemaps.cartocdn.com/light_all//{z}/{x}/{y}.png"] }) }), vectorLayer ], target: 'map', controls: ol.control.defaults({ attributionOptions: /** @type {olx.control.AttributionOptions} */ ({ collapsible: false }) }), view: new ol.View({ center: ol.proj.fromLonLat([103.986908, 1.353199]), rotation: 68*Math.PI/180, zoom: 18 }) }); map.getView().fit(extentToZoom,map.getSize()); var select_interaction = new ol.interaction.Select(); select_interaction.on("select", function (e) { // do something. e.element is the feature which was added var evt= e.selected; }); map.addInteraction(select_interaction); </script> </body> </html>
doc_4286
Until now people have been working in their own private repositories, but now we want to merge the entire project in a single repository. The question now is: how should the directory structure look? Should we have separate directories for each language, or should we separate it by component/project? How well does python/perl/java cope with a common directory layout? A: My experience indicates that this kind of layout is best: mylib/ src/ java/ python/ perl/ .../ bin/ java/ python/ perl/ stage/ dist/ src is your source, and is the only thing checked in. bin is where "compilation" occurs to during the build, and is not checked in. stage is where you copy things during the build to prepare them for packaging dist is where you put the build artifacts I put the module/component/library at the top of the hierarchy, because I build every module separately, and use a dependency manager to combine them as needed. Of course, naming conventions vary. But I've found this to work quite satisfactorily. A: I think the best thing to do would be to ensure that your various modules don't depend upon being in the same directory (i.e. separate by component). A lot of people seem to be deathly afraid of this idea, but a good set of build scripts should be able to automate away any pain. The end goal would be to make it easy to install the infrastructure, and then really easy to work on a single component once the environment is setup. (It's important to note that I come from the Perl and CL worlds, where we install "modules" into some global location, like ~/perl or ~/.sbcl, rather than including each module with each project, like Java people do. You'd think this would be a maintenance problem, but it ends up not being one. With a script that updates each module from your git repository (or CPAN) on a regular basis, it is really the best way.) Edit: one more thing: Projects always have external dependencies. My projects need Postgres and a working Linux install. It would be insane to bundle this with the app code in version control -- but a script to get everything setup on a fresh workstation is very helpful. I guess what I'm trying to say, in a roundabout way perhaps, is that I don't think you should treat your internal modules differently from external modules.
doc_4287
"type 'String' has no member 'playback'" func playSound() { guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return } do { try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: []) try AVAudioSession.sharedInstance().setActive(true) /* The following line is required for the player to work on iOS 11. Change the file type accordingly*/ player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue) /* iOS 10 and earlier require the following line: player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */ guard let player = player else { return } player.play() } catch let error { print(error.localizedDescription) } } A: I was looking around StackOverflow and I borrowed this piece of code which works, I don't know if its the conventional way of doing it though. Swift 4.2 import AVFoundation var player = AVAudioPlayer() let url = URL(fileURLWithPath: Bundle.main.path(forResource: "note1", ofType: "wav")!) do { player = try AVAudioPlayer(contentsOf: url) player.play() } catch { print("couldn't load file :(") } A: func playSound() { let soundURL = Bundle.main.url(forResource: selectedSoundFileName, withExtension: "wav") do{ audioPlayer = try AVAudioPlayer(contentsOf: soundURL!) audioPlayer.play() } catch { } } This is another variation that you might be able to try! Let me know if this format works for you. I built a xylophone app myself a long time ago inside of a Udemy course. Pretty much would be easier to put the sound files directly into your project and run them through there, than to pull them from anywhere in my opinion. this is the most "Swifty" way I could implement this for you. A: If you click jump to definition on AVAudioSession Xcode will open the raw source file for the class and from there you can view the structure of each method in the class. This is helpful for viewing the structure of each function and for determining the data parameters of each function. Additionally there are annotations above each variation of the class functions compatible for different iOS deployment targets, indicated by the @available(iOS 11.0, *) annotations. We're focusing on the open func setCategory function in this class. Helpful information in the raw source file Allowed categories: AVAudioSessionCategoryPlayback Allowed modes: AVAudioSessionModeDefault, AVAudioSessionModeMoviePlayback, AVAudioSessionModeSpokenAudio Allowed options: None. Options are allowed when changing the routing policy back to Default I edited the category and mode parameters in my function as follows: do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, mode: AVAudioSessionModeDefault, options: [.mixWithOthers, .allowAirPlay]) print("Playback OK") try AVAudioSession.sharedInstance().setActive(true) print("Session is Active") } catch { print(error) }
doc_4288
What is the best way to go about it? Maybe: 1. fork repo 2. make changes 3. update dependencies to use fork (4.) make pr to original repo A: I would advise not modifying the vendor directory yourself except for temporary debugging. Instead, in general the process today would be something like the following. * *For the sake of simplicity, remove the existing vendor directory while you work. (You'll rebuild it later with your changes.) $ rm -r ./vendor *Clone the upstream repo (or your own fork of the upstream repo) to a local directory. (Be sure to read the upstream maintainer's license, README, and/or contributing guide so that you understand their process for testing, code review, etc.!) $ git clone https://github.com/julian59189/somerepo As part of this step, you may need to add a go.mod file if the upstream repo doesn't already have one. $ pushd ./somerepo $ go mod init example.com/somerepo $ popd *Add a replace directive to your go.mod file to point the dependency to the fork. (For more detail, see Developing and testing against unpublished module code.) $ go mod edit -replace example.com/somerepo@someversion=./somerepo *Make and test the change in your local clone, and push it to your fork. Record the commit hash for later use. … $ go test ./... example.com/somerepo/... $ pushd ./somerepo $ git commit -a $ COMMIT=$(git rev-parse HEAD) $ git push $ popd *Send an upstream PR for the change, following the upstream author's instructions. *(optional) If you expect the PR to take a while to be merged, at this point you may want to update the replace directive to point to the published fork instead of the local clone. $ go mod edit -replace example.com/somerepo@someversion=github.com/julian59189/somerepo@$COMMIT $ go mod tidy Now anyone who checks out your repo and works within your module will use the fixed version, even if they re-run go mod vendor (for example, to pick up an unrelated fix in a different module). *(optional) Rebuild your local vendor directory, if you use one, with the replacement in effect, and commit the changes. At this point, your own module itself is fixed, but nobody who uses your module will see the fix (because you are not the authoritative owner of the upstream module). $ go mod vendor $ git add go.mod go.sum vendor $ git commit *Once the upstream PR is merged, drop your replace directive and update to the latest upstream. (If the upstream author hasn't tagged a release yet, you can use a pseudo-version by passing a specific commit hash to go get instead of latest; see Getting a specific commit using a repository identifier.) $ go mod edit -dropreplace=example.com/somerepo@someversion $ go get -d example.com/somerepo@latest $ go mod tidy $ go mod vendor # If you want to keep a vendor directory going forward. $ git add go.mod go.sum vendor $ git commit A: Regardless of the license, from a pragmatic point of view it depends a lot on the circumstances. * *If it is a critical bug affecting your production -> modifying vendor is probably the fastest way but the main drawback is that the fix should be cherry-picked each time the library is updated. *If is a nice to have thing or is not compromised in your backlog -> PR will benefit your project and also the community. Moreover, updating a version would be as easy as change it on the go.mod file. *Forking is the long path of modifying vendor, it has all drawbacks and one more: maintain an extra repository. In any case, avoid license restrictions with FREE software LIBRE is quite important.
doc_4289
I found one control that looks interesting (http://ammar.tawabini.com/2010/09/gridview-ajax-filter.html) but I'm wondering if there's some solution, which is more known / used / widespread / accepted by the community. A: DevExpress has awesome grid with filter builder: http://demos.devexpress.com/ASPxGridViewDemos/Filtering/FilterBuilder.aspx A: If you are using datasource controls you can use WhereParameters. LINQ -- Entity Framework You can use ControlParameters to populate from values in your search form. All this can be done with out any code behind. Do not confuse this with being easier or simpler but I think this is what you are looking for.
doc_4290
Is there any workaround for this? A: That's a basic fact of life for panels. It's not special to the TGridPanel, you will see the same effect for any control derived from TCustomPanel. The transparency is only supported when the application is themed. The grid panel is just a convenient way to layout your controls. If you want to support running unthemed then the simplest solution is to remove the TGridPanel and layout your controls manually. That's pretty much trivial to do. Handle the OnResize event of the control that currently contains the panel, and position your controls as desired.
doc_4291
class SGD(Optimizer): """ An optimizer that does plain Stochastic Gradient Descent (https://en.wikipedia.org/wiki/Stochastic_gradient_descent#Iterative_method) :param lr: the learning rate to use for optimization """ def __init__(self, lr): self.learning_rate = lr def run_update_rule(self, gradients, _): # :param gradients: a list of all computed gradient arrays # :return: a list of deltas for each provided gradient # TODO: implement SGD update rule and store the result in a variable called param_deltas (as a list) # HINT: it can be solved in a single line with a list comprehension ;) ### BEGIN SOLUTION param_deltas = [self.learning_rate * gradient for gradient in gradients] ### END SOLUTION return param_deltas I want to check run_update_rule() and more specifically the line param_deltas = [self.learning_rate * gradient for gradient in gradients] This is my yaml file. environment: Notebook evaluate: best generate_grader: true grader_diff_context_lines: 3 grader_diff_max_lines: 100 grader_problem_id: '1' grader_test_cases: - cases: 0: code: sgd_tests.SGD = SGD expected_output: sgd_tests.test_sgd() weight: 4.0 setup_code: '' name: deep learning I have come across https://docs.python.org/3/library/inspect.html this module in Python. But not sure how to achieve this.
doc_4292
Possible Duplicate: WCF service: app.config versus attributes or a mixture of both can i override the hard coded configuration with the app.config configuration? for example, i have this hard coded configuration: [ServiceBehavior(TransactionTimeout = "00:02:00")] public class DateTimeService : IDateTimeService { //.... } and i want to override this with app.config configuration, like this: <serviceBehaviors > <behavior name ="DateTimeService_serviceBehavior"> <serviceTimeouts transactionTimeout ="00:01:00"/> </behavior> </serviceBehaviors> is it possible ? also, is it possible to merge those configurations in case of different elements?
doc_4293
- (void)viewDidLoad { [super viewDidLoad]; RKURL *baseURL = [RKURL URLWithBaseURLString:@"http://192.168.1.12"]; RKObjectManager *objectManager = [RKObjectManager objectManagerWithBaseURL:baseURL]; objectManager.client.baseURL = baseURL; RKObjectMapping *markerMapping = [RKObjectMapping mappingForClass:[Marker class]]; [markerMapping mapKeyPath:@"la" toAttribute:@"lat"]; [markerMapping mapKeyPath:@"lo" toAttribute:@"lon"]; [markerMapping mapKeyPath:@"des" toAttribute:@"description"]; [objectManager.mappingProvider setMapping:markerMapping forKeyPath:@"markers"]; } - (void)sendGet { NSString *lat = @"53.334932"; NSString *lon = @"-0.543749"; NSString *dist = @"1000"; NSDictionary *queryParams; queryParams = [NSDictionary dictionaryWithObjectsAndKeys:lat, @"la", lon, @"lo", dist, @"d", nil]; RKObjectManager *objectManager = [RKObjectManager sharedManager]; RKURL *URL = [RKURL URLWithBaseURL:[objectManager baseURL] resourcePath:@"/get_markers.php" queryParameters:queryParams]; [objectManager loadObjectsAtResourcePath:[NSString stringWithFormat:@"%@?%@", [URL resourcePath], [URL query]] delegate:self]; } The above code is working and I am happily working with the returned data. However, I cannot POST a record to be inserted in the database. I think I can reuse the sharedManager and even possibly the mapping. I do not need to handle any return. I have tried numerous variations of the following snippets. To no avail. The first snippet is an attempt to reuse the manager and mapping. Ignoring the mapping scope in this pseudo code the obvious flaw is that I cannot work out how to POST to the correct URL resource (baseURL & '/insert_marker.php'). So I haven't actually tried this: - (void)postInsert { Marker *mkr = [Marker alloc]; mkr.lat = @"53.334933"; mkr.lon = @"-0.543750"; mkr.description = @"some words"; RKObjectManager *objectManager = [RKObjectManager sharedManager]; [objectManager.mappingProvider setSerializationMapping:[markerMapping inverseMapping] forClass:[Marker class]]; [[RKObjectManager objectManager] postObject:mkr delegate:nil]; } This second snippet runs but crashes the app. Clearly, this is confused between string and url types but the object manager post will not compile with url. I am very confused! - (void)postInsert { RKParams* params = [RKParams params]; [params setValue:@"53.334933" forParam:@"la"]; [params setValue:@"-0.543750" forParam:@"l0"]; [params setValue:@"some words" forParam:@"des"]; RKObjectManager *objectManager = [RKObjectManager sharedManager]; NSString *URL = [RKURL URLWithBaseURL:[objectManager baseURL] resourcePath:@"/add_marker.php"]; [objectManager.client post:URL params:params delegate:nil]; } So, how can I POST with params (hopefully reusing the sharedManager, maybe the mapping and not handling a return)? A: As posted in the comments, try using NSStrings instead of RKURL like this: NSString *baseUrl = @"https://mysite.com"; [RKObjectManager objectManagerWithBaseURLString:baseUrl]; If you want to make something more robust, you can also try to make a post using the objectManager instead the client on the objectManager, for example you can use blocks: - (void) post: (id) myEntity onLoad:(RKObjectLoaderDidLoadObjectBlock) loadBlock onError:(RKRequestDidFailLoadWithErrorBlock)failBlock showingLoader:(BOOL)loaderWillShow{ RKObjectMapping *mapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForClass:[[myEntity class] class]]; [[RKObjectManager sharedManager] postObject:myEntity usingBlock:^(RKObjectLoader *loader) { [self settingsForLoader:loader withMapping:mapping onLoad:loadBlock onError:failBlock showingLoader:loaderWillShow]; }]; } //Settings For Loader definition: - (void) settingsForLoader: (RKObjectLoader *) loader withMapping: (RKObjectMapping *) mapping onLoad:(RKObjectLoaderDidLoadObjectBlock) loadBlock onError:(RKRequestDidFailLoadWithErrorBlock)failBlock showingLoader:(BOOL) loaderWillShow{ loader.objectMapping = mapping; loader.delegate = self; loader.onDidLoadObject = loadBlock; loader.onDidFailWithError = ^(NSError * error){ //NSLog(@"%@",error); }; loader.onDidFailLoadWithError = failBlock; loader.onDidLoadResponse = ^(RKResponse *response) { [self fireErrorBlock:failBlock onErrorInResponse:response disablingLoader:loaderWillShow]; }; }
doc_4294
I tried different variants of overflow and animation-duration. HTML: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="styles.css"> </head> <body> <p> <img class="logo" src="picture.png" width="80" height="80" align='left'> <div id="marquee"> <div id="text">some text string exceeding the container</div> </div> </body> </html> CSS: @keyframes slide { from { left: 100%; } to { left: -100%; } } @-webkit-keyframes slide { from { left: 100%; } to { left: -100%; } } #marquee { color: #FE5501; background: #111; width: 100%; height: 80px; line-height: 80px; position: absolute; display: inline-block; top: 10px; left: 100px; overflow: hidden; text-overflow: hidden; white-space: nowrap; } #text { position: absolute; font-family: "Consolas"; display: inline-block; top: 0; text-align: center; font-weight: bold; left: 0; width: 100%; height: 80px; font-size: 40px; animation-name: slide; animation-duration: 5s; animation-timing-function: linear; animation-iteration-count: infinite; -webkit-animation-name: slide; -webkit-animation-duration: 5s; -webkit-animation-timing-function: linear; -webkit-animation-iteration-count: infinite; white-space: nowrap; } I would really kile to get a design where next to the logo I would have a an animation that could display a long text so that I could use this in a nice 'ui'. A: If I understand correctly what you want to do I think you just need to set a fixed width to your marquee div. For example : width: calc(100vw - 120px); see the codepen here : https://codepen.io/marc-simplon/pen/xoKYbJ?editors=1100 Edit: The issue was with your 'width: 100%', because % is a relative unit, relative to the parent element. So you need to have a parent element with a fixed size. Therefore this (for example), also works : body { width: 100vw; } #marquee { width: 50%; } Edit 2: After CorpoKillsMe's comment, I modified the live demo provided to make the entire title slide in the container's defined width. See : https://codepen.io/marc-simplon/pen/OeLwZv?editors=1100 * *I removed the position: absolute attribute and the related attributes (top, etc) of the #text selector. *Then I use transform: translate(-100%); instead of left in the keyframe. *And the important modification : I removed the width attribute in the #text selector (It would have work with the position: absolute and left trick, but I think the transform solution's more elegant)
doc_4295
I write a small piece of php. code: public function actionModbus() { $errors = array(); $warnings = array(); $connection = BinaryStreamConnection::getBuilder() ->setPort(80) ->setHost('192.168.56.205') ->setReadTimeoutSec(3) // increase read timeout to 3 seconds ->build(); $startAddress = 2165; $quantity = 1; $slaveId = 1; // RTU packet slave id equivalent is Modbus TCP unitId $tcpPacket = new ReadHoldingRegistersRequest($startAddress, $quantity, $slaveId); $rtuPacket = RtuConverter::toRtu($tcpPacket); try { $binaryData = $connection->connect()->sendAndReceive($rtuPacket); $warnings[] = 'RTU Binary received (in hex): ' . unpack('H*', $binaryData)[1] . PHP_EOL; $response = RtuConverter::fromRtu($binaryData); $warnings[] = 'Parsed packet (in hex): ' . $response->toHex() . PHP_EOL; $warnings[] ='Data parsed from packet (bytes):' . PHP_EOL; print_r($response->getData()); }catch (\Exception $exception) { $errors[] = $exception->getMessage(); $errors[] = $exception->getLine(); }finally { $connection->close(); } $result = array('errors'=>$errors,'warnings'=>$warnings); Yii::$app->response->format = Response::FORMAT_JSON; Yii::$app->response->data = $result; } But I want to write one in C#. Please tell me a library or an example in C# A: There are quite a few libraries available including EasyModbus and NModbus4 both of which have good documentation and samples (and are mentioned in recent stackoverflow questions).
doc_4296
I need to be able to have a list of this object, and the list can also be serialized to xml and de serialized from xml. I have tried dictionary type, but this is causing errors when serializing to xml. I am using object xml serialization for the serialization. What data type should I use? Does such a data type exist? Thanks EDIT I can serialize a List<string[]>, but am wondering if another data type does exist.
doc_4297
I want first div to expand to parent's or the second div's height according to the increment of the second div's height <div id ="main"> <div id ="first"> <a href="#">Link</a> <a href="#">Link</a> <a href="#">Link</a> <a href="#">Link</a> </div> <div id ="second"> <a href="#">Link</a> <a href="#">Link</a> <a href="#">Link</a> <a href="#">Link</a> <a href="#">Link</a> <a href="#">Link</a> <a href="#">Link</a> <a href="#">Link</a> </div> </div> . #main{ overflow:hidden; border:1px solid black; } #first{ border:1px solid black; width:200px; float:left; } a{ display:block; padding:10px; } #second{ border:1px solid black; overflow:hidden; } JSFiddle A: The solution for your problem is: first you have to give a height to the parent div and then set the height of the child, #first to min-height: 100%, the code would be like this: #main { overflow:hidden; border:1px solid black; height: 400px; } #first { border:1px solid black; width:200px; float:left; min-height: 100%; } A: You can use display: table; applied to the #main container and display:table-row; and display:table-cell; applied to #first and #second to make the first child container take the height of its sibling container #second. Remember to add overflow:auto; to allow the first container to make it expand its height until the bottom. CSS #main{ overflow:hidden; border:1px solid black; display:table; width:100%; } #first{ border:1px solid black; width:200px; float:left; display:table-row; overflow:auto; height:100%; } a{ display:block; padding:10px; } #second{ border:1px solid black; overflow:hidden; height:400px; display:table-cell; width:100%; } DEMO http://jsfiddle.net/a_incarnati/djobkh7t/7/ A: I've removed the floats and changed the display types on your divs to fix the problem. See example CSS + fiddle: #main{ border: 1px solid black; display: table; width: 500px; } #first{ border: 1px solid black; width: 25%; display: table-cell; } #second{ border: 1px solid black; width: 75%; display: table-cell; } http://jsfiddle.net/djobkh7t/13/ You can set the display type of 'table' on the parent div, then 'table-cell' on the child div's.
doc_4298
def _remove_nans(self): def get_without_nans(array): mask = np.invert(np.isnan(array)) return array[mask] self.average_dynamic_depth = get_without_nans(self.average_dynamic_depth) # ... many more similar lines to clear more arrays This works, but is hard to read and more importantly its easy to make copy&paste errors like: self.a = get_without_nans(self.b) # <= b instead of a! Is it possible to give the parameter name as a parameter to the function get_without_nans() insteads of an array? So that I could somehow call it like: get_without_nans("self.average_dynamic_depth") # or get_without_nans("average_dynamic_depth") ? A: You can use getattr and setattr. The code would look like: def _remove_nans(self): def get_without_nans(self, attrname): array = getattr(self, attrname, None) if array is not None: mask = np.invert(np.isnan(array)) setattr(self, attrname, array[mask]) else: raise AttributeError("some error message") get_without_nans(self, "average_dynamic_depth") # ... many more similar lines to clear more arrays
doc_4299
I've been playing around with printing to my Samsung printer using the Windows driver that came with it, and it seems to work great. I assume though that other printers may not come with Windows drivers and then I would be stuck? Or would I be able to simply use the Generic/Text Driver to print to any printer that supports it? For the cash drawer I would need to send codes directly to the COM port which is fine with me, if it saves me the hassle of helping clients setup OPOS drivers on there systems. Am I going down the wrong path here? A: This is probably a slightly different answer to what you were looking for(!)... When working with "external interfaces" (e.g. printers, cash draws etc) always abstract things. You probably want to implement strategies - Pattern Strategy. You make an interface for the cash draw: public interface ICashDrawer { void Open(); } The provide implementations: * *one strategy is a class that uses COM to open the draw *another is something as simple as a class that does a Debug.WriteLine call so you don't need a cash draw connected to your PC during development e.g. public class ComPortCashDrawer : ICashDrawer { public void Open() { // open via COM port etc } } public class DebugWriterCashDrawer : ICashDrawer { public void Open() { Debug.WriteLine("DebugWriterCashDrawer.Open() @ " + DateTime.Now); } } Again for printing you have a print interface that takes the data: public interface IRecieptPrinter { bool Print(object someData); } then you make one or more implementations. * *Basic printer *Specialized label printer *a text based one that saves to a file... e.g. public class BasicRecieptPrinter : IRecieptPrinter { public bool Print(object someData) { // format for a basic A4 print return true; // e.g. success etc } } public class SpecificXyzRecieptPrinter : IRecieptPrinter { public bool Print(object someData) { // format for a specific printer return true; // e.g. success etc } } public class PlainTextFileRecieptPrinter : IRecieptPrinter { public bool Print(object someData) { // Render the data as plain old text or something and save // to a file for development or testing. return true; // e.g. success etc } } With respect to the SDK, if down the track you find you need it for some reason you write implementations using the SDK. Over time you may end up with several ways to interface with different external devices. The client may get a new cash draw one day etc etc. Is that clear, I can flesh out what I mean if you want but you probably get my drift. Your app sets itself up with the respective implementations at startup, you may want to take a look at Dependency injection as well and you will find things easier if you use a container to resolve the types. var printer = container.Resolve<IRecieptPrinter>(); PK :-) A: I've never dealt programmatically with what you're asking, but I do have some experience when it comes to POS systems which may help you. What you do for printing and for the cash drawer are highly dependent on the hardware you're working with. And there is a wide variety of hardware out there. In every POS system I've seen, there are multitudes of drivers for every conceivable receipt printer and cash drawer, so unless you're developing a full-blown system, just concentrate on the specific hardware you're going to be working with. Even then, try to factor your code well so that you maximize the benefit of the strategy pattern. If you're working with more than one type of device, you'll thank yourself later for implementing it that way. For printing, there are 3 fundamental types of printers you may encounter: * *Receipt printer that can only print text (antiquated, but still around) *Receipt printer that can print graphics *A standard printer printing 8.5" x 11" full-page invoices/credit memos (easy, 'nuff said) I believe most, if not all, modern receipt printers fall into category #2, but you could run into a legacy system using a printer from category #1. For category #2, you should be able to use the standard .NET printing interface. The only issue may be sending a control code to activate the cutting mechanism (if equipped) at the appropriate time(s); or, the printer driver may do it automatically based on the paper length specified in the printing algorithm. Again, I've never tried this, but if you have access to a receipt printer, you should be able to figure this stuff out in a hurry. If you're dealing with a single client who has a printer in category #1, you can make a good argument that it will be less expensive to buy a new printer in category #2 than it will be to pay you to develop a dead-end driver to print on their existing hardware. For cash drawers, I'm less familiar than with printers, but I know of two options as far as communication and hardware arrangement: * *Attaches via LPT port through the printer. (Cable chain: computer --> printer --> cash drawer) *Attached directly to the computer, either by a COM/LPT port or probably USB in a modern one. The first kind operates by sending control codes to the printer port (which the printer would hopefully ignore and not spit out an entire roll of receipt paper), while for the second you'll need to do the COM port communication stuff. In either case, the control codes are hardware-dependent. Most of the time they're found in the user manual, but sometimes the technical writer was feeling particularly evil that day, and you'll have to go digging online. A: From just a quick browse the MS point-of-sale system is based on Window Embedded which is really just a way to get a lower cost per unit and smaller Windows OS license. It seems there are some APIs specific to POS, but you seem to want to roll your own, you'll still probably want to use Windows Embedded in some way. Security will probably be job 1. A: To control the receipt printer directly, read up on the ESC/POS commands. These commands will allow you to open the cash drawer and print barcodes and images on the receipts. However, as your using C#, it maybe be easier to use the Microsoft Point of Service class library.