date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/20
191
736
<issue_start>username_0: I have a VSTS GIT repository, I want to create new remote repository which would be the copy of existing repository. How to do it ? Please note I am not looking for GIT clone to clone a local copy of remote repository. Atul<issue_comment>username_1: I think there is no in built command, create a local clone remove the git folder, create empty repo & copy the folder & push. Upvotes: 0 <issue_comment>username_2: Some options: * Clone the repo with `git clone --depth=1` (which only clones the most recent commit), then add a new remote and push. * If you're staying within your VSTS account, you can *[fork](https://learn.microsoft.com/en-us/vsts/git/concepts/forks)* the repo. Upvotes: 3 [selected_answer]
2018/03/20
233
746
<issue_start>username_0: currently I am using ``` for s in list: print(*s) ``` but it displays the list output as ``` ['this is'] ['the output'] ``` But I would like the output to be displayed as ``` this is the output ``` There should be a simple solution but i am still yet to come across one.<issue_comment>username_1: `list_string = ', '.join(list_name)` `print (list_string) #without brackets` Upvotes: 0 <issue_comment>username_2: Join using the newline character: ``` print("\n".join(your_list)) ``` Please note that `list` is a Python type and shouldn't be used as a variable name. Upvotes: 0 <issue_comment>username_3: ``` l = [['this is'], ['the output']] for sub_list in l: print(sub_list[0]) ``` Upvotes: 1
2018/03/20
330
1,116
<issue_start>username_0: I've just installed Bugzilla 5.0.4 on Centos 6.9 (upgrade from Bugzilla 4.2.1) It's `checksetup.pl` passes, but the website returns 'Internal Server Error'. The only thing in apache's error\_log is: > > /var/www/html/bugzilla/.htaccess: Options not allowed here > > > How should I approach fixing this?<issue_comment>username_1: Add 'Options' to AllowOverride in /etc/httpd/conf.d/buzilla.conf, and restart Apache. Upvotes: 1 <issue_comment>username_2: "Require" is a type of AuthConfig directives. You need to specify, in httpd.conf, that type of directives are allowed in .htaccess. ( See <https://httpd.apache.org/docs/2.4/mod/core.html#allowoverride> and <https://httpd.apache.org/docs/2.4/mod/overrides.html#override-indexes>) ``` AddHandler cgi-script .cgi Options +Indexes +ExecCGI DirectoryIndex index.cgi AllowOverride Limit AuthConfig Options Indexes FileInfo ``` The instructions from bugzilla does not have **AuthConfig** and the rest of the line here. You need to add them all in order to make /var/www/html/bugzilla/.htaccess acceptable to apache. Upvotes: 0
2018/03/20
1,499
5,584
<issue_start>username_0: I am Beginner in Ionic 2 . I am working on **Network Connection/Detection** Using Network native plugin. I want show **wifi symbol image** when there is **no Internet connection** Example . [![enter image description here](https://i.stack.imgur.com/yDnji.png)](https://i.stack.imgur.com/yDnji.png) And i want to hide this Dashboard when there is no internet connection and required to show **wifi image symbol** like above image [![enter image description here](https://i.stack.imgur.com/2Z8yJ.png)](https://i.stack.imgur.com/2Z8yJ.png) This is my code for **dashboard.html** ``` ![](assets/icon/location.png) Mapping ![](assets/icon/folder.png) Send manager ![Logo](assets/imgs/wifi.png) ![](assets/icon/question.png) Help ![](assets/icon/logout.png) Exit ```<issue_comment>username_1: **I will create for you`NetworkConnectionProvider.ts` provider for listening network event.** ``` import {Injectable} from '@angular/core'; import {Platform, ToastController, Events} from "ionic-angular"; import {Network} from "@ionic-native/network"; export enum ConnectionStatusEnum { Online, Offline } @Injectable() export class NetworkConnectionProvider { public isOnline: boolean = true; private previousStatus; constructor(private network: Network, private platform:Platform, private toastCtrl: ToastController, private eventCtrl: Events) { this.platform.ready().then(() => { this.previousStatus = ConnectionStatusEnum.Online; this.initializeNetworkEvents(); }); } public initializeNetworkEvents(): void { this.network.onDisconnect().subscribe(() => { if (this.previousStatus === ConnectionStatusEnum.Online) { this.eventCtrl.publish('network:offline'); } this.previousStatus = ConnectionStatusEnum.Offline; this.isOnline = false; }); this.network.onConnect().subscribe(() => { if (this.previousStatus === ConnectionStatusEnum.Offline) { this.eventCtrl.publish('network:online'); } this.previousStatus = ConnectionStatusEnum.Online; this.isOnline = true; }); } } ``` **And then inject in `NetworkConnectionProvider` in `app.module.ts`** **Provider Uses** **In `dashboard.ts`** First of all inject `private networkCheck:NetworkConnectionProvider` and `private eventCtrl: Events` in `constructor`. Then listen it. ``` flag:boolean=false; this.eventCtrl.subscribe('network:online', () => { // online action this.flag =true; }); this.eventCtrl.subscribe('network:offline', () => { // offline action this.flag =false; }); ``` **In `dashboard.html` need to modify** ``` ![](assets/icon/location.png) Mapping ![](assets/icon/folder.png) Send manager ![Logo](assets/imgs/wifi.png) ![](assets/icon/question.png) Help ![](assets/icon/logout.png) Exit ``` Upvotes: 2 <issue_comment>username_2: Following @username_1 answer. You can also use hidden attribute which doesn't delete your element from the Dom like ngIf does. ``` ``` Upvotes: 0 <issue_comment>username_3: I have get perfect image **hide and show w.r.to Internet connection** with this code **Import Network plugin** import { Network } from '@ionic-native/network'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/fromEvent'; **Put this under before constructor** ``` hide:boolean = true; ``` **Put this code under Constructor** ``` var offline = Observable.fromEvent(document, "offline"); var online = Observable.fromEvent(document, "online"); offline.subscribe(() => { this.hide =false; }); online.subscribe(()=>{ this.hide =true; }); ``` **Put this under html file** ``` ![Logo](assets/imgs/wifi.png) ``` //**Result :** When your device Internet is not available then wifi image is visible and wise versa.. Upvotes: 3 [selected_answer]<issue_comment>username_4: Maybe this concept can help you.. You can use @ionic-native/network To check current network connection inside the device ``` isConnected(): boolean { let conntype = this.network.type; return conntype && conntype !== 'unknown' && conntype !== 'none'; } ``` There is a function like `onConnect` and `onDisconnect` inside the `ionic-native/network` modules, but it only checks whenever you connect/disconnect the network from your phone when you were in-app. and maybe its useful to use the function if someone suddenly has no /disable the network connection Constructor : ``` constructor(private network: Network, private toast: ToastController) { } ``` Simply put in the constructor ``` if(!this.isConnected()) { this.openToast(this.isConnected()); } ``` Simply put inside the constructor of the page, This is how we can automatically check the network connection after the page is loaded openToast() function ``` openToast(isConnected: boolean) { let networkType = this.network.type; this.toast.create({ message: `Network type: ${networkType} and ${isConnected}`, duration: 3000 }).present(); } ``` and take note that in ionic 3.. The supported version of `@ionic-native/network` < 5.0.0 I tested on Ionic 3 can use version 4.6.0 This is how we declare `import { Network } from '@ionic-native/network/index';` More info : <https://www.npmjs.com/package/@ionic-native/network> > > Result : if the user open up the page with no internet connection, > it's toast up a message > > > I hope someone found this helpful information Upvotes: 0
2018/03/20
598
2,066
<issue_start>username_0: In my project I need to use Gotham Book font-family and I am using following code: ``` @font-face { font-family: 'Gotham Book'; src: url('assets/fonts/Gotham-Book.eot'), url('assets/fonts/Gotham-Book.eot?#iefix') format('embedded-opentype'), url('assets/fonts/Gotham-Book.woff2') format('woff2'), url('assets/fonts/Gotham-Book.woff') format('woff'), url('assets/fonts/Gotham-Book.ttf') format('truetype'); font-weight: normal; font-style: normal; } ``` If perfectly works in android devices and other browsers except safari browser. Please suggest what is the wrong in my code. What causing this issue? I also tried with Gotham Book svg import, but did not worked for me. Thank You in advance!<issue_comment>username_1: Try adding the whole URL of the font assets. **CSS:-** ``` @font-face { font-family: 'Gotham Book'; src: url('https://www.example.com/assets/fonts/Gotham-Book.eot'), url('https://www.example.com/assets/fonts/Gotham-Book.eot?#iefix') format('embedded-opentype'), url('https://www.example.com/assets/fonts/Gotham-Book.woff2') format('woff2'), url('https://www.example.com/assets/fonts/Gotham-Book.woff') format('woff'), url('https://www.example.com/assets/fonts/Gotham-Book.ttf') format('truetype'); font-weight: normal; font-style: normal; } ``` Thanks Upvotes: 0 <issue_comment>username_2: This is the working Solution CSS : ``` @font-face { font-family: "gotham"; src: url('ff/Gotham-Book.woff') format('woff'), url('ff/Gotham-Book.woff2') format('woff2'), url('ff/Gotham-Book.ttf') format('truetype'); font-weight: normal; } ``` and Please replace your existing font by downloading font from below URl: <https://drive.google.com/open?id=1pbdpXbPRCJC6Qi-QpNGt7WbLuwtwDRUW> Thanks Upvotes: 4 [selected_answer]
2018/03/20
540
1,736
<issue_start>username_0: I tried to concat two string using sql query. Below is my code which is not working. ``` SELECT TOP 100 CONCAT('James ','Stephen') AS [Column1] FROM [dbo].[ORDERS] Group BY () ORDER BY CONCAT('James ','Stephen') ASC ``` If I use `[Column1]` instead of `CONCAT('James ','Stephen')` in Order by clause, it seems working. ``` SELECT TOP 100 CONCAT('James ','Stephen') AS [Column1] FROM [dbo].[ORDERS] Group by () ORDER BY [Column1] ASC ``` Can anyone explain me, why did not the first query work?<issue_comment>username_1: Try adding the whole URL of the font assets. **CSS:-** ``` @font-face { font-family: 'Gotham Book'; src: url('https://www.example.com/assets/fonts/Gotham-Book.eot'), url('https://www.example.com/assets/fonts/Gotham-Book.eot?#iefix') format('embedded-opentype'), url('https://www.example.com/assets/fonts/Gotham-Book.woff2') format('woff2'), url('https://www.example.com/assets/fonts/Gotham-Book.woff') format('woff'), url('https://www.example.com/assets/fonts/Gotham-Book.ttf') format('truetype'); font-weight: normal; font-style: normal; } ``` Thanks Upvotes: 0 <issue_comment>username_2: This is the working Solution CSS : ``` @font-face { font-family: "gotham"; src: url('ff/Gotham-Book.woff') format('woff'), url('ff/Gotham-Book.woff2') format('woff2'), url('ff/Gotham-Book.ttf') format('truetype'); font-weight: normal; } ``` and Please replace your existing font by downloading font from below URl: <https://drive.google.com/open?id=1pbdpXbPRCJC6Qi-QpNGt7WbLuwtwDRUW> Thanks Upvotes: 4 [selected_answer]
2018/03/20
1,114
4,517
<issue_start>username_0: What I am trying to do is, there is no chance the two activities are running at the same time. So I am using for this method in my adaptor class. ``` Intent intent = new Intent().setClass(v.getContext(), WinnerDetailActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); v.getContext().startActivity(intent); ((Activity)context).finish(); ``` But when I click the back button, it doesn't go to the back activity. What am I doing wrong?<issue_comment>username_1: Just remove this line: ``` ((Activity)context).finish(); ``` Upvotes: 0 <issue_comment>username_2: Called the Finish method of activity at button click. finish() just lets the system know that the programmer wants the current Activity to be finished. `((Activity)context).finish();` Upvotes: 0 <issue_comment>username_3: Basically you should remove `finish()` method from your code so that it will not destroy that activity and keep it in stack. Once you call the [finish()](https://developer.android.com/reference/android/app/Activity.html#finish()) you can not go back to previous activity. [This question](https://stackoverflow.com/questions/10847526/what-exactly-activity-finish-method-is-doing) explains in details, what happens when you call `finish()` method. Upvotes: 2 <issue_comment>username_4: That is because you are finishing your activity which means when you press back you don't have any activity on your stack to go back to. so just remove finish so that i will push WinnerDetailActivity on top of your current activity and on back of WinnerDetailActivity it will open your current activity. ``` Intent intent = new Intent().setClass(v.getContext(), WinnerDetailActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); v.getContext().startActivity(intent); ``` And also read about [FLAG\_ACTIVITY\_SINGLE\_TOP](https://developer.android.com/reference/android/content/Intent.html) > > If set, the activity will not be launched if it is already running at > the top of the history stack. > > > Upvotes: 0 <issue_comment>username_5: ``` //Here intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); will alway remain in intent stack unless you finish it and once this activity is resume.. then it will act as the stack has only on Activity running... //So just remove ((Activity)context).finish(); Intent intent = new Intent().setClass(v.getContext(), WinnerDetailActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); v.getContext().startActivity(intent); ((Activity)context).finish(); ``` Upvotes: 0 <issue_comment>username_6: Remove `((Activity)context).finish();` in your code, because here you are **finishing your activity** which means when you press back you don't have any activity on your stack to go back to. **Finish()** method will destroy the current activity. You can use this method in cases when you dont want this activity to load again and again when the user presses back button. Basically it clears the activity from the current stack. So,no need to use **finish()** here Upvotes: 1 <issue_comment>username_7: ``` There is two way to resolve this 1.Just remove ((Activity)context).finish(); because Finish() method will destroy the current activity. 2.Just Add below method in your class public void onBackPressed() { super.onBackPressed(); startActivity(new Intent(CurrentActivity.this,DestinationActivity.class)); } DestinationActivity means Activity where you want to move. ``` Upvotes: 0 <issue_comment>username_8: This can be done in two ways: Method 1: Whenever you're stating a New Activity from an Activity, Make sure that you don't call `finish()`. Calling `finish()` will destroy the Previous Activity in the Stack. Next Method is by Overriding `onBackPressed()`, by doing so you can navigate to the desired Activity. ``` @Override public void onBackPressed() { super.onBackPressed(); Intent intent = new Intent( thisActivity.this, yourFirstActivity.class); startActivity(intent); finish(); } ``` Upvotes: 0 <issue_comment>username_9: **OnBack Pressed Method is used to go back to previous activity, super.onBackPressed() is used to navigate to previous activity without super.onBackpress it is not possible to traverse to previous activity.** ``` @Override public void onBackPressed() { super.onBackPressed(); } ``` Upvotes: 0
2018/03/20
1,026
4,175
<issue_start>username_0: I am facing problem while playing last frame of pixi spine animation directly. The animation works fine but i want to skip all frames and run last frame only.<issue_comment>username_1: Just remove this line: ``` ((Activity)context).finish(); ``` Upvotes: 0 <issue_comment>username_2: Called the Finish method of activity at button click. finish() just lets the system know that the programmer wants the current Activity to be finished. `((Activity)context).finish();` Upvotes: 0 <issue_comment>username_3: Basically you should remove `finish()` method from your code so that it will not destroy that activity and keep it in stack. Once you call the [finish()](https://developer.android.com/reference/android/app/Activity.html#finish()) you can not go back to previous activity. [This question](https://stackoverflow.com/questions/10847526/what-exactly-activity-finish-method-is-doing) explains in details, what happens when you call `finish()` method. Upvotes: 2 <issue_comment>username_4: That is because you are finishing your activity which means when you press back you don't have any activity on your stack to go back to. so just remove finish so that i will push WinnerDetailActivity on top of your current activity and on back of WinnerDetailActivity it will open your current activity. ``` Intent intent = new Intent().setClass(v.getContext(), WinnerDetailActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); v.getContext().startActivity(intent); ``` And also read about [FLAG\_ACTIVITY\_SINGLE\_TOP](https://developer.android.com/reference/android/content/Intent.html) > > If set, the activity will not be launched if it is already running at > the top of the history stack. > > > Upvotes: 0 <issue_comment>username_5: ``` //Here intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); will alway remain in intent stack unless you finish it and once this activity is resume.. then it will act as the stack has only on Activity running... //So just remove ((Activity)context).finish(); Intent intent = new Intent().setClass(v.getContext(), WinnerDetailActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); v.getContext().startActivity(intent); ((Activity)context).finish(); ``` Upvotes: 0 <issue_comment>username_6: Remove `((Activity)context).finish();` in your code, because here you are **finishing your activity** which means when you press back you don't have any activity on your stack to go back to. **Finish()** method will destroy the current activity. You can use this method in cases when you dont want this activity to load again and again when the user presses back button. Basically it clears the activity from the current stack. So,no need to use **finish()** here Upvotes: 1 <issue_comment>username_7: ``` There is two way to resolve this 1.Just remove ((Activity)context).finish(); because Finish() method will destroy the current activity. 2.Just Add below method in your class public void onBackPressed() { super.onBackPressed(); startActivity(new Intent(CurrentActivity.this,DestinationActivity.class)); } DestinationActivity means Activity where you want to move. ``` Upvotes: 0 <issue_comment>username_8: This can be done in two ways: Method 1: Whenever you're stating a New Activity from an Activity, Make sure that you don't call `finish()`. Calling `finish()` will destroy the Previous Activity in the Stack. Next Method is by Overriding `onBackPressed()`, by doing so you can navigate to the desired Activity. ``` @Override public void onBackPressed() { super.onBackPressed(); Intent intent = new Intent( thisActivity.this, yourFirstActivity.class); startActivity(intent); finish(); } ``` Upvotes: 0 <issue_comment>username_9: **OnBack Pressed Method is used to go back to previous activity, super.onBackPressed() is used to navigate to previous activity without super.onBackpress it is not possible to traverse to previous activity.** ``` @Override public void onBackPressed() { super.onBackPressed(); } ``` Upvotes: 0
2018/03/20
179
719
<issue_start>username_0: I have installed [octobercms](/questions/tagged/octobercms "show questions tagged 'octobercms'") and I want to check version number of my current installed [octobercms](/questions/tagged/octobercms "show questions tagged 'octobercms'"). How can I check via Command line,through **backend** (*after login*) and through any file?<issue_comment>username_1: If you go into the `Backend -> Settings -> Updates & Plugins` you will find `Current Build` number Upvotes: 3 [selected_answer]<issue_comment>username_2: Login into your backend and add a widget system status on your dashboard and here you can check your system build version. [Screenshot](https://i.stack.imgur.com/S27ge.png) Upvotes: -1
2018/03/20
229
1,125
<issue_start>username_0: I need an AppService to load a treeview with a recursive collection of entities like these: ``` ===Products=== Id Description Price Products[] ====> Id Description Price Products[] ====> Id Description Price Products[] ====> Id Description Price Products[] ``` Is there a ready-made class to derive from? If not, could you suggest what class to derive or what interface to implement, and how to proceed, please? **PS:** Possibly with full CRUD operations, but the most important is understand how to load the data.<issue_comment>username_1: If you go into the `Backend -> Settings -> Updates & Plugins` you will find `Current Build` number Upvotes: 3 [selected_answer]<issue_comment>username_2: Login into your backend and add a widget system status on your dashboard and here you can check your system build version. [Screenshot](https://i.stack.imgur.com/S27ge.png) Upvotes: -1
2018/03/20
787
3,082
<issue_start>username_0: I have a basic component that contains the `ngxPermissionsOnly` directive which is working as expected. The library is on github [here](https://github.com/AlexKhymenko/ngx-permissions). I generated the component using the @angular-cli which also auto-generated the unit test. e.g. Component ``` @Component({ selector: 'project-card', template: 'Hide Me' styleUrls: ['./project-card.component.scss'] }) export class ProjectCardComponent implements OnInit { //Do some stuff here } ``` e.g. Test ``` describe('ProjectCardComponent', () => { let component: ProjectCardComponent; let fixture: ComponentFixture; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ ProjectCardComponent, ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ProjectCardComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); ``` When I run the test I get the below error; ``` Can't bind to 'ngxPermissionsOnly' since it isn't a known property of 'div' ``` I tried adding the `NgxPermissionsDirective` to the `TestBed` declarations, however this directive is dependent on services from that library, and I would also have to inject them. I also tried importing the `NgxPermissionsModule` itself but it has it's own errors. It seems counter-intuitive to inject a whole bunch of services to test a simple component. Is there a way to mock this directive? Or another solution?<issue_comment>username_1: I think you can just create mocked/stub directive by the same name in the test file and declare that in your test. Or alternatively you could use CUSTOM\_ELEMENTS\_SCHEMA or NO\_ERRORS\_SCHEMA (more info [here](https://medium.com/@cnunciato/both-custom-elements-schema-and-no-errors-schema-have-been-mentioned-as-options-for-ignoring-the-f9ea78999cbe)) as a schema in your tests: ``` import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; describe('ProjectCardComponent', () => { let component: ProjectCardComponent; let fixture: ComponentFixture; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ ProjectCardComponent, ], schemas: [CUSTOM\_ELEMENTS\_SCHEMA] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ProjectCardComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); ``` This will skip the unknown properties in your DOM, but this shouldn't be used if you want to actually test how the directive works with your component. Upvotes: 1 <issue_comment>username_2: I had to import the `NgxPermissionsModule` and provide the `NgxPermissionsService`; ``` TestBed.configureTestingModule({ imports: [ NgxPermissionsModule.forRoot(), ... ], declarations: [ ProjectCardComponent, ... ], providers: [ NgxPermissionsService, ... ] }) ``` Upvotes: 3 [selected_answer]
2018/03/20
1,661
4,881
<issue_start>username_0: From the answer [from here](https://stackoverflow.com/questions/49367451/dynamically-pivot-columns-with-month-and-year) I build a solution that is good for me but I have still one problem. I had table: ``` ID | Year | Month | Multiply | Future | Current 123 | 2017 | 1 | 1.0 | 25 | null 123 | 2017 | 2 | 1.0 | 19 | 15 123 | 2017 | 3 | 1.0 | 13 | 0 123 | 2017 | 4 | 1.0 | 22 | 14 123 | 2017 | 5 | 1.0 | 13 | null ... | .... | ... | ... | .. | .. 123 | 2018 | 1 | 1.0 | 25 | 10 123 | 2018 | 2 | 1.0 | 25 | 10 ... | .... | ... | ... | .. | .. 124 | 2017 | 1 | 1 | 10 | 5 124 | 2017 | 2 | 1 | 15 | 2 ... | .... | ... | ... | .. | .. 124 | 2018 | 1 | 1 | 20 | 0 ``` I build this view to concatenate Year + Month and make IF statement: value in the new Value column I'm getting from Future and Current column - when the Current value is null get the Future value and multiply by Multiply, else get Current value and multiply by Multiply (even 0). Next to it I need to add a 'F' prefix when the value is got from Future column. ``` ID | Date | Value | 123 | 2017 - 1 | F25 | 123 | 2017 - 2 | 15 | 123 | 2017 - 3 | 0 | .. | .. | .. | ``` Code for it: ``` SELECT ID = ID, [Date] = [Date], [Value] = [Value] FROM ( SELECT ID, cast([Year] as varchar(30)) + ' - ' + cast([Month]as varchar(30)) as [Date], [Multiply], case when [Current] IS NULL /*OR [Current] = 0*/ then 'F' + CAST([Future] * [Multiply] as varchar(30)) else CAST([Current] * [Multiply] as varchar(30)) end as Value FROM dbo.CurrentFuture ) AS t ``` And from this I make this view via dynamically pivot. ``` ID | 2017 - 1 | 2017 - 10 | 2017 - 11 | 2017 - 12 | 2017 - 2 | ... | 2018 - 1 | ... 123 | F25 | .. | .. | .. | 15 | ... | 10 | ... 124 | 5 | 2 | .. | .. | .. | ... | 0 | ... ``` Code for it: ``` DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX) select @cols = STUFF((SELECT ',' + QUOTENAME([Date]) from dbo.UpperView group by [Date] order by [Date] FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') set @query = 'SELECT [ID],' + @cols + ' from ( select [ID], [Date],[Value] from [dbo].[UpperView] ) x pivot ( max([Value]) for [Date] in (' + @cols + ') ) p ' execute(@query); ``` As you can see columns in the new view are not sorting in a good way.. instead of 2017 - 1, 2017 - 2, 2017 - 3 I have 2017 - 1, 2017 - 10, 2017 - 11, 2017 - 12, 2017 - 2. Can you help me how to sort it properly?<issue_comment>username_1: From the limited information, What you want is the ordering of the column based on the Concatenated string of Year+ Month. What you need is to prefix the month with "0" for January - September and no prefix for October-December. so in effect you will achieve this. ``` ID | 2017 - 01 | 2017 - 02 | 2017 - 03 | ..... | 2017 - 09 |2018 - 10 |2018 - 11||2018 - 12| SELECT ID = ID, [Date] = [Date], [Value] = [Value] FROM ( SELECT ID, CAST([Year] AS VARCHAR(30))+' - '+RIGHT('0'+CAST([Month] AS VARCHAR(30)), 2) AS [Date], [Multiply], CASE WHEN [Current] IS NULL /*OR [Current] = 0*/ THEN 'F'+CAST([Future] * [Multiply] AS VARCHAR(30)) ELSE CAST([Current] * [Multiply] AS VARCHAR(30)) END AS Value FROM dbo.CurrentFuture ) AS t; ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Add new column to UpperView for sorting like this ``` cast([Year] as varchar(30)) + RIGHT('0' + cast([Month] as varchar(30)), 2) as [DateOrder] ``` and use this column for sorting at your column query instead of [Date] ``` select @cols = STUFF((SELECT ',' + QUOTENAME([Date]) from dbo.UpperView group by [Date], [DateOrder] order by [DateOrder] FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') ``` Upvotes: 1
2018/03/20
1,511
4,792
<issue_start>username_0: `$data` has ``` stdClass Object ( [class] => srt-fields [rules_field_1] => 1 [rules_condition_1] => 0 [rules_value_1] => text [rules_field_2] => 3 [rules_condition_2] => 1 [rules_value_2] => another_text ... ) ``` Now I have another array `$newdata`, I need to have index `$newdata['rules']` so that it should be something like: ``` $newdata['rules'] => array( [field] => 1, [condition] => 0, [value] => text ), array( [field]=> 3, [condition] =>1, [value] => another_text ), ... ``` Thanks!<issue_comment>username_1: ``` $i = 0; $j = 0; foreach($data as $key=>$value){ if($j == 0) { $newdata['rules'][$i]['field'] = $value; } if($j == 1) { $newdata['rules'][$i]['condition'] = $value; } if($j == 2) { $newdata['rules'][$i]['value'] = $value; $i++; } $j++; if($j > 2) { $j = 0; } } ``` You can try this code. Please ignore syntax error as I have not tried this code but it should give you the result. Upvotes: -1 <issue_comment>username_2: You could iterate over the properties of an object like an array: ``` $newdata['rules']=[]; foreach ($data as $key => $value) { if (substr($key,0,6)=='rules_') { // split key using '_' $parts = explode('_',$key); // get the 'name' $name = $parts[1] ; // get the index (-1 to be 0 based) $idx = $parts[2] - 1; // store data in new array $newdata['rules'][$idx][$name] = $value; } } print_r($newdata); ``` Outputs: ``` Array ( [rules] => Array ( [0] => Array ( [field] => 1 [condition] => 0 [value] => text ) [1] => Array ( [field] => 3 [condition] => 1 [value] => another_text ) ) ) ``` Upvotes: 1 <issue_comment>username_3: Here is working code, ``` $data = [ "class" => "srt-fields", "rules_field_1" => "1", "rules_condition_1" => "0", "rules_value_1" => "text", "rules_field_2" => "3", "rules_condition_2" => "1", "rules_value_2" => "another_text", ]; $result = []; foreach ($data as $k => $v) { $num = filter_var($k, FILTER_SANITIZE_NUMBER_INT); if (!empty($num)) { $result['rules'][$num][(str_replace(['rules_', '_'], '', preg_replace('/[0-9]+/', '', $k)))] = $v; } } $result['rules'] = array_values($result['rules']); print_r($result); ``` [str\_replace](http://php.net/manual/en/function.str-replace.php) — Replace all occurrences of the search string with the replacement string [filter\_var](http://php.net/manual/en/function.filter-var.php) — Filters a variable with a specified filter [preg\_replace](http://php.net/manual/en/function.preg-replace.php) — Perform a regular expression search and replace [str\_replace](http://php.net/manual/en/function.str-replace.php) — Replace all occurrences of the search string with the replacement string Here is working [demo](http://sandbox.onlinephpfunctions.com/code/8b0d048ba1b74ec14439ab943c49fdaf6978f475). Upvotes: 1 [selected_answer]<issue_comment>username_4: Definitely do not use regular expressions for this task -- because it is unnecessary resource overhead. Explode the keys on underscores, and use the individual components to construct the multi-level keys in your output array. Code: ([Demo](https://3v4l.org/sSLY0)) ``` $data = (object)[ "class" => "srt-fields", "rules_field_1" => "1", "rules_condition_1" => "0", "rules_value_1" => "text", "rules_field_2" => "3", "rules_condition_2" => "1", "rules_value_2" => "another_text" ]; foreach ($data as $key => $value) { $bits = explode('_',$key); // this will produce a 1-element array from `class` and a 3-element array from others if (isset($bits[2])) { // if element [2] exists, then process the qualifying data $newdata[$bits[0]][$bits[2]-1][$bits[1]] = $value; // ^^- make zero based } } var_export($newdata); ``` Output: ``` array ( 'rules' => array ( 0 => array ( 'field' => '1', 'condition' => '0', 'value' => 'text', ), 1 => array ( 'field' => '3', 'condition' => '1', 'value' => 'another_text', ), ), ) ``` I am using `-1` to make the output keys resemble a zero-based / indexed array. If your fields might not be consecutively ordered, you can remove the `-1` and write `$newdata['rules'] = array_values($newdata['rules']);` after the loop. Upvotes: 0
2018/03/20
692
2,716
<issue_start>username_0: I am new to Android development and I am creating an app for practicing purposes, my app only retrieves data from the webserver and copies it into the SQLite database, but how do I know if there is new data that I don't have in my local DB or it has been updated? Is there any way to tell Android "update this records and insert this new ones else if there aren't any do nothing"? Is the creation of a syncadapter a must or I can do it with `JobScheduler` or Firebase `JobDispatcher`?<issue_comment>username_1: Syncadapter are meant for these operations only, it's mechanism suits the best with your scenario. And for your query: > > Is the creation of a syncadapter a must or I can do it with jobScheduler or Firebase JobDispatcher? > > > You can refer this [answer](https://stackoverflow.com/a/30194606/4878972) Upvotes: 0 <issue_comment>username_2: There are 2 phases: 1. Using Push Notification to notify you application when there is a new piece of data. This will help sync data in real-time. 2. Your database and the server database should have some sign to detect if there is a new record. For instance, you can use an increment id, if the local id is smaller than the server's one, it is time to retrieve updated data.This will help sync data when users are off for a long time and then use the app again. Upvotes: 2 <issue_comment>username_3: > > How do I know if there is new data that I don't have in my local DB or it has been updated? > > > Well, there can be 2 mechanism for your app to know if there is new data which you need to fetch from the remote server and save to local `sqlite` database. Either `Push` or `Poll`. Now, which one to use would depend on the situation. **Polling** - Lets say user is looking a list of items. The users pulls to refresh, then you might choose to make a call to server to check if there is any new data. Or you may choose to continuously poll for new data continuously, which might not be a great idea since it might consume resources which is unnecessary. **Pushing** - When server has a new data, then it can send an [FCM push notification](https://firebase.google.com/docs/cloud-messaging/) with the appropriate data. You can handle the push notification in your app and update the database with the new data. For example, if you have one table only in your local db, you would have unique Id's for each row. You can include the `id` and other relevant information in the FCM message and update the corresponding row in your local db. Decent read: [Poll vs. Push - Any reasons to avoid Push Notifications?](https://stackoverflow.com/questions/20019104/poll-vs-push-any-reasons-to-avoid-push-notifications) Upvotes: 2
2018/03/20
672
2,359
<issue_start>username_0: I'm implementing a on my React Native app. Most of my screens are in a ScrollView. When I add the , it obstructs the content. While I want this bottom area to be "safe", I'd like the user to be able to see the content behind it, otherwise, the space is wasted. How do I implement a "transparent" safe area? **Simplified example:** ``` class ExampleScreen extends Component { render() { return ( Example Example Example (etc) ); } } ``` **Output:** ![](https://i.stack.imgur.com/GXqiJ.png) **Desired Output:** ![](https://i.stack.imgur.com/k8rMR.png)<issue_comment>username_1: You could try react-navigation's SafeAreaView. Just set it's `forceInset` prop to `{ bottom: 'never' }` and you'll see it behaves as your expectation. Example: <https://github.com/react-navigation/react-navigation/blob/master/examples/SafeAreaExample/App.js> Upvotes: 1 <issue_comment>username_2: In most you do not want to have your `ScrollView/FlatList` have as a descendant of a `SafeAreaView`. Instead you only want to wrap your `Header` and `TabBar` into a `SafeAreaView`. Some examples: Instead of this (WRONG EXAMPLE) ```js ``` you only wrap the header ```js ``` Also even if you do not really have a Header, you only want to avoid drawing behind the status bar, you can use the `SafeAreaView` as padding. ```js // <- Now anything after this gonna be rendered after the safe zone ``` Upvotes: 5 <issue_comment>username_3: ``` ... ``` Use this in scrollView Upvotes: -1 <issue_comment>username_4: In `ScrollView`, `contentInsetAdjustmentBehavior` controls inserting this safe area padding. Just set it as `automatic` ``` ``` --- Docs: ``` /** * This property specifies how the safe area insets are used to modify the content area of the scroll view. * The default value of this property must be 'automatic'. But the default value is 'never' until [email protected]. */ contentInsetAdjustmentBehavior?: 'automatic' | 'scrollableAxes' | 'never' | 'always'; ``` Well, even on 0.64 I had to set it manually. Whatever is up with that. Upvotes: 0 <issue_comment>username_5: Maybe this late answer but you can easily use ``` class ExampleScreen extends Component { render() { return ( Example Example Example (etc) ); } } ``` Upvotes: 4 <issue_comment>username_6: ``` <> Text ``` Upvotes: 1
2018/03/20
422
1,327
<issue_start>username_0: While creating an app using React native, in cmd I'm facing the following error message: > > ERROR: npm 5 is not supported yet. > > > `npm WARN deprecated [email protected]`: If using 2.x branch, please upgrade to at least 2.1.6 to avoid a serious bug with socket data flow and an import issue introduced in 2.1.0 `> @expo/[email protected] postinstall C:\Users\Rakesh\proj\node_modules\@expo\ngrok > node ./postinstall.js ngrok - binary unpacked.` npm notice created a lockfile as package-lock.json. You should commit this file. `+ [email protected] added 459 packages in 316.717s`. It looks like you're using npm 5, which was recently released. Create React Native App doesn't work with npm 5 yet, unfortunately. We recommend using npm 4 or yarn until some bugs are resolved. You can follow the known issues with npm 5 at: <https://github.com/npm/npm/issues/16991><issue_comment>username_1: You can downgrade your npm version by following `npm install [email protected] -g` and then try running app again. Upvotes: 3 <issue_comment>username_2: Simply downgrade **npm to 4.6.1** OR **Install Yarn** ``` npm install -g [email protected] ``` **OR** ``` npm install -g yarn ``` Yarn is better but I will prefer to **downgrade npm** because for some reason I'm getting a yarn.lock file error. Upvotes: 2
2018/03/20
1,268
4,313
<issue_start>username_0: ``` xml version="1.0" encoding="UTF-8"? true ``` this is the xml file i have (with multiple key value pairs), i need to get the value "true" in the C# variable "setting\_name" ``` private static bool setting_name = true; ``` This is what i have done so far ``` var setting_name = doc.Descendants("key").Where(k => k.Attribute("name").Value. Equals("setting_name")).Select(e => e.Elements("key")).FirstOrDefault(); ```<issue_comment>username_1: In case you need to get more than 1 pair, I suggest to create dictionary and then perform search: ``` var xDoc = XDocument.Load(filePath); var dict = xDoc.Root.Elements("key").ToDictionary(x => x.Attribute("name").Value, x => x.Value); var setting_name = dict.TryGetValue("setting_name", out var setting_name_str) ? bool.TryParse(setting_name_str, out var setting_name_value) && setting_name_value : false; //default value or exception ``` Upvotes: -1 <issue_comment>username_2: I would suggest to deserialize correctly to your class ``` public class Key { [XmlText] public bool Value { get; set; } [XmlAttribute("name")] public string Setting { get; set; } } [XmlRoot("settings")] public class Settings { [XmlElement("key")] public List Keys { get; set; } public Settings() { Keys = new List(); } } public static void Main(string[] args) { var xml = @"xml version=""1.0"" encoding=""UTF-8""? true "; var serializer = new XmlSerializer(typeof(Settings)); Settings result; using (TextReader reader = new StringReader(xml)) { result = (Settings)serializer.Deserialize(reader); } var res = result.Keys.First(); Console.WriteLine(string.Format("{0}, {1}", res.Setting, res.Value)); } ``` Upvotes: 1 <issue_comment>username_3: Try with xml deserializer. It is better to use it that way. I am not sure about the performance, you will have to check that. But if tomorrow, there is something which is update in your xml, the serialization thing will be more maintainable is what I feel. Use `System.Xml.Serialization` Namespace Classes: ``` [XmlRoot(ElementName="key")] public class Key { [XmlAttribute(AttributeName="name")] public string Name { get; set; } [XmlText] public string Text { get; set; } } [XmlRoot(ElementName="settings")] public class Settings { [XmlElement(ElementName="key")] public Key Key { get; set; } } ``` And then something like this: ``` var path = "path to your xml"; var serializer = new XmlSerializer(typeof(Settings[])); var reader = new StreamReader(path); reader.ReadToEnd(); var settings = (Settings[])serializer.Deserialize(reader); reader.Close(); return settings; ``` Try and check if this works. Note : I have not tested this code snippet. But you can try the idea Upvotes: 0 <issue_comment>username_4: If you are wanting to parse out the "True", you can use this Linq 2 XML: ``` void Main() { var doc = XDocument.Parse("xml version=\"1.0\" encoding=\"UTF-8\"?true"); string boolStr = doc.Root.Elements() .Where(e => e.Name.LocalName == "key" && e.Attribute("name").Value == "setting_name" ) .Single().Value; bool value = bool.Parse(boolStr); } ``` Upvotes: 2 <issue_comment>username_5: Another option can be to to use XPath. See <https://msdn.microsoft.com/en-us/library/ms256086(v=vs.110).aspx>: ``` var xml = @"xml version=""1.0"" encoding=""UTF-8""? true "; var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xml); var keys = xmlDoc.SelectNodes("//settings/key[@name=\"setting_name\"]"); Console.WriteLine(keys[0].InnerText); ``` Upvotes: 1 <issue_comment>username_6: I came up with a simple solution using "[username_5's](https://stackoverflow.com/a/49378922/7434451)" and "[username_4's](https://stackoverflow.com/a/49378705/7434451)" answer, which works really fine for my project with few key value pairs. hope this will help anyone seeing this post ``` xml version="1.0" encoding="UTF-8"? true ``` Code to parse this .xml key value pair to bool ``` var xmlDoc = new XmlDocument(); xmlDoc.Load("settings.xml"); //.xml file path var setting_name = xmlDoc.SelectNodes("//settings/key[@name=\"setting_name\"]"); bool setting_name = bool.Parse(setting_name[0].InnerText); ``` Upvotes: -1 [selected_answer]
2018/03/20
2,521
6,530
<issue_start>username_0: I want to compare dates of each object using `NSPredicate`. If the Object has same dateCreated It will return an array of object which has same dates. In the below Array of dictionary 0 index has the different date as compared to another one how can I get data like that. Ex: ``` { "Data": [ { "id": "c9967156ad8945fba8cc482cd8aad900", "description": "Hi", "dateCreated": "2018-03-20T06:15:11.000+0000", }, { "id": "343e70818044457b884f7ad1907803fa", "description": "The only ", "dateCreated": "2018-03-16T17:22:50.000+0000", }, { "id": "dd542edfaa364e40ae0ef0562b6831be", "description": "The new ", "dateCreated": "2018-03-16T17:10:36.000+0000", }, { "id": "090f43c83e5b42039f70b133d031e715", "description": "The new version ", "dateCreated": "2018-03-16T17:08:07.000+0000", }, { "id": "b2ddb8fa990843a28f0670d2b88e3d01", "description": "Add to the test", "dateCreated": "2018-03-16T17:08:07.000+0000", } ] } ``` **#Edit1**: I am converting dateCreated `String` object to `Date` and then I am using `NSPredicate` for desired data. Currently, I am trying with `NSPredicate` **#Edit2** Currently, I am not using NSPredicate. I am iterating each element of the array and compare its date ``` if let dateCur = dateCreated.dateFromISO8601 { if let datePrev = dateCreatedPrev.dateFromISO8601 { let curLocal = ISO8601.getStringDate(dateCur). // dd/MM/yyyy let prevLocal = ISO8601.getStringDate(datePrev). // dd/MM/yyyy if (curLocal.compare(prevLocal) != .orderedSame { //diffrent }else { //same } } } ``` I am using an extension for achieving it ``` extension Date { func getFormatter() -> DateFormatter { let formatter = DateFormatter() formatter.calendar = Calendar(identifier: .gregorian) formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX" return formatter } var iso8601: String { return Formatter.iso8601.string(from: self) } extension String { var dateFromISO8601: Date? { return Formatter.iso8601.date(from: self) // "Mar 22, 2017, 10:22 AM" } } ``` Can you please help me.<issue_comment>username_1: First of all there is no need to use `NSPredicate` in Swift (except the APIs which require `NSPredicate`). The native `filter` method is more appropriate. I recommend to decode the JSON ``` let jsonString = """ { "Data": [ {"id": "c9967156ad8945fba8cc482cd8aad900", "description": "Hi", "dateCreated": "2018-03-20T06:15:11.000+0000"}, {"id": "343e70818044457b884f7ad1907803fa", "description": "The only ", "dateCreated": "2018-03-16T17:22:50.000+0000"}, {"id": "dd542edfaa364e40ae0ef0562b6831be", "description": "The new ", "dateCreated": "2018-03-16T17:10:36.000+0000"}, {"id": "090f43c83e5b42039f70b133d031e715", "description": "The new version ", "dateCreated": "2018-03-16T17:08:07.000+0000"}, {"id": "b2ddb8fa990843a28f0670d2b88e3d01", "description": "Add to the test", "dateCreated": "2018-03-16T17:08:07.000+0000"} ] } """ ``` into custom structs ``` struct Root : Decodable { private enum CodingKeys : String, CodingKey { case items = "Data" } let items : [Item] } struct Item : Decodable { let id, description : String let dateCreated : Date } ``` The decoder uses a custom date formatter to decode the ISO8601 date properly ``` let data = Data(jsonString.utf8) let decoder = JSONDecoder() let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US_POSIX") dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SZ" decoder.dateDecodingStrategy = .formatted(dateFormatter) do { let result = try decoder.decode(Root.self, from: data) ``` The array is in `result.items`. Now you can `filter` the array by a specific date. In this example the reference date is created hard-coded with `DateComponents`. ``` let components = DateComponents(timeZone: TimeZone(secondsFromGMT: 0), year:2018, month:03, day:16, hour:17, minute:8, second:7) let date = Calendar.current.date(from: components)! let filteredItems = result.items.filter { $0.dateCreated == date } print(filteredItems) } catch { print(error) } ``` If you want to find all matching records for a given date in the array use a loop ``` for item in result.items { let filteredItems = result.items.filter { $0.dateCreated == item.dateCreated } if filteredItems.count > 1 { print(filteredItems) } } ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: You might look into `Dictionary`'s initializer [`init(grouping:by:)`](https://developer.apple.com/documentation/swift/dictionary/2919592-init) which was introduced in **Swift 4**. You should have your objects array. Then you can group them into `[String:Object]` where the `key` will be your `Date` in `yyyy-MM-dd` format as `String`. > > Prerequisites: Your `dateCreated` property should be in `Date` format. > > > ``` let groupedObjectBySameDate = Dictionary(grouping: objects) { (object) -> String in let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" return formatter.string(from: object.dateCreated) } ``` An example: ----------- As I don't know your data structure, I'm providing an easy example that can help you understand what's going on. ``` var dateFormatter: DateFormatter { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SZ" formatter.locale = Locale(identifier: "en_US_POSIX") return formatter } let stringDates = ["2018-03-20T06:15:11.000+0000", "2018-03-16T17:22:50.000+0000", "2018-03-16T17:10:36.000+0000", "2018-03-16T17:08:07.000+0000", "2018-03-16T17:08:07.000+0000"] let dates = stringDates.map { (each) -> Date in return dateFormatter.date(from: each) ?? Date(timeIntervalSinceReferenceDate: 0) } let groupedObjectBySameDate = Dictionary(grouping: dates) { (date) -> String in let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" return formatter.string(from: date) } print(groupedObjectBySameDate) // This will produce: // [ // "2018-03-20": [2018-03-20 06:15:11 +0000], // "2018-03-16": [2018-03-16 17:22:50 +0000, 2018-03-16 17:10:36 +0000, 2018-03-16 17:08:07 +0000, 2018-03-16 17:08:07 +0000] // ] ``` Upvotes: 0
2018/03/20
582
1,855
<issue_start>username_0: I'm new to programming and currently learning C from The C Programming Language by <NAME> and <NAME>. I have a difficult at section 1.8. Why when I'm trying to change ``` for (i = 1; n > 0; --n) ``` into ``` for (i = 1; n > 0; ++n) ``` the output is, ``` 0 1 1 1 2 3 2 2 3 3 2 3 4 2 3 5 2 3 6 2 3 7 2 3 8 2 3 9 2 3 ``` Why this is happen? Here is the full code, ``` #include int power(int m, int n); main(){ int i; for (i = 0; i < 10; ++i) printf("%d %7d %7d\n", i, power(2,i), power(3,i)); return 0; } int power(int base, int n){ int p; for ( p = 1; n > 0; --n) p = p \* base; return p; } ```<issue_comment>username_1: In the power methods' for-loop you decrement n until in some iteration of the loop n is zero (no longer n > 0). If you now change the loop to increment n every iteration, n will continue growing until you get an integer overflow ([Wikipedia: Integer overflow](https://en.wikipedia.org/wiki/Integer_overflow)) and n becomes negative at which point your program will terminate. Upvotes: 0 <issue_comment>username_2: the syntax of for loop is ``` for (initialization expr; test expr; update expr) ``` which means, the first expression will be executed once, the test expression is checked every time for ture or false every time the loop starts, and update expression is evaluated unconditionally on every time loop start. in this case, n-- is evaluated before checking n > 0, which means the loop will stop when n becomes 0. but if you change it to n++, n will keep on increasing every time of the loop, until the integer is overflowed. you can change the loop to the following to get output: ``` for (i = 1; i <= n; ++i) ``` Upvotes: 1
2018/03/20
347
1,264
<issue_start>username_0: I'm working on an application which reads heart rate from the finger using camera lens. I want after it's done with previewing the image to pass the results to a new `Activity`. I want to open the next `Activity` which is `Results.kt`. Here is what I've tried so far: ``` if (Beats != 0) { var intent = Intent(this, Results::class.java) ContextCompat.startActivity(intent) } ```<issue_comment>username_1: You can not use `this` as it's not an `Activity` and therefore not a `Context`. You have to provide a proper `Context` and can also pass flag saying new task: ``` if (Beats != 0) { var intent = Intent(MyClass.this.context, Results::class.java) MyClass.this.context.startActivity(intent) } ``` Here replace `MyClass` with your class name. Not sure if it will work or not. Upvotes: 0 <issue_comment>username_2: As long as you have a proper `Context` available, you can start your `Results` as follow: ``` if (Beats != 0) { var intent = Intent(context, Results::class.java) context.startActivity(intent) } ``` If your non-activity class does not have access to a `Context` right now, you should inject it somewhere (during creation of your object as a passed-in argument for example). Upvotes: 1
2018/03/20
363
1,286
<issue_start>username_0: I have made a npm package for the first time. For my daily dev, I have used `npm start` to start the server and then user can use localhost:3000 to view the pages. When I try to publish that to end users, I can still ask people to use `npm install` > `npm start` to use the package. However, it doesn't sound decent. How can I make people being able to use: ``` npm install myPackage myPackage start ``` to start the server and then they can open localhost: 3000 directly?<issue_comment>username_1: You need to create global package for your module so that it can be installed ``` npm i -g module ``` then provide some config file like gulpfile.js which will be used by your package to carry out the task to start server any other task Upvotes: 0 <issue_comment>username_2: You can make a global module and attach it to a bin command. [Here's the tutorial for that by npm itself](http://blog.npmjs.org/post/118810260230/building-a-simple-command-line-tool-with-npm). In your package.json file, you can add this: ``` "bin": { "your-command": "bin/path/to/js/file.js" } ``` and then whenever the user installs your module globally, then they can directly type in that command and the js file will execute your code. Upvotes: 3 [selected_answer]
2018/03/20
750
2,976
<issue_start>username_0: I have been trying many solutions out there for preventing the soft keyboard from pushing my layout when it appears. However, all solutions did not work. Simply, I want everything in my layout (buttons, imageViews, Background, textViews, textEdits) to stay in place when soft keyboard is shown. I do not care about what it will cover. I tried all of the following and all produced the same output and do not work: 1. (did not work) I tried writing `android:windowSoftInputMode="adjustNothing"` in my `AndroidManifest.xml` 2. (did not work) I tried writing `getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);`in my`onCreate()` though it did not work 3. I tried writing `android:windowSoftInputMode="adjustResize"` in my `AndroidManifest.xml` and also did not work 4. (did not work) I tried writing `android:windowSoftInputMode="stateHidden|adjustPan"` in my `AndroidManifest.xml` 5. (did not work) I also tried writing `android:windowSoftInputMode="stateVisible|adjustPan"` in my `AndroidManifest.xml` All the above solutions produced the following snapshot: The actual layout looks like this (this is what I want it to keep looking when soft keyboard is active): Any idea of how to prevent this? This is my AndroidManifest.xml ``` xml version="1.0" encoding="utf-8"? ``` MainActivity.xml ``` ```<issue_comment>username_1: This work for me ``` getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING); ``` Upvotes: 0 <issue_comment>username_2: Remove your Background image in xml file Set Background image in java file using below code: ``` getWindow().setBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.banner1)); ``` Upvotes: 2 [selected_answer]<issue_comment>username_3: I recently encountered the same thing. While staying in one Activity, sometimes the soft keyboard would cause re-layouts and sometimes it wouldn't, depending on what Fragment I had loaded. Finally I figured it out. It was caused by a RecyclerView being visible: ``` ``` That's it. If the Fragment I had loaded had a visible RecyclerView, the soft keyboard would cause re-layout. If not, it wouldn't. It even causes a re-layout of stuff that isn't part of the Fragment that contains the RecyclerView. That's how it looks in a ConstraintLayout. But it could also be in a RelativeLayout. If its visibility is "gone", the soft keyboard's appearance doesn't cause re-layout. If it's "visible", the soft keyboard's appearance causes a re-layout of the whole Activity. I don't know what versions of Android this "works" on, and I don't know whether it's intentional. I know you don't have one, but maybe something else in your .xml does the same thing, or has a RecyclerView in it. I'd surmise that the presence of the RecyclerView causes the SoftInputMode to be set. You could consider waiting for your view to finish laying out, then changing SoftInputMode, and see if it sticks. Upvotes: 0
2018/03/20
584
2,126
<issue_start>username_0: I am new to javascript and all so pardon me for the mistakes. I am trying to open a pop up for some device discovery. When clicked on the below div, ``` [Discover Device ...](#waitDiscoveryDialog) ``` it opens a pop up like this ``` Device Discovery ================ ### This will search for new Devices. [Cancel](#) ``` My requirement is to send the hi.name='action'; and hi.value='Discover' without the input button in the pop up. Because I am using flask framework and there i use this code ``` if request.method == 'POST': rf = request.form try: action = request.form["action"] except: action = "" if "Discover" == action: //code for discovering the device ``` Then close this pop up and open another pop up with a status like "Device found or not found". Can anyone help me to solve this.? Thanks in advance..<issue_comment>username_1: Please try ``` ``` Upvotes: 0 <issue_comment>username_2: As I can see in your code, there is no user input in the popup and you want to submit a static value. If this is the case, why do you even need to open a popup when it is not doing anything? You can simply write a function triggered on click of button that opens the popup as of now and submit the form. After submission, you can continue your function to open a popup for **"Device found or not found"** For example: ``` This is my popup ================ .myPopup { display: none; position: fixed; top: 0px; bottom: 0px; top: 0px; bottom: 0px; margin: auto; border: 1px solid black; border-radius: 5px; height: 500px; width: 500px; } .showPopup { display: inline-block; } ``` `Discover` ``` function submitForm() { var hi=document.createElement('input'); hi.type='hidden'; hi.name='action'; hi.value='Discover'; settings_form.appendChild(hi); settings_form.submit(); } settings_form[0].addEventListener("submit", function() { document.getElementsByClassName("myPopup")[0].classList.add("showPopup"); }); ``` Let me know if this helps. Upvotes: 2 [selected_answer]
2018/03/20
412
1,417
<issue_start>username_0: I need to have the unique values from a column (column c from sheet1) and have the unique values in an array so that I can reuse them again from that array. I'm new to stak so, please help me.<issue_comment>username_1: Please try ``` ``` Upvotes: 0 <issue_comment>username_2: As I can see in your code, there is no user input in the popup and you want to submit a static value. If this is the case, why do you even need to open a popup when it is not doing anything? You can simply write a function triggered on click of button that opens the popup as of now and submit the form. After submission, you can continue your function to open a popup for **"Device found or not found"** For example: ``` This is my popup ================ .myPopup { display: none; position: fixed; top: 0px; bottom: 0px; top: 0px; bottom: 0px; margin: auto; border: 1px solid black; border-radius: 5px; height: 500px; width: 500px; } .showPopup { display: inline-block; } ``` `Discover` ``` function submitForm() { var hi=document.createElement('input'); hi.type='hidden'; hi.name='action'; hi.value='Discover'; settings_form.appendChild(hi); settings_form.submit(); } settings_form[0].addEventListener("submit", function() { document.getElementsByClassName("myPopup")[0].classList.add("showPopup"); }); ``` Let me know if this helps. Upvotes: 2 [selected_answer]
2018/03/20
617
2,124
<issue_start>username_0: Using API, I am trying to fetch some incident data from a web portal. From portal I am getting multiple incident output. I have written a script to write a print output in a text file. My problem is, currently all incident output is getting stored in a single text file, I want to store this into multiple text file based on per incident. My current code is given below: ``` orig_stdout = sys.stdout f = open ('alerts.txt', 'w') sys.stdout = f #print data for i in data['alert']: print "Alert ID: " + str(i['alertId']) print "Alarm Time: " + i['dateStart'] print "Test Name: " + i['testName'] print "URL: " + i['permalink'] print "Rule ID: " + str(i['ruleId']) print "Rule Name: " + i['ruleName'] print "Test ID: " + str(i['testId']) print "Test Name: " + i['testName'] print "\n" sys.stdout = orig_stdout f.close() ```<issue_comment>username_1: Please try ``` ``` Upvotes: 0 <issue_comment>username_2: As I can see in your code, there is no user input in the popup and you want to submit a static value. If this is the case, why do you even need to open a popup when it is not doing anything? You can simply write a function triggered on click of button that opens the popup as of now and submit the form. After submission, you can continue your function to open a popup for **"Device found or not found"** For example: ``` This is my popup ================ .myPopup { display: none; position: fixed; top: 0px; bottom: 0px; top: 0px; bottom: 0px; margin: auto; border: 1px solid black; border-radius: 5px; height: 500px; width: 500px; } .showPopup { display: inline-block; } ``` `Discover` ``` function submitForm() { var hi=document.createElement('input'); hi.type='hidden'; hi.name='action'; hi.value='Discover'; settings_form.appendChild(hi); settings_form.submit(); } settings_form[0].addEventListener("submit", function() { document.getElementsByClassName("myPopup")[0].classList.add("showPopup"); }); ``` Let me know if this helps. Upvotes: 2 [selected_answer]
2018/03/20
795
2,696
<issue_start>username_0: I have created this code to see how many text boxes have something inputted in it and then to display the total in a message box, I want to know if I can make my below code any smaller by may putting it in a loop? ``` Dim TotalRooms = 0 If String.IsNullOrEmpty(txtRoom1.Text) Then TotalRooms = TotalRooms + 0 Else TotalRooms = TotalRooms + 1 End If If String.IsNullOrEmpty(txtRoom2.Text) Then TotalRooms = TotalRooms + 0 Else TotalRooms = TotalRooms + 1 End If If String.IsNullOrEmpty(txtRoom3.Text) Then TotalRooms = TotalRooms + 0 Else TotalRooms = TotalRooms + 1 End If If String.IsNullOrEmpty(txtRoom4.Text) Then TotalRooms = TotalRooms + 0 Else TotalRooms = TotalRooms + 1 End If If String.IsNullOrEmpty(txtRoom5.Text) Then TotalRooms = TotalRooms + 0 Else TotalRooms = TotalRooms + 1 End If If String.IsNullOrEmpty(txtRoom6.Text) Then TotalRooms = TotalRooms + 0 Else TotalRooms = TotalRooms + 1 End If If String.IsNullOrEmpty(txtRoom7.Text) Then TotalRooms = TotalRooms + 0 Else TotalRooms = TotalRooms + 1 End If If String.IsNullOrEmpty(txtRoom8.Text) Then TotalRooms = TotalRooms + 0 Else TotalRooms = TotalRooms + 1 End If If String.IsNullOrEmpty(txtRoom9.Text) Then TotalRooms = TotalRooms + 0 Else TotalRooms = TotalRooms + 1 End If If String.IsNullOrEmpty(txtRoom10.Text) Then TotalRooms = TotalRooms + 0 Else TotalRooms = TotalRooms + 1 End If MessageBox.Show(TotalRooms) ```<issue_comment>username_1: Please try ``` ``` Upvotes: 0 <issue_comment>username_2: As I can see in your code, there is no user input in the popup and you want to submit a static value. If this is the case, why do you even need to open a popup when it is not doing anything? You can simply write a function triggered on click of button that opens the popup as of now and submit the form. After submission, you can continue your function to open a popup for **"Device found or not found"** For example: ``` This is my popup ================ .myPopup { display: none; position: fixed; top: 0px; bottom: 0px; top: 0px; bottom: 0px; margin: auto; border: 1px solid black; border-radius: 5px; height: 500px; width: 500px; } .showPopup { display: inline-block; } ``` `Discover` ``` function submitForm() { var hi=document.createElement('input'); hi.type='hidden'; hi.name='action'; hi.value='Discover'; settings_form.appendChild(hi); settings_form.submit(); } settings_form[0].addEventListener("submit", function() { document.getElementsByClassName("myPopup")[0].classList.add("showPopup"); }); ``` Let me know if this helps. Upvotes: 2 [selected_answer]
2018/03/20
651
2,286
<issue_start>username_0: I wanted to receive data to my site on React through the API.I did everything as stated in the documentation, performed the installation of `npm install --save woocommerce-api`, created the object with parameters as in the documentation <http://woocommerce.github.io/woocommerce-rest-api-docs/?javascript#pagination> ``` import React, { Component } from 'react'; import '../App.css'; import WooCommerceAPI from 'woocommerce-api'; class Goods extends Component { WooCommerce = new WooCommerceAPI({ url: 'http://portland.com/wp/', // Your store URL consumerKey: '**KEY**', // Your consumer key consumerSecret: '**KEY**', // Your consumer secret wpAPI: true, // Enable the WP REST API integration version: 'wc/v2' // WooCommerce WP REST API version }); render() { return( ![appletv](/images/photo.png) {WooCommerce.get('products/1').name} black $49.99 ); } } export default Goods; ``` But I get `Line 20: 'WooCommerce' is not defined no-undef` Can u help me integrate correctly API in my site?<issue_comment>username_1: Please try ``` ``` Upvotes: 0 <issue_comment>username_2: As I can see in your code, there is no user input in the popup and you want to submit a static value. If this is the case, why do you even need to open a popup when it is not doing anything? You can simply write a function triggered on click of button that opens the popup as of now and submit the form. After submission, you can continue your function to open a popup for **"Device found or not found"** For example: ``` This is my popup ================ .myPopup { display: none; position: fixed; top: 0px; bottom: 0px; top: 0px; bottom: 0px; margin: auto; border: 1px solid black; border-radius: 5px; height: 500px; width: 500px; } .showPopup { display: inline-block; } ``` `Discover` ``` function submitForm() { var hi=document.createElement('input'); hi.type='hidden'; hi.name='action'; hi.value='Discover'; settings_form.appendChild(hi); settings_form.submit(); } settings_form[0].addEventListener("submit", function() { document.getElementsByClassName("myPopup")[0].classList.add("showPopup"); }); ``` Let me know if this helps. Upvotes: 2 [selected_answer]
2018/03/20
315
1,284
<issue_start>username_0: I am working on a custom entity on dynamic 365. This entity is manipulated on Dynamic 365 Portal using web forms. Whenever I am creating a record in the entity, it is showing "System" in out of the box "Created By"column. Can anybody tell me what is the reason behind it?<issue_comment>username_1: Owner, createdby, modifiedby = CRM Login user = systemuser Entity. It can be licensed user, application user (service account), or SYSTEM (only used by CRM product). Portal Login user = contact Entity (sometimes Lead). Records (OOB or custom entity) created in portal will be impersonated by product using SYSTEM user while creating in CRM DB. Because contact cannot be an owner or createdby. This is the reason. You may customize to have another custom attribute called `new_createdby_portal`and use [Entity Form Metadata](https://community.adxstudio.com/products/adxstudio-portals/documentation/configuration-guide/entity-form/entity-form-metadata/) mapping to capture this field from portal side without code. Upvotes: 0 <issue_comment>username_2: As explained above, the owner of a record in CRM is a lookup field to `systemuser` entity. The portal user is actually a `contact`, therefor can not be assigned as record owner. Upvotes: 2 [selected_answer]
2018/03/20
530
1,847
<issue_start>username_0: I have two array, first is month array second is result array, $monthArray = array("Jan 2018,Feb 2018","Mar 2018"); Need to sort the following array in the order of months ``` $result = array( array( "day" => "Feb 2018", "value" => "101" ), array( "day" => "Jan 2018", "value" => "18" ), array( "day" => "Mar 2018", "value" => "0" ) ``` I have to sort result array in month order like below output, ``` Array ( [0] => Array ( [day] => Jan 2018 [value] => 18 ) [1] => Array ( [day] => Feb 2018 [value] => 101 ) [2] => Array ( [day] => Mar 2018 [value] => 0 ) ) ``` I am trying by using sort,usort,ksort php functions but its not working.<issue_comment>username_1: Owner, createdby, modifiedby = CRM Login user = systemuser Entity. It can be licensed user, application user (service account), or SYSTEM (only used by CRM product). Portal Login user = contact Entity (sometimes Lead). Records (OOB or custom entity) created in portal will be impersonated by product using SYSTEM user while creating in CRM DB. Because contact cannot be an owner or createdby. This is the reason. You may customize to have another custom attribute called `new_createdby_portal`and use [Entity Form Metadata](https://community.adxstudio.com/products/adxstudio-portals/documentation/configuration-guide/entity-form/entity-form-metadata/) mapping to capture this field from portal side without code. Upvotes: 0 <issue_comment>username_2: As explained above, the owner of a record in CRM is a lookup field to `systemuser` entity. The portal user is actually a `contact`, therefor can not be assigned as record owner. Upvotes: 2 [selected_answer]
2018/03/20
692
2,113
<issue_start>username_0: I'm trying to write a simple logger using variadic templates for my understanding. It works, but with a catch. ``` void log() { std::cout << std::endl; } // variadic Template template void log(T t1, Args... args) { std::cout << t1<<" "; log(args...); } int main() { log("Logging", 1, 2, 3.2, 4); return 0; } ``` This is not outputting the last parameter `'4'` in the console. The output for this is `Logging 1 2 3.2` When I debugged, it's not entering the 'empty' log function at all. In fact, it compiles and gives the same output without that empty `log()` function. Can someone please explain why this is behaving that way?<issue_comment>username_1: In Visual Studio is it better to use namespace for similar with std function names In global namespace call of `log(4)` evaluates to macro `_GENERIC_MATH1(log, _CRTDEFAULT)` defined in `xtgmath.h` [![enter image description here](https://i.stack.imgur.com/CJSlQ.png)](https://i.stack.imgur.com/CJSlQ.png) ``` #include // - this indirectly includes macro \_GENERIC\_MATH1 from ^^^^^^^ namespace mylog{ void log() {} // variadic Template template void log(T t1, Args... args) { std::cout << t1 << " "; log(args...); // calling log with parameter pack // but the last call is log(4) // which is calling macro \_GENERIC\_MATH1 in global namespace } } int main() { mylog::log("Logging", 1, 2, 3.2, 4); return 0; } ``` For additional information have a look at the [username_2](https://stackoverflow.com/users/440558/some-programmer-dude) answer. Upvotes: 2 <issue_comment>username_2: The problem is that Visual C++ pulls in [`std::log`](http://en.cppreference.com/w/cpp/numeric/math/log) into the global namespace. Your chain of calls **should** be ``` log("Logging", 1, 2, 3.2, 4); log(1, 2, 3.2, 4); log(2, 3.2, 4); log(3.2, 4); log(4); log(); ``` The problem with Visual C++ is that the next to last call, `log(4)`, is really `std::log(4)`, which of course will not call your own `log` function. The simplest solution is to rename your function as something else. Upvotes: 3 [selected_answer]
2018/03/20
713
2,323
<issue_start>username_0: I have component using PrimeNg p-dropdown. html code: ``` ``` ts portNames decleration: ``` portNames: string[] =["Port 01","Port 02", "Port 03"]; ``` My Problem is that DropDown Does not Display Values "Port 01","Port 02", "Port 03". Maybe I have any mistake?<issue_comment>username_1: `portNames` should be an array of objects composed of a label and a value (not an array of strings) : ``` portNames = [ {label:'Port 01', value:'p01'}, {label:'Port 02', value:'p02'}, {label:'Port 03', value:'p03'} ]; ``` See [Plunker](https://plnkr.co/edit/Sc4jqnS8K8oAVCByWKMn?p=preview) Upvotes: 3 <issue_comment>username_2: Try adding your dropdown values in label and values ``` portNames =[ {label:'Port 01', value:'Port 01'}, {label:'Port 02', value:'Port 02'}, {label:'Port 03', value:'Port 03'}, ]; ``` Upvotes: 5 [selected_answer]<issue_comment>username_3: Its not necessary to use label and value in dropdown values. You can set optionLabel attribute in p-dropdown. This means value will be read from objects property the same as set in optionLabel attribute and will show up when calling item.label or selectedItem.label. Upvotes: 2 <issue_comment>username_4: Getting PrimeNG p-dropdown to work with array of strings is possible, though it is not well documented. I use it sometimes when selecting timezones. There might be cleaner options, but I use ng-template to populate the dropdown and onChange to store the selected string value: **HTML** ``` {{item}} {{item}} ``` **Component.ts** ``` portNames: string[] =["Port 01","Port 02", "Port 03"]; selectedPort=""; storeValue(event) { console.log(event); //event.value will likely be undefined, check event.originalEvent this.selectedPort = event.originalEvent.srcElement.innerText; } ``` Upvotes: 1 <issue_comment>username_5: I have a mix response for this that it works for me. **HTML** ``` {{item.item}} {{item.item}} ``` **Component** ``` portNames = [ {label:'Port 01', value:'p01'}, {label:'Port 02', value:'p02'}, {label:'Port 03', value:'p03'} ]; selectedPort=""; storeValue(event) { console.log("Selected item value:", event.event.value); this.selectedPort = event.event.value; } ``` Upvotes: 0
2018/03/20
964
3,689
<issue_start>username_0: I have news details inserted and i need to show it on the edit page but when i try to edit and delete it shows blanks page insert and show is working properly. i have been stucked on this from morning. id is getting from the database but it shows a blank page,Not using any Form helper 1.what's problem,is it on route file 2.is it on Controller file route.php ``` Route::get('/', function () { return view('welcome'); }); Route::resource('books','BookController'); Route::resource('news','NewsController'); Auth::routes(); Route::get('/news','NewsController@index')->name('news'); //Route::get('/news/create','NewsController@create'); //Route::get('/news/edit','NewsController@edit'); ``` Edit.blade.php ``` @extends('theme.default') @section('content') NEW BEE NEWS DETAILS {{csrf\_field()}} NEWS TITLE Example: SELFY PLAYSHARE NEWS news}}> DETAILED NEWS HERE NEWS LINK Example: https://play.google.com/store/apps/selfyplusure NEWS IMAGE ADD NEWS @endsection ``` NewsController.php ``` php namespace App\Http\Controllers; use Illuminate\Support\Facades\Auth; use App\News; use Illuminate\Http\Request; class NewsController extends Controller { public function index() { $news = News::all(); return view('news.index', ['news' = $news]); } public function create() { return view('news.create'); } public function store(Request $request) { $news=new News(); if($request->hasFile('addimage')){ $request->file('addimage'); $imagename=$request->addimage->store('public\newsimage'); $news->name = $request->input('atitle'); $news->alink = $request->input('alink'); $news->news = $request->input('news'); $news->imagename = $imagename; $news->save(); if($news) { return $this->index(); } } else{ return back()->withInput()->with('error', 'Error Creating News '); } } public function show(News $news) { // } public function edit(News $news) { $news=News::findOrFail($news->id); return view('news.edit',['News'=>$news]); } public function update(Request $request, $id) { $news = News::findOrFail($id); // update status as 1 $news->status = '1'; $news->save(); if ($news) { // insert datas as new records $newss = new News(); //On left field name in DB and on right field name in Form/view $newss->name = $request->input('atitle'); $newss->alink = $request->input('alink'); $newss->news = $request->input('news'); $newss->imagename = $request->input('addimage'); $newss->save(); if ($newss) { return $this->index(); } } } public function destroy($id) { $news = News::findOrFail($id); $news->status = '-1'; $news->save(); if ($news) { return $this->index(); } else{ return $this->index(); } } } ``` Link to delete and Edit ``` | | ```<issue_comment>username_1: In your controller try to use this. return view('news.edit',compact('news')); Upvotes: 0 <issue_comment>username_2: This is the link to edit ``` | ``` For delete please go through [Delete](https://stackoverflow.com/questions/33747583/delete-in-laravel-with-get-using-routeresource) Upvotes: 2 [selected_answer]
2018/03/20
1,026
4,149
<issue_start>username_0: I am a beginner and I am making a simple android game in which a user sign in into the app and play the game. After the game finishes I want to add the current score of the user with previous score and then store this total score in Firebase and then again retrieve the score next time when the user plays game. I am not getting on how should I save the Total score for every different user who sign in. this is my firebase json tree <https://drive.google.com/file/d/1T7-x3TP1TaA8_ntwfoRNdb2oMGV_swl6/view?usp=sharing> ``` private void updateScore() { TotalScore = new Firebase("https://bscitquiz.firebaseio.com/Users/" + username +"/highScore"); TotalScore.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Integer totalscore = dataSnapshot.getValue(Integer.class); totalscore = totalscore + mScore; dataSnapshot.getRef().setValue(totalscore); HighScore.setText("" +totalscore); } @Override public void onCancelled(FirebaseError firebaseError) { } }); } ```<issue_comment>username_1: You can have a path for score under User (for Eg: User/userId/score) where you can update the score each time after completing the game. Below is the javascript code. ``` firebase.database().ref('User').child(userId).child('score').set(currentScore).then(result => { const user = snap.val() const userKey = snap.key }).catch (function(err) { console.error(err) }) ``` Here currentScore is the value you want to update. You can go through this link if you want it in android: <https://firebase.google.com/docs/database/android/read-and-write> Upvotes: 0 <issue_comment>username_2: You can save each user's score under its name at the database and just update it each time. the android java code is written like this - ``` public static void updateScore(Integer score, String userId) { DatabaseReference ref = FirebaseDatabase.getInstance().getReference(); ref.child("Users").child(userId).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Integer previousScore = dataSnapshot.getValue(Integer.class); if (previousScore != null){ previousScore = previousScore + score; dataSnapshot.getRef().setValue(previousScore); } } @Override public void onCancelled(DatabaseError databaseError) { Log.e("frgrgr", "onCancelled", databaseError.toException()); } }); } ``` This way you retrieve the old score, update it, and send back to the database. Now at this way you have only the score value under each user. You can use the user's name for the child ref of "Users" if its unique or just generate an Id for each user. **Edit after understanding your need for a callback -** [callback in android?](https://stackoverflow.com/questions/2566852/callback-in-android) For adding a callback there are a few steps, 1. open a new java class with the following code - ``` public interface FireBaseCallbacks { interface GetScoreCallback { public void onGetScoreComplete(Integer score) } } ``` 2. add the callback parameter to your updateScore method - ``` private void updateScore(FireBaseCallbacks.GetDevicesCallback callback) { ... } ``` 3. call the callback parameter after you get the value - ``` Integer totalscore = dataSnapshot.getValue(Integer.class); callback.onGetScoreComplete(totalscore) ``` 4. call the method somewhere in your activity (at the point that you want to update the score) with this as a parameter to tell the callback where to come back to (regarding the activity) - ``` updateScore(this) ``` 5. now for the last step, implement the FireBaseCallbacks.GetScoreCallback to your activity and then you'll be forced to implement its onGetScoreComplete method. implement it and inside it you get the score as a parameter to do what ever you wish :) Hope this will help, let me know otherwise. Upvotes: 1
2018/03/20
334
1,222
<issue_start>username_0: I am trying to use ubuntu for php laravel project, I have setup all the requirements but now I am facing problem with gitkraken. I am trying to clone repo on var/www/html but I cant even enter in var folder please help [![enter image description here](https://i.stack.imgur.com/wh5Wb.png)](https://i.stack.imgur.com/wh5Wb.png)<issue_comment>username_1: You need to uninstall this application and install it from the [website](https://www.gitkraken.com/download).. the same happened with me .. for the main reason why this is happening .. you may check this answer [askUbuntu](https://askubuntu.com/questions/419610/permission-of-a-desktop-file) Upvotes: 4 [selected_answer]<issue_comment>username_2: Although the accepted answer is not technically incorrect, it did not actually solve the problem for me when running Ubuntu 18.04. You need to install the application from the website, but you MUST do so using the command-line like so: ``` wget https://release.gitkraken.com/linux/gitkraken-amd64.deb sudo dpkg -i gitkraken-amd64.deb ``` If you try to install it by just double-clicking the .deb file in your home directory, it will not work as snap does some funky things with it. Upvotes: 1
2018/03/20
592
2,197
<issue_start>username_0: I am working on a Code Receipt Number Auto Generate. Here is my code: ``` var conrecipt = new SqlConnection( ConfigurationManager.ConnectionStrings["con"].ConnectionString); conrecipt.Open(); var cmd = new SqlCommand("Select COALESCE(MAX(Reciptno),0) from Registration", conrecipt); int i = Convert.ToInt32(cmd.ExecuteScalar()); conrecipt.Close(); i++; Label3.Text = Reciptno + i.ToString(); ``` It's working fine. But I need to check 3 tables : Registration, Advance and one more table and need to find max from those id's. How can I do this in Asp.Net C# and MS SQL Server 2012?<issue_comment>username_1: You could use union for obtain all the reciptno and the select the max ``` select COALESCE(MAX(Reciptno),0) from ( Select Reciptno from Registration UNION Select Reciptno from Advance UNION Select Reciptno from one_more_table ) as t ``` AND If you have nvarchar you could use a convert ``` select COALESCE(MAX( convert (int, t.Reciptno)),0) from ( Select Reciptno from Registration UNION Select Reciptno from Advance UNION Select Reciptno from one_more_table ) as t ``` Upvotes: 2 <issue_comment>username_2: ``` SELECT MAX(M) FROM ( SELECT MAX(Value) as M Table1 UNION ALL SELECT MAX(Value) as M Table2 UNION ALL SELECT MAX(Value) as M Table3 ) as x ``` And in general it is more correct to use a sequence for all three tables and there will be no problems with the definition of a new value Upvotes: 2 <issue_comment>username_3: Use a stored procedure to implement the ID logic. In the stored proc you could find the IDs from all the relevant tables and calculate the maximum ID. You would then call the stored procedure from the app. For an even better solution, have a read about entity relationship design. Receipt is an entity that should define receipts including its ID (primary key) in one place. If Receipt Id is used in other tables this is called a foreign key which should be enforced in the database ensuring that every ID referenced in a table already exists in the "master" receipt table. Upvotes: 1 [selected_answer]
2018/03/20
371
1,536
<issue_start>username_0: I change the scheme to Apple Watch and hit run, the watch simulator shows up but my app icon is not even seen on the home screen of watch. I have been trying for days now. I tried **cleaning project, cleaning build folder, removing derived data, removing files in the watchOS DeviceSupport, restarting Xcode(9.2), restarting Apple Watch Simulator** *(External Displays option does not shows Apple Watch Alternatives by the way)* Can you help with the possibilities that might cause this issue? What else should I try? *Xcode does not launch my app on the watch simulator* :/ this is the summary of the issue.<issue_comment>username_1: On the iOS(iPhone) simulator launch the Apple "Apple Watch" app (not your app) scroll all the way down to the buttom, down there your app should have a loading icon next to it, wait 20 minutes if the icon haven't shown up on the watch, restart your computer, with the option to relaunch all apps ticked to off, launch xcode, then try the above mentioned. Upvotes: 1 <issue_comment>username_2: When trying out my first watchOS app, I was seeing the same behaviour. I could not find the app's icon in the simulator. The following is what I did. * I stopped the app in Xcode. * Launched it again. * This time I opened the main app in the iPhone simulator also. * The icon for the app appeared in the watch simulator among other apps and the app launched. * For ~10 seconds a loading indicator was shown. I was able to continue debugging normally from then on. Upvotes: 0
2018/03/20
826
2,600
<issue_start>username_0: I don't know why my website's Schema.org markup is showing number and characters instead of stars. For example, it's showing "3 out of 5" instead of "\*\*\*". ![](https://i.stack.imgur.com/TbF9e.png) How can I fix it? I'm using WordPress and All In One Schema Rich Snippets plugin.<issue_comment>username_1: Suffered with same problem. Finally after lot of search and trial I came up with this solution. This gets the template where the rating is displayed from. But it displays like this: `Rated 4.50 out of 5 based on 2 customer ratings (2 customer reviews)` ``` php wc\_get\_template( 'single-product/rating.php' ); ? ``` Then paste this css code in a custom css. ``` /*star rating for products*/ .rating-custom div.product .woocommerce-product-rating { margin-bottom: 1.618em; } .rating-custom .woocommerce-product-rating .star-rating { margin: .5em 4px 0 0; float: left; } .rating-custom .woocommerce-product-rating::after, .rating-custom .woocommerce-product-rating::before { content: ' '; display: table; } .rating-custom .woocommerce-product-rating { line-height: 2; } .rating-custom .star-rating { float: right; overflow: hidden; position: relative; height: 1em; line-height: 1; font-size: 1em; width: 5.4em; font-family: star; } .rating-custom .star-rating::before { content: '\73\73\73\73\73'; color: #d3ced2; float: left; top: 0; left: 0; position: absolute; } .rating-custom .star-rating { line-height: 1; font-size: 1em; font-family: star; } .rating-custom .star-rating span { overflow: hidden; float: left; top: 0; left: 0; position: absolute; padding-top: 1.5em; } .rating-custom .star-rating span::before { content: '\53\53\53\53\53'; top: 0; position: absolute; left: 0; } .rating-custom .star-rating span { overflow: hidden; float: left; top: 0; left: 0; position: absolute; padding-top: 1.5em; } ``` Output: [![rating output](https://i.stack.imgur.com/sOpd2.png)](https://i.stack.imgur.com/sOpd2.png) Upvotes: 2 <issue_comment>username_2: Am using elementor page builder and I encountered the same problem.Turns out that the problem arises when your are trying to display the star rating on a page other than woocommerce single product pages. Solution: assign `class="woocommerce"` to the elementor widget that you are using to place the star rating. It could be the shortcode widget, html, text editor or anything crazy you are trying to do with elementor Upvotes: 0
2018/03/20
226
860
<issue_start>username_0: I want to my HTML5 template support RTL (Right to Left). But I do not know how to do it. If someone helps me, then I will know it.<issue_comment>username_1: Basically you have to setup `dir=rtl` in your html for this like below: ``` ... ``` Add dir="rtl" to the html tag any time the overall document direction is right-to-left. This sets the base direction for the whole document. No dir attribute is needed for documents that have a base direction of left-to-right, since this is the default. Here is one very nice article to achieve RTL in your HTML template : <https://www.w3.org/International/questions/qa-html-dir> Upvotes: 2 <issue_comment>username_2: you apply ``` ``` You should apply rtl css file (framework) , from CDN otherwise download locally and give the path of file regarding in your working file. Upvotes: 1
2018/03/20
684
2,291
<issue_start>username_0: I know that if I want to check if an array does contain a certain value I should use `Arrays.asList(arrayName).contains(valueName)`. But how do I check if that value is not present? At first I just thought of putting ! in front like: ``` !Arrays.asList(arrayName).contains(valueName) ``` but that doesn't seem to work. I even tried writing the if statement like this: ``` if (Arrays.asList(arrayName).contains(valueName)==false) ``` but that doesn't seem to work either. Here is the code: ``` public int[] duplikati(int[] tabela){ int len = tabela.length; int c = 0; int[] count = new int[len]; for (int i=0;i ```<issue_comment>username_1: You can use Java 8 stream api as follows ``` Integer arr[]=new Integer[]{1,2,30,61}; System.out.println(Arrays.asList(arr).stream().noneMatch(element>element==10)); ``` You can go through the below link for explaination of [noneMatch()](https://beginnersbook.com/2017/11/java-8-stream-nonematch-example/) Upvotes: 0 <issue_comment>username_2: In, this specific case when you pass an array of primitive types into `Arrays.asList` you'll get back a List with a *single* element which is the provided array. So, when you do: ``` Arrays.asList(arrayName).contains(valueName) ``` The call `Arrays.asList(arrayName)` will return a `List` and then when you call `contains` the `valueName` will get boxed to an `Integer` and then get's compared with the element(s) in the list. because an `int[]` is never equal to an integer value, the `contains` call will always return `false`. Solution 1 - change the type of your arrays from `int[]` to `Integer[]`, then everything should work as you expect. Solution 2 - Assuming you do not want to change the type of the arrays for some reason, then you can do: ``` final int index = i; if(Arrays.stream(count).noneMatch(e -> e == tabela[index])){...} ``` inside the for loops. You can think of the `noneMatch` method as `!Arrays.asList(someArray).contains(someValue)` if it helps. Similarly, you can check if the array contains an element with: ``` final int index = i; if(Arrays.stream(count).anyMatch(e -> e == tabela[index])){...} ``` You can think of the `anyMatch` method as `Arrays.asList(someArray).contains(someValue)` if it helps. Upvotes: 1
2018/03/20
402
1,616
<issue_start>username_0: I am simultaneously doing speech to text and text to speech within an app but for some reason after Speech to conversion is over and the result for which is back from server , text to speech [default API of apple] doesn't produce any sound even though it reproduces same for static text at start of app. Here is the below code for text to speech conversion. ``` -(void)makeTextTalk:(NSString *)phraseToSpeak{ [self stopTalkingAPI]; AVSpeechSynthesizer *synthesizer = [[AVSpeechSynthesizer alloc]init]; AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc]initWithString:phraseToSpeak]; AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-IN"]; utterance.voice = voice; [synthesizer speakUtterance:utterance]; } ```<issue_comment>username_1: U Need to change AVAudioSessionMode to default once Speech To text process gets completed. Change it using this : ``` AVAudioSession *audioSession = [AVAudioSession sharedInstance]; [audioSession setCategory:AVAudioSessionCategoryPlayback]; [audioSession setMode:AVAudioSessionModeDefault error:nil]; ``` Upvotes: -1 <issue_comment>username_2: ``` _audioSession = [AVAudioSession sharedInstance]; [_audioSession setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker error:nil]; [_audioSession setMode:AVAudioSessionModeDefault error:nil]; ``` Finally , this solved it. Session Category must be AVSessionCategoryPlayAndRecord if TTS and STT is continuously working and the function must be called with set options parameter. Upvotes: 3 [selected_answer]
2018/03/20
656
2,466
<issue_start>username_0: I need to read `web.config` file, outside the application's folder (located in any other directory). I tried this code: ``` string filePath = @"C:\Users\Idrees\Downloads\New folder\Web.config"; Configuration c1 = ConfigurationManager.OpenExeConfiguration(filePath); var value1 = c1.AppSettings.Settings["Key1"].Value; ``` But it is giving me the error: > > Object reference not set to an instance of an object. > > > Because here, `c1.AppSettings` is an object, but `c1.AppSettings.Settings` contains not items (hence `0` Count). It is not really loading the `AppSettings` keys. When trying to read any `Key` from `Settings` collection, it gives this error. Is there any way how to load `AppSettings` keys from a `web.config` file outside the application folder. If I put same file within application folder, then it reads the keys successfully. This is my sample config file's content: ``` xml version="1.0" encoding="utf-8"? ``` I have a web application already running on my server. And I need to develop a small utility which has to do some job in database, and I don't want to write db credentials or connection string(and some other additional app-settings) in each application, I want it to read same thing from web.config.<issue_comment>username_1: Read documentation: [ConfigurationManager.OpenExeConfiguration on MSDN](https://msdn.microsoft.com/en-us/library/ms224437(v=vs.110).aspx) ``` public static Configuration OpenExeConfiguration( string exePath ) ``` > > This is EXE path > > > Upvotes: 1 <issue_comment>username_2: You can using `ConfigurationManager` to read arbitrary configuration files by opening a *mapped* exe configuration as follows: ``` var filePath = @"C:\Users\Idrees\Downloads\New folder\Web.config"; var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = filePath }; var configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); var value = configuration.AppSettings.Settings["Key1"].Value; ``` Upvotes: 4 [selected_answer]<issue_comment>username_3: As I understand from your comment you want some kind of shared configuration accross multiple app on the same computer. You may consider using external file like this : ``` xml version="1.0" encoding="utf-8" ? ``` in above .config example connectionStrings is sourced from an other file. Below an example what can be such an external config file: ``` ``` Upvotes: 2
2018/03/20
628
2,071
<issue_start>username_0: I have a problem in calculating the TOTAL. Although it works BUT when i try to remove a single row, the value is still there. It is still calculated by the total. How can i fix this? When i remove a single row, only the rows that are there, is calculated for the TOTAL? Here's my stackblitz code link [CODE LINK HERE](https://stackblitz.com/edit/angular-h2wdfz?file=app/app.component.ts) ``` ngOnInit(){ this.myForm.get('rows').valueChanges.subscribe(values => { resolvedPromise.then(() => { this.total = this.totals.reduce((sum, item) => sum + item.total, 0); }); }) } onDeleteRow(rowIndex) { let rows = this.myForm.get('rows') as FormArray; rows.removeAt(rowIndex) } ```<issue_comment>username_1: In OnDeleteRow you have: 1.-Delete the totals[rowIndex] 2.-recalculate total ``` onDeleteRow(rowIndex) { let rows = this.myForm.get('rows') as FormArray; rows.removeAt(rowIndex); this.totals.splice(rowIndex,1); //<--remove the totals[rowIndex] this.total=this.totals.reduce((sum,item)=>sum+item.total,0); //<--recalculate total } ``` Upvotes: 1 [selected_answer]<issue_comment>username_1: Yhe problem is that, the Changes depending about "i", we can add the property "material\_id to totals and change the function setOnChange ``` //When we create the "totals" //add the property "material_id" to Total material.materials.forEach(x => { rows.push(this.fb.group({ ... })) this.totals.push({amount:0,total:0,material_id:x.id}); //<--add the property material_id }) //then, in the function setOnChange setOnChange() { const formarray=this.myForm.get('rows') as FormArray; for (let i=0;i{ //search the index of "material\_id" let index=this.totals.findIndex(t=>t.material\_id==val.material\_id) if(val.dis\_checkbox){ ... this.totals[index].amount=value; //<--NOT this.totals[i], this.totals[index].total=values; } else { .... this.totals[index].amount=value; this.totals[index].total=value; } }); } } ``` Upvotes: 1
2018/03/20
602
2,116
<issue_start>username_0: When I connect to my Windows Server 2012R2 Azure VM via RDP, I have resolution 1600x900, which corresponds to my client PC resolution. However, when I run selenium UI tests on this machine with VSO agent, they are failing because screen resolution for agent session is 1024x768. In Device manager I can see that display adapter is Microsoft Hyper-V Video. When I access Screen Resolution section when connected via RDP, I can see only my resolution selected and grayed out and also message "The display settings can't be changed from a remote session". Is it possible to change default screen resolution for Windows Server 2012R2 running on Azure VM? I tried adding DefaultSettings.XResolution and DefaultSettings.YResolution values to registry but it didn't help.<issue_comment>username_1: In OnDeleteRow you have: 1.-Delete the totals[rowIndex] 2.-recalculate total ``` onDeleteRow(rowIndex) { let rows = this.myForm.get('rows') as FormArray; rows.removeAt(rowIndex); this.totals.splice(rowIndex,1); //<--remove the totals[rowIndex] this.total=this.totals.reduce((sum,item)=>sum+item.total,0); //<--recalculate total } ``` Upvotes: 1 [selected_answer]<issue_comment>username_1: Yhe problem is that, the Changes depending about "i", we can add the property "material\_id to totals and change the function setOnChange ``` //When we create the "totals" //add the property "material_id" to Total material.materials.forEach(x => { rows.push(this.fb.group({ ... })) this.totals.push({amount:0,total:0,material_id:x.id}); //<--add the property material_id }) //then, in the function setOnChange setOnChange() { const formarray=this.myForm.get('rows') as FormArray; for (let i=0;i{ //search the index of "material\_id" let index=this.totals.findIndex(t=>t.material\_id==val.material\_id) if(val.dis\_checkbox){ ... this.totals[index].amount=value; //<--NOT this.totals[i], this.totals[index].total=values; } else { .... this.totals[index].amount=value; this.totals[index].total=value; } }); } } ``` Upvotes: 1
2018/03/20
4,633
20,889
<issue_start>username_0: how to open activity to display message push notification android, i make project to push notification android, i send from php web and recieve on android, it just show the notification help me to display all message when we click the notification thank you. mainactivity.java ``` package com.example.jordi.notifi.activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.support.v4.content.LocalBroadcastManager; import android.text.TextUtils; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.messaging.FirebaseMessaging; import com.example.jordi.notifi.R; import com.example.jordi.notifi.app.Config; import com.example.jordi.notifi.util.NotificationUtils; public class MainActivity extends AppCompatActivity { private static final String TAG = MainActivity.class.getSimpleName(); private BroadcastReceiver mRegistrationBroadcastReceiver; private TextView txtRegId, txtMessage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txtRegId = (TextView) findViewById(R.id.txt_reg_id); txtMessage = (TextView) findViewById(R.id.txt_push_message); mRegistrationBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // checking for type intent filter if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) { // gcm successfully registered // now subscribe to `global` topic to receive app wide notifications FirebaseMessaging.getInstance().subscribeToTopic(Config.TOPIC_GLOBAL); displayFirebaseRegId(); } else if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) { // new push notification is received String message = intent.getStringExtra("message"); Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show(); txtMessage.setText(message); } } }; displayFirebaseRegId(); } // Fetches reg id from shared preferences // and displays on the screen private void displayFirebaseRegId() { SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0); String regId = pref.getString("regId", null); Log.e(TAG, "Firebase reg id: " + regId); if (!TextUtils.isEmpty(regId)) txtRegId.setText("Firebase Reg Id: " + regId); else txtRegId.setText("Firebase Reg Id is not received yet!"); } @Override protected void onResume() { super.onResume(); // register GCM registration complete receiver LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, new IntentFilter(Config.REGISTRATION_COMPLETE)); // register new push message receiver // by doing this, the activity will be notified each time a new message arrives LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, new IntentFilter(Config.PUSH_NOTIFICATION)); // clear the notification area when the app is opened NotificationUtils.clearNotifications(getApplicationContext()); } @Override protected void onPause() { LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver); super.onPause(); } } ``` myfirebasemessagingservice.java ``` package com.example.jordi.notifi.service; import android.content.Context; import android.content.Intent; import android.support.v4.content.LocalBroadcastManager; import android.text.TextUtils; import android.util.Log; import com.example.jordi.notifi.activity.MainActivity; import com.example.jordi.notifi.app.Config; import com.example.jordi.notifi.util.NotificationUtils; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import org.json.JSONException; import org.json.JSONObject; /** * Created by Jordi on 15/03/2018. */ public class MyFirebaseMessagingService extends FirebaseMessagingService { private static final String TAG = MyFirebaseMessagingService.class.getSimpleName(); private NotificationUtils notificationUtils; @Override public void onMessageReceived(RemoteMessage remoteMessage) { Log.e(TAG, "From: " + remoteMessage.getFrom()); if (remoteMessage == null) return; // Check if message contains a notification payload. if (remoteMessage.getNotification() != null) { Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody()); handleNotification(remoteMessage.getNotification().getBody()); } // Check if message contains a data payload. if (remoteMessage.getData().size() > 0) { Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString()); try { JSONObject json = new JSONObject(remoteMessage.getData().toString()); handleDataMessage(json); } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); } } } private void handleNotification(String message) { if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) { // app is in foreground, broadcast the push message Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION); pushNotification.putExtra("message", message); LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification); // play notification sound NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext()); notificationUtils.playNotificationSound(); }else{ // If the app is in background, firebase itself handles the notification } } private void handleDataMessage(JSONObject json) { Log.e(TAG, "push json: " + json.toString()); try { JSONObject data = json.getJSONObject("data"); String title = data.getString("title"); String message = data.getString("message"); boolean isBackground = data.getBoolean("is_background"); String imageUrl = data.getString("image"); String timestamp = data.getString("timestamp"); JSONObject payload = data.getJSONObject("payload"); Log.e(TAG, "title: " + title); Log.e(TAG, "message: " + message); Log.e(TAG, "isBackground: " + isBackground); Log.e(TAG, "payload: " + payload.toString()); Log.e(TAG, "imageUrl: " + imageUrl); Log.e(TAG, "timestamp: " + timestamp); if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) { // app is in foreground, broadcast the push message Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION); pushNotification.putExtra("message", message); LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification); // play notification sound NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext()); notificationUtils.playNotificationSound(); } else { // app is in background, show the notification in notification tray Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class); resultIntent.putExtra("message", message); // check for image attachment if (TextUtils.isEmpty(imageUrl)) { showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent); } else { // image is present, show notification with image showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, resultIntent, imageUrl); } } } catch (JSONException e) { Log.e(TAG, "Json Exception: " + e.getMessage()); } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); } } /** * Showing notification with text only */ private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) { notificationUtils = new NotificationUtils(context); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); notificationUtils.showNotificationMessage(title, message, timeStamp, intent); } /** * Showing notification with text and image */ private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) { notificationUtils = new NotificationUtils(context); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl); } } ``` myfirebaseinstanceIDservice.java ``` package com.example.jordi.notifi.service; import android.content.Intent; import android.content.SharedPreferences; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import com.example.jordi.notifi.app.Config; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; /** * Created by Jordi on 15/03/2018. */ public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService { private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName(); @Override public void onTokenRefresh() { super.onTokenRefresh(); String refreshedToken = FirebaseInstanceId.getInstance().getToken(); // Saving reg id to shared preferences storeRegIdInPref(refreshedToken); // sending reg id to your server sendRegistrationToServer(refreshedToken); // Notify UI that registration has completed, so the progress indicator can be hidden. Intent registrationComplete = new Intent(Config.REGISTRATION_COMPLETE); registrationComplete.putExtra("token", refreshedToken); LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete); } private void sendRegistrationToServer(final String token) { // sending gcm token to server Log.e(TAG, "sendRegistrationToServer: " + token); } private void storeRegIdInPref(String token) { SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0); SharedPreferences.Editor editor = pref.edit(); editor.putString("regId", token); editor.commit(); } } ``` Notificationutils.java ``` package com.example.jordi.notifi.util; import android.app.ActivityManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import android.support.v4.app.NotificationCompat; import android.text.Html; import android.text.TextUtils; import android.util.Patterns; import com.example.jordi.notifi.R; import com.example.jordi.notifi.app.Config; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; /** * Created by Jordi on 15/03/2018. */ public class NotificationUtils { private static String TAG = NotificationUtils.class.getSimpleName(); private Context mContext; public NotificationUtils(Context mContext) { this.mContext = mContext; } public void showNotificationMessage(String title, String message, String timeStamp, Intent intent) { showNotificationMessage(title, message, timeStamp, intent, null); } public void showNotificationMessage(final String title, final String message, final String timeStamp, Intent intent, String imageUrl) { // Check for empty push message if (TextUtils.isEmpty(message)) return; // notification icon final int icon = R.mipmap.ic_launcher; intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); final PendingIntent resultPendingIntent = PendingIntent.getActivity( mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT ); final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder( mContext); final Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + mContext.getPackageName() + "/raw/notification"); if (!TextUtils.isEmpty(imageUrl)) { if (imageUrl != null && imageUrl.length() > 4 && Patterns.WEB_URL.matcher(imageUrl).matches()) { Bitmap bitmap = getBitmapFromURL(imageUrl); if (bitmap != null) { showBigNotification(bitmap, mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound); } else { showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound); } } } else { showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound); playNotificationSound(); } } private void showSmallNotification(NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) { NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); inboxStyle.addLine(message); Notification notification; notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0) .setAutoCancel(true) .setContentTitle(title) .setContentIntent(resultPendingIntent) .setSound(alarmSound) .setStyle(inboxStyle) .setWhen(getTimeMilliSec(timeStamp)) .setSmallIcon(R.mipmap.ic_launcher) .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon)) .setContentText(message) .build(); NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(Config.NOTIFICATION_ID, notification); } private void showBigNotification(Bitmap bitmap, NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) { NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle(); bigPictureStyle.setBigContentTitle(title); bigPictureStyle.setSummaryText(Html.fromHtml(message).toString()); bigPictureStyle.bigPicture(bitmap); Notification notification; notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0) .setAutoCancel(true) .setContentTitle(title) .setContentIntent(resultPendingIntent) .setSound(alarmSound) .setStyle(bigPictureStyle) .setWhen(getTimeMilliSec(timeStamp)) .setSmallIcon(R.mipmap.ic_launcher) .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon)) .setContentText(message) .build(); NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(Config.NOTIFICATION_ID_BIG_IMAGE, notification); } /** * Downloading push notification image before displaying it in * the notification tray */ public Bitmap getBitmapFromURL(String strURL) { try { URL url = new URL(strURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); Bitmap myBitmap = BitmapFactory.decodeStream(input); return myBitmap; } catch (IOException e) { e.printStackTrace(); return null; } } // Playing notification sound public void playNotificationSound() { try { Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + mContext.getPackageName() + "/raw/notification"); Ringtone r = RingtoneManager.getRingtone(mContext, alarmSound); r.play(); } catch (Exception e) { e.printStackTrace(); } } /** * Method checks if the app is in background or not */ public static boolean isAppIsInBackground(Context context) { boolean isInBackground = true; ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) { List runningProcesses = am.getRunningAppProcesses(); for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) { if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE\_FOREGROUND) { for (String activeProcess : processInfo.pkgList) { if (activeProcess.equals(context.getPackageName())) { isInBackground = false; } } } } } else { List taskInfo = am.getRunningTasks(1); ComponentName componentInfo = taskInfo.get(0).topActivity; if (componentInfo.getPackageName().equals(context.getPackageName())) { isInBackground = false; } } return isInBackground; } // Clears notification tray messages public static void clearNotifications(Context context) { NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION\_SERVICE); notificationManager.cancelAll(); } public static long getTimeMilliSec(String timeStamp) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { Date date = format.parse(timeStamp); return date.getTime(); } catch (ParseException e) { e.printStackTrace(); } return 0; } } ```<issue_comment>username_1: In OnDeleteRow you have: 1.-Delete the totals[rowIndex] 2.-recalculate total ``` onDeleteRow(rowIndex) { let rows = this.myForm.get('rows') as FormArray; rows.removeAt(rowIndex); this.totals.splice(rowIndex,1); //<--remove the totals[rowIndex] this.total=this.totals.reduce((sum,item)=>sum+item.total,0); //<--recalculate total } ``` Upvotes: 1 [selected_answer]<issue_comment>username_1: Yhe problem is that, the Changes depending about "i", we can add the property "material\_id to totals and change the function setOnChange ``` //When we create the "totals" //add the property "material_id" to Total material.materials.forEach(x => { rows.push(this.fb.group({ ... })) this.totals.push({amount:0,total:0,material_id:x.id}); //<--add the property material_id }) //then, in the function setOnChange setOnChange() { const formarray=this.myForm.get('rows') as FormArray; for (let i=0;i{ //search the index of "material\_id" let index=this.totals.findIndex(t=>t.material\_id==val.material\_id) if(val.dis\_checkbox){ ... this.totals[index].amount=value; //<--NOT this.totals[i], this.totals[index].total=values; } else { .... this.totals[index].amount=value; this.totals[index].total=value; } }); } } ``` Upvotes: 1
2018/03/20
552
1,879
<issue_start>username_0: I know a lot of people asked that already but nothing seems to work. I want my footer to be on the bottom of the page. So far it is on the bottom of the screen, but if the page is bigger and you need to scroll, it just sticks there and stays in the middle. If I put `position: fixed` the footer scrolls with you. I want it to be at the **VERY BOTTOM** of the page, though, so you have to scroll down to see it in the first place, if the page is too big. I tried several different wrappers and pushers but nothing seems to work.<issue_comment>username_1: In OnDeleteRow you have: 1.-Delete the totals[rowIndex] 2.-recalculate total ``` onDeleteRow(rowIndex) { let rows = this.myForm.get('rows') as FormArray; rows.removeAt(rowIndex); this.totals.splice(rowIndex,1); //<--remove the totals[rowIndex] this.total=this.totals.reduce((sum,item)=>sum+item.total,0); //<--recalculate total } ``` Upvotes: 1 [selected_answer]<issue_comment>username_1: Yhe problem is that, the Changes depending about "i", we can add the property "material\_id to totals and change the function setOnChange ``` //When we create the "totals" //add the property "material_id" to Total material.materials.forEach(x => { rows.push(this.fb.group({ ... })) this.totals.push({amount:0,total:0,material_id:x.id}); //<--add the property material_id }) //then, in the function setOnChange setOnChange() { const formarray=this.myForm.get('rows') as FormArray; for (let i=0;i{ //search the index of "material\_id" let index=this.totals.findIndex(t=>t.material\_id==val.material\_id) if(val.dis\_checkbox){ ... this.totals[index].amount=value; //<--NOT this.totals[i], this.totals[index].total=values; } else { .... this.totals[index].amount=value; this.totals[index].total=value; } }); } } ``` Upvotes: 1
2018/03/20
493
1,515
<issue_start>username_0: I need a list of last date of the previous months for past 13 months; like 2-28-17 3-31-17 4-30-17 5-31-17 and so on until 2-28-18 how can i get this in Oracle Sql<issue_comment>username_1: In OnDeleteRow you have: 1.-Delete the totals[rowIndex] 2.-recalculate total ``` onDeleteRow(rowIndex) { let rows = this.myForm.get('rows') as FormArray; rows.removeAt(rowIndex); this.totals.splice(rowIndex,1); //<--remove the totals[rowIndex] this.total=this.totals.reduce((sum,item)=>sum+item.total,0); //<--recalculate total } ``` Upvotes: 1 [selected_answer]<issue_comment>username_1: Yhe problem is that, the Changes depending about "i", we can add the property "material\_id to totals and change the function setOnChange ``` //When we create the "totals" //add the property "material_id" to Total material.materials.forEach(x => { rows.push(this.fb.group({ ... })) this.totals.push({amount:0,total:0,material_id:x.id}); //<--add the property material_id }) //then, in the function setOnChange setOnChange() { const formarray=this.myForm.get('rows') as FormArray; for (let i=0;i{ //search the index of "material\_id" let index=this.totals.findIndex(t=>t.material\_id==val.material\_id) if(val.dis\_checkbox){ ... this.totals[index].amount=value; //<--NOT this.totals[i], this.totals[index].total=values; } else { .... this.totals[index].amount=value; this.totals[index].total=value; } }); } } ``` Upvotes: 1
2018/03/20
3,116
9,780
<issue_start>username_0: When I'm trying to send mail using php.text also send as an attachment with the name noname.html. please provide a solution for me. I have used this library to send email <https://github.com/google/google-api-php-client>. My code is like this.any help will be appreciated. ``` $client->setAccessToken($_SESSION['gmail_access_token']); $objGMail = new Google_Service_Gmail($client); $strMailContent = 'This is a test mail which is **sent via** using Gmail API client library. Thanks, **<NAME>..**'; // $strMailTextVersion = strip_tags($strMailContent, ''); $strRawMessage = ""; $boundary = uniqid(rand(), true); $subjectCharset = $charset = 'utf-8'; $strToMailName = 'NAME'; $strToMail = '<EMAIL>'; $strSesFromName = 'Premjith GMAIL API'; $strSesFromEmail = '<EMAIL>'; $strSubject = 'Test mail using GMail API - with attachment - ' . date('M d, Y h:i:s A'); $strRawMessage .= 'To: ' .$strToMailName . " <" . $strToMail . ">" . "\r\n"; $strRawMessage .= 'From: '.$strSesFromName . " <" . $strSesFromEmail . ">" . "\r\n"; $strRawMessage .= 'Subject: =?' . $subjectCharset . '?B?' . base64_encode($strSubject) . "?=\r\n"; $strRawMessage .= 'MIME-Version: 1.0' . "\r\n"; $strRawMessage .= 'Content-type: Multipart/Mixed; boundary="' . $boundary . '"' . "\r\n"; $filePath = 'abc.pdf'; $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension $mimeType = finfo_file($finfo, $filePath); $fileName = 'abc.pdf'; $fileData = base64_encode(file_get_contents($filePath)); $strRawMessage .= "\r\n--{$boundary}\r\n"; $strRawMessage .= 'Content-Type: '. $mimeType .'; name="'. $fileName .'";' . "\r\n"; $strRawMessage .= 'Content-ID: <' . $strSesFromEmail . '>' . "\r\n"; $strRawMessage .= 'Content-Description: ' . $fileName . ';' . "\r\n"; $strRawMessage .= 'Content-Disposition: attachment; filename="' . $fileName . '"; size=' . filesize($filePath). ';' . "\r\n"; $strRawMessage .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n"; $strRawMessage .= chunk_split(base64_encode(file_get_contents($filePath)), 76, "\n") . "\r\n"; $strRawMessage .= '--' . $boundary . "\r\n"; $strRawMessage .= "\r\n--{$boundary}\r\n"; $strRawMessage .= 'Content-Type: text/plain; charset=' . $charset . "\r\n"; $strRawMessage .= 'Content-Transfer-Encoding: 7bit' . "\r\n\r\n"; // $strRawMessage .= $strMailTextVersion . "\r\n"; $strRawMessage .= "--{$boundary}\r\n"; $strRawMessage .= 'Content-Type: text/html; charset=' . $charset . "\r\n"; $strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n"; $strRawMessage .= $strMailContent . "\r\n"; //Send Mails //Prepare the message in message/rfc822 try { // The message needs to be encoded in Base64URL $mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '='); $msg = new Google_Service_Gmail_Message(); $msg->setRaw($mime); $objSentMsg = $objGMail->users_messages->send("me", $msg); print('Message sent object'); // print($objSentMsg); } catch (Exception $e) { print($e->getMessage()); unset($_SESSION['access_token']); } ``` When I change the code line `$strRawMessage .= 'Content-type: Multipart/Mixed; boundary="' . $boundary . '"' . "\r\n";` to `$strRawMessage .= 'Content-type: Multipart/Alternative; boundary="' . $boundary . '"' . "\r\n";` Mail Send as html only with out attachment. Please help me<issue_comment>username_1: I have change my code like this its worked fine for me. Thank you all for the support. ``` $client->setAccessToken($_SESSION['gmail_access_token']); $objGMail = new Google_Service_Gmail($client); $strMailContent = 'This is a test mail which is **sent via** using Gmail API client library. Thanks, **username_1 K.K..**'; // $strMailTextVersion = strip_tags($strMailContent, ''); $strRawMessage = ""; $boundary = uniqid(rand(), true); $subjectCharset = $charset = 'utf-8'; $strToMailName = 'NAME'; $strToMail = '<EMAIL>'; $strSesFromName = 'username_1 GMAIL API'; $strSesFromEmail = '<EMAIL>'; $strSubject = 'Test mail using GMail API - with attachment - ' . date('M d, Y h:i:s A'); $strRawMessage .= 'To: ' .$strToMailName . " <" . $strToMail . ">" . "\r\n"; $strRawMessage .= 'From: '.$strSesFromName . " <" . $strSesFromEmail . ">" . "\r\n"; $strRawMessage .= 'Subject: =?' . $subjectCharset . '?B?' . base64_encode($strSubject) . "?=\r\n"; $strRawMessage .= 'MIME-Version: 1.0' . "\r\n"; $strRawMessage .= 'Content-type: Multipart/Mixed; boundary="' . $boundary . '"' . "\r\n"; $filePath = 'abc.pdf'; $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension $mimeType = finfo_file($finfo, $filePath); $fileName = 'abc.pdf'; $fileData = base64_encode(file_get_contents($filePath)); $strRawMessage .= "\r\n--{$boundary}\r\n"; $strRawMessage .= 'Content-Type: '. $mimeType .'; name="'. $fileName .'";' . "\r\n"; $strRawMessage .= 'Content-ID: <' . $strSesFromEmail . '>' . "\r\n"; $strRawMessage .= 'Content-Description: ' . $fileName . ';' . "\r\n"; $strRawMessage .= 'Content-Disposition: attachment; filename="' . $fileName . '"; size=' . filesize($filePath). ';' . "\r\n"; $strRawMessage .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n"; $strRawMessage .= chunk_split(base64_encode(file_get_contents($filePath)), 76, "\n") . "\r\n"; $strRawMessage .= "--{$boundary}\r\n"; $strRawMessage .= 'Content-Type: text/html; charset=' . $charset . "\r\n"; $strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n"; $strRawMessage .= $strMailContent . "\r\n"; //Send Mails //Prepare the message in message/rfc822 try { // The message needs to be encoded in Base64URL $mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '='); $msg = new Google_Service_Gmail_Message(); $msg->setRaw($mime); $objSentMsg = $objGMail->users_messages->send("me", $msg); print('Message sent object'); // print($objSentMsg); } catch (Exception $e) { print($e->getMessage()); unset($_SESSION['access_token']); } ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: The above code works fine for a single attachment. If you want to send multiple attachments just follow this code this allowed to send your mail body part with multiple attachments. ``` $client->setAccessToken($_SESSION['gmail_access_token']); $objGMail = new Google_Service_Gmail($client); $strMailContent = 'This is a test mail which is **sent via** using Gmail API client library. Thanks, **username_1 K.K..**'; $strRawMessage = ""; $boundary = uniqid(rand(), true); $subjectCharset = $charset = 'utf-8'; $strToMailName = 'NAME'; $strToMail = '<EMAIL>'; $strSesFromName = 'username_1 GMAIL API'; $strSesFromEmail = '<EMAIL>'; $strSubject = 'Test mail using GMail API - with attachment - ' . date('M d, Y h:i:s A'); $strRawMessage .= 'To: ' .$strToMailName . " <" . $strToMail . ">" . "\r\n"; $strRawMessage .= 'From: '.$strSesFromName . " <" . $strSesFromEmail . ">" . "\r\n"; $strRawMessage .= 'Subject: =?' . $subjectCharset . '?B?' . base64_encode($strSubject) . "?=\r\n"; $strRawMessage .= 'MIME-Version: 1.0' . "\r\n"; $strRawMessage .= 'Content-type: Multipart/Mixed; boundary="' . $boundary . '"' . "\r\n"; $strRawMessage .= "\r\n--{$boundary}\r\n"; $strRawMessage .= 'Content-Type: text/html; charset=' . $charset . "\r\n"; $strRawMessage .= "Content-Transfer-Encoding: base64" . "\r\n\r\n"; $strRawMessage .= $sentMailData->body . "\r\n"; $strRawMessage .= "--{$boundary}\r\n"; foreach ($files as $key => $filePath) { if($filePath!=""){ $array = explode('/', $filePath); $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension $mimeType = finfo_file($finfo, $filePath); $fileName = $array[sizeof($array)-1]; $fileData = base64_encode(file_get_contents($filePath)); $strRawMessage .= "\r\n--{$boundary}\r\n"; $strRawMessage .= 'Content-Type: '. $mimeType .'; name="'. $fileName .'";' . "\r\n"; $strRawMessage .= 'Content-ID: <' . $sentMailData->email. '>' . "\r\n"; $strRawMessage .= 'Content-Description: ' . $fileName . ';' . "\r\n"; $strRawMessage .= 'Content-Disposition: attachment; filename="' . $fileName . '"; size=' . filesize($filePath). ';' . "\r\n"; $strRawMessage .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n"; $strRawMessage .= chunk_split(base64_encode(file_get_contents($filePath)), 76, "\n") . "\r\n"; $strRawMessage .= "--{$boundary}\r\n"; } } //Send Mails //Prepare the message in message/rfc822 try { // The message needs to be encoded in Base64URL $mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '='); $msg = new Google_Service_Gmail_Message(); $msg->setRaw($mime); $objSentMsg = $service->users_messages->send("me", $msg); echo ' ``` '; print_r($objSentMsg); echo ' ``` '; if($sentMailData->attachments!=""){ $files = explode(',', $sentMailData->attachments); foreach ($files as $key => $filePath) { if($filePath!=""){ @unlink($filePath); } } } echo ' ``` '; print_r($sentMailData); echo ' ``` '; } catch (Exception $e) { print($e->getMessage()); } ``` Upvotes: 2
2018/03/20
1,485
5,206
<issue_start>username_0: I have this code: ``` public function taxesData(Product $product) { $taxes = \Auth::user()->taxes; foreach ($taxes as $tax) { echo "$product->getTax($tax)"; } } ``` which on testing gives this error: > > Type error: Too few arguments to function App\Product::getTax(), 0 passed in E:\projects\ims\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasAttributes.php on line 411 and exactly 1 expected > > > However, just a small change makes it works, but I am not able to understand. Why? ``` public function taxesData(Product $product) { $taxes = \Auth::user()->taxes; foreach ($taxes as $tax) { echo $product->getTax($tax); } } ``` Please help. I tried to simplify it for the purpose of posting here... actually i am creating json with html component for a datatable -> ``` public function taxesData(Product $product) { $taxes = \Auth::user()->taxes; return datatables() ->of($taxes) ->addColumn('check',function($tax) use($product){ if($product->hasTax($tax)){ return ""; }else{ return ""; } }) ->editColumn('tax', function($tax) use($product){ return " " }) ->toJson(); } ``` Adding getTax method ``` public function getTax(Tax $t) { if($this->hasTax($t)){ return $this->taxes->find($t->id)->pivot->tax; } else{ return $t->pivot->tax; } } public function hasTax(Tax $tax) { foreach ($this->taxes as $t) { if($t->id == $tax->id){ return true; } } return false; } ```<issue_comment>username_1: It fails because you are not following the correct syntax of echo strings. This would work: ``` echo "{$product->getTax($tax)}"; ``` or actually, because you dont' need the quotes for such a simple expression: ``` echo $product->getTax($tax); ``` Upvotes: 2 <issue_comment>username_2: Here's what I've done so far. Just for simplicity, I've created a sample Model. ``` // SampleModel.php public function relatedModels() { return $this->hasMany(RelatedModel::class); } // this is like an accessor, but since our model doesn't have // a property called `relatedModels`, Laravel will ignore it // until later... public function getRelatedModels() { return "Sample"; } ``` Given the following code, here are the outputs. ``` $a = SampleModel::find($id); $a->relatedModels; // this returns a collection of related models to this model. $a->getRelatedModels(); // this returns "Sample"; // HOWEVER, when we try to interpolate that member function call. "$a->getRelatedModels()" // this throws error that the method `getRelatedModels` must return a relationship. // I've also tried to add an argument to my existing function to be in-line with your situation. public function getRelatedModels($a) ... // this works well $a->getRelatedModels(1); // but this, yes, it throws the error as same as what you've got. "$a->getRelatedModels(1)"; ``` The error pointed out this line in the framework's codebase. ``` // HasAttributes.php protected function getRelationshipFromMethod($method) { $relation = $this->$method(); // <-- this line ``` For some reason, doing `"$a->getRelatedModels(1)"` triggers the `__get` magic method of the model. Which branches down to this stack call. ``` // Model.php public function __get($key) { return $this->getAttribute($key); } // | // V // HasAttributes.php public function getAttribute($key) { ... return $this->getRelationValue($key); } // | // V // HasAttributes.php public function getRelationValue($key) { ... if (method_exists($this, $key)) { return $this->getRelationshipFromMethod($key); } } // | // V // HasAttributes.php protected function getRelationshipFromMethod($method) { $relation = $this->$method(); // <-- lastly to this // $method = "getRelatedModels" // since our method `getRelatedModels` needs an argument // this call will fail since it wasn't able to provide an argument. ... } ``` That's why you're getting the too few arguments passed exception. I want to investigate further but I have to go home! I don't know if this is a legit bug for Laravel, but if you do think so, issue it on Laravel's github repository. **UPDATE** I've posted an issue in github and this is one of the comments which truly made sense for me. This is neither a issue with Laravel, nor with PHP. You are just using the wrong syntax, see it here: <https://github.com/laravel/framework/issues/23639> Github user *@staudenmeir* commented: > > `"$sampleModel->getRelatedModels()"` is equivalent to `"$sampleModel->getRelatedModels"."()"`. > > > The usage of variables in strings is limited to `"$foo"` and `"$foo->bar"`. Function calls like `"$foo->bar()"` > don't work. You can (but shouldn't) use curly braces for that: `"{$foo->bar()}"` > > > The better solution is just simple string concatenation: > > > `"text..." . $sampleModel->getRelatedModels() . "more text..."` > > > So that is why the magic method `__get` is being called. Upvotes: 3 [selected_answer]
2018/03/20
471
1,917
<issue_start>username_0: This is my spring boot application: ``` @SpringBootApplication @EnableTransactionManagement(proxyTargetClass=true) public class WhizhopApplication { public static void main(String[] args) { SpringApplication.run(WhizhopApplication.class, args); } } ``` This is my service: ``` @Service public class OrderService { @Autowired BillRepository billRepo; @Transactional(rollbackFor = Exception.class) public BaseDTO saveKot(BillDTO billDto) { try { //business logic billRepo.save(); } catch (Exception e) { TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } } } ``` If any exception occurs, the transaction is not rolled back.<issue_comment>username_1: Extract business logic into separate method annotated by `@Transactional(rollbackFor = Exception.class)` and remove annotation from `saveKot`. ``` public BaseDTO saveKot(BillDTO billDto) { try { businessLogic(billDto); } catch (Exception e) { // catch if it needed but manually rollback is not needed return null; } } @Transactional(rollbackFor = Exception.class) BaseDTO businessLogic(BillDTO billDto) throws Exception { // It will be automatically rolled back if Exception occurs ... } ``` Upvotes: 0 <issue_comment>username_2: You shouldn't catch exception if you want it to be processed with `@Transactional`. Also please note that: 1. `@Transactional` works only for public methods 2. [Spring’s @Transactional does not rollback on checked exceptions](https://www.catalysts.cc/wissenswertes/spring-transactional-rollback-on-checked-exceptions/) Upvotes: 2 <issue_comment>username_3: By default rollback from @Transactional is happen only for Runtime execption, if you want to change this behavior you can add `rollBackFor` parameter to annotation @Transactional(rollbackFor={MyException.class}) Upvotes: 0
2018/03/20
609
2,407
<issue_start>username_0: I have an int array with 1000 elements. I need to extract the size of various sub-populations within the array (How many are even, odd, greater than 500, etc..). I could use a for loop and a bunch of if statements to try add to a counting variable for each matching item such as: ``` for(int i = 0; i < someArray.length i++) { if(conditionA) sizeA++; if(conditionB) sizeB++; if(conditionC) sizeC++; ... } ``` or I could do something more lazy such as: ``` Supplier ease = () -> Arrays.stream(someArray); int sizeA = ease.get().filter(conditionA).toArray.length; int sizeB = ease.get().filter(conditionB).toArray.length; int sizeC = ease.get().filter(conditionC).toArray.length; ... ``` The benefit of doing it the second way seems to be limited to readability, but is there a massive hit on efficiency? Could it possibly be more efficient? I guess it boils down to is iterating through the array one time with 4 conditions always better than iterating through 4 times with one condition each time (assuming the conditions are independent). I am aware this particular example the second method has lots of additional method calls which I'm sure don't help efficiency any.<issue_comment>username_1: Extract business logic into separate method annotated by `@Transactional(rollbackFor = Exception.class)` and remove annotation from `saveKot`. ``` public BaseDTO saveKot(BillDTO billDto) { try { businessLogic(billDto); } catch (Exception e) { // catch if it needed but manually rollback is not needed return null; } } @Transactional(rollbackFor = Exception.class) BaseDTO businessLogic(BillDTO billDto) throws Exception { // It will be automatically rolled back if Exception occurs ... } ``` Upvotes: 0 <issue_comment>username_2: You shouldn't catch exception if you want it to be processed with `@Transactional`. Also please note that: 1. `@Transactional` works only for public methods 2. [Spring’s @Transactional does not rollback on checked exceptions](https://www.catalysts.cc/wissenswertes/spring-transactional-rollback-on-checked-exceptions/) Upvotes: 2 <issue_comment>username_3: By default rollback from @Transactional is happen only for Runtime execption, if you want to change this behavior you can add `rollBackFor` parameter to annotation @Transactional(rollbackFor={MyException.class}) Upvotes: 0
2018/03/20
432
1,670
<issue_start>username_0: The following code just won't change the port to 9874. It stays the same in Project -> Debug -> Web Server Settings -> App URL -> "<http://localhost:56021/>", which uses the 56021 port. I am using VS 2017 to create .net core webapi project. ``` public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup() .UseUrls("http://localhost:9874") .Build(); ``` It is the same even i change to Release mode.<issue_comment>username_1: Extract business logic into separate method annotated by `@Transactional(rollbackFor = Exception.class)` and remove annotation from `saveKot`. ``` public BaseDTO saveKot(BillDTO billDto) { try { businessLogic(billDto); } catch (Exception e) { // catch if it needed but manually rollback is not needed return null; } } @Transactional(rollbackFor = Exception.class) BaseDTO businessLogic(BillDTO billDto) throws Exception { // It will be automatically rolled back if Exception occurs ... } ``` Upvotes: 0 <issue_comment>username_2: You shouldn't catch exception if you want it to be processed with `@Transactional`. Also please note that: 1. `@Transactional` works only for public methods 2. [Spring’s @Transactional does not rollback on checked exceptions](https://www.catalysts.cc/wissenswertes/spring-transactional-rollback-on-checked-exceptions/) Upvotes: 2 <issue_comment>username_3: By default rollback from @Transactional is happen only for Runtime execption, if you want to change this behavior you can add `rollBackFor` parameter to annotation @Transactional(rollbackFor={MyException.class}) Upvotes: 0
2018/03/20
511
1,622
<issue_start>username_0: I need Javascript code to print all star patterns using a single program with only 2 for loops. I tried the following code but it prints only diamond shape. ``` var spaces = " "; var rows = "* "; while(rows.length < 200) { spaces += spaces; // doubles length each time rows += rows; // ditto } function diamond(n) { n = parseInt(n, 10); var i, s; // top: 1 to n console.log(" ``` "); for(i = 1; i <= n; ++i) { // write n-i spaces: console.log(spaces.substring(0,n-i)); // then write i asterisk+space sets: console.log( rows.substring(0,i+i) + "\n"); } // bottom: n-1 down to 1 for(i = n-1; i >= 1; --i) { // write n-i spaces: console.log( spaces.substring(0,n-i) ); // then write i asterisk+space sets: console.log( rows.substring(0,i+i) + "\n" ); } console.log(" ``` "); } diamond(9); ```<issue_comment>username_1: Well, there are many star patterns, you didn't specify which ones you're interested in. Anyway, if you can read and translate simple C code to Javascript, here is a link to 9 star pattern you could try <http://cbasicprogram.blogspot.it/2012/03/star-patterns.html> Star pattern algorithms are generally very simple to understand in every language since they are used as beginner exercises. If you don't find anything JS related, try and search in another language. Upvotes: 0 <issue_comment>username_2: You can try ``` let star = ""; for(let i=1; i<=50; i++) { for(let j=1; j<=i; j++) { star += "*"; } star += "\n"; } console.log(star); ``` Upvotes: 1
2018/03/20
615
2,009
<issue_start>username_0: I am playing around with an HTTP2 client/server implementation and I'm running into a `protocol_error` but I'm not sure why. ``` Received frame: {:length=>18, :type=>:settings, :flags=>[], :stream=>0, :payload=>[[:settings_max_concurrent_streams, 128], [:settings_initial_window_size, 65536], [:settings_max_frame_size, 16777215]]} Sent frame: {:type=>:settings, :stream=>0, :payload=>[], :flags=>[:ack]} Received frame: {:length=>4, :type=>:window_update, :flags=>[], :stream=>0, :increment=>2147418112} Sent frame: {:type=>:headers, :flags=>[:end_headers, :end_stream], :payload=>{":scheme"=>"https", ":method"=>"GET", ":path"=>"/index", ":authority"=>"www.example.com"}, :stream=>1} Received frame: {:length=>8, :type=>:goaway, :flags=>[], :stream=>0, :last_stream=>0, :error=>:protocol_error} ``` I'm almost certain this is a problem with stream IDs but I'm really new to the HTTP2 protocol so I'm actually not sure what's going wrong or why I'm getting the protocol error.<issue_comment>username_1: I would guess it is because you have not sent your Settings Frame - you have only acknowledged the server Settings Frame. The spec [could be clearer on this](https://www.rfc-editor.org/rfc/rfc7540#section-6.5): > > A SETTINGS frame MUST be sent by both endpoints at the start of a connection > > > Does an acknowledgement Settings Frame count? However [this section](https://www.rfc-editor.org/rfc/rfc7540#section-3.5) states: > > This sequence MUST be followed by a SETTINGS frame (Section 6.5), which MAY be empty. > ... > The SETTINGS frames received from a peer as part of the connection preface MUST be acknowledged (see Section 6.5.3) after sending the connection preface. > > > So I’m taking that as you must send your Settings Frame and then acknowledge the server Settings Frame. Upvotes: 2 [selected_answer]<issue_comment>username_2: Try with flags "chrome.exe --disable-http2" it will be vanished if it is related with http2 protocol error. Upvotes: 0
2018/03/20
751
3,112
<issue_start>username_0: I'm fairly new on using ConstraintLayout (java). What I want to achieve is something like when the numpad is being shown/hidden as a slide animation, I've tried something like this: ``` Animation a = new Animation() { @Override protected void applyTransformation(float interpolatedTime, Transformation t) { ConstraintLayout.LayoutParams lparams = (ConstraintLayout.LayoutParams) guideline.getLayoutParams(); lparams.guidePercent = 0.5f; guideline.setLayoutParams(lparams); } }; a.setDuration(3000); a.setFillAfter(true); guideline.startAnimation(a); ``` Yes, the guideline (and corresponding views that is attached to it) is being moved to the center of the screen but it is not as smooth as it is supposed to be. Is there a way to achieve the smoothness of the animation? Any suggestion would be much appreciated!<issue_comment>username_1: You can use a `ValueAnimator` Sample in Kotlin. ``` val guideline = findViewById(R.id.guideline2) as Guideline val end = (guideline.layoutParams as ConstraintLayout.LayoutParams).guidePercent // get end percent. start at 0 val valueAnimator = ValueAnimator.ofFloat(0f, end) valueAnimator.duration = 3000 // set duration valueAnimator.interpolator = AccelerateDecelerateInterpolator() // set interpolator and updateListener to get the animated value valueAnimator.addUpdateListener { valueAnimator -> val lp = guideline.layoutParams as ConstraintLayout.LayoutParams // get the float value lp.guidePercent = valueAnimator.animatedValue as Float // update layout params guideline.layoutParams = lp } valueAnimator.start() ``` Java Version ``` final Guideline guideline = findViewById(R.id.guideline2) ; ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams)guideline.getLayoutParams(); float end =lp.guidePercent; ValueAnimator valueAnimator = ValueAnimator.ofFloat(0f, end); valueAnimator.setDuration(3000); valueAnimator.setInterpolator(new AccelerateDecelerateInterpolator()); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams)guideline.getLayoutParams(); lp.guidePercent = valueAnimator.getAnimatedFraction(); guideline.setLayoutParams(lp); } }); ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: Try animating your layout with `ConstraintSet`. See [Beautiful animations using Android ConstraintLayout](https://robinhood.engineering/beautiful-animations-using-android-constraintlayout-eee5b72ecae3). > > [T]here is one other benefit of ConstraintLayout that most people are unaware of and the official documentation curiously doesn’t mention anything about: performing cool animations on your ConstraintLayout views with very little code. > > > There are other sources and some videos on this technique. I think that you will find it a smoother way to do what you are trying to do. Upvotes: 2
2018/03/20
532
2,083
<issue_start>username_0: I have two `spannable` object for same string and both have different styles. I need to merge all `spannable` objects and display all styles into `TextView`. From one of returning from `Html.fromHtml()` and second return StyleSpan(Bold). I tried `TextUtils.concate(htmlSpan, boldSpan)` but it displayed same string two times because it append `spannable`, i want to display my all styles into single string.<issue_comment>username_1: Use `SpannableStringBuilder` but you can create spans inside the `append` method ``` SpannableStringBuilder sb = new SpannableStringBuilder(); sb.append(String.valueOf(Html.fromHtml(stringToConvert)); sb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); ``` And then just set `sb` to your view ``` textView.setText(sb); ``` **EDIT**: I saw your edited question, Above I **rewrote this code** to get it to apply two spannables on one string. I think you cannot merge different spannable objects on one string. I believe a workaround would be to apply one span, then convert in to string and then apply the second span. This way it will apply two spans to one string. Or you can manage your bold text type via xml if you always need it in bold Upvotes: 2 <issue_comment>username_2: Finally i found my solution, Html.fromHtml() not have spannable type parameter, so firstly i got SpannableStringBuilder from Html.fromHtml() and carry forward it into create Bold StyleSpannable method then set into TextView, and it works awesome. It retain HTML spannable into bold StyleSpannable method. Thanks guys for your feed back and response of my answer. ``` SpannableStringBuilder spannable = setTextViewHTML(content); common.convertBoldString(spannable); textView.setText(spannable); ``` For the above code content is a variable, which contain words which i like to bold and it also contain HTML tags. `convertBoldString` is method in my Common methods class which has parameter `SpannableStringBuilder` and this object use to set bold StyleSpan. Upvotes: 0
2018/03/20
842
2,953
<issue_start>username_0: I have a class with a method which uses shutil.rmtree to remove some files if a param is passed as true, How to mock this behavior so as other tests don't break which needs these files. My class looks like this - ``` class FileConverter(object): def __init__(self, path_to_files): self._path_to_files = path_to_files def convert_files(self, rmv_src=False): doStuff() if rmv_src: shutil.rmtree(self.__path_to_files) def doStuff(): # does some stuff ``` Now my tests look like - ``` class TestFileConverter(unittest.TestCase): def test_convert_success(self): input_dir = 'resources/files' file_converter = FileConverter(input_dir) file_converter.convert_files() # assert the things from doStuff @mock.patch('shutil.rmtree') def test_convert_with_rmv(self, rm_mock): input_dir = 'resources/files' file_converter = FileConverter(input_dir) file_converter.convert_files(True) self.assertEquals(rm_mock, [call(input_dir)]) ``` Now when I run this testsuite the test with rmv gives me assertionError ``` != [call('resources/images')] ``` and the first test gives me file not found error since the mock did not work and the rmv source test removed the file ``` FileNotFoundError: [Errno 2] No such file or directory: 'resources/images' ``` If I comment out the second test with rmv\_source true then my first test works fine. What am I doing wrong here?<issue_comment>username_1: Your module has already imported `shutil.rmtree` so mocking it later in the test suite won't do anything. You need to mock the module when you import `FileConverter`, not afterwards. ``` import sys from mock import MagicMock sys.modules['shutil'] = MagicMock() # and/or sys.modules['shutil.rmtree'] = MagicMock() import FileConverter ``` If you still need to use shutil in your test code, then first import it using an alias,and use that when you need the 'real' module: ``` import sys from mock import MagicMock import shutil as shutil_orig sys.modules['shutil'] = MagicMock() import shutil print(type(shutil_orig.rmtree)) # print(type(shutil.rmtree)) # ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: The original post should work except the `call(input_dir)` did not work for me ``` @mock.patch('shutil.rmtree') def test_convert_with_rmv(self, rm_mock): input_dir = 'resources/files' rm_mock.return_value = 'REMOVED' file_converter = FileConverter(input_dir) file_converter.convert_files(True) rm_mock.assert_called_with(input_dir) self.assertEqual(rm_mock.return_value, 'REMOVED') ``` The `test_convert_with_rmv` has no way removed the `input_dir`, it probably never created in the first place. You could assert this statement in each test before and after `convert_files` called: ``` self.asserTrue(os.path.isdir(input_dir)) ``` Upvotes: 1
2018/03/20
1,591
4,302
<issue_start>username_0: Hello I am a beginner in HTML and CSS. I created a multiple table tag to with Power description but I cant align the level2 and level3 table tag from Level1. Another query. How can I create another sets of Level's that will be under to no Power? but I'm not able to get the desired result. actually the required is to create 8 sets of Level horizontally. The description name is fixed for individual boxes from L1-Sample1 to L3-Good. Please see below my initial HTML code. ```html | With Power | | | --- | | Level1 | | L1-Sample1 | value | value | | L1-sample2 | value | value | | L1-sample3 | value | value | | L1-sample4 | value | value | | | | --- | | Level2 | | L2-sample1 | value | value | | L2-sample2 | value | value | | L2-sample3 | value | value | | L2-sample4 | value | value | | L2-sample5 | value | value | L2-sample6 | value | value | L2-sample7 | value | value | | | | --- | | Level3 | | L3-Good | value | value | | L3-Bad | value | value | | No Power | | ``` Please see below sample image. [Desired Result](https://i.stack.imgur.com/lgNQl.jpg)<issue_comment>username_1: Because you are useing div tag in tr so remove and use `| | | --- |` Upvotes: 0 <issue_comment>username_2: Add `table{ width: 100%;}` or any width of your choice for equal table width. Upvotes: 0 <issue_comment>username_3: This will works, apply this CSS: ``` table { border-collapse: collapse; width: 100%; } table tr td { width: 120px; padding: 6px; } ``` Upvotes: 1 <issue_comment>username_4: If you are using `table`...you will need to use its elements `tbody`, `tr`, `td` properly also its attributes like `col-span`, `row-span`, `border` `cellpadding` etc... > > ***[Take reference for table here](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table)*** > > > Also when you write markup, its better to validate your code...you can use **[html validator](https://validator.w3.org/#validate_by_input)** to validate it You will need to wrap your tables inside a main table to align them like below ```css table { border-collapse: collapse; font: 13px Verdana; } h3 { margin: 0; } table, tr, td { border: 1px solid #000; } table table td { padding: 10px; } td { vertical-align: top; } ``` ```html | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | | | | --- | | With Power | | | | Level1 | | L1-Sample1 | value | value | | L1-sample2 | value | value | | L1-sample3 | value | value | | L1-sample4 | value | value | | Level2 | | L2-sample1 | value | value | | L2-sample2 | value | value | | L2-sample3 | value | value | | L2-sample4 | value | value | | L2-sample5 | value | value | | L2-sample6 | value | value | | L2-sample7 | value | value | | Level3 | | L3-Good | value | value | | L3-Bad | value | value | | | | | --- | | No Power | | | | Level1 | | L1-Sample1 | value | value | | L1-sample2 | value | value | | L1-sample3 | value | value | | L1-sample4 | value | value | | Level2 | | L2-sample1 | value | value | | L2-sample2 | value | value | | L2-sample3 | value | value | | L2-sample4 | value | value | | L2-sample5 | value | value | | L2-sample6 | value | value | | L2-sample7 | value | value | | Level3 | | L3-Good | value | value | | L3-Bad | value | value | | ``` Upvotes: 0 <issue_comment>username_5: Just want to share with you this code if this is correct to create the main and submain. THanks. ``` Main ---- Main1 Main2 | submain1 submain2 submain3 submain4 ``` Upvotes: 0
2018/03/20
984
4,037
<issue_start>username_0: I am trying to retrieve a row from database , changing certain columns value in it and adding it as new row (Entity Framework Core), But it is giving me error > > Cannot insert explicit value for identity column in table 'Audit\_Schedules' when IDENTITY\_INSERT is set to OFF. > > > This table have a Primary Key **"ScheduleId"** Below is my Code ``` AuditSchedules _schedules = new AuditSchedules(); using (var ctx = new QuestionnaireEntities(_configuration)) { _schedules = ctx.AuditSchedules.Where(x => x.ScheduleId == model.ScheduleID).SingleOrDefault(); _schedules.StaffId = model.TransferedAuditorCode; _schedules.StaffName = model.TransferedAuditorName; _schedules.FromDate = _schedules.ToDate = Convert.ToDateTime(model.TransferedScheduleDate); ctx.AuditSchedules.Add(_schedules); ctx.SaveChanges(); _subschedules = ctx.AuditSubSchedule.Where(x => x.SubScheduleId == model.SubScheduleID).SingleOrDefault(); _subschedules.IsHoliDay = "Y"; _subschedules.HolidayType = model.HolidayType; _subschedules.TransferedScheduleId = _schedules.ScheduleId.ToString(); ctx.AuditSubSchedule.Update(_subschedules); ctx.SaveChanges(); } ``` Error Comes In ``` ctx.AuditSchedules.Add(_schedules); ``` First I thought its conflicting in value of Schedule\_ID and not able to add duplicate Primary Key , But Schedule\_ID is auto generated field so this issue should not occur I also tried setting it to different value ``` _schedules.ScheduleId = 0; ``` but it does not insert . How Can I replicate a row with few changes in it (want to add a new row but modified values)<issue_comment>username_1: The error is simple, it is because you are adding the identity insert as a part of insert. If it is identity, it has to be auto generated. So either turn off before insert and then turn it on. Or make it auto generated. This error will be the same if you try and insert the same data from sql server. This is basically propagated from sql server. If you do not want an ID to be database generated, then you should use the DatabaseGenerated attribute on your model, as in ``` [DatabaseGenerated(DatabaseGeneratedOption.None)] public int ScheduleId {get;set;} ``` If you want the identity insert to be off you can try the technique [here](https://stackoverflow.com/questions/40896047/how-to-turn-on-identity-insert-in-net-core) Upvotes: 0 <issue_comment>username_2: EF Core behavior with auto generated values on insert is different than EF6. First, the property must have default value (`0`) in order to be auto generated. This allows identity inserts which was not possible in EF6. Second, the entity being added should not be already tracked by the context, because otherwise the context keeps internally some information that the entity key has been set and will include the value (even `0`) in the generated `INSERT` command, which in turn causes the exception you are getting. To achieve the goal, *before* calling the `Add` method: First make sure the entity is not tracked by either using [No-tracking query](https://learn.microsoft.com/en-us/ef/core/querying/tracking#no-tracking-queries) when obtaining it ``` _schedules = ctx.AuditSchedules .AsNoTracking() // <-- .Where(x => x.ScheduleId == model.ScheduleID) .SingleOrDefault(); ``` or explicitly detaching it ``` ctx.Entry(_schedules).State = EntityState.Detached; ``` Then reset the PK ``` _schedules.ScheduleId = 0; ``` The do other modifications and finally call ``` ctx.AuditSchedules.Add(_schedules); ``` This will work for simple entities w/o navigation properties / FKs. For complex entity graph you should use no tracking query, and then work with it the same way as with detached entity graphs. Upvotes: 4 [selected_answer]
2018/03/20
1,793
7,363
<issue_start>username_0: I have an ASP.NET Core 2.0 app hosted on an Azure App Service. This application is bound to `domainA.com`. I have one route in my app—for example, `domainA.com/route`. Now, I want to introduce another domain, but have it respond only to a different route—for example, `domainB.com`. What is the best way to do this?<issue_comment>username_1: One way to accomplish this is to make a [custom route constraint](https://www.c-sharpcorner.com/article/creating-custom-routing-constraint/) to specify which routes function for each domain name. DomainConstraint ---------------- ``` public class DomainConstraint : IRouteConstraint { private readonly string[] domains; public DomainConstraint(params string[] domains) { this.domains = domains ?? throw new ArgumentNullException(nameof(domains)); } public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection) { string domain = #if DEBUG // A domain specified as a query parameter takes precedence // over the hostname (in debug compile only). // This allows for testing without configuring IIS with a // static IP or editing the local hosts file. httpContext.Request.Query["domain"]; #else null; #endif if (string.IsNullOrEmpty(domain)) domain = httpContext.Request.Host.Host; return domains.Contains(domain); } } ``` Usage ----- ``` app.UseMvc(routes => { routes.MapRoute( name: "DomainA", template: "route", defaults: new { controller = "DomainA", action = "Route" }, constraints: new { _ = new DomainConstraint("domaina.com") }); routes.MapRoute( name: "DomainB", template: "route", defaults: new { controller = "DomainB", action = "Route" }, constraints: new { _ = new DomainConstraint("domainb.com") }); routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); ``` Note that if you fire this up in Visual Studio it won't work with the standard configuration. To allow for easy debugging without changing the configuration, you can specify the URL with the domain as a query string parameter: ``` /route?domain=domaina.com ``` This is just so you don't have to reconfigure IIS and your local hosts file to debug (although you still can if you prefer that way). During a `Release` build this feature is removed so it will only work with the *actual* domain name in production. Since routes respond to *all domain names* by default, it only makes sense to do it this way if you have a large amount of functionality that is shared between domains. If not, it is better to setup separate areas for each domain: ``` routes.MapRoute( name: "DomainA", template: "{controller=Home}/{action=Index}/{id?}", defaults: new { area = "DomainA" }, constraints: new { _ = new DomainConstraint("domaina.com") } ); routes.MapRoute( name: "DomainA", template: "{controller=Home}/{action=Index}/{id?}", defaults: new { area = "DomainB" }, constraints: new { _ = new DomainConstraint("domainb.com") } ); ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: For .net Core MVC, you can create a new IRouteConstraint and a RouteAttribute => IRouteConstraint.cs ``` using System; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Microsoft.AspNetCore.Routing { public class ConstraintHost : IRouteConstraint { public string _value { get; private set; } public ConstraintHost(string value) { _value = value; } public bool Match(HttpContext httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { string hostURL = httpContext.Request.Host.ToString(); if (hostURL == _value) { return true; } //} return false; //return hostURL.IndexOf(_value, StringComparison.OrdinalIgnoreCase) >= 0; } public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection) { throw new NotImplementedException(); } } public class ConstraintHostRouteAttribute : RouteAttribute { public ConstraintHostRouteAttribute(string template, string sitePermitted) : base(template) { SitePermitted = sitePermitted; } public RouteValueDictionary Constraints { get { var constraints = new RouteValueDictionary(); constraints.Add("host", new ConstraintHost(SitePermitted)); return constraints; } } public string SitePermitted { get; private set; } } } ``` And in your Controller can use it like that: ``` [ConstraintHostRoute("myroute1/xxx", "domaina.com")] [ConstraintHostRoute("myroute2/yyy", "domainb.com")] public async Task MyController() { return View(); } ``` Upvotes: 3 <issue_comment>username_3: ### Built-in Approach Since ASP.NET Core 3—and with continued support in ASP.NET Core 5 and 6—you can restrict individual route definitions to specific hostnames by using the **[`RequireHost()`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.routingendpointconventionbuilderextensions.requirehost?view=aspnetcore-3.1)** extension method, as discussed in [Allow routing to areas by hostname](https://github.com/dotnet/aspnetcore/issues/8264). (Contrary to the issue title, this isn't specific to areas.) ### Example So, to adapt [@nightowl888's example in the accepted answer](https://stackoverflow.com/a/49393828/3025856), you can now accomplish the same result without having to define a custom `IRouteConstraint`: ```cs app.UseMvc(routes => { routes.MapRoute( name: "DomainA", template: "route", defaults: new { controller = "DomainA", action = "Route" } ).RequireHost("domaina.com"); routes.MapRoute( name: "DomainB", template: "route", defaults: new { controller = "DomainB", action = "Route" } ).RequireHost("domainb.com"); routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}" ); }); ``` ### Attribute Routing Alternatively, if you prefer attribute routing, [as used in @yanga's approach](https://stackoverflow.com/a/50635119/3025856), you can now use the new (but poorly documented) **[`HostAttribute`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.routing.hostattribute?view=aspnetcore-5.0)** ([source code](https://github.com/dotnet/aspnetcore/blob/master/src/Http/Routing/src/HostAttribute.cs)): ```cs [Host("domainb.com")] public DomainController: Controller { … } ``` Obviously, this doesn't address the original problem, which was for ASP.NET Core 2. As this is an un(der)documented feature, however, I wanted to leave it here for people trying to solve this problem for ASP.NET Core 3+. Upvotes: 3
2018/03/20
1,043
3,841
<issue_start>username_0: I have multiple buttons 0 to 9 and other calculation methods like plus, minus, etc There are two display items, `Memory` and `Display`; `Memory` item is hidden. When click on `1` button then display value 1 in `Display` item. When click on `+` button then store value 1 in `Memory` item. When click on `=` button then add `Memory` + `Display` values and show answer on `Display` item. Question is how to code multiple calculation in equal to `=` button?<issue_comment>username_1: You have three registers: the button clicked, the display value and the memory value. So the calculation string `2+3=5` looks something like this: ``` button Display Memory 2 2 + 2 2 3 3 2 = 5 5 ``` As I understand your question, you want to handle a longer calculation, when the user types in several steps without pressing `=`, for instance `2+3+7/4*5=`. There are several ways to do this, but the most intuitive one for the user is to treat the arithmetic operators as having an implicit `=` operation, calculating the running sum and displaying that value. ``` button Display Memory 2 2 + 2 2 3 3 2 + 5 5 7 7 5 / 12 12 4 4 12 * 3 3 5 5 3 = 15 15 ``` To make this work you need another register item to track the current operator. ``` button Display Memory Operator 2 2 + 2 2 + 3 3 2 + + 5 5 + 7 7 5 + / 12 12 / 4 4 12 / * 3 3 * 5 5 3 * = 15 15 = ``` So when the user clicks a triggering button you execute something like this: ``` if :operator = '+' then :memory := :memory + :display; elsif :operator = '-' then :memory := :memory - :display; elsif :operator = '/' then :memory := :memory / :display; elsif :operator = '*' then :memory := :memory * :display; end if; :display := :memory; :operator := :button_value; ``` You will need to decide how to handle the situation when the user types two operations in a row e.g. `+/`. But probably you need to track previous button press too. So what is the purpose of `=`? Well, it depends on what the user types next. If they follow `=` with another operator then it's just a subtotal and the sum continues.... ``` button Display Memory 2 2 + 2 2 3 3 2 = 5 5 + 2 5 <-- continue with existing sum = 7 7 ``` ... but if they follow it with a number then we're starting a new sum and we reset the memory: ``` button Display Memory 2 2 + 2 2 3 3 2 = 5 5 2 2 <-- start a new sum + 2 2 2 2 2 = 4 4 ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Create a function like below. ``` create or replace function calculate(p_input VARCHAR2) RETURN VARCHAR2 IS v_output VARCHAR2(20); missing_expression EXCEPTION; invalid_identifier EXCEPTION; PRAGMA EXCEPTION_INIT(missing_expression, -936); PRAGMA EXCEPTION_INIT(invalid_identifier, -904); BEGIN EXECUTE IMMEDIATE 'SELECT '||p_input||' FROM dual' INTO v_output; RETURN v_output; EXCEPTION WHEN VALUE_ERROR OR MISSING_EXPRESSION OR INVALID_IDENTIFIER THEN RETURN 'ERROR'; END; / ``` Sample use in SQL, ``` SELECT CAST(CALCULATE('1+2-3+4+5') AS VARCHAR2(20)) output FROM dual; ``` In Oracle forms, ``` :block.io_display_item := CAST(CALCULATE(:block.io_display_item) AS VARCHAR2(20)); ``` Upvotes: 0
2018/03/20
1,092
4,070
<issue_start>username_0: I was wondering if there is a way to prevent the Modal from showing up when an ajax call returns an error. I've seen a few posts here already that use ``` e.stopPropagation(); ``` but I couldn't manage to make that work. My ajax call looks as follow ``` $.ajax({ url: url, data: data, dataType: 'json', cache: false, type: "POST", error: function (e) { //show error message $('#alertdone').removeClass('hidden'); }, //if ajax call is successful populate form fields and hide error message success: function (data) { //hides the error message $('#alertdone').addClass('hidden'); } }); ``` Thanks<issue_comment>username_1: You have three registers: the button clicked, the display value and the memory value. So the calculation string `2+3=5` looks something like this: ``` button Display Memory 2 2 + 2 2 3 3 2 = 5 5 ``` As I understand your question, you want to handle a longer calculation, when the user types in several steps without pressing `=`, for instance `2+3+7/4*5=`. There are several ways to do this, but the most intuitive one for the user is to treat the arithmetic operators as having an implicit `=` operation, calculating the running sum and displaying that value. ``` button Display Memory 2 2 + 2 2 3 3 2 + 5 5 7 7 5 / 12 12 4 4 12 * 3 3 5 5 3 = 15 15 ``` To make this work you need another register item to track the current operator. ``` button Display Memory Operator 2 2 + 2 2 + 3 3 2 + + 5 5 + 7 7 5 + / 12 12 / 4 4 12 / * 3 3 * 5 5 3 * = 15 15 = ``` So when the user clicks a triggering button you execute something like this: ``` if :operator = '+' then :memory := :memory + :display; elsif :operator = '-' then :memory := :memory - :display; elsif :operator = '/' then :memory := :memory / :display; elsif :operator = '*' then :memory := :memory * :display; end if; :display := :memory; :operator := :button_value; ``` You will need to decide how to handle the situation when the user types two operations in a row e.g. `+/`. But probably you need to track previous button press too. So what is the purpose of `=`? Well, it depends on what the user types next. If they follow `=` with another operator then it's just a subtotal and the sum continues.... ``` button Display Memory 2 2 + 2 2 3 3 2 = 5 5 + 2 5 <-- continue with existing sum = 7 7 ``` ... but if they follow it with a number then we're starting a new sum and we reset the memory: ``` button Display Memory 2 2 + 2 2 3 3 2 = 5 5 2 2 <-- start a new sum + 2 2 2 2 2 = 4 4 ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Create a function like below. ``` create or replace function calculate(p_input VARCHAR2) RETURN VARCHAR2 IS v_output VARCHAR2(20); missing_expression EXCEPTION; invalid_identifier EXCEPTION; PRAGMA EXCEPTION_INIT(missing_expression, -936); PRAGMA EXCEPTION_INIT(invalid_identifier, -904); BEGIN EXECUTE IMMEDIATE 'SELECT '||p_input||' FROM dual' INTO v_output; RETURN v_output; EXCEPTION WHEN VALUE_ERROR OR MISSING_EXPRESSION OR INVALID_IDENTIFIER THEN RETURN 'ERROR'; END; / ``` Sample use in SQL, ``` SELECT CAST(CALCULATE('1+2-3+4+5') AS VARCHAR2(20)) output FROM dual; ``` In Oracle forms, ``` :block.io_display_item := CAST(CALCULATE(:block.io_display_item) AS VARCHAR2(20)); ``` Upvotes: 0
2018/03/20
953
3,742
<issue_start>username_0: I am doing a migration of old project (Core Java + EJB + hibernate) from hibernate 3 to hibernate 5.2.12. Though hibernate 5.2.12 supports .hbm.xml file but as a part up gradation migrating from .hbm files to Annotated files. Below is the scenario i have, and the data model is tightly coupled classes. ``` public interface BaseEntity extends Serializable, Cloneable, Observable { public void setId(long id); public long getId(); ... few other generic attributes } public class BaseClass implements BaseEntity { protected long id; public void setId(long id) { this.id = id; } public long getId() { return objectId; } .. few other attributes } public class AuditableBaseClass extends BaseClass implements BaseEntity, Audit { ... few other attributes } public class Car extends AuditableBaseClass { .... some attributes } public class Bike extends AuditableBaseClass { ...some attributes } public class Truck extends AuditableBaseClass { ... some attributes } ``` If we look at the existing .hbm.xml file below, Used different sequence for the different classes ``` SEQ\_CAR < // some other properties SEQ\_BIKE // some other properties SEQ\_TRUCK ``` Simple definition for @Id using sequence is as below ``` @Id @GeneratedValue( strategy = GenerationType.SEQUENCE, generator = "sequence-generator" ) @SequenceGenerator( name = "sequence-generator", sequenceName = "SEQ_NAME" ) ``` For a fact that i know we need to use `@MappedSuperclass` to represent the super class. How to represent **sequence attribute for an @Id** column which is using **a different sequence for different child classes though all classes inherit the attribute id but uses different sequences for each.** Any help on this please?<issue_comment>username_1: Hibernate 5.2 doesn't allow us to have two identifier generators with the same name even they have different configurations because the scope is global as stated in JPA Spec. Because of that, you need to define your identifiers and generators in the entity classes. > > A sequence generator may be specified on the entity class or on the primary key field or property. The scope of the generator name is global to the persistence unit (across all generator types). > > > Reference: <https://hibernate.atlassian.net/browse/HHH-12329> by @<NAME> Upvotes: 0 <issue_comment>username_2: At first you must set @MappedSuperclass for BaseClass and use @GeneratedValue for attribute id with fix generator. After that use @SequenceGenerator in child class and set name attribute with generator in BaseClass. ``` @MappedSuperclass public class BaseClass implements BaseEntity { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "my_seq_gen") @Column(name = "ID") protected long id; public void setId(long id) { this.id = id; } public long getId() { return objectId; } .. few other attributes } public class AuditableBaseClass extends BaseClass implements BaseEntity, Audit { ... few other attributes } @Entity @Table(name="car") @SequenceGenerator(sequenceName = "car_id_seq", allocationSize = 1, name = "my_seq_gen") public class Car extends AuditableBaseClass { .... some attributes } @Entity @Table(name="bike") @SequenceGenerator(sequenceName = "bike_id_seq", allocationSize = 1, name = "my_seq_gen") public class Bike extends AuditableBaseClass { .... some attributes } @Entity @Table(name="truck") @SequenceGenerator(sequenceName = "truck_id_seq", allocationSize = 1, name = "my_seq_gen") public class Truck extends AuditableBaseClass { ... some attributes } ``` Upvotes: 2
2018/03/20
584
1,766
<issue_start>username_0: I have some data in the following date format. '27-SEP-97' i.e DD-MON-YY Now I want to convert this to YYYYMMDD. I am using the following script to convert this. ``` TO_CHAR(TO_DATE(CHD_DATE_FIRST_ACT,'DD-MON-YY'),'YYYYMMDD') ``` but this is giving me the following output. ``` 20970927 ``` I want this data to be in YYYYMMDD format, such that the output looks like this- **19970927**<issue_comment>username_1: If '27-SEP-97' is a string (which is what your words suggest), then such a combination of TO\_this and TO\_that might do the job: ``` SQL> with test as (select '27-SEP-97' datum from dual) 2 select to_char(to_date(datum, 'dd-mon-rr', 'nls_date_language = english'), 'yyyymmdd') result 3 from test; RESULT -------------------------------------------------------------------------------- 19970927 SQL> ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: --USE RR instead of YY in your query. select TO\_CHAR(TO\_DATE('27-SEP-97','DD-MON-RR'),'YYYYMMDD') from dual; Upvotes: 0 <issue_comment>username_3: You can make use of mysql `replace` and `str_to_date` functions `replace` takes 3 arguments as show below `replace(string,find_string,replace_with)` you should simply replace `-` with a blank string if your str is '27-SEP-97' to get the output as `19970927` execute the following in mysql `select replace(str_to_date('27-SEP-97','%d-%b-%Y'),'-','') as date;` output ``` +----------+ | date | +----------+ | 19970927 | +----------+ ``` `%b` is used to mention abbreviated month name click the below links to know more about mysql date and time functions **[Mysql Data and Time functions](https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html)** Upvotes: 0
2018/03/20
570
1,785
<issue_start>username_0: When creating a time timestamp from Date() function app is getting crash rarely, Is it the right way to handle it? ``` let time_stamp = String(Int(Date().timeIntervalSince1970*1000)) ``` The above code is getting crash rarely, in the test flight build. [![enter image description here](https://i.stack.imgur.com/kMMRY.png)](https://i.stack.imgur.com/kMMRY.png) Added the log, line number 3216 is the above one.<issue_comment>username_1: If '27-SEP-97' is a string (which is what your words suggest), then such a combination of TO\_this and TO\_that might do the job: ``` SQL> with test as (select '27-SEP-97' datum from dual) 2 select to_char(to_date(datum, 'dd-mon-rr', 'nls_date_language = english'), 'yyyymmdd') result 3 from test; RESULT -------------------------------------------------------------------------------- 19970927 SQL> ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: --USE RR instead of YY in your query. select TO\_CHAR(TO\_DATE('27-SEP-97','DD-MON-RR'),'YYYYMMDD') from dual; Upvotes: 0 <issue_comment>username_3: You can make use of mysql `replace` and `str_to_date` functions `replace` takes 3 arguments as show below `replace(string,find_string,replace_with)` you should simply replace `-` with a blank string if your str is '27-SEP-97' to get the output as `19970927` execute the following in mysql `select replace(str_to_date('27-SEP-97','%d-%b-%Y'),'-','') as date;` output ``` +----------+ | date | +----------+ | 19970927 | +----------+ ``` `%b` is used to mention abbreviated month name click the below links to know more about mysql date and time functions **[Mysql Data and Time functions](https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html)** Upvotes: 0
2018/03/20
602
2,145
<issue_start>username_0: I was trying to run a Flask project using Python 3.6. I encountered an error: ... from flask\_openid import OpenID ModuleNotFoundError: No module named 'flask\_openid' Flask-OpenID is available in my Python v3.5 dist-packages. (When I run: "sudo pip3 install Flask-OpenID", it shows "Requirement already satisfied (use --upgrade to upgrade): Flask-OpenID in /usr/local/lib/python3.5/dist-packages" ) What should I do to install openid for Python 3.6?<issue_comment>username_1: The [documentation](https://pythonhosted.org/Flask-OpenID/#how-to-use) states that you should import `OpenID` as follows: ``` from flask.ext.openid import OpenID ``` The package itself is installed correctly (in your Python3.5 environment), as shown by `pip` when you try to install it again: > > Requirement already satisfied (use --upgrade to upgrade): Flask-OpenID in /usr/local/lib/python3.5/dist-packages > > > However, as you state the in your question: > > I was trying to run a Flask project using **Python 3.6** > > > You might want to make sure your `python3` and `pip3` are actually pointing to where you want them to, e.g. on your terminal: ``` $ ls -l $(which pip3) ``` Or even better, you should really look into creating [virtualenvs](https://virtualenv.pypa.io/en/stable/) for your projects, it helps a lot avoiding these kinds of problems in the first place: * create a new Python 3.6 virtualenv * activate your new virtualenv * install your requirements with pip inside the virtualenv Then run your script in this virtualenv, and you'll be sure you are using exactly the Python you want, and your dependencies are where you expect them to be (and only there, not somewhere else messing up other projects). Now this might look like a lot of effort, but it takes no more than a couple minutes the first time you do it, will quickly become second nature, and save you a ton of headache down the road. Upvotes: 1 <issue_comment>username_2: For me, ``` python3.6 -m pip install flask_openid ``` solved the issue. The above command will install openid for python3.6. Upvotes: 1 [selected_answer]
2018/03/20
1,040
3,585
<issue_start>username_0: I need vba code in Excel to convert formula to its value, but only in specific column and only convert till last row with data Example: Sheet 1 Column B, E:J filled with lookup formula to get data from Sheet 2. Formula is filled from row 1 to 1500. Based on table array in sheet 2. Sheet 1 row 1 to 1000 return lookup result. I need to convert column B, E:J row 1 to 1000 formula to value while row 1001 to 1500 is still have lookup formula From internet search i can use this code... ``` Sub FormulaToValue() Dim N As Long, rng As Range N = Cells(Rows.Count, "A").End(xlUp).Row Set rng = Range(Cells(1, 1), Cells(N, Columns.Count)) rng.Value2 = rng.Value2 End Sub ``` This code will convert formula to value until last row with data only, in this case only row 1 to 1000 will be converted. But this code convert all columns in the sheet. I think i need to change Columns.Count to specific column range but i don't now how to write the right code. I'm not familiar with vba code Please help. Thank you<issue_comment>username_1: Put the column you require in this line ``` Set rng = Range(Cells(1, 1), Cells(N, Columns.Count)) ``` e.g. If you want to use column E ``` Set rng = Range(Cells(1, 5), Cells(N, 5)) ``` If you want to use multiple columns you can use a loop to go through them ``` Sub FormulaToValue() Dim N As Long, rng As Range Dim arr As Variant arr = Array("B", "E", "F", "G", "H", "I", "J") ' Read through each column Dim col As Variant For Each col In arr N = Cells(Rows.Count, col).End(xlUp).Row Set rng = Range(Cells(1, col), Cells(N, col)) rng.Value2 = rng.Value2 Next col End Sub ``` If you have columns like B:E then you need to go through them individually to find the last cell with data in each. Upvotes: 2 <issue_comment>username_2: I have this RON code where i have tweaked my excel where in excel file path there is formula and while i am trying to send an email VBA is picking reading it as formula and giving error no cells were found in line For Each FileCell In rng.SpecialCells(xlCellTypeConstants) thankful if you can please advice code copied here Sub Send\_Files() 'Working in Excel 2000-2016 'For Tips see: <http://www.rondebruin.nl/win/winmail/Outlook/tips.htm> Dim OutApp As Object Dim OutMail As Object Dim sh As Worksheet Dim cell As Range Dim FileCell As Range Dim rng As Range ``` With Application .EnableEvents = False .ScreenUpdating = False End With Set sh = Sheets("Sheet1") Set OutApp = CreateObject("Outlook.Application") For Each cell In sh.Columns("B").Cells.SpecialCells(xlCellTypeConstants) 'Enter the path/file names in the K:Z column in each row Set rng = sh.Cells(cell.Row, 1).Range("K1:Z1") If cell.Value Like "?*@?*.?*" And _ Application.WorksheetFunction.CountA(rng) > 0 Then Set OutMail = OutApp.CreateItem(0) With OutMail .to = cell.Value .Subject = "XXXXXX" .Body = "XXXXX" 'rng = rng.Text For Each FileCell In rng.SpecialCells(xlCellTypeConstants) If Trim(FileCell) <> "" Then If Dir(FileCell.Value) <> "" Then .Attachments.Add FileCell.Value End If End If Next FileCell .Send 'Or use .Display End With Set OutMail = Nothing End If Next cell Set OutApp = Nothing With Application .EnableEvents = True .ScreenUpdating = True End With ``` End Sub Upvotes: 0
2018/03/20
961
3,482
<issue_start>username_0: This my code of rest controller ``` @RequestMapping(value = "/?username={username}&password={<PASSWORD>}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}) @ResponseStatus(value= HttpStatus.OK) public UserDetails getUserDetails(@PathVariable("username") String username , @PathVariable("password") String password ) { System.out.println("This is controller"+username+","+password); UserDetails userDetails = userService.loadUserByUsername(username); System.out.println("Get Password "+userDetails.getPassword()); if(userDetails.getUsername().equals(username) && userDetails.getPassword().equals(password)) { return userDetails; } return null; } ``` When i pass url in postman the out pout will be <http://localhost:8080/hello/?username=<EMAIL>&password=<PASSWORD>> out put must be return json value but it will print nothing<issue_comment>username_1: Put the column you require in this line ``` Set rng = Range(Cells(1, 1), Cells(N, Columns.Count)) ``` e.g. If you want to use column E ``` Set rng = Range(Cells(1, 5), Cells(N, 5)) ``` If you want to use multiple columns you can use a loop to go through them ``` Sub FormulaToValue() Dim N As Long, rng As Range Dim arr As Variant arr = Array("B", "E", "F", "G", "H", "I", "J") ' Read through each column Dim col As Variant For Each col In arr N = Cells(Rows.Count, col).End(xlUp).Row Set rng = Range(Cells(1, col), Cells(N, col)) rng.Value2 = rng.Value2 Next col End Sub ``` If you have columns like B:E then you need to go through them individually to find the last cell with data in each. Upvotes: 2 <issue_comment>username_2: I have this RON code where i have tweaked my excel where in excel file path there is formula and while i am trying to send an email VBA is picking reading it as formula and giving error no cells were found in line For Each FileCell In rng.SpecialCells(xlCellTypeConstants) thankful if you can please advice code copied here Sub Send\_Files() 'Working in Excel 2000-2016 'For Tips see: <http://www.rondebruin.nl/win/winmail/Outlook/tips.htm> Dim OutApp As Object Dim OutMail As Object Dim sh As Worksheet Dim cell As Range Dim FileCell As Range Dim rng As Range ``` With Application .EnableEvents = False .ScreenUpdating = False End With Set sh = Sheets("Sheet1") Set OutApp = CreateObject("Outlook.Application") For Each cell In sh.Columns("B").Cells.SpecialCells(xlCellTypeConstants) 'Enter the path/file names in the K:Z column in each row Set rng = sh.Cells(cell.Row, 1).Range("K1:Z1") If cell.Value Like "?*@?*.?*" And _ Application.WorksheetFunction.CountA(rng) > 0 Then Set OutMail = OutApp.CreateItem(0) With OutMail .to = cell.Value .Subject = "XXXXXX" .Body = "XXXXX" 'rng = rng.Text For Each FileCell In rng.SpecialCells(xlCellTypeConstants) If Trim(FileCell) <> "" Then If Dir(FileCell.Value) <> "" Then .Attachments.Add FileCell.Value End If End If Next FileCell .Send 'Or use .Display End With Set OutMail = Nothing End If Next cell Set OutApp = Nothing With Application .EnableEvents = True .ScreenUpdating = True End With ``` End Sub Upvotes: 0
2018/03/20
690
2,524
<issue_start>username_0: I have built an angular 4 application with .Net core 2.0, visual studio 2017, and deployed to production server on IIS web server. The routing is working fine on localhost when refresh,but not working on live. I saw some answers in stackoverflow for IIS in web.config file. But I don't have web.config file under my project structure. can I add it manually or how can I fix it. ``` ``` Here is my app.routing file ``` const appRoutes: Routes = [ { path: '', redirectTo: 'admin-dashboard', pathMatch: 'full' }, { path: 'login', component: LoginComponent }, { path: 'forgotpassword', component: ForgotPasswordComponent }, { path: 'user-dashboard', component: DashboardComponent, canActivate: [AuthGuard] }, { path: 'notifications', component: NotificationsComponent, canActivate: [AuthGuard] }, { path: 'admin-dashboard', component: AdminDashboardComponent, canActivate: [AuthGuard], children: [ { path: '', component: ChairmanMessagesComponent, canActivate: [AuthGuard]}, { path: 'quotes', component: QuotesComponent, canActivate: [AuthGuard] }, { path: 'users', component: UsersComponent, canActivate: [AuthGuard] }, { path: 'notifications', component: AdminNotificationsComponent, canActivate: [AuthGuard] }, ] ``` }, ]; ``` export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes); ``` Please kindly let me know.<issue_comment>username_1: Routed apps must fallback to index.html so please look at this [link](https://angular.io/guide/deployment#routed-apps-must-fallback-to-indexhtml) and add config for IIS if that is what you are using,or edit your config here ``` ``` Upvotes: 0 <issue_comment>username_2: In back-end (server side) just map all (404) error/unrecognized requests to your index (which includes all angular build scripts).then it returns the index. In front-end, u can get what u need.It maps to the page which u need. eg:- [In spring Boot back-end this is an example answer](https://stackoverflow.com/questions/42865084/redirect-unknown-requests-to-index-html-in-springboot) Upvotes: 2 <issue_comment>username_3: I had the same problem when refreshing the browser on a route like: /users I fixed it by creating a folder called: users and inside a file: index.html ``` redirect users window.location.href = 'http://my-server:4200/'; ``` other solutions that i have read: 1) make your server redirect to index.html on a 404 error. 2) make your apache or iis add /index.html at the end of every route path Upvotes: 1
2018/03/20
409
1,306
<issue_start>username_0: I need to process two lists in `Ajax` success function. The below simple code works well for a single list but doesn't work with 2 lists. How can we process 2 lists separately in a `success function`. **jQuery Ajax** ``` success: function(data) { $.each(data, function() { $.each(this, function(k, v) { //do something with v }); }); } ``` **views.py** ``` lst1 = [1, 2, 3, 4, 5] lst2 = ['a', 'b', 'c', 'd', 'e'] context = { 'labels' : lst1, 'sk_labels': lst2 } return HttpResponse(json.dumps(context), content_type='application/json') ```<issue_comment>username_1: I had almost the same problem. Solution was pretty simple. Try using in first Jquery function call. It helped me parsing data correctly. > > JSON.parse(data); > > > ``` success: function(data) { $.each(JSON.parse(data), function() { $.each(this, function(k, v) { //do something with v }); });} ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: Refer to [`jQuery.each()`](http://api.jquery.com/jquery.each/)'s documentation. Try the following: ``` success: function(data) { $.each(data, function(contextKey, values) { $.each(values, function(index, value) { // do something with value }); }); } ``` Upvotes: 0
2018/03/20
476
1,728
<issue_start>username_0: I'm trying to save the application's root state on `mounted` lifecycle of VueJS and freeze the copy in `$root`'s `data`, and my attempt is as following, ``` mounted() { this.globalState = this.$store.state; }, data () { return { globalState: null } } ``` However this approach is updating `globalState` so I came up with another way to freeze it by using `Object.freeze()` but with no luck it keeps updating. Also I've tried to copy the `this.$store.state` to a `const` variable and update `globalState` via it, but it also fails. My last attempt is as following, I know it's an ugly code but please bear with it. ``` let emptyObj = {}; Object.defineProperty(emptyObj, 'globalState',{ value: this.$store.state, enumerable: false, configurable: false, writable: false } ); this.globalState = emptyObj.globalState; ``` My question is, how can I copy and freeze the initial state of the application and store it in single `data`?<issue_comment>username_1: I had almost the same problem. Solution was pretty simple. Try using in first Jquery function call. It helped me parsing data correctly. > > JSON.parse(data); > > > ``` success: function(data) { $.each(JSON.parse(data), function() { $.each(this, function(k, v) { //do something with v }); });} ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: Refer to [`jQuery.each()`](http://api.jquery.com/jquery.each/)'s documentation. Try the following: ``` success: function(data) { $.each(data, function(contextKey, values) { $.each(values, function(index, value) { // do something with value }); }); } ``` Upvotes: 0
2018/03/20
1,039
3,749
<issue_start>username_0: I created a modal which displays information specific to their id entries and placed the Approve and Reject button as below. [Screenshot of modal](https://i.stack.imgur.com/sYfbM.jpg) When a user click on "Accept" or "Reject", it needs to pass id related to the viewed entries so the user can perform the requested action, whether to accept or reject the entries (default status is 'pending'). **vendor.blade.php** ```html @method('PUT') @csrf Approve @method('PUT') @csrf Reject ``` In **VendorController.php** ``` public function index() { $vendors = DB::select('select company_name, roc_no, created_at from mides_vendors'); $vendor_id = Vendor::where('status', 'Pending'); return view('panel.vendor', ['vendors' => $vendors]); } ``` **ApprovedVendorController.php** ```html php namespace App\Http\Controllers; use App\User; use App\Vendor; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class ApproveVendorController extends Controller { public function approve(Request $request, $id) { DB::insert('insert into mides_users(name, email, password) select name,roc_no,password from mides_vendors where id = :id', ['id' = $id]); DB::update('update mides_vendors set status = :status where id = :id', ['status' => 'Approved', 'id' => $id]); return redirect('/'); } public function reject(Request $request, $id) { DB::update('update mides_vendors set status = :status where id = :id', ['status' => 'Rejected', 'id' => $id]); return redirect('/'); } } ``` **routes/web.php** ```html Route::prefix('/panel')->group(function () { Route::get('/dashboard', function () { return view('panel.dashboard'); }); /* These routes only display the information/modal Route::get('/approve-vendor', 'VendorController@showNewRegistration'); // return vendor.blade.php Route::get('/vendor-approved', 'VendorController@showApproved'); // return vendor-approve.blade.php Route::get('/vendor-reject', 'VendorController@showRejected'); // return vendor-reject.blade.php /* These route used to perform the specific action */ Route::put('/approve/{id}', 'ApproveVendorController@approve')->name('approve'); Route::put('/reject{id}', 'ApproveVendorController@reject')->name('reject'); }); ``` However, it returns this error. [Error got after clicking Accept or Reject](https://i.stack.imgur.com/248Mr.jpg) How do I pass the id of data? I tried as shown in [pass the database value to modal popup](https://stackoverflow.com/questions/39827189/pass-the-database-value-to-modal-popup) to create the modal using second answer option (besides the ajax ones). Do I need to create another controller for these? Edited: after do as explained by @Wreigh, it works, means that the status changed from 'pending' to 'accept/reject'. But, when I return to the previous page, which is the `/panel/approve-vendor` (the page is used for showing the pending list modal) then I got the error `undefined variable vendorId`.<issue_comment>username_1: I had almost the same problem. Solution was pretty simple. Try using in first Jquery function call. It helped me parsing data correctly. > > JSON.parse(data); > > > ``` success: function(data) { $.each(JSON.parse(data), function() { $.each(this, function(k, v) { //do something with v }); });} ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: Refer to [`jQuery.each()`](http://api.jquery.com/jquery.each/)'s documentation. Try the following: ``` success: function(data) { $.each(data, function(contextKey, values) { $.each(values, function(index, value) { // do something with value }); }); } ``` Upvotes: 0
2018/03/20
362
1,320
<issue_start>username_0: I have parent form called MainBackground and a user control named LoginUI. LoginUI is docked into the MainBackground. I need to change enability of a button (InfoButton) located in parent form to "true" when user clicks on the button "Log in" in the control form. But I can't access the parent button's properties. Control form's button clicking event code: ``` private void button1_Click(object sender, EventArgs e) { MainBackground.infoButton.Enabled = true; } ``` I tried solving it with parent controls, but still it doesn't seem to work. Thanks for any help!<issue_comment>username_1: I had almost the same problem. Solution was pretty simple. Try using in first Jquery function call. It helped me parsing data correctly. > > JSON.parse(data); > > > ``` success: function(data) { $.each(JSON.parse(data), function() { $.each(this, function(k, v) { //do something with v }); });} ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: Refer to [`jQuery.each()`](http://api.jquery.com/jquery.each/)'s documentation. Try the following: ``` success: function(data) { $.each(data, function(contextKey, values) { $.each(values, function(index, value) { // do something with value }); }); } ``` Upvotes: 0
2018/03/20
479
1,562
<issue_start>username_0: I have a java servlet service which need to be invoked from dot net application. I have found some code but in response stream i am receiving null.Where as when invoked through html it is working fine. Below is html code which is working when executed and xml structured data is pasted in textbox and invoked. ``` ``` below is my input in xml ``` xml version="1.0"? WMConnect abcuat 172.18.1.57 username test1234 Y en-US U ``` and output is as below in xml. [![enter image description here](https://i.stack.imgur.com/Q5FW1.png)](https://i.stack.imgur.com/Q5FW1.png) this works for html but from dot net application it throws null value. below code i have tried . [click here to check code i have tried](https://stackoverflow.com/questions/7874943/how-to-call-http-based-java-web-serviceservlet-in-asp-net). Thank you in advance.<issue_comment>username_1: I had almost the same problem. Solution was pretty simple. Try using in first Jquery function call. It helped me parsing data correctly. > > JSON.parse(data); > > > ``` success: function(data) { $.each(JSON.parse(data), function() { $.each(this, function(k, v) { //do something with v }); });} ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: Refer to [`jQuery.each()`](http://api.jquery.com/jquery.each/)'s documentation. Try the following: ``` success: function(data) { $.each(data, function(contextKey, values) { $.each(values, function(index, value) { // do something with value }); }); } ``` Upvotes: 0
2018/03/20
394
1,291
<issue_start>username_0: I have the following libraries being used in my AWS Lambda function: ``` pytz/ nltk/ nltk-3.2.5/ numpy/ psycopg2/ pandas/ spacy/ ``` But while I zip and upload these libraries along with my code on AWS S3 and link the S3 zip to Lambda Function it gives the following error: > > Unzipped size must be smaller than 262144000 bytes > This what happens when you try to save the zipped file on lambda > > > The size of my Zip is 62 Mb and AWS Lambda supports only 50MB per lambda function. Is there any better way in AWS to achieve this?<issue_comment>username_1: I had almost the same problem. Solution was pretty simple. Try using in first Jquery function call. It helped me parsing data correctly. > > JSON.parse(data); > > > ``` success: function(data) { $.each(JSON.parse(data), function() { $.each(this, function(k, v) { //do something with v }); });} ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: Refer to [`jQuery.each()`](http://api.jquery.com/jquery.each/)'s documentation. Try the following: ``` success: function(data) { $.each(data, function(contextKey, values) { $.each(values, function(index, value) { // do something with value }); }); } ``` Upvotes: 0
2018/03/20
1,547
5,531
<issue_start>username_0: I'm using `react-toastify` and I can't get a simple toast to be rendered... ``` import React from "react"; import { toast } from 'react-toastify'; class MyView extends React.Component<{}, {}> { constructor() { super(); this.state = { }; } componentDidMount() { toast("Hello", { autoClose: false }); } notify = () => toast("Hello", { autoClose: false }); render() { return ( Notify )} } ``` package.json (in "dependencies" section) ``` "react": "^16.2.0", "react-toastify": "^3.2.2" ``` If I debug it, I see that my toasts are queued, \_EventManager2 never gets the \_constant.ACTION.MOUNTED event that normally emits the toasts from the queue... ``` /** * Wait until the ToastContainer is mounted to dispatch the toast * and attach isActive method */ _EventManager2.default.on(_constant.ACTION.MOUNTED, function (containerInstance) { container = containerInstance; toaster.isActive = function (id) { return container.isToastActive(id); }; queue.forEach(function (item) { _EventManager2.default.emit(item.action, item.content, item.options); }); queue = []; }); ``` ..so there might be something wrong with that ToastContainer but what? I just use the sample code from the documentation. Thank you for your help!<issue_comment>username_1: You have to also `import 'react-toastify/dist/ReactToastify.css';` ``` import React, { Component } from 'react'; import { ToastContainer, toast } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; // minified version is also included // import 'react-toastify/dist/ReactToastify.min.css'; class App extends Component { notify = () => toast("Wow so easy !"); render(){ return ( Notify ! ); } } ``` Upvotes: 7 <issue_comment>username_2: Before declaring your class, add the following line: ``` toast.configure(); ``` Upvotes: 4 <issue_comment>username_3: The other solutions didn't work for me - turns out I wasn't passing a string to the `toast.*` function. For example: ``` getSomethingFromApi() .then((response) => { // this works fine because response.message is a string toast.notify(response.message) }) .catch((error) => { // this will fail to render because error is an object, not a string toast.error(error) }) ``` Upvotes: 3 <issue_comment>username_4: Even better, import minified css: `import 'react-toastify/dist/ReactToastify.min.css';` or in case you are importing it in .scss file `@import '~react-toastify/dist/ReactToastify.min.css';` Upvotes: 3 <issue_comment>username_5: My mistake was importing toast without {} curly braces because my course instructor did so. Try to change this: ``` import toast from 'react-toastify'; ``` To: ``` import { toast } from 'react-toastify'; ``` Also according to all other 'react-toastify' stackoverflow responses, installing latest version causes problem. So try uninstalling it and install older version that your course instructor did or version 4.1 seems to be working for most people. Uninstall first: ``` npm uninstall react-toastify --save ``` Then install 4.1 version: ``` npm i [email protected] ``` Upvotes: 0 <issue_comment>username_6: install react-toastify using command ```sh npm i react-toastify ``` Then: ```js import {ToastContainer,toast} from 'react-toastify' ``` and in return add ```js ``` and after that when you do `toast('hy')` then it will show toast Upvotes: 4 <issue_comment>username_7: For me moving `ReactToastify.css` above `toast` solved the issue! ``` import 'react-toastify/dist/ReactToastify.css'; // import first import { ToastContainer, toast } from 'react-toastify'; // then this ``` Upvotes: 2 <issue_comment>username_8: You need to remember to include the in your render. Upvotes: 2 <issue_comment>username_9: To make use of the react-toastify, Please follow below steps:- 1. Install the npm package npm i toastify --save 2. Import the react-toastify as shown below in that given order import 'react-toastify/dist/ReactToastify.css'; // import first import { ToastContainer, toast } from 'react-toastify'; // then this Upvotes: 0 <issue_comment>username_10: ``` import React from "react"; import { ToastContainer,toast } from 'react-toastify'; // <- add ToastContainer import 'react-toastify/dist/ReactToastify.css'; // <- add line class MyView extends React.Component<{}, {}> { constructor() { super(); this.state = { }; } componentDidMount() { toast("Hello", { autoClose: false }); } notify = () => toast("Hello", { autoClose: false }); render() { return ( Notify {/\* <- add line \*/} )} } ``` Upvotes: 0 <issue_comment>username_11: you have to import this CSS statement in the component that you want to render the toastify at ``` import 'react-toastify/dist/ReactToastify.css'; ``` Upvotes: 1 <issue_comment>username_12: Tried everything here but nothing work then I move the following lines in App.js then it start working. ``` import { ToastContainer, toast } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; ``` Upvotes: 1 <issue_comment>username_13: ```js // React-Tostify configuration import "react-toastify/dist/ReactToastify.css"; import {ToastContainer} from "react-toastify"; ``` maintain this order and include in return This worked for me! Upvotes: 0
2018/03/20
858
3,742
<issue_start>username_0: * I am using "TextWebSocketHandler" for websockets and "WebSocketConfigurer" to configure the websocket. * I have a scenario where different instances of the handler needs to be gererated. **For example:** if I am doing auction for some items, then I need to generate seperate WebSocketHandler instances for each auctionId. Could we attach "auctionId" as path parameter to the url so that different instance gets generated for different auction? Or Is there any other way to achieve this? This is how I am adding the handler: ``` @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(websocketTestHandler(), "/websocket-test"); } ```<issue_comment>username_1: If you want to use a `TextWebSocketHandler`, you could pass the auction id as part of the URL path. You'll have to copy the path to the WebSocket session during handshake (this is the only place where you'll get access to the `ServerHttpRequest` as the handshake is an http request) and then retrieve the attribute from your handler. Here's the implementation: ``` @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(auctionHandler(), "/auction/*") .addInterceptors(auctionInterceptor()); } @Bean public HandshakeInterceptor auctionInterceptor() { return new HandshakeInterceptor() { public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map attributes) throws Exception { // Get the URI segment corresponding to the auction id during handshake String path = request.getURI().getPath(); String auctionId = path.substring(path.lastIndexOf('/') + 1); // This will be added to the websocket session attributes.put("auctionId", auctionId); return true; } public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) { // Nothing to do after handshake } }; } @Bean public WebSocketHandler auctionHandler() { return new TextWebSocketHandler() { public void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException { // Retrieve the auction id from the websocket session (copied during the handshake) String auctionId = (String) session.getAttributes().get("auctionId"); // Your business logic... } }; } } ``` **Client:** ``` new WebSocket('ws://localhost:8080/auction/1'); ``` Even if this is a working solution, I would recommend you taking a look at [STOMP over WebSockets](https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#websocket-stomp), it will give you more flexibility. Upvotes: 5 [selected_answer]<issue_comment>username_2: Another option would be to get the value from the session URI. See example below where I check if the session contains the Box value. URI is like /chat/{box} ``` @Override public void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException { Map value = new Gson().fromJson(message.getPayload(), Map.class); String sender = value.get("sender"); String content = value.get("content"); String box = value.get("box"); for (WebSocketSession webSocketSession : sessions) { LOGGER.info("Get messages on box {} and URI {}", box, session.getUri().toString()); if (webSocketSession.getUri().toString().contains(box)) { webSocketSession.sendMessage(new TextMessage(sender + ": " + content + " !")); } } } ``` In that case you don't need an interceptor. Upvotes: 2
2018/03/20
743
2,740
<issue_start>username_0: I have just opened an old project here at work. Someone appears to have changed the indentation. It's set to 2 spaces instead of four space tabbing. [![enter image description here](https://i.stack.imgur.com/NYv7w.png)](https://i.stack.imgur.com/NYv7w.png) What I have tried: 1. I tried doing a `Ctrl` + `K``D` but that hasn't changed it back to proper indentation. 2. I Deleted the `_ReSharper.Caches` directory, and a new one is just created, no change to the indentation. When those didn't work, I have started comparing settings in my visual studio with two different solutions. Resharper settings appear to be identical so are the settings in visual studio. **Re-sharper settings** [![enter image description here](https://i.stack.imgur.com/2Zfx7.png)](https://i.stack.imgur.com/2Zfx7.png) **Visual studio settings** [![enter image description here](https://i.stack.imgur.com/cxSn9.png)](https://i.stack.imgur.com/cxSn9.png) Which makes me think this must be in one of the project files or something? If it's not an issue with the settings in my visual studio, what's overriding the tabbing? Of note when the project loads I swear it loads with proper indentation and then it's reformatted in the last second. Not sure it matters, but the projects are .net core 1.0 there are three projects in the solution all three appear to be affected. Hope someone has a fix for this; it's really hard to read it like this.<issue_comment>username_1: Visual Studio may be using an [.editorconfig](https://learn.microsoft.com/en-us/visualstudio/ide/create-portable-custom-editor-options) file in the project's directory (or in any parent directory) which allows for a consistent code style within a codebase regardless of user settings. Visual Studio should indicate this in the lower left-hand area of the IDE window. If this is the case, you'll need to modify `.editorconfig` and define a new style in order to change the configuration for the automatic formatting tools. Upvotes: 6 [selected_answer]<issue_comment>username_2: As people says in answers and comments this is probably a `.editorconfig`. In our case a developer started using VS Code and when upgrading to VS 2017 Visual Studio also accepts these files. This was the value in the file that was automatically added: ``` [*] end_of_line = crlf insert_final_newline = true indent_style = space indent_size = 2 trim_trailing_whitespace = true ``` By adding this we could use C# normally and the developer who wanted to use VS Code could continue to do that: ``` [*.cs] indent_style = space indent_size = 4 ``` <https://developercommunity.visualstudio.com/content/problem/44231/cant-set-indent-level-to-4-spaces-in-vs-2017.html> Upvotes: 4
2018/03/20
806
2,620
<issue_start>username_0: I am building a map structure by extracting 30-40 keys from unstructured text rows from messy csv data. i am extracting using regex on this messy data row , lot of time those values are not there so it generates exception, I put these 40-50 statements in try , catch block and able to parse but issue is one exception is generated other statement will not be extracted so I started putting each comment inside a try catch block . ``` try{ statment: 1 statment:2 . . .statement 30 } ``` how to handle elegantly such scenario in scala to capture exception in each statement and continue building map structure without puting each statement inside separate try catch block. ``` try{ stat1 } try{ stat2 } .... ``` Actual Code:- ``` var mp = scala.collection.immutable.Map[String, Any]() try{ // working on json payload var jsonpayloadstr= cleanstr.split("\"\\{\"")(1).split(",\"\\[")(0).split("\\}\",")(0).toString jsonpayloadstr ="{\""+jsonpayloadstr +"}" var jobj=scala.util.parsing.json.JSON.parseFull(jsonpayloadstr) var bdmap=jobj.get.asInstanceOf[Map[String, Map[String, Any]]]("Boundary") bdmap.map(x=>mp=mp+(x._1->x._2)) //batterystatus var batterystatus= jobj.get.asInstanceOf[Map[String, Map[String, Map[String,Double]]]]("Notification")("Data")("BatteryStatus") mp=mp+("BatteryStatus"->batterystatus.toInt) var locationMap= jobj.get.asInstanceOf[Map[String, Map[String, Map[String,Map[String,Any]]]]]("Notification")("Data")("Location") locationMap.map(x=>mp=mp+(x._1->x._2)) //tagid var tagId= jobj.get.asInstanceOf[Map[String, Map[String, Map[String,Any]]]]("Notification")("Data")("TagID") mp=mp+("TagID"-> tagId) //brechID var isBreached=jobj.get.asInstanceOf[Map[String, Map[String, Map[String,List[Map[String,Any]]]]]]("Notification")("Data")("SensorData")(0)("IsBreached") mp=mp+("IsBreached"-> isBreached) } catch{ case e: Exception => { println("Oops none get 123455dsdsd677") } } ``` Thanks<issue_comment>username_1: If you want to keep on parsing the other variables even if one fails, you can do something like: ``` val batterystatus = Try(...).toOption val locationMap = Try(...).toOption ... ``` That way you'll have values for everything that parsed correctly and you'll be forced to think about how to handle the ones that didn't. Upvotes: 3 [selected_answer]<issue_comment>username_2: I came to know a new way from reddit scala forum:- We shouldn't use exception-based extractions. Put your regexes in a list and map the list with the according extraction function, something like regex => Option[element] and flatten the list after. Upvotes: 0
2018/03/20
1,457
5,835
<issue_start>username_0: I've discovered a weird behavior on iOS 11 when I push `UIViewController` and change the `UINavigationBar` color to transparent. Important thing is that I'm using `largeTitles`. 1. I want to change red color of the navigation bar to transparent and this works fine. 2. However, if I tap on backButton, disable transparent style and red color style again something bad happened. NavigationBar on the ViewController is not red but still transparent. 3. As @Menoor Ranpura suggest I add another line which sets also a `backgroundColor` of view in `UIViewController` - and this is fine workaround when you set the same color like on `UINavigationBar`. However, it's not the solution for the problem because the large part of the navigation bar is still transparent. You can see it when you set the different color for a background. For example, I set the yellow. You can see the example here: [![enter image description here](https://i.stack.imgur.com/UenjC.gif)](https://i.stack.imgur.com/UenjC.gif) Question ======== How to properly change the navigation bar color **from transparent** to **red again**, when the `prefersLargeTitles` is set to `true`? Code ==== ``` class ExampleTableTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: "reuseID") navigationController?.navigationBar.redNavigationBar() title = "Red NavBar" } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) view.backgroundColor = .yellow navigationController?.navigationBar.redNavigationBar() } } //Transparent Navigation bar controller class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() title = "Transparent NavBar" view.backgroundColor = .blue self.navigationController?.navigationBar.prefersLargeTitles = true } override func viewWillAppear(_ animated: Bool) { self.navigationController?.navigationBar.transparentNavigationBar() } } extension UINavigationBar { func redNavigationBar() { setBackgroundImage(nil, for: .default) shadowImage = nil prefersLargeTitles = true tintColor = .white largeTitleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white] titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white] barTintColor = .red } func transparentNavigationBar() { setBackgroundImage(UIImage(), for: .default) shadowImage = UIImage() } } ``` Some tips that I've already tested: ----------------------------------- * Everything works fine when `prefersLargeTitles` is set to `false` * Everything works fine when `prefersLargeTitles` is set to `true`, but `navigationBar` changes are between non transparent colors. For example, if changing between green <-> yellow * I don't want to set `backgroundColor` on view. It's not an solution but kind of a workaround for this. Here you can see a screen from XCode: [![enter image description here](https://i.stack.imgur.com/4lInn.png)](https://i.stack.imgur.com/4lInn.png) Interesting fact is that, there is something called: `_UINavigationBarLargeTitleView` which is transparent. **How to access it?** ### Related problems: * [Make UINavigationBar transparent](https://stackoverflow.com/questions/2315862/make-uinavigationbar-transparent) * [UINavigationBar change colors on push](https://stackoverflow.com/questions/40243112/uinavigationbar-change-colors-on-push/40250912) **You can find example project here: <https://github.com/kamwysoc/LargeTitlesNavigationBarTransition>** --- UPDATE referring to @Menoor Ranpura answer ========================================== Code that @Menoor Ranpura suggest is a kind of a workaround. It's not a solution to set the same `backgroundColor` on `UIViewController` view like `UINavigationBar` has. However, I go a bit further and I change the color for a different than `UINavigationBar` controller has. And as you can see on above gif, when the `largeTitle` appears, the navigation bar becomes yellow - which means that is transparent - because we're able to see the yellow background of view.<issue_comment>username_1: call **greenNavigationBar()** in **viewWillAppear** ``` override func viewWillAppear(_ animated: Bool) { view.backgroundColor = .red // this is kind of a workaround, However if you set color which will be different that `UINavigationBar` color you see that `largeTitle` is transparent because it shows a `backgroundColor` of a ViewController view. navigationController?.navigationBar.greenNavigationBar() title = "Green Title" navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Next", style: .plain, target: self, action: #selector(showTransparentViewController)) } ``` Upvotes: 1 <issue_comment>username_2: Here's how you access `_UINavigationBarLargeTitleView`. I think you should submit a radar if you haven't already because setting the background colour this private ivar is only a hack and the issue at large still exists. Swift 3/4: ``` if let navigationBar = navigationController?.navigationBar, let titleView = navigationBar.subviews.first(where: {type(of: $0) == NSClassFromString("_UINavigationBarLargeTitleView")}) { } ``` Objective-C: ``` __block UIView *titleView; [navigationController.navigationBar.subviews enumerateObjectsUsingBlock:^(UIView *subview, NSUInteger index, BOOL *stop) { Class _UINavigationBarLargeTitleView = NSClassFromString(@"_UINavigationBarLargeTitleView"); if ([subview isKindOfClass:_UINavigationBarLargeTitleView]) { titleView = subview; *stop = YES; } }]; ``` Upvotes: 0
2018/03/20
474
1,788
<issue_start>username_0: Here is my code snippet. What am I doing wrong? Not able to replace the string. ``` f = open("template.html", "r") lines = f.read() string = ''' High ----- #### ''' if string in lines: print lines lines.replace("", "") print lines ```<issue_comment>username_1: call **greenNavigationBar()** in **viewWillAppear** ``` override func viewWillAppear(_ animated: Bool) { view.backgroundColor = .red // this is kind of a workaround, However if you set color which will be different that `UINavigationBar` color you see that `largeTitle` is transparent because it shows a `backgroundColor` of a ViewController view. navigationController?.navigationBar.greenNavigationBar() title = "Green Title" navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Next", style: .plain, target: self, action: #selector(showTransparentViewController)) } ``` Upvotes: 1 <issue_comment>username_2: Here's how you access `_UINavigationBarLargeTitleView`. I think you should submit a radar if you haven't already because setting the background colour this private ivar is only a hack and the issue at large still exists. Swift 3/4: ``` if let navigationBar = navigationController?.navigationBar, let titleView = navigationBar.subviews.first(where: {type(of: $0) == NSClassFromString("_UINavigationBarLargeTitleView")}) { } ``` Objective-C: ``` __block UIView *titleView; [navigationController.navigationBar.subviews enumerateObjectsUsingBlock:^(UIView *subview, NSUInteger index, BOOL *stop) { Class _UINavigationBarLargeTitleView = NSClassFromString(@"_UINavigationBarLargeTitleView"); if ([subview isKindOfClass:_UINavigationBarLargeTitleView]) { titleView = subview; *stop = YES; } }]; ``` Upvotes: 0
2018/03/20
387
1,379
<issue_start>username_0: I need the `AppTheme.colorAccent` to be brown but I need my `Snackbar` action color to be blue. How to change action button color of `Snackbar` from style without changing `AppTheme.colorAccent`? I've try this code but it does not work : ``` <item name="colorAccent">#3097ff</item> ```<issue_comment>username_1: You can define the color in the `colors.xml` and use it in the `snackbar` as follows: ``` val mySnackbar = Snackbar.make(findViewById(R.id.container),"Item added to cart.", Snackbar.LENGTH_SHORT) mySnackbar.setAction("view cart", View.OnClickListener {/*action to be triggered*/ }) mySnackbar.setActionTextColor(/*color defined*/) mySnackbar.show() ``` I implemented this in Kotlin. Upvotes: 0 <issue_comment>username_2: With the Material Components Library you can do it. Just add the **`snackbarButtonStyle`** attribute in your theme app. ``` <!-- Style to use for action button within a Snackbar in this theme. --> <item name="snackbarButtonStyle">@style/snackbar\_button</item> ... ``` Then define your custom style: ``` <item name="backgroundTint">@color/secondaryLightColor</item> <item name="android:textColor">@color/primaryDarkColor</item> ``` [![enter image description here](https://i.stack.imgur.com/m9ffe.png)](https://i.stack.imgur.com/m9ffe.png) It requires the version 1.1.0 of the library. Upvotes: 3
2018/03/20
301
989
<issue_start>username_0: Still wondering why its not working. ``` echo "[". $catrow['name'] . "]("$config_basedir. "/products.php?id=" . $catrow[)";} ``` I wanted to use a variable for the `products.php?id=&quot.`. Is there another way to solve this?<issue_comment>username_1: There is some issue in using quote in your code, please see the below code: ``` echo '['.$catrow['name'].']('.$config_basedir.'/products.php?id='.$catrow['name'].')'; ``` You can get value of `id` from URL as: `$id = $_GET["id"];` Upvotes: 0 <issue_comment>username_2: You really don't need the `"` . I think there is also a curly brace at the end of your which is also a possible problem. Kindly post the error php throws in your browser for more clarification Upvotes: -1 <issue_comment>username_3: Use this... ```html $catrow_name = $catrow['name']; $config_basedir = $config_basedir."/products.php?id=$catrow_name"; echo '['.$catrow['name'].']('.$config_basedir.')'; ``` Upvotes: 1 [selected_answer]
2018/03/20
870
2,762
<issue_start>username_0: I used to build my angular 5 projects with command: ``` ng build --prod --locale=de --base-href /onlineshopNP/de/ -op dist/de ``` I've updated my project to angular 6 and when I call the command, I'm getting an error like this: > > Schema validation failed with the following errors: > Data path "" should NOT have additional properties (o). > Error: Schema validation failed with the following errors: > Data path "" should NOT have additional properties (o). > at MergeMapSubscriber.registry.compile.pipe.operators\_1.concatMap.validatorResult [as project] (C:\Users\martin.kuenz\Documents\Angular\webshop\node\_modules\@angular-devkit\architect\src\architect.js:218:39) > at MergeMapSubscriber.\_tryNext (C:\Users\martin.kuenz\Documents\Angular\webshop\node\_modules\@angular-devkit\architect\node\_modules\rxjs\operators\mergeMap.js:122:27) > at MergeMapSubscriber.\_next (C:\Users\martin.kuenz\Documents\Angular\webshop\node\_modules\@angular-devkit\architect\node\_modules\rxjs\operators\mergeMap.js:112:18) > at MergeMapSubscriber.Subscriber.next (C:\Users\martin.kuenz\Documents\Angular\webshop\node\_modules\@angular-devkit\architect\node\_modules\rxjs\Subscriber.js:90:18) > at MergeMapSubscriber.notifyNext (C:\Users\martin.kuenz\Documents\Angular\webshop\node\_modules\@angular-devkit\architect\node\_modules\rxjs\operators\mergeMap.js:145:30) > at InnerSubscriber.\_next (C:\Users\martin.kuenz\Documents\Angular\webshop\node\_modules\@angular-devkit\architect\node\_modules\rxjs\InnerSubscriber.js:23:21) > at InnerSubscriber.Subscriber.next (C:\Users\martin.kuenz\Documents\Angular\webshop\node\_modules\@angular-devkit\architect\node\_modules\rxjs\Subscriber.js:90:18) > at SafeSubscriber.\_\_tryOrSetError (C:\Users\martin.kuenz\Documents\Angular\webshop\node\_modules\@angular-devkit\core\node\_modules\rxjs\Subscriber.js:248:16) > at SafeSubscriber.next (C:\Users\martin.kuenz\Documents\Angular\webshop\node\_modules\@angular-devkit\core\node\_modules\rxjs\Subscriber.js:188:27) > at MapSubscriber.\_next (C:\Users\martin.kuenz\Documents\Angular\webshop\node\_modules\@angular-devkit\core\node\_modules\rxjs\operators\map.js:85:26) > > > Can anybody help me? Thx<issue_comment>username_1: I've had a similar problem when I update from version 5 to version 6. Try with <https://update.angular.io/> This is a utility to define migration steps. I hope it helps. Upvotes: 0 <issue_comment>username_2: It seems that RxJS is causing problem, can you install rxjs-compat and check Upvotes: 0 <issue_comment>username_3: Create a fresh ng project using latest angular-cli and compare angular.json with your project's angular.json. You might be able to figure our the issue. Upvotes: 2 [selected_answer]
2018/03/20
392
1,530
<issue_start>username_0: Frequently `./sbt fastOptJS` throws a linking error at me, `Referring to non-existent method...`, that disappears if I run `./sbt clean` and then `./sbt fastOptJS` again. I was wondering, what could be a possible cause for this? Is this likely a `build.sbt` misconfiguration issue? Common coding style pitfall?<issue_comment>username_1: In my experience this is most often caused by incremental compiler not recompiling enough of your sources on certain changes. One particular issue I have seen is method signature changes where only the inferred return type changed to cause this, like when changing: ``` def x(a: Int, b: Double) = a ``` to ``` def x(a: Int, b: Double) = b ``` If this is the case, using explicit return types often helps: ``` def x(a: Int, b: Double): Double = a ``` (In reality more complex code is required to trigger the issue.) To me this happens both in Scala JS and Scala JVM. In Scala JVM it most often shows not during linking, but during execution, with the exception `NoSuchMethodError` thrown. Upvotes: 2 [selected_answer]<issue_comment>username_2: Although I have accepted another answer, I'm adding this one in the hope that it is useful to someone else who comes searching. <https://github.com/sbt/zinc/issues/249> Zinc's support for Macros is not perfect, and on occasion the Macro's definition changes, but some files using the Macro did not, and so their compiled code does not change, either, resulting in missing functions on the last step. Upvotes: 0
2018/03/20
483
1,897
<issue_start>username_0: The system environment check returned errors. Those errors will affect the functionality and stability of your TYPO3 CMS instance. Please check the install tool "System environment" for all details. The first image shows the typo3 backend status report error: ![**First image link** shows the typo3 backend status report error](https://i.stack.imgur.com/eIeCK.png) Here is the error on browser when I tried to access the frontend of the website: ![**Second image link** shows the error on browser when I tried to access the frontend of the website](https://i.stack.imgur.com/GJnrR.png) ![**3rd image ** shows screenshot of php error log](https://i.stack.imgur.com/LFQPj.png)<issue_comment>username_1: In my experience this is most often caused by incremental compiler not recompiling enough of your sources on certain changes. One particular issue I have seen is method signature changes where only the inferred return type changed to cause this, like when changing: ``` def x(a: Int, b: Double) = a ``` to ``` def x(a: Int, b: Double) = b ``` If this is the case, using explicit return types often helps: ``` def x(a: Int, b: Double): Double = a ``` (In reality more complex code is required to trigger the issue.) To me this happens both in Scala JS and Scala JVM. In Scala JVM it most often shows not during linking, but during execution, with the exception `NoSuchMethodError` thrown. Upvotes: 2 [selected_answer]<issue_comment>username_2: Although I have accepted another answer, I'm adding this one in the hope that it is useful to someone else who comes searching. <https://github.com/sbt/zinc/issues/249> Zinc's support for Macros is not perfect, and on occasion the Macro's definition changes, but some files using the Macro did not, and so their compiled code does not change, either, resulting in missing functions on the last step. Upvotes: 0
2018/03/20
867
2,343
<issue_start>username_0: i have a set of arrays: ``` $nums = array(2,3,1); $data = array(11,22,33,44,55,66); ``` what i want to do is to get a set of $data array from each number of `$nums` array, the output must be: ``` output: 2=11,22 3=33,44,55 1=66 ``` what i tried so far is to slice the array and remove the sliced values from an array but i didn't get the correct output. ``` for ($i=0; $i < count($nums); $i++) { $a = array_slice($data,0,$nums[$i]); for ($x=0; $x < $nums[$i]; $x++) { unset($data[0]); } } ```<issue_comment>username_1: Another alternative is to use another flavor [`array_splice`](http://php.net/manual/en/function.array-splice.php), it basically takes the array based on the offset that you inputted. It already takes care of the unsetting part since it already removes the portion that you selected. ``` $out = array(); foreach ($nums as $n) { $remove = array_splice($data, 0, $n); $out[] = $remove; echo $n . '=' . implode(',', $remove), "\n"; } // since nums has 2, 3, 1, what it does is, each iteration, take 2, take 3, take 1 ``` [Sample Output](https://3v4l.org/uUQVm) Also you could do an alternative and have no function usage at all. You'd need another loop though, just save / record the last index so that you know where to start the next num extraction: ``` $last = 0; // recorder $cnt = count($data); for ($i = 0; $i < count($nums); $i++) { $n = $nums[$i]; echo $n . '='; for ($h = 0; $h < $n; $h++) { echo $data[$last] . ', '; $last++; } echo "\n"; } ``` Upvotes: 2 <issue_comment>username_2: You can `array_shift` to remove the first element. ``` $nums = array(2,3,1); $data = array(11,22,33,44,55,66); foreach( $nums as $num ){ $t = array(); for ( $x = $num; $x>0; $x-- ) $t[] = array_shift($data); echo $num . " = " . implode(",",$t) . " "; } ``` This will result to: ``` 2 = 11,22 3 = 33,44,55 1 = 66 ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: This is the easiest and the simplest way, ``` php $nums = array(2,3,1); $data = array(11,22,33,44,55,66); $startingPoint = 0; echo "output:"."\n"; foreach($nums as $num){ $sliced_array = array_slice($data, $startingPoint, $num); $startingPoint = $num; echo $num."=".implode(",", $sliced_array)."\n"; } ? ``` Upvotes: 1
2018/03/20
446
1,406
<issue_start>username_0: ``` local a= >3500 local b= local c= <3700 ``` I don't know how I can make the 200 numbers in between into just the variable `b` ``` lives=1 while lives > 0 do math.randomseed(os.time()) local randomNumber1 = math.random(7200) local randomNumber = math.random(randomNumber1, 7200) print("Welcome to roulette!") local a= >3500 local b= local c= <3700 local number1 = io.read() local number1 = tonumber(number1) if number1== a and randomNumber == a then print("You won!") print("Number was "..randomNumber..) else if number1 == b and randomNumber == b then print("You won!") print("Number was "..randomNumber..) else if number1 == c and randomNumber == c then print("You won!") print("Number was "..randomNumber..) else print("Du tabte") print("Number was "..randomNumber..) io.read() lives=lives-1 end ```<issue_comment>username_1: You can't store multiple values in one variable. You can store many values in a table and put that single table in a variable, or into another table if you want many tables stored in one place. Upvotes: 0 <issue_comment>username_2: You can use a numeric for loop for that. In order to store multiple values in one variable use a table. ``` local numbers = {} local from = 3500 local to = 3699 for number = from, to do table.insert(numbers, number) end ``` Upvotes: 1
2018/03/20
1,169
3,426
<issue_start>username_0: Recently, I have studied 'Programming language' using standard [ML](http://en.wikipedia.org/wiki/ML_%28programming_language%29), and I've learned currying method(or something), so I applied it in Python. The below is simple function and currying. ``` def range_new(x, y): return [i for i in range(x, y+1)] def curry_2(f): return lambda x: lambda y: f(x, y) def uncurry_2(f): pass # I don't know it... print(range_new(1, 10)) curried_range = curry_2(range_new) countup = curried_range(1) print(countup(10)) print(curried_range(1)(10)) ``` The result is below. And it works well; with `curry_2` we can make a new function(`countup`). But, then I want to make an uncurried function. However, I don't know how I can make it. How can I do it? ``` [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ```<issue_comment>username_1: The easiest solution is to wrap the curried function again with code that uncurries it: ``` def uncurry_2(f): return lambda x, y: f(x)(y) uncurried_range = uncurry_2(curried_range) print(uncurried_range(1, 10)) ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: It's not exactly good style but you can access the variables in the closure using the (maybe CPython-only) [`__closure__`](https://docs.python.org/reference/datamodel.html#index-34) attribute of the returned `lambda`: ``` >>> countup.__closure__[0].cell_contents ``` This accesses the content of the innermost closure (the variable used in the innermost `lambda`) of your function `curry_2` and thus returns the function you used there. However in production code you shouldn't use that. It would be better to create a class (or function) for currying that supports accessing the uncurried function (which is something `lambda` does not provide). However some functools in Python support accessing the "decorated" function, for example `partial`: ``` >>> from functools import partial >>> countup = partial(range_new, 1) >>> print(countup(10)) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> countup.func ``` Upvotes: 3 <issue_comment>username_3: I believe by uncurry you mean you'd like to allow the function to accept more arguments. Have you considered using the "partial" function? It allows you to use as many arguments as desired when calling the method. ``` from functools import partial def f(a, b, c, d): print(a, b, c, d) g = partial(partial(f, 1, 2), 3) g(4) ``` Implementing it should be pretty straight forward ``` def partial(fn, *args): def new_func(*args2): newArgs = args + args2 fn(*newArgs) return new_func; ``` Note both the code presented in the original question, and the code above is known as partial application. Currying is more flexible than this typically - here's how you can do it with Python 3 (it is more tricky in Python 2). ``` def curry(fn, *args1): current_args = args1 sig = signature(fn) def new_fn(*args2): nonlocal current_args current_args += args2 if len(sig.parameters) > len(current_args): return new_fn else: return fn(*current_args) return new_fn j = curry(f) j(1)(2, 3)(4) ``` Now back to your code. range\_new can now be used in a few new ways: ``` print(range_new(1, 10)) curried_range = curry(range_new) countup = curried_range(1) print(countup(10)) countup_again = curried_range print(countup_again(1, 10)) ``` Upvotes: 3
2018/03/20
1,557
5,194
<issue_start>username_0: What is the correct way to declare a date in a swagger-file object? I would think it is: ``` startDate: type: string description: Start date example: "2017-01-01" format: date ``` But I see a lot of declarations like these: ``` startDate: type: string description: Start date example: "2017-01-01" format: date pattern: "YYYY-MM-DD" minLength: 0 maxLength: 10 ```<issue_comment>username_1: The [OpenAPI Specification](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#data-types) says that you must use: ```yaml type: string format: date # or date-time ``` The internet date/time standard used by OpenAPI is defined in [RFC 3339, section 5.6](https://www.rfc-editor.org/rfc/rfc3339#section-5.6) (effectively ISO 8601) and examples are provided in section 5.8. So for `date` values should look like "2018-03-20" and for `date-time`, "2018-03-20T09:12:28Z". As such, when using `date` or `date-time`, the `pattern` should be omitted. If you need to support dates/times formatted in a way that differs to RFC 3339, you are **not** allowed to specify your parameter as `format: date` or `format: date-time`. Instead, you should specify `type: string` with an appropriate `pattern` and remove `format`. Finally, note that a `pattern` of `"YYYY-MM-DD"` is invalid according to the specification: `pattern` must be a **regular expression**, not a placeholder or format string. Upvotes: 9 [selected_answer]<issue_comment>username_2: *pattern* should be a regular expression. This is stated in the [OpenAPI Specification](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#schema-object). > > *pattern* (This string SHOULD be a valid regular expression, according to the ECMA 262 regular expression dialect) > > > This is because OpenAPI objects are based off the JSON Schema specification. > > OpenAPI 2.0: This object is based on the JSON Schema Specification Draft 4 and uses > a predefined subset of it. > > > OpenAPI 3.0: This object is an extended subset of the JSON Schema Specification Wright Draft 00. > > > If a web service exposes a date or a date-time that doesn't conform to the Internet Date/Time Format described in [RFC3339](https://xml2rfc.tools.ietf.org/public/rfc/html/rfc3339.html#anchor14), then *date* and *date-time* are not valid values for the *format* field. The property must be defined as having a *type* equal to *string* without using *format*. Instead, *pattern* can be used to give a regular expression that defines the date or date-time pattern. This allows a client tool to automatically parse the date or date-time. I also recommend putting the format in the description field so human consumers can read it more easily. Upvotes: 3 <issue_comment>username_3: A correct example of declaring date in an Open API swagger file: ``` properties: releaseDate: type: date pattern: /([0-9]{4})-(?:[0-9]{2})-([0-9]{2})/ example: "2019-05-17" ``` Upvotes: 4 <issue_comment>username_4: For Swagger 2.0 --------------- ``` /room-availability: get: tags: - "realtime price & availability" summary: "Check realtime price & availability" description: "Check realtime price & availability" operationId: "getRealtimeQuote" produces: - "application/json" parameters: - in: "query" name: "checkInDate" description: "Check-in Date in DD-MM-YYYY format" type: "string" pattern: "^(3[01]|[12][0-9]|0[1-9])-(1[0-2]|0[1-9])-[0-9]{4}$" - in: "query" name: "numOfGuests" description: "Number of guests" type: "integer" format: "int16" - in: "query" name: "numOfNightsStay" description: "number of nights stay" type: "integer" format: "int16" - in: "query" name: "roomType" description: "Room type" type: "string" enum: - "King Size" - "Queen Size" - "Standard Room" - "Executive Suite" - in: "query" name: "hotelId" description: "Hotel Id" type: "string" ``` Upvotes: -1 <issue_comment>username_5: An example of OpenAPI 3 is based on document here: <https://swagger.io/docs/specification/data-models/data-types/> An optional format modifier serves as a hint at the contents and format of the string. OpenAPI defines the following built-in string formats: **date** – full-date notation as defined by RFC 3339, section 5.6, for example, 2017-07-21 **date-time** – the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z ``` BookingNoteRequest: type: object properties: note: type: string postedDate: type: string format: date example: '2022-07-01' postedTime: type: string format: date-time example: '2017-07-21T17:32:28Z' ``` If the date or date-time format does not follow the standard as defined by RFC 3339, then the *format* field should be removed and the *pattern* field added with a regular expression defining the format. Upvotes: 3
2018/03/20
863
2,894
<issue_start>username_0: ``` class Player def initialize(hp, attack, defence, gold) @hp = hp @attack = attack @defence = defence @gold = gold @inventory = inventory end def inventory @inventory = [] end def buy(item) if @gold >= item.price @gold-=item.price puts "You hand over #{item.price} gold, and get the #{item.name}." puts "You have #{gold} gold left over." @inventory.push([item.name,item.price,item.attack,item.defence]) puts "ITEMS IN INV: #{@inventory}" # output: ITEMS IN INV: [["Dagger", 4, 1, 0], ["Mucky Tunic", 2, 0, 2]] else puts "You can't afford this item." end end end player = Player.new(10,1,2,6) puts player.inventory.inspect # output: [] ``` The `inventory.push` line pushes the element to the array while it is inside the method, but when returned outside the method, the `inventory` array is empty. This is confusing because other variables that were changed inside that method in the same way come back as altered. sample output when printed from inside the buy method: ``` ITEMS IN INV: [["Dagger", 4, 1, 0], ["Mucky Tunic", 2, 0, 2]] ``` output with `player.inventory.inspect` outside of the method: ``` [] ```<issue_comment>username_1: I figured it out 10 seconds after posting this, after messing about with it for an hour. I needed to add `inventory` to `def initialize`, and then pass an empty array to `player = Player.new(10,1,2,6)` so it became `player = Player.new(10,1,2,6,[])`. I still don't know why this works. Upvotes: 0 <issue_comment>username_2: Whenever you call your `inventory` method: ``` def inventory @inventory = [] end ``` ... it assigns a new (empty) array to `@inventory`, thus overwriting any existing items. The correct way is to either assign `@inventory` in `initialize` and just return it from within the getter: ``` class Player def initialize(hp, attack, defence, gold) @hp = hp @attack = attack @defence = defence @gold = gold @inventory = [] end def inventory @inventory end # ... end ``` or to not assign it at all in `initialize` and use the [conditional assignment](http://ruby-doc.org/core-2.5.0/doc/syntax/assignment_rdoc.html#label-Abbreviated+Assignment) operator: ``` class Player def initialize(hp, attack, defence, gold) @hp = hp @attack = attack @defence = defence @gold = gold end def inventory @inventory ||= [] end # ... end ``` which will assign `[]` to `@inventory` only if it was `nil` or `false` (i.e. the first time you call `inventory`). A getter that just returns the corresponding instance variable (as in the former example) can also be created via [`attr_reader`](http://ruby-doc.org/core-2.5.0/Module.html#method-i-attr_reader): ``` class Player attr_reader :inventory # ... end ``` Upvotes: 3 [selected_answer]
2018/03/20
793
2,347
<issue_start>username_0: looking for how to go about this in SQL. For the same value of A, if two or more values of B exist, and one of the B values is null; show all combinations of A, B and C. Table: ``` A B C 1 2 3 4 5 6 7 8 9 1 null 4 1 2 4 9 3 5 9 null 7 ``` Expected Result: ``` A B C 1 2 3 1 null 4 1 2 4 9 3 5 9 null 7 ``` ThankYou :) Better example ![Input and expected output](https://i.stack.imgur.com/dfhN1.png)<issue_comment>username_1: Your requirements are slightly tricky. One way we can phrase it is that, in order to be retained, an `A` group has to have a distinct `B` count plus an optional increment by one for nulls present which is two or more. ``` SELECT t1.* FROM yourTable t1 INNER JOIN ( SELECT A FROM yourTable GROUP BY A HAVING COUNT(DISTINCT B) > 0 AND MAX(CASE WHEN B IS NULL THEN 1 ELSE 0 END) > 0 ) t2 ON t1.A = t2.A; ``` [Demo ----](http://rextester.com/RMHY47424) The demo is for MySQL but it so happens that the same query should run on SQLite as well. Upvotes: 2 <issue_comment>username_2: This should return your expected result, simply compare the count of *all* vs. *NOT NULL* rows: Based on [Tim's fiddle](http://rextester.com/JGHR64245): ``` SELECT t1.* FROM yourTable t1 INNER JOIN ( SELECT A FROM yourTable GROUP BY A HAVING COUNT(*) > COUNT(B) AND COUNT(*) > 1 ) t2 ON t1.A = t2.A; ``` Or as a simle Subquery: ``` SELECT * FROM yourTable WHERE A IN ( SELECT A FROM yourTable GROUP BY A HAVING COUNT(*) > COUNT(B) AND COUNT(*) > 1 ) ``` See [fiddle](http://rextester.com/IBXR9708) Upvotes: 2 <issue_comment>username_3: Based on example you just need simple `group by` clause and `join` them ``` select * from table t inner join ( select provider from table t group by provider having count(*) > 1 and sum(case when service is null then 1 else 0 END) >= 1 ) c on c.provider = t.provider ``` Upvotes: 0 <issue_comment>username_4: Yet another solution: ``` SELECT t1.* FROM #testdata t1 WHERE EXISTS (SELECT * FROM #testdata WHERE A = t1.A AND B IS NULL) AND EXISTS (SELECT * FROM #testdata WHERE A = t1.A AND B IS NOT NULL) ``` [SQL Fiddle](http://www.sqlfiddle.com/#!5/8b26aa/1) Upvotes: 1 [selected_answer]
2018/03/20
744
2,455
<issue_start>username_0: we verify the users of our application (in Oracle Forms 11g) using internal oracle database authentication. The user enters the user id, password and connection description in the default logon screen provided by Oracle Forms 11g (screenshot attached). When the user presses the CONNECT button in which trigger should I place the function to verify password constraints such as min password length etc in Oracle Forms? your inputs will be much appreciated thx [![enter image description here](https://i.stack.imgur.com/EFg6t.png)](https://i.stack.imgur.com/EFg6t.png)<issue_comment>username_1: Your requirements are slightly tricky. One way we can phrase it is that, in order to be retained, an `A` group has to have a distinct `B` count plus an optional increment by one for nulls present which is two or more. ``` SELECT t1.* FROM yourTable t1 INNER JOIN ( SELECT A FROM yourTable GROUP BY A HAVING COUNT(DISTINCT B) > 0 AND MAX(CASE WHEN B IS NULL THEN 1 ELSE 0 END) > 0 ) t2 ON t1.A = t2.A; ``` [Demo ----](http://rextester.com/RMHY47424) The demo is for MySQL but it so happens that the same query should run on SQLite as well. Upvotes: 2 <issue_comment>username_2: This should return your expected result, simply compare the count of *all* vs. *NOT NULL* rows: Based on [Tim's fiddle](http://rextester.com/JGHR64245): ``` SELECT t1.* FROM yourTable t1 INNER JOIN ( SELECT A FROM yourTable GROUP BY A HAVING COUNT(*) > COUNT(B) AND COUNT(*) > 1 ) t2 ON t1.A = t2.A; ``` Or as a simle Subquery: ``` SELECT * FROM yourTable WHERE A IN ( SELECT A FROM yourTable GROUP BY A HAVING COUNT(*) > COUNT(B) AND COUNT(*) > 1 ) ``` See [fiddle](http://rextester.com/IBXR9708) Upvotes: 2 <issue_comment>username_3: Based on example you just need simple `group by` clause and `join` them ``` select * from table t inner join ( select provider from table t group by provider having count(*) > 1 and sum(case when service is null then 1 else 0 END) >= 1 ) c on c.provider = t.provider ``` Upvotes: 0 <issue_comment>username_4: Yet another solution: ``` SELECT t1.* FROM #testdata t1 WHERE EXISTS (SELECT * FROM #testdata WHERE A = t1.A AND B IS NULL) AND EXISTS (SELECT * FROM #testdata WHERE A = t1.A AND B IS NOT NULL) ``` [SQL Fiddle](http://www.sqlfiddle.com/#!5/8b26aa/1) Upvotes: 1 [selected_answer]
2018/03/20
528
2,059
<issue_start>username_0: In the following code, I am attempting to iterate over `geoMarkers` and create a Marker for each. The line of code here needs some help: content: `@Html.Partial("~/Views/Search/_MyPartialView.cshtml", Model.ElementAt(' + i + '))` In this line above, I am attempting to pass the JavaScript variable `i` into a ASP.NET MVC call, which I know by searching isn't possible EXCEPT in cases where the JavaScript variable can be turned into a literal. In this case, I would like to turn the `i` into an int, but I'm struggling with the syntax. **How can I pass `i` into the `@Html.Partial` call?** Note that `_MyPartialView.cshtml` takes a `@model MyMarkerObject`. Thank you! ``` @model List @section scripts { ```<issue_comment>username_1: How about you pass the variable "i" as a query param and let your controller interpret it and use it as needed. Something like this: ``` @Html.Partial("~/Views/Search/_MyPartialView.cshtml?elementNo=" + i) ``` You can pass the model MyMarkerObject as well and then you can process it as needed. Upvotes: -1 <issue_comment>username_2: When view loaded all server side tags (Razor) will be loaded first then your javascript code will be executed , if you needed to call server side code from JS after your code loaded you need in this case to use asynchronous Ajax call. This is example for your code Controller ``` [HttpPost] public ActionResult MyPartialView( MyMarkerObject myMarkerObject ) { return PartialView("~/Views/Search/_MyPartialView.cshtml", myMarkerObject ); } //Javascript $.ajax({ url: '@Url.Action("Search","MyPartialView")', type: 'POST', data: JSON.stringify(item), dataType: 'json', contentType: 'application/json; charset=utf-8', error: function (xhr) { alert('Error: ' + xhr.statusText); }, success: function (result) { var infowindow = new google.maps.InfoWindow({ content: result }); }, async: true, processData: false }); ``` Upvotes: 1 [selected_answer]
2018/03/20
1,139
3,220
<issue_start>username_0: I have two sheets, one filled with data and other one empty. I want to reshape the data on the other sheet by putting it into the next row every 7 columns. This is my code, but it's not working. Can you help me to find the mistake that I'm making? ``` Set ws1 = Sheets("F2") Set ws2 = Sheets("List1") rangerow = ws1.Range("A" & Rows.Count).End(xlUp).Row rangecol = ws1.Range("A" & Columns.Count).End(xlToLeft).Column rangerow2 = ws2.Range("A" & Rows.Count).End(xlUp).Row rangecol2 = ws2.Range("A" & Columns.Count).End(xlToLeft).Column For i = 1 To 100 If j < 8 Then ws1.Range("A4").Copy ws2.Range("A1").PasteSpecial xlPasteValues ws2.Activate j = j + 1 Else Row = ws2.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row End If i = i + 1 Next ```<issue_comment>username_1: Try this: ``` Dim ws1 As Worksheet, ws2 As Worksheet, lastRow As Long, lastCol As Long, i As Long, j As Long i = 1 j = 1 Set ws1 = Sheets("F2") Set ws2 = Sheets("List1") With ws1 lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row lastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column End With For Each cell In ws1.Range(Cells(1, 1), Cells(lastRow, lastCol)) ws2.Cells(i, j) = cell j = j + 1 If j = 8 Then i = i + 1 j = 1 End If Next ``` Upvotes: 2 <issue_comment>username_2: You can `Set` your range in `"F2"` sheet to be dynamic, and then loop through each cell in the Range by using `For Each C In Rng`. Inside this loop, I have `CellCount` which represent the number of the cell inside the Range, every 7 columns I reset the column number here: ``` Col = CellCount Mod 7 ' get the column number , every 7 columns reset the column ``` and add 1 to the Row here: ``` PasteRow = Int((CellCount - 1) / 7) + 1 ' get the row number ``` ***Code*** ``` Option Explicit Sub CopyUpto7Columns() Dim ws1 As Worksheet, ws2 As Worksheet Dim Rng As Range, C As Range Dim LastRow As Long, CellCount As Long Dim PasteRow As Long, Col As Long Set ws1 = Sheets("F2") Set ws2 = Sheets("List1") With ws1 ' get dynamic last row LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row ' set the range object in sheet "F2" up to column 31 Set Rng = .Range(.Cells(1, 1), .Cells(LastRow, 31)) End With PasteRow = 1 ' start pasting from the first row CellCount = 1 ' reset cell count in Range ' loop through range (cell by cell) For Each C In Rng PasteRow = Int((CellCount - 1) / 7) + 1 ' get the row number Col = CellCount Mod 7 ' get the column number , every 7 columns reset the column If Col = 0 Then Col = 7 ws2.Cells(PasteRow, Col).Value = C.Value CellCount = CellCount + 1 Next C End Sub ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: Try The code below :) : ``` Sub test() Set ws1 = Sheets("F2") Set ws2 = Sheets("List1") rangerow = ws1.Cells(Rows.Count, 1).End(xlUp).Row rangecol = ws1.Cells(1, Columns.Count).End(xlToLeft).Column ii = 1 jj = 1 For i = 1 To rangerow For j = 1 To rangecol If jj = 8 Then ii = ii + 1 jj = 1 End If ws1.Cells(i, j).Copy ws2.Cells(ii, jj).PasteSpecial xlPasteValues jj = jj + 1 Next j Next i End Sub ``` Upvotes: 1
2018/03/20
1,341
4,647
<issue_start>username_0: I am using intel fortran 2016. I have defined some precision variables as follows: ``` ! definition of single, double and quad precision integer, parameter :: SINGLE_PRECISION = selected_real_kind(6, 37) integer, parameter :: DOUBLE_PRECISION = selected_real_kind(15, 307) ! is used as standard precision integer, parameter :: QUAD_PRECISION = selected_real_kind(33, 4931) ! definition of variable precision for REAL, INTEGER integer, parameter :: REAL_TYPE = DOUBLE_PRECISION integer, parameter :: INTEGER_TYPE = 4 ``` I would like to now use these to control the precision of a parameter that gets declared in a subroutine as follows: ``` SUBROUTINE SKIP(IUNIT,NBYTS) IMPLICIT DOUBLE PRECISION (A-H,O-Z) Character c*1 Parameter(n1 = 1024, nT1 = 8*n1) ``` I tried the following : ``` Parameter(INTEGER_TYPE)((n1 = 1024, nT1 = 8*n1) Parameter(INTEGER_TYPE)((n1 = 1024, nT1 = 8*n1, kind = INTEGER_TYPE) ``` All to no avail. What is the proper way to define parameter precision in Fortran? Thanks<issue_comment>username_1: You can define a parameter of a specific kind with ``` TYPE, PARAMETER :: name = value_kind ``` So to define, say, an integer n1 with kind INTEGER\_TYPE you do ``` integer(kind=INTEGER_TYPE), parameter :: n1 = 1024_INTEGER_TYPE ``` Upvotes: 1 <issue_comment>username_2: You have an answer which gives the best way to specify the kind of a named constant. You can find much more detail around [this question](https://stackoverflow.com/q/838310/3157076). However, I'll add some detail about the `parameter` statement. The `parameter` statement makes an object a named constant and specifies its value. It doesn't specify the type or kind of that object. The example of the question uses implicit typing for `n1` and `nT1`. These are implicitly default integer. The implicit rule may be changed (I won't show how), but the type may also be given explicitly: ``` integer(INTEGER_TYPE) n1, nT1 parameter (n1=1024, nT1=8*n1) ``` Still, the form of the other answer is preferable. And, as noted there, the kind of the literal constants may also be given in the `parameter` statement if desired. Upvotes: 1 <issue_comment>username_3: **Note:** this is essentially the same as [Francescalus' answer](https://stackoverflow.com/a/49379472/8344060), but with some extra fluf. The issue at hand here is related to the `IMPLICIT` statement. The [Fortran standard](https://j3-fortran.org/doc/year/10/10-007.pdf) makes the following statements : > > **5.5 IMPLICIT statement** > > > 1. In a scoping unit, an `IMPLICIT` statement specifies a type, and > possibly type parameters, for all implicitly typed data entities whose > names begin with one of the letters specified in the statement. > Alternatively, it may indicate that no implicit typing rules are to > apply in a particular scoping unit. > 2. > 3. In each scoping unit, there is a mapping, which may be null, between > each of the letters `A, B, ..., Z` and a type (and type parameters). > An `IMPLICIT` statement specifies the mapping for the letters in its > letter-spec-list. `IMPLICIT NONE` specifies the null mapping for all > the letters. If a mapping is not specified for a letter, the > default for a program unit or an interface body is default integer if > the letter is `I, J`, ..., or `N` and default real otherwise, and the > default for an internal or module procedure is the mapping in the host > scoping unit. > > > So in short, by default everything is of type default `REAL` unless it starts with `I`,`J`,...,`N`, then it is of type default `INTEGER`. In the example in the question, the variables `n1` and `nT1` are hence default `INTEGER` unless specified otherwise. Thus the following might be a solution : ``` subroutine skip(IUNIT,NBYTS) implicit double precision (A-H,O-Z) character c*1 integer(kind=integer_kind), parameter :: n1 = 1024, nT1 = 8*n1 ... end subroutine skip ``` As a general remark on variable declaration I would like to make the following remarks: * use `implicit none` as default. It makes debugging easier * avoid star notation, it is not part of the standard for anything but characters, and for characters it is declared obsolescent. * make use of `kind` parameters declared in the intrinsic module `iso_fortran_env` * be aware that `double precision` does not necessarily mean "double precision" in the literal or IEEE sense of the word. It just means, twice the storage of a `real` and a higher precision than `real`. (a higher precision could be one-digit). Upvotes: 3 [selected_answer]
2018/03/20
356
1,177
<issue_start>username_0: Using Linux 16.04 and docker All the containers are running fine .Successfully installed the chaincode on core peer. But At the time of chaincode instansiate ``` peer chaincode instantiate -o orderer.example.com:7050 -C $CHANNEL_NAME -n fabcar -l "golang" -v 1.0 -c '{"Args":[""]}' -P "OR ('Org1MSP.member','Org2MSP.member')" ``` Geeting error ``` `Error: could not send: rpc error: code = Unavailable desc = transport is closing` ``` Thanks in advance.<issue_comment>username_1: I was facing this issue because I enabled tls on the peer but not providing the tls and ca file to the orderer at the time of chaincode instantiate. Upvotes: 3 <issue_comment>username_2: This may work: 1. Bring down the network 2. Disable TLS in below files by commenting environment variables listed below. ``` base/docker-compose-base.yaml base/peer-base.yaml docker-compose-cli.yaml: docker-compose-e2e-template.yam ``` ENV: ``` CORE_PEER_TLS_ENABLED CORE_PEER_TLS_CERT_FILE CORE_PEER_TLS_KEY_FILE CORE_PEER_TLS_ROOTCERT_FILE ``` 3. Bring up the network Another way is to pass TLS certificate as an argument to peer fetch channel command. Upvotes: 0
2018/03/20
859
2,973
<issue_start>username_0: I `cherry-picked` a commit and resolved the conflicts, added them, now when I try to do git amend it fails with below message. > > fatal: You are in the middle of a cherry-pick -- cannot amend. > > > Why does git gives this message, is there a way to tell it things are fine?<issue_comment>username_1: The behaviour is defined in the [documentation](https://git-scm.com/docs/git-cherry-pick). What you need in your case is > > **--continue** > > Continue the operation in progress using the information in > .git/sequencer. Can be used to continue after resolving conflicts in a > failed cherry-pick or revert. > > > Upvotes: 1 <issue_comment>username_2: It seems that you did a `cherry-pick` before, which failed due to conflicts. Thus, git thinks you're still in the middle of the cherry pick, since it expects you to fix conflicts, add conflicted files and run `git cherry-pick --continue`. Your options here are to run `git cherry-pick --abort` which will abort the cherry pick, i.e. return the conflicted files to their previous state, possible losing changes, or to run `git cherry-pick --continue`, which will continue the cherry pick. When you do not remember when and what you did with the cherry-pick, this is probably the better option, althoough you should watch your repository closely before and after the `--continue` command. Both commands will get you out of the cherry-pick state and allow you to perform the amend. Upvotes: 3 <issue_comment>username_3: When running actions like `cherry-pick`, `rebase` or `merge`, `git` keeps track of several info on the base commit. It looks like a reasonable safety to prevent the base commit from being modified. --- I would advise you to somehow finish your `cherry-pick`, and then use `rebase -i` to modifiy the sequence of commits you want. If we use the following names : ``` --*--*-- ... --A--B <- HEAD \ *-- ... X <- cherry-picked commit # you are currently on B, you run : git cherry-pick X ``` If you wish to reach : ``` --*--*-- ... --A--B'--X' <- cherry-picked version of X \ ^ \ a modified version of B *-- ... X ``` you can : ``` # add the modifications intended for B' : git add -p [files] # create a regular commit, using "git commit" : git commit --*--*-- ... --A--B--C # complete the cherry-pick process : git add [files with solved conflicts] git cherry-pick --continue --*--*-- ... --A--B--C--X' # use 'rebase -i A' to squash B and C into one commit git rebase -i A # set the rebase actions to "squash C into B" # the result should be what you expect : --*--*-- ... --A--B'--X' ``` Upvotes: 0 <issue_comment>username_4: I manually removed `.git/CHERRY_PICK_HEAD` now git doesn't know I did a cherry-pick, so amend works like it was a normal commit amend. `cherry-pick --continue` adds a new commit message and would need to rebase which is a hassle. Upvotes: 5 [selected_answer]
2018/03/20
535
1,688
<issue_start>username_0: i have some strings from database > > email1 link1 data1 > > > email1 link1 data2 > > > email1 link2 data3 > > > email2 link3 data4 > > > How can i get such а json? ``` {log:[ {email: email1, link:link1, data:[data1,data2]}, {email: email1, link:link2, data:[data3]}, {email: email2, link:link3, data:[data4]} ]} ``` I do not know how to create a date array for given fields<issue_comment>username_1: You may try to first load your data in an object tree and then use a json converter like [Json.Net](https://www.newtonsoft.com/json). But you need to have a consistent format for your data. A kind of thing like the code below : ``` class Data{ //to be more defined maybe a string could be a start string value; } class Log{ string email; string link; List data; } List myLog = new List(); // load your "log" data into this list string json = JsonConvert.SerializeObject(myLog); ``` Upvotes: 2 <issue_comment>username_2: A slightly different answer from the first answer. Let's assume you already able to get the records from the database into this class. ``` public class Log { public string Email { get; set; } public string Link { get; set; } public string Data { get; set; } } ``` You can then group the logs by email and link using the following LINQ syntax. ``` var logs = new List(); // The list should come from the records in the database. var result = new { Log = logs.GroupBy(x => new { x.Email, x.Link }) .Select(y => new { y.Key.Email, y.Key.Link, Data = y.Select(z => z.Data) }) }; ``` And use `Newtonsoft.Json` to serialize it. ``` var json = JsonConvert.SerializeObject(result); ``` Upvotes: 2
2018/03/20
539
2,501
<issue_start>username_0: ``` enum TrackingEvent: String { case notificationScreenLoaded = "Notification Screen" case homeScreenLoaded = "Home Screen" case homeScreenViewBill = "Home Screen View Bill Button" case homeScreenPayBill = "Home Screen Pay Bill Button" case homeScreenViewLastPayment = "Home Screen Last Payment Section" case chartToggleUsage = "Charts Toggle" case chartExplanation = "Charts Explanation Screen" } ``` for this example, how do I get a random string? So far what I search in StackOverflow examples the enum are all `UInt32` return type<issue_comment>username_1: You need to create a function to get random `UInt32` with upper bound equal to the number of cases in the enum `TrackingEvent` and return the case based on a random number. ``` enum TrackingEvent: String { case notificationScreenLoaded = "Notification Screen" case homeScreenLoaded = "Home Screen" case homeScreenViewBill = "Home Screen View Bill Button" case homeScreenPayBill = "Home Screen Pay Bill Button" case homeScreenViewLastPayment = "Home Screen Last Payment Section" case chartToggleUsage = "Charts Toggle" case chartExplanation = "Charts Explanation Screen" static func random() -> TrackingEvent { let rand = arc4random_uniform(7) switch rand { case 1: return .homeScreenLoaded case 2: return .homeScreenViewBill case 3: return .homeScreenPayBill case 4: return .homeScreenViewLastPayment case 5: return .chartToggleUsage case 6: return .chartExplanation default: return .notificationScreenLoaded } } } ``` You can use it like `let random = TrackingEvent.random()` Upvotes: 2 <issue_comment>username_2: Put all into an array and emit a random index item, ``` extension TrackingEvent { static func random() -> TrackingEvent { let all: [TrackingEvent] = [.notificationScreenLoaded, .homeScreenLoaded, .homeScreenViewBill, .homeScreenPayBill, .homeScreenViewLastPayment, .chartToggleUsage, .chartExplanation] let randomIndex = Int(arc4random()) % all.count return all[randomIndex] } } ``` Upvotes: 4 [selected_answer]
2018/03/20
1,953
6,986
<issue_start>username_0: I have a problem with creating GUI with PyQT, I have attached the code for your reference. The problem is whenever a message box is shown, I cannot click OK or 'x' to close it. Can anyone show me how to deal with it? Thank you very much. Does anyone have the answer, I am very in need of it. ``` # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'button.ui' # # Created by: PyQt5 UI code generator 5.9.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox import os class Ui_SubWindow(object): def showMessageBox(self, title, message): msgBox=QMessageBox() msgBox.setIcon(QMessageBox.Warning) msgBox.setWindowTitle(title) msgBox.setText(message) msgBox.setStandardButtons(QMessageBox.Ok) msgBox.exec_() def checking_name(self): firstname=self.lineEdit.text() lastname=self.lineEdit_2.text() b=os.listdir(r'C:\Users\dngochuynh\PycharmProjects\fr-project\standalone\image folder\downsized image') for e in b: if str(firstname).lower() in e: if str(lastname).lower() in e: os.remove(r'C:\Users\dngochuynh\PycharmProjects\fr-project\standalone\image folder\downsized image\{}'.format(e)) self.showMessageBox('Warning','Image is deleted') else: self.showMessageBox('Warning','Cannot find the image, please check if your typing is correct') def setupUi(self, SubWindow): SubWindow.setObjectName("SubWindow") SubWindow.resize(350, 307) SubWindow.setStyleSheet("") self.centralwidget = QtWidgets.QWidget(SubWindow) self.centralwidget.setObjectName("centralwidget") self.forgetButton = QtWidgets.QPushButton(self.centralwidget) self.forgetButton.setGeometry(QtCore.QRect(120, 230, 111, 51)) font = QtGui.QFont() font.setPointSize(10) self.forgetButton.setFont(font) self.forgetButton.setObjectName("forgetButton") #################################################### self.forgetButton.clicked.connect(self.checking_name) self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(10, 20, 71, 31)) self.label.setObjectName("label") self.label_2 = QtWidgets.QLabel(self.centralwidget) self.label_2.setGeometry(QtCore.QRect(10, 60, 71, 31)) self.label_2.setObjectName("label_2") self.label_3 = QtWidgets.QLabel(self.centralwidget) self.label_3.setGeometry(QtCore.QRect(10, 140, 321, 61)) self.label_3.setText("") self.label_3.setObjectName("label_3") self.textBrowser = QtWidgets.QTextBrowser(self.centralwidget) self.textBrowser.setGeometry(QtCore.QRect(10, 110, 331, 111)) self.textBrowser.setObjectName("textBrowser") self.lineEdit = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit.setGeometry(QtCore.QRect(100, 20, 221, 31)) self.lineEdit.setObjectName("lineEdit") self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit_2.setGeometry(QtCore.QRect(100, 60, 221, 31)) self.lineEdit_2.setObjectName("lineEdit_2") SubWindow.setCentralWidget(self.centralwidget) self.statusbar = QtWidgets.QStatusBar(SubWindow) self.statusbar.setObjectName("statusbar") SubWindow.setStatusBar(self.statusbar) self.retranslateUi(SubWindow) QtCore.QMetaObject.connectSlotsByName(SubWindow) def retranslateUi(self, SubWindow): _translate = QtCore.QCoreApplication.translate SubWindow.setWindowTitle(_translate("SubWindow", "MainWindow")) self.forgetButton.setText(_translate("SubWindow", "Delete My Image")) self.label.setText(_translate("SubWindow", "First Name")) self.label_2.setText(_translate("SubWindow", "Last Name")) self.textBrowser.setHtml(_translate("SubWindow", "\n" "\n" "p, li { white-space: pre-wrap; }\n" "\n" "If because of privacy reason, you want to delete your image from the dabase. Please forllow the instruction: \n" "1. Enter your first name \n" "2. Enter your last name \n" "3. Press Delete My Image \n" "After that your image will be deleted from the database and the program will not recognize you, next time it running. ")) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) SubWindow = QtWidgets.QMainWindow() ui = Ui_SubWindow() ui.setupUi(SubWindow) SubWindow.show() sys.exit(app.exec_()) ``` [link to code](https://drive.google.com/file/d/1InBZt21R7bi21FFnmJxxM8gynUgkO7zl/view?usp=sharing)<issue_comment>username_1: I believe the problem is not that the message box won't close, but that it reopens immediately after it is closed. The way you have written your for statement, a message box will appear for every file in the directory regardless of if the it contains the first and last names. Upvotes: 1 <issue_comment>username_2: try replacing the method `checking\_name ' ``` ... def checking_name(self): firstname = str(self.lineEdit.text()).lower() lastname = str(self.lineEdit_2.text()).lower() b=os.listdir(r'C:\Users\dngochuynh\PycharmProjects\fr-project\standalone\image folder\downsized image') #for e in b: if (firstname in b) and firstname: if (lastname in b) and lastname: os.remove(r'C:\Users\dngochuynh\PycharmProjects\fr-project\standalone\image folder\downsized image\{}'.format(lastname)) self.showMessageBox('Warning','{} Image is deleted'.format(lastname)) self.lineEdit.setText("") self.lineEdit_2.setText("") else: self.showMessageBox('Warning','firstname != lastname') else: self.showMessageBox('Warning', 'Cannot find the `{}` image, please check if your typing is correct'\ .format(firstname)) ... ``` Upvotes: 0 <issue_comment>username_3: Thank you for all your answer, it is how I fixed the code ``` def checking_name(self): firstname=self.lineEdit.text() lastname=self.lineEdit_2.text() os.chdir(r'C:\Users\dngochuynh\PycharmProjects\fr-project\standalone\image folder\downsize image2') list_image=os.listdir(r'C:\Users\dngochuynh\PycharmProjects\fr-project\standalone\image folder\downsize image2') for e in list_image: if (str(firstname).lower() in str(e).lower()) and (str(lastname).lower() in str(e).lower()): os.remove(r'C:\Users\dngochuynh\PycharmProjects\fr-project\standalone\image folder\downsize image2\{}'.format(e)) self.showMessageBox('Confirmation','Image is deleted') break else: self.showMessageBox('Warning','Cannot find the image, please check if your typing is correct') ``` Upvotes: 0