text
stringlengths
15
59.8k
meta
dict
Q: How to internationalize a google workspace addon? I wrote a Gmail addon which is using different languages. But I cannot manage to translate the title in the sidebar nor the hover text of the icon. See yellow marks in screenshot. At first I thought the text is coming from the marketplace but it seems to be from manifest file appsscript.json. "addOns": { "common": { "name": "Translate", … as described here: https://developers.google.com/apps-script/manifest/addons None of the documentations provide an answer, because variables seem not to work in the manifest file: * *https://developers.google.com/apps-script/add-ons/how-tos/access-user-locale *https://developers.google.com/apps-script/add-ons/concepts/event-objects#common_event_object *https://developers.google.com/apps-script/reference/base/session#getactiveuserlocale I was looking around for solutions (i18n, translation, localisation, …), e.g. * *Use Google Apps Script function in manifest (JSON) - Gmail Addon --> question on file but different part *How to internationalize universalActions label in a Google Workspace Add-On --> solution I found for question above but not usable for name *Localizing Google Add-ons --> solution is for Chrome not Workspace Addons *Can I use getActiveUserLocale() in onOpen(e) of a published Add-on? --> not usable in manifest but could not find a solution. I can support different languages in the store and in the addon but not in manifest file? Does anyone have an idea or workaround? A: According to the Add-on manifest documentation, the mentioned manifest field is meant to store your add-on name. name: Required. The name of the add-on shown in the toolbar. Since this field is meant for the name of your add-on, it sounds like expected behavior not being able to update it on runtime. Here is an open Feature Request ticket with Google to add support for this functionality.
{ "language": "en", "url": "https://stackoverflow.com/questions/74740616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: What difference does it make change the order which you import modules on Python? So i was trying to learn the basics of creating GUI's with Tkinter, and i found this code in a tutorial: from tkinter import * from PIL import ImageTk, Image class Window(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.master = master self.init_window() def init_window(self): self.master.title("GUI") self.pack(fill=BOTH, expand=1) menu = Menu(self.master) self.master.config(menu=menu) file = Menu(menu) file.add_command(label="Exit", command=self.client_exit) menu.add_cascade(label="File", menu=file) edit = Menu(menu) edit.add_command(label="Show Img", command=self.showImg) edit.add_command(label="Show Text", command=self.showTxt) menu.add_cascade(label="Edit", menu=edit) def showImg(self): load = Image.open("chat-min.png") render = ImageTk.PhotoImage(load) img = Label(self, image=render) img.image = render img.place(x=0, y=0) def showTxt(self): text = Label(self, text="Maximum effort!") text.pack() def client_exit(self): exit() root = Tk() root.geometry("400x300") app = Window(root) root.mainloop() This code just creates a window, with a cascade menu and two options: File that has Exit that close the window; Edit that has Show Img and Show Text, that display a image and a text respectively. And if i switch the two lines where im importing tkinter, and ImageTk, Image, like this: from PIL import ImageTk, Image from tkinter import * I get an error saying that: type object 'Image' has no attribute 'open', when i click on Show Img, everything else works. Could anyone explain to me why this happens? Or what's wrong? A: Order only matters if there is a clash, with the last import winning (redefining), e.g. tkinter.Image redefines PIL.Image because it comes after. You can avoid this by keeping the tkinter import in a namespace, e.g. import tkinter as tk and then tk.XXX for any call in that module. It is generally best to avoid * all imports. The answer is provided by the comment here.
{ "language": "en", "url": "https://stackoverflow.com/questions/48877086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Flutter animations: how to keep position of parent widget I'm having some trouble with an animation in Flutter. There are 3 circles next to each other. When one of them is pressed, I want it to expand and collapse. The animation works, but the whole row of circles moves downward when it happens, to keep the top margin of the row the circles are in. How do I make sure the row keeps it original position? I've only applied the animation to the center circle to test it. I'm sorry if the code is messy, it's because I was testing this. This is the animation and animation controller: _animationController = AnimationController(vsync: this, duration: Duration(milliseconds: 200)); _animation = Tween(begin: 0.25, end: 0.35).animate( CurvedAnimation(parent: _animationController, curve: Curves.elasticIn)) ..addStatusListener((status) { if (status == AnimationStatus.completed) { _animationController.reverse(); } }); These are the circles: Column( children: <Widget>[ Container( margin: EdgeInsets.only(top: 16.0), child: Center( child: Text( 'Circles', style: TextStyle(fontSize: 18), ), ), ), Container( margin: EdgeInsets.only(top: 8.0), child: Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ Container( width: MediaQuery.of(context).size.width * 0.25, height: MediaQuery.of(context).size.height * 0.2, margin: EdgeInsets.symmetric(horizontal: 8.0), child: Center(child: Text('Circle')), decoration: BoxDecoration( shape: BoxShape.circle, border: Border.all(color: AppColors.primaryBlue)), ), AnimatedBuilder( animation: _animation, builder: (context, child) { return GestureDetector( onTap: () { _animationController.forward(); }, child: Container( width: MediaQuery.of(context).size.width * _animation.value, height: MediaQuery.of(context).size.height * _animation.value, margin: EdgeInsets.symmetric(horizontal: 8.0), child: Center(child: Text('Circle')), decoration: BoxDecoration( shape: BoxShape.circle, border: Border.all(color: AppColors.primaryBlue)), ), ); }, ), Container( width: MediaQuery.of(context).size.width * 0.25, height: MediaQuery.of(context).size.height * 0.2, margin: EdgeInsets.symmetric(horizontal: 8.0), child: Center(child: Text('Circle')), decoration: BoxDecoration( shape: BoxShape.circle, border: Border.all(color: AppColors.primaryBlue)), ) ], ), ), You can probably notice I'm quite new to animations in Flutter, so other feedback is very welcome too. Thanks! A: Output: Full code: Column( children: <Widget>[ Container( margin: EdgeInsets.only(top: 16.0), child: Center( child: Text( 'Circles', style: TextStyle(fontSize: 18), ), ), ), Container( height: 200, margin: EdgeInsets.only(top: 8.0), child: Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ Container( width: MediaQuery.of(context).size.width * 0.25, height: MediaQuery.of(context).size.height * 0.2, margin: EdgeInsets.symmetric(horizontal: 8.0), child: Center(child: Text('Circle')), decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: AppColors.primaryBlue)), ), Spacer(), AnimatedBuilder( animation: _animation, builder: (context, child) { return GestureDetector( onTap: () { _animationController.forward(); }, child: Container( width: MediaQuery.of(context).size.width * _animation.value, height: MediaQuery.of(context).size.height * _animation.value, margin: EdgeInsets.symmetric(horizontal: 8.0), child: Center(child: Text('Circle')), decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: AppColors.primaryBlue)), ), ); }, ), Spacer(), Container( width: MediaQuery.of(context).size.width * 0.25, height: MediaQuery.of(context).size.height * 0.2, margin: EdgeInsets.symmetric(horizontal: 8.0), child: Center(child: Text('Circle')), decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: AppColors.primaryBlue)), ) ], ), ), ], ); A: first i suggest you delete mainAxisSize: MainAxisSize.min, if that didn't work, try to wrap the animated builder with a container and give it the same proprities as those
{ "language": "en", "url": "https://stackoverflow.com/questions/56405744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to send a message or event into Server Unity3D? I am learning about Networking in Unity. I am confused on how can I send a message or event from client to server. I have these script already that successfully connect my client to server. This is my server script: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; public class ServerNetwork : MonoBehaviour { void Start() { SetupServer(); } // Create a server and listen on a port public void SetupServer() { NetworkServer.Listen(4444); NetworkServer.RegisterHandler(MsgType.Connect, OnClientConnected); Debug.Log("Server is running"); } void OnClientConnected(NetworkMessage netMsg) { Debug.Log("Client connected"); Debug.Log(netMsg.msgType); } } This is my client Script: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; public class ClientNetwork : MonoBehaviour { NetworkClient myClient; public bool isClientConnected = false; void Start() { SetupClient(); } // Create a client and connect to the server port public void SetupClient() { myClient = new NetworkClient(); myClient.RegisterHandler(MsgType.Connect, OnConnected); myClient.Connect("127.0.0.1", 4444); isClientConnected = true; } // client function public void OnConnected(NetworkMessage netMsg) { Debug.Log("Connected to server"); } } The Server Script is attached to "NetworkManager" Object on ServerScene The Client Script is attached to "NetworkManager" Object on ClientScene I have build ClientScene alone to run as a client, and running ServerScene inside editor With these script, I can already connect the client into the server. From this, how can I communicate from client to server ? the purpose here is to send real time score into the server from client every second. Thank You A: You have to use [SyncVars] Attribute. In short what it does is it synchronize a variable from client to the server. Here is a simple example from Unity3d Documentation. [SyncVar] int health; public void TakeDamage(int amount) { if (!isServer) return; health -= amount; } another way to do this is by using custom WebSocket implementation for Unity3D. There a few very good ones in GitHub.Also please take a look at the documentation Unity3d
{ "language": "en", "url": "https://stackoverflow.com/questions/51484610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Correctly get access to nested object in JavaScript I have the JS-object, that in Chrome's console looks as folllow: data: Object comparisonType: "IN" dateValue: "" numericalValue: 0 screeningCriterionId: "-4" screeningField.displayName: "Prop1" screeningField.fieldName: "Prop2" screeningField.groupName: "Prop3" screeningField.type: "MULTI" value: null And I need to read the screeningField.displayName: "Prop1" from this object , but trying to execute in console this myObject.screeningField.displayName I'm getting the error: TypeError: Cannot read property 'displayName' of undefined How to solve my problem ? A: Apparently the dot is actually included in the key name, try: myObject['screeningField.displayName']
{ "language": "en", "url": "https://stackoverflow.com/questions/13759052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do i efficiently use redux in react making request to backend server? I am new to using react and also new to redux, I am working on a project which uses Django for Back-end and React for Front-end. I want to use redux for data state management but i can not seem to be doing it right. The problem is that the request is reaching the back end and also i have been having trouble handling the axios returned promise. Here is my action transaction.js function: import axios from "axios"; export const CREATE_TRANSACTION = "CREATE_TRANSACTION"; export const VIEW_TRANSACTION = "VIEW_TRANSACTION"; export const UPDATE_TRANSACTION = "UPDATE_TRANSACTION"; export const LIST_TRANSACTIONS = "LIST_TRANSACTIONS"; export const DELETE_TRANSACTION = "DELETE+TRANSACTION"; export const GET_TRANSACTIONLIST_DATA = "GET_TRANSACTIONLIST_DATA"; const ROOT_URL = "http://127.0.0.1:8000/api/"; export const getTransactionList = () => (dispatch) => { axios .get(`${ROOT_URL}transactions/`, { headers: { "Content-Type": "application/json", }, }) .then((response) => { dispatch({ type: LIST_TRANSACTIONS, payload: response.data }); console.log(response.data); }); }; Here is my reducer transactions.js function: import { LIST_TRANSACTIONS } from "../actions/transaction"; export function TransactionReducer(state = {}, action) { switch (action.type) { case LIST_TRANSACTIONS: return action.payload; default: return state; } } My store.js: import { createStore, applyMiddleware, compose } from "redux"; import thunk from "redux-thunk"; import rootReducer from "./reducers"; const initialState = {}; const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({ latency: 0 }) : compose; const store = createStore( rootReducer, initialState, composeEnhancers(applyMiddleware(thunk)) ); export default store; Trying to display data using useSelector() import React, { useEffect } from "react"; import Table from "@mui/material/Table"; import TableBody from "@mui/material/TableBody"; import TableCell from "@mui/material/TableCell"; import TableContainer from "@mui/material/TableContainer"; import TableHead from "@mui/material/TableHead"; import TableRow from "@mui/material/TableRow"; import Paper from "@mui/material/Paper"; import { useSelector, useDispatch } from "react-redux"; import { getTransactionList } from "../../actions/transaction"; export default function TransactionList() { const dispatch = useDispatch(); const data = useSelector((state) => state.transactions); console.log(data); useEffect(() => { dispatch(getTransactionList()); }, [dispatch]); return ( <TableContainer component={Paper} sx={{ boxShadow: "none" }}> Lastly my index.js import React from "react"; import ReactDOM from "react-dom"; import App from "./App"; import reportWebVitals from "./reportWebVitals"; import { Provider } from "react-redux"; import store from "./store"; ReactDOM.render( <React.StrictMode> <Provider store={store}> {" "} <App /> </Provider> </React.StrictMode>, document.getElementById("root") ); reportWebVitals(); Please any help would be greatly appreciated, REMINDER I AM NEW TO USING THESE TECHNOLOGIES. Any further information required can be provided. A: I see a more or less correct setup. The only part I think is missing is when you do this: const store = createStore( rootReducer, initialState, composeEnhancers(applyMiddleware(thunk)) ); Where is your rootReducer? I mean, I'm missing your root reducer code with something like that: import { combineReducers } from 'redux'; import { TransactionReducer } from 'your/path/TransactionReducer'; import { fooReducer } from 'your/path/fooReducer'; import { barReducer } from 'your/path/barReducer'; export const rootReducer = combineReducers({ transactions: TransactionReducer, foo: fooReducer, bar: barReducer, }); It isn't it?
{ "language": "en", "url": "https://stackoverflow.com/questions/71480859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to remove customAnimations from childFragmentManager Android The code to apply custom animations is this, though when I pass childFragmentManager to a bottom sheet dialog fragment the same animations are applied which is not even overridding. .childFragmentManager .beginTransaction() .setCustomAnimations( enter, exit, popEnter, popExit ) .replace(R.id.fl_fragment_container, fragment, tag) .setReorderingAllowed(true) .apply { if (shouldAddToBackStack) addToBackStack(tag) } .commit() A: You can disable the animation from BottomSheetDialogFragment override fun onResume() { super.onResume() // Disable dialog window animations for this instance dialog?.window?.setWindowAnimations(-1) }
{ "language": "en", "url": "https://stackoverflow.com/questions/72046055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Keyboard layout related issue I run on Ubuntu 14.04. I have an issue related to the keyboard layout in GUI mode. I managed to fix it in the GUI by using: setxkbmap -layout us [1] and adding it to the ~/.bashrc. That works fine. However, the problem is that when I log to the text-mode terminal I receive an error - Cannot display "default display". This is not surprising because this command does not work in text mode. The question is: where should I put [1] and have no error in text mode terminal? A: Issue is solved. Added script to ~/.bashrc: if [ "$TERM" = "xterm" ]; then setxkbmap -layout "us" fi
{ "language": "en", "url": "https://stackoverflow.com/questions/28215264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Generate Scripts For All Triggers in Database Using Microsoft SQL Server Management Studio I'd like to generate an SQL Script that contains the SQL to create all of the triggers that exist in our database. The triggers were added directly via the SSMS query pane so, there is currently no source other than the trigger on the database itself. I have already tried the method where you right-click the database, select Tasks->Generate Scripts and used the "Script Entire Database and All Objects" option. While this does create a SQL script for the tables and constraints, it does not generate SQL for the triggers. I also understand that I can right click on each trigger in the database and select the Generate SQL Script option but, there is currently 46 tables under audit (For Insert, Update, and Delete). Rather manually generate an insert, update, and delete trigger script for each of the 46 tables, is there an easier way to do this? Or, should I start clicking, copying, and pasting? A: I know the answer has been accepted already, but want to provide another solution for cases when for some reason SSMS wizard is not able to generate script for triggers (in my case it was MSSQL2008R2) This solution is based on idea from dana above, but uses 'sql_modules' instead to provide the full code of the trigger if it exceeds 4000 chars (restriction of 'text' column of 'syscomments' view) select [definition],'GO' from sys.sql_modules m inner join sys.objects obj on obj.object_id=m.object_id where obj.type ='TR' Right click on the results grid and then "Save results as..." saves to file with formatting preserved A: To script all triggers you can define the stored procedure: SET ANSI_NULLS ON; GO SET QUOTED_IDENTIFIER ON; GO -- Procedure: -- [dbo].[SYS_ScriptAllTriggers] -- -- Parameter: -- @ScriptMode bit -- possible values: -- 0 - Script ALTER only -- 1 - Script CREATE only -- 2 - Script DROP + CREATE ALTER PROCEDURE [dbo].[SYS_ScriptAllTriggers] @ScriptMode int = 0 AS BEGIN DECLARE @script TABLE (script varchar(max), id int identity (1,1)) DECLARE @SQL VARCHAR(8000), @Text NVARCHAR(4000), @BlankSpaceAdded INT, @BasePos INT, @CurrentPos INT, @TextLength INT, @LineId INT, @MaxID INT, @AddOnLen INT, @LFCR INT, @DefinedLength INT, @SyscomText NVARCHAR(4000), @Line NVARCHAR(1000), @UserName SYSNAME, @ObjID INT, @OldTrigID INT; SET NOCOUNT ON; SET @DefinedLength = 1000; SET @BlankSpaceAdded = 0; SET @ScriptMode = ISNULL(@ScriptMode, 0); -- This Part Validated the Input parameters DECLARE @Triggers TABLE (username SYSNAME NOT NULL, trigname SYSNAME NOT NULL, objid INT NOT NULL); DECLARE @TrigText TABLE (objid INT NOT NULL, lineid INT NOT NULL, linetext NVARCHAR(1000) NULL); INSERT INTO @Triggers (username, trigname, objid) SELECT DISTINCT OBJECT_SCHEMA_NAME(B.id), B.name, B.id FROM dbo.sysobjects B, dbo.syscomments C WHERE B.type = 'TR' AND B.id = C.id AND C.encrypted = 0; IF EXISTS(SELECT C.* FROM syscomments C, sysobjects O WHERE O.id = C.id AND O.type = 'TR' AND C.encrypted = 1) BEGIN insert into @script select '/*'; insert into @script select 'The following encrypted triggers were found'; insert into @script select 'The procedure could not write the script for it'; insert into @script SELECT DISTINCT '[' + OBJECT_SCHEMA_NAME(B.id) + '].[' + B.name + ']' --, B.id FROM dbo.sysobjects B, dbo.syscomments C WHERE B.type = 'TR' AND B.id = C.id AND C.encrypted = 1; insert into @script select '*/'; END; DECLARE ms_crs_syscom CURSOR LOCAL forward_only FOR SELECT T.objid, C.text FROM @Triggers T, dbo.syscomments C WHERE T.objid = C.id ORDER BY T.objid, C.colid FOR READ ONLY; SELECT @LFCR = 2; SELECT @LineId = 1; OPEN ms_crs_syscom; SET @OldTrigID = -1; FETCH NEXT FROM ms_crs_syscom INTO @ObjID, @SyscomText; WHILE @@fetch_status = 0 BEGIN SELECT @BasePos = 1; SELECT @CurrentPos = 1; SELECT @TextLength = LEN(@SyscomText); IF @ObjID <> @OldTrigID BEGIN SET @LineID = 1; SET @OldTrigID = @ObjID; END; WHILE @CurrentPos != 0 BEGIN --Looking for end of line followed by carriage return SELECT @CurrentPos = CHARINDEX(CHAR(13) + CHAR(10), @SyscomText, @BasePos); --If carriage return found IF @CurrentPos != 0 BEGIN WHILE ( ISNULL(LEN(@Line), 0) + @BlankSpaceAdded + @CurrentPos - @BasePos + @LFCR ) > @DefinedLength BEGIN SELECT @AddOnLen = @DefinedLength - (ISNULL(LEN(@Line), 0) + @BlankSpaceAdded ); INSERT @TrigText VALUES ( @ObjID, @LineId, ISNULL(@Line, N'') + ISNULL(SUBSTRING(@SyscomText, @BasePos, @AddOnLen), N'')); SELECT @Line = NULL, @LineId = @LineId + 1, @BasePos = @BasePos + @AddOnLen, @BlankSpaceAdded = 0; END; SELECT @Line = ISNULL(@Line, N'') + ISNULL(SUBSTRING(@SyscomText, @BasePos, @CurrentPos - @BasePos + @LFCR), N''); SELECT @BasePos = @CurrentPos + 2; INSERT @TrigText VALUES ( @ObjID, @LineId, @Line ); SELECT @LineId = @LineId + 1; SELECT @Line = NULL; END; ELSE --else carriage return not found BEGIN IF @BasePos <= @TextLength BEGIN /*If new value for @Lines length will be > then the **defined length */ WHILE ( ISNULL(LEN(@Line), 0) + @BlankSpaceAdded + @TextLength - @BasePos + 1 ) > @DefinedLength BEGIN SELECT @AddOnLen = @DefinedLength - ( ISNULL(LEN(@Line), 0 ) + @BlankSpaceAdded ); INSERT @TrigText VALUES ( @ObjID, @LineId, ISNULL(@Line, N'') + ISNULL(SUBSTRING(@SyscomText, @BasePos, @AddOnLen), N'')); SELECT @Line = NULL, @LineId = @LineId + 1, @BasePos = @BasePos + @AddOnLen, @BlankSpaceAdded = 0; END; SELECT @Line = ISNULL(@Line, N'') + ISNULL(SUBSTRING(@SyscomText, @BasePos, @TextLength - @BasePos+1 ), N''); IF LEN(@Line) < @DefinedLength AND CHARINDEX(' ', @SyscomText, @TextLength + 1) > 0 BEGIN SELECT @Line = @Line + ' ', @BlankSpaceAdded = 1; END; END; END; END; FETCH NEXT FROM ms_crs_syscom INTO @ObjID, @SyscomText; END; IF @Line IS NOT NULL INSERT @TrigText VALUES ( @ObjID, @LineId, @Line ); CLOSE ms_crs_syscom; insert into @script select '-- You should run this result under dbo if your triggers belong to multiple users'; insert into @script select ''; IF @ScriptMode = 2 BEGIN insert into @script select '-- Dropping the Triggers'; insert into @script select ''; insert into @script SELECT 'IF EXISTS(SELECT * FROM sysobjects WHERE id = OBJECT_ID(''[' + username + '].[' + trigname + ']'')' + ' AND ObjectProperty(OBJECT_ID(''[' + username + '].[' + trigname + ']''), ''ISTRIGGER'') = 1)' + ' DROP TRIGGER [' + username + '].[' + trigname +']' + CHAR(13) + CHAR(10) + 'GO' + CHAR(13) + CHAR(10) FROM @Triggers; END; IF @ScriptMode = 0 BEGIN update @TrigText set linetext = replace(linetext, 'CREATE TRIGGER', 'ALTER TRIGGER') WHERE upper(left(replace(ltrim(linetext), char(9), ''), 14)) = 'CREATE TRIGGER' END insert into @script select '----------------------------------------------'; insert into @script select '-- Creation of Triggers'; insert into @script select ''; insert into @script select ''; DECLARE ms_users CURSOR LOCAL forward_only FOR SELECT T.username, T.objid, MAX(D.lineid) FROM @Triggers T, @TrigText D WHERE T.objid = D.objid GROUP BY T.username, T.objid FOR READ ONLY; OPEN ms_users; FETCH NEXT FROM ms_users INTO @UserName, @ObjID, @MaxID; WHILE @@fetch_status = 0 BEGIN insert into @script select 'setuser N''' + @UserName + '''' + CHAR(13) + CHAR(10); insert into @script SELECT '-- Text of the Trigger' = CASE lineid WHEN 1 THEN 'GO' + CHAR(13) + CHAR(10) + linetext WHEN @MaxID THEN linetext + 'GO' ELSE linetext END FROM @TrigText WHERE objid = @ObjID ORDER BY lineid; insert into @script select 'setuser'; FETCH NEXT FROM ms_users INTO @UserName, @ObjID, @MaxID; END; CLOSE ms_users; insert into @script select 'GO'; insert into @script select '------End ------'; DEALLOCATE ms_crs_syscom; DEALLOCATE ms_users; select script from @script order by id END How to execute it: SET nocount ON DECLARE @return_value INT EXEC @return_value = [dbo].[SYS_ScriptAllTriggers] @InclDrop = 1 SELECT 'Return Value' = @return_value GO A: How about this? select text from syscomments where text like '%CREATE TRIGGER%' EDIT - per jj's comment below, syscomments is deprecated and will be removed in the future. Please use either the wizard-based or script-based solutions listed above moving forward :) A: Database-> Tasks-> Generate Scripts -> Next -> Next On Choose Script Options UI, under Table/View Options Heading, set Script Triggers to True. A: Using my own version with the combination of answer found in here and other post(can't find the original quetion. select OBJECT_NAME(parent_obj) AS table_name,sysobj.name AS trigger_name, [definition],'GO' from sys.sql_modules m inner join sysobjects sysobj on sysobj.id=m.object_id INNER JOIN sys.tables t ON sysobj.parent_obj = t.object_id INNER JOIN sys.schemas s ON t.schema_id = s.schema_id WHERE sysobj.type = 'TR' and sysobj.name like 'NAME_OF_TRIGGER' order by sysobj.name
{ "language": "en", "url": "https://stackoverflow.com/questions/13200511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "76" }
Q: Ineligible app Submission to Facebook What features does my canvas app need, in order to submit the application on the App Center? Facebook gave me this response: Ineligible Submission Your app does not have high enough ratings and user engagement to be eligible for the App Center at this time. A: Are you trying to get your App into Facebook App center? In your case, it seems that you don't have enough users to do so. Facebook review process states that "Once your app has enough high user ratings and engagement, you can be submit your App Details Page for App Center listing...", it means that you need to run your App for a while. Per your question (but I don't think that that's your real issue), the eligibility requirements are (see the same link above): Eligibility Requirements These apps are eligible for the App Center when they reach high user engagement and user ratings: A canvas page app with Login Dialog. A mobile apps built for iOS or Android and uses Facebook Login SDK for iOS or Facebook Login SDK for Android (More) A app that is a website and uses Facebook Login These apps are not currently eligible for App Center: A Page Tab app A Desktop web game off of Facebook.com
{ "language": "en", "url": "https://stackoverflow.com/questions/19616719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: iOS Swift Getting Lazy Map Collection Values I am trying to get the value for "alert" but not having very much luck. LazyMapCollection<Dictionary<AnyHashable, Any>, AnyHashable>(_base: [AnyHashable("google.c.a.e"): 1, AnyHashable("google.c.a.ts"): 1475009164, AnyHashable("google.c.a.udt"): 0, AnyHashable("gcm.n.e"): 1, AnyHashable("aps"): { alert = "test message"; }, AnyHashable("google.c.a.c_id"): 9039575328704479116, AnyHashable("gcm.message_id"): 0:1475009164740581%df6f7f01df6f7f01], _transform: (Function)) This is the code is a using but it does not work correctly if (userInfo["aps"] != nil) { let msg = (userInfo["alert"] as? String)! let alert1 = UIAlertController(title: "Notification", message: msg, preferredStyle: .alert) alert1.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) -> Void in })) self.window?.rootViewController?.present(alert1, animated: true, completion: nil) completionHandler(.newData) } I am trying to display a local notification with the message of the value alert. Any ideas would be appreciated. Thank you A: This is my working solution if (userInfo["aps"] != nil) { if let notification = userInfo["aps"] as? NSDictionary, let alert = notification["alert"] as? String { let alert1 = UIAlertController(title: "Notification", message: alert, preferredStyle: .alert) alert1.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) -> Void in })) self.window?.rootViewController?.present(alert1, animated: true, completion: nil) completionHandler(.newData) } }
{ "language": "en", "url": "https://stackoverflow.com/questions/39734141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unknown error communicating between PHP and Actionscript I've got a problem that's either insanely simple or complex, it's up to you to find out. I've been working on trying to incorporate the URL Loader class into the beginners graphics program - Stencyl. I am fluent in HTML, CSS and PHP but actionscript is completely new to me so I really could use with a hand. Here's what I've got: There are 4 files hosted on my domain: Webpage.html Stylesheet.css RequestData.php FlashDoc.swf The html and css code is simple, no problems there and the swf file embed in the html document. The flash file is a simple form with a text field, submit button and two dynamic text fields. The code goes as follows: // Btn listener submit_btn.addEventListener(MouseEvent.CLICK, btnDown); // Btn Down function function btnDown(event:MouseEvent):void { // Assign a variable name for our URLVariables object var variables:URLVariables = new URLVariables(); // Build the varSend variable // Be sure you place the proper location reference to your PHP config file here var varSend:URLRequest = new URLRequest("http://www.mywebsite.com/config_flash.php"); varSend.method = URLRequestMethod.POST; varSend.data = variables; // Build the varLoader variable var varLoader:URLLoader = new URLLoader; varLoader.dataFormat = URLLoaderDataFormat.VARIABLES; varLoader.addEventListener(Event.COMPLETE, completeHandler); variables.uname = uname_txt.text; variables.sendRequest = "parse"; // Send the data to the php file varLoader.load(varSend); // When the data comes back from PHP we display it here function completeHandler(event:Event):void{ var phpVar1 = event.target.data.var1; var phpVar2 = event.target.data.var2; result1_txt.text = phpVar1; result2_txt.text = phpVar2; } } I then have a small PHP file with this code: <?php // Only run this script if the sendRequest is from our flash application if ($_POST['sendRequest'] == "parse") { // Access the value of the dynamic text field variable sent from flash $uname = $_POST['uname']; // Print two vars back to flash, you can also use "echo" in place of print print "var1=My name is $uname..."; print "&var2=...$uname is my name."; } ?> This is, for some reason, not working. The result is just two blank text fields and being an actionscript noob, I have no idea what is up. Any help would be greatly appreciated. Thank you for your time. A: The answer to your issue is both simple and surprising, if you're not used to AS3. In AS3, the flash.* classes tend to, when a setter is used, make and store a copy of the passed object. Since they store a copy, any modification on the original instance after the setter isn't applied on the copy, and thus is ignored. It is the case of, for example, DisplayObject.filters, ContextMenu.customItems or URLRequest.data. In your code, you are setting varSend.data = variables before filling variables. You should do the reverse : variables.uname = uname_txt.text; variables.sendRequest = "parse"; varSend.data = variables; // Send the data to the php file varLoader.load(varSend); Only some classes do that, and even then, they usually don't do it with all of their setters.
{ "language": "en", "url": "https://stackoverflow.com/questions/19301202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Struggling to get .fadeIn jQuery to work on a homepage image transition script I'm unsure if fadeIn is even the right transition (newbie), but I'm basically trying to have a crossfade between homepage images that change every 3 seconds. The changing is working successfully, but I don't know how to get them to fade. Currently there is just an abrupt switch. Here is my code: var images = ["image-link1", "image-link2"]; $(function () { var i = 0; document.getElementById("homeImage").src = images[i]; setInterval(function () { if (i == images.length) { i = 0; } else { document.getElementById("homeImage").src = images[i]; $(this).fadeIn("slow"); i++; } }, 3000); }); I'm using ASP.NET MVC. Thanks! A: You have to fade out before that, you can add fadeOut before changing the elememt's background and then add fadeIn when the background has changed A: The steps will be * *Show an image. *Fade out the current image. *After finished fading out, change the url to a new image. *Fade in to show the new image. Working solution: $(function () { var i = 0; document.getElementById("homeImage").src = images[i]; setInterval(function () { if (i == images.length - 1) { i = 0; } else { $('#homeImage').fadeOut("slow", function() { document.getElementById("homeImage").src = images[i]; $('#homeImage').fadeIn("slow"); }); i++; } }, 3000); }); A: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - Williams Marketing Studio</title> <link rel="stylesheet" href="~/Content/newstyle.css"> @RenderSection("metatags", required: false) @Scripts.Render("~/bundles/modernizr") </head> <body> <header> <nav> <div class="nav-bar"> <span><a href="/Home/Index"><img src="~/Content/Images/nav-image.png" class="img-nav" title="Williams Marketing Studio" aria-label="Company Logo" /></a></span> <ul class="nav-links"> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("Services", "Index", "Services")</li> <li>@Html.ActionLink("Categories", "Index", "Categories")</li> <li>@Html.ActionLink("Contact", "Contact", "Home")</li> </ul> @using (Html.BeginForm("Index", "Services", FormMethod.Get, new { @class = "navbar-form navbar-left" })) { <div class="flex-row"> @Html.TextBox("Search", null, new { @class = "form-input", @placeHolder = "Search Services" }) <button type="submit" class="button">Search</button> </div> } </div> </nav> </header> <section> <div> <p><img id="homeImage" src="~/Content/Images/home-image2.jpg" class="header-image" padding="0px" title="Homepage Image" aria-label="Colourful Laptop Screen"></p> </div> <div class="container body-content"> @RenderBody() <hr /> </section> <footer> <div class="footer"> <section class="footer-column"> Copyright &copy;@DateTime.Now.Year<br> <a href="mailto:[email protected]" title="Email Us">Williams Marketing Studio</a> <a href="https://validator.w3.org/docs/users.html#Calling" title="HTML Validator" style="color: #87edaa;">W3C Validator API</a> <a href="https://jigsaw.w3.org/css-validator/manual.html" title="CSS Validator" style="color: #87edaa;">CSS Validator</a> </section> <section class="footer-column"> <span><a href="/Home/Index" title="HOME" aria-label="HOME"><img src="~/Content/Images/nav-image.png" alt="footer logo" height="100px"></a></span> </section> <section class="footer-column"> <ul class="footer-links"> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("Services", "Index", "Services")</li> <li>@Html.ActionLink("Categories", "Index", "Categories")</li> <li>@Html.ActionLink("Contact", "Contact", "Home")</li> </ul> </section> </div> </footer> <!--<footer> <address> Written by <a href="mailto:[email protected]">Williams Marketing Studio</a><br> </address> <p>&copy; @DateTime.Now.Year </p> </footer>--> </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/74002067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I set an input mask property to a text filed of access database so that it will add leading zeros? I have a table field of text data type. I want to set an input mask property so that it add leading zeros to make 12 digits number. say, Input: 1256 it will automatically converted as 000000001256 how can I do this? A: No need to use input mask .. use textbox and use format() function when store the text Dim MyStr as String = format(val(txtNumber.Text),"000000000000")
{ "language": "en", "url": "https://stackoverflow.com/questions/17055101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to reload a shiny app when CSV file changes I have a shiny app which generates a distance matrix. It reads a database saved in a csv file, load as a data.frame and then it calculates the distance matrix. This app runs in a host and is used in the same network by other pc using options(shiny.host = '0.0.0.0') and options(shiny.port = 5050). The main problem is that when the csv is upload, the new information is not available for the shiny app due to the csv is already read, and the people that is using this app through browser is not able to stop and run again the shiny app in the rstudio to reread the csv data.base. Is it possible to reload automatically the app when the csv is modified? Any suggestions? Thanks in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/74122361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Firebase 3 permission denied after first-time sign-in with Google, works after second time I have a Google sign-in implemented according to instructions: https://firebase.google.com/docs/auth/android/google-signin#authenticate_with_firebase Authentication and sign-in work fine, the user is authenticated and signed-in and the listener is called: mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { // User is signed in Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid()); } else { // User is signed out Log.d(TAG, "onAuthStateChanged:signed_out"); } } However, when trying to read from a user node/path having a standard security rule: "users": { "$user_id": { ".read": "auth !== null && auth.uid === $user_id", ".write": "auth !== null" } } with the following code triggered later manually: DatabaseReference userRef = FirebaseDatabase.getInstance().getReference("users"); userRef.child(uid).addListenerForSingleValueEvent( new ValueEventListener() { @Override public void onDataChange(DataSnapshot data) { ... } @Override public void onCancelled(DatabaseError error) { Log.w(TAG, "fb sync onCancelled: " + error.getMessage()); } }); onCancelled is called with "permission denied". The uid is correct, equals to the user ID as returned by firebaseAuth.getCurrentUser().getUid() Now the important part is that everything works fine if I sign-out and sign-in again, or if I terminate and re-launch the app. So I guess something must be wrong with the FirebaseAuth state after the initial sign-in, or maybe I miss something again..? Tested with firebase-*:9.0.2 and play-services-auth:9.0.2 as well as 9.2.0. A: My observations with Firebase realtime database. It caches data on server side before adding to database (for a few milliseconds). Result: Read operations are few milliseconds faster than write operations. * *What's happening with your request: * *It reaches server and asks for data which is still not available in realtime database. *Why that so: * *because its cached and still to be added to realtime database. *all this caching and adding data to realtime database takes only milliseconds of time, but its significant when you immediately invoke data after adding because your Get Data request has reached the server before the node is created. *That's why it shows permission denied. *When this does not happen: * *When your device is using low speed internet connectivity, your request reaches Firebase server with a delay of 1-3 seconds, this happens naturally. So this problem will not arise there. *What to do now: * *Just introduce a delay of 2-3 seconds before requesting data for the first time. *This gives the whole operation of authentication, node creation and adding data enough time to complete. *Everything will be smooth from there. A: Thanks to the suggestion from Mr Frank I've managed to pinpoint the culprit. The problem occurs when the user signs in with Google while being already signed in anonymously (which I didn't take into account). So a workaround would be to sign out the anonymous user (FirebaseAuth.getInstance().sign_out()) before trying to sign in with Google, although I believe it's still undesired behavior, because it makes linking accounts problematic. Here's an example to reproduce the problem: public class TestAuthGoogle extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener { static private final String TAG = TestAuthGoogle.class.getSimpleName(); private GoogleApiClient mGoogleApiClient; public static final int RC_SIGN_IN = 9001; private Handler mHandler = new Handler(); @Override public void onStart() { super.onStart(); signInAnonymously(); mHandler.postDelayed(new Runnable() { @Override public void run() { signInGoogle(); } },5000); } void signInAnonymously() { FirebaseAuth.getInstance().signInAnonymously() .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Log.d(TAG, "signInAnonymously:onComplete:" + task.isSuccessful()); if (!task.isSuccessful()) { Log.w(TAG, "signInAnonymously", task.getException()); } } }); } void signInGoogle() { GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.my_web_client_id)) .requestEmail() .build(); mGoogleApiClient = new GoogleApiClient.Builder(TestAuthGoogle.this) .enableAutoManage(TestAuthGoogle.this, TestAuthGoogle.this) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, RC_SIGN_IN); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RC_SIGN_IN) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); if (result.isSuccess()) { GoogleSignInAccount account = result.getSignInAccount(); firebaseAuthWithGoogle(account); Log.d(TAG,"Authenticated"); } else { Log.d(TAG,"Authentication failed"); } } } private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId()); AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); FirebaseAuth.getInstance().signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful()); if (task.isSuccessful()) { Log.d(TAG,"Signed in"); mHandler.postDelayed(new Runnable() { @Override public void run() { readFromDatabase(); } },5000); } else { Log.w(TAG, "signInWithCredential: " + task.getException().getMessage()); } } }); } void readFromDatabase() { Log.d(TAG,"read from db"); DatabaseReference uRef = FirebaseDatabase.getInstance().getReference("users"); uRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).addListenerForSingleValueEvent( new ValueEventListener() { @Override public void onDataChange(DataSnapshot data) { Log.d(TAG, "fb onDataChange: " + data.getValue()); } @Override public void onCancelled(DatabaseError error) { Log.w(TAG, "fb onCancelled: " + error.getMessage()); } }); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { Log.d(TAG,"onConnectionFailed"); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/38111682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Rails i18n Attributes Not Working via JSON API We have a RoR 4.2.5.1 API server and an AngularJS frontend. I'm trying get the internationalism working and have setup my en.yml as so en: activerecord: attributes: nas: calledstationid: 'AP Mac' errors: models: nas: attributes: calledstationid: blank: invalid: taken: "has already been added to a location" When I create 'nas' with a taken calledstationid, I'm expecting "AP Mac has already been added to a location". Instead I get, "calledstationid..." def create @nas = Nas.new( calledstationid: params[:box][:calledstationid] ) respond_to do |format| if @nas.save format.json { render template: 'api/v1/boxes/show.json.jbuilder', status: 201 } else @errors = @nas.errors format.json { render template: 'api/v1/shared/index.json.jbuilder', status: 422 } end end end When I use the bang, I can see the calledstationid is replaced with ap mac in the logs. So... my question is, why is the field name not being updated in the @nas.errors object? And how can I get this to work for multiple locales. -- EDIT -- The error object: @messages={:calledstationid=>["has already been added to a location"]}> A: You have 2 options to solve this. First: Edit your yaml file and replace the message with the below : "%{attribute} has already been added to a location" Second: What you are getting is standard and correct output as per the current YAML configuration. But to get what you are looking for, without changing the YAML, need to use ActiveModel::Errors#full_messages.Because this method prepends the attribute name to the error message.
{ "language": "en", "url": "https://stackoverflow.com/questions/35113584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android XML layout checkbox "onclick" method bind to a function not found in MainActivity Is it possible in Android to bind the "onclick" method from a checkbox to a function defined in a java class file directly in the XML file? something like this //XML layout File .... <CheckBox android:id="@+id/checkbox_1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/testString" android:textColor="@color/testcolor" android:onClick="onClickCheckbox_1_do"/> ... public class TestClass{ ... public void onClickCheckbox_1_do(View view) { //DoStuff } } Thanks! A: Yes, you can. I just did. Write this code in your layout file: <CheckBox android:layout_width="match_parent" android:layout_height="match_parent" android:onClick="click"/> And in your activity: public void click(View view) { } A: Yes! it's possible. To define the click event handler for a checkbox, you should add android:onClick attribute to the element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method. The method you declare in the android:onClick attribute must have a signature exactly as shown above. Specifically, the method must: 1. Be public 2. Return void, and 3. Define a View as its only parameter (this will be the View that was clicked) Below is the code examples: xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <CheckBox android:id="@+id/checkbox_meat" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/meat" android:onClick="onCheckboxClicked"/> <CheckBox android:id="@+id/checkbox_cheese" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/cheese" android:onClick="onCheckboxClicked"/> </LinearLayout> The activity method should look as follows: public void onCheckboxClicked(View view) { // Is the view now checked? boolean checked = ((CheckBox) view).isChecked(); // Check which checkbox was clicked switch(view.getId()) { case R.id.checkbox_meat: if (checked) // Put some meat on the sandwich else // Remove the meat break; case R.id.checkbox_cheese: if (checked) // Cheese me else // I'm lactose intolerant break; // TODO: Veggie sandwich } } I hope you find this helpful.
{ "language": "en", "url": "https://stackoverflow.com/questions/61817232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Query on Optional fields with QueryDSL I've had some trouble trying to figure out how QueryDSL is working with Java 8 Optional attributes. I have configured QueryDSL, and queries like tests?field=valueare working on the String attributes. But as some of the getters of my class have Optional return types, the QTest class that is generated contains SimplePath<Optional<String>> instead of a simple StringPath for a String attribute. See below : Test.class @QueryEntity @Document(collection = "test") public class Test { private String field; private String optionalField; Test(String field, String optionalField) { this.field = field; this.optionalField = optionalField; } public String getField() { return field; } public Optional<String> getOptionalField() { return Optional.ofNullable(optionalField); } } Generated QTest.class @Generated("com.querydsl.codegen.EntitySerializer") public class QTest extends EntityPathBase<Test> { private static final long serialVersionUID = -609090735L; public static final QTest test = new QTest("test"); public final StringPath field = createString("field"); public final ComparablePath<java.util.UUID> id = createComparable("id", java.util.UUID.class); public final SimplePath<java.util.Optional<String>> optionalField = createSimple("optionalField", java.util.Optional.class); } The object in the database is such : { "field":"value", "optionalField":"optionalValue" } The controller : @RestController @RequestMapping("/tests") public class TestController { private final TestService testService; @Inject public TestController (final TestService testService) { this.testService = testService; } @GetMapping() public ResponseEntity<Page<Test>> getAllWithPredicate(Pageable pageable, @QuerydslPredicate(root = Test.class) Predicate predicate) { return new ResponseEntity<>(this.testService.getAllTestsWithPredicate(pageable, predicate), HttpStatus.OK); } @PostMapping public ResponseEntity<Test> createTest(@RequestBody Test test) { return new ResponseEntity<>(this.testService.createTest(test), HttpStatus.CREATED); } } Service : @Service public class TestService { private final TestRepository testRepository; @Inject public TestService(final TestRepository repo) { this.testRepository = repo; } public Page<Test> getAllTestsWithPredicate(Pageable pageable, Predicate predicate) { return this.testRepository.findAll(predicate, pageable); } public Test createTest(Test test) { Test savedTest = testRepository.save(test); return savedTest; } } And the repository : @Repository public interface TestRepository extends JpaRepository<Test, String>, QuerydslPredicateExecutor<Test>, QuerydslBinderCustomizer<QTest> { @Override default public void customize(QuerydslBindings bindings, QTest root) { bindings.bind(String.class).first((StringPath path, String value) -> path.containsIgnoreCase(value)); } } So, first of all I wanted to process a containsIgnoreCase on both of my fields. This containsIgnoreCase is perfectly working on the normal field. But when it comes to the Optional, with this request : tests?optionalField=optionalValue I got this error message : java.lang.ClassCastException: com.querydsl.core.types.dsl.SimplePath cannot be cast to com.querydsl.core.types.dsl.StringPath at org.springframework.data.querydsl.binding.QuerydslBindings$MultiValueBindingAdapter.bind(QuerydslBindings.java:506) ~[spring-data-commons-1.13.10.RELEASE.jar:na] at org.springframework.data.querydsl.binding.QuerydslPredicateBuilder.invokeBinding(QuerydslPredicateBuilder.java:139) ~[spring-data-commons-1.13.10.RELEASE.jar:na] at org.springframework.data.querydsl.binding.QuerydslPredicateBuilder.getPredicate(QuerydslPredicateBuilder.java:113) ~[spring-data-commons-1.13.10.RELEASE.jar:na] ... That seems to be a normal behavior because of the QTest type generated for this field (SimplePath<Optional<String>> instead of StringPath), but the fact is that I can't find any working way to deal with this optionalField. So my questions are : Can QueryDSL work with Optional<String> values ? And if so, how am I supposed to query on these fields ? Thank you for your help ! :)
{ "language": "en", "url": "https://stackoverflow.com/questions/58879134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP Curl Proxy, how to define $_FILES['foo']['name'] I'm using CURL to make a PHP Proxy that forward a multipart form. The form have an input type="file". The proxy receive the following data: array 'foo' => array 'name' => string 'wt.jpg' (length=6) 'type' => string 'image/jpeg' (length=10) 'tmp_name' => string '/tmp/phpoIvraK' (length=14) 'error' => int 0 'size' => int 7427 So I'm expecting the page at the end to receive the same array (except for the tmp_name) Right now I receive this: 'foo' => array 'name' => 'phpoIvraK' 'type' => 'image/jpeg' 'tmp_name' => '/tmp/php5ZhCwy' 'error' => 0 'size' => 7427 As you can see, the name is now the tmp_name that the proxy is receiving, so the original filename is lost. Here's the PHP Code: $arrFields = $_POST; foreach($_FILES as $k => $file) $arrFields[$k] = '@' . $file['tmp_name'] . ';type=' . $file['type']; curl_setopt($ressource, CURLOPT_POSTFIELDS, $arrFields); Ps.: I know I could make a new variable, but the goal here is to respect the variable format, and make the usage of the proxy as transparent as possible for the person that'll use it. Is it me or the only solution would be to rename the tmp file in the /tmp before resending it ? That looks a bit silly to me ... $arrFields = $_POST; foreach($_FILES as $k => $file){ move_uploaded_file($file['tmp_name'], $file['name']); $arrFields[$k] = '@' . $file['name'] . ';type=' . $file['type']; } curl_setopt($ressource, CURLOPT_POSTFIELDS, $arrFields); A: I think you shouldn't use the tmp file but instead store the file with it's real name somewhere, pass it to the POSTFIELDS param and after executing remove it. That seems to easiest way to me. curl doesn't care about the original request, it just does what you tell it to do and that is ... send the temp file over. A: Faced similar situation and this is how I solved it Pass the actual file name along with the request $arrInputs["uploadvia"] = 'curl'; $arrInputs["actualfilename"]= $_FILES["upfile1"]["name"]; $arrInputs["upfile1"] = "@".$_FILES["upfile1"]["tmp_name"].";type=".$_FILES["upfile1"]["type"].";"; curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $arrInputs); And at the other end, put this block if($_POST['uploadvia'] == "curl") { $_FILES["upfile1"]["name"] = $_REQUEST['actualfilename']; }
{ "language": "en", "url": "https://stackoverflow.com/questions/5097403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the time complexity of an algorithm with the setTimeout function? Given the following sorting algorithm, what is the time complexity of the sort? function sort(arr) { arr.forEach(i => { setTimeout(() => console.log(i), i) }) } const n = [100, 1000000, 10000, 3600000, 3, 5, 0, 1, 9]; sort(n); Output: 0 1 3 5 9 100 10000 3600000 // After 1 hour
{ "language": "en", "url": "https://stackoverflow.com/questions/63459610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Clojure: Rename and select keys from map with one iteration In Clojure, I want to both rename-keys and select-keys from a map. The simple way of doing is with: (-> m (rename-keys new-names) (select-keys (vals new-names))) But this will itetate over the entire map twice. Is there a way to do it with one iteration? A: Sure, there is a way to do it with a single iteration. You could do it using reduce-kv function: (reduce-kv #(assoc %1 %3 (get m %2)) {} new-names) or just a for loop: (into {} (for [[k v] new-names] [v (get m k)])) If you want a really simple piece of code, you could use fmap function from algo.generic library: (fmap m (map-invert new-names))
{ "language": "en", "url": "https://stackoverflow.com/questions/30186390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Why the string is always empty? I try to use LINQ to read XML file. However, the string which store the value of selected attribute is always empty. Here is the code: string output = ""; XDocument loaded = XDocument.Load(@"d:\input.xml"); var ta = from tmp in loaded.Descendants("NewDataSet.Table") select tmp.Element("E1"); foreach (string ss in ta) { ouput += ss; } The output string is always empty. But the ss string has correct value. What is the problem? I've no idea how to add xml file with style. So i have to update the xml file as image. :( A: Now that you have shown your XML, here's how to fix your code: var ta = from tmp in loaded.Descendants("Table") select tmp.Element("E1"); You do not use . in XML as you do in C# to navigate the XML tree. You could also navigate a XML tree using XPath: var ta = from tmp in loaded.XPathSelectElements("NewDataSet/Table/E1") select tmp; Also I would recommend you to use a StringBuilder instead of string concatenations for this output variable: var ta = from tmp in loaded.Descendants("Table") select tmp.Element("E1"); var builder = new StringBuilder(); foreach (string ss in ta) { builder.Append(ss); } string output = builder.ToString(); A: var ta = from tmp in loaded.Descendants("Table") select tmp.Element("E1");
{ "language": "en", "url": "https://stackoverflow.com/questions/7298045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to control colors assigned to data groups? Code: mtcars %>% group_by(cyl,am) %>% ggvis(~mpg, fill = ~factor(cyl)) %>% layer_densities() The code above plots density graphs for each group of "cyl" and assigns different colors according to three levels of cyl: (4,6,8). But I don't have control over what color is assigned to each group. How can I assign specific colors e.g. "red", "green", and "yellow" to each group? A: You can add the following to your ggvis function ... %>% scale_ordinal("fill", range = c("red", "green", "yellow"))
{ "language": "en", "url": "https://stackoverflow.com/questions/35183653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ignoring RegisterValidateFunction() for flag pointer 0x10ef76ec0: no flag found at that address in Xcode How can I fix the issue? W0721 13:54:19.105928 1 commandlineflags.cc:1503] Ignoring RegisterValidateFunction() for flag pointer 0x10ef76ec0: no flag found at that address A: This problem occurs because your code try to using non-existing pointer in cocoa pods. You may using framework that using cocoa pods and install needed pods on the main project. The solution is to make cocoa pods version similar in both framework and project , run pod update from the terminal in both framework and project or specify every pod version to be same in both Example framework pod file : pod 'GooglePlaces' '~> 3.1.0' project pod file : pod 'GooglePlaces' '~> 3.1.0' I hope this solve your problem. A: I've seen this error when I had a UITableView in a view controller and: * *I connected the DataSource and Delegate for table view in the Storyboard. *I did NOT declare the UIViewController as UITableViewDelegate and UITableViewDataSource. I usually assign delegate/datasource in code (which would have given me a warning).
{ "language": "en", "url": "https://stackoverflow.com/questions/51454279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Check if numpy array is in list of numpy arrays I have a list of numpy arrays and a single numpy array. I want to check if that single array is a member of the list. I suppose there exist a method and I haven't searched properly... This is what I came up with: def inList(array, list): for element in list: if np.array_equal(element, array): return True return False Is this implementation correct? Is there any ready function for this? A: lets say you have an array like this: a= [array([ 1, 24, 4, 5]), array([ 22, 4, 123]), array([11, 1, 1])] #convert all subarrays to list a= [ list(item) for item in a ] no you can check for a sublist like this: In [80]: [1,22,4] in a Out[80]: False In [81]: [1,24,4,5] in a Out[81]: True A: Using the verb is when talking about python is a bit ambiguous. This example covers all the cases I could think of: from __future__ import print_function from numpy import array, array_equal, allclose myarr0 = array([1, 0]) myarr1 = array([3.4499999, 3.2]) mylistarr = [array([1, 2, 3]), array([1, 0]), array([3.45, 3.2])] #test for identity: def is_arr_in_list(myarr, list_arrays): return next((True for elem in list_arrays if elem is myarr), False) print(is_arr_in_list(mylistarr[2], mylistarr)) #->True print(is_arr_in_list(myarr0, mylistarr)) #->False #myarr0 is equal to mylistarr[1], but it is not the same object! #test for exact equality def arreq_in_list(myarr, list_arrays): return next((True for elem in list_arrays if array_equal(elem, myarr)), False) print(arreq_in_list(myarr0, mylistarr)) # -> True print(arreq_in_list(myarr1, mylistarr)) # -> False #test for approximate equality (for floating point types) def arreqclose_in_list(myarr, list_arrays): return next((True for elem in list_arrays if elem.size == myarr.size and allclose(elem, myarr)), False) print(arreqclose_in_list(myarr1, mylistarr)) #-> True PS:do NOT use list for a variable name, as it is a reserved keyword, and often leads to subtle errors. Similarly, do not use array. A: There is a much simpler way without the need to loop using np.all(). It only works when all the arrays within the list of arrays have the same shape: list_np_arrays = np.array([[1., 1.], [1., 2.]]) array_to_check = np.array([1., 2.]) is_in_list = np.any(np.all(array_to_check == list_np_arrays, axis=1)) The variable is_in_list indicates if there is any array within he list of numpy arrays which is equal to the array to check.
{ "language": "en", "url": "https://stackoverflow.com/questions/23979146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "35" }
Q: JSONP works in jQuery but not in mootools I'm trying to convert my code to Mootools (I like the coding paradigm better). I am doing cross-domain AJAX where I own both domains (closed network). I am just requesting simple JSON from my server. I get these errors in Mootools (jQuery works): Resource interpreted as Script but transferred with MIME type text/plain. Uncaught SyntaxError: Unexpected token : var url = http://localhost:3000/ Server: var http = require('http'), json = {"hi" : false}; http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end(JSON.stringify(json)); }).listen(3000, function() { console.log("Server on " + 3000); }); jQuery: $.ajax({ url: url, type: "GET", dataType: 'json', success: function (data) { } }); Mootools: var myRequest = new Request.JSONP({ url: url, onComplete: function (data) { alert(JSON.stringify(data)); } }); myRequest.send(); I've tried adding these headers to no avail.: 'Accept': 'application/json', 'Content-Type': 'application/json' This seems to be a client-side thing and not a server-side thing since it works in jQuery. A: What does URL look like? jQuery figures out it's a JSONP request by adding ?callback= or ?foo= to the url. Request.JSONP instead uses an option callbackKey. There's no method option for JSONP (in any library), since it's just injecting a script tag. var myRequest = new Request.JSONP({ url: url, callbackKey: 'callback' onComplete: function(data){} }).send(); I have a feeling, however, you aren't using JSONP, but rather XHR with JSON. If that's the case, use Request.JSON, not Request.JSONP. Edit Since it sounds, from the comments on this answer, that you're not using JSONP, just do this: new Request.JSON({ url: url, method: 'get', onSuccess: function (data){ console.log(data) } }).send() Edit 2 To change the request headers just add them as an option: new Request.JSON({ headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*' }, url: url, method: 'get', onSuccess: function (data){ console.log(data) } }).send() A: You had a syntax error in your code. var myRequest = new Request.JSONP({ url: url, method: 'get', onComplete: function(data){} }); myRequest.send(); Also, the response should be wrapped with callback function, example: http://jsfiddle.net/zalun/yVbYQ/ A: Your ajax call should be like this $.ajax({ type: "GET", url: "http://localhost:17370/SampleService.asmx/HelloWorld", data: "{}", crossDomain: true, contentType: "application/json; charset=utf-8", dataType: "jsonp", async:false, success:function(data,status){ alert(data); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert("Error Occured!" + " | " + XMLHttpRequest + " | " + textStatus + " | " + errorThrown); } }); Your server side method should not return simple string it should return response in jsonp format for that you need to follow this blog: http://msrtechnical.blogspot.in/
{ "language": "en", "url": "https://stackoverflow.com/questions/5629137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: sort data from mysql table using php Can you help me how to sort my data from MySQL table ? I want to sort is by using the table head : <?php if(isset($_POST['search'])) { $valueTosearch = $_POST['searchvalue']; $query = "SELECT * FROM `admin` WHERE CONCAT(`id`, `name`, `gender`, `user_group`, `date_registered`) LIKE '%".$valueTosearch."%'"; $search_result = filterTable($query); } else { $query = "SELECT * FROM `admin`"; $search_result = filterTable($query); } function filterTable($query) { include('config/dbconnect.php'); $filter_result = mysqli_query($con, $query); return $filter_result; } ?> <form method='post' action=''> <div><input type = 'text' name = 'searchvalue' placeholder="search by name"> <span> <div style='margin-bottom:3px; margin-top:3px'> <input id='gradient' class='search-btn' type = 'hidden' name = 'search' value = 'search'> </div> </span> <div style="height: auto"> <table id='responsive_table'> <thead> <tr> <th scope="col"><a href="sort">name</a></th> <th scope="col"><a href="sort">sex</a></th> <th scope="col"><a href="sort">user group</a></th> <th scope="col"><a href="sort">date register</a></th> </tr> </thead> <?php while($row = mysqli_fetch_array($search_result)): ?> <tbody> <tr> <td scope="row" data-label='name'><?php echo $row['name']; ?></td> <td data-label='sex'><?php echo $row['gender']; ?></td> <td data-label='user group'><?php echo $row['user_group']; ?></td> <td data-label='date register'><?php echo $row['date_registered']; ?></td> </tr> </tbody> <?php endwhile; ?> </table> </div> </form> A: Why don't you use order by clause: SELECT * FROM table ORDER BY column; Order By Reference A: You can modified your query as below for sorting: sql > select * from <table name> order by <column name>; default sorting is ascending order else for descending you can do like sql > select * from <table name> order by <column name> desc; A: If you could use JQuery, it's very simple, you have just to add the following javascript code: $( document ).ready(function() { $("#responsive_table").DataTable({ ordering: true, searching: true }); }); for a complete example see the following code: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> <script src="https://code.jquery.com/jquery-3.1.0.js"></script> <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css"> <script> $( document ).ready(function() { $("#responsive_table").DataTable({ ordering: true, searching: true }); }); </script> </head> <body> <form method='post' action=''> <div style="height: auto"> <table id='responsive_table'> <thead> <tr> <th scope="col">name</th> <th scope="col">sex</th> <th scope="col">user group</th> <th scope="col">date register</th> </tr> </thead> <tbody> <tr> <td scope="row" data-label='name'>HERE</td> <td data-label='sex'>Your</td> <td data-label='user group'>data</td> <td data-label='date register'>loaded</td> </tr> <tr> <td scope="row" data-label='name'>via</td> <td data-label='sex'>PHP</td> <td data-label='user group'>loop</td> <td data-label='date register'>bye</td> </tr> </tbody> </table> </div> </form> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/40170383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android get data from gmail, attachment is json What I want: Get data from json in gmail attachment. Description: Open Gmail, click attachment which is json file. Json file handle data which I need to procesing. In Manifest I declarated <intent-filter> <action android:name="android.intent.action.VIEW" /> <data android:mimeType="application/json"/> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> Next i use Intent intent = getIntent(); if(intent.getAction().equals(Intent.ACTION_VIEW)){ intent.getData <- I suppose from here i can get my infomation } But intent.getData only return Uri, and I read someone i must use ContentResolver, InputStream and something else to for example write my data from json to string. If some can explain how it works on example I will appreciate it. A: Ok i have it if (intent.getAction().equals(Intent.ACTION_VIEW)) { Toast.makeText(this, "work", Toast.LENGTH_SHORT).show(); Uri data = intent.getData(); // ContentResolver contentResolver = getContentResolver(); String text = getStringFromShare(data); Log.d("sasas", "onCreate: sometext"); } } private String getStringFromShare(Uri data) { String text = null; try { ContentResolver cr = getApplicationContext().getContentResolver(); InputStream is = cr.openInputStream(data); if (is != null) { StringBuffer buf = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String str; if (is != null) { while ((str = reader.readLine()) != null) { buf.append(str); } } is.close(); text = buf.toString(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return text; }
{ "language": "en", "url": "https://stackoverflow.com/questions/55407288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to load a STL vector with a constant If I have a vector<double> that has already been resized to be 1200, what is the best way to load that vector with the same value in each slot? The value is not known at compile time. Right now I just use a loop through all 1200 slots and set each slot equal to the value. I was wondering if this was the best way to do this. A: You can use std::vector constructor explicit vector (size_type n, const value_type& val = value_type(), const allocator_type& alloc = allocator_type()); next way vector<double> myVector; double value = 1.; myVector = vector<double>(1200, value); alternative is std::fill, which will avoid memory allocation std::fill(begin(myVector), end(myVector), value); A: You could use loop unrolling: std::vector<double> my_vector(1200); for (int i = 0; i < 300; i += 4) { my_vector[i + 0] = value; my_vector[i + 1] = value; my_vector[i + 2] = value; my_vector[i + 3] = value; } I suggest playing around with the number of assignments in the loop. The idea here is to reduce the overhead of incrementing and branching (do more data operations).
{ "language": "en", "url": "https://stackoverflow.com/questions/60309383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JSF PrimeFaces datatable filtering I 'record' objects and I put them in a datatable. A record has a boolean value 'Ignored', my idea is to make a filter so that it either shows all ignored records or everything. Here is my code: <p:column headerText="Status" filterMatchMode="equals" filterBy="#{record.ignored}"> <f:facet name="filter"> <p:selectOneButton onchange="PF('logTable').filter()"> <f:converter converterId="javax.faces.Boolean" /> <f:selectItem itemLabel="All" itemValue="" /> <f:selectItem itemLabel="Ignored" itemValue="#{record.ignored}" /> </p:selectOneButton> </f:facet> <h:outputText value="#{record.status}" /> </p:column> For some reason it is not working properly which i could not find, after searching for some examples online. A: The item value for this item <f:selectItem itemLabel="Ignored" itemValue="#{record.ignored}" /> should be either true or false since that is the condition that will be check during the filtering of the records <f:selectItem itemLabel="Ignored" itemValue="true" />
{ "language": "en", "url": "https://stackoverflow.com/questions/45635217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Splash with 9 patch ruins next activity I have a splash screen with my company's logo in the center of it with a little progress bar under it. I launch the splash as the first activity, and before that happens I display an image of the splash (without the progress bar, just the logo) using the app's theme background. I placed a 9 patch image of the in the app's theme android:windowBackground, and when the extension of that file is .9.png - the splash activity is displayed on the top left corner of the screen in a smaller size. Changing the extension to .png makes the splash display correctly over the whole screen, but of course my first image is stretch horribly ,because it's much smaller than the screen. Exmaple: This is the logo The picture below is how the app looks when the splash has been loaded and I am using the .9.png extension The picture below is how the app looks when the splash has been loaded and I am using the .png extension The pic above is how I want the splash to look, but without the .9.png extension the app looks like this (picture below) before the splash loads Anybody experienced this issue? Couldn't find it online. Thanks for the help. A: Solved the issue. Instead of changing the app's theme's windowBackground to my 9patch image, I added a new theme with the 9patch background and attached it to my first activity. So the basic rule is, don't put a 9patch image in the app's theme background. Place it in the first activity's theme instead. Source for this solution: https://developer.appcelerator.com/question/149184/9-patch-splash-screen-initial-window-does-not-fill-screen
{ "language": "en", "url": "https://stackoverflow.com/questions/24739943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Accessing App Store Data Is there a way to access app logo, category, price and other app store information using the app store url. Want my app to be able to access app store information from the apps url. Is this possible? A: You can use the iTunes Search API: http://www.apple.com/itunes/affiliates/resources/documentation/itunes-store-web-service-search-api.html This page can help you better understand how the iTunes Search API works: http://www.phponwebsites.com/2015/03/get-app-details-from-apple-itunes-using-php.html
{ "language": "en", "url": "https://stackoverflow.com/questions/35441733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Microsoft JET SQL Query Logging or "How do I debug my customer's program?" The problem: We use a program written by our biggest customer to receive orders, book tranports and do other order-related stuff. We have no other chance but to use the program and the customer is very unsupportive when it comes to problems with their program. We just have to live with the program. Now this program is most of the time extremely slow when using it with two or more user so I tried to look behind the curtain and find the source of the problem. Some points about the program I found out so far: * *It's written in VB 6.0 *It uses a password-protected Access-DB (Access 2000 MDB) that is located a folder on one user's machine. *That folder is shared over the network and used by all other users. *It uses the msjet40.dll version 4.00.9704 to communicate with access. I guess it's ADO? I also used Process Monitor to monitor file access and found out why the program is so slow: it is doing thousands of read operations on the mdb-file, even when the program is idle. Over the network this is of course tremendously slow: Process Monitor Trace http://img217.imageshack.us/img217/1456/screenshothw5.png The real question: Is there any way to monitor the queries that are responsible for the read activity? Is there a trace flag I can set? Hooking the JET DLL's? I guess the program is doing some expensive queries that are causing JET to read lots of data in the process. PS: I already tried to put the mdb on our company's file server with the success that accessing it was even slower than over the local share. I also tried changing the locking mechanisms (opportunistic locking) on the client with no success. I want to know what's going on and need some hard facts and suggestions for our customer's developer to help him/her make the programm faster. A: To get your grubby hands on exactly what Access is doing query-wise behind the scenes there's an undocumented feature called JETSHOWPLAN - when switched on in the registry it creates a showplan.out text file. The details are in this TechRepublic article alternate, summarized here: The ShowPlan option was added to Jet 3.0, and produces a text file that contains the query's plan. (ShowPlan doesn't support subqueries.) You must enable it by adding a Debug key to the registry like so: \\HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\JET\4.0\Engines\Debug Under the new Debug key, add a string data type named JETSHOWPLAN (you must use all uppercase letters). Then, add the key value ON to enable the feature. If Access has been running in the background, you must close it and relaunch it for the function to work. When ShowPlan is enabled, Jet creates a text file named SHOWPLAN.OUT (which might end up in your My Documents folder or the current default folder, depending on the version of Jet you're using) every time Jet compiles a query. You can then view this text file for clues to how Jet is running your queries. We recommend that you disable this feature by changing the key's value to OFF unless you're specifically using it. Jet appends the plan to an existing file and eventually, the process actually slows things down. Turn on the feature only when you need to review a specific query plan. Open the database, run the query, and then disable the feature. For tracking down nightmare problems it's unbeatable - it's the sort of thing you get on your big expensive industrial databases - this feature is cool - it's lovely and fluffy - it's my friend… ;-) A: Could you not throw a packet sniffer (like Wireshark) on the network and watch the traffic between one user and the host machine? A: If it uses an ODBC connection you can enable logging for that. * *Start ODBC Data Source Administrator. *Select the Tracing tab *Select the Start Tracing Now button. *Select Apply or OK. *Run the app for awhile. *Return to ODBC Administrator. *Select the Tracing tab. *Select the Stop Tracing Now button. *The trace can be viewed in the location that you initially specified in the Log file Path box. A: First question: Do you have a copy of MS Access 2000 or better? If so: When you say the MDB is "password protected", do you mean that when you try to open it using MS Access you get a prompt for a password only, or does it prompt you for a user name and password? (Or give you an error message that says, "You do not have the necessary permissions to use the foo.mdb object."?) If it's the latter, (user-level security), look for a corresponding .MDW file that goes along with the MDB. If you find it, this is the "workgroup information file" that is used as a "key" for opening the MDB. Try making a desktop shortcut with a target like: "Path to MSACCESS.EXE" "Path To foo.mdb" /wrkgrp "Path to foo.mdw" MS Access should then prompt you for your user name and password which is (hopefully) the same as what the VB6 app asks you for. This would at least allow you to open the MDB file and look at the table structure to see if there are any obvious design flaws. Beyond that, as far as I know, Eduardo is correct that you pretty much need to be able to run a debugger on the developer's source code to find out exactly what the real-time queries are doing... A: It is not possible without the help of the developers. Sorry.
{ "language": "en", "url": "https://stackoverflow.com/questions/153053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Android Espresso: checking if a TextView is showing a formatted string from resource Suppose you have a formatted string like this: <string name="saving">You saved %1$s with %2$s</string> now if you want to check if your TextView is showing it correctly, so naturally, something like this would work: Espresso.onView(withId(R.id.tv)) .check(matches(withText(R.string.saving))) but it doesn't and I cannot check the text with hardcoded strings because it might be on another language. so is there even a way for that? A: Maybe something like: Espresso.onView(withId(R.id.tv)) .perform(object :ViewAction{ override fun getDescription(): String { return "Normalizing the string" } override fun getConstraints(): Matcher<View> { return isAssignableFrom(TextView::class.java) } override fun perform(uiController: UiController?, view: View?) { val tv = view as TextView if (tv.text.matches(Regex("You saved (.)*? with (.)*"))) { tv.text = "You saved %1\$s with %2\$s" } } }).check(matches(withText(R.string.saving)))
{ "language": "en", "url": "https://stackoverflow.com/questions/59873971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to draw ellipses in Scilab with orientation? The existing functions xarc draw an ellipse, but the semi-major axes are aligned with the plot axes. Is there a way to 'rotate' the ellipse so it has an orientation that is not with the plot axes? A: If the arc is the only element drawn in the axes, then you can actually use xarc() to generate it, and then rotate the whole axes: clf xarc(0, 1, 3, 1, 0, 310*64) isoview gca().rotation_angles(2) = 70; But, its likely not the case. Then the arc must be generated as a polyline object, and then rotate() can be used to rotate it: clf alpha = 0:1:310; [a, b, xc, yc] = (3, 1, 2, 2); x = xc + a*cosd(alpha); y = yc + b*sind(alpha); r = 20; // rotation angle in ° xyR = rotate([x;y], r/180*%pi, [xc ; yc])'; plot(xyR(:,1), xyR(:,2))
{ "language": "en", "url": "https://stackoverflow.com/questions/71056092", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to communicate my server using GSM modem ip address in java? I am using sim900 gsm model for my server to connect from gprs network. My server is connected to lan. I want to connect my server from ethernet and gprs. I have installed this server in phytech board with arch linux os and gsm model is connected through serial port ie, /dev/ttyO0.I searched lot on this but got only AT command communication and that i can able to do. My question is, i should be able to communicate my server by client using either lan or gprs or how can i assign gsm modem ip address to my server? I need any steps or piece of code for this, where i can understand. Any help will be appreciated.
{ "language": "en", "url": "https://stackoverflow.com/questions/35145432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Converting number to hours? Hello I have this using javascript : var newhour = 20.5; hour.setHours(newhour); The problem is when I do console.log(hour) I get 20:05 but I would like to get 20:30. How can I do this ? Thank you a lot ! A: You need to convert 0.5 into the number of minutes: var newhour = 20.5; var hour = new Date(); var newhours = Math.floor(newhour), newmins = 60 * (newhour - newhours); hour.setHours(newhours); hour.setMinutes(newmins); console.log(hour.toTimeString()); A: You could set the hours, minutes and seconds by getting only the parts for the units. function setTime(date, time) { ['setHours', 'setMinutes', 'setSeconds'] .reduce((t, k) => (date[k](Math.floor(t)), t % 1 * 60), time); } var hour = new Date, newhour = 8.5; setTime(hour, newhour); console.log(hour); A: I would like to get 20:30 To set the time to exactly 20:30:00.000 from newhour = 20.5, you would take advantage of setHours() having four (optional) arguments (see MDN). Simply convert newhour to milliseconds (multiply by 3600000), and pass as fourth argument: hour.setHours(0, 0, 0, 20.5 * 36e5); Demo code here: var someDate = new Date; var newHour = 20.5; someDate.setHours(0, 0, 0, newHour * 36e5); console.log(someDate.toString()); A: You could use momentjs duration for that: const duration = moment.duration(20.5, 'hours') console.log(duration.hours() + ':' + duration.minutes()); <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
{ "language": "en", "url": "https://stackoverflow.com/questions/58727397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Nginx container exits with code 1 when upstream node is not available OVERVIEW Nginx runs in Docker container, also NodeJS application (worker) runs in another one, all managed by Docker Compose. Configuration has an upstream: container of worker 1 is also up and running, while node with worker 2 is not. upstream nodeapp { server appconfig_host-nodejs-app-worker_1:3000; server appconfig_host-nodejs-app-worker_2:3000; } It is then used in location block to proxy pass all requests. location /api/ { proxy_pass http://nodeapp/; } ACTUAL RESULT When worker 2 is in configuration (the container which is not running), I got error [emerg] 1#1: host not found in upstream "appconfig_host-nodejs-app-worker_2:3000" and container exits with code 1. When I remove line with second worker from upstream configuration, and keep just worker 1, then everything works just fine, proxy works as expected, serving my NodeJS app at /localhost/api/. EXPECTED RESULT I'd expect Nginx built-in balancing working so that it holds sending requests to worker 2, until it is alive again. I.e. service operates normally, not having worker 2 in the upstream, so all requests go to worker 1. Please advise what might be wrong here, as I could not find any way to fix that for few hours already. Thanks a lot in advance. A: Problem is that nginx tries to resolve any DNS names you define in the configuration at startup time (rather than request time) and it fails if it cannot resolve one of the names. Check this answer for possible solutions/workarounds: https://stackoverflow.com/a/32846603/1078969 A: "Nginx container exits with code 1". This error can also be caused by a syntax error in a .conf file, such as inserting a colon between name:value pairs when you shouldnt, due to confounding syntax rules with different config files. You stand a good chance of finding a complaint that points you to the line in question in the log files.
{ "language": "en", "url": "https://stackoverflow.com/questions/48490111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why .config directory is not listed when excluded from gitignore using wildcard (*) and git status? I know the question is a bit cryptic, I couldn't word it exactly in a single sentence (might need some help on that). I initialized git in my home directory (i.e, ~/, on Arch Linux) to backup my dot-files (mainly configs). I want to include every file and folder in it except the ones starting with a . (like .config/ and .bashrc). So I made a .gitignore file whose contents are: # Ignore everything * # Except these files and folders !.* But the problem is when I list all the untracked files (git status), it doesn't list the .config/ directory for some reason. I tried playing around with .gitignore and adding !*/ shows all directories including .config/ and also Documents, Downloads etc, which I don't want to include. And instead adding !.*/ shows every other directory that starts with a . like .cache/, .vim/ etc. But for some reason the .config/ doesn't show up. I even tried !.config/ and !.config it doesn't work. The only thing that works is !*/ (all directories, which is not what I want) Any way to solve this. Its really annoying. [Solved]: it was a bug The bug has been fixed in git version 2.34.1 Check the accepted answer. A: TL;DR After the bug fix, you'll want what you put in your "kinda solved" section, or something similar. I think you'll want what I put in my "bottom line" section, really: /* !/.* Long As jthill noted in a comment, there is a bug in the .gitignore wildcard handling in Git 2.34.0, which will be fixed in 2.34.1. In this case I think the bug is making your wildcarding work better than it would otherwise, though. The first lines: # Ignore everything * do just what they claim: ignore everything. All files and folders (directories) are ignored. Subsequent lines insert exceptions. But hang on a moment, what does ignored really mean? To get there, we must note what Git's index (or staging area) is and how Git makes new commits from the index / staging-area. The index, or staging area, in Git, is a central and crucial concept. Trying to use Git without understanding what the index is doing is a bit like trying to pilot an airplane without understanding what the wings and engine are for.1 So: the index is all about the next commit you plan to make. If you never make any new commits, you don't really need to know about it, but if you do want to make new commits, you need to know this.2 When you first extract some commit, in order to use and work on it, Git fills in its index from that commit, so that the index contains all the files from that commit. From this point onward, everything you are doing in your working tree, in the pursuit of making a new commit, is irrelevant to Git. That is, it's irrelevant up until you tell Git that you'd like Git to copy updated and/or new files into Git's index. The git add command is about updating Git's index. The files you name to git add, with git add file1 file2 for instance, are to be copied into Git's index. If there's already a copy of those two files, those copies get booted out of the index, replaced with the updated ones. If not, those files are newly added to the index. Once a file is in the index, you can replace it at any time: any .gitignore entry is irrelevant at this point. You can also remove it from the index, with git rm, or by using git add after removing the working tree copy: either one will remove the index copy. Now it's no longer in the index and the .gitignore entries are back in play. You can use an en-masse git add, as in git add . or git add *,3 to have Git scan directories and files and add them for you. When you do this, Git will skip certain directories and/or files if it can, and this is an area where .gitignore really comes into play. 1"Why should I care about those? I only care about getting my passengers and cargo from point A to point B, and those are inside the plane, not out on the wings." 2To extend the plane analogy a bit more: if you're just planning to use the fuselage as a house, then indeed, you don't need to care about the engines and wings. 3Note that in Unix-like shells, git add * is quite different from git add . because the shell will expand * for Git: Git never sees the literal asterisk. When the shell expands *, it does so with dot-files excluded, by default at least (bash in particular has a control knob to change this behavior). In some CLIs, the literal asterisk * gets through to Git, and then Git will expand *, and now it can act like git add . if Git wants it to. But it's easier to type in git add . (no SHIFT key required) so that's what I always do anyway, which removes the difference in the first place. How Git scans the working tree If you run git add . or equivalent (see footnote 3 again), Git will: * *Open the directory .. *Open and read any .gitignore file at this level, adding (appending) these rules to the ignore rules. (These rules then get dropped when we finish this directory.) *Read this directory: it contains the names of files and sub-directories ("folders", if you prefer that term). *Check each file and folder name as we read them, against all the ignore rules that are in effect right now. Note that some rules apply only to directories / folders, and others apply to both folders and files. The folder-only rules are those that end with a slash. Also, some rules are "positive" (do ignore) and some are "negative" (do not ignore). The negative rules are the ones starting with !. Git finds the last applicable rule, whatever that is, in the current set of rules, and then obeys that rule. So first, let's define which rules apply to which directory-scan results, and then what the various rules do. A rule in a .gitignore can be: * *a simple text string with no slashes, such as generated.file; *a text string with a trailing slash, but no other slashes: somedir/; *a text string with a leading or embedded slash, with or without a trailing slash: /foo, a/b, /foo/, a/b/, and so on; or *any of the above with various glob-style wildcard characters. These can all be negated: if a rule starts with ! it's negated, and we strip off the ! and then use the remaining tests. The two keys tests are these: * *Does the entry end with a literal /? If so, it applies only to directories / folders. Ignore that slash while answering the remaining question. *Does the entry begin with or contain a slash / character? (The one at the end does not count here.) If so, this entry is anchored or rooted (I like the term anchored myself, but I've seen both terms used). An anchored entry matches only a file or folder name found at this level. That is, /foo or foo/bar won't match sub/foo or sub/foo/bar, only ./foo and ./foo/bar, where . is the directory (folder) that Git is scanning right now. This means that if the entry has several levels—foo/bar or one/two/three for instance—Git will have to remember to apply this entry when it gets around to scanning bar in foo, or two in one and three in one/two. So we do have to consider "higher level" rules. But since lower level rules get appended, a lower level .gitignore can cancel out the higher level one if it wants to. An un-anchored entry applies here and—unless overridden—in every sub-directory as well. That is, if we do have ./one/two/three, Git will presumably open and read one to find two, and then open and read two to find three, all while still working on the current directory. Meanwhile any un-anchored entry from this .gitignore will apply within the one and one/two directories, and within one/two/three if that's a directory, and so on. So, there's already a lot to think about. Now we throw in glob matches. The usual glob is *: people write foo*bar or *.pyc or whatever. Git allows ** as well, with meaning similar to that in bash: zero or more directories. (I've found ** in Git to be weird and in my opinion slightly buggy, where it sometimes seems to mean "one or more" instead of "zero or more", so I recommend avoiding ** if possible. It's hard to reason about, so it's generally not a great idea in the first place, and Git's ignore rules mostly eliminate any need for **. So if you are going to use it, test it carefully and be prepared to have it shift on you in some future Git, in case the one-or-more ?bug? gets fixed, or affects your use case, or whatever.) Let's suppose, then, that we have these two entries: * !.* Git opens and reads . and finds the following names: dir file .dir .file where dir and .dir are directories (folders) and file and .file are non-directories (files). The * rule matches all four names. The !.* rule matches the last two names. The !.* rule is later in the .gitignore file, so it overrides the * rule. Git therefore "sees" .dir and .file. Since .file is a file, this means that git add . "sees" it. It will check whether .file needs to be git add-ed to displace the existing .file file, or added to the index. Since dir and file are excluded, this scanning pass doesn't see them, and does not try to git add either one. Since dir itself is a directory (not a file), it's never in the index itself. There may be a file in the index named dir/thing, and Git will check to see if that should be updated by this git add ., but Git won't scan dir to see if there are other files in dir. Since file is an excluded file, the scanning pass does not see it. But if file already exists in the index, Git will check to see if it should be updated by this git add ., even though it didn't get scanned here. In other words, these "existing files already in the index" checks happen outside (either before or after) the "scan the directories" pass. Meanwhile, since .dir isn't excluded, Git now opens and reads .dir, recursively: * *Git checks for a .dir/.gitignore (the .gitignore that applies to entries found in .dir). If that exists, Git appends those rules. *Git scans .dir recursively, using all the same methods. Then it's done scanning .dir so Git removes the appended rules. Let's look now at the rules Git has in effect as it scans .dir. The appended-to rules If there is a .dir/.gitignore, Git opens and reads it and appends to the existing rules. If not, we still have the same set of rules in effect: * (positive wildcard: ignore every name) !.* (negative wildcard: don't ignore dot-names) What's in .dir? Let's say we have: file1 dir1 .file2 .dir2 The name file1 matches * so it gets ignored. Git won't git add it to the index if it's not already there. Similarly, dir1 matches *, so it gets ignored. Git won't even scan it to see if there are any files there. The name .file2 matches *, but also matches .*, so the override negative entry is the rule that applies: Git will git add .dir/.file2. The name .dir2 has the same features, so the override applies and Git will open and read .dir/.dir2. This goes through the same recursion as before: Git looks for .dir/.dir2/.gitignore to append rules, and will use the appended-to rules while scanning .dir/.dir2, and then drop back to our own .dir/.gitignore-appended rule set while continuing to scan .dir, and then return from this recursion level and drop the .dir/.gitignore rules. The bottom line In the end, the trick here is that we want the * rule to apply only at the top level. Once we get into, say, .foo/, we don't want to ignore .foo/main_config and .foo/secondary_config. So we want * to apply only at the top level. Using: # Ignore everything * # Except these files and folders !.* !.*/* gets us closer: we ignore everything, but then—via the negative rules !.* and !.*/*—we carefully don't ignore .foo and the like. Once we get into .foo, we carefully don't ignore .foo/main_config. The bug, or possible bug, depending on what you really do want, here is ... well, suppose we have .foo/thing1/config and .foo/thing2/config. The .*/* pattern contains an embedded slash, which means it is anchored. It matches .foo/thing1, so that directory gets scanned. But it doesn't match .foo/thing1/config. We could try something like: !.*/* !.*/**/ I particularly hate this one because ** is so tough to reason about. We could also write: !.*/* !.*/*/ !.*/**/ in case the ** "one or more" bug bites us (I don't think it will, but it's a consideration). But it's simplest to anchor the original globs, by writing: /* !/.* This makes the top level .gitignore rules apply only to top-level work-tree entries. Sub-level .gitignore files, if they exist, can establish sub-level rules and do not need to override any top-level rules, because the top-level rules already don't apply at any sub-level, thanks to anchoring.
{ "language": "en", "url": "https://stackoverflow.com/questions/70098335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: "window" is undefined during server side rendering with nashorn and webpack4 I'm tring to create isomorphic application using SpringMVC, Nashorn, webpack4 and VueJS. I faced with a problem during evaluation of javascript (webpack4 bundle) by Nashorn engine. It's throws ScriptExceptions like: * *"window" is undefined *"cannot read property 'userAgent' from undefined' of window.navigator if i set window in nashorn-polyfill.js. I tried a lot of variants, but didn't find solution or workaround to make webpack bundle stop thinking that it runs in browser. If somebody knows how to fix it, it will be great. My webpack.config.js: const path = require("path"); const HtmlWebpackPlugin = require("html-webpack-plugin"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const WebpackMd5Hash = require("webpack-md5-hash"); const CleanWebpackPlugin = require("clean-webpack-plugin"); const VueLoaderPlugin = require('vue-loader/lib/plugin'); const ROOT = path.join(__dirname, "src/main/resources/"); const SRC = path.join(ROOT, "index.js"); const TARGET = path.join(__dirname, "src/main/webapp", "dist"); module.exports = { devtool: "source-map", entry: SRC, output: { path: TARGET, filename: "bundle.js", //.[chunkhash] publicPath: "/", library: "Isomorphic", libraryTarget: 'umd', umdNamedDefine: true, globalObject: 'this' }, resolve: { alias: { "vue$": "vue/dist/vue.esm.js" } }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader" }, }, { test: /\.scss$/, use: ["style-loader", MiniCssExtractPlugin.loader, "css-loader", "postcss-loader", "sass-loader"] }, { test: /\.vue$/, loader: 'vue-loader', }, ] }, plugins: [ new CleanWebpackPlugin(TARGET, {}), new MiniCssExtractPlugin({ filename: "assets/css/style.[contenthash].css" }), new HtmlWebpackPlugin({ title: "Welcome to Isomorphic world!", inject: false, hash: true, template: ROOT + "/assets/templates/index.html", filename: "templates/index.html" }), new WebpackMd5Hash(), new VueLoaderPlugin() ], devServer: { port: 5000, open: false, overlay: true, watchOptions: { aggregateTimeout: 300 } } }; I found soulution for Node: to set output.globalObject: 'this' and tried to downgrade webpack version to 3.12.0, but it hasn't helped me. Server side rendering in Vue.java: package components; import jdk.nashorn.api.scripting.NashornScriptEngine; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.stereotype.Component; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import java.io.IOException; @Component public class Vue { @Value(value = "classpath:static/nashorn-polyfill.js") private Resource nashornPolyfillFile; @Value(value = "/dist/bundle.js") private Resource bundleJsFile; public String renderEntryPoint() throws ScriptException, IOException { NashornScriptEngine nashornScriptEngine = getNashornScriptEngine(); try { Object html = nashornScriptEngine.invokeFunction("renderServer"); return String.valueOf(html); } catch (Exception e) { throw new IllegalStateException("Error! Failed to render vue component!", e); } } private NashornScriptEngine getNashornScriptEngine() throws ScriptException, IOException { NashornScriptEngine nashornScriptEngine = (NashornScriptEngine) new ScriptEngineManager() .getEngineByName("nashorn"); evaluateScripts(nashornScriptEngine, nashornPolyfillFile, bundleJsFile); return nashornScriptEngine; } private void evaluateScripts(NashornScriptEngine nashornScriptEngine, Resource... resources) throws ScriptException, IOException { for (Resource resource : resources) { nashornScriptEngine.eval("load('" + resource.getURI() + "')"); } } } nashorn-polyfill.js: var global = this; // var window = this; //leads to another error "cannot read property 'userAgent' from undefined' of window.navigator. var console = {}; console.debug = print; console.warn = print; console.log = print; console.error = print; GitHub - if it's more comfortable for someone.
{ "language": "en", "url": "https://stackoverflow.com/questions/51640886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using generic List and ArrayList I'm trying to fill a list with all controls ID contained in an aspx page. If I use ArrayList for that purpose, that list is generated OK. Example function: AddControls1. But if I use generic List, I got a NullReferenceException error. Example function: AddControls2. What I'm doing wrong when creating generic List? Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load ''success ! Dim controlList1 As New ArrayList() controlList1 = AddControls1(Page.Controls, controlList1) For Each str As String In controlList1 Response.Write(str & "<br/>") Next ''FAIL Dim controlList2 As New List(Of String) controlList2 = Nothing controlList2 = AddControls2(Page.Controls, controlList2) For Each ctl As String In controlList2 Response.Write(ctl & "<br/>") Next End Sub Private Function AddControls1(ByVal page As ControlCollection, ByVal controlList As ArrayList) As ArrayList For Each c As Control In page If c.ID IsNot Nothing Then controlList.Add(c.ID) End If If c.HasControls() Then AddControls1(c.Controls, controlList) End If Next Return controlList End Function Private Function AddControls2(ByVal page As ControlCollection, ByVal controlList As List(Of String)) As List(Of String) For Each c As Control In page If c.ID IsNot Nothing Then controlList.Add(c.ID) <-- here I got NullReferenceException error End If If c.HasControls() Then AddControls2(c.Controls, controlList) End If Next Return controlList End Function A: controlList2 = Nothing There's your failure. You're specifically setting the list to null, then trying to use it. A: You are setting it to Nothing which is null controlList2 = Nothing
{ "language": "en", "url": "https://stackoverflow.com/questions/17497225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UnauthorizedAccessException when creating a registry key I'm researching on how to add a shortcut in the windows context menu to my application. I came across this article and I tried it out. This is the code it uses to create a key in the registry. private void btnAddMenu_Click(object sender, System.EventArgs e) { RegistryKey regmenu = null; RegistryKey regcmd = null; try { regmenu = Registry.ClassesRoot.CreateSubKey(MenuName); if(regmenu != null) regmenu.SetValue("",this.txtName.Text); regcmd = Registry.ClassesRoot.CreateSubKey(Command); if(regcmd != null) regcmd.SetValue("",this.txtPath.Text); } catch(Exception ex) { MessageBox.Show(this,ex.ToString()); } finally { if(regmenu != null) regmenu.Close(); if(regcmd != null) regcmd.Close(); } } The problem is if I run it through my Administrator account, it works fine. But when I do it through a different account which doesn't have admin privileges, it throws this exception. system.unauthorizedaccessexception access to the registry key is denied Now if I were to use this code in one of my own applications to create a shortcut in the context menu, I can't be sure every user would run it as the Administrator, right? Is there any way in C# to escalate the user privileges when creating the registry key? If you know any other way to add an item to the windows context menu, I'd be interested in them too. Thank you. A: You could escalate your permissions much the same way installers do it. It will require user interaction, as that's the way the OS is designed (and rightly so) - you can't go around it. A: You cannot escalate permissions as such (at least I'd like to know about it, but doesn't seem possible as yet), but you need to run / start your app (embed into manifest) elevated. Please take a look at these entries... How do I force my .NET application to run as administrator? Elevating process privilege programatically? I'd suggest what comments said, running that from the setup. Or let your app run as admin from the start, or possibly jump start an elevated process from your app - when needed (e.g. running another exe of yours that has its manifest properly).
{ "language": "en", "url": "https://stackoverflow.com/questions/10042095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: how can i delete whole day rows on condition column values.. pandas i have below times series data frames i wanna delete rows on condtion (check everyday) : check aaa>100 then delete all day rows (in belows, delete all 2015-12-01 rows because aaa column last 3 have 1000 value) .... date time aaa 2015-12-01,00:00:00,0 2015-12-01,00:15:00,0 2015-12-01,00:30:00,0 2015-12-01,00:45:00,0 2015-12-01,01:00:00,0 2015-12-01,01:15:00,0 2015-12-01,01:30:00,0 2015-12-01,01:45:00,0 2015-12-01,02:00:00,0 2015-12-01,02:15:00,0 2015-12-01,02:30:00,0 2015-12-01,02:45:00,0 2015-12-01,03:00:00,0 2015-12-01,03:15:00,0 2015-12-01,03:30:00,0 2015-12-01,03:45:00,0 2015-12-01,04:00:00,0 2015-12-01,04:15:00,0 2015-12-01,04:30:00,0 2015-12-01,04:45:00,0 2015-12-01,05:00:00,0 2015-12-01,05:15:00,0 2015-12-01,05:30:00,0 2015-12-01,05:45:00,0 2015-12-01,06:00:00,0 2015-12-01,06:15:00,0 2015-12-01,06:30:00,1000 2015-12-01,06:45:00,1000 2015-12-01,07:00:00,1000 .... how can i do it ? A: I think you need if MultiIndex first compare values of aaa by condition and then filter all values in first level by boolean indexing, last filter again by isin with inverted condition by ~: print (df) aaa date time 2015-12-01 00:00:00 0 00:15:00 0 00:30:00 0 00:45:00 0 2015-12-02 05:00:00 0 05:15:00 200 05:30:00 0 05:45:00 0 2015-12-03 06:00:00 0 06:15:00 0 06:30:00 1000 06:45:00 1000 07:00:00 1000 lvl0 = df.index.get_level_values(0) idx = lvl0[df['aaa'].gt(100)].unique() print (idx) Index(['2015-12-02', '2015-12-03'], dtype='object', name='date') df = df[~lvl0.isin(idx)] print (df) aaa date time 2015-12-01 00:00:00 0 00:15:00 0 00:30:00 0 00:45:00 0 And if first column is not index only compare column date: print (df) date time aaa 0 2015-12-01 00:00:00 0 1 2015-12-01 00:15:00 0 2 2015-12-01 00:30:00 0 3 2015-12-01 00:45:00 0 4 2015-12-02 05:00:00 0 5 2015-12-02 05:15:00 200 6 2015-12-02 05:30:00 0 7 2015-12-02 05:45:00 0 8 2015-12-03 06:00:00 0 9 2015-12-03 06:15:00 0 10 2015-12-03 06:30:00 1000 11 2015-12-03 06:45:00 1000 12 2015-12-03 07:00:00 1000 idx = df.loc[df['aaa'].gt(100), 'date'].unique() print (idx) ['2015-12-02' '2015-12-03'] df = df[~df['date'].isin(idx)] print (df) date time aaa 0 2015-12-01 00:00:00 0 1 2015-12-01 00:15:00 0 2 2015-12-01 00:30:00 0 3 2015-12-01 00:45:00 0
{ "language": "en", "url": "https://stackoverflow.com/questions/48556510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Selenium screenshot_as_png not working using chrome on Ubuntu 18 I'm trying to screenshot a specific web_element using screenshot_as_png method but an error is being raised. Everything works fine when I run this program on my Windows 10, but it fails on my AWS EC2 Ubuntu 18.04 main.py from selenium import webdriver options = webdriver.ChromeOptions() options.add_argument('--disable-notifications') options.add_argument("headless") options.add_argument("start-maximized") options.add_argument("disable-infobars") options.add_argument("--disable-extensions") options.add_argument("--disable-gpu") options.add_argument("--disable-dev-shm-usage") options.add_argument("--no-sandbox") chrome = webdriver.Chrome(options=options) chrome.get('http://stackoverflow.com/') element = chrome.find_element_by_css_selector('.-main.grid--cell') element.screenshot() #Error! chrome.quit() The error is the following: selenium.common.exceptions.WebDriverException: Message: unknown command: session/5c9bda106805d0d80a3f5c7b63dbf410/element/0.35398631812343306-1/screenshot The setup I'm using: (Session info: headless chrome=80.0.3987.87) (Driver info: chromedriver=2.41.578700 (2f1ed5f9343c13f73144538f15c00b370eda6706),platform=Linux 4.15.0-1060-aws x86_64) A: It seems that screenshot_as_png is not a valid command, Try following this way: https://pythonspot.com/selenium-take-screenshot/ Regards! A: There is no method to the element object. It is holding the reference of the element returned by the method driver.find_element_by_css_selector('.-main.grid--cell'). Hence the error. There is method in the WebDriver class called save_screenshot("filename.extension") from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() options.binary_location = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe" driver = webdriver.Chrome(options=options, executable_path="C:/Users/Downloads/chromedriver.exe", ) driver.get('http://stackoverflow.com/') element = driver.find_element_by_css_selector('.-main.grid--cell') #element.screenshot_as_png() # there is no method on the element object hence the error driver.save_screenshot("screenshot.png") # this is the method to get the screenshot driver.quit()
{ "language": "en", "url": "https://stackoverflow.com/questions/60491358", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NoMethodError in UsersController#edit with undefined method `signed_in?' class UsersController < ApplicationController before_filter :signed_in_user, only: [:index, :edit, :update] before_filter :correct_user, only: [:edit, :update] private def user_params params.require(:user).permit(:name, :email, :password,:password_confirmation) end def signed_in_user unless signed_in? store_location redirect_to signin_url, notice: "Please sign in." end end def correct_user @user = User.find(params[:id]) redirect_to(root_url) unless current_user?(@user) end end code in session helper: def sign_in(user) remember_token = User.new_remember_token cookies.permanent[:remember_token] = remember_token user.update_attribute(:remember_token, User.encrypt(remember_token)) self.current_user = user end def signed_in? !current_user.nil? end I am using this code, But I am unable to edit and update my details in the database. As I am extremely new to this, Need someone help. Thanks in Advance.... A: Have you included the SessionHelper module in your controller? From your example code, I'm assuming you're using the RailsTutorial by Michael Hartl. You have to include the SessionsHelper in your ApplicationController to be able to use it in all controllers. Check out Listing 8.14 in the book: class ApplicationController < ActionController::Base protect_from_forgery include SessionsHelper # Force signout to prevent CSRF attacks def handle_unverified_request sign_out super end end
{ "language": "en", "url": "https://stackoverflow.com/questions/20562970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multiple subplots to personalize I make some subplots by using: fig, ax = plt.subplots(nrows=2, ncols=3, sharex=True, sharey=True) Then, I would like to personalize the subplots, e.g., with: plt.subplots_adjust(hspace = 0., wspace= 0.) However, I would like to personalize the ticks as well, like removing the ticks and the labels for some of those subplots. How could I do that? The problem is that, after the definition, ax is a numpy array: I don't know that much of it, what I know is that it is impossible to use attributes (like, ax[0].set_yticks([])). A: If you create a 2D array of plots, e.g. with: >>> fig, axarray = plt.subplots(3, 4) then axarray is a 2D array of objects, with each element containing a matplotlib.axes.AxesSubplot: >>> axarray.shape (3, 4) The problem is that when you index axarray[0], you're actually indexing a whole row of that array, containing several axes: >>> axarray[0].shape (4,) >>> type(axarray[0]) numpy.ndarray However, if you address a single element in the array then you can set its attributes in the normal way: >>> type(axarray[0,0]) matplotlib.axes.AxesSubplot >>> axarray[0,0].set_title('Top left') A quick way of setting the attributes of all of the axes in the array is to loop over a flat iterator on the axis array: for ii,ax in enumerate(axarray.flat): ax.set_title('Axis %i' %ii) Another thing you can do is 'unpack' the axes in the array into a nested tuple of individual axis objects, although this gets a bit awkward when you're dealing with large numbers of rows/columns: fig, ((ax1, ax2, ax3, ax4), (ax5, ax6, ax7, ax8), (ax9, ax10, ax11, ax12)) \ = plt.subplots(3,4) A: When using this method: fig, ax = plt.subplots(nrows=2, ncols=3, sharex=True, sharey=True) you have two choices, either call the elements of the array ax like you have suggested (but you will need to use two indices or flatten it): ax[0][0].plot(... ax.flat[0].plot(... this second line is useful if you loop over the plots. Or you can modify in the following way: fig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(nrows=2, ncols=3, sharex=True, sharey=True) It will depend on your use case which is better, I typically call the array ax if there is a chance I will change the number of subplot.
{ "language": "en", "url": "https://stackoverflow.com/questions/19315087", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rapid fire with logitech lua script? When writing lua scripts for my logitech g502, I've gotten rapid fire to work, but it will continue to execute mouse presses after the mouse one button is released as long as the ctrl key is held. I am wondering if there is any kind of iteration that would allow me to signal a function that presses and releases the mouse but under the conditional that the same mouse button is pressed.(For example, ctrl must be held and rapid fire only executes when mouse button 1 is held down, as opposed to until ctrl is released). Here is the code I am referring to EnablePrimaryMouseButtonEvents(true); function OnEvent(event, arg) if IsModifierPressed("lctrl") then repeat if IsMouseButtonPressed(1) then repeat PressMouseButton(1) Sleep(15) ReleaseMouseButton(1) until not IsMouseButtonPressed(1) end until not IsModifierPressed("lctrl") end end I am wondering if there is any kind of iteration that would allow me to signal a function that presses and releases the mouse but under the conditional that the same mouse button is pressed.(For example, ctrl must be held and rapid fire only executes when mouse button 1 is held down, as opposed to until ctrl is released). Alternatives I have considered: binding fire to another key that isn't mouse button 1, and having it repeated when mouse button one is pressed. Thanks in advance A: The actual problem is you're trying to simultaneously read real status and simulate press/release the same mouse button. The only way to resolve this problem is (as you have suggested) to bind fire to additional key. For example, in the game config you assign both left mouse button and keyboard key combination CtrlP to "Fire". Please note that P without a modifier must be NOT assigned to any action in the game. And your script would be the following: EnablePrimaryMouseButtonEvents(true) function OnEvent(event, arg) if event == "MOUSE_BUTTON_PRESSED" and arg == 1 and IsModifierPressed("lctrl") then repeat Sleep(15) PressKey("P") Sleep(15) ReleaseKey("P") until not IsMouseButtonPressed(1) or not IsModifierPressed("lctrl") end end
{ "language": "en", "url": "https://stackoverflow.com/questions/58121181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Finishing Activity from another activity Say I have 3 activities A, B and C. A leads to B which leads to C. I would like to be able to move back and forth between A and B but I want to finish both A and B once C gets started. I understand how to close B when starting C via the intent but how do I also close A when C gets started? A: Use this flag when you are opening the C acitivity. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); This will clear all the activities on top of C. A: Since A is your root (starting) activity, consider using A as a dispatcher. When you want to launch C and finish all other activities before (under) it, do this: // Launch ActivityA (our dispatcher) Intent intent = new Intent(this, ActivityA.class); // Setting CLEAR_TOP ensures that all other activities on top of ActivityA will be finished intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // Add an extra telling ActivityA that it should launch ActivityC intent.putExtra("startActivityC", true); startActivity(intent); in ActivityA.onCreate() do this: super.onCreate(); Intent intent = getIntent(); if (intent.hasExtra("startActivityC")) { // Need to start ActivityC from here startActivity(new Intent(this, ActivityC.class)); // Finish this activity so C is the only one in the task finish(); // Return so no further code gets executed in onCreate() return; } The idea here is that you launch ActivityA (your dispatcher) using FLAG_ACTIVITY_CLEAR_TOP so that it is the only activity in the task and you tell it what activity you want it to launch. It will then launch that activity and finish itself. This will leave you with only ActivityC in the stack.
{ "language": "en", "url": "https://stackoverflow.com/questions/15556138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Insert after parent of element What sort of selector would be I need in order to insert after the parent (divouter) of the test3 class in the example below? Thanks. <div class='divouter'> <div class='divinner'> <input class=test1></input> </div> </div> <div class='divouter'> <div class='divinner'> <input class=test2></input> </div> </div> <div class='divouter'> <div class='divinner'> <input class=test3></input> </div> </div> <div class='divouter'> <div class='divinner'> <input class=test4></input> </div> </div> A: You could use the $.after() method: $(".test3").closest(".divouter").after("<div>Foo</div>"); Or the $.insertAfter() method: $("<div>Foo</div>").insertAfter( $(".test3").closest(".divouter") ); A: .divouter:parent A: I think you want the "after()" method: $('input.test3').focus(function() { $(this).closest('div.divouter').after('<div>Hi!</div>'); });
{ "language": "en", "url": "https://stackoverflow.com/questions/2262659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Failed to reset MySQL password Recently I tried to reset mySQL password using command prompt using this instruction https://dev.mysql.com/doc/mysql-windows-excerpt/5.7/en/resetting-permissions-windows.html . I did exactly as in the instruction but my it didn't turn out as how it is supposed to be. It just stopped there after I pressed enter, nothing happened, no errors or warnings or whatsoever. I even tried restarting the server with the new password. here's the result of the command. like i said, no errors or warnings after i pressed enter. and here's the error when i try to restart the server with the new password i expected this output here (i got this from a youtube video; the guy did exactly the same thing) A: Tryout these steps: * *Stop your MySQL server completely. This can be done from Wamp(if you use it), or start “services.msc” using Run window, and stop the service there. *Open your MS-DOS command prompt using “cmd” inside the Run window. Then go to your MySQL bin folder, such as C:\MySQL\bin. Path is different if you use Wamp. *Execute the following command in the command prompt: mysqld.exe -u root --skip-grant-tables *Leave the current MS-DOS command prompt as it is, and open a new MS-DOS command prompt window. *Go to your MySQL bin folder again. *Enter “mysql” and press enter. *You should now have the MySQL command prompt working. Type “use mysql;” so that we switch to the “mysql” database. *Execute the following command to update the password: UPDATE user SET Password = PASSWORD('your_new_passowrd') WHERE User = 'root'; However, you can now run almost any SQL command that you wish. After you are finished close the first command prompt, and type “exit;” in the second command prompt. You can now start the MySQL service. That’s it.
{ "language": "en", "url": "https://stackoverflow.com/questions/58051492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django restframework unique error not processed When I did not fill in the necessary fields, Django would return a message to the client, but when the field was unique, an error message would appear. Why didn't Django handle it? models.py class UserModel(models.Model): email = models.EmailField(unique=True) username = models.CharField(max_length=16, blank=True, null=True) password = models.CharField(max_length=512) is_active = models.BooleanField(default=False) sign_up_date = models.DateTimeField(auto_now_add=True) sign_in_date = models.DateTimeField(null=True, blank=True) serializers.py class UserSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) email = serializers.EmailField() username = serializers.CharField(max_length=16) password = serializers.CharField(max_length=512) is_active = serializers.BooleanField(read_only=True, default=False) sign_up_date = serializers.DateTimeField(read_only=True) sign_in_date = serializers.DateTimeField(read_only=True) class Meta: model = UserModel fields = ( 'id', 'email', 'username', 'password', 'is_active', 'sign_up_date', 'sign_in_date',) views.py class SignupView(CreateAPIView): serializer_class = UserSerializer queryset = UserModel.objects.all() error IntegrityError at /api/signup/ duplicate key value violates unique constraint "User_email_key" DETAIL: Key (email)=([email protected]) already exists. I hope Django can return error messages to the client. {"email": ["already exists"]} A: In the UserSerializer you are declaring some of the model fields again such as email etc. By doing that the behavior of the field is not copied from how it was defined on the model. It works as if that behavior has been overridden. You can drop email = serializers.EmailField() and then the default behaviour would kick in and you will get to see the error message corresponding to unique field. In the same fashion you could drop other fields too which are just replicas of the fields on the model.
{ "language": "en", "url": "https://stackoverflow.com/questions/68554183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Create an Array from Keys in JSON Data I need to create an array from a list of Keys in JSON data. The current data looks like this: { "Investment": [ { "name": "Average", "value": "170.0" } ], "Recordkeeping Administration": [ { "name": "Average", "value": "88.0" } ], "Total Bundled": [ { "name": "Average", "value": "268.0" } ], "Trustee": [ { "name": "Average", "value": "10.0" } ], "chart_type": [ { "name": "column", "value": "column" } ] } I need an array that looks like this: ["Investment", "Recordkeeping Administration", "Total Bundled", "Trustee"] A: Thanks to Joshua K. Object.keys(o) worked perfectly.
{ "language": "en", "url": "https://stackoverflow.com/questions/31993460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Oracle SQL Results duplicating with join I am trying to use the following code : SELECT a.part_no, sum(a.BUY_QTY_DUE) AS Tot_Ord, sum(b.REVISED_QTY_DUE) AS S_O_Tot FROM CUSTOMER_ORDER_JOIN a LEFT OUTER JOIN SHOP_ORD b ON a.part_no= b.part_no AND b.contract = '20' AND b.state = 'Planned' WHERE a.PART_NO = '10002261' AND a.OBJSTATE = 'Released' AND a.CONTRACT = '10' GROUP BY a.part_no However I am seeing duplicated results, I know this is to do with the join but not sure how to fix :( Results The results I expect to see are, Tot_Ord = 277 (6 instances of 23, 3 instances of 46, 1 instance of 1) 10 lines in total S_O_Tot = 46 (2 instances of 23) 2 lines in Total Any help would be greatly appreciated, Thanks, Jamie A: SELECT a.part_no, sum(a.BUY_QTY_DUE) AS Tot_Ord, sum(nvl(b.REVISED_QTY_DUE,0)) AS S_O_Tot FROM CUSTOMER_ORDER_JOIN a LEFT OUTER JOIN SHOP_ORD b ON (a.part_no= b.part_no AND b.contract = '20' AND b.state = 'Planned') WHERE a.PART_NO = '10002261' AND a.OBJSTATE = 'Released' AND a.CONTRACT = '10' I have deleted grouping because you are filtering on this filed anyway
{ "language": "en", "url": "https://stackoverflow.com/questions/53411348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Replace text grabbed from Wikipedia I grab some text from wikipedia and there's a tricky part. In some articles there is this(ignore bad formatting): (pron.: /ˌhjuˠˈlɒri/) I need this gone; however there might be useful data in this way: (pron.: /ˈliːsə ˈɛdəlstiːn/; born May 21, 1966) I have noticed that it ends with "/" or "/;" and it starts with pron.: I have tried and tried, but miserably failed. Is there any regex master to help me out there? (per request) the best I could get working is to replace the parentheses s = s.replace(/(.*?)/, ' '); A: Try this $str = "(pron.: /ˌhjuˠˈlɒri/)"; $a = preg_replace('#\/(.*?)\/#','',$str); var_dump($a); And after this if you want to remove the pron.:, use str_replace. Output string(9) "(pron.: )" Codepad
{ "language": "en", "url": "https://stackoverflow.com/questions/16535142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery AJAX see redirect as status 200 not 302? I am using jQuery and the jQuery.form plugin to submit my form (also using ASP.Net MVC). Problem is the user is in a section of the site that uses forms authentication and if their auth cookie expires during their time on the page instead of getting back a status of 302, which would be the redirect to the login page, I still get 200? In FireBug I see the 302 Found and then my login page is served next as a 200 which is the status code sent back to my Ajax call. How do I detect that they have been logged out if I never see the 302 sent back to the jQuery form plugin? A: I really like this solution. By changing the 302 response on ajax requests to a 401 it allows you to setup your ajax on the client side to monitor any ajax request looking for a 401 and if it finds one to redirect to the login page. Very simple and effective. Global.asax: protected void Application_EndRequest() { if (Context.Response.StatusCode == 302 && Context.Request.Headers["X-Requested-With"] == "XMLHttpRequest") { Context.Response.Clear(); Context.Response.StatusCode = 401; } } Client Side Code: $(function () { $.ajaxSetup({ statusCode: { 401: function () { location.href = '/Logon.aspx?ReturnUrl=' + location.pathname; } } }); }); A: try with cache: false cache option in jquery ajax: $.ajax({ url: "test.html", cache: false, success: function(html){ $("#results").append(html); } }); ---EDIT Try with this in C# code : protected void Page_Load(object sender, System.EventArgs e) { Response.Cache.SetCacheability(HttpCacheability.NoCache); ... } A: A similar problem has been encountered before. Is the solution given in this question helpful? A: This is the solution I've used in the past: Server side: When I'm checking to see if a session is still valid, I also keep an eye out for the "X-Requested-With" header, which should be "XMLHttpRequest" if you're using jQuery (NOTE: IE tends to return the header name in lower case, so watch for that as well). If the session has indeed expired and the header is present, instead of using an HTTP redirect, I respond with a simple JSON object like this: { "SESSION": "EXPIRED" } Client side: In my onload code, I use jQuery's ajaxComplete event to check all incoming request payloads for the session expired object. The code looks something like this: $(window).ajaxComplete(function(ev, xmlhr, options){ try { var json = $.parseJSON(xmlhr.responseText); } catch(e) { console.log('Session OK'); return; } if ($.isPlainObject(json) && json.SESSION == 'EXPIRED') { console.log('Session Expired'); //inform the user and window.location them somewhere else return; } console.log('Session OK'); }); A: I'm pretty sure you will never get the 302 in the completed status of the XHR object. If a redirect occurs then the connection is still in process until you see the response from the login page (which should be 200, if it exists). However, why do you need to see the 302? Surely if you are getting a redirect to login.php then simply getting the url (or parsing for content) of the returned response tells you they have been logged out? An alternative, only if you want to know as soon as the session has expired (before they do some action), is to poll the server using setTimeout or similar to get information on the authentication status. Good luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/1268165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Function being called faster I hava made a flappy bird game and there are 2 frames. frame 1 is for playing while 2 is for death. I put a trace call on a function to see how many times is it called due to a problem. I found out that the more i die , the speedy my function call gets and the gravity is increased more times, so, my character flappy falls faster each time it dies.Please help. Here's the code: var calls = 0; flappy.addEventListener(Event.ENTER_FRAME, fl_gravity); function fl_gravity(event: Event): void { calls++; if (dead) { if (flappy.hitTestObject(ground)) { gravity = 0; } else { gravity += 0.5; } upPressed = false; } else { flappy.x += 2.5; } flappy.y += gravity; gravity += 0.5; trace(calls); } A: It probably happens because when you die and get back to frame 1 (where this code probably is) you add another enterframe listener so now your function is executed twice per frame (one time for each event listener). Make sure you add your event listener only once: var initialized:Boolean; if(!initialized) { initialized = true; flappy.addEventListener(Event.ENTER_FRAME, fl_gravity); } A: It looks like you're increasing the bird's gravity not only if it isn't dead but if it is. It lies outside of the conditional. Remove the line that increases your gravity outside of the conditional (line 16 in that excerpt)
{ "language": "en", "url": "https://stackoverflow.com/questions/44436084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I add a FooterView here? I have a custom adapter which formats for me, alphabet headers and then corresponding names underthem, but I want to put a unique footer at the bottom that will display the number of contacts, for example "Total number of contacts in list: 21" class LetterAdapter extends ArrayAdapter<String> { LetterAdapter() { super(ContactProjectActivity.this, R.layout.row, R.id.label, sortedNames); } public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; if (row == null) { LayoutInflater inflater=getLayoutInflater(); row = inflater.inflate(R.layout.row, parent, false); } TextView label = (TextView) row.findViewById(R.id.label); label.setText(sortedNames.get(position)); if (sortedNames.get(position).length() == 1) { //label.setText("The size is " + searchNames.size()); label.setTextSize(15); row.setBackgroundColor(Color.GRAY); } else { label.setTextSize(20); label.setTextColor(Color.BLACK); row.setBackgroundColor(Color.WHITE); } return(row); } } I am extending ListActivity so I don't have a ListView variable in my code. Any code snippets or suggestions would be helpful. I want to customize the footer also, with its own background color (similar to how I did the letter headers in the code). A: You could get the ListView from you ListActivity with the method getListView() and then try to set your footer view before you set the adapter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7937611", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP Copy file to my website from remote site $link = "http://vcdn8.yobt.tv/content/a8/68/e6/a868e6dc4688ecfc0c26de00ed08db7f871427/vid/1_1024x576.mp4"; copy($link, '../video/video12465123.mp4'); I'm trying to copy this video but always stop at between 1 mb - 2 mb , and it says 500 Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator to inform of the time the error occurred and of anything you might have done that may have caused the error. More information about this error may be available in the server error log. Error log: [Mon Feb 03 06:36:38 2014] [warn] [client 217.131.165.102] mod_fcgid: read data timeout in 45 seconds [Mon Feb 03 06:36:38 2014] [error] [client 217.131.165.102] Premature end of script headers: videoekle.php A: This is an apache timeout error. If you run your PHP script from the command line (instead of through apache), you shouldn't get this timeout error. If you need to run the script through apache, you can increase the FcgidIOTimeout setting in /etc/httpd/conf.d/fcgid.conf, and restart apache, and that should solve the problem. A: Try using curl, forcing timout set_time_limit(400);// to infinity for example $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://vcdn8.yobt.tv/content/a8/68/e6/a868e6dc4688ecfc0c26de00ed08db7f871427/vid/1_1024x576.mp4"); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0); curl_setopt($ch, CURLOPT_TIMEOUT, 400); //timeout in seconds $response = curl_exec($ch); curl_close($ch); Then save it to the file.
{ "language": "en", "url": "https://stackoverflow.com/questions/21515736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: File splitter in C++ I'm trying to make a file splitter/joiner in C++ and I have trouble with my split function. I used an MP4 file for a quick test and the result was: every other parts are OK but the last part always doesn't work. I don't understand this. Can anyone please explain it to me? Here is my split function: void split_F(const char* file_name, int number_of_part) { FILE *fp_read = fopen(file_name, "rb"); //calculate file size int file_size; fseek(fp_read, 0L, SEEK_END); file_size = ftell(fp_read); rewind(fp_read); //reset file pointer //calculate number of parts //int number_of_part = (int)ceil((double)file_size / size_of_part); long size_of_part; size_of_part = (int)floor((double)file_size / number_of_part); cout << "Total files after split: " << number_of_part << endl << "...Processing..." << endl; //main process char name[255] = ""; for (int count = 1; count <= number_of_part; count++) { sprintf(name, "%s.part_%03d", file_name, count); FILE *fp_write = fopen(name, "wb"); //create buffer char *buffer = new char[size_of_part]; memset(buffer, NULL, size_of_part); //reset buffer fread(buffer, size_of_part, 1, fp_read); fwrite(buffer, size_of_part, 1, fp_write); fseek(fp_read, count*size_of_part, SEEK_SET); cout << "> File: " << name << " done babe!" << endl; delete[] buffer; fclose(fp_write); } fclose(fp_read); } A: The last part will be potentially smaller or larger than size_of_part, as the original file size is not a multiple of it. You need to adapt the size of the last part automatically. For instance, if you have a file size of 1000 bytes, and 7 parts. Your computed file size will be 142. 7*142 = 994, you are missing the last 6 bytes. Is this your problem? The fseek is not required, why are you using it? You just need to read the input file sequentially void split_F(const char* file_name, int number_of_part) { FILE *fp_read = fopen(file_name, "rb"); //calculate file size int file_size; fseek(fp_read, 0L, SEEK_END); file_size = ftell(fp_read); rewind(fp_read); //reset file pointer //calculate number of parts long size_of_part; size_of_part = (int)ceil((double)file_size / number_of_part); cout << "Total files after split: " << number_of_part << endl << "...Processing..." << endl; //main process char name[255] = ""; int bytesRemaining = file_size; //create buffer, we reuse it for each part char *buffer = new char[size_of_part]; //No need to reset buffer //memset(buffer, NULL, partSize); for (int count = 1; count <= number_of_part; count++) { sprintf(name, "%s.part_%03d", file_name, count); FILE *fp_write = fopen(name, "wb"); int partSize; if(bytesRemaining > size_of_part) { partSize = size_of_part; } else { partSize = bytesRemaining; } fread(buffer, partSize, 1, fp_read); fwrite(buffer, partSize, 1, fp_write); cout << "> File: " << name << " done babe!" << endl; fclose(fp_write); } fclose(fp_read); delete[] buffer; } A: You are calculating size_of_part as a rounded quotient of file size and the requested number of parts. You then proceed to read the file in chunks of that exact size. This will fail unless the file size is a multiple of number_of_parts. You need to fix your code to allow the last part to be smaller than size_of_part. A: Your file may not divide into N parts of equal lengths (suppose the file is 7 bytes long and you divide it into 3 parts...?) long remaining_size = file_size; long size_of_part; size_of_part = (file_size + number_of_part - 1) / number_of_part; This makes the part length rounded up, so possibly the last part will be shorter than all preceding parts. //create buffer char *buffer = new char[size_of_part]; //main process char name[255] = ""; for (int count = 1; count <= number_of_part; count++) { sprintf(name, "%s.part_%03d", file_name, count); FILE *fp_write = fopen(name, "wb"); long this_part_size = remaining_size < size_of_part ? remaining_size : size_of_part; fread(buffer, this_part_size, 1, fp_read); fwrite(buffer, this_part_size, 1, fp_write); cout << "> File: " << name << " done babe!" << endl; fclose(fp_write); remaining_size -= this_part_size; } delete[] buffer;
{ "language": "en", "url": "https://stackoverflow.com/questions/29698626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AWS SSL Certificate Not Propagating Throughout The Site I have a SSL Cert from AWS, and the front page works. We have a CLB, that uses it. However, if I go any deeper than this, it will not be a secure connection. We have a splash page as the site is being developed (that has no access to the rest of the page), however we can access the rest of the page in the live environment, and chrome says: "Your connection to the site is not fully secure."(although still https). What gives? A: This is a common problem when setting up SSL for a web site. This issue is that your web pages are being requested using HTTPS but the page itself is requesting resources using HTTP. Start Google Chrome (or similar). Load your web site page. Press F-12 to open the debugger. Press F-5 to refresh the page. Note any lines that look like the following: Mixed Content: The page at 'https://mywebsite.com/' was loaded over HTTPS, but requested an insecure image 'http://mywebsite.com/images/homepage_top.png'. This content should also be served over HTTPS. You will then need to edit the HTML content (or page generator such as PHP) to correctly use HTTPS instead of HTTP.
{ "language": "en", "url": "https://stackoverflow.com/questions/47461163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to implement pagination for string array in collection view in swift 4 import UIKit class ProductListViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource { @IBOutlet weak var productListCell: UICollectionView! var manArray = ["Men","m1","m2","m3","m4","m5","m6","m7"] var mPrice = ["789","1259","959","1625","1259","936","980","1500"] override func viewDidLoad() { super.viewDidLoad() productListCell.delegate = self productListCell.dataSource = self } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return manArray.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ListCollectionViewCell", for: indexPath) as! ListCollectionViewCell cell.productImg.image = UIImage(named: manArray[indexPath.row]) cell.productlbl.text = "\(manArray[indexPath.row])" cell.productprice.text = "\(mPrice[indexPath.row])" return cell } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if indexPath.row == manArray.count - 1 { let tmpArray = ["Men","m1","m2","m3","m4","m5","m6","m7"] let tmpArray2 = ["789","1259","959","1625","1259","936","980","1500"] manArray.append(contentsOf: tmpArray) mPrice.append(contentsOf: tmpArray2) productListCell.reloadData() } } } Here is my Updated code A: Try this code func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if indexPath.row == manArray.count - 1 { let tmpArray = ["Men","m1","m2","m3","m4","m5","m6","m7"] let tmpArray2 = ["789","1259","959","1625","1259","936","980","1500"] manArray.append(contentsOf: tmpArray) mPrice.append(contentsOf: tmpArray2) yourCollectionView.reloadData() } }
{ "language": "en", "url": "https://stackoverflow.com/questions/50998733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error number 2202 when creating user group for sql server 2008 using C# VS 2008 in Vista I'm trying to create user group for registered in SQL Server 2008. This is my code : [DllImport("Netapi32.dll", CharSet=CharSet.Unicode)] internal static extern int NetLocalGroupAdd([In, MarsharAS(UnmanagedType.LPWStr)] string serverName,[In] int level, [In] reg NativeHeaders.LOCALGROUP_INFO_1 info0, out int paramError); internal struct LOCALGROUP_INFO_1 { public string lgrpi1_name; public string lgrpi1_comment; } $ always return error number 2202( User name not valid ) Public void CreateWinAuthGroup () { var localgroup_info_ = new LOCALGROUP_INFO_1 { lgrpi1_name = "TesUserGroup", lgrpi1_comment = "Group for My Application" } int error = NetLocalGroupAdd(serverName, 0, ref localgroup_info_, out paramerror); } Has anyone else faced this issue? This source running well on my standalone test application. But always returns error when integrated with main application. Thanks for any help. A: Found the error.it's because I doing testing using my custom string group user name. so it will be running well. but on real class, error is because username group format not valid. error 2202 is : error number description for Terminal Server . So the problem is closed.
{ "language": "en", "url": "https://stackoverflow.com/questions/12690950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: can't get my UIButton to show up as semi-transparent I'm adding a UIButton as a subView in a popup and I can't get it to show up semi-transparently. The background for the main view of the popup does show up semi-transparently, but this UIButton stays fully opaque. Can someone tell my why the code below is not working? Thanks. UIButton* checkButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; checkButton.frame = CGRectMake(187, 288, 30, 30); [checkButton setTitle:@"?" forState:UIControlStateNormal]; checkButton.opaque = NO; [checkButton setBackgroundColor:[UIColor colorWithWhite:1.0 alpha:0.3]]; [checkButton setTitleColor: [UIColor colorWithRed: 51 / 255.0 green:0 blue: 153 / 255.0 alpha:0.5] forState: UIControlStateNormal]; [checkButton addTarget:self action:@selector(check) forControlEvents:UIControlEventTouchUpInside]; [self addSubview:checkButton]; A: The background for a RoundedRect button is the rectangle in which it is located, and not the button itself. Try changing the background color to red or something equally visible and you will see that the background is only visible between the rounded corners of the button and the rectangular frame in which the button is set. Sadly, you cannot change the color of the button, which is what most people think they are doing when they change the backgroundColor property. To change the button color, you will need to use UIButtonTypeCustom. A: try setting your UIColor to myButton.layer.backgroundColor = [UIColor x..] you'll need a #import <QuartzCore/QuartzCore.h> im pretty sure the colour in the rounded rect button is in the layer, not in the regular background, this is why people struggle to change its colour.. alternately, put the alpha on the views colour back to 1 and hit the views alpha property, that'll certainly do the lot in one move. A: PengOne is right – setting the background color doesn't change the color of the rounded rect. It only affects the corners around the rect. But you can also just set the button's alpha property to something less than one. Try 0.7 to make the view semi-transparent. A: Try using UIButtonTypeCustom instead UIButtonTypeRoundedRect as the button type. A: UIButtonTypeRoundedRect is weird. Setting background /alpha etc on it only changes the background of the rectangle into which the button is rendered. You could change the button type to UIButtonTypeCustom and then use QuartzCore to set cornerRadius to make it appear rounded.
{ "language": "en", "url": "https://stackoverflow.com/questions/6631317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Array of extends T> in Java Is it possible to declare an array of something that extends some class? I can do: Map[] foo; T[] foo; //(in generic class) Map... foo; //(as argument declaration for "implicit" array) T... foo; //(as argument declaration in generic class for "implicit" array) But I need something like: <? extends Map>[] foo; <? extends T>[] foo; //(in generic class) <? extends Map>... foo; //(as argument declaration for "implicit" array) <? extends T>... foo; //(as argument declaration in generic class for "implicit" array) It could be used some List<? extends T> instead but it's not quite an array. For Example, if you want to use it in a like this: public class MyClass<T> { public void foo(int someOtherStuff, <? extends T>... optionalArray){ //some code } } Maybe "implicit" array isn't correct, please tell me how they're called correctly. A: Objects in Java are polymorphic: You can simply declare an array of a common base type and have objects of all kinds of derived classes in it. To go with Radiodef's example, this is valid code: Number[] foo = {new Integer(0), new Double(1), new Long(2), ...}; What Java does not have is a mechanism that defines an array restricted to one particular derived type of some known base class, where the particular derived type is only known at runtime. So, if you mean public void foo(int someOtherStuff, <? extends T>... optionalArray) to check whether the objects in optionalArray are all of the same derived type, then the answer is that this can not be done automatically. You can however use public void foo(int someOtherStuff, T... optionalArray) to get the guarantee that all objects in the array are derived of the same class T. They may be of different derived types, though. A: By the way.. I found the answer to the initial question, maybe somebody needs it one day: public class MyClass<T> { public <R extends T> void foo(int someOtherStuff, R... optionalArray){ //some code } } Found it by mistake by looking at the implementation of Arrays.asList(T[] a). In knew I've seen that syntax somewhere just didn't remember where. A: You're completely right Radiodef and Felix Thanks a lot for your detailed explaination! I just thought I have to declare it like that because something didn't work and I thought that was the problem. But something different was really the problem. Just want to mention it quickly: I have following generic class: public class MyClass<T> { public void foo1(List<Object> someList){ //wrong //some code } public void foo1(Object... someArray){ //some code } public void foo2(List<? extends T> someList){ foo1(someList); //some code } } I wanted that foo2 would invoke foo1(List<Object> someList) but instead it invoked foo1(Object... someArray) even though T will always extend Object (or not?) However, to make that work, foo1(List<Object> someList) needs to be declared like this: public void foo1(List<? extends Object> someList){ //correct //some code } then foo2 will invoke this rather than foo1(Object... someArray).
{ "language": "en", "url": "https://stackoverflow.com/questions/36117112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Progamming Principles and Practice using C++ by Bjarne Stroustrup , chapter 12 : A Display Model , First example I'm currently reading Progamming Principles and Practice using C++ by Bjarne Stroustrup . And I'm trying to code this example in the book. #include "Simple_window.h" #include "Graph.h" int main() { using namespace Graph_lib; Point tl(100,100); Simple_window win(tl,600,400,"Canvas"); Polygon poly; poly.add(Point(300,200)); poly.add(Point(350,100)); poly.add(Point(400,200)); poly.set_color(Color::red); win.attach (poly); win.wait_for_button(); } I debugged and it gave out these lines : Error LNK2001 unresolved external symbol "public: __cdecl Graph_lib::Window::Window(struct Graph_lib::Point,int,int,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (??0Window@Graph_lib@@QEAA@UPoint@1@HHAEBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) WindowsProject5 E:\Visual C++\WindowsProject5\WindowsProject5.obj 1 Error LNK2001 unresolved external symbol "public: void __cdecl Graph_lib::Window::attach(class Graph_lib::Widget &)" (?attach@Window@Graph_lib@@QEAAXAEAVWidget@2@@Z) WindowsProject5 E:\Visual C++\WindowsProject5\WindowsProject5.obj 1 Error LNK2001 unresolved external symbol "public: void __cdecl Graph_lib::Window::attach(class Graph_lib::Shape &)" (?attach@Window@Graph_lib@@QEAAXAEAVShape@2@@Z) WindowsProject5 E:\Visual C++\WindowsProject5\WindowsProject5.obj 1 Error LNK2001 unresolved external symbol "public: void __cdecl Graph_lib::Polygon::add(struct Graph_lib::Point)" (?add@Polygon@Graph_lib@@QEAAXUPoint@2@@Z) WindowsProject5 E:\Visual C++\WindowsProject5\WindowsProject5.obj 1 Error LNK2001 unresolved external symbol "public: virtual void __cdecl Graph_lib::Shape::move(int,int)" (?move@Shape@Graph_lib@@UEAAXHH@Z) WindowsProject5 E:\Visual C++\WindowsProject5\WindowsProject5.obj 1 Error LNK2001 unresolved external symbol "public: virtual void __cdecl Graph_lib::Polygon::draw_lines(void)const " (?draw_lines@Polygon@Graph_lib@@UEBAXXZ) WindowsProject5 E:\Visual C++\WindowsProject5\WindowsProject5.obj 1 Error LNK2001 unresolved external symbol "public: virtual void __cdecl Graph_lib::Open_polyline::draw_lines(void)const " (?draw_lines@Open_polyline@Graph_lib@@UEBAXXZ) WindowsProject5 E:\Visual C++\WindowsProject5\WindowsProject5.obj 1 Error LNK2001 unresolved external symbol "public: virtual void __cdecl Graph_lib::Closed_polyline::draw_lines(void)const " (?draw_lines@Closed_polyline@Graph_lib@@UEBAXXZ) WindowsProject5 E:\Visual C++\WindowsProject5\WindowsProject5.obj 1 Error LNK2001 unresolved external symbol "public: virtual void __cdecl Graph_lib::Button::attach(class Graph_lib::Window &)" (?attach@Button@Graph_lib@@UEAAXAEAVWindow@2@@Z) WindowsProject5 E:\Visual C++\WindowsProject5\WindowsProject5.obj 1 Error LNK2001 unresolved external symbol "protected: virtual void __cdecl Graph_lib::Window::draw(void)" (?draw@Window@Graph_lib@@MEAAXXZ) WindowsProject5 E:\Visual C++\WindowsProject5\WindowsProject5.obj 1 Error LNK2001 unresolved external symbol "protected: virtual void __cdecl Graph_lib::Shape::draw_lines(void)const " (?draw_lines@Shape@Graph_lib@@MEBAXXZ) WindowsProject5 E:\Visual C++\WindowsProject5\WindowsProject5.obj 1? I tried but still can not solve it . Can anyone help me with this problem ? Really appreciate . Sorry my English is not so good.
{ "language": "en", "url": "https://stackoverflow.com/questions/71325878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Events for fs createReadStream Not Always Being Called I have an fs filestream being used to serve file downloads which are dynamically created. I get this stream and pipe it to my response object after setting appropriate headers. I also set a couple stream events so that if there's an error or the stream ends, it removes the generated files from the file system. I'm running into an issue where, on occasion, when the download isn't correctly initialized or finished there may be some hanging files left on the file system. I believe this is because of the events I hook into the stream. My code: stream = fs.createReadStream( fileName, {bufferSize: 64*1024}) had_error = false; stream.on 'error', (err) -> had_error = err stream.on 'close', -> if had_error console.log(had_error) fs.unlink fileName, (error) -> if error console.log("DELETE ERROR") console.log error fs.unlink dataFileName, (error) -> if error console.log("DELETE ERROR") console.log error Checking on the stream API documentation the 'close' event isn't called by all streams. I would use the 'end' event, however according to the docs: Indicates that no more 'data' events will happen. If the stream is also writable, it may be possible to continue writing. I'm worried if I were to use the 'end' event could you run into the issue where if I remove these files and the stream isn't finished writing to the http response that it will lead to a corrupt download. Any "for sure" event that can be used as a catch to remove these files and not break downloads? Worst case scenario I write a cronjob to remove these files (bleh). A: I never did figure out a sure-fire way of ensuring the event gets called. I'm guessing that if the response object never actually starts the stream, it never starts thus never having an ending event. If anyone knows a workaround feel free to answer and get a free accepted answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/15163567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Find the second occurrence of string in a file with quoted text and return name of that String I have a file abc.txt containing quoted strings. For the following input ./executeSQL.sh alt_tbl.sql /scratch/app/product/fmw/obpinstall/patchStage/1000050165/files/obp/ identifyInvalidObjects.sql Current time : 15:01:34 SP2-0734: unknown command beginning "echo "Curr..." - rest of line ignored. SP2-0734: unknown command beginning "/home/alam..." - rest of line ignored. ALTER TABLE "FLX_PI_FIN_PROF_LIAB_DTLS" ADD ("LIAB_DTL_SL_NO" NUMBER NOT NULL ENABLE) * ERROR at line 1: ORA-01758: table must be empty to add mandatory (NOT NULL) column I want to return alt_tbl.sql A: The following will extract alt_tbl.sql from the file abc.txt: with open('abc.txt') as f_input: text = f_input.read() file_name = text.split(' ', 2)[1] print file_name A: With a csv reader will be more apt with a check for quotes using csv sniffer to check for multiple delimiters import csv scndval=None li=[] scndval=None with open('abc.txt', 'rb') as csvfile: dialect = csv.Sniffer().sniff(csvfile.read(1024), delimiters=" \t") csvfile.seek(0) csvreader = csv.reader(csvfile, dialect,quotechar='"') for row in csvreader: li+=row if (li)>1: scndval = li[1] break print scndval I/P : hello "how are you" ? O/P : how are you
{ "language": "en", "url": "https://stackoverflow.com/questions/33952263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: get javascript variable value and store it to django variable and use it vice versa I want to store the javascript values in my django variables or use it in my view query //javascript values want to store in django var js_latitude = 122.33; var js_longitude = 12.22; django_latitude = js_latitude django_longitude = js_longitude save this value to my Django variable and calculate or multiply the values then it will be displayed by view or use in my query . just like location variable and save to Django and calculate distance than also
{ "language": "en", "url": "https://stackoverflow.com/questions/61884784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Regex for Mediawiki replacement I am using the Replace Text extension in MW 1.23 (which uses MySQL regexps) and I want to run regexes that will result in replacements like the ones in the examples below. The point is that it should find only matches that have a single Greek (extended/polytonic) word between the tags or just a word failing that. Replacing this bit first: <b class="b3"> and then the second one: </b> Is not an option as there are other instances that should not be replaced. Examples: First string of each example is the actual string, second string the way it should be after the replacement. The Greek word could be any Greek word (here "σπυρίς" and "ὑσμίνη"): 1. Dim. of <b class="b3">σπυρίς</b> Dim. of [[σπυρίς]] 2. cf. <b class="b3">ὑσμίνη</b> cf. [[ὑσμίνη]] A: Search for the following pattern: <b class="b3">([^\s-\.]*?[σπυρίς]+?[^\s-\.]*?)<\/b> And replace it with that: [[$1]] [σπυρίς] can be extended with any greek character you want to have at least in between the tags.
{ "language": "en", "url": "https://stackoverflow.com/questions/41509436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cannot retrieve ALL datatable names from database I am developing some code to tabulate the datatable names and their corresponding columns from a database. I want to have the list that I can see on the MS SQL Report Builder - Query Designer: Here's my code: SqlConnection conn = new SqlConnection("Data Source = server; Initial catalog = Catalog; Integrated Security = true"); conn.Open(); DataTable dt = conn.GetSchema("Tables"); List<string> tablenames = new List<string>(); foreach(DataRow dr in dt.Rows){ string table = (string)dr[2]; if((string)dr[1] == "dbo"){ //Creating a list of table names for "dbo" schema tablenames.Add(table); } } foreach(string table in tablenames){ if(true){ SqlDataReader reader = new SqlCommand("SELECT * FROM " + table, conn).ExecuteReader(); //Iterating the entire list of table names and getting the column names for(int column = 0; column < reader.FieldCount; column++){ Console.WriteLine("Catalog - dbo - " + table + " - " + reader.GetName(column)); } reader.Close(); } } Console.WriteLine("END"); Console.ReadLine(); However, the list that I get doesn't display (among others) the first table "AccountBillingCode", even though I know it's contained within the list of strings. If I change the statement: if(true) by if(table.StartsWith('A')) Then, "AccountBillingCode" is listed in the output. I don't understand why there are some tables getting excluded from my code. Any ideas? Thanks! A: Something like this as an idea. select t.name,c.name from sys.tables as t left join sys.columns as c on t.object_id=c.object_id order by t.name,c.column_id A: Apparently, there's nothing wrong with the code. It's just the code is too long for the Console, and when copying from there, the content at the top is missing. Disappointing mystery this time. Sorry! Thanks for the answers anyway!
{ "language": "en", "url": "https://stackoverflow.com/questions/72197955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Custom Authentication using AbstractAuthenticationProcessingFilter with permitted paths and Also enabling method security with roles I am trying to implement a custom token based authentication with authentication filter: public class AuthAuthenticationFilter extends AbstractAuthenticationProcessingFilter { @Override public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException { //some code here } @Override protected void successfulAuthentication(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) { final Authentication authResult) throws IOException, ServletException { SecurityContextHolder.getContext().setAuthentication(authResult); chain.doFilter(request, response); } } Registering it with @Configuration @Order(2) @EnableWebSecurity(debug = true) public class Security extends WebSecurityConfigurerAdapter { // constructor and beans etc @Override protected void configure(HttpSecurity http) throws Exception { http.csrf() .disable().sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .requestMatchers(PROTECTED_URLS).hasAnyRole(getAllrolles()).anyRequest() .authenticated() .and() .addFilterBefore(authAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class) .formLogin().disable() .httpBasic().disable() .logout().disable(); } } I have another websecurity config with order 1 for whitelisted urls: @Configuration @Order(1) public class SecurityWhiteList extends WebSecurityConfigurerAdapter { //constructor and permitted path etc @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().authorizeRequests() .requestMatchers(permittedPaths()).permitAll() .and() .anonymous(); } } At last, I have a configuration for method security as follows: @Configuration @EnableGlobalMethodSecurity(prePostEnabled = true) public class MethodSecurity extends GlobalMethodSecurityConfiguration { private final RoleHierarchy roleHierarchy; @Autowired public MethodSecurity(RoleHierarchy roleHierarchy) { this.roleHierarchy = roleHierarchy; } @Override protected MethodSecurityExpressionHandler createExpressionHandler() { DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler(); expressionHandler.setRoleHierarchy(roleHierarchy); return expressionHandler; } } The problem here is, I get 403 for the endpoints having method security in the service method annotated with @PreAuthorize("hasAuthority('ROLE_SOMETHING')) even though the users do have ROLE_SOMETHING. It works, if @PreAuthorize("hasAuthority('ROLE_SOMETHING')) is not present and roles authentication, permitted path everything works. After debugging, I found that my method security runs before AuthAuthenticationFilter and thus the security context is not populated yet so the user gets ROLE_ANONYMOUS. My question is: Is it possible to make the authentication filter fire before method security? Or am I entirely doing it wrong? Like I should instead use oncePerRequestFilter instead of AbstractAuthenticationProcessingFilter?
{ "language": "en", "url": "https://stackoverflow.com/questions/73472935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to instantiate a scikit-learn model from a string variable? I have a list of models as parameters in a YAML file. When I read them into my Python script, they appear there as strings: my_model = "LinearRegression()" print(type(my_model)) #output: <class 'str'> I want to initialize my sklearn model as: model = LinearRegression() but with LinearRegression() being a string variable. At the moment, naturally, model = my_model is a string, and can't be fitted, etc. How to instantiate the sklearn model from a string variable? My use case: I want to put different models in a YAML file as params in order to sweep over them in the model fine-tuning procedure (a simple AutoML). A: You have few options: * *Use eval as a quick&dirty solution: from sklearn.linear_model import LinearRegression model_str = 'LinearRegression()' model = eval(model_str) print(model) Note: using eval is not a safe because it will execute any string so if you have no control about a string variable being executed a malicious code may be executed. Also you need to import exact the same class before using eval. Without the first line the code will not work. *use pickle.dumps from sklearn.linear_model import LinearRegression model_class_serialized = pickle.dumps(LinearRegression) print(model_class_serialized) model_class = pickle.loads(model_class_serialized) print(model_class) In that case you do not need explicitly import classes from sklearn. An example of saving models to YAML: import pickle import yaml from sklearn.linear_model import LinearRegression from sklearn.ensemble import RandomForestClassifier from sklearn.svm import LinearSVC models = [LinearRegression, RandomForestClassifier, LinearSVC] with open('models.yml', 'w') as out_file: yaml.dump({m.__name__: pickle.dumps(m) for m in models}, out_file) After that you can read YAML file like that: import pickle import yaml with open('models.yml', 'r') as in_file: models = yaml.load(in_file, Loader=yaml.FullLoader) models = {name: pickle.loads(serialized_cls) for name, serialized_cls in models.items()} print(models) Which produces: {'LinearRegression': <class 'sklearn.linear_model._base.LinearRegression'>, 'LinearSVC': <class 'sklearn.svm._classes.LinearSVC'>, 'RandomForestClassifier': <class 'sklearn.ensemble._forest.RandomForestClassifier'>} so you can easily instantiate these models: model = models['RandomForestClassifier']() print(model) # model.fit(...)
{ "language": "en", "url": "https://stackoverflow.com/questions/74141661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Grails form token not available for ajax forms? In grails it is easy to add tokens to prevent form double submission and also the click hijacking. Just add useToken="true" to the form tag: <g:form ... useToken="true" > But, this is not available for formRemote tag. I know that I can do normal form and write js code to transform them into ajax froms with token, but because of that is odd that is not supported by default in the formRemote tag. Any reason for this, or is just (another) bug in Grails?
{ "language": "en", "url": "https://stackoverflow.com/questions/14975542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: material-ui component style customization – change color of select component to white I want to use a dropdown menu of the material-ui components (see https://material-ui.com/components/selects/). Therefore, I copied the specific component out of the example: Component return <div> <FormControl variant="outlined" className={classes.root}> <InputLabel ref={inputLabel} id="demo-simple-select-outlined-label"> Plan </InputLabel> <Select labelId="demo-simple-select-outlined-label" id="demo-simple-select-outlined" value={age} onChange={handleChange} labelWidth={labelWidth} > <MenuItem value=""> <em>None</em> </MenuItem> <MenuItem value={10}>dsnfsdjfnsduifn</MenuItem> <MenuItem value={20}>Twenty</MenuItem> <MenuItem value={30}>Thirty</MenuItem> </Select> </FormControl> Style const useStyles = makeStyles(theme => ({ root: { margin: theme.spacing(1), minWidth: 120, color: 'white', borderColor: 'white' },})); Because of my app design, I want to change the color of this dropdown menu to white. At the moment the component looks like this: As you can see in the component, the variant is outlined. As I understand the documentation (https://material-ui.com/api/select/) I have to overwrite the .MuiSelect-outlined class but I am not sure how I can do this. Unfortunately, the manual only describes the style of simple buttons and not how I can change the style of more complex components like these. I hope someone can give me an example how I can change the color of the outline, the text and the arrow to white. A: There you go .MuiOutlinedInput-notchedOutline { border-color: #fff;//for border color } .MuiSelect-icon { color: #fff;// for icon drop down icon color } .MuiInputLabel-root { color: #fff;// for lable color } For focus just add the parent .Mui-focused selector on these A: const useStyles = makeStyles(theme => ({ select: { borderColor: 'white' }, fomrControl{ margin: theme.spacing(1), minWidth: 120, color: 'white', } }));
{ "language": "en", "url": "https://stackoverflow.com/questions/59474264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using a DocumentTermMatrix with a neural net classifier to make predictions in R I have been trying to learn how to use a DocumentTermMatrix to make predictions in R. I have been using the following link as a reference to try and make predictions for a different dataset. https://rpubs.com/cen0te/naivebayes-sentimentpolarity Here, the author uses an IMDB movie review dataset where the review text is analysed. Predictions are then made based on the review text as to whether the review is positive or negative using the Naive Bayes classifier (from e1071). The dataset contains a separate column with yes/no values where if a review was positive, the value is 'yes' else it is 'no'. I have successfully implemented this for the naive bayes classifier on a different dataset however I now want to use different classifiers to do this so I can compare their performance. I have been trying to use the neural net classifier (from the neuralnet package) however I do not know where to begin. For the naive bayes classifier the following code was used to make predictions: classifier <- naiveBayes(train_DocumentTermMatrix, input_training_data$class, laplace = 1) pred <- predict(classifier, test_DocumentTermMatrix) For the neural net package, I require a formula to run the classifier however I want to make predictions based on the document term matrix so I am confused as to what the formula is. Could somebody please point me to the right direction and tell me how to proceed with this?
{ "language": "en", "url": "https://stackoverflow.com/questions/40835490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to run 2 functions simultaneously in vuejs I wanted to run 2 functions simultaneously in VUE. One function will be called when component is mounted and it will be running every 10 seconds. The other function will start executing when we click on the button. Now my problem is when I click the button the function start executing and the first function will not be called till this function completed its execution. <template> <div> <select v-model="file_id" class="form-control" id=""> <option v-for="(file, index) in files" :value="file.value" :key="index"> {{ file.label }} </option> </select> <button class="btn btn-success" @click="handleFileUpload">Import</button> </div> </template> <script> export default { data() { return { files: [], }; }, mounted() { this.upload_status = setInterval(() => { this.getUploadedStatus(); }, 5000); }, methods: { handleFileUpload() { //it will start executing when we click the button (need to call API) axios.post(); }, getUploadedStatus() { //it has to run every 10 seconds (Need to call API) axios.get(); }, beforeDestroy() { clearInterval(this.upload_status); }, }, }; </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/73815405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I play an audio (or audio/video) file from a DLL written in C++? We want to play audio (and video) files from a DLL. RenderSharedEvent/TimerDriven works, but for a number of reasons we prefer to do playback at a higher level- Media Foundation, or even the deprecated MediaPlay or waveOut functions would work. However, so far I'm not seeing the callbacks, and they seem to be a critical part of the process. Is that because they don't work from a DLL, or is there something I'm missing? I remember it used to be impossible to use waveOut from a DLL, but I assumed the new frameworks would support a DLL.
{ "language": "en", "url": "https://stackoverflow.com/questions/13128191", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem extracting Youtube search results I am new to Python and have learned basis of Web Scraping with bs4. here i tried to extract all the links of Youtube search results , it doesn't work like on other sites. i analyzed the search result html data and the links of search results were in anchor tag with id "video title" , but the tag doesn't appear in my bs4 parsed html document from bs4 import BeautifulSoup as bs import requests name=input("Enter video name ") url='https://www.youtube.com/results?search_query='+name searched=requests.get(url) soup=bs(searched.text,'html.parser') aid=soup.find_all('a',{'id':'video-title'}) print(aid) i expect the output contain all the search result. i have not learned other packages , i want to do this in bs4 if possible. A: All this trouble to get YouTube search result data is just a waste of time and effort. Why not try out these options * *YouTube Data API *Selenium + Headless chrome That being said, for the first 20 results, you can get the data from the JavaScript content in the source. The answer to that is given below. After about 1 hr of making sense of the resulting json, it still fails for some queries.YouTube is a very complicated site. The response may vary based on location, browser, search query etc. We are extracting the data from this script tag in the source. Code: from bs4 import BeautifulSoup as bs import requests import re import json headers={ 'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36' } name=input("Enter video name: ") url='https://www.youtube.com/results?search_query=hello'+name searched=requests.get(url,headers=headers) soup=bs(searched.text,'html.parser') aid=soup.find('script',string=re.compile('ytInitialData')) extracted_josn_text=aid.text.split(';')[0].replace('window["ytInitialData"] =','').strip() video_results=json.loads(extracted_josn_text) #print(item_section=video_results["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"][1]) item_section=video_results["contents"]["twoColumnSearchResultsRenderer"]["primaryContents"]["sectionListRenderer"]["contents"][0]["itemSectionRenderer"]["contents"] for item in item_section: try: video_info=item["videoRenderer"] title=video_info["title"]["simpleText"] url=video_info["navigationEndpoint"]["commandMetadata"]["webCommandMetadata"]["url"] print('Title:',title) print('Url:',url, end="\n----------\n") except KeyError: pass Output: Enter video name: hello Title: New Punjabi Songs 2017-Hello Hello(Ful Song)-Prince Narula-Yuvika Chaudhary-Latest Punjabi Song 2017 Url: /watch?v=mv326-zVpAQ ---------- Title: Alan Walker - The Spectre Url: /watch?v=wJnBTPUQS5A ---------- Title: Hello Hello (Full HD) - Rajvir Jawanda | MixSingh | Josan Bros | New Punjabi Songs 2018 Url: /watch?v=xydupjQSj44 ---------- Title: Bachchan - Hello Hello - Kannada Movie Full Song Video | Sudeep | Bhavana | V Harikrishna Url: /watch?v=oLMMgoug4Uk ---------- Title: Hello Hello latest 2017 16 june punjabi song Url: /watch?v=MqCSsPXw8QU ---------- Title: Hello Hello | + More Kids Songs | Super Simple Songs Url: /watch?v=saDkICxEdgY ---------- Title: 'Gallan Goodiyaan' Full VIDEO Song | Dil Dhadakne Do | T-Series Url: /watch?v=jCEdTq3j-0U ---------- Title: Hello Hello Gippy Grewal Feat. Dr. Zeus Full Song HD | Latest Punjabi Song 2013 Url: /watch?v=IRW2O4QZhgs ---------- Title: Hello Hello | Pataakha | Malaika Arora | Vishal Bhardwaj & Rekha Bhardwaj | Gulzar | Ganesh Acharya Url: /watch?v=RxBAitQLSLA ---------- Title: Hello Hello (Lyrical Audio) Prince Narula ft. Yuvika Chaudhary | Punjabi Lyrical Audio 2017 | WHM Url: /watch?v=v8VIsIvhDoQ ---------- Title: Hello Hello Full Video Song || Bhale Bhale Magadivoi || Nani, Lavanya Tripathi Url: /watch?v=y3FI02OO_kU ---------- Title: Hello hello gaad bahe dhufee na egaa (new comedy hhhhhh) Url: /watch?v=DuRrcTo4rgg ---------- Title: Proper Patola - Official Video | Namaste England | Arjun | Parineeti | Badshah | Diljit | Aastha Url: /watch?v=YmXJp4RtBCM ---------- Title: Official Video: Nikle Currant Song | Jassi Gill | Neha Kakkar | Sukh-E Muzical Doctorz | Jaani Url: /watch?v=uBaqgt5V0mU ---------- Title: Insane (Full Song) Sukhe - Jaani - Arvindr Khaira - White Hill Music - Latest Punjabi Song 2018 Url: /watch?v=mKpPhVVF8So ---------- Title: Radha bole HELLO HELLO-cartoon song mix with step up 2 Url: /watch?v=TFCTgNCzrck ---------- Title: Hello Song | CoCoMelon Nursery Rhymes & Kids Songs Url: /watch?v=fxVMqaViVaA ---------- Title: Bachchan - Hello Hello Unplugged Version | Sudeep | Bhavana | V Harikrishna Url: /watch?v=lvH3kTGJeEQ ---------- Title: Hello Hello! Can You Clap Your Hands? | Original Kids Song | Super Simple Songs Url: /watch?v=fN1Cyr0ZK9M ---------- One last thing that you can try out is to emulate the API used by youtube itself ie. POST request to https://www.youtube.com/results?search_query=yoursearchtext It has a lot of cookie and session values being sent as parameters. You may need to emulate all of them. You may need to use Requests session objects to do that.
{ "language": "en", "url": "https://stackoverflow.com/questions/56054147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to create pdf programmatically in specific format? I have all the data in NSData object but I dont know how to create a pdf that will display in this format. The main problem is that product does not have a fixed content size, there will be more and more depending upon the customer, how much he/she purchases. I don't want to make uiview like below format because if do so then how do captured entire uitableview in .png format. Please give the logic how to create pdf for below format. Thanks a ton! A: There are two ways to create PDFs in iOS: If you want text in your PDF, you need to use Quartz 2D There is no API that helps you to draw in tabular format. You need to draw lines, text by calculating x and y positions, all done manually. If you have fixed set of fields then only you can follow this approach. Else, you can create a html page for your required format, and then set this page in PDF as an image, a very simple approach. Both will be done using Quartz 2D Hope this helps :) A: Best place to start here and then here need to draw a table with lines and add text and image to it also :) For info refer and docs A: There are two ways to draw PDF. * *Using UIKit API: For this your can draw pdf line by line & image by imagem i.e. Object by Object. Link to this is : http://www.raywenderlich.com/6581/how-to-create-a-pdf-with-quartz-2d-in-ios-5-tutorial-part-1 *Using Quartz 2D Api: Using this You can draw pdf using the UIViews. Link for the same is: http://mobile.tutsplus.com/tutorials/iphone/generating-pdf-documents/ http://www.ioslearner.com/generate-pdf-programmatically-iphoneipad/ The UIKit Api creates a nice clean & smooth PDF. While Quartz2D framework creates a little blur pdf. So you need to be sure before using it. Let me know if it works or any issues.
{ "language": "en", "url": "https://stackoverflow.com/questions/12472118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: No matching constructor for initialization of "Type" I am writing a board game using C++ (with SFML2.2 library, Xcode 6.1.1). I created two classes: block and board. The idea is to create a 4x4 vector of blocks inside board. The codes are below: In block.h #ifndef __Game1024__block__ #define __Game1024__block__ #include <stdio.h> #include <iostream> #endif /* defined(__Game1024__block__) */ using namespace std; class block{ public: sf::RectangleShape rect; sf::Text text; block(); block(const int X,const int Y,const double size, const double blockSize, const double charSize, const int value, const sf::Color fillColor, const sf::Color textColor); }; In block.cpp #include <SFML/Audio.hpp> #include <SFML/Graphics.hpp> #include <string> #include <sstream> #include "block.h" using namespace std; block::block(){} block::block(const int X,const int Y,const double size, const double blockSize, const double charSize, const int value, const sf::Color fillColor, const sf::Color textColor){ double centerX = (X+0.5)*size; double centerY = (Y+0.5)*size; stringstream ss; ss << value; string sval = ss.str(); rect.setSize(sf::Vector2f(blockSize,blockSize)); rect.setOrigin(blockSize/2.0, blockSize/2.0); rect.setPosition(centerX, centerY); rect.setFillColor(fillColor); text.setStyle(sf::Text::Bold); text.setCharacterSize(charSize); text.setString(sval); text.setColor(textColor); text.setOrigin(text.getLocalBounds().width/2.0, text.getLocalBounds().height); text.setPosition(centerX, centerY); } In board.h #ifndef __Game1024__board__ #define __Game1024__board__ #include <stdio.h> #endif /* defined(__Game1024__board__) */ #include <vector> #include "block.h" using namespace std; class board{ private: int winSizeX; int winSizeY; int margin; double charSize; public: vector<vector<block>> matrix; board(); board(int winSizeX_,int winSizeY_,int margin_, double charSize_); void draw(); }; And in board.cpp #include "board.h" //#include <SFML/Audio.hpp> #include <SFML/Graphics.hpp> #include "block.h" using namespace std; board::board(){} board::board(int winSizeX_,int winSizeY_,int margin_, double charSize_){ winSizeX = winSizeX_; winSizeY = winSizeY_; margin = margin_; charSize = charSize_; matrix = vector<vector<block>>(4,vector<block>(4)); double size = winSizeX/4.0; // = 256 double blockSize = size - 2*margin; const sf::Color fillColor = sf::Color::Red; const sf::Color textColor = sf::Color::White; sf::Font font; if(!font.loadFromFile("./sansation.ttf")){ exit(EXIT_FAILURE); }; for (int i = 0; i < 4; ++i){ for (int j = 0; j < 4; ++j){ int value = 4*j + i + 1; matrix[i][j] = block(i,j,size,blockSize, charSize,value,fillColor,textColor); matrix[i][j].text.setFont(font); matrix[i][j].text.setOrigin(matrix[i][j].text.getLocalBounds().width/2.0,b[i][j].text.getLocalBounds().height); } } } The error comes from board.cpp matrix[i][j] = block(i,j,size,blockSize, charSize,value,fillColor,textColor); One weird thing is when I typed matrix[i][j] = block, the autofill of my IDE (Xcode) will generate matrix[i][j] = block(<#const int X#>, <#const int Y#>, <#const double size#>, <#const double blockSize#>, <#const double charSize#>, <#const int value#>, <#const int fillColor#>, <#const int textColor#>) The last two arguments of constructor block are changed from type sf::Color into int. If I create a 4x4 vector of blocks in the main.cpp file and call the constructor of block, there is no error... Any help? Thanks in advance! [Update] I attached the scrrenshot of the error message A: Thanks @molbdnilo I made a stupid mistake that I forgot to include the SFML header in "block.h" #include <SFML/Graphics.hpp> Now problem solved! Thanks for all advices. I am new to C++ projects, please feel free to speak out all my bad practices in the code. Very helpful!
{ "language": "en", "url": "https://stackoverflow.com/questions/28153581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Access to object in module Im doing some logic which parse json data to object and I want to expose in some module specific object outside that other module can use, I try with the following which doesnt work,any other idea? var jsonObject; module.exports = { parse: function () { //here I do the parsing .... jsonObject = JSON.parse(res) , //here I want to expose it outside jsonObj:jsonObject } A: If you are trying to expose the entire object, you build it like you would any other JavaScript object and then use module.exports at the end : MyObj = function(){ this.somevar = 1234; this.subfunction1 = function(){}; } module.exports = MyObj; If you just want to expose certain functions, you don't NEED to build it like an object, and then you can export the individual functions : var somevar = 1234; subfunction1 = function(){}; nonExposedFunction = function(){}; module.exports = { subfunction1:subfunction1, somevar:somevar }; A: you simply assign the result of JSON.parse to this.jsonObj: module.exports = { parse: function (res) { this.jsonObj = JSON.parse(res); } }; Using this.jsonObj you are exposing the JSON object to the outside and you can use your module in this way: var parser = require('./parser.js'), jsonString = // You JSON string to parse... parser.parse(jsonString); console.log(parser.jsonObj);
{ "language": "en", "url": "https://stackoverflow.com/questions/31781710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Setting CSS classes with current_user I'm having trouble arriving at an approach to this problem. tl;dr I want to be able to set the css class of an li to the name of the current_user that posted the chat. Then based on that class, I'll apply different styling. This is for a chat window and I want all the current users messages to display on one side and I want all other messages to display on the other side with a different color, etc. I have a file.js.coffee that basically reads in some user input and apends it to an ordered list and adds some elements and classes along the way projectRef.on "child_added", (snapshot) -> message = snapshot.val() $("<li class='self'>").append($("<div class='message'>").append($("<p>").text(message.text))).prepend($("<b/>").text(message.name + ": ")).appendTo $("#messagesDiv") $("#messagesDiv")[0].scrollTop = $("#messagesDiv")[0].scrollHeight $("#messageInput").keypress (e) -> if e.keyCode is 13 text = $("#messageInput").val() projectRef.push name: userName text: text $("#messageInput").val "" The above would yield something like this in the browser <li class="self"> <b>User : </b> <div class="message"> <p>My chatt message from file.js.coffee!!</p> </div> </li> That 'self' class in the li is what I have been trying to dynamically set based on the current_user. So I have 2 issues - 1. I'm trying to figure out who posted the li and 2. I'm trying to dynamically set the class of that li based on the user that chatted/posted it. My thinking was something along the lines of in the file.js.coffee use JQuery to grab that li and add the <%= current_user.name %> as a class then I could have a file.js.erb where I would do something like <% unless $('li').hasClass('<%= current_user.name %>'); %> <%= $('li').toggleClass('others') %> <% end %> This way it checks if the class of the target li is from the current user and if it is keep the css class as self if not toggle it to others. Then I could style the classes appropriately (left, right, background-color:blue;, etc). Is there a more correct way to approach this problem given what I am trying to accomplish? I think so.. A: It seems like you are saying you're trying to assign a class as the current user's name. I'm wondering if going that far is necessary. Assigning the list element with a class named "current_user" might be enough, then have separate CSS to control anything with class named "current_user". Here's an example fiddle. CSS li { list-style:none; clear:both; float:right; text-align:right; background-color:#A7A2A0; border:1px solid #EEE; width:200px; margin:10px; padding:5px; } li.current_user { float:left; text-align:left; background-color:#24887F; } HTML <li class="current_user"> <b>Current User:</b> <div class="message"> <p>My message!</p> </div> </li> <li> <b>All Other Users:</b> <div class="message"> <p>Other person's smessage.</p> </div> </li> UPDATE: Looking at the firebase example I altered it to add a class "current_user" if the username matched the the name of the user that wrote the message. Below is the part of the code that I altered in the "displayChatMessage" function, I also added CSS to the head section for the "current_user" class. Here's a link to the working example, view it in to different web browsers using different usernames at the same time to see. function displayChatMessage(name, text) { if(name == $('#nameInput').val()){ $('<div/>').text(text).prepend($('<em/>').text(name+': ')).appendTo($('#messagesDiv')).addClass('current_user'); $('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight; } else{ $('<div/>').text(text).prepend($('<em/>').text(name+': ')).appendTo($('#messagesDiv')); $('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight; } }; This is the CSS I added to the head. <style type="text/css"> .current_user { background-color:#24887F; } </style> A: There are many users using the app concurrently. But for every user, there is only one current_user in session. Don't mix it up. Since the message is to be processed by server, you can easily add a new attribute of message.klass in server side by judging the message comes from current_user. If it is, the class may be current, else blank or others. Then, in JS $('li').addClass('<%= message.klass %>')
{ "language": "en", "url": "https://stackoverflow.com/questions/17636353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Meteor: change a user password WITHOUT logout? Accounts.setPassword(userId, password); Before Meteor v1.0.2, the user was not logout when calling this function. Since v1.0.2, I quote from https://github.com/meteor/meteor/blob/devel/History.md, "Expire a user's password reset and login tokens in all circumstances when their password is changed". I don't know the reason of this change,but the fact is that function above logout the user. Is there a way, with v1.0.2, to change a user password without logout the user? If not, how do I downgrade the package account-base so the behaviour is like before? Thanks. A: The above answer is correct and here's the exact copy-paste code in case you're struggling: Accounts.setPassword(userId, password, {logout: false}); Note: make sure you are doing this call server side. A: Accounts.setPassword(userId, password, options) This method now supports options parameter that includes options.logout option which could be used to prevent the current user's logout. A: You could use Accounts.changePassword (docs) to change the password instead, this will not affect the user's existing tokens (as from) https://github.com/meteor/meteor/blob/devel/packages/accounts-password/password_server.js#L299-L302 If you want to do this from the server without knowing the existing password you would have to fork the accounts-password package and remove this line: https://github.com/meteor/meteor/blob/devel/packages/accounts-password/password_server.js#L338 and add this package into the /packages directory of your app If you want to downgrade your package (so long as the version you're using of meteor supports it): meteor remove accounts-password meteor add [email protected]
{ "language": "en", "url": "https://stackoverflow.com/questions/27693329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Why am I getting error: initializing argument 1 of 'Item::Item(int)' [-fpermissive] in Eclipse when I try to compile my C++ code? I'm new to C++, and have finally given up on trying to get this to compile after staring at it for too long. The compiler seems to be rejecting the constructor prototype in the header file for some reason... I can't figure out what's wrong with it. Item.h: #ifndef ITEM_H_ #define ITEM_H_ class Item { public: Item(int); //This line is what Eclipse keeps flagging up with the error in the title virtual ~Item(); Item* getNextPtr(); int getValue(); void setNextPtr(Item *); }; #endif /* ITEM_H_ */ In my Item.cpp file I have: int val; Item* nextPtr = 0; Item::Item(int value) { val = value; } Item* Item::getNextPtr() { return nextPtr; } void Item::setNextPtr(Item *nextItem) { nextPtr = nextItem; } int Item::getValue() { return val; } Item::~Item() { // TODO Auto-generated destructor stub } Oops, I'm using GCC. And yeah, they should have been member variables! How do I go about doing that using this format? The code where I use instantiate Item is below. I am aware that there should be no global variables in that either... #include "LinkList.h" #include "Item.h" Item* first = 0; int length = 0; LinkList::LinkList(int values[], int size) { length = size; if (length > 0) { Item firstItem = new Item(values[0]); Item *prev = &firstItem; first = &firstItem; for (int i = 0; i < size; i++) { Item it = new Item(values[i]); prev->setNextPtr(&it); //set 'next' pointer of previous item to current item prev = &it; // set the current item as the new previous item } } } LinkList::~LinkList() { for (int i = 0; i < length; i++) { Item firstItem = *first; Item *newFirst = firstItem.getNextPtr(); delete(first); first = newFirst; } } int LinkList::pop() { Item firstItem = *first; first = firstItem.getNextPtr(); return firstItem.getValue(); } I've just noticed a bug with the functionality of the pop() and destructor functions... please ignore those, I just want to figure out what's wrong with the instantiation of Item. GCC error: Info: Internal Builder is used for build g++ -O0 -g3 -Wall -c -fmessage-length=0 -o "src\\LinkList.o" "..\\src\\LinkList.cpp" ..\src\LinkList.cpp: In constructor 'LinkList::LinkList(int*, int)': ..\src\LinkList.cpp:16:38: error: invalid conversion from 'Item*' to 'int' [-fpermissive] ..\src\/Item.h:14:2: error: initializing argument 1 of 'Item::Item(int)' [-fpermissive] ..\src\LinkList.cpp:20:32: error: invalid conversion from 'Item*' to 'int' [-fpermissive] ..\src\/Item.h:14:2: error: initializing argument 1 of 'Item::Item(int)' [-fpermissive] 21:24:26 Build Finished (took 256ms) A: Here: Item firstItem = new Item(values[0]); You are creating a new Item with an item pointer as its argument. This is the same as: Item firstItem(new Item(values[0])); And it should be: Item *firstItem = new Item(values[0]);
{ "language": "en", "url": "https://stackoverflow.com/questions/14224421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: why my custom tld not accessible from /WEB-INF/lib/ In my web application I'd placed my custom.tld file in /WEB-INF/lib/custom.tld and referenced in my web.xml as <jsp-config> <taglib> <taglib-uri>customTldUri</taglib-uri> <taglib-location>/WEB-INF/lib/custom.tld</taglib-location> </taglib> </jsp-config> and if I do add taglib in jsp then I'm getting JasperException for not able to find/add referenced tld. But if I do move the custom.tld to /WEB-INF/custom.tld and update the web.xml to <taglib-location>/WEB-INF/custom.tld</taglib-location> then it works. But in the same project I do have struts tld files added in /WEB-INF/lib/struts-*.tld and there is not exception for them. My question is why my custom.tld is not accessible if I do place it in /WEB-INF/lib/ while the strtus tlds are working fine?
{ "language": "en", "url": "https://stackoverflow.com/questions/28512046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Copy from HTML div without copying the formatting style I have a div which has a bunch of styling (font-family, font-size, background-color, etc.) and I'd like to be able to copy text from it, and paste it into a rich text editor (Google Docs or Gmail for eg.) without it pasting the styles. I know I can use the "paste without formatting" or equivalent option, but I'd like to know if there's a clean way to disable copying the formatting at all on the webpage itself, because I only care about the text. To test: run this snippet, copy the styled text, and paste it into a google doc. <div style="background-color: orange"> Copy me! </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/67064042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Scala / Spray: Return all rejections as JSON I'm writing a JSON API using Spray 1.2.1 and I would like to return all HTTP Responses in the following format by default. { "type":"error", "status":404, "message":"Not Found" } My own custom rejections / exceptions will have less generic content in the 'message' field, but I'm looking for a way of globally formatting (and possibly otherwise decorating, for debug/testing) all non-2xx responses. Is this possible without handling every possible rejection and status code? Thanks! Sam A: I don't know if this is generic enough for you but here's how I do something similar: import spray.json.DefaultJsonProtocol case class Rejection(type:String, status: Int, message: String) object RejectionJsonProtocol extends DefaultJsonProtocol{ implicit val rejectionFormat = jsonFormat3(Rejection) } Then you can complete your routes with a Rejection, possibly in your RouteExceptionHandler like this: trait RouteExceptionHandlers extends HttpService { import RejectionJsonProtocol._ implicit def routeExceptionHandler(implicit log: LoggingContext) = ExceptionHandler { case e: UnsuccessfulResponseException => requestUri { uri => complete(e.response.status, Rejection("error",e.response.status,"Not found")) } } //other exceptions go here }
{ "language": "en", "url": "https://stackoverflow.com/questions/23531290", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CLion doesn't sort include statements on commit I'm using clang-format to define rules for sorting my include statements. This works perfectly when using the "Code > Reformat Code" button or pressing CTRL + ALT + L within a file. However, even when setting the "Reformat code" checkbox in the CLion commit dialog, the include statements don't get sorted when commiting. For some reason other formatting tasks (such as fixing indentation) take place when commiting. It's just the include sorting that's missing. Does anybody know why that is the case? Many thanks! From the .clang-format file: IncludeCategories: - Regex: '^<.*\.h>' Priority: 1 - Regex: '^<[^.]*>' Priority: 2 - Regex: '<.*>' Priority: 3 - Regex: '.*' Priority: 3 IncludeBlocks: Regroup SortIncludes: true A: JetBrains Support confirmed to be that this is a bug within CLion that they managed to reproduce on their system. Hoping for it to be fixed in a future version :)
{ "language": "en", "url": "https://stackoverflow.com/questions/73290845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is possible to make screen shot in ipad programmatically? Possible Duplicate: screenshots programmatically in IPad with the image name Is possible to make screenshot programmatically like this? I want to be able to take screenshots of the current screen, which is not necessarily my app, i.e., my app may be in the background when activated. You might think of it as programatically pressing the home and sleep button at the same time. I am aware that this will be limited to jailbroken devices.
{ "language": "en", "url": "https://stackoverflow.com/questions/9568273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Assigning id to validation message I am trying to assign id to span where validation message is dynamically shown. Am I doing some thing wrong? <div>@Html.ValidationMessageFor(model => model.Title,new{id="prjTitle"})</div> It throws Argument type is not assignable to parameter string A: just use the correct overload: @Html.ValidationMessageFor(model => model.YourProperty, "", new { @class = "a-class-if-you-want-one", id = "yourId" }) A: There is no overload that takes only the linq expression and an html attributes object. According to MSDN there is an overload that takes a linq expression, an errormessage (string) AND an html attributes object, like this: @Html.ValidationMessageFor(model => model.Title,"entry invalid",new{id="prjTitle"}) A: public static MvcHtmlString IDValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string id) { var validationString = Regex.Replace(htmlHelper.ValidationMessageFor(expression).ToString(), @"^data-valmsg-for=""*\""$", String.Format("data-valmsg-for=\"{0}\"", id)); return MvcHtmlString.Create(validationString); }
{ "language": "en", "url": "https://stackoverflow.com/questions/21100548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Jenkins and local PyCharm running tests using different path I am checking out a project from git repo. The project was run on Jenkins. One of the unit tests file is reading the file with filename: filename = os.path.join(self.config_dir, name, 'my_parameters.json') This works fine on Jenkins, but failed to work on my local machine using pyCharm. On the local machine, I have to change the filename to: filename = '../' + os.path.join(self.config_dir, name, 'my_parameters.json') to make the test works. It seems that Jenkins and local pyCharm is running test files in different path. How do I resolve this issue to make the code running in both machines? Thank you!
{ "language": "en", "url": "https://stackoverflow.com/questions/51410897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: problem with mapping table in NHibernate I rewrite application from ASP.NET to Silverlight and use NHibernate 2. Tables in my db looks like this: alt text http://img268.imageshack.us/img268/4940/tablesqp.jpg In Dziecko table I have reference to id of Opiekun and Grupy. In ASP it's ok for me but in videos Summer with NHibernate I see that Stephen Bohlen in exchange use object of this type, for me its Opiekun and Grupy.But in SQL Server I can't define object type, so better is map only this id[will I could problem querying for id] and or something else ?? Using all object of specific type is efficiency? We must query all object in exchange only int type of id's ?? A: (I hope I've understood your question correctly.) The relations in your database are always defined in database types, probably either an int or a uniqueidentifer in the case of foreign key columns. The database should know nothing of the data transfer objects NHibernate returns to your application code. When you map the foreign key columns in your data transfer objects using ManyToOne, etc., you specify the type of the object because NHibernate knows that the relation is always going to be between the foreign key column you specify in the attribute, and the Id (primary key) of the object type to be returned. This saves you the trouble of doing extra queries to return parent or child entities -- NHibernate just does a JOIN for you automatically and returns the relational information as an object hierarchy, instead of just a set of id values.
{ "language": "en", "url": "https://stackoverflow.com/questions/2750655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multiline regular expressions with python requests module I am iterating over a web page line by line using requests, but trying to capture some multi-line regular expressions: import requests r = requests.get(url) for line in r.iter_lines(): pat = re.search(regex, line) if pat: print pat.group(1) I have tried concatenating the whole file into one long string, but that seems wrong. What is the best way to capture these multiline expressions (preferably using requests)? Note: I am new to requests. I have looked at the docs but haven't found, or understood, the answer. Thanks A: r = requests.get(url) pat = re.search(regex, r.text)
{ "language": "en", "url": "https://stackoverflow.com/questions/26597009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Classroom.Courses.CourseWork.patch I am trying to update the "state" of an assignment within Google Classroom using Google Apps Script. The current state of the assingment is DRAFT. I am trying in two different codes and get two different errors: function publicarBorradores() { var courseId = "320315007220" var assingid = "320315007244" var newState = { "state":'PUBLISHED'} var patchDraft = Classroom.Courses.CourseWork.patch(newState,courseId,assingid); patchDraft.updateMask = newState; or patchDraft.updateMask = 'state' } I always get the same Error: "GoogleJsonResponseException: API call to classroom.courses.courseWork.patch failed with error: updateMask: Update mask is required" I also tried this other way: function valoresDraft (){ var courseId = "320315007220" var assingId = "320315007244" changeState(courseId,assingId); } function changeState(courseId,assingId) { var estado = {'state': "PUBLISHED",} const patchDraft = Classroom.Courses.CourseWork patchDraft.patch(estado, courseId, assID,{"updateMask":"state"}); } And I get a different error: "API call to classroom.courses.courseWork.patch failed with error: @ProjectPermissionDenied The Developer Console project is not permitted to make this request." which is strange as I am the owner of the class AND I have published via the same "Developer Console project" other publications within this same class. (The class was NOT created via API. I created it manually from within classroom.google.com) Thanks A: The are a few issues with your code: * *In the first example, the GoogleJsonResponseException: API call to classroom.courses.courseWork.patch failed with error: updateMask: Update mask is required" error you are receiving is due to the fact that you are not specifying the updateMask field before making the request. So even though you added the patchDraft.updateMask = newState; line, this won't help as it will be execute after the API call. *The second example ends up executing properly because you supplied the updateMask field at the time of making the request. However, since the class was created manually from the Classroom UI, this is the expected behavior, as the class is essentially not associated with any Developer Console Project. According to the documentation: ProjectPermissionDenied indicates that the request attempted to modify a resource associated with a different Developer Console project. Possible Action: Indicate that your application cannot make the desired request. It can only be made by the Developer Console project of the OAuth client ID that created the resource. What you can do in this situation is to create the class from the API and afterwards execute the patch call. Reference * *Classroom API Access Errors.
{ "language": "en", "url": "https://stackoverflow.com/questions/69036227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I return an object (ie. List) from an object mocked with NSubstitute? I am using NSubstitute to mock one of my classes/interfaces. One of the functions implemented by my class should return an object of type List. But when I try to use _mockedObject.MyFunction().Returns(myList), it gives me an error saying I cannot convert between my List and an object of type Func. I figured I could pass my list as a string using some ToString() function and convert it back? But that doesn't seem particularly clean as I'm expecting a list to come back from my function. I saw from a video on Unit Testing with Dependency Injection that you can return objects from mocked objects with Moq (https://www.youtube.com/watch?v=DwbYxP-etMY). I am considering switching to that if I can't manage to return an object with NSubstitute. A: Here is an example of how to return a List<string> from an object mocked by NSubstitute: using System.Collections.Generic; using NSubstitute; using Xunit; public interface ISomeType { List<string> MyFunction(); } public class SampleFixture { [Fact] public void ReturnList() { var _mockedObject = Substitute.For<ISomeType>(); var myList = new List<string> { "hello", "world" }; _mockedObject.MyFunction().Returns(myList); // Checking MyFunction() now stubbed correctly: Assert.Equal(new List<string> { "hello", "world" }, _mockedObject.MyFunction()); } } The error you have described sounds like there are different types involved. Hopefully the above example will help show the source of the problem, but if not please post an example of the _mockedObject interface and the test (as suggested in @jpgrassi's comment).
{ "language": "en", "url": "https://stackoverflow.com/questions/57383809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MS Tests/ Moq - ExpectedException failing I'm trying to create unit test for one of my method using MS test and Moq. Below is my interface, implementation class and method. public interface IDocumentManagementHandler { Task AddData(long documentId, string metadataCategoryName, List<KeyValuePair<string, string>> metadata); } public class DocumentManagementHandler : IDocumentManagementHandler { private readonly IService _service; private readonly IFService _fService; public readonly ILogger _logger; private static readonly long rootFolderId = 123456; public DocumentManagementHandler(IService Service, IFService FService, ILogger Logger) { _service = Service; _fService = FService; _logger = Logger; } public Task AddData(long documentId, string metadataCategoryName, List<KeyValuePair<string, string>> metadata) { if(string.IsNullOrEmpty(metadataCategoryName)) throw new ArgumentNullException(nameof(metadataCategoryName)); if (metadata == null) throw new ArgumentNullException(nameof(metadata)); return AddDocumentMetadataAsync(documentId, metadataCategoryName, metadata); } My MSTest method [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void TestAddData() { long documentID = 123; string metadataCategoryName = null; List<KeyValuePair<string, string>> metadata = null; var documentHandler = new Mock<IDocumentManagementHandler>(); documentHandler.Setup(s => s.AddData(documentID, metadataCategoryName, metadata)); var newresult = documentHandler.Object.AddData(documentID, metadataCategoryName, metadata); } I'm expecting the test method to pass when I pass the variable "metadataCategoryName" as NULL but test is failing with the message "Test method did not throw expected exception System.ArgumentNullException." . Any idea what's wrong here. A: Your issue: you are using a mock representing an interface of the object containing the method you want to test, which means your code is never really called (a breakpoint would have revealed this particular issue). As for how you should have written your test : [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void TestAddData() { long documentID = 123; string metadataCategoryName = null; List<KeyValuePair<string, string>> metadata = null; // Configure as needed using Mock.Get() var service = Mock.Of<IService>(); var fService = Mock.Of<IFService>(); var logger = Mock.Of<ILogger>(); var documentHandler = new DocumentManagementHandler(service, fService, logger); documentHandler.AddData(documentID, metadataCategoryName, metadata); } Additionally, you might want to assert the data contained in your exception. E.g. To check that your ArgumentNullException is reporting the correct parameter name
{ "language": "en", "url": "https://stackoverflow.com/questions/73868159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Make php date dropdown function 'sticky' Out of coffee and brain's given up... ...can anyone help to make this form date dropdown function retain selected month on $_POST ['submit'] or isset($missing) in the case of there being an error/missing field etc function createMonths($id='month_select', $selected=null) { /*** array of months ***/ $months = array( 1=>'Jan', 2=>'Feb', 3=>'Mar', 4=>'Apr', 5=>'May', 6=>'Jun', 7=>'Jul', 8=>'Aug', 9=>'Sep', 10=>'Oct', 11=>'Nov', 12=>'Dec'); /*** current month ***/ $selected = is_null($selected) ? date('m') : $selected; $select = '<select name="'.$id.'" id="'.$id.'">'."\n"; foreach($months as $key=>$mon) { $select .= '<option value="'.str_pad($key, 2, "0", STR_PAD_LEFT).'"'; $select .= ($key==$selected) ? ' selected="selected"' : ''; $select .= ">$mon</option>\n"; } $select .= '</select>'; return $select; } A: In the event you have invalid form data, you should check if the $_POST['month_select'] variable is set and not empty and create your dropdown passing in it's value like so: $selected = (!empty($_POST['month_select'])) ? $_POST['month_select'] : null; createMonths('month_select', $selected); function createMonths($id='month_select', $selected = null) { /*** array of months ***/ $months = array( '01'=>'Jan', '02'=>'Feb', '03'=>'Mar', '04'=>'Apr', '05'=>'May', '06'=>'Jun', '07'=>'Jul', '08'=>'Aug', '09'=>'Sep', '10'=>'Oct', '11'=>'Nov', '12'=>'Dec'); /*** current month ***/ $selected = is_null($selected) ? date('n') : $selected; $select = '<select name="'.$id.'" id="'.$id.'">'."\n"; $select .= "<option value=""></option>\n"; foreach($months as $key => $mon) { $select .= '<option value="'.$key.'"'; $select .= ($key == $selected) ? ' selected="selected"' : ''; $select .= ">$mon</option>\n"; } $select .= '</select>'; return $select; } I have also taken the liberty of fixing your createMonths() function by the recommendation regarding date('n') and changing your array keys to strings as this will avoid having to pad your months.
{ "language": "en", "url": "https://stackoverflow.com/questions/1636915", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ruby on rails - thin - HTTP GET URL > 1024 When I use an URL bigger than 1024 appear this in the console of the rails server. Invalid request: HTTP element REQUEST_PATH is longer than the 1024 allowed length. /home/vagrant/.rvm/gems/ruby-1.9.3-p448/gems/thin-1.6.1/lib/thin/request.rb:84:in `execute' /home/vagrant/.rvm/gems/ruby-1.9.3-p448/gems/thin-1.6.1/lib/thin/request.rb:84:in `parse' /home/vagrant/.rvm/gems/ruby-1.9.3-p448/gems/thin-1.6.1/lib/thin/connection.rb:41:in `receive_data' /home/vagrant/.rvm/gems/ruby-1.9.3-p448/gems/eventmachine-1.0.3/lib/eventmachine.rb:187:in `run_machine' /home/vagrant/.rvm/gems/ruby-1.9.3-p448/gems/eventmachine-1.0.3/lib/eventmachine.rb:187:in `run' /home/vagrant/.rvm/gems/ruby-1.9.3-p448/gems/thin-1.6.1/lib/thin/backends/base.rb:73:in `start' /home/vagrant/.rvm/gems/ruby-1.9.3-p448/gems/thin-1.6.1/lib/thin/server.rb:162:in `start' /home/vagrant/.rvm/gems/ruby-1.9.3-p448@global/gems/rack-1.5.2/lib/rack/handler/thin.rb:16:in `run' /home/vagrant/.rvm/gems/ruby-1.9.3-p448@global/gems/rack-1.5.2/lib/rack/server.rb:264:in `start' /home/vagrant/.rvm/gems/ruby-1.9.3-p448@global/gems/railties-4.0.1/lib/rails/commands/server.rb:84:in `start' /home/vagrant/.rvm/gems/ruby-1.9.3-p448@global/gems/railties-4.0.1/lib/rails/commands.rb:76:in `block in <top (r equired)>' /home/vagrant/.rvm/gems/ruby-1.9.3-p448@global/gems/railties-4.0.1/lib/rails/commands.rb:71:in `tap' /home/vagrant/.rvm/gems/ruby-1.9.3-p448@global/gems/railties-4.0.1/lib/rails/commands.rb:71:in `<top (required)> ' bin/rails:4:in `require' bin/rails:4:in `<main>' Can I rescue this exception?
{ "language": "en", "url": "https://stackoverflow.com/questions/22171418", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: QuantLib's HestonModelHelper class is throwing error I have below QuantLib model in python - import QuantLib as ql import pandas as pd day_count = ql.Actual365Fixed() calendar = ql.UnitedStates() calculation_date = ql.Date(6, 11, 2015) spot = ql.SimpleQuote(659.37) risk_free_rate = ql.SimpleQuote(0.01) dividend_rate = ql.SimpleQuote(0.0) riskFreeCurve = ql.FlatForward( calculation_date, ql.QuoteHandle(risk_free_rate), day_count ) dividend_yield = ql.FlatForward( calculation_date, ql.QuoteHandle(dividend_rate), day_count ) yield_ts = ql.YieldTermStructureHandle(riskFreeCurve) dividend_ts = ql.YieldTermStructureHandle(dividend_yield) p = ql.Period(ql.Date(6,12,2015) - calculation_date, ql.Days) s = 527.50 vols = 0.35 helper = ql.HestonModelHelper( p, calendar, ql.QuoteHandle(spot), ql.QuoteHandle(ql.SimpleQuote(s)), ql.QuoteHandle(ql.SimpleQuote(vols)), yield_ts, dividend_ts ) With above I got below error - Traceback (most recent call last): File "<stdin>", line 8, in <module> File "/usr/local/lib/python2.7/dist-packages/QuantLib/QuantLib.py", line 9840, in __init__ _QuantLib.HestonModelHelper_swiginit(self, _QuantLib.new_HestonModelHelper(*args)) TypeError: Wrong number or type of arguments for overloaded function 'new_HestonModelHelper'. Possible C/C++ prototypes are: HestonModelHelper::HestonModelHelper(Period const &,Calendar const &,Real const,Real const,Handle< Quote > const &,Handle< YieldTermStructure > const &,Handle< YieldTermStructure > const &,BlackCalibrationHelper::CalibrationErrorType) HestonModelHelper::HestonModelHelper(Period const &,Calendar const &,Real const,Real const,Handle< Quote > const &,Handle< YieldTermStructure > const &,Handle< YieldTermStructure > const &) Any clue where my code went wrong will be highly helpful. Thanks, A: The problem is that the HestonModelHelper expects the type of the spot and the strike to be a float. For it to work with minimal change, use: helper = ql.HestonModelHelper( p, calendar, spot.value(), s, ql.QuoteHandle(ql.SimpleQuote(vols)), yield_ts, dividend_ts )
{ "language": "en", "url": "https://stackoverflow.com/questions/62693773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }