text
stringlengths
15
59.8k
meta
dict
Q: persistent vs immutable data structure Is there any difference in a persistent and immutable data structure? Wikipedia refers to immutable data structure when discussing persistence but I have a feeling there might be a subtle difference between the two. A: Immutability is an implementation technique. Among other things, it provides persistence, which is an interface. The persistence API is something like: * *version update(operation o, version v) performs operation o on version v, returning a new version. If the data structure is immutable, the new version is a new structure (that may share immutable parts of the old structure). If the data structure isn't immutable, the returned version might just be a version number. The version v remains a valid version, and it shouldn't change in any observe-able way because of this update - the update is only visible in the returned version, not in v. *data observe(query q, version v) observes a data structure at version v without changing it or creating a new version. For more about these differences, see: * *The chapter "Persistent data structures" by Haim Kaplan in Handbook on Data Structures and Applications *"Making Data Structures Persistent" by Driscoll et al. *The first lecture of the Spring 2012 incarnation of MIT's 6.851: Advanced Data Structures A: Yes, there is a difference. An immutable data structure cannot be modified in any way after its creation. The only way to effective modify it would be to make a mutable copy or something similar (e.g. slightly modifying the parameters you pass to the constructor of the new one). A persistent data structure, on the other hand, is mutable in the sense that the exposed API appears to allow changes to the data structure. In truth, though, any changes will retain a pointer to the existing data structure (and therefore every preceding structure); they only seem to mutate the data structure because the exposed API returns a new pointer that may include pointers to a subset of the previous data structure (in trees, e.g., we will point at the node whose subtree hasn't changed as a result of the operation).
{ "language": "en", "url": "https://stackoverflow.com/questions/10034537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Action Script: Drawing on video I was wondering how to draw over a video like this. http://www.bannerblog.com.au/2009/06/burger_king_sharpie.php A: I'm not sure that in the example is drawing process over video. As for me It's a 3d model with video background. And you could sync prerecorded states with 3d object transformations (position, rotation, mesh transformations), or create well textured object. Here for your tutorial how to draw over the 3D objects A: Easy! Use Adobe After Effects (or any number of other compositing programs).
{ "language": "en", "url": "https://stackoverflow.com/questions/22565072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL 'belong to' logic So, I have been trying to write a query in SQL but facing an issue. I am trying to write a 'belongs to' kind of condition. What I want to do is if the values being fetched belongs to a column in another table then populate one thing otherwise populate null. for ex. NAME table ID NAMES 1 A 2 B 3 C 4 D 5 E XYZ table ID 2 4 5 I wrote the query something like this (CASE WHEN NAME.ID IN (SELECT ID FROM XYZ) THEN NAME.NAMES ELSE NULL END ) AS 'ABC' This query does run but it has been running for 14 hours (OBVIOUSLY FOR A VERY HUGE AMOUNT OF DATA) and still there is no result. Is there some flaw in this logic or is there some better way it could be done? I expect a result like this: ABC NULL B NULL D E A: You just need a plain left join here: SELECT CASE WHEN t2.ID IS NOT NULL THEN t1.NAMES END AS ABC FROM NAME t1 LEFT JOIN XYZ t2 ON t1.ID = t2.ID; Demo Note that a CASE expressions else condition, if not explicitly specified, defaults to NULL. This behavior works here because you want to render NULL if a given record in the NAME table does not match to any record in the XYZ table. A: The problem isn't your logic. It is simply how the code is optimized. The subquery is probably being run for each row in the outer query. I would recommend switching to exists: (case when exists (select 1 from xyz where xyz.id = name.id) then name.names end) as abc This maintains the semantics of your original query. In particular, there is no danger that duplicates in xyz would return multiple rows (as would happen with a left join). For performance for this -- or for the left join -- you want an index on xyz(id).
{ "language": "en", "url": "https://stackoverflow.com/questions/51779558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Angular2: Too many calls on Observable So currently I created a service in order to path data from one component to another. Let's say I have a select component and a component factory. In order to pass a selected value from a select component to factory I designed this service. Here is how the service looks like: import { Injectable } from '@angular/core'; import {Subject} from "rxjs/Subject"; @Injectable() export class ObservableService { private dataSource = new Subject(); data = []; data$ = this.dataSource.asObservable(); updateFilter(value) { this.data.push(value); console.log('Changes transfer'); this.dataSource.next(this.data) } } So, as I said I have to path data from my html select input that belongs to select component to factory, and here is the select component html <select (change)="onChange($event)"> <option value="">Options</option> <option *ngFor="let option of options" [value]="option.value">{{ option.name }}</option> </select> And here is the way I sending selected value from select component to observable service: private onChange(option) { console.log('Changes sent'); this._observable.updateFilter(option); } Here is how I'm catching data in factory component ngOnInit() { this._observable.data$.subscribe( data => console.log('Changes detected'); ) } You may notice console commands that I put on each stage of data transfer. And in fact I got this: Changes sent Changes transfer (13) Changes detected So in fact the observable subscriber detected 13 changes! Please, help me to understand where this strange behavior goes from?
{ "language": "en", "url": "https://stackoverflow.com/questions/41301886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Issues with https:// non-www re-directing to https://www I have a website which has recently moved from http:// to https:// The site is built with MVC hosted on IIS7, and I know I should have 4 bindings in place for this. the main one: https://www.example.com (port:443 - ip address: *) and 3 others all to 301 re-direct to the above. http://www.example.com - (port:80 - ip address: * -re-direct works) http://example.com - (port:80 - ip address: * -re-direct works) https://example.com - (port:443 - ip address: * -re-direct does not work) Trying to troubleshoot why the bottom one is failing with Site could not be reached. server DNS address could not be found. Below is the code I am using to re-direct http to https // The base only redirects GET, but we added HEAD as well. This avoids exceptions for bots crawling using HEAD. // The other requests will throw an exception to ensure the correct verbs are used. // We fall back to the base method as the mvc exceptions are marked as internal. if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase) && !String.Equals(filterContext.HttpContext.Request.HttpMethod, "HEAD", StringComparison.OrdinalIgnoreCase)) { base.HandleNonHttpsRequest(filterContext); } // Redirect to HTTPS version of page // We updated this to redirect using 301 (permanent) instead of 302 (temporary). string url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl; filterContext.Result = new RedirectResult(url, true); Any ideas what is going wrong here with the bottom binding? Trying to set up 4th property on Google Webmaster Search Console and obviously can't due to failing DNS. Any help at all is greatly appreciated. Cheers A: It's better do this kind of thing on web-server level rather than in app code. For IIS, you need to change file Web.config by adding a rewrite rules. I was not able to test it, but you should add something like that: <rewrite> <rules> <rule name="Redirect to www" patternSyntax="Wildcard" stopProcessing="true"> <match url="*" /> <conditions> <add input="{HTTP_HOST}" pattern="example.com" /> </conditions> <action type="Redirect" url="http://www.example.com/{R:0}" /> </rule> <rule name="HTTP Redirect to HTTPS" enabled="true" stopProcessing="true"> <match url="(.*)" ignoreCase="false" /> <conditions> <add input="{HTTPS}" pattern="off" /> </conditions> <action type="Redirect" url="https://www.example.com/{R:1}" appendQueryString="true" redirectType="Permanent" /> </rule> </rules> A: The issue was with the DNS on our domain provider.
{ "language": "en", "url": "https://stackoverflow.com/questions/42722987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Illegal mix of collations for operation ' IN ', While using LINQ Lambda with contains clause I am having Linq query that fetch city names as keyValue pair, Refer below code public List<KeyValuePair<string, int>> GetCityKeyValuesByNames(List<string> cityNames) { var cityList = _cityRepo .GetConditionalQuery(x => cityNames.Contains(x.Name)) .Select(x => new { Key = x.Name, Value = x.Id }) .AsEnumerable() .Select(x => new KeyValuePair<string, int>(x.Key, x.Value)) .ToList(); return cityList; } However we getting Eception MySql.Data.MySqlClient.MySqlException: Illegal mix of collations for operation ' IN ', How I can control the collation in EF Linq query?
{ "language": "en", "url": "https://stackoverflow.com/questions/70001760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iOS framework to get audio in from dock connector How would I go abouts playing an 'audio in' through the dock connector in an iOS app? I'm making an app just for myself and have no plans of putting it into the apple store. I have the 30pin breakout board, and on it there are pins for L/R audio in, but I can not find any info on how to use them? Thanks A: As far as I'm aware, your only officially supported option for any accessory using the dock connector would be to use the External Accessory Framework, which requires enrollment in the Made for iPod Program (overkill for your purposes). However, the iPhone and iPod both support line-in via the headphone jack, and there are plenty of apps that make use of audio input. At least it provides some possibilities. A: Have you looked at the pinouts for the dock connector floating about? It appears that certain resistances connected to pin 21 indicate to the iDevice what is connected. 68kΩ seems to be the magic number for audio in/out.
{ "language": "en", "url": "https://stackoverflow.com/questions/4185790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Firebase Web Version 9 updateProfile not updating the authorized user I'm using Firebase Web version 9 in a react app. I have a sign-up form with first name, email, and password inputs. When the form is submitted, I need to create an authorized user with Firebase and immediately update that new user's first name and profile picture. I'm using two Firebase auth functions - createUserWithEmailAndPassword() and updateProfile(). A new user is always created when the form is submitted, but the profile updates only happen once in a while. I haven't been able to pinpoint the cases when the profile update is successful. Any ideas on what I'm missing? Would love some feedback and guidance. Thank you! Here's the code for the sign-up page. import { useState, useEffect } from 'react'; import { Link, useNavigate } from 'react-router-dom'; import { StyledHeader, StyledFooter, StyledDropdown, StyledForm, } from '../styles'; import { getAuth, createUserWithEmailAndPassword, updateProfile, } from 'firebase/auth'; import { ShortFooter, LanguageSelect, Form } from '../components'; import { logo, p1, p2, p3, p4, p5 } from '../assets'; const SignUp = ({ children }) => { const [firstName, setfirstName] = useState(''); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [isFirstNameEmpty, setIsFirstNameEmpty] = useState(true); const [isEmailEmpty, setIsEmailEmpty] = useState(true); const [isPasswordEmpty, setIsPasswordEmpty] = useState(true); const [error, setError] = useState(''); const [checked, setChecked] = useState(true); const [isShown, setIsShown] = useState(true); const isInvalid = firstName === '' || email === '' || password === ''; const navigate = useNavigate(); const userProfileImgs = [p1, p2, p3, p4, p5]; useEffect(() => { setTimeout(() => { // ️ scroll to top on page load window.scrollTo({ top: 0, left: 0, behavior: 'smooth' }); }, 100); }, []); const handlefirstNameChange = (firstName) => { if (firstName.length !== 0) { setIsFirstNameEmpty(false); } else { setIsFirstNameEmpty(true); } }; const handleEmailChange = (email) => { if (email.length !== 0) { setIsEmailEmpty(false); } else { setIsEmailEmpty(true); } }; const handlePasswordChange = (password) => { if (password.length !== 0) { setIsPasswordEmpty(false); } else { setIsPasswordEmpty(true); } }; const handleCheckbox = () => { setChecked((checked) => !checked); }; const handleLearnMore = (e) => { e.preventDefault(); setIsShown((isShown) => !isShown); }; const handleSignUp = async (e) => { e.preventDefault(); try { // firebase work! const auth = getAuth(); let { user } = await createUserWithEmailAndPassword( auth, email, password ); console.debug(`User ${user.uid} created`); // updating the user's profile with their first name and a random profile image await updateProfile(user, { displayName: firstName, photoURL: userProfileImgs[Math.floor(Math.random() * userProfileImgs.length)], }); console.debug(`User profile updated`); // navigate to the profile page navigate('/profile'); } catch (e) { if (e.message === 'Firebase: Error (auth/email-already-in-use).') { setError('That email is already in use, please try again.'); } } }; return ( <> <StyledHeader height="120"> <div className="header__background"> <div className="header__frame"> <div> <Link to="/"> <img className="header__logo" src={logo} alt="Netflix Logo" /> </Link> </div> </div> <form onSubmit={handleSignUp} className="form__container"> <StyledForm padding="20px 68px 40px"> <Form error={error} isEmailEmpty={isEmailEmpty} email={email} setEmail={setEmail} handleEmailChange={handleEmailChange} isPasswordEmpty={isPasswordEmpty} password={password} setPassword={setPassword} handlePasswordChange={handlePasswordChange} isInvalid={isInvalid} checked={checked} handleCheckbox={handleCheckbox} handleLearnMore={handleLearnMore} isShown={isShown} isFirstNameEmpty={isFirstNameEmpty} firstName={firstName} setfirstName={setfirstName} handlefirstNameChange={handlefirstNameChange} method="post" /> </StyledForm> </form> <div className="signIn__footer-container"> <div className="signIn__footer-background"> <StyledFooter backgroundColor="transparent" padding="10px 70px 40px 70px" > <ShortFooter> <StyledDropdown> <LanguageSelect /> </StyledDropdown> </ShortFooter> </StyledFooter> </div> </div> </div> {children} </StyledHeader> </> ); }; export default SignUp; This is the error I'm getting in the console. Error A: Based on how my app was set up I ultimately decided to remove the photoURL property altogether since it could be defined elsewhere in the app. After testing, only one of my images worked. This is why I experienced the full profile updates working out sometimes since random images were selected each time a new user signs up. I ended up sticking wth this image as the default image. As @adsy mentioned, my profile updates weren't happening consistently because certain profile images I had exceeded the allowed input body length for this property. The example in the Docs shows a link with 43 characters but no other information. The path to the profile images in the question are much shorter than this so I still need some understanding. After researching a bit, I didn't come across the maximum limit set. It's now something to contact Google Developer's support team about. If anyone has the information for the allowed input body length for this property, feel free to share it on this post. Thanks! const handleSignUp = async (e) => { e.preventDefault(); try { // firebase work! const auth = getAuth(); let { user } = await createUserWithEmailAndPassword( auth, email, password ); console.debug(`User ${user.uid} created`); // updating the user's profile with their first name await updateProfile(user, { displayName: firstName, }); console.debug(`User profile updated`); // navigate to the profile page navigate('/profile'); } catch (e) { if (e.message === 'Firebase: Error (auth/email-already-in-use).') { setError('That email is already in use, please try again.'); } } };
{ "language": "en", "url": "https://stackoverflow.com/questions/74168716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to search in string for inside of and unwrap it with PHP What is the best way to reformat the HTML with PHP. Put span tag outside of a tag? This: <p style="text-align:center"> <a href="#" target="_blank"><span style="color:green">Text Link</span></a> </p> To: <p style="text-align:center"> <span style="color:green"><a href="#" target="_blank">Text Link</a></span> </p> A: You can make a good use of preg_match function: $str = '<p style="text-align:center"> <a href="#" target="_blank"><span style="color:green">Text Link</span></a> </p>'; if(preg_match('/^(\<p.*?\>).*(\<a.*?\>).*(\<span.*?\>)([0-9a-zA-Z ]*).*$/is', $str, $regs)) { // $regs = [ // 0 => ... (original string) // 1 => '<p style="text-align:center">', // 2 => '<a href="#" target="_blank">', // 3 => '<span style="color:green">', // 4 => 'Text Link'] $newStr = $regs[1].$regs[3].$regs[2].$regs[4].'</a></span></p>'; } You may have to change the [0-9a-zA-Z ]* in regular expression to match your links format. If input HTML is multiple line text then you have to use s modifier after the regular exception, I also used i as case insensitive just to be sure noone mixed <P> and <p> tag together and so on... Note that this if fairly specific solution and for more general solution you should use something like loading HTML into DOM and working with nodes, but this is pretty simple and quick solution for this particular case.
{ "language": "en", "url": "https://stackoverflow.com/questions/47396861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: np.insert() -1 as the position of an element I am playing with the NumPy library and there is a behaviour that I do not understand: I defined a simple vector Y: Y = np.array([6,7,8],dtype = np.int16) Then, I tried to add an additional element at the end of the array using the np.insert() method. I specified the position to be at -1: Z = np.insert(Y,(-1),(19)) My element was inserted not on the last, but on the penultimate position: Output Could somebody explain my why this element was not inserted at the end of my array? A: Negative indexes are calculated using len(l) + i (with l being the object and i being the negative index). For example, with a list x = [1, 2, 3, 4] the index -2 is calculated as 4-2 = 2, so x[-2] returns 3 In this example, the index -1 is calculated as index 2 Therefore, 19 is inserted at index 2, the penultimate position. To fix this, use Z = np.insert(Y, len(Y), 19). PS - this is the same with list.insert, not just with numpy arrays Edit (suggested by Homer512): np.append may be easier than np.insert if you want to add to the end of an array: Z = np.append(Y, 19)
{ "language": "en", "url": "https://stackoverflow.com/questions/72677214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: why the computed method work on only one record? i did this method which compute the late hours of an employee and convert it at days in dedication filed on payslip, it working well but when there is more than one payslip and i need to get the sumition of dedication field of all payslips for an employee it give me just one record and return other records = 0.00 , here the methode @api.multi @api.depends('date_to','date_to','employee_id') def compute_amount(self): for rec in self: rec.attend = self.env['hr.attendance'].search( [('check_in', '>=', rec.date_from), ('check_out', '<=', rec.date_to), ('employee_id', '=', rec.employee_id.id), ]) late=[float(s.late) for s in rec.attend] tot_late= float(sum(late)) rec.dedication = tot_late / 8 pass dedication = fields.Float(string="Dedication", required=False,compute=compute_amount ) if i try to print all record i get a list like this [0.0, 0.0, 1.7551388888888888] if there is 3 payslips the list return only one record with the real value and other record = 0 any help will be apriciated A: It's probably because the rec.dedication = tot_late / 8 is outside the for rec in self loop. Which means the value is only set on the last record it computes. Also, the pass value seems unnecessary here.
{ "language": "en", "url": "https://stackoverflow.com/questions/59340675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: uisng multer with typescript: Property 'file' does not exist on type 'Request'.ts(2339) I am using https://www.npmjs.com/package/multer library and my node.js app is written in typescript. I get the following typescript error in my code. Property 'file' does not exist on type 'Request'.ts(2339) public document = async (req: Request, res: Response): Promise<any> => { const documentFile = req.file; } How can i resolve this. The req is the express Request object but multers middleware appends a .file into this request object. However it is not aware of this because the types request interface does not originally contain a file properly A: Like @daliusd mentioned in his answer, the accepted answer here should be: npm i @types/multer --save-dev req.files is now typed and recognized by the Typescript compiler. A: Probably we can just extend Request interface MulterRequest extends Request { file: any; } public document = async (req: Request, res: Response): Promise<any> => { const documentFile = (req as MulterRequest).file; } or may be like this code interface MulterRequest extends Request { file: any; } public document = async (req: MulterRequest , res: Response): Promise<any> => { const documentFile = req.file; } A: Or install @types/multer with npm i @types/multer --save-dev and check out this https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18569 A: if using typescript with express-fileupload you can install @types/express-fileupload as dev dependencie and it will be solved
{ "language": "en", "url": "https://stackoverflow.com/questions/58393620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Apache Beam count HBase row block and not return Start to try out the Apache Beam and try to use it to read and count HBase table. When try to read the table without the Count.globally, it can read the row, but when try to count number of rows, the process hung and never exit. Here is the very simple code: Pipeline p = Pipeline.create(options); p.apply("read", HBaseIO.read().withConfiguration(configuration).withTableId(HBASE_TABLE)) .apply(ParDo.of(new DoFn<Result, String>() { @ProcessElement public void processElement(ProcessContext c) { Result result = c.element(); String rowkey = Bytes.toString(result.getRow()); System.out.println("row key: " + rowkey); c.output(rowkey); } })) .apply(Count.<String>globally()) .apply("FormatResults", MapElements.via(new SimpleFunction<Long, String>() { public String apply(Long element) { System.out.println("result: " + element.toString()); return element.toString(); } })); when use Count.globally, the process never finish. When comment it out, the process print all the rows. Anyy ideas? A: Which version of beam are you using? Thanks for bringing this issue. I tried to reproduce your case and indeed there seems to be an issue with colliding versions of guava that breaks transforms with HBaseIO. I sent a pull request to fix the shading of this, I will keep you updated once it is merged so you can test if it works. Thanks again.
{ "language": "en", "url": "https://stackoverflow.com/questions/43092030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting error Uninitialized ASN.1 value when trying to use pympler.tracker.SummaryTracker() I have a memory leak in my python2.7 code and I'm trying to debug it using pympler. Traceback (most recent call last): File "eta/dynamic_eta_worker.py", line 29, in <module> tr = tracker.SummaryTracker() File "/usr/local/lib/python2.7/site-packages/pympler/tracker.py", line 45, in __init__ self.s0 = summary.summarize(muppy.get_objects()) File "/usr/local/lib/python2.7/site-packages/pympler/summary.py", line 131, in summarize total_size[otype] = _getsizeof(o) File "/usr/local/lib/python2.7/site-packages/pyasn1/type/base.py", line 145, in plug raise error.PyAsn1Error('Uninitialized ASN.1 value ("%s" attribute looked up)' % name) pyasn1.error.PyAsn1Error: Uninitialized ASN.1 value ("__sizeof__" attribute looked up) Tried to search here and in google and came out with nothing. The thing is that when I call pympler.tracker.SummaryTracker() from the python console it works like a charm. Thanks. A: pip install -U pyasn1 please try to upgrade pyasn1 version
{ "language": "en", "url": "https://stackoverflow.com/questions/42088990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Localizing XIB files - why there is a need I am beginner in iOS. I learned how to localize XIB files. This way two versions of my XIB file are created, say one for English version and one for Spanish. Here is sample of the spanish localized XIB: I was curious why there is need for localizing XIB files? I know how to localize any string using string tables and NSLocalizedString() method. Is localizing XIB files good because it is not possible/easy to use localized strings as titles for the controls in the interface builder? A: If you move to storyboards and autolayout you don't need to localize your UI, you just need to provide the localised strings files. A: Is localizing XIB files good because it is not possible/easy to use localized strings as titles for the controls in the interface builder? The backside is, when you need to show a message to the user sometimes needed the label localized text without colon. The xib provides name with colon and without. Sometimes hard to keep in evidence what / where is in localized xib. You can make an utility software to make easier the localisation of strings and editing those inline with many languages. That why I prefer strings localized over xib.
{ "language": "en", "url": "https://stackoverflow.com/questions/18231233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to start and stop jboss from apache ant build.xml file I have make jar war EAR using ant and Hudson and store all files at some temp folder now I want to copy all war and ear files to jboss jboss/default/deploy folder using Apache ANT How can I do this?? Following is my master build file which call all other build.xml files and make jar war ear files but after making this all files this don't copy all any of the files to jboss/default/deploy folder <copy todir="${jbossdeploy.dir}" overwrite="yes"> <fileset dir="${class.dir}/ear" includes="MessageBoardEAR.ear"/> </copy> <project name="master" > <property name="class.dir" location="../Source/buildwork" /> <property name="ecpsproperties.dir" location="D:\ecpsproperties\jars\platform" /> <property name="jbossdeploy.dir" location="D:\jboss-6.1.0.Final\server\default\deploy" /> <target name="clean"> <delete dir="${class.dir}" /> </target> <target name="makedir"> <mkdir dir="${class.dir}" /> <mkdir dir="${class.dir}/jar" /> <mkdir dir="${class.dir}/ear" /> <mkdir dir="${class.dir}/war" /> </target> <filelist id="projects" dir="."> <file name="../Source/ValueObjects/build.xml"/> <file name="../Source/ECPSValueObjects/build.xml"/> <file name="../Source/ECPSUtils/build.xml"/> <file name="../Source/CommonExceptions/build.xml"/> <file name="../Source/ECPSExceptions/build.xml"/> <file name="../Source/ECPSCommon/build.xml"/> <file name="../Source/BaseDAO/build.xml"/> <file name="../Source/PageManagerValueObjects/build.xml"/> <file name="../Source/PageManagerDAO/build.xml"/> <file name="../Source/ECPSDAO/build.xml"/> <file name="../Source/PageManagerEJBClient/build.xml"/> <file name="../Source/PartyEJBClient/build.xml"/> <file name="../Source/ReportsEJBClient/build.xml"/> <file name="../Source/StagingEJBClient/build.xml"/> <file name="../Source/MessageBoardEJBClient/build.xml"/> <file name="../Source/PageManagerFacade/build.xml"/> <file name="../Source/PartyFacade/build.xml"/> <file name="../Source/ReportsFacade/build.xml"/> <file name="../Source/StagingFacade/build.xml"/> <file name="../Source/MessageBoardFacade/build.xml"/> <file name="../Source/MessageBoardEJB/build.xml"/> <file name="../Source/MessageBoardEAR/build.xml"/> <file name="../Source/PageManagerEJB/build.xml"/> <file name="../Source/PageManagerEAR/build.xml"/> <file name="../Source/PartyEJB/build.xml"/> <file name="../Source/PartyEAR/build.xml"/> <file name="../Source/ReportsEJB/build.xml"/> <file name="../Source/ReportsEAR/build.xml"/> <file name="../Source/StagingEJB/build.xml"/> <file name="../Source/StagingEAR/build.xml"/> <file name="../Source/Admin/build.xml"/> <file name="../Source/eCPSClient/build.xml"/> <file name="../Source/MessageBoardServices/build.xml"/> <file name="../Source/OAuth/build.xml"/> <file name="../Source/PageManagerRest/build.xml"/> <file name="../Source/PartyServices/build.xml"/> <file name="../Source/ReportsServices/build.xml"/> <file name="../Source/StagingServices/build.xml"/> </filelist> <copy todir="${jbossdeploy.dir}" overwrite="yes"> <fileset dir="${class.dir}/ear" includes="MessageBoardEAR.ear"/> </copy> <target name="main" depends="clean, makedir"> <subant> <filelist refid="projects" /> </subant> </target> </project> A: use copy task e.g. <copy file="myfile.txt" todir="../some/other/dir"/> A: this should work as I have added copy task under main : <project name="master" > <property name="class.dir" location="../Source/buildwork" /> <property name="ecpsproperties.dir" location="D:\ecpsproperties\jars\platform" /> <property name="jbossdeploy.dir" location="D:\jboss-6.1.0.Final\server\default\deploy" /> <target name="clean"> <delete dir="${class.dir}" /> </target> <target name="makedir"> <mkdir dir="${class.dir}" /> <mkdir dir="${class.dir}/jar" /> <mkdir dir="${class.dir}/ear" /> <mkdir dir="${class.dir}/war" /> </target> <filelist id="projects" dir="."> <file name="../Source/ValueObjects/build.xml"/> <file name="../Source/ECPSValueObjects/build.xml"/> <file name="../Source/ECPSUtils/build.xml"/> <file name="../Source/CommonExceptions/build.xml"/> <file name="../Source/ECPSExceptions/build.xml"/> <file name="../Source/ECPSCommon/build.xml"/> <file name="../Source/BaseDAO/build.xml"/> <file name="../Source/PageManagerValueObjects/build.xml"/> <file name="../Source/PageManagerDAO/build.xml"/> <file name="../Source/ECPSDAO/build.xml"/> <file name="../Source/PageManagerEJBClient/build.xml"/> <file name="../Source/PartyEJBClient/build.xml"/> <file name="../Source/ReportsEJBClient/build.xml"/> <file name="../Source/StagingEJBClient/build.xml"/> <file name="../Source/MessageBoardEJBClient/build.xml"/> <file name="../Source/PageManagerFacade/build.xml"/> <file name="../Source/PartyFacade/build.xml"/> <file name="../Source/ReportsFacade/build.xml"/> <file name="../Source/StagingFacade/build.xml"/> <file name="../Source/MessageBoardFacade/build.xml"/> <file name="../Source/MessageBoardEJB/build.xml"/> <file name="../Source/MessageBoardEAR/build.xml"/> <file name="../Source/PageManagerEJB/build.xml"/> <file name="../Source/PageManagerEAR/build.xml"/> <file name="../Source/PartyEJB/build.xml"/> <file name="../Source/PartyEAR/build.xml"/> <file name="../Source/ReportsEJB/build.xml"/> <file name="../Source/ReportsEAR/build.xml"/> <file name="../Source/StagingEJB/build.xml"/> <file name="../Source/StagingEAR/build.xml"/> <file name="../Source/Admin/build.xml"/> <file name="../Source/eCPSClient/build.xml"/> <file name="../Source/MessageBoardServices/build.xml"/> <file name="../Source/OAuth/build.xml"/> <file name="../Source/PageManagerRest/build.xml"/> <file name="../Source/PartyServices/build.xml"/> <file name="../Source/ReportsServices/build.xml"/> <file name="../Source/StagingServices/build.xml"/> </filelist> <target name="main" depends="clean, makedir"> <subant> <filelist refid="projects" /> </subant> <copy todir="${jbossdeploy.dir}" overwrite="yes"> <fileset dir="${class.dir}/ear" includes="MessageBoardEAR.ear"/> </copy> </target> </project>
{ "language": "en", "url": "https://stackoverflow.com/questions/10225122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Storyboard Scene Editor vanished I'm still new to Xcode and developing iOS apps...when I was editing my storyboard, I somehow removed the menu that displays the list of scenes (which defaults to the right side of the file navigator). How do you bring this menu/view back up? A: If I understand what you want you must just click on the button at the bottom in yellow highlight:
{ "language": "en", "url": "https://stackoverflow.com/questions/40365271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Advantage of Class component over react hooks Every where I see are the advantages of hooks over class component , but still class components in react do exist so can anyone tell me the advantages of class components over hooks?
{ "language": "en", "url": "https://stackoverflow.com/questions/71423718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Image options to customize the visibility of tabs Expected behaviour: With respect to my use case, when the user clicks on image button, I must allow the user to only upload the image and hence I have to hide the URL tab. Actual behaviour: Currently there is no such option to hide the URL and to display only upload tab.
{ "language": "en", "url": "https://stackoverflow.com/questions/63096987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can you tell Google's gmail servers to ignore a missing messageID? We receive 12 emails daily from a vendor that supply data for management required reports. We originally set up a Gmail account to receive these messages which are processed by a CRON job. We discovered early on that the messages were never recorded as received by the email client, so we had them sent to another account and then auto-forwarded. This worked fine for a lot of months, then suddenly, a few months ago, messages that were auto-forwarded were randomly being rejected (the number of messages rejected has increased, but occasionally one or two still get through.) Interestingly, when we forward the messages manually, they go through just fine. Since we owned the account that was doing the auto-forwarding, we received the bounce backs. The bounce message from mailer-daemon@googlemail.com was comprised of a graphic of a stop light with the red light lit, and the text: Your message to destination_email@gmail.com has been blocked. See technical details below for more information. Below that is the technical details: The response was:<br />550 5.7.1 [209.85.220.41] Messages missing a valid messageId header are not accepted. s198-20020a632ccf000000b0042a2fdfda1csor3403081pgs.60 - gsmtp When we look at the header of the original message received from the data vendor we see this is the message ID: <6302575f.810a0220.ceb0b.5763SMTPIN_ADDED_MISSING@mx.google.com> When we forward the message manually (which are always received), a complete message ID is included in the forwarded message. We asked the vendor to either update their SMTP server to include a message ID, or programatically add a generated message ID (e.g., using a library such as Python has) so that their messages were compliant with the RFC, and were told that for security reasons they cannot do that. So we are on our own. Please note that we cannot just put a rule into the receiving Gmail account telling it to accept these messages, they are never received by the client, they are being blocked at Google. Is there a way to tell the Gmail servers for this account to ignore the message ID? Or is there another way we can work around this?
{ "language": "en", "url": "https://stackoverflow.com/questions/73436960", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AVAudioPlayer Not Working upon SpriteKit Scene Loading I was struggling hardcore with a simple task: Play an audio file in the background when a SpriteKit scene loads. I copied an audio file named "Test Song.wav" into my project and it was also found in my assets when I look under "Build Phases" > "Copy Bundle Resources" (which was what this post suggested to check for) My code compiled just fine, and my ring/silent switch was correctly turned to ring, but the audio didn't play when the scene loaded. I'm using * *Xcode Version 8.0 beta *iPhone 6S Plus running iOS 10 Beta 1 Here was my broken code: import AVFoundation class GameScene: SKScene { override func didMove(to view: SKView) { if let path = Bundle.main().pathForResource("Test Song", ofType: "wav") { let filePath = NSURL(fileURLWithPath:path) let songPlayer = try! AVAudioPlayer.init(contentsOf: filePath as URL) songPlayer.numberOfLoops = 0 songPlayer.prepareToPlay() songPlayer.play() } } } Note: I learned that in Swift 3.0, AVAudioPlayer's init() method no longer accepted the NSError parameter, so this code DOES NOT compile: var error:NSError? audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error) A: Thanks to this website I learned that my problem was the scope of my AVAudioPlayer object. Here is the working code: class GameScene: SKScene { var songPlayer:AVAudioPlayer? override func didMove(to view: SKView) { if let path = Bundle.main().pathForResource("Test Song", ofType: "wav") { let filePath = NSURL(fileURLWithPath:path) songPlayer = try! AVAudioPlayer.init(contentsOf: filePath as URL) songPlayer?.numberOfLoops = 0 //This line is not required if you want continuous looping music songPlayer?.prepareToPlay() songPlayer?.play() } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/38005361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set attributes while dynamically creating enum using EnumBuilder I have to create Enum dynamically from XML. XML format is as below: <?xml version="1.0" encoding="utf-8"?> <Category xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Game> <Name>Tekken</Name> <Code>10</Code> </Game> <Game> <Name>NFS</Name> <Code>20</Code> </Game> <Game> <Name>FinalFa</Name> <Code>40</Code> </Game> </Category> I want to create Enum which looks like this: [DataContract] [Flags] public enum Category { [EnumMember] Tekken = 10, [EnumMember] NFS = 20, [EnumMember] FinalFa = 40, } So far I have been able to create this: public enum Category { Tekken = 10, NFS = 20, FinalFa = 40, } C# code used to generate the Enum: private static void Create() { AppDomain currentDomain = AppDomain.CurrentDomain; AssemblyName asmName = new AssemblyName("EnumAssembly"); AssemblyBuilder asmBuilder = currentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave); ModuleBuilder mb = asmBuilder.DefineDynamicModule(asmName.Name, asmName.Name + ".dll"); EnumBuilder eb = mb.DefineEnum("MyNamespace.Category", TypeAttributes.Public, typeof(int)); FieldBuilder fb1 = eb.DefineLiteral("Tekken", 10); FieldBuilder fb2 = eb.DefineLiteral("NFS", 20); FieldBuilder fb3 = eb.DefineLiteral("FinalFa", 40); Type eType = eb.CreateType(); asmBuilder.Save(asmName.Name + ".dll"); foreach (object obj in Enum.GetValues(eType)) { Console.WriteLine("{0}.{1} = {2}", eType, obj, ((int)obj)); } } How can I add the attributes [DataContract], [Flags] and [EnumMember] to my enum? A: As you see, the DefineLiteral method returns a FieldBuilder (fb1, fb2, fb3). You can use SetCustomAttribute on the FieldBuilder to set an attribute. The linked MSDN article has an example on how to use it. The gist of it though, would be to use a CustomAttributeBuilder to build your attribute, then give it to SetCustomAttribute. A: Not exactly sure but something like this: Type myType = typeof(DataContract); ConstructorInfo myInfo = myType.GetConstructor(); eb.SetCustomAttribute(myInfo);
{ "language": "en", "url": "https://stackoverflow.com/questions/26279268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to access data inside Json nested objects from an API I am using cryptocomare API to get crypto coins data within a Nextjs App. What i doing is that when a user clicks on a perticular symbol, i redirect it to the coin details page where i try to extract the clicked symbol with getServerSideProps as follows and then dynamically put in the API call and send it to the API server. ` export const getServerSideProps = async (context) => { const res = await fetch( `https://min-api.cryptocompare.com/data/pricemultifull?tsyms=USD&fsyms=${context.params.symbol}` ); const icon = await res.json(); return { props: { icon, }, }; }; ` This call returns a json object of nested objects and it goes to 2-3 levels deep. On Top it looks like following: API call response Inside my code, I want to access the data Object -> RAW -> (whatever the user clicked on). But, Since the Symbol or coin queried by the user is dynamic (means i can't predict what is clicked) I never know what to query. SO i tried this to access the data object.RAW[0] In principal it should give me the whatever object is inside the object.RAW But it returns undefined Can please someone guide me , how can i get the data inside object.RAW without knowing what is inside? Thanks! I have tried object.RAW[0] to access the data...,.... A: You can use Object.values(object.RAW) to get an array of the values inside RAW (assuming RAW is not undefined) Doc: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
{ "language": "en", "url": "https://stackoverflow.com/questions/74615844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: goodness of fit of umap I'm given a 20122-dim matrix, each column is a 20-element vector. Now I apply umap to the matrix and get a 2122 matrix and a umap plot. How to measure the goodness of fit of this umap model? Is there any standard way to do that? A: UMAP has multiple purposes like clustering, supervised learning and outlier detection. What exactly do you want to do with UMAP? In case of clustering, you can take a look at sklearn cluster evaluation and compare the scores with other algorithms like t-SNE. To look for the structure, you can reduce your data to 2-3 dimensions and use a scatter plot to eye check the results. When you have labeled data, you can try to classify them with (nonlinear) classifiers like a random forest and compare the result score (e.g. accuracy) with other dimension reduction techniques like PCA. Maybe you look for the trustworthiness from sklearn. You can compare the scores of PCA with the score of UMAP or any other dimension reduction algorithm. source
{ "language": "en", "url": "https://stackoverflow.com/questions/73254937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to flip a pdf page upside down using python? I'm trying to flip pdf pages upside down using python. I have tried multiple libraries like PyPdf2, PyMuPDF and pdfminer. There is documentation on how to rotate a page, but that is not what I'm looking for. The closest solution I found was on one of PyMuPDF documentation pages, but its an example and doesn't offer the code as to how it was achieved. You can find the example page here: https://pymupdf.readthedocs.io/en/latest/matrix.html#flipping . Again the task is to flip the pdf pages not to rotate them. Thank you, in advance for your answers. A: The flipping is achieved by multiplying with a matrix that is initialized with those parameters: # Flip the page left-right (a = -1). destpage.showPDFpage(r * fitz.Matrix(a=-1), src, sourcepage.number) OR: # Flip the page up-down (d = -1). destpage.showPDFpage(r * fitz.Matrix(d=-1), src, sourcepage.number)
{ "language": "en", "url": "https://stackoverflow.com/questions/63545734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to constrain method to return type where : Attribute I have an attribute [System.AttributeUsage(System.AttributeTargets.Class] public class ModuleValues : System.Attribute { public Guid? Id { get; set; } public ModuleValues(string id) { Id = Guid.Parse(id); } } How can I create a generic method that returns the attribute once found? public static T GetAttribute<T>(Type type) where T : Attribute { object[] attrs = typeof(T).GetCustomAttributes(true); foreach (Attribute attr in attrs) { if (attr.GetType() == typeof (T)) { //Console.WriteLine(attr.ToString()); return attr as T; } } return default(T); } With the constraint in place, my method always returns null. When I remove the constraint, I can find the attribute with a Console.WriteLine but cannot return it because the line return attr as T; gives compile error The type parameter 'T' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint Example usage from my console: Assembly x = Assembly.GetAssembly(typeof(MyBase)); Type[] types = x.GetTypes(); foreach (Type type in types) { if (type.IsSubclassOf(typeof (MyBase))) { ModuleValues s = CustomAttributeHelper.GetAttribute<ModuleValues>(type); Console.WriteLine("S" + s); } } A: This should be: object[] attrs = type.GetCustomAttributes(true); Changing typeof(T) to input type. The GetCustomAttributes method gets attributes ON the called type. A: This line is the problem: object[] attrs = typeof(T).GetCustomAttributes(true); You're calling GetCustomAttributes on Type - not on the type that you're actually interested in. You want: object[] attrs = type.GetCustomAttributes(true); Or rather more simply, replace the rest of the method with: return (T) type.GetCustomAttributes(typeof(T), true).FirstOrDefault(); Note that that will also pick up attributes which are subclasses of T, but I'd expect that to be more useful anyway, in the rare cases where you're actually using inheritance on attributes.
{ "language": "en", "url": "https://stackoverflow.com/questions/23623689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ttransforming XML using XSLT with count I am trying to transform the following XML using XSLT Input XML <lst name="facet_pivot"> <arr name="party-name,entry-number,release-number"> <lst> <str name="field">party-name</str> <str name="value">XYZ CONSULTANTS</str> <int name="count">348</int> <arr name="pivot"> <lst> <str name="field">entry-number</str> <null name="value"/> <int name="count">1</int> <arr name="pivot"> <lst> <str name="field">release-number</str> <null name="value"/> <int name="count">1</int> </lst> </arr> </lst> <lst> <str name="field">entry-number</str> <null name="value"/> <int name="count">1</int> <arr name="pivot"> <lst> <str name="field">release-number</str> <null name="value"/> <int name="count">1</int> </lst> </arr> </lst> <lst> <str name="field">entry-number</str> <null name="value"/> <int name="count">1</int> <arr name="pivot"> <lst> <str name="field">release-number</str> <null name="value"/> <int name="count">1</int> </lst> </arr> </lst> <lst> <str name="field">entry-number</str> <str name="value">8300012706</str> <int name="count">1</int> <arr name="pivot"> <lst> <str name="field">release-number</str> <null name="value"/> <int name="count">1</int> </lst> </arr> </lst> <lst> <str name="field">entry-number</str> <str name="value">8300012821</str> <int name="count">1</int> <arr name="pivot"> <lst> <str name="field">release-number</str> <null name="value"/> <int name="count">1</int> </lst> </arr> </lst> <lst> <str name="field">entry-number</str> <str name="value">8300018075</str> <int name="count">1</int> <arr name="pivot"> <lst> <str name="field">release-number</str> <null name="value"/> <int name="count">1</int> </lst> </arr> </lst> <lst> <str name="field">entry-number</str> <str name="value">8300018083</str> <int name="count">1</int> <arr name="pivot"> <lst> <str name="field">release-number</str> <null name="value"/> <int name="count">1</int> </lst> </arr> </lst> <lst> <str name="field">entry-number</str> <str name="value">8300018133</str> <int name="count">1</int> <arr name="pivot"> <lst> <str name="field">release-number</str> <null name="value"/> <int name="count">1</int> </lst> </arr> </lst> <lst> <str name="field">entry-number</str> <str name="value">8300018141</str> <int name="count">1</int> <arr name="pivot"> <lst> <str name="field">release-number</str> <null name="value"/> <int name="count">1</int> </lst> </arr> </lst> <lst> <str name="field">entry-number</str> <null name="value"/> <int name="count">270</int> <arr name="pivot"> <lst> <str name="field">release-number</str> <null name="value"/> <int name="count">270</int> </lst> </arr> </lst> </arr> </lst> </arr> </lst> into something like required Output XML <reply> <party-name>XYZ CONSULTANTS</party-name> <count>348</count> <no-entry-release-count>4</no-entry-release-count> </reply> And Iam having issues transforming . I have tried using following xsl template <xsl:for-each select="lst"> <ns:party-name><xsl:value-of select="str[@name='value']"/></ns:party-name> <ns:shipments-count><xsl:value-of select="int[@name='count']" /></ns:shipments-count> <xsl:for-each select="arr[@name='pivot']"> <xsl:if test="lst/null[@name='value'] = '' and lst/arr[@name='pivot']/lst/null[@name='value']/text() = ''"> <ns:no-entry-or-line-release-count> <xsl:value-of select ="count(lst/null[@name='value'] = '' and lst/arr[@name='pivot']/lst/null[@name='value']/text() = '')"> </xsl:value-of> </ns:no-entry-or-line-release-count> </xsl:if> </xsl:for-each> </xsl:for-each> </xsl:template> but count always returns 1.Seems i am doing some thing wrong. I am not able to figure it out why it is always returning one. Any help is appreciated. A: You can use this template to get required counts. <xsl:template match="lst/arr/lst"> <ns:reply> <ns:party-name> <xsl:value-of select="str[@name='value']"/> </ns:party-name> <ns:shipments-count> <xsl:value-of select="int[@name='count']" /> </ns:shipments-count> <ns:no-entry-or-line-release-count> <xsl:value-of select ="count(arr[@name='pivot']/lst[count(str[@name='value'])=0]/arr[@name='pivot']/lst/int[@name='count'])"> </xsl:value-of> </ns:no-entry-or-line-release-count> </ns:reply> </xsl:template>
{ "language": "en", "url": "https://stackoverflow.com/questions/57318212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SwiftUI UIHostingController navigation title animation broken When I use a UIHostingController to push a new SwiftUI.View to the navigation stack of an existing UIKit UIViewController the animation of the title in the navigation bar is broken. I tested in Xcode 12.0 on a pure new project. Watch carefully the title "UIHostingController". You can see how the animation looks different from normal push animation, it just "appears" out of nothing and looks broken. The second animation happens already from SwiftUI.NavigationLink which looks fine. Here is a link to the sample project if you want to try it out: https://www.dropbox.com/s/mjkuzhpsb6yvlir/HostingControllerTest.zip?dl=0 See this GIF image: (open in another browser tab if you don't the see GIF animation) This is the code behind: class ViewController: UIViewController { private let button = UIButton(frame: .zero) override func viewDidLoad() { super.viewDidLoad() self.title = "UIHostingController Title Test" self.view.backgroundColor = UIColor.white self.view.addSubview(self.button) button.translatesAutoresizingMaskIntoConstraints = false button.setTitle("Push UIHostingController", for: .normal) button.addTarget(self, action: #selector(Self.pushVC), for: .touchUpInside) button.setTitleColor(.blue, for: .normal) NSLayoutConstraint.activate([ button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor), button.centerYAnchor.constraint(equalTo: self.view.centerYAnchor), button.widthAnchor.constraint(equalTo: self.view.widthAnchor), button.heightAnchor.constraint(equalToConstant: 50) ]) } @objc private func pushVC() { let vc = UIHostingController(rootView: Content()) self.navigationController?.pushViewController(vc, animated: true) } } struct Content: View { var body: some View { NavigationLink(destination: Content2()) { Text("Push NavigationLink") } .navigationTitle("UIHostingController") } } struct Content2: View { var body: some View { Text("Coming from NavigationLink") .navigationTitle("Native SwiftUI View") } } A: Found the solution for this issue. UIHostingController is in fact just a normal UIViewController (with some add-ons for SwiftUI). Which means everything which is available for a UIViewController is as well available for UIHostingController. So the solution for this is to set everything related to the navigation bar on UIHostingController and not in the wrapped SwiftUI View. let vc = UIHostingController(rootView: Content()) vc.title = "My custom title" Also all navigations buttons work much better if directly set on UIHostingController. A good alternative is also to directly derive from UIHostingController and implement custom needed behavior there. A: To force UIHostingController to set up its navigation item we can pre-render it in a separate window: let window = UIWindow(frame: .zero) window.rootViewController = UINavigationController(rootViewController: hostingController) window.isHidden = false window.layoutIfNeeded() The window could even be cached for pre-rendering other views.
{ "language": "en", "url": "https://stackoverflow.com/questions/69537578", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Insufficient access rights on cross-reference id in Salesforce when attempting to insert object from Mule I signed up for a Salesforce developer account and then created an Account object in Salesforce. I then ran a mule workflow to insert an Order object into Salesforce and it returns this error against the Account Id: [SaveResult errors='{[1][Error fields='{[0]}' message='insufficient access rights on cross-reference id: 0010Y00000A7kCp' statusCode='INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY' ] ,}' id='null' success='false' ] The same data is inserted successfully from https://workbench.developerforce.com so looks like something to do the call coming from Mule. Is there a setting for external applications that needs to be activated? There is only one user which is me and is the same one I used to create the Salesforce account and it has System Administrator privileges. When I change the login credentials to my other Salesforce developer account it works (this other account was setup in 2015). Is there a setting that needs to be changed or permissions added and if so how and where would I do this? Datamapper looks like this for the salesforce developer account that fails: output.Pricebook2Id = "01s0Y0000026KHiQAM"; output.AccountId = "0010Y00000A7kCpQAJ"; output.Status = "Draft"; output.Type = "Order"; output.BillingCity = "New York"; output.EffectiveDate = str2date("2016-10-16","yyyy-MM-dd"); Thanks for any help
{ "language": "en", "url": "https://stackoverflow.com/questions/41063794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Invalid action configuration: Exception while trying to read the task definition artifact file I have a Codepipeline that deploys an ECR image to an ECS cluster using an ECS Blue / Green Deployment action. The pipeline contains two sources: one for the ECR image using an AWS ECR action and another one for fetching the configuration from Github using a ThirdParty Github action. The ECR action outputs an image artifact while the Github action outputs a config artifact. Both of these artifacts are provided as an input to the ECS Blue / Green Deployment action. The pipeline fails at the ECS Blue / Green Deployment action with the following error (visible from AWS console): Invalid action configuration Exception while trying to read the task definition artifact file from: config Here is the structure of the pipeline (some details are edited for anonymity): $ aws codepipeline get-pipeline --name my-codepipeline { "pipeline": { "name": "my-codepipeline", "roleArn": "arn:aws:iam::123456789000:role/my-codepipeline-role", "artifactStore": { "type": "S3", "location": "my-codepipeline-s3" }, "stages": [ { "name": "Source", "actions": [ { "name": "ImageSource", "actionTypeId": { "category": "Source", "owner": "AWS", "provider": "ECR", "version": "1" }, "runOrder": 1, "configuration": { "ImageTag": "latest", "RepositoryName": "my-ecr" }, "outputArtifacts": [ { "name": "image" } ], "inputArtifacts": [] }, { "name": "ConfigSource", "actionTypeId": { "category": "Source", "owner": "ThirdParty", "provider": "GitHub", "version": "1" }, "runOrder": 1, "configuration": { "Branch": "master", "OAuthToken": "****", "Owner": "me", "PollForSourceChanges": "false", "Repo": "application-config" }, "outputArtifacts": [ { "name": "config" } ], "inputArtifacts": [] } ] }, { "name": "Deploy", "actions": [ { "name": "DeployBackend", "actionTypeId": { "category": "Deploy", "owner": "AWS", "provider": "CodeDeployToECS", "version": "1" }, "runOrder": 1, "configuration": { "AppSpecTemplateArtifact": "config", "AppSpecTemplatePath": "production/appspec.yaml", "ApplicationName": "my-codedeploy", "DeploymentGroupName": "my-codedeploy-group", "Image1ArtifactName": "image", "Image1ContainerName": "IMAGE_NAME", "TaskDefinitionTemplateArtifact": "config", "TaskDefinitionTemplatePath": "production/taskdef.json" }, "outputArtifacts": [], "inputArtifacts": [ { "name": "image" }, { "name": "config" } ] } ] } ], "version": 1 }, "metadata": { "pipelineArn": "arn:aws:codepipeline:ap-northeast-1:123456789000:my-codepipeline", "created": 1564107543.285, "updated": 1564107543.285 } } I have checked the compressed artifact in the S3 and it definitely contains the configuration files in the Github repository at the location specified by AppSpecTemplatePath and TaskDefinitionTemplatePath. Here is the content of appspec.yaml: $ cat production/appspec.yaml version: 0.0 Resources: - TargetService: Type: AWS::ECS::Service Properties: TaskDefinition: <TASK_DEFINITION> LoadBalancerInfo: ContainerName: "my-container" ContainerPort: 80 A: After extensively trying out things, I stumbled upon a thread in a foreign language which I cannot find it. The thread said something about the artifact being passed to the action cannot be larger than 3 MB. I solved my problem by reducing the size of the artifact (config). The configuration repository is shared among many projects and by moving those items to another project, I decreased the compressed artifact size from 14 MB to 3 kB. Miraculously, everything worked fine. AWS if you are reading this, please add more documentation about the artifact size limits to ECS CodeDeploy as I don't see any mention about this and I have no way of debugging this problem with such a general error message. A: As far as I understand there are three major things we have to check as even if there is a syntax issue on file we might get the exception * *Files exists on correct path and you have already verified this. *Content of the both taskdef.json file and appspec.yaml is proper without any syntax error and we can always refer to this document [1] for it. *Also make sure that image has correct place holder "<IMAGE1_NAME>". *Also if these options don't work then you may try to create on test public github repo just put taskdef.json and appspec.yaml file in it and test the same thing. [1] Tutorial: Create a Pipeline with an Amazon ECR Source and ECS-to-CodeDeploy Deployment - https://docs.aws.amazon.com/codepipeline/latest/userguide/tutorials-ecs-ecr-codedeploy.html A: Thought I know a little about artifact config and could not found any help. I created another codecommit repo where i stored appspec.yml and taskdef.json file only and followed this aws userguide. And this worked Previously I was committing those file with main project repo. But every time it failed in deploy state with this message.[Exception while trying to read the task definition artifact file from ...] I felt safe this way in production codebuild and codedeploy are separated in pipeline. I created artifact pipeline and build pipeline. Two pipeline. To blue/green ECS service.
{ "language": "en", "url": "https://stackoverflow.com/questions/57216053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Foundation 5 off-canvas full height of device I'm using Foundation's off-canvas navigation, attempting to make a navigation that takes up the full height of the device. By default, the height of the menu options are determined by the height of the content being shown. This means if your content is less than the height of the menu items, your menu items will be invisible. I would like both the menu, and the height of the content section to be fixed at the height of the device. With only scrolling in the content section if needed. Setting the height, and min-height of content area to 100% doesn't seem to have any effect - only using a fixed height e.g. 500px will change the height - but then this isn't scalable. How is this achieved? If I give '.inner-wrap' a fixed height, the whole thing will adjust. How can I make sure .inner-wrap takes the full height of a device? <div class="off-canvas-wrap"> <div class="inner-wrap"> <nav class="tab-bar"> <section class="left-small"> <a class="left-off-canvas-toggle menu-icon" ><span></span></a> </section> </nav> <aside class="left-off-canvas-menu"> <ul class="off-canvas-list"> <li><label>Label</label></li> <li><a href="#">link</a></li> <li><a href="#">link</a></li> <li><a href="#">link</a></li> </ul> </aside> <section class="main-section"> <div class="section-inner"> <p>blah blah</p> <p>test</p> </div> </section> <a class="exit-off-canvas"></a> </div> </div> A: Try if this works, first enclose the <div class="off-canvas-wrap"> in another div <div class="page"> <div class="off-canvas-wrap"> <div class="inner-wrap"> [..] </div> </div> </div> And then set the following css, body,html{ height:100%; width:100%; } .off-canvas-wrap,.inner-wrap{ height:100%; } If you want to block scrolling, say for a chat client, set .page height to 100%. And that would be body,html{ height:100%; width:100%; } .off-canvas-wrap,.inner-wrap{ height:100%; } .page{ height:100%; } A: This is the best way I've found and its pretty simple and non-hackish NOTE: this only works on some css3 browsers. Compatible Browsers Sass Version: .off-canvas-wrap { .inner-wrap{ min-height: 100vh; } } CSS Version: .off-canvas-wrap, .off-canvas-wrap > .inner-wrap { min-height: 100vh; } Edit: Foundation 6 sites version .off-canvas-wrapper-inner, .off-canvas{ min-height: 100vh; } A: I had the same problems and this is what i've done: i put .off-convas-wrapper , .inner-wrapper and aside out of my main content and just use .right(left)-off-canvas-toggle inside my body and my problem has solved. with this way i dont need contents anymore. BTW i put .exit-off-canvas at the end of my main content befor closing inner-wrapper tag A: I had to hack the JS a bit, I found that depending on when the content is taller than the browser/device height or does not push to 100% height there were issues. Here’s my suggested fix: https://github.com/zurb/foundation/issues/3800
{ "language": "en", "url": "https://stackoverflow.com/questions/20158607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: Using FOR XML to group against 2 sql tables I have a sql query below, that I would like to format as XML using the FOR XML syntax. SELECT gr.id, gr.created, ts.ordernumber FROM trGrouped gr INNER JOIN transactions ts ON ts.grouped_id = gr.id WHERE ts.ordernumber IN ('4003970100000383', '4003970100000376', '4003970100000369', '1022108100000018') This is an example of the XML format I would like the query to look like. <trans_groups> <grouped id="56" created="4/14/2017"> <ordernumber>1022108100000001</ordernumber> <ordernumber>1022108100000002</ordernumber> <ordernumber>1022108100000003</ordernumber> </grouped> <grouped id="57" created="4/14/2017"> <ordernumber>1022109100000001</ordernumber> <ordernumber>1022109100000002</ordernumber> </grouped> </trans_groups> So far I have not been able to get this quite right. I have tried the following but this is not grouping the orders. select gr.id as [@id], gr.created as [@created], ( SELECT ts.ordernumber as ordernumber ) FROM trGrouped gr inner join transactions ts on ts.grouped_id = gr.id where ts.ordernumber in('4003970100000383', '4003970100000376', '4003970100000369', '1022108100000018') FOR XML PATH('grouped'), ROOT('trans_groups') A: Here is one approach Example Declare @YourTable table (id int,created date, ordernumber varchar(25)) Insert Into @YourTable values (56,'04/14/2017','1022108100000001') ,(56,'04/14/2017','1022108100000002') ,(56,'04/14/2017','1022108100000003') ,(57,'04/14/2017','1022109100000001') ,(57,'04/14/2017','1022109100000002') Select [@id] = id ,[@created] = convert(VARCHAR(10), created, 101) ,( Select ordernumber From @YourTable A1 Where A1.id = A.id For XML Path(''), type ) From (Select Distinct ID,Created From @YourTable ) A For XML Path('grouped'), Root('trans_groups') Returns <trans_groups> <grouped id="56" created="04/14/2017"> <ordernumber>1022108100000001</ordernumber> <ordernumber>1022108100000002</ordernumber> <ordernumber>1022108100000003</ordernumber> </grouped> <grouped id="57" created="04/14/2017"> <ordernumber>1022109100000001</ordernumber> <ordernumber>1022109100000002</ordernumber> </grouped> </trans_groups> A: This is working for me. select gr.id as [@id], gr.created as [@created], ( SELECT ordernumber as ordernumber from transactions where grouped_id = grouped_id and ordernumber in ('4003970100000383', '4003970100000376', '4003970100000369', '1022108100000018') FOR XML path(''), type ) FROM (SELECT distinct gr.id, created FROM trGrouped gr inner join transactions ts on ts.grouped_id = gr.id where ts.ordernumber in('4003970100000383', '4003970100000376', '4003970100000369', '1022108100000018')) gr FOR XML PATH('grouped'), ROOT('trans_groups')
{ "language": "en", "url": "https://stackoverflow.com/questions/43554314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can't convert object of type java.lang.String to type - Firebase Error its firebase Error I cant get it please Help me to solve and tell me the reason why its happens. sorry For english and try to solve it E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.kunalgharate.weedon, PID: 16793 com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.kunalgharate.weedon.Friends at com.google.android.gms.internal.zg.zzb(Unknown Source) at com.google.android.gms.internal.zg.zza(Unknown Source) at com.google.firebase.database.DataSnapshot.getValue(Unknown Source) at com.firebase.ui.database.ClassSnapshotParser.parseSnapshot(ClassSnapshotParser.java:22) at com.firebase.ui.database.ObservableSnapshotArray.getObject(ObservableSnapshotArray.java:160) at com.firebase.ui.database.CachingObservableSnapshotArray.getObject(CachingObservableSnapshotArray.java:40) at com.firebase.ui.database.FirebaseRecyclerAdapter.getItem(FirebaseRecyclerAdapter.java:180) at com.firebase.ui.database.FirebaseRecyclerAdapter.onBindViewHolder(FirebaseRecyclerAdapter.java:217) at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6482) at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6515) at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5458) at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5724) at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5563) at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5559) at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2229) at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1556) at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1516) at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:608) at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3693) at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3410) at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1710) at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:346) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871) at android.view.Choreographer.doCallbacks(Choreographer.java:683) at android.view.Choreographer.doFrame(Choreographer.java:616) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857) at android.os.Handler.handleCallback(Handler.java:751) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6123) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) Application terminated. Activity Main import android.content.Context; import android.content.Intent; import android.os.Build; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.squareup.picasso.Picasso; import de.hdodenhof.circleimageview.CircleImageView; public class MainActivity extends AppCompatActivity { private FirebaseAuth mAuth; RecyclerView mSubsList; DatabaseReference mFriendsDatabase; DatabaseReference mUsersDatabase; private String mCurrent_user_id; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.main_page_toolbar); setSupportActionBar(toolbar); getSupportActionBar().setTitle("WeedON"); mAuth = FirebaseAuth.getInstance(); mCurrent_user_id = mAuth.getCurrentUser().getUid(); mSubsList =findViewById(R.id.subscribes_list); mSubsList.setHasFixedSize(true); mSubsList.setLayoutManager(new LinearLayoutManager(this)); mFriendsDatabase = FirebaseDatabase.getInstance().getReference().child("subscribers").child(mCurrent_user_id); mFriendsDatabase.keepSynced(true); mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users"); mUsersDatabase.keepSynced(true); } private void signOut() { mAuth.signOut(); } @Override protected void onStart() { super.onStart(); FirebaseRecyclerAdapter<Friends,MainViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Friends,MainViewHolder>( Friends.class, R.layout.single_service_layout, MainViewHolder.class, mFriendsDatabase ) { @Override protected void populateViewHolder(MainViewHolder viewHolder, Friends model, int position) { } }; mSubsList.setAdapter(firebaseRecyclerAdapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); if(item.getItemId() == R.id.main_logout_btn){ // mUserRef.child("online").setValue(ServerValue.TIMESTAMP); signOut(); Intent intent = new Intent(this, LoginActivity.class); startActivity(intent); finish(); // sendToStart(); } if(item.getItemId() == R.id.main_settings_btn){ Intent settingsIntent = new Intent(MainActivity.this, SettingsActivity.class); startActivity(settingsIntent); } if(item.getItemId() == R.id.main_all_btn){ Intent settingsIntent = new Intent(MainActivity.this, AllServicesActivity.class); startActivity(settingsIntent); } return true; } public static class MainViewHolder extends RecyclerView.ViewHolder{ View mView; public MainViewHolder(View itemView) { super(itemView); mView =itemView; } } } Database Screenshot enter image description here its Not showing layout Error or code Error what should i do ? A: By looking at your database I can see that your mFriendsDatabase DatabseReference points to some 'String' Values and you are telling your firebaseRecyclerAdapter that those are of type 'Friends,that is why the exception is thrown.Most probably your are doing a mistake while saving the value to database,instead of saving a Friends object you are saving some String value.But if that's not the case you can change your firebaseRecyclerAdapter to this... FirebaseRecyclerAdapter<String,MainViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<String,MainViewHolder>( String.class, R.layout.single_service_layout, MainViewHolder.class, mFriendsDatabase ) { @Override protected void populateViewHolder(MainViewHolder viewHolder, String mString, int position) { Log.d("TAG",mString); } }; mSubsList.setAdapter(firebaseRecyclerAdapter); A: To display those messages, please use the following code: DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference(); DatabaseReference uidRef = rootRef.child("subscribers").child(mCurrent_user_id); ValueEventListener eventListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(DataSnapshot ds : dataSnapshot.getChildren()) { String message = ds.getValue(String.class); Log.d("TAG", message); } } @Override public void onCancelled(DatabaseError databaseError) {} }; uidRef.addListenerForSingleValueEvent(eventListener);
{ "language": "en", "url": "https://stackoverflow.com/questions/47868662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: how to get in extjs getHours() values in 12 hours format currently getting hour values in 24 hours format Ext.application({ name: 'Fiddle', launch: function () { var t1 = Ext.create('Ext.form.field.Time', { xtype: 'timefield', name: 'in', fieldLabel: 'Time In', minValue: '6:00 AM', maxValue: '8:00 PM', increment: 60, renderTo: Ext.getBody() }); var time = Ext.Date.add(new Date(), Ext.Date.HOUR, + 14).getHours(); //getting hour values in 24 format want in 12 hours format t1.setMaxValue(time); //unable to setMaxValue } }); A: You can use Ext.Date class for getting 12 hours format. Here is defied some formats:- * *g 12-hour format of an hour without leading zeros 1 to 12 *i Minutes, with leading zeros 00 to 59 *a Lowercase Ante meridiem and Post meridiem am or pm *A Uppercase Ante meridiem and Post meridiem AM or PM I have created an Sencha fiddle demo it is showing how is working. Hope this will help you to solve your problem. Ext.create('Ext.form.Panel', { title: 'Time Card', width: 300, bodyPadding: 10, renderTo: Ext.getBody(), defaults: { xtype: 'timefield', minValue: '6:00 AM', maxValue: '8:00 PM', increment: 30, anchor: '100%', listeners: { change: function (timefield, newValue) { Ext.Msg.alert('Succes', 'Good you have selected <b>' + Ext.Date.format(newValue, 'g:i A') + '</b>'); } } }, items: [{ name: 'in', fieldLabel: 'Time In' }, { name: 'out', fieldLabel: 'Time Out' }, { xtype: 'button', text: 'Get current GMT+14 Time', handler: function () { var date = new Date(), dateGmtPlus14 = new Date(date.valueOf() + date.getTimezoneOffset() * 60000); //Multiply this by 60,000 (milliseconds in a minute) to get the milliseconds and subtract from the date to create a new date Ext.Msg.alert('Succes', 'Current time with GMT+14 is <br> 12 hours format : <b>' + Ext.Date.format(dateGmtPlus14, 'g:i:s A') + '</b><br>24 hours format: <b> ' + Ext.Date.format(dateGmtPlus14, 'G:i:s') + '</b>'); } }] }); You can use Date.getTimezoneOffset() or MDN. This returns the time difference between your date and GMT in minutes. Multiply this by 60,000 (milliseconds in a minute) to get the milliseconds and subtract from the date to create a new date. new Date(date.valueOf() + date.getTimezoneOffset() * 60000)
{ "language": "en", "url": "https://stackoverflow.com/questions/46676360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: IF-THEN-ELSE statements in postgresql I'm looking to write a postgresql query to do the following : if(field1 > 0, field2 / field1 , 0) I've tried this query, but it's not working if (field1 > 0) then return field2 / field1 as field3 else return 0 as field3 thank youu A: In general, an alternative to case when ... is coalesce(nullif(x,bad_value),y) (that cannot be used in OP's case). For example, select coalesce(nullif(y,''),x), coalesce(nullif(x,''),y), * from ( (select 'abc' as x, '' as y) union all (select 'def' as x, 'ghi' as y) union all (select '' as x, 'jkl' as y) union all (select null as x, 'mno' as y) union all (select 'pqr' as x, null as y) ) q gives: coalesce | coalesce | x | y ----------+----------+-----+----- abc | abc | abc | ghi | def | def | ghi jkl | jkl | | jkl mno | mno | | mno pqr | pqr | pqr | (5 rows) A: case when field1>0 then field2/field1 else 0 end as field3 A: As stated in PostgreSQL docs here: The SQL CASE expression is a generic conditional expression, similar to if/else statements in other programming languages. Code snippet specifically answering your question: SELECT field1, field2, CASE WHEN field1>0 THEN field2/field1 ELSE 0 END AS field3 FROM test
{ "language": "en", "url": "https://stackoverflow.com/questions/19029842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "136" }
Q: Conditional redirect URL java It's realted to Conditional redirect the current URLs to new URLs, so that I can write "ONE script" and copy it into all the current old HTMLs for the same script. It would help those users whom had bookmarked the old URL and redirect to the new URL. I have an old webpeges like * *www.oldsite.com/a1.html *www.oldsite.com/a1/5698.html *www.oldsite.com/x1.html *www.oldsite.com/YY1.html and want to get current URL of an user and using location.path and redirect to newsite.com base on the path (suffix) ie * *www.oldsite.com/a1.html to www.newsite.com/b1.html *www.oldsite.com/a1/5698.html to www.newsite.com/b1/5698.html *www.oldsite.com/x1.html to www.newsite.com/99.html *www.oldsite.com/YY1.html to www.newsite.com/ZZ1.html I have tried many times but fail! Since I am a new comer to HTML, can anyone can help me? My site held more than a hundred old html! Here is my draft <html> <head> <javascript> if window.location.path='/al.html' { window.location="http://www.newsite.com/b1.html"} else if window.location.path='/al/5698.html' { window.location="http://www.newsite.com/b1/5698.html"} ......... </script> </head> A: Given import java.net.URI; URI oldUri; you can do that translation by creating a new uri from the old. URI newUri = new URI( oldUri.getScheme(), "www.newsite.com", translatePath(oldUri.getPath()), oldUri.getQuery(), oldUri.getFragment()); You haven't provided enough examples for me to know what translatePath should do, but given a string like "/a1.html" it returns "/b1.html".
{ "language": "en", "url": "https://stackoverflow.com/questions/15226030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multiply Vector Elements by Vector to Return a Square Matrix I am fairly new to APL and am struggling to multiply each element of a vector v by the vector in such a fashion that it returns an n x n square matrix where n is the length of the vector. For example, v ← 1 0 0 1. I have attempted to create a function such as: ⍳⍴v{⍵×⍵[⍺]}v 1 4 9 16 I am failing to iterate the ioda through the vector, which is one part I need guidance on. My overall goal is to return a matrix: v_1 x v --> 1 0 0 1 v_2 x v --> 0 0 0 0 v_3 x v --> 0 0 0 0 v_4 x v --> 1 0 0 1 I will keep trying to figure this out. Any help is appreciated, thanks! A: "Outer product" comes to rescue: (⍳10)∘.×⍳10 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100 BTW, in case you are trying to learn Dyalog APL, I'd recommend having a look at "Mastering Dyalog APL". And in case you're trying to learn a different dialect, I'd recommend considering to change to Dyalog. (I'm a Dyalog-Fanboy and have made the change myself 20yrs ago. Today Dyalog appears to be practically the only APL-Interpreter that is actively developed and enhanced...)
{ "language": "en", "url": "https://stackoverflow.com/questions/40272357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: gtk odd behavior GtkTree append tree_add is called by g_idle_add in another thread odd behaviour is that the hash is garbage, how would the message digest end up garbled? the rest of the odd behaviour has been fixed with the below suggestions #include <pthread.h> #include <openssl/evp.h> #include <gcrypt.h> #include <gtk/gtk.h> unsigned char *mdSHA256(char *data, size_t *len) { unsigned char *md = calloc(33, sizeof(char)); int mdlen; EVP_MD_CTX *mdctx; EVP_add_digest(EVP_sha256()); mdctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL); EVP_DigestUpdate(mdctx, data, *len); EVP_DigestFinal_ex(mdctx, md, &mdlen); EVP_MD_CTX_destroy(mdctx); EVP_cleanup(); *len = mdlen; return md; } struct peer { int approved; int port; unsigned char *address; gcry_sexp_t pubkey; struct sf_connection *connection; struct peer *next; struct peer *prev; }; struct peer *peers = NULL; struct peer *peer_new() { struct peer *_peer = malloc(sizeof(struct peer)); if(peers == NULL) { _peer->next = _peer; _peer->prev = _peer; peers = _peer; } else { peers->prev->next = _peer; _peer->prev = peers->prev; peers->prev = _peer; _peer->next = peers; } return _peer; } void *mainthread(void *m) { //code removed so you can run this sleep(2); struct peer *new_peer = new_peer(); new_peer->port = 66666; new_peer->address = "127.0.0.1"; new_peer->pubkey = NULL; new_peer->approved = 0; g_idle_add(tree_add, new_peer); } gboolean tree_add(gpointer data) { struct peer *new_peer = data; GtkTreeIter iter; size_t size = gcry_sexp_sprint(new_peer->pubkey, GCRY SEXP_FMT_ADVANCED, NULL, 0); char *buf = malloc(size); gcry_sexp_sprint(new_peer->pubkey, GCRYSEXP_FMT_ADVANCED, buf, size); unsigned char *md = mdSHA256(buf, &size); gtk_tree_store_append(serverstore, &iter, NULL); gtk_tree_store_set(serverstore, &iter, COL_IP, new_peer->address, COL_PORT, new_peer->port, COL_PUBKEYMD, md, COL_APPROVED, new_peer->approved, -1); free(buf); free(md); return 0; } GtkWidget *setup_tree() { GtkWidget *tree; GtkTreeViewColumn *column; GtkCellRenderer *renderer; serverstore = gtk_tree_store_new(N_COLUMNS, G_TYPE_STRING, G_TYPE_INT, G_TYPE_STRING, G_TYPE_BOOLEAN); tree = gtk_tree_view_new_with_model(GTK_TREE_MODEL(serverstore)); g_object_unref(G_OBJECT(serverstore)); renderer = gtk_cell_renderer_text_new(); column = gtk_tree_view_column_new_with_attributes("IP", renderer, "text", COL_IP, NULL); gtk_tree_view_append_column(GTK_TREE_VIEW(tree), column); renderer = gtk_cell_renderer_text_new(); column = gtk_tree_view_column_new_with_attributes("Port", renderer, "text", COL_PORT, NULL); gtk_tree_view_append_column(GTK_TREE_VIEW(tree), column); renderer = gtk_cell_renderer_text_new(); column = gtk_tree_view_column_new_with_attributes("PubKey", renderer, "text", COL_PUBKEYMD, NULL); gtk_tree_view_append_column(GTK_TREE_VIEW(tree), column); renderer = gtk_cell_renderer_toggle_new(); column = gtk_tree_view_column_new_with_attributes("Approved", renderer, "active", COL_APPROVED, NULL); gtk_tree_view_append_column(GTK_TREE_VIEW(tree), column); return tree; } void on_window_main_destroy() { raise(SIGINT); gtk_main_quit(); } int main(int argc, char **argv) { GtkWidget *window; GtkWidget *view; pthread_t main_thread; if(pthread_create(&main_thread, NULL, mainthread, NULL)) { fprintf(stderr, "Error creating thread\n"); return 1; } gtk_init(&argc, &argv); window = gtk_window_new(GTK_WINDOW_TOPLEVEL); g_signal_connect(window, "destroy", on_window_main_destroy, NULL); gtk_window_set_title(GTK_WINDOW(window), "ProjXverse Master"); gtk_window_set_default_size(GTK_WINDOW(window), 640, 480); view = setup_tree(); gtk_container_add(GTK_CONTAINER(window), view); gtk_widget_show_all(window); gtk_main(); pthread_join(main_thread, NULL); return 0; } to make gcc -c main.c -o test `pkg-config --cflags --libs gtk+-3.0` -lcrypto -lgcrypt -lpthread
{ "language": "en", "url": "https://stackoverflow.com/questions/33966618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: File download fails with AFNetworking and other frameworks. wifi goes to sleep automatically - objective c I'm downloading files with AFNetworking framework. File downloads well in foreground mode. But when I put my app to background, WiFi goes to sleep automatically after 10 minutes, by iOS, and my AFNetworking request loses connection. In my AppDelegate I have this code to run background task: -(void) runBackgroundTask { if (bgTaskId!=UIBackgroundTaskInvalid) [[UIApplication sharedApplication] endBackgroundTask: bgTaskId]; UIBackgroundTaskIdentifier newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ [[UIApplication sharedApplication] endBackgroundTask: bgTaskId]; [self runBackgroundTask]; }]; bgTaskId = newTaskId; } How disable automatic WiFi sleep? If I run music on my app and downloading file - everything is OK. WiFi doesn't disable. How I can solve this problem?
{ "language": "en", "url": "https://stackoverflow.com/questions/16123236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery toggling all divs instead of just one I have a bunch of div that I am going to toggle upon click. However, I do not want to have a bunch of different jquery functions to accomplish the same thing. The problem is that my current function will toggle all of the divs as opposed to just the selected one. Any solutions for toggling only the one that is selected without having a bunch of jquery functions? JSFIDDLE HTML: <div class="help-spacer"> <div class="help-info"> <a href="" class="help-info-link"><i class="fa fa-plus-circle"></i> Hello</a> </div> <div class="help-info-text" hidden> Hello Hello Hello </div> </div> <div class="help-spacer"> <div class="help-info"> <a href="" class="help-info-link"><i class="fa fa-plus-circle"></i> Hello</a> </div> <div class="help-info-text" hidden> Hello Hello Hello </div> </div> CSS: .help-info { background: #f1f1f1; width: 650px; margin: 0 auto; padding: 15px 20px; font-family: 'Open Sans', serif; } .help-info-open { background: #1795db; width: 650px; margin: 0 auto; padding: 15px 20px; font-family: 'Open Sans', serif; } .help-info-link { color: #5c5c5c; } .help-info-link-open { color: #ffffff; } .help-info-text { background: #fff; font-family: 'Open Sans', serif; color: #5c5c5c; width: 650px; margin: 0 auto; padding: 15px 20px; box-shadow: 0px 1px 2px 0px rgba(0,0,0,0.2); -moz-box-shadow: 0px 1px 2px 0px rgba(0,0,0,0.2); -webkit-box-shadow: 0px 1px 2px 0px rgba(0,0,0,0.2); -o-box-shadow: 0px 1px 2px 0px rgba(0,0,0,0.2); } JQUERY: $(".help-info-link").click(function(event){ event.preventDefault(); $('.help-info').toggleClass('help-info-open'); $('.help-info-link').toggleClass('help-info-link-open'); $('.help-info-text').toggle(); }); A: Inside the event handler, this refers to the clicked element. So you can do something like this: $(".help-info-link").click(function(event){ event.preventDefault(); $(this).closest('.help-info').toggleClass('help-info-open'); $(this).toggleClass('help-info-link-open'); $(this).closest('.help-info').next('.help-info-text').toggle(); }); See here: http://jsfiddle.net/4q6b0gn4/ A: Instead of closest you could use the direct parent function, and a next function like i've done here: http://jsfiddle.net/uq6xcdo5/1/ $(".help-info-link").click(function(event){ event.preventDefault(); $(this).parent().toggleClass('help-info-open'); $(this).toggleClass('help-info-link-open'); $(this).parent().next(".help-info-text").toggle(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/25253354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dynamically instancing a class then deleting it right away? I created my own class but when I try to instantiate it I run into a wall. Here's my code: m_interpolation = new Interpolation(m_mesureList, width, height, parent); delete m_interpolation; Which generates the error: Heap block at 0B3E9E40 modified at 0B3E9E68 past requested size of 20 I don't see what I'm doing wrong... For information here is the full definition of my class Interpolation.h and Interpolation.cpp if that's of any help. Added a destructor but still didn't fix the problem. Interpolation::~Interpolation() { delete m_progress; m_progress = 0; } A: In the ctor: Populating m_w: up to (m_N-1) for (int i(0); i < m_N; ++i) { m_pt.push_back(QPointF(mesureList[i]->getX(), mesureList[i]->getY())); m_w.push_back(mesureList[i]->getAngle()); } Later: accessing m_w[m_N], beyond the end of the vector for (i = m_N; i >= 0; --i) { sum = m_w[i]; for (j = i+1; j < m_N; j++) sum -= LU[i][j]*m_w[j]; m_w[i] = sum / LU[i][i]; } A: Something inside the constructor Interpolation::Interopolation() or the destructor Interpolation::~Interpolation() is writing beyond the size of the object.
{ "language": "en", "url": "https://stackoverflow.com/questions/11160013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Change date format of pandas column (month-day-year to day-month-year) Got the following issue. I have an column in my pandas with some dates and some empty values. Example: 1 - 3-20-2019 2 - 3 - 2-25-2019 etc I want to convert the format from month-day-year to day-month-year, and when its empty, i just want to keep it empty. What is the fastest approach? Thanks! A: One can initialize the data for the days using strings, then convert the strings to datetimes. A print can then deliver the objects in the needed format. I will use an other format (with dots as separators), so that the conversion is clear between the steps. Sample code first: import pandas as pd data = {'day': ['3-20-2019', None, '2-25-2019'] } df = pd.DataFrame( data ) df['day'] = pd.to_datetime(df['day']) df['day'] = df['day'].dt.strftime('%d.%m.%Y') df[ df == 'NaT' ] = '' Comments on the above. The first instance of df is in the ipython interpreter: In [56]: df['day'] Out[56]: 0 3-20-2019 1 None 2 2-25-2019 Name: day, dtype: object After the conversion to datetime: In [58]: df['day'] Out[58]: 0 2019-03-20 1 NaT 2 2019-02-25 Name: day, dtype: datetime64[ns] so that we have In [59]: df['day'].dt.strftime('%d.%m.%Y') Out[59]: 0 20.03.2019 1 NaT 2 25.02.2019 Name: day, dtype: object That NaT makes problems. So we replace all its occurrences with the empty string. In [73]: df[ df=='NaT' ] = '' In [74]: df Out[74]: day 0 20.03.2019 1 2 25.02.2019 A: Not sure if this is the fastest way to get it done. Anyway, df = pd.DataFrame({'Date': {0: '3-20-2019', 1:"", 2:"2-25-2019"}}) #your dataframe df['Date'] = pd.to_datetime(df.Date) #convert to datetime format df['Date'] = [d.strftime('%d-%m-%Y') if not pd.isnull(d) else '' for d in df['Date']] Output: Date 0 20-03-2019 1 2 25-02-2019
{ "language": "en", "url": "https://stackoverflow.com/questions/58327249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Move 50,000 selected emails (not all) from one IMAP folder to another on same server? I use an IMAP mail folder that contains 80,000 messages, and I'd like to move a selected subset of ~50,000 messages (all the messages dated in 2020) to another folder on the same IMAP server. Can this be scripted from the Linux command line on the client computer (not on the IMAP server computer)? Fetchmail? Movemail? Anything? Also same question for deletion: is there a way to select (say) 50,000 emails from 2018 in an IMAP mail folder and delete them, via Linux command line tools? Note: The server is outlook.com (Office 365) if it matters. I tried using Outlook (GUI) for this operation, but it can't even select "all emails from year" in any efficient way. I also tried Thunderbird with Owl to speak Exchange, and even though I can select the emails, the big move simply doesn't occur. A scripting approach is the latest attempt. Thank you! A: I recently found myself having to automatically move messages on an IMAP server from one folder to another. To do this reliably, I wrote a script which I call imap-helper. It connects to an IMAP server and moves messages matching a given query string between two folders. It uses Mail::IMAPClient which is supplied by a package (perl-mail-imapclient) in my distribution (Arch). In my coment on the original post I suggested using gnutls-cli to connect to your IMAP server; I still recommend doing this to get a grasp of what's happening behind the scenes (and so you can debug your query syntax more quickly). Here's an example raw IMAP session just for reference, but the script that follows it should be better suited for your problem. * *(The tool rlwrap provides GNU Readline editing and history to the interaction) $ rlwrap -S "> " gnutls-cli imap.mail.yahoo.com -p 993 > A LOGIN myusername mypassword A OK LOGIN completed > A LIST "" * # List all the folders on the server * LIST (\HasNoChildren) "/" "ALL" * LIST (\Junk \HasNoChildren) "/" "Bulk Mail" * LIST (\HasNoChildren) "/" "Inbox" ... A OK LIST completed > A SELECT Inbox * 12 EXISTS * 0 RECENT ... A OK [READ-WRITE] SELECT completed; now in selected state > A SEARCH BEFORE 01-Jan-2021 * SEARCH 11 12 A OK SEARCH completed > A MOVE 11,12 "Bulk Mail" * OK [COPYUID 1609256255 58:59 57:58] ... A OK MOVE completed As for the script, I have tested it on my Gmail Inbox which has 13000 messages. I moved them all from INBOX to INBOX2 (which Gmail created automatically). This took a couple of minutes. Then I moved them back again. I'd be glad to hear if it works on your server. For your case what you'd do is first create a file called ~/.imap-creds.pl with your server, username, and password. Then you'd run something like $ imap-helper outlook FOLDER1 'SINCE "01-Jan-2019" BEFORE "01-Jan-2020"' FOLDER2 -e to move all messages in FOLDER1 that were received in 2019, into FOLDER2. The user interface is designed so that you can build the command one argument at a time: $ imap-helper # lists accounts from config file gmail ... $ imap-helper gmail # lists folders in the gmail account INBOX Personal Receipts ... $ imap-helper gmail INBOX # lists messages in INBOX ... etc. Here is the script: #!/usr/bin/perl # 21 Jan 2021 use warnings; use strict; use open (":encoding(UTF-8)", ":std" ); use Mail::IMAPClient; use Data::Dumper; $Data::Dumper::Indent=0; $Data::Dumper::Purity=1; $Data::Dumper::Terse=1; use Getopt::Long; Getopt::Long::Configure ("bundling", "no_ignore_case"); use Carp; $SIG{__DIE__} = sub { my $error = shift; Carp::confess "Error: "; }; # change the help text if you change this my $credfn=glob("~/.imap-creds.pl"); my($bad_args, $help, $verbose, $execute, $max, $zero_results_ok); GetOptions('-h|help' => \$help, '-v|verbose' => \$verbose, '-e|execute' => \$execute, '-z|zero-results-ok' => \$zero_results_ok, '-m|max=f' => \$max ) or $bad_args = 1; my ($action); my ($acct, $src, $dst, $query); sub verb { warn "imap-helper: ",@_,"\n" if $verbose; } if(@ARGV>4) { warn "Expected 4 arguments but you passed ".scalar(@ARGV); $bad_args = 1; } elsif(@ARGV==4) { $action = "move"; } elsif(@ARGV==3) { $action = "search"; } elsif(@ARGV==2) { $action = "list"; } elsif(@ARGV==1) { $action = "folders"; } elsif(@ARGV==0) { $action = "accounts"; } ($acct,$src,$query,$dst) = @ARGV; sub usage { "Usage: imap-helper [-h | -v | -e | -z] ACCOUNT SRC_FOLDER QUERY DST_FOLDER\n"; } sub help { q{ Options: -h --help print this message -v --verbose be verbose -e --execute execute the move -z --empty-search-ok exit 0 on empty search (for scripts) By default no messages are moved, pass -e to execute the move. Configuration: ~/.imap-creds.pl Config syntax: [ SERVER_NAME => { Server => "HOST", User => "USER", Password => "PASS" }, ... ] With zero arguments, lists accounts. With only the ACCOUNT argument, lists folders on ACCOUNT. With SRC_FOLDER argument, list contents of SRC_FOLDER. With QUERY argument, list results of QUERY. With DST_FOLDER argument, plan a move of messages matching QUERY from SRC_FOLDER to DST_FOLDER. Pass "-e" to execute the move. QUERY is an IMAP query, like "ALL" or 'BEFORE "15-Jan-2021"' (dates must be in this exact format). Other keywords include TO, CC, FROM, SUBJECT, TEXT; AND, OR, NOT; LARGER, SMALLER; NEW, RECENT, SEEN, ANSWERED. See <https://tools.ietf.org/html/rfc3501> for a full list. IMAP queries can be combined, for example: $ imap-helper gmail INBOX 'SINCE "01-Jan-2020" BEFORE "01-Jan-2021"' # (lists all INBOX messages from 2020) This tool uses MOVE which is not part of the original IMAP RFC but which should be well supported. Example interaction: $ cat .imap-creds.pl [ yahoo => { Server => 'imap.mail.yahoo.com', User => 'napoleon', Password => 'MYPASSWORD123' }, gmail => ... ] $ imap-helper yahoo gmail $ imap-helper yahoo ALL Archive Inbox ... $ imap-helper yahoo Inbox 48 19 Jan 2021 XXXXX@yahoo.com YYYYY@gmail.com test 2 ... $ imap-helper yahoo Inbox "BEFORE 15-Jan-2021" 50 29 Dec 2020 XXXXX@yahoo.com YYYYY@yahoo.com test 1 ... $ imap-helper yahoo Inbox "BEFORE 15-Jan-2021" Archive -e -v -z imap-helper: Connecting to server imap.mail.yahoo.com as XXXXX imap-helper: Searching for BEFORE 15-Jan-2021 imap-helper: Found 1 matches for BEFORE 15-Jan-2021 imap-helper: Moving 1 messages }; } if($bad_args) { print STDERR usage; exit(1) } if($help) { my $pager = $ENV{PAGER};; open STDOUT, "| $pager" or warn "Not paging STDOUT: $!\n" if defined $pager; print (usage, help); close(STDOUT); wait(); exit(0); } die "Shouldn't get here" if !defined $action; ################################################################ ## LOGIN if(!-e $credfn) { die "Missing credential file $credfn\n"; } my $creds = eval `cat $credfn`; #verb (Dumper($creds)); ref $creds eq "ARRAY" or die "Expected an array: $credfn\n". "Got: ".(Dumper($creds))."\n"; if($action eq "accounts") { # no account specified, just list them all verb "Listing accounts from $credfn\n"; my $ind = 0; my @accts = grep {!($ind++ % 2)} (@$creds); print "$_\n" for(@accts); exit(0); } my %creds = @$creds; my $srvcr = $creds{$acct}; if(!defined $srvcr) { die "Account $acct not found in $credfn\n"; } verb "Connecting to server $srvcr->{Server} as $srvcr->{User}"; my $imap = Mail::IMAPClient->new( Server => $srvcr->{Server}, User => $srvcr->{User}, Password => $srvcr->{Password}, Ssl => 1, Uid => 1, ) or die "Could not connect to $srvcr->{Server} as $srvcr->{User}\n"; if($action eq "folders") { my $folders = $imap->folders or die "Error listing folders: ", $imap->LastError, "\n"; print join("\n",@$folders),"\n"; exit(0); } $imap->select( $src ) or die "Select $src error: ", $imap->LastError, "\n"; # Truncate a string $s to width $w, for use in a table sub trunc { my ($s, $w) = @_; $s = "" if !defined($s); if(ref $s eq "ARRAY") { $s = join(",",@$s); } my $l = length($s); my $o; if($l>=$w) { $o = substr($s,0,$w-3)."..."; } else { $o = $s.(" "x($w-$l)); } return $o; } sub show_msgs { my @msgs = @_; # this should but doesn't work (as first argument to parse_headers) # my $r = $imap->Range(@msgs); my $heads = $imap->parse_headers(\@msgs, "Date", "Subject", "To", "From"); # for my $msg (sort {$a <=> $b} (keys %$heads)) { for my $msg (@msgs) { my $hs = $heads->{$msg}; my $date = $hs->{Date}->[0]||""; # remove weekday and HH:MM:SS from date $date =~ s/^\D+,\s*//; $date =~ s/ \d\d:.*$//; print trunc($msg,7)," ", trunc($date,12)," ", trunc($hs->{To},25)," ", trunc($hs->{From},25)," ", trunc($hs->{Subject},25), "\n"; } } if($action eq "list") { my @msgs = $imap->messages; if(defined($max) && @msgs>$max) { @msgs = @msgs[0..($max-1)]; } show_msgs(@msgs); exit(0); } verb "Searching for $query"; my @msgs = $imap->search($query); if(!@msgs) { if(!$zero_results_ok) { die "Error or no matches for $query ",$imap->LastError,"\n"; } else { verb "No matches found for $query"; exit 0; } } verb "Found ".(@msgs)." matches for $query"; if(defined $max && @msgs > $max) { @msgs = @msgs[0..($max-1)]; } if($action eq "search") { show_msgs(@msgs); exit(0); } if($action eq "move") { verb "Moving ".(@msgs)." messages"; my $msgstr=join(",",@msgs); if(!$execute) { warn "Would have moved $msgstr from $src to $dst\n"; warn "Pass -e to execute move\n"; } else { $imap->move($dst,$msgstr) or die "Could not move messages\n"; } exit(0); } die "Something wrong";
{ "language": "en", "url": "https://stackoverflow.com/questions/65613589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why am I *not* getting this warning: "variable masks earlier declaration"? Here's my entire script, crafted to include two variable with the same name, one of which is masking the other: #!/usr/bin/env perl use strict; use warnings; my $hi = "First hi"; print "$hi\n"; { my $hi = "Second hi"; print "$hi\n"; } print "$hi\n"; If I run this script, I get this output, and noticeably no warnings: First hi Second hi First hi If I remove the curly braces around the second $hi variable so that is in the same scope as the first $hi variable, I get this warning: "my" variable $hi masks earlier declaration in same scope at hi.pl However, I want this warning even when the variable is not in the same scope. I want the warning every time a variable name is shadowing another. How can I enable this warning? Is there a Perl Critic policy that I can enable that will warn me about this? A: Did you try this: Perl::Critic::Policy::Variables::ProhibitReusedNames;
{ "language": "en", "url": "https://stackoverflow.com/questions/25304592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: WPF Datagrid does not fill the entire height and width when maximizing window My DataGrid is not taking the whole space when I maximize the window in my WPF application. This is how I created the layout: <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <Grid Grid.Row="0" Grid.Column="0" Width="265"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="200" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <Label Grid.Row="0" Grid.Column="0" Content="Date From:" /> <Label Grid.Row="1" Grid.Column="0" Content="Date To:" /> <DatePicker Grid.Column="1" Grid.Row="0" Margin="3" x:Name="DateFrom" /> <DatePicker Grid.Column="1" Grid.Row="1" Margin="3" x:Name="DateTo" /> <Button Grid.Column="1" Grid.Row="2" HorizontalAlignment="Right" MinWidth="80" Margin="3" Content="Send" Click="PopulateGrid" x:Name="BtnPopulateGrid"/> </Grid> <StackPanel Grid.Row="0" Grid.Column="1"> <DataGrid Width="Auto" x:Name="Grid" Height="553" Padding="10 0 0 0" VerticalScrollBarVisibility="Visible" Margin="10,0,-707,0" /> </StackPanel> </Grid> and this is how it looks like on regular size: and this is how it looks like when window is max: What can I try next? I am new to WPF. A: <Grid> <Grid.RowDefinitions> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Grid Grid.Row="0" Grid.Column="0"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="200" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <Label Grid.Row="0" Grid.Column="0" Content="Date From:" /> <Label Grid.Row="1" Grid.Column="0" Content="Date To:" /> <DatePicker Grid.Column="1" Grid.Row="0" Margin="3" x:Name="DateFrom" /> <DatePicker Grid.Column="1" Grid.Row="1" Margin="3" x:Name="DateTo" /> <Button Grid.Column="1" Grid.Row="2" HorizontalAlignment="Right" MinWidth="80" Margin="3" Content="Send" Click="PopulateGrid" x:Name="BtnPopulateGrid"/> </Grid> <Grid Grid.Row="0" Grid.Column="1"> <DataGrid x:Name="Grid" Padding="10 0 0 0" VerticalScrollBarVisibility="Visible" /> </Grid> </Grid> Firstly if you wanna make your datagrid fill a container automatically, you need to use Grid, not StackPanel also your datagrid sizes need to be set auto. Edit: As @Erjon said : You don't have to use a container when you have a single DataGrid.But if you have more components with your DataGrid, Grid will be a better container choice instead of StackPanel. Your main GridDefination sizes were set as Auto, that was wrong.You need to work with "*" if you want a resposive design.Auto means that "Set this control's size with its children". A: Try adding in the datagrid ColumnWidth="*" It will expand all columns to avaiable space and the datagrid will fill it's parent The second ColumnDefinition of the first grid should be <ColumnDefinition Width="*" /> And as @Zacos said in my answers comment you have to remove Width
{ "language": "en", "url": "https://stackoverflow.com/questions/56852098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using rails3-jquery-autocomplete from a nested form I receive this error when I type an existing topic into the topic field of my form: Started GET "/posts/autocomplete_topic_name?term=test" for 127.0.0.1 at 2011-05-21 10:51:19 -0700 Processing by PostsController#show as JSON Parameters: {"term"=>"test", "id"=>"autocomplete_topic_name"} Post Load (0.2ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = 0 LIMIT 1 Completed in 28ms ActiveRecord::RecordNotFound (Couldn't find Post with ID=autocomplete_topic_name): app/controllers/posts_controller.rb:9:in `show' Rendered /home/dude/.rvm/gems/ruby-1.9.2-p180/gems/actionpack-3.0.6/lib/action_dispatch/middleware/templates/rescues/_trace.erb (2.5ms) Rendered /home/dude/.rvm/gems/ruby-1.9.2-p180/gems/actionpack-3.0.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (4.2ms) Rendered /home/dude/.rvm/gems/ruby-1.9.2-p180/gems/actionpack-3.0.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (14.2ms) The topics "test" and "testing" exist. models: class Topic < ActiveRecord::Base has_many :posts validates :name, :presence => true, attr_accessible :name, :post_id end class Post < ActiveRecord::Base belongs_to :topic accepts_nested_attributes_for :topic attr_accessible :name, :title, :content, :topic, :topic_attributes end view: /posts/new renders only this form: (uses simple_form) <%= simple_form_for :post, :url => { :controller => :posts, :action => "create" } do |f| %> <h1>Create a Post</h1> <%= f.input :name, :label => false, :placeholder => "Name (optional)", :required => false %> <%= f.input :title, :label => false, :placeholder => "Title" %> <%= f.input :content, :label => false, :placeholder => "Content", :as => :text %> <%= f.simple_fields_for :topic do |topic_form| %> <%= topic_form.input :name, :label => false, :placeholder => "Topic", :url => autocomplete_topic_name_path, :as => :autocomplete %> <% end %> <%= raw recaptcha_tags -%> <%= f.button :submit, "Post" %> <% end %> controller: class PostsController < ApplicationController autocomplete :topic, :name, :full => true respond_to :html, :js, :xml def new @post = Post.new end def create topic_name = params[:post].delete(:topic) @topic = Topic.find_or_create_by_name(topic_name) @post = Post.new(params[:post]) @post.topic = @topic respond_to do |format| if verify_recaptcha(:model => @post) && @post.save format.html { redirect_to(@post, :notice => 'Post was successfully created.') } else flash.delete(:recaptcha_error) flash.now[:error] = "Incorrect word verification. Are you sure you\'re human?" format.html { render :action => "new" } end end end end Line 9 of the Posts controller is: @post = Post.find(params[:id]) in the posts#show routes.rb: MyApp::Application.routes.draw do root :to => "posts#index" resources :topics resources :posts resources :comments match "posts/autocomplete_topic_name", :as => "autocomplete_topic_name" end Here's my gemfile: gem 'rails', '3.0.6' gem 'sqlite3' gem 'ancestry' gem 'jquery-rails', '>= 1.0.3' gem 'kaminari' gem 'nifty-generators' gem 'rdiscount' gem 'rails3-jquery-autocomplete' gem 'recaptcha', :require => 'recaptcha/rails' gem 'simple_form' and schema: create_table "posts", :force => true do |t| t.string "name" t.string "title" t.text "content" t.integer "topic_id" t.datetime "created_at" t.datetime "updated_at" end create_table "topics", :force => true do |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" end Thanks for taking a look. A: Within your routes file, try moving the "match 'posts/...'" line before "resources :posts".
{ "language": "en", "url": "https://stackoverflow.com/questions/6083718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C# WinFormApp DataGridView cannot show object inside of List UPD: I have found this article: http://www.developer-corner.com/blog/2007/07/19/datagridview-how-to-bind-nested-objects/ , but it is pretty old, posted in 2007. I have C# win forms app and I want to show list of items in datagridView: here is the List: ` public static List<Item> ItemsList { get; set; } = new List<Item>() { new Item() { Id = 1, ItemName = "Ice Tea", ItemCategory = new Category(){ Name = "Drinks" }, Price = 4000.00, },...}` as you can see I have another object ItemCategory inside Item. Here is the code to connect to dataGrid: dataGridAllProducts.DataSource = Item.ItemsList; The problem is that I cannot get the Name from ItemsList and show in rows, here is what it shows in output: As you can see instead of Drinks it shows another thing. Also i tried to loop through my list using foreach and rows to datagrid but it throwed some errors . A: On class Category add this code: public override string ToString(){ return this.Name; } When you call the object on need a string, the object Category show Name property. A: The column binding for the data grid view might not be right. Please try the following in the design view: 1. Right click on your data grid view and select "Edit Columns" 2. Select the column for which the data is not coming right. 3. In the "DataPropertyName" under "Data" mention "Name" i.e. the property name of your Item class.
{ "language": "en", "url": "https://stackoverflow.com/questions/49019913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Building a partial state inside an action to update a REST API I have a bound action: updateAge(age) Part of my state is this: //user data user { name: 'foo', age: 10 } In my action creator, can I do something like this? export const updateAge = (age) => (dispatch, getState) => { let currentState = { ...getState().user, age } dispatch(updateUser(currentState)) //updates API } This would save work on my back end as I would just have one route handling all user updates. router.post('/user'....) As long as I make sure only one fetch/post happens at any given time, is this a good pattern? What are the pros and cons?
{ "language": "en", "url": "https://stackoverflow.com/questions/53348033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Repair Presentation Error with chart.replace_data() I used the chart.replace_data() to replace the old category labels with the new ones. When I opened the output presentation, I saw the message to repair the presentation and when I clicked the repair button, all the data of the presentation are gone. Here's my code: from pptx.enum.chart import XL_CHART_TYPE from pptx import Presentation #from pptx.chart.data import CategoryChartData from pptx.chart.data import ChartData from google_trans_new import google_translator trans=google_translator() proj1 = Presentation("C:/Users/naych/Documents/chart.pptx") rev_lbl=[] for slide in proj1.slides: for shape in slide.shapes: if shape.has_chart: chart=shape.chart if chart.chart_title.has_text_frame: chart_title_str=chart.chart_title.text_frame.text rev=trans.translate(chart_title_str,lang_tgt='ja') chart.chart_title.text_frame.text=rev print(shape.name) chart_data=ChartData() for category in chart.plots[0].categories: cat_lbl=category.label rev_lbl.append(trans.translate(cat_lbl,lang_tgt='ja')) chart_data.categories=rev_lbl chart.replace_data(chart_data) proj1.save('chart_lang.pptx') I am very happy if you help me to fix it. Please! Thank you.
{ "language": "en", "url": "https://stackoverflow.com/questions/65740835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Server responding with response code 400 when making http head request using httpurlconnection To a certain website , i am making HTTP head request to get header data using java. I have used the following code to do that. String url2 = "https://pagalworld.com.se/siteuploads/files/sfd14/6934/Har Har Shambhu Ringtone_320(PagalWorld.com.se).mp3"; String req_method = "HEAD"; HttpsURLConnection conn = null; try { System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); URL UrlConnection = new URL(url2); conn = (HttpsURLConnection) UrlConnection.openConnection(); String host = UrlConnection.getHost().toString()+":80"; conn.setRequestMethod(req_method); conn.setRequestProperty("Host", host); conn.setRequestProperty("Accept", "*/*"); conn.setRequestProperty("Connection","keep-alive"); conn.setRequestProperty(DownloadApiConfig.USER_AGENT_REQUEST_HEADER, DownloadApiConfig.USER_AGENT_REQUEST_HEADER_VALUE); System.out.println("Host:Port = "+host); Map<String,List<String>> data = conn.getRequestProperties(); System.out.println("Connection code : "+conn.getResponseCode()); System.out.println("Connection Msg : "+conn.getResponseMessage()); for(String key:data.keySet()){ System.out.println(key + " " + data.get(key)); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ conn.disconnect(); } Now the problem is , Server is responding with response code 400 (Bad request). But when i am making the same request from postman with same request headers, it gives response code 200 (Ok). http head request using Postman Another thing is, if i am making the request with same request headers as before using okhttp client library then also it's responding with response code 200. Now what's wrong with my code ? A: I couldn't found any major issue on your code. I've tried to run your code inside one of my Android project. To avoid NetworkOnMainThreadException I've run the code snippet inside a thread. Then run it and found the expected response header in the log. Possible Solutions (What can you do now?) * *Try run my callApi() method inside your project. *Change your url to https://pagalworld.com.se/siteuploads/files/sfd14/6934/Har%20Har%20Shambhu%20Ringtone_320(PagalWorld.com.se).mp3 (replaced SPACE with %20). There is a chance for BAD request with white space URL. Here is the significant output I/System.out: ConnHeadRes: null HTTP/1.1 200 OK I/System.out: ConnHeadRes: Accept-Ranges bytes I/System.out: ConnHeadRes: Age 693 I/System.out: ConnHeadRes: CF-Cache-Status HIT I/System.out: ConnHeadRes: CF-RAY 73f0ccbd1a5169b1-DAC I/System.out: ConnHeadRes: Connection keep-alive I/System.out: ConnHeadRes: content-disposition attachment I/System.out: ConnHeadRes: Content-Length 1221768 I/System.out: ConnHeadRes: Content-Type application/octet-stream I/System.out: ConnHeadRes: Date Tue, 23 Aug 2022 03:35:42 GMT I/System.out: ConnHeadRes: Expect-CT max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" I/System.out: ConnHeadRes: last-modified Thu, 11 Aug 2022 14:41:49 GMT I/System.out: ConnHeadRes: NEL {"success_fraction":0,"report_to":"cf-nel","max_age":604800} I/System.out: ConnHeadRes: Report-To {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=nywwKM746VO8KiwrIJAIq6hoJ1D8eJphddRHtpP%2BkXxWPQCJayYi23um4V7mlUXd4kdWOXN%2FrXrTN6NA7sZWa%2BzU4L6tCx2v28VAkH51TPNfDVbeHGTHgwY8PCuulIdN3ek%2FloEn"}],"group":"cf-nel","max_age":604800} I/System.out: ConnHeadRes: Server cloudflare I/System.out: ConnHeadRes: Strict-Transport-Security max-age=15552000; includeSubDomains; preload I/System.out: ConnHeadRes: Vary Accept-Encoding I/System.out: ConnHeadRes: X-Android-Received-Millis 1661225741490 I/System.out: ConnHeadRes: X-Android-Response-Source NETWORK 200 I/System.out: ConnHeadRes: X-Android-Selected-Protocol http/1.1 I/System.out: ConnHeadRes: X-Android-Sent-Millis 1661225741442 I/System.out: ConnHeadRes: x-content-type-options nosniff I/System.out: ConnHeadRes: x-nginx-upstream-cache-status MISS What I've changed in the code? * *Run the code inside a thread *Update USER_AGENT_REQUEST_HEADER field and value. *Get response headers in a Map object. *Iterate the Map object and print key-value in log. Here is the code sample: void callApi() { Thread thread = new Thread(() -> { try { String url2 = "https://pagalworld.com.se/siteuploads/files/sfd14/6934/Har Har Shambhu Ringtone_320(PagalWorld.com.se).mp3"; String req_method = "HEAD"; HttpsURLConnection conn = null; try { System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); URL UrlConnection = new URL(url2); conn = (HttpsURLConnection) UrlConnection.openConnection(); String host = UrlConnection.getHost() + ":80"; conn.setRequestMethod(req_method); conn.setRequestProperty("Host", host); conn.setRequestProperty("Accept", "*/*"); conn.setRequestProperty("Connection", "keep-alive"); conn.setRequestProperty("user-agent", "android"); System.out.println("Host:Port = " + host); Map<String, List<String>> data = conn.getRequestProperties(); System.out.println("Connection code : " + conn.getResponseCode()); System.out.println("Connection Msg : " + conn.getResponseMessage()); for (String key : data.keySet()) { System.out.println(key + " " + data.get(key)); } Map<String, List<String>> responseHeader = conn.getHeaderFields(); for (Map.Entry<String, List<String>> entry : responseHeader.entrySet()) { for (String value: entry.getValue()) { System.out.println("ConnHeadRes: " + entry.getKey() + " " + value); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { conn.disconnect(); } } catch (Exception e) { e.printStackTrace(); } }); thread.start(); } So, as far I understand I can say, there is no issue in your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/73449083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Looking up a value in a column for most matching values in two other columns Into a pandas dataframe I retrieve via an API option chain data for a stock. In the column 'expiration' you can see that in this test case I have three option series with expiries at respectively: 2019-08-15, 2019-09-15 and 2019-10-15. What I want to achieve is: * *for each option series (3 in this test case) *lookup the 'strike' price that is closest to 'undPrice' (=price of the underlying stock) *for the 'strike' price that is closest to 'undPrice' look up the corresponding value in 'IV_model' (=implied volatility) *fill that value in the column 'desired_outcome' for all the option combinations of that expiration series (so, in this test case three times block with identical values) *So, there are basically three look-ups within one series of data. This is the code for a test case that comes close to my live environment: import pandas as pd undPrice = 202 df = pd.DataFrame(columns=['expiration', 'strike', 'undPrice', 'IV_model', 'desired_outcome']) df['expiration'] = ['2019-08-15', '2019-08-15', '2019-08-15', '2019-08-15', '2019-08-15', '2019-08-15', '2019-08-15', '2019-08-15', '2019-09-15', '2019-09-15', '2019-09-15', '2019-09-15', '2019-09-15', '2019-09-15', '2019-09-15', '2019-09-15', '2019-09-15', '2019-09-15', '2019-10-15', '2019-10-15', '2019-10-15', '2019-10-15', '2019-10-15', '2019-10-15', '2019-10-15', '2019-10-15', '2019-10-15', '2019-10-15'] df['expiration'] = df['expiration'].apply(lambda x: pd.to_datetime(str(x), utc=True,format='%Y-%m-%d')) df['strike'] = [170, 175, 180, 185, 190, 195, 200, 205, 165, 170, 175, 180, 185, 190, 195, 200, 205, 210, 160, 165, 170, 175, 180, 185, 190, 195, 200, 205] df['undPrice'] = [undPrice, undPrice, undPrice, undPrice, undPrice, undPrice, undPrice, undPrice, undPrice, undPrice, undPrice, undPrice, undPrice, undPrice, undPrice, undPrice, undPrice, undPrice, undPrice, undPrice, undPrice, undPrice, undPrice, undPrice, undPrice, undPrice, undPrice, undPrice] df['IV_model'] = [0.28, 0.27, 0.26, 0.25, 0.24, 0.23, 0.22, 0.21, 0.35, 0.34, 0.33, 0.32, 0.31, 0.30, 0.29, 0.28, 0.27, 0.26, 0.42, 0.41, 0.40, 0.39, 0.38, 0.37, 0.36, 0.35, 0.34, 0.33] df['IV_model'] = df['IV_model'].map('{:.2%}'.format) df['desired_outcome'] = [0.22, 0.22, 0.22, 0.22, 0.22, 0.22, 0.22, 0.22, 0.28, 0.28, 0.28, 0.28, 0.28, 0.28, 0.28, 0.28, 0.28, 0.28, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34, 0.34] df['desired_outcome'] = df['desired_outcome'].map('{:.2%}'.format) print(df) And this would the (desired) outcome (obviously 'desired_outcome' filled in manually): expiration strike undPrice IV_model desired_outcome 0 2019-08-15 00:00:00+00:00 170 202 28.00% 22.00% 1 2019-08-15 00:00:00+00:00 175 202 27.00% 22.00% 2 2019-08-15 00:00:00+00:00 180 202 26.00% 22.00% 3 2019-08-15 00:00:00+00:00 185 202 25.00% 22.00% 4 2019-08-15 00:00:00+00:00 190 202 24.00% 22.00% 5 2019-08-15 00:00:00+00:00 195 202 23.00% 22.00% 6 2019-08-15 00:00:00+00:00 200 202 22.00% 22.00% 7 2019-08-15 00:00:00+00:00 205 202 21.00% 22.00% 8 2019-09-15 00:00:00+00:00 165 202 35.00% 28.00% 9 2019-09-15 00:00:00+00:00 170 202 34.00% 28.00% 10 2019-09-15 00:00:00+00:00 175 202 33.00% 28.00% 11 2019-09-15 00:00:00+00:00 180 202 32.00% 28.00% 12 2019-09-15 00:00:00+00:00 185 202 31.00% 28.00% 13 2019-09-15 00:00:00+00:00 190 202 30.00% 28.00% 14 2019-09-15 00:00:00+00:00 195 202 29.00% 28.00% 15 2019-09-15 00:00:00+00:00 200 202 28.00% 28.00% 16 2019-09-15 00:00:00+00:00 205 202 27.00% 28.00% 17 2019-09-15 00:00:00+00:00 210 202 26.00% 28.00% 18 2019-10-15 00:00:00+00:00 160 202 42.00% 34.00% 19 2019-10-15 00:00:00+00:00 165 202 41.00% 34.00% 20 2019-10-15 00:00:00+00:00 170 202 40.00% 34.00% 21 2019-10-15 00:00:00+00:00 175 202 39.00% 34.00% 22 2019-10-15 00:00:00+00:00 180 202 38.00% 34.00% 23 2019-10-15 00:00:00+00:00 185 202 37.00% 34.00% 24 2019-10-15 00:00:00+00:00 190 202 36.00% 34.00% 25 2019-10-15 00:00:00+00:00 195 202 35.00% 34.00% 26 2019-10-15 00:00:00+00:00 200 202 34.00% 34.00% 27 2019-10-15 00:00:00+00:00 205 202 33.00% 34.00% I am a relative beginner in Python programming, I came a long way already but this is out of my league. I hope that somebody can help me out with this one. A: Here's one way: Create a dict of the expiration to IV_model by finding the min distance between undPrice and strike. desiredOutcomeMap = df.groupby('expiration').apply(lambda x: df.loc[abs(x['undPrice']-x['strike']).idxmin(), 'IV_model']).to_dict() Then map it to the original df. df['desired_outcome'] = df['expiration'].map(desiredOutcomeMap)
{ "language": "en", "url": "https://stackoverflow.com/questions/57115144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: docker stats not shows ZERO Net I/O for the containers that are streaming video I have created a Kubernetes Cluster of Physical Machine and VMs. The containers deployed are displaying the values for Memory and CPU but Network I/O values are ZERO/ZERO although I am streaming video from the containers. There are some PAUSE containers created against each container on POD, they are also showing 0/0 Net I/O. I tried to get the data through cadvisor but it also doesnt show the data for network I/O for the running containers. CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS ce0eebabe881 k8s_video_hello-world-5c78949d4d-mpzqh_default_5d0b8e18-1419-4c5b-9aef-25627fcf2e0c_0 0.02% 19.82MiB / 15.59GiB 0.12% 0B / 0B 0B / 0B 1 0a47b078ba26 k8s_video_hello-world-5c78949d4d-xfvcz_default_b8ec6c0a-ffe3-4f77-ae97-e0a6b162e078_0 0.02% 20.35MiB / 15.59GiB 0.13% 0B / 0B 0B / 0B 1 d68827bc3a8e k8s_video_hello-world-5c78949d4d-h95kq_default_9086a833-e3e1-410e-98bb-8db11314bf65_0 0.03% 19.32MiB / 15.59GiB 0.12% 0B / 0B 0B / 0B 1 80130bc836ac k8s_video_hello-world-5c78949d4d-hc7hx_default_77dcf557-8450-47c3-91d0-52369c7c37ac_0 0.02% 19.6MiB / 15.59GiB 0.12% 0B / 0B 0B / 0B 1 37392f5c807b k8s_POD_hello-world-5c78949d4d-mpzqh_default_5d0b8e18-1419-4c5b-9aef-25627fcf2e0c_0 0.00% 1.281MiB / 15.59GiB 0.01% 0B / 0B 0B / 0B 1 1736a8064c72 k8s_POD_hello-world-5c78949d4d-h95kq_default_9086a833-e3e1-410e-98bb-8db11314bf65_0 0.00% 1.508MiB / 15.59GiB 0.01% 0B / 0B 0B / 0B 1 aef03f775aeb k8s_POD_hello-world-5c78949d4d-xfvcz_default_b8ec6c0a-ffe3-4f77-ae97-e0a6b162e078_0 0.00% 944KiB / 15.59GiB 0.01% 0B / 0B 0B / 0B 1 a89c5c6399b1 k8s_POD_hello-world-5c78949d4d-hc7hx_default_77dcf557-8450-47c3-91d0-52369c7c37ac_0 0.00% 1.379MiB / 15.59GiB 0.01% 0B / 0B 0B / 0B 1 When I ran Docker stats for containers deployed on swarm, the Docker Stats and cadvisor was working fine. A: If package ifconfig in present in your image they you can always do kubectl exec <pod_name> ifconfig output might looks like the following: eth0 Link encap:Ethernet HWaddr DA:6E:42:4F:87:EE inet addr:10.8.1.9 Bcast:0.0.0.0 Mask:255.255.255.0 inet6 addr: fe80::d86e:42ff:fe4f:87ee/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1460 Metric:1 RX packets:1282 errors:0 dropped:0 overruns:0 frame:0 TX packets:1296 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:122059 (119.1 KiB) TX bytes:122960 (120.0 KiB) lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:65536 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) Now on explain why docker stats won't work. Kubernetes doesn't use Docker networking, it uses CNI - Container Network Interface. A CNI plugin is responsible for inserting a network interface into the container network namespace (e.g. one end of a veth pair) and making any necessary changes on the host (e.g. attaching the other end of the veth into a bridge). It should then assign the IP to the interface and setup the routes consistent with the IP Address Management section by invoking appropriate IPAM plugin. I strongly advice you to read @Ian Lewis blog What are Kubernetes Pods Anyway? If you would like to know more about networking I recommend great read of Kubernetes Networking: Behind the scenes by @Nicolas Leiva. I hope this will sheds some light on the subject.
{ "language": "en", "url": "https://stackoverflow.com/questions/57205251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Automatically unpack a tuple in a function call in C++ I am using range-v3 and sometimes I used ranges::views::enumerate to have the id of the value that I'm iterating on. enumerate view returns a tuple containing the id and the value, so I would like to know if its possible to unpack directly that tuple. This would be an example: samplers | ranges::views::enumerate | ranges::views::transform([](const auto samplerId, const auto &jSampler){...} | ranges::to_vector;
{ "language": "en", "url": "https://stackoverflow.com/questions/65854263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to position a div scrollbar on the left hand side? Is it possible to specify a position (left or right hand side) for the placement of a vertical scrollbar on a div? For example look at this page which explains how to use the overflow attribute. Is there some way of placing that scrollbar on the left hand side of the scrollable area? A: .list_container { direction: rtl; overflow:auto; height: 50px; width: 50px; } .item_direction { direction:ltr; } <div class="list_container"> <div class="item_direction">1</div> <div class="item_direction">2</div> <div class="item_direction">3</div> <div class="item_direction">4</div> <div class="item_direction">5</div> <div class="item_direction">6</div> <div class="item_direction">7</div> <div class="item_direction">8</div> <div class="item_direction">9</div> <div class="item_direction">10</div> <div class="item_direction">11</div> <div class="item_direction">12</div> </div> Working Example: JSFiddle or Cut and paste solution that works for all major browsers (Even Safari) Any height or width will work <style> .list_container { direction: rtl; overflow:auto; height: 50px; width: 50px; } .item_direction { direction:ltr; } </style> <div class="list_container"> <div class="item_direction">1</div> <div class="item_direction">2</div> <div class="item_direction">3</div> <div class="item_direction">4</div> <div class="item_direction">5</div> <div class="item_direction">6</div> <div class="item_direction">7</div> <div class="item_direction">8</div> <div class="item_direction">9</div> <div class="item_direction">10</div> <div class="item_direction">11</div> <div class="item_direction">12</div> </div> Optionally add class="item_direction to each item to change the direction of the text flow back, while preserving the container direction. A: No, you can't change scrollbars placement without any additional issues. You can change text-direction to right-to-left ( rtl ), but it also change text position inside block. This code can helps you, but I not sure it works in all browsers and OS. <element style="direction: rtl; text-align: left;" /> A: Kind of an old question, but I thought I should throw in a method which wasn't widely available when this question was asked. You can reverse the side of the scrollbar in modern browsers using transform: scaleX(-1) on a parent <div>, then apply the same transform to reverse a child, "sleeve" element. HTML <div class="parent"> <div class="sleeve"> <!-- content --> </div> </div> CSS .parent { overflow: auto; transform: scaleX(-1); //Reflects the parent horizontally } .sleeve { transform: scaleX(-1); //Flips the child back to normal } Note: You may need to use an -ms-transform or -webkit-transform prefix for browsers as old as IE 9. Check CanIUse and click "show all" to see older browser requirements. A: I have the same problem. but when i add direction: rtl; in tabs and accordion combo but it crashes my structure. The way to do it is add div with direction: rtl; as parent element, and for child div set direction: ltr;. I use this first https://api.jquery.com/wrap/ $( ".your selector of child element" ).wrap( "<div class='scroll'></div>" ); then just simply work with css :) In children div add to css .your_class { direction: ltr; } And to parent div added by jQuery with class .scroll .scroll { unicode-bidi:bidi-override; direction: rtl; overflow: scroll; overflow-x: hidden!important; } Works prefect for me http://jsfiddle.net/jw3jsz08/1/ A: You could try direction:rtl; in your css. Then reset the text direction in the inner div #scroll{ direction:rtl; overflow:auto; height:50px; width:50px;} #scroll div{ direction:ltr; } Untested. A: Here is what I have done to make the right scroll bar work. The only thing needed to be considered is when using 'direction: rtl' and whole table also need to be changed. Hopefully this gives you an idea how to do it. Example: <table dir='rtl'><tr><td>Display Last</td><td>Display Second</td><td>Display First</td></table> Check this: JSFiddle A: There is a dedicated npm package for it. css-scrollbar-side
{ "language": "en", "url": "https://stackoverflow.com/questions/7347532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "115" }
Q: Remove all rows from the table at once with completion in Swift In my app I want to be able to remove all the rows of a particular table at once and reload the table on a completion block call. I know how to remove a single row: override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { switch editingStyle { case .Delete: // remove the deleted item from the model let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate let context:NSManagedObjectContext = appDel.managedObjectContext! context.deleteObject(myData[indexPath.row] as NSManagedObject) myData.removeAtIndex(indexPath.row) context.save(nil) //tableView.reloadData() // remove the deleted item from the `UITableView` self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) default: return } } I also know that I can fetch all the rows and delete them one by one in a loop, but I'm struggling on how to add a completion block to it, so I can redraw the table after deletion is done. Any kind of help is highly appreciated. A: Basically all you need to do is do what you said you want to do in a completion block - just remove all the items from the datasource and update the table. The UITableView datasource delegate methods will do the rest for you and empty the tableView. A: Just use deleteRowsAtIndexPaths:withRowAnimation: method and apply code from a following question — How to detect that animation has ended on UITableView beginUpdates/endUpdates? It will give you completion block functionality that you are looking, so you will be able to call reloadData in it. For Swift it will look as following: CATransaction.begin() CATransaction.setCompletionBlock { //Reload data here } tableView.beginUpdates() //Remove cells here tableView.endUpdates() CATransaction.commit() A: Some sample code below. The usual way would be to perform a big delete or add operation on a background thread and then use a notification to trigger the merge on the main thread. So the code below assumes the following: * *You have a main ManagedObjectContext which is used by the FetchedResultsController in your TableView *You have a helper function to launch the delete or load methods on background threads *You create background managedObjectContexts and register for ContextDidSave notifications which you then use to merge the changes into the main context Helper function for calling load or delete. - (void)deleteDataInBackground { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) { [self deleteData]; }); } Load function /* Loads the required seed data */ // Usually called on a background thread and therefor we need to process the DidSave notification // to merge the changed with the main context so the UI gets updated func loadData() { //FLOG(" called"); let bgContext:NSManagedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.ConfinementConcurrencyType) // Register for saves in order to merge any data from background threads NSNotificationCenter.defaultCenter().addObserver(self, selector:"storesDidSave:", name: NSManagedObjectContextDidSaveNotification, object:bgContext) while (persistentStoreCoordinator == nil) { //FLOG(@" persistentStoreCoordinator = nil, waiting 5 seconds to try again..."); sleep(5); } bgContext.persistentStoreCoordinator = persistentStoreCoordinator insertStatusCode(bgContext, number: 0, name: "Not started") insertStatusCode(bgContext, number: 1, name: "Started on track") insertStatusCode(bgContext, number: 2, name: "Behind schedule") insertStatusCode(bgContext, number: 3, name: "Completed") insertStatusCode(bgContext, number: 4, name: "Completed behind schedule") insertStatusCode(bgContext, number: 5, name: "On hold or cancelled") bgContext.processPendingChanges() do { try bgContext.save() //FLOG(" Seed data loaded") } catch { //FLOG(" Unresolved error \(error), \(error?.userInfo)") } } Code to insert new records func insertStatusCode(moc:NSManagedObjectContext, number:Int, name:String) { //FLOG(" called") if let newManagedObject:NSManagedObject = NSEntityDescription.insertNewObjectForEntityForName("StatusCode", inManagedObjectContext:moc) { newManagedObject.setValue(number, forKey:"number") newManagedObject.setValue(name, forKey:"name") } } Code to process the notifications and merge the changes into the main context // NB - this may be called from a background thread so make sure we run on the main thread !! // This is when transaction logs are loaded func storesDidSave(notification: NSNotification!) { // Ignore any notifications from the main thread because we only need to merge data // loaded from other threads. if (NSThread.isMainThread()) { //FLOG(" main thread saved context") return } NSOperationQueue.mainQueue().addOperationWithBlock { //FLOG("storesDidSave ") // Set this so that after the timer goes off we perform a save // - without this the deletes don't appear to trigger the fetchedResultsController delegate methods ! self.import_or_save = true self.createTimer() // Timer to prevent this happening too often! if let moc = self.managedObjectContext { moc.mergeChangesFromContextDidSaveNotification(notification) } } } And here is a Obj-C delete function, note that there are some checks to make sure the objects have not been deleted by another thread... - (void)deleteData { FLOG(@"deleteData called"); _deleteJobCount++; [self postJobStartedNotification]; FLOG(@" waiting 5 seconds..."); sleep(5); [self showBackgroundTaskActive]; NSManagedObjectContext *bgContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]; // Register for saves in order to merge any data from background threads [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(storesDidSave:) name: NSManagedObjectContextDidSaveNotification object:bgContext]; while (self.persistentStoreCoordinator == nil) { FLOG(@" persistentStoreCoordinator = nil, waiting 5 seconds to try again..."); sleep(5); } bgContext.persistentStoreCoordinator = [self persistentStoreCoordinator]; FLOG(@" fetching data..."); NSArray *companies = [self getData:@"Company" sortField:@"name" predicate:nil managedObjectContext:bgContext]; NSUInteger count = companies.count; if (count>2) { for (int i = 0; i<3; i++) { NSManagedObject *object = [companies objectAtIndex:i]; // Must wrap this incase another thread deleted it already @try { if ([object isDeleted]) { FLOG(@" object has been deleted"); } else { FLOG(@" deleting %@", [object valueForKey:@"name"]); [bgContext deleteObject:object]; [bgContext processPendingChanges]; NSError *error = nil; if (![bgContext save:&error]) { FLOG(@" Unresolved error %@, %@", error, [error userInfo]); } } } @catch (NSException *exception) { FLOG(@" error deleting object"); FLOG(@" exception is %@", exception); } FLOG(@" waiting 5 seconds..."); sleep(0.01); } } [[NSNotificationCenter defaultCenter] removeObserver:self name: NSManagedObjectContextDidSaveNotification object:bgContext]; /* dispatch_async(dispatch_get_main_queue(),^(void){ [[NSNotificationCenter defaultCenter] removeObserver:self name: NSManagedObjectContextDidSaveNotification object:nil]; }); */ FLOG(@" delete ended..."); [self showBackgroundTaskInactive]; _deleteJobCount--; [self postJobDoneNotification]; } If you have large batched take a look at the Core Data batch functions.
{ "language": "en", "url": "https://stackoverflow.com/questions/31122861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cython function with variable sized matrix input I am trying to convert part of a native python function to cython to improve the compute time. I would like to write a cython function just for the loop component that is taking up the time (as ipython lprun kindly told me). However this function takes in variably sized matrices .. and I can't see how to bring that across easily to statically typed cython. for index1 in range(0,num_products): for index2 in range(0,num_products): cond_prob = (data[index1] * data[index2]).sum() / max(col_sums[index1], col_sums[index2]) prox[index1][index2] = cond_prob This issue is that num_products changes year to year, so the matrix (data) size is variable. What is the best strategy here? * *Should I write two C functions. One to create a matrix of a certain dimension using memalloc, and then One to do the loops over the created matrix? *Is there some fancy cython/numpy wizardry to help in this scenario? Can I write a C function that takes in a variably sized Numpy Array in memory and pass the size? A: Cython code is (strategically) statically typed, but that doesn't mean that arrays must have a fixed size. In straight C passing a multidimensional array to a function can be a little awkward maybe, but in Cython you should be able to do something like the following: Note I took the function and variable names from your follow-up question. import numpy as np cimport numpy as np cimport cython @cython.boundscheck(False) @cython.cdivision(True) def cooccurance_probability_cy(double[:,:] X): cdef int P, i, j, k P = X.shape[0] cdef double item cdef double [:] CS = np.sum(X, axis=1) cdef double [:,:] D = np.empty((P, P), dtype=np.float) for i in range(P): for j in range(P): item = 0 for k in range(P): item += X[i,k] * X[j,k] D[i,j] = item / max(CS[i], CS[j]) return D On the other hand, using just Numpy should also be quite fast for this problem, if you use the right functions and some broadcasting. In fact, as the calculation complexity is dominated by the matrix multiplication, I found the following is much faster than the Cython code above (np.inner uses a highly optimized BLAS routine): def new(X): CS = np.sum(X, axis=1, keepdims=True) D = np.inner(X,X) / np.maximum(CS, CS.T) return D A: Have you tried getting rid of the for loops in numpy? for the first part of your equation you could for example try: (data[ np.newaxis,:] * data[:,np.newaxis]).sum(2) if memory is an issue you can also use the np.einsum() function. For the second part one could probably also cook up a numpy expression (bit more difficult) if you've not already tried that.
{ "language": "en", "url": "https://stackoverflow.com/questions/22779437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is a command equivalent to DateTime? I learned shell scripting for a little while and decided to recreate this question's accepted answer, though I can't really find how a DateTime equivalent would be in it. How can I get a DateTime command? (In relation to Date time in Linux bash) A: You can get the date by passing the date argument when declaring a variable: var=$(date '+%d/%m/%Y %H:%M:%S'); And as pointed out by @Cyrus, you can also not use date via: printf -v var "%(%d/%m/%Y %H:%M:%S)T\n" -1
{ "language": "en", "url": "https://stackoverflow.com/questions/65468627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to display intellisense's suggestions in the order they are defined? For example i've been created a struct struct man { public int age; public bool sex; public float growth; } And when in code I'm start typing something like this: static void GetSex(man Joe) { int age = Joe. } It gives me variants sorted by name. Like this age growth sex But how can I make visual studio not to sort by name? And give list like this age sex growth Like I wrote it in order i want. A: What you're seeing is the Visual Studio "IntelliSense" feature. You can find settings for it under the "Tools / Options" menu, but there are very few. You can choose what displays in the list, which key(s) selects the highlighted item, and how the first highlighted item is selected, but there's nothing available that would allow you to reorder the items.
{ "language": "en", "url": "https://stackoverflow.com/questions/21626637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Connect SourceTree to new Visual Studio 2017 I have just moved from VS2015 to VS2017 and when I open a file from SourceTree it is opening the file in my VS2015 instance. How do I make it open the files in 2017? I cannot delete VS2015 so that is not an option. A: You don't need to change any settings in Source Tree. Instead, to open it in other editors like VS Code, Visual Studio 2015, Visual Studio 2017/2019/2022, you need to change the default filetype opening setting you wish to open in your operating system. Perform the following steps:
{ "language": "en", "url": "https://stackoverflow.com/questions/43722406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to type hint a list with different types in specific positions I'm trying to type hint a list that contains multiple types in a specific order. Something like: l: list[str, int] = ["text", 10] Where the first element will always be a str and the second always an int. MyPy doesn't accept this as list takes exactly 1 argument. If this were a tuple it would work perfectly well, but I need this to be mutable. If there is a data structure other than a list that would work I'd be open to that. I could probably make a custom class that would behave the way I want, but that seems excessive. Is there a better way to do this?
{ "language": "en", "url": "https://stackoverflow.com/questions/70429758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using EWS to remove room from a meeting I need to remove a room from specific meeting using EWS (SOAP). I have an impersonation user and using it, im manage to get a list of all the meetings in a specific room, but I wan't manage so fur to update the meeting by removing the room from it (make the room available for booking). I tried to remove all attendees from the meeting, it removes the attendees but keeps the room, I tried to remove location - it clears the location field but still keeps the room as meeting attendee. Help would be appreciated, near to give up here :( A: OK, just solved it:) The answer was to impersonate a room account and then simple decline the invitation. hope it will help to someone...
{ "language": "en", "url": "https://stackoverflow.com/questions/41921472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jsp project connection with other project In Eclipse: there is a maven jsp web project(jspP) running ok. In the java resources of this web project (folder: Java Resources --src --local.java.code). I create a java class (caller.java) where I create instances of classes from another project(outP). the project outP is correctly imported in caller.java (import com.java.....) and obviously there are no errors. When I create another main.java (with a main method) class inside the local.java.code and call the caller.java, it executes ok bringing results.. BUT: when I create an instance of the caller.java inside a jsp page, I get an error: Stacktrace:] with root cause java.lang.NoClassDefFoundError: com/java..... obviously the error is referencing the classes inside the outP. Now, I understand this is a run-time error and it could be solved if I insert the jar file of the outP inside the lib folder of jspP (Correct???).. But the question is: Since I am working oh the outP project, I need to "link" it somehow with the jspP... How do I do that "dynamic" linking? A: All the other classes you import from caller.java (from another project outP) should eventually be placed on the WEB-INF/lib You can use eclipse or MAVEN to do that.
{ "language": "en", "url": "https://stackoverflow.com/questions/30439445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mounted docker volume to host directory contains only files from the last container I'm launching multiple linked containers. All containers mount host directory /var/log/tipsi/ to the same called internal directory. The problem I see files in /var/log/tipsi only from the last container: * *tipsi_solr and tipsi_erl has the same files set *tipsi_web container (the last launched container) don't see files above, but only its own files *host directory contains files only from the #2 (tipsi_web) I'm launching container using fig. Here is the used config: solr: build: ../tipsi_solr/ volumes: - /var/log/tipsi:/var/log/tipsi - /home/docker/code/tipsi/solr/collection1/data erl: build: ../tipsi_erl/ volumes: - /var/log/tipsi:/var/log/tipsi web: build: . volumes: - /var/log/tipsi:/var/log/tipsi - /etc/cert:/etc/cert ports: - "443:443" - "80:80" links: - solr:tipsi-solr.local - erl:tipsi-erl.local The interesting thing - lsof shows absent files for tipsi_erl pid (launched on host): prompt:~$ sudo lsof -p 12717 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME beam.smp 12717 root 12w REG 252,0 0 9323763 /var/log/tipsi/stacked_cache_error.log beam.smp 12717 root 13w REG 252,0 739192 9323765 /var/log/tipsi/stacked_cache_debug.log But they aren't accessible with other apps: ls /var/log/tipsi/stacked_cache_debug.log 22:35:29 ls: cannot access /var/log/tipsi/stacked_cache_debug.log: No such file or directory Also, I tried both specifying and removing VOLUME param in Dockerfile for the all containers without any luck. Any ideas why those files aren't shown? A: I believe you're hitting https://github.com/docker/fig/issues/447 If you added VOLUME to the Dockerfile at one point, you keep getting the contents of that volume when you recreate. You should fig rm --force to clear out the old containers, after that it should start working and using the host volumes.
{ "language": "en", "url": "https://stackoverflow.com/questions/27747669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Unable to load Microsoft.Extensions.DependencyInjection.Abstractions 2.2.0 version assembly I'm getting following error when i try to load 2.2.0 version of Microsoft.Extensions.DependencyInjection.Abstractions assembly. My .net core web app is always trying to load 2.1.0 assembly. All assembly references are point to 2.2.0 version. Please find the below load error. Could not load file or assembly 'Microsoft.Extensions.DependencyInjection.Abstractions, Version=2.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)":"Microsoft.Extensions.DependencyInjection.Abstractions, Version=2.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60 CSPROJ File: <Project Sdk="Microsoft.NET.Sdk.Web"> <ItemGroup> <PackageReference Include="Alachisoft.NCache.SDK" Version="4.9.1" /> <PackageReference Include="Alachisoft.NCache.SessionServices" Version="4.9.1" /> <PackageReference Include="Alachisoft.NCache.SessionStateProvider" Version="4.9.1" /> <PackageReference Include="AutoMapper" Version="8.1.0" /> <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="6.1.0" /> <PackageReference Include="EntityFramework" Version="6.2.0" /> <PackageReference Include="log4net" Version="2.0.8" /> <PackageReference Include="Microsoft.AspNet.Mvc" Version="5.2.7" /> <PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Authentication" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.ViewCompilation" Version="2.2.0" PrivateAssets="All" /> <PackageReference Include="Microsoft.AspNetCore.ResponseCaching" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Session" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.2.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.6" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.2.4" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.2.4" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.2.4"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.2.0" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="2.2.0" /> <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="2.2.0" /> <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.3" /> <PackageReference Include="Moment.js" Version="2.24.0" /> <PackageReference Include="Newtonsoft.Json" Version="12.0.2" /> <PackageReference Include="NLog" Version="4.6.3" /> <PackageReference Include="NLog.MailKit" Version="3.0.2" /> <PackageReference Include="NLog.Schema" Version="4.6.3" /> <PackageReference Include="NLog.Web.AspNetCore" Version="4.8.2" /> <PackageReference Include="StackExchange.Redis.Extensions.NetCore" Version="1.0.1" /> <PackageReference Include="System.Net.Http" Version="4.3.4" /> <PackageReference Include="Telerik.UI.for.AspNet.Core" Version="2018.3.1017" /> <PackageReference Include="Telerik.Windows.Documents.Core" Version="2019.2.612" /> <PackageReference Include="Telerik.Windows.Documents.Fixed" Version="2019.2.612" /> <PackageReference Include="Telerik.Windows.Documents.Spreadsheet" Version="2019.2.612" /> <PackageReference Include="Telerik.Windows.Documents.Spreadsheet.FormatProviders.OpenXml" Version="2019.2.612" /> <PackageReference Include="underscore.js" Version="1.8.3" /> <PackageReference Include="WindowsBase" Version="4.6.1055" /> <PackageReference Include="Z.EntityFramework.Plus.EF6" Version="1.8.25" /> </Project>
{ "language": "en", "url": "https://stackoverflow.com/questions/59072009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Security Group and Subnet belong to different networks I am working on deploying IaC to AWS. All is well except for a perplexing issuing I am having with my deployment of EC2 instances through an ASG. When I run Terraform apply I get the following error message: "Security Group sg-xxxxx and Subnet subnet-xxxxx belong to different networks. Launching EC2 instance failed." Terraform is using trying to use a default subnet instead of the subnet I defined to be used with the vpc I created. I am not using an ELB at the moment only using an LC and ASG. Below are the code snippet's. Any insight would be helpful! /****************************************************************** Subnet Definitions *******************************************************************/ //Define the public subnet for availability zone A. resource "aws_subnet" "Subnet_A_Public" { vpc_id = "${aws_vpc.terraform-vpc.id}" cidr_block = "${var.public_subnet_a}" availability_zone = "${var.availability_zone_a}" tags { Name = "Subnet A - Public" } } //Define the public subnet for availability zone B. resource "aws_subnet" "Subnet_B_Public" { vpc_id = "${aws_vpc.terraform-vpc.id}" cidr_block = "${var.public_subnet_b}" availability_zone = "${var.availability_zone_b}" tags { Name = "Subnet B - Public" } } /********************************************************************* Security Group (SG) Definitions **********************************************************************/ //Define the public security group. resource "aws_security_group" "tf-public-sg" { name = "TF-Public-SG" description = "Allow incoming HTTP/HTTPS connections and SSH access from the Internet." vpc_id = "${aws_vpc.terraform-vpc.id}" //Accept tcp port 80 (HTTP) from the Internet. ingress { from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } //Accept tcp port 443 (HTTPS) from the Internet. ingress { from_port = 443 to_port = 443 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } //Accept tcp port 22 (SSH) from the Internet. ingress { from_port = 22 to_port = 22 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } //Accept all ICMP inbound from the Internet. ingress { from_port = -1 to_port = -1 protocol = "icmp" cidr_blocks = ["0.0.0.0/0"] } lifecycle { create_before_destroy = true } tags { Name = "Terraform Public SG" } } /************************************************************************** PUBLIC ASG & LC ***************************************************************************/ resource "aws_launch_configuration" "terraform-public-lc" { image_id = "${var.ami}" instance_type = "${var.instance_type}" security_groups = ["${aws_security_group.tf-public-sg.id}"] lifecycle { create_before_destroy = true } } resource "aws_autoscaling_group" "tf-public-asg" { launch_configuration = "${aws_launch_configuration.terraform-public-lc.id}" availability_zones = ["${var.availability_zone_a}", "${var.availability_zone_b}"] name = "tf-public-asg" min_size = "${var.asg_min_pubic}" max_size = "${var.asg_max_public}" desired_capacity = "${var.asg_desired_capacity_public}" tags { key = "Name" value = "tf-public-asg" //value = "${var.public_instance_name}-${count.index}" propagate_at_launch = true } } /************************************************************************ END PUBLIC ASG & LC *************************************************************************/
{ "language": "en", "url": "https://stackoverflow.com/questions/53193203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Angular ng-class ternary doesn't update my template as the model changes When my page initially loads it properly sets the class using this ng-class ternary operator: <div ng-class="{{day.current}} ? 'currPeriod' : 'notCurrPeriod'"> {{day.date | date:"d"}} </div> Note - this html is in a template, used by a directive, generated in an ng-repeat The value of the day {{day.date | date:"d"}} updates, but the class is not applied. Oddly, my dev tools shows a disparity: 1 = true so it should evaluate to currPeriod but the element class is still notCurrPeriod. I tried $scope.$apply() at the end of the modal change, but that didn't work. How can I get the template to rerun and apply this ternary? or is there a better way to do this? A: <div ng-class="{'currPeriod': day.current, 'notCurrPeriod': !day.current}"> {{day.date | date:"d"}} </div> ng-class doesn't work this way, use the object syntax to acheive what you want, or you can either set a default style when the day isn't in the current period, and apply the class when it is, it would shorten your ng-class statement
{ "language": "en", "url": "https://stackoverflow.com/questions/35511733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: R: Combine columns in matrix having same column name I have a large document-Term matrix. I want to combine columns which with the same column name. I have found someone asked the same problem and had work solution. Combine columns in matrix having same column name I have tried using the answer to do. But R returns an error message to me. Error: cannot allocate vector of size 49.3 Gb #my large matrix tf_mat <- as.matrix(dtm_title) %>% cbind(as.matrix(dtm_abstract)) %>% cbind(as.matrix(dtm_claim)) #Combine columns with same column name. nms <- colnames(tf_mat) tf_mat %*% sapply(unique(nms),"==", nms) Error: cannot allocate vector of size 49.3 Gb Is there any way to solve it? Or is there any other solution? A: Thanks for all of your opinion. I have tried use another way from Combine columns in matrix having same column name. I think it's more suitable for my case, and don't take lot of time to execute. nms <- colnames(tf_mat) tf_mat_bind <- sapply(unique(nms), function(i)rowSums(tf_mat[, nms==i, drop=FALSE]))
{ "language": "en", "url": "https://stackoverflow.com/questions/45808214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Enhance performance with for loop and linq query i have an object array and i need to get some object Info from database based on certain parameters, i am implementing this: public IList<object[]> GetRelevants(Registro[] records) { List<object[]> returnList = new List<object[]>(); using (var session = SessionFactory.OpenStatelessSession()) { for (int kr = 0; kr < records.Length; kr++) { Registro record = records[kr]; var query = session.QueryOver<Registro>() .Where(sb => sb.Asunto == record.Asunto) .And(sb => sb.FechaInicial == record.FechaInicial) .And(sb => sb.FechaFinal == record.FechaFinal) .And(sb => sb.FoliosDesde == record.FoliosDesde) .And(sb => sb.FoliosHasta == record.FoliosHasta) .And(sb => sb.TomoNumero == record.TomoNumero) .And(sb => sb.TomoTotal == record.TomoTotal) .And(sb => sb.SerieCodigo == record.SerieCodigo) .And(sb => sb.Caja == record.Caja) .And(sb => sb.Carpeta == record.Carpeta).SelectList(list => list .Select(p => p.Id) .Select(p => p.NuevaCaja) .Select(p => p.NuevaCarpeta) .Select(p => p.Periodo)); var result = query.SingleOrDefault<object[]>(); returnList.Add(result); } } return returnList; } In records however, there are more than 10000 items so NHibernate takes about 10 minutes to do that. Is there any way to enhance performance in this? A: A good solution would probably be to ditch NHibernate for this task and insert your data into a temporary table, then join on that temporary table. However, if you want to use NHibernate, you could speed this up by not issuing 10,000 separate queries (which is what's happening now). You could try to break your query into reasonably sized chunks instead: List<object[]> ProcessChunk( IStatelessSession session, int start, IEnumerable<Registro> currentChunk) { var disjunction = Restrictions.Disjunction(); foreach (var item in currentChunk) { var restriction = Restrictions.Conjunction() .Add(Restrictions.Where<Registro>(t => t.Asunto == item.Asunto)) /* etc, calling .Add(..) for every field you want to include */ disjunction.Add(restriction); } return session.QueryOver<Registro>() .Where(disjunction) .SelectList(list => list .Select(t => t.Id) /* etc, the rest of the select list */ .List<object[]>() .ToList(); } Then call that method from your main loop: const int chunkSize = 500; for (int kr = 0; kr < records.Length; kr += chunkSize) { var currentChunk = records.Skip(i).Take(chunkSize); resultList.AddRange(ProcessChunk(session, i, currentChunk)); } What you're doing here is issuing 20 (instead of 10,000) queries that look like: select /* select list */ from [Registro] where ([Registro].[Asunto] = 'somevalue' and ... and ... and .. ) or ([Registro].[Asunto] = 'someothervalue' and ... and ... and ... ) /* x500, one for each item in the chunk */ and so on. Each query will return up to 500 records if 500 is the size of each chunk. This is still not going to be blazing fast. My local test about halved the running time. Depending on your database engine, you might quickly run up against a maximum number of parameters that you can pass. You'll probably have to play with the chunkSize to get it to work. You could probably get this down to a few seconds if you used a temporary table and ditched NHibernate though.
{ "language": "en", "url": "https://stackoverflow.com/questions/27155493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error Resource ID #0x0 using setImageResource Android Adapter RecyclerView I'm learning Android, and I have a problem with my Adapter. I can get the Text in the Adapter but, I have problems with Setting the Image Source. [This is the result if i comment the code ] [this is an example of what i want but setting the images from my array. I use integer-array with item drawable in arrays.xml <integer-array name="champ_image"> <item>@drawable/aatrox</item> <item>@drawable/ahri</item> <item>@drawable/akali</item> <item>@drawable/alistar</item> <item>@drawable/amumu</item> <item>@drawable/anivia</item> <item>@drawable/ashe</item> </integer-array> Here is my Error LogCat: 01-04 03:09:30.057 19392-19392/com.sagar.materialdesigndemo E/AndroidRuntime: FATAL EXCEPTION: main 01-04 03:09:30.057 19392-19392/com.sagar.materialdesigndemo E/AndroidRuntime: Process: com.sagar.materialdesigndemo, PID: 19392 01-04 03:09:30.057 19392-19392/com.sagar.materialdesigndemo E/AndroidRuntime: android.content.res.Resources$NotFoundException: Resource ID #0x0 01-04 03:09:30.057 19392-19392/com.sagar.materialdesigndemo E/AndroidRuntime: at android.content.res.Resources.getValue(Resources.java:1307) 01-04 03:09:30.057 19392-19392/com.sagar.materialdesigndemo E/AndroidRuntime: at android.content.res.Resources.getDrawable(Resources.java:826) 01-04 03:09:30.057 19392-19392/com.sagar.materialdesigndemo E/AndroidRuntime: at android.content.Context.getDrawable(Context.java:403) 01-04 03:09:30.057 19392-19392/com.sagar.materialdesigndemo E/AndroidRuntime: at android.support.v4.content.ContextCompatApi21.getDrawable(ContextCompatApi21.java:26) 01-04 03:09:30.057 19392-19392/com.sagar.materialdesigndemo E/AndroidRuntime: at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:321) 01-04 03:09:30.057 19392-19392/com.sagar.materialdesigndemo E/AndroidRuntime: at android.support.v7.internal.widget.TintManager.getDrawable(TintManager.java:177) 01-04 03:09:30.057 19392-19392/com.sagar.materialdesigndemo E/AndroidRuntime: at android.support.v7.internal.widget.TintManager.getDrawable(TintManager.java:170) 01-04 03:09:30.057 19392-19392/com.sagar.materialdesigndemo E/AndroidRuntime: at android.support.v7.widget.AppCompatImageHelper.setImageResource(AppCompatImageHelper.java:53) 01-04 03:09:30.057 19392-19392/com.sagar.materialdesigndemo E/AndroidRuntime: at android.support.v7.widget.AppCompatImageView.setImageResource(AppCompatImageView.java:74) 01-04 03:09:30.057 19392-19392/com.sagar.materialdesigndemo E/AndroidRuntime: at com.sagar.adapters.ChampAdapter.onBindViewHolder(ChampAdapter.java:55) 01-04 03:09:30.057 19392-19392/com.sagar.materialdesigndemo E/AndroidRuntime: at com.sagar.adapters.ChampAdapter.onBindViewHolder(ChampAdapter.java:15) 01-04 03:09:30.057 19392-19392/com.sagar.materialdesigndemo E/AndroidRuntime: at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5212) Here is my Adapter called ChampAdapter, I think the problem is in: holder.champImg.setImageResource(champItem.get(position).champImg); //HERE public class ChampAdapter extends RecyclerView.Adapter<ChampAdapter.ViewHolder> { public List<ChampionItemModel> champItem; public ChampAdapter(List<ChampionItemModel> champItem){this.champItem = champItem;} public class ViewHolder extends RecyclerView.ViewHolder{ TextView champName; TextView roleChamp; ImageView champImg; public ViewHolder(View itemView) { super(itemView); this.champName = (TextView)itemView.findViewById(R.id.champ_name); this.roleChamp = (TextView)itemView.findViewById(R.id.champ_role); this.champImg = (ImageView)itemView.findViewById(R.id.champ_image); } } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_champs,parent,false); ViewHolder viewHolder = new ViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.itemView.setClickable(true); holder.itemView.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ } }); holder.champName.setText(champItem.get(position).champName); holder.roleChamp.setText(champItem.get(position).roleChamp); holder.champImg.setImageResource(champItem.get(position).champImg); //HERE IS THE PROBLEM } @Override public int getItemCount() { return champItem.size();} } And here is the rest of the code * *Model: public class ChampionItemModel { public String champName; public String roleChamp; public int champImg; public ChampionItemModel(String champName, String roleChamp, int champImg){ this.champName = champName; this.roleChamp = roleChamp; this.champImg = champImg; } } *Fragment method called initializeChampsItemList: private void initializeChampsItemList(){ ChampionItemModel championItemModel; String[] champsNames = getResources().getStringArray(R.array.champ_name); String[] champsRoles = getResources().getStringArray(R.array.champ_role); int[] champsImages = getResources().getIntArray(R.array.champ_image); final int length = champsNames.length; for(int i=0;i<length;i++){ championItemModel = new ChampionItemModel(champsNames[i], champsRoles[i], champsImages[i]); champItems.add(championItemModel); } } A: As in arrays.xml champ_image Array item is @drawable/aatrox means champ_image is typed Array instead of int. so use obtainTypedArray method which return TypedArray as: TypedArray imgsTypedArray = getResources().obtainTypedArray(R.array.champ_image); Now use TypedArray.getResourceId to get drawable id's and pass it to ChampionItemModel as: for(int i=0;i<length;i++){ int drawableId= imgsTypedArray.getResourceId(i, -1); championItemModel = new ChampionItemModel(champsNames[i], champsRoles[i], drawableId); champItems.add(championItemModel); } A: I assume you are trying to load images from drawable folder. Then declare 'champsImages' array like following: int[] champsImages = {R.drawable.image1, R.drawable.image2, R.drawable.image3, ...to more}; I think it will help to achieve your expected result. A: http://developer.android.com/guide/topics/resources/more-resources.html#TypedArray XML file saved at res/values/arrays.xml: <?xml version="1.0" encoding="utf-8"?> <resources> <array name="icons"> <item>@drawable/home</item> <item>@drawable/settings</item> <item>@drawable/logout</item> </array> <array name="colors"> <item>#FFFF0000</item> <item>#FF00FF00</item> <item>#FF0000FF</item> </array> </resources> This application code retrieves each array and then obtains the first entry in each array: Resources res = getResources(); TypedArray icons = res.obtainTypedArray(R.array.icons); Drawable drawable = icons.getDrawable(0); TypedArray colors = res.obtainTypedArray(R.array.colors); int color = colors.getColor(0,0);
{ "language": "en", "url": "https://stackoverflow.com/questions/34586871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mysql error "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock" I am having problem accessing my database, when I try to run mysql -h localhost -u root -p and enter the password I am recieving this kind of error ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) Wonder why I get this. When I type mysql --version I have no error and got this msg: mysql Ver 14.14 Distrib 5.5.22, for debian-linux-gnu (x86_64) using readline 6.2 But when I type this comman mysql -v I got an error that says: ERROR 2002 (HY000): Can't connect to local MySQL server through socket /var/run/mysqld/mysqld.sock' (2) I thought mysql --version and mysql -v are desame Any help will be much appreciated. Thank you A: I get that error when the MySQL service isn't running. What OS are you on? I'm on Debian GNU/Linux, so I start the service with # service mysql start but other systems may use something different, like start or invoke-rc.d or something.
{ "language": "en", "url": "https://stackoverflow.com/questions/10611619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Getting error with variance_ratio() function of R package 'codyn' ("One or more replicates consists of only a single species") I'm trying to use the function variance_ratio() from the 'codyn' package to find whether two populations' abundances are positively or negatively correlated over time. The column I'm using for species.var isn't actually the species names; it's names for the two populations. For replicate.var, I am using a variable called "siteyear." When I try to find the variance ratio, I'm getting the error message "Error in check_multispp(df, species.var, replicate.var): One or more replicates consists of only a single species; please remove these replicates prior to calculations." I assume this error means that one of the "species" is not found at all in some of the replicates, making its abundance always zero. However, I checked and all the site-years have abundance >0 for both "species", for at least one time point. There are some time points where one population has 0 abundance, but I don't see why that should be an issue. A: In trying to create minimal sample data that would replicate the error, I managed to figure out the cause. There were some replicates in my data frame with only one value for time.var (the time series had just one time point). This was flagged by the function check_multispp(), which is supposed to check whether the time series has more than one species, but the error message was slightly misleading.
{ "language": "en", "url": "https://stackoverflow.com/questions/72778585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Doesn't work z-index when using negative issue of margin-top I have div element with white color space and buttons, below location image. I want to have buttons on the image instead white color, but when I lift up image(used margin-top:-55px;), buttons location below and z-index dosn't work. .main_panel { text-align: center; z-index: 9999; overflow: visible; } section { height: 100vh; background-color: #fff; position: relative; overflow: hidden; z-index: 2; } .slider { background-color: #fff; } .slider img { margin-top: -55px; z-index: 1; } .main_button_left { font-weight: 700; color: white; text-decoration: none; padding: .8em 1em calc(.8em + 3px); padding: 15px 0px 15px 10px; border-radius: 3px; background: #ff6500; transition: 1s; border-color: #ff6500; border-bottom-left-radius: 10px; font-size: 15px; width: 200px; } .main_button { font-weight: 700; color: white; text-decoration: none; padding: .8em 1em calc(.8em + 3px); padding: 15px 0px 15px 10px; border-radius: 3px; background: #ff6500; transition: 1s; border-color: #ff6500; font-size: 15px; width: 200px; } button.main_button:hover, button.main_button_right:hover, button.main_button_left:hover { background: #ffcd07; border-color: #ffcd07; } .main_button_right { font-weight: 700; color: white; text-decoration: none; padding: .8em 1em calc(.8em + 3px); padding: 15px 0px 15px 10px; border-radius: 3px; background: #ff6500; transition: 1s; border-color: #ff6500; border-bottom-right-radius: 10px; font-size: 15px; width: 200px; } <section class="slider"> <div class="main_panel"> <button class="main_button_left">Some text</button> <button class="main_button">Some text</button> <button class="main_button">Some text</button> <button class="main_button">Some text</button> <button class="main_button">Some text</button> <button class="main_button">Some text</button> <button class="main_button">Some text</button> <button class="main_button_right">Some text</button> </div> <img src="http://dummyimage.com/1200x500"> </section>
{ "language": "en", "url": "https://stackoverflow.com/questions/44231584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OneSignal ios cordova app is quit when tap on notification 2017-01-25 12:48:02.057770 onesignaldemo[1009:314358] [DEBUG] [WL_PUSH] -[Push processRemotePushNotification:] in Push.m:426 :: Push: didReceive Remote notification 2017-01-25 12:48:03.065772 onesignaldemo[1009:314358] [FATAL] [WORKLIGHT] Uncaught Exception: * -[__NSSingleObjectArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0] 2017-01-25 12:48:03.093979 onesignaldemo[1009:314358] Terminating app due to uncaught exception 'NSRangeException', reason: ' -[__NSSingleObjectArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]' * First throw call stack: (0x190eed1b8 0x18f92455c 0x190ede420 0x10011d514 0x10011cfb8 0x1919ea46c 0x190e9b1d8 0x190e9aeec 0x190e9a7a8 0x190e983a4 0x190dc62b8 0x19287a198 0x197041510 0x197254c3c 0x19725885c 0x190ef3150 0x190de5eac 0x190dea95c 0x196a8bdd4 0x190ef1070 0x190dea80c 0x196abc92c 0x195bea254 0x19613dba0 0x195519044 0x19551862c 0x195518a6c 0x1955185c8 0x19551862c 0x1955185c8 0x19551862c 0x195512328 0x1953e4a68 0x194e1e770 0x195101f50 0x19663edec 0x19663fc0c 0x196aca61c 0x197256dd4 0x10039f5c0 0x191a01048 0x190e9ab5c 0x190e9a434 0x190e980a4 0x190dc62b8 0x19287a198 0x196e0d7fc 0x196e08534 0x1000183d0 0x18fda95b8) libc++abi.dylib: terminating with uncaught exception of type NSException Blockquote This is the Payload I am getting in app cordova.require('cordova/exec').nativeCallback('OneSignalPush998202862',1, { "shown" : true, "payload" : { "body" : "wwww", "sound" : "default", "notificationID" : "93d30e95-8af8-4e47-a50d-e09af9fd9498", "rawPayload" : { "aps" : { "alert" : "wwww", "sound" : "default" }, "custom" : { "a" : { "foo" : "bar" }, "i" : "93d30e95-8af8-4e47-a50d-e09af9fd9498" } }, "additionalData" : { "foo" : "bar" } }, "isAppInFocus" : true, "displayType" : 2 } ,1) Worklight version is 7.1 Error at this code of CDVCommandDelegateImpl.m - (void)evalJsHelper2:(NSString*)js { CDV_EXEC_LOG(@"Exec: evalling: %@", [js substringToIndex:MIN([js length], 160)]); NSString* commandsJSON = [_viewController.webView stringByEvaluatingJavaScriptFromString:js]; if ([commandsJSON length] > 0) { CDV_EXEC_LOG(@"Exec: Retrieved new exec messages by chaining."); } [_commandQueue enqueueCommandBatch:commandsJSON]; [_commandQueue executePending]; } Error Reproduction Push notification is working fine. App is able to receive notification App is in inactive state: If I'm click on notification, app will open and it shows the notification alert inside app and suddenly its quit. App is Active state: Notification will be automatically displays in app and app will stuck there. A: I could integrate Onesignal in my ios app. The issue was in config.xml I commented the push related tags in config.xml.
{ "language": "en", "url": "https://stackoverflow.com/questions/41845653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Error with define in Racket I just discovered Racket a few days ago, and I'm trying to get more comfortable with it by writing a little script that generates images to represent source code using #lang slideshow. I know that when programming in a functional paradigm it's good practice to create almost all your variables with let, but I find that it introduces too many levels of nesting and that Racket's let has an overcomplicated API which requires superfluous parentheses. I'm sure this is to remove ambiguity when using let in more powerful ways, but for my purposes it's just an annoyance. Consequently, I'm creating all my variables with define, and writing blocks with begin if I need to (such as in the body of an if statement). The problem is that I've repeatedly been getting what seem to be very mysterious errors. I'm sure I'm just making some silly beginner's mistake, being new to the language, but I really can't seem to find the source of the complaint. Here's the offending code: (define sub-code (foldr ht-append (rectangle 0 0) (map internal-style (rest code)))) although what we're defining sub-code to seems pretty irrelevant. If I replace it with (define sub-code '()) I receive the same error. DrRacket is saying that define is being used in an expression context. I understand what this error would normally mean - IE that it would raise when you write code like (print (define x 10)), but I can't see what would trigger it here. If it helps, this define is at the beginning of a begin block, inside an if statement (if (list? code) (begin (define sub-code '()) ; a few more define statements and finally an expression )) The specific error message DrRacket is printing is define: not allowed in an expression context in: (define sub-code (quote ())) I thought maybe define isn't allowed in begin blocks, but I checked the docs and one of the examples for begin is (begin (define x 10) x) So I don't really know what to do. Thanks in advance! A: As GoZoner explained, you can't use define in an expression context. What could you do instead? Use let: (if (list? code) (let ([x '()]) x) ... Or it would work with an "empty" let and define: (if (list? code) (let () (define x '()) x) ... But that's a bit silly. Or use cond and define: (cond [(list? code) (define x '()) x] ... This last way -- using cond and define -- is closest to what the current Racket style guide recommends. A: Here's more details, from the Racket docs. The different contexts are required because macros must expand differently, depending on which language forms are allowed. As others have said, definitions are not allowed in expression contexts ("expr ..." in the docs), but are ok in other contexts. In other doc entries, "body ..." indicates an internal-definition context (guide, reference), for example in lambda bodies, and "form ..." indicates all non-expression contexts, like in the docs for begin. A: Definitions are allowed in a 'body' context, like in lambda and let among others. The consequent and alternate clauses of if are not body contexts; they are expression contexts and therefore definitions are not allowed. begin is special - begin in a body context allows definitions, but begin in an expression contexts forbids definitions. Your case falls in to the later. For example: (define (foo . args) #| body context #|) (define foo (lambda args #| body context |#)) (define (foo . args) (let (...) #| body context |#)) Syntactic keywords that requires expressions: if, cond, case, and, or, when, unless, do, begin. Check out the formal syntax in any Scheme report (r{4,5,6,7}rs); look for <body>, <sequence>, <command>, and <expression>. Also, if you need a body context in an expression, just wrap a let syntactic form, as such: (if test (let () (define foo 'foo) (list foo foo)) alternate) A: Or you could wrap the expressions in (begin) e.g.(begin (define x 10) (define y 100) (define z 1000))
{ "language": "en", "url": "https://stackoverflow.com/questions/16221336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: i have a problem filter datetime in mysql i have this query: select b.observation, b.created_date (datetime field) FROM logistics_wms.reception_documents a join logistics_wms.reception b on a.reception_id = b.id join logistics_wms.document c on a.documents_id = c.id join logistics_wms.document_type d on d.id = c.document_type_id join logistics_wms.document_line e on c.id = e.document_id join logistics_wms.product g on e.product_id = g.id where b.status = 'SUBMITTED' and b.created_date >= '2020-04-01 00:00:00' i used '2020-04-01' too And the result is: but if i used: select b.observation, b.created_date (datetime field) FROM logistics_wms.reception_documents a join logistics_wms.reception b on a.reception_id = b.id join logistics_wms.document c on a.documents_id = c.id join logistics_wms.document_type d on d.id = c.document_type_id join logistics_wms.document_line e on c.id = e.document_id join logistics_wms.product g on e.product_id = g.id where b.status = 'SUBMITTED' and b.created_date >= '2020-04-15 00:00:00' i used '2020-04-15' too the result is: why when i select 2020-04-01 the query doesn´t get the last two records of the second query??!! Please help me Thank you A: Given the fact that time has no importance in your case (00:00:00), it is much simpler to use MySQL DATE function in your filter. Can you try using : where b.status = 'SUBMITTED' and DATE(b.created_date) >= '2020-04-01' and where b.status = 'SUBMITTED' and DATE(b.created_date) >= '2020-04-15'
{ "language": "en", "url": "https://stackoverflow.com/questions/61308140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to pick second element starting from the last one? I have two elements and they have the same class and I want to pick the second element starting from the last one. ( I hope image tells you everything) I tried nth-child but my two elements have same class which is why I can't do with nth-child any idea ? A: you can use nth-last-child(2) or nth-last-of-type(2), this will select the 2nd last item. li { display: inline-block } li:nth-last-child(2) { color: red } <ul> <li>test</li> <li>test</li> <li>test</li> <li>test</li> <li>test</li> </ul> <hr /> <ul> <li>test</li> <li>test</li> <li>test</li> <li>test</li> <li>test</li> <li>test</li> <li>test</li> </ul>
{ "language": "en", "url": "https://stackoverflow.com/questions/39459950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: joining tables , data between dates I am practicing with northwind database: I am quite new to sql. Question I am trying to solve is : Q. Total Sales for each customer in October 1996 (based on OrderDate). Show the result in CustomerID, CompanyName, and [total sales], sorted in [total sales] in Decending order. I have used this code but doesn't seems to be correct , please advise. select c.customerid , c.companyname , o.orderdate , sum(od.unitprice *od.Quantity*1-od.Discount) as totalsales from customers as c , orders as o , [Order Details] as od where o.customerid = c.CustomerID and o.OrderID = od.OrderID and o.OrderDate >= '1996/10/01' and o.orderdate <= '1996/10/31' group by c.customerid , c.companyname, o.orderdate order by totalsales desc ; ******************************* A: I suspect is it just the method of calculation inside the sum function SELECT c.customerid , c.companyname , o.orderdate , SUM((od.unitprice * od.Quantity) * (1 - od.Discount)) AS totalsales FROM customers AS c INNER JOIN orders AS o ON o.customerid = c.CustomerID INNER JOIN [Order Details] AS od ON o.OrderID = od.OrderID WHERE o.OrderDate >= '1996-10-01' AND o.orderdate < '1996-11-01' -- move up one day, use less than GROUP BY c.customerid , c.companyname , o.orderdate ORDER BY totalsales DESC ; * *(od.unitprice * od.Quantity) provides total discounted price, then *the discount rate is (1 - od.Discount) *multiply those (od.unitprice * od.Quantity) * (1 - od.Discount) for total discounted price Please note I have changed the syntax of the joins! PLEASE learn this more modern syntax. Don't use commas between table names in the from clause, then conditions such as AND o.customerid = c.CustomerID move to after ON instead of within the where clause.. Also, the most reliable date literals in SQL Server are yyyymmdd and the second best is yyyy-mm-dd. It's good to see you using year first, but I would suggest using dashes not slashes, or (even better) no delimiter. e.g. WHERE o.OrderDate >= '19961001' AND o.orderdate < '19961101' Also note that I have removed the <= and replaced it with < and moved that higher date to the first of the next month. It is actually easier this way as every month has a day 1, just use less than this higher date.
{ "language": "en", "url": "https://stackoverflow.com/questions/53057592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Search for a double word inside .txt file using batch file I did some research on google for finding the answer on my question the only thing i found that was similar too my question was on this site: Search for a word inside .txt file using batch file I made a batch file that is creating a .txt file with 8 lines like this: Hello Mate How Are You Doing Bye Bye I want to make a batch file that can detect double words inside the text file in this file it must detect Bye In the batch file that also made the .txt file with the 8 lines I want to let it detect the double word Bye in the text file and after some research I came to the conclusion that this must be possible with findstr. Can findtr detect that the word Bye twice occurs? In my file i want to get a report like this echo in the text file you made %isn't or there is% a double word so I want the result of findstr into the variable %isn't or there is% Sorry if this is a bad question but im new to stackoverflow and im dutch :/ (lot of text translated with google translate) and can you explain if this is a bad question how i can make it clearer for you A: here is something to start with: @echo off for /f %%i in (t.txt) do for /f %%a in ('type t.txt^|findstr /x "%%i"^|find /v /c "" ') do if %%a gtr 1 echo %%i findstr can't count, so we have to use find /c as helper see find /?, findstr /? and for /? for more information. A: Stephan's answer works, but it prints out every replicate word as many times as it appears. It also fairly inefficient, reading the entire file once for every line in the file. Here is a fairly simple pure batch solution that prints out each replicate word only once. The task is much simpler if you use SORT to group all the replicates together. However, the Windows SORT command ignores case, so the IF must also ignore case. This solution only reads the file twice, regardless of size, once for SORT, and once for FOR /F. @echo off setlocal enableDelayedExpansion set "prev=" set "dup=" for /f "delims=" %%W in ('sort test.txt') do ( if /i %%W==!prev! ( if not defined dup echo(%%W set dup=1 ) else set "dup=" set "prev=%%W" ) If you want the word comparison to be case sensitive, then the above algorithm requires a case sensitive SORT routine. I've written JSORT.BAT to do just that (among other things). It is pure script (hybrid JScript/batch) that runs natively on Windows. But if you are willing to use a JScrpt/batch hybrid, then the solution becomes very simple if you add my JREPL.BAT regular expression find/replace utility. The /M option allows me to search for repeated words across newlines. jsort test.txt | jrepl "^(.+)$(\r?\n\1$)+" $1 /jmatch /m There is significant initialization time to fire up the JScript engine, so this solution is a bit slower than the pure batch solution if the file is small. But if the file is large, than this is much faster than the pure batch solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/37488144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Check if port is open from the server itself I've a Centos 6.5 - Apache server. This server is in a private LAN (it has a private IP 10.x.x.x) and is linked to a domain name. If I test port 443 from webtools with the domain name, it seems that it's blocked, but I want to understand if it's blocked from a firewall outside the server or if it depends from the server configuration. Is there anyway I can check if the port is open for the server? iptables firewall is empty. A: You could simply try to telnet from the server to itself. So if you'd want to check if port 443 is responding, run: telnet localhost 443 if the response is telnet: Unable to connect to remote host: Connection refused then there's probably nothing listening on that port.
{ "language": "en", "url": "https://stackoverflow.com/questions/28631392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Angular + Rails: Delete posts I have an angular/rails app and I currently have the ability to post things, but I cannot seem to write the code required to delete posts. My Github: https://github.com/JeremyLopez/ToDoList/tree/master/ToDoList To create: (tasks.js) angular.module('toDoList') .factory('tasks', [ '$http', function($http){ var o = { tasks: [] }; o.create = function(task) { return $http.post('/tasks.json', task).success(function(data){ o.tasks.push(data); }); }; but how would I write something very similar only deleting the post? I have included my github since I am unsure which file is pertinent, but please focus on app/controller/tasks_controller.rb, javascripts/home/mainCtrl.js, and most importantly javascripts/tasks/tasks.js. Thanks A: This function works! o.destroy = function(task) { return $http.delete('/tasks/' + task.id + '.json').success(function(data){ console.log("Task " + task.title + " has been deleted!") }); }; ...I did have to make changes to my app/controllers/tasks_controller.rb: def destroy task = Task.find(params[:id]) task.destroy respond_with task end
{ "language": "en", "url": "https://stackoverflow.com/questions/34205458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Xcode DispatchQueue.main.async inside or outside large loop? i am trying to edit/Insert CoreData objects , what i am doing is this : DispatchQueue.main.async { for track in allTracks { if let i = allObjects.index(where: { $0.sid == ddTools().md5("\(track.song_name)\(track.artist_name)") } ) { self.log("[NEW][\(i)] Already in DB : \(track.song_name)") }else { self.insert_track(track) } } } but its still blocking the UI if Array has over 500+ object , is it safe if i do this ? for track in allTracks { DispatchQueue.main.async { if let i = allObjects.index(where: { $0.sid == ddTools().md5("\(track.song_name)\(track.artist_name)") } ) { self.log("[NEW][\(i)] Already in DB : \(track.song_name)") }else { self.insert_track(track) } } } can i use DispatchQueue.main.async inside looping of CoreData objects ! to void blocking UI after some advices i have updated the function to this func insert_or_update_songs(tracks:[DTO_SONG],onComplete:(()->())!) { let allTasksGroup = DispatchGroup() var totalFinished:Int = 0 for track in tracks { DispatchQueue.main.async { allTasksGroup.enter() //Fetch if Exists let context = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext let songHash = ddTools().md5("\(track.song_name)\(track.artist_name)") let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Song_Entity") request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [NSPredicate(format:"sid = %@", songHash), NSPredicate(format:"sid != %@", "")]) do{ if try context.count(for:request) > 0 { //Update the Track if let _tracks:[Song_Entity] = try context.fetch(request) as? [Song_Entity] { self.update_track(track, _tracks[0]) } }else //Insert as new track { self.insert_track(track,context :context) } if context.hasChanges { do { try context.save() self.log(" New Changes has been Saved.") } catch let error as NSError { self.log(" Could not save. \(error), \(error.userInfo)") } } totalFinished += 1 print(" \(totalFinished)/\(tracks.count)") allTasksGroup.leave() }catch let error as NSError { self.log("[HASH] Error while checking Track if in DB: \(error), \(error.userInfo)") } } } //When all done allTasksGroup.notify(queue: .main) { self.log("[INSERT OR UPDATE BATCH] Total Finished : \(totalFinished)/\(tracks.count) ") if totalFinished == tracks.count { if onComplete != nil { onComplete() } } } A: For both CoreData tread safety and responsiveness of your UI, I'd go with doing the thread switch at the insert point: for track in allTracks { if let i = allObjects.index(where: { $0.sid == ddTools().md5("\(track.song_name)\(track.artist_name)") } ) { self.log("[NEW][\(i)] Already in DB : \(track.song_name)") } else { DispatchQueue.main.async { self.insert_track(track) } } } A: Both snippets of code are wrong. allTracks are core-data objects that are attached to a particular context - which is not thread safe. You cannot access these objects - neither reading or writing - from the main thread. You can save the information - and then pass that to the main thread. If you doing the fetch to use on the main thread, you shouldn't be using a background thread in the first place. It is better to just do the fetch on the main thread.
{ "language": "en", "url": "https://stackoverflow.com/questions/46997978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error when running QDB2 driver on deployment machine I am using Win7 and db2 express. I have successfully compiled and used the db2 drivers on one of my machines, but when trying to use it on another computer that does not have db2 installed the driver won't run and return an empty string as an error. Just to make sure I copied everything from ibm/sqllib/bin to a directory that can be found on the computer I use for deployment and dependency walker confirms that indeed the qsqldb2 driver can find the libraries inside that directory. Yet the problem remains and my app won't run properly, any ideas on how to solve this error? A: I am yet not sure if this classifies as an answer or not but, even though in my development machine it worked fine with the libraries inside ibm/sqllib/bin. The way I made it work on my deployment machine is by instead providing it with the libraries coming with the clidriver.
{ "language": "en", "url": "https://stackoverflow.com/questions/27522415", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: html5 time validation issue using pattern I am using the HTML5 in build validation but for Time, i am sing the following code The code is pretty simple as it is just checking the format of the time, i am not sure what i am doing wrong here <input name="taskStartTime" type="text" value="05:15 PM" placeholder="Enter a valid start time." size="10" pattern="/^\d{1,2}:\d{2}([ap]m)?$/" title="Enter Valid Time"> But it is not validating and it says invalid time, i think my regex is right, but not sure what is going on here... A: Remove the forward slashes: they are part of JavaScript regex literal syntax, not part of general regex syntax. You don't really need the ^ and $ either because for an input element pattern they are implied. The value you are setting in your example, 05:15 PM won't match your regex either, because it has a space in it and because the "PM" is in capitals. To allow for that: pattern="\d{1,2}:\d{2}( ?[apAP][mM])?" Note that for html5 input pattern attributes you can't set the i case insensitive flag that JavaScript (and some other regex implementations) allow. According to the specification it does use the JS syntax for the pattern itself, but "it is compiled "with the global, ignoreCase, and multiline flags disabled". A: try this <input name="taskStartTime" type="text" value="05:15 PM" placeholder="Enter a valid start time." size="10" pattern="^\d{1,2}:\d{2}\s([AP]M)?$" title="Enter Valid Time">
{ "language": "en", "url": "https://stackoverflow.com/questions/26956430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: check if a file exists in zip archive I'm using windows 7 ultimate and I want to check on the command line whether or not a file exists inside a zip archive. I'd prefer if the procedure does not include downloading other stuff. A: try with the zipjs.bat: call zipjs.bat list -source "C:\myZip.zip" -flat yes|find /i "filename" && ( echo file does exists in the zip color )|| ( echo file does NOT exists in the zip )
{ "language": "en", "url": "https://stackoverflow.com/questions/32183113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to update column with multiple conditions taking a corresponding value from another column Python Pandas The output is more like the following SQL statement. UPDATE table_A SET final=(cs+fhfa+sz)/3 WHERE cs IS NOT NULL AND fhfa IS NOT NULL AND sz IS NOT NULL; Here cs+fhfa+sz are all individual columns in the sql table ( and in dataframe) If I want to convert this SQL statement to pandas operation in python, this will be more like : df['div_3'] = (df.cs+df.fhfa+df.sz) /3 df['final'] = df.loc[(df['cs'] != None) & (df['fhfa'] != None) & (df['sz'] != None) ] = df['div_3'] But this does not guarantee "corresponding values" being put finally. How to achieve this?? Do i really need to create another column div_3 with all the sum of 3 columns? Can this be done without another column creation? A: Filter on pd.Series.notnull and call mean. c = ['cs', 'fhfa', 'sz'] df['final'] = df[df[c].notnull().all(1)][c].mean(1) A: IIUC: df.loc[:, 'final'] = df.loc[df[['cs','fhfa','sz']].notnull().all(1), ['cs','fhfa','sz']].sum(1)/3 .all(1) - is the same as .all(axis=1), which means - all values in each row must be True
{ "language": "en", "url": "https://stackoverflow.com/questions/46807834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: When I redeploy my google project ID, I see an error in gcloud.app.deploy saying Insufficient permissions to create Google Cloud Storage bucket My google project ID is "ulapph-public-1" and its been working fine since 2015. But yesterday when I redeployed the project, it says: ERROR: (gcloud.app.deploy) Error Response: [7] Insufficient permissions to create Google Cloud Storage bucket. The link to the Google Cloud Storage is no longer accessible as well: https://console.cloud.google.com/storage/browser/ulapph-public-1.appspot.com?project=ulapph-public-1 Then the Google Cloud Storage browser says this error: A required resource is not available. Tracking Number: c4898802499062169 I tried checking the IAM but no luck, the deploy won't proceed. I even tried going to Appengine->Settings->Default Cloud Storage Bucket then the button I see there is "Create" but when I click it the error says "Default Cloud Storage Bucket creation failed". I also checked the cloud storage browser settings and I noticed that there is no associated service account for the cloud storage. Compared to my other project IDs, I usually see here the service account like: service-123456789012@gs-project-accounts.iam.gserviceaccount.com Cloud Storage Service Account Each project has an associated Cloud Storage service account. This is used to perform certain background actions: receiving PubSub notifications and encrypting/decrypting KMS encrypted objects. Is there anyone who is familiar with this issue? - How do I manually add the missing service account service-123456789012@gs-project-accounts.iam.gserviceaccount.com? - What could have triggered the removal of the service account? File "/google/google-cloud-sdk/lib/googlecloudsdk/api_lib/util/waiter.py", line 320, in _IsNotDone return not poller.IsDone(operation) File "/google/google-cloud-sdk/lib/googlecloudsdk/api_lib/app/operations_util.py", line 182, in IsDone encoding.MessageToPyValue(operation.error))) OperationError: Error Response: [7] Insufficient permissions to create Google Cloud Storage bucket. Details: [ [ { "@type": "type.googleapis.com/google.rpc.ResourceInfo", "resourceName": "staging.ulapph-public-1.appspot.com", "resourceType": "cloud storage bucket" } ] ] ERROR: (gcloud.app.deploy) Error Response: [7] Insufficient permissions to create Google Cloud Storage bucket. Details: [ [ { "@type": "type.googleapis.com/google.rpc.ResourceInfo", "resourceName": "staging.ulapph-public-1.appspot.com", "resourceType": "cloud storage bucket" } ] ] Note that all my other google projects are working fine and the billing is fine but I only have Bronze support package so I can't connect to a technical support.
{ "language": "en", "url": "https://stackoverflow.com/questions/56921261", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can a byte-range in a m3u8 playlist be length 0? According to the HLS Pantos spec, a byte-range in a m3u8 playlist should look like #EXT-X-BYTERANGE:<n>[@<o>] where "n is a decimal-integer indicating the length of the sub-range in bytes". However, this doesn't specify if "n" can be 0 or negative. This is a particular issue for caption playlists which may have a gap where no captions appear... Is this a valid playlist? #EXTM3U #EXT-X-TARGETDURATION:10 #EXT-X-MEDIA-SEQUENCE:0 #EXT-X-VERSION:4 #EXTINF:10.0, #EXT-X-BYTERANGE:100@0 media.ts #EXTINF:10.0, #EXT-X-BYTERANGE:0@100 media.ts #EXTINF:10.0, #EXT-X-BYTERANGE:50@100 media.ts A: No, playlist entries with a byte-range length of 0 are NOT valid. A: Byte-range can not be zero in any case. I don't think any streamer will send zero value for this.
{ "language": "en", "url": "https://stackoverflow.com/questions/26264214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Progress Bar in revolution slider WordPress I found code to make my Progress Bar look like i need from this source . Everything work fine as expected. But i need to make entire Progress Bar width 50% off main page. I try to add all span in one div and make this div 50-60% width but this didn't help. Need some help with that, thanks A: You can use jQuerys function .wrapAll() to wrap the span elements in a parent container. Give that new container a class and set position to absolute, left offset to 25% and right offset to 25%. // JS api.on('revolution.slide.onloaded', function() { var totalSlides = api.revmaxslide(), perc = parseFloat((100 / totalSlides).toFixed(2)); for(var i = 0; i < totalSlides; i++) { progressSlots[i] = jQuery( '<span class="rev-progress-perc" ' + 'style="width: ' + perc + '%; left: ' + (perc * i) + '%" ' + 'data-slide="' + i + '" ' + '/>' ); } progressSlots.wrapAll('slots-wrapper'); api.append(progressSlots); progressBar = jQuery('.tp-bannertimer'); progressSlots = jQuery('.rev-progress-perc').on('click', changeSlides); }) ... // CSS .slots-wrapper{ position: absolute; z-index:99; bottom: 0; left: 25%; right: 25%; }
{ "language": "en", "url": "https://stackoverflow.com/questions/50922939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: how this sample Forged digital certificate I found a pe file,when i check digital certificate,i found winxp can identity the digital cert,but win10 can not,virus total also show that this file is not signd Is this a fake digital cert? how to made this happen? winxp info: enter image description here win10 info enter image description here A: Windows XP used SHA1 hashes in the signatures, which is not supported on 10: Source: The following table shows which OS's support SHA-1 and SHA-256 code signatures: +---------------------+-------------------------------+------------------------------+ | Windows OS | SHA-1 | SHA-256 | +---------------------+-------------------------------+------------------------------+ | XP SP3, Server 2003 | Yes | No (need KB968730, KB938397) | | Vista, Server 2008 | Yes | No (need KB2763674) | | 7, Server 2008 R2 | No (if signed after 1/1/2016) | Yes (with latest updates) | | 8.1, Server 2012 R2 | No (if signed after 1/1/2016) | Yes | | 10, Server 2016 | No (if signed after 1/1/2016) | Yes | +---------------------+-------------------------------+------------------------------+
{ "language": "en", "url": "https://stackoverflow.com/questions/64620170", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wrong encoding when running from JAR, from Eclipse works perfectly I am facing the problem similar to How to Force a jar to uses(or the jvm runs in) utf-8 instead of the system's default encoding. There is a server and client java applications. If I run both of them from Eclipse then everything works just fine. If I make jars then a String exchanged between them gets spoiled (wrong encoding). If I run both images with -Dfile.enconding=utf-8 JVM parameter then it works okay. But since the link above says that it is not the best solution (at least requires running jar from bat) I have tried to solve the issue with specifying encoding to BufferedReader. But it fails and with jar it is difficult to debug. This code is for sending request and getting one line in JSON format as reply. The reply is proved to have UTF-8 encoding. public static String sendRequest (String request) { if (request == null) return null; try { URL url = new URL(request); HttpsURLConnection con = (HttpsURLConnection)url.openConnection(); BufferedReader inReader = new BufferedReader(new InputStreamReader(con.getInputStream(), Charset.forName("UTF-8"))); String line = inReader.readLine(); inReader.close(); return line; } catch (Exception e) { e.printStackTrace(System.err); } return null; } This is how the line look like {"response":[{"uid":123456,"first_name":"Имя","last_name":"Фамилия"}]} Then I prepare it to use in Gson.fromJson() int beginIndex = reply.indexOf('['); int endIndex = reply.indexOf(']'); reply = reply.substring(beginIndex + 1, endIndex); SocialPerson vkPerson = new Gson().fromJson(reply, SocialPerson.class); After that the String is being sent to server using Netty's ChannelBuffer generated with ChannelBuffers.wrappedBuffer() and NettyUtils.writeStrings() I try to debug Client in Eclipse and Server running from jar, then Eclipse shows that until the string is really given to framework to deliver it looks valid. Then I debug Server and Client runs from Jar and once string being received it already looks like rubbish. At server side private final String username; private final String password; public SimpleCredentials(ChannelBuffer buffer) { this.username = NettyUtils.readString(buffer); this.password = NettyUtils.readString(buffer); } Where do you think the problem can be? Sorry, I can not post all the code here. UPD: username is generated from firstName and lastName ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(opCode, NettyUtils.writeStrings(userId, userName, refKey)); A: When you read the network stream you need to reencode your strings manually if the automatically way fails. It is possible that the libiary which you are using is ignoring the content encoding or maybe it is missing in the HTTP-response. Somewhere in your code will be a byte array which you can convert in the String constructor: String xxx = new String(bytes, "utf-8"); If you get the String with the wrong encoding you can check this code: String rightEncoded = new String(wrongEncodedString.getBytes("Cp1252"), "utf-8"); A: You shouldn't be using the file.encoding system property. The best way to avoid such encoding issues is to never assume anything about default platform encodings and always provide an encoding when constructing readers or when converting bytes to Strings and vice versa. Your sendRequest method seems to be OK with respect to handling encodings: it reads characters from the input, explicitly mentioning that it expects the stream to be encoded in UTF-8. However, we can't see the other end of the client/server sequence. Quoting you: After that the String is being sent to server using Netty's ChannelBuffer generated with ChannelBuffers.wrappedBuffer() and NettyUtils.writeStrings() You also mentioned that you can't attach the entire code here, which is understandable; therefore, I'd advise that you look into how exactly you're sending those strings out, and whether or not you're explicitly specifying an encoding while doing so. EDIT as per OP's update: well, I'm sorry that I am not familiar with Netty, but still I'll take a shot here. Doesn't NettyUtils.writeStrings(), or any of the code that calls it, accept a character encoding? I can't find the JavaDoc to any NettyUtils online. Work with me here. :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/13598921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Prompt for input within a loop Linux shell I'm creating a script to check in an interactive prompt whether to delete a cron entry or not: function cron_check() { crontab -l result=$? if [[ $result -eq 0 ]]; then crontab -l > crontab.out cat crontab.out | while read cron_entry do # ignore commented cron entries [ "${cron_entry#\#}" = "$cron_entry" ] || continue # skip comment read -u3 -p "Do you want to remove this cron entry: $cron_entry, Please enter [Y/N]" yn case $yn in [yY] | [yY][Ee][Ss] ) sed -i "/$cron_entry/d" crontab.out;; [nN] | [n|N][O|o] ) break;; * ) echo "Please answer Y or N.";; esac done 3<&0 < crontab.out crontab crontab.out fi } cron_check However the prompt part is not working, when running the script I'm getting: Please answer Y or N. Any help how to solve this ? Thank you ! A: To be able to use read in your case, you need something like this using a special file descriptor : while read crontab_entry; do ... read -u3 -p 'question' yn ... done 3<&0 < crontab.out because STDIN is already fed by the crontab output A: I used a special file descriptor for the cat command instead and done some modifications to the sed command to work correctly. function cron_check() { crontab -l result=$? if [[ $result -eq 0 ]]; then crontab -l > crontab.out exec 3< crontab.out while read -u 3 cron_entry do # ignore commented cron entries [ "${cron_entry#\#}" = "$cron_entry" ] || continue # skip comment read -p "Do you want to remove this cron entry: $cron_entry, Please enter [Y/N]" yn case $yn in [yY] | [yY][Ee][Ss] ) cron_entry_esc=$(sed 's/[\*\.&/]/\\&/g' <<<"$cron_entry");crontab -l | sed "/$cron_entry_esc/d" | crontab -;; [nN] | [n|N][O|o] ) continue;; * ) echo "Please answer Y or N.";; esac done fi } cron_check
{ "language": "en", "url": "https://stackoverflow.com/questions/27676438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: NullPointerException when initializing EbeanServer I'm attempting to use EbeanORM to connect to MS SQL Server 2012. In addition, I'm using Spring and the jTDS driver. I'm getting the following exception when initializing the Spring context: Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ebeanServer' defined in class path resource [spring.xml]: Invocation of init method failed; nested exception is java.lang.NullPointerException at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:753) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83) at com.example.cloud.dal.Dal.<clinit>(Dal.java:48) ... 43 more Caused by: java.lang.NullPointerException at com.avaje.ebeaninternal.server.changelog.DefaultChangeLogListener.configure(DefaultChangeLogListener.java:62) at com.avaje.ebeaninternal.server.core.DefaultServer.configureServerPlugins(DefaultServer.java:257) at com.avaje.ebeaninternal.server.core.DefaultServer.<init>(DefaultServer.java:248) at com.avaje.ebeaninternal.server.core.DefaultContainer.createServer(DefaultContainer.java:130) at com.avaje.ebeaninternal.server.core.DefaultContainer.createServer(DefaultContainer.java:45) at com.avaje.ebean.EbeanServerFactory.createInternal(EbeanServerFactory.java:108) at com.avaje.ebean.EbeanServerFactory.create(EbeanServerFactory.java:67) at com.avaje.ebean.springsupport.factory.EbeanServerFactoryBean.afterPropertiesSet(EbeanServerFactoryBean.java:54) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$6.run(AbstractAutowireCapableBeanFactory.java:1627) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1624) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574) ... 55 more Looking at the code in question, I see this is related to configuration. It appears that an expected properties object is null, and it's not expected to be. I do see the following error in the logs: 16:39:12.070 [run-main-2] ERROR c.a.ebean.config.PropertyMapLoader - ebean.properties not found This error is confusing to me. Since I'm using Spring to configure the EbeanServer, it seems like I shouldn't need an ebean.properties (EDIT: adding an empty ebean.properties makes the error go away, but not the exception in question). In fact, at one point this setup was working (I could read/write to the DB). Now it's not, and I'm going crazy trying to figure out what changed. Here's my spring.xml: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd "> <import resource="classpath:default-ebean-server.xml"/> <context:property-placeholder location="classpath:dal.properties" /> <context:component-scan base-package="com.example.dal.service" /> <context:component-scan base-package="com.example.dal.dao" /> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="net.sourceforge.jtds.jdbc.Driver" /> <property name="jdbcUrl" value="${db.jdbc_url}" /> <property name="user" value="${db.user}" /> <property name="password" value="${db.password}" /> <!-- these are C3P0 properties --> <property name="initialPoolSize" value="${db.min_pool_size}" /> <property name="minPoolSize" value="${db.min_pool_size}" /> <property name="maxPoolSize" value="${db.max_pool_size}" /> <property name="preferredTestQuery" value="SELECT 1" /> <property name="idleConnectionTestPeriod" value="300" /> <property name="connectionCustomizerClassName" value="com.example.dal.IsolationLevelConnectionCustomizer" /> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <bean id="serverConfig" parent="defaultEbeanServerConfig"> <property name="name" value="serverConfig"/> <property name="packages"> <list> <value>com.example.dal.model</value> </list> </property> <property name="dataSource" ref="dataSource"/> </bean> <bean id="ebeanServer" class="com.avaje.ebean.springsupport.factory.EbeanServerFactoryBean"> <property name="serverConfig" ref="serverConfig"/> </bean> </beans> Possibly relevant details: * *Java 8 *EbeanORM 6.4.1 *Spring 4.1.7.RELEASE *avaje-ebeanorm-spring 4.5.3 *jTDS 1.3.1 A: Figured it out myself, finally. The Short Answer It appears that a new feature introduced in EbeanORM 6.4.1 breaks something. This is the feature in question: https://github.com/ebean-orm/avaje-ebeanorm/issues/390. Downgrading (see below) to 6.3.1 resolves the issue. The Long Answer I had been using EbeanORM 6.3.1 when I first got things working. I upgraded to 6.4.1, seeing that it had been released a couple days ago. I noticed that things broke shortly after (no automated tests yet). I downgraded to 6.3.1 again, but this didn't fix things so I assumed it was a red herring. Unbeknownst to me, SBT/Ivy was evicting 6.3.1 in favour of 6.4.1, even though I was explicitly depending on 6.3.1. avaje-ebeanorm-spring, which I'm also using, depends on avaje-ebeanorm with version specifier [6,7). So, for some reason, SBT/Ivy decided that 6.4.1 was the best resolution of these two version requirements (WTF.... ). I figured this out with this excellent plugin: https://github.com/jrudolph/sbt-dependency-graph. To force SBT to give me 6.3.1, I modified my dependencies to add the exclude: "org.avaje.ebeanorm" % "avaje-ebeanorm" % "6.3.1", "org.avaje.ebeanorm" % "avaje-ebeanorm-spring" % "4.5.3" exclude("org.avaje.ebeanorm", "avaje-ebeanorm")
{ "language": "en", "url": "https://stackoverflow.com/questions/32259596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PUT method is not working in front end but works in Postman Please, help me. I am doing PERN stack app, and I can't understand why my PUT method is not working in front end but works in Postman perfectly. When I add a todo - "drink water" for example, in database id appears as should "drink water" and in fron end as well it appears, but when I edit that todo in front end it's null in database and front end as well, looks like that: description {id: 56, todo: null} Here is a code of EditTodo.js: export default function EditTodo({ todo }) { const [description, setDescription] = useState(todo); console.log("todos", todo); console.log("description", description); // Edit function const editText = async (id) => { try { const body = { description }; const response = await fetch(`http://localhost:5000/todos/${id}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); console.log("response", response); window.location = "/"; } catch (error) { console.error(error.message); } }; return ( <Fragment> <button type="button" className="btn btn-warning" data-toggle="modal" data-target="#myModal" > Edit </button> <div className="modal" id="myModal"> <div className="modal-dialog"> <div className="modal-content"> <div className="modal-header"> <h4 className="modal-title">Edit Todo</h4> <button type="button" className="close" data-dismiss="modal" ></button> </div> <div className="modal-body"> <input type="text" className="form-control" value={description.todo} onChange={(e) => setDescription(e.target.value)} /> </div> <div className="modal-footer"> <button type="button" className="btn btn-warning" data-dismiss="modal" onClick={() => editText(todo.id)} > Edit </button> <button type="button" className="btn btn-danger" data-dismiss="modal" > Close </button> </div> </div> </div> </div> </Fragment> ); } Looks like EditText function is not executed when I edit the todo. Thanks in advance. A: Where do you set the todo? A put request replaces the current values with new ones. If you only set the description property but leave the todo out, it will overwrite it with an empty string, clearing any data you had in there. Either set the old value of the todo before making your put request or use a patch instead. A patch only affect certain selected values instead of everything. Anyway, it's still very possible to do this with a put instead. Try creating a useEffect where you set your todo to state. Something like this: const todoVar = description.find((desc)=> desc.id === todo.id); useEffect(()=>{ if(todoVar){ setDescription(description.todo) } },[todoVar, setDescription]) Basically, you want to set the todo value from your database to it's original value before making your PUT request. This way it won't be empty/null.
{ "language": "en", "url": "https://stackoverflow.com/questions/72686535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Callback for when obj changes position? In MaxScript, how would I detect if an object has been moved with an event? I have tried detecting transform but this doesn't work: when transform $Body do ( print"moved" ) It also cannot freeze the ui or the program, since it has to detect when an object is actively moving. A: Your forgot the changes keyword. The correct syntax is when transform $Body changes do ( print "moved" ) A: An already key-framed node will not trigger this handler it is not being driven by the user, but by the system. This will not trigger when you press play in the trackbar. Without knowing exactly what you intend to do it's difficult to recommend an alternative. If you wish to report the position or transform information of a specific node when the trackbar/currentTime changes, you could use registerTimeCallback and unRegisterTimeCallback . fn reportObject = ( print $Box001.pos ) registerTimeCallback reportObject This will trigger when the play button is used, or when you scrub the time bar. Read the documentation regarding timecallbacks as they have specific rules. Hopefully this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/37148441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: the deleteRows function is populating my Google Sheet with 500 blank rows The below trigger works great, but when executed it repopulates my sheet with 500 rows. After the trigger is executed I need it to only show the 1st row. function deleteRows() { var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet 1'); var start, howManyToDelete; start = 2; howManyToDelete = sheet.getLastRow() - start + 1; } A: Answer in the comments from the original poster: All good I solved the issue. I changed the 'start = 2;' to 'start = 3'. This generated the titles and only one empty row to begin working form
{ "language": "en", "url": "https://stackoverflow.com/questions/69450268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In Vue 2, is there a way to (temporarily) disable a component from updating computed properties? I have a component that I essentially want to to stay static while things are updating in the parent, and I want to set some kind of boolean to indicate when it's ready to update the component properties. Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/68922879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Difference between Lighthouse numbers and observed performance I have spent literally weeks chasing the perfect desktop and mobile scores from Google Search Console. My website is new, so there is not enough data, and I'm forced to use Lighthouse. At 1AM today my score was 97 desktop, 80 mobile. At 2PM today, with no changes, it dropped to 80/32. I am also being informed that there is a FOIT due to improper loading of code. I have run these tests dozens of times over the past few weeks, making minor changes and then looking at their impact. I am chasing smoke. Just before I wrote this note my son and I decided to test real-world timing for the first time. I have a desktop pc, Windows 10, all properly updated. i-5 processor about 3 years old, 12 gb RAM, with a 300 MB/s cable modem connection on ethernet (wired). Lighthouse speed: Time to Interactive: 1.8s The website loaded so fast it was not measurable with a digital stopwatch,at well under 1 second. Next, we tried mobile connections over home wifi (Netgear Nighthawk AC 1900). First with a Samsung S8 cellphone accessing the website via my Google Ads website link. Time from pressing the website button to complete load: 1.8 seconds, +/- .2 seconds. Next, my son's iPhone8 plus. Time to complete load: 1.6 seconds, +/- .2 seconds. Lighthouse result: "Time to Interactive"8.4s. The results were close on the desktop, but off by about 400% on the mobile connections. I am a retired doctor with no IT training, but I know where to find the information I need and apply it. I just spent the last 2 weeks chasing numbers that have little relationship to real-world experience; an enormous waste of time. I suggest that if there is not enough real-life data to assess "time to interactive", that you might be better served not using a service that attempts to mimic real-world experience with such poor correlation. I just wasted a lot of time chasing numbers that tend to arbitrarily change and have no relationship to observable and measurable performance, and I am sure I'm not the only one. In addition, there was zero observable FOIT on any device, so if it does exist, it is too fast for the human eye to observe, and as such is irrelevant. Knowing this, what is the purpose of the Lighthouse test, why do its numerical scores change so dramatically during the course of a day, and how do the numerical results of such a test improve real-world experience?
{ "language": "en", "url": "https://stackoverflow.com/questions/64073021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Throw a temporary argument passed by reference inline void my_assert( bool cond, const std::exception &e = my_assert_failed() ) { if ( !cond ) throw e; } The standard ensures that: A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full expression containing the call. And for a thrown temporary object: The temporary persists as long as there is a handler being executed for that exception. Can I infer that a temporary that is passed to my_assert survives until the catch block finishes? A: From N4296 (first draft after final C++14) [15.1p3]: Throwing an exception copy-initializes (8.5, 12.8) a temporary object, called the exception object. The temporary is an lvalue and is used to initialize the variable declared in the matching handler (15.3). So you can't assume that your temporary "survives the throw". If throwing, the copy constructor of an exception object of type std::exception will be called with e as the argument. The temporary that e is bound to will be destroyed when control leaves the full expression containing the call to my_assert (either after a normal return or as part of stack unwinding, since you're conditionally throwing the exception). There are circumstances when the copy construction of the exception object can be elided, but this is not one of them, according to [12.8p31.2]: — in a throw-expression (5.17), when the operand is the name of a non-volatile automatic object (other than a function or catch-clause parameter) whose scope does not extend beyond the end of the innermost enclosing try-block (if there is one), the copy/move operation from the operand to the exception object (15.1) can be omitted by constructing the automatic object directly into the exception object (emphasis mine)
{ "language": "en", "url": "https://stackoverflow.com/questions/28875810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Flot - Create multiple series bar chart and add multiple colors to one of the series I need to create the following chart using jquery flot. I think to create it with multiple series but I have the following problem: I need the one series to be in different colors for each bar (the first in the image), and I found support only for one color for each series. Can anyone please help?
{ "language": "en", "url": "https://stackoverflow.com/questions/29144040", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Loading additional modals from server with Paginator.clientPager I'm trying to load additional modals from the server after the initial fetch with Paginator.clientPager This is my collection, pretty much copy pasted from the example code on github. return new (Backbone.Paginator.clientPager.extend({ model: model, paginator_core: { type: 'GET', dataType: 'json', url: '/odata/LibraryFile' }, paginator_ui: { // the lowest page index your API allows to be accessed firstPage: 1, // which page should the paginator start from // (also, the actual page the paginator is on) currentPage: 1, // how many items per page should be shown perPage: 2, // a default number of total pages to query in case the API or // service you are using does not support providing the total // number of pages for us. // 10 as a default in case your service doesn't return the total totalPages: 5 }, server_api: { // number of items to return per request/page '$skip': function () { return this.perPage * (this.currentPage - 1) }, '$top': function () { return this.perPage }, }, parse: function (response) { console.log(response); return response.value; } }))(); I'm calling the initial fetch like so myCollection.fetch({ success: function(){ myCollection.pager(); }, silent:true }); Then, after the user has browsed trough the local pages with the clientPager, he probably wants to load in more pages, without deleting the first pages. I try to achieve this like this, but for some reason, after i call pager(); the 2 new records are removed. myCollection.currentPage = 2; myCollection.fetch({ success: function(){ console.log(myCollection.length) // 4 models, with correct data myCollection.pager(); console.log(myCollection.length) // the 2 new records are removed }, silent:true, remove: false // don't remove old records }); What am i doing wrong, how can i load it 2 more pages with the Paginator.clientPager ? I don't want to use requestPager because then i can't do in memory pre-caching, at least, i think. A: In my experience, this is caused by the pager() method of Backbone.Paginator.clientPager. You can take a look at the code here: Backbone.Paginator.clientPager Lines 292 through to 294 show that the Backbone.Paginator.clientPager.origModels is only assigned to the current models (the one whose length you correctly tested in your illustrations above) if it's undefined. The problem is that by the time the user probably wants to load more pages without deleting the first, the origModels property would already be set as a result of the initial fetch. This means you'd have to explicitly make origModels undefined again before pager() would act as you want. Note what happens later on line 296 of the source code (models is assigned to a copy of origModels). That's why your two new records were removed. The following code should work as you intended: myCollection.currentPage = 2; myCollection.fetch({ success: function(){ delete myCollection.origModels; // to ensure that origModels is overridden in pager() call below myCollection.pager(); }, silent:true, remove: false // don't remove old records });
{ "language": "en", "url": "https://stackoverflow.com/questions/17150979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }