text
stringlengths
15
59.8k
meta
dict
Q: Google sheets API limits for SAAS applications We want to develop an API integration for Google Sheets in our SAAS platform, we have around 1000 users and each user in our platform will be connecting their own Google Account to the integration. I see the API limits are 500 requests per 100 seconds per project, and 100 requests per 100 seconds per user. What I'm not 100% clear on is if these limits apply to our platform integration as a whole (all users on our platform) or the limits apply to each connected Google Account? I'm assuming the API limit applies to each individual connected Google Account in our integration so each user in our platform will have their own individual requests limits? I want to be sure though because the alternative of having only 100 requests per 100 seconds is not very scalable across 1000 users in our platform. Any clarification on this would be highly appreciated! A: The way the API limits would work for you is that: Every user would have a limit of 100 requests per 100 seconds per user, since you are performing these requests on the behalf of the user. If you application was performing these requests instead, then you would reach the 500 requests per 100 seconds. Hope this clarifies it!
{ "language": "en", "url": "https://stackoverflow.com/questions/58245342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Selecting only first match with CSS document.querySelector("h2") returns only the first element that matches that class selector. Could this be done in CSS? It is not like doing: h2:first-child as this would select every <h2> that is the first element of its parent... Take for example this: <body> <h1>Title</h1> <h2>Sub</h2> <article> <h1>Title2</h1> <p>Blabla</p> <h2>Introduction</h2> <p>Blabla</p> <h2>Methods</h2> <h2>Conclusions</h2> </article> <footer> <h2>Bla</h2> </footer> </body> I know there are ways to select only that <h2> containing "Sub", but could I ask like in querySelector: get all of them and filter the first, the second or the third one...?
{ "language": "en", "url": "https://stackoverflow.com/questions/31401391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting state object dynamically using the data returned using Promise.all and fetch API : React+Typescript I am using fetch API and promise.all for a scenario where I am passing an array of URL'S from where I am fetching the data. The data retrieved from all the above URL'S needs to be set to the state object. Say I have an array of 5 URL's , the result returned by these must be assigned to the 5 different values inside my state object. Using React along with typescript. Help would be appreciated. This is what I have tried so far import * as React from 'react'; const urls = [ 'http://localhost:3001/url1', 'http://localhost:3001/url2', 'http://localhost:3001/url3', ] interface IState { test: [], result: [], returnVal: [] } export default class App extends React.Component<{},IState> { constructor(props:any) { super(props); this.state = { test: [], result: [], returnVal: [] } checkStatus(response:any) { if (response.ok) { return Promise.resolve(response); } else { return Promise.reject(new Error(response.statusText)); } } parseJSON(response:any) { return response.json(); } setData(data:any){ Object.entries(this.state).forEach(([key], index) => { this.setState({ [key]: data[index] }) }); } componentDidMount() { Promise.all(urls.map(url => fetch(url) .then(this.checkStatus) .then(this.parseJSON) .catch(error => console.log('There was a problem!', error)) )) .then(data => { this.setData(data); }) } render() { return( //some rendering code ) } } Need to set the data returned from promise to the state object variables. A: Promise.all(urls.map(url => fetch(url) .then(this.checkStatus) .then(this.parseJSON) )) .then(jsons => { var newState = {}; var index = 0; for(var key in this.state) newState[key] = jsons[index++]; this.setState(newState); })
{ "language": "en", "url": "https://stackoverflow.com/questions/55720653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Simple Function to latch_setbit_resetbit I have 32-bit MCU. The port uses 32 digital IO functionality.STM32F469/479 Series. I am looking for a sample code to Latch a particular bit/particular pin in PORTA Set/RESET function particular bit In port A. Can some one guide me on how it can be done using AND/OR/XOR operation?
{ "language": "en", "url": "https://stackoverflow.com/questions/74099604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: React - passing data between components This is my first try at a simple React application. Working with the Openweather API and AXIOS. I took Stephen Grider's course on Udemy and I'm trying to create something on my own now, but I still have problems when passing data between components. I have a SearchBar component and I'd love to be able to pass the input value to the parent component's state, so I can then update it with each search and render it into the DOM. However, I keep running into errors. I tried passing a function as a prop to my SearchBar component but I'm getting errors: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the App component. citySearch is not defined This is confusing to me, as I tried to copy the exact steps from the course, where it seems to be working just fine. But again, I'm very new to this so it is probably just me making some sort of a rookie mistake. Any tips would be much appreciated. Check my code below: App.js import React, { Component } from 'react'; import './App.css'; //Libraries import axios from 'axios'; //Components import SearchBar from './Components/search-bar'; class App extends Component { constructor(props){ super(props); this.state = { city: 'London', country: 'uk', temperature: 0, humidity: 0, pressure: 0 } //Axios call let city = this.state.city; let country = this.state.country; axios .get(`http://api.openweathermap.org/data/2.5/weather?APPID=${API_KEY}&q=${city},${country}`) .then(function(response) { this.setState({ city: response.data.name, country: response.data.name, temperature: response.data.main.temp, humidity: response.data.main.humidity, pressure: response.data.main.pressure }); }.bind(this)) .catch(function(error) { console.log(error); }); this.citySearch('London'); } citySearch(city){ this.setState({city}) } render() { return ( <div className="container"> <h1 className="display-1 text-center">Weather App</h1> <SearchBar onSearchTermChange={citySearch} /> </div> ); } } export default App; SearchBar component: import React, { Component } from 'react'; class SearchBar extends Component { constructor(props) { super(props); this.state = { city: "" }; } render() { return ( <input value={this.state.city} onChange={this.onHandleChange} className="form-control mt-3" placeholder="Enter a city name..." type="text" /> ); } onHandleChange(city) { this.setState({ city }); this.props.onSearchTermChange(city); } } export default SearchBar; A: You just setState in constructor. If you want to make a call you can put it in componentWillMount() or componentDidMount() import React, { Component } from 'react'; import './App.css'; //Libraries import axios from 'axios'; //Components import SearchBar from './Components/search-bar'; class App extends Component { constructor(props){ super(props); this.state = { city: 'London', country: 'uk', temperature: 0, humidity: 0, pressure: 0 } } citySearch(city){ this.setState({city}) } componentWillMount(){ //Axios call let city = this.state.city; let country = this.state.country; axios .get(`http://api.openweathermap.org/data/2.5/weather?APPID=${API_KEY}&q=${city},${country}`) .then(function(response) { this.setState({ city: response.data.name, country: response.data.name, temperature: response.data.main.temp, humidity: response.data.main.humidity, pressure: response.data.main.pressure }); }.bind(this)) .catch(function(error) { console.log(error); }); this.citySearch('London'); } render() { return ( <div className="container"> <h1 className="display-1 text-center">Weather App</h1> <SearchBar onSearchTermChange={citySearch} /> </div> ); } } export default App; A: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the App component. This is because of your axios call inside the constructor. Put your axios call in componentDidMount should resolve it citySearch is not defined It is because React cannot find citySearch function. You should change <SearchBar onSearchTermChange={citySearch} /> to <SearchBar onSearchTermChange={this.citySearch} /> In order to use citySearch this way, you should also bind citySearch in your constructor In summary: import React, { Component } from 'react'; import './App.css'; //Libraries import axios from 'axios'; //Components import SearchBar from './Components/search-bar'; class App extends Component { constructor(props){ super(props); this.state = { city: 'London', country: 'uk', temperature: 0, humidity: 0, pressure: 0 } this.citySearch = this.citySearch.bind(this) } componentDidMount() { //Axios call let city = this.state.city; let country = this.state.country; axios .get(`http://api.openweathermap.org/data/2.5/weather?APPID=${API_KEY}&q=${city},${country}`) .then(function(response) { this.setState({ city: response.data.name, country: response.data.name, temperature: response.data.main.temp, humidity: response.data.main.humidity, pressure: response.data.main.pressure }); }.bind(this)) .catch(function(error) { console.log(error); }); } citySearch(city){ this.setState({city}) } render() { return ( <div className="container"> <h1 className="display-1 text-center">Weather App</h1> <SearchBar onSearchTermChange={this.citySearch} /> </div> ); } } export default App; Don't call setState in your constructor, you can just initialize your state like your did. So the original setState in your constructor should be deleted. UPDATE To search again everytime you call citySearch. import React, { Component } from 'react'; import './App.css'; //Libraries import axios from 'axios'; //Components import SearchBar from './Components/search-bar'; class App extends Component { constructor(props){ super(props); this.state = { city: 'London', country: 'uk', temperature: 0, humidity: 0, pressure: 0 } this.citySearch = this.citySearch.bind(this) } componentDidMount() { axioSearch(); } axioSearch(city) { let city = city || this.state.city; let country = this.state.country; axios .get(`http://api.openweathermap.org/data/2.5/weather?APPID=${API_KEY}&q=${city},${country}`) .then(function(response) { this.setState({ city: response.data.name, country: response.data.name, temperature: response.data.main.temp, humidity: response.data.main.humidity, pressure: response.data.main.pressure }); }.bind(this)) .catch(function(error) { console.log(error); }); } citySearch(city){ this.axioSearch(city); } render() { return ( <div className="container"> <h1 className="display-1 text-center">Weather App</h1> <SearchBar onSearchTermChange={this.citySearch} /> </div> ); } } export default App; A: First, you should not make your axios calls in the constructor. The component is not yet mounted at this point. Do this in a componentDidMount to ensure that the component is already mounted. Secodly, you did not bind citySearch to the App class. So in the SearchBar component, it does not know that the citySearch Method should be called from the App class. It is advisable to do this binding in the App class constructor for optimization reasons. Lastly, I will advise you to write React in a more functional way leveraging state management frameworks like Redux or Flux The code below should work import React, { Component } from 'react'; import './App.css'; //Libraries import axios from 'axios'; //Components import SearchBar from './Components/search-bar'; class App extends Component { constructor(props){ super(props); this.state = { city: 'London', country: 'uk', temperature: 0, humidity: 0, pressure: 0 } this.citySearch = this.citySearch.bind(this); this.citySearch('London'); } citySearch(city){ this.setState({city}) } componentDidMount() { //Axios call let {city, country} = this.state; axios .get(`http://api.openweathermap.org/data/2.5/weather?APPID=${API_KEY}&q=${city},${country}`) .then(function(response) { this.setState({ city: response.data.name, country: response.data.name, temperature: response.data.main.temp, humidity: response.data.main.humidity, pressure: response.data.main.pressure }); }.bind(this)) .catch(function(error) { console.log(error); }); } render() { return ( <div className="container"> <h1 className="display-1 text-center">Weather App</h1> <SearchBar onSearchTermChange={citySearch} /> </div> ); } } export default App; For the searchBar component, you didn't bind onHandleChange in the SearchBar component. This will throw errors. You should do this in the searchBar constructor constructor() { ... this.onHandleChange = this.onHandleChange.bind(this) //Very important you do this } A: To pass data from child components to the parent component you have to use a callback method. Check this out. (About how to pass data from parent to child and child to parent). I know that I'm not touching your code here (I'm sorry), but if you're interested in a different approach this works. https://medium.com/@ruthmpardee/passing-data-between-react-components-103ad82ebd17
{ "language": "en", "url": "https://stackoverflow.com/questions/46091409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Not able to hide ARSLineProgress in iOS 15 I am new in swift and I am not able to hide ARSLineProgress in iOS 15. Its was working fine below iOS 15. My code is like this ARSLineProgress.hide() The hide() function contain public static func hide() { ars_hideLoader(ars_currentLoader, withCompletionBlock: nil) } I have download pod file from this page https://github.com/soberman/ARSLineProgress Did someone face the same issue A: This has been fixed on the following PR https://github.com/soberman/ARSLineProgress/pull/36 The fix is to add CATransaction.commit() to the hide function. This was not my work. func ars_hideLoader(_ loader: ARSLoader?, withCompletionBlock block: (() -> Void)?) { guard let loader = loader else { return } ars_dispatchOnMainQueue { let currentLayer = loader.emptyView.layer.presentation() let alpha = Double(currentLayer?.opacity ?? 0) let fixedTime = alpha * ars_config.backgroundViewDismissAnimationDuration CATransaction.begin() CATransaction.setCompletionBlock(block) let alphaAnimation = CABasicAnimation(keyPath: "opacity") alphaAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) alphaAnimation.fromValue = alpha alphaAnimation.toValue = 0 alphaAnimation.duration = fixedTime alphaAnimation.isRemovedOnCompletion = true loader.emptyView.layer.removeAnimation(forKey: "alpha") loader.emptyView.alpha = 0 loader.emptyView.layer.add(alphaAnimation, forKey: "alpha") let scaleAnimation = CABasicAnimation(keyPath: "transform") scaleAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) scaleAnimation.fromValue = CGAffineTransform(scaleX: 1, y: 1) scaleAnimation.toValue = CGAffineTransform(scaleX: ars_config.backgroundViewDismissTransformScale, y: ars_config.backgroundViewDismissTransformScale) scaleAnimation.duration = fixedTime scaleAnimation.isRemovedOnCompletion = true loader.backgroundView.layer.removeAnimation(forKey: "transform") loader.backgroundView.layer.add(scaleAnimation, forKey: "transform") CATransaction.commit() } ars_dispatchAfter(ars_config.backgroundViewDismissAnimationDuration) { ars_cleanupLoader(loader) } }
{ "language": "en", "url": "https://stackoverflow.com/questions/69750222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Getting average of sums Example collection: List<Product> list = new List<Product>(); list.Add(new Product { Id = 1, Good = 50, Total = 50 }); list.Add(new Product { Id = 2, Good = 18, Total = 30 }); list.Add(new Product { Id = 2, Good = 15, Total = 30 }); list.Add(new Product { Id = 1, Good = 40, Total = 50 }); list.Add(new Product { Id = 3, Good = 6, Total = 10 }); list.Add(new Product { Id = 1, Good = 45, Total = 50 }); list.Add(new Product { Id = 3, Good = 8, Total = 10 }); Number of products is unknown. What I need as a result is to get a percentage for each distinct product good/total, and then an average for all products. In this case: Product Id=1, GoodSum = 50 + 40 + 45 = 135, TotalSum = 50 + 50 + 50 = 150, Perc = 135/150 Product Id=2, GoodSum = 18 + 15 = 33, TotalSum = 30 + 30 = 60, Perc = 33/60 Product Id=3, GoodSum = 6 + 8 = 14, TotalSum = 10 + 10 = 20, Perc = 14/20 Avg = Avg(135/150 + 35/60 + 14/20) = Avg(0.9 + 0.55 + 0.7) = 2.15 / 3 = 7.17 Can we do this with Linq, I am only interested in Linq solution. A: Something like this? var groups = list.GroupBy(l => l.Id) .Select(g => new { Id = g.Key, GoodSum = g.Sum(i=>i.Good), TotalSum= g.Sum(i=>i.Total), Perc = (double) g.Sum(i=>i.Good) / g.Sum(i=>i.Total) } ); var average = groups.Average(g=>g.Perc); Note that your answer for Avg should be 0.717 not 7.17. A: Try this : var avg = list.GroupBy(G => G.Id) .Select(G => (G.Sum(T => T.Good)/G.Sum(T => T.TotalSum))) .Average();
{ "language": "en", "url": "https://stackoverflow.com/questions/15029707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting DIV ID on AJAX loaded content I have div with unique id and I'm trying to get that div id with jQuery <div class="quantity" id="UNIQUE_ID">Quantity</div> Everything works good, but after loading div with ajax - I just can't get id from loaded div. $('.quantity').click(function() { $.post('quantity.php', { id: $(this).attr('id') }, function(output) { $(this).html(output); }); }); Any ideas? A: This should work $('.quantity').click(function() { var that = this; $.post('quantity.php', { quantityId: $(that).attr('id') }, function(data) { $(that).html(data); }); }); But this is how i'd write it <div class="quantity" data-id='<?=$unique_id?>'> Quantity </div> $('.quantity').on('click', function() { var that = this; $.post('quantity.php', { quantityId: $(that).data('id') }, function(data) { $(that).html(data); }); }); And for dynamic divs <div class="quantity" data-id='<?=$unique_id?>'> Quantity </div> $(document).on('click', '.quantity', function() { var that = this; $.post('quantity.php', { quantityId: $(that).data('id') }, function(data) { $(that).html(data); }); }); A: The onclick binding to your div won't work once the div has been refreshed (it binded on document.ready() right?). The solution will be either to rebind the function to your element every time you change it (a bad one) or use the on() function of jquery. Example code: $(document).on('click', '.quantity', function(){ var id = $(this).attr('id'); $.post('quantity.php', { quantityId: id }, function(data){ $('#'+ id).html(data); }); }); UPDATE: As discussed in comments, the on method should bind to the document as a whole and not the the class to actually work as the deprecated live() method.
{ "language": "en", "url": "https://stackoverflow.com/questions/17516572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Align text below input I have a text-input with a list below. I now want the list to start exactly under the input on the left side. Here is a jsFiddle. CSS / HTML / Demo body { text-align: center; } #underbox li { display: inline-block; text-decoration: underline; } <input type="text" style="width: 200px;" /> <ul id="underbox"> <li>Test</li> <li>Next</li> </ul> A: Change your styles to: body{ text-align: center; } input { width: 200px; } ul { text-align: left; margin: 0 auto; padding: 0; width: 200px; } #underbox li{ display: inline-block; text-decoration: underline; } input and ul => same width / ul => text-align: center; margin: 0 auto (for set position to center); padding: 0 (disable default style); jsfiddle A: something like this: #underbox { width: 200px; margin: 0 auto; padding: 0; list-style-type: none; } #underbox li { margin-right: 5px; text-decoration: underline; text-align: left; float: left; } A: Try to add style to the ul element like that: http://jsfiddle.net/csdtesting/j6f8L7Lp/ body { text-align: center; } #underbox li { display: inline-block; text-decoration: underline; } ul#underbox { padding: 0; list-style-type: none; margin: 0; } <input type="text" style="width: 200px;" /> <ul id="underbox"> <li>Test</li> <li>Next</li> </ul>
{ "language": "en", "url": "https://stackoverflow.com/questions/26196529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Create -help- module for web application What is the best solution for create and merge help for my web application , I want create HTML help for entire solution and help for each page, Is there any module for this purpose? A: You can use SandCastle. It is now maintained as part of SandCastle Help File Builder or SHFB. http://shfb.codeplex.com/ SandCastle depends on Microsoft Help Workshop, which you have to download separately. If you want to just create your own help system and not product API documentation, then just use the HTML Help Workshop on its own. It very simple, to use. Just create HTML pages for each help section and compile. Read the documentation. HTML Help is also available as part of the Visual Studio SDK. Reference: http://msdn.microsoft.com/en-us/library/windows/desktop/ms670169(v=vs.85).aspx Download: http://www.microsoft.com/en-us/download/details.aspx?id=21138 Important: As of March 2012 there is no HTML Help Workshop 1.4. VS 2010 doesn't use MS Help2 format so there is no Help2 compiler available for it. Starting with VS 2010, the new MS Help Viewer format is used. Reference: http://msdn.microsoft.com/en-us/library/vstudio/hh492077.aspx MS Help Viewer SDK for Visual Studio: http://msdn.microsoft.com/en-us/library/dd627473.aspx Hope that helps. I would suggest you to use SandCastle (SHFB), because you get best of all worlds. You can create compiled HLP2 files, Help Viewer Content and also a simple online HTML help.
{ "language": "en", "url": "https://stackoverflow.com/questions/18051048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Any C++ library for Johansen co-integration test? Any Ideas ? Will be highly appreciated. A: Assuming you mean this test, I think I found a library that will help you. Check out the Gnu Regression, Econometrics and Time-series Library.
{ "language": "en", "url": "https://stackoverflow.com/questions/2827600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Swift dismissing view with clunky animation I simply have a ViewController that I would like to dismiss. And this is my dismissAction: @objc private func dismissView(){ self.dismiss(animated: true, completion: nil) UserDefaultsService.shared.updateDataSourceArrayWithWishlist(wishlist: self.wishList) let dataSourceArray = UserDefaultsService.shared.getDataSourceArray() // update datasource array in MainVC self.dismissWishlistDelegate?.dismissWishlistVC(dataArray: dataSourceArray, dropDownArray: self.dropOptions, shouldDeleteWithAnimation: false, wishlistToDelete: self.wishList) } Proble: The dismiss animation is very clunky and not fluent at all. I found out that if I remove everything in the function but only call self.dismiss it is working perfectly fine. What is the issue here? Any idea on how I can fix this? A: You can try to light-weight load in main thread by DispatchQueue.global().async { UserDefaultsService.shared.updateDataSourceArrayWithWishlist(wishlist: self.wishList) } And instead of let dataSourceArray = UserDefaultsService.shared.getDataSourceArray() use self.wishList directly in the last line
{ "language": "en", "url": "https://stackoverflow.com/questions/65957998", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Update recyclerview on Edittext text change I have a Edittext and a recyclerview below it in fragment. The recyclerview row item has a textview. I have set the adapter and everything is working fine. I would like to change each item of the recyclerview with text in edittext and somehow it's not working. I tried with itemArrayAdapter.notifyDataSetChanged() on getListForRv() method. @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_fonts, container, false); itemList = new ArrayList<FontItem>(); EditText editText = view.findViewById(R.id.edit_text); itemArrayAdapter = new ItemArrayAdapter(R.layout.recyclerview_item, itemList); recyclerView = (RecyclerView) view.findViewById(R.id.font_list); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(itemArrayAdapter); getListForRv(10); editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { getListForRv(90); } @Override public void afterTextChanged(Editable s) { getListForRv(90); } }); return view; } private void getListForRv(int k) { for (int i = k; i < 1000; i++) { itemList.add(new FontItem("Item " + i)); } itemArrayAdapter.notifyDataSetChanged(); } A: call your getListForRv() on edit text afterTextChanged methode. A: notifyDataSetChanged will refresh all itemview, if you want to synchronize all edittext I have two solution: * *databinding : you can use ObservableField *Create a listener and make sure all item keep the listener,when editext was changed, call the listener then all itemview will accept the change A: Finally I managed to solve this by doing the following, don't know if it's a bad practice but works for me: @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_fonts, container, false); itemList = new ArrayList<FontItem>(); EditText editText = getActivity().findViewById(R.id.edit_text); itemArrayAdapter = new ItemArrayAdapter(R.layout.recyclerview_item, itemList); recyclerView = (RecyclerView) view.findViewById(R.id.font_list); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(itemArrayAdapter); getListForRv(10); editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(itemArrayAdapter); getListForRv(90); itemArrayAdapter.notifyDataSetChanged(); } @Override public void afterTextChanged(Editable s) { } }); return view; } private void getListForRv(int k) { if (!itemList.isEmpty()) itemList.clear(); for (int i = k; i < 1000; i++) { itemList.add(new FontItem("Item " + i)); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/58555152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Why my pycharm can not debug forever? My computer version is Win7. And what ever .py I debug, this pycharm will show me en error like this: ValueError: bad marshal data (string ref out of range) So what's wrong with pycharm, I tried to user newest version of pycharm but I helpless, the same error will show again. I used to reinstall my win7 (becauser I have Shadow Mode software) and it work for a period. Is there body have a good solution? A: I don't think the problem is directly related to the pydev debugger in this case... my bet is that for some reason you're having corrupted .pyc files (don't know why thought). Try cleaning your .pyc files from your pycharm installation and your own files and run it again (you may try running with pydev which has the same debugger backend if you want to see if you reproduce the issue there).
{ "language": "en", "url": "https://stackoverflow.com/questions/37177675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: In React, what is a better place to store big data arrays? I'm building an interactive plot in React where the user can select multiple variables and add them to a single plot. Each of these "variables" represent scientific data and are stored as arrays with 100k to 3 million elements. I don't feel very inclined to store these variables in the React state as their contents never change and I'd prefer to control when the UI needs to re-render manually instead of letting React automagically traverse these arrays trying to find out if they have changed, which renders my application unresponsive. Is there any preferred way of storing this data and sharing it with React? Right now I just store everything in a global variable. A: There aren't many places you can store it though. If the data never changes, there's no downside in storing it in state, no changes means no re-renders. It sounds like there's quite a bit of it, so you can't store it in local storage due to limits. If you build a data set inside React by doing a bunch of API calls, revisit the API itself - it should return the data you care for, rarely a bunch of data segments you have to splice together yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/54372576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Proxy in development mode of React won't redirect I'm building an app with create-react-app. I have local Apache server running on port 80 to execute my backend API PHP scripts. I have added "proxy": "http://localhost:80" to my package.json, but on this axios requests: getAllCategories = () => { const url = process.env.PUBLIC_URL+`/api/api/categories/categories.php`; axios.get(url) .then(res => { const categories = res.data.data; this.setState({ categories }); }).catch(err => { console.log('Axios fetch error:',err); }) } My request are directed to Request URL: http://localhost:3000/api/api/categories/categories.php according to Chrome Devtools and I'm not getting the data required. In the build mode on remote server everything works fine with those paths indicated. How can I configure proxy in dev mode to access my API files? A: Have you tired path like this? axios.get(`/api/api/categories/categories.php`) ... A: If you are using create-react-app install http-proxy-middleware as a dev dependency and in your src folder create a file called setupProxy.js (it must be spelt exactly like that). In that file: const proxy = require('http-proxy-middleware'); module.exports = function(app) { app.use(proxy('/api', { target: 'http://localhost:80' })); }; You will need to restart the app for it to take effect. Your api calls should not need the process.env
{ "language": "en", "url": "https://stackoverflow.com/questions/57242270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Update table field by summing field from another table I am trying to update a table filed taking value from another table by summing a field based on EmpID. In tblEmpInfo EmpID is primary key. I have saw few post on this site but couldn't adopt to my file. Here is my code till yet. UPDATE tblEmpInfo AS c INNER JOIN (SELECT EmpID, SUM(ProfidentFund) AS total FROM tblTransactions GROUP BY EmpID) AS x ON c.EmpID = x.EmpID SET c.ProfidentFund = x.total; Above code give me following warning and do not update value to tblEmpInfo tblEmpInfo screenshot. tblTransactions screenshot. And my expected output. A: You can try the below - UPDATE c SET c.ProfidentFund = x.total from tblEmpInfo AS c INNER JOIN (SELECT EmpID, SUM(ProfidentFund) AS total FROM tblTransactions GROUP BY EmpID) AS x ON c.EmpID = x.EmpID
{ "language": "en", "url": "https://stackoverflow.com/questions/62929358", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Self Join using a Group By clause getting "Invalid Identifier" error I'm trying to put together a Self Join using a Group By clause to see which person is getting paid the highest in their respective jobs but I keep getting this error 00904. 00000 - "%s: invalid identifier" Below is my code that I am currently trying to fix: Select a.*,b.sal From EMP a,(Select job,MAX(sal) From EMP Group By job) b Where a.empno = b.empno I did some research and I couldn't find anything that pertained to what I am doing (maybe becayse what I am doing is too simple?) but nonetheless I am looking for anything that will point me in the right direction. Thanks in advance. A: You don't have a column called empno that you are returning in the subquery. I think you want something like this which will return the max(sal) for each employee based on the job: Select a.*, b.sal From EMP a inner join ( Select job, MAX(sal) sal From emp Group By job ) c on a.job = b.job A: Try this instead: Select a.* From EMP a INNER JOIN ( Select job, MAX(sal) MaxSal From EMP Group By job ) b ON a.job = b.job AND a.sal = b.MaxSal
{ "language": "en", "url": "https://stackoverflow.com/questions/13883249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: findViewById retrurns wrong element? I can't understand why findViewById returns the wrong element, here is the class: public class EventDetailsFragment extends FragmentActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.event_details); Log.d("First", findViewById(R.id.tuxtView1).getClass().toString()); Log.d("Second", findViewById(R.id.tuxtView2).getClass().toString()); Log.d("Third", findViewById(R.id.imageView1).getClass().toString()); } } And here is the xml: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/green" android:orientation="horizontal" android:paddingLeft="10dp" android:paddingRight="10dp" android:paddingTop="10dp"> <RelativeLayout android:id="@+id/relativeLayout1" android:layout_width="0dp" android:layout_height="175dp" android:layout_gravity="center_horizontal" android:layout_weight="1" android:background="#fff" android:gravity="right" > <ImageView android:id="@+id/imageView1" android:layout_width="110dp" android:layout_height="match_parent" android:layout_weight="1" android:src="@drawable/ic_event_image" /> <TextView android:id="@+id/tuxtView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginTop="10dp" /> <TextView android:id="@+id/tuxtView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/tuxtView2" android:layout_toRightOf="@+id/imageView1" android:textColor="#555" android:textSize="20dp" /> </RelativeLayout> </LinearLayout> The logcat ouput is: 12-26 23:43:20.249: D/First(6789): class android.widget.TextView 12-26 23:43:20.249: D/Second(6789): class android.widget.ImageView 12-26 23:43:20.249: D/Third(6789): class android.widget.TextView So the point is, why do I get a imageview with id R.id.tuxtView2 and a textview with id R.id.imageView1. The application crashes if I want to assign a text value to R.id.tuxtView2, casted as a TextView. A: Try to reload your project, maybe something wrong with R.java, or verify you are calling the good file with setContentView. By refreshing/cleaning your project the R.java file will be reloaded and will find the named widgets. A: I copied your code and made a dummy app. I got these results: 12-27 00:03:48.332: D/First(9165): class android.widget.TextView 12-27 00:03:48.332: D/Second(9165): class android.widget.TextView 12-27 00:03:48.332: D/Third(9165): class android.widget.ImageView Apparently there is nothing wrong with the code A: I've tried almost everything here, but nothing worked until I added a new component to the activity and, after running, noticing that the new component didn't show. It suggested my app wasn't updating with the runs. It worked by manually uninstalling the old version of the app an then running again.
{ "language": "en", "url": "https://stackoverflow.com/questions/8639667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: strange Java compilation error with typed interface I have come across a very strange compilation error. At first I thought it was a bug in IntelliJ, but now I've tried with Eclipse and see the same thing. I have the following interface: public interface PluginDriver<T extends Plugin> { PluginBuilder<T> getBuilder(); Set<PluginParam> getParams(); Set<String> getStrings(); } where Plugin is an abstract class: public abstract class Plugin and we also have a POJO as follows: public class PluginParam { ... } Now I have a DriverManager to return an instance of a PluginDriver, and here I will try to use that: PluginDriver driver = DriverManager.getDriver(transformer.getPlugin()); PluginBuilder builder = driver.getBuilder(); for (PluginParam o : driver.getParams()) { //type mismatch - cannot convert from element type Object to PluginParam } for (String s : driver.getStrings()) { //type mismatch: cannot convert from element type Object to String } The for loop commands don't compile, for reasons that I don't understand. The interface specifies concrete return types for those methods, not type T. Now, if I change the following line: PluginDriver<Plugin> driver = DriverManager.getDriver(transformer.getPlugin()); everything suddenly plays nicely. Similarly, if I remove the type arguments from the interface, it will work. I could understand that the getBuilder() method might not work if we hadn't correctly typed the PluginDriver. But how could it possibly complain about the getStrings() method? ==EDIT This is not a duplicate of Combining Raw Types and Generic Methods, since that question refers to a method with typed parameters. The method I'm asking about is untyped. A: The JLS says, "The type of a constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) of a raw type C that is not inherited from its superclasses or superinterfaces is the raw type that corresponds to the erasure of its type in the generic declaration corresponding to C." http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.8 When you declared a variable of the raw interface type, you forced the member methods to have raw types also. That's what screwed up the class cast. The documentation rules. A: Here: PluginDriver driver = DriverManager.getDriver(transformer.getPlugin()); You are creating a raw type. Bad idea. Can lead to all sorts of problems - see here. Thus the answer is simple: never do that! When you are using generic types, then make sure that you have a "generic" on (one/both) sides of your declaration/definition!
{ "language": "en", "url": "https://stackoverflow.com/questions/42483366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change the colors of xdebug output? The red and yellow standard colors of xdebug can hurt your eyes after a few hours. http://www.designified.com/blog/article/76/restyling-xdebug-output describes how to replace the style with javascript requiring jquery. I was looking for a more straight forward way and finally found one. A: The solution is the !important tag, it overrides the existing style values. Use the following css code to avoid eye cancer when using xdebug: .xdebug-error { font-size: 12px !important; width: 95% !important; margin: 0 auto 10px auto !important; border-color: #666 !important; background: #ddd !important; } .xdebug-error th, .xdebug-error td { padding: 2px !important; } .xdebug-error th { background: #ccc !important; } .xdebug-error span { display: none !important; } .xdebug-error_description th { font-size: 1.2em !important; padding: 20px 4px 20px 100px !important; background: #ccc no-repeat left top !important; } .xdebug-error_callStack th { background: #666 !important; color: #ddd !important; } A: Have a nice xdebug! Yes you can. Try this css below. table.xdebug-error { width: auto; background: white; border: none; border-spacing: none; border-collapse: collapse; box-shadow: 0px 3px 10px 0px black; position: fixed; top: 0px; right: 0px; z-index: 8888; font: 14px verdana; transform-origin: top right; transform: scaleX(0.4); opacity: 0.3; transition: all 200ms ease; } table.xdebug-error caption, table.xdebug-error th, table.xdebug-error td { text-align: left; vertical-align: middle; } table.xdebug-error a img { border: 0; } table.xdebug-error :focus { outline: 0; } table.xdebug-error pre { margin: 0; } table.xdebug-error tbody tr td, table.xdebug-error tbody tr th { border: none; border-bottom: 1px solid rgba(0,0,0,0.2); font-weight: normal; } table.xdebug-error tbody tr td { padding: 3px !important; vertical-align: top; } table.xdebug-error tbody tr th { padding: 13px !important; } table.xdebug-error tbody tr td:nth-of-type(1) { width: 5% !important; } table.xdebug-error tbody tr th[bgcolor='#f57900'] { font-weight: normal; background: steelblue; color: white; } table.xdebug-error tbody tr th[bgcolor='#f57900'] span { display: none; } table.xdebug-error tbody tr font[color='#00bb00'] { color: #005e00; } table.xdebug-error tbody tr td small { display: none; } table.xdebug-error tbody tr td i { padding-left: 12px; } table.xdebug-error:hover { transform: none; opacity: 1; } CONS: * *Depending on your other css defs, you may have to fiddle a bit until it looks as promised. *It's not as beautiful as a Laravel/Symfony error PROS: * *You can see the actual page, despite the error. (Message will be dimmed and pushed on the right side, appearing on mouse hover.) *It's nothing more than CSS *You can even add it to your page via CSS Live Editor Plugin or something similar; therefore, no need to add to your own code *It won't break your styling, won't stuff a whole lot of text into a tiny container where the error happened, etc. - because it's position:fixed. *Pleasant to the eye - you'll end up throwing errors just to see it again :) A: Another option is to disable xdebug from overloading var_dump. In the php.ini [XDebug] section add xdebug.overload_var_dump=0 Formatting the output is then up to you; one such way could be wrapping var_dump in your own debug function that prints <pre> tags. A: // notice the line height, the padding(cellspacing), monospace font, font size, making readability better at least for me. // // A FILENAME : xdebug_stack_trace.css // // This is how the xdebug_stack_trace.css is called from the index.php page // // &lt;style&gt;&lt;?php require_once("./resources/css/xdebug_stack_trace.css");?&gt;&lt;/ style&gt; // // notice that on the line above there is a space between the slash // and the 'style', on the ending 'style' tag, otherwise the display // get all messed up when this page gets loaded. // // make sure that when you copy the 'style' line from here to the // index page, that you remove the extra space at the ending 'style' // tag of the index page. // +---------+---------+---------+---------+---------+---------+---------+ // orange/black td header line // +---------+---------+---------+---------+---------+---------+---------+ .xdebug-error th { font-family:monospace; font-weight:normal; font-size:15px; padding: 6px 6px 6px 6px; border:1px solid black; background: #FFCC99; // orange color:#000000; // black } // +---------+---------+---------+---------+---------+---------+---------+ // black/white th header line // +---------+---------+---------+---------+---------+---------+---------+ .xdebug-error > tr:first-child > th:first-child, .xdebug-error > tbody > tr:first-child > th:first-child { line-height:1.6em; padding: 10px 10px 10px 10px; border:1px solid #000000; background: #000000; // black color:#FFFFFF; } // +---------+---------+---------+---------+---------+---------+---------+ // green/black td content one or more lines // +---------+---------+---------+---------+---------+---------+---------+ .xdebug-error td { font-size:14px; padding: 6px 6px 6px 6px; border:1px solid green; background: #D1FFE8; // light green } // +---------+---------+---------+---------+---------+---------+---------+
{ "language": "en", "url": "https://stackoverflow.com/questions/19405735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why Azure takes so long to setup a Load Balancer? I have set up an application gateway in almost five different regions in Azure and every time Azure take around 15-20 mins to complete the setup. Whereas AWS will do it in a couple of minutes, why Azure requires such a long time? A: You should try using Application Gateway V2, its a lot faster to create. updates are almost instantaneous (well, at least compared to V1). But I believe V1 is using windows VM's underneath, so it creates a set of vms for you, then it configures them. Each update would be a "sliding window" update, with 1 vm being recreated at a time. As far as I know. A: Application Gateway is a layer 7 load balancer which, as far as I understand, is a Windows VM (or collection of Windows VMs, depending on selected size) under the covers, which take some time to come up and be configured. In my experience, this time is usually around 15-30 minutes, depending on region and local time of day, capacity, etc. Azure Load balancers on the other hand are layer 4 load balancers, which typically take in the order of 1-2 minutes to come up. A: So, yes talking about the load balancer if you say it normally takes less than a minute to get deployed. But coming onto the Application gateway yeah it takes 15-20 minutes every time the reason being: * *Configuration Settings: Microsoft has the set of the vacant load balancers ready at their backend and when they receive a request to deploy a particular load balancer in any region, they just assign it an IP as requested by the user and it gets deployed within a minute. But coming onto the Application gateway, azure need to start deploying the load balancer [App Gateway in this case] from the scratch, need to attach it to the VNET so deployed and making it ready for the backend pools IP Address configuration and all, which basically take time about [15-20 minutes]. Now, Azure has brought up the V2 of the Application Gateway, a lot faster to create usually 5 minutes. And also talking about updates they are also really quick and instantaneous. *Subscriptions: Secondly, the reason that it takes time is subscription. Suppose, you have the MSDN, free subscription in your Azure account. And another individual sitting at any different place is using the enterprise applications subscription [basically a pay as you go] in his azure account. Now, both of you raise a request to deploy an Application gateway in the same region at the same time then, Microsoft will give the person request with the enterprise subscription the higher priority than your free subscription request. Which is another reason that it results in a delay. As I am using the enterprise edition so it takes 2 minutes for a VM to deploy which gets deployed in 5-6 minutes if using the free subscription! Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/56679772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to use transactions in DotNetNuke? I'm trying to do the most simple thing and apply a transaction to the CreatePortal method. If I'm using TransactionScope - It promotes to DTC for some unknown reason - BAD. using (var ts = new TransactionScope()) { var portalController = new PortalController(); var portalId = portalController.CreatePortal( "TESTTESTTEST", string.Empty, string.Empty, "TESTTESTTEST_" + new Random().Next(999999), UserController.GeneratePassword(), "TESTTESTTEST_" + new Random().Next(999999) + "@something.com", string.Empty, string.Empty, Globals.ApplicationMapPath + "/Portals/_default/", "Default Website.template", "Portals/TESTTEST", "TESTTESTTEST", string.Empty, string.Empty, false); ts.Complete(); } If I'm using DataProvider.Instance().GetTransaction and performs RollbackTransaction at the end - IT DOES NOT ROLLBACK, which means that the transaction didn't even work. var t = Data.DataProvider.Instance().GetTransaction(); var portalController = new PortalController(); var portalId = portalController.CreatePortal( "TESTTESTTEST", string.Empty, string.Empty, "TESTTESTTEST_" + new Random().Next(999999), UserController.GeneratePassword(), "TESTTESTTEST_" + new Random().Next(999999) + "@something.com", string.Empty, string.Empty, Globals.ApplicationMapPath + "/Portals/_default/", "Default Website.template", "Portals/TESTTEST", "TESTTESTTEST", string.Empty, string.Empty, false); Data.DataProvider.Instance().RollbackTransaction(t); So, How to use transactions in DotNetNuke? A: When you create a transaction through the GetTransaction method, the DataProvider just creates a new connection and gives you the transaction. You would then need to manually use that transaction to perform whatever action you're going to take against the database. There isn't a way to pass that transaction so that it gets used by, for example, CreatePortal, or any other built-in DNN function. That functionality appears to be just for any additional database access you might make. In terms of how to wrap a call from the DNN core in a transaction, I don't think you can. The cleanest solution I know to recommend (which, unfortunately, still isn't very clean) is to manually call the stored procedure, using a transaction, rather than going through the controller class. What's your use case, maybe I can recommend a solution that solves the problem some other way... A: I was able to use Transactions in DNN with the help of this article. It doesn't apply to your case, but will help others trying to leverage transactions in DNN.
{ "language": "en", "url": "https://stackoverflow.com/questions/1478612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Azure Mobile Service Single Sign on Microsoft Account I have implemented single sign on using the WL api, but I only recently realized that I need to call mobileService.login on top of that to use the nice authentication features of Azure Mobile Services. I followed this tutorial http://www.windowsazure.com/en-us/develop/mobile/tutorials/single-sign-on-windows-8-js/#add-authentication and added this piece of code: var login = function () { return new WinJS.Promise(function (complete) { WL.init(); WL.login({ scope: ["wl.signin", "wl.basic", "wl.birthday", "wl.emails"] }).then(function (result) { session = result.session; WinJS.Promise.join([ WL.api({ path: "me", method: "GET" }), mobileService.login("microsoftaccount", session.authentication_token) ]).done(function (results) { var profile = results[0]; var mobileServicesUser = results[1]; var title = "Welcome " + profile.first_name + "!"; var message = "You are now logged in as: " + mobileServicesUser.userId; var dialog = new Windows.UI.Popups.MessageDialog(message, title); dialog.showAsync().done(complete); }); }, function (error) { session = null; var dialog = new Windows.UI.Popups.MessageDialog("You must log in.", "Login Required"); dialog.showAsync().done(complete); }); }); } however on this line mobileService.login("microsoftaccount", session.authentication_token) my session.authentication_token is undefined. (I have an access_token) If I don't pass the token, I am prompted to sign in every time I launch the app, which defeats the purpose of the integrated sign on. Any ideas? A: To get the authentication token, you need to pass the redirect URI to the call to WL.init: WL.init({ redirect_uri: "<< INSERT REDIRECT DOMAIN HERE >>" }); Where the redirect domain must be the same as the one in your Live Connect application.
{ "language": "en", "url": "https://stackoverflow.com/questions/15013213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Axios promise value render always 'undefined' Inside a componentDiMount function of a child component, I'm using an external function (getResults) to populate a state value. This getResults function, call an external API with axios. Here is my code: componentDidMount() { const cluster = '...'; const index= '...'; const field= '...'; const paragraphs = uuids.map(uuid => { // Get the results. getResults(cluster, index, field, uuid, 'source') .then(results => { // Get value with console.log OK. console.log(results); // Return a undefined value... return results; }) .catch(error => { console.error(error); }); }); After reading many, many posts I see that my problem seems to be the axios delay to generate the results. To resolve my problem, I have tested many solutions without success: check the rendered value in the render section... How can I resolve this problem? Do I modify an element in the componentDiMount function or directly in the external getResults function ? Thanks for your help. A: Normally, in an axios request, the data comes in results.data Also, because you don't return anything inside .map, it will just be an array of undefined. You need to return inside .map componentDidMount() { const cluster = '...'; const index= '...'; const field= '...'; const paragraphs = uuids.map(uuid => { // Get the results. // ADDED RETURN INSIDE .map return getResults(cluster, index, field, uuid, 'source') .then(results => { // Get value with console.log OK. console.log(results); // Return a undefined value... return results; }) .catch(error => { console.error(error); }); }); And if you want to get the data from paragraphs, you need to use Promise.all or async/await for it to work.
{ "language": "en", "url": "https://stackoverflow.com/questions/60298620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP Composer autoload not working, no classes initiated I'm trying to use Composer within PHP. I've installed composer within my project directory, then installed some needed PHP classes/methods with cli: php composer.phar require ahsankhatri/firestore-php php composer.phar require guzzlehttp/guzzle Great, this worked fine! After installing succesfully, I optimized the lockfile with: php composer.phar dump-autoload --optimize 101 classes where added (cli returned this message). Now I added the autoloader to my PHP file, I thought this would be easy... just add the autoload.php <?php require 'vendor/autoload.php'; //print_r(get_declared_classes()); $firestoreClient = new FirestoreClient('Dimo-233713', ' AIzaSyCNHz_EbF13KuAvEnlBIto_2n1eIqkCnzk', [ 'database' => 'test', ]); But, when I run this script on my XAMPP, the PHP log says: [28-Mar-2019 13:27:33 Europe/Berlin] PHP Fatal error: Uncaught Error: Class 'FirestoreClient' not found in /Users/***/Documents/Websites/xampp/domare.nl/htdocs/subdomains/portal/firestore.php:6 Stack trace: #0 {main} thrown in /Users/***/Documents/Websites/xampp/domare.nl/htdocs/subdomains/portal/firestore.php on line 6 Class cannot be found. I dumped all classes as you can see at the commented line. But there is no class loaded I requested with composer. Not one of the 101 classes... What is wrong here? Working with PHPStorm. Running on XAMPP with PHP7.2.4 And here is the Composer.json file { "require": { "guzzlehttp/guzzle": "^6.3", "ahsankhatri/firestore-php": "^2.0" } } And this is the composer.lock file's json { "_readme": [ "This file locks the dependencies of your project to a known state", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], "content-hash": "caedd171718e9452e0e742dcd84f2235", "packages": [ { "name": "ahsankhatri/firestore-php", "version": "v2.0.1", "source": { "type": "git", "url": "https://github.com/ahsankhatri/firestore-php.git", "reference": "ecdd92bdcb3f00c0b94e0e1909ac104fe20b1eb8" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/ahsankhatri/firestore-php/zipball/ecdd92bdcb3f00c0b94e0e1909ac104fe20b1eb8", "reference": "ecdd92bdcb3f00c0b94e0e1909ac104fe20b1eb8", "shasum": "" }, "require": { "ext-curl": "*", "ext-json": "*", "guzzlehttp/guzzle": "~6.0|~5.0|~4.0", "php": ">=5.6.6" }, "require-dev": { "phpunit/phpunit": "5.7" }, "type": "library", "autoload": { "psr-4": { "MrShan0\\PHPFirestore\\": "src" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Ahsaan Muhammad Yousuf", "email": "ahsankhatri1992@gmail.com", "homepage": "https://ahsaan.me", "role": "Developer" } ], "description": "Firestore PHP Client", "homepage": "https://github.com/ahsankhatri/firestore-php", "keywords": [ "firebase", "firestore", "google", "php" ], "time": "2019-02-25T13:27:14+00:00" }, { "name": "guzzlehttp/guzzle", "version": "6.3.3", "source": { "type": "git", "url": "https://github.com/guzzle/guzzle.git", "reference": "407b0cb880ace85c9b63c5f9551db498cb2d50ba" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/guzzle/guzzle/zipball/407b0cb880ace85c9b63c5f9551db498cb2d50ba", "reference": "407b0cb880ace85c9b63c5f9551db498cb2d50ba", "shasum": "" }, "require": { "guzzlehttp/promises": "^1.0", "guzzlehttp/psr7": "^1.4", "php": ">=5.5" }, "require-dev": { "ext-curl": "*", "phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.4 || ^7.0", "psr/log": "^1.0" }, "suggest": { "psr/log": "Required for using the Log middleware" }, "type": "library", "extra": { "branch-alias": { "dev-master": "6.3-dev" } }, "autoload": { "files": [ "src/functions_include.php" ], "psr-4": { "GuzzleHttp\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Michael Dowling", "email": "mtdowling@gmail.com", "homepage": "https://github.com/mtdowling" } ], "description": "Guzzle is a PHP HTTP client library", "homepage": "http://guzzlephp.org/", "keywords": [ "client", "curl", "framework", "http", "http client", "rest", "web service" ], "time": "2018-04-22T15:46:56+00:00" }, { "name": "guzzlehttp/promises", "version": "v1.3.1", "source": { "type": "git", "url": "https://github.com/guzzle/promises.git", "reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/guzzle/promises/zipball/a59da6cf61d80060647ff4d3eb2c03a2bc694646", "reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646", "shasum": "" }, "require": { "php": ">=5.5.0" }, "require-dev": { "phpunit/phpunit": "^4.0" }, "type": "library", "extra": { "branch-alias": { "dev-master": "1.4-dev" } }, "autoload": { "psr-4": { "GuzzleHttp\\Promise\\": "src/" }, "files": [ "src/functions_include.php" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Michael Dowling", "email": "mtdowling@gmail.com", "homepage": "https://github.com/mtdowling" } ], "description": "Guzzle promises library", "keywords": [ "promise" ], "time": "2016-12-20T10:07:11+00:00" }, { "name": "guzzlehttp/psr7", "version": "1.5.2", "source": { "type": "git", "url": "https://github.com/guzzle/psr7.git", "reference": "9f83dded91781a01c63574e387eaa769be769115" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/guzzle/psr7/zipball/9f83dded91781a01c63574e387eaa769be769115", "reference": "9f83dded91781a01c63574e387eaa769be769115", "shasum": "" }, "require": { "php": ">=5.4.0", "psr/http-message": "~1.0", "ralouphie/getallheaders": "^2.0.5" }, "provide": { "psr/http-message-implementation": "1.0" }, "require-dev": { "phpunit/phpunit": "~4.8.36 || ^5.7.27 || ^6.5.8" }, "type": "library", "extra": { "branch-alias": { "dev-master": "1.5-dev" } }, "autoload": { "psr-4": { "GuzzleHttp\\Psr7\\": "src/" }, "files": [ "src/functions_include.php" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Michael Dowling", "email": "mtdowling@gmail.com", "homepage": "https://github.com/mtdowling" }, { "name": "Tobias Schultze", "homepage": "https://github.com/Tobion" } ], "description": "PSR-7 message implementation that also provides common utility methods", "keywords": [ "http", "message", "psr-7", "request", "response", "stream", "uri", "url" ], "time": "2018-12-04T20:46:45+00:00" }, { "name": "psr/http-message", "version": "1.0.1", "source": { "type": "git", "url": "https://github.com/php-fig/http-message.git", "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363", "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363", "shasum": "" }, "require": { "php": ">=5.3.0" }, "type": "library", "extra": { "branch-alias": { "dev-master": "1.0.x-dev" } }, "autoload": { "psr-4": { "Psr\\Http\\Message\\": "src/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "PHP-FIG", "homepage": "http://www.php-fig.org/" } ], "description": "Common interface for HTTP messages", "homepage": "https://github.com/php-fig/http-message", "keywords": [ "http", "http-message", "psr", "psr-7", "request", "response" ], "time": "2016-08-06T14:39:51+00:00" }, { "name": "ralouphie/getallheaders", "version": "2.0.5", "source": { "type": "git", "url": "https://github.com/ralouphie/getallheaders.git", "reference": "5601c8a83fbba7ef674a7369456d12f1e0d0eafa" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/5601c8a83fbba7ef674a7369456d12f1e0d0eafa", "reference": "5601c8a83fbba7ef674a7369456d12f1e0d0eafa", "shasum": "" }, "require": { "php": ">=5.3" }, "require-dev": { "phpunit/phpunit": "~3.7.0", "satooshi/php-coveralls": ">=1.0" }, "type": "library", "autoload": { "files": [ "src/getallheaders.php" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Ralph Khattar", "email": "ralph.khattar@gmail.com" } ], "description": "A polyfill for getallheaders.", "time": "2016-02-11T07:05:27+00:00" } ], "packages-dev": [], "aliases": [], "minimum-stability": "stable", "stability-flags": [], "prefer-stable": false, "prefer-lowest": false, "platform": [], "platform-dev": [] }
{ "language": "en", "url": "https://stackoverflow.com/questions/55398103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Inserting a new node at the beginning of a linked list in C The struct looks like this: typedef char AirportCode [4]; typedef struct node { AirportCode airport; struct node *next; }Node; My function looks like this: void insertFirst(AirportCode code, Node **listPtr){ Node *Holder = *listPtr; Node *newNode = (Node *)malloc(sizeof(Node)); if (*listPtr == NULL){ (*listPtr)->airport = code; (*listPtr)->next = NULL; } else{ *listPtr = newNode; newNode->airport = code; newNode->next = holder; } } The error message is: incompatible types when assigning to type 'AirportCode' from type 'char *' This error message is on both of the lines where I assign the code values. A: The problem is that you can't assign arrays in C. You can only initialize them. Also, you can't pass an array to a function - what actually gets passed is a pointer to the first element of the array. The following statement typedef char AirportCode[4]; defines a type AirportCode of type char[4] - an array of 4 characters. In your function insertFirst, you are assigning code which is of type char * to (*listPtr)->airport which is of type AirportCode or char[4]. These two are incompatible types and hence you are getting the error. Since you can't pass an array to a function, what you should do is pass a pointer to the first element of the array and the array length as well. Then copy the array to the corresponding member of the structure. The below three declarations are exactly the same. The array parameter in the function is actually a pointer to a character. void insertFirst(AirportCode code, Node **listPtr); void insertFirst(char code[4], Node **listPtr); void insertFirst(char *code, Node **listPtr); Also, you should not cast the result of malloc. Don't let the typedef clutter the namespace and cause confusion. You are better off without it in this case. If the if condition *listPtr == NULL is true, then you are dereferencing the null pointer in the block which is obviously an error. if(*listPtr == NULL) { // the below statements dereference the null pointer // which is an error and would cause program crash // due to segfault. (*listPtr)->airport = code; (*listPtr)->next = NULL; } From your else block, I assume you are trying to add a new node at the beginning of the linked list. I suggest the following changes (thanks to Jonathan Leffler). typedef struct node { char airport[4]; // no typedef. explicit array declaration. struct node *next; } Node; void insertFirst(char *code, Node **listPtr) { Node *oldHead = *listPtr; Node *newNode = malloc(sizeof(Node)); if(newNode == NULL) { // check for NULL printf("Not enough memory to allocate\n"); return; } // if the struct member code is a string, then use strncpy to // guard against buffer overrun, else use memcpy to copy // code to airport. this is assuming that the buffer pointed // to by code is never smaller than sizeof newNode->airport memcpy(newNode->airport, code, sizeof newNode->airport); newNode->next = oldHead; *listPtr = newNode; // make listPtr point to the new head } A: the basics goes like this int a=10,b; b=a Above works Fine the same thing for array int a[]={1,2,3}; int b[3] b=a; ---> this wrong way correct way is for(i=0;i<3;i++) { b[i]=a[i]; } OR strcpy(b,a); char a[4],b[4]; gets(a); b=a;----->wrong assigning correct way strcpy(b,a); For more details find Inserting New Node
{ "language": "en", "url": "https://stackoverflow.com/questions/22216576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Overloading Base Class function Ok I have a class that wraps all WinAPI controls to make them operate like Java/C#/.Net controls (yes I know there are libraries that do this already) and looks like: class Control { public: //Bunch of other stuff.. virtual HWND GetHandle() const; }; and a derived class that looks like: class MenuBar: public Control { public: //Bunch of other stuff.. virtual HMENU GetHandle() const; enum class Flags { POPUP = MF_POPUP, STRING = MF_STRING }; }; However, the compiler gives me an error about wrong return type for overloading the Base Class' GetHandle function. How can I overload the GetHandle to have a different return type and to make it ignore the Base class's implementation? I really like the name GetHandle() and didn't want to change it (though that is an option).. Is there another way? I'm asking because perhaps there is a way to make it forget that the base class has an implementation? A: You need covariant return types. The return type from the derived class needs to be a pointer or reference derived from the return type of the base class. This can be accomplished by wrapping HWND and HMENU in a class hierarchy making a parallel of the API's organization. Templates may help if it's all generic.
{ "language": "en", "url": "https://stackoverflow.com/questions/16745776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Runtime analysis for the partitioning of an array with Quicksort Im working on a research paper about quicksort for school and thus I have to make a precise runtime analysis on best and worst case for my algorithm but im struggling with the part of my while-statements. I understand why its log(n) since you have so many recursive calls that you have n/2^k = 1 and this equation gives you n = 2^k, k = log2(n) and so on ... well since i did understand the recursive calls this part does not really matter but what matters is my following code: } } I have to specify the "cost" for each statement in dependence of my elements n. So i added a +1 for every if statement since they are simple statements and now i dont now how to get the cost for the while loops. The outer loop runs until the pointers i and j cross so the outer loop gets execuated at least n/2+1 (+1 for the exit condition) - but i cant find out how often the inner two while loops run. I thought that they would run also n/2 times but this cant work since our teacher taught us that we have to multiply the costs whenever we have nested statements which would result in a (n/2+1)*((n/2)+1)+((n/2)+1)) which is clearly n^2 and not O(n) ... And yes i have to add a +1 for each abort condition and if statement altough they dont really matter ... I hope you can help me by telling me whats my mistake that i get a O(n^2) runtime although it has to be O(n) Side note: I think for the while-loops it doesnt matter if its the best or worst case so dont mind that Thanks in advance ChampSilver A: The reason why the worst case run time is O(n) is that if you have a careful look at the code, you realize that you visit each array index at most once: observe that index i only increases at size, and index j only decrease, therefore you'll go at most once over each index. For example, if you have an array a[] of size 10, then the initial index i will be 0, and j will be 9. x will be (randlomly) somewhere in between, let's say x=4. Then, the outer while loop enters, and the first inner while loop increases index i until a[i] >= a[x]. The second inner while loop does the same to index j, for the opposite direction. But the sum of total iterations of both inner loops is at most 10. At which point the next outer while loop check will return false and no second iteration will occur. A: Lets start with this: our teacher taught us that we have to multiply the costs whenever we have nested statements which would result in a (n/2+1)*((n/2)+1)+((n/2)+1)) which is clearly n^2 and not O(n) This is only true if the looping variables in inner and outer loops are independent of each other. eg. for i in range(1..10): for j in range(1..10): do something This is because, for every value of i, inner loop iterates for all values of j. So, this is O(n^2). Now, lets look the other example: for i in range(1..10): for i in range(1..10): do something In this case, the outer loop runs only once as when inner loop exits, condition for outer loop also discontinues. So, this is, O(n). Now, lets look at your while loops. The outer condition is while i is less than j. Inside, we are always incrementing i and decreasing j. So, in this case, the total number of times while statements (all 3) are executed will be the upper bound on i + j, which is 2n. So, complexity is O(2n) or, O(n). EDIT: I am making this edit to explain what "complexity" means, practically. It is a way of approximating/calculating, number of iterations that are made in total, all loops and instructions combined, as size of input increases. So, if you really want to know that, just assign a variable, say a and add 1 to a as the 1st line of every loop. Then print a for different input sizes and you will know what O() notation means, theoretically vs practically.
{ "language": "en", "url": "https://stackoverflow.com/questions/42956323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to minimize switch statement? I am using switch statement to handle over 20 cases. It there a way to minimize a long switch statement for e.g as given below: switch (something) { case 1: doX(); break; case 2: doY(); break; case 3: doN(); break; // And so on... } Edit: As all are asking I have to clarify that this is a javascript question. A: You have provide only a pseudo-code. You should have provide your actual code so that I may have guided you better. Anyhow you may use the following short form for your long swith statement. var cases = { 1: doX, 2: doY, 3: doN //......................cases from 4 to 19 20: doZ }; if (cases[something]) { cases[something](); } Hope it helps. A: You can if there are some cases for which task is same. For example: if for both case 1 and case 10 same method doX() happens, you could do this: switch (something) { case 1: case 10: doX(); break; //... } Furthermore, if you have a common task that you would be done for many cases like for case - 12, 13, 14, 15 and 16, doA() will be executed. Let it be for default case. It will lessen writing many cases. switch (something) { // for case 12, 13, 14, 15, 16 default: doA(); break; } A: You might use ES6 Map functionality to create a map of your functions then you just need to call it with the dynamic key value. var myMap = new Map(), doX = n => console.log(n), doY = n => console.log(n*2), doN = n => console.log(n/2), something = 2; myMap.set(1,doX) .set(2,doY) .set(3,doN); myMap.get(something)(4); The same could be implemented by an ordinary object as well like var myMap = {}, doX = n => console.log(n), doY = n => console.log(n*2), doN = n => console.log(n/2), something = 3; myMap[1] = doX; myMap[2] = doY; myMap[3] = doN; myMap[something](4);
{ "language": "en", "url": "https://stackoverflow.com/questions/39306567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Rails build fails in Travis due to undefined method 'encrypted_password=' for User So I have a User model that uses the Devise gem. # == Schema Information # # Table name: USERS # # u_id :integer not null, primary key # email :string(255) default(""), not null # encrypted_password :string(255) default(""), not null # reset_password_token :string(255) # reset_password_sent_at :datetime # remember_created_at :datetime # sign_in_count :integer default(0), not null # current_sign_in_at :datetime # last_sign_in_at :datetime # current_sign_in_ip :string(255) # last_sign_in_ip :string(255) # join_date :datetime # organization :string(255) # created_at :datetime # updated_at :datetime # class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable self.table_name = "USERS" end I also have a Factory girl factory to create the user object for my RSpec tests FactoryGirl.define do factory :user do |user| user.email 'test@example.com' user.password Devise.friendly_token[0,20] end end All my tests on my local environment with rake spec pass, but when I run the Travis build, it always fails at the RSpec tests with: undefined method `encrypted_password=' for #<User:0x67c24931> # ./spec/models/user_spec.rb:26:in `(root)' Here is my user_spec.rb require 'rails_helper' RSpec.describe User, :type => :model do it "successfully creates a user" do @user = FactoryGirl.create :user expect(@user.save).to be_truthy end end I've checked via rails c that User.new.respond_to?(:encrypted_password=) returns true. I'm not sure what could be wrong and I can't find any answers to my problem. So, am I missing something? Edit: Forgot to include my .travis.yml language: ruby rvm: - jruby-1.7.15 env: - DB=mysql script: - export JRUBY_OPTS=--1.9 - RAILS_ENV=test bundle exec rake --trace db:migrate spec before_script: - mysql -e 'create database test_db' EDIT2: Adding in Travis log for db migrations $ RAILS_ENV=test bundle exec rake --trace db:migrate spec ** Invoke db:migrate (first_time) ** Invoke environment (first_time) ** Execute environment ** Invoke db:load_config (first_time) ** Execute db:load_config ** Execute db:migrate == 20141031200108 CreateAllTables: migrating ================================== -- create_table("GROUPS", {:primary_key=>"g_id", :force=>true}) -> 0.0130s -- create_table("TICKET_PRIORITY", {:primary_key=>"tp_id", :force=>true}) -> 0.0120s -- create_table("USERS", {:primary_key=>"u_id", :force=>true}) -> 0.0110s -- create_table("BOARDS", {:primary_key=>"b_id", :force=>true}) -> 0.0120s -- add_index("BOARDS", ["current_sprint_id"], {:name=>"current_sprint_id", :using=>:btree}) -> 0.0370s -> 0 rows -- add_index("BOARDS", ["p_id"], {:name=>"p_id", :using=>:btree}) -> 0.0200s -> 0 rows -- create_table("COMMENTS", {:primary_key=>"c_id", :force=>true}) -> 0.0120s -- add_index("COMMENTS", ["u_id"], {:name=>"u_id", :using=>:btree}) -> 0.0210s -> 0 rows -- create_table("GROUP_PERMISSIONS", {:id=>false, :force=>true}) -> 0.0120s -- add_index("GROUP_PERMISSIONS", ["g_id"], {:name=>"g_id", :using=>:btree}) -> 0.0190s -> 0 rows -- create_table("PROJECTS", {:primary_key=>"p_id", :force=>true}) -> 0.0150s -- add_index("PROJECTS", ["owner_id"], {:name=>"owner_id", :using=>:btree}) -> 0.0190s -> 0 rows -- create_table("SPRINTS", {:primary_key=>"s_id", :force=>true}) -> 0.0110s -- add_index("SPRINTS", ["b_id"], {:name=>"b_id", :using=>:btree}) -> 0.0190s -> 0 rows -- create_table("TICKET_ASSIGNMENT_HISTORY", {:id=>false, :force=>true}) -> 0.0140s -- add_index("TICKET_ASSIGNMENT_HISTORY", ["t_id"], {:name=>"t_id", :using=>:btree}) -> 0.0210s -> 0 rows -- add_index("TICKET_ASSIGNMENT_HISTORY", ["u_id"], {:name=>"u_id", :using=>:btree}) -> 0.0210s -> 0 rows -- create_table("TICKET_STATUS_HISTORY", {:primary_key=>"tsh_id", :force=>true}) -> 0.0130s -- add_index("TICKET_STATUS_HISTORY", ["t_id"], {:name=>"t_id", :using=>:btree}) -> 0.0180s -> 0 rows -- create_table("TICKET_TAGS", {:id=>false, :force=>true}) -> 0.0120s -- add_index("TICKET_TAGS", ["t_id"], {:name=>"t_id", :using=>:btree}) -> 0.0170s -> 0 rows -- create_table("TICKETS", {:primary_key=>"t_id", :force=>true}) -> 0.0150s -- add_index("TICKETS", ["b_id"], {:name=>"b_id", :using=>:btree}) -> 0.0180s -> 0 rows -- add_index("TICKETS", ["current_status_id"], {:name=>"current_status_id", :using=>:btree}) -> 0.0180s -> 0 rows -- add_index("TICKETS", ["s_id"], {:name=>"s_id", :using=>:btree}) -> 0.0220s -> 0 rows -- add_index("TICKETS", ["tp_id"], {:name=>"tp_id", :using=>:btree}) -> 0.0220s -> 0 rows -- create_table("USER_GROUP", {:id=>false, :force=>true}) -> 0.0160s -- add_index("USER_GROUP", ["g_id"], {:name=>"g_id", :using=>:btree}) -> 0.0190s -> 0 rows -- add_index("USER_GROUP", ["u_id"], {:name=>"u_id", :using=>:btree}) -> 0.0180s -> 0 rows == 20141031200108 CreateAllTables: migrated (0.5070s) ========================= == 20141031201446 UpdateEnumsInTables: migrating ============================== -- remove_column(:TICKETS, :type, :string) -> 0.0290s -> 0 rows -- add_column(:TICKETS, :type, :integer) -> 0.0250s -> 0 rows -- remove_column(:TICKET_ASSIGNMENT_HISTORY, :relationship, :string) -> 0.0240s -> 0 rows -- add_column(:TICKET_ASSIGNMENT_HISTORY, :relationship, :integer) -> 0.0280s -> 0 rows -- remove_column(:TICKET_STATUS_HISTORY, :new_status, :string) -> 0.0250s -> 0 rows -- add_column(:TICKET_STATUS_HISTORY, :new_status, :integer) -> 0.0250s -> 0 rows == 20141031201446 UpdateEnumsInTables: migrated (0.1580s) ===================== == 20141106220707 ModifyGroupPermissions: migrating =========================== -- remove_column(:GROUP_PERMISSIONS, :name) -> 0.0230s -> 0 rows -- remove_column(:GROUP_PERMISSIONS, :rank) -> 0.0250s -> 0 rows -- add_column(:GROUP_PERMISSIONS, :pm_id, :integer) -> 0.0280s -> 0 rows -- create_table("PERMISSIONS", {:primary_key=>"pm_id", :force=>true}) -> 0.0110s == 20141106220707 ModifyGroupPermissions: migrated (0.0880s) ================== == 20141107011729 DeviseCreateUsers: migrating ================================ -- create_table(:users, {:primary_key=>"u_id", :force=>true}) -> 0.0160s -- add_index(:users, :email, {:unique=>true}) -> 0.0350s -> 0 rows -- add_index(:users, :reset_password_token, {:unique=>true}) -> 0.0200s -> 0 rows == 20141107011729 DeviseCreateUsers: migrated (0.0790s) ======================= ** Invoke db:_dump (first_time) ** Execute db:_dump ** Invoke db:schema:dump (first_time) ** Invoke environment ** Invoke db:load_config ** Execute db:schema:dump ** Invoke spec (first_time) ** Invoke spec:prepare (first_time) ** Execute spec:prepare ** Invoke test:prepare (first_time) ** Execute test:prepare ** Execute spec Edit: I also tried running mysql -uroot -e 'use test_db; describe users;' right before running rake spec on travis and it showed the user table had the encrypted_password column. I also ran cat db/schema.rb to see if the migrations fully happened, and encrypted_password was also there. Now I'm not sure what could be wrong since the field is in the database. A: Well when I created my tables in MySQL I used capital names for all my table names. For some reason when running it locally, the table names were still uppercase in development mode, but were lowercase for test mode. So, in my user model, I simply changed the self.table_name = "USERS" to self.table_name = "users" and that fixed my problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/26943394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Paypal email notification on sandbox Hey I was working with Paypal express checkout and I wondering if the notifications that I receive after someone has made a payment is according to the DoExpressCheckout response? and how can I change it? A: You can't change the PayPal payment notification sent as a result of your DoExpressCheckout call. You can, however, send them an email yourself in addition to it.
{ "language": "en", "url": "https://stackoverflow.com/questions/20080478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: R: Extract data from several files based on X,Ys I have a data frame df in R containing X, Y UTM coordinates. The sample data looks like this: ID X Y 1 333229 6580393 2 333229 6580500 3 333229 6581500 4 325889 6584200 ... The hourly wind speed and wind direction data for above (and other) X, Ys is located in a directory containing meteorological data of many years (1995 - 2011, more than 100,000 .dat files). Each file, for example, named as "hourly_333229_6580393_2010.dat" contains hourly data of a single year like this: Day Month Year hour w_speed w_dir 1 1 2010 1 5.02 247.55 2 1 2010 2 2.6 320.12 3 1 2010 3 3 315.25 From this directory, I would like to extract hourly wind speed and direction data for above X,Ys and for the period 1 May 2005 - 31 July 2005 in the following manner: ID Year Month Day hour X Y w_speed w_dir 1 2005 5 1 1 333229 6580393 2.01 120 2 2005 5 1 2 333229 6580393 5.2 370 3 2005 5 1 3 333229 6580393 1.5 115 ... How could I achieve this using R in an optimized way? Any help/suggestions would be highly appreciated. A: First, I would suggest creating a function for the purpose of opening each dat-file. Please replace the read.table function by the function you use for opening the dat-files. In this case, the function contains both coordinates and the months to which respect it filters the dataframe as arguments. Arguments could however be extended by year and days for instance. To keep it simple I only included months. open_dat <- function(X, Y, left, right) { dat <- read.table(paste("hourly", X, Y, "2005.dat", sep = "_"), header=TRUE) %>% as.tibble() dat$X <- X dat$Y <- Y dat %>% filter(between(Month, left, right)) } Then, we can apply the function to the dataframe that contains X and Y for the days that are between May and July (numbers 5 and 7): full_df <- map2_dfr(df$X, df$Y, open_dat, left = 5, right =7)
{ "language": "en", "url": "https://stackoverflow.com/questions/57564371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Extracting data from Excel to R as it is I have a excel containing values. The values are merged at some places like shown below (Table A). While extracting into R, I get in a different way like shown below (Table B) Table A library(readxl) Book3 <- read_excel("~/Book3.xlsx") Table B If you look at table B, NA's are introduced in between where the values are merged. Is there a way to eliminate this. I need exactly the same in Excel. Please guide A: You can use read.xlsx function from openxlsx package. fillMergedCells = T can fill both the columns with the same values. library(openxlsx) read.xlsx(data, fillMergedCells=T) If You are considering only the look and feel of the table as the same as in Excel than try flextables which can show exactly the same merged output as in Excel Like This Table below
{ "language": "en", "url": "https://stackoverflow.com/questions/58887592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does abstract class have to implement all methods from interface? interface BaseInter{ name : string; test(); } abstract class Abs implements baseInter{ } In TypeScript, compiler complaints that the class incorrectly implements the interface: name is missing in type abs. Here Absis an abstract class and so why do we need to implement the interface over there? A: You need to re-write all of the members/methods in the interface and add the abstract keyword to them, so in your case: interface baseInter { name: string; test(); } abstract class abs implements baseInter { abstract name: string; abstract test(); } (code in playground) There was a suggestion for it: Missing property declaration in abstract class implementing interfaces but it was declined for this reason: Although, the convenience of not writing the declaration would be nice, the possible confusion/complexity arising from this change would not warrant it. by examine the declaration, it is not clear which members appear on the type, is it all properties, methods, or properties with call signatures; would they be considered abstract? optional? A: You can get what you want with a slight trick that defeats the compile-time errors: interface baseInter { name : string; test(); } interface abs extends baseInter {} abstract class abs implements baseInter{ } This trick takes advantage of Typescript's Declaration Merging, and was originally presented here and posted on a related SO question here. A: Interfaces are used for defining a contract regarding the shape of an object. Use constructor to pass in properties to the class interface BaseInter { name : string; test(): boolean; } abstract class Abs implements BaseInter { constructor(public name: string) {} test(): boolean { throw new Error('Not implemented') } }
{ "language": "en", "url": "https://stackoverflow.com/questions/44593961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "34" }
Q: will db monitoring with pg_stat/pg_statio slow down my other queries? I recently built a database monitoring plugin for postgresql that queries the pg_stat and pg_statio tables in postgresql. I want to understand/test how my plugin might affect my database but fear that if i just turned my plugin on my database, my database may crash and burn... I was hoping that someone could suggest some testing methods or answer some of my questions/concerns below: 1) I was wondering if these monitoring queries would cause my other non-monitoring queries (which I assume also need to write to the pg_statio tables to update these statistics) to lock up. 2) Is there a way for me to capture database traffic on a postgresql database table so I can maybe replay this traffic on a copy of the database? A: will db monitoring with pg_stat/pg_statio slow down my other queries? No. Not significantly, anyway. 1) I was wondering if these monitoring queries would cause my other non-monitoring queries (which I assume also need to write to the pg_statio tables to update these statistics) to lock up. No. In PostgreSQL reads do not block writes. 2) Is there a way for me to capture database traffic on a postgresql database table so I can maybe replay this traffic on a copy of the database? Not easily, at the present time. You can record statements and parameters in the logs, along with a log_line_prefix that lets you reassemble them into transactions and sessions. It'll be painful to parse the logs for this though. Also, IIRC super-long statements can be truncated. You can in PostgreSQL 9.4 extract the rows changed using logical decoding, but that doesn't tell you which statements changed them, and it doesn't let you reproduce the load. Replaying the change stream is a very different load to creating it in the first place. Tools like pg_stat_statements can help a bit, but won't give you a verbatim stream of changes.
{ "language": "en", "url": "https://stackoverflow.com/questions/32381640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reuse the same models in ASP.NET MVC and WPF MVVM I'm developing an application in WPF MVVM, but I'll also need to create an MVC project in the same solution. I would like to know if there is any way to reuse the same Models in both classes, and the best way to do it, since to meet the MVVM specifications For example, I need to add a "PropertyChanged" to the set of my properties, something unnecessary in MVC project. A: I agree with @@Douglas Gandini. You should define your business objects in a separate assembly that you can reference from both your ASP.NET and WPF applications. These classes should not implement any client-specific interfaces such as INotifyPropertyChanged but be pure POCO classes that contains business logic only. In your WPF application, you could then create a view model class that implements the INotifyPropertyChanged interface and wraps any properties of the business object that it makes sense to expose to and bind to from the view. The view model then has a reference to the model, i.e. your business object that is defined in a separate assembly that may be shared between several different client applications, and the view binds to the view model. This is typically how the MVVM design pattern is (or should be) implemented in a WPF application. The view model class contains your application logic, for example how to notify the view when a data bound property value is changed, and the model contains the business logic that is the same across all platforms and applications. Of course this means that you will end up with a larger number of classes in total but this is not necessarily a bad thing as each class has its own responsibility. The responsibility of a view model is to act as a model for the application specific XAML view whereas the responsibility of the model class is to implement the business logic. A: Create a shared assembly. Call it Contracts or Models and share it between your WPF and MVC
{ "language": "en", "url": "https://stackoverflow.com/questions/41506055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Spark streaming scala window length by number of objects I am using spark and scala and I would like to create a window operation with length set in number of objects i.e. the window starts empty, as the stream initiates the objects are stored in the window up until it holds 10 objects and when the 11th comes the first is dropped. Is this possible or do I have to use an other structure like a list or array? The documentation (http://spark.apache.org/docs/latest/streaming-programming-guide.html#window-operations) and some googling only refer to a time based window (length and interval). Thank you in advance. A: Window in Spark streaming is characterized by windowDuration and slideDuration (optional). So, it is a time window. But you can consider using Apache Flink. It supports both count windows and time windows. But in comparison to Spark, Flink has another streaming ideology. It process incoming events as they arrive (Spark processes events in micro-batches). As a result, Flink may have some restrictions. Give it a try if it suits your needs.
{ "language": "en", "url": "https://stackoverflow.com/questions/36711439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to extract data from an embed Raphael dataset to CSV? Attempting to extract the data from this Google Politics Insights webpage from "Jan-2012 to the Present" for Mitt Romney and Barack Obama for the following datasets: * *Search Trends Based on volume *Google News Mentions Mentions in articles and blog posts *YouTube Video Views Views from candidate channels For visual example, here's what I mean: Using Firebug I was able to figure out the data is stored in a format readable by Raphael 2.1.0; looked at the dataset and nothing strikes me as a simple way to convert the data to CSV. How do I convert the data per chart per presidential candidate into a CSV that has a table for "Search Trends", "Google News Mentions", and "YouTube Video Views" broken down by the smallest increment of time with the results measured in the graph are set to a value of "0.0 to 1.0"? (Note: The reason for "0.0 to 1.0" is the graphs do not appear to give volume info, so the volume is relative to the height of the graph itself.) Alternatively, if there's another source for all three datasets in CSV, that would work too. A: First thing to do is to find out where the data comes from, so I looked up the network traffic in my developer console, and found it very soon: The data is stored as json here. Now you've got plenty of data for each candidate. I don't know exactly in what relation these numbers are but they definitely are used for their calulation in the graph. I found out that the position in the main.js is on line 392 where they calculate the data with this expression: Math.log(dataPoints[i][j] * 100.0) / Math.log(logScaleBase); My guess is: Without the logarithm and a bit exponential calculation you should get the right results.
{ "language": "en", "url": "https://stackoverflow.com/questions/11954091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Open files located in the ACCDocs I've developed a plugin project in Visual Studio with RevitAPI to open batch Revit files to export data. I can add many files which are on the networks and the plugin automatically opens all the files. Is it possible to open files that are in the ACC Docs cloud? I know I can open AccDocs which were be already downloaded with searching in collaboration cache folder, but how to open files which are not yet downloaded? Thanks A: Since you mentioned the collaboration cache folder, I suppose your Revit model is the Revit Cloud Worksharing model (a.k.a C4R model, model of Autodesk Collaboration for Revit). If so, we can call APS Data Management to obtain the projectGuid and modelGuid in the model's version tip like below. { "type":"versions", "id":"urn:adsk.wipprod:fs.file:vf.abcd1234?version=1", "attributes":{ "name":"fileName.rvt", "displayName":"fileName.rvt", ... "mimeType":"application/vnd.autodesk.r360", "storageSize":123456, "fileType":"rvt", "extension":{ "type":"versions:autodesk.bim360:C4RModel", .... "data":{ ... "projectGuid":"48da72af-3aa6-4b76-866b-c11bb3d53883", .... "modelGuid":"e666fa30-9808-42f4-a05b-8cb8da576fe9", .... } } }, .... } Afterward, open the C4R model using Revit API like below: var region = ModelPathUtils.CloudRegionUS; //!<<< depends on where your BIM360/ACC account is based, US or EU. var projectGuid = new Guid("48da72af-3aa6-4b76-866b-c11bb3d53883"); var modelGuid = new Guid("e666fa30-9808-42f4-a05b-8cb8da576fe9"); var modelPath = ModelPathUtils.ConvertCloudGUIDsToCloudPath( region, projectGuid, modelGuid ); //!<<< For Revit 2023 and newer. //var modelPath = ModelPathUtils.ConvertCloudGUIDsToCloudPath( projectGuid, modelGuid ); //!<<< For Revit 2019 ~ 2022 var openOptions = new OpenOptions(); app.OpenAndActivateDocument( modelPath, openOptions ); //!<<< on desktop // app.OpenDocumentFile( modelPath, openOptions ); //!<<< on Design Automation for Revit or don't want to activate the model on Revit desktop. References: * *https://aps.autodesk.com/blog/accessing-bim-360-design-models-revit *https://thebuildingcoder.typepad.com/blog/2020/04/revit-2021-cloud-model-api.html#4.4 *https://help.autodesk.com/view/RVT/2023/ENU/?guid=Revit_API_Revit_API_Developers_Guide_Introduction_Application_and_Document_CloudFiles_html
{ "language": "en", "url": "https://stackoverflow.com/questions/75530623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Accounting spaces in palindrome program This is a program that accepts a string of words and checks if the words are palindromes and if it is one, it prints it. However if a string has a space in it, my program won't count it as a palindrome (Example: nurses run). What should I be adding to make the program exclude the space, when it's accounting for palindromes? Palindrome: a word, phrase, or sequence that reads the same backwards as forwards, e.g. 'madam' or 'nurses run' import sys strings = [] for s in sys.argv[1:]: strings += [s] def is_palindrome(word): if len(word) <= 2 and word[0] == word[-1]: return True elif word[0] == word[-1]: is_palindrome(word[1:-1]) return True else: return False def printpalindromes(strings): for s in strings: if is_palindrome(s) == True: print(s) printpalindromes(strings) A: Try stripping out the whitespaces before doing the palindrome check >>> x = "nurses run" >>> x.replace(" ", "") 'nursesrun' A: You can use reversed: def palindrome(word): if ' ' in word: word = word.replace(' ', '') palindrome = reversed(word) for letter, rev_letter in zip(word, palindrome): if letter != rev_letter: return 'Not Palindrome' return 'Palindrome' A: Your code is still incorrect in the elif statement. You've added return True when you should actually be returning the response from your recursive call as previously mentioned. def is_palindrome(word): if len(word) <= 2 and word[0] == word[-1]: return True elif word[0] == word[-1]: return is_palindrome(word[1:-1]) else: return False A: Here's a simpler solution of your problem: import sys sys.argv = [" nurses ", " run "] word = "".join([s.strip() for s in sys.argv]) print("{} {} palindrome".format(word, "is" if word == word[::-1] else "is not")) or you can just create the word out of sys.argv like this: word = "".join(sys.argv).replace(" ","")
{ "language": "en", "url": "https://stackoverflow.com/questions/46384327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Is there a way to ignore the maxRequestLength limit of 2GB file uploads? Here's where I'm setting maxRequestLength to 2GB (the max value), which indicates the maximum request size supported by ASP.NET: <system.web> <httpRuntime maxRequestLength="2097151" executionTimeout="3600"/> ... and here I'm setting the maxAllowedContentLength to 4GB (the max value), which specifies the maximum length of content in a request supported by IIS <system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength="4294967295"/> </requestFiltering> </security> ... I'd like to be able to upload files up to 4GB, but I'm limited by the maxRequestLength field. I noticed that this third party upload tool (http://www.element-it.com/onlinehelp/webconfig.html) has a ignoreHttpRuntimeMaxRequestLength property, which allows it to upload files up to 4GB. Does anyone know if I can ignore the maxRequestLength value like this other upload tool does? A: Considering the Type of MaxRequestLength is a Int, at the moment there is no way to parse a value higher than Int.Max correctly. I heard they might be increasing IIS8 but nothing concrete from Microsoft as of yet. The only way I've seen in .Net 4.5 is to use HttpRequest.GetBufferlessInputStream which Gets a Stream object that can be used to read the incoming HTTP entity body, optionally disabling the request-length limit that is set in the MaxRequestLength property. A: In my case these were the changes I needed to apply: <system.web> <httpRuntime targetFramework="4.6.1" maxRequestLength="2147483647" /> </system.web> <system.webServer> <serverRuntime uploadReadAheadSize="2147483647" /> <security> <requestFiltering> <requestLimits maxAllowedContentLength="2147483647" /> </requestFiltering> </security> </system.webServer> In order to add the serverRuntime follow the intructions in the first answer of this question A: You should be able to override the settings inside machine.config by adding the same node into your application's web.config like so. Microsoft has some information about ASP.NET Configuration File Hierarchy and Inheritance. NOTE: Erik Philips is right and the max size of maxRequestLength is 2,147,483,647 (Int32.MaxValue). This answer is to illustrate how to override a setting defined in machine.config (or any .config) from within your application's web.config/ <configuration> ... <system.web> <httpRuntime maxRequestLength="2147483647"/> ... ... </system.web> ... </configuration> In doing this though, you might also want to increase your timeout or it might, well, time out.
{ "language": "en", "url": "https://stackoverflow.com/questions/13129746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Could not load file or assembly 'Autofac, Version=2.6.1.841 with webservice I'm building an web service on sharepoint with IoC. Here is my main code: [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1), WebService(Namespace = "http://tempuri.org/")] class WebService : System.Web.Services.WebService { private static IContainer Container { get; set; } private DataTable Articles=new DataTable(); private string display; [WebMethod(EnableSession = true, Description = "Web method for using search service")] public string DisplayArticles() { var builder = new ContainerBuilder(); builder.RegisterType<WebServiceRepo>().As<IArticlesRepository>(); Container = builder.Build(); Search(); return display; } public void Search() { using (var scope = Container.BeginLifetimeScope()) { var repo = scope.Resolve<IArticlesRepository>(); Articles.Load(repo.GetArticles(),LoadOption.OverwriteChanges); display = repo.ReturnArticles(Articles); } } } The problem is an error I'm getting when trying to invoke method that uses Autofac: System.IO.FileNotFoundException: Could not load file or assembly 'Autofac, Version=2.6.1.841, Culture=neutral, PublicKeyToken=17863af14b0044da' or one of its dependencies. The system cannot find the file specified. at SOAP_WebService.WebService.DisplayArticles() It says about file not being found, but an Autofac.dll with version 2.6.1.841 exists in bin/debug folder. I'm using this version of autofac because working on sharepoint 2010, I can only choose .net framework v3.5 and it's one of the newest version that operates on this version of .net framework. Answers provided in simmiliar questions did not help me. A: Somehow i managed to work it out... If anyone will have a simmiliar problem: The Autofac assembly I added to the references in my project, was somehow impossible to find by visual studio, despite the fact that file existed in my project (I'll be gratefull if someone will explain me why did it happen). The solution to it was adding this assembly to the GAC via Developer Command Prompt by this command: gacutil /i <path to the assembly> /f
{ "language": "en", "url": "https://stackoverflow.com/questions/45456010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Code::Blocks cannot find vector header EDIT: I have solved this problem, with Tomalak's help. It appears that I mistakenly uninstalled libstdc++6-4.4-dev_4.4.3 when I was making space to install code::blocks into, thus removing the STL headers. Code::Blocks now works perfectly fine. Hey everyone, I'm back yet again to bug you. I have recently installed Code::Blocks in order to follow along with a SDL tutorial, mainly to make it easier with the file creation process (i.e. not having to deal with makefiles for the time being) I have been compiling/running the examples (so far) just fine, but I've now hit a snag. On the tutorial for entities, the header file includes <vector> - yet code::blocks is stating it cannot find said header file. It's a .h header file, but it's recognizing it as C++ (I think, judging from the project options) - all my headers are .h, all my sources are .cpp... I have searched Google for a solution, and many people state that this error occurs when they try to use in a .c file by mistake. This is not the case, unless Code::Blocks is recognizing my .h as a C-header. In case you're wondering, I am running Lucid Puppy Linux 5.2 (aka LuPu), a Ubuntu derivative. (Installed Code::Blocks from the Ubuntu repositories) In advance, thank you very much for the help. A: As it turns out, it was not a Code::Blocks issue - I had mistakenly un-installed the libstdc++6-4.4-dev_4.4.3 package. So, if any of you all get this same problem make sure the libstdc++ development files are installed! LOL
{ "language": "en", "url": "https://stackoverflow.com/questions/5526373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I want to block certain directories in my hosting I was wondering if someone knows how to block certain directories such as "http://www.example.com/images, css, includes" etc. Because when I type my web address with a sub directory, it shows what's inside those sub-directories such as my css files, images etc. I have read about a few articles about this but failed to understand as I have very poor knowledge in computer. A: You can create this one rule in root .htaccess to block those directories listings: RewriteEngine On RewriteRule ^(css|images|includes|js)/?$ - [NC,F]
{ "language": "en", "url": "https://stackoverflow.com/questions/25845666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How can I bitbang Arduino Nano RP2040 Connect for multiple AM2320 temperature sensors? Useage of bitbang libraries? can you help me with the following?: I'm a beginner and have an Arduino Nano RP2040 Connect and four AM2320 temperature sensors, but each have the same address, that can't be changed (this project is for my graduation exam). I got an info, that it is possible to create more I2C buses "in a software way" by using 4 functions (a start, a stop, one that can transmit a bit, and one that can read a bit). In this way, any of the digital pins can be programmed as SDA/SCL. I have been told that there's a library named 'SoftwareWire', but I can't really understand the commands of it, and which comes after the other. Has anyone anything about this? Searched for bitbanging in a 'software-way', found that there are libraries for this, but can't deal with the commands. A: hi i will pass to you a function that works for me with 3 i2c sensors sh21 with same adress #include <Wire.h> #include "SHT2x.h" uint32_t start; uint32_t stop; SHT2x sht; float tempN1; float humN1; float dwn1; float tempN2; float humN2; float dwn2; float tempN3; float humN3; float dwn3; int flip = 0; void sht21read(){ if (flip == 0) { Wire.begin(21, 22); // 2 delay(100); // myHTU21D.begin(); sht.begin(21, 22); start = micros(); sht.read(); stop = micros(); delay(250); tempN1 = sht.getTemperature(); humN1 = sht.getHumidity(); // dwn1 = SHT2x.GetDewPoint(); delay(250); Wire.end(); flip = 1; } else if (flip == 1) { Wire.begin(32, 22); // 4 delay(100); // myHTU21D.be sht.begin();gin(); sht.begin(32, 22); start = micros(); sht.read(); stop = micros(); delay(250); tempN2 = sht.getTemperature(); humN2 = sht.getHumidity(); // dwn2 = SHT2x.GetDewPoint(); delay(250); Wire.end(); flip = 2; } else if (flip == 2) { Wire.begin(27, 22); // 13 delay(100); // myHTU21D.begin(); sht.begin(27, 22); start = micros(); sht.read(); stop = micros(); delay(250); tempN3 = sht.getTemperature(); humN3 = sht.getHumidity(); // dwn3 = SHT2x.GetDewPoint(); delay(250); Wire.end(); flip = 3; } else if (flip == 3) { flip = 0; Serial.print("TEMPERATURA N1= "); Serial.print(tempN1); Serial.print(""); Serial.print("HUMEDAD N1= "); Serial.print(humN1); Serial.print(""); Serial.print("||||"); Serial.print("TEMPERATURA N2= "); Serial.print(tempN2); Serial.print(""); Serial.print("HUMEDAD N2= "); Serial.print(humN2); Serial.print(""); Serial.print("||||"); Serial.print("TEMPERATURA N3= "); Serial.print(tempN3); Serial.print(""); Serial.print("HUMEDAD N3= "); Serial.print(humN3); Serial.println(""); delay(5000); } } then you run the function sht21read(); (or with your own name) on void loop and uala all working
{ "language": "en", "url": "https://stackoverflow.com/questions/74207696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Accessing Swagger outside the Spring Boot Context path My spring boot application have a contextPath like as shown below server.contextPath=/api I have added springfox swagger configuration and was able to get the swagger url from the given url like as shown below http://localhost:8080/api/swagger-ui.html Actually what I would want is to get the swagger ui outside the contextPath like as shown below http://localhost:8080/swagger-ui.html Like to know if this is possible or not. A: I didn't try it but maybe it can help you. If it's way to find out if swagger is running and when yes you can dynamically set System.setProperty("server.servlet.context-path", "/"); SpringApplication.run(Application.class, args); But as I said I didn't test and maybe this is stupid. Anyway I will try to test some solutions and I will write you
{ "language": "en", "url": "https://stackoverflow.com/questions/52362975", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android: Repetitive Android Activity Workflow. Fire and Forget? I am working on an application that tries to streamline data entry from a very repetitive process: * *Enter some details that require full-screen graphics and would be confusing if scrolled *Enter some more atomic details *Enter yet more atomic details *Apply the accumulated data *Go back to step 1 I am pretty sure that i can represent this as 3 separate Activities and then just fire up new Intents for each activity in each cycle. What I can't yet get a sense of is whether this is a viable approach. Question 1: If I do a fire-and-forget approach, how much of the resource management is going to be handled by Android? Will it just happily deallocate/reuse/etc. activities behind the scenes? Or is this something i have to manage myself? Question 2: Is there a way to cause the reusing of activities so that only one instance of each activity is ever allocated and is just reused for each cycle? Question 3: Can one manipulate the activity stack so that there aren't ~100 (approximated number of expected cycles) cycles worth of activities on the stack? I'd like to be able to use the back key no more than three times and exit out of the data entry portion to a summary page. Question 4: Can anyone suggest alternate approaches to the cycles of activities problem? I have considered view flippers and tabs, but wasn't sure that would be better or not. A: Will it just happily deallocate/reuse/etc. activities behind the scenes? Yes. Is there a way to cause the reusing of activities so that only one instance of each activity is ever allocated and is just reused for each cycle? Try FLAG_ACTIVITY_REORDER_TO_FRONT on your Intent to launch the activity. Based on the docs, it should give you your desired behavior. Can one manipulate the activity stack so that there aren't ~100 (approximated number of expected cycles) cycles worth of activities on the stack? 100? You must be expecting some very patient users. Regardless, FLAG_ACTIVITY_REORDER_TO_FRONT should cover that too. Can anyone suggest alternate approaches to the cycles of activities problem? I have considered view flippers and tabs, but wasn't sure that would be better or not. Tabs aren't great for things where you're trying to enforce a flow, since tabs are designed for random (not sequential) access. ViewFlipper/ViewSwitcher could work, though then you have to manage BACK button functionality and make sure you're not effectively leaking memory within the activity, since you're expecting people to be using it for an extended period.
{ "language": "en", "url": "https://stackoverflow.com/questions/3382790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CDI - Observing Container Events I am trying to observe both the startup and shutdown events for a CDI web application. I have an ApplicationScoped bean that listens for those events: @ApplicationScoped public class PrettyfacesStartupObserver { private static final Log LOGGER = LogFactory.getLog(PrettyfacesStartupObserver.class); public PrettyfacesStartupObserver() { LOGGER.debug("\n\n\n\n\n\n\n\n\n\nconstructor"); } public void onStartup(@Observes AfterBeanDiscovery afterBeanDiscovery ) { LOGGER.debug("\n\n\n\n\n\n\n\n\n\nafter bean discover"); } public void onStartup(@Observes AfterDeploymentValidation afterDeploymentValidation ) { LOGGER.debug("\n\n\n\n\n\n\n\n\n\n\nafter deployment validation"); } public void onShutdown(@Observes BeforeShutdown beforeShutdown ) { LOGGER.debug("\n\n\n\n\n\n\n\n\n\n\nbefore shutdown:" + beforeShutdown); } I don't see anything in the logs. What am I missing? A: The "special file" mentioned by Walter White is: META-INF/services/javax.enterprise.inject.spi.Extension That file should contain the fully-qualified name of your Extension class. ie: org.mydomain.extension.MyExtension A: Thanks to Pete Muir, the solution was to implement the Extension interface. Once I did that, along with creating a special file, it worked perfectly. The thing to remember is, if you want to observe (or act on) container events, you must implement the extension interface as it is a special event. https://docs.jboss.org/weld/reference/latest/en-US/html/extend.html#d0e4984 Walter
{ "language": "en", "url": "https://stackoverflow.com/questions/3540137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Where does the Android build process store the final image file (that gets flashed into a phone device)? After going through the build process (found at: http://source.android.com/source/building.html) for the master branch (or the whole Android tree, not just for a specific phone such as for NexusS), where would I be able to find the final platform image in the Android file hierarchy? The specific image that gets flashed onto the actual phone at the very end of the process. Reason behind this query: I cannot do the "flashing to device" steps (such as running "$ adb reboot bootloader") as found in the link I've provided b/c the Android development environment I've set up is inside a virtual machine (Ubuntu 10.04 via VirtualBox) that exists on a server (of which I am unable to access its USB ports to directly plug in my phone). I am currently connecting to that VM through Windows RDP (of which I am unsure if it has VRDP capability?). Since it does not seem that I can find a solution that allows for my RDP connection to the VM to use local USB (of my physical computer, a Windows 7), I need to find the final file or files the Android build process creates (after running the "$make adb bootloader" command) so I can directly load them onto the phone (a Nexus S) on my physical computer. Does anyone know where these image files are? A: Try out/target/product/XXXXX from your build directory where XXXXX if your build target, maguro for the Galaxy Nexus for instance or generic for the emulator.
{ "language": "en", "url": "https://stackoverflow.com/questions/11041088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Access Mac OS X Application Menu from Java I'm writing a Java application designed for all platforms, but specifically, I am working on OS X appearance and integration (I use NetBeans on my MacBook Pro). I'd like to access the application's menu, i.e. the bolded menu named after the application. I want to register listeners for the About and Quit items, as well as show the Preferences item. I wouldn't mind adding a few more items of my own, too. So, how do I do this? I have seen previous posts refer to OSXAdapter, but the geniuses at Apple decided to remove it from their library (or rename it ambiguously) because all links redirect to the main page, and all my searching has been fruitless. I've also seen a MacOSAppAdapter class, but I am unsure how to use it. All the importing and new classes and hierarchies is bit confusing. EDIT: This is what I did to tie into the About, Preferences, and Quit items: I made a new class, MacOSXAboutHandler, that extends com.apple.eawt.Application Its constructor simply invokes setAboutHandler(AboutHandler aH) and I provide it with my own listener that extends AboutHandler In my main class I determine if I am running on a Mac using System.getProperty("os.name").contains("mac") If this is true, then I simply create a new instance of MacOSXAboutHandler. The constructor adds my handler, and whenever the application is run (or even tested within NetBeans), clicking the About... item on the application's bolded menu executes the code I specified in my AboutHandler. The same is done for preferences and quit, simply replacing occurrences of "about" with the appropriate action. All these handlers are written as any other Java listener would be. A: You might want to have a look at Bringing your Java Application to Mac OS X and (more importantly) Bringing your Java Application to Mac OS X Part 2 and Bringing your Java Application to Mac OS X Part 3 You might Java System Property Reference for Mac of use You may want to take a look at Apple's Java 6 Extensions API, from my brief reading, it would appear that you basically want to use the default instance if com.apple.eawt.Application and supply the handlers you need (such as setAboutHandler). You may also want to read through The Java on Mac OS X About, Quit and Preferences menu items and events article, which should provide some more additional hints.
{ "language": "en", "url": "https://stackoverflow.com/questions/11734104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Sending JSON Post Request using CURL on Form Submit PHP I have this function where I enroll a token to make a transaction process without the need to key-in of credentials. Some blogs stated that curl exec does the job in executing the curl, but nothing is happening with this function. can I somehow trigger this CURL using submit button in form? also, how can I know the errors of CURL? $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'url here', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS =>'{ "clientIp": $_clientip, "ipAddress": $_ipaddress, "merchantId": $_mid, "notificationUrl": $_noturl, "requestId": $_requestid, "responseUrl": $_resurl, "signature": "1f4856d7868b1c352e015211e79df194d6fa1babc624084dd00027bf89538184d75f19991d008c1d99d2b5a28c2eea7f928e304611562eb838216e3664eac628", "trxType": "createtoken", "verify": "Y", "address1": $_addr1, "address2": $_addr2, "city": $_city, "country": $_country, "email": $_email, "fName": $_fname, "lName": $_lname, "mName": $_mname, "mobile": $_mobile, "phone": $_phone, "state": $_state, "postal": "" }', CURLOPT_HTTPHEADER => array( 'Content-Type: application/json', 'Idempotency-Key: HMCENRO202001140009T', 'Authorization: Basic Og==' ), )); $response = curl_exec($curl); curl_close($curl); echo $response; A: you can try it via defining the body as structured representation and then transform it to JSON: $recipient['dst'] = "+000000"; $message['recipients'] = array($recipient); $message['text'] = "this is a test message"; $job['messages'] = array($message); $json = json_encode($job); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'url here', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => $json, CURLOPT_HTTPHEADER => array( 'Content-Type: application/json', 'Idempotency-Key: HMCENRO202001140009T', 'Authorization: Basic Og==' ), )); $response = curl_exec($curl); curl_close($curl); echo $response;
{ "language": "en", "url": "https://stackoverflow.com/questions/68095686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Disable socket timeout, via setsockopt() Say I have the following code in C++ that will set the time out for a socket: struct timeval time_val_struct = { 0 }; time_val_struct.tv_sec = 1; time_val_struct.tv_usec = 0; return_value = setsockopt(this->m_fdSocket, SOL_SOCKET, SO_RCVTIMEO,(const char*) &time_val_struct, sizeof(time_val_struct)); if (return_value == -1) return; How do I disable the timeout using the same command? A: You have to set the timeout value to 0. This will do the trick. struct timeval time_val_struct; time_val_struct.tv_sec = 0; time_val_struct.tv_usec = 0; A reference can be found here: https://linux.die.net/man/7/socket If the timeout is set to zero (the default) then the operation will never timeout
{ "language": "en", "url": "https://stackoverflow.com/questions/49706883", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Appach Guacomole JS RDP window scaling I'm using javascript Apache Guacamole Client on my website for RDP control. I've faced a problem - on window resize display wasn't resized. I've tried to use "scale" method of Guacamole Display: guac = new Guacamole.Client(tunnel); ... guac.getDisplay().scale(myScale); This method changes display size. However when the resize is performed, mouse coordinates are kept as they were on client. So mouse pointer on client and on web screen are not matched. A: The Fix is to apply scaling to mouse coordinates too: let scale = 1; $(document).ready(function ($) { $(window).resize(function () { nsZoomZoom(); }); //Get screen resolution. origHeigth = window.screen.height * window.devicePixelRatio; origWidth = window.screen.width * window.devicePixelRatio; nsZoomZoom(); function nsZoomZoom() { //Calculating scalse let htmlWidth = $(window).innerWidth(); var htmlHeigth = $(window).height(); var xscale = htmlWidth / origWidth; var yscale = htmlHeigth / origHeigth; //This is done to handle both X and Y axis slacing scale = Math.min(xscale, yscale); //Add 10% to scale because window always less than screen resolution scale += scale / 10; //Change Cuacamole Display scale guac.getDisplay().scale(scale); } }); ... guac = new Guacamole.Client(tunnel); const guacEl = guac.getDisplay().getElement(); rootEl.appendChild(guacEl); mouse = new Guacamole.Mouse(guacEl); mouse.onmousedown = mouse.onmouseup = (state) => guac.sendMouseState(state); //The fix is here mouse.onmousemove = (state) => { updateMouseState(state); }; //Handle mouse coordinates scaling let updateMouseState = (mouseState) => { mouseState.y = mouseState.y / scale; mouseState.x = mouseState.x / scale; guac.sendMouseState(mouseState); } I hope it'll help someone. A: kban,When drag and drop browser’s right-down corner,gua display zone will left a blank(down or right direction),this seems only executing browser’s guacamole js's scale function,how to solute this problem ?enter image description here
{ "language": "en", "url": "https://stackoverflow.com/questions/61098287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Check for a variable being categorized differently in dataset R I'm trying to write some sort of function in R that can solve a particular problem for me. Issue: I have a large dataset of 20,000 observations. Each observation has 13 features, one of them is the city, and the other is the county. I'm trying to think of an efficient way to check whether or not any city appears in different counties. For instance, I noticed this anomaly in the data: City | County San Francisco | San Francisco County San Francisco | Alpine County I'm trying to determine a simple way to check other instances of this. I considered using table(data$city, data$county) However, it seems error prone since there are 10 counties and hundreds of cities, so trying to manually check seems inconvenient in terms of accuracy. I'm thinking of a simple for loop with something inside for (x in 1:length(data$city)){ if (data$city %in% } I was trying to check if the city appears in multiple counties to see if there were any geographical anomalies or dirty data. However creating a for loop in this context seems more difficult than it should be since R is designed differently than a language such as C++. Can someone help me to create some way to test my problem? A: One way to do this is to use tapply() function: df <- data.frame(City=c( "city1","city2","city3","city1","city2","city5"), County = c("a", "b","a","b","a","b")) df$City[which(tapply(df$County, df$City, length) > 1)] This will create the following output: > df$City[which(tapply(df$County, df$City, length) > 1, useNames=FALSE)] [1] city1 city2 Levels: city1 city2 city3 city5 As you can see from the above - it will list which cities are in more than 1 region. A: We can use tidyverse library(dplyr) df %>% group_by(City) %>% filter(n_distinct(County) > 1) %>% distinct(City) %>% pull(City) #[1] city1 city2 #Levels: city1 city2 city3 city5
{ "language": "en", "url": "https://stackoverflow.com/questions/50093453", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: use a class from the other child module in maven I have two child modules, A and Util. And I have added the dependency in the pom file of A likes: <dependency> <groupId>xxx</groupId> <artifactId>Util</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> With this, I can use the class of Util in module A. But when I want to generate the jar of A, there is an error of xxx does not exit where xxx es the class of module Util. I want to know how I can generate the .jar Update: The error information is: And After I added the dependency, there is not the .jar in the Maven dependencies, it is a file "Util": The Util module is : I also used "maven install" in Util and the result is: The command I used to generate is "mvn clean package -DskipTests=true" A: I was also facing same issue. What I did this: Just right click on maven dependencies of project A > select properties > click on use maven project settings > uncheck Resolve dependencies from Workspace projects Eclipse displays that when the dependency is found in the same workspace. You can disable this in maven or project settings, then you'd need to build using mvn to see your dependency jar listed like other. A: I have solved it! the dependency should be: <dependency> <groupId>AWSTest</groupId> <artifactId>AWSUtil</artifactId> <version>0.0.1-SNAPSHOT</version> <type>test-jar</type> </dependency>
{ "language": "en", "url": "https://stackoverflow.com/questions/46564146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Convert varbinary value to string to get the same value I need to convert the VarBinary value to a String value and I want to get the same value as VarBinary. Please see the below: DECLARE @RFID INT SET @RFID = 1292202724 SELECT CONVERT(VARBINARY(8), @RFID) AS 'VARBINARY_VALUE' SELECT CAST((CONVERT(VARBINARY(8), @RFID)) AS NVARCHAR) AS 'STRING_VALUE' --Using Cast SELECT CONVERT(NVARCHAR(15),(CONVERT(VARBINARY(8), @RFID))) AS 'STRING_VALUE' --Using Convert Below is the result: What I want is the string value should get the same value "0x4D0572E4" as VarBinary value. But as you can see, I cannot convert to string. If you have the solution, please let me know. A: When you look at the official docs for convert you find that for binary data there is a style option of 0, 1, 2. Style option 1 gives the value in hex format. DECLARE @RFID INT = 1292202724; SELECT CONVERT(VARBINARY(8), @RFID) AS 'VARBINARY_VALUE'; SELECT CONVERT(NVARCHAR(15), CONVERT(VARBINARY(8), @RFID), 1 /* style 1 */) AS 'STRING_VALUE'; --Using Convert
{ "language": "en", "url": "https://stackoverflow.com/questions/62125289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Generate code coverage reports for Android Maven Library Project I have a Android Library project and an Android Test project. The test project has Android dependency and junit dependency. The modules are: * *MyProject *MySample *MyProjectTest MySample uses MyProject as a library and gives an apk as output. MyProjectTest has MySample as dependency and it has the test cases. The unit test cannot run on jvm. That is why MySample project is used which generates an apk and the unit tests can run on the emulator. They run as instrumented tests as they need an emulator to execute. There are lots of documentation available for an ant build but very few for maven android project. I have configured emma for code coverage, but the coverage files are not generated. My poms follow this link.https://code.google.com/p/maven-android-plugin/wiki/EmmaMaven with the following modification. * *The tested.project.dir is set to MySample */data/data/(package of MySample)/files/coverage.ec in property pullSource I get the error: "Cannot pull coverage.ec from device as it doesnt exist." Please help. Any pointer to the same is much appreciated. Also I am open to any coverage tools. My only constraint is I need to test Maven Android Library Project. I tried with cobertura too but still couldnt generate any coverage reports.
{ "language": "en", "url": "https://stackoverflow.com/questions/16438302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Logs from spring boot with quartz not printing[using log4j2] I m using Spring boot with Quartz along with log4j2.properties. The logs related to quartz jobs are not getting printed. All other logs are getting printed. Should I add any specific config for getting this printed? public class Scheduler { private static Logger log = LogManager.getLogger(); public static void main(String[] args) throws Exception { //following getting printed log.info("Scheduler is testing"); SpringApplication.run(Scheduler.class, args); } @Scheduled(cron="*/2 * * * * *") public void execute() { //following not getting printed log.info("Scheduler ...."); } } The logs from cron are not printing. I am using log4j2.properties for configuring. The properties I am using: #START name=PropertiesConfig #Folder location property.filename = /Users/folder #both console and file appenders = console, file rootLogger.level = debug rootLogger.appenderRefs = stdout rootLogger.appenderRef.stdout.ref = STDOUT appender.console.type = Console appender.console.name = STDOUT appender.console.layout.type = PatternLayout appender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n appender.file.type = File appender.file.name = LOGFILE appender.file.fileName=${filename}/gt.log appender.file.layout.type=PatternLayout appender.file.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n loggers=file #Project package base logger.file.name=com.mypackage logger.file.level = debug logger.file.appenderRefs = file logger.file.appenderRef.file.ref = LOGFILE #END A: Make sure your execute() method just being invoked. If you're using @Scheduled, make sure that you have the @EnableScheduling annotation, for example: @SpringBootApplication @EnableScheduling // Make sure this is present public class ScheduledTaskApplication { private static final Logger log = LogManager.getLogger(); public static void main(String[] args) { log.info("Scheduler is testing"); SpringApplication.run(ScheduledTaskApplication.class, args); } @Scheduled(cron="*/2 * * * * *") public void execute() { //following not getting printed log.info("Scheduler ...."); } } Additionally, make sure that you configured the logging.config property in application.properties: logging.config=classpath:log4j2.properties If you don't do this, it seems that the logging behaves weird, since the message in main() will be written to the proper logger, but afterwards it changes it to the rootLogger, causing all other messages within that class (not only the messages within test() to be written to the console).
{ "language": "en", "url": "https://stackoverflow.com/questions/46419637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to rename only one string from ng-repeat Refer the below code, I am getting 0: {status: "DRAFT", $$hashKey: "object:282"} 1: {status: "SUBMITTED", $$hashKey: "object:283"} 2: {status: "APPROVED", $$hashKey: "object:284"} 3: {status: "REJECTED", $$hashKey: "object:285"} 4: {status: "RESUBMIT", $$hashKey: "object:286"} 5: {status: "APPROVAL_NR", $$hashKey: "object:287"} length: 6 __proto__: Array(0) as a response in "statusdata", I am using ng-repeat to display these data as a dropdown. I want to rename the last "approval_nr" in the view. A: From angular docs: https://docs.angularjs.org/api/ng/directive/ngRepeat You can use $last. $last boolean true if the repeated element is last in the iterator. You can also check this one: Different class for the last element in ng-repeat. I would implement it like the following: function renameIfLast(name, isLast) { if (isLast) { return name.toUpperCase(); // do you rename logic here << } else { return name; } } <h1 ng-repeat="x in records">{{renameIfLast(x.status, $last)}}</h1>
{ "language": "en", "url": "https://stackoverflow.com/questions/58182886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Exporting json from Angular Library I created a library that I wish to contain a collection of default json configuration objects that the user can use in consuming application. I put these json objects in json files, set resolveJsonModue: true in my tsconfig to allow importing json files, import them into a barrel index.ts, and try to export them in my public-api.ts. I get the following error: Module parse failed: Unexpected token (1:9) File was processed with these loaders: * ../../node_modules/@ngtools/webpack/src/index.js You may need an additional loader to handle the result of these loaders. > export * as areacharts from './area-charts'; I'm pretty sure this is because I'm just json files here. Is there a way I export elements from my .json files from my library, or should I move them to .ts files?
{ "language": "en", "url": "https://stackoverflow.com/questions/63037292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: filter mongoose documents based on the specific fields and attributes I'm developing a website using the MEAN stack (MongoDB/Express/Angular/Node). I have a product schema with 12 different fields/properties, including size, color, brand, model, etc. What is the best and most efficient way to filter products, in Angular or on the server-side?And how can i chain the results if the client had selected more than one property?What would that look like? A: Assuming there will be a lot of products, it will be too much to download to the client in order to filter using Angular. It doesn't scale very well. As the list of products gets bigger and bigger, it will be less and less performant. The better way would, generally, be to let MongoDB do the filtering for you. It's very fast. But, you can control the filtering from Angular by posting to the server the filtering term you want on the endpoint used for that method of filtering, for example, using the http module http.post('/api/filter/' + methodOfFiltering, { 'term': termtoFilterBy }, function(dataReturned) { // use dataReturned to do something with the data }); Put this in an angular service method, so you can inject it into any of your controllers/components. Create an endpoint that will use the method and the keyword in the mongoose query. I'm assuming that you're using Express for your server routes. app.post('/api/filter/:method', function(req, res) { var method = req.params.method; var termToFilterBy = req.body.term; productSchema.find({method: termToFilterBy}, function(err, products) { res.send(products); }); }); Let me know if this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/40267298", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: React-d3 Line Chart not showing and showing no errors I'm trying to create my first react d3 line chart but I'm running into a snag. There are no errors showing up when I inspect Chrome so I'm not sure why it's not showing up. I feel like I'm close though. I've tried to look at other examples but I don't find many with csv examples for some reason. Here is my code: import React, { useRef, useEffect, useState } from "react"; import * as d3 from "d3"; import csvData from "../sandbox.csv"; import { select, line, curveCardinal, axisBottom, axisRight, scaleLinear, } from "d3"; function ActionsLineGraph() { const [data, setData] = useState(null); const [loading, setLoading] = React.useState(true); // const [data, setData] = useState([25, 30, 45, 60, 20, 65, 75]); const svgRef = useRef(); // will be called initially and on every data change useEffect(() => { d3.csv(csvData).then((data) => { // console.log("Fetching Data"); console.log(data); setData(data); setLoading(false); const svg = select(svgRef.current); const xScale = scaleLinear() .domain([0, data.length - 1]) .range([0, 300]); const yScale = scaleLinear().domain([0, 150]).range([150, 0]); const xAxis = axisBottom(xScale) .ticks(data.length) .tickFormat((index) => index + 1); svg.select(".x-axis").style("transform", "translateY(150px)").call(xAxis); const yAxis = axisRight(yScale); svg.select(".y-axis").style("transform", "translateX(300px)").call(yAxis); // set the dimensions and margins of the graph const margin = { top: 20, right: 20, bottom: 50, left: 70 }, width = 300 - margin.left - margin.right, height = 150 - margin.top - margin.bottom; // add X axis and Y axis const x = d3.scaleTime().range([0, width]); const y = d3.scaleLinear().range([height, 0]); const parseTime = d3.timeParse("%Y-%m-%d"); const myLine = d3.line() .x(d => x(xScale(parseTime(d.date)))) .y(d => y(yScale(Number(d.added)))); /* const myLine = d3.line() .x((d) => { return x(parseTime(d.date)); }) .y((d) => { return y(Number(d.added)); }); */ svg .append("path") .data([data]) .attr("class", "line") .attr("fill", "none") .attr("stroke", "steelblue") .attr("stroke-width", 10) .attr("d", myLine) .style('overflow', 'visible') // .style("transform", "translate(500px, 150px)"); }); }, []); return ( <React.Fragment> <svg ref={svgRef}> <g className="x-axis" /> <g className="y-axis" /> </svg> </React.Fragment> ); } export default ActionsLineGraph; Here is my csv data I'm using: date,added,updated,deleted 2021-09-15,10,9,8 2021-09-16,20,11,7 2021-09-17,15,12,9 2021-09-18,20,9,8 2021-09-19,20,9,8 Currently, it just shows the tips of the axes Any and all help or direction is appreciated. A: Your code contains some errors. See a solution in the snippet: const csvData = `date,added,updated,deleted 2021-09-15,10,9,8 2021-09-16,20,11,7 2021-09-17,15,12,9 2021-09-18,20,9,8 2021-09-19,20,9,8 `; const ActionsLineGraph = (props) => { const svgRef = React.useRef(); // will be called initially and on every data change React.useEffect(() => { const data = d3.csvParse(csvData); console.log(data); const parseTime = d3.timeParse("%Y-%m-%d"); const svg = d3.select(svgRef.current); const from = parseTime(data[0].date); const to = parseTime(data[data.length-1].date); console.log('FROM: ', from); console.log('TO: ', to); const xScale = d3.scaleTime() .domain([to, from]) .range([300, 0]); const yScale = d3.scaleLinear().domain([0, 30]).range([150, 0]); const xAxis = d3.axisBottom(xScale) .ticks(data.length) .tickFormat((index) => index + 1); svg.select(".x-axis").style("transform", "translateY(150px)").call(xAxis); const yAxis = d3.axisRight(yScale); svg.select(".y-axis").style("transform", "translateX(300px)").call(yAxis); // set the dimensions and margins of the graph const margin = { top: 20, right: 20, bottom: 50, left: 70 }, width = 300 - margin.left - margin.right, height = 150 - margin.top - margin.bottom; // add X axis and Y axis const x = d3.scaleTime().range([0, width]); const y = d3.scaleLinear().range([height, 0]); const path = data.reduce((path, item, index) => { const x = xScale(parseTime(item.date)); const y = yScale(Number(item.added)); const point = `${x},${y}`; return index === 0 ? `M ${point}` : `${path} L ${point}`; }, null); console.log('PATH: ', path); svg.append("path") .attr("class", "line") .attr("fill", "none") .attr("stroke", "steelblue") .attr("stroke-width", 10) .attr("d", path) }, [svgRef]); return ( <svg ref={svgRef}> <g className="x-axis" /> <g className="y-axis" /> </svg> ); } ReactDOM.render(<ActionsLineGraph />, document.querySelector("#app")) <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.14.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.14.0/umd/react-dom.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.6.1/d3.min.js"></script> <div id="app"></div>
{ "language": "en", "url": "https://stackoverflow.com/questions/73210086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In Layman's Terms, What Purpose Does the Warning Header Field in HTTP/1.1 Serve? Related Questions: * *HTTP 403 Response vs HTTP 401 Response *Is it Possible to Send an HTTP 401 and HTTP 302 Redirect with a Location Header? Background: I'm developing a PHP web application that will redirect clients to custom error pages based on the semantic errors encountered. The specific one related to my question is which error to serve when a client that is logged out attempts to access a resource that is protected. I've read people doing the following: * *Just use the PHP function header() to redirect using a standard HTTP 302 to your error page *Have a PHP script call a custom function that checks the permissions of the client and serves the appropriate error page as an included template *Utilize the existing Basic or Digest authentication built into HTTP. The Dilemma Since I'm using a PHP form-based methodology with sessions to authenticate users, and the HTTP 1.1 spec calls for a mandatory WWW-Authenticate header, I don't want to send a HTTP 401 response back ( even though it looks the most attractive to just send and deviate from spec ). Question I noticed an optional Warning Header under general headers that perhaps I could use to send also with my request. Can I use the warning header to show to a client that my particular response is semantically different than an assumed generic response?
{ "language": "en", "url": "https://stackoverflow.com/questions/21141746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: unable to post data from react js to node js I am following a mern stack tutorial and trying to send data to api from react js form which is: import axios from 'axios' import { useState } from 'react' import './share.css' export default function Share() { const [username, setUsername] = useState('') const [file, setFile] = useState(null) const handleSubmit = async(e)=>{ e.preventDefault() const newPost = { username: username } if(file){ const data = new FormData() const fileName = file.name data.append('name', fileName) data.append('file', file) newPost.pic = fileName console.log(newPost) try{ await axios.post('http://localhost:5000/upload', data) }catch(err){ console.log(err) } } try{ await axios.post('http://localhost:5000/post/post', newPost) }catch(err){ console.log(err) } } return ( <form className='share' onSubmit={handleSubmit}> <div className='shareTop'> <span>M</span> <input className='shareInput' type='text' placeholder="What's happening?" onChange={(e)=>setUsername(e.target.value) } /> </div> <div className='shareBottom'> <div className='bottomIcons'> <label htmlFor='file'> <i class="fa-solid fa-face-meh"></i> <input type='file' style={{display:"none"}} name='file' id='file' onChange={(e)=>setFile(e.target.files[0])} /> </label> <i class="fa-solid fa-calendar"></i> <i class="fa-solid fa-notes"></i> <i class="fa-solid fa-bookmark"></i> </div> <button type='submit'>Tweet</button> </div> </form> ) } and my index js (serve side) file is: const express = require('express') const app = express() const mongoose = require('mongoose') const helmet = require('helmet') const morgan = require('morgan') const postRoute = require('./routes/posts') const multer = require('multer') const bodyParser = require('body-parser') const cors = require('cors') app.use(cors()) app.use(express.json()) app.use(morgan('common')) app.use(helmet()) app.use(express.static('uploads')) const storage = multer.diskStorage({ destination: function(req, file, cb){ cb(null, './uploads') }, filename: function(req, file, cb){ cb(null, req.body.name) } }) const upload = multer({storage}); app.post('/upload', upload.single('file'), (req, res)=>{ }) app.use('/post/', postRoute) mongoose.connect('mongodb://localhost:27017/twitter').then(()=>{ console.log("Connected to Database") }) app.listen(5000, ()=>{ console.log('Listening') }) and posts route is: const express = require('express') const router = express.Router() const Post = require('../models/Post') router.post('/post', async(req, res)=>{ const post = new Post({ username: req.body.username, pic: req.body.pic }) try{ const newPost = await post.save() console.log("post has been saved") res.status(200).json("Post has been saved") }catch(err){ res.status(500).json(err) } }) router.put('/:id', async(req, res)=>{ const post =await Post.findByIdAndUpdate(req.params.id, {$set:req.body}) res.status(200).json("Account has been updated") }) router.get('/', async (req, res)=>{ const posts = await Post.find() res.status(200).json(posts) }) router.delete('/', async(req, res)=>{ await Post.deleteMany() }) module.exports = router So the problem is that the file is being uploaded to backend but the data does not, after doing some research i realized that the second try and catch block where i am posting the content is not being called, just the first api where we upload file is being called, can someone tell me what am i doing?
{ "language": "en", "url": "https://stackoverflow.com/questions/71983376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Delete a Entire Reg Directory using Perl I would like to Delete the Registry in Windows Machine using a perl command. How can I do that . I tried few command from Internet it is getting executed but not deleted Please provide help !! The below code executes , but doesn't delete the Reg Key use warnings; use strict; use Win32::TieRegistry( Delimiter=>"/", ArrayValues=>0 ); my $myway= delete $Registry->{"HKEY_LOCAL_MACHINE/SOFTWARE/Keypath"}; print "Done"; A: First you need the right permission to delete a registry key (try run the Perl script from a CMD with admin privileges), second according to the documentation you can only delete a key provided it does not contain any subkeys: You can use the Perl delete function to delete a value from a Registry key or to delete a subkey as long that subkey contains no subkeys of its own. Third, even if you run with admin privileges there can still be keys that you cannot delete, see this Q&A for more information. So if you want to delete an entire subtree, you need to iterate bottom up through the tree and delete each subkey separately. Here is an example: use feature qw(say); use warnings; use strict; use Data::Dumper qw(Dumper); use Win32::RunAsAdmin qw(force); use Win32API::Registry qw(regLastError KEY_READ KEY_WRITE); use Win32::TieRegistry( Delimiter=>"/", ArrayValues=>0 ); { # Choose the top root node that should be deleted # Note: This and all its subkeys will be deleted from the registry. # Note: Will only succeed if you have permission to write to each sub key my $top_key_name = "HKEY_CLASSES_ROOT/Directory/Background/shell/Foo"; my $tree = $Registry->Open( $top_key_name, { Access=>KEY_READ()|KEY_WRITE(), Delimiter=>"/" } ); die "Could not open key $top_key_name: $^E" if !defined $tree; delete_subtree( $tree, my $level = 0); } sub delete_subtree { my ($tree, $level) = @_; my $path = $tree->Path(); my @subkeys = $tree->SubKeyNames(); for my $name (@subkeys) { my $subtree = $tree->{$name."/"}; if (!defined $subtree) { die "Cannot access subkey $name for $path: " . regLastError() . ". Abort."; } if (ref $subtree) { delete_subtree($subtree, $level + 1); } else { die "Subkey $name for $path is not a hash ref. Abort."; } } # assuming the previous recursive code has deleted all sub keys of the # current key, we can now try delete this key say "Trying to delete $path .."; my $res = delete $Registry->{$path}; if (!defined $res) { die "..Failed to delete key : $^E"; } else { say " -> success"; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/63021710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: React onMouse doesnt fire on iOS devices I've built a React app which works fine in the computer, but the button won't fire on my iOS phone. I've tried adding the cursor:'pointer' like that: <button onClick={() => setdata((previous) => !previous)} type="button" style={{ cursor: 'pointer' }}>Start</button> I've also added it in the .css of the button. (in all 3 widths I'm using, for mobile/tablet/pc) Tried onMouseClick / onClick / etc.. doesn't help. Any ideas? A: You've tried onMouseDown? <button onMouseDown={() => setdata((previous) => !previous)} type="button" style={{ cursor: 'pointer' }} > Start </button> source: https://stackoverflow.com/a/37273344/19503616 A: It's possible that the issue might be with the type of the button or with the way the event handler is being attached to the button. Try changing the type of the button from "button" to "submit". Also, make sure that the onClick event handler is correctly attached to the button component. Here's how it should look: <button type="submit" onClick={() => setdata((previous) => !previous)} style={{ cursor: 'pointer' }}>Start</button> If the above does not work, try debugging the issue by using console.log statements within the event handler to check if it's being called.
{ "language": "en", "url": "https://stackoverflow.com/questions/75348195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android whatsapp attachment icon 1) when I use some apps to send a file to whatsapp directly, there is an icon text (DB) and extra text under the icon (DB). pls see below pic. However, my code below gives me plain icon (without DB) and without extra text Uri lvUri = FileProvider.getUriForFile(pActivity, BuildConfig.APPLICATION_ID + ".provider", pFile); Intent intent = new Intent(pAction); intent.putExtra(Intent.EXTRA_EMAIL, new String[] { }); intent.putExtra(Intent.EXTRA_SUBJECT, "EXTRA_SUBJECT"); intent.putExtra(Intent.EXTRA_TEXT, "EXTRA_TEXT"); intent.putExtra(Intent.EXTRA_STREAM, lvUri); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setType("application/xml"); 2) is there any way to send an attachment together with a message at the same time? thank you A: You have to draw over using a suitable Layout like RelativeLayout. Using ImageView and TextView, it is possible to have such result.
{ "language": "en", "url": "https://stackoverflow.com/questions/45945101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Beginner Q: How to use variables declared in if/else indentation I've tried everything I can think of at this point. I am trying to create my first game in which the player can make choices by entering one-word answers. The game works when the questions are isolated. However, if I want to create a decision that redirects the player to another part of the game (Lines 7 to direct to line 10 through river1 variable), I receive the error: NameError: name 'river1' is not defined, even though I defined it in the 7th line. I assume it is because it is defined within an indentation. However, I don't know how to fix that and still have it work as required. Any help would be appreciated. Thanks print("Welcome to Treasure Island! \nIts your mission to find the treasure.") crossroads = input("You begin at a cross roads, do you go left or right? ").lower() if crossroads == "left": enemies = input("You ran into enemies, attack? ").lower() if enemies == "no": print("You ran to the lake") river1 = input("You found a long river, it leads somewhere. Swim or wait? ").lower() else: print("You were overpowered and died, game over") if crossroads == "right": river1 if river1 == "swim": print("You swam and drowned, Game over") else: print("You found a boat") A: Explaining the workflow of your program. I tried your program & got this C:\Users\LENOVO\Desktop\so>python try.py Welcome to Treasure Island! Its your mission to find the treasure. You begin at a cross roads, do you go left or right? left You ran into enemies, attack? no You ran to the lake You found a long river, it leads somewhere. Swim or wait? right C:\Users\LENOVO\Desktop\so>python try.py Welcome to Treasure Island! Its your mission to find the treasure. You begin at a cross roads, do you go left or right? right Traceback (most recent call last): File "try.py", line 11, in <module> river1 NameError: name 'river1' is not defined The reason river1 is not defined and you getting that error is because when I entered "right" the program goes to the 2nd if thus since crossroads == "left" will be False. When it executes the code on the second if there is REALLY NO variable or object named river1. Why is there no river1 variable where you created or put it on the first if? Well that is because the first if does not even get executed (when I enter "right") thus NOT creating your river1 variable. You might think once you put it there it will be created but it will only be created when that part of code is executed. So if you would like to have a variable river1 globally you can create it a top and initialize it let's say None or an empty string , your call. river1 = '' print("Welcome to Treasure Island! \nIts your mission to find the treasure.") crossroads = input("You begin at a cross roads, do you go left or right? ").lower() if crossroads == "left": enemies = input("You ran into enemies, attack? ").lower() if enemies == "no": print("You ran to the lake") river1 = input("You found a long river, it leads somewhere. Swim or wait? ").lower() else: print("You were overpowered and died, game over") if crossroads == "right": river1 if river1 == "swim": print("You swam and drowned, Game over") else: print("You found a boat") A: For variables that may only be defined under certain circumstances, you have a couple of options. First, you can declare them all beforehand: print("Welcome to Treasure Island! \nIts your mission to find the treasure.") crossroads = input("You begin at a cross roads, do you go left or right? ").lower() enemies = None river1 = None if crossroads == "left": ... Or, you can test to see if they exist: if crossroads == "right": if river1 and river1 == "swim": ... A: I believe that what you are looking for is how to reuse your code. Use functions. def river1_func(): choice = input("You found a long river, it leads somewhere. Swim or wait? ").lower() if choice == "swim": print("You swam and drowned, Game over") else: print("You found a boat") if __name__ == "__main__": print("Welcome to Treasure Island! \nIts your mission to find the treasure.") crossroads = input("You begin at a cross roads, do you go left or right? ").lower() if crossroads == "left": enemies = input("You ran into enemies, attack? ").lower() if enemies == "no": print("You ran to the lake") river1_func() else: print("You were overpowered and died, game over") if crossroads == "right": river1_func()
{ "language": "en", "url": "https://stackoverflow.com/questions/65360235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get the values of each row of a .txt(CSV) file array I am trying to get the values of an array (example trips_list.trip_id should pour out all the trip_id(s) of the array trips_list.) .trips.txt file : route_id,service_id,trip_id,trip_headsign,trip_short_name,direction_id,shape_id,wheelchair_accessible,bikes_allowed TaSj-16APR,CT-16APR-Caltrain-Saturday-02,23a,DIRIDON STATION,23,0,cal_tam_sj,, TaSj-16APR,CT-16APR-Caltrain-Saturday-02,25a,DIRIDON STATION,25,0,cal_tam_sj,, TaSj-16APR,CT-16APR-Caltrain-Saturday-02,27a,DIRIDON STATION,27,0,cal_tam_sj,,................. Here is what I have for now : function get(url) { return new Promise(function(resolve, reject) { var req = new XMLHttpRequest(); req.open('GET', url); req.onload = function() { if (req.status == 200) { resolve(req.response); } else { reject(Error(req.statusText)); } }; req.onerror = function() { reject(Error("Network Error")); }; req.send(); }); } get('../data/trips.txt').then(function(response) { //console.log("Success!", response.split(/(\r\n|\n)/)); var trips_list = response.split(/(\r\n|\n)/); if(Array.isArray(trips_list)) { console.log('true'); } else { console.log('Not An Array') } var re = /,/; var headers = trips_list.shift().split(re); var route_id = headers.indexOf("route_id"); var service_id = headers.indexOf("service_id"); var trip_id = headers.indexOf("trip_id"); var trip_headsign = headers.indexOf("trip_headsign"); var mainArray = trips_list.map(function(val, key) { return val.split(re); }).filter(Boolean); var trip_id = headers.indexOf("trip_id"); var tripid = trips_list.map(function(val, key) { return val.split(re)[trip_id]; }).filter(Boolean); var service_id = headers.indexOf("service_id"); var serviceid = trips_list.map(function(val, key) { return val.split(re)[service_id]; }).filter(Boolean); var route_id = headers.indexOf("route_id"); var routeid = trips_list.map(function(val, key) { return val.split(re)[route_id]; }).filter(Boolean); var tripstr = ''; var i; for (i = 0; i < routeid.length; i++) { tripstr += '<div class="tripper"><b>RID:</b> <em>'+routeid[i]+'</em> <b>SID:</b> <em>'+serviceid[i]+'</em> <b>TID:</b> <em>'+tripid[i]+'</em></div>'; } tripResults.innerHTML = tripstr; //console.log(tripstr); }, function(error) { console.error("Failed!", error); }); Browser output: RID: SID: CT-16APR-Caltrain-Saturday-02 TID: 23a RID: TaSj-16APR SID: CT-16APR-Caltrain-Saturday-02 TID: 25a RID: SID: CT-16APR-Caltrain-Saturday-02 TID: 27a RID: TaSj-16APR SID: CT-16APR-Caltrain-Saturday-02 TID: 01a RID: SID: CT-16APR-Caltrain-Saturday-02 TID: 29a RID: TaSj-16APR SID: CT-16APR-Caltrain-Saturday-02 TID: 31a RID: SID: CT-16APR-Caltrain-Saturday-02 TID: 33a................. RID: Lo-16APR SID: undefined TID: undefined RID: SID: undefined TID: undefined RID: Lo-16APR SID: undefined TID: undefined RID: SID: undefined TID: undefined RID: Lo-16APR SID: undefined TID: undefined RID: SID: undefined TID: undefined RID: Lo-16APR SID: undefined TID: undefined My output is skipping values and sometimes printing out undefine. Any better way to get the values(route_id,service_id,trip_id,trip_headsign,trip_short_name,direction_id,shape_id,wheelchair_accessible,bikes_allowed) of the text file for each row?
{ "language": "en", "url": "https://stackoverflow.com/questions/36821807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to store python code output to csv file i want to store my python code result in to csv file but here is my python code i am not show my python result in my csv file import csv import json from collections import Counter with open('result.csv', 'w') as output: with open('simplejson2.json', 'r') as f: str1=f.read() output_data=csv.writer(output, delimiter=',') data_csv= csv.reader(f, delimiter=',') data=json.loads(str1) c = Counter(k[:] for d in data for k, v in d.items() if k.startswith('sta') and v) output_data.writerow(d) print("there are total", c['status'], "test case") c = Counter(k[:] for d in data for k, v in d.items() if k.startswith('status') and v.startswith('failed')) output_data.writerow(d) if c['status'] > 0: print("There are", c['status'], "failed cases") else: print("there are", c['status'], "sucessfully pass") this is my simplejson2.json file [ { "status": "passed", "name": "Whiskers", "species" : "cat", "foods": { "likes": ["celery", "strawberries"], "dislikes": ["carrots"] } }, { "status": "failed", "name": "Woof", "species" : "dog", "foods": { "likes": ["dog food"], "dislikes": ["cat food"] } }, { "status": "failed", "name": "Fluffy", "species" : "cat", "foods": { "likes": ["canned food"], "dislikes": ["dry food"] } } ] my python code output is :- there are total 3 test case there are 2 test case failed A: You are trying to save d in csv which is not assigned anywhere. You are assigning d here only which will not be available outside here. Or you want to save c in csv but mistakenly you wrote d. Edit according to comment: with open('simplejson2.json', 'r') as f: str1=f.read() data_csv= csv.reader(f, delimiter=',') You can read f only inside with. If you are trying to read f outside with then the file is already closed you give you that error. A: no idea what you are trying to achieve (or why you need a counter instead of just using len), but this is a working version of your code: import csv import json from collections import Counter with open('result.csv', 'w') as output: with open('simplejson2.json', 'r') as f: str1=f.read() output_data=csv.writer(output, delimiter=',') data_csv= csv.reader(f, delimiter=',') data=json.loads(str1) status_fields = [k[:] for d in data for k, v in d.items() if k.startswith('sta') and v] c = Counter(status_fields) output_data.writerow(status_fields) print("there are total", c['status'], "test case") status_fields_failed = [k[:] for d in data for k, v in d.items() if k.startswith('status') and v.startswith('failed')] c = Counter(status_fields_failed) output_data.writerow(status_fields_failed) if c['status'] > 0: print("There are", c['status'], "failed cases") else: print("there are", c['status'], "sucessfully pass") content of generated file result.csv status,status,status status,status changes made: * *indentation *fixed for-loop expression (d undefined, iterable required by Counter constructor)
{ "language": "en", "url": "https://stackoverflow.com/questions/68407537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Loop through keys in JSON array that start with specific key name Is there an efficient way to loop through the keys in a JSON array that start with the key name 'option' and either loop through them all or set a max? I'm currently doing this following: $.each(shopifyProductJSON.variants, function(index, variant) { variantOptions = new Array(); variantOptions.push(variant.option1); variantOptions.push(variant.option2); variantOptions.push(variant.option3); }); Which is fine but want it to be more dynamic in case more options are added in the future. An example of part of the JSON array for each variant: inventory_management: null inventory_policy: "deny" inventory_quantity: 0 old_inventory_quantity: 0 option1: "Bronze" option2: "Satin Gold" option3: "600mm" position: 1 price: "550.00" I thought this would've worked... variantOptions = new Array(); for (i = 1; i < 4; i++) { var key = 'option' + i; variantOptions.push(key); } A: To solve your immediate issue you need to access the objects properties in the loop, not push the string in to the array: let variantOptions = []; for (i = 1; i < 4; i++) { var key = 'option' + i; if (data.hasOwnProperty(key)) { variantOptions.push(data[key]); } } That being said, if the options are going to be of a dynamic length it makes far more sense to return them as an array instead of individual numbered properties, assuming you have control over the response format. You could change the response to this: { inventory_management: null inventory_policy: "deny" inventory_quantity: 0 old_inventory_quantity: 0 options: ['Bronze', 'Satin Gold', '600mm'], position: 1 price: "550.00" } Then the JS to access the options becomes a simple property accessor: let variantOptions = data.options;
{ "language": "en", "url": "https://stackoverflow.com/questions/53555957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Access View from Timer or Handler App crashes, I am unable to use the same view in Timer Class I need the app to refresh a value and display it Timer t = new Timer(); //Set the schedule function and rate t.scheduleAtFixedRate(new TimerTask() { @Override public void run() { //Called each time when 1000 milliseconds (1 second) (the period parameter) find(v); } }, //Set how long before to start calling the TimerTask (in milliseconds) 0, //Set the amount of time between each execution (in milliseconds) 10000); public void find(View view) { if (btAdapter.isDiscovering()) { //the button is pressed when it discovers, so cancel the discovery btAdapter.cancelDiscovery(); } else { BTArrayAdapter.clear(); btAdapter.startDiscovery(); registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND)); } } A: Usually in this situation you need to use Activity.runOnUiThread() Timer t = new Timer(); //Set the schedule function and rate t.scheduleAtFixedRate(new TimerTask() { @Override public void run() { //Called each time when 1000 milliseconds (1 second) (the period parameter) runOnUiThread(new Runnable() { public void run() {find(v);} }); } }, //Set how long before to start calling the TimerTask (in milliseconds) 0, //Set the amount of time between each execution (in milliseconds) 10000);
{ "language": "en", "url": "https://stackoverflow.com/questions/32953055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Add Multiple Apache Document Root under one port I'm looking to have 1 domain point to different drives in my pc. I've got my document root on D:\ working fine on port 80. But I also want drive E:\ to show when I load my domain. I understand I can use virtual hosts on different ports but thats not what I want because I want everything visible under the single domain of the root folder when I load www.example.com. Is this possible? A: No, you cannot have more than one domain root. You can use mod_alias to configure other file system paths for example, you could have: Alias /working d:/working Alias /other e:/
{ "language": "en", "url": "https://stackoverflow.com/questions/17030106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: async await not working with Timer I have a Presence monitor class which is used to detect users active/inactive status. That class has a timer in its Start method which called on application start: public class PresenceMonitor { private volatile bool _running; private Timer _timer; private readonly TimeSpan _presenceCheckInterval = TimeSpan.FromMinutes(1); public PresenceMonitor() { } public void Start() { // Start the timer _timer = new Timer(_ => { Check(); }, null, TimeSpan.Zero, _presenceCheckInterval); } private void Check() { if (_running) { return; } _running = true; // Dowork } } The "Check" method is fired after every one minute. That piece of code is working fine but now my "Do work" methods have become async await so I had to change this Presence Monitor class to something like this: public class PresenceMonitor { private volatile bool _running; private Timer _timer; private readonly TimeSpan _presenceCheckInterval = TimeSpan.FromMinutes(1); public PresenceMonitor() { } public void Start() { // Start the timer var timer = new System.Threading.Timer(async (e) => { await CheckAsync(); }, null, TimeSpan.Zero, _presenceCheckInterval); } private async Task CheckAsync() { if (_running) { return; } _running = true; // await DoworkAsync } } Unfortunately "CheckAsync" method now is getting fired once only instead of every minute. Can you tell me what I am doing wrong here to call async await after regular intervals? Is there any correct way to do the same? A: You could consider creating an event and handler to handle the timer ticks and then invoke your check. public class PresenceMonitor { private volatile bool _running; private Timer timer; private readonly TimeSpan _presenceCheckInterval = TimeSpan.FromMinutes(1); public PresenceMonitor() { Tick += OnTick; } public void Start() { if (_running) { return; //already running } // Start the timer timer = new System.Threading.Timer(_ => { Tick(this, EventArgs.Empty);//rasie event }, null, TimeSpan.Zero, _presenceCheckInterval); } private event EventHandler Tick = delegate { }; private async void OnTick(object sender, EventArgs args) { if (_running) { return; } _running = true; await DoworkAsync(); } private Task DoworkAsync() { //... } } A: If I understand correctly your requirements, you can get rid of timer and use asynchronous loop. But you need make Start method asynchronous too public class PresenceMonitor { private volatile bool _running; // possible not needed "volatile" anymore private readonly int _presenceCheckInterval = 60000; // Milliseconds public PresenceMonitor() { } public async Task Start() { while (true) // may be use some "exit" logic { await CheckAsync(); await Task.Delay(_presenceCheckInterval) } } private async Task CheckAsync() { if (_running) { return; } _running = true; // await DoworkAsync } } Then you can start monitoring var monitor = new PresenceMonitor(); await monitor.Start(); You can even start monitoring in synchronous way var monitor = new PresenceMonitor(); monitor.Start(); // Will start monitoring But approach above is "dangerous" in the way, that any exception thrown inside CheckAsync method will not be propagated. When you start using async-await be ready to "convert" whole application to support it.
{ "language": "en", "url": "https://stackoverflow.com/questions/46253554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to determine if a context-free grammar describes a regular language? Given an arbitrary context-free grammar, how can I check whether it describes a regular language? I'm not looking for exam "tricks". I'm looking for a foolproof mechanical test that I can code. If it helps, here's an example of a CFG that I might receive as an input. Specifically, notice that the answer must be much more complicated than just looking for left- or right-recursion, since the presence of another type of recursion does not automatically imply the grammar is irregular. S: A B C D X A: A a A: B: b B B: C: c C c C: c D: D d D D: d X: x Y X: Y: y X Y: A: There is no such mechanical procedure because the problem of determining whether a CFG defines a regular language is undecidable. This result is a simple application of Greibach's Thereom.
{ "language": "en", "url": "https://stackoverflow.com/questions/31643381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Jquery sliders not working together online,but they work fine on offline page The site www.grapho-line.com is using two sliders but only the main slider is working(the one with the big pictures).The thumbnail slider(right below the main jquery slider) is not working as you can see on site. However both work fine when i run the website on localhost. <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Home | Grapho Line Trading LLC</title> <link href="style.css" rel="stylesheet" type="text/css"> <link href="slider.css" rel="stylesheet" type="text/css"> <link href="themes/generic.css" rel="stylesheet" type="text/css" /> <link href="themes/1/slider2.css" rel="stylesheet" type="text/css" /> <script src="themes/jquery-1.7.1.min.js" type="text/javascript"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="s3Slider.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#slider1').s3Slider({ timeOut: 5000 }); }); </script> <script src="themes/1/jquery-slider.js" type="text/javascript"></script> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <script src="http://www.google.com/jsapi?key=AIzaSyA5m1Nc8ws2BbmPRwKu5gFradvD_hgq6G0" type="text/javascript"></script> <script type="text/javascript"> google.load("feeds", "1"); function feedLoaded(result) { if (!result.error) { var container = document.getElementById("homenews3content"); container.innerHTML = ''; for (var i = 0; i < result.feed.entries.length; i++) { var entry = result.feed.entries[i]; var div = document.createElement("div"); div.appendChild(document.createTextNode(entry.title)); container.appendChild(div); } } } function OnLoad() { var feed = new google.feeds.Feed("http://feeds.feedburner.com/KodakNewsReleases.xml"); feed.includeHistoricalEntries(); // tell the API we want to have old entries too feed.setNumEntries(3); feed.load(feedLoaded); } google.setOnLoadCallback(OnLoad); </script> <style> #main{ background:#fabd2b; height:740px; } </style> </head> <body> <div id="main"> <img src="logonew.png" id="kodaklogo" /> <img src="grapho.png" id="mainbackground"/> <div id="headmenu"> <ul id="nav"> <li><a href="index.html">HOME</a></li> <li class="sub"><a href="products.html">PRODUCTS</a> <ul> <li><a href="flexographic&letterpress.html"> &nbsp;Flexographic & Letterpress</a></li> <li><a href="offsetctp.html"> &nbsp;Offset CTP</a></li> <li><a href="proofing&wideformat.html"> &nbsp;Proofing & Wide Format</a></li> <li><a href="brandprotectionsolutions.html">&nbsp;Brand Protection Solutions</a></li> <li><a href="enterprisemarketing.html">&nbsp;Enterprise Marketing</a></li> <li><a href="productionworkflow.html">&nbsp;Production Workflow Solutions</a></li> <li><a href="colormanagement.html">&nbsp;Color Management & Screening</a></li> </ul> </li> <li><a href="aboutus.html">ABOUT US</a></li> <li><a href="contactus.html">CONTACT US</a></li> </ul> </div> <div id="slider1"> <ul id="slider1Content"> <li class="slider1Image"> <a href=""><img src="example_images/wide/flexcelnxplate.jpg" alt="1" /></a> <span class="left"><strong>KODAK FLEXCEL NX</strong><br /><br />KODAK FLEXCEL NX Plates are an important part of the KODAK FLEXCEL NX System. With the FLEXCEL NX System for the first time you can achieve gravure-class print quality on a wide variety of substrates.</span></li> <li class="slider1Image"> <a href="aboutus.html"><img src="example_images/wide/flexoplates.jpg" alt="2" /></a> <span class="left"><strong>KODAK FLEXCEL SR</strong><br /><br />KODAK FLEXCEL SR Flexographic Plates have been designed to bring brand owners confidence that their packaging will be produced reliably and consistently, and to bring printers of packaging materials increased productivity and peace of mind.</span></li> <li class="slider1Image"> <img src="example_images/wide/flexelnx.JPG" alt="3" /> <span class="left"><strong>KODAK FLEXCEL NX System</strong><br /><br />The KODAK FLEXCEL NX Wide System allows you to take full advantage of the unique benefits that KODAK FLEXCEL NX Plates offer.It utilizes the proven KODAK SQUARESPOT Imaging Technology to deliver exceptional image quality. </span></li> <li class="slider1Image"> <img src="example_images/wide/directengraving.jpg" alt="4" /> <span class="left"><strong>KODAK FLEXCEL Direct</strong><br /><br />The KODAK FLEXCEL Direct System offers a brand new approach to direct engraving of elastomers for flexographic printing.The FLEXCEL Direct System is ideal for both printers and prepress service providers</span></li> <li class="slider1Image"> <img src="example_images/wide/flexo.jpg" alt="6" /> <span class="left"><strong>KODAK FLEXCEL NX System</strong><br /><br />YOU CAN with the KODAK FLEXCEL NX System, a complete solution for digital plate making that enables you to push the boundaries of flexo printing.</span></li> <li class="slider1Image"> <img src="example_images/wide/m800.jpg" alt="5" /> <span class="left"><strong>KODAK MAGNUS 800</strong><br /><br />The KODAK MAGNUS 800 Platesetter is a reliable 8-page CTP device with advanced automation options, offering exceptional productivity and stability to meet the needs of offset printers.</span></li> <div class="clear slider1Image"></div> </ul> </div> <div id="homecenter"> <div class="div2"> <div id="mcts1"> <a href="productionworkflow.html"><img src="images/DigiCap_300x140_695X250.jpg" /></a> <a href="brandprotectionsolutions.html"> <img src="images/3-pharma-protection.jpg" /></a> <a href="colormanagement.html"> <img src="images/header_spotless_695X250.jpg" /></a> <a href="enterprisemarketing.html"> <img src="images/mqdefault.jpg" /></a> <a href="products/ctp/prepress.html"> <img src="images/IPM-Hero2_695x210_695X250.jpg" /></a> <a href="proofing&wideformat.html"> <img src="images/proofingandwideformat.jpg" /></a> <a href="flexographic&letterpress.html"> <img src="images/flexographic.jpg" /></a> <a href="products/proofing/kodakmatchprint.html"><img src="images/matchprint_IceCudesLo_695X250.jpg" /></a> </div> </div> <br/><br/> <div class="homenews3"> <b>&nbsp;&nbsp;&nbsp;Latest news from <a href="http://graphics.kodak.com" target="_blank" >Kodak Graphics</a></b><br/><br/> <div id="homenews3content"> </div> </div> </div> </div> </body> </html> A: Use a file search to see if the following path is valid: themes/1/
{ "language": "en", "url": "https://stackoverflow.com/questions/15113444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is Apple's documentation on ARCamera.transform orientation backwards? I'm having a hard time grasping the Apple documentation regarding the ARCamera.transform. Excerpt: In camera space, the x-axis points to the right when the device is in UIDeviceOrientationLandscapeRight orientation—that is, the x-axis always points along the long axis of the device, from the front-facing camera toward the Home button. Okay, so the positive x-axis points to the right, towards the Home button, when we are in landscape right... But the documentation for UIDeviceOrientationLandscapeRight says: The device is in landscape mode, with the device held upright and the home button on the left side. So in landscape right, the Home button is on the left. This contradicts the statement that the Home button and positive x-axis point to the right. What am I missing? Are the docs wrong? Do they intend to reference the documentation of UIInterfaceOrienation.landscapeRight? A: Looks like they've fixed their documentation for UIDeviceOrientationLandscapeRight: The device is in landscape mode, with the device held upright and the Home button on the right side.
{ "language": "en", "url": "https://stackoverflow.com/questions/58438950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: File and logger was not created for slf4j In my application i am using slf4j for logger. I have used logback.xml for configuration. While am running main class i am getting correct response, meaning for my testing purpose i write one main class. But same configuration after build and deploy i am not getting any response. Logger file also not created and log was not captured. Here i have mentioned my configuration xml file. logback.xml <?xml version="1.0" encoding="UTF-8"?> <configuration> <!-- Send debug messages to System.out --> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <!-- By default, encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder --> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{5} - %msg%n</pattern> </encoder> </appender> <!-- Send debug messages to a file at "c:/jcg.log" --> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>d:/Logs/truprovider.log</file> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <Pattern>%d{yyyy-MM-dd_HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern> </encoder> <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> <FileNamePattern>d:/Logs/truprovider.%i.log.zip</FileNamePattern> <MinIndex>1</MinIndex> <MaxIndex>10</MaxIndex> </rollingPolicy> <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <MaxFileSize>10MB</MaxFileSize> </triggeringPolicy> </appender> <logger name="com.cts.emblem.batch" level="INFO" additivity="false"> <appender-ref ref="STDOUT" /> <appender-ref ref="FILE" /> </logger> <!-- By default, the level of the root level is set to DEBUG --> <root level="INFO"> <appender-ref ref="STDOUT" /> </root> </configuration> A: Based on the information that you've provided its hard to tell what happens, I suspect (just a wild guess) that logging infrastructure wasn't configured at all, because this file somehow hasn't propagated to the artifact (WAR, I assume) When you run the application you can place a breakpoint on any log.*** message(like log.info) and check whether it has any assigned appenders in a list, again, as a hypothesis the list of appenders will be just empty. A: I am getting default logger for my wildfly server. After modified the server configuration the problem will solved. Place the jboss-deployment-structure.xml file under META-INF. jboss-deployment-structure.xml <?xml version="1.0" encoding="UTF-8"?> <jboss-deployment-structure> <deployment> <exclusions> <module name="org.apache.commons.logging" /> <module name="org.apache.log4j" /> <module name="org.jboss.logging" /> <module name="org.jboss.logging.jul-to-slf4j-stub" /> <module name="org.jboss.logmanager" /> <module name="org.jboss.logmanager.log4j" /> <module name="org.slf4j" /> <module name="org.slf4j.impl" /> </exclusions> </deployment> </jboss-deployment-structure>
{ "language": "en", "url": "https://stackoverflow.com/questions/50348987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to get dictionary max values I want to get keys of a dictionary, with top 5 values. For example numbers = {'one':1, 'two':2, 'three':3, 'four':4, 'five':5, 'six':6} and I want to get ['one', 'two', 'three', 'four', 'five'] A: You can iterate over keys in a dictionary. myDict = {'one': 1, "two": 2} for key in myDict: print(key) You could check for the value associated with a key, and add the key to a list if it meets a certain test. A: You can try r_numbers = {y:x for x,y in numbers.items()} r_numbers Out[1]: {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six'} [r_numbers[x] for x in sorted(r_numbers.keys())[:5]] Out[2] : ['one', 'two', 'three', 'four', 'five']
{ "language": "en", "url": "https://stackoverflow.com/questions/47821377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Swift Core Data group results into tuples I have a Core Data table like such: How can I use a combination of collection operators in Swift so that the fetch results in array of tuples with definition like this: [(date: String, values: [Int])]? For example, the table above would yield: Optional([("2/1/2016", [2, 3]), ("2/2/2016", [7])]) The second part of the tuple is an array of variable length... A: This is how I did it, without collection (doesn't seem to have a shortcut to doing it with collection operators); basically it's just a nested fetch request: func dailyitems() -> [(date: String, items: [Item])]? { let request = NSFetchRequest(entityName: ItemEntity); request.returnsDistinctResults = true; request.resultType = NSFetchRequestResultType.DictionaryResultType; request.propertiesToFetch = NSArray(object: "date_string") as [AnyObject]; var array_tuples : [(date: String, items: [Item])]?; var daily_items : [Item] = [] do { let distinctResults: NSArray? = try context.executeFetchRequest(request); if(distinctResults == nil || distinctResults!.count < 1) { return nil; } array_tuples = []; for date in distinctResults! { let Itemrequest = NSFetchRequest(entityName: ItemEntity); Itemrequest.predicate = NSPredicate(format: "date_string == %@", date.valueForKey("date_string") as! String); do { let dayitems = try context.executeFetchRequest(Itemrequest) as? [NSManagedObject]; if(dayitems != nil && dayitems?.count > 0) { daily_items = []; for dayItem in dayitems! { daily_items.append( Item( item: dayItem.valueForKey("item") as! String, date: dayItem.valueForKey("date_string") as! String, value: dayItem.valueForKey("value") as! Int, ) ); } array_tuples?.append((date: date.valueForKey("date_string") as! String, items: daily_items)); } } catch { return nil; } } } catch { return nil; } return array_tuples; } Not sure if there's a more efficient way to do this...
{ "language": "en", "url": "https://stackoverflow.com/questions/35951593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python, Selenium find element is only by css? I'm trying to perform a login to the apple website using selenium but when looking for the ' sign in button' using the find_element_by_id I get an error implying it's a css selector, What does that mean? I thought I was searching for the HTML element. class AppleMusicUploader: def __init__(self, user): self.user = user self.driver = webdriver.Chrome(executable_path=CHROMEDRIVER) def connect_to_user(self): self.driver.get(APPLEMUSIC_LOGIN_PAGE) self.wait_for_load(element_id='account_name_text_field') apple_id = self.driver.find_element_by_id('account_name_text_field') apple_id.send_keys(self.user['email']) self.driver.find_element_by_id(id_='sign-in').click() self.wait_for_load(element_id='password_text_field') password = self.driver.find_element_by_id('password_text_field') password.send_keys(self.user['password']) self.driver.find_element_by_id(id_='sign-in').click() The Error: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="account_name_text_field"]"} From the HTML Page: <input type="text" class="force-ltr form-textbox form-textbox-text" id="account_name_text_field" can-field="accountName" autocomplete="off" autocorrect="off" autocapitalize="off" aria-required="true" required="required" spellcheck="false" ($focus)="appleIdFocusHandler()" ($keyup)="appleIdKeyupHandler()" ($blur)="appleIdBlurHandler()" placeholder="Apple&nbsp;ID" autofocus=""> A: The problem could be that the ID you want is not loading before you do your next step. Try waiting for the element to load with the following "wait_for_load" function: from selenium.webdriver.support import expected_conditions as EC from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By class AppleMusicUploader: def __init__(self, user): self.user = user self.driver = webdriver.Chrome(executable_path=CHROMEDRIVER) def connect_to_user(self): self.driver.get(APPLEMUSIC_LOGIN_PAGE) self.wait_for_load('account_name_text_field') apple_id = self.driver.find_element_by_id('account_name_text_field') password = self.driver.find_element_by_id('password_text_field') apple_id.send_keys(self.user['email']) self.driver.implicitly_wait(10) password.send_keys(self.user['password']) self.driver.implicitly_wait(10) self.driver.find_element_by_class_name( "si-button btn fed-ui moved fed-ui-animation-show remember-me ").click() def wait_for_load(element_id): timeout = 5 # 5 second time out on loading element_present = EC.presence_of_element_located((By.ID, element_id)) WebDriverWait(self.driver, timeout).until(element_present)
{ "language": "en", "url": "https://stackoverflow.com/questions/61876204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to position image in a circle android layout I'm trying to design a rosary app where the beads are individual images so that I can configure each image at will, but I am having trouble positioning them in a relativelayout to make a perfect circle. They're very rigid and angular instead of circular. (see image) What other options do i have? A: It would be a better option to create a custom view and do the drawing yourself. If u wanna stick with the viewgroup solution create a custom viewgroup and handle the measuring,layout pass yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/37845825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is Fetch task in Hive works faster than Map-only task? It is possible to enable Fetch task in Hive for simple query instead of Map or MapReduce using hive hive.fetch.task.conversion parameter. Please explain why Fetch task is running much faster than Map especially when doing some simple work (for example select * from table limit 10;)? What map-only task is doing additionally in this case? The performance difference is more than 20 times faster in my case. Both tasks should read the table data, isn't it? A: FetchTask directly fetches data, whereas Mapreduce will invoke a map reduce job <property> <name>hive.fetch.task.conversion</name> <value>minimal</value> <description> Some select queries can be converted to single FETCH task minimizing latency.Currently the query should be single sourced not having any subquery and should not have any aggregations or distincts (which incurrs RS), lateral views and joins. 1. minimal : SELECT STAR, FILTER on partition columns, LIMIT only 2. more : SELECT, FILTER, LIMIT only (+TABLESAMPLE, virtual columns) </description> </property> Also there is another parameter hive.fetch.task.conversion.threshold which by default in 0.10-0.13 is -1 and >0.14 is 1G(1073741824) This indicates that, If table size is greater than 1G use Mapreduce instead of Fetch task more detail
{ "language": "en", "url": "https://stackoverflow.com/questions/39894681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Alias for JDK is not working in ZSH but works in bash The following aliases are working in bash but not in ZSH: # Different installed version of JDK export JAVA_8_HOME=$(/usr/libexec/java_home -v1.8) export JAVA_11_HOME=$(/usr/libexec/java_home -v11) alias java8='export JAVA_HOME=$JAVA_8_HOME' alias java11='export JAVA_HOME=$JAVA_11_HOME' # default to Java 11 java11 I only get the following error: zsh: command not found: java8 I can change the JDK version if I do it like this: export JAVA_HOME=$(/usr/libexec/java_home -v 1.8) But the alias java8 or java11 are not recognised. A: I'm assuming these all appear in your .bashrc file. You need to add them to .zshrc for zsh to define them.
{ "language": "en", "url": "https://stackoverflow.com/questions/59360696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I manage read and write AWS Aurora host endpoints in CakePHP? I am working with a CakePHP based API that utilizes AWS Aurora to manage our MySQL database. The CakePHP application has many large read queries that that requires a separate Reader Endpoint to not exhaust the database resources. The way this works is that AWS gives you separate endpoints to use in the host field when you connect CakePHP to it. I went ahead and configured it the following way, which works. The folowing datasources are set up in config/app.php, using the reader and cluster (default) endpoints for the host value: <?php // Other data-source and app settings are omitted, to keep things simple return [ 'Datasources' => [ 'default' => [ 'host' => 'mydbcluster.cluster-123456789012.us-east-1.rds.amazonaws.com', ], 'read' => [ 'host' => 'mydbcluster.cluster-ro-123456789012.us-east-1.rds.amazonaws.com', ], ] ]; Both the 'read' and 'default' data sources point to the same database, but so this additional data source is purely configured to support the read only host value. At this point, all I have to do is overwrite the default connection to read on the queries that need the read connection: <?php /** * Class TaskNotesController * * @property \App\Model\Table\TaskNotesTable $TaskNotes */ class TaskNotesController extends \Cake\Controller\Controller { public function index(): void { $taskNotes = $this->TaskNotes ->setConnection(\Cake\Datasource\ConnectionManager::get('read')) ->find('all') ->where(['foo' => 'bar']); } } However, I would like to apply the read endpoint to all read queries in the application. It seems like Cake would have a cleaner way of doing this, to avoid attaching the setConnection() call on every query. Can you tell me if there is a more streamlined way of doing this in CakePHP? Thanks in advance! A: That topic comes up every once in a while, but the conclusion always has been that this isn't something that the core wants to support: https://github.com/cakephp/cakephp/issues/9197 So you're on your own here, and there's many ways how you could solve this in a more DRY manner, but that depends to a non-negligible degree on your application's specific needs. It's hard to give any proper generic advice on this, as doing things wrong can have dire consequences. Like if you'd blindly apply a specific connection to all read operations, you'd very likely end up very sad when your application will issue a read on a different connection while you're in a transaction that writes something based on the read data. All that being sad, you could split your models into read/write ones, going down the CQRS-ish route, you could use behaviors that provide a more straightforward and reusable API for your tables, you could move your operations into the model layer and hide the possibly a bit dirty implementation that way, you could configure the default connection based on the requested endpoint, eg whether it's a read or a write one, etc. There's many ways to "solve" the problem, but I'm afraid it's not something anyone here could definitively answer. A: I needed this too, and solved it by extending the Table class to an "AppTable." I overrode the find() method to use a different version of query(), which I called readQuery(). Within my readQuery(), I modified the $_connection member variable to use my read-only connection before generating the query with $this->query(). Then when the query was generated, I switched it back to the write connection. I included checks to make sure I didn't do this if there was an active transaction or if anything had been written previously in the request lifecycle (because the replication might not have finished yet, and I'd get old data). It wasn't terribly difficult to set up; you just need to be willing to extend Cake's base Table class a bit to switch between the two connections when generating the Query object in find().
{ "language": "en", "url": "https://stackoverflow.com/questions/67829501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Delphi 2007 variant type initialization I am trying to declare a constant array for validating type properties held by input object. but i am doing something incorrect, please have a look at below code: // Record to hold Name-Value pair for checking entities TValues = record Name : WideString; Value : Variant; end; const coarrType1Properties : array[0..5] of TValues = ( (Name : 'HARDWARE'; Value : TRUE), (Name : 'SOFTWARE'; Value : TRUE), (Name : 'TAG'; Value : TRUE), (Name : 'AUTHORIZED'; Value : TRUE), (Name : 'ID'; Value : 700), (Name : 'CODE'; Value : 0) ); but I am getting delphi compile time error for type value i.e. This type cannot be initialized. How to prevent this error? Or can we have alternate solution etc. Please assist... A: For these (Boolean, Integer) and other simple types, you could initialize with TVarData and typecast back to Variant: type TValues = record Name: WideString; Value: TVarData; end; const coarrType1Properties : array[0..5] of TValues = ( (Name: 'HARDWARE'; Value: (VType: varBoolean; VBoolean: True)), (Name: 'SOFTWARE'; Value: (VType: varBoolean; VBoolean: True)), (Name: 'TAG'; Value: (VType: varBoolean; VBoolean: True)), (Name: 'AUTHORIZED'; Value: (VType: varBoolean; VBoolean: True)), (Name: 'ID'; Value: (VType: varInteger; VInteger: 700)), (Name: 'CODE'; Value: (VType: varInteger; VInteger: 0)) ); procedure Test; var I: Integer; begin for I := Low(coarrType1Properties) to High(coarrType1Properties) do Writeln(Format('coarrType1Properties[%d]: ''%s'', %s', [I, coarrType1Properties[I].Name, VarToStr(Variant(coarrType1Properties[I].Value))])); end; A: The documentation states: File types (including type Text), and the type Variant cannot be initialized, that is, you cannot declare typed constants or initialized variables of these types. So your problem is with your variant record member. This means that you need a different approach and you will have to abandon the use of a constant array. function Values(const Name: WideString; const Value: Variant): TValues; begin Result.Name := Name; Result.Value := Value; end; type TValuesArray = array of TValues; function ValuesArray(const Values: array of TValues): TValuesArray; var i: Integer; begin SetLength(Result, Length(Values)); for i := 0 to high(Result) do Result[i] := Values[i]; end; var coarrType1Properties: TValuesArray; initialization coarrType1Properties := ValuesArray([ Values('HARDWARE', TRUE), Values('SOFTWARE', TRUE), Values('TAG', TRUE), Values('AUTHORIZED', TRUE), Values('ID', 700), Values('CODE', 0) ]); A: E2071: Variants can not be initialized with a constant expression. A: Form D2007 help: E2071: This type cannot be initialized File types (including type Text), and the type Variant cannot be initialized, that is, you cannot declare typed constants or initialized variables of these types. program Produce; var V: Variant = 0; begin end. // The example tries to declare an initialized variable of type Variant, which illegal. program Solve; var V: Variant; begin V := 0; end. The solution is to initialize a normal variable with an assignment statement.
{ "language": "en", "url": "https://stackoverflow.com/questions/6341806", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why I can not install new maven? I download a new maven and execute using the full path, but still get the old version, and it doesn't help even I put it on PATH. It's very weird. I run the maven as version of 3.3.9, but it still use the 3.2.5 -bash-4.1# /usr/hdp/2.3.2.0-2950/apache-maven-3.3.9/bin/mvn --version Apache Maven 3.2.5 (12a6b3acb947671f09b81f49094c53f426d8cea1; 2014-12-14T17:29:23+00:00) Maven home: /usr/share/apache-maven Java version: 1.7.0_91, vendor: Oracle Corporation Java home: /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.91.x86_64/jre Default locale: en_US, platform encoding: UTF-8 OS name: "linux", version: "2.6.32-573.7.1.el6.x86_64", arch: "amd64", family: "unix" A: M2_HOME is set as the old maven home directory. Seems maven will pick up the MAVEN from this environment variable.
{ "language": "en", "url": "https://stackoverflow.com/questions/35475310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails: Passing User state between many controllers I have a simple Rails application with multiple controllers and I want to pass User state around between many different controllers and views. The user can have a organization and a project. I want to pass current_org and current_project across all my controllers/views, which are the objects for the current organization and the current project. What's the best way to do this? I want to reduce the need to make a database call on every page load. Is it possible to persist these in current_user so that I can call current_user.current_project? A: As web requests are stateless at heart, each new page render will require re-fetching data from somewhere. Your current_user method is itself making a database call behind the scenes (assuming a stock Devise setup) to load the user on each page load. Similarly, while you can define a helper or module to share current_org and current_project values, like Ritaful pointed out, they will need to make database calls to fetch their values. Or at least, that's the typical Rails answer. You do have some other options. The first is to use the session storage to store the objects, through either native Ruby marshaling (a dangerous path, as the legacy systems I work with have shown) or through perhaps JSON serialization: # marshalling def current_org # this will break if your organization object contains a proc, and # can risk exploding your session storage if your object gets large session[:current_org] ||= current_user.organization end # serialization def current_org session[:current_org] ||= current_user.organization.to_json end However, the JSON object won't be an ActiveRecord model, so your code will have to adapt. You can technically make it a record through #from_json, but your relations won't work like you expect and in general you'd be straying too far into the woods at that point. Overall, I would avoid trying to prematurely optimize your database calls. A schema with proper indices can perform index lookups very quickly, so these lookups are unlikely to cause a problem. If you do start seeing issues, I'd start with looking into eager loading to reduce the number of queries made per page load, but not try too hard to eliminate them. As you scale, you can add layers of caching and dig into optimizations to further reduce database impact. A: You can create two methods in your ApplicationHelper def current_project current_user.current_project end def current_org current_user.current_org end These will be available to all controllers and views. For more information, check "How to Use Rails Helpers (Complete Guide)". A: What about the session? It's probably the easiest way. I remember I did something like this: * *When use logs in assign that id to session[:current_user_id] *Whenever a user navigates to another page have a private method that looks something like this: def setup(id) @user = User.find(id) end *Run that method in a before_action method like this: before_action do setup(session[:current_session_id]) end
{ "language": "en", "url": "https://stackoverflow.com/questions/62050339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to suppress Java compiler warnings for specific functions We are always taught to make sure we use a break in switch statements to avoid fall-through. The Java compiler warns about these situations to help us not make trivial (but drastic) errors. I have, however, used case fall-through as a feature (we don't have to get into it here, but it provides a very elegant solution). However the compiler spits out massive amounts of warnings that may obscure warnings that I need to know about. I know how I can change the compiler to ignore ALL fall-through warnings, but I would like to implement this on a method-by-method basis to avoid missing a place where I did not intend for fall-through to happen. Any Ideas? A: If you really, really must do this, and you are sure you are not making a mistake, check out the @SuppressWarnings annotation. I suppose in your case you need @SuppressWarnings("fallthrough") A: Is the annotation @SuppressWarnings (javadoc) what you are looking for? For example: @SuppressWarnings("unchecked") public void someMethod(...) { ... } A: To complete other answer about SuppressWarnings: @SuppressWarnings("fallthrough") Try to supress all the fall-through warning at the compiler level is a bad thing: as you've explained, the cases where you need to pass through the warning are clearly identified. Thus, it should be explicitly written in the code (the @SuppressWarnings("fallthrough") annotation with an optionnal comment is welcome). Doing so, you'll still have the fall-through warning if you really forget a break somewhere elese in your code. A: You could create a structure of 'if' statements in place of the switch. Might not be as visually pleasing however neither is warning supression. A: @SuppressWarnings("fallthrough") Java has always followed the C-style of switch statements, where you need to explicititly break out of a switch unless you wish to simply fall through and execute the code in the case below. This can be dangerous of course and errors of this kind can be very hard to track down. In the following example, case 1 lacks a break: @SuppressWarnings("fallthrough") public void fallthroughTest(int i) { switch (i) { case 1: // Execute both 1 and 2 case 2: // Execute only 1 } }
{ "language": "en", "url": "https://stackoverflow.com/questions/593996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: Buttons in UITableView I want to create UITableView where some cells are buttons. Help me, what is the right way to do it? 1) I can use something like that: UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease]; } if (indexPath.section == 1){ if (indexPath.row == 0){ UIButton* loginButton = [[UIButton alloc] initWithFrame:CGRectMake(9,1,302, 48)]; [loginButton setBackgroundImage:[UIImage imageNamed:@"LoginButton.png"] forState:UIControlStateNormal]; [loginButton setBackgroundImage:[UIImage imageNamed:@"LoginButton_pressed.png"] forState:UIControlStateSelected]; [loginButton setTitle:@"Login" forState:UIControlStateNormal]; [cell setBackgroundColor:[UIColor clearColor]]; [cell addSubview:loginButton]; [loginButton release]; } } but I see that button is transparent and looks strange. 2) don't use any UIButtons and make what I want entirely using UITableViewCells Thank you four your attention, I'm completely new for iOS, but I'm trying to make app without xib. A: you have not set button type ,it is read only property .so you can not direct assign it so change your code like this: UIButton* loginButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [loginButton setFrame:CGRectMake(5,5,302, 34)]; [loginButton setBackgroundImage:[UIImage imageNamed:@"LoginButton.png"] forState:UIControlStateNormal]; [loginButton setBackgroundImage:[UIImage imageNamed:@"LoginButton_pressed.png"] forState:UIControlStateSelected]; [loginButton setTitle:@"Login" forState:UIControlStateNormal]; [cell setBackgroundColor:[UIColor clearColor]]; [cell addSubview:loginButton];
{ "language": "en", "url": "https://stackoverflow.com/questions/9927099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: rails: Scheduled jobs but run at most one at single time I have the scheduled job which run every 5 seconds. I'm now using backgroudRB for scheduling. But sometimes, the job may take more than 5 seconds and i don't want more than one job is running at the same time. In .Net, we can use Mutex class, but I'm not sure about what should I use in rails application. Thanks. A: Yuck, I remember using backgrounDRb, it was horrible. I use Resque now, after using delayed_job. Both work well, and you can solve your problem by only running a single worker. You can find both on Github.
{ "language": "en", "url": "https://stackoverflow.com/questions/3544454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add unique objects to a list in Python I'm trying to add objects to a list but when I print elements of that list, I get the attributes of the last object. import random class Unit: arr = [] def __init__(self): self.arr.clear() for i in range(2): self.arr.append(random.randint(1, 100)) print("arr in Unit ", self.arr) class SetOfUnits: lst = [] def __init__(self): self.lst.clear() for i in range(3): self.lst.append(Unit()) print("arr in SetOfUnits ", self.lst[i].arr) p = SetOfUnits() for i in range(3): print(p.lst[i].arr) I got this: arr in Unit [17, 16] arr in SetOfUnits [17, 16] arr in Unit [98, 20] arr in SetOfUnits [98, 20] arr in Unit [16, 39] arr in SetOfUnits [16, 39] [16, 39] [16, 39] [16, 39] The problem is with the last 3 lines. It looks like that objects p.lst[0], p.lst[1], p.lst[2] refer to the same object, not different ones. I would like to get: [17, 16] [98, 20] [16, 39] Could you help me to find out what am I doing wrong? A: Define your lists inside the __init__ function. class Unit: def __init__(self): self.arr = [] self.arr.clear() for i in range(2): self.arr.append(random.randint(1, 100)) print("arr in Unit ", self.arr) class SetOfUnits: def __init__(self): self.lst = [] self.lst.clear() for i in range(3): self.lst.append(Unit()) print("arr in SetOfUnits ", self.lst[i].arr) The way you are doing it, you define your variables class-wise, you need it to be instance-wise. See: class variable vs instance variable --Python A: lst and arr are class attributes, not instance attributes.
{ "language": "en", "url": "https://stackoverflow.com/questions/57019002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Preserve space coming in data in XSLT I have data coming like this <Table1> <row_description>Low Touch</row_description> <_x0038_ /> <_x0039_ /> <_x0031_0 /> <_x0031_1 /> <_x0031_2 /> </Table1> <Table1> <row_description> DMA/ALGO</row_description> <_x0038_ /> <_x0039_ /> <_x0031_0 /> <_x0031_1 /> <_x0031_2 /> </Table1> <Table1> <row_description> PT</row_description> <_x0038_ /> <_x0039_ /> <_x0031_0 /> <_x0031_1 /> <_x0031_2 /> </Table1> and my XSLT does this <xsl:for-each select="*"> <TableCell Padding="10,1" BorderThickness="1,1,1,1" BorderBrush="#FF888888"> <xsl:if test="position()=1"> <Paragraph> <Span> <Run> <xsl:value-of select="text()" /> </Run> </Span> </Paragraph> </xsl:if> <xsl:if test="position()>1"> <Paragraph TextAlignment="Right"> <Span> <Run> <xsl:value-of select="text()"/> </Run> </Span> </Paragraph> </xsl:if> </TableCell> </xsl:for-each> but it is removing space coming before my text PT to PT. How to preserve space coming in data? A: In your XSLT make use of: <xsl:preserve-space elements="*" /> See: http://www.w3schools.com/xsl/el_preserve-space.asp When I have the following input XML: <?xml version="1.0" encoding="UTF-8"?> <data> <Table1> <row_description>Low Touch</row_description> <_x0038_/> <_x0039_/> <_x0031_0/> <_x0031_1/> <_x0031_2/> </Table1> <Table1> <row_description> DMA/ALGO</row_description> <_x0038_/> <_x0039_/> <_x0031_0/> <_x0031_1/> <_x0031_2/> </Table1> <Table1> <row_description> PT</row_description> <_x0038_/> <_x0039_/> <_x0031_0/> <_x0031_1/> <_x0031_2/> </Table1> </data> And I use the following XSLT: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="html" encoding="UTF-8" indent="yes"/> <xsl:preserve-space elements="*" /> <xsl:template match="@*|node()"> <xsl:apply-templates select="@*|node()" /> </xsl:template> <xsl:template match="Table1"> <xsl:for-each select="*"> <TableCell Padding="10,1" BorderThickness="1,1,1,1" BorderBrush="#FF888888"> <xsl:if test="position()=1"> <Paragraph> <Span> <Run> <xsl:value-of select="text()" /> </Run> </Span> </Paragraph> </xsl:if> <xsl:if test="position()>1"> <Paragraph TextAlignment="Right"> <Span> <Run> <xsl:value-of select="text()"/> </Run> </Span> </Paragraph> </xsl:if> </TableCell> </xsl:for-each> </xsl:template> </xsl:stylesheet> The output shows as expected: <TableCell Padding="10,1" BorderThickness="1,1,1,1" BorderBrush="#FF888888"> <Paragraph><Span><Run>Low Touch</Run> </Span></Paragraph> </TableCell> <TableCell Padding="10,1" BorderThickness="1,1,1,1" BorderBrush="#FF888888"> <Paragraph TextAlignment="Right"><Span><Run></Run> </Span></Paragraph> </TableCell> <TableCell Padding="10,1" BorderThickness="1,1,1,1" BorderBrush="#FF888888"> <Paragraph TextAlignment="Right"><Span><Run></Run> </Span></Paragraph> </TableCell> <TableCell Padding="10,1" BorderThickness="1,1,1,1" BorderBrush="#FF888888"> <Paragraph TextAlignment="Right"><Span><Run></Run> </Span></Paragraph> </TableCell> <TableCell Padding="10,1" BorderThickness="1,1,1,1" BorderBrush="#FF888888"> <Paragraph TextAlignment="Right"><Span><Run></Run> </Span></Paragraph> </TableCell> <TableCell Padding="10,1" BorderThickness="1,1,1,1" BorderBrush="#FF888888"> <Paragraph TextAlignment="Right"><Span><Run></Run> </Span></Paragraph> </TableCell> <TableCell Padding="10,1" BorderThickness="1,1,1,1" BorderBrush="#FF888888"> <Paragraph><Span><Run> DMA/ALGO</Run> </Span></Paragraph> </TableCell> <TableCell Padding="10,1" BorderThickness="1,1,1,1" BorderBrush="#FF888888"> <Paragraph TextAlignment="Right"><Span><Run></Run> </Span></Paragraph> </TableCell> <TableCell Padding="10,1" BorderThickness="1,1,1,1" BorderBrush="#FF888888"> <Paragraph TextAlignment="Right"><Span><Run></Run> </Span></Paragraph> </TableCell> <TableCell Padding="10,1" BorderThickness="1,1,1,1" BorderBrush="#FF888888"> <Paragraph TextAlignment="Right"><Span><Run></Run> </Span></Paragraph> </TableCell> <TableCell Padding="10,1" BorderThickness="1,1,1,1" BorderBrush="#FF888888"> <Paragraph TextAlignment="Right"><Span><Run></Run> </Span></Paragraph> </TableCell> <TableCell Padding="10,1" BorderThickness="1,1,1,1" BorderBrush="#FF888888"> <Paragraph TextAlignment="Right"><Span><Run></Run> </Span></Paragraph> </TableCell> <TableCell Padding="10,1" BorderThickness="1,1,1,1" BorderBrush="#FF888888"> <Paragraph><Span><Run> PT</Run> </Span></Paragraph> </TableCell> <TableCell Padding="10,1" BorderThickness="1,1,1,1" BorderBrush="#FF888888"> <Paragraph TextAlignment="Right"><Span><Run></Run> </Span></Paragraph> </TableCell> <TableCell Padding="10,1" BorderThickness="1,1,1,1" BorderBrush="#FF888888"> <Paragraph TextAlignment="Right"><Span><Run></Run> </Span></Paragraph> </TableCell> <TableCell Padding="10,1" BorderThickness="1,1,1,1" BorderBrush="#FF888888"> <Paragraph TextAlignment="Right"><Span><Run></Run> </Span></Paragraph> </TableCell> <TableCell Padding="10,1" BorderThickness="1,1,1,1" BorderBrush="#FF888888"> <Paragraph TextAlignment="Right"><Span><Run></Run> </Span></Paragraph> </TableCell> <TableCell Padding="10,1" BorderThickness="1,1,1,1" BorderBrush="#FF888888"> <Paragraph TextAlignment="Right"><Span><Run></Run> </Span></Paragraph> </TableCell> The value <Run> PT</Run> still has the spaces in it. As XSLT processor I used Altova XMLSpy. A: I am OP and I did this to overcome my problem <Run xml:space="preserve"><xsl:value-of select="text()" /></Run> Note: After writing xml:space="preserve", please make sure <xsl:value-of select="text()" />is in the same line. If we write like this <Run xml:space="preserve"> <xsl:value-of select="text()" /> </Run> it will also consider the indentation of xsl as text as we have said to preserve space.
{ "language": "en", "url": "https://stackoverflow.com/questions/19176146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I group a column of totals into a set where each set has a maximum I have a collection of records, each record has a total; I want to split the whole collection up into sets, each set can only hold so much (20 in the example). I have thought about two methods so far and I've shown a simple representation below: Sets are separate: * *set1 has the first two since 5+10=15 (the next 12 will put it over 20). *set2 will have the next two since 12+7=19. Another Idea I toyed with is just to add a set column onto the source data set: I'm trying to figure out an easy way to complete this using formula, if it's easier to complete in VBA I'll then go that route. Thanks for the help, I've been thinking about this all week and don't even know what to search for. **Edit: I'm an idiot. A: I couldn't come up with a formula, but here is a pretty brute force way of doing it: Sub test() Dim i As Long, _ lr As Long, _ sumValue As Long, _ counter As Long lr = Range("A" & Rows.Count).End(xlUp).Row counter = 1 For i = 1 To lr sumValue = sumValue + Range("A" & i) If sumValue <= 20 Then Range("B" & i).Value = counter Else sumValue = 0 counter = counter + 1 i = i - 1 End If Next i End Sub For what it's worth, my results were a tad bit different as I calculated 5+10+12 to be greater than 20... A: I found the answer by browsing through the related section. =IF(A2="a",ROUNDDOWN((B2-1)/20,0)+1,IF(SUMIF($C1:C$2,C1,$B1:B$2)+B2>20,C1+1,C1)) Here is a link to that answer. I'm going to accept @sous2817's answer because it was the most helpful and would've been the path I took if I went for the VBA approach. Thanks again guys! A: =ROUNDUP(SUM(R5C[-1]:RC[-1])/20,0) or =ROUNDUP(SUM(C$5:C5)/20,0) where the formula starts at D5 and is pulled down. A: The described problem can also be solved with a dynamic array solution in newer versions of excel (Office365). An example for a possible solution could look like this: which uses the following formula for the sets 2-5: =LET( rows,$B$5:$B$17, vals,$C$5:$C$17, excl,$F$5:F$15, rows_filt,OFFSET(rows,COUNT(excl),0,COUNT(rows)-COUNT(excl)), vals_filt,OFFSET(vals,COUNT(excl),0,COUNT(rows)-COUNT(excl)), cumsum,MMULT(N(ROW(vals_filt)>=TRANSPOSE(ROW(vals_filt))),vals_filt), FILTER(rows_filt,cumsum<=20) ) but to avoid reference to itself, the formula for set 1 is: =LET( rows,$B$5:$B$17, vals,$C$5:$C$17, cumsum,MMULT(N(ROW(vals)>=TRANSPOSE(ROW(vals))),vals), FILTER(rows,cumsum<=20) ) (also shown in the screenshot here)
{ "language": "en", "url": "https://stackoverflow.com/questions/28963311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySQL Query where id = id_product error i'm working with mysql in a nodejs web app. I don't understand why when I ask for some id (key) it gives me more than 1 result. When I: SELECT * FROM products WHERE id = 1; This happens, I get 3 results, but I only want 1: 1, 001 and 0000001. I just want the info of one product (id: 1 in this example) How can I fix this? ID type is varchar(20) If I use LIKE instead of = my result changes: SELECT * FROM products WHERE id LIKE 0000001; I get the info of id = 1 instead 0000001. Don't know why. Thanks A: The WHERE clause of your query contains a comparison of a literal numeric value with a string (column id). When it needs to compare values of different type, MySQL uses several rules to convert one or both of the values to a common type. Some of the type conversion rules are not intuitive. The last rule is the only one that matches a comparison of an integer number with a string: In all other cases, the arguments are compared as floating-point (real) numbers. When they are converted to floating-point (real) numbers, 1 (integer), '1', '0001' and '0000001' are all equal. In order to get an exact match the literal value you put in the query must have the same type as the column id (i.e string). The query should be: SELECT * FROM products WHERE id = '1' A: Numbers in MySQL (and the real world) don't have leading zeros. Strings do. So, you just need to make the comparison using the right type: SELECT * FROM products WHERE id = '1'; What happens with your original query is that the id is converted to a number. And '1', '001' and '0000001' are all converted to the same integer -- 1. Hence, all three pass the filter. A: The problem is that you are looking by a varchar type using an integer cast. Try to add quotes to the id parameter: SELECT * FROM products WHERE id = '1'; If you want to add integer ids with with leading zeros, I recommend you to use the zerofill option: https://dev.mysql.com/doc/refman/5.5/en/numeric-type-attributes.html If you want to use use alphanumeric values then keeps the ID type as varchar, but remember to enclose the search param into quotes.
{ "language": "en", "url": "https://stackoverflow.com/questions/36317626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Question about shell commands and grep Does anyone know why grep "p\{2\}" textfile will find "apple" if it's in the file, but grep p\{2\} textfile won't? I'm new to using a command line and regular expressions, and this is puzzling me. A: Although this has already been answered, but since you are new to all this stuff, here is how to debug it: -- get the pid of current shell (using ps). PID TTY TIME CMD 1611 pts/0 00:00:00 su 1619 pts/0 00:00:00 bash 1763 pts/0 00:00:00 ps -- from some other shell, attach strace (system call tracer) to the required pid (here 1619): strace -f -o <output_file> -p 1619 -- Run both the commands that you tried -- open the output file and look for exec family calls for the required process, here: grep The output on my machine is some thing like: 1723 execve("/bin/grep", ["grep", "--color=auto", "p{2}", "foo"], [/* 19 vars */]) = 0 1725 execve("/bin/grep", ["grep", "--color=auto", "p\\{2\\}", "foo"], [/* 19 vars */]) = 0 Now you can see the difference how grep was executed in both the cases and can figure out the problem yourself. :) still the -e flag mystery is yet to be solved.... A: Without the quotes, the shell will try to expanding the options. In your case the curly brackets '{}' have a special meaning in the shell much like the asterisk '*' which expands to a wildcard. A: With quotes, your complete regex gets passed directly to grep. Without the quotes, grep sees your regex as p{2}. Edit: To clarify, without the quotes your slashes are being removed by shell before your regex is passed to grep. Try: echo grep p\{2\} test.txt And you'll see your output as... grep p{2} test.txt The quotes prevent shell from escaping characters before they get to grep. You could also escape your slashes and it will work without quotes - grep p\\{2\\} test.txt A: From the grep man page In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). so these two become functional equivalent egrep p{2} and grep "p\{2\}" the first uses EREs(Extended Regular Expressions) the second uses BREs(Basic Regular Expressions) in your example because your using grep(which supports BREs when you don't use the -e switch) and you're enclosed in quotes so "\{" gets expanded as a special BRE character. You second instance doesn't work because your just looking for the literal string 2{p} which doesn't exist in your file you can demonstrate that grep is expanding your string as a BRE by trying: grep "p\{2" grep will complain grep: Unmatched \{ A: The first one greps the pattern using regex, then pp: echo "apple" | grep 'p\{2\}' The second one greps the pattern literally, then p{2}: echo "ap{2}le" | grep p\{2\}
{ "language": "en", "url": "https://stackoverflow.com/questions/5916032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Inserting value in List of values of a Key in Dictionary I have a rowsDictionary that its keys point to a list of EmployeeSummary classes. In those EmployeeSummary classes we also have a string property of Delivery_System I am looping through this in this way but now stuck in the part that I want to have a deliverySystemFinder dictioanry that its keys are combinedKey as below and the value for each key is a list of distinct delivery_system values //rowsDictionary is a Dictionary<string, List<EmployeeSummary>> Dictionary<string, List<string>> deliverySystemFinder = new Dictionary<string, List<string>>(); foreach (string key in rowsDictionary.Keys) { List<EmployeeSummary> empList = rowsDictionary[key]; foreach (EmployeeSummary emp in empList) { string combinedKey = emp.LastName.Trim().ToUpper() + emp.FirstName.Trim().ToUpper(); string delivery_system = emp.Delivery_System; // so now I should go and //A) does deliverySystemFinder have this combinedKey? if not add it. //B) Does combinedKey in the list of its values already have the value for delivery_system? if it does not then add it } } A: This would work, for start: foreach (string key in rowsDictionary.Keys) { List<EmployeeSummary> empList = rowsDictionary[key]; foreach (EmployeeSummary emp in empList) { string combinedKey = emp.LastName.Trim().ToUpper() + emp.FirstName.Trim().ToUpper(); string delivery_system = emp.Delivery_System; List<string> systems = null; // check if the dictionary contains the list if (!deliverySystemFinder.TryGetValue(combinedKey, out systems)) { // if not, create it and add it systems = new List<string>(); deliverySystemFinder[combinedKey] = systems; } // check if the list contains the value and add it if (!systems.Contains(delivery_system)) systems.Add(delivery_system); } } Now, a couple of remarks: * *It doesn't make sense to iterate through Keys, and then do a lookup in each iteration. You can directly iterate KeyValuePairs using a foreach loop. *Using concatenated strings as unique keys often fails. In this case, what happens if you have users { LastName="Some", FirstName="Body" } and { LastName="So", FirstName="Mebody" } in your list? *Checking if a List contains a value is a O(n) operation. You would greatly improve performance if you used a HashSet<string> instead. Finally, the simplest way to achieve what you're trying to do is to ditch those loops and simply use: // returns a Dictionary<EmployeeSummary, List<string>> // which maps each distinct EmployeeSummary into a list of // distinct delivery systems var groupByEmployee = rowsDictionary .SelectMany(kvp => kvp.Value) .GroupBy(s => s, new EmployeeSummaryEqualityComparer()) .ToDictionary( s => s.Key, s => s.Select(x => x.Delivery_System).Distinct().ToList()); With EmployeeSummaryEqualityComparer defined something like: class EmployeeSummaryEqualityComparer : IEqualityComparer<EmployeeSummary> { public bool Equals(EmployeeSummary x, EmployeeSummary y) { if (object.ReferenceEquals(x, null)) return object.ReferenceEquals(y, null); return x.FirstName == y.FirstName && x.LastName == y.LastName && ... (depending on what constitutes 'equal' for you) } public int GetHashCode(EmployeeSummary x) { unchecked { var h = 31; // null checks might not be necessary? h = h * 7 + (x.FirstName != null ? x.FirstName.GetHashCode() : 0); h = h * 7 + (x.LastName != null ? x.LastName.GetHashCode() : 0); ... other properties similarly ... return h; } } } If you really think that using the string key will work in all your cases, you can do it without the custom equality comparer: // returns a Dictionary<string, List<string>> var groupByEmployee = rowsDictionary .SelectMany(kvp => kvp.Value) .GroupBy(s => s.LastName.ToUpper() + s.FirstName.ToUpper()) .ToDictionary( s => s.Key, s => s.Select(x => x.Delivery_System).Distinct().ToList());
{ "language": "en", "url": "https://stackoverflow.com/questions/24958406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Set routing key in kaazing jmsclient.js and publish message using amqp Can anyone guide me how to use routing key to send/receive message on queue using jmsclient.js. Reference taken from https://demo.kaazing.com/demo/jms/javascript/jms-javascript.html. As of now, i have to create multiple queues with distinct names for the number of consumers listening. I want to have only one queue but with different routing key specified for each consumer. A: You can set a property with some unique key for each consumer. Then when you consume messages, use a selector. The link you refer to have already an example selector, `symbol=KZNG', but you could use whatever key/value that suits your need. Something like receiver=CentralAvenueOffice or receiver=theOldFishFactory
{ "language": "en", "url": "https://stackoverflow.com/questions/25374742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Sending and receiving info through camera intent I want to take a picture by opening the camera app using intent. I know how to do that. The problem is that the image comes onActivityResult call. Is there a way I persist a data such as ID so that when I receive the image on activity result, I can use the ID to (say store image path and ID in db). If I pass data to the camera intent, will get it back in the intent? I know one approach is to have class variable and store it there but I have feeling this is prone for errors Thanks A: If I pass data to the camera intent, will get it back in the intent? No. I know one approach is to have class variable and store it there but I have feeling this is prone for errors If by "class variable", you mean a field on your activity or fragment, that is the appropriate approach. However, since there is a chance that your process will be terminated while the camera app is in the foreground, you need to hold onto that information in the saved instance state Bundle, so you get it back if your activity or fragment gets re-created. This sample app demonstrates the technique.
{ "language": "en", "url": "https://stackoverflow.com/questions/49650894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }