File size: 178,959 Bytes
dbe8248
 
 
 
 
 
 
 
 
 
83039ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
{"text": "Q: How to modify non-configurable, non-writable properties in Javascript? I'm writing a simple EventEmitter is ES5.\nThe objective is to ensure that all properties on EventEmitter instances are\nnon-writable and non-configurable.\"\nAfter 6 hours of racking my brain I still can't figure out how to, increase the listenerCount, for example if the configurable descriptor is set to false.\nHere's an example of what I have:\nvar eventEmitter = function(){\n  var listeners = listeners || 0;\n  var events = events || {};\n\n  Object.defineProperties(this, {\n   listeners: {\n    value : 0,\n    configurable: false,\n    writable: false\n  },\n  events: {\n    value: {},\n    configurable : false,\n    writable: false\n    }\n  });\n  return this;\n};\n\n\neventEmmitter.prototype.on = function(ev, cb) {\n  if (typeof ev !== 'string') throw new TypeError(\"Event should be type string\", \"index.js\", 6);\n  if (typeof cb !== 'function' || cb === null || cb === undefined) throw new TypeError(\"callback should be type function\", \"index.js\", 7);\n\n  if (this.events[ev]){\n    this.events[ev].push(cb);\n  } else {\n    this.events[ev] = [cb];\n  }\n\n  this.listeners ++;\n  return this;\n};\n\n\nA: I would recommend the use of an IIFE (immediatly invoked function expression):\nvar coolObj=(function(){\nvar public={};\nvar nonpublic={};\nnonpublic.a=0;\npublic.getA=function(){nonpublic.a++;return nonpublic.a;};\n\nreturn public;\n})();\n\nNow you can do:\ncoolObj.getA();//1\ncoolObj.getA();//2\ncoolObj.a;//undefined\ncoolObj.nonpublic;//undefined\ncoolObj.nonpublic.a;//undefined\n\nI know this is not the answer youve expected, but i think its the easiest way of doing sth like that.\n\nA: You can use a proxy which requires a key in order to define properties:\n\n\nfunction createObject() {\r\n  var key = {configurable: true};\r\n  return [new Proxy({}, {\r\n    defineProperty(target, prop, desc) {\r\n      if (desc.value === key) {\r\n        return Reflect.defineProperty(target, prop, key);\r\n      }\r\n    }\r\n  }), key];\r\n}\r\nfunction func() {\r\n  var [obj, key] = createObject();\r\n  key.value = 0;\r\n  Reflect.defineProperty(obj, \"value\", {value: key});\r\n  key.value = function() {\r\n    key.value = obj.value + 1;\r\n    Reflect.defineProperty(obj, \"value\", {value: key});\r\n  };\r\n  Reflect.defineProperty(obj, \"increase\", {value: key});\r\n  return obj;\r\n}\r\nvar obj = func();\r\nconsole.log(obj.value); // 0\r\ntry { obj.value = 123; } catch(err) {}\r\ntry { Object.defineProperty(obj, \"value\", {value: 123}); } catch(err) {}\r\nconsole.log(obj.value); // 0\r\nobj.increase();\r\nconsole.log(obj.value); // 1\n\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/41069927", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}}
{"text": "Q: Image hiding under button android Image view is hiding under the button what changes I can do so that the image view can be above the button view pager also have bottom padding so that button can properly accommodate. The image is showing on the other parts but not above the button.\n  <?xml version=\"1.0\" encoding=\"utf-8\"?>\n    <androidx.constraintlayout.widget.ConstraintLayout\n        xmlns:android=\"http://schemas.android.com/apk/res/android\"\n        xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"match_parent\"\n        android:orientation=\"vertical\"\n        tools:context=\".McqActivity\"\n        android:id=\"@+id/fragment\"\n        >\n    \n        <RelativeLayout\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            app:layout_constraintBottom_toBottomOf=\"parent\"\n            app:layout_constraintEnd_toEndOf=\"parent\"\n            app:layout_constraintStart_toStartOf=\"parent\">\n    \n    \n                <ImageView\n                android:id=\"@+id/starFirst\"\n                android:layout_width=\"50dp\"\n                android:layout_height=\"50dp\"\n                android:src=\"@drawable/ic_baseline_star_24\"\n                />                  \n    \n    \n            <com.google.android.material.button.MaterialButton\n                android:id=\"@+id/right\"\n                android:layout_width=\"match_parent\"\n                android:layout_height=\"wrap_content\"\n                 />\n    \n        </RelativeLayout>\n    \n        <androidx.viewpager2.widget.ViewPager2\n            android:id=\"@+id/questions_view_frag\"\n            android:layout_width=\"match_parent\"\n            android:layout_height=\"0dp\"\n            app:layout_constraintBottom_toBottomOf=\"parent\"\n            app:layout_constraintEnd_toEndOf=\"parent\"\n            app:layout_constraintHorizontal_bias=\"0.0\"\n            app:layout_constraintStart_toStartOf=\"parent\"\n            app:layout_constraintTop_toTopOf=\"parent\"\n            app:layout_constraintVertical_bias=\"0.0\"\n            android:orientation=\"horizontal\"\n            android:paddingBottom=\"20dp\"\n            android:paddingTop=\"50dp\"\n            >\n    \n        </androidx.viewpager2.widget.ViewPager2>\n        \n    \n    </androidx.constraintlayout.widget.ConstraintLayout>\n\n\nA: layout_constraintBottom_toBottomOf and other layout_constraint... won't work inside RelativeLayout, these are desired to work with ConstraintLayout as strict parent. if you want to align two Views next to/below/above inside RelativeLayoyut you have to use other attributes, e.g.\nandroid:layout_below=\"@+id/starFirst\"\nandroid:layout_above=\"@+id/starFirst\"\nandroid:layout_toRightOf=\"@id/starFirst\"\nandroid:layout_toLeftOf=\"@id/starFirst\"\n\nnote that every attr which starts with layout_ is desired to be read by strict parent, not by View which have such attrs set. every ViewGroup have own set of such\nedit: turned out that this is an elevation case/issue (Z axis), so useful attributes are\nandroid:translationZ=\"100dp\"\nandroid:elevation=\"100dp\"\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/70017985", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Handling multiple exceptions I have written a class which loads configuration objects of my application and keeps track of them so that I can easily write out changes or reload the whole configuration at once with a single method call. However, each configuration object might potentially throw an exception when doing IO, yet I do not want those errors to cancel the overall process in order to give the other objects still a chance to reload/write. Therefore I collect all exceptions which are thrown while iterating over the objects and store them in a super-exception, which is thrown after the loop, since each exception must still be handled and someone has to be notified of what exactly went wrong. However, that approach looks a bit odd to me. Someone out there with a cleaner solution? \nHere is some code of the mentioned class:\npublic synchronized void store() throws MultipleCauseException\n    {\n    MultipleCauseException me = new MultipleCauseException(\"unable to store some resources\");\n    for(Resource resource : this.resources.values())\n        {\n        try\n            {\n            resource.store();\n            }\n        catch(StoreException e)\n            {\n            me.addCause(e);\n            }\n        }\n    if(me.hasCauses())\n        throw me;\n    }\n\n\nA: If you want to keep the results of the operations, which it seems you do as you purposely carry on, then throwing an exception is the wrong thing to do. Generally you should aim not to disturb anything if you throw an exception.\nWhat I suggest is passing the exceptions, or data derived from them, to an error handling callback as you go along.\npublic interface StoreExceptionHandler {\n    void handle(StoreException exc);\n}\n\npublic synchronized void store(StoreExceptionHandler excHandler) {\n    for (Resource resource : this.resources.values()) {\n        try {\n            resource.store();\n        } catch (StoreException exc) {\n            excHandler.handle(exc);\n        }\n    }\n    /* ... return normally ... */\n]\n\n\nA: There are guiding principles in designing what and when exceptions should be thrown, and the two relevant ones for this scenario are:\n\n\n*\n\n*Throw exceptions appropriate to the abstraction (i.e. the exception translation paradigm)\n\n*Throw exceptions early if possible\n\n\nThe way you translate StoreException to MultipleCauseException seems reasonable to me, although lumping different types of exception into one may not be the best idea. Unfortunately Java doesn't support generic Throwables, so perhaps the only alternative is to create a separate MultipleStoreException subclass instead.\nWith regards to throwing exceptions as early as possible (which you're NOT doing), I will say that it's okay to bend the rule in certain cases. I feel like the danger of delaying a throw is when exceptional situations nest into a chain reaction unnecessarily. Whenever possible, you want to avoid this and localize the exception to the smallest scope possible.\nIn your case, if it makes sense to conceptually think of storing of resources as multiple independent tasks, then it may be okay to \"batch process\" the exception the way you did. In other situations where the tasks has more complicated interdependency relationship, however, lumping it all together will make the task of analyzing the exceptions harder.\nIn a more abstract sense, in graph theory terms, I think it's okay to merge a node with multiple childless children into one. It's probably not okay to merge a whole big subtree, or even worse, a cyclic graph, into one node.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/2444580", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "8"}}
{"text": "Q: What is the meaning of Duration in Amazon RDS Backup window What does Duration specify?\nDoes it mean that the backup will start between 01:00 to 01:30 and keep running until it has completed? Or does it have a different meaning?\n\n\nA: The duration window indicates the time in which the backup will start. I can start anywhere between the time specified and could last longer than the window.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/58445170", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-1"}}
{"text": "Q: Uncontrolled input of type text to be controlled warning I'm trying to create a multi step registration form using React and Redux.\nThe main component is as follows :    \nimport React, {PropTypes} from 'react';\nimport {connect} from 'react-redux';\nimport {bindActionCreators} from 'redux';\nimport * as actionCreators from '../../actions/actionCreators';\nimport countries from '../../data/countries';\n\nimport RegistrationFormStepOne from './registrationFormStepOne';\nimport RegistrationFormStepTwo from './registrationFormStepTwo';\nimport RegistrationFormStepThree from './registrationFormStepThree';\nimport RegistrationFormStepFour from './registrationFormStepFour';\n\nclass RegistrationPage extends React.Component {\n    constructor(props) {\n        super(props);\n\n        this.state = {\n            user: Object.assign({}, this.props.userData),\n            fileNames: {},\n            selectedFile: {},\n            icons: {\n                idCard: 'upload',\n                statuten: 'upload',\n                blankLetterhead: 'upload',\n                companyPhoto: 'upload'\n            },\n            step: 1,\n            errors: {}\n        };\n\n        this.setUser = this.setUser.bind(this);\n        this.onButtonClick = this.onButtonClick.bind(this);\n        this.onButtonPreviousClick = this.onButtonPreviousClick.bind(this);\n        this.changeCheckboxState = this.changeCheckboxState.bind(this);\n        this.onFileChange = this.onFileChange.bind(this);\n        this.routerWillLeave = this.routerWillLeave.bind(this);\n    }\n\n    componentDidMount() {\n        this.context.router.setRouteLeaveHook(this.props.route, this.routerWillLeave);\n    }\n\n    routerWillLeave(nextLocation) {\n        if (this.state.step > 1) {\n            this.setState({step: this.state.step - 1});\n            return false;\n        }\n    }\n\n    getCountries(){\n        return countries;\n    }\n\n\n    setUser(event) {\n        const field = event.target.name;\n        const value = event.target.value;\n\n        let user = this.state.user;\n        user[field] = value;\n        this.setState({user: user});\n\n    }\n\n    validation(){\n        const user = this.state.user;\n        const languageReg = this.props.currentLanguage.default.registrationPage;\n        let formIsValid = true;\n        let errors = {};\n\n        if(!user.companyName){\n            formIsValid = false;\n            errors.companyName = languageReg.companyNameEmpty;\n        }\n\n        if(!user.btwNumber){\n            formIsValid = false;\n            errors.btwNumber = languageReg.btwNumberEmpty;\n        }\n\n        if(!user.address){\n            formIsValid = false;\n            errors.address = languageReg.addressEmpty;\n        }\n\n        if(!user.country){\n            formIsValid = false;\n            errors.country = languageReg.countryEmpty;\n        }\n\n        if(!user.zipcode){\n            formIsValid = false;\n            errors.zipcode = languageReg.zipcodeEmpty;\n        }\n\n        if(!user.place){\n            formIsValid = false;\n            errors.place = languageReg.placeEmpty;\n        }\n\n\n        if(!user.firstName){\n            formIsValid = false;\n            errors.firstName = languageReg.firstnameEmpty;\n        }\n\n\n\n        this.setState({errors: errors});\n        return formIsValid;\n    }\n\n    onFileChange(name, event) {\n        event.preventDefault();\n        let file = event.target.value;\n\n        let filename = file.split('\\\\').pop(); //We get only the name of the file\n        let filenameWithoutExtension = filename.replace(/\\.[^/.]+$/, \"\"); //We get the name of the file without extension\n\n        let user = this.state.user;\n        let fileNames = this.state.fileNames;\n        let selectedFile = this.state.selectedFile;\n        let icons = this.state.icons;\n\n        switch (name.btnName) {\n            case \"idCard\" :\n                fileNames[name.btnName] = filenameWithoutExtension;\n                //Check if file is selected\n                if(file){\n                    selectedFile[name.btnName] = \"fileSelected\";\n                    user[\"idCardFile\"] = true;\n                    icons[\"idCard\"] = \"check\";\n                }else{\n                    selectedFile[name.btnName] = \"\";\n                    user[\"idCardFile\"] = false;\n                    icons[\"idCard\"] = \"upload\";\n                }\n                break;\n            case \"statuten\" :\n                fileNames[name.btnName] = filenameWithoutExtension;\n\n                //Check if file is selected\n                if(file){\n                    selectedFile[name.btnName] = \"fileSelected\";\n                    user[\"statutenFile\"] = true;\n                    icons[\"statuten\"] = \"check\";\n                }else{\n                    selectedFile[name.btnName] = \"\";\n                    user[\"statutenFile\"] = false;\n                    icons[\"statuten\"] = \"upload\";\n                }\n                break;\n            case \"blankLetterhead\" :\n                fileNames[name.btnName] = filenameWithoutExtension;\n\n                //Check if file is selected\n                if(file){\n                    selectedFile[name.btnName] = \"fileSelected\";\n                    user[\"blankLetterheadFile\"] = true;\n                    icons[\"blankLetterhead\"] = \"check\";\n                }else{\n                    selectedFile[name.btnName] = \"\";\n                    user[\"blankLetterheadFile\"] = false;\n                    icons[\"blankLetterhead\"] = \"upload\";\n                }\n                break;\n            default:\n                fileNames[name.btnName] = filenameWithoutExtension;\n                //Check if file is selected\n                if(file){\n                    selectedFile[name.btnName] = \"fileSelected\";\n                    user[\"companyPhotoFile\"] = true;\n                    icons[\"companyPhoto\"] = \"check\";\n                }else{\n                    selectedFile[name.btnName] = \"\";\n                    user[\"companyPhotoFile\"] = false;\n                    icons[\"companyPhoto\"] = \"upload\";\n                }\n        }\n\n        this.setState({user: user, fileNames: fileNames, selectedFile: selectedFile, icons: icons});\n    }\n\n    changeCheckboxState(event) {\n        let chcName = event.target.name;\n        let user = this.state.user;\n\n        switch (chcName) {\n            case \"chcEmailNotificationsYes\":\n                user[\"emailNotifications\"] = event.target.checked;\n                break;\n            case \"chcEmailNotificationsNo\":\n                user[\"emailNotifications\"] = !event.target.checked;\n                break;\n            case \"chcTerms\":\n                if(typeof this.state.user.terms === \"undefined\"){\n                    user[\"terms\"] = false;\n                }else{\n                    user[\"terms\"] = !this.state.user.terms;\n                }\n\n                break;\n            case \"chcSmsYes\":\n                user[\"smsNotifications\"] = event.target.checked;\n                break;\n            default:\n                user[\"smsNotifications\"] = !event.target.checked;\n        }\n        this.setState({user: user});\n        this.props.actions.userRegistration(this.state.user);\n    }\n\n    onButtonClick(name, event) {\n        event.preventDefault();\n        this.props.actions.userRegistration(this.state.user);\n        switch (name) {\n            case \"stepFourConfirmation\":\n                this.setState({step: 1});\n                break;\n            case \"stepTwoNext\":\n                this.setState({step: 3});\n                break;\n            case \"stepThreeFinish\":\n                this.setState({step: 4});\n                break;\n            default:\n                if(this.validation()) {\n                   this.setState({step: 2});\n                }\n        }\n    }\n\n\n    onButtonPreviousClick(){\n        this.setState({step: this.state.step - 1});\n    }\n\n    render() {\n        const languageReg = this.props.currentLanguage.default.registrationPage;\n\n        console.log(this.state.user);\n        let formStep = '';\n        let step = this.state.step;\n        switch (step) {\n            case 1:\n                formStep = (<RegistrationFormStepOne user={this.props.userData}\n                                                     onChange={this.setUser}\n                                                     onButtonClick={this.onButtonClick}\n                                                     countries={this.getCountries(countries)}\n                                                     errors={this.state.errors}\n                                                     step={step}/>);\n                break;\n            case 2:\n                formStep = (<RegistrationFormStepTwo user={this.props.userData}\n                                                     onChange={this.setUser}\n                                                     onButtonClick={this.onButtonClick}\n                                                     onButtonPreviousClick={this.onButtonPreviousClick}\n                                                     errors={this.state.errors}/>);\n                break;\n            case 3:\n                formStep = (<RegistrationFormStepThree user={this.props.userData}\n                                                       onFileChange={this.onFileChange}\n                                                       onButtonClick={this.onButtonClick}\n                                                       onButtonPreviousClick={this.onButtonPreviousClick}\n                                                       errors={this.state.errors}\n                                                       fileNames={this.state.fileNames}\n                                                       icons={this.state.icons}\n                                                       fileChosen={this.state.selectedFile}/>);\n                break;\n\n            default:\n                formStep = (<RegistrationFormStepFour user={this.props.userData}\n                                                      onChange={this.setUser}\n                                                      onChangeCheckboxState={this.changeCheckboxState}\n                                                      onButtonClick={this.onButtonClick}\n                                                      onButtonPreviousClick={this.onButtonPreviousClick}\n                                                      errors={this.state.errors}/>);\n        }\n\n        return (\n            <div className=\"sidebar-menu-container\" id=\"sidebar-menu-container\">\n\n                <div className=\"sidebar-menu-push\">\n\n                    <div className=\"sidebar-menu-overlay\"></div>\n\n                    <div className=\"sidebar-menu-inner\">\n                        <div className=\"contact-form\">\n                            <div className=\"container\">\n                                <div className=\"row\">\n                                    <div className=\"col-md-10 col-md-offset-1 col-md-offset-right-1\">\n                                        {React.cloneElement(formStep, {currentLanguage: languageReg})}\n                                    </div>\n                                </div>\n                            </div>\n                        </div>\n                    </div>\n                </div>\n            </div>\n        );\n    }\n}\n\nRegistrationPage.contextTypes = {\n    router: PropTypes.object\n};\n\nfunction mapStateToProps(state, ownProps) {\n    return {\n        userData: state.userRegistrationReducer\n    };\n}\n\nfunction mapDispatchToProps(dispatch) {\n    return {\n        actions: bindActionCreators(actionCreators, dispatch)\n    };\n}\n\nexport default connect(mapStateToProps, mapDispatchToProps)(RegistrationPage);\n\nThe first step component is as follows\n    import React from 'react';\nimport Button from '../../common/formElements/button';\nimport RegistrationFormHeader from './registrationFormHeader';\nimport TextInput from '../../common/formElements/textInput';\nimport SelectInput from '../../common/formElements/selectInput';\n\nconst RegistrationFormStepOne = ({user, onChange, onButtonClick, errors, currentLanguage, countries}) => {\n\n  const language = currentLanguage;\n\n  return (\n    <div className=\"contact_form\">\n      <form role=\"form\" action=\"\" method=\"post\" id=\"contact_form\">\n        <div className=\"row\">\n          <RegistrationFormHeader activeTab={0} currentLanguage={language}/>\n          <div className=\"hideOnBigScreens descBox\">\n            <div className=\"headerTitle\">{language.businessInfoConfig}</div>\n            <div className=\"titleDesc\">{language.businessBoxDesc}</div>\n          </div>\n          <div className=\"col-lg-12\">\n            <h6 className=\"registrationFormDesc col-lg-10 col-lg-offset-1 col-lg-offset-right-2 col-xs-12\">\n              {language.businessDesc}\n            </h6>\n            <div className=\"clearfix\"></div>\n            <div className=\"col-sm-6\">\n              <TextInput\n                type=\"text\"\n                name=\"companyName\"\n                label={language.companyNameLabel}\n                labelClass=\"control-label\"\n                placeholder={language.companyNameLabel}\n                className=\"templateInput\"\n                id=\"company\"\n                onChange={onChange}\n                value={user.companyName}\n                errors={errors.companyName}\n              />\n            </div>\n            <div className=\"col-sm-6\">\n              <TextInput\n                type=\"text\"\n                name=\"btwNumber\"\n                label={language.vatNumberLabel}\n                placeholder={language.vatNumberLabel}\n                className=\"templateInput\"\n                id=\"btwNumber\"\n                onChange={onChange}\n                value={user.btwNumber}\n                errors={errors.btwNumber}\n              />\n            </div>\n\n            <div className=\"col-sm-12\" style={{marginBottom: 25}}>\n              <TextInput\n                type=\"text\"\n                name=\"address\"\n                label={language.addressLabel}\n                placeholder={language.address1Placeholder}\n                className=\"templateInput\"\n                id=\"address\"\n                onChange={onChange}\n                value={user.address}\n                errors={errors.address}\n              />\n            </div>\n\n            <div className=\"col-sm-12\" style={{marginBottom: 25}}>\n              <TextInput\n                type=\"text\"\n                name=\"address1\"\n                placeholder={language.address2Placeholder}\n                className=\"templateInput\"\n                id=\"address\"\n                onChange={onChange}\n                value={user.address1}\n                errors=\"\"\n              />\n            </div>\n\n            <div className=\"col-sm-12\">\n              <TextInput\n                type=\"text\"\n                name=\"address2\"\n                placeholder={language.address3Placeholder}\n                className=\"templateInput\"\n                id=\"address\"\n                onChange={onChange}\n                value={user.address2}\n                errors=\"\"\n              />\n            </div>\n\n              <div className=\"col-sm-3\">\n              <SelectInput name=\"country\"\n                           label={language.selectCountryLabel}\n                           onChange={onChange}\n                           options={countries}\n                           className=\"templateInput selectField\"\n                           defaultOption={language.selectCountry}\n                           value={user.country}\n                           errors={errors.country}\n                           />\n                </div>\n\n            <div className=\"col-sm-3\">\n\n              <TextInput\n                type=\"text\"\n                name=\"zipcode\"\n                label={language.zipcodeLabel}\n                placeholder={language.zipcodeLabel}\n                className=\"templateInput\"\n                id=\"zipcode\"\n                onChange={onChange}\n                value={user.zipcode}\n                errors={errors.zipcode}\n              />\n            </div>\n            <div className=\"col-sm-6\">\n              <TextInput\n                type=\"text\"\n                name=\"place\"\n                label={language.placeLabel}\n                placeholder={language.placeLabel}\n                className=\"templateInput\"\n                id=\"place\"\n                onChange={onChange}\n                value={user.place}\n                errors={errors.place}\n              />\n            </div>\n          </div>\n          <div className=\"clearfix\"></div>\n          <div className=\"col-lg-12\" style={{marginLeft: 15, marginTop: 30}}>\n            <Button onClick={onButtonClick.bind(this)}\n                    name=\"stepOneNext\"\n                    value={language.btnNext}\n                    icon=\"arrow-circle-right\"\n                    style={{margin: '0 auto 60px'}}/>\n          </div>\n        </div>\n      </form>\n    </div>\n  );\n};\n\nexport default RegistrationFormStepOne;\n\nI try to add some simple validation and I've added validation function in my main component and then I check on button click if the returned value true or false is. If it's true, than I set step state to a appropriate value. And it works if I validate only the form fields of the first step, but when I try to also validate one or more form fields of the next step (now I'm trying to validate also the first field of the second step)\nif(!user.firstName){\n        formIsValid = false;\n        errors.firstName = languageReg.firstnameEmpty;\n    }\n\nI get than \nWarning: TextInput is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.\nWithout the validation function works everything perfect.\nAny advice?\nEDIT\n    import React, {propTypes} from 'react';\nimport _ from 'lodash';\n\nconst TextInput = ({errors, style, name, labelClass, label, className, placeholder, id, value, onChange, type}) => {\n  let wrapperClass = \"form-group\";\n\n  if (errors) {\n    wrapperClass += \" \" + \"inputHasError\";\n  }\n\n  return (\n    <div className={wrapperClass} style={style}>\n      <label htmlFor={name} className={labelClass}>{label}</label>\n      <input type={type}\n             className={className}\n             placeholder={placeholder}\n             name={name}\n             id={id}\n             value={value}\n             style={{}}\n             onChange={onChange}\n      />\n      <div className=\"errorBox\">{errors}</div>\n    </div>\n  );\n};\n\nTextInput.propTypes = {\n  name: React.PropTypes.string.isRequired,\n  label: React.PropTypes.string,\n  onChange: React.PropTypes.func.isRequired,\n  type: React.PropTypes.string.isRequired,\n  id: React.PropTypes.string,\n  style: React.PropTypes.object,\n  placeholder: React.PropTypes.string,\n  className: React.PropTypes.string,\n  labelClass: React.PropTypes.string,\n  value: React.PropTypes.string,\n  errors: React.PropTypes.string\n};\n\nexport default TextInput;\n\nThis is second step component : \nimport React from 'react';\nimport Button from '../../common/formElements/button';\nimport RegistrationFormHeader from './registrationFormHeader';\nimport TextInput from '../../common/formElements/textInput';\n\n\nconst RegistrationFormStepTwo = ({user, onChange, onButtonClick, onButtonPreviousClick, errors, currentLanguage}) => {\n    const language = currentLanguage;\n\n    return (\n        <div className=\"contact_form\">\n            <form role=\"form\" action=\"\" method=\"post\" id=\"contact_form\">\n                <div className=\"row\">\n                    <RegistrationFormHeader activeTab={1} currentLanguage={language}/>\n                    <div className=\"hideOnBigScreens descBox\">\n                        <div className=\"headerTitle\">{language.personalInfoConfig}</div>\n                        <div className=\"titleDesc\">{language.personalBoxDesc}</div>\n                    </div>\n                    <div className=\"col-lg-12\">\n                        <h6 className=\"registrationFormDesc col-lg-10 col-lg-offset-1 col-lg-offset-right-2 col-xs-12\">\n                            {language.personalDesc}\n                        </h6>\n                        <div className=\"col-lg-6 col-md-6 col-sm-6 col-xs-12\">\n                            <TextInput\n                                type=\"text\"\n                                name=\"firstName\"\n                                label={language.firsnameLabel}\n                                placeholder={language.firsnameLabel}\n                                className=\"templateInput\"\n                                id=\"name\"\n                                onChange={onChange}\n                                value={user.firstName}\n                                errors={errors.firstName}\n                            />\n                        </div>\n                        <div className=\"col-lg-6 col-md-6 col-sm-6 col-xs-12\">\n                            <TextInput\n                                type=\"text\"\n                                name=\"lastName\"\n                                label={language.lastnameLabel}\n                                placeholder={language.lastnameLabel}\n                                className=\"templateInput\"\n                                id=\"name\"\n                                onChange={onChange}\n                                value={user.lastName}\n                                errors={errors.lastName}\n                            />\n                        </div>\n\n                        <div className=\"col-lg-6 col-md-6 col-sm-6 col-xs-12\">\n                            <TextInput\n                                type=\"text\"\n                                name=\"phone\"\n                                label={language.phoneLabel}\n                                placeholder={language.phoneLabel}\n                                className=\"templateInput\"\n                                id=\"phone\"\n                                onChange={onChange}\n                                value={user.phone}\n                                errors={errors.phone}\n\n                            />\n                        </div>\n\n                        <div className=\"col-lg-6 col-md-6 col-sm-6 col-xs-12\">\n                            <TextInput\n                                type=\"text\"\n                                name=\"mobilePhone\"\n                                label={language.mobileLabel}\n                                placeholder={language.mobileLabel}\n                                className=\"templateInput\"\n                                id=\"phone\"\n                                style={{}}\n                                onChange={onChange}\n                                value={user.mobilePhone}\n                                errors={errors.mobilePhone}\n                            />\n                        </div>\n                        <div className=\"clearfix\"></div>\n\n                        <div className=\"col-lg-12 col-md-12 col-sm-12 col-xs-12\">\n                            <TextInput\n                                type=\"text\"\n                                name=\"email\"\n                                id=\"email\"\n                                label={language.emailLabel}\n                                placeholder={language.emailLabel}\n                                className=\"templateInput\"\n                                style={{}}\n                                onChange={onChange}\n                                value={user.email}\n                                errors={errors.email}\n                            />\n                        </div>\n\n                        <div className=\"col-lg-12 col-md-12 col-sm-12 col-xs-12\">\n                            <TextInput\n                                type=\"text\"\n                                name=\"userName\"\n                                label={language.usernameLabel}\n                                placeholder={language.usernameLabel}\n                                className=\"templateInput\"\n                                id=\"name\"\n                                onChange={onChange}\n                                value={user.userName}\n                                errors={errors.userName}\n                            />\n                        </div>\n\n                        <div className=\"col-lg-6 col-md-6 col-sm-6 col-xs-12\">\n                            <TextInput\n                                type=\"password\"\n                                name=\"password\"\n                                label={language.passwordLabel}\n                                placeholder={language.passwordLabel}\n                                className=\"templateInput\"\n                                id=\"password\"\n                                onChange={onChange}\n                                value={user.password}\n                                errors={errors.password}\n                            />\n                        </div>\n                        <div className=\"col-lg-6 col-md-6 col-sm-6 col-xs-12\">\n                            <TextInput\n                                type=\"password\"\n                                name=\"confirmPassword\"\n                                label={language.passwordConfirmLabel}\n                                placeholder={language.passwordConfirmLabel}\n                                className=\"templateInput\"\n                                id=\"password\"\n                                onChange={onChange}\n                                value={user.confirmPassword}\n                                errors={errors.confirmPassword}\n                            />\n                        </div>\n\n                    </div>\n                    <div className=\"clearfix\"></div>\n                    <div className=\"col-lg-6 col-xs-6\" style={{marginTop: 30}}>\n                        <Button onClick={onButtonPreviousClick}\n                                name=\"btnPrevious\"\n                                value={language.btnPrevious}\n                                icon=\"arrow-circle-left\"\n                                style={{marginRight: 10, float: 'right'}}/>\n                    </div>\n                    <div className=\"col-lg-6 col-xs-6\" style={{marginTop: 30}}>\n                        <Button onClick={onButtonClick} name=\"stepTwoNext\" value={language.btnNext}\n                                icon=\"arrow-circle-right\" style={{marginLeft: 10, float: 'left'}}/>\n                    </div>\n                </div>\n            </form>\n        </div>\n\n    );\n};\n\nexport default RegistrationFormStepTwo;\n\n\nA: This is why the warning exists: When the value is specified as undefined, React has no way of knowing if you intended to render a component with an empty value or if you intended for the component to be uncontrolled. It is a source of bugs. \nYou could do a null/undefined check, before passing the value to the input.\na source\n\nA: @Kokovin Vladislav is right. To put this in code, you can do this in all your input values:\n<TextInput\n    // your other code\n    value={user.firstName || ''}\n/>\n\nThat is, if you don't find the value of first name, then give it an empty value.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/38014397", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "6"}}
{"text": "Q: Interleaving the rows of two different SQL tables, group by one row My Sql query is like this\n$view =  mysql_query (\"SELECT domain,count(distinct session_id) as \n         views FROM `statistik` left join statistik_strippeddomains on \n         statistik_strippeddomains.id = statistik.strippeddomain WHERE\n         `angebote_id` = '\".(int)$_GET['id'].\"' and strippeddomain!=1 \n         group by domain having count (distinct session_id) >\n         \".(int)($film_daten['angebote_views']/100).\"  order \n         count(distinct session_id$vladd) desc limit 25\");\n\nHow can I write its Codeigniter Model I appreciate any Help\n\nA: try this\n$this->db->select('statistik.domain,statistik.count(DISTINCT(session_id)) as views');\n$this->db->from('statistik');\n$this->db->join('statistik_strippeddomains', 'statistik_strippeddomains.id = statistik.strippeddomain', 'left'); \n$this->db->where('angebote_id',$_GET['id']);\n$this->db->where('strippeddomain !=',1);\n$this->db->group_by('domain');\n$this->db->having('count > '.$film_daten['angebote_views']/100, NULL, FALSE);\n$this->db->order_by('count','desc');\n$this->db->limit('25');\n$query = $this->db->get();\n\nComment me If you have any query.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/39852573", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Query conditions to insert data from a form What I'm trying to do is: \nIf the age input in my form = 28, 30, 25 or 21 then I want to auto insert value 8 in the column (VE), else keep it empty. Is this the right way to do that?\nif($form_data->action == 'Insert')\n        {\n\n            $age=array(28, 30, 25, 21);\n            $age_str=implode(\"','\", $age);\n\n                if($form_data->age == $age_str){\n\n                $query=\"INSERT INTO tbl\n                        (VE) VALUE ('8') WHERE id= '\".$form_data->id.\"'\n                \";\n                    $statement = $connect->prepare($query);\n                    $statement->execute();\n            }\n            $data = array(\n                ':date'             =>  $date,\n                ':first_name'       =>  $first_name,\n                ':last_name'        =>  $last_name,\n                ':age'          =>  $age\n            );\n            $query = \"\n            INSERT INTO tbl\n                (date, first_name, last_name, age) VALUES \n                (:date, :first_name, :last_name, :age)\n            \";\n            $statement = $connect->prepare($query);\n\n\n            if($statement->execute($data))\n            {\n                $message = 'Data Inserted';\n            }\n        }\n\n\n\nAlso, how do I insert the new row with the row id from the other form data going into tbl?\n\nA: Use php's in_array instead of trying to compare a string. To get the id of the query where you insert the form data, you can return the id of the insert row from your prepared statement.\nif ($form_data->action == 'Insert') {\n\n    // assuming $age, $date, $first_name, $last_name\n    // already declared prior to this block\n    $data = array(\n      ':date'             =>  $date,\n      ':first_name'       =>  $first_name,\n      ':last_name'        =>  $last_name,\n      ':age'          =>  $age\n    );\n\n    $query = \"\n      INSERT INTO tbl\n        (date, first_name, last_name, age) VALUES \n        (:date, :first_name, :last_name, :age)\n    \";\n    $statement = $connect->prepare($query);\n\n    if ($statement->execute($data)) {\n        $message = 'Data Inserted';\n\n        // $id is the last inserted id for (tbl)\n        $id = $connect->lastInsertID();\n\n        // NOW you can insert your child row in the other table\n        $ages_to_insert = array(28, 30, 25, 21);\n\n        // in_array uses your array...so you don't need\n        // if($form_data->age == $age_str){\n\n        if (in_array($form_data->age, $ages_to_insert)) {\n\n            $query=\"UPDATE tbl SER VE = '8' WHERE id= '\".$id.\"'\";\n            $statement2 = $connect->prepare($query);\n            $statement2->execute();\n        }\n    }\n}\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/58903757", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Is the function $\\ln(ax + b)$ increasing/decreasing, concave/convex? $h(x) = \\ln(ax + b)$ \nNB. Examine your results acccording to values of $(a,b)$\nI've differentiated twice in order to get the following:\n$$\nh''(x) = -\\frac{a^2}{(ax+b)^2}\n$$\nI think this proves that $h(x)$ is concave for all value of $a$ and $b$ since $h''(x)\\le0$. Is this correct?\nI don't know how to prove whether it's increasing/decreasing or what the NB really means so any help with that would be great.\n\nA: we now that the domain of the function is:\n$$ax+b\\gt 0\\Rightarrow x\\gt\\frac{-b}{a}\\text{so the domain is:}(\\frac{-b}{a},+\\infty)$$\n$$f'(x)=\\frac{a}{ax+b}$$\nin the domain of the function since we have $x\\gt\\frac{-b}{a}\\Rightarrow ax+b>0 $ the sign of $f'(x)=\\frac{a}{ax+b}$ will be dependent to the sign of $a$ so:\nif $a\\gt 0\\Rightarrow f'(x)\\gt 0$ and $f(x)$ will be increasing in its domain\nif $a\\lt 0\\Rightarrow f'(x)\\lt 0$ and $f(x)$ will be decreasing in its domain\nNote the phrases in its domain in the above expression, we always study the behaviors of functions in their domain\n$$f''(x)=\\frac{-a^2}{(ax+b)^2}$$\nas you said without we always have $f''(x)<0$ so without considering the sign of $a$, $f(x)$ will be a convex function\nThe value of $b$ doesnot influence the first and second derivation and so will not affect concavity, convexity, increase or decrease of the function \nhere is the diagram for $f(x)=\\ln(2x+1)$ as you see $a=2\\gt 0$ and $f(x)$ is increasing and convex\n \nhere is the diagram for $f(x)=\\ln(-2x+1)$ as you see $a=-2\\lt 0$ and $f(x)$ is decreasing and convex\n\n\nA: $$h^{ \\prime  }\\left( x \\right) =\\frac { a }{ ax+b } >0$$\n$1$.if  $a>0$   $ax+b>0$  $\\Rightarrow $ $ax>-b$ $\\Rightarrow $ $x>-\\frac { b }{ a } $ function is increasing\n$2$.if   $a<0 $ $x<-\\frac { b }{ a } $ function is decreasing\nAnd about concavity you are right,find second derivative and check intervals\n", "meta": {"language": "en", "url": "https://math.stackexchange.com/questions/1400530", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Accessing array value is null Hello I have decoded a json string that I sent to my server and Im trying to get the values from him.\nMy problem is that I cant get the values from the inner arrays.\nThis is my code:\n<?php\n\n    $post = file_get_contents('php://input');\n\n    $arrayBig = json_decode($post, true);\n\n    foreach ($arrayBig as $array)\n    {\n\n\n    $exercise = $array['exercise'];\n\n    $response[\"exercise\"] = $exercise;\n    $response[\"array\"] = $array;\n\n    echo json_encode($response);\n\n\n    }\n\n?>\n\nWhen I get the answer from my $response I get this values:\n{\"exercise\":null,\"array\":[{\"exercise\":\"foo\",\"reps\":\"foo\"}]}\n\nWhy is $array['exercise'] null if I can see that is not null in the array\nThanks.\n\nA: Because of the [{...}] you are getting an array in an array when you decode your array key.\nSo:\n$exercise = $array['exercise'];\n\nShould be:\n$exercise = $array[0]['exercise'];\n\nSee the example here.\n\nA: From looking at the result of $response['array'], it looks like $array is actually this\n[['exercise' => 'foo', 'reps' => 'foo']]\n\nthat is, an associative array nested within a numeric one. You should probably do some value checking before blindly assigning values but in the interest of brevity...\n$exercise = $array[0]['exercise'];\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/21893968", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Composer update show this error: VirtualAlloc() failed: [0x00000008] Composer worked find yesterday, but today after I trying install:\ncomposer require --prefer-dist \"himiklab/yii2-recaptcha-widget\" \"*\"\nWhile run composer update command it show me error:\n\nVirtualAlloc() failed: [0x00000008] VirtualAlloc() failed:\n[0x00000008] PHP Fatal error:  Out of memory (allocated 956301312)\n(tried to allocate 201326600 bytes) in\nphar://C:/ProgramData/ComposerSetup/bin/composer.phar/src/Composer/DependencyResolver/RuleSet.php\non line 84\nFatal error: Out of memory (allocated 956301312) (tried to allocate\n201326600 bytes) in\nphar://C:/ProgramData/ComposerSetup/bin/composer.phar/src/Composer/DependencyResolver/RuleSet.php\non line 84\n\nI try update composer on my other projects, it is worked fine. After some researching I increased memory_limit: 4096M(also -1) in php.ini file. Then I tried to increase virtual memory in Computer->Properties, but still show error.\nI try to run next command:\ncomposer update -vvv --profile, result in attached image\nComposer error\nAny help would be greatly appreciated.\n\nA: You are probably using 32bit PHP. This version cannot allocate enough memory for composer even if you change the memory_limit to -1 (unlimited).\nPlease use 64 bit PHP with the Composer to get rid of these memory problems.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/49994946", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}}
{"text": "Q: How do I get the original values of in an Update SQL Trigger I'm not very familiar with triggers so thank you for your patience.\nI have a database table with four columns for user text input and just four date columns showing when the user text input was last changed. What I want the trigger to do is to compare the original and new values of the user text input columns and if they are different update the date column with getdate(). I don't know how to do this. The code I wrote can't get the pre-update value of the field so it can't be compared to the post-update value. Does anyone know how to do it?\n(Normally I would do this in a stored procedure. However this database table can also be directly edited by an Access database and we can't convert those changes to use the stored procedure. This only leaves us with using a trigger.)\n\nA: In sql server there are two special tables availble in the trigger called inserted and deleted. Same structure as the table on which the trigger is implemented. \ninserted has the new versions, deleted the old.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/10453001", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "3"}}
{"text": "Q: Create Executable progeam of addition in C on linux I am new to Linux. Sorry I am asking very basic question. On windows I have Main.cpp file having code for addition of two number. In Visual studio gives me .exe. But how to do it on Linux. On my Linux machine have gcc compiler no IDE.\nWhat I write in Make file and how to run. \nMain.cpp has code like\n#include <stido.h>\n#include <conio.h>\n// Static library file included\n//#include \"Add.h\"\nint main()\n{\n    int a,b,c;\n\n    a = 10;\n    b = 20;\n\n    c= a+b;\n    //Add function in static lib (.a in case of linux)\n    //c= Add(a,b);\n    printf(\"Addition is :%d\",c);\n\n\n    return 0;\n}\n\nAfter that I want use Add function which is in Addition. How to use with above program removing commented in code?\n\nA: For c++ code, the command is usually something like:\ng++ Main.cpp -o FileNameToWriteTo\n\nAlternatively, if you just run\ng++ Main.cpp\n\nit will output to a default file called a.out.\nEither way, you can then run whichever file you created by doing:\n./FileNameToWriteTo.out\n\nSee this for more details: http://pages.cs.wisc.edu/~beechung/ref/gcc-intro.html\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/39793206", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-3"}}
{"text": "Q: QProgressBar updates as function progress How to initializa the operation of QProgressBar, I already declare her maximum, minimum, range and values.\nI want to assimilate the progress of QProgressBar with the \"sleep_for\" function.\nCurrent code:\nvoid MainPrograma::on_pushCorre_clicked()\n{\n    QPlainTextEdit *printNaTela = ui->plainTextEdit;\n    printNaTela->moveCursor(QTextCursor::End);\n    printNaTela->insertPlainText(\"corrida iniciada\\n\");\n\n    QProgressBar *progresso = ui->progressBar;\n    progresso->setMaximum(100);\n    progresso->setMinimum(0);\n    progresso->setRange(0, 100);\n    progresso->setValue(0);\n    progresso->show();\n\n    WORD wEndereco = 53606;\n    WORD wValor = 01;\n    WORD ifValor = 0;\n    EscreveVariavel(wEndereco, wValor);\n\n\n//How to assimilate QProgressBar to this function:\nstd::this_thread::sleep_for(std::chrono::milliseconds(15000));\n//StackOverFlow help me please\n\n\n    EscreveVariavel(wEndereco, ifValor);\n\n\nA: use a QTimer\nand in the slot update the value of the progressbar\nMainWindow::MainWindow(QWidget *parent) :\n    QMainWindow(parent),\n    ui(new Ui::MainWindow)\n{\n    ui->setupUi(this);\n    t = new QTimer(this);\n    t->setSingleShot(false);\n    c = 0;\n    connect(t, &QTimer::timeout, [this]()\n    {   c++;\n        if (c==100) {\n            c=0;\n        }\n        qDebug() << \"T...\";\n        ui->progressBar->setValue(c);\n    });\n}\n\nMainWindow::~MainWindow()\n{\n    delete ui;\n}\n\nvoid MainWindow::on_pushButton_clicked()\n{\n    t->start(100);\n}\n\n\nA: I'm not sure about your intentions with such sleep: are you simulating long wait? do you have feedback about progress during such process? Is it a blocking task (as in the example) or it will be asynchronous?\nAs a direct answer (fixed waiting time, blocking) I think it is enough to make a loop with smaller sleeps, like:\nEscreveVariavel(wEndereco, wValor);\nfor (int ii = 0; ii < 100; ++ii) {\n   progresso->setValue(ii);\n   qApp->processEvents(); // necessary to update the UI\n   std::this_thread::sleep_for(std::chrono::milliseconds(150));\n}\nEscreveVariavel(wEndereco, ifValor);\n\nNote that you may end waiting a bit more time due to thread scheduling and UI refresh.\nFor an async task you should pass the progress bar to be updated, or some kind of callback that does such update. Keep in mind that UI can only be refreshed from main thread.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/64987457", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Preallocation and Vectorization Speedup I am trying to improve the speed of script I am trying to run.\nHere is the code: (my machine = 4 core win 7)\nclear y;\nn=100;\nx=linspace(0,1,n);\n% no y pre-allocation using zeros\nstart_time=tic;\n\nfor k=1:n,\n    y(k) =  (1-(3/5)*x(k)+(3/20)*x(k)^2 -(x(k)^3/60)) / (1+(2/5)*x(k)-(1/20)*x(k)^2);\nend\n\nelapsed_time1 = toc(start_time);\nfprintf('Computational time for serialized solution: %f\\n',elapsed_time1);\n\nAbove code gives 0.013654 elapsed time.\nOn the other hand, I was tried to use pre-allocation by adding y = zeros(1,n); in the above code where the comment is but the running time is similar around ~0.01. Any ideas why? I was told it would improve by a factor of 2. Am I missing something?\nLastly is there any type of vectorization in Matlab that will allow me to forget about the for loop in the above code?\nThanks,\n\nA: In your code: try with n=10000 and you'll see more of a difference (a factor of almost 10 on my machine).\nThese things related with allocation are most noticeable when the size of your variable is large. In that case it's more difficult for Matlab to dynamically allocate memory for that variable.\n\nTo reduce the number of operations: do it vectorized, and reuse intermediate results to avoid powers:\ny = (1 + x.*(-3/5 + x.*(3/20 - x/60))) ./ (1 + x.*(2/5 - x/20));\n\nBenchmarking:\nWith n=100:\nParag's / venergiac's solution:\n>> tic\nfor count = 1:100\ny=(1-(3/5)*x+(3/20)*x.^2 -(x.^3/60))./(1+(2/5)*x-(1/20)*x.^2);\nend\ntoc\nElapsed time is 0.010769 seconds.\n\nMy solution:\n>> tic\nfor count = 1:100\ny = (1 + x.*(-3/5 + x.*(3/20 - x/60))) ./ (1 + x.*(2/5 - x/20));\nend\ntoc\nElapsed time is 0.006186 seconds.\n\n\nA: You don't need a for loop. Replace the for loop with the following and MATLAB will handle it.\ny=(1-(3/5)*x+(3/20)*x.^2 -(x.^3/60))./(1+(2/5)*x-(1/20)*x.^2);\n\nThis may give a computational advantage when vectors become larger in size. Smaller size is the reason why you cannot see the effect of pre-allocation. Read this page for additional tips on how to improve the performance.\nEdit: I observed that at larger sizes, n>=10^6, I am getting a constant performance improvement when I try the following:\nx=0:1/n:1;\n\ninstead of using linspace. At n=10^7, I gain 0.05 seconds (0.03 vs 0.08) by NOT using linspace. \n\nA: try operation element per element (.*, .^)\nclear y;\nn=50000;\nx=linspace(0,1,n);\n% no y pre-allocation using zeros\nstart_time=tic;\n\nfor k=1:n,\n    y(k) =  (1-(3/5)*x(k)+(3/20)*x(k)^2 -(x(k)^3/60)) / (1+(2/5)*x(k)-(1/20)*x(k)^2);\nend\n\nelapsed_time1 = toc(start_time);\nfprintf('Computational time for serialized solution: %f\\n',elapsed_time1);\n\nstart_time=tic;\ny =  (1-(3/5)*x+(3/20)*x.^2 -(x.^3/60)) / (1+(2/5)*x-(1/20)*x.^2);\n\nelapsed_time1 = toc(start_time);\nfprintf('Computational time for product solution: %f\\n',elapsed_time1);\n\nmy data\n\nComputational time for serialized solution: 2.578290\nComputational time for serialized solution: 0.010060\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/21564052", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}}
{"text": "Q: Scala and Akka HTTP: Request inside a request & issue with threads I am new to learning Scala, Akka Streams and Akka HTTP, so apologies beforehand if the question is too basic.\nI want to do an HTTP request inside an HTTP request, just like in the following piece of code:\n  implicit val system = ActorSystem(\"ActorSystem\")\n  implicit val materializer = ActorMaterializer\n  import system.dispatcher\n\n  val requestHandler: Flow[HttpRequest, HttpResponse, _] = Flow[HttpRequest].map {\n    case HttpRequest(HttpMethods.GET, Uri.Path(\"/api\"), _, _, _) =>\n      val responseFuture = Http().singleRequest(HttpRequest(uri = \"http://www.google.com\"))\n      responseFuture.onComplete {\n        case Success(response) =>\n          response.discardEntityBytes()\n          println(s\"The request was successful\")\n        case Failure(ex) =>\n          println(s\"The request failed with: $ex\")\n      }\n      //Await.result(responseFuture, 10 seconds)\n      println(\"Reached HttpResponse\")\n      HttpResponse(\n        StatusCodes.OK\n      )\n  }\n\n  Http().bindAndHandle(requestHandler, \"localhost\", 8080)  \n\nBut in the above case the result looks like this, meaning that Reached HttpResponse is reached first before completing the request:\nReached HttpResponse\nThe request was successful\n\nI tried using Await.result(responseFuture, 10 seconds) (currently commented out) but it made no difference.\nWhat am I missing here? Any help will be greatly appreciated!\nMany thanks in advance!\n\nA: map is a function that takes request and produces a response:\nHttpRequest => HttpResponse\n\nThe challenge is that response is a type of Future. Therefore, you need a function that deals with it. The function that takes HttpRequest and returns Future of HttpResponse.\nHttpRequest => Future[HttpResponse]\n\nAnd voila, mapAsync is exactly what you need:\nval requestHandler: Flow[HttpRequest, HttpResponse, _] = Flow[HttpRequest].mapAsync(2) {\n  case HttpRequest(HttpMethods.GET, Uri.Path(\"/api\"), _, _, _) =>\n    Http().singleRequest(HttpRequest(uri = \"http://www.google.com\")).map (resp => {\n      resp.discardEntityBytes()\n      println(s\"The request was successful\")\n      HttpResponse(StatusCodes.OK)\n    })\n}\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/61038711", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "5"}}
{"text": "Q: Initial Boundary Value Problem for a Wave Equation $u_{tt}=4u_{xx}$ Solve the initial boundary value problem:\n\\begin{equation} \\begin{aligned} \nu_{tt} &= 4u_{xx} \\quad   x > 0, \\, t > 0 \\\\\nu(x, 0) &= x^2/8, \\\\ \nu_t(x, 0) &= x \\quad  x \u2265 0 \\\\\nu(0,t) &= t^2, \\quad t \u2265 0.\\end{aligned} \\end{equation}\nThis question is from here. Seeing that that question is not active, how would we approach this?\n", "meta": {"language": "en", "url": "https://math.stackexchange.com/questions/4581378", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Dealing with four digits: memcache sorts 1000 before 150 from least to greatest In app engine I retrieve a list of items stored in memcache:\nitems = memcache.get(\"ITEMS\")\n\nand sort them by amount and price:\nitems.sort(key = lambda x:(x.price, x.amount))\n\nWhich works most of the time, when the amount is three digits. However, when I have 2 items with 150 and 1000 amounts for the same price, the entry with 1000 goes before other one. How can I fix this?\n\nA: fixed it: \nitems.sort(key = lambda x:((float)(x.price), (int)(x.amount)))\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/21960862", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Do codigniter 3.1.7 support hmvc? I tried but no luck From the very first answer of this \nHow to implement HMVC in codeigniter 3.0? I tried all steps with codigniter 3.7.1 but no luck. I am still getting 404.\n$config['modules_locations'] = array(\n    APPPATH.'modules/' => '../modules/',\n);\n\nThen I tried putting the above code in application/config/config.php but still 404\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/48606954", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Saving time - Compiling c++ and plotting at the same time gnuplot Hi in order to save time whene I execute the code I command this line :\ng++ name.cpp && ./a.out \n\nwhere nome,cpp is the name of the file that contains the code. If I succesively I need to plot some data generated by the exucatable with Gnuplot there is a way to add in the previous line instead of writing:\ngnuplot\nplot \"name2.dat\" \n\n?\n\nA: you can:\ng++ name.cpp && ./a.out && gnuplot -e \"plot 'name2.dat'; pause -1\"\n\ngnuplot exits when you hit return (see help pause for more options)\nif you want to start an interactive gnuplot session there is a dirty way I implemented.\ng++ name.cpp && ./a.out && gnuplot -e \"plot 'name2.dat' -\n\n(pay attention to the final minus sign)\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/50157509", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-1"}}
{"text": "Q: How to put a Hyphen in column Total Cost Value in power bi I have a table with blank value, but i want a hyphen \"-\" to appear when the value is null.\nUsing an expression similar to this:\nvar VLGROUP =\n(Expression\u2026\u2026\nRETURN\nIF(\nISBLANK(VLGROUP),\nBLANK(),\nVLGROUP)\nSomeone know if is possible?\nThanks!!\nenter image description here\ngur.com/C0u8s.png\n\n\n\nA: Try this below option-\nSales for the Group = \n\nvar sales =\n    CALCULATE( \n        SUM(Financialcostcenter[amount]), \n        Financialcostcenter[partnercompany]= \"BRE\", \n        Financialcostcenter[2 digits]=71, \n        DATESYTD('Datas'[Date])\n    ) \n    + \n    CALCULATE( \n        SUM(Financialcostcenter[amount]), \n        Financialcostcenter[partnercompany]= \"GRM\", \n        Financialcostcenter[2 digits]=71, \n        DATESYTD('Datas'[Date])\n    ) \n\n\nRETURN IF(sales = BLANK(),\"-\", -(sales))\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/63953889", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Part time job at the vegetable/fruits shop. You recently applied for a job at the vegetable/fruits store and the shop owner called you for a small quiz.so you went there and everything was going apparently well\u2026 but then he asked you that since his favourite number is 10 and his favourite fruit is orange so he wants to make a pyramid of oranges where the triangle on the base is an equilateral triangle made having 10 oranges on each side, then the total number of oranges in the complete pyramid will be??\nNote-this is a homework question from sequences and series  and not something I picked from a puzzle book\u2026 I tried solving it but I am not able to visualise it properly so I am not able to get the correct answer.\n\nA: Triangle on base will have (1 + 2 + 3 + 4+ ... +10)\nNext one will have as above but only to 9 - and so on until you only have 1 at the top\nI have deliberately not done the entire calculation for you - if you are still confused after this attempt to help you visualize it, add a comment and I will clarify more\n\nA: Here is how I visualise it. Triangle on base will have ( 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 ) oranges and the next one will have ( 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 ). \nSo the total amount will be : 10*1 + 9*2 + 8*3 + 7*4 + 6*5 + 5*6 + 4*7 + 3*8 + 2*9 + 1*10\n", "meta": {"language": "en", "url": "https://math.stackexchange.com/questions/1509492", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-1"}}
{"text": "Q: Constraints on an embedded subclass - Grails, GORM, Mongo I've been pulling my hair out with this issue for a couple of days.\nI have an embedded subclass with several specified constraints. My issue is that these constraints are never enforced,\nI'm using grails 2.3.11 and the mongodb plugin 3.0.2.\nHere is my setup (Simplified slightly).\nMedia class\nclass Media{\nObjectId id;\nString name;\nFilm film;\n\nstatic mapWith = \"mongo\"\nstatic embedded = [\"film\"]\n}\n\nFilm Class \nclass Film{\nObjectId id;\nString name;\n\nstatic mapWith = \"mongo\"\nstatic belongsTo = [media : Media]\nstatic mapping = {\n    lazy:false\n}\nstatic constraints = {\nname(nullable:false) //works as expected. Save fails if name is set to null\n}\n}\n\nActionFilm Class\nclass ActionFilm extends Film{\nint score;\nString director;\n\n//These constraints are never enforeced. No matter what value I set the fields to the save is always successful\nstatic constraints = {\nscore(min:50) \ndirector(nullable:true)\n}\n}\n\nIs this an issue with Mongo and Gorm? Is it possible to have contraints in bth a parent and subclass? \nExample code when saving\npublic boolean saveMedia(){\nActionFilm film = new ActionFilm()\nfilm.setName(\"TRON\");\nfilm.setScore(2)\nfilm.setDirector(\"Ted\")\n\nMedia media = new Media()\nmedia.setName(\"myMedia\")\nmedia.setFilm(film)\nmedia.save(flush:true, failOnError:false)  //Saves successfully when it shouldn't as the score is below the minimum constrains\n\n}\nEdit\nI've played aroubd some more and the issue only persits when I'm saving the Media object with ActionFilm as an embedded object. If I save the ActionFilm object the validation is applied.\n ActionFilm film = new ActionFilm()\n    film.setName(\"TRON\");\n    film.setScore(2)\n    film.setDirector(\"Ted\")\n    film.save(flush:true, failOnError:false)  //Doesn't save as the diameter is wrong. Expected behaviour.\n\nSo the constraints are applied as expected when I save the ActionFilm object but aren't applied if its an embedded object. \n\nA: I've solved my issue in case anyone else comes across this. It may not be the optimal solution but I haven't found an alternative.\nI've added a custom validator to the  Media class that calls validate() on the embedded Film class and adds any errors that arise to the Media objects errors\nclass Media{\nObjectId id;\nString name;\nFilm film;\n\nstatic mapWith = \"mongo\"\nstatic embedded = [\"film\"]\n\n    static constraints = {\n            film(validator : {Film film, def obj, def errors ->\n                boolean valid = film.validate()\n                if(!valid){\n                    film.errors.allErrors.each {FieldError error ->\n                        final String field = \"film\"\n                        final String code = \"$error.code\"\n                        errors.rejectValue(field,code,error.arguments,error.defaultMessage )\n                    }\n                }\n                return valid\n            }\n            )\n        }\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/26994126", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: MySQL -> PHP Array -> Json need output in array plus object format i am trying to fetch data from MySQL and show it in JSON format\nThis is the partial PHP code\n$sql = \"SELECT item, cost, veg, spicy_level FROM food1\";\n$result = $conn->query($sql);\n\n    while($row = $result->fetch_assoc()) {\n\n    echo  json_encode($row),\"<br/>\";}\n\n?>\ni am getting output as \n{\"item\":\"dosa\",\"cost\":\"20\",\"veg\":\"0\",\"spicy_level\":\"1\"}\n{\"item\":\"idli\",\"cost\":\"20\",\"veg\":\"0\",\"spicy_level\":\"2\"}\n\nbut i need it as\nfood1:[\n{\"item\":\"dosa\",\"cost\":\"20\",\"veg\":\"0\",\"spicy_level\":\"1\"},\n{\"item\":\"idli\",\"cost\":\"20\",\"veg\":\"0\",\"spicy_level\":\"2\"}\n]\n\ncan anyone please guide me?\ni think what i am getting is in object format and i need output in array format i.e. with [ & ].\nvery new to this json and php.\n\nA: You can incapsulate query results in array and after print it;\n$sql = \"SELECT item, cost, veg,     spicy_level FROM food1\";\n$result = $conn->query($sql);\n$a = array();\nwhile($row = $result->fetch_assoc()) {\n  if($a['food1'] ==null)\n     $a['food1'] = array():\n  array_push($a['food1'],$row);}\n\n\n  echo json_encode($a);\n?></i>\n\n\nA: Your code should be :\n$sql = \"SELECT item, cost, veg, spicy_level FROM food1\";\n$result = $conn->query($sql);\n\n$food['food1'] = array();\n\nwhile($row = $result->fetch_assoc()) {\n    $food['food1'][] = $row;    \n}\n\necho  json_encode($food);\n\n\nA: Don't call json_encode each time through the loop. Put all the rows into an array, and then encode that.\n$food = array();\nwhile ($row = $result->fetch_assoc()) {\n    $food[] = $row;\n}\necho json_encode(array('food1' => $food));\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/28872111", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Find a relation between a,b and c $ a,b,c\\in \\Bbb R$\n$2x_1+2x_2+3x_3=a$\n$3x_1-x_2+5x_3=b$\n$x_1-3x_2+2x_3=c$\nif  a,b and c is a solution of this linear equation system find the relation between a,b and c\nI dont understand the question. without knowing a,b and c is a solution of eq.syst. I found\n$$\n        \\begin{matrix}\n        2 & 2 & 3 &a \\\\\n        3 & -1 & 5&b \\\\\n        0 & 0 & 0 &a+c-b\\\\\n        \\end{matrix}\n$$\nand therefore $b=a+c$\nwhen I use a,b and c as a solution\n$2a+2b+3c=a$\n$3a-b+5c=b$\n$a-3b+2c=c$\nreduced row echolon form is \n$$\n        \\begin{matrix}\n        1 & 0 & 0  \\\\\n        0 & 1 & 0 \\\\\n        0 & 0 & 1 \\\\\n        \\end{matrix}\n$$\nit gives a=0 b=0 c=0\n", "meta": {"language": "en", "url": "https://math.stackexchange.com/questions/1410531", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Firebase hosting randomly shows \"Site Not Found\" at custom domain We recently launched our firebase application at https://tnb-widgets.firebaseapp.com/ and https://thenextbid.com/ (the last one being our custom domain). It all works smoothly except for some seemingly random moments in which it shows a page stating \"Site Not Found\". This already happened multiple times and after a couple of minutes the site seems to be back again.\nThe last time this happened was at 2:37AM GMT-5 and the last time I deployed a new release to this same firebase hosting project was at 3:45PM the day before. This release also contained 80 files in total, so it cannot possibly be \"an empty directory\".\nOur firebase.json file looks like this:\n{\n  \"firestore\": {\n    \"rules\": \"firestore.rules\",\n    \"indexes\": \"firestore.indexes.json\"\n  },\n  \"hosting\": {\n    \"public\": \"build\",\n    \"ignore\": [\n      \"firebase.json\",\n      \"**/.*\",\n      \"**/node_modules/**\"\n    ],\n    \"rewrites\": [\n      {\n        \"source\": \"/api/**\",\n        \"function\": \"app\"\n      },\n      {\n        \"source\": \"**\",\n        \"destination\": \"/index.html\"\n      }\n    ]\n  },\n  \"storage\": {\n    \"rules\": \"storage.rules\"\n  }\n}\n\nThere's no service workers registered. The \"build\" folder contains 80 files and most importantly it contains the \"index.html\" at its root.\nDoes anyone have similar issues? I would appreciate any idea to solve this! Thanks.\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/52877497", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "3"}}
{"text": "Q: Reduce Time for Checking Out Code in Visual Studio Online I'm trying out VSO and it's taking over 2 minutes to sync with a GitHub repository.  It appears that it's checking out the whole thing on every build.  I made sure that the \"clean\" box is unchecked but it had no effect. \nAny ideas on how to get it to cache the source or is this even possible in VSO?\n\nA: Each build in VSO uses a new VM that is spun up just for your build. Short \nof hosting your own Build Server connected your VSO, I don't think it can be avoided.\nUnless there are ways to speed up a the process of downloading the code from a git repo, I think you're stuck.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/31390786", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-2"}}
{"text": "Q: How to skip a line when reading from a file I am reading stuff from a file and this is the format : c stands for circle and the double is the radius, r for rectangle and the double is width and height respectively and t for triangle and the double represents side length:\nc 12\nc 2\nr 3 4\nc 2.4\nt 2.9\n3 c          // wrong format \nt 2.9\n10 r        // wrong format \n\nI run this code:\nifstream infile(names);\nwhile(infile >> names) {\n    if(names.at(0) == 'c') {           \n        double r;                     \n        infile >> r;\n        cout << \"radius = \" << r << endl;\n    } else if(names.at(0) == 'r') {    \n        double w;                     \n        double h;                      \n        infile >> w;\n        infile >> h;\n        cout << \"width = \" << w << \", height = \" << h << endl;\n    } else if(names.at(0) == 't') {    \n        double s;                      \n        infile >> s;\n        cout << \"side = \" << s << endl;\n    } else {\n        continue;\n    }\n}\n\ninfile.close()\n\nAnd this is the output: \nradius = 12\nradius = 2\nwidth = 3, height = 4\nradius = 2.4\nside = 2.9\nradius = 0\n\nI was wondering how I can skip the wrong format line. I have tried using geline but still no luck\nEDIT: radius, height, width and side have to be > 0\n\nA: The biggest potential problems you are running up against is the fact that you assume a line is valid if it begins with a c, t or r without first validating the remainder of the line matches the format for a circle, triangle or rectangle. While not fatal to this data set, what happens if one of the lines was 'cat' or 'turtle'?\nBy failing to validate all parts of the line fit the \"mold\" so to speak, you risk attempting to output values of r, h & w or s that were not read from the file. A simple conditional check of the read to catch the potential failbit or badbit will let you validate you have read what you think you read.\nThe remainder is basically semantics of whether you use the niceties of C++ like a vector of struct for rectangles and whether you use a string instead of char*, etc. However, there are certain benefits of using a string to read/validate the remainder of each line (or you could check the stream state and use .clear() and .ignore())\nPutting those pieces together, you can do something like the following. Note, there are many, many different approaches you can take, this is just one approach,\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\ntypedef struct {        /* simple typedef for vect of rectangles */\n    int width, height;\n} rect_t;\n\nint main (int argc, char **argv) {\n\n    vector<double> cir;     /* vector of double for circle radius */\n    vector<double> tri;     /* vector of double for triangle side */\n    vector<rect_t> rect;    /* vector of rect_t for rectangles */\n    string line;            /* string to use a line buffer */\n\n    if (argc < 2) { /* validate at least one argument given */\n        cerr << \"error: insufficient input.\\n\"\n                \"usage: \" << argv[0] << \" filename\\n\";\n        return 1;\n    }\n\n    ifstream f (argv[1]);   /* open file given by first argument */\n    if (!f.is_open()) {     /* validate file open for reading */\n        cerr << \"error: file open failed '\" << argv[1] << \"'.\\n\";\n        return 1;\n    }\n\n    while (getline (f, line)) {     /* read each line into 'line' */\n        string shape;               /* string for shape */\n        istringstream s (line);     /* stringstream to parse line */\n        if (s >> shape) {           /* if shape read */\n            if (shape == \"c\") {     /* is it a \"c\"? */\n                double r;           /* radius */\n                string rest;        /* string to read rest of line */\n                if (s >> r && !getline (s, rest))  /* radius & nothing else */\n                    cir.push_back(r);   /* add radius to cir vector */\n                else    /* invalid line for circle, handle error */\n                    cerr << \"error: invalid radius or unexpected chars.\\n\";\n            }\n            else if (shape == \"t\") {\n                double l;           /* side length */\n                string rest;        /* string to read rest of line */\n                if (s >> l && !getline (s, rest))  /* length & nothing else */\n                    tri.push_back(l);   /* add length to tri vector */\n                else    /* invalid line for triangle, handle error */\n                    cerr << \"error: invalid triangle or unexpected chars.\\n\";\n            }\n            else if (shape == \"r\") {    /* is it a rect? */\n                rect_t tmp;             /* tmp rect_t */\n                if (s >> tmp.width && s >> tmp.height)  /* tmp & nohtin else */\n                    rect.push_back(tmp);    /* add to rect vector */\n                else    /* invalid line for rect, handle error */\n                    cerr << \"error: invalid width & height.\\n\";\n            }\n            else    /* line neither cir or rect, handle error */\n                cerr << \"error: unrecognized shape '\" << shape << \"'.\\n\";\n        }\n    }\n\n    cout << \"\\nthe circles are:\\n\";     /* output valid circles */\n    for (auto& i : cir)\n        cout << \"  c: \" << i << \"\\n\";\n\n    cout << \"\\nthe triangles are:\\n\";   /* output valid triangles */\n    for (auto& i : tri)\n        cout << \"  t: \" << i << \"\\n\";\n\n    cout << \"\\nthe rectangles are:\\n\";  /* output valid rectangles */\n    for (auto& i : rect)\n        cout << \"  r: \" << i.width << \" x \" << i.height << \"\\n\";\n}\n\nBy storing values for your circles, triangles and rectangles independent of each other, you then have the ability to handle each type of shape as its own collection, e.g.\nExample Use/Output\n$ ./bin/read_shapes dat/shapes.txt\nerror: unrecognized shape '3'.\nerror: unrecognized shape '10'.\n\nthe circles are:\n  c: 12\n  c: 2\n  c: 2.4\n\nthe triangles are:\n  t: 2.9\n  t: 2.9\n\nthe rectangles are:\n  r: 3 x 4\n\nLook things over and let me know if you have further questions. The main takeaway is to insure you validate down to the point you can insure what you have read is either a round-peg to fit in the circle hole, a square-peg to fit in a square hole, etc..\n\nA: The only thing I added was a getline where I put a comment at the \"else\" of the loop.\nwhile(infile >> names) {\n    if(names.at(0) == 'c') {           \n        double r;                     \n        infile >> r;\n        cout << \"radius = \" << r << endl;\n    } else if(names.at(0) == 'r') {    \n        double w;                     \n        double h;                      \n        infile >> w;\n        infile >> h;\n        cout << \"width = \" << w << \", height = \" << h << endl;\n    } else if(names.at(0) == 't') {    \n        double s;                      \n        infile >> s;\n        cout << \"side = \" << s << endl;\n    } else {\n        // discard of the rest of the line using getline()\n        getline(infile, names);\n        //cout << \"discard: \" << names << endl;\n\n    }\n}\n\nOutput:\nradius = 12\nradius = 2\nwidth = 3, height = 4\nradius = 2.4\nside = 2.9\nside = 2.9\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/49227626", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: How to filter post by join condition? I have a table called wpps_posts which have this structure:\nID | post_title | post_type\n 1      foo         zoacres-property\n 2      foo2        zoacres-property\n 3      foo3        post\n\nI would like to return all the posts with type zoacres-property and also I want filter them by price. Each price is stored inside the table wp_postmeta:\nmeta_id | post_id | meta_key | meta_value\n  100       2         price       5000 \n  100       1         price       0\n\nHow can I order all the posts by price ASC?\nI'm stuck with the following query:\nSELECT * FROM wpps_posts p\nINNER JOIN wpps_posts wp ON wp.ID = p.ID\nWHERE p.post_type = 'zoacres-property'\nORDER BY wp.meta??\n\nEXPECTED RESULT:\nID | post_title | post_type\n 1      foo         zoacres-property\n 2      foo2        zoacres-propertY\n\n\nA: SELECT * FROM wpps_posts p\nINNER JOIN wp_postmeta wp ON wp.post_ID = p.ID\nAND wp.meta_key='price'\nWHERE p.post_type = 'zoacres-property'\nORDER BY wp.meta_value asc\n\n\nA: You could do something like this, depends what other type of meta type records you have.\nSELECT * FROM wpps_posts\nLEFT JOIN wp_postmeta ON wp_postmeta.post_id = wpps_posts.ID AND wp_postmeta.meta_key = 'price'\nWHERE wpps_posts.post_type = 'zoacres-property'\nORDER BY wp_postmeta.meta_value\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/63576155", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Convert the existing nested dictionary output in string to a list to iterate over it I have a rest api which provides a list of key value pair's and we need to fetch all the id's from this json output file.\nContents of the json file\n{\n    \"count\": 6,\n    \"results\": [\n        {\n            \"key\": \"roles\",\n            \"id\": \"1586230\"\n        },\n        {\n            \"key\": \"roles\",\n            \"id\": \"1586951\"\n        },\n        {\n            \"key\": \"roles\",\n            \"id\": \"1586932\"\n        },\n    ],\n    \"roles\": {\n        \"1586230\": {\n            \"name\": \"Systems Engineer\",\n            \"deleted_at\": null,\n            \"created_at\": \"2022-04-22T03:22:24-07:00\",\n            \"updated_at\": \"2022-04-22T03:22:24-07:00\",\n            \"id\": \"1586230\"\n        },\n        \"1586951\": {\n            \"name\": \"Engineer- Software\",\n            \"deleted_at\": null,\n            \"created_at\": \"2022-05-05T01:51:29-07:00\",\n            \"updated_at\": \"2022-05-05T01:51:29-07:00\",\n            \"id\": \"1586951\"\n        },\n        \"1586932\": {\n            \"name\": \"Engineer- SW\",\n            \"deleted_at\": null,\n            \"created_at\": \"2022-05-05T01:38:37-07:00\",\n            \"updated_at\": \"2022-05-05T01:38:37-07:00\",\n            \"id\": \"1586932\"\n        },\n    },\n    \"meta\": {\n        \"count\": 6,\n        \"page_count\": 5,\n        \"page_number\": 1,\n        \"page_size\": 20\n    }\n}\n\nThe rest call saves the contents to a file called p1234.json Opened the file in python:\nwith open ('p1234.json') as file:\n    data2 = json.load(file)\n\nfor ids in data2['results']:\n    res= ids['id']\n    print(res)\n\nSimilarly\nwith open ('p1234.json') as file:\n    data2 = json.load(file)\n\nfor role in data2['roles']:\n    res= roles['name']\n    print(res)\n\nfails with errors.\nHow to iterate over a nested array do I can only get the values of names listed in roles array\nroles --> 1586230 --> name --> System Engineer\n\nThank you\n\nA: You have to loop over the items of the dictionary.\nfor key, value in data2['roles'].items():\n    res= value['name']\n    print(res)\n\n\nA: There is nothing wrong with your code, I run it and I didn't get any error.\nThe problem that I see though is your Json file, some commas shouldn't be there:\n{\n\"count\": 6,\n\"results\": [\n    {\n        \"key\": \"roles\",\n        \"id\": \"1586230\"\n    },\n    {\n        \"key\": \"roles\",\n        \"id\": \"1586951\"\n    },\n    {\n        \"key\": \"roles\",\n        \"id\": \"1586932\"\n    } \\\\ here\n],\n\"roles\": {\n    \"1586230\": {\n        \"name\": \"Systems Engineer\",\n        \"deleted_at\": null,\n        \"created_at\": \"2022-04-22T03:22:24-07:00\",\n        \"updated_at\": \"2022-04-22T03:22:24-07:00\",\n        \"id\": \"1586230\"\n    },\n    \"1586951\": {\n        \"name\": \"Engineer- Software\",\n        \"deleted_at\": null,\n        \"created_at\": \"2022-05-05T01:51:29-07:00\",\n        \"updated_at\": \"2022-05-05T01:51:29-07:00\",\n        \"id\": \"1586951\"\n    },\n    \"1586932\": {\n        \"name\": \"Engineer- SW\",\n        \"deleted_at\": null,\n        \"created_at\": \"2022-05-05T01:38:37-07:00\",\n        \"updated_at\": \"2022-05-05T01:38:37-07:00\",\n        \"id\": \"1586932\"\n    } \\\\ here \n},\n\"meta\": {\n    \"count\": 6,\n    \"page_count\": 5,\n    \"page_number\": 1,\n    \"page_size\": 20\n}\n\nafter that any parsing function will do the job.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/72434671", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-1"}}
{"text": "Q: how to store Image profile(jpg file) and PDF documents in AWS DynamoDB? I am migrating my Spring MVC services to the AWS API Gateway using Python Lambda with Dynamo Db , I have endpoint where i can store or retrieve the people image and also the reports which is PDF file , can you please suggest me which is the best practice to store the images and pdf files in AWS .\nYour help is really appreciated!!\n\nA: Keep in mind, DynamoDB has a 400KB limit on each item.\nI would recommend using S3 for images and PDF documents. It also allows you to set up a CDN much more easily, rather than using something like DynamoDB.\nYou can always link your S3 link to an item in DynamoDB if you need to store data related to the file.\n\nA: AWS DynamoDB has a limit on the row size to be max of 400KB. So, it is not advisable to store the binary content of image/PDF document in a column directly. Instead, you should store the image/PDF in S3 and have the link stored in a column in DynamoDB.\nIf you were using Java, you could have leveraged the S3Link abstraction that takes care of storing the content in S3 and maintaining the link in DynamoDB column.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/47903547", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}}
{"text": "Q: Split a column after specific characters I have a field data in mysql db. For example\nquot_number\n====================\nUMAC/ARC/161299/801\nUMAC/LAK/151542/1051\nUMAC/LAK/150958/00050\n\nIam expecting an output as below:\n801\n1051\n00050\n\nActually the last numbers or characters after the last '/' has to be shown in my sql query. Any ways to achieve it?\nI tried to add something like this, but not getting expected result:\nLEFT(quotation.quot_number, 16) as quot_number4\n\nright(quot_number,((CHAR_LENGTH(quot_number))-(InStr(quot_number,',')))) as quot_number5\n\n\nA: Use function substring_index.\nselect\n    substring_index(quot_number, '/', -1)\nfrom yourtable\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/41219251", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "3"}}
{"text": "Q: HTTPS connection using PEM Certificate I'm trying to POST HTTPS requests using a PEM certificate like following: \nimport httplib  \nCERT_FILE = '/path/certif.pem'\nconn = httplib.HTTPSConnection('10.10.10.10','443', cert_file =CERT_FILE)   \nconn.request(\"POST\", \"/\") \nresponse = conn.getresponse()       \nprint response.status, response.reason\nconn.close()\n\nI have the following error:\nTraceback (most recent call last):\nFile \"<stdin>\", line 1, in <module>\nFile \"/usr/lib/python2.6/httplib.py\", line 914, in request\nself._send_request(method, url, body, headers)\nFile \"/usr/lib/python2.6/httplib.py\", line 951, in _send_request\nself.endheaders()\nFile \"/usr/lib/python2.6/httplib.py\", line 908, in endheaders\nself._send_output()\nFile \"/usr/lib/python2.6/httplib.py\", line 780, in _send_output\nself.send(msg)\nFile \"/usr/lib/python2.6/httplib.py\", line 739, in send\nself.connect()\nFile \"/usr/lib/python2.6/httplib.py\", line 1116, in connect\nself.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file)\nFile \"/usr/lib/python2.6/ssl.py\", line 338, in wrap_socket\nsuppress_ragged_eofs=suppress_ragged_eofs)\nFile \"/usr/lib/python2.6/ssl.py\", line 118, in __init__\ncert_reqs, ssl_version, ca_certs)\nssl.SSLError: [Errno 336265225] _ssl.c:339: error:140B0009:SSL       \nroutines:**SSL_CTX_use_PrivateKey_file**:PEM lib\n\nWhen I remove the cert_file from httplib, I've the following response:\n200 ok\n\nWhen I add the Authentication header (like advised by MattH) with empty post payload, it works also.\nHowever, when I put the good request with the Path, the Body and the Header, like following (I simplified them...)\nbody = '<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">blablabla</S:Envelope>'\nURLprov = \"/syncaxis2/services/XXXsyncService\"\nauth_header = 'Basic %s' %  (\":\".join([\"xxx\",\"xxxxx\"]).encode('Base64').strip('\\r\\n'))\nconn.request(\"POST\",URLprov,body,{'Authenticate':auth_header})\n\nI have 401 Unauthorized response !\nAs you can see, first, I'm asked to provide the PrivateKey ! why did I need the PrivateKey if I'm a client ? then, when I remove the PrivateKey and the certificate, and put the Path/Body/headers I have 401 Unauthorized error with the message WWW-Authenticate: Basic realm=\"SYNCNB Server Realm\".\nCould any one explain this issue? Is there another way to send HTTPS request using a certificate in Python?\n\nA: It sounds like you need something similar to an answer I have provided before to perform simple client certificate authentication. Here is the code for convenience modified slightly for your question:\nimport httplib\nimport urllib2\n\nPEM_FILE = '/path/certif.pem' # Renamed from PEM_FILE to avoid confusion\nCLIENT_CERT_FILE = '/path/clientcert.p12' # This is your client cert!\n\n# HTTPS Client Auth solution for urllib2, inspired by\n# http://bugs.python.org/issue3466\n# and improved by David Norton of Three Pillar Software. In this\n# implementation, we use properties passed in rather than static module\n# fields.\nclass HTTPSClientAuthHandler(urllib2.HTTPSHandler):\n    def __init__(self, key, cert):\n        urllib2.HTTPSHandler.__init__(self)\n        self.key = key\n        self.cert = cert\n    def https_open(self, req):\n        #Rather than pass in a reference to a connection class, we pass in\n        # a reference to a function which, for all intents and purposes,\n        # will behave as a constructor\n        return self.do_open(self.getConnection, req)\n    def getConnection(self, host):\n        return httplib.HTTPSConnection(host, key_file=self.key, cert_file=self.cert)\n\n\ncert_handler = HTTPSClientAuthHandler(PEM_FILE, CLIENT_CERT_FILE)\nopener = urllib2.build_opener(cert_handler)\nurllib2.install_opener(opener)\n\nf = urllib2.urlopen(\"https://10.10.10.10\")\nprint f.code\n\n\nA: See http://docs.python.org/library/httplib.html\nhttplib.HTTPSConnection does not do any verification of the server\u2019s certificate.\nThe option to include your private certificate is when the server is doing certificate based authentication of clients. I.e. the server is checking the client has a certificate signed by a CA that it trusts and is allowed to access it's resources.\n\nIf you don't specify the cert optional argument, you should be able to connect to the HTTPS server, but not validate the server certificate.\n\nUpdate\nFollowing your comment that you've tried basic auth, it looks like the server still wants you to authenticate using basic auth. Either your credentials are invalid (have you independently verified them?) or your Authenticate header isn't formatted correctly. Modifying your example code to include a basic auth header and an empty post payload:\nimport httplib  \nconn = httplib.HTTPSConnection('10.10.10.10','443')   \nauth_header = 'Basic %s' % (\":\".join([\"myusername\",\"mypassword\"]).encode('Base64').strip('\\r\\n'))\nconn.request(\"POST\", \"/\",\"\",{'Authorization':auth_header}) \nresponse = conn.getresponse()       \nprint response.status, response.reason\nconn.close()\n\n\nA: What you're doing is trying to connect to a Web service that requires authentication based on client certificate.\nAre you sure you have a PEM file and not a PKCS#12 file?  A PEM file looks like this (yes, I know I included a private key...this is just a dummy that I generated for this example):\n-----BEGIN RSA PRIVATE KEY-----                                                                     \nMIICXQIBAAKBgQDDOKpQZexZtGMqb7F1OMwdcFpcQ/pqtCoOVCGIAUxT3uP0hOw8                                    \nCZNjLT2LoG4Tdl7Cl6t66SNzMVyUeFUrk5rkfnCJ+W9RIPkht3mv5A8yespeH27x                                    \nFjGVbyQ/3DvDOp9Hc2AOPbYDUMRmVa1amawxwqAFPBp9UZ3/vfU8nxwExwIDAQAB                                    \nAoGBAMCvt3svfr9zysViBTf8XYtZD/ctqYeUWEZYR9hj36CQyVLZuAnyMaWcS7j7                                    \nGmrfVNygs0LXxoO2Xvi0ZOxj/mZ6EcZd8n37LxTo0GcWvAE4JjPr7I4MR2OvGYa/                                    \n1696e82xwEnUdpyBv9z3ebleowQ1UWP88iq40oZYukUeignRAkEA9c7MABi5OJUq                                    \nhf9gwm/IBie63wHQbB2wVgB3UuCYEa4Zd5zcvJIKz7NfhsZKKcZJ6CBVxwUd84aQ                                    \nAue2DRwYQwJBAMtQ5yBA8howP2FDqcl9sovYR0jw7Etb9mwsRNzJwQRYYnqCC5yS                                    \nnOaNn8uHKzBcjvkNiSOEZFGKhKtSrlc9qy0CQQDfNMzMHac7uUAm85JynTyeUj9/                                    \nt88CDieMwNmZuXZ9P4HCuv86gMcueex5nt/DdVqxXYNmuL/M3lkxOiV3XBavAkAA                                    \nxow7KURDKU/0lQd+x0X5FpgfBRxBpVYpT3nrxbFAzP2DLh/RNxX2IzAq3JcjlhbN                                    \niGmvgv/G99pNtQEJQCj5AkAJcOvGM8+Qhg2xM0yXK0M79gxgPh2KEjppwhUmKEv9                                    \no9agBLWNU3EH9a6oOfsZZcapvUbWIw+OCx5MlxSFDamg                                                        \n-----END RSA PRIVATE KEY-----                                                                    \n-----BEGIN CERTIFICATE-----                                                                         \nMIIDfjCCAuegAwIBAgIJAOYJ/e6lsjrUMA0GCSqGSIb3DQEBBQUAMIGHMQswCQYD                                    \nVQQGEwJVUzELMAkGA1UECBMCRkwxDjAMBgNVBAcTBVRhbXBhMRQwEgYDVQQKEwtG                                    \nb29iYXIgSW5jLjEQMA4GA1UECxMHTnV0IEh1dDEXMBUGA1UEAxMOd3d3LmZvb2Jh                                    \nci5jb20xGjAYBgkqhkiG9w0BCQEWC2Zvb0BiYXIuY29tMB4XDTExMDUwNTE0MDk0                                    \nN1oXDTEyMDUwNDE0MDk0N1owgYcxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJGTDEO                                    \nMAwGA1UEBxMFVGFtcGExFDASBgNVBAoTC0Zvb2JhciBJbmMuMRAwDgYDVQQLEwdO                                    \ndXQgSHV0MRcwFQYDVQQDEw53d3cuZm9vYmFyLmNvbTEaMBgGCSqGSIb3DQEJARYL                                    \nZm9vQGJhci5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMM4qlBl7Fm0                                    \nYypvsXU4zB1wWlxD+mq0Kg5UIYgBTFPe4/SE7DwJk2MtPYugbhN2XsKXq3rpI3Mx                                    \nXJR4VSuTmuR+cIn5b1Eg+SG3ea/kDzJ6yl4fbvEWMZVvJD/cO8M6n0dzYA49tgNQ                                    \nxGZVrVqZrDHCoAU8Gn1Rnf+99TyfHATHAgMBAAGjge8wgewwHQYDVR0OBBYEFHZ+                                    \nCPLqn8jlT9Fmq7wy/kDSN8STMIG8BgNVHSMEgbQwgbGAFHZ+CPLqn8jlT9Fmq7wy                                    \n/kDSN8SToYGNpIGKMIGHMQswCQYDVQQGEwJVUzELMAkGA1UECBMCRkwxDjAMBgNV                                    \nBAcTBVRhbXBhMRQwEgYDVQQKEwtGb29iYXIgSW5jLjEQMA4GA1UECxMHTnV0IEh1                                    \ndDEXMBUGA1UEAxMOd3d3LmZvb2Jhci5jb20xGjAYBgkqhkiG9w0BCQEWC2Zvb0Bi                                    \nYXIuY29tggkA5gn97qWyOtQwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOB                                    \ngQAv13ewjgrIsm3Yo8tyqTUHCr/lLekWcucClaDgcHlCAH+WU8+fGY8cyLrFFRdk                                    \n4U5sD+P313Adg4VDyoocTO6enA9Vf1Ar5XMZ3l6k5yARjZNIbGO50IZfC/iblIZD                                    \nUpR2T7J/ggfq830ACfpOQF/+7K+LgFLekJ5dIRuD1KKyFg==                                                    \n-----END CERTIFICATE-----\n\nRead this question.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/5896380", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "8"}}
{"text": "Q: Flutter: Mensagem de erro Could not update files on device: HttpException Ol\u00e1, estou estudando Flutter e recentemente tive um problema, quando tentei executar meu projeto com Flutter run recebi a mensagem de erro:\nCould not update files on device: HttpException: Connection closed before full header was received, uri = http://127.0.0.1:50365/h3iViYQmEC4=/\nTentei com emulador e com meu pr\u00f3prio celular por\u00e9m recebo o mesmo erro.\nO estranho \u00e9 que quando eu crio um App em Flutter novo ele funciona, consigo fazer todas as modifica\u00e7\u00f5es porem se eu parar e tentar executar novamente o erro aparece e o App n\u00e3o roda.\nJ\u00e1 tentei reiniciar os dispositivos. Flutter clean Flutter doctor [Exibe que est\u00e1 tudo certo]\nAt\u00e9 meus app antigos que tinha feito pra estudar acontece a mesma coisa, sendo que estavam funcionando.\nMensagem completa com Flutter run:\n\n\n\n\n*\n\n*Estou usando Android.\n\n*Mensagem que aparece no celular \u00e9 a padr\u00e3o 'O app parou de funcionar, deseja encerrar?'\n\n\nA: [RESOLVIDO] - O problema era uma fonte externa que eu estava importando que aparentemente se corrompeu, percebi que aparece uma mensagem :\nEu retirei todo lugar que eu usava ela e voltou ao normal.\n", "meta": {"language": "pt", "url": "https://pt.stackoverflow.com/questions/448434", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: TFS configure variables on Release definition instantiation I have a release definition setup with several tasks. When a developer wants to create a release from this definition, i'd like to give them the option of selecting which features they'd like to release (turn on/off tasks). Ideally this would be via the Create Release dialog using a variable or similar.\nCan this be done? Or is the only way to achieve this to create a draft release and enable/disable the tasks on each environment? Believe this is prone to error (toggle task on one environment but forget to on another) and this is not an option as administrator has locked editing of definitions (prevent incorrect setup of production releases).\nUnderstand I can create separate release definitions to cover the options but it seems like a lot of duplication.\n\nA: Unfortunately, this is not supported in TFS currently. The workarounds are just like you mentioned above, to disable and enable those steps or use draft release.\nThis is a user voice about your request you could vote:\n https://visualstudio.uservoice.com/forums/330519-team-services/suggestions/19165690-select-steps-when-create-release\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/43777906", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: AWS S3 Internal Server Error: Tyring to upload pdf file on after another I'm trying to generate PDF file using FPDF and PHP and later upload to  AWS-s3 and generate the url. When I executed the below code in my local-machine Using XAMPP it's generating files and uploading it to S3.\nBut When I deployed in AWS server as an API it's uploading only first file and for other its giving 500 server error\nBelow is my code that I used in Local Machine\n    require '../fpdf/fpdf.php';\n    require 'start.php';\n\n    use Aws\\Exception\\AwsException;\n\n    $location = \"bangalore\";\n    $db     =   getConnection();\n    $query   = \"SELECT first_name FROM customer_info where location = '$location'\";\n    $execute = $db->query($query);\n    $result  = $execute->fetchAll(PDO::FETCH_ASSOC);\n\n  for($i = 0; $i < $len; $i++) {\n $pdf = new FPDF();\n $pdf->AddPage();\n\n$pdf->SetFont('Arial', 'B', 14);\n$txt = \"Legal Document of \".$result[$i]['first_name'];\n$pdf->Cell(180, 0, $txt, 0, 1, 'C');\n$pdf->Line(5, 20, 200, 20);\n\n$docname = $result[$i]['first_name'] . \".pdf\";\n$filepath = \"../file/{$docname}\";\n$pdf->Output($filepath, 'F');\n\n//s3 client\ntry {\n       $res = $S3->putObject([\n        'Bucket' => $config['S3']['bucket'],\n        'Key' => \"PATH_TO_THE_DOCUMENT/{$docname}\",\n        'Body' => fopen($filepath, 'rb'),\n        'ACL' => 'public-read'\n    ]);\n\n    var_dump($res[\"ObjectURL\"]);\n} catch (S3Exception $e) {\n    echo $e->getMessage() . \"\\n\";\n}\n\n}\nOutput:\n   Array ( [0] => Array ( [first_name] => Mohan ) [1] => Array ( [first_name] => Prem ) [2] => Array ( [first_name] => vikash ) [3] => Array ( [first_name] => kaushik ) )\n\n     string(70) \"https://streetsmartb2.s3.amazonaws.com/PATH_TO_THE FILE/Mohan.pdf\" \n\n string(72) \"https://streetsmartb2.s3.amazonaws.com/PATH_TO_THE FILE/Prem%20.pdf\" \n\nAPI CODE\n      //pdf generation another api\n      $app->post('/pdfmail', function() use($app){\n\n    //post parameters\n    $location = $app->request->post('loc');\n    $id       = $app->request->post('id');\n\n\n\n   $db = getConnection();\n   $query   = \"SELECT * FROM customer_info where location = '$location'\";\n  $execute = $db->query($query);\n  $result  = $execute->fetchAll(PDO::FETCH_ASSOC);\n  $len = sizeof($result);\n\n  //request array\n  $request = array();\n\n  if($result != Null) {\n      for($i = 0; $i < $len; $i++) {\n          $pdf = new FPDF();\n          $pdf->AddPage();\n\n          $pdf->SetFont('Arial', 'B', 14);\n          $txt = \"Document of Mr.\" . $result[$i]['first_name'];\n          $pdf->Cell(180, 0, $txt, 0, 1, 'C');\n          $pdf->Line(5, 20, 200, 20);\n\n          $docname = $result[$i]['first_name'] . \".pdf\";\n          var_dump($docname);\n          $filepath = \"../file/{$docname}\";\n          var_dump($filepath);\n          $pdf->Output($filepath, 'F');\n\n\n          //s3 client\n          require '../aws/aws-autoloader.php';\n\n          $config = require('config.php');\n\n\n          //create s3 instance\n          $S3 = S3Client::factory([\n              'version' => 'latest',\n              'region' => 'REGION',\n              'credentials' => array(\n                  'key' => $config['S3']['key'],\n                  'secret' => $config['S3']['secret']\n              )\n          ]);\n\n\n\n          try {\n              $res = $S3->putObject([\n                  'Bucket' => $config['S3']['bucket'],\n                  'Key' => \"PATH_TO_FILE{$docname}\",\n                  'Body' => fopen($filepath, 'rb'),\n                  'ACL' => 'public-read'\n              ]);\n              var_dump($res[\"ObjectURL\"]);\n          } catch (S3Exception $e) {\n              echo $e->getMessage() . \"\\n\";\n          }\n\n      }\n  }\n\nOUTPUT WHEN TESTED IN POSTMAN\n    string(10) \"vikash.pdf\"\n    string(18) \"../file/vikash.pdf\"\n   string(71) \"https://streetsmartb2.s3.amazonaws.com/PATH_TO_FILE/vikash.pdf\"\n  string(13) \"pradeepan.pdf\"\n   string(21) \"../file/pradeepan.pdf\"\n\nAfter this I'm getting internal server error.\n\nA: Instead of using require_once I've use require...So as the code traversed it was creating AWS Class again and again. \nCode\n      //s3 client\n      require '../aws/aws-autoloader.php'; //use require_once\n\n      $config = require('config.php');\n\n\n      //create s3 instance\n      $S3 = S3Client::factory([\n          'version' => 'latest',\n          'region' => 'REGION',\n          'credentials' => array(\n              'key' => $config['S3']['key'],\n              'secret' => $config['S3']['secret']\n          )\n      ]);\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/48921630", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Auto-generate @version value in javadoc For the @version tag in javadoc, I use the same value as in BuildConfig.VERSION_NAME. I would like to inject that value, instead of changing every file for each release.\nI tried:\n* @version {@value BuildConfig#VERSION_NAME}\nand\n* @version @versionName  (and add -tag versionName:a:\"2.2.2\")\nbut none of these works.\nI could run sed just before the doc gets generated, but I would rather prefer something 'officially' supported.\nAny ideas how to solve this?\n\nA: For the second form, you can put your custom tag at the beginning of a javadoc line.\n/**\n * This is a class of Foo<br/>\n *\n * @version\n *\n * @configVersion.\n */\n\nThen use command javadoc -version -tag configVersion.:a:\"2.2.2\" to generate your javadoc, the custom tag should be handled in this way. Note the last dot(.) character in custom tag name, as the command javadoc suggests\n\nNote: Custom tags that could override future standard tags:  @configVersion. To avoid potential overrides, use at least one period character (.) in custom tag names.\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/58002547", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: How to retrieve data from MongoDb Atlas and display in an ejs file using mongoose and Nodejs Thanks for the help in advance.\nI am trying to retrieve data from my database- myFirstDatabase and collection named as 'shipment' in mongondb. This is a nested schema but I am only interested in the parent data for now. I have this code which retrieves data to the console log. But how can I display or access the data in my orders.ejs file?\n\n\nShipment.find({}, function (err, data) {\n  if (err) throw err\n\n  console.log(data)\n})\n\n\nMongoDB connected...\n[\n  {\n    _id: new ObjectId(\"61353311261da54811ee0ca5\"),\n    name: 'Micky Mouse',\n    phone: '5557770000',\n    email: 'g@gmail.com',\n    address: {\n      address: '10 Merrybrook Drive',\n      city: 'Herndon',\n      state: 'Virginia',\n      zip: '21171',\n      country: 'United States',\n      _id: new ObjectId(\"61353311261da54811ee0ca6\")\n    },\n    items: {\n      car: 'Honda Pilot 2018',\n      boxItem: '3 uHaul boxes',\n      furniture: 'None',\n      electronics: '1 50\" Samsung TV',\n      bags: '2 black suites cases',\n      _id: new ObjectId(\"61353311261da54811ee0ca7\")\n    },\n    date: 2021-09-05T21:13:53.484Z,\n    __v: 0\n  }\n]\n\n\nThis is the ejs file, a table I am trying to populate the data i get from my mongodb\n\n\n<div class=\"mt-5 m-auto>\n  <h3 class=\"mt-5\">This is the order table</h3>\n  <%- include (\"./partials/messages\"); %>\n  <div class=\"col-sm\">\n    <table class=\"table table-striped table-hover\">\n      <thead>\n        <tr>\n          <th>#</th>\n          <th>Customer</th>\n          <th>Address</th>\n          <th>City</th>\n          <th>State</th>\n          <th>Zip</th>\n          <th>Phone</th>\n          <th>Status</th>\n        </tr>\n      </thead>\n      <tbody>\n        <tr class=\"success\">\n          <td>1</td>\n          <td></td>\n          <td></td>\n          <td></td>\n          <td></td>\n          <td></td>\n          <td></td>\n          <td></td>\n        </tr>\n      </tbody>\n    </table>\n  </div>\n</div>\n\n\n\nA: server.js\nconst express = require('express')\nconst mongoose = require('mongoose')\nconst Shipment= require('./models/shipment')\nconst app = express()\n\nmongoose.connect('mongodb://localhost/myFirstDatabase ', {\n    useNewUrlParser: true, useUnifiedTopology: true\n})\n\napp.set('view engine', 'ejs')\napp.use(express.urlencoded({ extended:false }))\n\napp.get('/', async (req,res) => {\n    const data= await Shipment.find()\n    res.render('index', { data: data})\n})\n\napp.listen(process.env.PORT || 5000);\n\nindex.ejs\nbelow is part of your ejs file\n<table class=\"table table-striped table-hover\">\n    <thead>\n        <tr>\n            <th>#</th>\n            <th>Customer</th>\n            <th>Address</th>\n            <th>City</th>\n            <th>State</th>\n            <th>Zip</th>\n            <th>Phone</th>\n            <th>Status</th>\n        </tr>\n    </thead>\n    <tbody>\n        <% data.forEach((e, index)=> { %> \n            <tr>\n                <td><%= index %></td>\n                <td><%= e.Customer %></td>\n                <td><%= e.Address %></td>\n                <td><%= e.City %></td>\n                <td><%= e.State %></td>\n                <td><%= e.Zip %></td>\n                <td><%= e.Phone %></td>\n                <td><%= e.Status %></td>\n            </tr>\n        <% }) %>  \n    </tbody>\n</table>\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/69067410", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: node.js app running using forever inaccessible after a while I have a node.js server and a java client communicating using socket.io. I use this api https://github.com/Gottox/socket.io-java-client for the java client. I am using forever module\nto run my server.\nEverything works well but after some time , my server becomes inaccessible and I need to restart it, Also, most of the times i need to update/edit my node.js server file in order to make my server work again (restarted). Its been two weeks already and im still keep restarting my server :(.\nHas anyone run into the same problem ? and solution or advice please. \nThanks\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/17628274", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Populating Fields in Table with GUIDs from Feature Class? Is there a way to add GUIDs from a feature class to a table based on specific attributes? I have a large maintenance record table that is tied to specific points through the GUID of that point. I have added new records but they are not tied to a point yet. Instead of going through and copy/pasting each pole GUID to the appropriate maintenance record manually, I was hoping to use model builder or python to populate the fields in the table automatically. The data that overlaps between the two is the name of the line and the pole number.\nI think this is a relationship (many to many), but both the line name and the pole number need to match. I'm also new to using model builder and python.\n\nA: ModelBuilder does not provide a solution where you can create an editable join based on multiple fields.  Your question is virtually the same as Auto populating field in attribute table, using several fields of record information from another table? and the answers are the same.  You must either concatenate the fields into a single new field, run my Multi-field Key to Single-field Key tool to create a new numeric field that represents the multi-field key or use the Make Query Table tool. I do not consider the Make Query Table option workable, since it cannot be edited, it drops unmatched records, and it requires that you constantly recreate your entire feature class each time to update it.\nA Python script could do it using a cursor and dictionary.  See my Blog on Turbo Charging Data Manipulation with Python Cursors and Dictionaries.  In particular look at the example of Creating a Multi-Field Python Dictionary Key to Replace a Concatenated Join Field.  Once a working script has been writen, this is actually the fastest of the methods and since once it completed you would have a single field key through your GUID, it is probably the best for your particular data.  The concatenated field or single field key would be redundant once your GUID was transferred.\nThe python script underlying the Multi-field key to Single field key tool has a more sophisticated method of doing the multi-field matching, since it preserves the sort order native to each field type rather than using the sorting that occurs when values are converted to strings.  So if you want a single key that sorts the same way that the separate fields would sort, this tool is the best.\n", "meta": {"language": "en", "url": "https://gis.stackexchange.com/questions/193524", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}}
{"text": "Q: No 'Access-Control-Allow-Origin' header is present on the requested resource. Laravel 5.4 with cors package Hi I was following this tutorial regarding Laravel and VueJs communication. \nhttps://www.youtube.com/watch?v=5hOMkFMxY90&list=PL3ZhWMazGi9IommUd5zQmjyNeF7s1sP7Y&index=8\nI have done exactly like it was said in the tutorial. It uses a CORS package https://github.com/barryvdh/laravel-cors/\nI have added the service provider middlewares everything as it was told in the tutorial but it just doesnt seem to work.\nI have tried it in Laravel 5.4 and Laravel 5.3 as well.\nThis is my RouetServiceProvider: \n\n            namespace App\\Providers;\n\n            use Illuminate\\Support\\Facades\\Route;\n            use Illuminate\\Foundation\\Support\\Providers\\RouteServiceProvider as ServiceProvider;\n\n            class RouteServiceProvider extends ServiceProvider\n            {\n            /**\n            * This namespace is applied to your controller routes.\n            *\n            * In addition, it is set as the URL generator's root namespace.\n            *\n            * @var string\n            */\n            protected $namespace = 'App\\Http\\Controllers';\n\n            /**\n            * Define your route model bindings, pattern filters, etc.\n            *\n            * @return void\n            */\n            public function boot()\n            {\n            //\n\n            parent::boot();\n            }\n\n            /**\n            * Define the routes for the application.\n            *\n            * @return void\n            */\n            public function map()\n            {\n            $this->mapApiRoutes();\n\n            $this->mapWebRoutes();\n\n            //\n            }\n\n            /**\n            * Define the \"web\" routes for the application.\n            *\n            * These routes all receive session state, CSRF protection, etc.\n            *\n            * @return void\n            */\n            protected function mapWebRoutes()\n            {\n            Route::group([\n            'middleware' => 'web',\n            'namespace' => $this->namespace,\n            ], function ($router) {\n            require base_path('routes/web.php');\n            });\n            }\n\n            /**\n            * Define the \"api\" routes for the application.\n            *\n            * These routes are typically stateless.\n            *\n            * @return void\n            */\n            protected function mapApiRoutes()\n            {\n            Route::group([\n            'middleware' => ['api' , 'cors'],\n            'namespace' => $this->namespace,\n            'prefix' => 'api',\n            ], function ($router) {\n            require base_path('routes/api.php');\n            });\n            }\n            }\n\nThis is my middleware code in kernel \n protected $middleware = [\n    \\Barryvdh\\Cors\\HandleCors::class,\n    \\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode::class,\n    \\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize::class,\n    \\App\\Http\\Middleware\\TrimStrings::class,\n    \\Illuminate\\Foundation\\Http\\Middleware\\ConvertEmptyStringsToNull::class,\n];\n\nI have added its service provider too.\nI have seen all the solutions here on stackoverflow but none of them seems to work. I do not need theoretical answer but a practical solution \nThanks \n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/43503718", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}}
{"text": "Q: no partition after installing ubuntu I cannot boot back my windows 8 disk after Ubuntu install.\nI installed Ubuntu. Probably I selected my main disk (I wanted to used the diskonkey disk). After about 3-4 screens (selecting time zone) I noticed that is using the wrong partition and I powered down the laptop.\nNow I don\u2019t have a partition table with windows 8. It cannot boot. I think I have to recover my MBR and partition table.\nI used the boot repair - this is what it showed: http://paste.ubuntu.com/9659707/\n\nA: Powering down in the middle of an installation because you've taken the wrong choice is always the worst decision you can take.  That is like powering down your car in the middle of a busy cross-road because you took a wrong turn.  (Just believe me: don't try this!)\nThe easiest way to solve this situation is to:\n\n\n*\n\n*Enable UEFI in the BIOS and reboot.\n\n*If that didn't work, take the recovery DVD that came with your machine and boot with that to get your system back.  Warning this will destroy all of your data still remaining on the drive. (You did make a back-up before starting the install didn't you?)\n\n\nThe more difficult way:\n\n\n*\n\n*Attach your back-up drive to the computer\n\n*Boot with the Ubuntu LiveCD\n\n*Press Ctrl+Alt+T and type:\nsudo apt-get install testdisk\ntestdisk\n\n\n*Follow  testdisk step-by-step instructions to save as much of your data as possible.\n\n*Recover using the Recovery DVD\n\n*Follow these instructions on how to efficiently partition a Windows-Ubuntu dual-boot and how to install Ubuntu on a pre-installed Windows 8 machine.\n\n", "meta": {"language": "en", "url": "https://askubuntu.com/questions/585361", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: How to pass outside function to WP_REST_Request Learning with WP REST I'm unsure how to properly pass what is typically at the beginning of a PHP page form to WP_REST_Response.  For example:\nAt the beginning of page-foobar.php if I have:\n// IP ADDRESS\nfunction ipAddress() {\n    if (isset($_SERVER['REMOTE_ADDR'])) :\n        $ip_address = $_SERVER['REMOTE_ADDR'];\n    else :\n        $ip_address = \"undefined\";\n    endif;\n    return $ip_address;\n}\n/*\n    Template Name: Foobar\n*/\n\nand need to use $ip_address in:\nfunction foobar(\\WP_REST_Request $request) {\n    if ($ip_address == \"undefined\") :\n        return new WP_Error( 'bad_ip', 'No IP found', array( 'status' => 404 ) );\n    endif;\n}\n\nhow would I go about doing that?  When I searched I ran across:\nPass a Variable from one file to another in WordPress but I dont think it would be a good idea to pass as a global.  Further researching Passing variables between files in WordPress or PHP but I've already called the template in functions.php.  How can I pass a function from the template to the function request if it's stored in a different file?\n\nA: My approach would be, to declare the function in functions.php and then call it whenever you need.\nSince you are trying to use superglobals, you can access them anywhere. Move the code from your page-foobar.php to your theme's functions.php, and use this whenever you need to access it:\nipAddress();\n\nSo, in your REST function you can have:\nfunction foobar(\\WP_REST_Request $request) {\n    $ip_address = ipAddress();\n    if ($ip_address == \"undefined\") :\n        return new WP_Error( 'bad_ip', 'No IP found', array( 'status' => 404 ) );\n    endif;\n}\n\n", "meta": {"language": "en", "url": "https://wordpress.stackexchange.com/questions/277095", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Swift: How to not load AppDelegate during Tests I have an OS X application which on startup loads some data from a server and pushes notifications to the NSUserNotificationCenter.\nNow I have the problem that this also happens during my unit tests. I found no way yet to prevent this. Of course I could stub the HTTP loads. But in some cases I want to test the loading and then the notifications get sent anyway. \nWhat I'm trying to do is to make the test runs not load the AppDelegate but a fake one that I'm only using for tests. I found several examples [1] on how to do that with UIApplicationMain, where you can pass a specific AppDelegate class name. The same is not possible with NSApplicationMain [2].\nWhat I've tried is the following:\nRemoved @NSApplicationMain from AppDelegate.swift, then added a main.swift with the following content:\nclass FakeAppDelegate: NSObject, NSApplicationDelegate {\n}\n\nNSApplication.sharedApplication()\nNSApp.delegate = FakeAppDelegate()\nNSApplicationMain(Process.argc, Process.unsafeArgv)\n\nThis code runs before tests but has no effect at all.\nI might have to say: My AppDelegate is almost empty. To handle the MainMenu.xib stuff I made a separate view controller which does the actual loading and notification stuff in awakeFromNib. \n[1] http://www.mokacoding.com/blog/prevent-unit-tests-from-loading-app-delegate-in-swift/\n[2] https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Miscellaneous/AppKit_Functions/#//apple_ref/c/func/NSApplicationMain\n\nA: Just an update on the previous accept answer, this is my main.swift:\nprivate func isTestRun() -> Bool {\n    return NSClassFromString(\"XCTestCase\") != nil\n}\n\nif isTestRun() {\n    // This skips setting up the app delegate\n    NSApplication.shared.run()\n} else {\n    // For some magical reason, the AppDelegate is setup when\n    // initialized this way\n    _ = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)\n}\n\nA bit more compact! I'm using Swift 4.1 and XCode 9.4.1\n\nA: After days of trying and failing I found an answer on the Apple forums:\n\nThe problem was that my main.swift file was initializing my AppDelegate before NSApplication had been initialized. The Apple documentation makes it clear that lots of other Cocoa classes rely on NSApplication to be up and running when they are initialized. Apparently, NSObject and NSWindow are two of them.\n\nSo my final and working code in main.swift looks like this:\nprivate func isTestRun() -> Bool {\n    return NSClassFromString(\"XCTest\") != nil\n}\n\nprivate func runApplication(\n    application: NSApplication = NSApplication.sharedApplication(),\n    delegate: NSObject.Type?   = nil,\n    bundle: NSBundle?          = nil,\n    nibName: String            = \"MainMenu\") {\n\n    var topLevelObjects: NSArray?\n\n    // Actual initialization of the delegate is deferred until here:\n    application.delegate = delegate?.init() as? NSApplicationDelegate\n\n    guard bundle != nil else {\n        application.run()\n        return\n    }\n\n    if bundle!.loadNibNamed(nibName, owner: application, topLevelObjects: &topLevelObjects ) {\n        application.run()\n    } else {\n        print(\"An error was encountered while starting the application.\")\n    }\n}\n\nif isTestRun() {\n    let mockDelegateClass = NSClassFromString(\"MockAppDelegate\") as? NSObject.Type\n    runApplication(delegate: mockDelegateClass)\n} else {\n    runApplication(delegate: AppDelegate.self, bundle: NSBundle.mainBundle())\n}\n\nSo the actual problem before was that the Nib was being loaded during tests. This solution prevents this. It just loads the application with a mocked application delegate whenever it detects a test run (By looking for the XCTest class).\nI'm sure I will have to tweak this a bit more. Especially when a start with UI Testing. But for the moment it works.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/39116318", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "7"}}
{"text": "Q: How to use std::transform with a lambda function that takes additional parameters In C++ 11 (or higher) can I use std::transform and a lambda function to transform a vector that also takes other parameters?  For example, how do I pass param to the lambda function below?\nstd::vector<double> a{ 10.0, 11.0, 12.0 };\nstd::vector<double> b{ 20.0, 30.0, 40.0 };\nstd::vector<double> c;\ndouble param = 1.5;\n//The desired function is c = (a-b)/param   \ntransform(a.begin(), a.end(), b.begin(), std::back_inserter(c),\n          [](double x1, double x2) {return(x1 - x2)/param; });\n\nstd::transform wants a function with two input parameters. Do I need to use std::bind?\n\nA: You just need to capture param in your capture list:\ntransform(a.begin(), a.end(), b.begin(), std::back_inserter(c),\n          [param](double x1, double x2) {return(x1 - x2)/param; });\n\nCapturing it by reference also works - and would be correct if param was a big class. But for a double param is fine.\n\nA: This is what the lambda capture is for.  You need to specify & or = or param in the capture block ([]) of the lambda.  \nstd::vector<double> a{ 10.0, 11.0, 12.0 };\nstd::vector<double> b{ 20.0, 30.0, 40.0 };\nstd::vector<double> c;\ndouble param = 1.5;\n//The desired function is c = (a-b)/param   \ntransform(a.begin(), a.end(), b.begin(), std::back_inserter(c),\n          [=](double x1, double x2) {return(x1 - x2)/param; });\n//         ^ capture all external variables used in the lambda by value\n\nIn the above code we just capture by value since copying a double and having a reference is pretty much the same thing performance wise and we don't need reference semantics.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/53011875", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}}
{"text": "Q: How can I add an intranet-only endpoint to my IIS hosted WCF service? I have a WCF service hosted in IIS that uses basicHttpBindings. I'm adding a new method to the ServiceContract that will be called from a console app to perform an administrative task. I got to thinking, well wouldn't it be nice if I gave this method its own endpoint. Then I thought and what if that endpoint wasn't even publicly accessible. It would be much better if only a computer on our LAN could access it. It might even be cool if only an AD administrator was authorized to use it, but I don't want to get too elaborate. So I added a new ServiceContract interface that includes my new method. How can I restrict it to LAN access only? Do I need a NetTcpBinding? Networking is not my strong suit and I'm a little confused, conceptually, on how a TCP endpoint could be hosted from IIS. Additionally, when hosting multiple endpoints, does each have to have its own address or can they be at the same address?\n\nA: I am gonna answer some of your questions\n\n\n*\n\n*there is no binding that would limit access to LAN network though you can use windows authentication to allow users from your network to use the service \n\n*the nettcpbinding is only a tcp connection and you can host it on IIS pof course\ncheck this link for more information hosting nettcp on IIS\n\n*you can have one base address for multiple endpoints , example:\nhttps://localhost:8080/calculator.svc\nnet.tccp://localhost:8080/calculator.svc\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/29483797", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: A Quickselect C Algorithm faster than C Qsort I have tried to implement a C QuickSelect algorithm as described in this post (3 way quicksort (C implementation)).\nHowever, all I get are performances 5 to 10 times less than the default qsort (even with an initial shuffling).\nI tried to dig into the original qsort source code as provide here (https://github.com/lattera/glibc/blob/master/stdlib/qsort.c), but it's too complex.\nDoes anybody have a simpler, and better algorithm?\nAny idea is welcomed.\nThanks,\nNB: my original problem is to try to get the Kth smallest values of an array to the first Kth indices. So I planned to call quickselect K times\nEDIT 1: Here is the Cython Code as copied and adapted from the link above\ncdef void qswap(void* a, void* b, const size_t size) nogil:\n    cdef char temp[size]# C99, use malloc otherwise\n    #char serves as the type for \"generic\" byte arrays\n\n    memcpy(temp, b,    size)\n    memcpy(b,    a,    size)\n    memcpy(a,    temp, size)\n\ncdef void qshuffle(void* base, size_t num, size_t size) nogil: #implementation of Fisher\n    cdef int i, j, tmp# create local variables to hold values for shuffle\n\n    for i in range(num - 1, 0, -1): # for loop to shuffle\n        j = c_rand() % (i + 1)#randomise j for shuffle with Fisher Yates\n        qswap(base + i*size, base + j*size, size)\n\ncdef void partition3(void* base,\n                      size_t *low, size_t *high, size_t size,\n                      QComparator compar) nogil:       \n    # Modified median-of-three and pivot selection.                      \n    cdef void *ptr = base\n    cdef size_t lt = low[0]\n    cdef size_t gt = high[0] # lt is the pivot\n    cdef size_t i = lt + 1# (+1 !) we don't compare pivot with itself\n    cdef int c = 0\n\n    while (i <= gt):\n        c = compar(ptr + i * size, ptr + lt * size)\n        if (c < 0):# base[i] < base[lt] => swap(i++,lt++)\n            qswap(ptr + lt * size, ptr + i * size, size)\n            i += 1\n            lt += 1\n        elif (c > 0):#base[i] > base[gt] => swap(i, gt--)\n            qswap(ptr + i * size, ptr + gt* size, size)\n            gt -= 1\n        else:#base[i] == base[gt]\n            i += 1\n    #base := [<<<<<lt=====gt>>>>>>]\n    low[0] = lt                                          \n    high[0] = gt \n\n\ncdef void qselectk3(void* base, size_t lo, size_t hi, \n   size_t size, size_t k, \n   QComparator compar) nogil:                                             \n    cdef size_t low = lo                                          \n    cdef size_t high = hi                                                      \n\n    partition3(base, &low, &high,  size, compar)    \n\n    if ((k - 1) < low): #k lies in the less-than-pivot partition           \n        high = low - 1\n        low = lo                      \n    elif ((k - 1) >= low and  (k - 1) <= high): #k lies in the equals-to-pivot partition\n        qswap(base, base + size*low, size)\n        return                              \n    else: # k > high => k lies in the greater-than-pivot partition                    \n        low = high + 1\n        high = hi \n    qselectk3(base, low, high, size, k, compar)\n\n\"\"\"\n A selection algorithm to find the nth smallest elements in an unordered list. \n these elements ARE placed at the nth positions of the input array                                                                         \n\"\"\"\ncdef void qselect(void* base, size_t num, size_t size,\n                              size_t n,\n                              QComparator compar) nogil:\n    cdef int k\n    qshuffle(base, num, size)\n    for k in range(n):\n        qselectk3(base + size*k, 0, num - k - 1, size, 1, compar)\n\nI use python timeit to get the performance of both method pyselect(with N=50) and pysort.\nLike this\ndef testPySelect():\n    A = np.random.randint(16, size=(10000), dtype=np.int32)\n    pyselect(A, 50)\ntimeit.timeit(testPySelect, number=1)\n\ndef testPySort():\n    A = np.random.randint(16, size=(10000), dtype=np.int32)\n    pysort(A)\ntimeit.timeit(testPySort, number=1)\n\n\nA: The answer by @chqrlie is the good and final answer, yet to complete the post, I am posting the Cython version along with the benchmarking results.\nIn short, the proposed solution is 2 times faster than qsort on long vectors!\n\n\n    cdef void qswap2(void *aptr, void *bptr, size_t size) nogil:\n        cdef uint8_t* ac = <uint8_t*>aptr\n        cdef uint8_t* bc = <uint8_t*>bptr\n        cdef uint8_t t\n        while (size > 0): t = ac[0]; ac[0] = bc[0]; bc[0] = t; ac += 1; bc += 1; size -= 1\n\n    cdef struct qselect2_stack:\n        uint8_t *base\n        uint8_t *last\n\n    cdef void qselect2(void *base, size_t nmemb, size_t size,\n                      size_t k, QComparator compar) nogil:\n        cdef qselect2_stack stack[64]\n        cdef qselect2_stack *sp = &stack[0]\n\n        cdef uint8_t *lb\n        cdef uint8_t*ub\n        cdef uint8_t *p\n        cdef uint8_t *i\n        cdef uint8_t *j\n        cdef uint8_t *top\n\n        if (nmemb < 2 or size <= 0):\n            return\n\n        top = <uint8_t *>base\n        if(k < nmemb): \n            top += k*size \n        else: \n            top += nmemb*size\n\n        sp.base = <uint8_t *>base\n        sp.last = <uint8_t *>base + (nmemb - 1) * size\n        sp += 1\n\n        cdef size_t offset\n\n        while (sp > stack):\n            sp -= 1\n            lb = sp.base\n            ub = sp.last\n\n            while (lb < ub and lb < top):\n                #select middle element as pivot and exchange with 1st element\n                offset = (ub - lb) >> 1\n                p = lb + offset - offset % size\n                qswap2(lb, p, size)\n\n                #partition into two segments\n                i = lb + size\n                j = ub\n                while 1:\n                    while (i < j and compar(lb, i) > 0):\n                        i += size\n                    while (j >= i and compar(j, lb) > 0):\n                        j -= size\n                    if (i >= j):\n                        break\n                    qswap2(i, j, size)\n                    i += size\n                    j -= size\n\n                # move pivot where it belongs\n                qswap2(lb, j, size)\n\n                # keep processing smallest segment, and stack largest\n                if (j - lb <= ub - j):\n                    sp.base = j + size\n                    sp.last = ub\n                    sp += 1\n                    ub = j - size\n                else:\n                    sp.base = lb\n                    sp.last = j - size\n                    sp += 1\n                    lb = j + size\n\n\n\n    cdef int int_comp(void* a, void* b) nogil:\n        cdef int ai = (<int*>a)[0] \n        cdef int bi = (<int*>b)[0]\n        return (ai > bi ) - (ai < bi)\n\n    def pyselect2(numpy.ndarray[int, ndim=1, mode=\"c\"] na, int n):\n        cdef int* a = <int*>&na[0]\n        qselect2(a, len(na), sizeof(int), n, int_comp)\n\n\nHere are the benchmark results (1,000 tests):\n\n#of elements   K      #qsort (s)                     #qselect2 (s)\n1,000          50     0.1261                         0.0895\n1,000          100    0.1261                         0.0910\n\n10,000         50     0.8113                         0.4157\n10,000         100    0.8113                         0.4367\n10,000         1,000  0.8113                         0.4746\n\n100,000        100    7.5428                         3.8259\n100,000        1,000  7,5428                         3.8325\n100,000        10,000 7,5428                         4.5727\n\nFor those who are curious, this piece of code is a jewel in the field of surface reconstruction using neural networks.\nThanks again to @chqrlie, your code is unique on The Web.\n\nA: Here is a quick implementation for your purpose: qsort_select is a simple implementation of qsort with automatic pruning of unnecessary ranges.\nWithout && lb < top, it behaves like the regular qsort except for pathological cases where more advanced versions have better heuristics. This extra test prevents complete sorting of ranges that are outside the target 0 .. (k-1). The function selects the k smallest values and sorts them, the rest of the array has the remaining values in an undefinite order.\n#include <stdio.h>\n#include <stdint.h>\n\nstatic void exchange_bytes(uint8_t *ac, uint8_t *bc, size_t size) {\n    while (size-- > 0) { uint8_t t = *ac; *ac++ = *bc; *bc++ = t; }\n}\n\n/* select and sort the k smallest elements from an array */\nvoid qsort_select(void *base, size_t nmemb, size_t size,\n                  int (*compar)(const void *a, const void *b), size_t k)\n{\n    struct { uint8_t *base, *last; } stack[64], *sp = stack;\n    uint8_t *lb, *ub, *p, *i, *j, *top;\n\n    if (nmemb < 2 || size <= 0)\n        return;\n\n    top = (uint8_t *)base + (k < nmemb ? k : nmemb) * size;\n    sp->base = (uint8_t *)base;\n    sp->last = (uint8_t *)base + (nmemb - 1) * size;\n    sp++;\n    while (sp > stack) {\n        --sp;\n        lb = sp->base;\n        ub = sp->last;\n        while (lb < ub && lb < top) {\n            /* select middle element as pivot and exchange with 1st element */\n            size_t offset = (ub - lb) >> 1;\n            p = lb + offset - offset % size;\n            exchange_bytes(lb, p, size);\n\n            /* partition into two segments */\n            for (i = lb + size, j = ub;; i += size, j -= size) {\n                while (i < j && compar(lb, i) > 0)\n                    i += size;\n                while (j >= i && compar(j, lb) > 0)\n                    j -= size;\n                if (i >= j)\n                    break;\n                exchange_bytes(i, j, size);\n            }\n            /* move pivot where it belongs */\n            exchange_bytes(lb, j, size);\n\n            /* keep processing smallest segment, and stack largest */\n            if (j - lb <= ub - j) {\n                sp->base = j + size;\n                sp->last = ub;\n                sp++;\n                ub = j - size;\n            } else {\n                sp->base = lb;\n                sp->last = j - size;\n                sp++;\n                lb = j + size;\n            }\n        }\n    }\n}\n\nint int_cmp(const void *a, const void *b) {\n    int aa = *(const int *)a;\n    int bb = *(const int *)b;\n    return (aa > bb) - (aa < bb);\n}\n\n#define ARRAY_SIZE  50000\n\nint array[ARRAY_SIZE];\n\nint main(void) {\n    int i;\n    for (i = 0; i < ARRAY_SIZE; i++) {\n        array[i] = ARRAY_SIZE - i;\n    }\n    qsort_select(array, ARRAY_SIZE, sizeof(*array), int_cmp, 50);\n    for (i = 0; i < 50; i++) {\n        printf(\"%d%c\", array[i], i + 1 == 50 ? '\\n' : ',');\n    }\n    return 0;\n}\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/52016431", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-3"}}
{"text": "Q: What is eating up my disk space? I have very recently installed Ubuntu 15.10. I have been watching the available amount of memory over two days, and i noticed that the free memory goes on decreasing at a slow rate. Initially the used memory was 5GB, Then it went on increasing to 6 to 6.5 and now it stands around 6.8. I haven't installed anything significant over this period (except some small packages worth a few MBs) .My home folder is just few 100kbs. What is eating up my disk space? How can find out if something is going on?\n\nA: The indicated amount seems to be .deb cache in majority. Issue this command:  \nsudo apt-get clean\n\nand after that check again the disk usage.\n\nA: You can find out how much space sub-directories occupy using the following command:\nsudo du -hxd 1 YOUR_PATH 2>/dev/null | sort -hr\n\nWhat it does:\n\n\n*\n\n*sudo: run the du command as root - only needed/recommended if you want to list stuff outside your own home directory.\n\n*du: disk usage analyzing tool. Arguments:\n\n\n*\n\n*-h: use human readable numeric output (i.e. 2048 bytes = 2K)\n\n*-x: stay on the same file system, do not list directories which are just mounted there\n\n*-d 1: display recursion depth is set to 1, that means it will only print the given directory and the direct subdirectories.\n\n*YOUR_PATH: The path which should be analyzed. Change this to whatever path you want.\n\n*2>/dev/null: we do not want error output (e.g. from when it tries to get the size of virtual files), so we pipe that to the digital nirvana a.k.a. /dev/null.\n\n\n*|: use the output of the previous command as input for the next command\n\n*sort: sort the input. Arguments:\n\n\n*\n\n*-h: recognize numbers like 2K and sort them according to their real value\n\n*-r: reversed order: print the largest numbers first\n\n\n\nExample for my file system root /:\n$ sudo du -hxd 1 / 2>/dev/null | sort -hr\n5,7G    /\n4,0G    /usr\n1,3G    /var\n358M    /lib\n49M     /opt\n15M     /etc\n13M     /sbin\n13M     /bin\n840K    /tmp\n32K     /root\n16K     /lost+found\n8,0K    /media\n4,0K    /srv\n4,0K    /mnt\n4,0K    /lib64\n4,0K    /cdrom\n\nNote that the given directory's total size is also included, not only the subdirectories.\n", "meta": {"language": "en", "url": "https://askubuntu.com/questions/725797", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Get values with no repeated data I have a query like this:\nSELECT\n      P.LegacyKey\n      ,D.DesignNumber\n      FROM tbl1 AS [SO]\n GROUP BY D.DesignNumber,P.LegacyKey\n ORDER BY LegacyKey\n\nit returning values like:\n+-----------+--------------+\n| LegacyKey | DesignNumber |\n+-----------+--------------+\n|     17134 |            1 |\n|     17134 |            2 |\n|     18017 |            7 |\n+-----------+--------------+\n\nThat I want to do is to find duplicate LegacyKeys and get only values who legacyKey is exist one time, so I use HAVING COUNT:\nSELECT\n      P.LegacyKey\n      ,D.DesignNumber\n      , COUNT([P].[LegacyKey])\n      FROM tbl1 AS [SO]\n GROUP BY D.DesignNumber,P.LegacyKey\n HAVING COUNT([P].[LegacyKey])  = 1\n ORDER BY LegacyKey\n\nBut this is returning bad data, because it is returning LegacyKey = 17134 again and desire result is to get values where LegacyKey exists one time.\nSo desire result should be only\n  18017 |            7 \n\nWhat am I doing wrong?\n\nA: You can simply do:\nSELECT P.LegacyKey, MAX(D.DesignNumber) as DesignNumber\nFROM tbl1 AS [SO]\nGROUP BY P.LegacyKey\nHAVING COUNT(DISTINCT D.DesignNumber) = 1;\nORDER BY LegacyKey;\n\nNo subquery is necessary.\n\nA: You need something like this:\nselect t2.LegacyKey, t2.DesignNumber\nfrom\n(\n    select t.LegacyKey \n    from tbl1 t\n    group by t.LegacyKey \n    having count(t.LegacyKey ) = 1\n)x\njoin tbl1 t2 on x.LegacyKey = t2.LegacyKey\n\nor\nselect t2.LegacyKey, t2.DesignNumber\nfrom tbl1 t2\nwhere t2.LegacyKey in\n(\n    select t.LegacyKey \n    from tbl1 t\n    group by t.LegacyKey \n    having count(t.LegacyKey ) = 1\n)\n\n\nA: You could try this \nNB - This is untested\nSELECT  *   \nFROM    (\n            SELECT\n                  P.LegacyKey AS LegacyKey,\n                  D.DesignNumber AS DesignNumber,\n                  COUNT([P].[LegacyKey]) AS cnt\n             FROM tbl1 AS [SO]\n             GROUP BY D.DesignNumber,P.LegacyKey\n             HAVING COUNT([P].[LegacyKey])  = 1\n        ) a\nWHERE   COUNT() OVER (PARTITION BY LegacyKey) = 1\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/54993000", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: @IBDesignable doesn't work in \"old\" project I have UIView subclass, for example, this:\n@IBDesignable\nclass GradientView: UIView {\n\n    @IBInspectable var firstColor: UIColor = UIColor.red\n    @IBInspectable var secondColor: UIColor = UIColor.green\n\n    @IBInspectable var vertical: Bool = true\n\n    override func awakeFromNib() {\n        super.awakeFromNib()\n\n        applyGradient()\n    }\n\n    func applyGradient() {\n        let colors = [firstColor.cgColor, secondColor.cgColor]\n\n        let layer = CAGradientLayer()\n        layer.colors = colors\n        layer.frame = self.bounds\n        layer.startPoint = CGPoint(x: 0, y: 0)\n        layer.endPoint = vertical ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0)\n\n        self.layer.addSublayer(layer)\n    }\n\n    override func prepareForInterfaceBuilder() {\n        super.prepareForInterfaceBuilder()\n        applyGradient()\n    }\n}\n\nIt successfully renders in Interface Builder for a new project, but it doesn't work for my \"old\" project. \nDoes anyone know why it happens?\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/45217918", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: How do I refer to the people living in the particular city? Is it random always? Where do demonyms come from? At times they take -ite, some times -an, -er and this one is jaw-dropping '-siders!'\n\nA person living in New York is a New Yorker (-er)   A person living in Delhi is Delhiite (-ite)  A person living in Sydney is Sydneysider (-sider -OMG! Really?)   A person living in Las Vegas is Las Vegan (-an)\n\nThere are innumerable cities across the world and remembering a demonym for each of them does not seem practical. \nI don't get demonyms without searching them on the Internet (and trust me, even after searching I fail to get them for some cities' residents!). \nThis becomes further difficult when the city name is long - say St. Louis, Amsterdam, Rio de Janeiro (Cariocas -full marks who knew this!) and many more. \nIs there any way we can assume/know the demonym of the city by looking at its spelling?\n\nA: Is there a hard and fast rule? Sadly, no. But there is a rule of thumb--which means it works, except when it doesn't.\nFirst: if the city is outside of the United States, US English usually (but not always) uses the naming convention of the native country. So \"Liverpudlian\" and \"Muenchner\" don't follow these rules; you need to learn that country's rules.\nWithin the United States, look at the sound (not the spelling!) of the last syllable of the city's name.\nDoes it end in a vowel sound? Add -n or -an.\n\n\n*\n\n*Atlantan\n\n*Cincinattian\n\n*Kenoshan\n\n*Pennsylvanian\n\n\nDoes it end in a hard d or k? Add -er.\n\n\n*\n\n*New Yorker\n\n*Oaklander\n\n*Portlander\n\n*Salt Laker\n\n\nDoes it end in an -l, or -r sound? Consider adding -ite.\n\n\n*\n\n*Seattleite\n\n*New Hampshirite\n\n\nDoes it end in an -s sound preceded by a schwa? Replace the s with an n.\n\n\n*\n\n*Kansan\n\n*Texan\n\n\nFor all other consonants, the most common rule is to add an -ian \n\n\n*\n\n*Oregonian\n\n*Bostonian\n\n*Knoxvillian\n\n\nAs always with English, there are then a ton of exceptions that you just have to learn.\n", "meta": {"language": "en", "url": "https://ell.stackexchange.com/questions/21370", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "4"}}
{"text": "Q: Passing object messages in Azure Queue Storage I'm trying to find a way to pass objects to the Azure Queue. I couldn't find a way to do this.\nAs I've seen I can pass string or byte array, which is not very comfortable for passing objects.\nIs there anyway to pass custom objects to the Queue?\nThanks!\n\nA: You can use the following classes as example:\n [Serializable]\n    public abstract class BaseMessage\n    {\n        public byte[] ToBinary()\n        {\n            BinaryFormatter bf = new BinaryFormatter();\n            byte[] output = null;\n            using (MemoryStream ms = new MemoryStream())\n            {\n                ms.Position = 0;\n                bf.Serialize(ms, this);\n                output = ms.GetBuffer();\n            }\n            return output;\n        }\n\n        public static T FromMessage<T>(CloudQueueMessage m)\n        {\n            byte[] buffer = m.AsBytes;\n            T returnValue = default(T);\n            using (MemoryStream ms = new MemoryStream(buffer))\n            {\n                ms.Position = 0;\n                BinaryFormatter bf = new BinaryFormatter();\n                returnValue = (T)bf.Deserialize(ms);\n            }\n            return returnValue;\n        }\n    }\n\nThen a StdQueue (a Queue that is strongly typed):\n   public class StdQueue<T> where T : BaseMessage, new()\n    {\n        protected CloudQueue queue;\n\n        public StdQueue(CloudQueue queue)\n        {\n            this.queue = queue;\n        }\n\n        public void AddMessage(T message)\n        {\n            CloudQueueMessage msg =\n            new CloudQueueMessage(message.ToBinary());\n            queue.AddMessage(msg);\n        }\n\n        public void DeleteMessage(CloudQueueMessage msg)\n        {\n            queue.DeleteMessage(msg);\n        }\n\n        public CloudQueueMessage GetMessage()\n        {\n            return queue.GetMessage(TimeSpan.FromSeconds(120));\n        }\n    }\n\nThen, all you have to do is to inherit the BaseMessage:\n[Serializable]\npublic class ParseTaskMessage : BaseMessage\n{\n    public Guid TaskId { get; set; }\n\n    public string BlobReferenceString { get; set; }\n\n    public DateTime TimeRequested { get; set; }\n}\n\nAnd make a queue that works with that message:\nCloudStorageAccount acc;\n            if (!CloudStorageAccount.TryParse(connectionString, out acc))\n            {\n                throw new ArgumentOutOfRangeException(\"connectionString\", \"Invalid connection string was introduced!\");\n            }\n            CloudQueueClient clnt = acc.CreateCloudQueueClient();\n            CloudQueue queue = clnt.GetQueueReference(processQueue);\n            queue.CreateIfNotExist();\n            this._queue = new StdQueue<ParseTaskMessage>(queue);\n\nHope this helps!\n\nA: Extension method that uses Newtonsoft.Json and async\n    public static async Task AddMessageAsJsonAsync<T>(this CloudQueue cloudQueue, T objectToAdd)\n    {\n        var messageAsJson = JsonConvert.SerializeObject(objectToAdd);\n        var cloudQueueMessage = new CloudQueueMessage(messageAsJson);\n        await cloudQueue.AddMessageAsync(cloudQueueMessage);\n    }\n\n\nA: I like this generalization approach but I don't like having to put Serialize attribute on all the classes I might want to put in a message and derived them from a base (I might already have a base class too) so I used...\nusing System;\nusing System.Text;\nusing Microsoft.WindowsAzure.Storage.Queue;\nusing Newtonsoft.Json;\n\nnamespace Example.Queue\n{\n    public static class CloudQueueMessageExtensions\n    {\n        public static CloudQueueMessage Serialize(Object o)\n        {\n            var stringBuilder = new StringBuilder();\n            stringBuilder.Append(o.GetType().FullName);\n            stringBuilder.Append(':');\n            stringBuilder.Append(JsonConvert.SerializeObject(o));\n            return new CloudQueueMessage(stringBuilder.ToString());\n        }\n\n        public static T Deserialize<T>(this CloudQueueMessage m)\n        {\n            int indexOf = m.AsString.IndexOf(':');\n\n            if (indexOf <= 0)\n                throw new Exception(string.Format(\"Cannot deserialize into object of type {0}\", \n                    typeof (T).FullName));\n\n            string typeName = m.AsString.Substring(0, indexOf);\n            string json = m.AsString.Substring(indexOf + 1);\n\n            if (typeName != typeof (T).FullName)\n            {\n                throw new Exception(string.Format(\"Cannot deserialize object of type {0} into one of type {1}\", \n                    typeName,\n                    typeof (T).FullName));\n            }\n\n            return JsonConvert.DeserializeObject<T>(json);\n        }\n    }\n}\n\ne.g.\nvar myobject = new MyObject();\n_queue.AddMessage( CloudQueueMessageExtensions.Serialize(myobject));\n\nvar myobject = _queue.GetMessage().Deserialize<MyObject>();\n\n\nA: In case the storage queue is used with WebJob or Azure function (quite common scenario) then the current Azure SDK allows to use POCO object directly. See examples here:\n\n\n*\n\n*https://learn.microsoft.com/en-us/sandbox/functions-recipes/queue-storage\n\n*https://github.com/Azure/azure-webjobs-sdk/wiki/Queues#trigger\nNote: The SDK will automatically use Newtonsoft.Json for serialization/deserialization under the hood.\n\nA: I liked @Akodo_Shado's approach to serialize with Newtonsoft.Json.  I updated it for Azure.Storage.Queues and also added a \"Retrieve and Delete\" method that deserializes the object from the queue.\npublic static class CloudQueueExtensions\n{\n    public static async Task AddMessageAsJsonAsync<T>(this QueueClient queueClient, T objectToAdd) where T : class\n    {\n        string messageAsJson = JsonConvert.SerializeObject(objectToAdd);\n        BinaryData cloudQueueMessage = new BinaryData(messageAsJson);\n        await queueClient.SendMessageAsync(cloudQueueMessage);\n    }\n\n    public static async Task<T> RetreiveAndDeleteMessageAsObjectAsync<T>(this QueueClient queueClient) where T : class\n    {\n\n        QueueMessage[] retrievedMessage = await queueClient.ReceiveMessagesAsync(1);\n        if (retrievedMessage.Length == 0) return null;\n        string theMessage = retrievedMessage[0].MessageText;\n        T instanceOfT = JsonConvert.DeserializeObject<T>(theMessage);\n        await queueClient.DeleteMessageAsync(retrievedMessage[0].MessageId, retrievedMessage[0].PopReceipt);\n\n        return instanceOfT;\n    }\n}\n\nThe RetreiveAndDeleteMessageAsObjectAsync is designed to process 1 message at time, but you could obviously rewrite to deserialize the full array of messages and return a ICollection<T> or similar.\n\nA: That is not right way to do it. queues are not ment for storing object. you need to put object in blob or table (serialized).\nI believe queue messgae body has 64kb size limit with sdk1.5 and 8kb wih lower versions.\nMessgae body is ment to transfer crutial data for workera that pick it up only.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/8550702", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "28"}}
{"text": "Q: Help needed renaming custom post I really have very little Wordpress knowledge and I need help with the following:\nI have a theme which uses a custom post called 'services'. I needed another custom post created which worked exactly the same as services so I went through all the code and copied and pasted wherever I found references to services and changed it to \"signage\". This worked ok, however on the WP admin screen, \"signage\" is called \"posts\" as is the original \"posts\", and I cant work out how to change the name to signage. I have been able to change the original \"posts\" name but not the custom post.\n\nA: It could be the 'name' in the labels array of the register post type. It would be much easier to help if you can show us your code.\n", "meta": {"language": "en", "url": "https://wordpress.stackexchange.com/questions/116728", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-1"}}
{"text": "Q: How to add FTP site in IIS 7 in Windows Vista Home premium edition How to add the FTP server in IIS 7 using Windows vista Home Premium Edition?\n\nA: Please check if FTP 7.5 can be used on your Windows Vista machine, http://www.iis.net/expand/FTP\nIf not, FileZilla is a free alternative, http://filezilla-project.org/download.php?type=server\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/2524250", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Unable to install any program Total newbie here, I installed Kubuntu about three days ago and have been trying to install some programmes, to date no success. No matter what I try to install I get the same error. I would be very grateful if someone could explain what is happening and how to resolve it, or point me to a document that can help.\nThanks in advance for your help,\nNoel \nsudo apt-get install muon\n[sudo] password for nleric: \nReading package lists... Done\nBuilding dependency tree       \nReading state information... Done\nSome packages could not be installed. This may mean that you have\nrequested an impossible situation or if you are using the unstable\ndistribution that some required packages have not yet been created\nor been moved out of Incoming.\nThe following information may help to resolve the situation:\n\nThe following packages have unmet dependencies:\n muon : Depends: apt-xapian-index but it is not going to be installed\nE: Unable to correct problems, you have held broken packages.\n\n\nA: the package \"apt-xapian-index\" is in the universe repository since Ubuntu 16.04 Xenial (see http://packages.ubuntu.com/xenial/apt-xapian-index). Before Ubuntu 16.04 Xenial the package \"apt-xapian-index\" was in the main repository, so it was always available, even if the user had the \"universe\" repository disabled. It's not the case anymore.\nTo confirm what is above just run the following:\napt-cache policy apt-xapian-index\n\nIf the result is not available it's because apt-get can't find it in the present repositories present in the file /etc/apt/sources.list.\nMy guess is that you have removed/disabled the universe repository from your APT /etc/apt/sources.list file. Make sure to add \"universe\" at the end of the the lines starting with \"deb\" in that file. Example, change the following line to have the universe repository enabled, in the file /etc/apt/sources.list file:\ndeb http://archive.ubuntu.com/ubuntu/ xenial main\n\nTo something like (add the last word in the line):\ndeb http://archive.ubuntu.com/ubuntu/ xenial main universe\n\nThen update apt-get repositories:\nsudo apt-get update\n\nApt-get will update its sources of available packages, now with the universe repository enabled. Then try to fix the problem:\nsudo apt-get install -f\n\n", "meta": {"language": "en", "url": "https://askubuntu.com/questions/796482", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: NLog not creating a log file inside AWS ec2 Linux I have a .net core application in AWS ec2 linux and it does NOT create a log file. The application on AWS ec2 linux is published with Deployment Mode: Self-contained and Target Runtime: linux-x64.\nI tried it on windows and it does create a log file but somehow it's not working in AWS ec2 linux.\nHeres what I did.\n\n\n*\n\n*Open ubuntu machine terminal (CLI) and Go to the project directory\n\n*Provide execute permissions: chmod 777 ./appname\n\n*Execute application\n\n*./appname\nNote: It displays the Hello World.\npublic static void Main(string[] args)\n    {\n        try\n        {\n            using (var logContext = new LogContextHelper(null, \"MBP\", \"MBP\",\n        new JObject() {\n                    { \"ASD\", \"asd\" },\n                    { \"ZXC\", \"asd\" },\n                    { \"QWE\", \"asd\" },\n                    { \"POI\", \"\" }\n        }, setAsContextLog: true))\n            { }\n        }\n        catch (Exception e)\n        {\n            Console.WriteLine(\"Error: {0}\", e);\n        }\n        //sample s = new sample(\"consuna\") { objectinitial = \"objuna\"};\n\n\n            Console.WriteLine(\"Hello World!\");\n        Console.ReadLine();\n    }\n}\n\n    Here is the NLog.config\n\n\n    <?xml version=\"1.0\" encoding=\"utf-8\" ?>\n        <nlog xmlns=\"http://www.nlog-project.org/schemas/NLog.xsd\"\n          xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n          xsi:schemaLocation=\"http://www.nlog-project.org/schemas/NLog.xsd                NLog.xsd\"\n          autoReload=\"true\"\n          throwExceptions=\"false\"\n          internalLogLevel=\"Off\" internalLogFile=\"c:\\temp\\nlog-internal.log\">\n\n        <variable name=\"myvar\" value=\"myvalue\"/>\n\n        <targets>\n        <target xsi:type=\"File\" name=\"fileMBP\" fileName=\"/home/ec2-user/mbpTESTING.log\"`enter code here`\n              layout=\"Logger=&quot;MBP API&quot;,\n        TimeStamp=&quot;${event-context:item=datetime}&quot;,\n        TimeStampMel=&quot;${event-context:item=datetimeMel}&quot;,\n        Message=&quot;${message}&quot;,\n        Context=&quot;${basedir}&quot;,\n        Command=&quot;${event-context:item=command}&quot;,\n        ${event-context:item=properties}\"\n            archiveFileName=\"/home/ec2-user/MBP.{#}.txt\"\n            archiveEvery=\"Day\"\n            archiveNumbering=\"DateAndSequence\"\n            maxArchiveFiles=\"7\"\n            concurrentWrites=\"true\"\n            keepFileOpen=\"false\"/>\n\n       </targets>\n\n       <rules>\n        <logger name=\"MBP\" minlevel=\"Trace\" writeTo=\"fileMBP\"/>\n       </rules>\n       </nlog>\n\n\n        I expect that it will create a log file with logs on it just like on windows.\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/57800735", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: EditText length with \"exceptions\" I have an EditText and I'd like to set maxLength to four numbers (in range -9999 to 9999). Problem is that if I setandroid:maxLength=\"4\" in xml I can write there e.q \"9999\" but it doesn't accept \"-9999\" because of length (5 char). Is there any opportunity how to solve it (programatically or anyhow)\nThanks\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/36794789", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Understanding hashCode(), equals() and toString() in Java I am beginner in Java and although I have a look at several questions and answers in SO, I am not sure if I completely understand the usage of hashCode(), equals() and toString() in Java. I encountered the following code in a project and want to understand the following issues:\n1. Is it meaningful to define these methods and call via super like return super.hashCode()?\n2. Where should we defines these three methods? For each entity? Or any other place in Java?\n3. Could you please explain me the philosophy of defining these 3 (or maybe similar ones that I have not seen  before) in Java?\n@Entity\n@SequenceGenerator(name = \"product_gen\", sequenceName = \"product_id_seq\")\n@Table\n@Getter\n@Setter\n@ToString(callSuper = true)\n@NoArgsConstructor\npublic class Product extends BaseEntity {\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"product_gen\")\n    private long id;\n\n    @Override\n    public int hashCode() {\n        return super.hashCode();\n    }\n\n    @Override\n    public boolean equals(Object other) {\n        return super.equals(other);\n    }\n}\n\n\n\nA: *\n\n*toString() method returns the String representation of an Object. The default implementation of toString() for an object returns the HashCode value of the Object. We'll come to what HashCode is.\nOverriding the toString() is straightforward and helps us print the content of the Object. @ToString annotation from Lombok does that for us. It Prints the class name and each field in the class with its value.\nThe @ToString annotation also takes in configuration keys for various behaviours. Read here. callSuper just denotes that an extended class needs to call the toString() from its parent.\nhashCode() for an object returns an integer value, generated by a hashing algorithm. This can be used to identify whether two objects have similar Hash values which eventually help identifying whether two variables are pointing to the same instance of the Object. If two objects are equal from the .equals() method, they must share the same HashCode\n\n\n*They are supposed to be defined on the entity, if at all you need to override them.\n\n\n*Each of the three have their own purposes. equals() and hashCode() are majorly used to identify whether two objects are the same/equal. Whereas, toString() is used to Serialise the object to make it more readable in logs.\nFrom Effective Java:\n\nYou must override hashCode() in every class that overrides equals().\nFailure to do so will result in a violation of the general contract\nfor Object.hashCode(), which will prevent your class from functioning\nproperly in conjunction with all hash-based collections, including\nHashMap, HashSet, and HashTable.\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/69024813", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: How to reference a variable from one activity to another I'm trying to get a variable string and integer from\nMain2Activity.java to MainActivity.java \n\nBut the problem is that I don't want to use the:\nstartActivity(intent);\n\nFor it to work. I just want the information to be passed so I can use it in my current activity. Is there any way to do this? What am I missing. This is how my MainActivity looks like:\nbtn.setOnClickListener(new View.OnClickListener() {\n    @Override\n    public void onClick(View v) {\n\n        TextView textView = (TextView)findViewById(R.id.textView7);\n\n        Intent intent = getIntent();\n        String A = intent.getStringExtra(\"Apples\");\n        textView.setText(A);\n    }\n});\n\nAnd my Main2Activty: \nIntent intent = new Intent(Main2Activity.this, MainActivity.class);\nintent.putExtra(\"Apples\", \"Red\");\n\nThanks for helping. Please only comment if you know what you're talking about. \n\nA: There is an other way, you can define a Class DataHolder and static variable for sharing variable between Activity\nExample\nclass DataHolder {\n    public static String appleColor = \"\";\n}\n\nThen you can use like this:\nIntent intent = new Intent(Main2Activity.this, MainActivity.class);\nDataHolder.appleColor = \"RED\";\n\nThen \nbtn.setOnClickListener(new View.OnClickListener() {\n    @Override\n    public void onClick(View v) {\n\n        TextView textView = (TextView)findViewById(R.id.textView7);\n\n        Intent intent = getIntent();\n        textView.setText(DataHolder.appleColor);\n    }\n});\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/48392826", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Replace black boot screen with Purple ( default ) I used to have Gnome and Cinnamon on my laptop. Maybe because of that, the boot screen has changed to a black one than default Purple boot screen. I have since then upgraded to 16.04 from 14.04 and everything was good. \nBut recently, I am facing frequent boot failure. The boot screen flashes, goes transparent and shows some terminal like activities in the background. In the end, mostly it will say some process failed and I never get to the GUI.\nThis is happening so frequently that I am not able to use my PC at all. Will replacing black boot screen with Purple solve this problem ? If no, kindly suggest a solution for the same. Thanks.\nPS: I now use Unity alone with 16.04\n", "meta": {"language": "en", "url": "https://askubuntu.com/questions/855301", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Only grep img tags that contain a keyword, but not img tags that don't? Using grep/regex, I am trying to pull img tags out of a file. I only want img tags that contain 'photobucket' in the source, and I do not want img tags that do not contain photobucket.\nWant:\n<img src=\"/photobucket/img21.png\">\n\nDo Not Want:\n<img src=\"/imgs/test.jpg\">\n<img src=\"/imgs/thiswillgetpulledtoo.jpg\"><p>We like photobucket</p>\n\nWhat I have tried:\n(<img.*?photobucket.*?>)\n\nThis did not work, because it pulled the second example in \"Do Not Want\", as there was a 'photobucket' and then a closing bracket. How can I only check for 'photobucket' up until the first closing bracket, and if photobucket is not contained, ignore it and move on?\n'photobucket' may be in different locations within the string.\n\nA: Just add a negation of > sign:\n(<img[^>]*?photobucket.*?>)\n\nhttps://regex101.com/r/tZ9lI9/2\n\nA: grep -o '<img[^>]*src=\"[^\"]*photobucket[^>]*>' infile\n\n-o returns only the matches. Split up:\n\n<img          # Start with <img\n[^>]*         # Zero or more of \"not >\"\nsrc=\"         # start of src attribute\n[^\"]*         # Zero or more or \"not quotes\"\nphotobucket   # Match photobucket\n[^>]*         # Zero or more of \"not >\"\n>             # Closing angle bracket\n\nFor the input file\n<img src=\"/imgs/test.jpg\">\n<img src=\"/imgs/thiswillgetpulledtoo.jpg\"><p>We like photobucket</p>\n<img src=\"/photobucket/img21.png\">\n<img alt=\"photobucket\" src=\"/something/img21.png\">\n<img alt=\"something\" src=\"/photobucket/img21.png\">\n<img src=\"/photobucket/img21.png\" alt=\"something\">\n<img src=\"/something/img21.png\" alt=\"photobucket\">\n\nthis returns \n$ grep -o '<img[^>]*src=\"[^\"]*photobucket[^>]*>' infile\n<img src=\"/photobucket/img21.png\">\n<img alt=\"something\" src=\"/photobucket/img21.png\">\n<img src=\"/photobucket/img21.png\" alt=\"something\">\n\nThe non-greedy .*? works only with the -P option (Perl regexes).\n\nA: Try the following:\n<img[^>]*?photobucket[^>]*?>\n\nThis way the regex can't got past the '>'\n\nA: Try with this pattern:\n<img.*src=\\\"[/a-zA-Z0-9_]+photobucket[/a-zA-Z0-9_]+\\.\\w+\\\".*>\n\nI\u00b4m not sure the characters admited by the name folders, but you just need add in the ranges \"[]\" before and after the \"photobucket\".\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/34882511", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Maximum number reached for Sharepoint 2007 number-type column In a SharePoint 2007 List, there is a number-type column which have a maximum value 1000. Suppose that the column is used for a auto-increment ID, what will happen if the ID exceed 1000?\nWill the next ID be reset to 0 or a error will occur?\n", "meta": {"language": "en", "url": "https://sharepoint.stackexchange.com/questions/19840", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Icon color of html5 input date picker How can I change the icon color of the native HTML5 date input (<input type=\"date\" />)?\nIs it possible to change the calendar icon color to HEX: #018bee or RGB: (1, 139, 238)? I saw a post saying that it was possible using filters, but I was unsuccessful.\n\nCodepen Example:\nhttps://codepen.io/gerisd/pen/VwPzqMy\nHTML:\n <input type=\"date\" id=\"deadline\" name=\"deadline\" value=\"2021-01-01\" required>\n\nCSS:\n#deadline{\n  width: 100%;\n  min-width: 100px;\n  border: none;\n  height: 100%;\n  background: none;\n  outline: none;\n  padding-inline: 5px;\n  resize: none;\n  border-right: 2px solid #dde2f1;\n  cursor: pointer;\n  color: #9fa3b1;\n  text-align: center;\n}\n\ninput[type=\"date\"]::-webkit-calendar-picker-indicator {\n  cursor: pointer;\n  border-radius: 4px;\n  margin-right: 2px;\n  filter: invert(0.8) sepia(100%) saturate(10000%) hue-rotate(240deg);\n}\n\n\nA: Have you tried using webkit? I found a similar qustion from\nenter link description here\ntry this code from that question maybe:\n::-webkit-calendar-picker-indicator {\nfilter: invert(1);\n\n}\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/66974856", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: how can i display data in detail component from list component? i have problem to display data from one component to another component.\ni put the data which i fetch from the serve in prova and i display the list of all work. but I can't transfer the data that is on \"prova\" to another component to make the details visible through their own id.\nthis is my apicall service\n\nimport { Injectable } from '@angular/core';\nimport {HttpClient,HttpClientModule,HttpResponse} from '@angular/common/http';\nimport {Observable} from \"rxjs\";\nimport {map} from \"rxjs/operators\";\nimport {results} from \"./results\"\n\n\n@Injectable({\n  providedIn: 'root'\n})\nexport class GetApiService {\n\n  constructor(\n    private http:HttpClient,\n  ) { }\n\n\n  apiCall():Observable<results[]>\n  {\n    return this.http.get('https://www.themuse.com/api/public/jobs?category=Engineering&page=10')\n    .pipe(map\n    (\n      (response:any) => {\n        const data = response.results;\n        console.log (data)\n        return data ;\n   \n      }\n    )\n    );\n   }\n}\n\nthis is my observable results\n  export interface results\n    {\n  categories : any;\ncompany: string;\ncontents:string;\nid : number;\n levels:string;\n locations:string;\n model_type: string;\n name: string;\n refs: string;\n short_name: string;\n type:string;\n\n  }\n\n\nthis is my component where are a list of works\nimport {results} from \"../results\";\nimport {GetApiService} from '../get-api.service';\nimport {switchMap} from \"rxjs/operators\";\nimport { Observable } from 'rxjs';\nimport { ActivatedRoute } from '@angular/router';\n\n\n@Component({\n  selector: 'app-work-list',\n  templateUrl: './work-list.component.html',\n  styleUrls: ['./work-list.component.css']\n})\nexport class WorkListComponent implements OnInit {\n   \n  prova: results[]=[] ;\n item: any;\n  selectedId: any ;\n  constructor(\n    private api :GetApiService,\n    private route: ActivatedRoute,\n  ) { }\n\n  ngOnInit(){\n\n    this.api.apiCall()\n    .subscribe\n      (\n        (data:results[]) => {\n          this.prova=data;\n        console.log (data);\n\n        });\n\n}\n}\n\nand the respectiv html connected by id\n    <div *ngFor=\"let item of prova \" \n    [class.selected]=\"item.id === selectedId\">\n                      \n    <a\n    [routerLink]=\"['/details',item.id]\">\n    <h1> {{ item.name }}</h1>\n    </a>\n    <h1> {{ item.id }}</h1>\n    <h1> {{ item.categories[0].name }}</h1>\n    <h1> {{ item.name }}</h1>\n\n      </div>\n\nthis is the details where i can't display the selected work with its own details\nimport { ActivatedRoute } from '@angular/router';\nimport {results}  from '../results';\nimport {GetApiService} from '../get-api.service';\nimport {switchMap} from \"rxjs/operators\";\n\n\n@Component({\nselector: 'app-work-details',\ntemplateUrl: './work-details.component.html',\nstyleUrls: ['./work-details.component.css']\n})\nexport class WorkDetailsComponent implements OnInit {\n@Input()\nitem: {\n  categories: any;\n  company: string;\n  contents: string;\n  id: number;\n  levels: string;\n  locations: string;\n  model_type: string;\n  name: string;\n  refs: string;\n  short_name: string;\n  type: string;\n} | undefined;\n@Input ()\nprova: results[]=[];\nselectedId:string | undefined;\nconstructor(\n  private route: ActivatedRoute,\n  private api: GetApiService,\n) { }\n\nngOnInit():void {\n\n   this.route.paramMap.subscribe\n    (params => {\n      this.item=this.prova[+params.get('selectedId')];\n\n**// it should  be somewthing like this but prova is empty.**\n      \n    })\n  ;\n}\n}\n\n\nA: It looks like you're mixing two different mechanisms?\nOne is of a parent -> child component relationship where you have your WorkDetailsComponent with an @Input() for prova, but at the same time, it looks like the component is its own page given your <a [routerLink]=\"['/details',item.id]\"> and the usage of this.route.paramMap.subscribe....\nFairly certain you can't have it both ways.\nYou either go parent -> child component wherein you pass in the relevant details using the @Input()s:\n<div *ngIf=\"selectedItem\">\n  <app-work-details [prova]=\"prova\" [selectedItem]=\"selectedItem\"></app-work-details>\n</div>\n\nOR you go with the separate page route which can be done one of two ways:\n\n*\n\n*Use the service as a shared service; have it remember the state (prova) so that when the details page loads, it can request the data for the relevant id.\n\n\n*Pass the additional data through the route params\nFor 1, it would look something like:\nprivate prova: results[]; // Save request response to this as well\n\npublic getItem(id: number): results {\n  return this.prova.find(x => x.id === id);\n}\n\nAnd then when you load your details page:\nngOnInit():void {\n\n   this.route.paramMap.subscribe\n    (params => {\n      this.selectedId=+params.get('selectedId');\n\n   this.item = this.service.getItem(this.selectedId);\n      \n    });\n}\n\nFor 2, it involves routing with additional data, something like this:\n<a [routerLink]=\"['/details',item.id]\" [state]=\"{ data: {prova}}\">..</a>\n\nThis article shows the various ways of getting data between components in better detail.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/65146369", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Shifting elements of an array to the right I am aware that there are solutions for shifting arrays out there. However no solution works for me. The code should achieve the following:\nThe method shift(int[] array, int places) takes in an array, shifts the elements places - times to the right and replaces the \"leftover\" elements with \"0\".\nSo far I have:\npublic static int[] shiftWithDrop(int[] array, int places) {\n            \n    if (places == 0 || array == null) {\n        return null;\n    }\n    for (int i = array.length-places-1; i >= 0; i-- ) {\n        array[i+places] = array[i];\n        array[i] = 0;\n    }               \n    return array;\n}\n\nThis code does only somehow work, but it does not return the desired result. What am I missing?\n\nA: There are several issues in this code:\n\n*\n\n*It returns null when places == 0 -- without shift, the original array needs to be returned\n\n*In the given loop implementation the major part of the array may be skipped and instead of replacing the first places elements with 0, actually a few elements in the beginning of the array are set to 0.\n\nAlso it is better to change the signature of the method to set places before the vararg array.\nSo to address these issues, the following solution is offered:\npublic static int[] shiftWithDrop(int places, int ... array) {\n    if(array == null || places <= 0) {\n        return array;\n    }\n    for (int i = array.length; i-- > 0;) {\n        array[i] = i  < places ? 0 : array[i - places];\n    }\n    \n    return array;\n}    \n\nTests:\nSystem.out.println(Arrays.toString(shiftWithDrop(1, 1, 2, 3, 4, 5)));\nSystem.out.println(Arrays.toString(shiftWithDrop(2, new int[]{1, 2, 3, 4, 5})));\nSystem.out.println(Arrays.toString(shiftWithDrop(3, 1, 2, 3, 4, 5)));\nSystem.out.println(Arrays.toString(shiftWithDrop(7, 1, 2, 3, 4, 5)));\n\nOutput:\n[0, 1, 2, 3, 4]\n[0, 0, 1, 2, 3]\n[0, 0, 0, 1, 2]\n[0, 0, 0, 0, 0]\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/70135652", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}