id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23533300
The new application still uses the Webforms Viewengine. It uses StructureMap for Dependency Injection. If possible I would like to upgrade manually. For upgrading from ASP.NET 1 to ASP.NET 2 I found the white paper http://www.asp.net/whitepapers/aspnet-mvc2-upgrade-notes The steps described in the document seem to be of little risk: * *Fiddle with web.csproj *Replace Version=1.0.0.0 in web.config by Version=2.0.0.0 *Reference System.Web.Mvc (v2.0.0.0) in the project *chnange bindingRedirect in web.config *update css and js files What about upgrading to MVC 4: Will there be different steps involved? A: You would follow a similar set of steps to upgrade to MVC 4. Microsoft has a whitepaper that outlines the steps required to manually upgrade a project from MVC 3 to MVC 4. I have upgraded from 3 to 4 following these steps and it was a pretty simple and smooth process. Going from 1 to 4 is a bigger jump of course, so to minimize headaches you might want to individually upgrade 1->2, 2->3, 3->4: if you run into any breaking code changes it will be easier to identify how to resolve them. But fundamentally, all you're really doing is changing project GUIDs and referencing newer DLLs and such. It's not brain surgery. To answer Ashok's question, MVC 4 is certainly deployable if you wish to use it today - my public blog is running it (on my own server). Use preview software at your own risk, of course. A: My understanding is that MVC 4 is still in developer preview so a lot of features may and likely will change when the RC version is release. Since it is in dev preview is it even deployable as a live site?
doc_23533301
<Application x:Class="Class.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" DispatcherUnhandledException="Application_DispatcherUnhandledException" StartupUri="StartClassWindow.xaml"> <Application.Resources> </Application.Resources> </Application> But then it started giving error like below: No matching constructor found on type 'Class.StartClassWindow'. You can use the Arguments or FactoryMethod directives to construct this type.' Line number '3' and line position '9'. Here is the StartClassWindow.xaml.cs: namespace Class { public partial class StartClassWindow : System.Windows.Window { public StartClassWindow(string classData) { InitializeComponent(); className = classData; function(); } //rest of the code. } } A: You need to add a parameter-less constructor to your StartClassWindow like this: public StartClassWindow(string classData) { InitializeComponent(); className = classData; function(); } public StartClassWindow() { } Or if you don't want to have another constructor you can override the OnStartup method in the App.xaml.cs but you should remove the StartupUri="StartClassWindow.xaml" in your App.xaml first. Like below: protected override void OnStartup(StartupEventArgs e) { StartClassWindow st = new StartClassWindow(""); st.Show(); } A: "Normally", your constructor must be parameterless: public Login() But, since you are using dependency injection, like this: public Login(IUserService userService) The constructor isn't parameterless, and the framework cannot instantiate the page if it's not told how to. For this there are a couple of options: Remove service from constructor Just like this, but you'll need to access the userservice differently: public Login() pre .net 4.8, 4.7, using Unity (or Prism) You can use a dependency injection framework like Unity to register the components. It is described here: https://www.wpftutorial.net/ReferenceArchitecture.html public class App : Application { protected override void OnStartup(StartupEventArgs e) { IUnityContainer container = new UnityContainer(); container.RegisterType<IUserService, UserService>(); MainWindow mainWindow = container.Resolve<MainWindow>(); mainWindow.Show(); } } Manual using Navigation Service Manually navigate, and do your own construction: NavigationService.Navigate(new LoginPage(new UserService); As described here: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/app-development/navigation-overview?view=netframeworkdesktop-4.8 .net 5 WPF, using built in DI If you are using .net 5, here is a tutorial. Make sure to register both the window and the service: https://executecommands.com/dependency-injection-in-wpf-net-core-csharp/ Here's an example: private void ConfigureServices(ServiceCollection services) { services.AddScoped<IUserService,UserService>(); services.AddSingleton<MainWindow>(); } private void OnStartup(object sender, StartupEventArgs e) { var mainWindow = serviceProvider.GetService<MainWindow>(); mainWindow.Show(); }
doc_23533302
The old syntax is [globalString = IENV:TYPO3_SSL=1] But in the documentation, there is no mention of TYPO3_SSL. https://docs.typo3.org/m/typo3/reference-typoscript/master/en-us/Conditions/ A: Starting with TYPO3 ver.: 9.4 and next, this can be used as a replacement: [request.getNormalizedParams().isHttps() == true] Here are some more references for migrating TypoScript conditions: * *https://wiki.sebkln.de/doku.php?id=typo3:about:conditions *https://usetypo3.com/symfony-expression-language-in-typo3.html *https://www.nitsan.in/blog/all-you-need-to-know-about-typoscript-conditions-with-symfony-expression-language/
doc_23533303
This is how I currently do it. @pytest.fixture(scope="module") def result_holder: return [] def test_creation(result_holder): object = create_object() assert object.status == 'created' # test that creation works as expected result_holder.append(object.id) # I need this value for the next test # ideally this test should only run if the previous test was successful def test_deletion(result_holder): previous_id = result_holder.pop() object = get_object(previous_id) # here I retrieve the object created in the first test object.delete() assert object.status == 'deleted' # test for deletion (before we go further, I'm aware of py.test passing results of one test to another - but the single answer on that question is off-topic, and the question itself is 2 years old) Using fixtures like this doesn't feel super clean... And the behavior is not clear if the first test fails (although that can be remedied by testing for the content of the fixture, or using something like the incremental fixture in the pytest doc and the comments below). Is there a better/more canonical way to do this? A: For sharing data between tests, you could use the pytest namespace or cache. Namespace Example with sharing data via namespace. Declare the shared variable via hook in conftest.py: # conftest.py import pytest def pytest_namespace(): return {'shared': None} Now access and redefine it in tests: import pytest def test_creation(): pytest.shared = 'spam' assert True def test_deletion(): assert pytest.shared == 'spam' Cache The cache is a neat feature because it is persisted on disk between test runs, so usually it comes handy when reusing results of some long-running tasks to save time on repeated test runs, but you can also use it for sharing data between tests. The cache object is available via config. You can access it i.e. via request fixture: def test_creation(request): request.config.cache.set('shared', 'spam') assert True def test_deletion(request): assert request.config.cache.get('shared', None) == 'spam' ideally this test should only run if the previous test was successful There is a plugin for that: pytest-dependency. Example: import pytest @pytest.mark.dependency() def test_creation(): assert False @pytest.mark.dependency(depends=['test_creation']) def test_deletion(): assert True will yield: $ pytest -v ============================= test session starts ============================= ... collected 2 items test_spam.py::test_creation FAILED [ 50%] test_spam.py::test_deletion SKIPPED [100%] ================================== FAILURES =================================== ________________________________ test_creation ________________________________ def test_creation(): > assert False E assert False test_spam.py:5: AssertionError ===================== 1 failed, 1 skipped in 0.09 seconds ===================== A: #Use return and then call it later so it'll look like: def test_creation(): object = create_object() assert object.status == 'created' return(object.id) #this doesn't show on stdout but it will hand it to what's calling it def test_update(id): object = test_creation object.id = id object.update() assert object.status == 'updated' # some more tests #If this is what youre thinking of there ya go
doc_23533304
z10k4m42 it would become array('z' => 10, 'k' => 4, 'm' => 42) Is this possible? A: Try the below: preg_match_all('/([a-z]+)(\d+)/', 'z10k4m42', $matches); $ret = array_combine($matches[1], $matches[2]);
doc_23533305
* *File is too big to even try open it in txt editor. *File is too big to upload it in phpmyadmin I aslo could't find how to do it in mysql console (only how to add 1 database from database.sql file, but in current case i am using mysqldump, so that won't work). I am using wamp on localhost. Any ideas? A: You can use, mysql -u username -p -D reqd_database --one-database < database.sql This will source only the SQL queries that apply to the chosen database.
doc_23533306
This following line of code is mentioned at the beginning of the code: points = 0 This represents that the player has no points at the moment, but later, these points will keep adding up and the value won't be 0. The first time the player encounters an increase in his points is in this function: def if_castle_right(): choice = "\nYou found a silver coin that's worth 5 points!" coin = 5 points += coin choice += "\nWhat will to do?" choice += "\n[a] Go back \n[b] See points \n[c] Quit \n>" inp = input(choice) if inp == 'a': if_castle() elif inp == 'b': point_total() return if_castle_right() elif inp == 'c': return else: char_input_fail() return if_castle_right() The problem is, when I execute the code, this is what is outputted: File "C:\Users\gabyp\Documents\python_work\game\choose_your_adventure_game.py", line 179, in if_castle_right points += coin UnboundLocalError: local variable 'points' referenced before assignment I don't know what else to do, because if I invert the points += coin into coin += points, it outputs normally, except that the 5 points that the coin is worth isn't added to the total, it just says 0. A: Add global points inside the function before points += coins. points = 0 def if_castle_right(): choice = "\nYou found a silver coin that's worth 5 points!" coin = 5 global points points += coin choice += "\nWhat will to do?" choice += "\n[a] Go back \n[b] See points \n[c] Quit \n>" inp = input(choice) if inp == 'a': if_castle() elif inp == 'b': point_total() return if_castle_right() elif inp == 'c': return else: char_input_fail() return if_castle_right() A: You can either declare it as a global variable, by calling global points inside the function, before it is accessed, or passing it as an argument and returning it along with if_castle_right() as a tuple like : def if_castle_right(points): . . . return (points,if_castle_right()) and calling the function as points,your_variable = if_castle_right(points)
doc_23533307
For that I have created a "Tweet" entity in my model & has generated a managed object class from XCode. I have declared Tweet ivar in my controller class & have synthesized it but when I try to put some value in it like tweet.text = @"Some parsed json tweet text"; And then NSLog the value of tweet.text it prints (null). What am I missing are there any extra considerations I need to take care of ...? I am very new to CoreData your help will be highly appreciated. Thanks in advance. Edit : NSManagedObjectContext *context = [self managedObjectContext]; NSManagedObject *managedTweetObject = [NSEntityDescription insertNewObjectForEntityForName:@"Tweet" inManagedObjectContext:context]; [managedTweetObject setValue:[NSDate date] forKey:@"timeStamp"]; this code works like a charm. A: Your description suggest that the Tweet class is either not properly setup or is not properly added to the build. An incorrect accessor could also cause the problem. It is hard to tell without code. You should post the Tweet class source.
doc_23533308
i wanted to change the position relating the marginTop with the page scroll, $(document).ready(function(){ $(window).scroll(function(){ var v= $(document).scrollTop(); console.log(v); if(v>50){ $('.menu').css({'marinTop':v+'px'}); console.log(true); }else{ $('.menu').css('marginTop','50px'); console.log(false); } }); }); but it just wont move the bar... :s A: Here: $(document).ready(function(){ $(window).scroll(function(){ var value = $(window).scrollTop(); if(value>+$('.menu').css('marginTop').replace(/px$/, "")) { $('.menu').css({'position':'fixed','top': 0}); }else{ $('.menu').css('position','static'); } }); }); Fixed 2 things: * *Removed the ".px" (css("marginTop") returns "50px", which can not be compared to a number) *You should really use "position: fixed" instead of a javascript-updated "position: absolute"
doc_23533309
For example, a MatchAllDocsQuery or a BooleanQuery that contains a MatchAllDocs clause are such queries that always return all the documents. Another example is a BooleanQuery that has a SHOULD-match clause that has a nested SHOULD-match clause that has a MatchAllDocs inside it. Note that a query that happens to return everything because it has all the possible terms in it or because the index is empty doesn't count as a query that always return all the documents. In other words, I would like to check whether a given query always returns everything no matter what the index contains. Is it possible or at least approximately possible? I'll accept an answer with a solution that doesn't work for any conceivable case if it works for any query that can be returned from Solr's Extended Dismax Query Parser. A: A BooleanQuery that contains a MatchAllDocsQuery as one of it's clauses doesn't necessarily return all documents, as the BooleanQuery may also contain other MUST or MUST_NOT clauses which would restrict the result set. I don't believe there is anything the does this out of the box, and trying to handle any sort of query that Solr might split out would be difficult. You would need to move through the queries recursively to ensure that everything effectively reduces to a MatchAllDocsQuery, ignoring scores. Something like (this is entirely untested at this point): boolean willMatchAll(Query query) { if (query instanceof MatchAllDocsQuery) return true; } else if (query instanceof BooleanQuery) { boolean foundMatchAll = false; for (BooleanClause clause : ((BooleanQuery)query).getClauses()) { if (clause.isProhibited()) { return false; //A reasonable assumption, that the MUST_NOT clauses won't be empty } else if (clause.isRequired()) { if (willMatchAll(clause.getQuery())) { foundMatchAll = true; } else { return false; //any MUST clause that is not a matchall means the boolean query will not match all } } else { if (willMatchAll(clause.getQuery())) { foundMatchAll = true; } } } //If a matchall has been found, and we haven't return false yet, this boolean query matches all documents return foundMatchAll; } else if (query instanceof DisjunctionMaxQuery) { boolean isMatchAll = false //If any disjunct is a matchall, the query will match all documents for (Query subquery : ((DisjunctuionMaxQuery)query).getDisjuncts()) { isMatchAll = isMatchAll || willMatchAll(subquery); } return isMatchAll; } else if (query instanceof ConstantScoreQuery) { //Traverse right through ConstantScoreQuery. The wrapper isn't of interest here. Query subquery = ((ConstantScoreQuery)query).getQuery() if (subquery == null) { return false; //It wraps a filter, not a query, and I don't believe a filter can be a matchall } return willMatchAll(subquery); } else { //No other standard queries may be or contain MatchAllDocsQueries, I don't believe. //Even a double open-ended range query restricts the results to those with a value in the specified field. return false; } } And if you also wanted to handle the stuff in org.apache.lucene.queries, there would be more query types to handle, like BoostingQuery and CustomScoreQuery, among others. But hopefully that gives some sort of idea on it. A: Good question, i am wondering if you can do : search and get numFound and compare that to see if your actual Query returns same numFound value. Am i missing something?
doc_23533310
So from what I understand, the way to do it is : 1. Call openlog to set the facility 2. Call syslog() to log. 3. Call closelog(). But what if I do not call openlog() before calling syslog()? What is the facility then? What is meant by "establishes a default to be used if none is specified". Where can one be specified, if not openlog()? A: Aah I think I got it. I think what it means is that for syslog(int priority, const char *message, ...); here priority can be multiple flags, as given in the freebsd man page example : syslog(LOG_INFO|LOG_LOCAL2, "foobar error: %m"); Here the facility is LOG_LOCAL2 and priority is LOG_INFO. So the facility mentioned in openlog() will take effect if none is provided in a call to syslog() as above.
doc_23533311
If I open a detail child view from a NavigationView, and then click on "Back", the TabBar would become transparent, showing the items in the Feed underneath the TabBar icons. * *FROM THE HOME FEED, OPEN A CHILD NAVIGATION DETAIL VIEW. --------------- *THEN ONCE INSIDE THE DETAIL VIEW, CLICK BACK. --------------- *YOU WILL SEE THIS BUG. THE TAB BAR WILL BE TRANSPARENT. --------------- A: With iOS 15, Apple has extended support for scrollEdgeAppearance to UIKit. This setting produces a transparent TabBar background by default. To fix the issue add the code below to your SceneDelegate file, to define the color of your TabBar, so it isn't made transparent automatically by SwiftUI. class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene( _ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions ) { guard let windowScene = (scene as? UIWindowScene) else { return } // MARK: ADD THIS CODE BELOW TO YOUR SCENE DELEGATE. // TAB BAR BACKGROUND COLOR HERE. UITabBar.appearance().barTintColor = UIColor.white // TAB BAR ICONS COLOR HERE. UITabBar.appearance().tintColor = UIColor.blue UITabBar.appearance().isTranslucent = true if #available(iOS 15.0, *) { let appearance = UITabBarAppearance() appearance.configureWithOpaqueBackground() // TAB BAR BACKGROUND COLOR HERE. (same as above) appearance.backgroundColor = UIColor.white UITabBar.appearance().standardAppearance = appearance UITabBar.appearance().scrollEdgeAppearance = UITabBar.appearance().standardAppearance } let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: RootView()) self.window = window window.makeKeyAndVisible() } } A: This was all I needed to do. if #available(iOS 15.0, *) { let tabBarAppearance = UITabBarAppearance() tabBarAppearance.configureWithDefaultBackground() UITabBar.appearance().scrollEdgeAppearance = tabBarAppearance }
doc_23533312
From the example below, I want to create the column group_id that attributes an id for every 3 observations. foo group_id 0 1 1 1 2 1 2 3 1 3 4 2 4 5 2 5 6 2 6 7 3 7 8 3 8 9 3 9 10 4 A: Another variant which may offer some flexibility :) 1. First for what you initially requested: mylist = [[i+1]*3 for i in range(len(df))] df['group_id'] = np.resize(mylist,len(df)) df index foo group_id 0 1 1 1 2 1 2 3 1 3 4 2 4 5 2 5 6 2 6 7 3 7 8 3 8 9 3 9 10 4 2. What if you would like to attribute strings? mylist = [[i]*3 for i in ['aaa','bbb','ccc','ddd']] df['group_id'] = np.resize(mylist,len(df)) df index foo group_id 0 1 aaa 1 2 aaa 2 3 aaa 3 4 bbb 4 5 bbb 5 6 bbb 6 7 ccc 7 8 ccc 8 9 ccc 9 10 ddd
doc_23533313
Here's my entire spec file: import { provide, PLATFORM_PIPES } from '@angular/core'; import { DatePipe } from '@angular/common'; import { addProviders, async, inject } from '@angular/core/testing'; import { Post, PostComponent, PostHtmlComponent } from './'; import { usingComponentFixture } from '../../test-helpers'; describe('Component: Post', () => { beforeEach(() => { provide(PLATFORM_PIPES, {useValue: DatePipe, multi: true }); addProviders([PostComponent, PostHtmlComponent, ]); }); it('should render an h1 tag with text matching the post title', usingComponentFixture(PostComponent, fixture => { let component = <PostComponent>fixture.componentInstance; let element = fixture.nativeElement; component.post = <Post>{ title: 'Hello', publishedOn: new Date('8/5/2016') }; fixture.detectChanges(); expect(element.querySelector('.blog-post-header h1').innerText).toBe('Hello'); }) ); }); And this is the component template: <div class="col-lg-8 col-md-7 col-sm-6"> <h1>{{post.title}}</h1> <p class="lead">{{post.publishedOn | date:'fullDate'}}</p> </div> A: I was able to resolve this issue. Here's what I had to do: * *npm install karma-intl-shim --save-dev *Add 'intl-shim' to the frameworks collection in karma.conf.js *Add the following to karma-test-shim.js (this is referenced in the files collection of karma.conf.js) require('karma-intl-shim'); require('./en-us.js'); // copied from https://github.com/andyearnshaw/Intl.js/blob/master/locale-data/json/en-US.json Intl.__addLocaleData(enUsLocaleData); A: Instead of mocking the DatePipe, you can use the transform method of DatePipe in typescript which is equivalent to the | operator in the HTML file import {DatePipe} from '@angular/common'; let pipe = new DatePipe('en'); expect(page.myDate.nativeElement.innerHTML).toBe(pipe.transform(model.date, 'dd/MM/yyyy'); A: For tests I mock date pipe: @Pipe({ name: 'date', pure: false // required to update the value when the promise is resolved }) export class MockedDatePipe implements PipeTransform { name: string = 'date'; transform(query: string, ...args: any[]): any { return query; } } Then when I configure testing module I inject it into declaration: TestBed.configureTestingModule( { providers: [ SelectionDispatcher, { provide: MyService, useClass: MockedMyServiceService } ], declarations: [ MyComponent, MockedTranslatePipe, MockedDatePipe ] }); A: That worked for me: import { DatePipe, registerLocaleData } from '@angular/common'; import localeDe from '@angular/common/locales/de'; registerLocaleData(localeDe); //.. describe('My Test', () => { let pipe = new DatePipe('de-DE'); it('My Test-Case', () => { expect(page.myDate.nativeElement.innerHTML).toBe(pipe.transform(model.date); }); }); You must set the right locale. That is a snippet from a Cypress-Test. A: that's what worked for me: import {DatePipe} from "@angular/common"; ... TestBed.configureTestingModule({ ... providers: [DatePipe] ... }); A: Expanding on other answers on here I was using the DatePipe in my component to produce a payload. I had the following setup. Return the transform method on DatePipe in the mock, matching parameters used by the component i.e. ('YY'). Otherwise we will just get undefined as the value when testing. .spec file import { DatePipe } from '@angular/common'; ..... const mockDatePipe = { transform: jest.fn((val) => new DatePipe('en').transform(val, 'YY')), }; ..... beforeEach(() => { component = new TestComponent( (mockDatePipe as unknown) as DatePipe, ..... ); }); it('should return correct payload', () => { expect(component.getPayload(new Date('2022-02-02')).toEqual( { purchaseYear: '22', } } .ts file public getPayload(date: new Date(), .....){ return { purchaseYear: this.datePipe.transform(date, 'YY') }; );
doc_23533314
Many many thank in advance. A: You can use Django as a backend for Apis and I would highly recommend using Frontend framework/Library like React/Vue. I know you want an easy solution for frontend like WordPress (drag & drop ) but I don't think there is such a thing which you can customize with liberty and according to your ease and have your full control over it. Plus, there are tons of themes and components available for React/Vue Or these libraries have a strong community. Alternate, You can use simple HTML with bootstrap, jquery. They too have tons of themes available.
doc_23533315
* *If it is checked then update the database with 1. *Else if it is unchecked then update it with 0. It works fine but it doesn't work if unchecked. <?php include('lib/db.php'); $facebook_id ="10001088"; $query1 = "SELECT `video`,`quran`,`medical`,`groups` FROM `man_facebook`.`users` WHERE `facebook_id`='$facebook_id'"; $result1 = mysql_query($query1); while($result = mysql_fetch_array($result1)) { $video = $result['video']; $quran = $result['quran']; $medical = $result['medical']; $groups = $result['groups']; echo $video; // echo $quran; ?> <form method="post" action="<? echo $_SERVER['REQUEST_URI']; ?>" > <input type="checkbox" name="video" id="video" value="<?echo $video;?>" <?php if($video == '1'){ echo "checked='checked'"; } else {} echo "/>" ?> <input type="submit" name="submit" value="Submit"> </form> <?php } if (isset($_POST['submit'])) { if (is_numeric($_POST['video']) && $_POST['video'] <2 ) { $video1 = isset($_POST['video']) ? '1' : '0'; echo $video1; $query = mysql_query("UPDATE `man_facebook`.`users` SET `video` ='$video1' WHERE `facebook_id`='$facebook_id'"); $video = $video1; echo '<meta http-equiv="refresh" content="0" />'; } } //echo $query; //header("Location: updatesql.php"); ?> Can I also use jquery to update it smoothly? A: I find this part a bit weird: if (is_numeric($_POST['video']) && $_POST['video'] <2 ) { $video1 = isset($_POST['video']) ? '1' : '0'; You first check if it is numeric and then check if it is set. If it wasn't set, that if would become false automatically. In other words, $video is always 1. Assuming $video can be only true/false (or maybe it comes as "checked"/"unchecked", not really sure), use it like this: $video1 = ($video ? '1' : '0'); Hopefully I spotted the issue successfully :) UPDATE <input type="checkbox" name="video" id="video" value="video" <?php if($video == '1'){ echo "checked='checked'"; } echo "/>"; ... if (isset($_POST['submit'])) { echo $_POST['video']; // again, please tell what it outputs here!!! $video1 = (($_POST['video'] == "video") ? '1' : '0'); A: checkbox update if (isset($_POST["send"]) && $_POST["send"] == "ok") { foreach ($_POST['membre'] as $id => $data) { mysql_query("UPDATE tablename SET param1='" . $data['param'] . "' WHERE id='" . $id . "'"); } } <form> <input type="hidden" name="send" value="ok" /> <td class="cel2" style=" width: 100px;"> <input name="membre[<?php print $val['id']; ?>][param]" type="checkbox" style="margin-top: 7px; width: 30px;" value="1" id="param" <?php if ($val['p'] == '1') print 'checked'; ?> /> </td> </form>
doc_23533316
But there are some cells which contains 'empty' - how can I set the expected value in the test condition, that I can check this 'empty' cells? I tryed to leave the expected value empty as well, but that results in following error-message: "ScalarValueCondition Condition (scalarValueCondition6) Failed: ResultSet 1 Row 6 Column 1: values do not match, actual '' expected ''. Thanks in advance! Immi A: This appears to be a defect in the DB unit test Scalar Value condition. Sorry about that. Would you mind filing a Connect bug for this at https://connect.microsoft.com/SQLServer/feedback/CreateFeedback.aspx using the category "Developer Tools (SSDT, BIDS, etc.)"? I'd suggest working around this by using the Data Checksum condition instead. I checked and it correctly distinguishes between null and ''. It takes a little more effort to configure, because you'll have to execute the query to gather the baseline checksum value, and it's a little less clear what the test is expecting.
doc_23533317
Anybody out there having the same problem? A: XCode keymap exists only in AppCode and CLion products. There is a feature request to make it available for IntelliJ IDEA as well (and WebStorm). You can try extracting the keymap from CLion distribution, it can be found here CLION_HOME\lib\resources.jar\keymaps\Xcode.xml. Then you can place it into idea.config.path\keymaps directory when IDE is not running.
doc_23533318
"There is a simple model of how to map entities to tables. It probably only works for rather simple cases. If you do not like that, you should code your own strategy. Spring Data JDBC offers only very limited support for customizing the strategy with annotations." https://docs.spring.io/spring-data/jdbc/docs/3.0.0/reference/html/#jdbc.why I was expecting Spring Data JDBC is also working for more complex cases. A: The limitations that rise from this simple model affect mostly legacy projects where you have a database that you maybe can't even change. Spring Data JDBC is not intended to map an arbitrary database model to an arbitrary Java domain model, but to use a Domain Driven Design approach and construct the database accordingly. But even in the cases where you hit the limitations of Spring Data JDBC you can always fall back on Springs JdbcTemplate without any conflict with the rest of your model which gets persisted by Spring Data JDBC. The same is not true for JPA. Of course you can use JdbcTemplate with JPA as well, but you now have to very different approaches to persistence in your application which can and will interact in interesting ways due to JPA caching and dirty checking. I therefore think Spring Data JDBC is an excellent choice for large application and complex models. It's limitations will push you in the direction of better defined smaller modules and less complex models.
doc_23533319
dir1/file1 dir1/file2 dir1/file3 dir2/file2 (dup) dir2/file4 I want the file output to be : dir1/file1 dir1/file2 dir1/file3 dir2/file4 embedded system so cant use tools metioned in : https://unix.stackexchange.com/questions/71176/find-duplicate-files A: Looking at the commands available to busybox, if I understand you would like to merge (mv) the non-duplicate files contained in dir2 to dir1 using only the tools available to busybox, then a linewise comparison using diff -q would be an efficient solution. (you could also use cmp instead in a similar manner, but its byte-wise comparison may be a bit slower). The comparison will require a brute-force file-by-file comparison to compare and then move the file without having the benefit of arrays. A short shell script that takes dir1 and dir2 as the arguments to the script could be implemented as follows: #!/bin/sh [ -d "$1" -a -d "$2" ] || { printf "usage: %s dir1 dir2\n" "$0" exit 1 } ## move all files in dir2 that do not match a file in dir1 (linewise) # to dir1 for i in "$2"/*; do for j in "$1"/*; do diff -q "$i" "$j" && isdup=1 || isdup=0 done [ "$isdup" -eq 0 ] && mv "$i" "$1" done printf "rm -r %s\n" "$2" # rm -r "$2" ## you can uncomment to actually remove dir2 Note: you can uncomment the actual removal of dir2 if you choose after you confirm the script operation. Test Files/Directories $ dir1> echo a > file1 $ dir1> echo b > file2 $ dir1> echo c > file3 $ dir2> echo b > file2 $ dir2> echo d > file4 $ ls -l dir1 total 20 -rw-r--r-- 1 david david 2 Nov 30 23:48 file1 -rw-r--r-- 1 david david 2 Nov 30 23:48 file2 -rw-r--r-- 1 david david 2 Nov 30 23:48 file3 $ ls -l dir2 total 16 -rw-r--r-- 1 david david 2 Nov 30 23:48 file2 -rw-r--r-- 1 david david 2 Nov 30 23:48 file4 Use/Output $ sh ../../bbdupes.sh dir1 dir2 Files dir2/file2 and dir1/file1 differ Files dir2/file2 and dir1/file3 differ Files dir2/file4 and dir1/file1 differ Files dir2/file4 and dir1/file2 differ Files dir2/file4 and dir1/file3 differ rm -r dir2 $ ls -l dir1 -rw-r--r-- 1 david david 2 Nov 30 23:48 file1 -rw-r--r-- 1 david david 2 Nov 30 23:48 file2 -rw-r--r-- 1 david david 2 Nov 30 23:48 file3 -rw-r--r-- 1 david david 2 Nov 30 23:48 file4 Note: to suppress default output showing file differ, add >/dev/null 2>&1 following the diff -q command. Let me know if you have further questions.
doc_23533320
Let me take an example of what I'm trying to achieve. I have an ECS cluster which can run around 10+ different task definitions. Each task definition contains almost the same configurations so to avoid code duplication I am building a reusable module. From what I have gathered there are 3 primary ways to structure your terraform directories. 1: project β”œβ”€β”€ modules | β”œβ”€ ecs | β”œβ”€β”€ main.tf | β”œβ”€β”€ variables.tf | β”œβ”€β”€ task | β”œβ”€β”€ main.tf | β”œβ”€β”€ variables.tf | | └── env | β”œβ”€β”€β”€ dev.tfvars | β”œβ”€β”€β”€ prod.tfvars | β”œβ”€β”€β”€ stage.tfvars | β”œβ”€β”€β”€ 10+ | | |── main.tf |── variable.tf With this structure, I would have to get the variables from the env folder and pass it with -var-files="env/dev.tfvars" and then in my main.tf I would have to pass the variable to the modules/ecs/task/main.tf which seems like a long way, and a lot of steps just to get a variable to the ecs/task/main.tf 2. project β”œβ”€β”€ modules | β”œβ”€ ecs | β”œβ”€β”€ main.tf | β”œβ”€β”€ variables.tf | β”œβ”€β”€ task | β”œβ”€β”€ main.tf | β”œβ”€β”€ variables.tf | | └── stage | β”œβ”€β”€β”€ main.tf | β”œβ”€β”€β”€ variable.tf | β”œβ”€β”€β”€ stage.tfvars | └── dev | β”œβ”€β”€β”€ main.tf | β”œβ”€β”€β”€ variable.tf | β”œβ”€β”€β”€ dev.tfvars | └── 10+ | β”œβ”€β”€β”€ main.tf | β”œβ”€β”€β”€ variable.tf | β”œβ”€β”€β”€ X.tfvars If you wish to apply environment-based variables to the modules/ecs/task/main.tf, you would have to start from the main.tf in for example stage which calls the modules/ecs/main.tf. and from there apply it through the /modules/ecs/main.tf which then applies it to the /modules/ecs/task/main.tf. The problem with this approach is also whenever I add a new module, I would have to add it to all the different environments' main.tf 3. project β”œβ”€β”€ modules | β”œβ”€β”€ ecs | β”œβ”€β”€ main.tf | β”œβ”€β”€ variables.tf | β”œβ”€β”€ task | β”œβ”€β”€ main.tf | β”œβ”€β”€ variables.tf | | | | |── main.tf |── variable.tf Using terraform workspaces, I can use locals in the modules/ecs/task/variables.tf to determine what environment I am building. Like this: modules/ecs/task.variables.tf locals { env="${terraform.workspace}" masterAccountIDS = { "default"="12121212" "dev"="84848484" } masterAccountID="${lookup(local.masterAccountIDS, local.env)}" } But this would require that every time I add a new environment I go through all my variables.tf files, and add a new entry called for example "stage". I can't figure out a way that would allow me not to copy paste code, or insert new things when adding new environments or keep it all located at one place, so I would maybe only have to edit one file. A: Using workspaces is the best bet for now. I am using something like below to manage all variables at one place - defaults.tf - /* DEFAULT VARIABLES */ locals { tags = { Project = "${var.project}" Contact = "vivek@vivekyadav.me" Requester = "Vivek" Creator = "Vivek" ManagedBy = "TF" Environ = "${local.workspace["environ"]}" } } locals { meta = { name_prefix = "hpy-${local.workspace["environ"]}-${local.workspace["project_name"]}" account_id = "${local.workspace["account_id"]}" region_name = "${local.workspace["region_name"]}" } } /* CUSTOM VARIABLES - ENVIRONMENT SPECIFIC */ ################ DEFAULT LOCALS - DEFINE ENV VARIABLES FOR APP ################# locals { env = { default = { project_name = "${var.project}" region_name = "${var.region}" environ = "dev" account_id = "356******001" } default_list = { } ################ DEV LOCALS - DEFINE ENV VARIABLES FOR APP ################# dev = { environ = "dev" } dev_list = { } ################ UAT LOCALS - DEFINE ENV VARIABLES FOR APP ################# uat = { environ = "uat" } uat_list = { } ################ PREP LOCALS - DEFINE ENV VARIABLES FOR APP ################# prep = { environ = "prep" } prep_list = { } ################ PRD LOCALS - DEFINE ENV VARIABLES FOR APP ################# prod = { environ = "prod" account_id = "3621****8334" } prod_list = { } } ################ EXPORTING ENV/WORKSPACE VARIABLES FOR APP ################# workspace = "${merge(local.env["default"], local.env[terraform.workspace])}" workspace_lists= "${merge(local.env["default_list"], local.env[format("%v_list",terraform.workspace)])}" } Now you can call above variables in your main definition - main.tf - module "s3" { source = "s3" tags = "${local.tags}" meta = "${local.meta}" workspace = "${local.workspace}" workspace_list = "${local.workspace_list}" } Now you can call defined the variables inside modules as below - "${var.workspace["environ"]}" PS - This is a workaround but works really well as if now. Terraform should provide something out of the box to manage it.
doc_23533321
temp7: 1.68219771725e-06 temp6: [[array([-60800056.33037408], dtype=object)]] Exception in thread Thread-4: Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner self.run() File "/opt/ros/indigo/lib/python2.7/dist-packages/rospy/timer.py", line 223, in run self._callback(TimerEvent(last_expected, last_real, current_expected, current_real, last_duration)) File "/home/husky/catkin_ws/src/huskybot_ekf_v2/src/meas_update.py", line 194, in meas_update_step thisJ = temp7 * math.exp(temp6) It seems like on the very last line thisJ =temp7* math.exp(temp6), that I can't take the exponent of temp6. Does anyone know the cause? for i in range(0,len(line_features)-1): for k in range(0, len(m)): mkx = m[k][0] mky = m[k][1] posex = predicted_pose.x posey = predicted_pose.y poseth = predicted_pose.theta distx = math.pow((mkx - posex), 2); disty = math.pow((mky - posey), 2); q = distx + disty angle = math.atan2(mky-posey, mkx-posex) - poseth expected_meas = numpy.array([[math.sqrt(q)], [angle], [0] ]) H = numpy.array([[-(mkx-posex)/math.sqrt(q), -(mky-posey)/math.sqrt(q) , 0], [(mky-posey)/q, -(mkx-posex)/q, -1], [0 , 0, 0]]) Qt = 0.5 innovation_cov = H*predicted_cov*numpy.transpose(H)+Qt innovation = ave_meas_dist - expected_meas dd = [[2]] #dd = array[0] #print 0.5*numpy.array(dd) temp5 = -1/2 * numpy.dot(numpy.transpose(innovation), numpy.linalg.inv(innovation_cov)) temp6 = numpy.dot(temp5, innovation) print math.sqrt(numpy.linalg.det(2*math.pi*innovation_cov)) * numpy.array(dd) temp7 = math.sqrt(numpy.linalg.det(2*math.pi*innovation_cov)) thisJ =temp7* math.exp(temp6) A: I tried to reproduce the error. The error I got is: TypeError: must be real number, not list If the error is same then it was solved by doing this: thisJ = temp7 * math.exp(temp6[0][0]) Because temp6 type is list containing list containing array object. Please do correct me if I am wrong.
doc_23533322
sxe ld ntdll.dll ;g However, the trick doesn't work at all, ModLoad: 7c900000 7c9b0000 ntdll.dll eax=010043af ebx=7ffde000 ecx=020f18f5 edx=00000034 esi=00c2f720 edi=00c2f6f2 eip=7c810867 esp=0006fffc ebp=00000720 iopl=0 nv up ei pl nz na po nc cs=001b ss=0023 ds=0023 es=0023 fs=0038 gs=0000 efl=00000200 7c810867 ?? ??? Processing initial command 'sxe ld ntdll.dll ;g' 0:000> sxe ld ntdll.dll ;g (ae8.6f4): Break instruction exception - code 80000003 (first chance) eax=00181eb4 ebx=7ffde000 ecx=00000001 edx=00000002 esi=00181f48 edi=00181eb4 eip=7c901230 esp=0006fb20 ebp=0006fc94 iopl=0 nv up ei pl nz na po nc cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00000202 ntdll!DbgBreakPoint: 7c901230 cc int 3 So, How to break into WinDBG when ntdll.dll is mapped into the new process? thanks [UPDATE] I exactly followed the steps as mentioned by jcopenha, but I don't know why Windbg gives a strange error(Memory access error) where Notepad.exe is running . Please give me a hand!Thanks a lot! 0:000> .restart /f CommandLine: C:\WINDOWS\NOTEPAD.EXE Symbol search path is: D:\Symbols\Symbols;SRV*D:\Symbols\MySymbols*http://msdl.microsoft.com/download/symbols Executable search path is: ModLoad: 01000000 01014000 notepad.exe eax=0100739d ebx=7ffd9000 ecx=020f18f5 edx=0000004e esi=00f7f73a edi=00f7f6f2 eip=7c810867 esp=0007fffc ebp=0000024c iopl=0 nv up ei pl nz na po nc cs=001b ss=0023 ds=0023 es=0023 fs=0038 gs=0000 efl=00000200 7c810867 ?? ??? 0:000> u 7c810867 7c810867 ?? ??? ^ Memory access error in 'u 7c810867' [UPDATE2] I found an odd instruction displayed at 7c810867, but p command still can work. Is it a bug in WinDBG? A: If you go to Debug->Event Filters and change "Create process" to "enabled" then restart the application it will start before ntdll.dll shows up in the module list. If you then do sxe ld ntdll.dll;g it will stop in ntdll!RtlUserThreadStart. 0:000> .restart /f CommandLine: C:\Windows\System32\notepad.exe Symbol search path is: SRV*d:\symbols*http://msdl.microsoft.com/download/symbols Executable search path is: ModLoad: 00000000`ffe00000 00000000`ffe35000 notepad.exe 00000000`7790c500 4883ec48 sub rsp,48h 0:000> sxe ld ntdll.dll;g ModLoad: 00000000`778e0000 00000000`77a89000 ntdll.dll ntdll!RtlUserThreadStart: 00000000`7790c500 4883ec48 sub rsp,48h A: Regarding the loading of ntdll, I recommend reading this. You can break into the process before any code runs with: windbg -xe cpr notepad Or windbg -xe ld:ntdll notepad ntdll will still be mapped into the process at this point -- you can't break in before this happens. As for the memory access error, kernel32 is not loaded into the process yet. The initial thread is queued to run at kernel32!BaseProcessStartThunk, but since kernel32 isn't loaded into the address space yet, you aren't going to see anything at that address. The reason the thread's start address is able to begin in unmapped memory is because before the thread begins its execution, the very first thing that happens is a user APC runs in the context of that initial thread that takes care of all the process initialization, including loading kernel32. You can see this event occur if you set a similar event, like: sxe ld kernel32 You will need to load symbols to get the internal functions names in the stack trace. In addition to the first link, you can read more about process initialization here. Hope this helps. A: As far as I remember ntdll is not mapped by the user-mode. If it was mapped in by the user-mode, what would map the module that maps ntdll? ntdll contains a set of stubs for syscalls to enter into the kernel and also contains a few other things such as a COFF loader which is part of process initialisation. It is a bit of a magic dll and it cannot be relocated, thus is always at the same virtual address in every process. If you want to break before ntdll is mapped I am afraid you will have to use a kernel debugger. May I ask what you are trying to achieve by breaking before ntdll is mapped?
doc_23533323
I did a test with 3 images that have 13KB altogether. After I combine them the final result has 42.5KB. Is there any solution to this without losing quality ? Thanks A: well 13KB * 3 = 42 KB thats right =) maybe: http://sheldon.lendrum.co.nz/php-gd-library-css-sprites_416/08/ or something else? there are many css sprite generators for php around (sourceforge ...)
doc_23533324
multiSort : true, sortname: 'orderNo asc, cd', sortorder: 'desc', How to do that? Is any other way to do that? I also tried below one $('#OrderGrid').jqGrid('sortGrid', 'orderNo', true, 'asc') .jqGrid('sortGrid', 'cd', true, 'desc'); But no luck still now... A: To set "desc" order one have to call sortGrid twice: $('#OrderGrid').jqGrid('sortGrid', 'orderNo', true, 'asc') .jqGrid('sortGrid', 'cd', true, 'desc') .jqGrid('sortGrid', 'cd', true, 'desc'); For example if you need to set sort direction of both orderNo and cd columns to desc you should use $('#OrderGrid').jqGrid('sortGrid', 'orderNo', true, 'desc') .jqGrid('sortGrid', 'orderNo', true, 'desc') .jqGrid('sortGrid', 'cd', true, 'desc') .jqGrid('sortGrid', 'cd', true, 'desc'); Be sure that you set multiSort option of jqGrid to true before calling of sortGrid: $('#OrderGrid').jqGrid('setGridParam', {multiSort: true}) .jqGrid('sortGrid', 'orderNo', true, 'asc') .jqGrid('sortGrid', 'cd', true, 'desc') .jqGrid('sortGrid', 'cd', true, 'desc'); Alternatively you can don't use sortGrid at all. The demo demonstrates the approach. It uses the following code setSorting.call($grid[0], "name", "desc"); setSorting.call($grid[0], "invdate", "asc"); $grid.jqGrid("setGridParam", { multiSort: true, sortname: "name desc, invdate asc" }).trigger("reloadGrid"); where setSorting function are defined as below var setSorting = function (colName, sortOrder) { var $self = $(this), colModel = $self.jqGrid("getGridParam", "colModel"), headers = $self[0].grid.headers, showSortIconsInAllCols = $self.jqGrid("getGridParam", "viewsortcols")[0], cmLength = colModel.length, cm, $sortSpan, i; for (i = 0; i < cmLength; i++) { cm = colModel[i]; if (cm.name === colName) { cm.lso = String(sortOrder).toLowerCase() === "desc" ? "desc" : "asc"; } $sortSpan = $(headers[i].el).find(">div.ui-jqgrid-sortable>span.s-ico"); if (showSortIconsInAllCols || cm.lso) { $sortSpan.show(); if (cm.lso) { $sortSpan.find(">span.ui-icon-" + cm.lso) .removeClass("ui-state-disabled"); } } } };
doc_23533325
class Project < ApplicationRecord has_many :comments has_many :contractor_projects has_many :contractors, through: :contractor_projects validates_presence_of :title, :contract_number, :category, :project_start_date, :project_end_date, :substantial_completion_date, :category, :solicitation_number, :project_officer, :location accepts_nested_attributes_for :contractor_projects end class Contractor < ApplicationRecord has_many :contractor_projects has_many :projects, through: :contractor_projects validates :name, presence: true validates :email, presence: true, uniqueness: true end class ContractorProject < ApplicationRecord belongs_to :contractor belongs_to :project end The ContractorProject model has an extra attribute #bid_status that I want to reflect on project's show page but it does not appear even though it's in the params when i raised it. A: below is sample method for your case def show @project = Project.find(params[:id] @contractors = @project.contractors end inside show.html.erb, you have to loop it, since it may get more than one records <% @contractors.each do |contractor| %> <%= contractor.bid_status %> <% end %>
doc_23533326
"Workorders" is a shared book that other departments put in Task request. The guys in the department, fill them out when they have completed the task. Each Sheet is renamed with the task number ID, so the sheet is never the same name. The "Workorders" book needs to be the main book. So is there a way for them to have a command button "Complete", that would move the active sheet they have filled out in "Workorders" into the "Completed Workorders" book. Either keep it open in the background, so they never see it, or if it can open, move the sheet, and close back. thank you for your help, and i do hope it is possible. A: Insert a button on the workbook and assign this code to the button, make sure to change the filename path to yours: Private Sub CommandButton1_Click() On Error Resume Next Dim sheetIndex As Integer sheetIndex = 1 Application.ScreenUpdating = False Workbooks.Open Filename:="C:\YourPath\Completed Workorders.xlsm" Windows("Workorders.xlsm").Activate ActiveSheet.Select ActiveSheet.Copy Before:=Workbooks("Completed Workorders.xlsm").Sheets(sheetIndex) sheetIndex = sheetIndex + 1 ActiveWorkbook.Save Windows("Completed Workorders.xlsm").Close Application.DisplayAlerts = False ActiveSheet.Delete Application.DisplayAlerts = True Application.ScreenUpdating = True End Sub
doc_23533327
<?php $ignore = array ('.', '..', '.DS_Store', 'index.php'); $num_ordnernamen = array (); if ($handle = opendir('./')) { while (false !== ($entry = readdir($handle))) { if (!in_array($entry, $ignore) && is_dir($entry)) { array_push($num_ordnernamen, $entry); } } } print_r ($num_ordnernamen); ?> , it returns the array as it should: Array ( [0] => firstfolder [1] => secondfolder ) It does, however, not work for if ($handle = opendir('../')) //or if ($handle = opendir('..')) //or if ($handle = opendir('../..')) … or anything else I try to get one level up. What am I missing here? A: * *Have you permissions to read parent directory? *Have you error reporting active? *There are directories in your parent directory? (your code print only directories)
doc_23533328
to this following I am unable to make this red border with CSS. Help is appreciated. Ignore the div width. Only thing I need help is the red background section. My code till now: .location-dtls { position: relative; width: 100%; padding-right: 15px; padding-left: 15px; display: flex; flex: 0 0 15%; max-width: 15%; flex-direction: column; align-items: center; justify-content: center; height: 80px; overflow-wrap: break-word !important; cursor: pointer; text-align: center; margin-bottom: 1.5rem; margin: 0.5rem; border-width: 0.001rem; border-style: solid; border-radius: 1rem; border-color: #e4e2e2; } <div class="location-dtls"> <div>Location 5</div> <div>Location 5 FN</div> </div> A: You can use pesudo elements to do this: .location-dtls { position: relative; width: 100%; padding-right: 15px; padding-left: 15px; display: flex; flex: 0 0 15%; max-width: 15%; flex-direction: column; align-items: center; justify-content: center; height: 80px; overflow-wrap: break-word !important; cursor: pointer; text-align: center; margin-bottom: 1.5rem; margin: 0.5rem; border-width: 0.001rem; border-style: solid; border-radius: 1rem; border-color: #e4e2e2; } .location-dtls::before { content: ""; position: absolute; top: 0; right: 0; width: 100%; height: 10px; background-color: red; border-radius: 1rem; } <div class="location-dtls"> <div>Location 5</div> <div>Location 5 FN</div> </div> A: The image you pasted has one additional rectangle, it seems. Do you only need the top section in red color, something like the following? You can achieve it by customizing the border-top-width and border-top-color rules. .location-dtls { position: relative; width: 100%; padding-right: 15px; padding-left: 15px; display: flex; flex: 0 0 15%; max-width: 15%; flex-direction: column; align-items: center; justify-content: center; height: 80px; overflow-wrap: break-word !important; cursor: pointer; text-align: center; margin-bottom: 1.5rem; margin: 0.5rem; border-width: 0.001rem; border-style: solid; border-radius: 1rem; border-color: #e4e2e2; border-top-width: 1.5rem; border-top-color: red; } <div class="location-dtls"> <div>Location 5</div> <div>Location 5 FN</div> </div> A: Simple solution for this will be .wrapper{ border:1px solid #ccc; display:inline-block; text-align:center; border-radius:.3em; } p{ margin:0; } .content{ padding:.3em 1em; } .red{ width:100%; height:1em; border-radius:.3em; background-color:red; border:1px solid #ccc; margin-top: -1px; margin-left: -1px; } <div class="wrapper"> <div class="red"></div> <div class="content"> <p>Location 5</p> <p>Location 5 FN</p> </div> </div>
doc_23533329
var myApp = angular.module('myApp', []); myApp.controller('myController', function ($scope,$http) { $scope.getDataFromServer = function() { $http ({ method:'GET', url:'jasoncontroller' }).success(function(data, status, headers, config){ $scope.sqldata = data; console.log("executing"); $scope.$watch('sqldata',function(newValue,oldValue){ console.info('changed'); console.log('new : ' + newValue); console.log('old : ' + oldValue); console.log('watch end'); }); }).error(function(data, status, headers, config){}); }; }); servlet doGet method protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("Executing get"); getSqlData sql = new getSqlData(); Gson gson = new GsonBuilder().serializeNulls().create(); String tabname="saleq315"; String json = gson.toJson(sql.gettabledata(tabname)); response.setContentType("application/json"); response.getWriter().write(json); System.out.println("data sent"); } Whenever i click to fetch data it never get me new data once i change the table name in tabname="saleq315"; after multiple click table data refresh. and when i log this to console i see http request getting executed mulpliple times. If you see the image attached, i changed the table name and click to get the data, first click - same table data --> console log one entry seconds click - same table data --> console log one entry third click - got new data --> console log 5 entries. Not sure what is happening here. [![enter image description here][1]][1]
doc_23533330
This is all well and good until the record submitter enters a carriage return into a freetext field, which Excel treats as a new line, and totally wrecks the formatting for re-entry into the database. A recent change seems to have made performing a find/replace of CR+LF on the data stored in the clipboard impossible. I have been doing it recently with this nifty bit of AHK script I found online: #h:: stringreplace,Clipboard,Clipboard,`r`n,&A_Space&,all Return Pasting the data into Notepad, copying it again, and then applying my find/replace script doesn't work. Pasting the data into Notepad++ and copying it again, then applying the script works too well. Each record line ends with a CRLF, so I need to keep some and remove the rest! This makes less likely that my method worked in the first place. Unless it was removing user entered CRLF and not the system entered ones. Implying they have some property of their own. Something is preventing these carriage returns from being removed. Is it possible they are being outputted not as carriage returns, but as a strange equivalent, and re-interpreted as CRLF by Windows software? Notepad seems to invisibly store whatever this character is, while Notepad++ does not. My VBA solution would be to remove all the returns and use the tabs to create and array, then dump the whole array into Excel. This method will still stumble on the possibility of the record containing a TAB in the free text part of a record, but I think this is quite rare. I think what I need to do is assess each part of the array and either: * *remove the CRLF *if it's tab position 49 in that row, split the array into two array values, add it to the array position immediately next to it and shunt the array along. I've managed to come up with some crude code for the purpose of putting data from the clipboard into an array and writing the values to Excel, but it has problems. I've tried replacing the vbCRLF with vbTab, but it's a crude start. Option Base 1 Sub clipcase() Dim wrdArray() As String Dim finalArray(201, 49) As String Dim RecordCount As Integer Dim maxCol, maxRow As Integer updatesOff maxCol = 49 maxRow = 201 maxCell = maxRow * maxCol Dim DataObj As MSForms.DataObject Set DataObj = New MSForms.DataObject DataObj.GetFromClipboard strPaste = DataObj.GetText(1) strPaste = Replace(strPaste, vbCrLf, vbTab) wrdArray() = Split(strPaste, vbTab) RecordCount = UBound(wrdArray) / 49 RecordCount = Application.Round(RecordCount, 0) For i = 1 To RecordCount + 1 For j = 1 To 49 finalArray(i, j) = wrdArray(k) k = k + 1 If k > UBound(wrdArray) Then GoTo dump Next j Next i dump: For i = 1 To UBound(finalArray, 1) For j = 1 To UBound(finalArray, 2) Cells(i, j).Value2 = finalArray(i, j) Next j Next i updatesOn End Sub Sub updatesOff() Application.Calculation = xlCalculationManual Application.ScreenUpdating = False End Sub Sub updatesOn() Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True End Sub
doc_23533331
var FeedsMain = global.FeedsMain = {} , colors = require('./colors') , conf = FeedsMain.conf = require('./conf').config , SITE_SECRET = conf.app.secret , zerorpc = require('zerorpc') , rpcClient = new zerorpc.Client() , feeds = require('socket.io').listen(conf.app.port) , services = require('./lib/services') , feedsService = services.getFeedsService() , authService = services.getAuthService() , profileVisitorsService = services.getProfileVisitorsService() , searchService = services.getSearchService() , usersService = services.getUserService() , temptingEventsDistributionService = services.getTemptingEventsDistributionService() , likesService = services.getLikesService() , commentsService = services.getCommentsService() , emitter = require('./lib/events').eventAPI , eventAPI = require('./lib/events').eventAPI , dataStore = require('./lib/events').store , _ = require('lodash') , cookie = require('cookie') , authMap = {} ; require('./clientResources').add(feeds); rpcClient.connect('tcp://127.0.0.1:4242'); rpcClient.on('error', function(error) { console.error('RPC client error:', error); }); feeds.set('log level', 1); feeds.set('authorization', function(handshakeData, accept) { console.log('authorization function run'); if (handshakeData.headers.cookie) { handshakeData.cookie = cookie.parse(handshakeData.headers.cookie); var dg_01 = handshakeData.cookie['dg_01'] ; if(dg_01) { rpcClient.invoke('getUser', dg_01, function(err, user) { if(err) { return accept('Unauthorized', false); } handshakeData.userId = user._id; handshakeData.user = user; handshakeData.sessionId = dg_01; setSessionId(user._id, dg_01); return accept(null, true); }); } else { console.log('Invalid session id: %s'.red, dg_01); return accept('Invalid Session!', false); } } else { return accept('No cookie transmitted.', false); } }); console.log('authorization method over'); As you would notice, all the variables are initialized ok. The feeds variable which is basically socket io initialization starts on port 4000. When I do localhost:4000, I get welcome to socket.io. However the authorization function doesn't run. I tried inserting a console.log('authorization function started') but it doesn't happen. However in the console I see authorization method over, which means that the authorization function was skipped completely. On my server everything works ok where I see messages like session set etc. that originate from authorization function. On my local it just doesn't seem to work. Anyone has a clue what could be the case.
doc_23533332
I want to blink the specific color, and then come back to black background. It all works fine... once. After this first blink nothing will happen. I've tried searching but couldn't find relevant answer. My guess it that I should somehow reset the state of the animation, but couldn't find any way to do that. This is the code I'm using for the animation: animate(withDuration: 0.2, animations: { //set first color //mainGroup is a WKInterfaceGroup self.mainGroup.setBackgroundColor(color) //set back black color self.mainGroup.setBackgroundColor(UIColor.black) }) A: I've researched a bit more. There are no options in animate function in WatchKit, and that is what makes it harder (can't use autoreverse). The solution is not perfect, but it more or less works. You need to first set the desired 'blink' color, and after that animate the transition to black. self.mainGroup.setBackgroundColor(color) animate(withDuration: 0.2, animations: { self.mainGroup.setBackgroundColor(UIColor.black) }) A: If you want a more complicated timing, e.g. smooth "in" animation, you can use delayed execution: animate(withDuration: 0.2) { self.mainGroup.setBackgroundColor(color) } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.21) { animate(withDuration: 0.2) { self.mainGroup.setBackgroundColor(.black) } }
doc_23533333
The first one is a double sided shader for Hololens from the Microsoft Holotoolkit: // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. Shader "MixedRealityToolkit/Obsolete/Fast Configurable 2 Sided" { Properties { _Mode("Rendering Mode", Float) = 0.0 [Toggle] _UseVertexColor("Vertex Color Enabled?", Float) = 0 [Toggle] _UseMainColor("Main Color Enabled?", Float) = 0 _Color("Main Color", Color) = (1,1,1,1) [Toggle] _UseMainTex("Main Texture Enabled?", Float) = 0 [NoScaleOffset]_MainTex("Main Texture", 2D) = "red" {} [Toggle] _UseOcclusionMap("Occlusion/Detail Texture Enabled?", Float) = 0 [NoScaleOffset]_OcclusionMap("Occlusion/Detail Texture", 2D) = "blue" {} [Toggle] _UseAmbient("Ambient Lighting Enabled?", Float) = 1 [Toggle] _UseDiffuse("Diffuse Lighting Enabled?", Float) = 1 [Toggle] _SpecularHighlights("Specular Lighting Enabled?", Float) = 0 [Toggle] _Shade4("Use additional lighting data? (Expensive!)", Float) = 0 [Toggle] _ForcePerPixel("Light per-pixel (always on if a map is set)", Float) = 0 _SpecColor("Specular Color", Color) = (0.5, 0.5, 0.5, 1) [PowerSlider(5.0)]_Specular("Specular (Specular Power)", Range(1.0, 100.0)) = 10.0 [Toggle] _UseSpecularMap("Use Specular Map? (per-pixel)", Float) = 0 [NoScaleOffset]_SpecularMap("Specular Map", 2D) = "white" {} _Gloss("Gloss (Specular Scale)", Range(0.1, 10.0)) = 1.0 [Toggle] _UseGlossMap("Use Gloss Map? (per-pixel)", Float) = 0 [NoScaleOffset]_GlossMap("Gloss Map", 2D) = "white" {} [Toggle] _UseBumpMap("Normal Map Enabled? (per-pixel)", Float) = 0 [NoScaleOffset][Normal] _BumpMap("Normal Map", 2D) = "bump" {} [Toggle] _UseReflections("Reflections Enabled?", Float) = 0 [NoScaleOffset]_CubeMap("CubeMap", Cube) = "" {} _ReflectionScale("Reflection Scale", Range(0.01, 3.0)) = 2.0 [Toggle]_CalibrationSpaceReflections("Reflect in calibration space?", Float) = 0 [Toggle] _UseRimLighting("Rim Lighting Enabled?", Float) = 0 [PowerSlider(.6)]_RimPower("Power", Range(0.1, 1.0)) = 0.7 _RimColor("Color", Color) = (1,1,1,1) [Toggle] _UseEmissionColor("Emission Color Enabled?", Float) = 0 _EmissionColor("Emission Color", Color) = (1,1,1,1) [Toggle] _UseEmissionMap("Emission Map Enabled?", Float) = 0 [NoScaleOffset] _EmissionMap("Emission Map", 2D) = "blue" {} _TextureScaleOffset("Texture Scale (XY) and Offset (ZW)", Vector) = (1, 1, 0, 0) [Enum(UnityEngine.Rendering.BlendMode)] _SrcBlend("SrcBlend", Float) = 1 //"One" [Enum(UnityEngine.Rendering.BlendMode)] _DstBlend("DestBlend", Float) = 0 //"Zero" [Enum(UnityEngine.Rendering.BlendOp)] _BlendOp("BlendOp", Float) = 0 //"Add" [Toggle] _AlphaTest("Alpha test enabled?", Float) = 0 _Cutoff("Alpha Cutoff", Range(-0.1, 1.0)) = -0.1 [Enum(UnityEngine.Rendering.CompareFunction)] _ZTest("ZTest", Float) = 4 //"LessEqual" [Enum(Off,0,On,1)] _ZWrite("ZWrite", Float) = 1 //"On" [Enum(UnityEngine.Rendering.ColorWriteMask)] _ColorWriteMask("ColorWriteMask", Float) = 15 //"All" } SubShader { Tags { "RenderType"="Opaque" "PerformanceChecks"="False" } LOD 100 Blend[_SrcBlend][_DstBlend] BlendOp[_BlendOp] ZTest[_ZTest] ZWrite[_ZWrite] Pass { Name "FRONT" Tags { "LightMode" = "ForwardBase" } Cull Back ColorMask[_ColorWriteMask] CGPROGRAM #pragma vertex vert #pragma fragment frag //compiles all variants needed by ForwardBase (forward rendering base) pass type. The variants deal with different lightmap types and main directional light having shadows on or off. #pragma multi_compile_fwdbase //expands to several variants to handle different fog types #pragma multi_compile_fog //We only target the HoloLens (and the Unity editor), so take advantage of shader model 5. #pragma target 5.0 #pragma only_renderers d3d11 //shader features are only compiled if a material uses them #pragma shader_feature _USEVERTEXCOLOR_ON #pragma shader_feature _USEMAINCOLOR_ON #pragma shader_feature _USEMAINTEX_ON #pragma shader_feature _USESOCCLUSIONMAP_ON #pragma shader_feature _USEBUMPMAP_ON #pragma shader_feature _USEAMBIENT_ON #pragma shader_feature _USEDIFFUSE_ON #pragma shader_feature _USESPECULAR_ON #pragma shader_feature _USEGLOSSMAP_ON #pragma shader_feature _SHADE4_ON #pragma shader_feature _USEREFLECTIONS_ON #pragma shader_feature _USERIMLIGHTING_ON #pragma shader_feature _USEEMISSIONCOLOR_ON #pragma shader_feature _USEEMISSIONTEX_ON #pragma shader_feature _ALPHATEST_ON //scale and offset will apply to all #pragma shader_feature _MainTex_SCALE_ON #pragma shader_feature _MainTex_OFFSET_ON //may be set from script so generate both paths #pragma multi_compile __ _NEAR_PLANE_FADE_ON #include "FastConfigurable.cginc" ENDCG } Pass { Name "BACK" Tags{ "LightMode" = "ForwardBase" } Cull Front ColorMask[_ColorWriteMask] CGPROGRAM #pragma vertex vert #pragma fragment frag //compiles all variants needed by ForwardBase (forward rendering base) pass type. The variants deal with different lightmap types and main directional light having shadows on or off. #pragma multi_compile_fwdbase //expands to several variants to handle different fog types #pragma multi_compile_fog //We only target the HoloLens (and the Unity editor), so take advantage of shader model 5. #pragma target 5.0 #pragma only_renderers d3d11 //shader features are only compiled if a material uses them #pragma shader_feature _USEMAINCOLOR_ON #pragma shader_feature _USEMAINTEX_ON #pragma shader_feature _USESOCCLUSIONMAP_ON #pragma shader_feature _USEBUMPMAP_ON #pragma shader_feature _USEAMBIENT_ON #pragma shader_feature _USEDIFFUSE_ON #pragma shader_feature _USESPECULAR_ON #pragma shader_feature _USEGLOSSMAP_ON #pragma shader_feature _SHADE4_ON #pragma shader_feature _USEEMISSIONCOLOR_ON #pragma shader_feature _USEEMISSIONTEX_ON //scale and offset will apply to all #pragma shader_feature _MainTex_SCALE_ON #pragma shader_feature _MainTex_OFFSET_ON //may be set from script so generate both paths #pragma multi_compile __ _NEAR_PLANE_FADE_ON #define FLIP_NORMALS 1 #include "FastConfigurable.cginc" ENDCG } } CustomEditor "HoloToolkit.Unity.FastConfigurable2SidedGUI" Fallback "VertexLit" //for shadows } The second one is a cross section shader from the Unity asset store: Shader "CrossSection/OnePlaneBSP" { Properties{ _Color("Color", Color) = (1,1,1,1) _CrossColor("Cross Section Color", Color) = (1,1,1,1) _MainTex("Albedo (RGB)", 2D) = "white" {} _Glossiness("Smoothness", Range(0,1)) = 0.5 _Metallic("Metallic", Range(0,1)) = 0.0 _PlaneNormal("PlaneNormal",Vector) = (0,1,0,0) _PlanePosition("PlanePosition",Vector) = (0,0,0,1) _StencilMask("Stencil Mask", Range(0, 255)) = 255 } SubShader { Tags { "RenderType"="Opaque" } //LOD 200 Stencil { Ref [_StencilMask] CompBack Always PassBack Replace CompFront Always PassFront Zero } Cull Back CGPROGRAM // Physically based Standard lighting model, and enable shadows on all light types #pragma surface surf Standard fullforwardshadows // Use shader model 3.0 target, to get nicer looking lighting #pragma target 3.0 sampler2D _MainTex; struct Input { float2 uv_MainTex; float3 worldPos; }; half _Glossiness; half _Metallic; fixed4 _Color; fixed4 _CrossColor; fixed3 _PlaneNormal; fixed3 _PlanePosition; bool checkVisability(fixed3 worldPos) { float dotProd1 = dot(worldPos - _PlanePosition, _PlaneNormal); return dotProd1 > 0 ; } void surf(Input IN, inout SurfaceOutputStandard o) { if (checkVisability(IN.worldPos))discard; fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color; o.Albedo = c.rgb; // Metallic and smoothness come from slider variables o.Metallic = _Metallic; o.Smoothness = _Glossiness; o.Alpha = c.a; } ENDCG Cull Front CGPROGRAM #pragma surface surf NoLighting noambient struct Input { half2 uv_MainTex; float3 worldPos; }; sampler2D _MainTex; fixed4 _Color; fixed4 _CrossColor; fixed3 _PlaneNormal; fixed3 _PlanePosition; bool checkVisability(fixed3 worldPos) { float dotProd1 = dot(worldPos - _PlanePosition, _PlaneNormal); return dotProd1 >0 ; } fixed4 LightingNoLighting(SurfaceOutput s, fixed3 lightDir, fixed atten) { fixed4 c; c.rgb = s.Albedo; c.a = s.Alpha; return c; } void surf(Input IN, inout SurfaceOutput o) { if (checkVisability(IN.worldPos))discard; o.Albedo = _CrossColor; } ENDCG } //FallBack "Diffuse" } I tried to start from the double sided shader and add pragma surf surface from the second one at the end of the first PASS like this: ... //End of the first PASS from the first shader #include "FastConfigurable.cginc" #pragma surface surf NoLighting noambient struct Input { half2 uv_MainTex; float3 worldPos; }; fixed4 _CrossColor; fixed3 _PlaneNormal; fixed3 _PlanePosition; bool checkVisability(fixed3 worldPos) { float dotProd1 = dot(worldPos - _PlanePosition, _PlaneNormal); return dotProd1 > 0; } fixed4 LightingNoLighting(SurfaceOutput s, fixed3 lightDir, fixed atten) { fixed4 c; c.rgb = s.Albedo; c.a = s.Alpha; return c; } void surf(Input IN, inout SurfaceOutput o) { if (checkVisability(IN.worldPos))discard; o.Albedo = _CrossColor; } ENDCG } Pass { Name "BACK" Tags{ "LightMode" = "ForwardBase" } Cull Front ColorMask[_ColorWriteMask] CGPROGRAM //Next of the second PASS of the first shader ... But I am getting the following errors: Shader Compiler Socket Exception: Terminating shader compiler process Shader compiler: Preprocess DoubleSidedStandardCrossCut.shader: Internal error communicating with the shader compiler process. Please report a bug including this shader and the editor log. Shader error in 'DoubleSidedStandardCrossCut': Parse error: syntax error, unexpected $end, expecting TOK_SHADER at line 1 If you have any tip or suggestion, I would really appreciate, thank you! A: As often, this boils down to what you want to achieve, and understanding which part of which shader does what you want in your final outcome. This is not very clear, and I can only make assumptions. It seems you have a given mesh; you wish that it can be (1) carved out based on a Plane, given its position and normal; and want (2) front-facing (F) and back-facing (B) surfaces to have different rendering properties. Writing multi-pass shaders is often just a shorthand for something you can do with just setup, albeit maybe with a little bit more overhead: Each pass is essentially another draw call, it could just as well be another object. Options: * *Write a multi-pass shader *Have 2 objects nested in a common transform, or have either object F or B nested into the other one. *Provided your mesh doesn't have sub-meshes, assign 2 materials into the MeshRenderer component. This list is usually assigning different materials to each sub-mesh, but if none is present it will just draw the Mesh again. In either case 2 and 3, you need 2 materials. They could both use the same shader, or for simplicity you could first author 2 shaders with baked-in properties: * *Material B(ack) has a lower render queue (maybe Geometry-1) since it always needs to be covered up by F(ront). (see https://docs.unity3d.com/Manual/SL-SubShaderTags.html) *Material B uses the Cull Front flag, and material F uses the Cull Back flag (the default one) *Both of them uses checkVisibility(IN.worldPos) to discard pixels that are carved out. On a side note: this needs to be fast since you seem to do VR, so I'd advocate to use the clip() hlsl instruction and have checkVisibility to return a float, to get rid of the conditional branching entirely.
doc_23533334
<script src="vendors/bower_components/jquery/dist/jquery.min.js"></script> <script src="vendors/bower_components/bootstrap/dist/js/bootstrap.min.js"></script> <script src="vendors/bower_components/flot/jquery.flot.js"></script> <script src="vendors/bower_components/flot/jquery.flot.resize.js"></script> <script src="vendors/bower_components/flot.curvedlines/curvedLines.js"></script> <script src="vendors/sparklines/jquery.sparkline.min.js"></script> <script src="vendors/bower_components/jquery.easy-pie-chart/dist/jquery.easypiechart.min.js"></script> <script src="vendors/bower_components/moment/min/moment.min.js"></script> <script src="vendors/bower_components/fullcalendar/dist/fullcalendar.min.js"></script> <script src="vendors/bower_components/simpleWeather/jquery.simpleWeather.min.js"></script> <script src="vendors/bower_components/Waves/dist/waves.min.js"></script> <script src="vendors/bootstrap-growl/bootstrap-growl.min.js"></script> <script src="vendors/bower_components/sweetalert/dist/sweetalert.min.js"></script> <script src="vendors/bower_components/malihu-custom-scrollbar-plugin/jquery.mCustomScrollbar.concat.min.js"></script> to this way of loading my dependencies using Requirejs // Config File for Require js requirejs.config({ shim: { bootstrap: { "deps": ['jquery'] }, jqueryflot: { "deps": ['jquery'] }, jqueryflotresize: { "deps": ['jquery'] }, curvedline: { "deps": ['jquery'] }, sparkedlines: { "deps": ['jquery'] }, bootstrapgrowl: { "deps": ['jquery'] }, sweetalert: { "deps": ['jquery'] }, customscroll: { "deps": ['jquery'] }, waves: { "deps": ['jquery'] }, autosize: { "deps": ['jquery'] }, timeago: { "deps": ['jquery'] }, datetimepicker: { "deps": ['jquery'] }, moment: { "deps": ['jquery'] }, appmin: { "deps": ['jquery', 'customscroll', 'waves', 'datetimepicker'] } }, baseUrl: 'lib', paths: { jquery: 'vendors/bower_components/jquery/dist/jquery.min', bootstrap: 'vendors/bower_components/bootstrap/dist/js/bootstrap.min', jqueryflot: 'vendors/bower_components/flot/jquery.flot', jqueryflotresize: 'vendors/bower_components/flot/jquery.flot.resize', curvedline: 'vendors/bower_components/flot.curvedlines/curvedLines', sparkedlines: 'vendors/sparklines/jquery.sparkline.min', waves: 'vendors/bower_components/Waves/dist/waves.min', bootstrapgrowl: 'vendors/bootstrap-growl/bootstrap-growl.min', sweetalert: 'vendors/bower_components/sweetalert/dist/sweetalert.min', customscroll: 'vendors/bower_components/malihu-custom-scrollbar-plugin/jquery.mCustomScrollbar.concat.min', autosize: 'vendors/bower_components/autosize/dist/autosize.min', moment: 'vendors/bower_components/moment/min/moment.min', datetimepicker: 'vendors/bower_components/eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min', appmin: 'js/app.min', global: 'js/global', menu: 'js/menu', loan: 'js/loan', login: 'js/login', payment: 'js/payment', timeago: 'js/timeago', suggestion: 'js/suggestions', settings: 'js/settings', contributions: 'js/contributions', profile: 'js/profile', dashboard: 'js/dashboard' } }); and then in my dashboard.html I load the files like so <script data-main="lib/js/config" src="lib/js/Requirejs.js"></script> <script> require(['config'], function(){ require(['js/libraryloaders/loadDashboardLibraries']); require(['js/dashboardjsloader']); }); </script> but the error I get is in the app.min.js it says Waves is undefined thus the reference Error am getting which is preventing my dashboard.html from loading properly. its seems that the third party library app.min.js is making use of waves and even after using the shim as above I still get the reference error The code for my dashboardjsloader.js are as follows define(['jquery', 'bootstrap', 'sparkedlines', 'waves', 'bootstrapgrowl', 'sweetalert', 'customscroll', 'appmin'], function ($, plot) { });
doc_23533335
The xml is: <payments> <pay3>5.1</pay3> <pay1>1</pay1> <pay2>50</pay2> <pay3>2</pay3> </payments> Tags <pay2>, <pay3> and <pay2> are optional and <pay1> is mandatory. All the <payX> tags may occur in any order and more than once or not to occur (except for <pay1>). So far I made the following xsd types but it is not working correctly if <pay1> is not present: <xs:simpleType name="TPayment"> <xs:restriction base="xs:decimal"> <xs:pattern value="[+]?\d+(\.\d{2})?" /> <xs:minInclusive value="0" /> </xs:restriction> </xs:simpleType> <xs:complexType name="TECR_Payments"> <xs:choice minOccurs="1" maxOccurs="unbounded"> <xs:element name="pay1" type="TPayment" maxOccurs="unbounded" /> <xs:element name="pay2" type="TPayment" minOccurs="0" maxOccurs="unbounded" /> <xs:element name="pay3" type="TPayment" minOccurs="0" maxOccurs="unbounded" /> <xs:element name="pay4" type="TPayment" minOccurs="0" maxOccurs="unbounded" /> </xs:choice> </xs:complexType> How to set that <pay1> is mandatory? A: Use this for your TECR_Payments type: <xs:complexType name="TECR_Payments"> <xs:sequence> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="pay2" type="TPayment" /> <xs:element name="pay3" type="TPayment" /> <xs:element name="pay4" type="TPayment" /> </xs:choice> <xs:element name="pay1" type="TPayment" /> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="pay1" type="TPayment" /> <xs:element name="pay2" type="TPayment" /> <xs:element name="pay3" type="TPayment" /> <xs:element name="pay4" type="TPayment" /> </xs:choice> </xs:sequence> </xs:complexType> This allows any number (including zero) of <pay2>, <pay3>, or <pay4> elements in any order, then requires one <pay1>, and then allows any number of <payX> elements in any order. Note that specifying minOccurs or maxOccurs on an xs:element inside an xs:choice doesn't really have the effect you want: The choice is first made between the type of element, and then the choice is made about how many elements of that type to use.
doc_23533336
it basically 1.gets a file id with "GET" method 2.gets the name and location of that file from database 3.sends it to the client with the headers and readfile but strangely that file always comes out as corrupted or damaged like if it's a zip or rar file file size is right and it opens ok but i cant open compressed files inside of it and that's when i get the file damaged error which is weird cuz if the code had a problem i shouldn't even be able to open the zip file(or at least i think i shouldn't) another thing is i've printed out the file with it's path right before sending the headers just to be sure everything is ok I've put the file address on the url and download the file , file was ok with no errors so everything is fine before sending the headers here is my code $file_id = isset($_GET['id']) && (int)$_GET['id'] != 0 ? (int)$_GET['id'] : exit; //////// finging file info $file = comon::get_all_by_condition('files' , 'id' , $file_id ); if(!$file) exit; foreach($file as $file){ $location = $file['location']; $filename = $file['file_name']; } ///////////// $site = comon::get_site_domian(); $ext = trim(end(explode('.' , $filename ))); $abslout_path = 'http://'.$site.'/'.$location.'/'.$filename; $relative = $location.'/'.$filename; ////////////////// content type switch($ext) { case 'txt': $cType = 'text/plain'; break; case 'pdf': $cType = 'application/pdf'; break; case 'zip': $cType = 'application/zip'; break; case 'doc': $cType = 'application/msword'; break; case 'xls': $cType = 'application/vnd.ms-excel'; break; case 'ppt': $cType = 'application/vnd.ms-powerpoint'; break; case 'gif': $cType = 'image/gif'; break; case 'png': $cType = 'image/png'; break; case 'jpeg': case 'jpg': $cType = 'image/jpg'; break; default: $cType = 'application/force-download'; break; } //////////////// just checking if(!file_exists($relative)){ echo $relative; echo '<br />'; exit; } if( !is_readable( $relative ) ) exit('its not redable'); if( headers_sent() ) exit('headers ? already sent !! '); header( 'Pragma: public' ); header( 'Expires: 0' ); header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' ); header( 'Cache-Control: private', false ); // required for certain browsers header( 'Content-Description:File Transfer' ); header($_SERVER['SERVER_PROTOCOL'].' 200 OK'); header( 'Content-Type:'.$cType); header( 'Content-Disposition: attachment; filename="'. basename($filename) . '";' ); header( 'Content-Transfer-Encoding: binary' ); header( 'Content-Length: ' . filesize($relative) ); readfile($abslout_path); exit; I've checked the headers couple times and they are fine(i think) , I've also add every headers known to man just to be sure ! I'm starting to think maybe it's something other than script like char encoding or folder permission ! or something like that !! am i missing something ? A: That seems allot of code just to force-download, here is a nice function I use all the time. It will handle files over 2GB too. <?php $file_id = (isset($_GET['id']) && (int)$_GET['id'] != 0) ? (int)$_GET['id'] : exit; /*finding file info*/ $file = comon::get_all_by_condition('files', 'id', $file_id); $path = $file['location'] . '/' . $file['file_name']; if (!is_file($path)) { echo 'File not found.('.$path.')'; } elseif (is_dir($path)) { echo 'Cannot download folder.'; } else { send_download($path); } return; //The function with example headers function send_download($file) { $basename = basename($file); $length = sprintf("%u", filesize($file)); header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . $basename . '"'); header('Content-Transfer-Encoding: binary'); header('Connection: Keep-Alive'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . $length); set_time_limit(0); readfile($file); } ?> A: if (file_exists($file)) { set_time_limit(0); header('Connection: Keep-Alive'); header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="'.basename($file).'"'); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); ob_clean(); flush(); readfile($file); } A: Very nice, helpful also... but there is a problem in your code - header('Content-Disposition: attachment; filename="'.basename($file).'"'; please change it with this following - header('Content-Disposition: attachment; filename="'.basename($file).'"'); you are forgot to close it. A: Your script may contain NOTICE or WARNING, try disabling error reporting on top of your script: error_reporting(0); A: Make sure you do not have any code executed after the last line readfile(FILE_NAME) I had to add die(); or exit(); as the last line, because MVC framework continues to render the view after readfile
doc_23533337
Here, how I makes calls via XHR: $.ajax = { pool: [], call: function(settings, onSuccess, onFailure) { var xhr = new XMLHttpRequest(); xhr.open(settings.type, settings.location, settings.async); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (xhr.status == 200) { var result = xhr.responseXML.xml.toString(); onSuccess($.Encoder.htmlDecode(result)); } }; $.ajax.pool.push(xhr); xhr.send(null); return xhr; } } Then: $.ajax.call({ type: "get", location: "Index.asmx/RaiseCallbackEvent?eventArgument=ramiz.uddin" , async: true }, function(e) {}, function(e){}) The webservice is fairly simple too: [WebMethod(EnableSession = true)] [ScriptMethod(UseHttpGet = true)] public string RaiseCallbackEvent(string eventArgument) { // some logic return "<say>hello</say>"; } And some web.config entries that allows POST, GET calls: <webServices> <protocols> <add name="HttpSoap"/> <add name="HttpPost"/> <add name="HttpGet"/> </protocols> </webServices> Could you please guide me what I've to do for asynchronous? Thanks. A: I bet you would find a lot of examples on Google but for the background, if you see there are functions listed as Begin[YourWebMethodName] and End[YourWebMethodName]. Begin... is called when invoking asynchronously wherein we have to pass a method which is called once the async call is finished and in this method apart from other processing you need to call End[YourWebMethodName] some code...... AsyncCallback ACB = new AsyncCallback(MyCallbackMethod); // Issue an asynchronous call<br> mywebsvc.BeginMyWebMethod1(name, ACB, mywebsvc); // Forget and Continue further //This is the function known as callback function <br> public void MyCallbackMethod(IAsyncResult asyncResult) { MyWebService mywebsvc = (MyWebService)asyncResult.AsyncState; result = webServ.EndMyWebMethod1(asyncResult); //use the result }
doc_23533338
That is <div class="form-group"> <label class="control-label col-sm-4"><b>Your role</b></label> <div class="col-sm-6"> <div class="row"> <div class="col-sm-4"> <label class="radio-inline"> <input type="radio" id="teacher" value="Teacher" name="role" required><b>Teacher</b> </label> </div> <div class="col-sm-4"> <label class="radio-inline"> <input type="radio" id="student" value="Student" name="role"required><b>Student<b> </label> <div class="col-sm-4"> <label class="radio-inline"> <input type="radio" id="administrator" value="administrator" name="role"required><b>Admin<b> </label> </div> </div> </div> </div> </div> And my insert format is $role ->role=$request['role']; I think my insert format is wrong. If it is wrong what will be the correct format? A: You need to do: $role->role = $request->input('role');
doc_23533339
I'm using man object class. Here's my class. class Man { private string _name; public string name { set { _name = value; } get { return _name; } } private string _address; public string address { set { _address = value; } get { return _address; } } } and I have two Lists here are those. List<Man> people= new List<Man>(); List<Man> people2 = new List<Man>(); public string tempname; Here's whole code for the row click event. private void dataGridView1_Click(object sender, EventArgs e) { foreach (DataGridViewRow row in dataGridView1.SelectedRows) { Man manobj = new Man(); manobj.name = Convert.ToString(row.Cells[0].Value); tempname = Convert.ToString(row.Cells[0].Value); manobj.address= Convert.ToString(row.Cells[1].Value); //Adding the man object people2.Add(manobj); BindingSource manbind2= new BindingSource(); manbind2.DataSource = people2; dataGridView2.DataSource = manbind2; dataGridView1.Rows.RemoveAt(row.Index); for (int i = 0; i < people.Count; i++) { Man tempman = people[i] as Man; if (tempman.name == tempname) { people.Remove(tempman); } } } } When I click sometimes I get this error message. The following exception occured in the DataGridView. System.indexOutOfRangeException:Index 0 does not have a value at System.Windows.Forms.CurrencyManager.get_Item(Int32index)at System.Windows.Forms.DataGridView.DataGridViewDataConnection.GetError(Int32rowIndex) To Replace this default dialog please handle the data error event. and cells getting emptied one by one and all the time error message pops up. Can anyone tell me how to correct it?
doc_23533340
I tried preg_match, but got tired after i saw all characters when doing Windos + . ...there is too much characters...and i just want to simplify my code..so how? A: RegEx will do the trick. Edit: I see now that you'd like to allow only specified characters, iterating the string will be sufficient for this. <?php function validateUsername($username, $minLength = 3, $maxLength = 20) { $allowed_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890._ //"; if (strlen($username) < $minLength || strlen($username) > $maxLength) { return false; } for ($i = 0; $i < strlen($username); $i++) { if (strpos($allowed_chars, $username[$i]) === false) { return false; } } return true; } $usernames = [ "test", "test123", "test_123", "test.123", "test-123", "test\"" ]; foreach ($usernames as $username) { echo "Username: $username is " . (validateUsername($username) ? "valid" : "invalid") . "<br>"; } ?>
doc_23533341
/Max A: In PHP 5.3: gc_collect_cycles(). A: Here's an article on memory management in PHP. You can also increase available memory in PHP if you aren't already maxed out. Keep in mind: Sometimes you can't just "dump memory". Depending on your algorithm, you may need the results from previous calculations for future calculations. The key here might be to break your problem up into smaller problems and solve them individually. Check out this article on Dynamic Programming. A: Provided this is not a server application, I would recommend breaking up the script into cron jobs. Anyway, the problem is more than likely that you're not being careful with your variables. If you're running out of memory, then then you need to remember to unset() your variables. As well, watch your variable scope. If a variable never goes out of scope, PHP GC cannot clean it up until you remove all references to it.
doc_23533342
Having the following SQL query SELECT MONTHNAME(r.date_of_application) month_name, MONTH(r.date_of_application) month, SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) pending, SUM(CASE WHEN status = 'attended' THEN 1 ELSE 0 END) attended, SUM(CASE WHEN status = 'absent' THEN 1 ELSE 0 END) absent, SUM(CASE WHEN status = 'canceled' THEN 1 ELSE 0 END) canceled FROM request r INNER JOIN user u ON u.id = r.user_id GROUP BY month_name , month ORDER BY 2 DESC; I get this result +------------+-------+---------+----------+--------+----------+ | month_name | month | pending | attended | absent | canceled | +------------+-------+---------+----------+--------+----------+ | October | 10 | 4 | 1 | 0 | 1 | +------------+-------+---------+----------+--------+----------+ Now I want to sum the values of the columns pending, attended, absent and canceled an add the result in a new column total. This is the expected result. +------------+-------+---------+----------+--------+----------+-------+ | month_name | month | pending | attended | absent | canceled | total | +------------+-------+---------+----------+--------+----------+-------+ | October | 10 | 4 | 1 | 0 | 1 | 6 | +------------+-------+---------+----------+--------+----------+-------+ This query could have many results Thanks in advance A: Just add a COUNT(*) aggregation term to capture the entire count of all statuses: SELECT MONTHNAME(r.date_of_application) month_name, MONTH(r.date_of_application) month, COUNT(CASE WHEN status = 'pending' THEN 1 END) pending, COUNT(CASE WHEN status = 'attended' THEN 1 END) attended, COUNT(CASE WHEN status = 'absent' THEN 1 END) absent, COUNT(CASE WHEN status = 'canceled' THEN 1 END) canceled, COUNT(*) total FROM request r INNER JOIN user u ON u.id = r.user_id GROUP BY month_name , month ORDER BY 2 DESC; Note: If you want the total to include only the four status values which you are currently tallying, then use a conditional aggregation: COUNT(CASE WHEN status IN ('pending', 'attended', 'absent', 'cancelled') THEN 1 END) AS total
doc_23533343
type T = { id: number; title: string; }; This type is used to create a list of Ts like so: const IT: StringMap<T> = { a: { id: 0, title: 'foo', }, b: { id: 1, title: 'bar', }, c: { id: 2, title: 'foobar', }, } I need a way to be able to retrieve one of these T type objects based on their id. So I created the following function: const getTUsingId = (ts: StringMap<T>, id: number): T => { Object.values(ts).forEach((t: T) => { if (t.id === id) { return t } }); // This is as a safeguard to return a default value in case an invalid id is passed return ts['a'] } For whatever reason, this function will always return ts['a'] regardless of what id I pass to it. Console logging t.id === id even returns true but it still carries on until the end of the ts map! Any help is highly appreciated! A: return won't break out of your loop. You need to use a plain for loop: const getTUsingId = (ts: StringMap<T>, id: number): T => { for (const t of Object.values(ts)) { if (t.id === id) { return t } } return ts['a'] } A: the forEach callback is for performing an action on every element in the array, it's return isn't used for termination, what you want is filter, find or a regular for loop Object.values(ts).filter((t: T) => { return t.id === id; }); return all values where the id matches as a fresh array, you would use this if there was a possibility of multiple match, you would then need to parse the returned array to decide which match was correct Object.values(ts).find((t: T) => { return t.id === id; }); return only the first matching value for(const t of Object.values(ts)) if (t.id === id) { return t } }); my preference would be find const getTUsingId = (ts: StringMap<T>, id: number): T => { return Object.values(ts).find((t: T) => t.id === id) ?? ts['a'] }
doc_23533344
#!/usr/bin/env python from urllib2 import urlopen import gc import xml.etree.ElementTree as ET import sqlite3 rosetta_url = ("https://boinc.bakerlab.org/rosetta/team_email_list.php?teamid=12575&account_key=Y&xml=1") root = ET.parse(urlopen(rosetta_url)).getroot() cpids = [el.text for el in root.findall('.//user/cpid')] print cpids conn = sqlite3.connect("GridcoinTeam.db") c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS GRIDCOINTEAM (cpid TEXT)''') c.executemany("INSERT INTO GRIDCOINTEAM VALUES (?);", cpids) conn.commit() conn.close() conn = sqlite3.connect("GridcoinTeam.db") c = conn.cursor() cpids = c.execute('select cpid from GRIDCOINTEAM').fetchall() conn.close() print cpids gc.collect() Im getting the error: Incorrect number of bindings supplied. The current statement uses 1, and there are 32 supplied. I tried making the insertion tuples by changing to c.executemany("INSERT INTO GRIDCOINTEAM VALUES (?);", (cpids, )) but that just gives: Incorrect number of bindings supplied. The current statement uses 1, and there are 3289 supplied. The XML extract is in the form ['5da243d1f47b7852d372c51d6ee660d7', '5a6d18b942518aca60833401e70b75b1', '527ab53f75164864b74a89f3db6986b8'], but there are several thousand entries. Thanks. A: You need to insert this as multiple rows instead of multiple columns into one row cpids = [el.text for el in root.findall('.//user/cpid')] cpids = zip(*[iter(cpids)]*1) print cpids A: The problem lies in c.executemany("INSERT INTO GRIDCOINTEAM VALUES (?);", cpids) This executemany expects a list of tuples, but you pass a list of strings. What the code does effectively is: for entry in cpids: c.execute("INSERT INTO GRIDCOINTEAM VALUES (?);", *entry) Note the star before entry, which unloads the string, and which gives you 32+ params whereas you only want one. In order to fix that we'd need to know your GRIDCOINTEAM table schema. If you have a table with only one column and you want to insert that, you could probably do this: for entry in cpids: c.execute("INSERT INTO GRIDCOINTEAM VALUES (?)", entry) In contrast to executemany, execute takes each parameter as one param - no tuples and lists unloading here. Alternatively you can resort to using executemany, but you'd then need to wrap every one of your strings in a tuple or generator: c.executemany("INSERT INTO GRIDCOINTEAM VALUES (?);", [(i,) for i in cpids])
doc_23533345
Paypal express works fine however paypal standard payments gets the problem as above. Lucas A: You have to examine the ajax request. You can use Firefox with the "HTTPfox" extension to track the single requests. Just look for the step, where the redirect is executed - and start the http tracker. Then you see the response. In the response you can see, what went wrong. I've got this error some weeks ago and it printed a full html page (with the report-number you can look up in the var/log/reports folder) or you can see a php error (maybe syntax error or bad sql query for example). If you get a blank page, you have to set the error_reporting to E_ALL. A: I thinkk that step is help. * *Log into Magento Admin *Hover over "System" Click "Configuration" *On the next page in the left menu under "Advanced" *Under the check "Mage_Paypal" is Enable or Disable. if is Disable then Enable this options. Then After the paypal is not redirect to paypal site. then please check your template code. hope this will sure help you
doc_23533346
var day=new Date().getDay(); switch (day) { case 0: window.document.location.href = 'su.html'; break; case 1: window.document.location.href = 'mo.html'; break; case 2: window.document.location.href = 'tu.html'; break; case 3: window.document.location.href = 'we.html'; break; case 4: window.document.location.href = 'th.html'; break; case 5: window.document.location.href = 'fr.html'; break; case 6: window.document.location.href = 'sa.html'; break; } }; it does not load the current html page. It loads the index.html file can somebody pls tell me how to make this could work ? thanks! i've got an array whith week days A: You can't put the javascript in every page, but only in a "loading" page that execute the code and navigate the user in the correct page. Loading page (With your script) -> Go in the correct page A: You will need to change your script to something like this if you want to have the same script in every page: window.onload=function(){ var day=new Date().getDay(); var path = window.location.pathname; var page = path.split("/").pop(); if(day == 0 && page != 'su.html') window.document.location.href = 'su.html'; else if(day == 1 && page != 'mo.html') window.document.location.href = 'mo.html'; else if(day == 2 && page != 'tu.html') window.document.location.href = 'tu.html'; else if(day == 3 && page != 'we.html') window.document.location.href = 'we.html'; else if(day == 4 && page != 'th.html') window.document.location.href = 'th.html'; else if(day == 5 && page != 'fr.html') window.document.location.href = 'fr.html'; else if(day == 6 && page != 'sa.html') window.document.location.href = 'sa.html'; };
doc_23533347
This is a derivative of, though not duplication of an existing question; Why use HttpClient for Synchronous Connection. Yet over and over, including in the article I see above, I see a consistent recommendation to use HttpClient, even in a synchronous scenario. The best reason I've seen is the accepted answer in the SO post above but it essentially boils down to; Use this because "shiny". Which I'm not liking as an acceptable answer for my scenario. I'd prefer to use the correct object for the task at hand and this seems to be the older HttpWebRequest. Even Ben Watson's excellent resource "Writing High-Performance .NET Code" states the following; Another example is the System.Net.HttpWebRequest class, which will throw an exception if it receives a non-200 response from a server. This bizarre behavior is thankfully corrected in the System.Net.Http.HttpClient class in .NET 4.5 But in my scenario, I actually do want that behavior. While there are a lot of good use cases for HttpClient, can anyone offer a good reason not to use HttpWebRequest in my scenario? Am I using the correct object or not? And more importantly, why? A: HttpClient is designed to give more control over http protocol, where else doing same in HttpWebRequest or WebClient was not that straight forward. Apart from asynchronous, there are many benefits of HttpClient Benefits of HttpClient Biggest benefit of HttpClient is plugin architecture, that lets you change underlying behavior of HTTP protocol easily. * *HttpClient is extensible, underlying HttpMessageHandler allows you to completely by pass underlying Microsoft's HttpClient implementation and you can plugin your own implementation. For example, in iOS and Android, instead of using .Net's HttpClient, we could use native Http stack. *It is easy to replace caching, cookies by customizing HttpMessageHandler *CancellationToken support is excellent when we want to cancel a long running Http request. *Not shiny, but important, Multi threaded, HttpClient is optimized to manage multiple requests with single instance. CPU time is utilized very efficiently without using too many locks (synchronous operations depend on locks, which is considerable overhead on CPU). Today we are living in world of micro services. In server with many clients to serve and mobile OS, CPU time is costly. Drawbacks Only drawback is async/await, you can't simply use async libraries easily in synchronous code without using a Task Runner or deadlocks. Though there are many libraries supporting how to synchronously use async code. There is no great benefit of HttpClient on Desktop application with lots of CPU time as spare. A: HttpClient's behavior is considered "cleaner" because a non-success response from the server doesn't necessarily mean something has gone awry. While it's not true of your situation, imagine a process that wants to check that a resource does not exist and expects that it typically does not. With HttpWebRequest, the normal execution flow throws an exception, which is kind of gross and can complicate things, whereas HttpClient does not. For your specific scenario, the distinction is perhaps irrelevant. Other situations in your program might prefer the HttpClient behavior though, and it's nice to standardize on a single HTTP client instead of having to juggle two. A: HttpClient is not a replacement of WebClient/HttpWebRequest. HttpWebRequest gives you more flexibility, but at the same time it makes your code bit more verbose. Where as HttpClient provides a simple interface. You can use HttpWebRequest over HttpClient if you really want the additional features. As per non-200 response code exceptions are concerned, HttpClient provides a way to simulate that behavior. You have to invoke response.EnsureSuccessStatusCode(); For more details please visit Usage of EnsureSuccessStatusCode and handling of HttpRequestException it throws
doc_23533348
Let's say I have: a = np.array([[1, 2, 3], [3, 4, 5], [1, 4, 6]]) b = np.array([[1, 2], [3, 4]]) and the result should look like this: [[1, 2, 3], [3, 4, 5]] Any advice on that? EDIT: So in the end this works. Not very handy but it works. for ii in range(a.shape[0]): u, v, w = a[ii,:] for jj in range(b.shape[0]): if (u == b[jj, 0] and v == b[jj, 1]): print [u, v, w] A: The numpy_indexed package (disclaimer: I am its author) contains functionality to solve such problems efficiently, without using any python loops: import numpy_indexed as npi a[npi.contains(b, a[:, :2])] A: If you prefer to not use another library but want to do this in numpy only, you can do something similar to what is suggested here and here, namely to use np.in1d (see docs) which does provide you with a mask indicating if an element in one 1D array exists in another 1D array. As the name indicates, this function only works for 1D arrays. But you can use a structured array view (using np.view) to cheat numpy into thinking you have 1D arrays. One caveat is though, that you need a deep copy of the first array a since np.view doesn't mix with slices, well. But if that is not too big of an issue for you, something along the lines of: a_cp = a[:, :2].copy() a[np.in1d(a_cp.view((np.void, a_cp.dtype.itemsize*a_cp.shape[1])).ravel(), b.view((np.void, b.dtype.itemsize*b.shape[1])).ravel())] might work for you. This directly uses the masked array to return the correct values from your array a. A: Check this, @Ernie. It may help you to get to the solution. ;D http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.in1d.html
doc_23533349
foo.py: """ This is foo a nice module """ import numpy as np def function(parameter): return(np.zeros(parameter)) Then in another script I want to call my module: import foo So my problem is that numpy module is loaded inside foo so I can call it from foo (for example I can foo.np.zeros()) Is there any way that I'm not aware of in which the module will still work without having all numpy loaded inside it (naturally numpy should be loaded globally so foo works but i don't want it to be accessible from foo.np) So far I've tried: if __name__ == '__main__': import numpy as np But this breaks the module foo even if numpy is loaded.
doc_23533350
In particular, I see two different reordering scenarios: 8.2.3.4 Loads May Be Reordered with Earlier Stores to Different Locations and 8.2.3.5 Intra-Processor Forwarding Is Allowed However, I do not understand the difference between these scenarios from the observable effects POW. The examples provided in those sections seem interchangeable to me. 8.2.3.4 example can be explained by 8.2.3.5 rule just as well as by its own rule. And the converse seems true to me as well, although I am not that sure in that case. So here is my question: are there better examples or explanations how the observable effects of 8.2.3.4 are different from observable effects of 8.2.3.5? A: The example at 8.2.3.5 should be "surprising" if you expect memory ordering to be all strict an clean, and even if you acknowledge that 8.2.3.4 allows loads to reorder with stores of different addresses. Processor 0 | Processor 1 -------------------------------------- mov [x],1 | mov [y],1 mov R1, [x] | mov R3,[y] mov R2, [y] | mov R4,[x] Note that the key part is that the newly added loads in the middle both return 1 (store-to-load forwarding makes that possible in the uarch without stalling). So in theory, you would expect that both stores have been "observed" globally by the time both these loads completed (that would have been the case with sequential consistency, where there is a unique ordering between stores and all cores see it). However, having later R2 = R4 = 0 as a valid outcome proves this is not the case - the stores are in fact observed locally first. In other words, allowing this outcome means that processor 0 sees the stores as time(x) < time(y), while processor 1 sees the opposite. This is a very important observation about the consistency of this memory model, which the previous example doesn't prove. This nuance is the biggest difference between Sequential Consistency and Total Store Ordering - the second example breaks SC, the first one doesn't.
doc_23533351
At the moment I am raising errors in the F# build script and this sets the exit code, but it also displays nasty exceptions and stackstraces in the build log. Thanks in advance and best regards, Steffen A: Thanks to Alexander I now know the answer. I have to call exit myExitCode.
doc_23533352
data Tree = Branches (List Tree) | Node Int sumTree : Tree -> Int sumTree (Branches xs) = sum (map sumTree xs) sumTree (Node x) = x If I want it pass the totality check, I have to expand map manually: data Tree = Branches (List Tree) | Node Int sumTree : Tree -> Int sumTree (Branches xs) = sum' xs where sum' [] = 0 sum' (x::xs) = sumTree x + sum' xs sumTree (Node x) = x Which makes a lot of power with functional programming not available if I want to avoid assert_total everywhere. Is there any way to workaround this issue?
doc_23533353
I'm using NavLink from react-router-dom and I want to toggle the className active to mark the link clicked here is the code: import React from 'react' import styles from './NavBar.module.css' import logo from '../assets/logos/icon-left-font-monochrome-white.svg' import { NavLink } from 'react-router-dom' export default function NavBar() { return ( <div className={styles.nav_contrainer}> <img className={styles.img} src={logo} alt='logo groupomania avec typo blanc' /> <nav className={styles.nav}> <NavLink to='/home' exact='true' className={(navData) => (navData.isActive ? 'active' : 'none')} style={{ textDecoration: 'none' }}> <li>Home</li> </NavLink> <NavLink to='/articlebuilder' className={(navData) => (navData.isActive ? 'active' : 'none')} style={{ textDecoration: 'none' }}> <li>Γ‰crire un article</li> </NavLink> <NavLink to='/profile' className={(navData) => (navData.isActive ? 'active' : 'none')} style={{ textDecoration: 'none' }}> <li>Profile</li> </NavLink> </nav> </div> ) } This code has a solution from an other post, how ever it's not working for me... I tried the exact='true' in all links but it still doesn't work. Here is the code where the path are linked <div className='App'> <Routes> <Route path='/' exact={true} element={<HomePage />} /> <Route path='/landingpage' exact={true} element={<LandingPage />} /> <Route path='/home' exact={true} element={<HomePage />} /> <Route path='/profile' exact={true} element={<Profile />} /> <Route path='/articlebuilder' exact={true} element={<ArticleBuilder />} /> <Route path='/signup' exact={true} element={<Signup />} /> <Route path='/signin' exact={true} element={<Signin />} /> </Routes> </div> this is the css file: .nav_contrainer { background-color: #ffac99; display: flex; align-items: center; justify-content: space-between; padding: 0em 0em 0em 1em; } nav { display: flex; position: sticky; } nav a { list-style: none; font-size: 1.6em; color: white; transition: all ease-in-out 350ms; padding: 10px; } nav a:hover { color: #870e07; cursor: pointer; } .nav_contrainer img { width: 15%; height: 15%; } .active { color: #870e07; font-weight: bold; } Have I missed something? A: It seems your class needs to be the active class from the NavBar CSS module. function NavBar() { return ( <div className={styles.nav_contrainer}> <img className={styles.img} src={logo} alt='logo groupomania avec typo blanc' /> <nav className={styles.nav}> <NavLink to="/home" className={(navData) => (navData.isActive ? styles.active : "none")} style={{ textDecoration: "none" }} > <li>Home</li> </NavLink> <NavLink to="/articlebuilder" className={(navData) => (navData.isActive ? styles.active : "none")} style={{ textDecoration: "none" }} > <li>Γ‰crire un article</li> </NavLink> <NavLink to="/profile" className={(navData) => (navData.isActive ? styles.active : "none")} style={{ textDecoration: "none" }} > <li>Profile</li> </NavLink> </nav> </div> ); }
doc_23533354
https://github.com/jacob-meacham/angular-notification-icons First step is Running: npm install angular-notification-icons --save I am not sure what path I need to run this? I try to run it in my project path but I am getting this error: npm ERR! code ENOSELF npm ERR! Refusing to install package with name "angular-notification-icons" under a package npm ERR! also called "angular-notification-icons". Did you name your project the same npm ERR! as the dependency you're installing? npm ERR! A: Problem cause when name of project in package.json is similar with the name of npm module. To solve please change project name in package.json to other. example "angular-notification-icons-test" { "name": "angular-notification-icons-test", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" }, ... }
doc_23533355
I'm not sure if this question makes much sense, if not, then any examples you can provide would very much appreciated. Kinds Regards Sid A: You should name them for processes as this is how it is conceptualized in WCF. The service interface has the ServiceContract attribute and the methods have the OperationContract attribute. The types your service uses have the DataContract attribute, e.g. Employee. This separation between operations and data types is one of the advantages of WCF.
doc_23533356
I wrote - Dim stringList As Variant Set stringList = Split(myMessage.Body, vbLf) Debug.Print stringList(0) But it says type mismatch. How do I fix it? A: * *Don't use Set to assign the array returned by the Split() function to your stringList variable. The Set keyword is used to assign an object reference. *It's better to declare the stringList as an array of String instead of a Variant since you already know the type of the value to be assigned. *One more thing, you might want to split the string using vbNewLine instead of vbLf. This should work: Sub SplitMsgBody() Dim stringList() As String stringList = Split(myMessage.Body, vbNewLine) 'or vbLf depending on your requirements. For Each s In stringList Debug.Print s Next End Sub Hope that helps.
doc_23533357
If I have a code that looks like this: <div style="font-family: arial; font-size: 11px; background: green;">Hello</div> And then open it with CKEditor, it looks like this: <div style="font-family: arial font-size: 11px background: green">Hello</div> The ; has disappeared. It does not matter which style settings I use, the semicolon disappears in all cases. It does not matter what element the style setting is in. The same problem appears in img, div, a, span... and so on. What shall I do? I am about 100% sure it is ckeditor that is the problem. I open the HTML right from the database. But what else than ckeditor could it be? I do not use any CMS site, just pure php. A: might be some configuration issues. reinstall properly because i am also using ckeditor it's works fine in all browser and support all kind of html or css tags
doc_23533358
A: I believe this feature is not available if you're using Expo, however if you're using Bare-bone RN then you'll be able to use the native modules provided from Firebase to initialize the dynamic links, this page shows detailed documentation on how to implement the feature you need for your app.
doc_23533359
A: I have encountered this problem before. The trouble is that in order to open a file in Excel, you usually have to load the entire file into memory. This is fine when the file is 50 or 500k, but when it's 5GB, the system cannot load it into memory. In order to work with that much data, you really need to load it into a database and run queries on it. Databases are optimized to work with large quantities of data (even way in excess of 5GB). The tricky part will be loading this data into a database. You need a program which can parse your file (read line by line) and insert each TSV value into the appropriate database column. Writing an app to do this yourself may be best. If you're a windows person, you can use C# (http://www.microsoft.com/visualstudio/eng/products/visual-studio-2010-express) and MSSQL Express (http://www.microsoft.com/en-us/download/details.aspx?id=29062). Here's a helpful resource for parsing (Modify CSV Parser to work with TSV files C#). Here's a resource for inserting rows into MSSQL (How to insert data into SQL Server) A: Agree with Dan, such data should be loaded into database and run queries on it. One handy tool to do that is DB Browser for SQLite. You can import csv, tsv files into this as tables and run SQL queries on it. It uses sqlite underline and supports most of the SQL functions. Works on Mac and Windows as well.
doc_23533360
I have a script.ps1 My script can be illustrated like this : function Begin{ #Step 1 : StartTodoSometing #Step2 : KeepDooingSomething } function StartTodoSometing{} function KeepDoingSomething{} This script have can be run on a local server or multiple remote server. The nested function StartTodoSometing and KeepDoingSomething are public so I can't put it in the "Begin" function. My question is, how can I run the "Begin" function on a remote computer ??? Thanks for your help !!! :) A: I don't know what you mean with public, but if it's a fileshare or anything you should be able to use the following: function Begin{ . .\POWERSHELLSCRIPT\LOCATION\StartTodoSometing.ps1 . .\POWERSHELLSCRIPT\LOCATION\KeepDoingSomething.ps1 #Step 1 : StartTodoSometing #Step2 : KeepDooingSomething }
doc_23533361
I use QT creator as IDE and enable C++14 by using flag in .pro QMAKE_CXXFLAGS += -std=c++14 here is the part of error that happens in BOOST library: c_time.hpp //! requires a pointer to a user created std::tm struct inline static std::tm* localtime(const std::time_t* t, std::tm* result) { result = std::localtime(t); if (!result) boost::throw_exception(std::runtime_error("could not convert calendar time to local time")); return result; } //! requires a pointer to a user created std::tm struct inline static std::tm* gmtime(const std::time_t* t, std::tm* result) { result = std::gmtime(t); if (!result) boost::throw_exception(std::runtime_error("could not convert calendar time to UTC time")); return result; } the compiler yelled that std::time_t time_t is not a part of std namespace also same problem as std::localtime and std::gmtime I also #include <ctime> <time.h> <cstdlib> in main before calling all boost libraries but it does not help. another thing that I found when i tried to trace back to ctime (std c++ file in C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\ctime) here is the part of the code in ctime #if _GLOBAL_USING && !defined(RC_INVOKED) _STD_BEGIN using _CSTD clock_t; using _CSTD size_t; using _CSTD time_t; using _CSTD tm; using _CSTD asctime; using _CSTD clock; using _CSTD ctime; using _CSTD difftime; using _CSTD gmtime; using _CSTD localtime; using _CSTD mktime; using _CSTD strftime; using _CSTD time; _STD_END #endif /* _GLOBAL_USING */ #endif /* _CTIME_ */code here the error is clock_t: symbol cannot be used in a using declaration error or clock_t is not a member of global namespace I tried with different versions of BOOST library ( boost 1.64, boost 1.65, boost 1.66) The libraries I download from precompile BOOST binaries and install directly to my machine ( https://sourceforge.net/projects/boost/files/boost-binaries/ ) here is my pro file from QT creator using MSVC2015 as compiler BOOST_PATH = C:/local/boost_1_66_0 INCLUDEPATH += $${BOOST_PATH} LIBS += -L$${BOOST_PATH}/lib64-msvc-14.1 LIBS += -lboost_atomic-vc140-mt-1_66 LIBS += -lboost_chrono-vc140-mt-1_66 .......... SOURCES += \ main.cpp \ mainwindow.cpp HEADERS += \ mainwindow.h FORMS += \ mainwindow.ui here is what my main.cpp look like. This is a clean QT Application project. There is nothing in other files #include <stdlib.h> #include <cstdlib> #include <limits> #include <fstream> #include <vector> #include "boost/filesystem.hpp" #include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); } NOTE: I think the problem is MSVC compiler find function in a wrong namespace. for example std::localtime() should find in std namespace but the compiler find this function "localtime" in c_time.hpp and it tries to match std::localtime to boost::localtime and give the error.
doc_23533362
Example: Enter: 1 2 3 4 5 6 Search: 5 Result: 1+2+3+4=10 because they are <5 #include <iostream> using namespace std; struct Nodo{ int dato; Nodo *next; }; Nodo *lista = NULL; //list of functions void menu(); void ingresarLista(Nodo *&, int); void printList(Nodo *); void searchList(Nodo *, int); //funcion menu void menu(){ int option, dato; do{ cout<<"MENU"<<endl; cout<<"1_Enter List of Whole Numbers"<<endl; cout<<"2_List sum before the entered number"<<endl; cout<<"s_Exit"<<endl; cout<<"Option"<<endl; cin>>option; //option with switch case switch(option){ case 1: cout<<"Enter Number"<<endl; cin>>dato; ingresarLista(lista, dato); cout<<endl; system("pause"); break; case 2: cout<<"Search number"<<endl; cin>>dato; printList(lista); cout<<endl; searchList(lista, dato); cout<<endl; system("pause"); break; } system("cls"); }while(option != 's'); } //function menu void ingresarLista(Nodo *&lista, int n){ Nodo * nnodo = new Nodo(); nnodo->dato = n; Nodo *aux1 = lista; Nodo *aux2; while((aux1 != NULL)&&(aux1->dato < n)){ aux2 = aux1; aux1 = aux1->next; } if(lista == aux1){ lista = nnodo; } else{ aux2->next = nnodo; } nnodo->next = aux1; cout<<"Inserted"<<n<<"Successfully"; } //print void printList(Nodo *lista){ Nodo *actual = new Nodo(); actual = lista; while(actual != NULL){ cout<<actual->dato<<">>"; actual= actual->next; } } //sum and search number void searchList(Nodo *lista, int n){ bool band = false;// bandera int b=0; //se inicializa a 0 Nodo *actual = new Nodo(); actual = lista; while(actual != NULL){ if(actual->dato == n){ band = true; } actual = actual->next; b=b+lista->dato; lista=lista->next; } if(band == true){ cout<<"The number " <<n<<" Exist"<<endl; cout<<"Sum "<<b<<" before the last node"<<endl; system("PAUSE"); } else{ cout<<"The number "<<n<<" does not exist"<<endl; cout<<"Can not be added "<<b<<endl; } } int main(int argc, char** argv) { menu();//funcion menu system("PAUSE"); return 0; } A: You never set your flag variable band to be true. If you change: if(actual->dato == n){ band = false; } to if(actual->dato == n){ band = true; } and also: if(band == false){ cout<<"The number " <<n<<" Exist"<<endl; cout<<"Sum "<<b<<" before the last node"<<endl; system("PAUSE"); } else{ cout<<"The number "<<n<<" does not exist"<<endl; cout<<"Can not be added "<<b<<endl; } to if(band == true){ cout<<"The number " <<n<<" Exist"<<endl; cout<<"Sum "<<b<<" before the last node"<<endl; system("PAUSE"); } else{ cout<<"The number "<<n<<" does not exist"<<endl; cout<<"Can not be added "<<b<<endl; } it should solve your problem. With these changes band starts off as false, gets set to true only if a match is found and the message printed depends on the value of band. In response to your comment, I missed this other bug. In the search routine the while condition needs to be changed from: while((actual != NULL)&&(actual->dato<n)) to: while(actual != NULL) otherwise it will never find a match. I suspect you copied and pasted the condition from the insertion logic and forgot to remove the additional condition. (Both terms are needed in the insert function).
doc_23533363
I run on the x86 platform and have 12 threads to read and write. Now I want to figure out what caused the situation, and I want to know if this is a thread-safe design or where it needs to continue to be optimized for higher performance. 12 threads to dequeue and 12 threads to enqueue. Development tools : Visual studio 2019 I am very much looking forward to your reply. thank u. #include <iostream> #include <functional> #include<atomic> #include<cassert> #include<thread> #include<vector> template<typename T> class mpmc_queue_t { public: mpmc_queue_t(size_t size) : _size(size), _mask(_size - 1), _buffer((node_t*)(new aligned_node_t[_size])) { assert((_size != 0) && ((_size & (~_size + 1)) == _size)); _read.store(0, std::memory_order_relaxed); _write.store(0, std::memory_order_relaxed); for (size_t i = 0; i < _size; ++i) { _buffer[i].status.store(false, std::memory_order_relaxed); } } ~mpmc_queue_t() { delete[] _buffer; } bool enqueue(const T& data) { auto write = _write.fetch_add(1, std::memory_order_relaxed); node_t* node = &_buffer[write & _mask]; while (true) { if (!node->status.load(std::memory_order_acquire)) { node->data = data; node->status.store(true, std::memory_order_release); return true; } std::this_thread::yield(); } } bool dequeue(T& data) { auto read = _read.fetch_add(1, std::memory_order_relaxed); node_t* node = &_buffer[read & _mask]; while (true) { if (node->status.load(std::memory_order_acquire)) { data = node->data; node->status.store(false, std::memory_order_release); return true; } std::this_thread::yield(); } } private: struct node_t { T data; std::atomic_bool status; }; typedef typename std::aligned_storage<sizeof(node_t), std::alignment_of<node_t>::value>::type aligned_node_t; typedef char cache_line_pad_t[64]; cache_line_pad_t _pad0; size_t _size; size_t _mask; node_t* const _buffer; cache_line_pad_t _pad1; std::atomic_size_t _read; cache_line_pad_t _pad2; std::atomic_size_t _write; cache_line_pad_t _pad3; }; #define COUNT 100000000 #define THREAD 12 typedef mpmc_queue_t<size_t> queue_t; template<typename T> void consumer_func(T* queue) { size_t count = COUNT; size_t value = 0; while (count > 0) { if (queue->dequeue(value)) { --count; } } std::cout << "consumer_func ID: " << std::this_thread::get_id() << " ok" << std::endl; } template<typename T> void producer_func(T* queue) { size_t count = COUNT; while (count > 0) { if (queue->enqueue(count)) { --count; } } std::cout << "producer_func ID: " << std::this_thread::get_id() << " ok" << std::endl; } template<typename T> long double run_test( T producer_func, T consumer_func) { typedef std::chrono::high_resolution_clock clock_t; typedef std::chrono::time_point<clock_t> time_t; time_t start; time_t end; start = clock_t::now(); std::thread producer0(producer_func); std::thread producer1(producer_func); std::thread producer2(producer_func); std::thread producer3(producer_func); std::thread producer4(producer_func); std::thread producer5(producer_func); std::thread producer6(producer_func); std::thread producer7(producer_func); std::thread producer8(producer_func); std::thread producer9(producer_func); std::thread producer10(producer_func); std::thread producer11(producer_func); std::thread consumer0(consumer_func); std::thread consumer1(consumer_func); std::thread consumer2(consumer_func); std::thread consumer3(consumer_func); std::thread consumer4(consumer_func); std::thread consumer5(consumer_func); std::thread consumer6(consumer_func); std::thread consumer7(consumer_func); std::thread consumer8(consumer_func); std::thread consumer9(consumer_func); std::thread consumer10(consumer_func); std::thread consumer11(consumer_func); producer0.join(); producer1.join(); producer2.join(); producer3.join(); producer4.join(); producer5.join(); producer6.join(); producer7.join(); producer8.join(); producer9.join(); producer10.join(); producer11.join(); consumer0.join(); consumer1.join(); consumer2.join(); consumer3.join(); consumer4.join(); consumer5.join(); consumer6.join(); consumer7.join(); consumer8.join(); consumer9.join(); consumer10.join(); consumer11.join(); end = clock_t::now(); return (end - start).count() * ((double)std::chrono::high_resolution_clock::period::num / std::chrono::high_resolution_clock::period::den); } int main() { { queue_t queue(65536); long double seconds = run_test(std::bind(&producer_func<queue_t>, &queue), std::bind(&consumer_func<queue_t>, &queue)); std::cout << "The control group completed " << COUNT * THREAD << " iterations in " << seconds << " seconds. " << ((long double)COUNT * THREAD / seconds) / 1000000 << " million enqueue/dequeue pairs per second." << std::endl; } return 0; } A: This design is not lock-free but "lock-less", because a thread in dequeue may have to wait for an enqueue operation on that item to finish (signaled via status), i.e., it does not provide the progress guarantee required by lock-freedom. As Matt Timmermans already pointed out, there is a problem when indexes wrap around. There is not guarantee that the status of the node has already been updated, or, since the operations on status are not sequentially consistent, whether this update is visible. This can result in a data race when, after a wrap around, two threads (in different rounds) try to push to the same node, because both observed node->status.load() returning false. To solve this, you can use a counter instead of a bool in the node to track the current round the node belongs to (similar to how it's done in this queue by Dmitry Vukov: http://www.1024cores.net/home/lock-free-algorithms/queues/bounded-mpmc-queue)
doc_23533364
Error:Execution failed for task ':app:dexDebug'. > com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_25\bin\java.exe'' finished with non-zero exit value 1 A: If you have support-v4 and support-v7 (with different version) in build.gradle then add this line into your build.gradle at top. configurations { all*.exclude group: 'com.android.support', module: 'support-v4' } Also read this A: in my case, the compile 'com.google.android.gms:play-services:+' in my build.gradle exceeded the 65k method limit. i changed it to compile 'com.google.android.gms:play-services-maps:6.5.87' to fix it (i only need maps in my application) hope that helps A: I got this error today out of nothing, after that i tried to update every single thing available, tried to change my gradle build as suggested here but none of it worked. After hours of dispair and AS updates, a simple "clean project" and "rebuild project" worked for me. A: Just rebuilding project fixes the issue (Build->Rebuild Project). You can also clean project A: Do this it really help me! configurations { all*.exclude group: 'com.android.support', module: 'support-v4' } write this inside gradle module. Hope it help! A: I fixed that adding: compile ('com.facebook.android:facebook-android-sdk:3.22.0@aar'){ exclude module: 'support-v4' } A: Remove google analytics V2 helps for me A: Try this : dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.1.1' }
doc_23533365
in Controller: $this->authorize('modifyTournamentRegistration', $player); in Policy: public function modifyTournamentRegistration(User $user, User $player) { return $user->id === $player->id || $user->inRole('admin'); } A: I found out that it is because of Input variable type in Policy. I added User class in AuthServiceProvider: protected $policies = [ 'App\Model' => 'App\Policies\ModelPolicy', User::class => UserPolicy::class, ]; Then, I defined the function in UserPolicy: public function modifyPlayerTournamentRegistration(User $user, User $player) { return $player->id === $user->id || $user->inRole('admin'); } And used it in Controller: $this->authorize('modifyTournamentRegistration', $player); It works as well :)
doc_23533366
brew install git I do this: which git which returns: /usr/local/bin/git I then do this: file /usr/local/bin/git which returns: /usr/local/bin/git: Mach-O executable i386 I need brew to install as x86_64. How can I force brew to build and install my apps as x86_64? brew --config Returns this: HOMEBREW_VERSION: 0.9 HEAD: 1c64a6624ed83ef17af6e98638b8165400e9e908 HOMEBREW_PREFIX: /usr/local HOMEBREW_CELLAR: /usr/local/Cellar CPU: quad-core 64-bit sandybridge OS X: 10.7.4 Kernel Architecture: x86_64 Xcode: 4.3.2 GCC-4.0: N/A GCC-4.2: N/A LLVM: build 2336 Clang: 3.1 build 318 MacPorts or Fink? false X11: /usr/X11 System Ruby: 1.8.7-357 Which Perl: /usr/bin/perl Which Python: /usr/bin/python Which Ruby: /Users/tdewell/.rvm/rubies/ruby-1.9.3-p194/bin/ruby Update: adding brew --env $ brew --env CC: /usr/bin/xcrun gcc-4.2 => /Developer/usr/bin/gcc-4.2 CXX: /usr/bin/xcrun g++-4.2 => /Developer/usr/bin/g++-4.2 LD: /usr/bin/xcrun gcc-4.2 => /Developer/usr/bin/gcc-4.2 CFLAGS: -Os -w -pipe -march=core2 -msse4 CXXFLAGS: -Os -w -pipe -march=core2 -msse4 MAKEFLAGS: -j4 A: This has been solved. I installed Xcode 4.3.2 via the App Store and installed the Command Line Tools, but I had an existing Xcode 3.1 installed from years ago. I Googled around and found these commands: sudo /Developer/Library/uninstall-devtools –mode=all sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer That cured my problem and after I did that the compilers changed for brew: $ brew --env CC: /usr/bin/clang CXX: /usr/bin/clang++ => /usr/bin/clang LD: /usr/bin/clang CFLAGS: -Os -w -pipe -march=native -Qunused-arguments CXXFLAGS: -Os -w -pipe -march=native -Qunused-arguments MAKEFLAGS: -j4 brew installs are much better now: $ which git /usr/local/bin/git $ file /usr/local/bin/git /usr/local/bin/git: Mach-O 64-bit executable x86_64 A: Try with xcode-select --install
doc_23533367
That's my code: private static void test(String src, String pwd, String dest) throws Exception { byte[] pwdByte = pwd != null ? pwd.getBytes() : null; PdfReader r = null; PdfStamper stp = null; FileOutputStream fos = null; try { r = new PdfReader(src, pwdByte); fos = new FileOutputStream(dest); stp = new PdfStamper(r, fos, '\0', true); } finally { stp.close(); fos.close(); r.close(); } } If i call test, the resulting pdf increases the size depending on the signed info: * *My initial pdf has a LTV sign but i need to add a timestamp. I need to addLtv() some pdfs and later addLtvNoTs() because it's a different TSA. This makes calling twice PdfReader in mode append and every time i do it increases my pdf in 190kb aprox. That means increasing it 380kb. http://developers.itextpdf.com/question/how-enable-ltv-timestamp-signature *I've tested calling above test method with a pdf with a simple sing and every time i call test() on the resulting pdf it increase 3,5kb each time (i think due to small sign info). Why pdfstamper increase my pdf size if it's signed even i don't add any change? How can i avoid it? 390kb it's a problem because i need to resign thousand of pdfs and store them. I'm using itext 5.5.9 Thanks in advance! A: This is a strange question because it reveals that you don't understand the concept of a digital signature. When you sign a PDF, you want to make sure that the signature breaks as soon as someone changes a single byte. Every time you sign a document, you protect the bytes of the previous revision of the document by adding a signature dictionary of which the contents contain a signed hash of at least the bytes you want to protect. See the following figure that shows a schema of a PDF that is signed three times: Suppose that you would want to add a fourth signature, and you would want the resulting file to have the same size as before, you would have to change some of the bytes in the existing document. That would break at least one of the existing signatures. You mention LTV. LTV implies adding a Document Security Store (DSS) and a Timestamp signature. The same rules apply: you have to add extra bytes, because the moment you change existing bytes, you'll break an existing signature: Every time the certificate of the latest timestamp signature expires, you have to repeat the same procedure: The total file size will always increase.
doc_23533368
Firstly, although the icon I am using is a .png with a transparent background the icon has an ugly white background. Second, the Icon has a right click menu with the options "Show" and "Close" however for unknown reasons both say "Ctrl - Q" next to them. Not only did I not specify this, but the hotkey combo does nothing. Here is the code I am using. It's almost directly lifted from the documentation: class SysTray(wx.TaskBarIcon): def __init__(self, parent, icon, text): wx.TaskBarIcon.__init__(self) self.parentApp = parent self.SetIcon(icon, text) self.CreateMenu() def CreateMenu(self): self.Bind(wx.EVT_TASKBAR_RIGHT_UP, self.ShowMenu) self.menu=wx.Menu() self.menu.Append(wx.ID_OPEN, "Show") self.menu.Append(wx.ID_EXIT, "Close") def ShowMenu(self,event): self.PopupMenu(self.menu) Which is implemented using: self.trayicon = SysTray(self, wx.Icon(TRAY_ICON, wx.BITMAP_TYPE_PNG), TRAY_TOOLTIP) self.trayicon.Bind(wx.EVT_MENU, self.OnExit, id=wx.ID_EXIT) self.trayicon.Bind(wx.EVT_MENU, self.OnShow, id=wx.ID_OPEN) A: wxPython uses something called an AcceleratorTable for keeping track of "hotkeys" or "shortcuts" or whatever you'd like to call them. Similar to the way you can define and set a sizer, you can define and set an AcceleratorTable and wxPython will use it. More on that here http://www.blog.pythonlibrary.org/2010/12/02/wxpython-keyboard-shortcuts-accelerators/ Also, in order to get the Ctrl-Q or Ctrl-O hotkeys you need to either specify them in the text or add them to the accelerator table. If you add the properly formatted text to the menu items, wxPython should recognize "this is a hotkey" and add it to the accelerator table for you automatically. self.menu.Append(wx.ID_OPEN, "Show\tCtrl+O") self.menu.Append(wx.ID_EXIT, "Close\tCtrl+Q")
doc_23533369
And I want to export report to PDF, but my report will not support languages different then English (other languages fields appear as blank), This is my code for generating the report JsonDataSource ds = new JsonDataSource(JRLoader.getInputStream(jsonFile)); JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperFile); parameters.put(JRParameter.REPORT_FILE_RESOLVER, new SimpleFileResolver(new File(reportDirPath))); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, ds); JasperExportManager.exportReportToPdfFile(jasperPrint, outputFilePath); I created a Font Extension using this tutorial: "http://community.jaspersoft.com/wiki/custom-font-font-extension" I export to jar file and add to my project class path, but all fields that are not in English are Still blank peter comment with this link was very helpful, it help me realize if my font is supporting the desire language in the first place A: The problem here was that font (ttf) did not support the language (tested using this How can I test if my font is rendered correctly in pdf?) so problem similar to How can I render hindi correctly when exporting to pdf?) Solution: Find a font that support the language(s) and use font-extension. For how to switch font between languages see this follow up question: Jasper report, load multiple Font Extension //Community wiki since I would preferred duplicated but difficult in low-traffic tag
doc_23533370
private void backButtonMouseClicked(java.awt.event.MouseEvent evt) { do stuff } is there some way to virtually use this method from another method without clicking the mouse on the button? A: Or you can just use button.doClick(); A: Yes, MouseEvent has public constructors, so you simply create one, and call the function with it. A: I believe you can say backButtonMouseClicked(new MouseEvent()) to call the method. Or maybe backButtonMouseClicked(null).
doc_23533371
composer remove barryvdh/laravel-debugbar It gives me this error: After that, I can't use the artisan command anymore. PHP just can't find the artisan command! I've tried with installing packages again composer install Here is the Macroable.php file public function __call($method, $parameters) { if (! static::hasMacro($method)) { throw new BadMethodCallException("Method {$method} does not exist."); } $macro = static::$macros[$method]; if ($macro instanceof Closure) { return call_user_func_array($macro->bindTo($this, static::class), $parameters); } return call_user_func_array($macro, $parameters); } It gives this error Prograbbly composer tries to execute "php artisan package:discover" where composer can't find the Artisan command. If anybody faced similar problem please help me out. Thanks A: The problem is that one of the service providers, either your own or one of the packages you've installed is making reference to the method as in the Macroable trait. Try running php artisan package:discover --vvv. That will give you a stack trace and you can find the offending code. A: I don't know What I've done but this problem fixed by removing a duplicate route!
doc_23533372
string[] capturetime = record.Time.Split(':'); string captime = capturetime[0] + ":" + capturetime[1] + ":" + capturetime[2] + "." + capturetime[3]; DateTime rightTime = Convert.ToDateTime(captime); After the second line run the value of captime is "11/01/2012 11:38:01.296" Error appear at the last line : "Index and length must refer to a location within the string. Parameter name: lengthmscorlib" I dont understand why. Because it run fine before :( Anyone can explain this ? tks so much Solved, tks everybody so much :) Code : string[] capturetime = newRecord.Time.Split(':'); string captime = capturetime[0] + ":" + capturetime[1] + ":" + capturetime [2] + "." + capturetime[3]; DateTime righttime; if(time[3].Length == 2) { righttime = DateTime.ParseExact(captime, "MM/dd/yyyy hh:mm:ss.ff", CultureInfo.InvariantCulture); } else { righttime = DateTime.ParseExact(captime, "MM/dd/yyyy hh:mm:ss.fff", CultureInfo.InvariantCulture); } So any idea for optimizing those code ???? Update : Is it me or my Visual Studio is Crazy??? The new code above got exception like the old code and when i changed back to the old code. It work fine like the old day ..wth is this :( A: You can use string dateString = "11/01/2012 11:38:01:296"; DateTime date = DateTime.ParseExact(dateString , "MM/dd/yyyy hh:mm:ss:fff", CultureInfo.InvariantCulture); A: If you look closely, the time you have given, doesn't have the last COLON. As per normal standards, It would be a dot. Check RecordTime value properly. "11/01/2012 11:38:01:296" is wrong "11/01/2012 11:38:01.296" is correct Hence making the indices of captureTime wrong. It would be, 0, 1 and 2. 3 would be out of bounds. A: just use DateTime.ParseExact(val, "MM/dd/yyyy HH:mm:ss:fff", new DateTimeFormatInfo()) without doing all the string splitting. A: I believe the best way to solve this is by using the CultureInfo/DateTimeFormat strings. However, if that's not applicable for you for some strange reason, here is a crude way of doing this. string val = @"11/01/2012 11:38:01:296"; string[] parts = val.Split(' '); var dt = DateTime.ParseExact(parts[0], "dd/MM/yyyy", new DateTimeFormatInfo()); double[] times = parts[1].Trim().Split(':').Select(s => double.Parse(s)).ToArray(); dt = dt.AddHours(times[0]); dt = dt.AddMinutes(times[1]); dt = dt.AddSeconds(times[2]); dt = dt.AddMilliseconds(times[3]); // OR -- dt.AddMilliseconds(times[0] * 60 * 60 * 1000 + times[1] * 60 * 1000 + times[2] * 1000 + times[3]);
doc_23533373
A: I have found the solution... I probably set that 300px width screen should be media query min-width, then I rendered it into the iframe and viewed in a 320px width screen and the iframe in the 320px screen was resized to 90% which made it less than 300px screen and the style did not apply.
doc_23533374
def nameProjectWindow(): tkWindow = Tk(className = 'Export Project') tkWindow.geometry("500x500") fileNameLabel = Label(tkWindow, text="File Name").grid(row=0, column=0) fileNameVar = StringVar() fileNameEntry = Entry(tkWindow, textvariable=fileNameVar).grid(row=0, column=1) save_btn = ttk.Button(tkWindow, text = 'Save File!', command = lambda : SaveFile()) save_btn.pack(side = TOP, pady = 20,padx = 50) def SaveFile(): data = [('All tyes(*.*)', '*.*')] file = asksaveasfile(filetypes = data, defaultextension = data) I think my save file function is good, but I'm having trouble creating a save button. When I'm at the name project window there's no save project button. Edit Here's the window:
doc_23533375
Text covers the after space correctly but when it goes to second column some space from the top till where the image ends on the first column is blank and starts after that. if ($this->myResetColumn) { $this->resetColumns(); $this->setEqualColumns($this->myCols, $this->myWidth); $this->setXY($this->GetX(), $this->GetY()); $this->selectColumn(); } $this->writeHTML($content, true, false, true, false, $align); Second Question It there a way, I can make few checks while the writeHTML() function is executing or I have to change the function itself, which will not be a good idea to change the source code. For AddPage, I override it, after the line at the end like this $this->startPage($orientation, $format, $tocpage); if (condition) { // some function call } but writeHTML() is a lengthy function to override and it will lose many options it has.
doc_23533376
I was working with 3.0.0, upgraded to 3.0.3 and receive this message when launching a new local database. "Starting Neo4j failed: Component 'org.neo4j.server.database.LifecycleManagingDatabase@bfdf32a' was successfully initialized, but failed to start. Please see attached cause exception. " I uninstalled both, deleted .neo4j file and reinstalled 3.0.3 -> same Any idea what to do? Best
doc_23533377
The overlay work for iOS but not available on android. Is there a way to extend the package and to have android working? I also found a site helping me to create a camera : https://thatcsharpguy.com/post/full-camera-page.1/ This works fine on iOS, possibly on android (haven't not tried). This document uses the old Camera api not Camera2 api to create the camera, so I can't use this. I would prefer to use latest Camera api.
doc_23533378
Example: Column1----Column2 value_1----5678976 value_2----7263535 value_1----1938773 value_2----3333445 value_3----2848465 So at the report header, i need to specify all distinctive values from Column1, comma separated. From mentioned example correct string will be: value_1,value_2,value_3 I tried to use formula WhilePrintingRecords; shared stringvar final_result; shared stringvar current_value; if len(final_result) = 0 then final_result = ""; current_value:= {Column1}; final_result := final_result+ "," + current_value; This is doesn't work Tried different one WhilePrintingRecords; stringVar final_result := ""; final_result = final_result + ( if InStr(final_result, {Column1}) > 0 then "" else final_result := "," + {Column1}; ); Also no result. Where did i go wrong? Thanks A: In order to make the formula show anything, you will need to call the values after you declare them. So your formula should look more like this: WhilePrintingRecords; shared stringvar final_result; shared stringvar current_value := {Column1}; if len(final_result) < 1 then final_result := {Column2}; final_result + ", " + current_value The problem is that you will only get one record since the formula is in the Report Header. The same would happen if you created an array and tried to display it in the report header. I think your best bet would be to create a subreport that you then display in the report header. Cheers, Chris EDIT: This took me a while but I think I finally got it. The key is the difference between WhileReadingRecords and WhilePrintingRecords. You need to fill the first formula while reading the records, that will ensure that when you actually go to display the data (WhilePrintingRecords), the formula in the Header has something in it to display. So here it goes: Formula 1 (place in Detail section): WhileReadingRecords; stringvar array a; numbervar i; if not({Column1} in a) then ( i := i + 1; redim preserve a[i]; a[i] := {Column1}; ); a[i] Formula 2 (place in Report Header): WhilePrintingRecords; stringvar array a; stringvar fin; numbervar j; for j := 1 to ubound(a) do ( fin := fin + a[j] + ", "; ) fin Hope this works now. -Chris A: Just a minor syntax error in Chris' second formula. The semicolon should be moved down a line, after the closing parenthesis of the FOR loop, so the last three lines would be: fin := fin + a[j] + ", " ); fin
doc_23533379
Basically having two matrices Am1, k and Bm2, k I need to get a matrix Cm1, m2. I can easily do this in scipy by using distance.sdist and select one of many distance metrics, and I also can do this in TF in a loop, but I can't figure out how to do this with matrix manipulations even for Eucledian distance. A: After a few hours I finally found how to do this in Tensorflow. My solution works only for Eucledian distance and is pretty verbose. I also do not have a mathematical proof (just a lot of handwaving, which I hope to make more rigorous): import tensorflow as tf import numpy as np from scipy.spatial.distance import cdist M1, M2, K = 3, 4, 2 # Scipy calculation a = np.random.rand(M1, K).astype(np.float32) b = np.random.rand(M2, K).astype(np.float32) print cdist(a, b, 'euclidean'), '\n' # TF calculation A = tf.Variable(a) B = tf.Variable(b) p1 = tf.matmul( tf.expand_dims(tf.reduce_sum(tf.square(A), 1), 1), tf.ones(shape=(1, M2)) ) p2 = tf.transpose(tf.matmul( tf.reshape(tf.reduce_sum(tf.square(B), 1), shape=[-1, 1]), tf.ones(shape=(M1, 1)), transpose_b=True )) res = tf.sqrt(tf.add(p1, p2) - 2 * tf.matmul(A, B, transpose_b=True)) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print sess.run(res) A: This will do it for tensors of arbitrary dimensionality (i.e. containing (..., N, d) vectors). Note that it isn't between collections (i.e. not like scipy.spatial.distance.cdist) it's instead within a single batch of vectors (i.e. like scipy.spatial.distance.pdist) import tensorflow as tf import string def pdist(arr): """Pairwise Euclidean distances between vectors contained at the back of tensors. Uses expansion: (x - y)^T (x - y) = x^Tx - 2x^Ty + y^Ty :param arr: (..., N, d) tensor :returns: (..., N, N) tensor of pairwise distances between vectors in the second-to-last dim. :rtype: tf.Tensor """ shape = tuple(arr.get_shape().as_list()) rank_ = len(shape) N, d = shape[-2:] # Build a prefix from the array without the indices we'll use later. pref = string.ascii_lowercase[:rank_ - 2] # Outer product of points (..., N, N) xxT = tf.einsum('{0}ni,{0}mi->{0}nm'.format(pref), arr, arr) # Inner product of points. (..., N) xTx = tf.einsum('{0}ni,{0}ni->{0}n'.format(pref), arr, arr) # (..., N, N) inner products tiled. xTx_tile = tf.tile(xTx[..., None], (1,) * (rank_ - 1) + (N,)) # Build the permuter. (sigh, no tf.swapaxes yet) permute = list(range(rank_)) permute[-2], permute[-1] = permute[-1], permute[-2] # dists = (x^Tx - 2x^Ty + y^Tx)^(1/2). Note the axis swapping is necessary to 'pair' x^Tx and y^Ty return tf.sqrt(xTx_tile - 2 * xxT + tf.transpose(xTx_tile, permute))
doc_23533380
I was thinking do it with a FOR, but my code didnΒ΄t work. For example: if we have this array "123456789" the value will be 2 and index = 1 and this numbers save it in a integer. I'm programming in ANSI C. #include <stdio.h> #include <stdlib.h> void main() { int a = 0, i = 0, indice, numero[20], vuelta, quedan, x; int cadenaNumeros[20000]; int num, num2; printf("\n\nEscribe el numero de palancas: "); scanf("%d", &num2); printf("\n\nEscriba el numero de la palanca roja: "); scanf("%d", &num); printf("\n\nIntroduzca una cadena de numeros: "); scanf("%d", &cadenaNumeros); for(i = 0; cadenaNumeros[i] < num2; i++); { cadenaNumeros[0] == numero[x]; printf("%d", numero[x]); } system("PAUSE"); return 0; } A: int index = -1, i = 0; // Assuming num2 is the number you're searching for // And the array size is 20000 for( ; i < 20000; i++) { if( cadenaNumeros[i] == num2) { index = i; break; } } if( index != -1) { printf( "Found %d at index %d\n", num2, index); } else { printf( "Number not found\n"); }
doc_23533381
The client only works again when I kill the process and restart it again. A: Your problem might be related to this issue: https://github.com/restlet/restlet-framework-java/issues/669#issuecomment-9455618 A: Solved the problem it was because I was not starting and stopping the client after each web service request.
doc_23533382
A: No, it is about a lot more, especially with more sophisticated obfuscators. They can produce IL that cannot be expressed in most languages, and where the logic flow is horribly tangled to befuddle the best of tools. With lots of time you can do it (probably lots by hand), and there is certainly an arms race between the obfuscators and deobfuscators - but you vastly underestimate the technology here. Also, note that many obfuscators look at an entire application (not just one assembly), so they can change the public API too. A: That is certainly the start of an obfuscator. Though some obfuscators will also encrypt strings and other such tricks to make it very difficult to reverse engineer the assembly. Of course, since the runtime needs to run the assembly after all of this, it is possible for a determined hacker to reverse engineer it :) A: There are 'deobfuscator' tools to undo several obfuscation techniques like Decrypt strings, Remove proxy methods, Devirtualize virtualized code, Remove anti-debug code, Remove junk classes, Restore the types of method parameters and fields and more... One very powerful tool is de4dot. But there are more. A: Obfuscation is about changing meaningful names like accountBalance to meaningless ones like a1. The application will obviously still work, but it will be more difficult to understand the algorithms inside it. A: It's depend upon the obfuscation technology used. Obsfucating variable name is only one part of the issue. A lot of obfuscation tools perform some kind of program flow obfuscation at the same time, which will complicate further code comprehension. At the end, the obfuscated IL won't be expressible easily (if at all) in most programming languages. Renaming the variables and fields won't help you much either, as having a lot of variable1, variable2.. won't help you to understand what you read.
doc_23533383
After payment, the user is redirected to a payment success page on my server. Will the session variable still be valid? A: The above answers are true if you are storing sessions using cookies. If cookies are disabled then a PHP_SESSION parameter will be passed in the URL. For the returning user to be able to continue using the session the payment gateway would need to redirect back with the same session hash. As stated if you are using the default PHP session settings then cookies should be in use and this would not be an issue. What about the users whom may have cookies disabled, your flow will break. Chances are slim and the amount of users effected may be small.
doc_23533384
public class Box<Item> { ... } public class Toolbox extends Box<Tool>{ ... } Given that Toolbox extends Box providing a Tool as the actual type for the generic placeholder, I would have thought it should be possible to do something like this: Box<Tool> box = new Box(); Toolbox toolbox = box; However, it seems this causes a type-mismatch. Why is this? A: It's not really a generics issue. Your problem is that you're assigning an object of a less specific type to a variable of a more specific type. You'd have the same problem if you tried to assign an Object to a String variable, even though String extends Object. You should, however, be able to write Box<Tool> box = new Toolbox(); with the class structure given. Just not the other way around. A: Box<Item> is the unbound generic type. Box<Tool> is a particular bound version of that same generic type. Toolbox is a subclass of Box<Tool> and thus is a discrete type from Box<Tool>.
doc_23533385
I am using 95% of titlewidth with logo in center using below code. But, this pushes navigation bar with toggle button on right 5% screen. **How can I switch navigation bar to be on left (as shown in picuture) and title bar with logo in center? ** dashboardHeader(title = tags$a(tags$img(src='Logo.png', height=80)), titleWidth = "95%") Any suggestions will be appreciated. Thanks, Krina A: There's probably a better way, but here's a hacky option: * *Conceal the logo as a dropdownMenu *Move logo to the center of the header using css *(Optional) Remove the css hover effect from the logo Other dropdownMenus remain right-aligned. library(shiny) library(shinydashboard) css <- HTML( "/* move logo to center */ #logo { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); } /* remove hover effect */ #logo > a:hover { background-color: transparent !important; color: transparent !important; }" ) ui <- dashboardPage( dashboardHeader(title = "Project Title", tags$li(class = "dropdown", id = "logo", tags$a(tags$img(height = "20px", src="https://www.r-project.org/logo/Rlogo.png") ), tags$style(css) ), dropdownMenu(type = "messages", badgeStatus = "primary", taskItem(value = 20, "Example" )) ), dashboardSidebar(), dashboardBody() ) server <- function(input, output, session) { } shinyApp(ui, server)
doc_23533386
I am using MATLAB's .NET functionality to create a Word document. I'd like to create a table and merge the top two cells in the lefthand column. So far I can create the table: NET.addAssembly('microsoft.office.interop.word'); %# Register Word assembly wordApp = Microsoft.Office.Interop.Word.ApplicationClass; %# Create an instance of Word wordDoc = wordApp.Documents; %# Get the object that handles documents newDoc = wordDoc.Add; %# Add a new document wordApp.Visible = 1; %# Make Word visible selection = wordApp.Selection; %# Get the selection object to manage selected area table = newDoc.Tables.Add(selection.Range, 3, 5); %# Create a table table.Style = 'Table Grid'; %# Add grid lines I'm having trouble calling the selection.MoveDown method. Running METHODSVIEW on this method indicates the following input parameters: * *Microsoft.Office.Word.Selection this *System.Object Unit *System.Object Count *System.Object Extend The Selection.MoveDown documentation on MSDN suggests that the Unit parameter is a WdUnits enumeration which I found in MATLAB at Microsoft.Office.Interop.Word.WdUnits.wdCell. My problem is that I can't find the WdMovementType enumeration needed by the Extend parameter. I want to use the wdExtend value but I can't find it. According to MSDN it should be at Microsoft.Office.Interop.Word.WdMovementType. Can anyone tell me where to find wdExtend? EDIT WdMovementType does in fact live where it's supposed to, i.e. Microsoft.Office.Interop.Word.WdMovementType. Now I'm getting an error when trying to run the MoveDown method: >> selection.MoveDown(Microsoft.Office.Interop.Word.WdUnits.wdCell, 1, Microsoft.Office.Interop.Word.WdMovementType.wdExtend); ??? Message: Bad parameter Source: Microsoft Word HelpLink: C:\Program Files (x86)\Microsoft Office\Office12\1033\WDMAIN11.CHM#36888 Any idea how to call this method properly? EDIT The call to MoveDown should use the wdLine value for the units: >> selection.MoveDown(Microsoft.Office.Interop.Word.WdUnits.wdLine, 1, Microsoft.Office.Interop.Word.WdMovementType.wdExtend); A: I used the following to check the enumerations in the Word assembly: >> word = NET.addAssembly('microsoft.office.interop.word'); >> word.Enums The results included: 'Microsoft.Office.Interop.Word.WdMovementType' so I thought I'd try accessing it even though it wasn't appearing in MATLAB's tab completion. Strangely enough, after accessing it once it now appears! I guess it was there all along. A: I suggest you to download the latest one assembly for the Word 2010. You can download them from microsoft.com How to: Install Office Primary Interop Assemblies
doc_23533387
.pointy { background-image: url('img/Header.png'); background-size: cover; background-repeat: no-repeat; color: white; font-size: 40px; background-color: orange; } <div style="margin-top: 100px"> <table style="float: left;"> <tr class="pointy"> <td>TITLE</td> </tr> </table> <table style="float: left;"> <tr class="pointy"> <td>TITLE</td> </tr> </table> <table style="float: left;"> <tr class="pointy"> <td>TITLE</td> </tr> </table> </div> I am trying to add the image as a background and achieve the design as in the image below. My Design But sadly I couldn't get it work. This is my result right now. Actual Result P.S Orange background is added just to see it clearly. A: Your background is bigger than the cell. To center the background image, you have to add background-position:center to class .pointy. See the following example: .pointy { background-image: url('http://placehold.it/200x40'); background-size: cover; background-repeat: no-repeat; background-position:center; color: white; font-size: 25px; height:40px; background-color: orange; vertical-align:bottom; } <div style="margin-top: 100px"> <table style="float: left;"> <tr class="pointy"> <td>TITLE</td> </tr> </table> <table style="float: left;"> <tr class="pointy"> <td>TITLE</td> </tr> </table> <table style="float: left;"> <tr class="pointy"> <td>TITLE</td> </tr> </table> </div> You can optimize your table structure. So you can also use the following example: table { margin-top:100px; } thead th { background-image: url('http://placehold.it/200x40'); background-size: cover; background-repeat: no-repeat; background-position:center; color: white; font-size: 25px; height:40px; background-color: orange; vertical-align:bottom; } <table> <thead> <th>TITLE</th> <th>TITLE</th> <th>TITLE</th> </thead> <tbody> <tr> <td>CONTENT</td> <td>CONTENT</td> <td>CONTENT</td> </tr> </tbody> </table> A: Probably you need to add background-position:center; and change background-size: cover; to background-size: contain; or background-size: 100%; A: you should use background-position A: It seems the background is bigger than your cell. You can try using background-size as described here: https://developer.mozilla.org/en/docs/Web/CSS/background-size probably setting it to 'contain' will give you the closes result: contain A keyword that scales the image as large as possible and maintains image aspect ratio (image doesn't get squished). Image is letterboxed within the container. When the image and container have different dimensions, the empty areas (either top/bottom of left/right) are filled with the background-color. In general you need to make sure the cell dimensions (width/hight) match the image exactly. A: An alternative option would be to create the effect using only CSS... This is useful if you want animations or hover effects for example. .pointy { color: white; font-size: 40px; background-color: #000; } .pointy td { position: relative; } .pointy td::before { content: ''; position: absolute; top: -40px; left: 0; right: 0; margin: auto; width: 0; height: 20px; border-bottom: solid 20px #000; border-left: solid 20px transparent; border-right: solid 20px transparent; } <div style="margin-top: 100px"> <table style="float: left;"> <tr class="pointy"> <td>TITLE</td> </tr> </table> <table style="float: left;"> <tr class="pointy"> <td>TITLE</td> </tr> </table> <table style="float: left;"> <tr class="pointy"> <td>TITLE</td> </tr> </table> </div> A: Setting the background-position:center and adjust some padding of the td can do the trick. Here is the working code: table { width: 33%; } .pointy { background-image: url('https://i.stack.imgur.com/JQISJ.png'); background-size: contain; background-repeat: no-repeat; color: white; font-size: 20px; background-position: center; text-align: center; vertical-align: bottom; } .pointy td { padding: 18px 0 5px 0; } <div style="margin-top: 100px"> <table style="float: left;"> <tr class="pointy"> <td>TITLE</td> </tr> </table> <table style="float: left;"> <tr class="pointy"> <td>TITLE</td> </tr> </table> <table style="float: left;"> <tr class="pointy"> <td>TITLE</td> </tr> </table> </div> A: For infos, an example with a better use of html tags (hx or th ) or CSS displays (inline-block,flex or grid ) h2, th { font-size: 30px; } .ib {white-space:nowrap;}/* keep a single line*/ .ib h2 { display: inline-block; } table { border-spacing: 4px 0 } .flex { display: flex; } .flex h2 { margin: 0 2px; } .grid { display: grid; grid-template-columns: repeat(auto-fill, 235px); grid-gap: 4px; min-width:800px; } /* bg it is about background-size. image missing replaced with average gradient*/ .title { padding: 1.5em 3em 0.5em; color: white; background: linear-gradient(to bottom, transparent 1em, black 1em), linear-gradient(45deg, black 44%, transparent 45%) right top no-repeat, linear-gradient(-45deg, black 44%, transparent 45%) left top no-repeat; background-size: auto, 50% 100%, 50% 100%; } <h1>header + h2 inline-block; </h1> <header class="ib"> <h2 class="title">title</h2> <h2 class="title">title</h2> <h2 class="title">title</h2> </header> <h1>table header, th </h1> <table> <thead> <tr> <th class="title"> title</th> <th class="title"> title</th> <th class="title"> title</th> </tr> </thead> </table> <h1>header + h2 and flex </h1> <header class="flex"> <h2 class="title">title</h2> <h2 class="title">title</h2> <h2 class="title">title</h2> </header> <h1>header + h2 and grid </h1> <header class="grid"> <h2 class="title">title</h2> <h2 class="title">title</h2> <h2 class="title">title</h2> </header>
doc_23533388
Not only do I want to reduce it to two decimals, but if it's less I need to add a zero. I'm using .1 in my examples below. var base = .1; //desired result is 0.10 var total; // the x100/100 method total = (base * 100) / 100; console.log(total); //outputs 0.1 // the .toFixed method total = (base).toFixed(2); console.log(total + " (" + typeof total + ")"); //looks right, but it's a string // unary +() total = +((base).toFixed(2)); console.log(total); //outputs .1
doc_23533389
Possible Duplicate: Upload max size in PHP? upload_max_filesize = 500M post_max_size = 500M i make these 2 settings in php.ini and upload video less than 400MB but can't upload A: It's hard to understand your question, but those variables aren't the only ones needed for a successful file uploading. * *Check if your HTML <form> has the proper enctype set. *You have to add <input type="hidden" name="MAX_FILE_SIZE" value="512000" /> to your <form> too. This input field specifies the maximum uploadable file size in bytes.
doc_23533390
I ask it because of nos's comment here: Why kernel code/thread executing in interrupt context cannot sleep? Also, interrupts usually require very fast servicing, or you can easily get into all sorts of trouble. Which kind of troubles could be made? A: Have you ever had that your computer was busy working, for instance during startup, and you kept pressing keys, and after a while you just got a beep and those keys weren't registered/buffered anymore? That's an example of what can happen. If you don't handle the interrupt fast enough, the inflow may be larger than you can handle, and there is no room to queue more interrupts. Modern hardware and modern OS'es will not run into such limits as quickly as Ye Olde DOS machine, but that doesn't mean that their buffers are unlimited.
doc_23533391
I have tried, restitution, density and even velocity, but of them worked. Could someone please guide me in the right direction. Nothing I find on here or Google seems to work. Image of Spaceship without Shield: Image of Spaceship with Shield: Image of Spaceship with Shield and showPhysics = true: func activateShield() { let shield1 = SKTexture(imageNamed: "shield-1") let shieldImages = [shield1, SKTexture(imageNamed: "shield-2"), SKTexture(imageNamed: "shield-3"), SKTexture(imageNamed: "shield-4"), SKTexture(imageNamed: "shield-5"), SKTexture(imageNamed: "shield-6")] let animateShield = SKAction.animate(with: shieldImages, timePerFrame: 0.10) let animateRepeatShield = SKAction.repeatForever(animateShield) shield = SKSpriteNode(texture: shield1) shield.name = "ShieldActive" shield.setScale(2.5) shield.position = player.position shield.zPosition = 3 shield.physicsBody = SKPhysicsBody(rectangleOf: shield.size) shield.physicsBody!.affectedByGravity = false shield.physicsBody!.categoryBitMask = PhysicsCategories.ShieldActive shield.physicsBody!.collisionBitMask = PhysicsCategories.Enemy shield.physicsBody!.contactTestBitMask = PhysicsCategories.Enemy | PhysicsCategories.LifePu shield.physicsBody!.isDynamic = true shield.physicsBody!.density = 0 self.addChild(shield) shield.run(animateRepeatShield) let joint = SKPhysicsJointFixed.joint(withBodyA: player.physicsBody!, bodyB:shield.physicsBody!, anchor:player.position) self.physicsWorld.add(joint) //turns off the shield in between 5-10 seconds shield.run(.wait(forDuration: 10, withRange: 0)) { self.shield.removeFromParent() } } A: I solved this with the help of @Ron by removing the PhysicsJoint altogether and then adding the shield.position.x += amountDragged same way it was done for the Spaceship and it worked perfectly. override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { for touch: AnyObject in touches{ let pointOfTouch = touch.location(in: self) let previousPointOfTouch = touch.previousLocation(in: self) let amountDragged = pointOfTouch.x - previousPointOfTouch.x if currentGameState == gameState.inGame{ player.position.x += amountDragged shield.position.x += amountDragged } if player.position.x > gameArea.maxX - player.size.width/2{ player.position.x = gameArea.maxX - player.size.width/2 } if player.position.x < gameArea.minX + player.size.width/2{ player.position.x = gameArea.minX + player.size.width/2 } if shield.position.x > gameArea.maxX - player.size.width/2{ shield.position.x = gameArea.maxX - player.size.width/2 } if shield.position.x < gameArea.minX + player.size.width/2{ shield.position.x = gameArea.minX + player.size.width/2 } } }
doc_23533392
like on click: the development i want to get its id: 1, <ul> <li><a href="#first_slide" id="1">the development</a></li> <li><a href="#second_slide" id="2">the design</a></li> <li><a href="#third_slide" id="3">the locate</a></li> <li><a href="#fourth_slide" id="4">the layout</a></li> <li><a href="#fifth_slide" id="5">the team</a></li> <li><a href="#sixth_slide" id="6">contact</a></li> </ul> A: You can use this.id inside .click() handler of anchors: $('ul li a').click(function() { console.log(this.id); }); Fiddle Demo If you use .click() handler on <li> elements then you can use .find() along with .attr() or .prop(): $('ul li').click(function() { console.log($(this).find('a').prop('id')); }); Fiddle Demo A: you can use this $('a').click(function(){ console.log(this.id) })
doc_23533393
This is my app navbarPageWithText <- function(..., text) { navbar <- navbarPage(...) textEl <- tags$p(class = "navbar-text", text) navbar[[3]][[1]]$children[[1]] <- htmltools::tagAppendChild( navbar[[3]][[1]]$children[[1]], textEl) navbar } # Call this function with an input (such as `textInput("text", NULL, "Search")`) if you # want to add an input to the navbar navbarPageWithInputs <- function(..., inputs) { navbar <- navbarPage(...) form <- tags$form(class = "navbar-form", inputs) navbar[[3]][[1]]$children[[1]] <- htmltools::tagAppendChild( navbar[[3]][[1]]$children[[1]], form) navbar } library(shiny) library(DT) Patient_005=as.data.frame(read.table(text = " Driver SNV_Tumour_005 SNV_Organoid_005 INDEL_Tumour_005 INDEL_Organoid_005 Deletion_Organoid_005 ABCB1 * * * - - - ACVR1B * * - - - - ACVR2A * - - - - - ")) Patient_013=as.data.frame(read.table(text = " Driver SNV_Tumour_013 SNV_Organoid_013 INDEL_Tumour_013 INDEL_Organoid_013 Deletion_Tumour_013 Deletion_Organoid_013 ABCB1 * - * - - - - ACVR1B * - - - - - - ACVR2A * - - - - - - ")) Patient_036 = as.data.frame(read.table(text = " Driver SNV_Organoid_036 INDEL_Organoid_036 Deletion_Organoid_036 ABCB1 * - * - ACVR1B * * * - ACVR2A * * - - ")) Patient_021 = as.data.frame(read.table(text = " Driver SNV_Organoid_021 INDEL_Organoid_021 ABCB1 * * - ACVR1B * * - ACVR2A * * * ")) ui <- shinyUI(navbarPage("Patients", tabPanel("Table",theme = "bootstrap.css", headerPanel("Genomic variations in OESO driver genes"), sidebarPanel(br(), tags$style("#select1 {border: 2px solid #dd4b39;}"), div( id = "loading-content", h2("Binary output"), navbarPageWithText( "* means that gene carries an event", text = "- means that no event has been observed" ) ), selectInput( "table_dataset", "Choose patient:", choices = c("Patient_005","Patient_013","Patient_036","Patient_021") ) ), mainPanel(DT::dataTableOutput("table")) ), tabPanel("Image", sidebarPanel( br(), tags$style("#select2 {background-color:blue;}"), selectInput( "image_dataset", "Choose image:", choices = c("Mutational_Signatures"="https://i.ibb.co/hZYc9nM/Mutational-Signatures1.png", "Total_and_Minor_Copy_Number" = "https://i.ibb.co/pRYxfwF/Total-and-Minor-Copy-Number.png", "Structural_Variations" = "https://i.ibb.co/JB4z6y6/Strutural-Variations.png", "Statistics" = "https://i.ibb.co/DYm2nm4/Statistics.png" , "Major_and_Minor_Copy_Number" = "https://i.ibb.co/ZV3DTXN/Major-and-Minor-Copy-Number.png", "Mutational_consequences_SNVs" = "https://i.ibb.co/CpyqRdr/Mutational-consequences.png" , "Mutational_consequences_INDEL" = "https://i.ibb.co/Vt4nwqd/Mutational-consequences-indel.png" , "Segment_mean" = "https://i.ibb.co/Cthk4ZD/Segment-mean.png" , "RNA_seq_Driver_Genes" = "https://i.ibb.co/qr9cvdN/RNA-seq.png" ) ) ), mainPanel( uiOutput("image") ), div( id = "loading-content", h2("Loading..."), navbarPageWithText( "Images of", text = "Organoid models" ) ) ),tags$head( tags$style(type = 'text/css', HTML('.navbar { background-color: skin-blue;} .navbar-default .navbar-brand{color: black;} .tab-panel{ background-color: skin-blue; color: black} .navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active > a:focus, .navbar-default .navbar-nav > .active > a:hover { color: #555; background-color: pink; }') ) ) )) server <- function(input, output) { # Related to displaying tables table_data <- reactive({ switch(input$table_dataset, "Patient_005" = Patient_005 ,"Patient_013" = Patient_013,"Patient_036" = Patient_036,"Patient_021" = Patient_021) }) column_data <- reactive({ switch(input$table_dataset, "Patient_005" = c('Driver','SNV_Tumour_005','SNV_Organoid_005','INDEL_Tumour_005','INDEL_Organoid_005','Deletion_Organoid_005'), "Patient_013" = c('SNV_Tumour_013','SNV_Organoid_013','INDEL_Tumour_013','INDEL_Organoid_013','Deletion_Tumour_013','Deletion_Organoid_013') ) }) output$table <- DT::renderDataTable({ datatable(table_data()) %>% formatStyle( column_data(), backgroundColor = styleEqual(c("*", "-"), c('green', 'red')) ) }) # Related to displaying images output$image <- renderUI({ tags$img(src = input$image_dataset) }) } shinyApp(ui=ui,server=server) I need to add this table as another panel with the title of MetaData > head(MetaData) Clinical.ID Barcode WTSI.Model.ID Tissue.Origin 1 OCC/SH/253/S/T 2000003422203 WTSI-OESO_005 Oesophageal 2 OCC/SH/254/S/T CGAP-A3F3F WTSI-OESO_013 Oesophageal 3 OCC/SH/255/S/T CGAP-73FED WTSI-OESO_036 Oesophageal 4 OCC/SH/255/S/N CGAP-70672 WTSI-OESO_037 Oesophageal Sample.type 1 Tumour 2 Tumour 3 Tumour 4 Normal > > dput(head(MetaData)) structure(list(Clinical.ID = structure(c(1L, 2L, 4L, 3L), .Label = c("OCC/SH/253/S/T", "OCC/SH/254/S/T", "OCC/SH/255/S/N", "OCC/SH/255/S/T"), class = "factor"), Barcode = structure(c(1L, 4L, 3L, 2L), .Label = c("2000003422203", "CGAP-70672", "CGAP-73FED", "CGAP-A3F3F"), class = "factor"), WTSI.Model.ID = structure(1:4, .Label = c("WTSI-OESO_005", "WTSI-OESO_013", "WTSI-OESO_036", "WTSI-OESO_037"), class = "factor"), Tissue.Origin = structure(c(1L, 1L, 1L, 1L), .Label = "Oesophageal", class = "factor"), Sample.type = structure(c(2L, 2L, 2L, 1L), .Label = c("Normal", "Tumour"), class = "factor")), row.names = c(NA, 4L), class = "data.frame") > Could you please give me a hand in adding this table as the third panel to my app?
doc_23533394
A: It depends how many resources you want to the actor to use. If there is a dedicated machine for a given actor, and it's ok for the actor to use all of the resources on that machine, then use TensorFlow's default settings. If you are creating more like one actor per core, then setting inter_op_parallelism_threads and intra_op_parallelism_threads to small values like 1 or 2 is a good idea. In general, you can try both approaches and see which is faster.
doc_23533395
<?xml version="1.0" encoding="utf-8"?> <BedrijfsInformatie xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Bedrijfsnaam>TotaalTechniek Europort bv</Bedrijfsnaam> <Naam>E.W. Messemaker</Naam> <Adres>Deltageul 71</Adres> <Postcode>3251 NG</Postcode> <Plaats>Stellendam</Plaats> <Emailadres>edwin@tt-europort.eu</Emailadres> <Telefoon>0187-499536</Telefoon> <Rechtsvorm>Besloten Vennootschap</Rechtsvorm> <Kvk>62.12.963.5</Kvk> <BTW>Nl.8546.72.011.B01</BTW> <Werkadres /> <Levering /> <IBAN /> <Swift /> <Betalingswijze>rekening</Betalingswijze> <Verzamelfactuur>nee</Verzamelfactuur> <Digitalefactuur>ja</Digitalefactuur> <EmailDigitalefactuur>info@tt-europort.eu</EmailDigitalefactuur> <Contactpersonen> <Contactpersoon> <Voornaam>Edwin</Voornaam> <Achternaam>Messemaker</Achternaam> <Emailadres>edwin@tt-europort.eu</Emailadres> <Telefoon>0187-499536</Telefoon> <Functie>DGA</Functie> <Monteur /> <CanOrder>Ja</CanOrder> <CanSeeStock>Ja</CanSeeStock> <CanSeeOrder>Ja</CanSeeOrder> <CanAddAddress>Ja</CanAddAddress> <CanSeePrice>Ja</CanSeePrice> <CanSeeCredit>Ja</CanSeeCredit> <CanSeePickup>Ja</CanSeePickup> </Contactpersoon> <Contactpersoon> <Voornaam>Gijs</Voornaam> <Achternaam>Alphen, van</Achternaam> <Emailadres>gijs@tt-europort.eu</Emailadres> <Telefoon>0651971605</Telefoon> <Functie>DGA</Functie> <Monteur /> <CanOrder>Ja</CanOrder> <CanSeeStock>Ja</CanSeeStock> <CanSeeOrder>Ja</CanSeeOrder> <CanAddAddress>Ja</CanAddAddress> <CanSeePrice>Ja</CanSeePrice> <CanSeeCredit>Ja</CanSeeCredit> <CanSeePickup>Nee</CanSeePickup> </Contactpersoon> </Contactpersonen> </BedrijfsInformatie> But if I do the import I get the error: Attribuut wordt niet verwacht. So the second line: <BedrijfsInformatie xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> NAv doesnt accept.But if I do like this: <BedrijfsInformatie> it works. But I cant do that manualy. Because the file has to read all his contents. Thank you Yes, with a XML port, this is the code of the xml port: Documentation() OnInitXMLport() OnPreXMLport() OnPostXMLport() BedrijfsInformatie - Import::OnAfterInitRecord() BedrijfsInformatie - Import::OnBeforeInsertRecord() BedrijfsInformatie - Import::OnAfterInsertRecord() BedrijfsInformatie - Export::OnPreXMLItem() BedrijfsInformatie - Export::OnAfterGetRecord() Bedrijfsnaam - Import::OnAfterAssignField() Bedrijfsnaam - Export::OnBeforePassField() Naam - Import::OnAfterAssignVariable() Naam - Export::OnBeforePassVariable() Adres - Import::OnAfterAssignVariable() Adres - Export::OnBeforePassVariable() Postcode - Import::OnAfterAssignVariable() Postcode - Export::OnBeforePassVariable() Plaats - Import::OnAfterAssignVariable() Plaats - Export::OnBeforePassVariable() Emailadres - Import::OnAfterAssignVariable() Emailadres - Export::OnBeforePassVariable() Telefoon - Import::OnAfterAssignVariable() Telefoon - Export::OnBeforePassVariable() Rechtsvorm - Import::OnAfterAssignVariable() Rechtsvorm - Export::OnBeforePassVariable() Kvk - Import::OnAfterAssignVariable() Kvk - Export::OnBeforePassVariable() BTW - Import::OnAfterAssignVariable() BTW - Export::OnBeforePassVariable() Werkadres - Import::OnAfterAssignVariable() IF Werkadres = 'verplicht' THEN "<Customer>"."Reference Mandatory" := TRUE ELSE "<Customer>"."Reference Mandatory" := FALSE; Werkadres - Export::OnBeforePassVariable() Levering - Import::OnAfterAssignVariable() IF Werkadres = 'verplicht' THEN "<Customer>"."Job Receipt No. Mandatory" := TRUE ELSE "<Customer>"."Job Receipt No. Mandatory" := FALSE; Levering - Export::OnBeforePassVariable() IBAN - Import::OnAfterAssignVariable() IBAN - Export::OnBeforePassVariable() Swift - Import::OnAfterAssignVariable() Swift - Export::OnBeforePassVariable() Betalingswijze - Import::OnAfterAssignVariable() //Determines which payment method is choosen(rekening, Kontant,automatische incasso in the xml file) CASE Betalingswijze OF 'kontant': TemplateHeader.Code :='KNT-KLANT'; 'rekening': TemplateHeader.Code :='REK-KLANT'; 'automatische incasso': TemplateHeader.Code :='BIN-INC-KL'; ELSE TemplateHeader.Code :='KONTANT'; END; Betalingswijze - Export::OnBeforePassVariable() Verzamelfactuur - Import::OnAfterAssignField() Verzamelfactuur - Export::OnBeforePassField() Digitalefactuur - Import::OnAfterAssignField() Digitalefactuur - Export::OnBeforePassField() EmailDigitalefactuur - Import::OnAfterAssignVariable() EmailDigitalefactuur - Export::OnBeforePassVariable() Contactpersonen - Import::OnAfterAssignVariable() Contactpersonen - Export::OnBeforePassVariable() Contactpersoon - Export::OnPreXMLItem() Contactpersoon - Export::OnAfterGetRecord() Contactpersoon - Import::OnAfterInitRecord() Contactpersoon - Import::OnBeforeInsertRecord() "<Contact>".Type := 1;//1 is for Person. 0 is for company Contactpersoon - Import::OnAfterInsertRecord() LoopCount := LoopCount + 1; IF FirstContact = '' THEN FirstContact := "<Contact>"."No."; Voornaam - Export::OnBeforePassField() Voornaam - Import::OnAfterAssignField() Achternaam - Export::OnBeforePassField() Achternaam - Import::OnAfterAssignField() Emailadres - Export::OnBeforePassField() Emailadres - Import::OnAfterAssignField() Telefoon - Export::OnBeforePassField() Telefoon - Import::OnAfterAssignField() Functie - Export::OnBeforePassField() Functie - Import::OnAfterAssignField() Monteur - Export::OnBeforePassField() Monteur - Import::OnAfterAssignField() CanOrder - Export::OnBeforePassVariable() CanOrder - Import::OnAfterAssignVariable() IF CanOrder = 'Ja' THEN "<Contact>".Right1 := TRUE ELSE "<Contact>".Right1:= FALSE; CanSeeStock - Export::OnBeforePassVariable() CanSeeStock - Import::OnAfterAssignVariable() IF CanOrder = 'Ja' THEN "<Contact>".Right2 := TRUE ELSE "<Contact>".Right2:= FALSE; CanSeeOrder - Export::OnBeforePassVariable() CanSeeOrder - Import::OnAfterAssignVariable() IF CanOrder = 'Ja' THEN "<Contact>".Right3 := TRUE ELSE "<Contact>".Right3:= FALSE; CanAddAddress - Export::OnBeforePassVariable() CanAddAddress - Import::OnAfterAssignVariable() IF CanOrder = 'Ja' THEN "<Contact>".Right4 := TRUE ELSE "<Contact>".Right4:= FALSE; CanSeePrice - Export::OnBeforePassVariable() CanSeePrice - Import::OnAfterAssignVariable() IF CanSeePrice = 'Ja' THEN "<Contact>".Right5 := TRUE ELSE "<Contact>".Right5:= FALSE; CanSeeCredit - Export::OnBeforePassVariable() CanSeeCredit - Import::OnAfterAssignVariable() IF CanOrder = 'Ja' THEN "<Contact>".Right6 := TRUE ELSE "<Contact>".Right6:= FALSE; CanSeePickup - Export::OnBeforePassVariable() CanSeePickup - Import::OnAfterAssignVariable() IF CanOrder = 'Ja' THEN "<Contact>".Right7 := TRUE ELSE "<Contact>".Right7:= FALSE; UpdateRecord() and this is the code for import: Documentation() Report - OnInitReport() Report - OnPreReport() Report - OnPostReport() IF Filename <> '' THEN ImportFile ELSE MESSAGE(NoFileText); Report - OnCreateHyperlink(VAR URL : Text[1024]) Report - OnHyperlink(URL : Text[1024]) UploadFile(VAR FileName : Text[1024]) IF NOT ISSERVICETIER THEN NewFileName := CommonDialogMgt.OpenFile(Caption,FileName,4,Filefilter,0) ELSE IF NOT(UPLOAD(Caption,'',Filefilter,FileName,NewFileName)) THEN NewFileName := ''; IF NewFileName <> '' THEN FileName := NewFileName; ImportFile() IF ISSERVICETIER THEN BEGIN IF UPLOADINTOSTREAM( 'Select the simple.xml file', '\\svdh04\data\NAV docs\webaanmelding\', 'XML File *.xml| *.xml', Filename, Stream) THEN MESSAGE(ImportCompleteText) ELSE EXIT; END ELSE BEGIN dFile.OPEN(Filename); dFile.CREATEINSTREAM(Stream); IF NOT XMLPORT.IMPORT(50010,Stream) THEN MESSAGE(ErrorText) ELSE MESSAGE(ImportCompleteText); END; IF NOT ISSERVICETIER THEN dFile.CLOSE; I have it now like this: //New code: dFile.TEXTMODE(FALSE); dFile.OPEN(SavePath); dFile.CREATEINSTREAM(Stream); InputText.READ(Stream); dFile.CLOSE; TextToFind := 'xmlns=""'; TextPos := InputText.TEXTPOS(TextToFind); WHILE TextPos <> 0 DO BEGIN InputText.GETSUBTEXT(SubText, 1, TextPos - 1); OutputText.ADDTEXT(SubText); InputText.GETSUBTEXT(InputText, TextPos + STRLEN(TextToFind)); TextPos := InputText.TEXTPOS(TextToFind); END; OutputText.ADDTEXT(InputText); dFile.TEXTMODE(FALSE); dFile.CREATE(SavePath); dFile.CREATEOUTSTREAM(NVOutStream); OutputText.WRITE(NVOutStream); dFile.CLOSE; //End new code IF ISSERVICETIER THEN BEGIN IF UPLOADINTOSTREAM( 'Select the simple.xml file', '\\svdh04\data\NAV docs\webaanmelding\', 'XML File *.xml| *.xml', Filename, Stream) THEN MESSAGE(ImportCompleteText) ELSE EXIT; END ELSE BEGIN dFile.OPEN(Filename); dFile.CREATEINSTREAM(Stream); IF NOT XMLPORT.IMPORT(50010,Stream) THEN MESSAGE(ErrorText) ELSE MESSAGE(ImportCompleteText); END; IF NOT ISSERVICETIER THEN dFile.CLOSE; But then I get this error: ok, I changed now to this: //New code: dFile.TEXTMODE(FALSE); dFile.OPEN(Filename); dFile.CREATEINSTREAM(Stream); InputText.READ(Stream); dFile.CLOSE; TextToFind := 'xmlns=""'; TextPos := InputText.TEXTPOS(TextToFind); MESSAGE(FORMAT(TextPos)); WHILE TextPos <> 0 DO BEGIN InputText.GETSUBTEXT(SubText, 1, TextPos - 1); OutputText.ADDTEXT(SubText); InputText.GETSUBTEXT(InputText, TextPos + STRLEN(TextToFind)); TextPos := InputText.TEXTPOS(TextToFind); END; OutputText.ADDTEXT(InputText); dFile.TEXTMODE(FALSE); dFile.CREATE(Filename); dFile.CREATEOUTSTREAM(NVOutStream); OutputText.WRITE(NVOutStream); dFile.CLOSE; //End new code IF ISSERVICETIER THEN BEGIN IF UPLOADINTOSTREAM( 'Select the simple.xml file', '\\svdh04\data\NAV docs\webaanmelding\', 'XML File *.xml| *.xml', Filename, Stream) THEN MESSAGE(ImportCompleteText) ELSE EXIT; END ELSE BEGIN dFile.OPEN(Filename); dFile.CREATEINSTREAM(Stream); IF NOT XMLPORT.IMPORT(50010,Stream) THEN MESSAGE(ErrorText) ELSE MESSAGE(ImportCompleteText); END; IF NOT ISSERVICETIER THEN dFile.CLOSE; But the problem is that: TextPos := InputText.TEXTPOS(TextToFind); TextPos is 0. Thank you A: Yes, because NAV 2009 doesn't support namespaces in XMLports. The solution is here: You have to remove the namespace(s) first with an xml transformation Cheers!
doc_23533396
Object {sd_src: Object, hd_src: Object} and the sd_src & hd_src objects contains (console.log) : Object file: "videofile.mp4" label: "HD" sd_src: Object{the same first obj} i create empty object dataSources = []; to push video sources to it in the for in loop then i create a for in loop to get object properties and push them to dataSources like this : for (var p in ReturnData.srcs) { if( ReturnData.srcs.hasOwnProperty(p) ) { dataSources.push( ReturnData.srcs[p] ); } } and the last touch i create the JWplayer 7 setup : jwplayer.key="myjwplayer.key"; var playerInstance = jwplayer("dv-watchvideo"); var dvPlayer = playerInstance.setup({ sources : **dataSources** , image: '', width: 558, height: 360, type: 'mp4', primary: "flash", startparam: ReturnData.startparam, skin: { url: "thin.min.css", name: "thin", } }); Note : the var dataSources between two stars the other problem is even when i push the objects inside dataSources when i try to log the var in the console is always return object with undefined keys , but when i remove the jwplayer setup the dataSources push work ! working codepen exemple but when i use ajax to return data will not work. if my method is wrong , is there any other way to do this ? A: I made a few changes to your syntax, per my suggestions in my earlier comments. Try adding your ajax sources to this pen: http://codepen.io/simsketch/pen/KVMVKe code excerpt: jwplayer("player").setup({ playlist: [{ sources : dataSources }], image: '', ... I think your primary mistake was not adding the playlist wrapper as explained here: https://support.jwplayer.com/customer/portal/articles/1710454-configuring-multiple-sources
doc_23533397
jQuery UI API Documentation jQuery site TutorialsPoint the source code itself and I cannot find the default time. I assume it is 400 ms because the animate() method is called to produce the clip effect, and the default time for animate() is 400 ms. Does anyone know if this is correct? Thanks! A: The answer is already in the comments, its 400ms. Heres a way to calculate the duration of timeouts, intervals, animations, effects,...: var starting = new Date().getTime(); setTimeout(function () { //or any animation,effect,... var ending = new Date().getTime(); alert(ending-starting); // ~500 }, 500);
doc_23533398
I want to use my font such like this <span class="icon-Electronic"></span> instead of this <span class="icon-Electronic"><span class="path1"></span><span class="path2"></span><span class="path3"></span><span class="path4"></span><span class="path5"></span><span class="path6"></span><span class="path7"></span><span class="path8"></span><span class="path9"></span><span class="path10"></span><span class="path11"></span><span class="path12"></span></span> what's wrong with my step? i need help A: This is because you have multiple paths in your svg file, You will need to merge them together externally and import it again If you have access to Adobe Illustrator, * *Open file in Illustrator *Select all *Go to Object > Path >Outline stroke *Then select all *Go to Windows > Pathfinder > Merge *Then save it and import again You can record this as an action in Illustrator for future use The above methods can be replicated in any other vector editing software like Inkscape(free). The steps will be almost same, But merging is very important.
doc_23533399
On clicking the tabs/navigation items, the corresponding page should get open. Can this be done using ngRoute? If yes, then how? Moreover, I will use that app in MEAN Stack app. I tried doing this using ui-router; it worked when deployed the app on tomcat. But whenever code is deployed on MEAN Stack, it doesn't work. Can any one please tell why is it happening? File Structure: Project Name |-- client | |-- js | | `-- app.js | |-- templates | | |-- about.html | | `-- home.html | `-- views | `-- index.html |-- server |-- node_modules |-- server.js `-- package.json index.html <!DOCTYPE html> <html> <head> <!-- CSS (load bootstrap) --> <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css"> <style> .navbar { border-radius:0; } </style> <!-- JS (load angular, ui-router, and our custom js file) --> <script src="http://code.angularjs.org/1.2.13/angular.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script> <script src="/client/js/app.js"></script> </head> <!-- angular app --> <body ng-app="routerApp"> <!-- NAVIGATION --> <nav class="navbar navbar-inverse" role="navigation"> <div class="navbar-header"> <a class="navbar-brand" ui-sref="#">AngularUI Router</a> </div> <ul class="nav navbar-nav"> <li><a ui-sref="home">Home</a></li> <li><a ui-sref="about">About</a></li> </ul> </nav> <div class="container"> <div ui-view></div> </div> </body> </html> app.js var routerApp = angular.module('routerApp', ['ui.router']); routerApp.config(function($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise('/home'); $stateProvider .state('home', { url: '/home', templateUrl: '/client/templates/home.html' }) .state('about', { url: '/about', templateUrl: '/client/templates/about.html' }); }); server.js var express = require('express'), app = express(); bodyParser = require('body-parser'); app.use(bodyParser()); app.get('/', function (req, res) { res.sendfile(__dirname + '/client/views/index.html'); }); app.use('/js', express.static(__dirname + '/client/js')); app.listen(3000, function() { console.log('I\'m Listening...'); }) A: First, what error are you getting in the console? At first glance, I see that some of your resources are missing the protocol in the uri. Now you are using uiRoute which gives you more flexibility than ngRoute. If you still wish to go with ngRoute, you need first to load the ngRoute module in your application and edit the routing: (function(){ var app = angular.module('module_name', ['ngRoute']); app.config(['$routeProvider',function($routeProvider) { $routeProvider .when('/url1', { controller: 'nameOfController', controllerAs: 'referenceToController', templateUrl: 'referenceToView', resolve: { // run all these methods before loading project method1: function(){ return value1 }, method2: function(){ return value1 } } }) .otherwise('/url2'); }]) }()); In order to achieve the desired functionality with ngRoute, you have several options: 1- Use ng-href directive: you can add the ng-href directive to the DOM element (your menu items) like this: <li><a ng-href="/#/home">Home</a></li> 2- Use $location service in the controller: you can add a click event listener to the DOM and call the path() method in the $location service like this (you need to create your controller first): $("a[ui-sref='home']").on("click", function(){ $location.path("/#/home");}); 3- Build your own directive: probably unnecessary if all you want is a simple menu bar. But if you wish to go beyond the basic behavior (like updating some data in the app for DOM manipulation or business logic purposes): <li><a ui-sref="home" my-costume-click-directive>Home</a></li> angular.module(app).directive('myCostumeClickDirective', function(){ return { link: function(scope, elm, attr, controller, transclude) { // your event listeners and methods go here } } });