id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23531000
I want to add granular details for every test at specific points (by function call on the Reporter object). Mocha custom reporter doc: https://mochajs.org/api/tutorial-custom-reporter.html
doc_23531001
Possible Duplicate: How do i rotate a window in xCode 4 interface builder tool thing? Is it possible to rotate : to landscape mode. I want my application to just support landscape mode therefore it will be easier if I could work on landscape mode with Xcode. I know how to rotate the view on the iPhone and iPad simulator but I actually want to rotate it in Xcode. A: It's under the Simulated Metrics section of the Attributes view.
doc_23531002
Update: new InjectionProperty("Age",25)) in InitContainer causing the exception. Code using Unity 3.0 public abstract class Person<T> where T : class { protected T profession; public Person(T profession) { this.profession = profession; } public abstract void WhoAreYou(); public int Age { get; set; } } public class Employee<T> : Person<T> where T : class { string personType; public Employee(T profession, string personType) : base(profession) { this.personType = personType; } public override void WhoAreYou() { Console.WriteLine("I am " + personType); Console.WriteLine("My age is " + Age); Console.WriteLine("Profession" + typeof(T).ToString()); } } public abstract class Profession { } public class Doctor : Profession { } class Program { static void Main(string[] args) { var container = InitContainer(); var p = container.Resolve<Person<Doctor>>(); p.WhoAreYou(); Console.ReadKey(); } static UnityContainer InitContainer() { UnityContainer container = new UnityContainer(); container.RegisterType(typeof(Person<>), typeof(Employee<>), new ContainerControlledLifetimeManager() , new InjectionConstructor(new GenericParameter("T"), "Employee"), new InjectionProperty("Age",25)); return container; } } A: Looks like you actually found a bug in Unity! This issue only occurs when you attempt to use the combination of an InjectionProperty on an inherited property with an open generics registration. This should be a supported scenario. I was able to reproduce this issue on Unity 3.0, 3.5, and 4.0 (latest). Any of the following fixes the issue... * *Remove generics *Change to closed generics registration *Move the property to the concrete class *Make the property abstract or virtual on the base class *Set the property in a different way other than using an InjectionProperty
doc_23531003
My issue is when I am clicking next button my page is refreshing. please help me to find this issue. My code and screen shot are given below. In firefox firebug console showing some error "TypeError: Argument 1 of Window.getDefaultComputedStyle is not an object." js #abilitytest: Click function for showing data in bootstrap model $( "#abilitytest" ).click(function() { $.post("/abilitytest", function(response){ $( "#abilityQuestions" ).html(response); }); }); $('.pagination a').on('click', function (event) { event.preventDefault(); var page = $(this).attr('href'); console.log(page); alert('hai'); }); Controller $abilitytests = Abilitytest::simplePaginate(1); return view('test.abilitytestmodal',['abilitytests' => $abilitytests]); A: Maybe there some trouble with binding event listener on $('.pagination a')? Try $(document).on('click', '.pagination a', function(event){ Instead of $('.pagination a').on('click', function (event) { A: Currently I am using laravel pagination built-in function simplePaginate(). Abilitytest::simplePaginate(1) the ul class of pagination will be class="pager".<ul class="pager">. If we are using laravel built-in function paginate() the ul class of pagination will be class="pagination".. So the issue is I am using wrong class name in JS file "<ul class="pagination">". So my code is $('.pager a').on('click', function (event) { event.preventDefault(); var page = $(this).attr('href'); console.log(page); alert('hai'); }); THanks A: you can use jQuery on document ready like this $(document).ready(function (){ $('.pagination a').on('click', function (event) {
doc_23531004
Unicode point number is U+0760 (I get it from https://unicode.scarfboy.com/) If the SQL is run using dbaccess the update works. If the character is replaced with different arabic character, the update works both in JDBC and dbaccess. DB_LOCALE is en_US.utf8 . Thank you in advance. The table create table tbl_demo_1 ( id serial not null, address varchar(100), primary key(id) ); insert into tbl_demo_1 values (1,'somevalue'); The SQL update tbl_demo_1 set address2 = 'BT. 8 ݠ MAIN ROAD' where id = 1; OS, IDS, JDK, JDBC * *OS : CentOS 8 *IDS : IBM Informix Dynamic Server Version 14.10.FC4W1DE *JDK : 1.8.0_172 *JDBC: 4.10.14, 4.50.7 *SQL client: SQuirrel SQL client, SQL Workbench/J A: When working with UTF-8 Informix databases is recommended to use the ICU libraries rather than the Informix GLS ones because ICU supports a more wider range. To enable ICU use make sure the GL_USEGLU environment variable is set to either 1 or 4 before the server is started and the database is created. More info here: https://informix.hcldoc.com/14.10/help/index.jsp?topic=%2Fcom.ibm.glsug.doc%2Fids_gug_063.htm Depending on your API (like JDBC or .NET) you may also need to include GL_USEGLU in the connection string for it to work properly.
doc_23531005
2012-10-15 12:14:15,865 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /bootstrap/css/bootstrap-responsive.css 2012-10-15 12:14:15,866 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /kickstart/css/docs.css 2012-10-15 12:14:15,867 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /kickstart/css/kickstart.css 2012-10-15 12:14:15,867 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /datepicker/css/datepicker.css 2012-10-15 12:14:15,868 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /bootstrap/js/bootstrap.js 2012-10-15 12:14:15,868 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /datepicker/js/bootstrap-datepicker.js 2012-10-15 12:14:15,869 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /kickstart/js/kickstart.js 2012-10-15 12:14:17,506 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /bootstrap/css/bootstrap.css 2012-10-15 12:14:17,506 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /bootstrap/css/bootstrap-responsive.css 2012-10-15 12:14:17,507 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /kickstart/css/docs.css 2012-10-15 12:14:17,507 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /kickstart/css/kickstart.css 2012-10-15 12:14:17,508 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /datepicker/css/datepicker.css 2012-10-15 12:14:17,508 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /bootstrap/js/bootstrap.js 2012-10-15 12:14:17,509 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /datepicker/js/bootstrap-datepicker.js 2012-10-15 12:14:17,509 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /kickstart/js/kickstart.js 2012-10-15 12:14:19,042 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /bootstrap/css/bootstrap.css 2012-10-15 12:14:19,043 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /bootstrap/css/bootstrap-responsive.css 2012-10-15 12:14:19,043 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /kickstart/css/docs.css 2012-10-15 12:14:19,044 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /kickstart/css/kickstart.css 2012-10-15 12:14:19,044 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /datepicker/css/datepicker.css 2012-10-15 12:14:19,045 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /bootstrap/js/bootstrap.js 2012-10-15 12:14:19,045 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /datepicker/js/bootstrap-datepicker.js 2012-10-15 12:14:19,045 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /kickstart/js/kickstart.js 2012-10-15 12:14:20,248 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /bootstrap/css/bootstrap.css 2012-10-15 12:14:20,249 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /bootstrap/css/bootstrap-responsive.css 2012-10-15 12:14:20,249 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /kickstart/css/docs.css 2012-10-15 12:14:20,250 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /kickstart/css/kickstart.css 2012-10-15 12:14:20,250 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /datepicker/css/datepicker.css 2012-10-15 12:14:20,251 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /bootstrap/js/bootstrap.js 2012-10-15 12:14:20,251 [http-28586-1] ERROR resource.ResourceMeta - Resource not found: /datepicker/js/bootstrap-datepicker.js 2012-10-15 12:14:20,252 [http-28586-1] ERROR resource.ResourceMeta - Resource not This app uses in-line plugins located in a folder caled "plugins" at the root. I then have this code in the BuildConfig.groovy to reference the plugins: grails.plugin.location.'spring-security-ui'="plugins/grails-spring-security-ui" grails.plugin.location.'kickstart-with-bootstrap'="plugins/ui" I only started getting this issue deploying the apps to the cloud once I used in-line plugins and never had this issue before:-S Can anyone please help me with this as its very annoying and I believe its being caused by the "resources" plugin. Just to note I have made sure that the code below is in the config.groovy file: grails.resources.adhoc.patterns = ['/images/*', '/css/*', '/js/*', '/plugins/*'] A: I fixed this by moving the resource into the right location as they were located somewhere different :S Thanks for the help! A: Have you tried using a similar approach to the solution explained here; Heroku, Grails: Missing resources if using multiple web dynos Regardless of the focus on multiple dynos it looks like it may be a similar issue.
doc_23531006
I need to send baseurl to my service so that i dynamically set the baseurl to my APIEndpoints. grunt serve baseurl:'http:111.111.11.11' Is there any way to do so using grunt cli ? Any help is highly appreciated.. thanks in advance
doc_23531007
Here is the button I want to click: Sign up I get the error: "UnhandledPromiseRejectionWarning: NoSuchElementError: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="email"]"}" I don't have any idea why it doesnt find this element. I put a long sleep, I can see this element, but Selenium does not. Whole page: var By = webdriver.By; var driver; class signUpPage { constructor() { driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build(); } typeCorrectEmail() { driver.findElement(By.xpath('//*[@id="email"]')); } clickSignUpButton() { driver.findElement(By.id("signup")).click(); } } module.exports = new signUpPage();``` tests.js file: ```var webdriver = require('selenium-webdriver'); var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build(); var homePage = require('./homePage'); var signUpPage = require('./signUpPage'); homePage.navigateToTrello(); driver.sleep(5000); homePage.clickSignInButton(); driver.sleep(10000); signUpPage.typeCorrectEmail();``` A: Type $x('//*[@id="email"]'), into the developer console to validate and see if the locator exists - does it show up? The first step is to see if this is a valid locator, if so then there is a problem with the code you have written. If it doesn't show up, you need to find another way to identify the element. More information here: https://yizeng.me/2014/03/23/evaluate-and-validate-xpath-css-selectors-in-chrome-developer-tools/
doc_23531008
i.e the user posts something and that post is duplicated in many tables for fast retrieval. But when that post changes (with an edit) it needs to be updated throughout the database, in all tables that contain that post (in tables that have different and unknown primary keys). Solutions I'm thinking of: * *Have a mapper table to track down the primary keys in all those tables, but it seems to lead to tables explosion (post is not the only property that might change). *Use Solr to do the mapping, but I fear I would be using it for the wrong purpose. Any enlightenments would be appreciated. EDIT (fictional schema). What if the post changes? or even the user's display_name? CREATE TABLE users ( id uuid, display_name text, PRIMARY KEY ((id)) ); CREATE TABLE posts ( id uuid, post text, poster_id uuid, poster_display_name text tags set<text>, statistics map<int, bigint>, PRIMARY KEY ((id)) ); CREATE TABLE posts_by_user ( user_id uuid, created timeuuid, post text, post_id uuid, tags set<text>, statistics map<int, bigint>, PRIMARY KEY ((id), created) ); A: It depends on the frequency of the updates. For instance, if users only update their names infrequently (a handful of time per user account), then it may be ok to use a secondary index. Just know that using a 2i is a scatter gather, so you'll see performance issues if it's a common operation. In those cases, you'll want to use a materialized view (either the ones in 3.0 or manage it yourself) to be able to get the list of all the posts for a given user, then update the user's display name. I recommend doing this in a background job, and giving the user a message like "it may take [some unit of time] for the change in your name to be reflected everywhere".
doc_23531009
My question is regarding a very primitive case of, what i believe to be, a compiler bug during initialization of non-local static (global) variables. I created a simple test-case to show the issue: int direct_init_var = 0xFEED; int direct_init_array[ 4 ] = { 0xDE, 0xCA, 0xFB, 0xAD }; int deref_init_var = direct_init_array[ 0 ]; int main( void ) { return 0; } As far as I understand it, this should pose no problem and deref_init_var shall be initialized to the value 0xDE. The initialization may happen after prior zero-init and, in newer standards, maybe even after the first call to main() but before any odr-use of the variable. From the C++98 Standard: Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place. A reference with static storage duration and an object of POD type with static storage duration can be initialized with a constant expression (5.19); this is called constant initialization. Together, zero-initialization and constant initialization are called static initialization; all other initialization is dynamic initialization. Ok, so I had a look at the assembly the compiler generated and I believe here is where the problem lies. This snippet shows the symbols for the declared and initialized variables: .section/data data1; .align 1; _direct_init_var: .global _direct_init_var; .type _direct_init_var,STT_OBJECT; .var = 0xFEED; ._direct_init_var.end: .align 1; _direct_init_array: .global _direct_init_array; .type _direct_init_array,STT_OBJECT; .var = 0x00DE,0x00CA,0x00FB,0x00AD; ._direct_init_array.end: .align 1; .global _deref_init_var; .type _deref_init_var,STT_OBJECT; .var _deref_init_var[1]; ._deref_init_var.end: For me, this seems to be malformed. The start symbol of _deref_init_var is not even defined and it appears to reference itself for initialization. I would have expected the following output: .section/data data1; .align 1; _direct_init_var: .global _direct_init_var; .type _direct_init_var,STT_OBJECT; .var = 0xFEED; ._direct_init_var.end: .align 1; _direct_init_array: .global _direct_init_array; .type _direct_init_array,STT_OBJECT; .var = 0x00DE,0x00CA,0x00FB,0x00AD; ._direct_init_array.end: .align 1; _deref_init_var: .global _deref_init_var; .type _deref_init_var,STT_OBJECT; .var _direct_init_array[0]; ._deref_init_var.end: Or even direct expansion of the initialization value: _deref_init_var: .global _deref_init_var; .type _deref_init_var,STT_OBJECT; .var = 0x00DE; ._deref_init_var.end: When I compile this program with MSVC (within a test-harness we use for debugging) I get this output for the variable in question: ?deref_init_var@@3FA DW DEH ; deref_init_var Am I wrong in blaming the VisualDSP++ compiler here? Thanks in advance, any input is greatly appreciated! EDIT: I think I overlooked a major problem in the whole system design. The application in question is loaded during runtime by an "OS" that calls certain functions within the application through a jump-table. I will have to investigate a bit, but i believe there is no dynamic initialization happening at all. Thanks for your comments, I totally misinterpreted what was happening.
doc_23531010
I am using foundation to build a website, the way I have built the nav bar is as follows: HTML: <nav class="top-bar"> <ul> <li><a href="about.html">About</a></li> <li id="menu-divider">|</li> <li><a href="testimonials.html">Testimonials</a></li> <li><a href="index.html"><img src="images/logo.png" alt=""></a></li> <li><a href="services.html">Services</a></li> <li id="menu-divider">|</li> <li><a href="contact.html">Contact</a></li> </ul> </nav> CSS: .top-bar { font-family: 'bebas_neueregular'; height: 150px; line-height: 100px; padding: 18px; width: 100%; position: relative; text-align:center; margin-bottom:10px; } .top-bar ul { display:inline-block; margin-left: auto ; margin-right: auto ;} .top-bar ul > li { display:inline-block; margin-left: auto ; margin-right: auto ;} #menu-divider { color:#ffffff; font-size: 24px;} As you can see in the picture, the way I have built it means that my center li element (my logo picture) is not in exact center as the other li elements are of different widths meaning they are all centered collectively. What I'm after is the logo in the dead center then the other li elements as they are centered around the logo. Thanks in advance for any help! A: You can play around but I'm pretty sure this does the trick: http://codepen.io/anon/pen/dYXQpz Use 3 containers (that means you lose your nav as a ul). Flex them and inside of the left and right one, flex the elements (end for the first, start for the other) <div class="nav-bar"> <div class="sideNav leftNav"> <div class="menu"> MENU 1 </div> <div class="split"></div> <div class="menu"> MENU 2 </div> </div> <div class="logo"> <img src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSN9qhGx6NftAepiMOjdGXkcW-UxkO9dtQ4VGRlepyzNC2S8xQCcA" /> </div> <div class="sideNav rightNav"> <div class="menu"> MENU 3 </div> <div class="split"></div> <div class="menu"> MENU 4 </div> </div> </div> Then apply the css. It can be improved but it can help you get started. .nav-bar { background: pink; display: flex; } .sideNav { flex: 1 0 auto; background: red; display: flex; } .leftNav { justify-content: flex-end; } .rightNav { justify-content: flex-start; } .sideNav > div { margin: 100px 20px 0 20px; } .split{width: 2px;background: white;height: 16px} Hope that helps. I loves flexbox.
doc_23531011
The Nancy convention is to store static content in /Content and the ASP.Net Core convention is to store it in /wwwroot, but I can't get my app to recognize either. My Startup.Configure method looks like this: public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseStaticFiles(); app.UseOwin(b => b.UseNancy()); } And my module route looks like this: Get("/big_file", _ => { return Response.AsFile("wwwroot/test.zip"); }); But Nancy always returns a 404 when I hit this route. I've also tried directing ASP.Net Core to the static directory expected by Nancy, like this: app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"Content")), RequestPath = new PathString("/Content") }); But this didn't work either. I've tried putting the file in /Content and in /wwwroot with the same result. And I've tried different casing of Content, but nothing seems to work. What am I missing? A: I figured it out. The issue was that I needed to let Nancy know what I wanted to use as the root path for the application. I did this by creating a class that inherits from IRootPathProvider. Nancy will discover any class that inherits from this on Startup, so you can put it wherever you want. public class DemoRootPathProvider : IRootPathProvider { public string GetRootPath() { return Directory.GetCurrentDirectory(); } } Once this was in place I was able to access static content in /Content. Additionally, I was able to add additional static directories (for example, if I wanted to stick with /wwwroot) by adding a class that inherits from DefaultNancyBootstrapper. Again, Nancy will find this on Startup, so you can put it anywhere. public class DemoBootstrapper : DefaultNancyBootstrapper { protected override void ConfigureConventions(NancyConventions conventions) { base.ConfigureConventions(conventions); conventions.StaticContentsConventions.Add( StaticContentConventionBuilder.AddDirectory("wwwroot") ); } }
doc_23531012
Please help me find the appropriate method here. Here is the HTML code, for reference: <select name="list" onchange="this.disabled=true;if(this.options[selectedIndex].value == '')this.disabled=false;else optionselect(this);" onfocus="hint('')"> And, these are the methods, I tried. Method-1: new Select(driver.findElement(By.xpath("xpath"))).selectByVisibleText("Text*"); new Select(driver.findElement(By.name("list"))).selectByVisibleText("Text"); Method-2: (I tried to use every possible approach to identify the dropdown element by name, abs xpath, rel xpath, cssSelector etc., but nothing seeems to identify the element) Select sel = new Select(element); sel.selectByValue("Value"); Thread.sleep(5000); Method-3: Select sel = new Select(element); sel.selectByIndex(11); Thread.sleep(5000); Method-4: Select select = new Select(driver.findElement(By.name("list"))); select.selectByVisibleText("Text"); I'm guessing the issue in all the above methods lies in identifying the drop down element. But I'm really not sure what's wrong here. A: Try with the below. WebElement dd= driver.findElement(By.xpath("//select[@name='list']")); Select s=new Select(dd); s.selectByIndex(1); A: Maybe you will have some luck using Actions? (use Firefox or Chrome, IE behaves weird when doing hover actions) Actions actions = new Actions(driver); WebElement hoverElement = driver.findElement(By.name("list")); Select sel = new Select(element); // hover over the element actions. moveToElement(hoverElement). perform(); // now maybe all of your approaches would work // sel.selectByIndex(11); // sel.selectByValue("Value"); // sel.selectByVisibleText("Text"); // or just find and click your desired element: WebElement targetElement = driver.findElement(targetElementLocator); actions. moveToElement(targetElement). click(). perform();
doc_23531013
However, the response keeps saying that my "Post data is empty", and I can't figure out why. I tested it with websites like https://reqbin.com/ with the data that is stored in my table and it works fine, since I get a "successful" response. Can someone help me figure out why my data keeps being emptied? Below is my code $url = "url that im trying to post Json to."; $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($json_object)); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); $result = curl_exec($ch); I've also tried using the http_build_query but it does not work. Thanks in advance! A: PHP recognizes application/x-www-form-urlencoded standard data type by default // one $post = $GLOBALS['HTTP_RAW_POST_DATA']; // two $post = file_get_contents("php://input");
doc_23531014
I need all the features of the Firefox address bar, but I want to control the "history" from which the suggestions are made. This is for Winforms or WPF. A: I doubt it; it's effectively just an editable ComboBox. It would be pretty easy to replicate in WPF. Is there any part of the control you think would be difficult to implement?
doc_23531015
public class Request { public String name; @JsonUnwrapped @JsonInclude(JsonInclude.Include.NON_NULL) public DateOfBirth dateOfBirth; } public class DateOfBirth { public int day; public int month; public int year; } { "name" : "John Doe" } Deserealization of this JSON creates a Request object with name John Doe and dateOfBirth with day, month and year 0. How can I override this behaviour so that dateOfBirth is null. Worth noting that on removing @JsonUnwrapped annotation, such JSON is deserealized into null object, so I feel like I am missing some trick here. Jackson version - 2.13.1
doc_23531016
I have a Tag model, and each tag has_many resources :through => resource tags. Each resource also has_many tags. I need to know the number of resource each tag has (I dont care about the other way around). The problem is it says unkown key cache_counter This is my model Tag.rb has_many :resource_tags, :dependent => :destroy, :counter_cache => :resource_count has_many :resources, :through => :resource_tags Resource.rb has_many :resource_tags, :dependent => :destroy has_many :tags, :through => :resource_tags My migration: class CreateTags < ActiveRecord::Migration def change create_table :tags do |t| t.string :name t.integer :resource_count, :default => 0 t.timestamps end end end A: :counter_cache option is for belongs_to method in resorce_tag model belongs_to :tag, :counter_cache => :resource_count and i think it is better to name column resources_count (plural)
doc_23531017
public class CustomAdapter extends BaseAdapter { Context c; CustomAdapter(Context c) { this.c=c; } @Override public int getCount() { // TODO Auto-generated method stub return 3; } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return arg0; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub final int pos=position; LayoutInflater inflater=LayoutInflater.from(c); View v=inflater.inflate(R.layout.layout_list_item, parent, false); ImageButton image_button=v.findViewById(R.id.imagebutton); image_button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(c, "Image Button clicked:" + pos, Toast.LENGTH_SHORT).show(); } }); return v; } } How do I make all imagebuttons clickable? I tried searching for answers and as per an answer given here: how to make an imageview clickable in an listview I tried but only my first row button is clickable. Please help. A: In your custom adapter constructor LayoutInflater mInflater; CustomAdapter(Context c) { mInflater = LayoutInflater.from(c); // initialize inflater in the constructor. // need not initialize everytime getView is called. } Use a View Holder http://developer.android.com/training/improving-layouts/smooth-scrolling.html static class ViewHolder { ImageButton ib; } @Override public View getView(int position, View item, ViewGroup parent) { ViewHolder holder; if(item == null){ item = mInflater.inflate(R.layout.elementos_lista_temas, null); holder = new ViewHolder(); holder.ib = (ImageButton) item.findViewById(R.id.imagebutton); item.setTag(holder); } else{ holder = (ViewHolder)item.getTag(); } return item; } Then in your activity class ListView lv = (ListView) findViewById(R.id.listview); CustomAdapter cus = new CustomAdapter(this); lv.setAdapter(cus); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> listView, View itemView, int itemPosition, long itemId) { Toast.makeText(ActivityName.this, "Image Button clicked:" + itemPosition, Toast.LENGTH_SHORT).show(); } }); A: As told by "the World of Listview-2010" see below link show how to use viewholder class with custom listview in android http://impressive-artworx.de/2011/list-all-installed-apps/ Hope this helps you.
doc_23531018
def _gram_matrix(self, F, N, M): print("in gram") F = np.reshape(F,(M,N)) F_trans = np.transpose(F) return np.dot(F,F_trans) def _single_style_loss(self, a, g): print("in single style loss") print("a shape ",a.shape) N = a.shape[3] M = a.shape[1]*a.shape[2] gram_a = self._gram_matrix(a,N,M) gram_g = self._gram_matrix(g,N,M) print("out of gram") multiplier = 1/(4*N*N*M*M) print("leaving single style loss") return_val = np.subtract(gram_a,gram_g) print("subtract was fine") return_val = np.square(return_val) print("square was fine") array_sum = np.sum(return_val) print("sum was fine") array_sum = multiplier*array_sum print("multiplier was fine") print("going to return ",array_sum) return array_sum def _style_loss(self, A): print("in style loss") loss = 0; with tf.Session() as sess: sess.run(self.input_img.assign(self.initial_img)) generated_layers = sess.run([getattr(self.vgg,layer) for layer in self.style_layers]) sess.run(self.input_img.assign(self.style_img))#reset input_img to style img for i in range(len(self.style_layer_w)): print("len ",self.style_layer_w) print("len generated layers",len(generated_layers)) print("len style layers",len(A)) loss += self.style_layer_w[i]*self._single_style_loss(A[i],generated_layers[i]) print("loss ",loss) self.style_loss = loss print("out of style loss") so the error I get is: "leaving single style loss Killed: 9" This is why I conclude the next line (the np.subtract line) is the problem. Sadly, I do not know why this line is a problem and I would greatly appreciate whatever insight anyone could offer. Thanks!
doc_23531019
I've got this Dictionary and would like to use its keys to set properties as in the foreach below. I don't know if this is at compile or runtime, my guess is compile time... I put *limb* in as pseudo-code for how I'm imagining it might work. The property mechDef.Head is an object of type LocationLoadoutDef with its property CurrentInternalStructure being float. Hope that makes sense! Much obliged for any assistance. public class Settings { public readonly Dictionary<string, bool> LimbRepair = new Dictionary<string, bool> { { "Head", false }, { "LeftArm", false }, { "RightArm", false }, { "CenterTorso", false }, { "LeftTorso", false }, { "RightTorso", false }, { "LeftLeg", false }, { "RightLeg", false }, }; } MechDef mechDef = new MechDef (__instance.DataManager.MechDefs.Get(id), __instance.GenerateSimGameUID()); foreach (string limb in settings.LimbRepair.Keys) { if (!settings.LimbRepair[limb]) { mechDef.*limb*.CurrentInternalStructure = Math.Max (1f, mechDef.*limb*.CurrentInternalStructure * (float)rng.NextDouble()); } A: You can do it with Reflection, but.... This is quite easy to do with Reflection, and you'll probably get a couple answers on here that show you how, but since you are writing a game, I'm guessing you want the best performance possible, and Reflection isn't always going to give you that. Below is a solution that requires no reflection but still allows you to use the loop structure you want. It just requires a little bit of setup when you create the object, then you can access your properties as if they were in a dictionary. Solution: Use a dictionary of delegates to map the properties First we need to write a utility class that represents a property. Since properties can be different types, this is a generic class with a type argument. class PropertyWrapper<T> { private readonly Func<T> _getter; private readonly Action<T> _setter; public PropertyWrapper(Func<T> getter, Action<T> setter) { _getter = getter; _setter = setter; } public T Value { get { return _getter(); } set { _setter(value); } } } The idea behind this class is that you create it to represent any property you want, and call its methods to read and set the property. The class knows how to read and set the property because you tell it how, when you construct it, by passing it a short lambda expression that does the work. This utility will allow you to put all the properties that represent limbs into a dictionary. Then you can look them up by string, just like your settings. So for example your MechDefinition might look like this: class MechDef { public Limb Head { get; set; } public Limb LeftArm { get; set; } public Limb RightArm { get; set; } public Limb LeftTorso { get; set; } public Limb RightTorso { get; set; } public Limb CenterTorso { get; set; } public Limb RightLeg { get; set; } public Limb LeftLeg { get; set; } private readonly Dictionary<string, PropertyWrapper<Limb>> Properties; public MechDef() { Properties = new Dictionary<string, PropertyWrapper<Limb>> { {"Head", new PropertyWrapper<Limb>( () => Head, v => Head = v ) }, {"LeftArm", new PropertyWrapper<Limb>( () => LeftArm, v => LeftArm = v ) }, {"RightArm", new PropertyWrapper<Limb>( () => RightArm, v => RightArm = v ) }, {"CenterTorso",new PropertyWrapper<Limb>( () => CenterTorso, v => CenterTorso = v )}, {"RightTorso", new PropertyWrapper<Limb>( () => RightTorso, v => RightTorso = v ) }, {"LeftTorso", new PropertyWrapper<Limb>( () => LeftTorso, v => LeftTorso = v ) }, {"RightLeg", new PropertyWrapper<Limb>( () => RightLeg, v => RightLeg = v ) }, {"LeftLeg", new PropertyWrapper<Limb>( () => LeftLeg, v => LeftLeg = v ) } }; foreach (var property in Properties.Values) property.Value = new Limb(); } public Limb this[string name] { get { return Properties[name].Value; } set { Properties[name].Value = value; } } } Yes, there is a bit of setup there, but it's all in one place, and it only executes once, when you instantiate the MechDef. Now you can access all of the limbs by string: foreach (var pair in settings.LimbRepair) { if (pair.Value != false) continue; var limb = mechDef[pair.Key]; limb.CurrentInternalStructure = Math.Max ( 1.0F, limb.CurrentInternalStructure * (float)rng.NextDouble() ); } Link to DotNetFiddle example A: You can create a DynamicObject to create your own dynamic Dictionary, See the explanation here Assume that you want to provide alternative syntax for accessing values in a dictionary, so that instead of writing sampleDictionary["Text"] = "Sample text", you can write sampleDictionary.Text = "Sample text". This is the example from the same MSDN article above: public class DynamicDictionary : DynamicObject { // The inner dictionary Dictionary<string, object> dictionary = new Dictionary<string, object>(); public int Count { get { return dictionary.Count; } } // If you try to get a value of a property not defined // in the class, this method is called. public override bool TryGetMember(GetMemberBinder binder, out object result) { // Converting the property name to lowercase so // that property names become case-insensitive. string name = binder.Name.ToLower(); // If the property name is found in a dictionary, set the result parameter // to the property value and return true. Otherwise, return false. return dictionary.TryGetValue(name, out result); } // If you try to set a value of a property that is not // defined in the class, this method is called. public override bool TrySetMember(SetMemberBinder binder, object value) { // Converting the property name to lowercase so that // property names become case-insensitive. dictionary[binder.Name.ToLower()] = value; // You can always add a value to a dictionary, so this method always returns true. return true; } } And this is how you can use your DynamicDictionary: dynamic person = new DynamicDictionary(); // Adding new dynamic properties. The TrySetMember method is called. person.FirstName = "Ellen"; person.LastName = "Adams"; A: Reflection is one way to get at it. https://stackoverflow.com/a/1954663/83250 actually answers this perfectly. I would however restructure your data so the mechDef object is another dictionary but if you must keep it like your question asks, this will work: void Main() { Dictionary<string, bool> limbRepair = new Dictionary<string, bool> { { "Head", false }, { "LeftArm", false }, { "RightArm", false }, // Etc. }; MechDefinition mechDef = new MechDefinition(); List<Limb> limbs = new List<Limb>(); foreach (KeyValuePair<string, bool> limbsToRepair in limbRepair.Where(x => !x.Value)) { Limb limb = mechDef.GetPropValue<Limb>(limbsToRepair.Key); limb.CurrentInternalStructure = 9001; } } public class MechDefinition { public MechDefinition() { Head = new Limb { Id = Guid.NewGuid(), DateAdded = DateTime.Parse("2018-01-01"), Name = "Main Head", CurrentInternalStructure = 8675309 }; } public Guid Id { get; set; } public string Name { get; set; } public int CurrentInternalStructure { get; set; } public Limb Head { get; set; } = new Limb(); public Limb LeftArm { get; set; } = new Limb(); public Limb RightArm { get; set; } = new Limb(); // etc... } public class Limb { public Guid Id { get; set; } public string Name { get; set; } public DateTime DateAdded { get; set; } public int CurrentInternalStructure { get; set; } public bool IsDisabled { get; set; } } public static class ReflectionHelpers { public static object GetPropValue(this object obj, string name) { foreach (string part in name.Split('.')) { if (obj == null) { return null; } Type type = obj.GetType(); PropertyInfo info = type.GetProperty(part); if (info == null) { return null; } obj = info.GetValue(obj, null); } return obj; } public static T GetPropValue<T>(this object obj, string name) { object retval = GetPropValue(obj, name); if (retval == null) { return default(T); } // throws InvalidCastException if types are incompatible return (T)retval; } } Be aware that reflection is a very costly operation. If you are dealing with large sets of data, it will be very inefficient. Take a look at https://stackoverflow.com/a/7478557/83250 for a performance overview. Also code-wise, I prefer to stay away from dynamic and reflection altogether. Reflection has its perks when you need to access a property attribute and dynamic is great if you don't have a strongly typed object. With that said, C# is a strongly typed language and should be treated as such whenever possible. By restructuring your mechDef as a Dictionary<string, Limb> object or something similar you will have a more efficient application. A: You can always create classic and working if .. else or switch. Or create dictionary with function to update correct property public class Repair { public bool Active { get; set; } public Action<MechDef> Update { get; set; } } public class Settings { public readonly Dictionary<string, Repair> LimbRepair = new Dictionary<string, bool> { { "Head", new Repair { Active = false, mechDef => mechDef.Head.CurrentInternalStructure = yourFunctionForHead } }, { "LeftArm", new Repair { Active = false, mechDef => mechDef.LeftArm.CurrentInternalStructure = yourFunctionForLeftArm } }, // ... and so on }; } Then in the loop you will call correct update action, become much cleaner to use settings class with benefits of strong types and compiler help which prevent dynamic runtime errors var updates = settings.LimbRepair.Where(pair => pair.Value.Active == false) .Select(pair => pair.Value); foreach (var repair in updates) { repair.Update(); } A: If I understand correctly, You have something like this: class LocationLoadoutDef { public LocationLoadoutDef() { Head = new Prop(); LeftArm = new Prop(); RightArm = new Prop(); CenterTorso = new Prop(); LeftTorso = new Prop(); RightTorso = new Prop(); LeftLeg = new Prop(); RightLeg = new Prop(); } public Prop Head { get; set; } public Prop LeftArm { get; set; } public Prop RightArm { get; set; } public Prop CenterTorso { get; set; } public Prop LeftTorso { get; set; } public Prop RightTorso { get; set; } public Prop LeftLeg { get; set; } public Prop RightLeg { get; set; } ... } class Prop { public float CurrentInternalStructure { get; set; } ... } So you can use reflection getting the type of the object and the property. This is an example based on your pseudocode: // your instance of LocationLoadoutDef var mechDef = new LocationLoadoutDef(); //For reflection you need obtain the type Type mechType = mechDef.GetType(); // loop your Dictionary foreach (string limb in LimbRepair.Keys) { // If the property is false in the dictionary and the type has a property with that name if (!LimbRepair[limb] && mechType.GetProperties().Any(p => p.Name == limb)) { // Obtain the instance of the property var property = mechType.GetProperty(limb).GetValue(mechDef) ; // Get the property type Type propertyType = property.GetType(); // If the property has a property CurrentInternalStructure if (propertyType.GetProperties().Any(p => p.Name == "CurrentInternalStructure")) { // Obtain the current value for CurrentInternalStructure var currentValue = propertyType.GetProperty("CurrentInternalStructure").GetValue(property); // calculate the new value (I don't know what is rng) var newValue = 1f ; //Math.Max(1f, (float)currentValue * (float)rng.NextDouble()); // set de value in the property propertyType.GetProperty("CurrentInternalStructure").SetValue(property, newValue); } } }
doc_23531020
I already have Scala and Java installed. I got Stanford CoreNLP but I'm not sure if I set it up correctly. I ran 'sbt compile' and 'sbt assembly' with the build.sbt file in the 'processors' files that I got from the repository mentioned above. It seemed to work, though I got some warnings. I moved all the .jar files I could find into a classes folder within a target folder. I followed the instructions from here: http://www.codecommit.com/blog/scala/joint-compilation-of-scala-and-java-sources to compile the example java code in the sistanlp/processors repository (the last code example in the readme), I entered the following: javac -d /home/mra235/processors-master/processors-master/target/scala-2.11/classes -classpath $SCALA_HOME/lib/scala-library.jar:/home/mra235/processors-master/processors-master/target/scala-2.11/classes src/main/java/*.java But I got errors, in particular the following error: warning: Cannot find annotation method 'bytes()' in type 'ScalaSignature' I am out of ideas ... I probably set up something incorrectly, such as the processors repository or the Standford CoreNLP, but then I don't know what I did wrong.
doc_23531021
-- react-native-router-flux: v4.0.0-beta.31 -- react-native: v0.55.2 enter image description here Actually, I want to passing props("Recent_Measurement") from drawer(in this case, "main_tab") to its nested scence ("measure_tab"). However, whenever I try to pass props to the nested scene, it cannot recognize. For reference, below figure is about my router-flux structure. enter image description here
doc_23531022
* *bower_components * *lib1 * *lib1.js *lib1.min.js <- create this file if doesn't exist *lib2 * *lib2.js *lib2.min.js <- create this file in it's own lib2 folder *lib3 * *lib3.js *lib3.min.js <- and so on... This is my grunt Config so far: uglify: { dev: { files:[ { expand: true, src: 'bower_components/modernizr/modernizr.js', dest: '/', ext:'.min.js' }, { expand: true, src: 'bower_components/angular-facebook/lin/angular-facebook.js', dest: '/', ext: '.min.js' }] }, main: { src: 'temp/app.min.js', dest:'dist/app.min.js' } } the Grunt task says that copied modernizr to it's own folder but when I look at it, the file is not there and after the first file Grunt passes to the next task and ignores the 'second' file in the array. I was just testing this obviously I'd like to implement a way that grunt scan all the dependencies in bower_components automatically. btw, I don't mind to change the task to any other library. A: the / in your dest-option means the root path (were your gruntfile resides). just delete the dest-option or put an empty string there. important: this just works with the expand-option set! { expand: true, src: 'bower_components/modernizr/modernizr.js', ext:'.min.js' } Edit: for scanning all folders an minimizing all js files do it like this (note the second argument in src to not minify files which are already minified): { expand: true, src: ['bower_components/**/*.js', '!bower_components/**/*.min.js'], ext:'.min.js' }
doc_23531023
A: I guess it's pretty much uncommon to show database entries in a diagram, because there are usually way too many of them. And actually, it can be a business-specific diagram, you can think of any DB-based application as a form of such "diagram", showing database entries in a way comfortable to the user. Another way of making up such diagram is to use some variation of the E-R diagram, but show the data instead of the schema, like in this wikipedia article. A: Yacoder mentioned ER diagrams. That's a good place to start. ER diagrams are simpler than UML diagrams. I've seen ER diagrams with well over a hundred boxes, and way more lines between boxes. The paper covers an entire wall. In case you think this is way too complicated, it still easier to understand a hundred tables than a hundred thousand lines of code.
doc_23531024
If I process as Form2.ShowDialog then all works fine. If I process as Form2.Show then I have added code to fire a change to reload the grid, this seems to function as desired (via debug I see the event to reload the grid being run). When I run Form2.Show and Form2 closes the following code is executed. Private Sub sbrReset() Try GridControl1.DataSource = Nothing GridView1.Columns.Clear() dsGrid1.Clear() Using cmd As New SqlClient.SqlCommand("spInventoryControlMtnFiberSize", GetOpenConnection) With {.CommandType = CommandType.StoredProcedure} With cmd.Parameters .Add(New SqlParameter("@Action", SqlDbType.Int)).Value = 23 End With daGrid1.SelectCommand = cmd daGrid1.Fill(dsGrid1, "table") bsGrid1.DataSource = dsGrid1 End Using GridControl1.DataSource = dsGrid1.Tables("table") GridView1.BestFitColumns() GridView1.Columns(0).Fixed = Columns.FixedStyle.Left Catch ex As Exception MsgBox(ex.ToString) End Try End Sub Changes made to the database are not showing up in Form1 grid when grid reloaded. When I debug dsGrid1 shows the new value, but the grid on the form does not show new value.
doc_23531025
One video can have multiple video_category and a video_category can be associated with multiple videos: therefore the video_category_join table TABLE: video | video_id | title | description | duration | |-------------------------------------------- | 12 | hello | ... | 190 | | 24 | hello | ... | 190 | | 78 | hello | ... | 190 | | 34 | hello | ... | 190 | | 91 | hello | ... | 190 | | 88 | hello | ... | 190 | TABLE: video_category | video_category_id | name | |------------------------------ | 4 | music | | 8 | tv | | 5 | black | | 2 | politic | | 1 | movie | | 6 | other | TABLE: video_category_join | video_id | video_category_id | |------------------------------ | 24 | 4 | | 24 | 5 | | 88 | 1 | | 91 | 6 | | 91 | 5 | | 78 | 4 | Given a video_id, i want to pick random videos that DON'T have the same category as the given video_id. So, for example, if the video_id is 24, the result set should return videos that dont have the same category as video_id 24. In this case, the only videos that dont have the same category as video_id 24 are: video_id 88. This is a query that i thought could work, but if the given video_id has no categories it returns nothing. SELECT DISTINCT v.video_id, v.title, v.duration, 2 AS preferred FROM video_category_join vc JOIN video_category_join vc2 ON vc2.video_category_id <> vc.video_category_id AND vc2.video_id <> vc.video_id JOIN video v ON v.video_id = vc2.video_id WHERE vc.video_id = 5 ORDER BY RAND() LIMIT 20 A: One method uses a self-join and aggregation. The join matches on the categories; the having returns videos that do not share any categories: select vc.video_id from video_category vc left join video_category vc2 on vc2.video_category_id = vc.video_category_id and vc2.video_id = 5 group by vc.video_id having count(vc2.video_id) = 0; A: You can do it with joins select * from video where video_id not in ( select distinct v.video_id from video v left join video_category_join vc on v.video_id = vc.video_id where vc.video_category_id in ( select video_category_id from video_category_join where video_id = 24) ) order by rand() limit 5 This will select 5 random videos that are not in the same category as video #24
doc_23531026
This is my MqttServer.java class that sets up the Netty server and binds it to a specific port. EventLoopGroup bossPool=new NioEventLoopGroup(); EventLoopGroup workerPool=new NioEventLoopGroup(); try { ServerBootstrap boot=new ServerBootstrap(); boot.group(bossPool,workerPool); boot.channel(NioServerSocketChannel.class); boot.childHandler(new MqttProxyChannel()); boot.bind(port).sync().channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); }finally { workerPool.shutdownGracefully(); bossPool.shutdownGracefully(); } } Now I did a load testing of my application on my Mac having the following configuration The netty performance was exceptional. I had a look at the jstack while executing my code and found that netty NIO spawns about 19 threads and none of them seem to be stuck up waiting for channels or something else. Then I executed my code on a linux machine This is a 2 core 15GB machine. The problem is that the packet sent by my MQTT client seems to take a long time to pass through the netty pipeline and also on taking jstack I found that there were 5 netty threads and all were stuck up like this ."nioEventLoopGroup-3-4" #112 prio=10 os_prio=0 tid=0x00007fb774008800 nid=0x2a0e runnable [0x00007fb768fec000] java.lang.Thread.State: RUNNABLE at sun.nio.ch.EPollArrayWrapper.epollWait(Native Method) at sun.nio.ch.EPollArrayWrapper.poll(EPollArrayWrapper.java:269) at sun.nio.ch.EPollSelectorImpl.doSelect(EPollSelectorImpl.java:79) at sun.nio.ch.SelectorImpl.lockAndDoSelect(SelectorImpl.java:86) - locked <0x00000006d0fdc898> (a io.netty.channel.nio.SelectedSelectionKeySet) - locked <0x00000006d100ae90> (a java.util.Collections$UnmodifiableSet) - locked <0x00000006d0fdc7f0> (a sun.nio.ch.EPollSelectorImpl) at sun.nio.ch.SelectorImpl.select(SelectorImpl.java:97) at io.netty.channel.nio.NioEventLoop.select(NioEventLoop.java:621) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:309) at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:834) at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:137) at java.lang.Thread.run(Thread.java:745) Is this some performance issue related to epoll on linux machine. If yes then what changes should be made to netty configuration to handle this or to improve performance. Edit Java Version on local system is :- java version "1.8.0_40" Java(TM) SE Runtime Environment (build 1.8.0_40-b27) Java HotSpot(TM) 64-Bit Server VM (build 25.40-b25, mixed mode) Java version on AWS is :- openjdk version "1.8.0_40-internal" OpenJDK Runtime Environment (build 1.8.0_40-internal-b09) OpenJDK 64-Bit Server VM (build 25.40-b13, mixed mode) A: Here are my findings from implementing a very simple HTTP → Kafka forklift: * *Consider switching to EpollEventLoopGroup. Simple autoreplace NioEventLoopGroup → EpollEventLoopGroup gave me 30% perfomance boost. *Removing LoggingHandler from the pipeline (if you have any) can give you a CPU usage drop (in my case CPU the drop was almost unbelievable: 80%). A: Play around with the worker threads to see if this improves performance. The standard constructor of NioEventLoopGroup() creates the default amount of event loop threads: DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt( "io.netty.eventLoopThreads", Runtime.getRuntime().availableProcessors() * 2)); As you can see you can pass io.netty.eventLoopThreads as a launch argument but I usually don't do that. You can also pass the amount of threads in the constructor of NioEventLoopGroup(). In our environment we have netty servers that accept communication from hundreds of clients. Usually one boss thread to handle the connections is enough. The worker thread amount needs to be scaled though. We use this: private final static int BOSS_THREADS = 1; private final static int MAX_WORKER_THREADS = 12; EventLoopGroup bossGroup = new NioEventLoopGroup(BOSS_THREADS); EventLoopGroup workerGroup = new NioEventLoopGroup(calculateThreadCount()); private int calculateThreadCount() { int threadCount; if ((threadCount = SystemPropertyUtil.getInt("io.netty.eventLoopThreads", 0)) > 0) { return threadCount; } else { threadCount = Runtime.getRuntime().availableProcessors() * 2; return threadCount > MAX_WORKER_THREADS ? MAX_WORKER_THREADS : threadCount; } } So in our case we use just one boss thread. The worker threads depend on if a launch argument has been given. If not then use cores * 2 but never more than 12. You will have to test yourself though what numbers work best for your environment.
doc_23531027
Here is the code: l=open('bla.txt', mode='a+') l.write('zxc vbn mju\n') l.write('asd fgh jkl\n') l.write('qwerty uiop') print(l.read()) A: You always need to keep track of your cursor. Your problem was that the cursor was already at the end so due that reason you wasn't able to print anything Solution: l=open('bla.txt', mode='a+') l.write('zxc vbn mju\n') l.write('asd fgh jkl\n') l.write('qwerty uiop') l.seek(0) print(l.read()) A: First write something in a file. with open("Path\\To\\File.txt", "a+") as f: f.write("Something, something") Then read with open("Path\\To\\File.txt", "r+") as f: f.seek(0) # Sets cursor to start of file print(f.read()) Hope this helps.
doc_23531028
function compareDate(s, e) { var date1 = dateStartDate.GetDate(); date1 = date1.format("dd/MM/yyyy"); 13/08/2013 var date2 = dateEndDate.GetDate(); //28/07/2013 if (date2 != null) { date2 = date2.format("dd/MM/yyyy"); if (date2.toString() === date1.toString()) { e.IsValid = true; } else { if (date2 < date1) { e.IsValid = false; } else { e.IsValid = true; } } } } But when I am having these two dates 13/08/2013 and 28/07/2013 this is returning true can some one help me A: You are not comparing dates, you are comparing strings lexicographically (character by character). The string representations of these two dates are in this order: "13/08/2013" < "28/07/2013" since "1" < "2" What you want is comparing the Date objects themselves in the same way: var a = new Date(); var b = new Date(); console.log(a < b); // true console.log(a > b); // false A: By far the easiest method is to subtract one date from the other and compare the result. var oDateOne = new Date(); var oDateTwo = new Date(); alert(oDateOne - oDateTwo === 0); alert(oDateOne - oDateTwo < 0); alert(oDateOne - oDateTwo > 0); See this
doc_23531029
Here are the dependencies in build.gradle: dependencies { implementation 'com.android.support:appcompat-v7:19.+' implementation 'com.android.support:support-v4:19.+' implementation 'com.google.android.gms:play-services-ads:15.0.0' } But when I try to build the project, the Java compiler gives the following errors: TextAppearance.Material.Notification not found. TextAppearance.Material.Notification.Info not found. TextAppearance.Material.Notification.Time not found. TextAppearance.Material.Notification.Title not found. Thanks in advance for suggestions! A: I solved changing compileSdkVersion from 19 to 26. I also changed targetSdkVersion.
doc_23531030
I have a test that starts the server, fetches the available data from a given route and asserts the received values. Everything works fine, except that Jest never exits after executing this test. This is my test: import { app } from "../../src/application.js"; import { describe, expect, test } from "@jest/globals"; import request from "supertest"; describe("Customer Handler", () => { test("should retrieve all existing customer(s)", async () => { const expected = [ // ...real values here; omitted for brevity ]; const response = await request(app).get(`/api/customers`); expect(response.statusCode).toStrictEqual(200); expect(response.headers["content-type"]).toContain("application/json"); expect(response.body).toStrictEqual(expected); }); }); The application.js file looks very much like a usual Express setup/configuration file: import { CustomerHandler } from "./handler/customer.handler.js"; import connection from "../knexfile.js"; import express from "express"; import Knex from "knex"; import { Model } from "objection"; const app = express(); Model.knex(Knex(connection[process.env.NODE_ENV])); // ...removed helmet and some other config for brevity app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use("/api/customers", CustomerHandler); app.use((err, req, res, next) => { res.status(err.status || 500); res.json({ errors: { error: err, message: err.message, }, }); next(); }); export { app }; I've tried --detectOpenHandles, but nothing else is printed in the console, so I can't see any hints about what the issue might be — which I suspect it's Knex / Objection because I'm using SQLite, so probably the connection to the database is not getting closed. In the meantime I'm using --forceExit, but I would like to figure it out why is Jest not able to exit. A: OK, looks like I was on the right track for this one. Refactoring application.js to export the Knex object (after it's configured), and calling knex.destroy() after the test passes is the solution for this setup. // application.js ... const knex = Knex(connection[process.env.NODE_ENV]); Model.knex(knex); ... export { app, knex }; ...then in the test(s), make sure you import knex and call destroy(): // customer.handler.test.js import { app, knex } from "../../src/application.js"; import { afterAll, describe, expect, test } from "@jest/globals"; import request from "supertest"; describe("Customer Handler", () => { afterAll(async () => { await knex.destroy(); }); test("should retrieve all existing customer(s)", async () => { const expected = [ /* ...real values here */ ]; ... expect(response.body).toStrictEqual(expected); }); });
doc_23531031
The help desk application can log support request from a phone call, email, website. We can get questions sent to us from registered customers and non-registered customers. The only reason to keep the help desk application in the same database is so that we can share the user base. But then again we can have the user create a new account for support or sync the user accounts with the help desk application. If we separate the help desk application, our database backup will be smaller. Or we can just keep the help desk application in the same database, which makes development/integration a lot easier overall, having only one database to backup. (Maybe larger but still one database with everything.) What to do? A: I think this is a subjective answer, but I would keep the help desk system as a separate entity, unless there is a good business reason to use the same user base. This is mostly based on what I've seen in professional helpdesk call logging/ticket software, but I do have another compelling reason - security - logic is as follows: Generally, a helpdesk ticketing system generally needs less sensitive information than other business system (accounting, shopping, CRM, etc). Your technicians will likely need to know how to contact a customer, but probably won't need to store full addresses, birth dates, etc. All of the following is based on an assumption - that your existing customer data contains sensitive or personally identifiable data that would not be needed by your ticketing system. * *Principle 1: Reducing the attack surface area by limiting the stored data. Generally, I subscribe to the principle that you should ONLY collect the data you absolutely need. Having less sensitive information available means less that an attacker can steal. *Principle 2: Reducing the surface area by minimizing avenues of attack into existing sensitive data. Assuming you already have a large user base, and assuming that you're already storing potentially useful data about your customers, adding another application with hooks into that data is just adding further avenues of attack into the existing customer base. This leads me to... *Principle 3: Least privilege. The user you set up for the helpdesk software database should have access ONLY to the data absolutely needed by your helpdesk analysts. Accomplishing this is easier if you design your database with a specific set of needs in mind. It's a lot more difficult from a maintenance standpoint to have to set up views and stored procedures over sensitive data in order to only allow access to the non-sensitive data than it is to have a database designed to have only the data that you need. Of course, I may be over-thinking it. And there are other compelling reasons for going either route. I'm just trying to give you something to think about. A: This will definitely be a subjective answer based upon your environment. You have to weigh the benefits/drawbacks of one choice with the benefits/drawbacks of the other choice. However, my opinion would be that the best benefits will be found in separating the two databases. I really don't like to have one database with two purposes. Instead look to create a database with one purpose only. Here are the benefits I see to doing this: * *Portability - if you decide to move the helpdesk to a different server, you can without issue. The same is true if you want to move the corporate database somewhere else *Separation of concerns - each database is designed for its own purpose. The security of one won't interfere with the security of the other. *Backup policies - Currently, you can only have one backup policy for both systems since they are in the same database. If you split them, you could back up one more often than the other (and the backup would be smaller/faster). The drawbacks I see (not being able to access the corporate data as easily) actually come out as a positive in my mind. Accessing the data from the corporate database sounds good but it can be a security issue (also a maintainability issue). Instead, this way you can limit how much access (and what type of access) is granted to the helpdesk system. Databases can access each other fairly easily so it won't be that inconvenient and it will allow you to add a nice security barrier between your corporate data and your helpdesk data.
doc_23531032
My application code. ConnectionParams connectionParams = new ConnectionParams.Builder() .setProjectId("my_pid") .setRegistry("my_reg", "my_server") .setDeviceId("my_device_name") .build(); IotCoreClient client = new IotCoreClient.Builder() .setConnectionParams(connectionParams) .setKeyPair(keys) .setTelemetryQueue(new LinkedTransferQueue<TelemetryEvent>()) .build(); client.connect(); client.publishDeviceState("Test data\n".getBytes()); client.publishTelemetry(new TelemetryEvent("Sonata".getBytes(), null,TelemetryEvent.QOS_AT_LEAST_ONCE)); But there is method for sending device sensors data to IoT platform ("publishTelemetry(Parms...)). client.publishTelemetry(new TelemetryEvent("Sonata".getBytes(), null,TelemetryEvent.QOS_AT_LEAST_ONCE)); This code is works, but I can't find this data "Sonata" in google cloud platform, and I can't understand how can I use telemetry events on Pub/Sub topic? Updated I found the solution. For first step I had added subscriber to topic. Example. Topic projects/my-project-id/topics/firstTop Example Subscriber (fsub is subscriber name) projects/my-project-id/subscriptions/fsub And I had wrote simple subscriber code in java, and sent message from Android of things device. And I had get telemetry data. This is subscriber code in java import com.google.api.gax.core.CredentialsProvider; import com.google.auth.Credentials; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.pubsub.v1.AckReplyConsumer; import com.google.cloud.pubsub.v1.MessageReceiver; import com.google.cloud.pubsub.v1.Subscriber; import com.google.common.collect.Lists; import com.google.pubsub.v1.ProjectSubscriptionName; import com.google.pubsub.v1.PubsubMessage; import java.io.FileInputStream; import java.io.IOException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingDeque; public class SubscriberExample { private static final String PROJECT_ID = "my-project-id"; private static final BlockingQueue<PubsubMessage> messages = new LinkedBlockingDeque<>(); static class MessageReceiverExample implements MessageReceiver { @Override public void receiveMessage(PubsubMessage message, AckReplyConsumer consumer) { messages.offer(message); consumer.ack(); } } public static void main(String... args) throws Exception { String subscriptionId = "YOUR_SUBSCRIBER_ID"; ProjectSubscriptionName subscriptionName = ProjectSubscriptionName.of(PROJECT_ID, subscriptionId); Subscriber subscriber = null; try { GoogleCredentials credentials = GoogleCredentials .fromStream(new FileInputStream("~/google_cloud_pubsub-Project-0b66ab8c5060.json")) // you can get here https://cloud.google.com/docs/authentication/getting-started .createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform")); subscriber = Subscriber.newBuilder(subscriptionName, new MessageReceiverExample()) .setCredentialsProvider(new CredentialsProvider() { @Override public Credentials getCredentials() throws IOException { return credentials; } }).build(); subscriber.startAsync().awaitRunning(); while (true) { PubsubMessage message = messages.take(); System.out.println("Message Id: " + message.getMessageId()); System.out.println("Data: " + message.getData().toStringUtf8()); } } finally { if (subscriber != null) { subscriber.stopAsync(); } } } } A: First to check that it's working and the connection really is going to your project, the easiest way is to look at the Google Cloud Platform console for your project, and on the device page inside the IoT Core section (IoT Core->registry->device), there's a tab for "Configuration & state history" which, you should see "Test data" there (as set with the publishDeviceState call). That should confirm that at least everything else is working as expected. Assuming that's the case, now you'll want to look at Pub/Sub documentation to start to get a handle on what you can do with Pub/Sub. Here is the main doc page. My recommendation is to look into Google Cloud Functions as a place to get up and running quickly. Depending on what you want to do, Cloud Dataflow might also be a good option to look into. Each of those products triggers based off messages getting published into Cloud Pub/Sub. So as soon as you're calling "publishTelemetry", it sends the telemetry to IoT Core, which then publishes the message into the Pub/Sub topic specified in the IoT Core registry when you created it. Then the triggered products (GCF and Dataflow) receive the Pub/Sub object which you can get the telemetry data from. There's examples in the docs on how to do it.
doc_23531033
I want to compile it and I want to modify it. So I started with its source code which I have downloaded. Now I have seen that in supported compilers there is Visual C++ here... How to setup it? EDIT: I have successfully setup it but now i am looking for some options to run GDALDEM.cpp. A: You can get Visual C++ by downloading the free version of Visual Studio from Microsoft. Follow the link you have supplied, and go to the downloads section. Once it's installed you should be able to read the help to see how to open and compile your project. A: For Setup, I did it... just sharing so someone can save time Step 1 Download this Project from here This project is just project file. You need to copy GDAL source code to it in next steps.. Step 2 Extract it. Step 3 Now copy paste all folders/files from gdal-1.11.1 folder to project solution folder Select all files as shown below, press Ctrl +C Now paste in extracted project Step 4 Now open Visual C++ -> Open Project -> Select Project Step 5 Simple Setup done....
doc_23531034
Error: Undefined symbols for architecture arm64: "_IOHIDEventCreateDigitizerEvent", referenced from: -[UIEvent(KIFAdditions) kif_setIOHIDEventWithTouches:] in UIEvent+KIFAdditions.o -[UIEvent(KIFAdditions) kif_setIOHIDEventWithTouches:] in libKIF.a(UIEvent+KIFAdditions.o) "_IOHIDEventCreateDigitizerFingerEventWithQuality", referenced from: -[UIEvent(KIFAdditions) kif_setIOHIDEventWithTouches:] in UIEvent+KIFAdditions.o -[UIEvent(KIFAdditions) kif_setIOHIDEventWithTouches:] in libKIF.a(UIEvent+KIFAdditions.o) "_OBJC_CLASS_$_SenTestCase", referenced from: l_OBJC_$_CATEGORY_SenTestCase_$_KIFAdditions in SenTestCase-KIFAdditions.o "_IOHIDEventAppendEvent", referenced from: -[UIEvent(KIFAdditions) kif_setIOHIDEventWithTouches:] in UIEvent+KIFAdditions.o -[UIEvent(KIFAdditions) kif_setIOHIDEventWithTouches:] in libKIF.a(UIEvent+KIFAdditions.o) ld: symbol(s) not found for architecture arm64 clang: error: linker command failed with exit code 1 (use -v to see invocation) Does anyone know whats going on here. Seems only that file has problem building for arm64. Please let me know if anyone has success building KIF v3.2.0 in their project. Thanks! A: It was happening because of missing IOKit.framework.
doc_23531035
Here is the class' code. As you can see, the path is absolute. I want to change it to a relative file path pointing to a folder in my website's directory. A: Usually Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) returns the path where the current assembly resides. You could use string logName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "MyLogFile.log"); to create the log file name. Question is really whether logging to the application's folder is permitted by the OS. Also, for Web-applications, the log file would be publically visible and accessible through the web browser. A: For a website use: HttpContext.Current.Server.MapPath("~/"); A: You might also could try this solution: string path = AppDomain.CurrentDomain.BaseDirectory + "anotherFolder"; This would put the base dir of the app and a folder inside of the project!
doc_23531036
How can I share the dashboard with other team members which are not a part of same AWS account with minimum privilege ? Do the members need Quicksight account to view a dashboard ? Please let me know. A: There's only one way to share dashboards to external users not from your account, i.e. to embed your dashboards to some web application. That way, only the person accessing your web app can access the dashboards. Alternatively, you may invite users to your account with minimal privileges. More details here.
doc_23531037
Here is what I have Private Sub cmdClockin_Click() Dim StrSQL As String Dim Cin As Date Dim Ein As String Dim Jin As String Cin = Now() Ein = Me.ComboEmp Jin = Me.comboJob StrSQL = "INSERT INTO Records (proStart, proEmployee, proJob) VALUES ('" & Cin & "', '" & Ein & "', '" & Jin & "');" DoCmd.SetWarnings False DoCmd.RunSQL StrSQL DoCmd.SetWarnings True End Sub I do not get any errors, but nothing gets written to the table. I have been scouring different websites and for some reason I cant figure out what I'm doing wrong. Any help would be amazing Thanks, Chris A: Insert Now directly, consider if Ein or Jin are numeric (thus no quotes), and do check your SQL: StrSQL = "INSERT INTO Records (proStart, proEmployee, proJob) VALUES (Now(), '" & Ein & "', '" & Jin & "');" MsgBox StrSQL A: First suggestion change table name from Records to some other name. You need to qualify time as Date/Time by a hash # symbol instead of single quote (') for date data type. Check below StrSQL = "INSERT INTO Records (proStart, proEmployee, proJob) VALUES (#" & Cin & "#, '" & Ein & "', '" & Jin & "');"
doc_23531038
I usually do it using matplotlib using matplotlib.use('qt5agg') which results in the window below. I need the same window layout for cv2
doc_23531039
* *The Query looks at each record from select cust_nofrom customers C1. *The first record is checked against the first NOT EXIST query to make sure it does not exist. If it does not exist it returns TRUE, else FALSE. If TRUE it continues to be checked against the second NOT EXIST query and also returns TRUE or FALSE. SELECT cust_no FROM customers C1 WHERE NOT EXISTS ( SELECT * FROM orders, order_details OD1 WHERE orders.order_no = OD1.order_no AND orders.cust_no = C1.cust_no AND NOT EXISTS ( SELECT * FROM products WHERE OD1.prod_cod = products.prod_cod AND products.prod_cod = 'STAND' ) )
doc_23531040
ERROR: type should be string, got "\nhttps://www.digitalocean.com/community/tutorials/how-to-install-and-use-redis\n this tutorial suggests to do sudo make install after make test, but when I am doing \"sudo make install\", it give me the below prompt\n\nHint: It's a good idea to run 'make test' ;)\n\nINSTALL install\nINSTALL install\nINSTALL install\nINSTALL install\nINSTALL install\n\nI do not have any idea whether this will create any problem in installing the cli globally.\nAny suggestions on this will be a great help.\n\nA: You can alternatively copy the server and cli application by doing:\nsudo cp src/redis-server /usr/local/bin/\nsudo cp src/redis-cli /usr/local/bin/\n\nas described in the Redis documentation.\n"
doc_23531041
What I can see: phantomjs stops after page.onLoadStarted and never goes beyond that. What I've tried: Different servers: Webrick, Puma and Unicorn and all have the same problem. Different IPs: I've changed the url inside the script.js file to load localhost, an internal IP and an external IP that connects to rails app. They all fail. script.js var page = require('webpage').create(); page.open('http://localhost:3000/my/page'); page.onLoadFinished = function() { page.render('image.png'); phantom.exit(); } I don't think the problem is with script.js because if I run phantomjs script.js in terminal, it works. Is it not possible to get a screenshot from the same server that is initializing phantomjs, even if it's a different page/controller?
doc_23531042
$(document).ready(function() { $('#container-1').tabs(); } .... <div id="container-1"> <ul> <li><a href="#fragment-1"><span>Home</span></a></li> <li><a href="#fragment-2"><span>Contact</span></a></li> </ul> </div> ... It works fine! I need the tab click event. If it is the Home tab click, I have to do alert();. How do I achieve this? A: Set the id of the Home tab span element: <li><a href="#fragment-1"><span id="home">Home</span></a></li> And add the click handler to it somewhere: $("#home").click(function() { alert("Home tab is selected!"); }); A: Personally, I'd handle it all in the tab configuration itself rather than adding click events to the elements which ultimately will be the clickable part of the tab. If you do it via the tab config, then all of your tab logic is centralized thus making things cleaner and you don't need to be familiar with the implementation details of the tabs: $(document).ready(function() { $('#container-1').tabs({ selected : function(e, ui) { if (ui.index == 0) { alert('Home clicked!'); } } }); }); .... <div id="container-1"> <ul> <li><a href="#fragment-1"><span>Home</span></a></li> <li><a href="#fragment-2"><span>Contact</span></a></li> </ul> </div> A: If you want the tab click event, you would do something like one of the following. $("#tabid").click(function(e) { e.preventDefault(); // Do tab click logic }); or $(".tabclass").click(function(e) { e.preventDefault(); // Do tab click logic }); Do a search for jQuery cheat sheet to get yourself a very useful jQuery cheat sheet.
doc_23531043
I load data from Google BigQuery like this: dConf = { "mapred.bq.project.id": project_id, "mapred.bq.gcs.bucket": bucket, "mapred.bq.input.project.id": project_id, "mapred.bq.input.dataset.id":dataset_id, "mapred.bq.input.table.id": table_id } rdd_dataset_raw = sc.newAPIHadoopRDD( "com.google.cloud.hadoop.io.bigquery.JsonTextBigQueryInputFormat", "org.apache.hadoop.io.LongWritable", "com.google.gson.JsonObject", conf=dConf ) Whose output looks like this (rdd_dataset_raw.take(2)): [(0, u'{"group_id":"1","pertubations":"Current Affairs,Sport,Technology"}'), (67, u'{"group_id":"2","pertubations":"Current Affairs,Sport,Celeb Gossip"}')] Some trivial processing, with repartitioning: rdd_dataset = ( rdd_dataset_raw .repartition(nr_partitions) .map(lambda t, json=json: json.loads(t[1])) ) which looks like this: [{u'group_id': u'1', u'pertubations': u'Current Affairs,Sport,Technology'}, {u'group_id': u'2', u'pertubations': u'Current Affairs,Sport,Celeb Gossip'}] When I save the RDD to Google storage with: rdd_dataset_raw.saveAsTextFile("gs://bucket/directory") This creates nr_partitions part files. However, these part files are not evenly sized. They increase in n**2, where n is the part file number. In other words, part-00000 contains 0 lines part-00001 contains 1 line part-00002 contains 2 lines part-00003 contains 4 lines part-00004 contains 8 lines etc. Most of these also finish practically immediately, where the later parts run out of memory. What is going on!? How do I make the partitions take even load? A: It was as simple as replacing repartition with partitionBy: rdd_dataset = ( rdd_dataset_raw .partitionBy(nr_partitions) .map(lambda t, json=json: json.loads(t[1])) ) Note this needed to be done as early as possible. Passing an unpartitioned rdd and then partitioning later broke. Docs
doc_23531044
e.g. if I want to invoke the bar method for the object, foo, I can use foo.send("bar") Is there any way of doing something similar using objective-c? tks! A: For general use (method with a return value and any number of arguments), use NSInvocation: if ([target respondsToSelector:theSelector]) { NSInvocation *invocation = [NSInvocation invocationWithMethodSignature: [target methodSignatureForSelector:theSelector]]; [invocation setTarget:target]; [invocation setSelector:theSelector]; // Note: Indexes 0 and 1 correspond to the implicit arguments self and _cmd, // which are set using setTarget and setSelector. [invocation setArgument:arg1 atIndex:2]; [invocation setArgument:arg2 atIndex:3]; [invocation setArgument:arg3 atIndex:4]; // ...and so on [invocation invoke]; [invocation getReturnValue:&retVal]; // Create a local variable to contain the return value. } A: There are several options, as far as I know * *You could use NSObject's performSelector: method. This, however, is only really good for methods that have few or no arguments. *Use the NSInvocation class. This is a bit heftier, but is a lot more flexible. *You might be able to use objc_msgSend(), but it's probably a bad idea to call it directly, due to other stuff that the runtime might be doing behind the scenes. A: if ([foo respondsToSelector:@selector(bar)]) [foo performSelector:@selector(bar))];
doc_23531045
@Nullable private <S> S read(TypeInformation<S> type, @Nullable Bson bson, ObjectPath path) { if (null == bson) { return null; } else { TypeInformation<? extends S> typeToUse = this.typeMapper.readType(bson, type); Class<? extends S> rawType = typeToUse.getType(); if (this.conversions.hasCustomReadTarget(bson.getClass(), rawType)) { return this.conversionService.convert(bson, rawType); } else if (DBObject.class.isAssignableFrom(rawType)) { return bson; } else if (Document.class.isAssignableFrom(rawType)) { return bson; } else if (typeToUse.isCollectionLike() && bson instanceof List) { return this.readCollectionOrArray(typeToUse, (List)bson, path); } else if (typeToUse.isMap()) { return this.readMap(typeToUse, bson, path); } else if (bson instanceof Collection) { throw new MappingException(String.format("Cannot convert %1$s of type %2$s into an instance of %3$s! Implement a custom Converter<%2$s, %3$s> and register it with the CustomConversions. Parent object was: %4$s", bson, BasicDBList.class, typeToUse.getType(), path)); } else if (typeToUse.equals(ClassTypeInformation.OBJECT)) { return bson; } else { Document target = bson instanceof BasicDBObject ? new Document((BasicDBObject)bson) : (Document)bson; MongoPersistentEntity<?> entity = (MongoPersistentEntity)this.mappingContext.getPersistentEntity(typeToUse); if (entity == null) { throw new MappingException(String.format("Expected to read Document %s into type %s but didn't find a PersistentEntity for the latter!", target, typeToUse.getType())); } else { return this.read((MongoPersistentEntity)this.mappingContext.getRequiredPersistentEntity(typeToUse), target, path); } } } } this line: else if (DBObject.class.isAssignableFrom(rawType)) { return bson; } when i try to converter the response to DBObject,this is return bson.class(Document.class),For exanple: List<DBObject> userList = mongoTemplate.findAll(DBObject.class, "user_info"); the "userList" element is Document.class Actually。 so,when execute this code: DBObject obj = userList.get(1) this is a problem: "org.bson.Document cannot be cast to com.mongodb.DBObject." is it right? why i execute: mongoTemplate.findAll(DBObject.class, "user_info") ,i will take the Document.class of List? not DBObject.class of List?
doc_23531046
In the WinForms's DatagridView we had FirstDisplayedScrollingRowIndex. Is there an equivalent for the WPF variant? I'm using a CollectionView in my ViewModel which is bound to a DataGrid in XAML. Just to be clear: I don't want to get the SelectedRow's index, this I can already do... Example I've got 20 items in my ObservableCollection and my Datagrid can only show 13 due to size-restrictions. Item2 was previously selected by the user and after that the user scrolled a bit down, so items 5-17 are visible. How do I get the index of item5? XAML <Style x:Key="DatagridStyle" TargetType="DataGrid"> <Setter Property="AutoGenerateColumns" Value="False"/> <Setter Property="Background" Value="{StaticResource ColorDatagridBackground}"/> <Setter Property="IsReadOnly" Value="True"/> <Setter Property="CanUserAddRows" Value="False"/> <Setter Property="CanUserDeleteRows" Value="False"/> <Setter Property="CanUserResizeColumns" Value="False"/> <Setter Property="CanUserReorderColumns" Value="True"/> <Setter Property="CanUserSortColumns" Value="True"/> <Setter Property="ColumnHeaderHeight" Value="25"/> <Setter Property="Margin" Value="0,5,0,5"/> <Setter Property="ItemsSource" Value="{Binding ItemCollection}"/> </Style> <DataGrid DockPanel.Dock="Top" Style="{StaticResource DatagridStyle}" util:DataGridColumnsBehavior.BindableColumns="{Binding DatagridColumns, UpdateSourceTrigger=PropertyChanged}" IsSynchronizedWithCurrentItem="True" EnableRowVirtualization="True"> <i:Interaction.Behaviors> <util:DataGridScrollBehaviour /> </i:Interaction.Behaviors> </DataGrid> ViewModel private ObservableCollection<DataGridColumn> _datagridColumns; private CollectionView _itemCollection; private CollectionViewSource _itemCollectionSource; public ObservableCollection<DataGridColumn> DatagridColumns { get => _datagridColumns; set { _datagridColumns = value; RaisePropertyChanged(); } } public CollectionView ItemCollection { get => _itemCollection; set { _itemCollection = value; RaisePropertyChanged(); } } public CollectionViewSource ItemCollectionSource { get => _itemCollectionSource; set { _itemCollectionSource = value; RaisePropertyChanged(); } } _datagridColumns = MainViewModel.GetColumns(MainViewModel.AppMode.Match); _itemCollectionSource = new CollectionViewSource(); ItemCollectionSource.Source = _vml.Main.ItemList; _itemCollection = (CollectionView)ItemCollectionSource.View; Desired Result: if my view-area is ... - at the top and I add an item at the top (due to current sorting), I want my view-area to stay at the top, so I can see my new item - at the bottom and I add an item at the bottom (due to current sorting), I want my view-area to move to the 'new' bottom, so I can see my new item - is anywhere in the middle, I want to keep looking at the same X items I can access the SortOrder via my CollectionView, but in order to determine where my view-area needs to be moved, I do need to know, where my view-area currently is (top, middle, bottom) A: For my problem (a scrollviewer with an items control) I found the solution was to capture the scroll changed event and use it. Since a DataGrid has a scroll viewer I think you can do the same, or instead of scroll changed use the same logic elsewhere that makes the most sense. So in the window code behind: private void dgScrollChanged(object sender, ScrollChangedEventArgs e) { int i = 0; DataGrid dg = (DataGrid)sender; foreach (ObservableFlatObservations o in dg.Items) { UIElement v = (UIElement)dg.ItemContainerGenerator.ContainerFromItem(o); GeneralTransform childTransform = v.TransformToAncestor((ScrollViewer)sender); Rect rectangle = childTransform.TransformBounds(new Rect(new Point(0, 0), v.RenderSize)); Rect result = Rect.Intersect(new Rect(new Point(0, 0), ((ScrollViewer)sender).RenderSize), rectangle); if (result != Rect.Empty) { //This one is visible so do some stuff return;// i is the index of this item } i++; } } And in the datagrid xaml definition: <DataGrid x:Name="MainDataGrid" AutoGenerateColumns="False" HorizontalAlignment="Stretch" Margin="0,0,0,0" VerticalAlignment="Stretch" ItemsSource="{Binding oFObs.View}" SelectedItem="{Binding CurrentObs, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" IsReadOnly="True" Grid.Row="1" Grid.ColumnSpan="3" ScrollViewer.ScrollChanged="dgScrollChanged"> I haven't tested this with my datagrid quite yet, but this method worked well for my original case. Note my data element names are not mapped to your question, but I think you can modify this to work with what you have. After actually trying this, it turns out to perhaps be simpler. In the event handler only rows that are visible in the grid will return a value from the ContainerFromItem call because the datagrid virtualizes the contents. So I think if you do something like this you can find the first visible index in the datagrid: private void dgScrollChanged(object sender, ScrollChangedEventArgs e) { int i = 0; DataGrid dg = (DataGrid)sender; foreach (GetFlatObservationsResult o in dg.ItemsSource) { DataGridRow v = (DataGridRow)dg.ItemContainerGenerator.ContainerFromItem(o); if(v!=null) { //i is the index of the first visable row //do some stuff return; } i++; } } A: you can add SelectedIndex="{Binding SelIndex}" attribute in the collection tag. Where SelIndex will be the property in your ViewModel file bounded to this attribute.
doc_23531047
its show like this in above screenshot y-Axes show me 10 but point hover show 6 how to solve this problem? this is code var lables = []; s = [{ 'example1' : '{01-Mar-17 : 0, 02-Mar-17 : 6}', 'example2' : '{01-Mar-17: 0, 02-Mar-17: 4}' }]; var example1 = []; var example2 = []; $.each(s.example1,function(i,j){ lables.push(i); example1.push(j); }); $.each(s.example2,function(i,k){ example2.push(k); }); var ctx = document.getElementById('chartdata').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: lables, datasets: [{ label: 'Example 1', fill: false, lineTension: 0.1, backgroundColor: convertHex('#00a3d0',40), borderColor: convertHex('#00a3d0',80), borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: convertHex('#00a3d0',90), pointBackgroundColor: "#fff", pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: convertHex('#00a3d0',100), pointHoverBorderColor: convertHex('#00a3d0',100), pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, data: example1, spanGaps: false, }, { label: 'Example 2', fill: false, lineTension: 0.1, backgroundColor: convertHex('#8a6d3b',40), borderColor: convertHex('#8a6d3b',80), borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: convertHex('#8a6d3b',90), pointBackgroundColor: "#fff", pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: convertHex('#8a6d3b',100), pointHoverBorderColor: convertHex('#8a6d3b',100), pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, data: example2, spanGaps: false, } ] }, options: { responsive: true, scales: { yAxes: [{ stacked: true, ticks: { min: 0, stepSize: 5, } }] } } }); A: The reason why the dataset named 'Example 2' is at 10 instead of 6 on the y-axis is because of how you have your line graph configured. You have configured the y-axis to be stacked (stacked: true) so what you are really looking at is a stacked line chart. See the config below (which was taken directly from your question). scales: { yAxes: [{ stacked: true, ticks: { min: 0, stepSize: 5, } }] } Stacked line charts work by plotting each dataset right on top of the other. In this case the y value for that point is 6, so it is added to the y value of the previous dataset (which is 4) to plot the point at 10 on the y-axis. To change this simply set stacked: false and both lines will be plotted as you were expecting. scales: { yAxes: [{ stacked: false, ticks: { min: 0, stepSize: 5, } }] } See this codepen example. A: data creation is causing problem. Check fiddle var lables = []; var s = [{ example1 : {'01-Mar-17' : '0', '02-Mar-17' : '6'}, example2 : {'01-Mar-17':'0', '02-Mar-17': '4'} }]; var example1 = []; var example2 = []; $.each(s,function(i,item){ $.each(item.example1,function(i,j){ lables.push(i); example1.push(j); }); $.each(item.example2,function(i,j){ example2.push(j); }); }); var ctx = document.getElementById('chartdata'); var myChart = new Chart(ctx, { type: 'line', data: { labels: lables, datasets: [{ label: 'Example 1', fill: false, lineTension: 0.1, backgroundColor: '#00a3d0', borderColor: '#00a3d0', borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: '#00a3d0', pointBackgroundColor: "#fff", pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: '#00a3d0', pointHoverBorderColor: '#00a3d0', pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, data: example1, spanGaps: false, }, { label: 'Example 2', fill: false, lineTension: 0.1, backgroundColor: '#8a6d3b', borderColor: '#8a6d3b', borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: '#8a6d3b', pointBackgroundColor: "#fff", pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: '#8a6d3b', pointHoverBorderColor: '#8a6d3b', pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, data: example2, spanGaps: false, } ] }, options: { responsive: true, scales: { yAxes: [{ stacked: false, ticks: { min: 0, stepSize: 5, } }] } } }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.min.js"></script> <canvas id="chartdata" ></canvas>
doc_23531048
HoC import React, { PropTypes, Component } from "react"; import { omit } from "lodash/fp"; const propsFilter = omit(["onSelect"]); export default function selectable(onSelect, isSelected) { return (component) => { const wrappedName = component.displayName || component.name || "Component"; const displayName = `Selectable(${wrappedName})`; const onClick = () => onSelect && onSelect(!isSelected); class SelectableWrapper extends Component { render() { return <component onClick={ onClick } { ...propsFilter(this.props) } />; } } SelectableWrapper.displayName = displayName; SelectableWrapper.propTypes = Object.assign({ onSelect: PropTypes.func, isSelected: PropTypes.bool, }, component.propTypes); return SelectableWrapper; }; } Test /* eslint-env mocha */ "use strict"; import React from "react"; import { expect } from "chai"; import { spy } from "sinon"; import { mount } from "enzyme"; import selectable from "../../../src/js/components/tables/selectable"; describe("<SelectableHOC />", () => { let onSelect, isSelected; const TestElement = () => <p className="test">Hi</p>; const el = () => selectable(onSelect, isSelected)(TestElement); beforeEach("setup spy", () => onSelect = new spy()); it("renders the wrapped component, passing through props", () => { const hoc = el(); const wrapper = mount(<hoc name="foo" />); expect(wrapper).to.contain("p.test"); }); it("doesn't pass through onSelect"); it("sets onClick on the child component, which triggers onSelect"); }); When I try wrapper.debug() in the test, I just get <hoc data-reactroot="" name="foo"></hoc>. The output of the test (which fails) is: 1) <SelectableHOC /> renders the wrapped component, passing through props: AssertionError: expected <HTMLUnknownElement /> to contain p.test HTML: <hoc data-reactroot="" name="foo"></hoc> at Context.<anonymous> (test/components/tables/selectable.spec.js:43:39) A: The name of your component is in lowercase and in JSX name starting with a lowercase name are considered to be HTML tags, not the custom components. So you'll need to capitalize your component name. Also, I recommend you changing the name of your component to something more meaningful to avoid clashing with the React.Component. You can read more about it in the official react docs and this question. A: You have to find the wrapped component and check the props on that const elWrapper = wrapper.find('TestElement'); expect(elWrapper.prop('onClick').to.not.equal(null); expect(elWrapper.prop('onSelect').to.equal(undefined);
doc_23531049
public String getStudentId(Id userId) throws Exception { String sid = null; try { UserDbLoader userDbLoader = UserDbLoader.Default.getInstance(); User ul = userDbLoader.loadById(userId); sid = ul.getStudentId(); System.out.println(""); System.out.println("***Debug Section 1***"); System.out.println("Student ID: " + sid); } catch (Exception e) { e.printStackTrace(); } return sid; } And I want to pass the variable sid to the next String method which uses dbcp2 to connect to a DB to return a corresponding value: pidm The second String method is: public String dbQuery(String sid) { String student_id = sid; String pdTemp = null; Connection connection = null; PreparedStatement statement = null; ResultSet rs = null; try { BasicDataSource bds = MapSource.getInstance().getBds(); connection = bds.getConnection(); statement = connection.prepareStatement("select pidm from b21_toolbar_timetable_mapping where student_id = ?"); statement.setObject(1, student_id); rs = statement.executeQuery(); while (rs.next()) { pdTemp = rs.getNString("pidm"); } System.out.println(""); System.out.println("**** Debug Section 2 ***"); System.out.println("**** SID: " + sid); System.out.println("**** student_id: " + student_id); System.out.println("**** PIDM: " + pdTemp); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (statement != null) statement.close(); if (connection != null) connection.close(); } catch (SQLException e) { e.printStackTrace(); } } return pdTemp; } My question is what have am I missing? The sid variable is not passing through to the try statement in dbQuery so the Debug Section 2 statements contain no outputs.
doc_23531050
Name Item Date value1 value2 Marc bike 21-Dec-17 7 1000 Marc bike 05-Jan-18 9 2000 Marc bike 27-Jul-18 4 500 John house 14-Dec-17 4 500 John house 02-Feb-18 6 500 John house 07-Feb-18 8 1000 John house 16-Feb-18 2 1000 John house 05-Dec-21 7 1000 John house 27-Aug-25 8 500 John car 17-Apr-18 4 500 I would like to bin value1 and value2 into monthly buckets (each 3rd wednesday for the next 48 months) for each name-item-combination. So there are 49 time buckets for each combination with the sum of value1 and value2 for each month: Marc/bike, John/house, John/car, ... The solution for John/house would look like: Name Item TimeBucket value1 value2 John house 20-Dec-17 4 500 John house 17-Jan-18 0 0 John house 21-Feb-18 16 2500 John house 21-Mar-18 0 0 John house 18-Apr-18 0 0 John house … 0 0 John house 17-Nov-21 0 0 John house 15-Dec-21 7 1000 John house rest 8 500 i cant get to a result with pandas. The only solution I can think of is a row-by-row iteration through the dataframe, but I'd really like to avoid having to do this. Is there an elegant way to do it? A: The question really boils down to three steps: 1. How to find the third Wednesday of every month? This may not be the most elegant solution, but you can filter out the third Wednesday of every month by masking a pandas DatetimeIndex which contains every day in the time frame. # generate a DatetimeIndex for all days in the relevant time frame from datetime import datetime start = datetime(2017, 12, 1) end = datetime(2022, 1, 31) days = pd.date_range(start, end, freq='D') # filter out only the third wednesday of each month import itertools third_wednesdays = [] for year, month in itertools.product(range(2017, 2023), range(1,13)): mask = (days.weekday == 2) & \ (days.year == year) & \ (days.month == month) if len(days[mask]) > 0: third_wednesdays.append(days[mask][2]) bucket_lower_bounds = pd.DatetimeIndex(third_wednesdays) Convert the resulting list to a DatetimeIndex so you can use it as the lower bounds of the bins in step 2. 2. How to bin values of a DataFrame? Then, once you have the list of buckets as a DatetimeIndex, you can simply use panda's cut function to assign each date to a bucket. Convert date columns to integers before passing them into cut, and then convert the result back to dates: time_buckets = pd.to_datetime( pd.cut( x = pd.to_numeric(df['Date']), bins = pd.to_numeric(bucket_lower_bounds), labels = bucket_lower_bounds[:-1] ) ) The series time_buckets assigns each index value of your original data frame to a bucket's lower bound. We can simply add it to the original data frame now: df['TimeBucket'] = time_buckets The result should look somewhat like this (not that NaT stands for the "rest" bucket): Name Item Date value1 value2 TimeBucket 0 Marc bike 2017-12-21 7 1000 2017-12-20 1 Marc bike 2018-01-05 9 2000 2017-12-20 2 Marc bike 2018-07-27 4 500 2018-07-18 3 John house 2017-12-14 4 500 NaT 4 John house 2018-02-02 6 500 2018-01-17 5 John house 2018-02-07 8 1000 2018-01-17 6 John house 2018-02-16 2 1000 2018-01-17 7 John house 2021-12-05 7 1000 2021-11-17 8 John house 2025-08-27 8 500 NaT 9 John car 2018-04-17 4 500 2018-03-21 3. How to aggregate a binned DataFrame? Now it's as simple as using groupby to get the sums for each combination of name, item and bucket: df.groupby(['Name','Item','TimeBucket']).sum() Result: Name Item TimeBucket value1 value2 John car 2018-03-21 4 500 house 2018-01-17 16 2500 2021-11-17 7 1000 Marc bike 2017-12-20 16 3000 2018-07-18 4 500 Unfortunately, NaT values are excluded from groupby. If you need to sum those as well, perhaps it would be easiest to make sure that your list of buckets has at least one bucket for every date in your input range. Edit: Step 2 requires pandas version >= 0.18.1.
doc_23531051
and I have some categorized data in my database - For example- I have data of Three Categories. Category 1 Category 2 Category 3 Categories could be changed. Like 2,3,4,5 etc. And i have facility to show a limit of data. Ex. Lets say Admin want to show only 9 Records So now we have three categories and x limit (which is 9 according to example). and best thing is that- I need to show N numbers of records from each category and total X records. Here N numbers is for each Category. So it will look like this: N1 + N2 + N3 = X (limit ex. 9) N1 from Category1 N2 from Category2 N3 from Category3 So basically i have formulated it like this - NumberOfRecordPerCategory = X (limit) / N (Number of Categories) But it is actually working if i set the limit multiple of 3 like 6,9,12 etc. So my Question is- How do i manage the total records according to limit (X) - 1. if Admin set the limit which is not multiple by 3 like 8,10,11, etc. 2. if Admin change the number of category Like 2 or 4, then how could i manage this? Please give some idea about this. and please let me know if Question is not clear. A: What I would choose for your requirement is ceil (round fractions up). If there is some fractions because the number is not multiple by 3, for example 11 with 3 categories, then have the limitation of 4,4,3 for each category. This could be done by having two limit values: limit of total, limit per category. Here's my suggestion for your needs (code) : <?php /* $data = array ( "category1" => array (1,2,3,4,5), "category2" => array (10,20,30,40,50), "category3" => array (100,200,300,400,500), ); */ $limit = 11; // given by the admin $number_of_categories = count($data); $limit_per_category = ceil ( $limit / $number_of_categories ); // ceil (11 / 3) = 4 $cnt = 0; // tracking the total number of retrieved data. foreach ($data as $row) { $cnt_category = 0; foreach ($row as $item) { echo $item . "\n"; // print the first N (NumberOfRecordPerCategory) data $cnt_category++; $cnt++; if ($cnt >= $limit) break; // exit the loop if ($cnt_category >= $limit_per_category) break; // move to next category } if ($cnt >= $limit) break; // exit the loop }
doc_23531052
The problem essentially reduces to calculate the solar zenith angle for that specified day when the solar azimuth angle is equal to the azimuth angle made by the points and compare it to the altitude angle made by both points (if the altitude angle is greater than the zenith angle, the point is shaded). My issue is that equations in literature calculate the zenith first according to location and datetime, and then the solar azimuth as a function of the zenith. Both are correlated, but trying to solve the equations as functions of the solar azimuth seems to be analytically intractable (online equation solvers don't give answers). I either want to know whether is a equation of the zenith as a function of the solar azimuth or if there is an analytical solution for the equation: a sin(x) + b cos(x) = c I tried solving the solar azimuth equation as a function of the zenith, and ran into a equation of the basic form a sin(x) + b cos(x) = c, which apparently has no analytical answer.
doc_23531053
I'm using this guide to install it: How to install Nginx GeoIP module But I face this problem when I try to set the path of GeoIp in nginx.cof: nginx: [emerg] unknown directive "geoip_country" in /etc/nginx/nginx.conf:7 nginx: configuration file /etc/nginx/nginx.conf test failed And these are the lines I'v added to nginx.conf : geoip_country /usr/local/share/GeoIP/GeoIP.dat; geoip_city /usr/local/share/GeoIP/GeoLiteCity.dat; I searched this issu in google, one answer was it should be in main{} section but when I insert main{} in nginx.conf and insert the lines in there, I see another error says main{} is wrong! Also I read somewhere else that main{} is the same nginx.conf file! I'm so confused, Can anyone help me with this? [UPDATE] this is the http section in my nginx.conf: http { include /etc/nginx/mime.types; # For user configurations not maintained by DirectAdmin. Empty by default. include /etc/nginx/nginx-includes.conf; # Supplemental configuration include /etc/nginx/nginx-modsecurity-enable.conf; include /etc/nginx/nginx-defaults.conf; include /etc/nginx/nginx-gzip.conf; include /etc/nginx/directadmin-ips.conf; include /etc/nginx/directadmin-settings.conf; include /etc/nginx/nginx-vhosts.conf; include /etc/nginx/directadmin-vhosts.conf; geoip_country /usr/local/share/GeoIP/GeoIP.dat; geoip_city /usr/local/share/GeoIP/GeoLiteCity.dat; # Set php-fpm geoip variables fastcgi_param GEOIP_COUNTRY_CODE $geoip_country_code; fastcgi_param GEOIP_COUNTRY_CODE3 $geoip_country_code3; fastcgi_param GEOIP_COUNTRY_NAME $geoip_country_name; fastcgi_param GEOIP_CITY_COUNTRY_CODE $geoip_city_country_code; fastcgi_param GEOIP_CITY_COUNTRY_CODE3 $geoip_city_country_code3; fastcgi_param GEOIP_CITY_COUNTRY_NAME $geoip_city_country_name; fastcgi_param GEOIP_REGION $geoip_region; fastcgi_param GEOIP_CITY $geoip_city; fastcgi_param GEOIP_POSTAL_CODE $geoip_postal_code; fastcgi_param GEOIP_CITY_CONTINENT_CODE $geoip_city_continent_code; fastcgi_param GEOIP_LATITUDE $geoip_latitude; fastcgi_param GEOIP_LONGITUDE $geoip_longitude; } Is there any problem with it?
doc_23531054
* *My foremost question is: How do I set/change the file icon in a QFileInfo object? If you look at my code, Qlist<QFileInfo> lists the icon of all my folders in my home directory as gnome-fs-directory. Which means, QFileInfo lists even my desktop folder's icon as plain gnome-fs-directory. But I want Desktop to have QFileIconProvider::Desktop as icon. * *Which consequently leads to the 2nd question: Is QFileInfo the appropriate class to use to find out the icon that QFileSystemModel would use? * *Which leads to the 3rd question: Why did my QDir not pass QFileSystemModel a QFileInfo list with the appropriate icon role for Desktop? * *So the ultimate question is, what do I have to do to ensure QFileSystemModel uses the appropriate icon role, when listing itself in a tree view or list view? Code to find out the file icon of each folder in the home folder: void MainWindow::fileIconInfo(QFileSystemModel *model) { QFileIconProvider *iconprov = model->iconProvider(); QFileInfoList fileInfoList = QDir::home().entryInfoList(); QFileInfoList::Iterator i; foreach (QFileInfo fi, fileInfoList){ if (fi.fileName() == QString("Desktop")) /*change the icon to QFileIconProvider::Desktop*/; //the following line indicates all my icons are gnome-fs-directory!!*/ std::cout << iconprov->icon(fi).name().toStdString() << std::endl; } } This is my main window: MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); fileSystemTree(ui->listView); fileSystemTree(ui->treeView); } Setting the model for the view: void MainWindow::fileSystemTree(QAbstractItemView *view) { QFileSystemModel *model = new QFileSystemModel; model->setRootPath(QDir::homePath()); view->setModel(model); view->setRootIndex(model->index(QDir::homePath())); fileIconInfo(model); } A: I think what you are describing is caused by the fact that QFileIconProvider is detecting that you use Gnome, and the is using Gtk style - no matter what. Could you try to start some other desktop environment and see if problem remains? If it does then I am right and only thing you can do is to subclass QFileSystemModel and change QIcon returned from data method - but this is quite crude and non-flexible solution.
doc_23531055
I am having the following plpgsql function CREATE OR REPLACE FUNCTION public.getall_available_products( IN start_day_id integer, IN end_day_id integer) RETURNS TABLE(id integer) AS $BODY$ SELECT product_id As id FROM product_days WHERE available > 0 AND days_id BETWEEN start_day_id AND end_day_id $BODY$ LANGUAGE sql VOLATILE I need to use the result of the above function in a join query in another plpgsql function CREATE OR REPLACE FUNCTION public.get_available_product_details( IN start_day_id integer, IN end_day_id integer) RETURNS SETOF record AS $BODY$declare begin SELECT pd.days_id As pd_days_id, pd.id AS p_id, pd.name AS p_name FROM product p JOIN product_days pd Using(id) WHERE pd.id in Select * from //here I need to use the result of the getall_available_products //function end; $BODY$ LANGUAGE plpgsql VOLATILE How should I use the result of the first function in the second function? where I specify with comments. A: You can select from set / table returning functions like tables or views. In your case: SELECT pd.days_id As pd_days_id, pd.id AS p_id, pd.name AS p_name FROM product p JOIN product_days pd USING(id) WHERE pd.id IN (SELECT a.id FROM public.getall_available_products(start_day_id, end_day_id) a); You may even join with functions: SELECT pd.days_id As pd_days_id, pd.id AS p_id, pd.name AS p_name FROM product p JOIN product_days pd USING(id) JOIN public.getall_available_products(start_day_id, end_day_id) a ON pd.id = a.id; This should give the same result. Note: If you want pass column values as function arguments you should take a look at the relatively new keyword LATERAL.
doc_23531056
<div *ngFor="let template of templates; index as i"> <div id="{{template.templateName}}_front_{{i}}" [innerHTML]="(template.templateHtmlFront) | safeHtml"> </div> <div id="{{template.templateName}}_back_{{i}}" [innerHTML]="(template.templateHtmlBack) | safeHtml"></div> </div> I want to convert each front and back template in an image. so i have written following code in ts file async createFiles() { const imageData: any[] = []; for (let tempIdx = 0; tempIdx < this.templates.length; tempIdx++) { const containerFront = document.getElementById(`${template.templateName}_front_${tempIdx}`); //save front template if (containerFront) { await htmlToImage.toJpeg(containerFront) .then((dataUrl) => { const imageName = `${template.templateId}_front.jpeg`; const imageBlob: Blob = this.service.dataURItoBlob(dataUrl); const imageFile = new File([imageBlob], imageName, { type: 'image/jpeg' }); imageData.push(imageFile); }).catch(function (error) { console.error('oops, something went wrong!', error); }); } //Save back const containerBack = document.getElementById(`${template.templateName}_back_${tempIdx}`); if (containerBack) { await htmlToImage.toJpeg(containerBack) .then((dataUrl) => { const imageName = `${template.templateId}_back.jpeg`; const imageBlob: Blob = this.service.dataURItoBlob(dataUrl); const imageFile = new File([imageBlob], imageName, { type: 'image/jpeg' }); imageData.push(imgFile); }).catch(function (error) { console.error('oops, something went wrong!', error); }); } } } } This works fine for max 10 to 15 record, but of templates size is more than 15 then application hangs(or crashes). For 10-15 records also it takes 15mins(which is very slow) Is there any better way to make it work?
doc_23531057
In the process,I found three open source projects meet my need ,osmand,mapsforge and osmdroid.With my study going on, a few questions came to me. The picture is a screenshot of google map app on Android,it shows a base map ,some markers and an information window. As we all know , users can touch marker and information window,and they can response to the touch gesture. Here comes the first question. 1.Are marker and information window View/ViewGroup or picture elements which are just drawn on the base map?Which choice is better? * *In osmand, marker is picture element while information window is a custom dialog. * *In mapsforge ,there is only marker and the marker is a picture element. * *In osmdroid, they are both picture elements. As for the touch event for the marker and information window. * *In osmand ,user can long touch on the map and the information window will appear.User can also touch the window to do further things.When long touch event activated,one of a layers will intercept the event and dispatch it through those abstract layer until meet the specific layer which can consume it.After a complex calculation and process, the information window will appear on that point.Marker can be put later and it doesn't response to touch. *mapsforge haven't implement touch event for marker. *as for osmdroid , I have't digged into it. The touch event handle of marker and information window of these three doesn't implement as complete as google map api and other apis I used before. Here is what I think? If they are view, MapView should be ViewGroup or be a combination of container(ViewGroup) and BaseMap(View). * *benefit:maybe it is easier to handle the touch event. *shortcoming:the relative relation between MapView and them should be well considered when map moves. If they are picture elements,MapView can just be View (or ViewGroup). * *benefit:the relative relation talked above is not that a problem *shortcoming:the touch event should be well calculated and handled. For now: * *MapView in Mapsforge is ViewGroup *OsmandMapTileView which is similar to MapView in Osmand is SurfaceView *MapView in osmdroid is ViewGroup So here comes the second question: 2.How should we choose the base class combination of Marker and MapView? What are benefits and shortcomings of each combination ? Discussion in mapsforge google group I'd appreciate it if you share your thoughts!
doc_23531058
first time of my navigation is to be as follows Name -> List -> Details In the Details page when the user selects any option then i am calling the same activity once again to show new Details. This goes on for n number of times. In the Details page i have three important buttons 1. back, 2. List, 3. Home My problem from Details page are 1. when List button is clicked i have to move on to the List Activity, and by pressing back button from List Activity i need to show Home page, not Details Page 2. when Home button is clicked i have to move on to the Home Activity, and by pressing back button from Home Activity i need the app to get closed. 3. back -> a. when the user comes first time to the Details page, by pressing back button he needs to move to List Activity b. after loading the Details activity again and again, by pressing the back button user can move on to previous Details, here the condition is while starting the activity i should not give finish(), because this causes the data to get loaded of a long time how to overcome the above issues A: Now we'll see your issues one by one: 1. when List button is clicked i have to move on to the List Activity, and by pressing back button from List Activity i need to show Home page, not Details Page Now you can achieve this by: Do not call finish() for home or list activity whenever you go to any other activity. In this way, Home activity will always be present on stack. So now, call startActivity for Home activity or List activity with flag set as FLAG_ACTIVITY_REORDER_TO_FRONT that should bring your activity to front. 2. when Home button is clicked i have to move on to the Home Activity, and by pressing back button from Home Activity i need the app to get closed. 3. back -> a. when the user comes first time to the Details page, by pressing back button he needs to move to List Activity b. after loading the Details activity again and again, by pressing the back button user can move on to previous Details, here the condition is while starting the activity i should not give finish(), because this causes the data to get loaded of a long time Again this can be done by using same as startActivity for Home with flag set as above. OR use startActivityForResult() from details to any other activity. So, now when you want to go back to Home activity from (all) Details activity, and use setResult as ex.: RESULT_FINISH and in onActivityResult() check for this result code and if you receive this result code, call finish for details activity. This way, all your Details activity will get finished. And from Home activity. if you press finish(), your app will get closed (make sure all your activities are calling finish at some point of time.) since all your activities are getting finished. EDIT: When you go from Home > List > Details, your issue is: 1. when List button is clicked from details activity, i have to move on to the List Activity, and by pressing back button from List Activity i need to show Home page, not Details Page. This will work, if you dont call finish() for any of the activity Home > List > Details. Now, you can call Details from Details many times, for this, what I suggested, this is a dummy code: public class Details extends Activity{ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); /* * If user presses back button, handle it like this: */ if(requestCode == REQUEST_DETAILS) { if(resultCode == RESULT_FINISH) { finish(); } } // In this way all your Details Activity will get finished. } @Override public void onBackPressed() { super.onBackPressed(); /* * If user presses back button, call following: * * set some flag as TRUE, ex.: * * flagIsFinishing = true; * * setResult(RESULT_FINISH); * finish() */ } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* * if(flagIsFinishing) { * setResult(RESULT_FINISH); * finish(); * } * */ } @Override protected void onResume() { super.onResume(); /* * On selecting any option call Details activity like * * startActivityForResult(intent, REQUEST_DETAILS); */ } } A: i solved the issue by using a flag in OnResume() In Details page when List button is clicked i am calling onBackPressed();, at that time i am setting a boolean flag to be true. by default if the Detail Activity is called for the first time it gets back to the previous activity ie List Activity. If the Detail activity is called for n number of times, and the List button is clicked, with boolean value true, in onResume i have called the function onBackPressed(); and it gets moved to the List Activity
doc_23531059
- (void)getData { ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[dataUrl stringByAppendingFormat:@"%@",self.selectedID]]]; [request setResponseEncoding:NSUTF8StringEncoding]; SBJSON *parser = [[SBJSON alloc] init]; NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithCapacity:3]; [data setObject:self.username forKey:@"username"]; [data setObject:self.password forKey:@"password"]; NSString *dataJSON = [parser stringWithFragment:data error:nil]; [request appendPostData:[dataJSON dataUsingEncoding:NSUTF8StringEncoding]]; [request setDelegate:self]; [request setDidFinishSelector:@selector(requestSuccess:)]; [request setDidFailSelector:@selector(requestFailed:)]; [self.queue addOperation: request]; [self.queue go]; } - (void)requestSuccess:(ASIHTTPRequest *)request { NSLog(@"success: %@", [request responseString]); } A: I managed to fix this. Following is the change! ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[dataUrl stringByAppendingFormat:@"%@",self.selectedID]]]; [request setResponseEncoding:NSUTF8StringEncoding]; -- > Wrong!!! request.defaultResponseEncoding = NSUTF8StringEncoding; --> Correct!
doc_23531060
As the string length is variable, storing a relatively short string on relational database system will cause significant waste of space so, there is a NoSQL database system that makes this possible? EDIT This large strings are base64-encoded images. When I get an encoded image I have to generate data from it and give a response. Generate the data takes time and the images can repeat, this motivates the storing of the image and associated data. To fetch data associated to specific image, the query should ask for the image itself because it's all I receive
doc_23531061
The function box creates a single box (which will get repeated using the addMultipleBox function) and adds a mouseover event. In this scenario the mouseover works correctly function box() { let square = document.createElement('div') square.setAttribute('class', 'box') container.appendChild(square) square.addEventListener('mouseover', () => { square.classList.add('blackPen') }) } //creates the etch a sketch board with multiple 'boxes' function addMultipleBoxes() { for(let i = 0; i < 256; i++) { box() } } Now if I try and grab the class of 'box' outside the function and add an event listener to it nothing happens. I do have this code at the bottom so it's not like i'm trying to grab divs before they are created. I'd like to be able to grab it outside so I can create another function that on a mouse click I remove the class of 'blackPen' which will remove the background color of black on the square, essentially wiping the board clean. Here is what I have for that let boxx = document.querySelector('.box') console.log(boxx) boxx.addEventListener('mouseover', () => { boxx.classList.add('blackPen') }) When I console.log 'Boxx' I get the <div class="box"></div>. If I console.log "square" above in the box function I get the same thing as Boxx. Any insight would be much appreciated! A: The box() function adds the class to each element as it is made, as required. A reference made to an element using querySelector contains only one element - the first in the document with the specified selector. See https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector This snippet illustrates the idea with four divs, all the same class. let boxx = document.querySelector('.box') boxx.addEventListener('mouseover', () => { boxx.classList.add('blackPen') }) .box { display: inline-block; width: 70px; aspect-ratio: 1; background: yellow; border: 1px solid red; } .blackPen { background: black; } <p><b>mouseover applied to element got by querySelector</b></p> <p>(move mouse over divs)</d> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <p>querySelector, returns the <em>first</em> Element within the document that matches the specified selector</p> A reference to all elements with a given class can be made using querySelectorAll(), which returns a live node list with references to all the elements of the given selector. See: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll Having made the reference, you will still have to loop through them in order to add the event listeners required. node lists and html collections are array-like structures that can have individual members referenced by and index [0],[1], and so on. This snippet illustrates adding a new class to each div in a node list formed using querySelectorAll: let boxx = document.querySelectorAll('.box') for (let i=0; i<boxx.length; i++) { boxx[i].addEventListener('mouseover', () => { boxx[i].classList.add('blackPen'); boxx[i].classList.remove('cancel'); }); boxx[i].addEventListener('click', () => { boxx[i].classList.add('cancel') }); } // next i boxx element; .box { display: inline-block; width: 70px; aspect-ratio: 1; background: yellow; border: 1px solid red; } .blackPen { background: black; } .cancel { background: yellow; } <p><b>mouseover applied to all elements got by querySelectorAll</b><br>(move mouse over divs)</d> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <p>A click event was also added to all elements, to replace the class added by the mouseover event<br>click boxes to see the effect</p> Note that the node collection only needs to be made once to be used for any further manipulations. In the snippet a mouseover event adds a class to make the background black while a click event cancels it.
doc_23531062
Using excel 2016 desktop. I have tried researching problem but am limited knowledge to know what to search for to describe the issue I am having. I recorded a macro with (Ctrl+n assigned) to add a new line in a worksheet and copy some formulas down (its a record of variations on a project, each time a new variation is requested we add a line to record it). This was working absolutely fine, until... I tried a little VBA to 'use sheet name as date' but deleted it as found another way to do what I wanted. Since I deleted this macro the first one (Ctrl+n above) now opens a new workbook instead of adding a new line! When I run the macro from Macros Dialogue window 'Run' it works fine but if I use 'Ctrl n' it opens a new workbook instead! Please can you help.. Thank You Sub NewVariation() ' ' NewVariation Macro ' ' Keyboard Shortcut: Ctrl+n ' Cells.Find(What:="notes", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate Selection.End(xlUp).Select Rows("10:10").Select Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove Range("I9").Select Selection.Copy Range("I10").Select ActiveSheet.Paste Range("L9:M9").Select Application.CutCopyMode = False Selection.Copy Range("L10").Select ActiveSheet.Paste Range("P9").Select Application.CutCopyMode = False Selection.Copy Range("P10").Select ActiveSheet.Paste End Sub A: It is resolved. I opened the macro dialogue box, highlighted the 'NewVariation' macro and opened 'options' which was showing a blank entry on the 'shortcut key Ctrl+' so I added 'n' and closed the box so it now works. I have no idea why this made it start working properly again or why its stopped in the first place! Thank you anyone that was looking to help and would still appreciate an answer as to what has occurred but understand otherwise. Thank You
doc_23531063
This successful experience makes me to think that WINE must in turn call some Linux API (X, xfs, ...?) and then provide my program the results I want. Now I would like to get the same list directly from Linux in C or C++. Which way should I take in order to achieve this goal? What API documentations should I study? A: WINE font inspires me a lot, but I decide to stop researching the solution for my own question as the technology required to retrieve printer fonts in X window seems to be not trivial. I choose to use the font list given by Delphi's TPrinter running in WINE instead. I close this question.
doc_23531064
waveformCache is assumed to be a global var cL = document.getElementById('track' + trackId + 'WaveformL'); var cR = document.getElementById('track' + trackId + 'WaveformR'); if (waveformCache.hasOwnProperty(track.path)) { var waveformCacheItem = waveformCache[track.path]; if (waveformCacheItem.hasOwnProperty('left')) { // restore canvas data here to cL element } } else { waveformCache[track.path] = {}; var left = track.data.getChannelData(0); var ctx1 = cL.getContext('2d'); ctx1.save(); ctx1.strokeStyle = 'rgb(49,73,11)'; ctx1.translate(0, 55/2); //centers where the line drawing starts horizontally for(var i = 0; i < left.length; i += 200) { var x1 = Math.floor(track.waveformLength * i / left.length); //first parameter affects the length of the drawn waveform #ZOOM var y1 = left[i] * 55/2; ctx1.beginPath(); ctx1.moveTo(x1, 0); ctx1.lineTo(x1 + 1, y1); ctx1.stroke(); } ctx1.restore(); waveformCache[track.path].left = ctx1; } A: An outline of how to serialize an html5 canvas CanvasRendingContext2D The canvas context (CanvasRendingContext2D ) holds the canvas' properties (styling, current transformation, etc). Important! The context does not hold all the executed drawing commands that created the canvas content. Context Properties: * *Coloring: strokeStyle, fillStyle(1), globalAlpha, *Line styles: lineWidth, lineCap, lineJoin, miterLimit, *Text Styles: font, textAlign, textBaseline, *Compositing: globalCompositeOperation, *Shadowing: shadowColor, shadowBlur, shadowOffsetX, shadowOffsetY (1) fillStyle is usually a string ('#ff0000'), but it can alternatively hold a reference to a gradient object or pattern object. To save the context's fillStyle, you will have to either ignore gradients / patterns or also serialize the gradient / pattern properties. Here's how to save context properties into an object var properties=['strokeStyle','lineWidth','font','globalAlpha', 'globalCompositeOperation','shadowColor','shadowBlur', 'shadowOffsetX','shadowOffsetY','lineCap','lineJoin', 'miterLimit','textAlign','textBaseline']; var serializedContext={} for(var i=0;i<properties.length;i++){ var prop=properties[i]; serializedContext[prop]=context[prop]; } // fillStyle can be a headache if(typeof context.fillStyle === 'string'){ serializedContext['fillStyle']=context.fillStyle; }else{ // do lots more work to serialize gradient or pattern :-O } Here's how to copy saved context properties into a new context: var context=myOtherCanvas.getContext('2d'); for(var i=0;i<properties.length;i++){ var prop=properties[i]; context[prop]=serializedContext[prop]; } // fillStyle can be a headache if(typeof context.fillStyle === 'string'){ serializedContext['fillStyle']=context.fillStyle; }else{ // do lots more work to re-establish gradient or pattern :-O } Re-executing the drawings If you want to re-execute all the drawings commands, you must save the commands and their arguments. From your example code, it looks like your drawings involve line segments(moveTo & lineTo) so you can save each segment as a segment-object in an array of segment-objects. var segments=[]; segments.push({moveX:10, moveY:20, lineX:100, lineY:35}); ... and push all the other line segments And then you can "replay" the line-segment drawing commands after you've reset all the context properties: // redraw every line segment ctx.beginPath() for(var i=0;i<segments.length;i++){ var s=segments[i]; ctx.moveTo(s.moveX,s.moveY); ctx.lineTo(s.lineX,s.lineY); } ctx.stroke(); You can also serialize and replay all the common drawing commands (arc, beginPath, bezierCurveTo , clearRect, clip, closePath, fill, fillRect, fillText, lineTo, moveTo, quadraticCurveTo, rect, restore, rotate, save, scale, setTransform, stroke, strokeRect, strokeText, transform, translate). Save each command name & associated arguments in an object and save all those command-objects in an array. These commands return values so you will need to do more work to handle them: measureText, getImageData (putImageData), toDataURL, isPointInPath, isPointInStroke, createImageData, createLinearGradient, createRadialGradient, createPattern. Luckily, these commands are used are used less often than the more common (simpler) commands. About portability If you use this method of saving all properties & drawing commands into object arrays, you can easily serialize them all into JSON strings with JSON.stringify and you can easily deserialize them back into object arrays with JSON.parse. Having your canvas properties & drawing commands serialized to strings means that you can easily transport them to a server for storage and then fetch them for replaying. A: You can use a Path2D object to store your paths commands at. Then store the path in your global object. When you need to re-apply the path, simply stroke or fill using the stored path object. For example: var path = new Path2D(); ... path.moveTo(.. , ..); path.lineTo(.. , ..); etc. Later when you need to recall the path: ctx.stroke(path); (A bonus is that you can initialize it using SVG paths. This means you can just define your path using SVG commands and store that as a single string. Reapply using the route of Path2D at a slight cost of performance when initializing.) Path2D can be polyfilled for browsers which do not yet support it (see notes for special cases).
doc_23531065
public ref class MyClass { public: property double x { double get(); void set(double value); } MyClass(); } If I use a pointer to instantiate the object I can set the x property like this : MyClass^ obj = gcnew MyClass(); obj->x = 10.0; If I do not use a pointer, then I have a compilation error (C2228: left of '.x' must have class/struct/union) using this code : MyClass obj(); obj.x = 10.0; What should I do for the second example ? Is this syntax issue specific to properties or to any member of a non-pointed object ? A: You just got trapped by the most vexing parse: MyClass obj(); This does not define a variable obj of type MyClass. If declares a function obj that takes no parameter and returns MyClass. Just write this instead: MyClass obj; obj.x = 10.0; Or this: MyClass obj{}; obj.x = 10.0; Both compile just fine. obj uses stack semantics despite the fact that MyClass does not implement IDisposable (ie has no ~MyClass member in C++/CLI). A: The second syntax is called stack semantics. It creates the object and "destroys" it, when the variable gets out of scope. In fact not the memory is freed, but Dispose is called for the object. So the second syntax using a period instead of the pointer operator -> is only valid vor objects with stack semantics. See also https://msdn.microsoft.com/en-us/library/ms177191.aspx
doc_23531066
I have a grid within a canvas. The grid is added programmatically, not in xaml and is much smaller than the canvas. I want to programmatically add a control (text box) at the position the user clicks on the grid. The application may or may not be full screen and users screen resolutions may differ. Currently I'm using a mouse down event and getting a point: Dim p As Point = Mouse.GetPosition(myGrid) And then using the point.x and point.y with Canvas.SetLeft and Canvas.SetTop but this only works when the app is full screen and the screen res is consistent. I know it's bad form to ask for code but please include a snippet in your answer as I've been wrestling with this for some time & going round in circles. I'm using VB but answers in any language will be welcome. Thanks very much. A: Grid arranges its children basically mostly on the child's Margin property. So do this OnClick of your grid: // dont forget to add an event handler on creating the grid Grid myGrid = new Grid(); myGrid.MouseDown += myGrid_MouseDown; private void myGrid_MouseDown(object sender, MouserEventArgs e) { Point p = e.GetPosition(myGrid); TextBox tb = new TextBox(); tb.Margin = new Thickness(p.X, p.Y, 0, 0); tb.HorizontalAlignment = HorizontalAlignment.Left; tb.VerticalAlignment = VerticalAlignment.Top; // cuz we set margin on Top and Left sides.. myGrid.Children.Add(tb); } Hope it helps :) A: I think that the problem is not on your code but in your xaml. Mouse.GetPosition(myGrid) should works well. I think that your Grid is not the same size as your Canvas. Try something like this: <DockPanel> <Canvas x:Name="can"> <Grid Height="{Binding ElementName=can, Path=ActualHeight}" Width="{Binding ElementName=can, Path=ActualWidth}" Background="Red" PreviewMouseDown="Grid_PreviewMouseDown" /> </Canvas> </DockPanel>
doc_23531067
I think I forget something.. I try to do the configuration, but I have an error : "cannot use new with an expression whose type lacks a call or construct signature" So how can I use a constructor here .. ? Must I create a component in React ? This is my code : import * as Sequelize from 'sequelize' const sequelize = new Sequelize('mysql://root@localhost:3306/dbtestseq', { timestamps: true, paranoid: true } as Sequelize.Options) export default sequelize Thank you
doc_23531068
var myVariable = document.getElementById('mydropdownlist'); But I want to pull it using a selection in the dropdown list: So something like this, but it is not working var mySecondVariable = $('select option:contains("New York")').parent(); Can anyone tell me what the issue is with the second line of code? A: the code is storing the select as an object that contains the select itself instead of storing it as an object of type HTMLSelectElement as you want, if you use var mySecondVariable = $('select option:contains("New York")').parent()[0]; or var mySecondVariable = $('select option:contains("New York")').parent().get(0); it should work perfectly, although I'm not sure if there's any better solution, if so someone should state it. in jQuery FAQs
doc_23531069
public static int partition(List list, ListElement elemL, ListElement elemR){ ListElement elemX; ... elemR = elemX.next; return x; } And at the end of the funktion the elemR is changed, but after calling the function from the main method the parameter elemR has still the same value like before the function call. What's the problem? How can i change this ListElement and "save" this change after the function is called without changing the return type to ListElement (i need the integer return value too)? A: Java functions parameters are called by reference name, meaning that when you place an object as an function argument, the JVM copies the reference's value to a new variable, and passes it to the function as an argument. If you change the contents of the object, then the original object will change, but if you change the actual value of the reference, then these changes will be destroyed when the function ends. I hope it helps
doc_23531070
This is my view: def home(request): symbol = "BTCUSDT" tst = client.get_ticker(symbol=symbol) test = tst['lastPrice'] context={"test":test} return render(request, "main/home.html", context ) And the template's line looks something like this: <h3> var: {{test}} </h3> There are two problems here: 1) From the little i know, Django itself is not asynchronous, so i need to find a way to update that part of the template in real time, without having to refresh the whole page. 2) At the actual moment, the API is requested when the page is opened/refreshed, but to stream the price, it should be always running. I tried this (awful) solution: add a while true in the view, but of course it broke my code, executing only the part the while statement. Any advice is appreciated :) A: You should separate your frontend and backend in order to dynamically update the DOM contents without needing to render the whole DOM each time. The responsibility of frontend would be to request and fetch the latest values when a user does an action that warrant a refresh or fetching of updated data. The request need to made asynchronously via e.g. AJAX. The newer JS frameworks e.g. React, Vue use virtual DOM that use an intermediate virtual DOM that they use to push the updates and finally update the real DOM in a single go; which makes them very performant. The (Django) backend should expose an API that would take (AJAX) requests from backend for specific resources, and serve them. A nice framework for Django is DRF (Django REST Framework), which exposes REST endpoints that you can call from frontend via AJAX and get reponse back so that the frontend can do necessary updates. This is a failrly high level view, and is written to give you an idea that you can implement by digging deeper.
doc_23531071
The db structure looks like this: DB, Please look Okay and i have set the mapping templates as shown below: Mapping Templates Finally my Lambda code: console.log('function starts'); const AWS = require('aws-sdk'); const docClient = new AWS.DynamoDB.DocumentClient({region: 'us-east-2'}); exports.handler = function(event, context, callback){ console.log('processing event: %j', event); let scanningParameters = { TableName: 'users', Key: { "userid": event.userid }, Limit: 1 //maximum result of 1 items }; //In dynamoDB scan looks through your entire table and fetches all data docClient.get(scanningParameters, function(err,data){ if(err){ callback(err, null); }else{ callback(null,data); } }); } TEST TIME However, using CURL to test my progress returns: curl -X GET \ mysite\ -H 'Content-Type: application/json' \ -d '{ “userid”: “some user id” }' But getting: {"errorMessage":"One or more parameter values were invalid: An AttributeValue may not contain an empty string","errorType":"ValidationException","stackTrace":["Request.extractError (/var/runtime/node_modules/aws-sdk/lib/protocol/json.js:48:27)","Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:105:20)","Request.emit (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:77:10)","Request.emit (/var/runtime/node_modules/aws-sdk/lib/request.js:683:14)","Request.transition (/var/runtime/node_modules/aws-sdk/lib/request.js:22:10)","AcceptorStateMachine.runTo (/var/runtime/node_modules/aws-sdk/lib/state_machine.js:14:12)","/var/runtime/node_modules/aws-sdk/lib/state_machine.js:26:10","Request. (/var/runtime/node_modules/aws-sdk/lib/request.js:38:9)","Request. (/var/runtime/node_modules/aws-sdk/lib/request.js:685:12)","Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:115:18)"]}
doc_23531072
This is what my tsconfig.json configuration looks like: { "compilerOptions": { "module": "es6", "target": "es6", "lib": ["es6"], "sourceMap": true, } } Test Case Using a Pair of Modules: I wrote a simple test-case senario using two modules. * *The first module — module1.ts — only exports a constant, as shown below: * * export const testText = "It works!"; *The second module — main.ts — just imports the export from the first module: * * import { testText } from 'module1'; alert(testText); The output file of the second module (or main.js) is embedded in my index.html document, and I have added the type-attribute as type="module" to the <script ...> tag, as is shown below: <script src="main.js" type="module"></script> When I test this with either Firefox (dom.moduleScripts.enabled is set in about:config) or Chrome Canary (Experimental Web Platform flag is set) it doesn't work. The Typescript compiler seems to transpile the TS import { testText } from 'module1';-statement to the JS statement import { testText } from 'module1';. (Note: both are exactly the same) The correct ES6 import-statement would be: import { testText } from 'module1.js'; (Note the .js file extension) If I manually add the file extension to the generated code, it works. Did I do something wrong or does the Typescript "module": "es6" setting just not work correctly? Is there a way to configure the tsc in such a way that .js file extensions are added to the generated import statements? A: This is a confusing design choice in TypeScript. In the short term you can work around it by specifying the output file: in main.ts specify the .js extension and path: import { testText } from './module1.js'; alert(testText); This will pick up module.ts correctly, but output with the .js extension included. Note that you also need to prefix local files with ./ as 'bare' module names are reserved for future use. A: NOTE FROM AUTHOR: "The date that this answer was published is different than the date that the answer was originally created on. Due to changes in TypeScript, I have had to write a new answer twice. Because dates are extremely relevant in this post, I have included them in a couple places, in-case the answer gets stale. This will help readers know when I was referencing certain versions of any technologies that I have written about below." Originally Authored in December of 2021 The "es-module-specifier" Flag Fix for TS, ESM, NODE stacks ESM was not an easy technology to incorporate into Node. And when it came to writing Node ES-Modules in the TypeScript language, well, that actually looked like, at a certain point in time, that it could never happen. IMO, it seemed like certain projects, didn't want to do what they, now have done, to support the Standard in the Node Back-end RTE. Anyhow, lets move on... Initially when I answered this question I suggested that people who are experiencing this issue use the following flag: node --es-module-specifier-resolution=node (FYI: The solution came from the link attached to the snippet) The flag worked, or worked as the best solution up to this point (or well up to TS 4.7 Nightly Release). IT SHOULD BE NOTED That depending on the environment, and the project, that you are working in, this will still be the best solution for now. However, a Better Solution has been Made Available. At this Point in Time Much has Changed: During the Nightly releases of v4.6 TypeScript added support for new module & moduleResolution specifiers, which are ("obviously") set in the tsconfig.json. They were released during the v4.6 nightly builds, just a little while before v4.6 beta was released, and 4.7 became the nightly build. Now, v4.7 is beta, and v4.8 is the new nightly build (I mention all this version stuff, just to make sure your up to date). These are the new specifiers/settings that TS has given to us * *"module": "NodeNext" *"moduleResolution": "NodeNext" It has been Announced that v4.7 will include the new settings The reason I say this is because, the new TSC-flags (aka tsconfig settings) were available in v4.6, which, if you remember, I stated a couple paragraphs ago, however; TypeScript decided not to release them in the current latest version (typescript@latest) version which is v4.6. So, they will be included in TypeScript officially, when v4.7 is no longer in beta, and becomes the latest version. They should always be used with "esModuleInterop": true, (unless somethings change on the "Node.js" side of things. The "esModuleInterop" setting eases support for ESM, and some of the node modules will need it to work properly with the new ESM import/export module system. This is the ESM tsconfig.*.json configuration template, which I add as a starting point to each new project. "compilerOptions": { // Obviously you need to define your file-system "rootDir": "source", "outDir": "build", // THE SETTINGS BELOW DEFINE FEATURE SUPPORT, MODULE SUPPORT, AND ES-SYNTAX SUPPORT "lib": ["ESNext"], "target": "ES2020", "module": "NodeNext", "moduleResolution": "NodeNext", "esModuleInterop": true, // Eases ESM support "types": ["node"], "allowSyntheticDefaultImports": true, } Written on: MAY 22nd, 2022 8:50am PST Gaining Support for the module & moduleResolution Specifiers So you have a couple different TS versions you can use to support the new configurations. You can either use Beta or Nightly. Below is a chart that demonstrates the 3 available versions. As of right now, typescript@latest is @ v4.6, and does not support the new configurations. TS RELEASE VERSION NPM COMMAND TO EXECUTE HAS SUPPORT? TS Latest v4.6 npm i -D typescript@latest NO TS Beta v4.7 npm i -D typescript@beta YES TS Nightly v4.8 npm i -D typescript@next YES Configure your Development Environment to use the Latest Ver You need to configure your environment to use the new TypeScript version. I obviously cannot document ever editor's configuration, but V.S. Code seems to be the most common for TypeScript, and V.S. 2022 uses a similar configuration. In VS Code, you will add the following configuration to your workspace ./.vscode/settings.json file. // "./.vscode/settings.json" { "typescript.tsdk": "./node_modules/typescript/lib",} Configuring Your Runtime Environment (Which, for this answer, is Node.js) But why is this so? Why do I need to configure my RTE? Whats the deal??? Doesn't the RTE know everything? * *No, the RTE doesn't just automatically know everything. It has to have some sort of instructions, or clues. **But didn't we already Configure the tsconfig.json file? * *Yes, but that is for TypeScript, now we need to make sure node is ready for our TS configuration. We need to tell node that we are going to be executing an ECMAScript Module, and not a CommonJS module. We can do this one of two different ways. * *The first is to configure our package.json file using the package.json configuration file's "type" field. // @file "package.json" { "name": "project-name", "version: "2.4.16", "type": "module", // <-- Lets env know this project is an ESM // the rest of your package.json file configuration... } *Alternatively, you can do the some thing as above, but by using the --input-type "module" flag *Lastly, you can do, what I prefer to do, and just create each file using the ESM file extensions. In js it is .ejs, and in typescript it is .ets. For Example, your index file will be index.ets and TSC will emit index.ejs. Lastly, its IMPORTANT that you understand how imports work when writing an "ES-Module". I will list some notes, I think that will be the best format for this info. * *You have to use JavaScript file extensions when importing files. *ESM imports are imported using URI's, and not by use of "possix filepaths". The opposite was true for CJS Modules. *Special chars must be percent-encoded, such as # with %23 and ? with %3F. *TypeScript won't make you prepend the MimeType, but ESM uses prepended data types so its a best practice to do so. For example, its a best practice to import from Node API's & Libraries using the following URI format: import EventEmitter from 'node:events'; const eEmit = new EventEmitter();
doc_23531073
A: See here for examples on how to use Service Bus output bindings: https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-service-bus#output---javascript-example You should be able to create multiple output bindings for multiple topics as well like this (didn't test it) { "bindings": [ { //... "direction": "in" }, { "name": "outputSbQueue1", "type": "serviceBus", "queueName": "testqueue1", "connection": "MyServiceBusConnection", "direction": "out" }, { "name": "outputSbQueue2", "type": "serviceBus", "queueName": "testqueue2", "connection": "MyServiceBusConnection", "direction": "out" } ], "disabled": false } Output binding for CosmosDB see here: https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-cosmosdb-v2#output---javascript-examples
doc_23531074
I see that Rserve might be the correct system to use as the R server, but all of the examples appear to be Java based. Is there anyone who has built some basic socket connections from Tcl into Rserve that can provide some examples of how to make these connections and pass information in, perform some operations and pass the results back? Currently, I can use Rscript to accomplish this by passing a text file exported from our system, but would like a more elegant solution communicating directly in binary form if possible.
doc_23531075
I just learned from this two source code : //==================================================== file = udpServer.c ===== //= A message "server" program to demonstrate sockets programming = //============================================================================= //= Notes: = //= 1) This program conditionally compiles for Winsock and BSD sockets. = //= Set the initial #define to WIN or BSD as appropriate. = //= 2) This program serves a message to program udpClient running on = //= another host. = //= 3) The steps #'s correspond to lecture topics. = //=---------------------------------------------------------------------------= //= Example execution: (udpServer and udpClient running on host 127.0.0.1) = //= Waiting for recvfrom() to complete... = //= IP address of client = 127.0.0.1 port = 55476) = //= Received from client: Test message from CLIENT to SERVER = //=---------------------------------------------------------------------------= //= Build: bcc32 udpServer.c or cl udpServer.c wsock32.lib for Winsock = //= gcc udpServer.c -lsocket -lnsl for BSD = //=---------------------------------------------------------------------------= //= Execute: udpServer = //=---------------------------------------------------------------------------= //= Author: Ken Christensen = //= University of South Florida = //= WWW: http://www.csee.usf.edu/~christen = //= Email: christen@csee.usf.edu = //=---------------------------------------------------------------------------= //= History: KJC (08/02/08) - Genesis (from server1.c) = //= KJC (09/07/09) - Minor clean-up = //= KJC (09/22/13) - Minor clean-up to fix warnings = //============================================================================= #define WIN // WIN for Winsock and BSD for BSD sockets //----- Include files -------------------------------------------------------- #include <stdio.h> // Needed for printf() #include <string.h> // Needed for memcpy() and strcpy() #include <stdlib.h> // Needed for exit() #ifdef WIN #include <windows.h> // Needed for all Winsock stuff #endif #ifdef BSD #include <sys/types.h> // Needed for sockets stuff #include <netinet/in.h> // Needed for sockets stuff #include <sys/socket.h> // Needed for sockets stuff #include <arpa/inet.h> // Needed for sockets stuff #include <fcntl.h> // Needed for sockets stuff #include <netdb.h> // Needed for sockets stuff #endif //----- Defines -------------------------------------------------------------- #define PORT_NUM 1050 // Arbitrary port number for the server //===== Main program ========================================================= int main() { #ifdef WIN WORD wVersionRequested = MAKEWORD(1,1); // Stuff for WSA functions WSADATA wsaData; // Stuff for WSA functions #endif int server_s; // Server socket descriptor struct sockaddr_in server_addr; // Server Internet address struct sockaddr_in client_addr; // Client Internet address struct in_addr client_ip_addr; // Client IP address int addr_len; // Internet address length char out_buf[4096]; // Output buffer for data char in_buf[4096]; // Input buffer for data int retcode; // Return code #ifdef WIN // This stuff initializes winsock WSAStartup(wVersionRequested, &wsaData); #endif // >>> Step #1 <<< // Create a socket // - AF_INET is Address Family Internet and SOCK_DGRAM is datagram server_s = socket(AF_INET, SOCK_DGRAM, 0); if (server_s < 0) { printf("*** ERROR - socket() failed \n"); exit(-1); } // >>> Step #2 <<< // Fill-in my socket's address information server_addr.sin_family = AF_INET; // Address family to use server_addr.sin_port = htons(PORT_NUM); // Port number to use server_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on any IP address retcode = bind(server_s, (struct sockaddr *)&server_addr, sizeof(server_addr)); if (retcode < 0) { printf("*** ERROR - bind() failed \n"); exit(-1); } // >>> Step #3 <<< // Wait to receive a message from client printf("Waiting for recvfrom() to complete... \n"); addr_len = sizeof(client_addr); retcode = recvfrom(server_s, in_buf, sizeof(in_buf), 0, (struct sockaddr *)&client_addr, &addr_len); if (retcode < 0) { printf("*** ERROR - recvfrom() failed \n"); exit(-1); } // Copy the four-byte client IP address into an IP address structure memcpy(&client_ip_addr, &client_addr.sin_addr.s_addr, 4); // Print an informational message of IP address and port of the client printf("IP address of client = %s port = %d) \n", inet_ntoa(client_ip_addr), ntohs(client_addr.sin_port)); // Output the received message printf("Received from client: %s \n", in_buf); // >>> Step #4 <<< // Send to the client using the server socket strcpy(out_buf, "This is a reply message from SERVER to CLIENT"); retcode = sendto(server_s, out_buf, (strlen(out_buf) + 1), 0, (struct sockaddr *)&client_addr, sizeof(client_addr)); if (retcode < 0) { printf("*** ERROR - sendto() failed \n"); exit(-1); } // >>> Step #5 <<< // Close all open sockets #ifdef WIN retcode = closesocket(server_s); if (retcode < 0) { printf("*** ERROR - closesocket() failed \n"); exit(-1); } #endif #ifdef BSD retcode = close(server_s); if (retcode < 0) { printf("*** ERROR - close() failed \n"); exit(-1); } #endif #ifdef WIN // This stuff cleans-up winsock WSACleanup(); #endif // Return zero and terminate return(0); } and //=========================================== file = udpClientBroadcast.c ===== //= A message "client" program to demonstrate sockets programming = //= - This is udpClient.c modified to use broadcast = //============================================================================= //= Notes: = //= 1) This program conditionally compiles for Winsock and BSD sockets. = //= Set the initial #define to WIN or BSD as appropriate. = //= 2) This program needs udpServer to be running on another host. = //= Program udpServer must be started first. = //=---------------------------------------------------------------------------= //= Example execution: (udpServer and udpClientBroadcast on host 127.0.0.1) = //= Received from server: This is a reply message from SERVER to CLIENT = //=---------------------------------------------------------------------------= //= Build: Windows: Borland: bcc32 udpClientBroadcast.c = //= Visual C cmd line: cl udpClientBroadcast.c wsock32.lib = //= MinGW: gcc udpClientBroadcast.c -lws2_32 = //= Unix: gcc udpClientBroadcast.c -lnsl -o udpClientBroadcast = //=---------------------------------------------------------------------------= //= Execute: udpClientBroadcast = //=---------------------------------------------------------------------------= //= Author: Ken Christensen = //= University of South Florida = //= WWW: http://www.csee.usf.edu/~christen = //= Email: christen@csee.usf.edu = //=---------------------------------------------------------------------------= //= History: KJC (04/10/10) - Genesis (from udpClient.c) = //============================================================================= #define WIN // WIN for Winsock and BSD for BSD sockets //----- Include files --------------------------------------------------------- #include <stdio.h> // Needed for printf() #include <string.h> // Needed for memcpy() and strcpy() #ifdef WIN #include <windows.h> // Needed for all Winsock stuff #endif #ifdef BSD #include <sys/types.h> // Needed for sockets stuff #include <netinet/in.h> // Needed for sockets stuff #include <sys/socket.h> // Needed for sockets stuff #include <arpa/inet.h> // Needed for sockets stuff #include <fcntl.h> // Needed for sockets stuff #include <netdb.h> // Needed for sockets stuff #endif //----- Defines --------------------------------------------------------------- #define PORT_NUM 1050 // Port number used //===== Main program ========================================================== void main(void) { #ifdef WIN WORD wVersionRequested = MAKEWORD(1,1); // Stuff for WSA functions WSADATA wsaData; // Stuff for WSA functions #endif int client_s; // Client socket descriptor struct sockaddr_in server_addr; // Server Internet address int addr_len; // Internet address length char out_buf[4096]; // Output buffer for data char in_buf[4096]; // Input buffer for data int retcode; // Return code int iOptVal; // Socket option value int iOptLen; // Socket option length #ifdef WIN // This stuff initializes winsock WSAStartup(wVersionRequested, &wsaData); #endif // Create a socket client_s = socket(AF_INET, SOCK_DGRAM, 0); if (client_s < 0) { printf("*** ERROR - socket() failed \n"); exit(-1); } // Fill-in server socket's address information server_addr.sin_family = AF_INET; // Address family to use server_addr.sin_port = htons(PORT_NUM); // Port num to use server_addr.sin_addr.s_addr = inet_addr(INADDR_ANY); // Need this for Broadcast // Set socket to use MAC-level broadcast iOptVal = 1; iOptLen = sizeof(int); setsockopt(client_s, SOL_SOCKET, SO_BROADCAST, (char*)&iOptVal, iOptLen); // Assign a message to buffer out_buf strcpy(out_buf, "Test message from CLIENT to SERVER"); // Now send the message to server. retcode = sendto(client_s, out_buf, (strlen(out_buf) + 1), 0, (struct sockaddr *)&server_addr, sizeof(server_addr)); if (retcode < 0) { printf("*** ERROR - sendto() failed \n"); exit(-1); } // Wait to receive a message addr_len = sizeof(server_addr); retcode = recvfrom(client_s, in_buf, sizeof(in_buf), 0, (struct sockaddr *)&server_addr, &addr_len); if (retcode < 0) { printf("*** ERROR - recvfrom() failed \n"); exit(-1); } // Output the received message printf("Received from server: %s \n", in_buf); // Close all open sockets #ifdef WIN retcode = closesocket(client_s); if (retcode < 0) { printf("*** ERROR - closesocket() failed \n"); exit(-1); } #endif #ifdef BSD retcode = close(client_s); if (retcode < 0) { printf("*** ERROR - close() failed \n"); exit(-1); } #endif #ifdef WIN // This stuff cleans-up winsock WSACleanup(); #endif } These two codes works fine for me, however these are 2 applications and I just want 1 application that can act as a server and also as a client. So I combine these two source codes into one using a thread. Again, the program works, but the listener socket accepts the connection from the broadcasted message. What I want is the listener to block the incoming connection from the loopback address. How to do that? edit : example I have 2 computers, one is A(192.168.1.100) and the other is B(192.168.1.101), when i run the program computer A receive the message from itself, what I want is A receive only any except A. EDIT 27/01/2014 : after a few days of searching i think i wasn't be able to find the solution to my problem. however, there's an alternate way to make it possible. first step is to get your local computer IP Address. second step is to construct your message before it is send for example format is "ipAddress_messageToSend". third step create function to process incoming message from recvfrom() function that will split the incoming message by "_" so that you'll have two dimensional arrays, the first row is for IP Address where this message come from and the second is the message itself. fourth step, you'll have to do comparation between incoming message IP Address and your computer IP Address. you can use this code below to obtain an IP Address. char ac[80]; gethostname(ac, sizeof(ac)); struct hostent *phe = gethostbyname(ac); struct in_addr addr; memcpy(&addr, phe->h_addr_list[0], sizeof(struct in_addr)); printf("IP Address is : %s\n", inet_ntoa(addr)); fifth step when the IP is compared and they're same do nothing, if not then do what you want to do. hope this will help you all A: Based on your responses to the comments, the problem is that you the server is receiving messages from the client running in the same node. You want the server to filter out those messages sent out by itself. In order to achieve that the servers needs: 1-Before beginning, server detects its own interfaces and IP addresses. Winsock should have a function like getifaddrs. Here there is a link of a similar question related to Windows: Get the IP Address of local computer You add the list of local addresses in a list or any other data structure. This is a similar problem for UNIX: Lazarus: How to list all the available network connection on a system? 2-Whenever a message is received, after recvfrom, the server compares client_addr.sin_addr.s_addr with the list of own addresses to detect its own messages. Then filter out those messages. I don't think it is possible to filter out messages from itself in a different way, in a simple way. In Linux you could filter out messages from itself using iptables and I don't know if Windows has a similar mechanism. Other recommendations: 1-You should use multicast for your chat application instead of broadcast. Then systems not running the chat application are not affected by the chat messages. 2-You could complement the multicast or broadcast mechanism with a method that assures every peer can read all messages. Broadcast and multicast messages could be lost by a peer. There are various ways to implement it. But that's the next step once you solve this question. A: You're getting data from loopback because you're binding to INADDR_ANY. See this thread for a more complete explanation/example: Using a specific network interface for a socket in windows
doc_23531076
Error: expected ';' before '.' token Here is the code for the debug_iterator_base class that the error is referencing: class debug_iterator_base { private: mutable const debug_iterator_registry* m_registry; mutable const debug_iterator_base* m_next; // this is line 63 ... The obvious problem is: there is no period on that line. If one of the relevant symbols were a macro then I'd have something to go on, but that is not the case. Why does the compiler think there's a period here? Edit: I am using Wind River g++ 4.3.3 to build. It looks like the issue might simply be that this compiler is too old to support mutable const applied to a self-referential member of a class. Defining BOOST_CB_ENABLE_DEBUG to be 0 seems to be a way around this issue.
doc_23531077
I tried to do it using a for loop that checks slices of the appropriate size (3 chars in this case) but get a Type error. I appreciate your help. This is the code I tried: s = 'bobobslobbob' i = 0 counter = -1 for i in s: counter = counter + 1 if s[i:i+2] == 'bob': i = i + 1 print('Number of times bob occurs is:',counter) A: You can do it easily using re.findall >>> import re >>> s = 'bobobslobbob' >>> >>> len(re.findall(r'(?=bob)', s)) 3 A: If not considering overlapping s='bobobslobbob' s.count('bob')
doc_23531078
A: No that's not possible, you can't link an application with mixed versions of Qt, actually you can't even compile it.. if you need something very specific you can extract from the code, but you need a commercial license for this.
doc_23531079
def save_info(self): name = 'hello' var1 = 'other item' var2 = 1 ... TV_SERIES_FIELDS_TO_UPDATE = ['name', 'var2', 'var3', 'var4', ...] for field in TV_SERIES_FIELDS_TO_UPDATE: current_value = getattr_or_none(obj, field) new_value = # how do I get the variable of `name` ("hello") ? Given a string of the variable name, how would I get its value within the current function? A: Use locals(): def save_info(): name = 'hello' var1 = 'other item' var2 = 1 TV_SERIES_FIELDS_TO_UPDATE = ['name', 'var1', 'var2'] for field in TV_SERIES_FIELDS_TO_UPDATE: print field, locals()[field] save_info() However, I'd urge you consider using an explicit dictionary instead of having a bunch of unrelated variables. A: You have two option Access local variables def save_info(self): name = 'hello' var1 = 'other item' var2 = 1 ... TV_SERIES_FIELDS_TO_UPDATE = ['name', 'var2', 'var3', 'var4', ...] for field in TV_SERIES_FIELDS_TO_UPDATE: current_value = getattr_or_none(obj, field) new_value = locals().get(field) but if I were you I would rewrite the code and use dictionary. TV_SERIES_FIELDS_TO_UPDATE = { 'name_of_the_show': 'value', 'second_show': 'value2' } for key, value in TV_SERIES_FIELDS_TO_UPDATE.items(): new_value = # od some magic with value
doc_23531080
A: There isn't, unfortunately. You'll have to do it with JavaScript or on the server side. A: Not really. There was an effort to allow for a :contains() selector but that got removed. Here's a sneaky way to get the effect you want, though I suspect what you really need to do is fix the way your JavaScript executes sorts. So what you can do is add an attribute to your list, I've called mine data-score and replicate the scores. Then using the CSS attribute match selectors, you add some content, the "E", and alongside that you make the "E" black, and the original content ("O") white. <style type="text/css"> ul { list-style-type: none; } /* turn the "0" white */ li[data-score="0"] { color: #fff; } /* make an E, in black */ li[data-score="0"]:before { content: "E"; color: #000; } </style> <ul> <li data-score="100">100</li> <li data-score="0">0</li> <li data-score="10">10</li> <li data-score="5">5</li> <li data-score="100">100</li> </ul> Which will display as: 100 E 10 5 100 With the "0" really being there, but not visible. Read more about: :before selector, content, data attributes. Additionally, if you just plain output the "E" for a "0", and use data attributes for the sort, you can avoid the CSS hackery I'm suggesting.
doc_23531081
It's not my code, but i found it very useful. This is the code: * *The values ​​are read from an excel document *As you can see I'm trying to play around with this command colors=plt.cm.jet((R)/(Rmax)), but it's not working. import pandas as pd import numpy as np import matplotlib.pyplot as plt import mpl_toolkits.mplot3d.axes3d as axes3d # Read data file and plot df = pd.read_csv('EIRP_Data.csv') #henter data fra Excel theta1d = df['Theta'] theta1d = np.array(theta1d); theta2d = theta1d.reshape([37,73]) #"Theta" kolonen blir hentet ut, satt i numpy array og gjort om til 2d array phi1d = df['Phi'] phi1d = np.array(phi1d); phi2d = phi1d.reshape([37,73]) #"Phi" kolonen blir hentet ut, satt i numpy array og gjort om til 2d Array power1d = df['Power'] power1d = np.array(power1d); power2d = power1d.reshape([37,73]) #"Power" kolonen blir hentet ut, satt i numpy array og gjort om til 2d array THETA = np.deg2rad(theta2d) PHI = np.deg2rad(phi2d) R = power2d Rmax = np.max(R) Rmin = np.min(R) N = R / Rmax #Gjør om polar til kartesisk X = R * np.sin(THETA) * np.cos(PHI) Y = R * np.sin(THETA) * np.sin(PHI) Z = R * np.cos(THETA) fig = plt.figure() #plot spesifikasjoner/settings ax = fig.add_subplot(1,1,1, projection='3d') ax.grid(True) ax.axis('on') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_zticklabels([]) #colors =plt.cm.jet( (X.max()-X)/float((X-X.min()).max())) colors =plt.cm.jet( (R)/(Rmax) ) ax.plot_surface( X, Y, Z, rstride=1, cstride=1, facecolors=colors, linewidth=0, antialiased=True, alpha=0.5, zorder = 0.5) ax.view_init(azim=300, elev = 30) # Add Spherical Grid phi ,theta = np.linspace(0, 2 * np.pi, 40), np.linspace(0, np.pi, 40) PHI, THETA = np.meshgrid(phi,theta) R = Rmax X = R * np.sin(THETA) * np.cos(PHI) Y = R * np.sin(THETA) * np.sin(PHI) Z = R * np.cos(THETA) ax.plot_wireframe(X, Y, Z, linewidth=0.5, rstride=20, cstride=20) plt.show() A: I have the following code to consider the radius for the color scale. The thing that did the trick was using a colormap to get the color values for the normalized R (here color-weights). X = np.ones((phiSize, thetaSize)) # Prepare arrays to hold the cartesian coordinate data. Y = np.ones((phiSize, thetaSize)) Z = np.ones((phiSize, thetaSize)) color_weight = np.ones((phiSize, thetaSize)) min_dBi = np.abs(df["dBi"].min()) for phi_idx, phi in enumerate(np.unique(df["Phi"])): for theta_idx, theta in enumerate(np.unique(df["Theta"])): e = df.query(f"Phi=={phi} and Theta=={theta}").iloc[0]["dBi"] e = min_dBi + e # so we dont have any negative numbers xe, ye, ze = sph2cart1(e, math.radians(theta), math.radians(phi)) # Calculate cartesian coordinates X[phi_idx, theta_idx] = xe # Store cartesian coordinates Y[phi_idx, theta_idx] = ye Z[phi_idx, theta_idx] = ze color_weight[phi_idx, theta_idx] = e ax.plot_surface(X, Y, Z, color='b') # Plot surface plt.ylabel('Y') plt.xlabel('X') # Plot formatting plt.show() with phisizeand thetaSize the number of unique phis and thetas in my data. The dBi of my antenna was stored in a pandas in the dBi column. A: I can't see the dataset but i think all about tuples. If you delete "facecolors=colors" in plot_surface and then replace this: cmap=plt.get_cmap('jet') I think the problem will be solved.
doc_23531082
So I will be grateful if anyone can please help me out with this issue. Here is my full Plugin Code : <?php /* Plugin Name: CiviCRM Contribution Later Payment Plugin URI: http://www.stackoverflow.com/cv/nicefellow1234 Description: This plugin helps in paying due contribution payments through a web form by entering Contribution ID. Author: Umair Shah Yousafzai Version: 1.0 Author URI: http://www.huntedhunter.com/mycv/ */ function my_plugin_activate() { // DO your activation task. /* $post_id = wp_insert_post( array( 'post_status' => 'publish', 'post_type' => 'page', 'post_title' => 'Contribution Later Payment Page', 'post_content' => 'Pay Your Contribution Payment Now.' ) ); if ($post_id) { error_log("New Page Added."); } */ } register_activation_hook(__FILE__,"my_plugin_activate"); function cl_pay() { if ($_POST) { if ($_POST['cl_check_email']) { $contact_email = $_POST["contact_email"]; global $wpdb; $sql = $wpdb->prepare("SELECT * FROM civicrm_contact WHERE sort_name = %s", $contact_email); $results = $wpdb->get_results($sql); $count = count($results); $contact_id = $results[0]->id; if (!$count > 0 ) { $sql = $wpdb->prepare("SELECT * FROM civicrm_email WHERE email = %s", $contact_email); $results = $wpdb->get_results($sql); $count = count($results); $contact_id = $results[0]->contact_id; } } if ($_POST['cl_check_phone']) { $contact_phone = $_POST["contact_phone"]; global $wpdb; $sql = $wpdb->prepare("SELECT * FROM civicrm_phone WHERE phone = %s", $contact_phone); $results = $wpdb->get_results($sql); $count = count($results); $contact_id = $results[0]->contact_id; } if ($_POST['cl_check_full_name']) { $first_name = $_POST["first_name"]; $last_name = $_POST["last_name"]; $full_name = $first_name." ".$last_name; global $wpdb; $sql = $wpdb->prepare("SELECT * FROM civicrm_contact WHERE display_name = %s", $full_name); $results = $wpdb->get_results($sql); $count = count($results); $contact_id = $results[0]->id; //echo "<pre>"; //print_r($results); //echo "</pre>"; } $sql = $wpdb->prepare("SELECT * FROM civicrm_contribution WHERE contact_id = %s", $contact_id); $results = $wpdb->get_results($sql); $count = count($results); $amount = $results[0]->total_amount; if ($count > 0) { setcookie("display_check", "none", time()+5); } if (isset($amount)) { setcookie("display_amount", "block", time()+5); } } ?> <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,400italic,600' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('#choice').change(function () { if ( this.value === 'option_1' ) { $("#option_1").show("slow"); $("#option_2").hide("slow"); $("#option_3").hide("slow"); } else if ( this.value === 'option_2' ) { $("#option_2").show("slow"); $("#option_1").hide("slow"); $("#option_3").hide("slow"); } else if ( this.value === 'option_3' ) { $("#option_3").show("slow"); $("#option_1").hide("slow"); $("#option_2").hide("slow"); } else if ( this.value === 'not_specified' ) { $("#option_1").hide("slow"); $("#option_2").hide("slow"); $("#option_3").hide("slow"); } }); }); </script> <style> html { height: 100%; /*Image only BG fallback*/ background: url('http://thecodeplayer.com/uploads/media/gs.png'); /*background = gradient + image pattern combo*/ background: linear-gradient(rgba(196, 102, 0, 0.2), rgba(155, 89, 182, 0.2)), url('http://thecodeplayer.com/uploads/media/gs.png'); } body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, form, fieldset, input, textarea, p, blockquote, th, td { padding:0; margin:0;} fieldset, img {border:0} ol, ul, li {list-style:none} :focus {outline:none} body, input, textarea, select { font-family: 'Open Sans', sans-serif; font-size: 16px; color: #4c4c4c; } p { font-size: 12px; width: 150px; display: inline-block; margin-left: 18px; } h1.testboxh1 { font-size: 32px; font-weight: 300; color: #4c4c4c; text-align: center; padding-top: 10px; margin-bottom: 10px; } html{ background-color: #ffffff; } .testbox { margin: 20px auto; width: 455px; -webkit-border-radius: 8px/7px; -moz-border-radius: 8px/7px; border-radius: 8px/7px; background-color: #ebebeb; -webkit-box-shadow: 1px 2px 5px rgba(0,0,0,.31); -moz-box-shadow: 1px 2px 5px rgba(0,0,0,.31); box-shadow: 1px 2px 5px rgba(0,0,0,.31); border: solid 1px #cbc9c9; } input[type=radio] { visibility: hidden; } form{ margin: 0 30px; text-align:center; } label.radio { cursor: pointer; text-indent: 35px; overflow: visible; display: inline-block; position: relative; margin-bottom: 15px; } label.radio:before { background: #3a57af; content:''; position: absolute; top:2px; left: 0; width: 20px; height: 20px; border-radius: 100%; } label.radio:after { opacity: 0; content: ''; position: absolute; width: 0.5em; height: 0.30em; background: transparent; top: 7.5px; left: 4.5px; border: 3px solid #ffffff; border-top: none; border-right: none; -webkit-transform: rotate(-45deg); -moz-transform: rotate(-45deg); -o-transform: rotate(-45deg); -ms-transform: rotate(-45deg); transform: rotate(-45deg); } input[type=radio]:checked + label:after { opacity: 1; } hr{ color: #a9a9a9; } input[type=text],input[type=password],select { text-align:center; width: 200px; height: 39px; -webkit-border-radius: 0px 4px 4px 0px/5px 5px 4px 4px; -moz-border-radius: 0px 4px 4px 0px/0px 0px 4px 4px; border-radius: 0px 4px 4px 0px/5px 5px 4px 4px; background-color: #fff; -webkit-box-shadow: 1px 2px 5px rgba(0,0,0,.09); -moz-box-shadow: 1px 2px 5px rgba(0,0,0,.09); box-shadow: 1px 2px 5px rgba(0,0,0,.09); border: solid 1px #cbc9c9; margin-left: -5px; margin-top: 13px; padding-left: 10px; } input[type=password]{ margin-bottom: 25px; } #icon { width: 30px; height:20px; background-color: #3a57af; padding: 8px 0px 8px 15px; margin-left: 15px; margin-top: -10px; -webkit-border-radius: 4px 0px 0px 4px; -moz-border-radius: 4px 0px 0px 4px; border-radius: 4px 0px 0px 4px; color: white; -webkit-box-shadow: 1px 2px 5px rgba(0,0,0,.09); -moz-box-shadow: 1px 2px 5px rgba(0,0,0,.09); box-shadow: 1px 2px 5px rgba(0,0,0,.09); border: solid 0px #cbc9c9; } .gender { margin-left: 30px; margin-bottom: 30px; } .accounttype{ margin-left: 8px; margin-top: 20px; } input.button { text-align:center; font-size: 14px; font-weight: 600; color: white; padding : 8px 30px 8px 30px; text-decoration: none; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; background-color: #3a57af; -webkit-box-shadow: 0 3px rgba(58,87,175,.75); -moz-box-shadow: 0 3px rgba(58,87,175,.75); box-shadow: 0 3px rgba(58,87,175,.75); transition: all 0.1s linear 0s; } input.button:hover { top: 3px; background-color:#2e458b; -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; } </style> </br></br></br></br> <div class="testbox"> <h1 class="testboxh1">Pay Due Contribution Pay</h1> <div class="pay_check" style="display:<?php if (!isset($_COOKIE['display_check'])) {echo "block";} else {echo $_COOKIE['display_check']; }?>;"> <form action="" method="post" > <hr> <!---<div class="accounttype"> <input type="radio" value="None" id="radioOne" name="account" checked/> <label for="radioOne" class="radio" chec>Personal</label> <input type="radio" value="None" id="radioTwo" name="account" /> <label for="radioTwo" class="radio">Company</label> </div> ---> <center><h3>::Search By::</h3></center> <select name="choice" id="choice"> </br> <option value="not_specified">Not Specified</option> <option value="option_1">Contact Email</option> <option value="option_2">Contact Phone</option> <option value="option_3">Full Name</option> </select> <div id="option_1" style="display:none;"> <hr> <center><h3 style="padding-top: 10px;">::Enter Contact Email::</h3></center> <form action="" method="post" > <input type="text" name="contact_email" placeholder="Contact Email" style="width:250px;"></br> </br> <input type="submit" name="cl_check_email" class="button" value="Check"> </form> </br><hr> </div> <div id="option_2" style="display:none;"> <hr> <center><h3 style="padding-top: 10px;">::Enter Contact Phone No::</h3></center> <form action="" method="post" > <input type="text" name="contact_phone" placeholder="Contact Phone No" style="width:250px;"> </br> </br> <input type="submit" name="cl_check_phone" class="button" value="Check"> </form> </br><hr> </div> <div id="option_3" style="display:none;"> <hr> <form action="" method="post" > <center><h3 style="padding-top: 10px;">::Enter Full Name::</h3></center> <input type="text" name="first_name" placeholder="First Name"> <input type="text" name="last_name" placeholder="Last Name"></br> </br> <input type="submit" name="cl_check_full_name" class="button" value="Check"> </form> </br><hr> </div> </br> <!-- <label id="icon" for="cl_id"><i class="fa fa-tag " style="padding-right: 13px;"></i></label> <input type="text" name="cl_id" id="cl_id" placeholder="Contribution ID" required/></br> --> </br></br> </div> <div class="cl_pay" style="display:<?php if (!isset($_COOKIE['display_amount'])) {echo "none";} else {echo $_COOKIE['display_amount']; }?>;"> <form action="" method="post" > <hr> <label id="icon" for="cl_pay" style="border-radius:4px;padding-right: 100px;padding-left: 100px;background-color:#422252;"><i class="fa fa-usd " style=""> <strong><?php echo $amount; ?></strong></i></label> </br> <hr> <input type="submit" name="cl_pay" class="button" value="Pay"> </br></br> </form> </div> </div> <?php } add_shortcode("cl-pay", "cl_pay"); function my_plugin_deactivate() { // DO your activation task. error_log("My Plugin Got Deactivated."); } register_deactivation_hook(__FILE__,"my_plugin_deactivate"); ?> The Error which I am getting is : Warning: Cannot modify header information - headers already sent by (output started at D:\xampp\htdocs\civicrm_development\wp-includes\class.wp-scripts.php:180) in D:\xampp\htdocs\civicrm_development\wp-content\plugins\civicrm_later_contribution_pay.php on line 97 Warning: Cannot modify header information - headers already sent by (output started at D:\xampp\htdocs\civicrm_development\wp-includes\class.wp-scripts.php:180) in D:\xampp\htdocs\civicrm_development\wp-content\plugins\civicrm_later_contribution_pay.php on line 100 Besides on Line 97 & 100 I have following code : 97 : if ($count > 0) { setcookie("display_check", "none", time()+5); } 100 : if (isset($amount)) { setcookie("display_amount", "block", time()+5); } } A: I faced the same thing when I was working with my new PHP Server. You need to do two things to tackle this issue. * *Never ever allow any HTML to escape before the headers are sent. (Very Tough) *Turn on Output Buffering. (Best and Easy way) To turn on Output Buffering, you need to set in your php.ini: output_buffering On Or in your program: ini_set("output_buffering", 1); // OR ob_start();
doc_23531083
bus.$on('loadTeams', (data) => { this.$store.dispatch('updateTeams', data) }) bus.$on('loadDepartments', (data) => { this.$store.dispatch('updateDepartments', data) }) They both get called correctly (I've confirmed that...). Now, in my vuex store.js, I have this: mutations: { .... updateDepartments: (state, payload) => { state.departments = payload }, updateTeams: (state, payload) => { state.teams = payload }, ... } updateTeams works fine, but updateDepartments errors with: [vuex] unknown action type: updateDepartments ...but I just can't see why. Any ideas? A: if you want to call mutations directly dont dispatch but use commit. Dispatch is for actions. This video helped me understand the difference: https://www.youtube.com/watch?v=nFh7-HfODYY A: You do not dispatch a mutation, you commit it, so change the code to bus.$on('loadTeams', (data) => { this.$store.commit('updateTeams', data) }) bus.$on('loadDepartments', (data) => { this.$store.commit('updateDepartments', data) })
doc_23531084
My idea was to use the vlookup function to find the row which has the date of the respective day and to paste the value brought in by the refresh button. So I tried the following VBA script: (in the code "Today" is the name I gave to the day's date (31/01/2014 above) and "DI" is the info I want to update (10,27 above) Sub Test1() Dim SearchDI As Range Set SearchDI = WorksheetFunction.VLookup(Range("Today"), Range("A:B"), 2, 0) Range("DI").Select Selection.Copy Range("SearchDI").Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False End Sub It didn't work. Does anybody know what approach could I use to look for the present date in a list and copy the value on the cell next to it?
doc_23531085
SELECT sum(Qty) AS Qty FROM sap_rekap_bc23 INNER JOIN masterunit_sap ON masterunit_sap.unit = sap_rekap_bc23.Unit WHERE Qty>0 AND invno='T62TJ92013' GROUP BY HS_Code,HS_Desc,unit_tpb,Curr,Price,invno And the result show up Qty = 3144.6 But when i try insert to another table with my code (on PHP) $qryuraian = "SELECT sum(Qty) AS Qty FROM sap_rekap_bc23 INNER JOIN masterunit_sap ON masterunit_sap.unit = sap_rekap_bc23.Unit WHERE Qty>0 AND invno='T62TJ92013' GROUP BY HS_Code,HS_Desc,unit_tpb,Curr,Price,invno"; $listuraian = mysql_query($qryuraian,$conn); while($item=mysql_fetch_array($listuraian)) { $inserttmp = "INSERT INTO tmp_sap_rekap_bc23 (Qty) VALUES ('".$item['Qty']."')"; //mysql_query($inserttmp,$connweb); } The Result my Qty on tmp_sap_rekap_bc23 show 3145. Why my data instant became rounded?? even tough my table tmp_sap_rekap_bc23 on field Qty was type Double??? Any ideas?? A: Found my problem!!. Is was my fault. I was set my field Qty on tmp_sap_rekap_bc23 length into 225 not 0. So i changed into 0. And viola is working back normal.
doc_23531086
This is how its look: @GetMapping("/userTransactions/{user_id}") public String getUserTransactions(@PathVariable("user_id") long user_id, TransactionGroup transactionGroup, Model model) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); UserDetailsImpl user = (UserDetailsImpl) authentication.getPrincipal(); long userId = user.getId(); model.addAttribute("userId", userId); List<Transaction> transactions = transactionRepository.getTransactionsByUserId(user_id); List<TransactionGroup> transactionByDate = new ArrayList<>(); List<Transaction> transOnSingleDate = new ArrayList<>(); boolean currDates = transactions.stream().findFirst().isPresent(); if (currDates) { LocalDate currDate = transactions.get(0).getDate(); TransactionGroup transGroup = new TransactionGroup(); for (Transaction t : transactions) { if (!currDate.isEqual(t.getDate())) { transGroup.setDate(currDate); transGroup.setTransactions(transOnSingleDate); transactionByDate.add(transGroup); transGroup = new TransactionGroup(); transOnSingleDate = new ArrayList<>(); } transOnSingleDate.add(t); currDate = t.getDate(); } transGroup.setDate(currDate); transGroup.setTransactions(transOnSingleDate); transactionByDate.add(transGroup); for (TransactionGroup group: transactionByDate) { LocalDate date = group.getDate(); transactions = group.getTransactions(); double income = transactions.stream() .filter(trans -> trans.getTransactionType().getDisplayName().equalsIgnoreCase("income")) .mapToDouble(Transaction::getAmount) .sum(); double expense = transactions.stream() .filter(trans -> trans.getTransactionType().getDisplayName().equalsIgnoreCase("expense")) .mapToDouble(Transaction::getAmount) .sum(); double balance = income - expense; model.addAttribute("balance", balance); System.out.println("date:" + date + ",income:" + income + ",expense:" + expense + ",balance:" + balance); } } else { System.out.println("Empty"); } model.addAttribute("transactionGroup", transactionByDate); return "transactions"; } You should see: double balance = income - expense; model.addAttribute("balance", balance); And this is my thymeleaf: <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" th:href="@{/css/transaction.css}"/> <meta name="viewport" content="width=device-width"/> <script src="http://localhost:35729/livereload.js"></script> <script src="https://kit.fontawesome.com/9ab80cc16b.js" crossorigin="anonymous"></script> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>Users</title> </head> <body> <header> <h1 class="logo">Spender</h1> <input type="checkbox" class="nav-toggle" id="nav-toggle"> <nav> <ul> <li><a th:href="@{/api/test/homePage}">Homepage</a></li> <li><a id="wallets" th:href="@{/api/wallet/userWallet/balance/{userId} (userId=${userId})}">Wallets</a></li> <li><a href="javascript: document.logoutForm.submit()" role="menuitem">Logout</a></li> </ul> </nav> <label for="nav-toggle" class="nav-toggle-label"> <span></span> </label> </header> <br> <br> <br> <br> <br> <br> <br> <br> <div class="date" th:each="singleGroup : ${transactionGroup}"> <h1 th:text="${singleGroup .date}"></h1><h1 th:text="${balance}"></h1> <div class="transaction" th:each="singleTrans : ${singleGroup.transactions}"> <h2>Amount: <span th:text="${singleTrans.amount}"></span></h2><br> <h2>Note: <span th:text="${singleTrans.note}"></span></h2><br> <h2>Wallet name: <span th:text="${singleTrans .walletName}"></span></h2><br> <h2>Expense Category: <span th:text="${singleTrans .expenseCategories}"></span></h2><br> <h2>IncomeCategory: <span th:text="${singleTrans .incomeCategories}"></span></h2> <a class="card__link" th:href="@{/api/transaction/delete/{id}(id=${singleTrans.id})}" th:data-confirm-delete="|Are you sure you want to delete ${singleTrans.walletName} wallet?|" onclick="if (!confirm(this.getAttribute('data-confirm-delete'))) return false">Delete</a> <a class="card__link" th:href="@{/api/transaction/showFormForUpdate/{id}(id=${singleTrans.id})}">Update</a> <hr> </div> </div> <div style="text-align:center" th:if="${#lists.isEmpty(transactionGroup)}"><h1>You don't have any transaction</h1> <a th:href="@{/api/wallet/userWallet/balance/{userId} (userId=${userId})}">Wallets</a> </div> <form name="logoutForm" th:action="@{/api/auth/signout}" method="post" th:hidden="true"> <input hidden type="submit" value="Sign Out"/> </form> </body> </html> I want to display that value right after <h1 th:text="${singleGroup .date}"></h1> And I tried like: <h1 th:text="${singleGroup .date}"></h1><h1 th:text="${balance}"></h1> What is the problem? For example, my output in the console from the controller is good, and looks like this: date:2023-03-03,income:100.0,expense:50.0,balance:50.0 date:2023-03-16,income:100.0,expense:15.0,balance:85.0 But on page, I have like in console, two dates and for both dates are printed 85 instead 50 for date 03/03/2023 and 85 for date 03/16/2023, value 85 is printed for both of them. How I can extract this double value in my thymeleaf to show appropiate value like in console? A: Your balance attribute is not part of transaction group. So, when you call model.addAttribute("balance", balance); in loop, your previous value is overwritten. Add balance attribute to transaction group instead
doc_23531087
public class Order { public int OrderID { get; set; } public string CustomerID { get; set; } public int? EmployeeID { get; set; } public DateTime? OrderDate { get; set; } public DateTime? RequiredDate { get; set; } public DateTime? ShippedDate { get; set; } public int? ShipVia { get; set; } public decimal? Freight { get; set; } public string ShipName { get; set; } public string ShipAddress { get; set; } public string ShipCity { get; set; } public string ShipRegion { get; set; } public string ShipPostalCode { get; set; } public string ShipCountry { get; set; } public Customer Customer { get; set; } } A: It's short for the type Nullable<T> where T is the type that precedes the ?. Thus public int? EmployeeID { get; set; } is equivalent to public Nullable<int> EmployeeID { get; set; } Effectively, a nullable type allows you to assign null to value types. These types are very special as various operators and methods on the corresponding non-nullable type are "lifted" to the nullable type. Note that T must be a non-nullable value type. Also, it's a common misconception that Nullable<T> is a reference type. It is a value type, albeit a rather special one (it gets help from the compiler to be so special). For example, boxing and unboxing operations are treated very specially (the underlying value is boxed, unless it is null in which case the boxed instance of object is the null reference; if null is unboxed to an instance of a nullable type, it is unboxed to the value where HasValue is false). A: It means its nullable. A nullable value can contain a value or it can be null, like this: int? myVar = 4; myVar = null //myVar is now null. This would be illegal is myVar wasn't nullable myVar = 17 // myVar now contains 17 A: It means the variable is nullable. A: [ValueType]? is shorthand for the Nullable class. It will accept a null assignment (which value types can't). When you're ready to access the value, you can check myNullable == null or myNullable.HasValue and the actual valueType (int, DateTime, whatever) will be in myNullable.Value. A: It just makes the value nullable. Which means you can assign "null" to the property. Without the "?" You wouldn't be able to. A: nullable, when you use the database, you can set column as int null so in the c# int is not null,because int is the value type. so in c# support the int?
doc_23531088
tmp = list(struct.unpack("f" * size, f.read(4 * size))) where f = open(filename, 'rb') and size is always 200. When I run it, I get struct.error: unpack requires a bytes object of length 800. I did a print of f.read(4 * size) and it only gave me b'', which obviously isn't 800 characters long, so is that the issue? Here's the full code for context: def getVectorData(filename): f = open(filename,"rb") words = int(f.read(4)) # # of unique words size = int(f.read(4)) # # of dimensions vocab = [" "] * (words * max_w) M = [] for b in range(0,words): a = 0 while True: c = f.read(1) # reading each word character by character. #print(c) # this does return actual data, not just '' vocab[b * max_w + a] = c; if len(c) == 0 or c == ' ': break if (a < max_w) and vocab[b * max_w + a] != '\n': a += 1 print(f.read(4 * size)) tmp = list(struct.unpack("f"*size,f.read(4 * size)))
doc_23531089
The upload widget is being used on a create in a Kendo Grid. I am also going to need to find an id that is created server side to use as a parameter in the ashx handler and the wcf method url for the upload. Right now I am hard coding the id. Code below: $('#files').kendoUpload({ async: { autoUpload: false, saveUrl: "save" }, multiple: true, complete: function onComplete(e) { $.map(e.files, function (file) { var info = file.name; e.sender.options.async.saveUrl = attachURL + "&changeControlRequestID=" + 148 + "&changeControlRequestPendingID=" + pendingId + "&directoryName=\\sat1mvdwb022.NAOTEST.G.LAB.GMACFS.COM\BSMShare\BSM\ChangeControl" + "&fileName=" + info; }); }, upload: function onUpload(e) { $.map(e.files, function (file) { var info = file.name; e.sender.options.async.saveUrl = "ChangeControlHandler.ashx?upload=true"; }); } }); The first async saveUrl is linked to an ashx file. Code below : public class ChangeControlHandler : IHttpHandler { public void ProcessRequest (HttpContext context) { int ccrID = 146; if (context.Request.Files.Count > 0) { HttpFileCollection fileCollection = context.Request.Files; if (fileCollection.Count > 0) { HttpPostedFile filePath = fileCollection[0]; string savepath = "filepath"; string name = filePath.FileName.Remove(filePath.FileName.LastIndexOf(".")); string fileName = ccrID.ToString() + "_" + name.Remove(0, name.LastIndexOf(@"\") + 1) + "_" + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Year.ToString(); string fileExt = fileName.Remove(0, fileName.LastIndexOf(".")); if (!Directory.Exists(savepath)) Directory.CreateDirectory(savepath); filePath.SaveAs(savepath + fileName + fileExt); context.Response.StatusCode = (int)HttpStatusCode.OK; } } context.Response.ContentType = "text/plain"; context.Response.Write("Hello World"); } public bool IsReusable { get { return false; } } } The file is being uploaded to the folder but it breaks with this error causing the upload to fail. Jquery error
doc_23531090
typedef struct SCNVector3 { CGFloat x, y , z; } SCNVector3; Or when trying to write an overload function : func * (left: SCNVector3, right: CGFloat) -> SCNVector3 { return SCNVector3Make(left.x * right, left.y * right, left.z * right) } I get the "cannot invoke '' with an argument list of type" error. Aren't left.x, left.y and left.z supposed to be CGfloat ? How and when is it decided if CGFloat will be a double or a float? A: In the iOS 8.1 SDK headers, the SCNVectorX types are based on Float, as can be seen by command-clicking on SCNVector3: struct SCNVector3 { var x: Float var y: Float var z: Float } func SCNVector3Make(x: Float, y: Float, z: Float) -> SCNVector3 This is different from the OS X 10.10 SDK where CGFloat is used. So the documentation seems to be wrong. The following compiles in an iOS project: func * (left: SCNVector3, right: Float) -> SCNVector3 { return SCNVector3Make(left.x * right, left.y * right, left.z * right) }
doc_23531091
I don't understand how to do this? function validation() { var date_start = document.getElementById('date_start').value; const now = new Date(date_start) const oneYearFromNow = now.setFullYear(now.getFullYear() + 2); if(now < oneYearFromNow) { document.getElementById('date_startError').innerHTML = " ** Error date ! "; return false; } } <!DOCTYPE html> <html lang="fr"> <head> <meta charset="utf-8"> <title>Titre de la page</title> <link rel="stylesheet" href="style.css"> <script src="script.js"></script> </head> <body> <form action="#" onsubmit="return validation()" > <br> <label>Date start : </label> <br> <input type="date" name="date_start" id="date_start"> <br> <span id="date_startError"></span> <br> <input type="submit" value="ok"> </form> </body> </html> Thank you in advance for your help and your time. A: You can set max on input[type="date"] to limit the maximum date. You can also set it using JS so that it can be dynamic. You can use what you have: const now = new Date(date_start) const oneYearFromNow = now.setFullYear(now.getFullYear() + 2); Then you can use querySelector to get the input element and setAttribute to set its max attribute to the value of oneYearFormNow converted to an ISOString A: Try this, Input date type has a max attribute, <input type="date" id="myDate" name="bday" min="1980-01-01" max="2000-01-01"/> The calendar will be disabled once you reach the date mentioned within the max attribute You can set max attribute from Javascript as follows: var date_start = document.getElementById('date_start').value; const now = new Date(date_start) const fd = now.setFullYear(now.getFullYear() + 2); var nextTwoYears = fd.getDate() + '/' + (fd.getMonth()+1) + '/' +.fd.getFullYear() document.getElementById('date_start').setAttribute('max', nextTwoYears) A: I think you're mixing current date with the date input by the user. Also beware that when you did this: now.setFullYear(now.getFullYear() + 2); you were also updating the year of the date saved in now variable, which is not what you expected if you want to compare it later. Please check this snippet: function validation() { var date_start = document.getElementById('date_start').value; const inputDate = new Date(date_start); const yearFromImputDate = inputDate.getFullYear(); const now = new Date(); const twoYearsFromNow = now.getFullYear() + 2; if(yearFromImputDate > twoYearsFromNow) { document.getElementById('date_startError').innerHTML = " ** Error date ! "; return false; } console.log("Date is valid"); return true; } <!DOCTYPE html> <html lang="fr"> <head> <meta charset="utf-8"> <title>Titre de la page</title> <link rel="stylesheet" href="style.css"> <script src="script.js"></script> </head> <body> <form action="#" onsubmit="return validation()" > <br> <label>Date start : </label> <br> <input type="date" name="date_start" id="date_start"> <br> <span id="date_startError"></span> <br> <input type="submit" value="ok"> </form> </body> </html>
doc_23531092
A: row index is not included as part of the event data. On the onRowSelect callback, you could simply perform an indexOf(data) on the array you are using to populate your datatable. A: With PrimeNG, they have the option to add a [pSelectableRowIndex] property. To do this, on your template body, add let-rowIndex="rowIndex" (you can name this how you prefer such as let-ri. Now on your <tr>, add [pSelectableRowIndex]="rowIndex". The index will now be included in the $event on selection. Example: <ng-template pTemplate="body" let-rowData let-rowIndex="rowIndex"> <tr [pSelectableRow]="rowData" [pSelectableRowIndex]="rowIndex"> <td>{{rowData['val']}}</td> </tr> </ng-template>
doc_23531093
Going to http://localhost/AppName/community/ (note the trailing slash) gives me an unmarked up page of the forum with an Error that the page could not be found. I would like to prevent this from happening, and make XenForo use the URL I've supplied. I've tried setting the <base> to <base href="http://localhost/AppName/community/" />, but to no success. The Board URL in the Admin CP of XenForo is also set to http://localhost/AppName/community (with no trailing slash) If you have a clue how to fix this, that'd be great. A: Didn't find an exact solution to my issue, but kind of moved around the issue by placing my community folder from /app/webroot/ to the root /. In addition I had to add this line to the .HTACCESS file: RewriteCond %{REQUEST_URI} !^/community(.*) Edit 11-23-2012: I seem to have found the solution I was looking for. I moved my installation back to /app/webroot and set the DocumentRoot in my vhost file accordingly: DocumentRoot C:/wamp/www/sitename/app/webroot
doc_23531094
The transformation works as expected; however, in the debugger, I still have to choose an XML document from the XML-Dropdown menu. It doesn't seem to matter at all which document I choose (I can even choose the XSLT file itself), but as long as I don't select any document from the dropdown, the debugger controls remain greyed out and I cannot step into the first instruction. Is this a bug or did I oversee some configuration option? Thanks, Philipp A: You can switch to the XSLT debugger perspective with only the XSLT stylesheet opened. In the XML and XSL combo boxes you can choose the XSLT stylesheet. There is a combo box in which you can use the XSLT processor (in your case it's probably Saxon 9 PE) and after that combo box there is a small XSLT processor configuration button which you can press to edit the used initial template. Regards, Radu
doc_23531095
We’re reaching out in response to your recent appeal regarding enforcement of your app. We are unable to approve your app’s use of REQUEST_INSTALL_PACKAGES permission because the use of the permission is not directly related to the core purpose of the app. I have tried the workaround I found on starkoverflow. Like adding <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" tools:node="remove" /> But I don't see it working because I can still see the REQUEST_INSTALL_PACKAGES permission still listed in the manifest merger debug report. Which will eventually make them reject the app again If anyone can assist, I would be grateful.
doc_23531096
HTTP Status 415 - Cannot consume content type Both of the python REST client libraries I've tried, restclient on github and python-rest-client on google code, do send a Content-Type header when making GET requests. My understanding from reviewing http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html is that clients should only send Content-Type headers on POST and PUT requests. Is that correct? The fact that both of these libraries do sent the header makes me think that servers typically ignore it, rather than return a client error code. A: Although not explicitly outlined in the spec, one could make some inferences. Section 7.2.1 states Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. That's pretty obvious, and makes sense. Given that, we can have a look at Section 9 (Method Definitions) to see which ones mention that they'd possibly have an entity in the request body. Three of them mention it: OPTIONS If the OPTIONS request includes an entity-body (as indicated by the presence of Content-Length or Transfer-Encoding)... POST ...used to request that the origin server accept the entity enclosed in the request... PUT ...requests that the enclosed entity be stored under the supplied Request-URI And one method specificially disallows entities, TRACE: A TRACE request MUST NOT include an entity. In reality you could send any method (except TRACE) with an entity in the body and a Content-Type header. However, per the spec, I wouldn't expect the server to do anything with it unless it were one of the three methods above. I would also say that the software you're using that responds with the HTTP Status 415 is in violation of the specification. Section 4.3 says: ...if the request method does not include defined semantics for an entity-body, then the message-body SHOULD be ignored when handling the request. Since the spec doesn't include defined semantics for an entity body with a GET request, the server should ignore it. Additionally if no entity was provided in the request, and the Content-Length is zero (assuming the Transfer-Encoding header is not set and is not "identity"), the server should not try to consume an entity, regardless of of the request method or whether or not there's a Content-Type header present. This can be backed up by the order of precedence for determining the message length described in Section 4.4. A: 415 Cannot consume content type This problem happens if the REST Resource has @Consumes suggesting to accept a particular MIME Type. To fix this set the correct "Accept" Header in the Request/Resource call along with "Content-Type" header. For MockHttpRequest from RESTEasy it can be done simply as request.accept(MediaType.APPLICATION_JSON); request.contentType(MediaType.APPLICATION_JSON);
doc_23531097
I want to achieve something like this The documentation for rmq has not mentioned about images in for UITextFieldStylers. Update : For those who might find this useful, I have implemented it as follows with jamon's recommendation. Screen @email = rmq.append(UITextField, :email_field) do |q| q.append(UIImageView, :password_image) end Stylesheet def password_image(st) st.image = image.resource('image-name') //add margin etc inside frame end A: I would recommend just adding a UIImageView to the left of the UITextField and positioning it there. Keep it simple.
doc_23531098
Now my code is something like this. File: services/auth-service.js angular.module('myApp') .factory('gapi', function ($q) { var auth2; gapi.load('auth2', function () { auth2 = gapi.auth2.init({ client_id: '649922003965-ni9e6nad25dh3ejoll70va550kt7cu5u.apps.googleusercontent.com' }); }); return { isSignedIn: function () { return auth2.isSignedIn.get(); } } }); File: controllers/dashboard.js angular.module('myApp') .controller('DashboardCtrl', function (gapi) { alert(gapi.isSignedIn()); }); Now the problem is that, when alert() command is ran in the dashboard.js file, by that time auth2 hasn't loaded (because it loads from the Google API via internet I guess) therefore I get an error that isSignedIn can't be called off undefined. So what I would ideally need is probably something like a C# await function which waits for the value to be returned and them calls off it's method. Any solutions would be really appreciated. I've spent hours trying promises, and other approaches but I was not able to get any of them to work. UPDATE: Most of your answers would work in the scenario mentioned above. Let's try this scenario which is more complex and should've been mentioned in the first place. (Sorry for that). File: scripts/app.js .state('main', { url: '/admin', abstract: 'true', templateUrl: 'views/main.html', resolve: { check: function ($q, auth) { if(!auth.isSignedIn()) { $q.reject({authenticated: 'false'}); } } } }) .state('admin', { url: '', parent: 'main', templateUrl: 'views/admin.html' }) Now, if I use promises here, angular wouldn't wait for the promise to be resolved. It would simple load the view and calling $q.reject after the view has been loaded will be of no use. A: You can achieve this using promises in this way: File: services/auth-service.js angular.module('myApp') .factory('gapi', function ($q) { var auth2; var isSignedInDeferred = $q.defer(); gapi.load('auth2', function () { auth2 = gapi.auth2.init({ client_id: '649922003965-ni9e6nad25dh3ejoll70va550kt7cu5u.apps.googleusercontent.com' }); isSignedInDeferred.resolve(auth2.isSignedIn.get()); }); return { isSignedIn: function () { return isSignedInDeferred.promise; } } }); File: controllers/dashboard.js angular.module('myApp') .controller('DashboardCtrl', function (gapi) { gapi.isSignedIn().then(isSigned) { alert(isSigned); } }); Just change your isSignedIn function to return promise and resolve that promise when you have the value. A: The feature is available on drafts for ES7, babel (a transpiler) has support for async/await if you feel comfortable with it. That being said, this can be done easily with just promises: gapi.client.load(name, version, callback) Loads the client library interface to a particular API. If a callback is not provided, a promise is returned. The loaded API interface will be in the form gapi.client.api.collection.method. For example, the Moderator API would create methods like gapi.client.moderator.series.list. The api already gives you back a promise, so no need to wrap it around q, all you need to do is return that promise: return gapi.load('auth2').then(function() { return gapi.auth2.init({ client_id: '649922003965-ni9e6nad25dh3ejoll70va550kt7cu5u.apps.googleusercontent.com' }); }); Now, from your controller: gapi.then(function(auth2){ //auth2 already loaded }); Edit: Assuming you can get the returned promise on your check function. All you need to is: var possiblyRejectedPromise = gapi.then(function(auth2){ if(!auth2.isSignedIn.get()){ throw new Error('Not logged in'); } else { //LoggedIn return true; } }); return possiblyRejectedPromise; A: There is no equivalent to await in ES5. You need to get into the mindset of handling events as they happen and updating your application state based on those events. For your specific issue, I believe you are correct in your assumption that it is failing because the auth2 variable has not been set (and therefore is undefined). The "auth2 undefined" state is one of the application states that your code needs to handle. The solution may be as simple as changing your isSignedIn function like this: isSignedIn: function () { return auth2 && auth2.isSignedIn.get(); } This way it will only return true when the auth2 variable has been set and the isSignedIn property is true.
doc_23531099
|ID | variable | value.x | value.y | | --- | -------- | ------- | ------- | |1 | Temp | -0.71 | -0.74 | |2 | Temp | -0.53 | -0.50 | |3 | Temp | -0.48 | -0.51 | |4 | Temp | -0.65 | -0.66 | |5 | Temp | -0.49 | -0.56 | |6 | Prep | -0.72 | -0.75 | |7 | Prep | -0.64 | -0.65 | |8 | Prep | -0.56 | -0.54 | |9 | Prep | -0.46 | -0.47 | |10 | Prep | -0.44 | -0.44 | I would like to get the residuals of correlation for each variable. Thanks in advance, A: If you just want to add the residuals from a model to your data table, modelr::add_residuals() is a nice convenience function for this exact purpose. You can use dplyr::group_split() and purrr::map() to simultaneously run this on multiple subsets of your original data. I assumed a simple linear model but you can substitute other standard model objects. library(tidyverse) library(modelr) d <- structure(list(ID = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"), variable = c("Temp", "Temp", "Temp", "Temp", "Temp", "Prep", "Prep", "Prep", "Prep", "Prep"), x = c(-0.71, -0.53, -0.48, -0.65, -0.49, -0.72, -0.64, -0.56, -0.46, -0.44), y = c(-0.74, -0.5, -0.51, -0.66, -0.56, -0.75, -0.65, -0.54, -0.47, -0.44)), row.names = c(NA, -10L), class = "data.frame") d %>% group_split(variable) %>% map(~add_residuals(data = .x, lm(y~x, data = .x))) %>% bind_rows() #> # A tibble: 10 x 5 #> ID variable x y resid #> <chr> <chr> <dbl> <dbl> <dbl> #> 1 6 Prep -0.72 -0.75 -0.0116 #> 2 7 Prep -0.64 -0.65 0.00205 #> 3 8 Prep -0.56 -0.54 0.0257 #> 4 9 Prep -0.46 -0.47 -0.0123 #> 5 10 Prep -0.44 -0.44 -0.00386 #> 6 1 Temp -0.71 -0.74 -0.0156 #> 7 2 Temp -0.53 -0.5 0.0543 #> 8 3 Temp -0.48 -0.51 -0.00293 #> 9 4 Temp -0.65 -0.66 0.00770 #> 10 5 Temp -0.49 -0.56 -0.0435 Created on 2022-04-07 by the reprex package (v2.0.1)