text
stringlengths
15
59.8k
meta
dict
Q: Make keyboard NOT dismiss when opening a ModalViewController Possible Duplicate: How can I keep the keyboard present even when presenting a modal view controller? I have an opened keyboard on one viewcontroller and I want to show another one. But when I show it, keyboard goes down. But I don't want it to go down. I want it to stay. How can I achieve this? I don't call any endEditings and resignFirstResponders myself.
{ "language": "en", "url": "https://stackoverflow.com/questions/12315978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where to get a pre-built Chromium to easily do modifications? Chromium takes too long to get compiled, like 7 hours on a regular powerful desktop. I'm thinking of some where to get a pre-built Chromium, with which I will be able to compile again only some files to re-link to make a new Chromium binary. Possible to compile just some source code files and re-link (re-link object files)? A: It's hard to build Chromium from source but it's every easy to build a new browser based on Chromium. With GitHub Electron, any app based on it is a real Chromium browser, and developers may create custom UI for their Electron-based browsers. However, modern browsers would require having servers for storing users' sync data, this might not be easily affordable for 1-man development army to create a new browser for the mass. Electron app is a pack of Chromium sandbox, and Node.js backend, the 2 communicate thru' IPC as Node.js will be able to access all resources. GitHub Electron: https://electronjs.org
{ "language": "en", "url": "https://stackoverflow.com/questions/61995913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pandas: How to pivot rows into columns I am looking for a way to pivot around 600 columns into rows. Here's a sample with only 4 of those columns (good, bad, ok, Horrible): df: RecordID good bad ok Horrible A 0 0 1 0 B 1 0 0 1 desired output: RecordID Column Value A Good 0 A Bad 0 A Ok 1 A Horrible 0 B Good 1 B Bad 0 B Ok 0 B Horrible 1 A: You can use .stack() as follows. Using .stack() is preferred as it naturally resulted in rows already sorted in the order of RecordID so that you don't need to waste processing time sorting on it again, especially important when you have a large number of columns. df = df.set_index('RecordID').stack().reset_index().rename(columns={'level_1': 'Column', 0: 'Value'}) Output: RecordID Column Value 0 A good 0 1 A bad 0 2 A ok 1 3 A Horrible 0 4 B good 1 5 B bad 0 6 B ok 0 7 B Horrible 1 A: You can use melt function: (df.melt(id_vars='RecordID', var_name='Column', value_name='Value') .sort_values('RecordID') .reset_index(drop=True) ) Output: RecordID Column Value 0 A good 0 1 A bad 0 2 A ok 1 3 A Horrible 0 4 B good 1 5 B bad 0 6 B ok 0 7 B Horrible 1 A: Adding dataframe: import pandas as pd import numpy as np data2 = {'RecordID': ['a', 'b', 'c'], 'good': [0, 1, 1], 'bad': [0, 0, 1], 'horrible': [0, 1, 1], 'ok': [1, 0, 0]} # Convert the dictionary into DataFrame df = pd.DataFrame(data2) Melt data: https://pandas.pydata.org/docs/reference/api/pandas.melt.html melted = df.melt(id_vars='RecordID', var_name='Column', value_name='Value') melted Optionally: Group By - for summ or mean values: f2 = melted.groupby(['Column']).sum() df2
{ "language": "en", "url": "https://stackoverflow.com/questions/66992652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to run kubectl exec on scripts that never end I have a mssql pod that I need to use the sql_exporter to export its metrics. I was able to set up this whole thing manually fine: * *download the binary *install the package *run ./sql_exporter on the pod to start listening on port for metrics I tried to automate this using kubectl exec -it ... and was able to do step 1 and 2. When I try to do step 3 with kubectl exec -it "$mssql_pod_name" -- bash -c ./sql_exporter the script just hangs and I understand as the server is just going to be listening forever, but this stops the rest of my installation scripts. I0722 21:26:54.299112 435 main.go:52] Starting SQL exporter (version=0.5, branch=master, revision=fc5ed07ee38c5b90bab285392c43edfe32d271c5) (go=go1.11.3, user=root@f24ba5099571, date=20190114-09:24:06) I0722 21:26:54.299534 435 config.go:18] Loading configuration from sql_exporter.yml I0722 21:26:54.300102 435 config.go:131] Loaded collector "mssql_standard" from mssql_standard.collector.yml I0722 21:26:54.300207 435 main.go:67] Listening on :9399 <nothing else, never ends> Any tips on just silencing this and let it run in the background (I cannot ctrl-c as that will stop the port-listening). Or is there a better way to automate plugin install upon pod deployment? Thank you A: To answer your question: This answer should help you. You should (!?) be able to use ./sql_exporter & to run the process in the background (when not using --stdin --tty). If that doesn't work, you can try nohup as described by the same answer. To recommend a better approach: Using kubectl exec is not a good way to program a Kubernetes cluster. kubectl exec is best used for debugging rather than deploying solutions to a cluster. I assume someone has created a Kubernetes Deployment (or similar) for Microsoft SQL Server. You now want to complement that Deployment with the exporter. You have options: * *Augment the existing Deployment and add the sql_exporter as a sidecar (another container) in the Pod that includes the Microsoft SQL Server container. The exporter accesses the SQL Server via localhost. This is a common pattern when deploying functionality that complements an application (e.g. logging, monitoring) *Create a new Deployment (or similar) for the sql_exporter and run it as a standalone Service. Configure it scrape one|more Microsoft SQL Server instances. Both these approaches: * *take more work but they're "more Kubernetes" solutions and provide better repeatability|auditability etc. *require that you create a container for sql_exporter (although I assume the exporter's authors already provide this).
{ "language": "en", "url": "https://stackoverflow.com/questions/73086332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to put a link on the bottom right hand side of a page I am currently using the following code to do it. <span style="position: absolute; bottom: 0pt; right: 0pt;"> Load time: 1.1920928955078E-5 seconds</span> The problem I am having is that if the page is scrollable then it is midway through the page. I am sure that there is a simple solution for this, but I can't come up with it. Any help or suggestions would be greatly appreciated. A: You'll need the div have position fixed instead of absolute. Fiddle: http://jsfiddle.net/hqkm7/ A: <\span style="position: absolute; bottom: 0pt; right: 0pt;">Load time: 1.1920928955078E-5 seconds<\/span> should be <span style="position: absolute; bottom: 0pt; right: 0pt;">Load time: 1.1920928955078E-5 seconds</span> A: you need to use position:fixed instead of position:absolute. position:absolute does not scroll with the page while positions:fixed does (by taking your span out of the flow of the page).
{ "language": "en", "url": "https://stackoverflow.com/questions/6381412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is this a valid regular language expression for a binary string? Can it be condensed into something more concise? The regular expression is: (10) U ((10(0 U 1))*10) The language I am trying to write is this:(q2 is the accept state and {0,1} is the langauge) (q0,0)=q3 (q0,1)=q1 (q1,0)=q2 — accept state (q1,1)=q3 (q2,0)=q0 (q2,1)=q0 (q3,0)=q3 (q3,1)=q3
{ "language": "en", "url": "https://stackoverflow.com/questions/62976958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL check if next row doesn't exist I have an MsSQL server and what I am doing is selecting rows from the table. Currently I have two rows so I was wondering how would I check if there are no other rows after second one without making another query? For example table users id name pass 1 joe 123 2 bob abc How would I check if there is no row after 2 with just a query? I am willing to combining it with my current query, which just selects the data. A: You can return the number of rows in your query as another column: SELECT id, name, pass, count(*) over () as rows FROM users Keep in mind that this is telling you the number of rows returned by the query, not the number of rows in the table. However, if you specify a "TOP n" in your select, the rows column will give you the number of rows that would have been returned if you didn't have "Top n" A: If you're trying to paginate the trick is to query one more record than you actually need for the current page. By counting the result (mysql_num_rows) and comparing that to your page size, you can then decide if there is a 'next page'. If you were using mysql you could also use SQL_CALC_FOUND_ROWS() in your query, which calculates the number of rows that would be returned without the LIMIT clause. Maybe there is an equivalent for that in MsSQL? A: I assume that you are inserting manually the first 2 rows of your table. According to that, my idea is to just do a select where the id is more than 2 like this: SELECT * FROM users WHERE id > 2; I also assume that you are using PHP so mysql_num_rows will return you 0 if no data is found, otherwise it will return you the number of rows from your query and now you know that you need to do a while or some loop to retrieve the data after id number 2.
{ "language": "en", "url": "https://stackoverflow.com/questions/10216645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get MouseOver trigger event alter child items I have a MouseOver event for a border. Within that border (further down) I have a couple of Borders with RotateTransforms... How can I, within the top level Border hover event alter their transform? (i.e. change their rotation?) <Border.Style> <Style> <Style.Triggers> <Trigger Property="Border.IsMouseOver" Value="True"> <Setter Property="Border.Background" Value="#f0f0f0" /> </Trigger> </Style.Triggers> </Style> </Border.Style> Further down the tree, but inside this border is <Border Padding="3" Width="73" Height="57" Background="White" RenderTransformOrigin="0.5, 0.5"> <Border.Effect> <DropShadowEffect BlurRadius="4" Direction="0" ShadowDepth="0" Color="#aa505050" /> </Border.Effect> <Border.RenderTransform> <RotateTransform Angle="-2" /> </Border.RenderTransform> </Border> A: You could use a DataTrigger in an inner border Style with FindAncestor or ElementName binding to get the IsMouseOver of your outer border. i.e. <Border.Style> <Style TargetType="Border"> <Setter Property="RenderTransform"> <Setter.Value> <RotateTransform Angle="3"/> </Setter.Value> </Setter> <Style.Triggers> <DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=IsMouseOver}" Value="True"> <Setter Property="RenderTransform"> <Setter.Value> <RotateTransform Angle="6"/> </Setter.Value> </Setter> </DataTrigger > </Style.Triggers> </Style> </Border.Style>
{ "language": "en", "url": "https://stackoverflow.com/questions/16422439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Pass data (retrieved from server) from parent route to its child route My Angular application have parent and child route. I am using (ui-router) I what to build that parent route data (which are retrieved from server using $resource) are passed to its child route. Here will be my application code. When I debugged my code, then "phaseTasks" in child route always was empty Array. flowAdminApp.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider){ $stateProvider .state('phase', { url: "/phases/:phase_id", template: JST['layouts/admin/flows/tasks/index'], resolve: { phaseTasks: ['$stateParams', 'taskData', function( $stateParams, taskData ){ return taskData.getPhaseTasks($stateParams.phase_id); }] }, controller: 'taskListController' }) .state('phase.task', { url: "/tasks/:task_id", template: JST['layouts/admin/flows/tasks/show'], resolve: { task: ['$stateParams', 'phaseTasks', function( $stateParams, phaseTasks ){ // phaseTasks is empty Array }] }, controller: 'taskController' }) }]); flowAdminApp.factory('taskData', [ '$resource', function ($resource) { return { getPhaseTasks: function (phase_id) { return $resource('/admin/tasks.json?phase_id=:phase_id', {phase_id:'@phase_id'}).query({phase_id:phase_id}); } } }]); When I changed my code that parent data are static, then "phaseTasks" passed to child route correctly. flowAdminApp.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider){ $stateProvider .state('phase', { url: "/phases/:phase_id", template: JST['layouts/admin/flows/tasks/index'], resolve: { phaseTasks: ['$stateParams', function( $stateParams ){ return [{a: 1}] }] }, controller: 'taskListController' }) .state('phase.task', { url: "/tasks/:task_id", template: JST['layouts/admin/flows/tasks/show'], resolve: { task: ['$stateParams', 'phaseTasks', function( $stateParams, phaseTasks ){ // phaseTasks is [{a: 1}] }] }, controller: 'taskController' }) }]); How to pass data (retrieved from server) from parent route to its child route or prevent child route loading until parent route data are retrieved from database ? A: Try to implement your getPhaseTasks service method using a promise flowAdminApp.factory('taskData', [ '$resource','$q' function ($resource,$q) { return { getPhaseTasks: function (phase_id) { var defer = $q.defer(); $resource('/admin/tasks.json?phase_id=:phase_id', {phase_id:'@phase_id'}) .query({phase_id:phase_id}, function(data){ defer.resolve(data); }, function(error) { defer.reject(error); }); return defer.promise; } } }]); I think the problem currently is that the $resource api is async in nature and returns an array, which gets filled in the future. Since there is no promise available for your $state routes the resolve function does not wait.
{ "language": "en", "url": "https://stackoverflow.com/questions/18933097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Xpath selector does not work I'm quite new in XPath and I can't figure out what's wrong with this selector: '//div[@id="records"].//div[@class="record"]' The structure html: The thing is that I want to get all <div class="record"> elements. What's wrong please? EDIT: Elaborated snippet: A: your xpath wrong syntax, just get rid of the "." and you'll get all the div elements with attribute class="record" '//div[@id="records"]//div[@class="record"]' if (as you said in the comments) you want to get all anchor elements then try this xpath: '//div[@id="records"]/div[@class="record"]/a[contains(@href,"firma")]'
{ "language": "en", "url": "https://stackoverflow.com/questions/33733326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the Dojo Equivalent to Button Click In JavaScript - If I want to fire a button I do this - <button type = 'button' id='myButton'>HiddenButton</button> <script> function callAutoClick(){ document.getElementById('myButton').click(); } </script> When I want to fire this button click, say, onChange of a text field - <input type= 'text' onchange ='callAutoClick()'/> I am not able to do the same in DOJO. I have found a solution using Javascript - var divId = document.getElementById('myDivID'); divId.getElementsByTagName("button")[0].click(); But I don't want to have the dependency with the DivID. Is it possible to click a button just knowing the button's controlID. All I could find online were methods to define an OnClick() using dojo for a button and not clicking the button itself. Plus I am designing the page with a BPM Tool so on including sections the DivID changes. When I open the page in FireBug I can see this - <div id="div_1_1_2_1" class="Button CoachView CoachView_invisible CoachView_show" data-ibmbpm-layoutpreview="vertical" data-eventid="boundaryEvent_2" data-viewid="Hidden_Cancel" data-config="config23" data-bindingtype="" data-binding="" data-type="com.ibm.bpm.coach.Snapshot_2d5b8abc_ade1_4b8c_a9aa_dfc746e757d8.Button"> <button class="BPMButton BPMButtonBorder" type="button">Hidden_Cancel</button> </div> If you guys could suggest me a way to access the DOM object using the data-viewId also it would cater to my need. Thanks in advance :) A: You can use dojo/query: function progClick() { require(["dojo/query"], function(query) { query("div[data-viewid=myViewId] > button").forEach(function(node) { node.click(); }); }); } <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/dojo/1.10.1/dojo/dojo.js" data-dojo-config="async: true"></script> <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/dojo/1.10.1/dijit/themes/claro/claro.css"> </head> <body class="claro"> <div id="everChangingId" data-viewid="myViewId"> <button type="button" onclick="alert('my button got clicked!')">My Button</button> </div> <hr/> <button type="button" onclick="progClick()">Programatically Click My button</button> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/26880977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Expand one card on click Currently using Material-UI-React for the first time to build out cards that expand, the issue I'm running into is when I click on one card to expand, they all expand.How can I refactor my code to only allow the card that is clicked on to expand not affecting the others? const useStyles = makeStyles(theme => ({ card: { maxWidth: 300 }, media: { height: 0, paddingTop: '56.25%' // 16:9 }, expand: { transform: 'rotate(0deg)', marginLeft: 'auto', transition: theme.transitions.create('transform', { duration: theme.transitions.duration.shortest }) }, expandOpen: { transform: 'rotate(180deg)' } })); const HomePageCards = props => { console.log(props); const classes = useStyles(); const [expanded, setExpanded] = React.useState(false); function handleExpandClick() { setExpanded(!expanded); } return ( <Card className={classes.card}> <CardHeader title={props.title} subheader={`User: ${props.username}`} /> <CardMedia className={classes.media} image='https://source.unsplash.com/1600x900/?crafts' title={props.title} /> <CardContent> <Typography variant='body2' color='textSecondary' component='p'> {props.description} </Typography> </CardContent> <CardActions disableSpacing> <IconButton className={clsx(classes.expand, { [classes.expandOpen]: expanded })} onClick={handleExpandClick} aria-expanded={expanded} aria-label='show more' > <ExpandMoreIcon /> </IconButton> </CardActions> <Collapse in={expanded} timeout='auto' unmountOnExit> <CardContent> <Typography paragraph>Method:</Typography> <Typography paragraph> <strong>Step 1:</strong> {props.step_1} </Typography> <Typography paragraph> <strong>Step 2:</strong> {props.step_2} </Typography> <Typography paragraph> <strong>Step 3:</strong> {props.step_3} </Typography> <Typography> <strong>Step 4:</strong> {props.step_4} </Typography> <Typography> <strong>Step 5:</strong> {props.step_5} </Typography> </CardContent> </Collapse> </Card> ); }; import React, { useEffect, useState } from 'react'; import Axios from 'axios'; import HomePageCards from '../HomePageCards/HomePageCards'; const HomePage = props => { const [users, setUsers] = useState([]); useEffect(() => { const token = localStorage.getItem('token'); Axios.get('https://bw-how-to.herokuapp.com/guides', { headers: { authorization: token } }) .then(res => { // console.log('Data', res.data); setUsers(res.data); }) .catch(err => console.error(err)); }, []); return ( <div className='character-list grid-view'> {users.map(user => ( <HomePageCards {...user} key={user.id} /> ))} </div> ); }; export default HomePage; I looked around but can't seem to find the solution. Any suggestions or guidance would be greatly appreciated. Thank you in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/57699182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Contact Form 7 allow in HTML tag area How can I enable contact form 7 shortcode in HTML area( Where only allow html tag ) . [contact-form-7 id="2358" title="Contact Form 1"] Actually, I would like to allow 3rd slide of my web site. http://vistabrand.com/ A: You can output it in php like this <?php echo do_shortcode( '[contact-form-7 id="617" title="capta contact form"]' ); ?> Search on web little bit before posting, Search on web little bit before posting, I found this on Google.
{ "language": "en", "url": "https://stackoverflow.com/questions/23215157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I control visibility of generated protobuf-classes in Java? I found an answer for .NET, but can't find a way for Java. I'd like to set the visibility of the generated protobuf-classes automatically to private. Currently, when I compile my .proto-Files, everything is set to public.
{ "language": "en", "url": "https://stackoverflow.com/questions/75373473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Only a part of data ca be inserted into csv I want to insert all data which I scrape from web into csv, but only a part of info can be inserted! why this happen should I use MySQL database instead of csv And I want to connect this csv file to web browser by using flask. plus when I insert many import text like "import re" into top of the function "input_to_output(site,oc,id,place,pg)" after "import csv" , I can not import most of them. Is this because csv method do something? The most thing I want to know is the first one why only a part of data can be inserted. def townwork_page(oc,place,pg): import csv import re from bs4 import BeautifulSoup import requests name_list=[] ac={"":"","北海道":"101","青森":"110","東京":"041","茨城":"047","千葉":"043","埼玉":"044","群馬":"045","神奈川":"042","栃木":"046",\ "秋田":"110","岩手":"109","山形":"108","宮城":"106","福島":"107","静岡":"600","愛知":"081","岐阜":"085","山梨":"118","新潟":"117","福井":"124",\ "長野":"116","滋賀":"064","富山":"122","石川":"123","三重":"084","奈良":"065","和歌山":"066","京都":"063","大阪":"061","兵庫":"062","鳥取":"133",\ "島根":"134","岡山":"132","佐賀":"441","山口":"135","広島":"131","香川":"136","徳島":"138","愛媛":"137","高知":"139","福岡":"440","長崎":"442",\ "大分":"444","熊本":"443","宮崎":"445","鹿児島":"446","沖縄":"447"} jc={"":"","IT/コンピュータ":"005","営業":"009","専門職/その他":"017","レジャー/エンタメ":"011","接客/サービス":"010","物流/配送":"012","建築/土木":"013","教育":"014"\ ,"医療/介護/福祉":"015","飲食/フード":"001","販売":"002","事務":"003","総務/企画":"004","IT/コンピュータ":"005","軽作業":"018","芸能":"008","マスコミ/出版":"007",\ "工場/製造":"019"} if any([oc not in jc, place not in ac]): print("Input collectlly!") return "" if type(oc)==str: oc=oc,"" if type(place)==str: place=place,"" url_form="https://townwork.net/joSrchRsltList/?" if oc: for i in oc: if i: url_form+="jc="+jc[i]+"&" if place: for j in place: if j: url_form+="ac="+ac[j]+"&" if pg: for l in range(1,pg+1): url_form+="pg="+str(l)+"&" if url_form[-1]=="&": url_form=url_form[:-1] res=requests.get(url_form) soup=BeautifulSoup(res.text,"html.parser") company_name=soup.findAll(class_="job-lst-main-ttl-txt") for i in company_name: if i.get_text().split() not in name_list: name_list.append(i.get_text().split()) return name_list def input_to_output(site,oc,id,place,pg): import csv if site=="タウンワーク": with open ("output.csv","w+",newline='',encoding="utf-8") as csvFile: try: writer=csv.writer(csvFile,lineterminator='\n') writer.writerow(["information"]) for line in townwork_page(oc,place,pg): writer.writerow(line) finally: csvFile.close() elif site=="食べログ": with open ("output.csv","w+",newline='') as csvFile: try: writer=csv.writer(csvFile) writer.writerow(("information")) writer.writerow((tabelog_page(place,pg))) finally: csvFile.close() else: print("write collectlly!") input_to_output("タウンワーク","営業","","北海道",10) scraping site is "タウンワーク". Is there any grammer problem
{ "language": "en", "url": "https://stackoverflow.com/questions/55665130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to implement Google's DoubleClick Ads in an android application? How do we implement google's double click for displaying ads in our android application? Can someone provide me steps that needs to be followed to implement the same. Thanks in advance A: Check this link - http://code.google.com/mobile/afma_ads/docs/ it explains it all (well most of it to get started!) I went on a similar path looking for a ad serving support in my android app - eventually I settled for Mobclix - I am happy :-) Check the question I had posed at Serving Ads in Android App -
{ "language": "en", "url": "https://stackoverflow.com/questions/5468775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Chrome Packaged App: Open Website in New Tab I'm updating one of my chrome apps to just launch the web app (why? I don't have the time to continue updating the chrome app, alone with the desktop apps for offline use) Here's what the manifests starts with... "app": { "background": { "scripts": [ "background.js" ] } }, I just want it to open a new tab to the website now instead of launching a packaged app. So I tried the following... "app": { "launch": { "web_url": "http://stackoverflow.com/" } }, An error occurred: Failed to process your item. Please specify background subsection of app section in the manifest. "app": { "launch": { "web_url": "http://stackoverflow.com/" }, "background": { "scripts": [ "background.js" ] } }, An error occurred: Failed to process your item. Application specifications for packaged and hosted apps are incompatible. Please refer to manifest specification. The manifest may not contain a launch object inside the app object. So I decided to stick with just the background script and try to just create a new tab that way. background.js chrome.app.runtime.onLaunched.addListener(function(launchData) { chrome.app.window.create( 'index.html', { id: 'mainWindow', innerBounds: { 'width': 800, 'height': 600 } } ); }); index.html <script> var a = document.createElement("a") a.href = "http://stackoverflow.com/" a.target = "_blank" document.body.appendChild(a) a.click() </script> I was finally able to successfully add a new tab with... chrome.app.runtime.onLaunched.addListener(function(launchData) { window.open("http://stackoverflow.com/") }) in my background.js script. However the following error occurs... I clicked on the "Learn More" button but that too gave me the same "Aw, Snap!" page Does anyone know why I can't open a new tab in a chrome packaged app? and How am I suppose to open a new tab in a chrome packaged app? A: Use chrome.browser.openTab({ url: "" }, callback) with the "browser" permission. https://developer.chrome.com/apps/browser#method-openTab
{ "language": "en", "url": "https://stackoverflow.com/questions/36526684", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Other Users Cannot Connect to SQL Data Connection I have been banging my head for hours now trying to figure out this issue. Currently, I have an Excel 2013 file that I created with a few pivot charts. The pivot charts are connected to SQL Server 2012. I personally can refresh the data without any issues on my end, however whenever someone else tries to open the database connection they receive the following error. I have tested this on multiple users and each one experiences the same error. Any suggestions on what's going on here? A: Either your users need to instal the same SQL Server driver you use, or you need to change yours to match their drivers: https://support.microsoft.com/en-us/help/2022518/error-message-class-not-registered-when-you-update-powerpivot-data
{ "language": "en", "url": "https://stackoverflow.com/questions/44423068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: objective c setter method memory management I have question about allocating and releasing objects: if I have code like this: MyObject *object = [[MyObject alloc] init]; NSMutableString *string = [[NSMutableString alloc]initWithString:@"bla"]; object.myString = string; NSLog(@"retain count: %d",[object.myString retainCount]); //gives me 2 [string release]; NSLog(@"retain count: %d",[object.myString retainCount]); //gives me 1 Than I have exactly what I want. I need just one reference and I have retain count 1 but if I use object.myString = [[NSMutableString alloc]initWithString:@"bla"]; my property look like this: @property (nonatomic,retain) NSMutableString *myString; one alloc, and one setter method with retain gives me as retain count 2 If I release the object after resignment than the app crashes. I dont know why? So , do i have to always create an object with a temporary reference, than assign to real reference and release the temp reference like first code? or is there any other way? A: Yes and no. Generally, this is a common pattern: // create the object, retain count 1 MyObject *myObject = [[MyObject alloc] init]; // increment the retain count in the setter self.myObjectProperty = myObject; // let go of the object before the end of the current method [myObject release]; You can avoid the release, sort of, by using autorelease pools. More accurately, you indicate that you want the object to be released soon: MyObject *myObject = [[[MyObject alloc] init] autorelease]; self.myObjectProperty = myObject; // all done! With many of the Apple-provided classes, you can use class methods other than alloc/init to get objects that are already autoreleased. Your example could be rewritten as: MyObject *myObject = [[MyObject alloc] init]; myObject.myString = [NSMutableString stringWithFormat:@"bla"]; A final note: -retainCount is a blunt object. Particularly with NSStrings and other built-in classes, it may return results that are quite different from what you expect. Generally you should avoid it.
{ "language": "en", "url": "https://stackoverflow.com/questions/3538610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# anonymous method/block? I cannot understand this piece of code what is the "ViewDissapearing"? And what about "add" and "remove" blocks? public event EventHandler ViewDisappearing; public event EventHandler ViewDissapearing { add { ViewDisappearing += value; } remove { ViewDisappearing -= value; } } A: This is done to provide two names for the same event. "ViewDissapearing" is how the event was previously wrongly named, and all existing code that subscribes to the "ViewDissapearing" event is instead rerouted to subscribe to the new correctly spelt "ViewDisappearing" event instead. The add { ... } block is executed when someone calls ViewDissapearing += ..., which does nothing more than ViewDisappearing += that same .... Similarly for the remove { ... } block and -=. A: This is to allow other code to attach to this event. This is the same idea as the Get / Set Property of a variable. For Events it is Add / Remove. As with Properties of variables, you can use the Variable directly, or you can use an Property. You usually use the Properrty if you want to add some custom code when adding a event. A: This is explicitly stating what is normally autogenerated by the compiler for an event in a class.
{ "language": "en", "url": "https://stackoverflow.com/questions/10982292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I convert quaternion values to specific angles I'm getting quaternion values, and I want to convert these values to 2 angles. One of the angles is between the "ground plane" (please correct me if this is an incorrect name for it) and the fictional vector between the origin and the quaternion point ( the complementary angle of gamma ). The second angle is the rotational angle, this is the rotation that the vector has made relatively to a plane perpendicular to the vector ( R in the picture ). I looked lot up on the internet, but everything I try has a range of -90° to 90°, while I want it to go from -180° to 180°. This is the last version of code I ended up with: float gx = 2 * (x*z - w*y); float gy = 2 * (w*x + y*z); float gz = w*w - x*x - y*y + z*z; float yaw = atan2(2*x*y - 2*w*z, 2*w*w + 2*x*x - 1); // about Z axis float pitch = atan(gx / sqrt(gy*gy + gz*gz)); // about Y axis float roll = atan(gy/gz); // about X axis Serial.print(" yaw "); Serial.print(yaw * 180/M_PI,0); Serial.print(" pitch "); Serial.print(pitch * 180/M_PI,2); Serial.print(" sideways "); // Don't mind this section as I'm applying a mathematical function I created if(pitch > 0) Serial.println((roll * 180/M_PI) * (1/(1+pow(1.293,((pitch * 180/M_PI)-51.57)))), 2); else if(pitch == 0) Serial.println(roll * 180/M_PI, 2); else if(pitch < 0) Serial.println((roll * 180/M_PI) * (1/(1+pow(1.293,(((pitch) * (-180)/M_PI)-51.57)))), 2); A: You should always use atan2(y,x) instead of atan(y/x). It is a common mistake. – Somos He wrote this on a math form were I asked this too, and that was my stupid mistake -_- My new version is: float gx = 2 * (x*z - w*y); float gy = 2 * (w*x + y*z); float gz = w*w - x*x - y*y + z*z; float yaw = atan2(2*x*y - 2*w*z, 2*w*w + 2*x*x - 1); // about Z axis float pitch = atan2(gx, sqrt(gy*gy + gz*gz)); // about Y axis float roll = atan2(gy, gz); // about X axis /*Serial.print(" yaw "); Serial.print(yaw * 180/M_PI,0);*/ Serial.print(" pitch "); Serial.print(pitch * 180/M_PI,2); Serial.print(" sideways "); // Please don't pay attention to the extra function I made for the project but it doesn't have to do with the problem if(pitch > 0) Serial.println((roll * 180/M_PI) * (1/(1+pow(1.293,((pitch * 180/M_PI)-51.57)))), 2); else if(pitch == 0) Serial.println(roll * 180/M_PI, 2); else if(pitch < 0) Serial.println((roll * 180/M_PI) * (1/(1+pow(1.293,(((pitch) * (-180)/M_PI)-51.57)))), 2);
{ "language": "en", "url": "https://stackoverflow.com/questions/54204844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Navigation based application without a uitableview error I do this: First create navigation based application. Then delete UITableView from rootViewController.xib, add a UIView connect it to File's Owner. Change UITableView to UIViewController in RootViewcontroller.h Finally clean all methods of UITableView in RootViewcontroller.m But when I run the project receives this error: -[RootViewcontroller tableView:numberOfRowsInSection:]:unreconized selector sent to instance What am I doing wrong? A: There are a few possibility. * *Make sure that UITableView protocol is implemented in the header file. Eg @interface TestingViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> *Check that your connection from in the Interface Builder and make sure its linked properly
{ "language": "en", "url": "https://stackoverflow.com/questions/7725011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Datepicker Javafx I am facing difficulty in date picker implementation (JAVAFX). I need these characters in my date picker I want to restrict only numeric input and a specific length of input in the date picker.It should have fixed / / in it which cannot be removed by user.
{ "language": "en", "url": "https://stackoverflow.com/questions/71780468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android: best way(9 patch or gradient shape in xml) to draw two gradients(see screenshot) I need to add background to a textview, the background has two parts: top half is a gradent from color A to B, bottom part is a gradient from color C to D and B does not equal to C, it is actually a semi-transparent shadow, I intentionally put an orange layer underneath it to make it clear to see. I am looking for the best way to do it, using shape/gradient only allows me setting startColor, centerColor and endColor but I need for color points. Using 9 patch is a bit complicated. Or can I merge two gradients together so each has two colors and together give me four colors? Thanks! A: 9 patch seems the simplest way to achieve what you want. And I believe, it would generate less computations to display your image. 9 patch is not so complicated, even easy. Did you try the android 9 patch tool?
{ "language": "en", "url": "https://stackoverflow.com/questions/6400987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: yii active record join models Using Yii framework. I have 3 models. Articles - table articles(id, name) ArticlesToAuthors - table articles_to_authors (id, article_id, author_id, type) Authors - table authors (id, name) I need to get authors.*, article_to_authors.type for specific article_id. I was trying to make relation in ArticlesToAuthors model like that: 'authors' => array(self::HAS_MANY, 'Authors', array('id' => 'author_id'), ), then i made query: $authors = ArticlesToAuthors::model()->with('authors')->findAll(array('condition' => 'article_id=2217') ); foreach($authors as $a) { //this is not working #var_dump($a->authors->name); #var_dump($a->name); //this works fine foreach($a->authors as $aa) { var_dump($aa->name); } } * *Can i get all active record object in one and not to do foreach in foreach? I need an analogue to sql "SELECT atoa., a. FROM articles_to_authors atoa LEFT JOIN authors a ON atoa.author_id=a.id WHERE atoa.article_id=:article_id" *Am i doing right? p.s. - sorry for my bad english. A: It looks like you need the following relations: in your ArticlesToAuthors table: 'author' => array(self::BELONGS_TO, 'Authors', 'author_id'), 'article' => array(self::BELONGS_TO, 'Articles', 'article_id'), and, for completeness, in your Authors table: 'articlesToAuthors' => array(self::HAS_MANY, 'ArticlesToAuthors', array('id' => 'author_id'), ), This should allow you to access $a->author->name. Not tested, that's just off the top of my head.
{ "language": "en", "url": "https://stackoverflow.com/questions/11878810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Pyqt add 9 elements in layout and then lot of layout in group box I want to make elements in row in one layout and a lot of layouts will be in GroupBox, it must be like this. Result Interface I try to release this formLayout = QFormLayout() for i in range(50): formLayout.addRow(QLabel(i), QPushButton("Start")) groupBox.setLayout(formLayout) self.scrollArea.setWidget(groupBox) self.scrollArea.setWidgetResizable(True) Result from code I know that i should make in grib layout, because i have a lot of elements, but how can I create a layout with layouts which everyone have 9 elements? Just explain how it should be grouped , like this scrollArea->groupBox->formLayout.addrow(elements) I don't need full code, him I can write myself. A: The layout you're showing is not a form layout, it could be a grid layout, but it actually seems more like a QTableView (or QTableWidget) or even a QTreeView (if those small arrows on the left are used to expand elements). Using nested layouts in this case might not be a good solution, as each layout would be independent from the others, with the result that the widgets might not be properly aligned. This small arrows for expand element in that case a QTreeView with a QStandardItemModel or a QTreeWidget might help, then use setItemWidget() to add buttons. – musicamante
{ "language": "en", "url": "https://stackoverflow.com/questions/70205317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Header android 9patch I would like to create a full screen header for Android. I created the image that is 70 * 480 px (& 9patch). how can I do? I tried using the galaxy tab .. but it does not fill the screen horizontally. This is the code: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:foo="http://schemas.android.com/apk/res/aaa.bbb" android:id="@+id/db1_root" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/background"> <ImageView android:src="@drawable/header" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="top" > </ImageView> thanks in advance. A: You need to set the android:scaleType and optionally android:adjustViewBounds. Play around with these two attributes to get the desired effect. http://developer.android.com/reference/android/widget/ImageView.html#attr_android:scaleType A: Use this code to add your ImageView to the xml file <shush.android.util.AspectImageView android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/header" /> Add this class: package shush.android.util; import android.content.Context; import android.util.AttributeSet; import android.view.View; /** * @author Sherif elKhatib * */ public class AspectImageView extends View { public AspectImageView(Context context) { super(context); } public AspectImageView(Context context, AttributeSet attrs) { super(context, attrs); } public AspectImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = MeasureSpec.getSize(widthMeasureSpec); int height = width * getBackground().getIntrinsicHeight() / getBackground().getIntrinsicWidth(); setMeasuredDimension(width, height); } } A: try this <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:foo="http://schemas.android.com/apk/res/aaa.bbb" android:id="@+id/db1_root" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/background"> <ImageView android:src="@drawable/header" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_gravity="top" > </ImageView>
{ "language": "en", "url": "https://stackoverflow.com/questions/10634541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add picture to JLabel? How to add a picture to JLabelin Java? A: You can use ImageIcon JLabel l = new JLabel(new ImageIcon("path-to-file")); A: Try this code: ImageIcon imageIcon = new ImageIcon("yourFilepth"); JLabel label = new JLabel(imageIcon); For more Info A: jLabel1 = new javax.swing.JLabel(); jLabel1.setIcon(new javax.swing.ImageIcon("C:\\Users\\admin\\Desktop\\Picture 34029.jpg")); Here i posted the code that got generated automatically in netbeans.Hope my code helps in this regards keep coding goodluck. A: You have to supply to the JLabel an Icon implementation (i.e ImageIcon). You can do it trough the setIcon method, as in your question, or through the JLabel constructor: Image image=GenerateImage.toImage(true); //this generates an image file ImageIcon icon = new ImageIcon(image); JLabel thumb = new JLabel(); thumb.setIcon(icon); I recommend you to read the Javadoc for JLabel, Icon, and ImageIcon. Also, you can check the How to Use Labels Tutorial, for more information. Also have a look at this tutorial: Handling Images in a Java GUI Application
{ "language": "en", "url": "https://stackoverflow.com/questions/35480659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PowerShell: Difference between (ConvertTo-* | Set-Content) and (Export-*)? I'm new to PowerShell, and trying to learn things the write way, I noticed in this case that I can export data in many different manners, what I want to ask about is this case, Get-Process | ConvertTo-Csv | Set-Content -Path .\Process.txt and : Get-Process | Export-Csv -Path .\Process.txt Both exports the list of the processes into a CSV file on my desktop, and give the same result. The first one : Converts the processes to CSV first then it writes it onto the file. The second one : Exports the Processes directly to the file. What's really the difference between the two cases, is there performance difference, time execution difference, or anything else I'm not aware of ? A: They are pretty much the same. There shouldn't be any big difference when it comes to performance and time: Measure-Command { Get-Process | ConvertTo-Csv | Set-Content -Path .\Process.txt } Days : 0 Hours : 0 Minutes : 0 Seconds : 2 Milliseconds : 880 Ticks : 28801761 TotalDays : 3,33353715277778E-05 TotalHours : 0,000800048916666667 TotalMinutes : 0,048002935 TotalSeconds : 2,8801761 TotalMilliseconds : 2880,1761 Measure-Command { Get-Process | Export-Csv -Path .\Process2.txt } Days : 0 Hours : 0 Minutes : 0 Seconds : 2 Milliseconds : 772 Ticks : 27724661 TotalDays : 3,20887280092593E-05 TotalHours : 0,000770129472222222 TotalMinutes : 0,0462077683333333 TotalSeconds : 2,7724661 TotalMilliseconds : 2772,4661 This is because Export-CSV and ConvertTo-CSV run 90% of the same code. They share the same helper-class Microsoft.PowerShell.Commands.ExportCsvHelper to create the header and convert objects to csv. The only difference is that ConvertTo-CSV writes the CSV-object(string) to the pipeline using WriteObject(), while Export-CSV directly writes it to a file using a StreamWriter. To find this yourself, you could look inside Microsoft.PowerShell.Commands.Utility.dll. I won't be posting the code directly because I'm not sure if it's legal or not. :-) If you need the CSV-output to be displayed or sent through a third-party API etc., then use ConvertTo-CSV. If you need the data stored in a CSV-file, then you should use Export-CSV.
{ "language": "en", "url": "https://stackoverflow.com/questions/24975679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to test mp3 upload in Django DRF, via PUT? I try to test mp3 modification (hence PUT). I have the following so far: client = Client() with open('my_modified_audio.mp3', 'rb') as fp: response = client.put( f"/resource/{resource_id}/", data={'audio': fp}) However, I get response.status_code == 415 because the serializer line in DRF's ModelViewSet serializer = self.get_serializer(instance, data=request.data, partial=partial). fails with rest_framework.exceptions.UnsupportedMediaType: Unsupported media type "application/octet-stream" in request. I have tried setting format="multipart", setting the content type to json or form-encoded, nothing helped so far. The Resource model uses FileField: class Resource(models.Model): audio = models.FileField(upload_to='uploads') How can I make this put request work? A: I think that the following will work: The client: import requests ... client = Client() files = [('audio': open('my_modified_audio.mp3', 'rb'))] url = f"/resource/{resource_id}/" # response = client.put(url, data=None, files=files) # You can test it using the `requests` instead of Client() response = requests.put(url, data=None, files=files) The serializer: class AudioSerializer(serializers.Serializer): """ AudioSerializer """ audio = serializers.FileField(...) def create(self, validated_data): ... def update(self, instance, validated_data): ... The view: from rest_framework.generics import UpdateAPIView class AudioView(UpdateAPIView): ... parser_classes = (FormParser, MultiPartParser) serializer_class = AudioSerializer ... A: Inspired by @athansp's answer, I compared the source code of client.post and client.put and it turns out, put's implementation slightly differs from post, so a workable way of submitting files with put is: from django.test.client import MULTIPART_CONTENT, encode_multipart, BOUNDARY client = Client() with open('my_modified_audio.mp3', 'rb') as fp: response = client.put( f"/resource/{resource_id}/", data=encode_multipart(BOUNDARY, { 'other_field': 'some other data', 'audio': fp, }), content_type=MULTIPART_CONTENT ) Lol.
{ "language": "en", "url": "https://stackoverflow.com/questions/67035864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change element tag name Mootools I am at the end , sooo many posts and Fiddle examples on how to change tag name of all elements on page with Jquery but NONE with mootools. Is there any way to do it? I need to convert all tr to div, not able to change the actual page html, must do it with Moo. Please help. i have 15 tr's in a div , crazy huh! <div id="mydiv"> <tr></tr> <tr></tr> ... </div> I need to convert them to divs but keep all attributes and html within tr's in tact. PLEASE help! Thank you! A: Replacing elements in mootools is easy, as long as the markup is not invalid as above. http://jsfiddle.net/dimitar/4WatG/1/ document.getElements("#mydiv span").each(function(el) { new Element("div", { html: el.get("html") }).replaces(el); }); this will replace all spans for divs in the above markup (use spans instead of trs). as stated up, http://jsfiddle.net/dimitar/4WatG/ -> firefox strips invalid markup of TR not being a child of a table which makes it hard to target. A: I'm just going to leave this floating here. Element.implement({'swapTagName': function(newTagName) { return new Element(newTagName, {html: this.get('html')}).replaces(this); }}); Usage: //cleaning HTML3.2 like it's 2012 target.getElements('font[size=5pt],b').swapTagName('h2').addClass('header_paragraphs'); target.getElements('font').swapTagName('p');
{ "language": "en", "url": "https://stackoverflow.com/questions/7736970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Passing data from bootstrap model I am trying to pass the data from bootstrap model and display it on a table. However, the problem here is I am unable to pass the data and the column only display null values. I am a newbie, so I need some help on how to pass the data Day and Session? <table class="table order-list" id="myTable"> <thead> <tr> <th> Day </th> <th> Type </th> </tr> </thead> <tbody> </tbody> </table> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> </div> <div id="daypicker" class="modal-body"> <div class="container"> <h5>Select A Day: </h5> <select class="selectpicker" data-style="btn-info" multiple data-max-options="1" data-live-search="true"> <optgroup label="Day"> <option>Monday</option> <option>Tuesday</option> </optgroup> </select> <h5>Select A Session: </h5> <select class="selectpicker" data-style="btn-info" multiple data-max-options="1" data-live-search="true"> <optgroup label="Session"> <option>Morning</option> </optgroup> </select> </br> </br> </div> </div> </br> </br> </br> <div class="modal-footer"> <button id="addrow" type="button" class="btn btn-primary">Add</a> <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button> </div> </div> </div> </div> <script> $(document).ready(function () { var counter = 0; $("#addrow").on("click", function () { var newRow = $("<tr>"); var cols = ""; cols += '<td><input type="text" class="form-control" name="Day' + counter + '"/></td>'; cols += '<td><input type="text" class="form-control" name="Session' + counter + '"/></td>'; newRow.append(cols); $("table.order-list").append(newRow); counter++; }); }); </script> A: * *You haven't closed the tag correctly for the "#addrow" button. *You can extract the values from the modal like so (after you give the <select> elements a proper id: var dayPickerSelect1 = $("#daypicker-select1").val(); var dayPickerSelect2 = $("#daypicker-select2").val(); *You can then pass the extracted values to the table like so: <input type="text" class="form-control" name="Day' + counter + '" value="' + dayPickerSelect1 + '"/> <input type="text" class="form-control" name="Session' + counter + '" value="' + dayPickerSelect2 + '"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/38767998", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pass null arguments to native module in React-Native android I have a react-native NativeModule with a single method @ReactMethod public void sendEvent(String message, Integer code) { ... } I want to be able to pass null for the code argument in js, but when I do e.g. TestModule.sendEvent('this is a test', null); I get com.facebook.react.bridge.NativeArgumentsParseException: TypeError: expected dynamic type `double', but had type `null' (constructing arguments for TestModule.sendEvent at argument index 1) How can null be passed as an argument? A: You can't pass null in Integer values. public void sendEvent(String message, Integer code) { Here Integer code return invalid either pass 0 or change it to String code So now you can pass null values.
{ "language": "en", "url": "https://stackoverflow.com/questions/45731730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Heroku nodejs Procfile never picked up It seems that my nodejs application is never deploying on Heroku. While my build successfully completes with the following message: [154] ./server.ts 2.1 kB {0} [built] [238] ./src 160 bytes {0} [built] [244] (webpack)/buildin/module.js 517 bytes {0} [built] [259] ./dist/server/main.bundle.js 76.1 kB {0} [built] + 301 hidden modules Node server listening on http://localhost:5000 I'm only just seeing Heroku's Blank app: Other symptoms: My builds never end: And no dynos are being instantiated: This is despite the fact that I'm providing a Procfile, like so: web: npm start See my package.json: { "name": "vivonslagrasse-app", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "start": "node dist/server.js", "build": "ng build --prod", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e", "universal": "ng build --prod --aot && ng build --prod --app ssr --output-hashing=false && webpack --config webpack.server.config.js --progress --colors && node dist/server.js", "postinstall": "npm run universal" }, "private": true, "dependencies": { "@angular/animations": "^5.2.0", "@angular/common": "^5.2.0", "@angular/compiler": "^5.2.0", "@angular/core": "^5.2.0", "@angular/forms": "^5.2.0", "@angular/http": "^5.2.0", "@angular/platform-browser": "^5.2.0", "@angular/platform-browser-dynamic": "^5.2.0", "@angular/platform-server": "^5.2.9", "@angular/router": "^5.2.0", "@nguniversal/module-map-ngfactory-loader": "^5.0.0-beta.8", "@ngx-translate/core": "^9.1.1", "@ngx-translate/http-loader": "^2.0.1", "@nicky-lenaers/ngx-scroll-to": "^0.6.0", "ngx-cookie": "^2.0.1", "core-js": "^2.4.1", "foundation-sites": "^6.4.4-rc1", "rxjs": "^5.5.6", "ts-loader": "^3.5.0", "xmlhttprequest": "^1.8.0", "zone.js": "^0.8.19" }, "devDependencies": { "@angular/cli": "~1.7.0", "@angular/compiler-cli": "^5.2.0", "@angular/language-service": "^5.2.0", "@types/jasmine": "~2.8.3", "@types/jasminewd2": "~2.0.2", "@types/jquery": "^3.3.1", "@types/node": "~6.0.60", "codelyzer": "^4.0.1", "jasmine-core": "~2.8.0", "jasmine-spec-reporter": "~4.2.1", "karma": "~2.0.0", "karma-chrome-launcher": "~2.2.0", "karma-coverage-istanbul-reporter": "^1.2.1", "karma-jasmine": "~1.1.0", "karma-jasmine-html-reporter": "^0.2.2", "protractor": "~5.1.2", "ts-node": "~4.1.0", "tslint": "~5.9.1", "typescript": "~2.5.3" }, "engines": { "node": "7.7.4", "npm": "5.6.0" } } Note that I need to run a node server since this is an angular universal app and the initial page's contents need to be server-generated. EDIT: I'm adding my server.ts file (the generated server.js is too long to be reproduced here) // These are important and needed before anything else import 'zone.js/dist/zone-node'; import 'reflect-metadata'; import { renderModuleFactory } from '@angular/platform-server'; import { enableProdMode } from '@angular/core'; import * as express from 'express'; import { join } from 'path'; import { readFileSync } from 'fs'; (global as any).XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; // Faster server renders w/ Prod mode (dev mode never needed) enableProdMode(); // Express server const app = express(); const PORT = process.env.PORT || 5000; const DIST_FOLDER = join(process.cwd(), 'dist'); // Our index.html we'll use as our template const template = readFileSync(join(DIST_FOLDER, 'browser', 'index.html')).toString(); // * NOTE :: leave this as require() since this file is built Dynamically from webpack const {AppServerModuleNgFactory, LAZY_MODULE_MAP} = require('./dist/server/main.bundle'); const {provideModuleMap} = require('@nguniversal/module-map-ngfactory-loader'); app.engine('html', (_, options, callback) => { renderModuleFactory(AppServerModuleNgFactory, { // Our index.html document: template, url: options.req.url, // DI so that we can get lazy-loading to work differently (since we need it to just instantly render it) extraProviders: [ provideModuleMap(LAZY_MODULE_MAP) ] }).then(html => { callback(null, html); }); }); app.set('view engine', 'html'); app.set('views', join(DIST_FOLDER, 'browser')); // Server static files from /browser app.get('*.*', express.static(join(DIST_FOLDER, 'browser'))); // All regular routes use the Universal engine app.get('*', (req, res) => { res.render(join(DIST_FOLDER, 'browser', 'index.html'), {req}); }); // Start up the Node server app.listen(PORT, () => { console.log(`Node server listening on http://localhost:${PORT}`); }); Needless to say, this setup works perfectly on my development machine... Your help will be highly appreciated. I already spent 2,5 hours on this. A: Use process.env.port in server.js to listen const port = process.env.port || 5000; app.listen(port);
{ "language": "en", "url": "https://stackoverflow.com/questions/49572544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: solr: Adding content-disposition to SolrQueryResponse I have a custom request handler that is extending RequestHandlerBase. The purpose of this handler is to search the index for the given user query. Instead of omitting the results on the browser at client side, the response data should be downloaded as a file. Here is my handleRequestBody function code @Override public void handleRequestBody(final, SolrQueryRequest req,final SolrQueryResponse res) { tempFile = File.createTempFile(UUID.randomUUID().toString(),".tmp", new File(FILE_PATH)); writeSearchResultstoFile(tempFile); ContentStreamBase outConentStream = new ContentStreamBase.FileStream(tempFile); outConentStream.setContentType("application/download"); rsp.add(RawResponseWriter.CONTENT, outConentStream); } The problem is the file is being downloaded with .part file at client side. rsp.getResponseHeader().add("Content-Disposition", "filename=data.csv"); didn't help much. Could some please tell me how to set the Content-Disposition. A: Since I see that you are formatting your results as CSV I am curious as to whether you have looked at the CSVResponseFormat that Solr has supported since release 3.1
{ "language": "en", "url": "https://stackoverflow.com/questions/9210177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trying to understand packets captured with tcpdump So I have intercepted a packet being sent from my android device to an apps server. I want to understand what my phone is sending to the server. I have rooted the phone, and install tcpdump on it. I have used adb shell to run: tcpdump -n -i wlan0 -w OUTPUT_FILE src host IP_ADDRESS and greater 200 I have gotten the packet on my pc and run it through wireshark. I have been told that the long list of "........" prevalent in the ascii section is because there is no ascii representation of the specific HEX. Is that true? I have been able to determine the packet is not encrypted, because I can see clear text strings in the ascii that I type in the app. I am guessing the data is either binary OR base64 encoded JSON, converted to hex and sent to the server. Is there any step I can take to further understand the structure of the data sent from my device to the remote server? Any other tips, or random insights would be super helpful. A: Is that true? Yes. Is there any step I can take to further understand the structure of the data sent from my device to the remote server? The captured packet includes an Ethernet Ⅱ header and an IPv4 header and a UDP header as follows: Ethernet Ⅱ: from 20:e5:2a:4f:b9:4f (NETGEAR) to 44:80:eb:ea:ef:9b (Motorola) IPv4: from 169.55.244.58 to 192.168.1.12, not fragmented UDP: from port 14242 to port 48818, payload length=1406 bytes The right chunk of the 3rd line (i.e. bb 19 43 4f 02 c8 2b a3) is the start of the application data. To analyze the application data, you need to know what protocol the application used to send the packet and to learn the protocol.
{ "language": "en", "url": "https://stackoverflow.com/questions/41499543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Keras TensorFlow Hub: Getting started with simple ELMO network I'm trying to get a simple ELMO model working from TensorFlow hub but, it's turning out to be a challenge. When I run the my code, I'm getting the error: "Inputs to eager execution function cannot be Keras symbolic tensors, but found [<tf.Tensor 'input_69:0' shape=(None, 10) dtype=string>]" I think I'm messing up the sequence_length args or the inputs. Can anyone please help me? import tensorflow as tf import tensorflow_hub as hub import re from tensorflow import keras import tensorflow.keras from tensorflow.keras.layers import Input, Dense,Flatten import numpy as np import keras.callbacks import io from sklearn.model_selection import train_test_split i = 0 max_cells = 51 #countLines() x_data = np.zeros((max_cells, 10, 1), dtype='object') y_data = np.zeros((max_cells, 3), dtype='float32') seqs = np.zeros((max_cells), dtype='int32') with io.open('./data/names-sample.txt', encoding='utf-8') as f: content = f.readlines() for line in content: line = re.sub("[\n]", " ", line) tokens = line.split() for t in range(0, min(10,len(tokens))): tkn = tokens[t] x_data[i,t] = tkn seqs[i] = len(tokens) y_data[i,0] = 1 i = i+1 def build_model(): tokens = Input(shape=[10,], dtype=tf.string) seq_lens = Input(shape=[], dtype=tf.int32) elmo = hub.KerasLayer( "https://tfhub.dev/google/elmo/3", trainable=False, output_key="elmo", signature="tokens", ) out = elmo({"tokens": tokens, "sequence_len": seqs}) model = keras.Model(inputs=[tokens, seq_lens], outputs=out) model.compile("adam", loss="sparse_categorical_crossentropy") model.summary() return model x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.70, shuffle=True) model = build_model() model.fit(x_train, y_train,validation_data=(x_test, y_test),epochs=1,batch_size=32) Full Error: TypeError: An op outside of the function building code is being passed a "Graph" tensor. It is possible to have Graph tensors leak out of the function building context by including a tf.init_scope in your function building code. For example, the following function will fail: @tf.function def has_init_scope(): my_constant = tf.constant(1.) with tf.init_scope(): added = my_constant * 2 The graph tensor has name: input_69:0 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\temp\Simon\TempElmoNames.py", line 66, in model = build_model() File "C:\temp\Simon\TempElmoNames.py", line 56, in build_model out = elmo({"tokens": tokens, "sequence_len": seqs}) File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py", line 891, in call outputs = self.call(cast_inputs, *args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_hub\keras_layer.py", line 229, in call result = f() File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\eager\function.py", line 1081, in call return self._call_impl(args, kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\eager\function.py", line 1121, in _call_impl return self._call_flat(args, self.captured_inputs, cancellation_manager) File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\eager\function.py", line 1224, in _call_flat ctx, args, cancellation_manager=cancellation_manager) File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\eager\function.py", line 511, in call ctx=ctx) File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\eager\execute.py", line 75, in quick_execute "tensors, but found {}".format(keras_symbolic_tensors)) _SymbolicException: Inputs to eager execution function cannot be Keras symbolic tensors, but found [<tf.Tensor 'input_69:0' shape=(None, 10) dtype=string>] Here are the versions I'm working with: Keras: 2.3.1 TF: 2.0.0 TH-hub: 0.12.0 UPDATE 1: I upgraded Keras (2.6.0) TF (2.6.0) & TF Hub(0.12.0) and changed the build_model method on how the seqs and seq_lens are passed. def build_model(): tokens = Input(shape=[10,], dtype=tf.string) seq_lens = Input(shape=[], dtype=tf.int32) elmo = hub.KerasLayer( "https://tfhub.dev/google/elmo/3", trainable=False, output_key="elmo", signature="tokens", ) out = elmo({"tokens": tokens, "sequence_len": seq_lens}) model = keras.Model(inputs=[tokens, seqs], outputs=out) model.compile("adam", loss="sparse_categorical_crossentropy") model.summary() return model Now I'm getting the error: ValueError: Input tensors to a Functional must come from tf.keras.Input. Received: [3 3 2 2 3 3 3 5 3 3 3 2 7 2 2 2 3 2 2 3 3 3 3 3 3 2 3 2 3 2 3 3 2 3 3 2 3 2 2 2 2 3 2 2 3 3 5 3 3 3 0] (missing previous layer metadata). A: I don't believe it is a bug rather TF gives us freedom in choosing each method. While we can mix match the layer subclass with keras functional api, I guess we can't make the model subclass work with the Model api of keras. This is where, in my opinion the distinction between eager execution and keras graph mode comes into conflict giving rise to this "SymbolicException". Making TF aware beforehand what mode it should execute solves it. A: Ok finally got it working. The first I did it upgraded: Keras: 2.2.4 TF: 1.15.0 TF: 0.12.0 Next changed my code to use the right version of ELMO model: import tensorflow_hub as hub import tensorflow as tf elmo = hub.Module("https://tfhub.dev/google/elmo/3", trainable=False) from tensorflow.keras.layers import Input, Lambda, Bidirectional, Dense, Dropout, Flatten, LSTM from tensorflow.keras.models import Model def ELMoEmbedding(input_text): return elmo(tf.reshape(tf.cast(input_text, tf.string), [-1]), signature="default", as_dict=True)["elmo"] def build_model(): input_layer = Input(shape=(1,), dtype="string", name="Input_layer") embedding_layer = Lambda(ELMoEmbedding, output_shape=(1024, ), name="Elmo_Embedding")(input_layer) BiLSTM = Bidirectional(LSTM(128, return_sequences= False, recurrent_dropout=0.2, dropout=0.2), name="BiLSTM")(embedding_layer) Dense_layer_1 = Dense(64, activation='relu')(BiLSTM) Dropout_layer_1 = Dropout(0.5)(Dense_layer_1) Dense_layer_2 = Dense(32, activation='relu')(Dropout_layer_1) Dropout_layer_2 = Dropout(0.5)(Dense_layer_2) output_layer = Dense(3, activation='sigmoid')(Dropout_layer_2) model = Model(inputs=[input_layer], outputs=output_layer, name="BiLSTM with ELMo Embeddings") model.summary() model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy']) return model elmo_BiDirectional_model = build_model() import numpy as np import io import re from tensorflow import keras i = 0 max_cells = 300 x_data = np.zeros((max_cells, 1), dtype='object') y_data = np.zeros((max_cells, 3), dtype='float32') with tf.Session() as session: session.run(tf.global_variables_initializer()) session.run(tf.tables_initializer()) model_elmo = elmo_BiDirectional_model.fit(x_data, y_data, epochs=100, batch_size=5) train_prediction = elmo_BiDirectional_model.predict(x_data)
{ "language": "en", "url": "https://stackoverflow.com/questions/69684502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Where is defined the TgtOutFormat type in PDFtoolkit VCL library? I have a problem to set watermark image format in the TgtImageWatermarkTemplate component (which is part of the Gnostice PDFtoolkit VCL library). I have the following code: var Watermark: TgtImageWatermarkTemplate; begin ... // create and set watermark properties Watermark := TgtImageWatermarkTemplate.Create; Watermark.ImageFormat := ofJPEG; // <- this line fails the compilation ... end; But it fails to compile with the following error: [DCC Error] Unit1.pas(186): E2003 Undeclared identifier: 'ofJPEG' [DCC Fatal Error] Project1.dpr(5): F2063 Could not compile used unit 'Unit1.pas' Failed Elapsed time: 00:00:01.5 In which unit is the ofJPEG identifier declared (I think it's member of the TgtOutFormat enumeration)? Which unit should I add to my uses clause? A: Please include gtCstPDFDoc unit in your PAS file. The enumeration TgtImageFormat is from that. UPDATE: The enumeration values start with if and so it is ifJPEG.
{ "language": "en", "url": "https://stackoverflow.com/questions/28655260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to add custom header to AFNetworking on a JSONRequestOperation Hi, I have the following code accessing a URL: NSString * stringURL = [NSString stringWithFormat:@"%@/%@/someAPI", kSERVICE_URL, kSERVICE_VERSION]; NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:stringURL]]; AFJSONRequestOperation * operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { completionHandler(JSON, nil); } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { completionHandler(nil, error); }]; But I want to pass the user token as a parameter on HEADER, like X-USER-TOKEN. Cant find it on AFNetworking documentation, should I change the operation type? A: I did this :) [manager.requestSerializer setValue:[NSString stringWithFormat:@"Token token=\"%@\"", _userObj.oAuth] forHTTPHeaderField:@"Authorization"]; A: Use AFHTTPClient or subclass it! You can set default headers with -setDefaultHeader:value: like this : [self setDefaultHeader:@"X-USER-TOKEN" value:userToken]; You can check the documentation A: If you have a layer of abstraction, let's say APIManager, then you should do the following inside a particular method [[HTTPClient sharedHTTPClient].requestSerializer setValue:YOUR_KEY forHTTPHeaderField:@"X-Register"]; A: NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url]; [request setValue: @"X-USER-TOKEN" forHTTPHeaderField:@"< clientToken >"]; [AFJSONRequestOperation JSONRequestOperationWithRequest: request ...]
{ "language": "en", "url": "https://stackoverflow.com/questions/15141115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Making a android button’s background translucent, Is there a way to make an android button’s background translucent within xml code, So the button has no background drawable? A: android:background="@android:color/transparent" You can also set your own colors: android:background="#80000000" The first two hex characters represent opacity. So #00000000 would be fully transparent. #80000000 would be 50% transparent. #FF000000 is opaque. The other six values are the color itself. #80FF8080 is a color I just made up and is a translucent sort of pinkish. A: Set the background to the standard android transparent color. In Code: myButton.setBackground(getResources().getColor(android.R.color.transparent)); In xml: android:background="@android:color/transparent" A: The best way is to create a selector.
{ "language": "en", "url": "https://stackoverflow.com/questions/21294782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AppDelegate.swift line 0 type metadata accessor for _ContiguousArrayStorage crash There is a strange crash happening in my code when I try upgrade the app version. Here is the crash report for the crash :- Crashed: com.apple.root.user-initiated-qos 0 libswiftCore.dylib 0x102f6f95c specialized _assertionFailure(_:_:file:line:flags:) + 164 1 Quickride 0x1011b02f8 type metadata accessor for _ContiguousArrayStorage<String> (AppDelegate.swift) 2 Quickride 0x1011a1cfc closure #1 in closure #1 in AppDelegate.persistentContainer.getter (AppDelegate.swift) 3 Quickride 0x1015196cc thunk for @callee_owned (@owned NSPersistentStoreDescription, @owned Error?) -> () (UserDataCache.swift) 4 CoreData 0x184f3d6d0 -[NSPersistentStoreCoordinator _doAddPersistentStoreWithDescription:privateCopy:completionHandler:] + 920 5 CoreData 0x184f3d8a0 -[NSPersistentStoreCoordinator addPersistentStoreWithDescription:completionHandler:] + 172 6 CoreData 0x18500100c -[NSPersistentContainer loadPersistentStoresWithCompletionHandler:] + 484 7 Quickride 0x1011a1c6c AppDelegate.persistentContainer.getter (AppDelegate.swift:670) 8 Quickride 0x10123a72c specialized static CoreDataHelper.getNSMangedObjectContext() (CoreDataHelper.swift:18) 9 Quickride 0x101131664 specialized static ContactPersistenceHelper.clearAllContacts() (ContactPersistenceHelper.swift:113) 10 Quickride 0x10123efd0 specialized UserModuleSessionManager.clearUserPersistentStore() (UserModuleSessionManager.swift:103) 11 Quickride 0x1010417d4 specialized QRSessionManager.performSessionChangeOperationOnModule(moduleSessionHandler:sessionChangeOperationId:) (QRSessionManager.swift) 12 Quickride 0x10103df24 QRSessionManager.callSessionChangeOperationOnAllModules(sessionChangeOperationId:isShutdownSequence:) (QRSessionManager.swift:256) 13 Quickride 0x10103d410 QRSessionManager.onResumeUserSession() (QRSessionManager.swift:159) 14 Quickride 0x1013125b0 SessionManagerController.resumeUserSession(sessionChangeCompletionListener:) (SessionManagerController.swift:82) 15 Quickride 0x10128b0c8 closure #1 in AppStartupHandler.resumeUserSessionAndNavigateToAppropriateInitialView() (AppStartupHandler.swift:38) 16 Quickride 0x100ee5784 thunk for @callee_owned () -> () (RideManagementModuleSessonHandler.swift) 17 libdispatch.dylib 0x181e50aa0 _dispatch_call_block_and_release + 24 18 libdispatch.dylib 0x181e50a60 _dispatch_client_callout + 16 19 libdispatch.dylib 0x181e5ddfc _dispatch_root_queue_drain + 924 20 libdispatch.dylib 0x181e5d9fc _dispatch_worker_thread3 + 120 21 libsystem_pthread.dylib 0x182183fac _pthread_wqthread + 1176 22 libsystem_pthread.dylib 0x182183b08 start_wqthread + 4 Any help guys on whats this strange crash all about ? Tried a lot but couldn't figure you..... Thanks in advance
{ "language": "en", "url": "https://stackoverflow.com/questions/53633104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problems after Importing an android project from github into Eclipse I'm trying to tinker with this project and am having some issues importing it. https://github.com/HoloAddict/FeedEx I'm a beginner still, and have made a couple of test projects from scratch, but I think I'd learn a little faster by going through working code in a larger project. Just can't get rid of errors to even build the existing code. These are the steps I have taken: * *imported it in as a Git project (file - Import - Git - Projects from Git) *gen folder error (does not exist or not source) - right clicked on gen, Buld path - Use as a source folder. This made that particular error go away *all the src files were listed as src.net.fred... packages, so all the imports were errors. Right click - build path - configure build path - added Feedex/src in build path, got rid of those errors. *have the R.java problem... tried many clean-build approaches, no luck. Also tried taking one from a clean project, creating package net.fred.feedex in gen, creating file R.java, and putting code in from a clean project, but no luck. It did make the import R go away, but of course left many errors where the res class references are broken, again because that R file is missing (I think). So that's where I am. It seems like I have an R.java problem, but I may have messed up on one of the other steps. Either way, thanks for the help. A: When you imported the project did you check the "Copy projects into workspace"? If not import your project again and see if this problem still continues.
{ "language": "en", "url": "https://stackoverflow.com/questions/20613458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: RES_NOT_FOUND after login using JAAS I am using JAAS to authenticate users accessing the protected area of my web application. The login page looks like this: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"> <h:head> <meta http-equiv="Content-Type" content="text/html; UTF-8" /> <title>Test</title> </h:head> <h:body> <ui:composition template="template/common/commonLayout.xhtml"> <ui:define name="content"> <form name="loginForm" method="post" action="j_security_check"> <table> <tr> <td colspan="2">Login to the your application:</td> </tr> <tr> <td>Select something:</td> <td><h:selectOneMenu> <f:selectItems value="#{loginScreenBean.listSomething}" /> </h:selectOneMenu><br /></td> </tr> <tr> <td>Name:</td> <td><input type="text" name="j_username" /></td> </tr> <tr> <td>Password:</td> <td><input type="password" name="j_password" /></td> </tr> <tr> <td colspan="2"><input type="submit" value="Go" /></td> </tr> </table> </form> </ui:define> </ui:composition> </h:body> </html> My web-xml looks like this: <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>patchit</display-name> <welcome-file-list> <welcome-file>test.html</welcome-file> </welcome-file-list> <security-role> <role-name>admin</role-name> </security-role> <security-constraint> <display-name>Example Security Constraint</display-name> <web-resource-collection> <web-resource-name>Protected Area</web-resource-name> <url-pattern>/protected/*</url-pattern> <http-method>DELETE</http-method> <http-method>GET</http-method> <http-method>POST</http-method> <http-method>PUT</http-method> </web-resource-collection> <auth-constraint> <role-name>admin</role-name> </auth-constraint> </security-constraint> <login-config> <auth-method>FORM</auth-method> <realm-name>Example Form-Based Authentication Area</realm-name> <form-login-config> <form-login-page>/login.xhtml</form-login-page> <form-error-page>/login-error.xhtml</form-error-page> </form-login-config> </login-config> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.xhtml</url-pattern> </servlet-mapping> <context-param> <description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description> <param-name>javax.faces.STATE_SAVING_METHOD</param-name> <param-value>client</param-value> </context-param> <context-param> <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name> <param-value>resources.application</param-value> </context-param> <listener> <listener-class>com.sun.faces.config.ConfigureListener</listener-class> </listener> </web-app> my jaas config looks like this: CustomLogin { de.kungfuzius.test.security.SimpleLoginModule sufficient; }; so when I open a page in the protected area like contextpath/protected/test.xhtml I am presented the login.xhtml with the login form. Once I hit the submit button the user is authenticated, but instead of being forwarded/redirected to the initially requested page I am redirected to contextpath/protected/RES_NOT_FOUND. To check if the user is really authenticated I tried to access contextpath/protected/test.xhtml again at it worked. Any help is greatly appreciated. Thanks! A: wow, interesting behavior. I had a look at the requests using fiddler and I found a request to context/protected/RES_NOT_FOUND. This request came from a css file which was referenced in my template, but did not exist yet. When I remove this reference to the style sheet it works!!!
{ "language": "en", "url": "https://stackoverflow.com/questions/25244465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: using font-awesome in fnCreatedCell Recently learned a new way to use data-attributes within a datatable. Previously, I would code the columns in this manner (please note the font-awesome tags): "columns": [{ "data": "", "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) { $(nTd).html("<a href='#' title='Edit Account' class='modAccount' data-voyid='"+oData.VOYID+"' data-servicename='"+oData.SERVICE_NAME+"' data-vesselname='"+oData.VESSEL_NAME+"' data-voyage='"+oData.VOYAGE+"' data-bound='"+oData.BOUND+"' data-cargoweek='"+oData.CARGO_WEEK+"' data-cargoyear='"+oData.CARGO_YEAR+"' data-allocation='"+oData.ALLOCATION+"' data-importvoyage='"+oData.IMPORT_VOYAGE+"' data-adddate='"+oData.ADD_DATE+"' data-adduser='"+oData.ADD_USER+"' data-moddate='"+oData.MOD_DATE+"' data-moduser='"+oData.MOD_USER+"'><i class='fa fa-edit fa-fw'> </i></a>"); }, The method I just learned follows this format: "columns": [{ "data": "", "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) { $('<a />', { 'href': '#', 'title': 'Edit Account', 'class': 'modAccount', 'data-voyid': oData.VOYID, 'data-servicename': oData.SERVICE_NAME, 'data-vesselname': oData.VESSEL_NAME, 'data-voyage': oData.VOYAGE, 'data-bound': oData.BOUND, 'data-cargoweek': oData.CARGO_WEEK, 'data-cargoyear': oData.CARGO_YEAR, 'data-allocation': oData.ALLOCATION, 'data-importvoyage': oData.IMPORT_VOYAGE, 'data-adddate': oData.ADD_DATE, 'data-adduser': oData.ADD_USER, 'data-moddate': oData.MOD_DATE, 'data-moduser': oData.MOD_USER, 'text': '<i class="fa fa-edit fa-fw"> </i>' <-- does not work }).appendTo(nTd); } }, I had no problem bringing in the font-awesome icon with the first piece of code. The second piece of code is where I need the icons now. If you'll notice in the 'text' section in the second piece of code, I tried to pull in the font-awesome icons there. But on screen, I only see the code, not the icon. How can I fix this to include the font-awesome icons? Thank you. A: You're adding HTML so you supply the string to the html property, instead of text in the object initialiser: 'html': '<i class="fa fa-edit fa-fw"> </i>'
{ "language": "en", "url": "https://stackoverflow.com/questions/54812815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Decrypting a string to Byte array I was doing encrypting a array of string containing only 0s and 1s like this : public String[] binaryToText1(String[] binary1, int lengthofshares) { String[] encrptedfinally = new String[lengthofshares]; for(int tt = 0; tt < lengthofshares; tt++) { String ss2 = ""; String ss = binary1[tt]; String mynextChar; ss2 = new java.math.BigInteger(ss, 2).toString(16); encrptedfinally[tt] = ss2; } return encrptedfinally; } Here lengthofshares is just the size of string array binary1.But i got stuck when i tried to convert it back to an String array of 0 and 1 I was not able to come up with a solution. Function of decryption is somewhat like this : public String[] textToBinary(String[] alpha, int myK) { String[] ans = new String[myK + 3]; for(int t = 0; t < myK; t++) { String s = alpha[t]; byte bytes[] = new byte[s.length()]; char c[] = s.toCharArray(); int i; for(i = 0; i < s.length(); i++) { bytes[i] = (byte) c[i]; } StringBuilder binary = new StringBuilder(); for(byte b : bytes) { int val = b; for(i = 0; i < 8; i++) { binary.append((val & 128) == 0 ? 0 : 1); val <<= 1; } } ans[t] = binary.toString(); } return ans; } But results are different.Please help.Am not able to get the reason for it being wrong A: Unfortunately, I don't really understand your code, and I also couldn't figure out if you just want plain String-to-byte conversion or if you also want to do some naive encrypting. In any case, I think the code below does most of what you want. It uses bitmasks to extract the bits from a 0 to 255 integer representing a char (char + 127). Similary, it uses bitwise OR to convert the binary String[] representation of the String back to chars and finally, back to a String. public static void main(String[] args) { String test = "Don't worry, this is just a test"; List<String> binary = stringToBinary(test); System.out.println(binary); System.out.println(binaryToString(binary)); } public static List<String> stringToBinary(String input) { LinkedList<String> binary = new LinkedList<String>(); char[] input_char = input.toCharArray(); for (int c = input_char.length - 1 ; c >= 0; c--) { int charAsInt = input_char[c] + 127; // Char range is -127 to 128. Convert to 0 to 255 for (int n = 0; n < 8; n++) { binary.addFirst((charAsInt & 1) == 1 ? "1" : "0"); charAsInt >>>= 1; } } return binary; } public static String binaryToString(List<String> binary) { char[] result_char = new char[binary.size() / 8]; for (int by = 0; by < binary.size() / 8; by++) { int charAsInt = 0; for (int bit = 0; bit < 8; bit++) { charAsInt <<= 1; charAsInt |= binary.get(by * 8 + bit).equals("1") ? 1 : 0; } result_char[by] = (char) (charAsInt - 127); } return new String(result_char); }
{ "language": "en", "url": "https://stackoverflow.com/questions/23017996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: click returns only the first item value in jQuery I have many products with the same class name and I want a user click on the item to return only the clicked item values but my code is returning the value of the first product only.one more thing i want when user click on images the record stores in the cart but here in my case when user click on image the selected product value returned and again when user click on another image the previous value get replace with this one i dont want to replace it i want to add in other li how it can be done. Here is my code: <div class="left"> <div class="left-top"> <ul class="add"> <li>bellle belle belle 25cl <p>2 Unit(s) at PKR 0.8/Unit(s)</p> </li> <li> PKR 1.6 </li> <li> processor amd 8-core </li> <li> PKR 1980.0 </li> <li> processor amd 8-core <p></p> </li> <li> PKR 1980.0 </li> <li>Total:PKR 1993.0 <p>Taxes:PKR 0.0</p> </li> </ul> </div> <div class="right-bottom"> <div class="box2"> <p>pkr 800.0</p> <img src="images/col.png" /> <h1>Beverges</h1> </div> <div class="box2"> <p>pkr 700.0</p> <img src="images/col.png" /> <h1>Beverges</h1> </div> <div class="box2"> <p>pkr 700.0</p> <img src="images/col.png" /> <h1>Beverges</h1> </div> <div class="box2"> <p>pkr 700.0</p> <img src="images/col.png" /> <h1>Beverges</h1> </div> <div class="box2"> <p>pkr 700.0</p> <img src="images/col.png" /> <h1>Beverges</h1> </div> <div class="box2"> <p>pkr 700.0</p> <img src="images/col.png" /> <h1>Beverges</h1> </div> <div class="box2"> <p>pkr 700.0</p> <img src="images/col.png" /> <h1>Beverges</h1> </div> <div class="box2"> <p>pkr 700.0</p> <img src="images/col.png" /> <h1>Beverges</h1> </div> <div class="box2"> <p>pkr 700.0</p> <img src="images/col.png" /> <h1>Beverges</h1> </div> <div class="box2"> <p>pkr 700.0</p> <img src="images/col.png" /> <h1>Beverges</h1> </div> <div class="box2"> <p>pkr 700.0</p> <img src="images/col.png" /> <h1>Beverges</h1> </div> <div class="box2"> <p>pkr 700.0</p> <img src="images/col.png" /> <h1>Beverges</h1> </div> <div class="box2"> <p>pkr 700.0</p> <img src="images/col.png" /> <h1>Beverges</h1> </div> <div class="box2"> <p>pkr 700.0</p> <img src="images/col.png" /> <h1>Beverges</h1> </div> <div class="box2"> <p>pkr 800.0</p> <img src="images/col.png" /> <h1>Beverg</h1> </div> </div> </div> </div> The script i have written for it is here. <script type="text/javascript"> $(document).ready(function() { $('.box2').click(function(){ var price=$(".box2 p").html(); var product=$(".box2 h1").html(); $(".add li:first-child").text(product); $(".add li:nth-child(2)").text(price); }); }); </script> A: You need too use this, this inside a JQuery event handler is the DOM element that has the handler attached. Use var price=$(this).find("p").html(); var product=$(this).find("h1").html(); instead of var price=$(".box2 p").html(); var product=$(".box2 h1").html(); A: Use $(this).find('p') //or $(this).find('h1') Instead of $(".box2 p").html() A: $(document).ready(function() { $('.box2').click(function(){ var price=$( this).find('p').html(); var product=$( this).find('h1').html(); $(".add li:first-child").text(product+ price); }); }); Your jquery should looks like Demo A: You can use like this (A faster way): $('.box2').click(function(){ var price=$(".box2 p", this).html(); var product=$(".box2 h1", this).html(); $(".add li:first-child", this).text(product); $(".add li:nth-child(2)", this).text(price); }); A: <script type="text/javascript"> $(document).ready(function() { $('.box2').click(function(){ var price=$(this).find("p").html(); var product=$(this).find("h1").html(); }); }); </script> A: try var price=$( this).find('p').html();
{ "language": "en", "url": "https://stackoverflow.com/questions/22657952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: comparing extended objects private List<Fruit> myFruit = new Vector<Fruit>(); ok so if I have a list of different types of fruit objects how could I go through the list and compare the different objects. public class Fruit{ String type; String color; } public class Grape extends Fruit{ int seedCount; public Grape(Attributes attributes){ this.type = attributes.getValue("type"); this.color=attributes.getValue("color"); this.seedCount=attributes.getValue("seedCount"); } public class Banana extends Fruit{ String color; public Banana(Attributes attributes){ this.type = attributes.getValue("type"); this.color=attributes.getValue("color"); } public load(localName name, Attributes attributes){ if (name.equalsIgnoreCase("grape"){ Grape grape = new Grape(attributes); myFruit.add(grape); } if (name.equalsIgnoreCase("banana"){ Banana banana = new Banana(attributes); myFruit.add(banana); } } So how would I go about sorting through the list of Fruit and displaying specific properties of these objects based on what type of object they are. Ie. if type=Grape display seedCount. A: * *If you want to sort Fruit, you need to implement the Comparable interface for the Fruit class. *If you want to display attributes, have an abstract method in Fruit class and provide the implementations in the subclass. This way depending on the instance of the Fruit , it will show the corresponding properties. public abstract class Fruit implements Comparable{ public abstract void displayProperties(); @Override public int compareTo(Fruit otherFruit){ return 0; } } public class Banana extends Fruit { private int seedCount; @Override public void displayProperties() { // TODO Auto-generated method stub System.out.println(seedCount); } } public class Grape extends Fruit{ private String color; @Override public void displayProperties() { // TODO Auto-generated method stub System.out.println(color); } } A: You could add an abstract method to Fruit displayProperties() You would then be forced to impliment the method for all types of fruit, then in your for loop you would just call displayProperties() A: This isn't recommended, but you could use if(object instanceof Class) { Class temp = (Class) object //operate on object } But what you should do is create a Fruit interface that gives access to the important info related to all fruit, in general you shouldn't cast down to get extra information. While downcasting isn't evil, it could mean you aren't taking full advantage of polymorphism. To take advantage of polymorphism one should ensure that the supertype the subtypes share has methods to get as much info or behavior as necessary. For example, lets say you have a list of HousePets, and the HousePets consist of the subtypes Dog and Cat. You loop over this list and want to wag all of the tails of the HousePets that can wag their tails. For simplicity there are two ways to do this, either only the Dog has the method 'wagTail()' (since Cats don't wag tails), or HousePets has a method called 'wagTail()' that is inherited by Cats and Dogs (but the Cat's version does nothing). If we choose the first example the code would look something like this: for(HousePet pet : petList) if(pet instanceof Dog) { ((Dog)pet).wagTail(); } And for the second example it would look like this: for(HousePet pet : petList) pet.wagTail(); The second example takes a little less code and is a little more streamlined. In the worst case scenario, if we go with the first option, we will need an if-block for each new subtype of HousePet, which will make the code bulkier/uglier/etc. Better yet we could have a HousePet method called "showHappiness", and the Dog would wag its tail while the cat purred. A: I think you need an instanceof operator. It allows you to check object type. if (list.get(0) instanceof Grape) { // list.get(0) is Grape }
{ "language": "en", "url": "https://stackoverflow.com/questions/14990790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Redux dispatch inside Meteor.call or get Meteor.call value My project works with Meteor and react-redux For redux to work, one must be able to access the dispatch function in the this.props of the component. However when I use Meteor.call the callback's this property does not contain the redux function dispatch as is expected. So this is my Meteor.call: var testing; Meteor.call('seed', mergedobj, function(err, seed){ if(err){ console.log('ERROR ERROR ERROR: when calling seed err', err); if(err.error === 'SWE_RISE_TRANS_NEGATIVE'){ } }else{ console.log('return of seed', seed) console.log('this', this) //this.props.dispatch(seedAction(seed)) testing = seed } }) console.log('testing', testing) //'INITIAL' and not seed!! I either need to change the this of the callback so I can call this.props.dispatch inside of the callback or I need to get the value of seed outside of the callback..... How do I achieve this? How do I get the value of seed inside variable that is outside of the callback's scope? A: How about using this syntax: const dispatch = this.props.dispatch; Meteor.call('seed', mergedobj, function(err, seed){ if(err){ // error handling here. }else{ dispatch(seedAction(seed)); } }) So you don't have to deal with this keyword.
{ "language": "en", "url": "https://stackoverflow.com/questions/48370233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tabulator getElement is not a function I currently have a tabulator table of 100 elements in the array. When I call the function to grab the specific cell, it manages to grab the first 25 rows and change the color of the specific cell that I want. The problem is that the ones after isn't changing color when everything else is the same. How do I get around it? Here is the code that I am using to generate the background color. It works for the first 25 rows but it wasn't able to grab the next 75 rows var allRowData = table.getRows(); // loops the entire row allRowData.forEach(x => { // using the row data, grab the columns and compare with a condition scope.columns.forEach(y => { if (y.priority == 3) { // checks for the priority number to add a color to it var rowCell = x.getCell(`${y.fieldName}`); rowCell.getElement().style.backgroundColor = "#F00"; } }); }); A: You should not be trying to directly manipulate the layout of the table from outside of Tabulator. Tabulator uses a virtual DOM which means that it will create and destroy elements of the table as needed, which means that you can only style elements that are currently visible, when these elements are updated any previous formatting can be lost without notice. If you wish to style cell elements you must use the formatter function in the column definition or the rowFormatter function on the table which are called when the rows/cells are redrawn. Full details of these can be found in the Formatter Documentation If you are wanting to change the state of rows based on something outside of the table, then your formatters should reference this external variable and when you update the external state you should trigger the redraw function on the table to retrigger the formatters
{ "language": "en", "url": "https://stackoverflow.com/questions/65222088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: No equivalent of Yes yes command in linux prints y infinitely on the console. This is helpful to respond to few interactive commands with y. For e.g. yes | cp A/*.txt B automatically overwrites all files in destination directory. Is there an equivalent command in linux that prints n infinitely? A: yes accepts an argument, y is just the default value. You can use: yes n | command How cool is that? Pro tip: # Use this and see what happens yes maybe | command Note: Not every command implements maybe.
{ "language": "en", "url": "https://stackoverflow.com/questions/45912081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: cmd type without printing filenames I have a makefile that concatenates two files to create a small kernel. I am using the following command: type boot_sect.bin kernel.bin > os-image Unfortunately, type still shows something on the cmd: boot_sect.bin kernel.bin Is there a way to not show the filenames with type? A: You can try the following command: copy /y /b boot_sect.bin+kernel.bin os-image > nul The /y switch is to automatically overwrite the destination file in case it already exists and /b is for binary copy.
{ "language": "en", "url": "https://stackoverflow.com/questions/18170531", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: :dependent => :destroy isn't calling the destroy method before the deletion? I have a note model, with the following association note.rb has_many :note_categories, :dependent => :destroy has_many :categories, :through => :note_categories The NoteCategory model was created to function as a join table between notes and categories. Initially it was just a model/table, but I've created a controller to do some custom stuff when someone is removing a category from a note. note_categories_controller.rb def destroy p "in notes_categories_controller destroy" note_category_to_delete = NoteCategory.find(params[:id]) #some custom stuff note_category_to_delete.destroy respond_to do |format| format.html { redirect_to(notes_url } format.xml { head :ok } end end This works fine, because I can use this link to create a button which will remove a category from a note: <%= button_to 'Remove', note_category, :confirm => 'Are you sure?', :controller => :note_categories, :method => :delete %> and it works fine. The problem is, when I delete a note, the note_category rows the belonged to the note are getting deleted, but the destroy method isn't being run. I know this because the custom code isn't being run, and the terminal output in the first line doesn't show up in the terminal. Here is the terminal output: Note Load (0.7ms) SELECT * FROM "notes" WHERE ("notes"."id" = 245) NoteCategory Load (0.5ms) SELECT * FROM "note_categories" WHERE ("note_categories".note_id = 245) NoteCategory Destroy (0.3ms) DELETE FROM "note_categories" WHERE "id" = 146 Note Destroy (0.2ms) DELETE FROM "notes" WHERE "id" = 245 I thought that by using :dependent => :destroy, the destroy method in the NoteCategories Controller should run before it's deleted. What am I doing wrong? A: :dependent => :destroy will call the destroy method on the model not the controller. From the documentation: If set to :destroy all the associated objects are destroyed alongside this object by calling their destroy method. That is, if you want something custom to your note_categories before being destroyed, you'll have to either override the destroy method in your NoteCategory model, or use an after_destroy/before_destroy callback. Either way, using :dependent => :destroy will never execute code contained within your controller, which is why you're not seeing the output of the puts statement in the terminal.
{ "language": "en", "url": "https://stackoverflow.com/questions/3547616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Navbar contents, icons, and card body? (HTML, bootstrap) So I have 3 issues: * *The contents of my navbar after the navbar-brand area will not show up for some reason. I am trying to add a home button, about section with a drop-down menu containing: 'Our mission', 'our team', 'faq;' a contact button, etc. (see picture for reference) *The icon in my card footers will not appear *How do I make the gray part of the cards a transparent gray color that also shows the body background? <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"> <link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@700&display=swap" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="app3.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <title>Quarantine Blog</title> </head> <body> <nav class="navbar bg-dark navbar-dark"> <div class="container"> <a href="" class="navbar-brand">Quarantine Pal</a> </div> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li class="active"><a href="">Home</a></li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> About </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Our Mission</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Our Team</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">FAQ</a> </div> <li><a href="">Contact</a></li> <li><a href="">Our Founder</a></li> <li><a href="">Press</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="#">Sign Up <i class="fa fa-user-plus"></i></a></li> <li><a href="#">Login <i class="fa fa-user"></i></a></li> </li> </ul> </div><!-- /.navbar-collapse --> </div> </nav> <section id="header" class="jumbotron text-center"> <h1 class="display-3">Quarantine State of Mind</h1> <p class="lead">Exploring the 'New Normal'</p> <a href="" class="btn btn-primary">Sign Up</a> <a href="" class="btn btn-success">Login</a> </section> <div class="container"> <div class="card-deck"> <div class="card"> <img src="https://images.unsplash.com/photo-1588776409240-05d32e7614f5?ixlib=rb-1.2.1&auto=format&fit=crop&w=1400&q=80" class="card-img-top" alt="Sailor Moon"> <div class="card-body"> <h5 class="card-title text-center">Self-Care and Burn Out</h5> <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p> </div> <div class="card-footer"> <a href="" class="btn btn-outline btn-success btn-sm">Download</a> <a href="" class="btn btn-outline btn-danger btn-sm"><i class="far fa-heart"></i></a> </div> </div> <div class="card"> <img src="https://images.unsplash.com/photo-1588779851655-558c2897779d?ixlib=rb-1.2.1&auto=format&fit=crop&w=1400&q=80" class="card-img-top" alt="Inuyasha"> <div class="card-body"> <h5 class="card-title text-center">Help Fight Coronavirus</h5> <p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p> <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p> </div> <div class="card-footer"> <a href="" class="btn btn-outline btn-success btn-sm">Download</a> <a href="" class="btn btn-outline btn-danger btn-sm"><i class="far fa-heart"></i></a> </div> </div> <div class="card"> <img src="https://images.unsplash.com/photo-1588777308282-b3dd5ce9fb67?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1400&q=80" class="card-img-top" alt="Dragon Ball Z"> <div class="card-body"> <h5 class="card-title text-center">Pandemic Socializing</h5> <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p> <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p> </div> <div class="card-footer"> <a href="" class="btn btn-outline btn-success btn-sm">Download</a> <a href="" class="btn btn-outline btn-danger btn-sm"><i class="far fa-heart"></i></a> </div> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> </body> </html> CSS: #header { background-color: transparent; background-position: center bottom; } h1 { color: white; text-shadow: 0px 4px 3px rgba(0, 0, 0, 0.4), 0px 8px 13px rgba(0, 0, 0, 0.1), 0px 18px 23px rgba(0, 0, 0, 0.2); font-family: 'Source Sans Pro', sans-serif; } .navbar-brand { color: white; text-shadow: 0px 4px 3px rgba(0, 0, 0, 0.4), 0px 8px 13px rgba(0, 0, 0, 0.1), 0px 18px 23px rgba(0, 0, 0, 0.2); font-family: 'Source Sans Pro', sans-serif; } .navbar.bg-dark.navbar-dark { background-color: transparent !important; } body { background-image: url('https://images.unsplash.com/photo-1588774210246-a1dc467758df?ixlib=rb-1.2.1&auto=format&fit=crop&w=1934&q=80') } .card-body { font-family: 'Source Sans Pro', } .lead { color: white; text-shadow: 0px 4px 3px rgba(0, 0, 0, 0.4), 0px 8px 13px rgba(0, 0, 0, 0.1), 0px 18px 23px rgba(0, 0, 0, 0.2); font-family: 'Source Sans Pro', sans-serif; } .card-body { background-color: gray; opacity: 80%; } .card-title { color: white; font-family: 'Source Sans Pro', sans-serif; } .card-text { color: white; font-family: 'Source Sans Pro', sans-serif; } A: * *I have fixed your navigation issue. You may need to change the style of the navigation items. *I also fix your icon display issue, you need to use Font Awesome 4 style. fa fa-heart-o *Finally, I also add in CSS code to make the background of the card body becomes 80% transparent. Class .card background-color need to set to transparent and class card-footer background-color need to set to white. .card { background-color: transparent !important; } .card-body { background-color: gray; opacity: 80%; } .card-footer { background-color: #fff !important; } #header { background-color: transparent; background-position: center bottom; } h1 { color: white; text-shadow: 0px 4px 3px rgba(0, 0, 0, 0.4), 0px 8px 13px rgba(0, 0, 0, 0.1), 0px 18px 23px rgba(0, 0, 0, 0.2); font-family: 'Source Sans Pro', sans-serif; } .navbar-brand { color: white; text-shadow: 0px 4px 3px rgba(0, 0, 0, 0.4), 0px 8px 13px rgba(0, 0, 0, 0.1), 0px 18px 23px rgba(0, 0, 0, 0.2); font-family: 'Source Sans Pro', sans-serif; } .navbar.bg-dark.navbar-dark { background-color: transparent !important; } body { background-image: url('https://images.unsplash.com/photo-1588774210246-a1dc467758df?ixlib=rb-1.2.1&auto=format&fit=crop&w=1934&q=80') } .card-body { font-family: 'Source Sans Pro', } .lead { color: white; text-shadow: 0px 4px 3px rgba(0, 0, 0, 0.4), 0px 8px 13px rgba(0, 0, 0, 0.1), 0px 18px 23px rgba(0, 0, 0, 0.2); font-family: 'Source Sans Pro', sans-serif; } .card { background-color: transparent !important; } .card-body { background-color: gray; opacity: 80%; } .card-footer { background-color: #fff !important; } .card-title { color: white; font-family: 'Source Sans Pro', sans-serif; } .card-text { color: white; font-family: 'Source Sans Pro', sans-serif; } <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <nav class="navbar navbar-expand-lg bg-dark navbar-dark"> <!-- <div class="container" style="background: yellow;"> --> <a href="" class="navbar-brand">Quarantine Pal</a> <!-- </div> --> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="nav navbar-nav mr-auto"> <li class="nav-item active"><a class="nav-link" href="">Home</a></li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> About </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Our Mission</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Our Team</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">FAQ</a> </div> </li> <li class="nav-item"><a class="nav-link" href="">Contact</a></li> <li class="nav-item"><a class="nav-link" href="">Our Founder</a></li> <li class="nav-item"><a class="nav-link" href="">Press</a></li> </ul> <ul class="nav navbar-nav navbar-right "> <li class="nav-item"><a class="nav-link" href="#">Sign Up <i class="fa fa-user-plus"></i></a></li> <li class="nav-item"><a class="nav-link" href="#">Login <i class="fa fa-user"></i></a></li> </ul> </div> <!-- /.navbar-collapse --> <!-- </div> --> </nav> <section id="header" class="jumbotron text-center"> <h1 class="display-3">Quarantine State of Mind</h1> <p class="lead">Exploring the 'New Normal'</p> <a href="" class="btn btn-primary">Sign Up</a> <a href="" class="btn btn-success">Login</a> </section> <div class="container"> <div class="card-deck"> <div class="card"> <img src="https://images.unsplash.com/photo-1588776409240-05d32e7614f5?ixlib=rb-1.2.1&auto=format&fit=crop&w=1400&q=80" class="card-img-top" alt="Sailor Moon"> <div class="card-body"> <h5 class="card-title text-center">Self-Care and Burn Out</h5> <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p> </div> <div class="card-footer"> <a href="" class="btn btn-outline btn-success btn-sm">Download</a> <a href="" class="btn btn-outline btn-danger btn-sm"><i class="fa fa-heart-o"></i></a> </div> </div> <div class="card"> <img src="https://images.unsplash.com/photo-1588779851655-558c2897779d?ixlib=rb-1.2.1&auto=format&fit=crop&w=1400&q=80" class="card-img-top" alt="Inuyasha"> <div class="card-body"> <h5 class="card-title text-center">Help Fight Coronavirus</h5> <p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p> <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p> </div> <div class="card-footer"> <a href="" class="btn btn-outline btn-success btn-sm">Download</a> <a href="" class="btn btn-outline btn-danger btn-sm"><i class="fa fa-heart-o"></i></a> </div> </div> <div class="card"> <img src="https://images.unsplash.com/photo-1588777308282-b3dd5ce9fb67?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1400&q=80" class="card-img-top" alt="Dragon Ball Z"> <div class="card-body"> <h5 class="card-title text-center">Pandemic Socializing</h5> <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p> <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p> </div> <div class="card-footer"> <a href="" class="btn btn-outline btn-success btn-sm">Download</a> <a href="" class="btn btn-outline btn-danger btn-sm"><i class="fa fa-heart-o"></i></a> </div> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
{ "language": "en", "url": "https://stackoverflow.com/questions/61859875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: connect to Apple Watch through node.js I am looking to try to connect a workout from my Apple Watch to my node.js application. I am not using react or anything, I just specifically want to connect to the Apple Watch through node.js and grab the data. Is it possible through an Api, without using swift? A: You can use any API provided by apple to use it in your React app. You can find the documentation here.
{ "language": "en", "url": "https://stackoverflow.com/questions/70137720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't add compiler options for nvcc in nsight eclipse How do I add options to my nvcc using nsight eclipse. I tried to modify the command option Under Project->Properties->Build->Settings->Tool Settings-> NVCC Compiler. I changed it from "nvcc" to "nvcc --someoption". However when it compiles I see this output "/usr/local/cuda-7.0/bin/nvcc -O3 -ccbin gcc-4.9 -std=c++11 -gencode arch=compute_35,code=sm_35 -gencode arch=compute_52,code=sm_52 -odir "." -M -o "binomial.d" "../binomial.cu" Notice that --someoption in not in it. How can I add an option in eclipse? I also noticed that I can change the command from nvcc to some gibberish and it still compiles so I think that option does not affect anything. If so how can I add compiler options which eclipse does not include in its gui. A: I would recommend using the -optf switch that is selectable under Project Settings... Build ... Settings...Tool Settings...Miscellaneous and add your own file to the project that contains whatever compiler switches you want to add. I think most compiler switches are already covered in the GUI, however.
{ "language": "en", "url": "https://stackoverflow.com/questions/32021303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: runtime error : return value gets lost I'm working on this project : https://github.com/zsteve/zebra-zmachine-interpreter which is supposed to be an interpreter for z-machine story files, but I'm still working on it. Anyway, the error I'm having is within ztext.cpp and ZDictionary's unit test main.cpp. zChartoDictionaryZCharString() is supposed to return a pointer to a string/array of zwords. It is creating/calculating that array properly, but is strangely failing to return it properly... the error occurs at line 499 of ztext.cpp : [code] return (outWord);[/code] Right at this point, outWord points to an array of zwords : {15 25, 28 ab} allocated by new[] Once it returns to line 42 in https://github.com/zsteve/zebra-zmachine-interpreter/blob/master/zdictionary/zdictionary/main.cpp , the returned zword* now points to {50 00, 00 00}, which shouldn't happen. I spent an hour debugging the entire thing until I figured out that this was where it went wrong. So my question is : what causes this problem in my program? I suspect it's either unmatched new[]/delete[] (could this cause it?) or the std::vector objects in zChartoDictionaryZCharString(). Here is the code : in main.cpp (/zdictionary/zdictionary/main.cpp) from line 40: // error occurs here : // at this point : tmp == {15 25 28 ab} zword* tmp=zChartoDictionaryZCharString(tmp_); in ztext.cpp (/ztext/ztext/ztext.cpp) from line 502: zword* zChartoDictionaryZCharString(zword* zstring) { // converts a normal zchar string to a dictionary zchar string // returns a zword* to either a 2 or 3 zword array. std::vector<zchar> vector1=expandZChars(zstring); std::vector<zchar> vector2(0); if(zVersion<=3){ // for versions 1 to 3, dictionary word length is 4 bytes (6 zchars) int done=0; for(int i=0; i<vector1.size() && i<6; i++, done++) { vector2.push_back(vector1[i]); } if(done<6) { for(int i=done; i<6; i++) { vector2.push_back(5); } } // now we need to pack them to 2x zwords. zword* outData=new zword[2]; zchar* zcharArray=new zchar[vector2.size()]; for(int i=0; i<vector2.size(); i++) zcharArray[i]=vector2[i]; outData[0]=endianize(packZChars(zcharArray)); outData[1]=endianize(packZChars(zcharArray+3)|128); delete[] zcharArray; vector1.clear(); vector2.clear(); return outData; }else if(zVersion>3){ // for versions 4 and up, dictionary word length is 6 bytes (9 zchars) int done=0; for(int i=0; i<vector1.size() && i<9; i++, done++) { vector2.push_back(vector1[i]); } if(done<9) { for(int i=done; i<9; i++) { vector2.push_back(5); } } // now we need to pack them to 3x zwords. zword* outData=new zword[3]; zchar* zcharArray=new zchar[vector2.size()]; for(int i=0; i<vector2.size(); i++) zcharArray[i]=vector2[i]; outData[0]=packZChars(zcharArray); outData[1]=packZChars(zcharArray+3); outData[2]=packZChars(zcharArray+6); outData[2]|=128; for(int i=0; i<3; i++) outData[i]=endianize(outData[i]); delete[] zcharArray; return outData; } } Any help on fixing this would be greatly appreciated. Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/19310728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: java array casting? How can it be that i get a class cast exception when i try to do: PrioritetArraySorteret<String> p = new PrioritetArraySorteret<String>(); the error is in the constructor? public class PrioritetArraySorteret<E> implements PrioritetADT<E> { private int capacity = 5; private Entry S[]; private int size; public PrioritetArraySorteret() { S = (Entry[]) new Object[capacity]; size = 0; } private class Entry implements Comparable<Entry> { private int key; private E value; public Entry(int key, E value) { this.key = key; this.value = value; } public int getKey() { return key; } public E getValue() { return value; } } A: You really are declaring an array of type Object and trying to cast it, which doesn't work. Instead, in your constructor, do: S = new Entry[capacity]; A: Why do you do a cast in S = (Entry[]) new Object[capacity]; and not just S = new Entry[capacity]; That would probably solve the problem. A: Your error appears to be attempting to mix generics with something that can't handle this use of generics - namely, arrays. Changing the definition of S to List<Entry<E>>, and the instantiation to new ArrayList<Entry<E>>(capacity) allows your program to run (given the limited sample). Some other random notes, given your sample: * *You've named your array-to-sort S. Please follow the standard naming conventions (other people will expect you to), and give it a meaningful name. It doesn't help that it may look similar to 5 (depends on font, I'll admit). *capacity is an instance variable used for initialization for every instance of the class (and nowhere else). Change this to a final static variable and/or change the name of the variable to reference why this is the case *You define size - Likely, you should be returning S.size() regardless, unless you have some (unstated) specific need. *Your use of the terms key and value suggests you are attempting to use (or maybe implement) a HashMap.
{ "language": "en", "url": "https://stackoverflow.com/questions/7986374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I make it so my code displays a cerrtain amount of lines (like it does) but backwards So when I enter 4, instead of say 4 bottles of beer etc, It will start with 100 and go to 96 and then stop (ending with the final line) import java.util.Scanner; public class ThreeDotNine { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("How many Verses would you like to print: "); String num = sc.nextLine(); int num2 = Integer.parseInt(num); String s = " "; for (int x = num2; x > 0; x--) { System.out.println(x + " bottles of beer on the wall " + x + " bottles of beer"); System.out.println("Take one down, pass it around, " + (x - 1) + " bottles of beer on the wall.\n"); } System.out.print("Go to the store, buy some more, "); System.out.println("99 bottles of beer on the wall.\n"); } } A: there is nothing wrong with the program. It works fine, Just check it again How many Verses would you like to print: 4 4 bottles of beer on the wall 4 bottles of beer Take one down, pass it around, 3 bottles of beer on the wall. 3 bottles of beer on the wall 3 bottles of beer Take one down, pass it around, 2 bottles of beer on the wall. 2 bottles of beer on the wall 2 bottles of beer Take one down, pass it around, 1 bottles of beer on the wall. 1 bottles of beer on the wall 1 bottles of beer Take one down, pass it around, 0 bottles of beer on the wall. Go to the store, buy some more, 99 bottles of beer on the wall. A: I would try it like that: for ( int x = 0; x <= num2; x++ ) { int y = 100 - x; System.out.println(y + " bottles of beer on the wall " + y + " bottles of beer"); System.out.println("Take one down, pass it around, " + (y - 1) + " bottles of beer on the wall.\n"); } It's easier to understand if you define a second variable. Now you have your output with 100 99 98 97 96
{ "language": "en", "url": "https://stackoverflow.com/questions/40391733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to deserialize derived class with other derived class as property I have 2 projects. One is a WPF application and second is my "toolkit" with predefined WPF control, XML deserialization and some base configuration classes. In my toolkit I have a ConfigurationBase class: public class ConfigurationBase : XmlDeserializeConfigSectionHandler { public GuiConfigurationBase GuiConfiguration { get; set; } } This is GuiConfigurationBase public class GuiConfigurationBase { public int LogLineCount { get; set; } } My toolkit contains predefined View for in app log messages. So my LogViewModel constructor requires a ConfigurationBase which should contain GuiConfiguration with LogLineCount property. This is because I don't want to implement in app log for every application. Then I have a WPF project. It contains a class Config which is derived from ConfigurationBase. It's extended with some other props which are not important. I also needed to extend GuiConfigurationBase so I have class called GuiConfiguration which derives from GuiConfigurationBase. public class Config : ConfigurationBase { public string AppName { get; set; } } public class GuiConfiguration : GuiConfigurationBase { public int TextSize { get; set; } } I am also using XmlSerializer for deseserializing my XML file. I need to fill both of my derived classes. How I can achieve this please? I tried some abstraction for base classes but with no success. Thank you for any suggestion. A: I found a solution. It's necessary to use XmlAttributeOverrides. Because I have two projects I had to use reflection to retrieve classes which derive from GuiConfigurationBase. (I don't know anything about project where is my toolkit project referenced) Then add new XmlElementAttribute for each class (in my case it should be enough to use Linq First() method) - This should be same as XmlIncludeAttribute(Type) And finaly add XmlAttributeOverrides for ConfigurationBase class's property GuiConfiguration Here is my deserialize method: public T Deserialize<T>(string input) where T : class { //Init attrbibutee overrides XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides(); XmlAttributes attrs = new XmlAttributes(); //Load all types which derive from GuiConfiguration base var guiConfTypes = (from lAssembly in AppDomain.CurrentDomain.GetAssemblies() from lType in lAssembly.GetTypes() where typeof(GuiConfigurationBase).IsAssignableFrom(lType) && lType != typeof(GuiConfigurationBase) select lType).ToArray(); //All classes which derive from GuiConfigurationBase foreach (var guiConf in guiConfTypes) { XmlElementAttribute attr = new XmlElementAttribute { ElementName = guiConf.Name, Type = guiConf }; attrs.XmlElements.Add(attr); } //Add Attribute overrides for ConfigurationBase class's property GuiConfiguration attrOverrides.Add(typeof(ConfigurationBase), nameof(ConfigurationBase.GuiConfiguration), attrs); XmlSerializer ser = new XmlSerializer(typeof(T), attrOverrides); using (StringReader sr = new StringReader(input)) { return (T)ser.Deserialize(sr); } } I hope it will help someone else :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/58025541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Capture time difference between values of two regular expression reference names in Jmeter I defined regular expressions in my JMeter test plan and I'm able to capture the values in simple variables in user.variables. But I'm trying to calculate the time difference between two variables as follows in Beanshell post processor and I'm not getting any result in my report. import javax.xml.bind.DatatypeConverter; vars.put("old_date_submitted", "submittedDate"); // submittedDate, succeeddedDate and runningDates are regular expr. reference names vars.put("old_date_succeeded", "succeededDate"); vars.put("old_date_running", "runningDate"); Calendar cal_s = DatatypeConverter.parseDateTime(vars.get("old_date_submitted")); Calendar cal_c = DatatypeConverter.parseDateTime(vars.get("old_date_succeeded")); Calendar cal_r = DatatypeConverter.parseDateTime(vars.get("old_date_running")); Date new_date1 = cal_s.getTime(); // submitted Time Date new_date2 = cal_c.getTime(); // succeeded Time Date new_date3 = cal_r.getTime(); // running Time long new_date1_ms = new_date1.getTime(); // submitted Time long new_date2_ms = new_date2.getTime(); long new_date3_ms = new_date3.getTime(); log.info("Date in milliseconds: " + new_date1_ms); long delta1 = new_date2_ms - new_date1_ms; //calculate the difference (succeededDate - submittedDate) long delta2 = new_date3_ms - new_date1_ms; //calculate the difference (runningDate - submittedDate) vars.put("delta1", String.valueOf("delta1")); // store the result into a JMeter Variable vars.put("delta2", String.valueOf("delta2")); // store the result into a JMeter Variable A: This bit: vars.put("old_date_submitted", "submittedDate"); // submittedDate, succeeddedDate and runningDates are regular expr. reference names vars.put("old_date_succeeded", "succeededDate"); vars.put("old_date_running", "runningDate"); seems odd to me. Given: submittedDate, succeeddedDate and runningDates are regular expr. reference names My expectation is that you should be using JMeter Variables instead of hardcoded strings there, so you should change your code to look like: vars.put("old_date_submitted", vars.get("submittedDate")); // submittedDate, succeeddedDate and runningDates are regular expr. reference names vars.put("old_date_succeeded", vars.get("succeededDate")); vars.put("old_date_running", vars.get("runningDate")); So most likely your code is failing at DatatypeConverter.parseDateTime. Next time you face any problem with your Beanshell scripts consider the following troubleshooting techniques: * *Check jmeter.log file - in case of Beanshell script failure the error will be printed there *Add debug(); directive to the very beginning of your Beanshell script - it will trigger debugging output to stdout *Put your Beanshell code in try/catch block like: try { //your code here } catch (Throwable ex) { log.error("Something went wrong", ex); throw ex; } This way you get more "human-friendly" stacktrace printed to jmeter.log file. See How to Use BeanShell: JMeter's Favorite Built-in Component guide for more information on using Beanshell in JMeter tests.
{ "language": "en", "url": "https://stackoverflow.com/questions/38300505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Generic response in retrofit I have 2 calls using retrofit, because the API is poorly design I get difference structure of JSON so I have two different model objects. what I want to achieve is smaller fetch method and to avoid the duplicate code. I'm trying to use generic class for the pojo but without success. Thanks, my models: public class GenreResponse { @SerializedName("genre") @Expose private Genre genre; @SerializedName("sort") @Expose private String sort; @SerializedName("page") @Expose private Integer page; @SerializedName("limit") @Expose private Integer limit; @SerializedName("events") @Expose private List<Movie> events; @SerializedName("subGenres") @Expose private List<SubGenre> subGenres = new ArrayList<>(); public List<SubGenre> getSubGenres() { return subGenres; } public Genre getGenre() { return genre; } public String getSort() { return sort; } public Integer getPage() { return page; } public Integer getLimit() { return limit; } public List<Movie> getEvents() { return events; } } public class GeneralSearchResponse { @SerializedName("query") @Expose private String query; @SerializedName("sort") @Expose private String sort; @SerializedName("page") @Expose private String page; @SerializedName("limit") @Expose private Integer limit; @SerializedName("amount") @Expose private Integer amount; @SerializedName("events") @Expose private List<Movie> events; @SerializedName("sideNav") @Expose private List<SideNav> sideNavList = new ArrayList<>(); public List<Movie> getEvents() { return events; } private class SideNav { @SerializedName("id") @Expose private Integer id; @SerializedName("name") @Expose private String name; @SerializedName("englishName") @Expose private String englishName; @SerializedName("amount") @Expose private Integer amount; @SerializedName("isKidsEvents") @Expose private Boolean isKidsEvent; } } my method: private void fetchGenresData(String genreId, int page, final boolean addMore, String sortType) { switch (fragmentMode) { case MODE_GENRE: Observable<GenreResponse> observableGenre = RxUtils.wrapRetrofitCall( VODApplication.getInstance() .getApi() .getGenres(genreType, genreId, page, DEFAULT_PAGE_LIMIT, sortType)); RxUtils.wrapAsync(observableGenre).subscribe(new Action1<GenreResponse>() { @Override public void call(GenreResponse response) { if (addMore) { mAdapter.remove(mAdapter.getItemCount() - 1); mAdapter.addAll(response.getEvents()); } else { // called for the first time. mAdapter.setGenres(response.getEvents()); mSpinnerView.setListener(GenreFragment.this); mSpinnerView.initSpinners(response); } isLoading = false; } }, new Action1<Throwable>() { @Override public void call(Throwable t) { ((GenreScreen) getActivity()).getDialog().dismiss(); } }); break; case MODE_SEARCH: AppUtils.hideKeyboard(getActivity()); .enqueue(new Callback<GeneralSearchResponse>() { @Override public void onResponse(Call<GeneralSearchResponse> call, Response<GeneralSearchResponse> response) { if (addMore) { mAdapter.remove(mAdapter.getItemCount() - 1); mAdapter.addAll(response.body().getEvents()); } else { // called for the first time. mAdapter.setGenres(response.body().getEvents()); mSpinnerView.setListener(GenreFragment.this); } isLoading = false; } @Override public void onFailure(Call<GeneralSearchResponse> call, Throwable t) { Log.d(TAG, "call: " + t.getMessage()); } }); break; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/40914926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Positioning 2 elements (countdown timer and button) in row, side by side - they are not centered I have a problem with one of sections in my HTML code. My idea is simply: one section made by 1 row, who is divided on 2 columns. In left column i tried to put countodwn timer, and "submit" button in right column. They have to be side by side, and on equal distance in regards to each other; but there are some problems - they are on unequal distance and i am wondering how to fix it... Also, when i test how draft of my site looks on mobile, parts of the clock do not stay together - they just move under each other. Here is a jsfiddle. What i am doing wrong? <div class="container-fluid"> <div class="row align-items-center"><div class="col-6 mx-auto"> <h3 style=" font-family: Open Sans; font-weight: light; font-size: 20px; color: 636363;letter-spacing: 1px; padding-left:110px;">Deadline:</h3> <div id="clockdiv"> <div> <span class="days"></span> <div class="smalltext">Days</div> </div> <div> <span class="hours"></span> <div class="smalltext">Hours</div> </div> <div> <span class="minutes"></span> <div class="smalltext">Minutes</div> </div> <div> <span class="seconds"></span> <div class="smalltext">Seconds</div> </div> </div> </div> <div class="col-6 mx-auto"> <button class="button button1" style="width: 300px; height: 100px;">Submit</button> </div> </div> </div> And CSS: #clockdiv{ font-family: Open Sans; color: #ffffff; display: inline-block; font-weight: 100; text-align: center; font-size: 30px; } #clockdiv > div{ padding: 0px; border-radius: 3px; background: #fffff; display: inline-block; } #clockdiv div > span{ padding: 15px; border-radius: 3px; background: #000; display: inline-block; position: relative; } .smalltext{ padding-top: 5px; font-size: 16px; color: #000; position: relative; } .button { background-color: #fff; border: none; color: white; text-align: center; text-decoration: none; font-size: 16px; font-family: 'Open Sans'; margin: 4px 2px; -webkit-transition-duration: 0.4s; transition-duration: 0.4s; cursor: pointer; } .button1 { background-color: white; color: #000; border: 2px solid #000; } .button1:hover { background-color: #fff; color: white;
{ "language": "en", "url": "https://stackoverflow.com/questions/54318825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: regex to filter php array by conditional existence of value I have have a php array $arr[0] = "something/somethingelse/anotherval"; $arr[1] = "something/!somevar/anotherval"; $arr[3] = "something/!notcorrect/anotherval"; $arr[4] = "something/somethingelse/_MyVal"; $arr[5] = "something/_MyVal/anotherval"; $arr[6] = "something/_AnotherNotCorrect/anotherval"; I'm using array_filter to filter the array by certain criteria... $f = array_filter(array_keys($arr), function ($k){ return ( strpos($k, 'something/') !== false ); }); This returns all my vals where the term something/ is matched... I'd like to be able to say IF we encounter a ![something here] or a _[something here] then we need to make sure that the [something here] matches either $afterExcl or $afterUnderscore. If we didn't encounter a ! or _ then just check the strpos($k, 'something/') !== false check... (notice that the ! and _ portions may or may not be at the end of val string) I'm assuming this is regex, but I've always struggled to build them. CLARIFICATION Thanks. Clarification though, the ! or _ sequence may not be the next directory after something/, it may three or four more steps in. AND, I'll be providing a $afterExcl or $afterUnderscore value which will designate approved values. Basically the client is using ! and _ to denote "regions" ie. something/images/!Canada something/videos/tutorials/!Canada or something/images/!USA or something/images/!Mexico OR last something/images/All then I'd specify $afterExcl=Canada My filter would return something/images/!Canada something/videos/tutorials/!Canada something/images/All A: You can use something like this: $f = array_filter(array_keys($arr), function ($k){ return preg_match('~something/(?![_!])~', $k); }); The negative lookahead (?!...) checks if the slash isn't followed by a ! or a _. Note that preg_match returns 1 if found or 0 if not. If you want to return true or false you can do it with the ternary operator: return preg_match('~something/(?![_!])~', $k) ? true : false; an other way: If you use strpos, I assume that the string you describe as 'something/' is a fixed string $str, in other words you know the length of this strings. Since strpos returns the position $pos in the string of the occurence, you can easily check if at the position $pos + strlen($str) there is either an exclamation mark or an underscore. (you could, for example, extract this next character and check if it is in the array array('!', '_'))
{ "language": "en", "url": "https://stackoverflow.com/questions/25517717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ssis 2008, delete contents from excel im using SSIS for SQL Server 2008. My SSIS package grabs data from sql and exports it to an excel file. But everytime it does this I want new data on the excel. The problem right now is, If i execute the package more than one time I will have the old data plus the new one on the excel file. I only want the new data displayed. On the SSIS, on the Control Flow tab I have an Data Flow task. On the Data Flow tab I have an OLEDB source and an Excel Destination in order to put the data on the excel. So im thinking on deleting the contents from the excel on the SSIS every time before the data gets inserted on the excel. The excel file has an image, a title and the column names. I want these data to stay. But I want the data from the rows deleted. How can I do this? Thanks... A: Ok. What I did was to make a copy of the file and load the data on the new file, and everytime the ssis loads it overwrites the file, so I always have new data..........Thanks!!
{ "language": "en", "url": "https://stackoverflow.com/questions/13916232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: google script detect empty cell after edit -- Take 2 This is related to onEdit functionality and a question with the same title found here . I am not getting the responses they are indicating I might or should when cells go from having values to empty, and those work around solutions did not work as a result. It's as if something has changed since those answers were given or there is different underlying behavior. Here is a link to spreadsheet with a simple example. In this example, I have a cell with data validation on it. In context, this cell allows me to pick sales ticket IDs from a list to recall data. After I have recalled the data, if I remove the value from the selection cell with backspace or delete, the onEdit function should be called, a falsy value should exist for "e.value" and I should be able to clear the data it retrieved. Pretty simple. == Full Testing Protocal == 1) When the cell is blank and I pick a value from the list, I test the e.value property for truthy, i get truthy response, and it completes a function to get data. 2) When the cell is NOT blank and I pick a value from the list, I test the e.value property for truthy, i get truthy response, and it completes a function to get data. 3) When the cell is NOT blank, and I click into the cell and select backspace or delete to empty the cell. I test the e.value property for truthy and instead of getting a falsy response, I get an object back?! {old_value=xxxx}. So, not only do I not get a falsy value, I get an object returned instead that is missing the value item in it?? From looking at the other post, it seems when there is no "value", google has decided to leave the "value" item out of the e object instead of leaving "value" item in the e object and setting it to null or blank. I don't know why that was chosen, but that's the way I interpret that. That said, it seems to me that decision should not have mattered. If I'm testing for an item in an object and the item doesn't exist, I should get a falsy of some sort, but instead, I'm getting an object returned to me?! The only way that I know of that might to work around this is to check for variable type to see if an object was returned which is really terribly confusing for those new to programming and shouldn't be required. I will try that shortly, but wanted to get this out first. I do recall running into this several years ago and not taking the time to try to get a sound answer. function onEdit(e){ Logger.log("onEdit running") var ss = SpreadsheetApp.getActiveSpreadsheet(); if (ss.getRangeByName("sTkt_uniqueID_recall").getA1Notation() == e.range.getA1Notation() ){ Logger.log("onEdit - sTkt_uniqueID_recall") if(e.value){ Logger.log("recall ID cell has value - get Data") Logger.log(e.value) //sTkt_getRecallData() }else{ //oE.value should be blank, null or something falsy.. //instead an object is returned?! {old_value: xxxxxx} // and thus is not null and thus it never gets here.. Logger.log("recall ID cell now empty - clear Data") Logger.log(e.value) //sTkt_clearForm() } Logger.log("onEdit fxnComplete") } } Thanks for the help with this. EDIT: Added logs. Logs when item is in cell... [19-10-20 15:17:18:071 PDT] onEdit running [19-10-20 15:17:18:159 PDT] onEdit - sTkt_uniqueID_recall [19-10-20 15:17:18:160 PDT] recall ID cell has value - get Data [19-10-20 15:17:18:160 PDT] 1002 [19-10-20 15:17:18:161 PDT] onEdit fxnComplete Logs when item has been deleted -- it takes wrong path b/c of the object with oldValue in it... [19-10-20 15:15:25:411 PDT] onEdit running [19-10-20 15:15:25:509 PDT] onEdit - sTkt_uniqueID_recall [19-10-20 15:15:25:510 PDT] recall ID cell has value - get Data [19-10-20 15:15:25:511 PDT] {oldValue=1001.0} [19-10-20 15:15:25:511 PDT] onEdit fxnComplete EDIT: Providing the full event object shows this clearly. Should have just done that earlier. As you can see old value is in there, but there is an object being returned for "value" instead of a falsy (blank or something else)... [19-10-20 15:54:19:750 PDT] {authMode=LIMITED, range=Range, source=Spreadsheet, oldValue=10/3/2019--6939, [email protected], value={oldValue=10/3/2019--6939}} EDIT: I've tested a work around and this is the one I will likely use as it remind me of exactly what is going on AND Im thinking if the issue gets cleaned up or fixed, this work around should still work and I wouldn't need to make any changes in places it may go in. if(e.value && typeof e.value !== 'object') A: * *In your situation, using your shared Spreadsheet, when you delete the value from the cell "C4" of the data validation with the delete button, the event object of e of onEdit(e) has "value":{"oldValue":"deleted value"}. * *You want to know about this situation. If my understanding is correct, how about this answer? When I had tested this, in your situation, I noticed that the border of cell under the simple trigger is related to this situation. Preparation 1: For the explanation, it supposes as follows. * *Create new Spreadsheet. *Put a text of sample to the cell "A1". *Set a simple trigger of the OnEdit event trigger as the script of function onEdit(e) {Logger.log(JSON.stringify(e))}. * *At the explanation, e of the event object is used, when the OnEdit event trigger was fired. Sample situations 1: Situation 1A: When the value of sample of the cell "A1" is deleted by the delete button, e of the event object returns the following value. {"authMode":{},"range":{"columnStart":1,"rowStart":1,"rowEnd":1,"columnEnd":1},"source":{},"user":{"nickname":"","email":""}} Situation 1B: When the text of sample in the cell "A1" is deleted by deleting each character using the backspace key, e of the event object returns the following value. {"authMode":{},"range":{"columnStart":1,"rowStart":1,"rowEnd":1,"columnEnd":1},"source":{},"oldValue":"sample","user":{"nickname":"","email":""},"value":{"oldValue":"sample"}} Sample situations 2: Here, in order to replicate your situation, please set the border to the cell "A1". Situation 2A: When the value of sample of the cell "A1", which was surrounded by the border, is deleted by the delete button, e of the event object returns the following value. {"authMode":{},"range":{"columnStart":1,"rowStart":1,"rowEnd":1,"columnEnd":1},"source":{},"oldValue":"sample","user":{"nickname":"","email":""},"value":{"oldValue":"sample"}} Situation 2B: When the text of sample in the cell "A1", which was surrounded by the border, is deleted by deleting each character using the backspace key, e of the event object returns the following value. {"authMode":{},"range":{"columnStart":1,"rowStart":1,"rowEnd":1,"columnEnd":1},"source":{},"oldValue":"sample","user":{"nickname":"","email":""},"value":{"oldValue":"sample"}} Preparation 2: For the explanation, it supposes as follows. * *Create new Spreadsheet. *Put a text of sample to the cell "A1". *Copy and paste the script of function InstallOnEdit(e) {Logger.log(JSON.stringify(e))}. * *At the explanation, e of the event object is used, when the OnEdit event trigger was fired. *Set the installable OnEdit event trigger to the function of InstallOnEdit. Sample situations 1: Situation 1A: When the value of sample of the cell "A1" is deleted by the delete button, e of the event object returns the following value. {"authMode":{},"range":{"columnStart":1,"rowStart":1,"rowEnd":1,"columnEnd":1},"source":{},"triggerUid":"###","user":{"nickname":"###","email":"###@gmail.com"}} Situation 1B: When the text of sample in the cell "A1" is deleted by deleting each character using the backspace key, e of the event object returns the following value. {"authMode":{},"range":{"columnStart":1,"rowStart":1,"rowEnd":1,"columnEnd":1},"source":{},"oldValue":"sample","triggerUid":"###","user":{"nickname":"###","email":"###@gmail.com"}} Sample situations 2: Here, in order to replicate your situation, please set the border to the cell "A1". Situation 2A: When the value of sample of the cell "A1", which was surrounded by the border, is deleted by the delete button, e of the event object returns the following value. {"authMode":{},"range":{"columnStart":1,"rowStart":1,"rowEnd":1,"columnEnd":1},"source":{},"oldValue":"sample","triggerUid":"###","user":{"nickname":"###","email":"###@gmail.com"}} Situation 2B: When the text of sample in the cell "A1", which was surrounded by the border, is deleted by deleting each character using the backspace key, e of the event object returns the following value. {"authMode":{},"range":{"columnStart":1,"rowStart":1,"rowEnd":1,"columnEnd":1},"source":{},"oldValue":"sample","triggerUid":"###","user":{"nickname":"###","email":"###@gmail.com"}} Results and discussions: From above experiment, the following results could be obtained. * *Values of the event object depend on the situation with and without the border of cell. * *Also above situation can be seen at not only the border, but also the cases that the background color of the cell, the format (font color, size, bold and so on) except for the default font format. *It seems that when the cell and font are changed from the default settings, the event object returns the values of "Sample situations 2". *Values of the event object also depend on with and without using the installable event trigger. *In the case of the cell with the default cell and font under the simple trigger, * *When the value of sample of the cell "A1" is deleted by the delete button, e of the event object has no both oldValue and value. *When the text of sample in the cell "A1" is deleted by deleting each character using the backspace key, e of the event object has both oldValue and value. And value is {"oldValue":"deleted value"}. *In the case of the cell with the border under the simple trigger, * *When the value of sample of the cell "A1" is deleted by the delete button and also the text of sample in the cell "A1" is deleted by deleting each character using the backspace key, e of the event object has both oldValue and value. And value is {"oldValue":"deleted value"}. *In the case of the cell with the default cell and font under the installable trigger, * *When the value of sample of the cell "A1" is deleted by the delete button, e of the event object has no both oldValue and value. *When the text of sample in the cell "A1" is deleted by deleting each character using the backspace key, e of the event object has oldValue and no value. And oldValue is the deleted value which is not the object. *In the case of the cell with the border under the installable trigger, * *When the value of sample of the cell "A1" is deleted by the delete button and also the text of sample in the cell "A1" is deleted by deleting each character using the backspace key, e of the event object has oldValue and no value. And oldValue is the deleted value which is not the object. From above results, I thought that the values (no both oldValue and value) of event object from the default condition of the cell and font might be a bug or the specification. But I had looked for the official document about this. Unfortunately, I couldn't still find it. About your situation: Using above results, when your shared Spreadsheet was tested, the cell "C4" is surrounded by the border. And the simple trigger is used. So the situation is the same with above "Sample situations 2" of "Preparation 1". By this, when the value of cell "C4" is deleted by the delete button, "value":{"oldValue":"deleted value"} is returned. In this case, how about the following method? * *When you want to use the simple trigger, I think that the script of the bottom of your question can be used. *When you can use the installable OnEdit event trigger, you can know whether the value was deleted by checking with and without value in the event object e. References: * *Event Objects *Simple Triggers *Installable Triggers
{ "language": "en", "url": "https://stackoverflow.com/questions/58477852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Qt font renders weird on OS X I just started using Qt (using Qt 5 beta 1), and I found that the fonts rendered in OS X 10.6.8 are messed up. I've tried using different fonts, but they all look like the image I've posted below (very thin, pixelated). How can I get the fonts to render correctly? The code I'm using is simply: #include <QApplication> #include <QLabel> int main(int argc, char *argv[]) { QApplication a(argc, argv); QLabel label("The quick brown fox jumps over the lazy dog..."); label.show(); return a.exec(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/12939540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: MATLAB Fit a line to a histogram I am just wondering, how would I go about fitting a line to histogram, using the z-counts as weights? An example of this is shown below (although this post just discusses overlaying multiple plots), taken from Scatter plot with density in Matlab). My initial thought is to make an array consisting of each pixel from the density plot, repeated n times to make a scatter plot (n == the number of counts), then do a linear polyfit. This seems awfully redundant though. A: The other approach is to do a weighted least squares solution. You need the (x,y) location of each pixel and the number of counts n within each pixel. Then, I think that you'd do the weighted least-squares this way: %gather your known data...have x,y, and n all in the same order as each other A = [x(:) ones(length(x),1)]; %here are the x values from your histogram b = y(:); %here are the y-values from your histogram C = diag(n(:)); %counts from each pixel in your 2D histogram %Define polynomial coefficients as p = [slope; y_offset]; %usual least-squares solution...written here for reference % b = A*p; %remember, p = [slope; y_offset]; % p = inv(A'*A)*(A'*b); %remember, p = [slope; y_offset]; %We want to apply a weighting matrix, so incorporate the weighting matrix % A' * b = A' * C * A * p; p = inv(A' * C * A)*(A' * b); %remember, p = [slope; y_offset]; The biggest uncertainty for me with this solution is whether the C matrix should be made up of n or n.^2, I can never remember. Hopefully, someone can correct me in the comments, if needed. A: If you have the original data, which is a collection of (x,y) points, you simply do a polyfit on the original data: p = polyfit(x(:),y(:),1); %linear fit That will give you a best fit (in the least-squares sense) to the original data, which is what you want. If you do not have the original data, and you only have the 2D histogram, the approach that you defined (which basically recreates a facsimile of the original data) will give a similar answer as if you did the polyfit on the original data.
{ "language": "en", "url": "https://stackoverflow.com/questions/27336771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom image shuffler not working? Basically, what I'm trying to do is shuffle through images using some JavaScript code. All it does is change the display style of the current image to block, and at the same time change the previous one to none. The HTML code: <body> <img src="http://bit.ly/yOqqbg" id="image1" style="display: block;"> <img src="http://bit.ly/dezBUZ" id="image2" style="display: none;"> <img src="http://bit.ly/IvM5HE" id="image3" style="display: none;"> </body>​ The JavaScript code: var id = ["image1", "image2", "image3"]; //Array with the id's in the document you want to shuffle through var i = 0; //Set inital array element initiateTimer(); //Get the loop going function initiateTimer() { if (i > id.length) { i = 0; initiateTimer(); } setTimeout(function() { changeElement(); }, 2000); //2000 = 2 seconds } function changeElement() { if (id === 0) { document.getElementById(id[2]).style.display = 'none'; document.getElementById(id[i]).style.display = 'block'; } else { document.getElementById(id[i - 1]).style.display = 'none'; document.getElementById(id[i]).style.display = 'block'; } i += 1; initiateTimer(); } ​ A: when i === 3 you will have problems if (i > id.length) { should become if (i >= id.length) { UPDATE: http://jsfiddle.net/HgNuc/
{ "language": "en", "url": "https://stackoverflow.com/questions/10201412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cant open a doc file from the browser I have a link using tag and it is linked to a .doc file in the server. When I click on the link, instead of giving the open, save box, it opens the file in the browser in the binary format. Has anyone encountered this problem? I am using a Weblogic server. A: As Russ said, sometimes you have to add the Content-Type header to explicitly set the mime type; and sometimes, you also have to add a Content-Disposition header, perhaps to a value like "attachment; filename=doc1.doc" If Russ' fix doesn't work for you, try adding this additional header. A: try setting the MIME Type, possibly to application/msword or application/doc EDIT: If the server doesn't know the mime type of the file then it defaults to text/plain and displays the bytes.
{ "language": "en", "url": "https://stackoverflow.com/questions/1101010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is Microsoft.PythonTools.Attacher.exe blocking Visual Studio 2010? At least two or three times a day Visual Studio gets stuck (in a deadlock I suspect) and displays the spinning-toilet-bowl-of-death cursor and pops up the dreaded "Microsoft Visual Studio is Busy" notification in the notification area: It used to be that when this happened Visual Studio would stay like that for hours (and possibly until the end of time itself or a power cut) unless I kicked it to the kerb with an "End Process" in task manager. More recently I noticed another process always seemed to be lurking about whenever this problem arises - Microsoft.PythonTools.Attacher.exe - which is part of the Python Tools for Visual Studio project: If I kill that process then Visual Studio manages to free itself from whatever deadly embrace it's got itself into and can continue on its way, and this is what I look out for every time VS does this. Whilst I do have Python Tools for Visual Studio 1.0 installed, the projects I am working on are plain old ASP.NET MVC3 apps written in C#. I'm not using any Python code or libraries and often I only have one instance of Visual Studio running. What I also observe is that this process doesn't always start/appear for whole development sessions, and when it does, it seems to start up an random times (i.e. it's not there for the first hour or two and then it magically appears in the process list in task manager), but when it does I know I'm going be in trouble at some point. Does anyone know why this process seems to randomly start and why it's interfering with Visual Studio in such a dramatic fashion? I'm running Visual Studio 2010 Premium SP1 on Windows 7 Ultimate x64 SP1. A: When you do Debug->Attach to Process you'll see that VS displays a list of processes and along with them it displays the types of code that you can debug which are running in those processes. To get this information VS queries the various installed debug engines. So when we get queried we go and inspect a bunch of processes to see what's going on. If it's a 32 bit process life is easy - we can use various APIs to enumerate the modules and try and figure out if there's a Python interpreter in the process. If it's a 64-bit process life is a little tougher because we're running inside of VS and it's a 32-bit process. We can't use the APIs from a 32-bit to a 64-bit process so instead we spawn a helper process to do the work. It sounds like this helper process is somehow becoming a zombie on your system. It'd be great if you could attach VS to it and send any stack traces back in a bug. But we should also provide some defense in depth and timeout if the helper process isn't responding. Finally killing it should generally be safe, it's not doing anything stateful, and we'll start a new one when we need it. If you never use Debug->Attach to Process for Python debugging there's probably a trivial file update to our .pkgdef file which I could track down and post which would make this problem go away entirely.
{ "language": "en", "url": "https://stackoverflow.com/questions/10740000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to trigger fresh install instead of update? I'm an android developer and I'll be releasing a new update of my application in the coming days. But the new update is a complete redesign of the app's entire architecture, so I'd like the user to uninstall the previous version of the app before he installs the new version so that all the cached data/already logged in user gets cleared and the user makes a fresh start. I was wondering how I could make this happen? What are my best options? Thanks! A: If you use sqflite or shared_preferences simply remove all data in the main() function with clear all keys or clear the database. Then you need to write a function that will execute this part of the code once. So basically that's all. import 'package:shared_preferences/shared_preferences.dart'; void main(List<String> arguments) async { bool isDataCleared = false; if (isDataCleared == false) { final prefs = await SharedPreferences.getInstance(); prefs.clear(); isDataCleared = true; prefs.setBool('isDataCleared', isDataCleared); } else { // Do something or continue } } I hope it will help! A: You must have made the changes in your code previously for it to trigger an update whenever there is a new release automatically. There is a workaround I can think of though: You can embed some data in this new release which should be passed to the backend. If this new data is not passed, you should log them out with an error message to update the application. This approach is because the backend is the only common link between the old and new applications.
{ "language": "en", "url": "https://stackoverflow.com/questions/72327105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tutorial to create phone book contact in Android SDK Although there are sites out there to help me create a contact, I am still not able to understand how to do it, Can someone give me a pointer/link/suggestion, that teaches me from scratch how to create a phone contact that will eventually show up in phone contacts list. Thank you. A: While I don't know of any tutorials to show step by step. These links may help: * *Using the Contacts API *ContactManager - Contact Manager
{ "language": "en", "url": "https://stackoverflow.com/questions/7324394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Mongoose Connection I read the quick start from the Mongoose website and I almost copy the code, but I cannot connect the MongoDB using Node.js. var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test'); exports.test = function(req, res) { var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); console.log("h1"); db.once('open', function callback () { console.log("h"); }); res.render('test'); }; This is my code. The console only prints h1, not h. Where am I wrong? A: Mongoose connection using Singleton Pattern Mongoose Connection File - db.js //Import the mongoose module const mongoose = require('mongoose'); class Database { // Singleton connection = mongoose.connection; constructor() { try { this.connection .on('open', console.info.bind(console, 'Database connection: open')) .on('close', console.info.bind(console, 'Database connection: close')) .on('disconnected', console.info.bind(console, 'Database connection: disconnecting')) .on('disconnected', console.info.bind(console, 'Database connection: disconnected')) .on('reconnected', console.info.bind(console, 'Database connection: reconnected')) .on('fullsetup', console.info.bind(console, 'Database connection: fullsetup')) .on('all', console.info.bind(console, 'Database connection: all')) .on('error', console.error.bind(console, 'MongoDB connection: error:')); } catch (error) { console.error(error); } } async connect(username, password, dbname) { try { await mongoose.connect( `mongodb+srv://${username}:${password}@cluster0.2a7nn.mongodb.net/${dbname}?retryWrites=true&w=majority`, { useNewUrlParser: true, useUnifiedTopology: true } ); } catch (error) { console.error(error); } } async close() { try { await this.connection.close(); } catch (error) { console.error(error); } } } module.exports = new Database(); call the connection from app.js const express = require("express"); // Express Server Framework const Database = require("./utils/db"); const app = express(); Database.connect("username", "password", "dbname"); module.exports = app; A: When you call mongoose.connect, it will set up a connection with the database. However, you attach the event listener for open at a much later point in time (when a request is being handled), meaning that the connection is probably already active and the open event has already been called (you just weren't yet listening for it). You should rearrange your code so that the event handler is as close (in time) to the connect call as possible: var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test'); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function callback () { console.log("h"); }); exports.test = function(req,res) { res.render('test'); }; A: I had the same error popping up. Then I found out that I didn't have a mongod running and listening for connections. To do that you just need to open another command prompt (cmd) and run mongod A: The safest way to do this, it to "listen for the connect event". This way you don't care how long it takes for the DB to give you a connection. Once that is done - you should start the server. Also.. config.MONGOOSE is exposed across your app, so you only have one DB connection. If you want to use mongoose's connection, simply require config in your module, and call config.Mongoose. Hope this helps out someone! Here's the code. var mongoURI; mongoose.connection.on("open", function(ref) { console.log("Connected to mongo server."); return start_up(); }); mongoose.connection.on("error", function(err) { console.log("Could not connect to mongo server!"); return console.log(err); }); mongoURI = "mongodb://localhost/dbanme"; config.MONGOOSE = mongoose.connect(mongoURI); A: Mongoose's default connection logic is deprecated as of 4.11.0. It is recommended to use the new connection logic: * *useMongoClient option *native promise library Here is the example from npm module: mongoose-connect-db // Connection options const defaultOptions = { // Use native promises (in driver) promiseLibrary: global.Promise, useMongoClient: true, // Write concern (Journal Acknowledged) w: 1, j: true }; function connect (mongoose, dbURI, options = {}) { // Merge options with defaults const driverOptions = Object.assign(defaultOptions, options); // Use Promise from options (mongoose) mongoose.Promise = driverOptions.promiseLibrary; // Connect mongoose.connect(dbURI, driverOptions); // If the Node process ends, close the Mongoose connection process.on('SIGINT', () => { mongoose.connection.close(() => { process.exit(0); }); }); return mongoose.connection; } A: A simple way i make a connection: const mongoose = require('mongoose') mongoose.connect(<connection string>); mongoose.Promise = global.Promise; mongoose.connection.on("error", error => { console.log('Problem connection to the database'+error); });
{ "language": "en", "url": "https://stackoverflow.com/questions/20360531", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: Android TV :Show Row Title always How do I get the title of the individual rows to always appear instead of only when it is selected? Like the example here in Youtube app, "Uploads" and "Popular Uploads" should always be seen. A: I just answered this question here, but the general gist is: I was able to achieve this affect by calling setExpand(true) as the first line of my onCreateView() in my RowsFragment. If you want to lock this effect forever, you can override setExpand(...) in your RowsFragment and just call super.setExpand(true). I believe you'll still need the initial call in onCreateView() though.
{ "language": "en", "url": "https://stackoverflow.com/questions/39401447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the best data structure to store playing cards held in a player's hand? I'm beginner in java and I'm currently creating a card game like gin rummy for Android. I want to know what's the best implementation for creating Hand class? What's the best way where to store the card returned by Deck.dealt()? * *Array *ArrayList *Vector *HashSet *LinkedList Also, I would appreciate if anyone could provide a gin rummy open source links. A: I think a good idea would be to use an interface (List if element are ordered, or Set if elements are not ordered. You can use the implementation you prefer, for example: List<Card> deck = new ArrayList<Card>(); or Set<Card> deck = new HashSet<Card>(); A: If you really want to understand the nuances between the collection types, here goes. List isn't technically appropriate except when the game is Bohnanza (which, ahem, is one of the greatest card games of all time, but I'mma let me finish). List says, among other things, that one hand containing the Ace and King of Clubs, and another hand containing the King and Ace of Clubs, are fundamentally not the same hand. This is a much stronger dependence on order than simply "well, I want to remember the order that the user wants to see their cards in", which is a property that tons of non-List collections have, like LinkedHashSet and Guava's ImmutableSet. List also implies that there is some particular significance attached to the card that sits in index N. This is true of no card game I know. Set isn't generally appropriate for card games -- only the ones that use a single deck of completely unique cards. To allow duplicates but still have order-independent equality, the type to use is Guava's Multiset. For example HashMultiset or ImmutableMultiset. Note that most multiset implementations represent multiple "equal" cards by storing just the card and a count, so when iterating over them, duplicates of a card you have in your hand must always appear together. If it's important to let the user freely control the order of cards in her hand, you would need LinkedListMultiset. Now that lesson time is over.... well, let's be honest. Calling myHand.equals(yourHand), or using an entire hand as a key in a Map is not actually something you're ever going to do... so go ahead and use the ArrayList, you'll be fine. :-) A: Store them in an ArrayList. Cards in a hand are in a certain order, not in an unordered pile. This ordering is preserved in a List over a Set. ArrayList also gives you the opportunity to select a specific card by index, which will be helpful as you implement the game. Keep in mind that as long as you design your Hand class properly, you can always change this data structure easily at any point in the future. As long as you keep this in mind with any class you design, you can always change it if you realize you need something different. A: Well, a HashSet is faster(as far as I know), but if you want to make a card game, then maybe you will wish to sort the cards. That is why I would suggest using a List. If you are a beginner, then maybe the best thing would be to use an ArrayList. It's easy to use and understand. At least this is what I would do. If you want to learn more, I suggest reading about each one's unique properties so that you can decide for yourself. And yes, like greuze said before, you should use an interface for more flexibility. A: Firstly, use of Vector is discouraged in the latest versions of Java, so you can probably ignore that one. Secondly, as you'll know if you're read the Javadoc on those remaining classes, they all have advantages or disadvantages. Some have an order, some can take duplicate values, some cannot and so on. Therefore I think the best approach is to write some pseudo-code for your application which is not based on a specific class (just write things like 'add Card to Hand', 'remove card from Hand'). Once you have some of this pseudo code you will be able to see your requirements more clearly; will you want to keep the cards in the hand in a specific order? will you want to be able to retrieve cards from the hand by a key? Then, your choice will be clearer. A: Keeping the deck in a List makes sense as it does maintain order. I tend to default to using Lists.newArrayList() to create a List. Lists is part of Guava. I strongly recommend using and getting to know Guava since it has many useful offerings. It would make sense to be able to keep the hand in some data structure that could be sorted easily in order to make it easier to compare hands. OTOH, IIRC, gin rummy hands aren't all that large.
{ "language": "en", "url": "https://stackoverflow.com/questions/9128486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Using nonce or hash values in content-security-policy for inline styles I am adding content-security-policy settings for my web app and would like to be strict about inline scripts and inline styles. I have inline scripts working properly but am having trouble with inline styles. For background, my web app uses Elixir/Phoenix on the back end and includes React components on the front end. Nonce for Inline Scripts - Works I have just a smattering of inline scripts to get the React components bootstrapped. Per CSP guidelines, I'm using nonce values to handle these inline scripts. Specifically, I generate a new nonce value server side on each page load and include it in the content-security-policy header and also inject it into a nonce attribute in the script tags using server side rendering. This works fine. Nonce for Inline Styles - Doesn't Work Inlines styles are another story. Inlines styles are pretty common in React. My hope was that I could use a similar nonce approach for this, but so far I have not been able to get it to work. Nonce values are listed in the style-src page at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/style-src so it seems like this should work, though that section of the doc references scripts so maybe not. I have tried injecting a nonce attribute into the generated HTML, but this does not work. I continue to receive the normal error messages. Refused to apply inline style because it violates the following Content Security Policy directive: "default-src 'self' 'nonce-my-long-ugly-random-nonce-value'". Either the 'unsafe-inline' keyword, a hash ('sha256-specific-hash'), or a nonce ('nonce-...') is required to enable inline execution. Note also that 'style-src' was not explicitly set, so 'default-src' is used as a fallback. I've been searching for a while and have yet to find any hint that nonce values work for inline styles, other than what I mention above. Can anyone confirm that nonce values work for inline styles? If they don't work, it seems like using hashes is my next best bet. I can get hashes to work, by looking at each error message like the one above and adding the hash to the content-security-policy header. That is not a very scalable solution though, and if I have to go that route I'd like to know if anyone has come up with a way to automate generating the hashes without having to manually navigate everywhere in the app and look at the error message to get the hash. Any help you can provide is appreciated. Thanks. Justin A: After looking at Content Security Policy allow inline style without unsafe-inline it appears this isn't supported, perhaps because the spec seems to imply that it is referring only to inline styles in a <style> tag, similar how the spec refers to inline scripts in a <script> tag. Assuming that is correct, it looks like I'll have to go the hash route or add 'unsafe-inline' just for style-src.
{ "language": "en", "url": "https://stackoverflow.com/questions/51793793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SELECT UPDATE SQL Not Working I have 2 forms First Form has Public Class frmMain Friend strBillIDNumber As String Friend strBillPassword As String Friend ds As New DataSet Friend cnn As OleDbConnection Friend sql As String Friend adptr As OleDbDataAdapter Dim attempt As Integer = 1 Private Sub btnSign_Click(sender As Object, e As EventArgs) Handles btnSign.Click Dim connectionString As String connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Renz\Documents\Visual Studio 2012\FINAL\Database\UsersDB.accdb;" sql = "Select ID, LASTNAME, FIRSTNAME, LOGINSTATUS from TblUser" cnn = New OleDbConnection(connectionString) Try cnn.Open() adptr = New OleDbDataAdapter(sql, cnn) adptr.Fill(ds) For i = 0 To ds.Tables(0).Rows.Count - 1 If ds.Tables(0).Rows(i).Item(0) = txtID.Text Then MessageBox.Show("UserName Matched") If ds.Tables(0).Rows(i).Item(1) = txtPassword.Text Then MessageBox.Show("Password Matched") If txtPassword.Text = "admin" Then MessageBox.Show("You are now Logged In as Admin.") frmFaculty.Show() Me.Hide() Else frmStudent.lblSI.Text = ds.Tables(0).Rows(i).Item(0) frmStudent.lblLN.Text = ds.Tables(0).Rows(i).Item(1) frmStudent.lblFN.Text = ds.Tables(0).Rows(i).Item(2) frmStudent.lblLS.Text = ds.Tables(0).Rows(i).Item(3) MessageBox.Show("You are now Logged In.") frmStudent.Show() Me.Hide() End If Else MessageBox.Show("Invalid Password.") MessageBox.Show("Please Try Again." & vbNewLine & "ATTEMPT: " & attempt & " out of 3") attempt = attempt + 1 End If End If Next adptr.Dispose() cnn.Close() Catch ex As Exception MessageBox.Show("Please Try Again!") End Try 'log-in attempt 3x fail' If attempt > 3 Then MessageBox.Show("You have exceeded the number of login attempt." & vbNewLine & "Please Contact the Administrator.") End If End Sub And my Second Form Has Imports System.Data.OleDb Public Class frmStudent Dim TimeInHold As String Private Sub loginBTN_Click(sender As Object, e As EventArgs) Handles loginBTN.Click Dim cnn2 As New OleDbConnection Dim Command As OleDbCommand Dim i As Integer Dim sql2 As String Dim status As String Try cnn2 = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Renz\Documents\Visual Studio 2012\FINAL\Database\AuditDB.mdb;") cnn2.Open() sql2 = "INSERT INTO Audit ([ID],[TIMEIN]) VALUES('" & frmMain.txtID.Text & "','" & DateTime.Now & "')" Command = New OleDbCommand(sql2, cnn2) i = Command.ExecuteNonQuery Catch ex As Exception cnn2.Close() End Try MessageBox.Show("You have successfully Signed in." & vbNewLine & " Please Don't Forget to Logout.") frmMain.cnn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Renz\Documents\Visual Studio 2012\FINAL\Database\UsersDB.accdb;") frmMain.cnn.Open() frmMain.adptr = New OleDbDataAdapter(frmMain.sql, frmMain.cnn) frmMain.adptr.Fill(frmMain.ds) If frmMain.ds.Tables(0).Rows(i).Item(0) = lblSI.Text Then frmMain.sql = "UPDATE TblUser SET LOGINSTATUS = 'SignedIn'" frmMain.cnn.Close() End If Me.Close() frmMain.Show() frmMain.txtID.Text = String.Empty frmMain.txtPassword.Text = String.Empty End Sub I can't get my SELECT and UPDATE sql statement to work that will get the data set from form 1. And when the button is clicked, it will update the field "LoginStatus" to a value of "Signed In". P.S. I'm creating a time-in, time-out monitoring system that will determine if the user is an admin or a student and will redirect them to their corresponding forms. Student form will have sign in and sign out buttons, and will record their time in and time out. When sign in is clicked, it will be grayed out. Please Help.. A: If frmMain.ds.Tables(0).Rows(i).Item(0) = lblSI.Text Then frmMain.sql = "UPDATE TblUser SET LOGINSTATUS = 'SignedIn'" frmMain.cnn.Close() End If It seems that the UPDATE statement doesn't get executed. I don't see ExecuteNonQuery for it. ps: The UPDATE statement is to update all records in the table. Look out! ps2: I'm not familiar with the VB(.net) :) A: I think you are missing executeNonQuery in second form and is there only one user then query is fine if more than one consider using " Where Clause" eg. sql= "UPDATE TblUser SET LOGINSTATUS = 'SignedIn' where ID =" <provide id> if that doesn't solve your problem then feel free to ask more. Regards.
{ "language": "en", "url": "https://stackoverflow.com/questions/19217893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Gatsby Dynamic Image I have a problem: this is my Heroes component const Hero = styled.div` display: flex; flex-direction: column; justify-content: flex-end; background: linear-gradient(to top, #1f1f21 1%, #1f1f21 1%,rgba(25, 26, 27, 0) 100%) , url(${props => props.bgdesktop}) no-repeat top center; height: 100vh; background-size: cover; @media (max-width:1024px) { background: linear-gradient(to top, #1f1f21 1%, #1f1f21 1%,rgba(25, 26, 27, 0) 100%) , url(${props => props.bgtablet}) no-repeat center top; } @media (max-width:480px) { background:linear-gradient(to top, rgba(31, 31, 33, 1) 2%, rgba(31, 31,33, 1) 5%,rgba(25, 26, 27, 0) 100%) , url(${props => props.bgmobile}) no-repeat center top; } ` class Heroes extends React.Component { constructor(props) { super(props); ... render() { return ( <Hero bgdesktop={this.props.bgdesktop} bgtablet={this.props.bgtablet} bgmobile={this.props.bgmobile}/> )}} Then I added this component to 'pages/Hero.js': export default props => { const hero = props.location.href ? heroCards.find(h => h.name === props.location.href.substring(28)) : heroCards[0] return ( <Layout> <Heroes bgdesktop={require(`./../images/BG/${hero.name}_Desktop.jpg`)} bgtablet={require(`./../images/BG/${hero.name}_Tablet.jpg`)} bgmobile={require(`./../images/BG/${hero.name}_Mobile.jpg`)} /> </Layout> ) } Now, clicking on different buttons on the Home page, I'm redirected different pages that take different bg depending on 'name' included in heroes.js (located in costants folder). It works on local but not on production and the problem is gatsby that doesn't allow that '{require(./../images/BG/${hero.name}_Desktop.jpg)}'. How can I solve this problem? A: I don't think you need require for this. Why not use the prop you pass and bake that into a string literal that you insert into the component (without require and outside of the return)? const mobilePath = `./../images/BG/${props.bgmobile}_Mobile.jpg`; const desktopPath = `./../images/BG/${props.bgdesktop}_Desktop.jpg`; return( <Heroes mobile={mobilePath} desktop={desktopPath} /> ) EDIT: the substring part could be added in either <Heroes> before passing the prop. Or by filtering the prop in <Hero> and passing that variable instead of the prop
{ "language": "en", "url": "https://stackoverflow.com/questions/55044068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Recursion time complexity I am looking for help in understanding what the Time/Space complexity of my solution, for finding permutations of an array, is. I know that because I am using an Array.forEach method that my time complexity includes O(n), however since I am also using recursion I do not know how the time complexity changes. The recursion seems to me to be in O(n) time complexity as well. Does that make the overall time complexity of the algorithm O(n^2)? And for space complexity is that 0(n) as well? since each recursion call returns a bigger memory array? Thanks in advance. function getPermutations(array) { if (array.length <= 1){ return array.length === 0 ? array : [array]; } let lastNum = array[array.length - 1] let arrayWithoutLastNum = array.slice(0, array.length - 1); let permutations = getPermutations(arrayWithoutLastNum); let memory = [] permutations.forEach(element => { for(let i = 0; i <= element.length; i++){ let elementCopy = element.slice(0); elementCopy.splice(i, 0, lastNum) memory.push(elementCopy) } }) return memory }
{ "language": "en", "url": "https://stackoverflow.com/questions/73878792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I need to delete an element in an array everytime a user press , but when is being output after deletion I got long number like ; 124352919 int main () { int a[]={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,66,67,68,69,70,71,72,73,74,75}; char ans; int i = 0; int pos = 0; cout<<"Press y to generate number"<<"\n"; cin >> ans; while(ans=='y'||ans=='Y') { cout<<"\n\nEnter position to Delete number :: "; cin>>pos; --pos; for(i=pos;i<=size-1;i++) { a[i]=a[i+1]; cout<<" "<<a[i]<<" "; } cout<<"\nNew Array is :: \n\n"; for(i=0;i<size-1;i++) { } cout<<"Press y to generate number"<<"\n"; cin >> ans; } cout << "\n\n"; //I need to delete an element in the array ,for example ; if I input position 67 ,it deletes position 67 but when the array is being after deletion , I got 1312123131 at the end A: You can't delete an element from an array, but you can delete a vector element like this: #include <iostream> #include <vector> using namespace std; int main() { vector<int> nums = { 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,66,67,68,69,70,71,72,73,74,75 }; char ans; int pos = 0; cout << "Press y to generate number: "; cin >> ans; while (ans == 'y' || ans == 'Y') { cout << "\n\nEnter position to Delete number: "; cin >> pos; --pos; nums.erase(nums.begin() + pos); cout << "\nNew Array is:\n\n"; for (const auto& element : nums) { std::cout << element << '\n'; } cout << "Press y to generate number" << "\n"; cin >> ans; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/71068134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Python MultiProcessing I'm using Python Python Multiprocessing for a RabbitMQ Consumers. On Application Start I create 4 WorkerProcesses. def start_workers(num=4): for i in xrange(num): process = WorkerProcess() process.start() Below you find my WorkerClass. The Logic works so far, I create 4 parallel Consumer Processes. But the Problem is after a Process got killed. I want to create a new Process. The Problem in the Logic below is that the new Process is created as child process from the old one and after a while the memory runs out of space. Is there any possibility with Python Multiprocessing to start a new process and kill the old one correctly? class WorkerProcess(multiprocessing.Process): def ___init__(self): app.logger.info('%s: Starting new Thread!', self.name) super(multiprocessing.Process, self).__init__() def shutdown(self): process = WorkerProcess() process.start() return True def kill(self): start_workers(1) self.terminate() def run(self): try: # Connect to RabbitMQ credentials = pika.PlainCredentials(app.config.get('RABBIT_USER'), app.config.get('RABBIT_PASS')) connection = pika.BlockingConnection( pika.ConnectionParameters(host=app.config.get('RABBITMQ_SERVER'), port=5672, credentials=credentials)) channel = connection.channel() # Declare the Queue channel.queue_declare(queue='screenshotlayer', auto_delete=False, durable=True) app.logger.info('%s: Start to consume from RabbitMQ.', self.name) channel.basic_qos(prefetch_count=1) channel.basic_consume(callback, queue='screenshotlayer') channel.start_consuming() app.logger.info('%s: Thread is going to sleep!', self.name) # do what channel.start_consuming() does but with stoppping signal #while self.stop_working.is_set(): # channel.transport.connection.process_data_events() channel.stop_consuming() connection.close() except Exception as e: self.shutdown() return 0 Thank You A: In the main process, keep track of your subprocesses (in a list) and loop over them with .join(timeout=50) (https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Process.join). Then check is he is alive (https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Process.is_alive). If he is not, replace him with a fresh one. def start_workers(n): wks = [] for _ in range(n): wks.append(WorkerProcess()) wks[-1].start() while True: #Remove all terminated process wks = [p for p in wks if p.is_alive()] #Start new process for i in range(n-len(wks)): wks.append(WorkerProcess()) wks[-1].start() A: I would not handle the process pool management myself. Instead, I would use the ProcessPoolExecutor from the concurrent.future module. No need to inherit the WorkerProcess to inherit the Process class. Just write your actual code in the class and then submit it to a process pool executor. The executor would have a pool of processes always ready to execute your tasks. This way you can keep things simple and less headache for you. You can read more about in my blog post here: http://masnun.com/2016/03/29/python-a-quick-introduction-to-the-concurrent-futures-module.html Example Code: from concurrent.futures import ProcessPoolExecutor from time import sleep def return_after_5_secs(message): sleep(5) return message pool = ProcessPoolExecutor(3) future = pool.submit(return_after_5_secs, ("hello")) print(future.done()) sleep(5) print(future.done()) print("Result: " + future.result())
{ "language": "en", "url": "https://stackoverflow.com/questions/37612535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OutputDebugString error I use: OutputDebugString(L"My error"); in Visual Studio 2010, but instead of displaying "My error", I get just an "ERROR" in the window. How do I fix this issue? A: Since you're explicitly passing an UNICODE string, I'd suggest you also explicitly call OutputDebugStringW(). Otherwise, if the UNICODE preprocessor symbol is not defined in your compilation unit, the ANSI version of the function (OutputDebugStringA()) would end up being called with an UNICODE string, which it does not support, and it should result in a compilation error. EDIT: You cannot use OutputDebugString() to write a string in your application's status bar. OutputDebugString() only sends the string you pass to the debugger. You have to use the appropriate API to write text to the status bar instead. In your case, wxStatusBar::SetStatusText() should do the trick.
{ "language": "en", "url": "https://stackoverflow.com/questions/6800521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does FPS go down if canvas is larger than 255x220? I've found a wierd phenomenon with HTML5 canvas. I was getting a lower than expected framerate, but only in Firefox, and only on one computer (but not on another I tested). The wierd thing is, if I reduce the canvas size to be 255x250 or less, Firefox performs similar to other browsers. If I add one more pixel in width, the FPS falls rapidly to a third. I've made a jsPerf to demonstrate the problem: http://jsperf.com/critical-canvas-size (Make sure that the grey rectangle is on screen. I let the tests fail if not, because I found it changes the results if you scroll away accidentally.) All four test cases are pretty similar with most browsers on most systems, but on this one PC with Firefox 17, I see the following: The PC in question is running an older Red Hat Linux, and I guess it probably doesn't have hardware accelleration support (from the OS side). So, what could be the cause for this? Is there anything I can do in my code to circumvent the issue? (I've been thinking about using several small canvasses instead of one large one, for example.) Edit: Here is a standalone html file that exibits the problem, and one that doesn't. The only difference is the width of the canvas, 251 vs. 250. (You can comment out the spinner animation, it is just to make the problem visible. Also please excuse the accuracy of the FPS timer, its implementation is very simple.) The 250px version gets about 60 FPS, in fact it seems to be capped. You can increase the numIterations variable to make the frame function draw a multiple amount of tiles. I can get up to numIterations = 100, or 120000 tiles/sec, while still having a decent framerate. However, the 251px version gives me even for numIterations = 1 a framerate below 20, or less than 1000 tiles/sec. A: This makes sense because drawing to the canvas and clearing the canvas are expensive methods; if you have a smaller canvas and call clearRect on it every animation step then it will perform better than a larger canvas running the exact same code. The best thing to do is optimise your draw method to only clear what changed each frame. Once you do that you will notice a performance boost; this article will help with other areas in which you can increase performance. I'm developing with canvas too and have found that WebKit based browsers, in general, handle canvas operations quicker than Gecko in most cases. A: I actually see similar behavior. I believe it is when you cross the 65776 pixel barrier -> not 65536 as you would expect. I don't yet know why this is the case, but it is likely some kind of internal data structure or data type issue (possibly its using a hash and needs to grow the table at that point) inside your browser. Your test is actually invalid on my chrome browser - it does not exhibit the same performance drop. I wrote some test cases http://jsperf.com/pixel-count-matters/2 and http://jsperf.com/magic-canvas/2 Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/14366155", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: React Actions using RxJS for parallel async calls I am having an existing action that calls the api with list of IDs as querystring parameter and fetches the thumbnail response for the passed IDs. In some cases, count of IDs can be 150-200 records. Hence, I am working on making this APIs call batch based and run in parallel using forkJoin and subscribe methods of RxJs. I'm facing following 3 issues regarding the implementation. * *I am able to get the batch based response in next method of subscribe. However, the action invoked in this function along with response is not getting invoked. *maxParallelQueries dont seems to be working as intended. All the fetchThumbnailObservables() are executed at once and not in the batches of 3 as set as constant/ *How to handle return of observable so that mergeMap do not give syntax error . Argument of type '({ payload }: IAction) => void' is not assignable to parameter of type '(value: IAction, index: number) => ObservableInput<any>'. Type 'void' is not assignable to type 'ObservableInput<any>'.ts(2345) Here is my current code looks like. Any help would be great on this. const getThumbnails: Epic<IAction, IAction, IStoreState> = (action$, state$) => action$.ofType(ActionTypes.AssetActions.DATA.FETCH_THUMBNAILS).pipe( mergeMap( ({ payload }) => { const assetIds = Object.keys(payload); const meta = payload; const batchSize = 10; const maxParallelQueries = 3; const fetchThumbnailObservables : Observable<IThumbnailResponse>[] = []; for (let count = 0; count < assetIds.length; count += batchSize) { fetchThumbnailObservables.push(AssetDataService.fetchThumbnailData(assetIds.slice(count, count + batchSize))); } forkJoin(fetchThumbnailObservables) .pipe(mergeMap(fetchThumbnailObservable => fetchThumbnailObservable, maxParallelQueries)) // Issue 1 : maxParallelQueries limit is not working .subscribe({ complete: () => { }, error: () => { }, next: (response) => { // Issue 2 : below action dont seems to be getting invoked actions.AssetActions.receivedThumbnailsAction(response, meta) }, }); // Issue 3 : How to handle return of observable // Added below code for prevennting error raised by mergeMap( ({ payload }) => { return new Observable<any>(); }), catchError((error) => of(actions.Common.errorOccured({ error }))) ); ``` A: I do not know Epics, but I think I can give you some hints about how to address this problem. Let's start from the fact that you have an array of ids, assetIds, and you want to make an http call for each id with a controlled level of concurrency, maxParallelQueries. In this case from function and mergeMap operator are yor friends. What you need to do is // from function transform an array of values, in this case, to a stream of values from(assetIds).pipe( mergeMap(id => { // do whatever you need to do and eventually return an Observable return AssetDataService.fetchThumbnailData(id) }, maxParallelQueries) // the second parameter of mergeMap is the concurrency ) In this way you should be able to invoke the http calls keeping the limit of concurrency you have established A: * *I am able to get the batch based response in next method of subscribe. However, the action invoked in this function along with response is not getting invoked. You mustn't call an action imperatively in redux-observable. Instead you need to queue them. actions.AssetActions.receivedThumbnailsAction(response, meta) would return an plain object of the shape {type: "MY_ACTION", payload: ...} instead of dispatching an action. You rather want to return that object wrapped inside an observable inside mergeMap in order to add the next action to the queue. (see solution below) *maxParallelQueries dont seems to be working as intended. All the fetchThumbnailObservables() are executed at once and not in the batches of 3 as set as constant/ First guess: What is the return type of AssetDataService.fetchThumbnailData(assetIds.slice(count, count + batchSize))? If it is of type Promise then maxParallelQueries has no effect because promises are eager and start immediately when created thus before mergeMap has the chance to control the request. So make sure that fetchThumbnailData returns an observable. Use defer rather than from if you need to convert a Promise to an Observable to make sure that a promise is not being fired prematurely inside fetchThumbnailData. Second guess: forkJoin is firing all the request so mergeMap doesn't even have the chance to restrict the number of parallel queries. I'm surprised that typescript doesn't warn you here about the incorrect return type in mergeMap(fetchThumbnailObservable => fetchThumbnailObservable, ...). My solution below replaces forJoin with from and should enable your maxParallelQueries. *How to handle return of observable so that mergeMap do not give syntax error . Argument of type '({ payload }: IAction) => void' is not assignable to parameter of type '(value: IAction, index: number) => ObservableInput'. Type 'void' is not assignable to type 'ObservableInput'.ts(2345) This is not a syntax error. In an epic you have either the option to return an empty observable return empty() if no subsequent actions are intended or dispatch another action by returning an observable of type IAction. Here my (untested) attempt to meet your requirements: const getThumbnails: Epic<IAction, IAction, IStoreState> = (action$, state$) => action$.ofType(ActionTypes.AssetActions.DATA.FETCH_THUMBNAILS).pipe( mergeMap( ({ payload }) => { const assetIds = Object.keys(payload); const meta = payload; const batchSize = 10; const maxParallelQueries = 3; const fetchThumbnailObservables : Observable<IThumbnailResponse>[] = []; for (let count = 0; count < assetIds.length; count += batchSize) { fetchThumbnailObservables.push( AssetDataService.fetchThumbnailData( assetIds.slice(count, count + batchSize) ) ); } return from(fetchThumbnailObservables) .pipe( mergeMap( fetchThumbnailObservable => fetchThumbnailObservable, maxParallelQueries ), map((response) => // dispatch action for each response actions.AssetActions.receivedThumbnailsAction(response, meta) ), // catch error early so epic continue on error catchError((error) => of(actions.Common.errorOccured({ error }))) ); }) ); Please notice that I moved catchError closer to the request (inside the inner forkJoin Observable) so that the epic does not get terminated when an error occurs. Error Handling - redux observable This is so because when catchError is active it replaces the failed observable with the one that is returned by catchError. And I assume you don't want to replace the whole epic in case of an error? And one thing: redux-observable handles the subscriptions for you so won't need to call .subscribe or .unsubscribe anywhere in your application. You just need to care a about the lifecycle of observables. Most important to know here is when does an observable start, what happens to it when it completes, when does it complete or what happens when an observable throws.
{ "language": "en", "url": "https://stackoverflow.com/questions/66565527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Stream compaction and transform based on the index in CUDA I have an array of float that I would like to perform a stram compaction operation on, like what is presented here: Parallel Prefix Sum (Scan) with CUDA, and then apply a transform based on the value and the address or the original element. For example, I have an array with the values {10,-1, -10, 2}, and I want to return all the elements with an absolute value greater than 5, and apply a transform taking the value and its address in the array. The result here would be {transform(10,0),transform(-10,2)}. I'm trying to use thrust with this, but this code will run often on large arrays, so ideally it wouldn't use buffers and multiple traversals of the array. Is it possible to do what I'd like to do without allocating a secondary array and doing multiple traversals? If yes, does such code exist in the wild? Or at least does anybody have any pointers to which functions of thrust or any other library I could compose to reach my goal? A: Yes, it's possible in thrust with a single thrust algorithm call (I assume that is what you mean by "without ... doing multiple traversals") and without "allocating a secondary array". One approach would be to pass the data array plus an index/"address" array (via thrust::counting_iterator, which avoids the allocation) to a thrust::transform_iterator which creates your "transform" operation (combined with an appropriate functor). You would then pass the above transform iterator to an appropriate thrust stream compaction algorithm to select the values you want. Here's a possible approach: $ cat t1044.cu #include <thrust/device_vector.h> #include <thrust/iterator/counting_iterator.h> #include <thrust/iterator/transform_iterator.h> #include <thrust/iterator/zip_iterator.h> #include <thrust/copy.h> #include <math.h> #include <iostream> __host__ __device__ int my_transform(int data, int idx){ return (data - idx); //put whatever transform you want here } struct my_transform_func : public thrust::unary_function<thrust::tuple<int, int>, int> { __host__ __device__ int operator()(thrust::tuple<int, int> &t){ return my_transform(thrust::get<0>(t), thrust::get<1>(t)); } }; struct my_test_func { __host__ __device__ bool operator()(int data){ return (abs(data) > 5); } }; int main(){ int data[] = {10,-1,-10,2}; int dsize = sizeof(data)/sizeof(int); thrust::device_vector<int> d_data(data, data+dsize); thrust::device_vector<int> d_result(dsize); int rsize = thrust::copy_if(thrust::make_transform_iterator(thrust::make_zip_iterator(thrust::make_tuple(d_data.begin(), thrust::counting_iterator<int>(0))), my_transform_func()), thrust::make_transform_iterator(thrust::make_zip_iterator(thrust::make_tuple(d_data.end(), thrust::counting_iterator<int>(dsize))), my_transform_func()), d_data.begin(), d_result.begin(), my_test_func()) - d_result.begin(); thrust::copy_n(d_result.begin(), rsize, std::ostream_iterator<int>(std::cout, ",")); std::cout << std::endl; return 0; } $ nvcc -o t1044 t1044.cu $ ./t1044 10,-12, $ Some possible criticisms of this approach: * *It would appear to be loading the d_data elements twice (once for the transform operation, once for the stencil). However, it's possible that the CUDA optimizing compiler would recognize the redundant load in the thread code that ultimately gets generated, and optimize it out. *It would appear that we are performing the transform operation on every data element, whether we intend to save it or not in the result. Once again, it's possible that the thrust copy_if implementation may actually defer the data loading operation until after the stencil decision is made. If that were the case, its possible that the transform only gets done on an as-needed basis. Even if it is done always, this may be an insignificant issue, since many thrust operations tend to be load/store or memory bandwidth bound, not compute bound. However an interesting alternate approach could be to use the adaptation created by @m.s. here which creates a transform applied to the output iterator step, which would presumably limit the transform operation to only be performed on the data elements that are actually being saved in the result, although I have not inspected that closely either. *As mentioned in the comment below, this approach does allocate temporary storage (thrust does so under the hood, as part of the copy_if operation) and of course I'm explicitly allocating O(n) storage for the result. I suspect the thrust allocation (a single cudaMalloc) is probably also for O(n) storage. While it may be possible to do all the things asked for (parallel prefix sum, stream compaction, data transformation) with absolutely no extra storage of any kind (so perhaps the request is for an in-place operation), I think that crafting an algorithm that way is likely to have significant negative performance implications, if it is doable at all (it's not clear to me a parallel prefix sum can be realized with absolutely no additional storage of any kind, let alone coupling that with a stream compaction i.e. data movement in parallel). Since thrust frees all such temporary storage it uses, there can't be much of a storage concern associated with frequent use of this method. The only remaining concern (I guess) is performance. If the performance is a concern, then the time overhead associated with the temporary allocations should be mostly eliminated by coupling the above algorithm with a thrust custom allocator (also see here), which would allocate the maximum needed storage buffer once, then re-use that buffer each time the above algorithm is used.
{ "language": "en", "url": "https://stackoverflow.com/questions/34790307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MongoDB and Spring Data performance Issue I am using MongoDB with Spring Data for creating our prototype application. The save operation is very fast but for listing the results the performance is very poor even when their are just 3 to 4 records persisted. Another amazing part is the the performance deteriorates with each consecutive list operation. Just to give an idea here is the single json which is not the largest in the world. { "enquiryId": "574feac25215eae3e2e1434b", "enquiryName": "Mineral Shipment", "dateOfEnquiry": null, "requiredFrom": 1465324200000, "requiredTo": 1483036200000, "source": { "locationId": null, "area": { "pincode": null, "area": null, "city": { "cityId": null, "cityName": "Panjim", "state": { "stateId": null, "stateName": " Goa 403001", "country": { "countryId": null, "countryName": " India" } } } } }, "destination": { "locationId": null, "area": { "pincode": null, "area": null, "city": { "cityId": null, "cityName": "Ludhiana", "state": { "stateId": null, "stateName": " Punjab 141001", "country": { "countryId": null, "countryName": " India" } } } } }, "shipment": { "shipmentId": null, "enquiryId": null, "shipmentName": "Mineral Shipment", "valueOfGoods": null, "categories": [ { "categoryId": null, "categoryName": "Hazardous,Flammable", "subCategories": null, "shipmentId": null } ], "modes": [ { "modeId": null, "modeName": "WATER", "modeDescription": null, "shipmentId": null } ], "items": [ { "itemId": null, "itemName": "Coal", "shape": null, "form": null, "dimension": null, "weight": null, "quantity": null, "shipmentId": null }, { "itemId": null, "itemName": "Nickel", "shape": null, "form": null, "dimension": null, "weight": null, "quantity": null, "shipmentId": null } ] }, "transportEnquiries": [ { "transportEnquiryId": null, "transport": { "transportId": null, "name": "Flat Bed", "mode": { "modeId": null, "modeName": "WATER", "modeDescription": "The two world wars gave a great impetus to the development of air transport in almost all the countries of the world", "shipmentId": null }, "type": { "typeId": null, "name": "LWH", "modeId": null, "illustrationURL": null }, "desc": "Description of Flat Bed" } } ], "storageEnquiries": [], "packagingEnquiries": null, "insuranceEnquiries": null, "documentationEnquiry": null, "trackingToolRequired": null, "customerSupportRequired": null, "insuranceRequired": null, "storageRequired": null, "documentationRequired": null, "published": false, "userId": null } And here is the Spring Service public class EnquiryManagementService implements IEnquiryManagementService{ @Autowired private EnquiryRepository enquiryRepository; public Enquiry createEnquiry(Enquiry enquiry) { Enquiry enquiryObj = (Enquiry)enquiry; Enquiry e = enquiryRepository.save(enquiryObj); return e; } @Override public List<Enquiry> listEnquiry(int start) { long startTime = System.currentTimeMillis(); Page<Enquiry> enquiries = enquiryRepository.findAll(new PageRequest(start,10)); long endTime = System.currentTimeMillis(); System.out.println("Time Taken = "+(endTime-startTime)); return enquiries.getContent(); } } Here are the results of the times taken in processing the findAll() 4 times consequtively without adding any more records. There are only 4 records in the system and you can see the time taken is 10.7 sec, 25.7 sec, 41.9 sec, and 58.5 sec. Each request takes a lifetime of its own to complete. * *Time Taken = 10768 *Time Taken = 25785 *Time Taken = 41921 *Time Taken = 58530 Given below is the configuration of my system - Intel Core i3 2330M @2.2 GHz - 2 GB RAM - 64 bit Windows 7 - MongoDB version locally installed on my system : 3.2 - At the time of executing this query CPU utilization 50% and memory 80% Ideally this operation must happen in less than half a second or at max a second. Any kind of help would be great.
{ "language": "en", "url": "https://stackoverflow.com/questions/37642572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get data from website's dd tag via VBA I am trying to get data from a website, but I cannot get this part of my VBA code to work. I have tried to look here, e.g. Excel VBA to find dd & dt tag but I could not find the answer. This is the HTML code I am trying to get data from: <div @*id="show7" class="collapse visible" *@> <h3 class="rapport__h3">Folkbokföring</h3> <dl class="rapport__list m-b-25"> <dt>Gatuadress</dt> <dd/> <dt>Postnummer</dt> <dd/> <dt>Postort</dt> <dd/> <dt>Kommun</dt> <dd> </dd> <dt>Län</dt> <dd>&#xD6;rebro (18)</dd> </dl> <h3 class="rapport__h3">Särskild adress</h3> <dl class="rapport__list m-b-25"> <dt>Gatuadress</dt> <dd class="UpplysningTableSecondTd">Poste Restante</dd> <dt>Postadress</dt> <dd class="UpplysningTableSecondTd">701 00 &#xD6;rebro</dd> </dl> I am trying to retrieve the class="UpplysningTableSecondTd" data. Neither of the below is working, and I have tried different things. Set All_dd = oHDoc.getElementsByClassName("rapport__list m-b-25").getElementsByClassName("UpplysningTableSecondTd")(0).innerText Set All_dd = oHDoc.getElementsById("show7").getElementsByTag("UpplysningTableSecondTd") Thanks. A: I managed to solve it. Debug.Print oHDoc.getElementsByClassName("UpplysningTableSecondTd").Item(0).innerText Debug.Print oHDoc.getElementsByClassName("UpplysningTableSecondTd").Item(1).innerText
{ "language": "en", "url": "https://stackoverflow.com/questions/56579667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: XSSFCell Style seems to be slow I'm currently using apache POI to automatically tranfers data from xls file to xlsm file after some process. I have strong executing time constraint and the setters on XSSFCellStyle is very time consuming. In fact i have files with thousands of cell to transfert and method on boder (SetBorder & SetBorder color) take 3 ms to 5 ms to execution each on 1 cell. In my context 1300 thousands it takes 30 sec to execute. In a graph on JProfiler, we can see the most time spend on these methods is in state "waiting". Is it normal for you or not ? Thanks a lot!! A: in for example org.apache.poi.xssf.model.StylesTable.putStyle( XSSFCellStyle ) they try to find the xfs twice. It uses an ArrayList. The more cells, the slower this operation is. If you can, try to avoid a lot of dates.
{ "language": "en", "url": "https://stackoverflow.com/questions/21940768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Iterating through my fonts list to display them more efficiently Answer located here: Setting multiple different Typefaces to the TextViews in a ListView I have 20 fonts in a list that changes a TextView based on the user's selection. I want to keep adding more custom fonts, but it's getting very tedious doing this manually for each addition. In the following use case, the user presses a button that opens a menu (not shown). I want to display these buttons in their respective fonts, by setting a typeface to each TextView in the menu: Typeface Aclonica = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Aclonica.ttf"); TextView fontMenuAclonica = (TextView) this.view.findViewById(R.id.fontMenuAclonica); fontMenuAclonica.setTypeface(Aclonica); Typeface Arimo = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Arimo-Regular.ttf"); TextView fontMenuArimo = (TextView) this.view.findViewById(R.id.fontMenuArminoRegular); fontMenuArimo.setTypeface(Arimo); Is there a more efficient way to do this than by repeating this code over and over again? Can't I just have one base implementation of the code and list of values for the Typeface name, TextView name, and font name? Typeface typefaceName = Typeface.createFromAsset(getActivity().getAssets(), "fonts/font.ttf"); TextView textViewName = (TextView) this.view.findViewById(R.id.resourceId); textViewName.setTypeface(typefaceName); Update: I suppose it's more efficient to set up a ListView: ListView fontsListView = (ListView) this.view.findViewById(R.id.MenuLayout); penis String[] fonts = new String[]{ "Aclonica", "Amino-Regular" }; ArrayList<String> planetList = new ArrayList<String>(); planetList.addAll(Arrays.<String>asList(Arrays.toString(fonts))); for( int i = 0; i <= fonts.length - 1; i++) { planetList[i].setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/" + fonts[i] + ".ttf")); } Here is the XML: <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:textColor="#ffffff" android:id="@+id/rowTextView" android:textSize="20sp" android:gravity="center_horizontal" android:padding="10dp" android:typeface="sans" android:fontFamily="sans-serif-light" /> How do I iterate through the TextViews that are created so that I can programmatically set their Typefaces?
{ "language": "en", "url": "https://stackoverflow.com/questions/34347631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to compute a least common ancestor algorithm's time complexity? I came into an article which talking about the LCA algorithms, the code is simple http://leetcode.com/2011/07/lowest-common-ancestor-of-a-binary-tree-part-i.html // Return #nodes that matches P or Q in the subtree. int countMatchesPQ(Node *root, Node *p, Node *q) { if (!root) return 0; int matches = countMatchesPQ(root->left, p, q) + countMatchesPQ(root->right, p, q); if (root == p || root == q) return 1 + matches; else return matches; } Node *LCA(Node *root, Node *p, Node *q) { if (!root || !p || !q) return NULL; if (root == p || root == q) return root; int totalMatches = countMatchesPQ(root->left, p, q); if (totalMatches == 1) return root; else if (totalMatches == 2) return LCA(root->left, p, q); else /* totalMatches == 0 */ return LCA(root->right, p, q); } but I was wondering how compute the time complexity of the algorithm,can anyone help me? A: The complexity of LCA is O(h) where h is the height of the tree. The upper bound of the tree height is O(n), where n denotes the number of vertices/nodes in the tree. If your tree is balanced, (see AVL, red black tree) the height is order of log(n), consequently the total complexity of the algorithm is O(log(n)). A: The worst case for this algorithm would be if the nodes are sibling leave nodes. Node *LCA(Node *root, Node *p, Node *q) { for root call countMatchesPQ; for(root->left_or_right_child) call countMatchesPQ; /* Recursive call */ for(root->left_or_right_child->left_or_right_child) call countMatchesPQ; ... for(parent of leave nodes of p and q) call countMatchesPQ; } countMatchesPQ is called for height of tree times - 1. Lets call height of tree as h. Now check the complexity of helper function int countMatchesPQ(Node *root, Node *p, Node *q) { Search p and q in left sub tree recursively Search p and q in right sub tree recursively } So this is an extensive search and the final complexity is N where N is the number of nodes in the tree. Adding both observations, total complexity of the algorithm is O(h * N) If tree is balanced, h = log N (RB tree, treap etc) If tree is unbalanced, in worse case h may be up to N So complexity in terms of N can be given as For balanced binary tree: O(N logN) To be more precise, it is actual h(N + N/2 + N/4...) for balanced tree and hence should come 2hN For unbalanced binary tree: O(N2) To be more precise, it is actual h(N + N-1 + N-2...) for balanced tree and hence should come h x N x (N+1) / 2 So the worse case complexity is N2 Your algorithm doesn't use any memory. By using some memory to save path, you can improve your algorithm drastically.
{ "language": "en", "url": "https://stackoverflow.com/questions/24097107", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to show only color coding in the legend of my plotly scatterplot in python I'm plotting some PCAs with plotly.express scatterplot function, and coding the samples by region (color) and breed (symbol). When I plot it, the legend show me all 67 different breeds in their combinations of symbols and colors. Is there a way to show only the color categories instead? My data looks like this: PC1 PC2 PC3 Breed Region Sample1 value value value breed1 Region1 Sample2 value value value breed2 Region1 Sample3 value value value breed3 Region2 Sample4 value value value breed1 Region1 Right now my code is just the basic command: fig=px.scatter(pca, x="PC2",y="PC1", color="Region", symbol="Breed", labels={ "PC2":"PC2-{}%".format(eigen[1]), "PC1":"PC1-{}%".format(eigen[0]) }) fig.layout.update(showlegend=True) fig['layout']['height'] = 800 fig['layout']['width'] = 800 fig.show() Any ideas? A: You can add these lines: region_lst = [] for trace in fig["data"]: trace["name"] = trace["name"].split(",")[0] if trace["name"] not in region_lst and trace["marker"]['symbol'] == 'circle': trace["showlegend"] = True region_lst.append(trace["name"]) else: trace["showlegend"] = False fig.update_layout(legend_title = "region") fig.show() Before adding the lines of code: After adding the code: I used this dataframe: import plotly.express as px df = px.data.medals_long() fig = px.scatter(df, y="nation", x="count", color="medal", symbol="count") A: * *specifying color and symbol results in legend being combination of values in respective columns *to have legend only be values in one column, change to use just color *to represent second column as symbols, change each trace to use a list of symbols *have synthesized data based on your description full code import pandas as pd import numpy as np import plotly.express as px from plotly.validators.scatter.marker import SymbolValidator eigen = [0.5, 0.7] # simulate data n = 1000 pca = pd.DataFrame( { **{f"PC{c}": np.random.uniform(1, 5, n) for c in range(1, 4, 1)}, **{ "Breed": np.random.choice([f"breed{x}" for x in range(67)], n), "Region": np.random.choice([f"Region{x}" for x in range(10)], n), }, } ) # just color by Region fig = px.scatter( pca, x="PC2", y="PC1", color="Region", labels={"PC2": "PC2-{}%".format(eigen[1]), "PC1": "PC1-{}%".format(eigen[0])}, ) # build dict that maps as Breed to a symbol symbol_map = { t: s for t, s in zip(np.sort(pca["Breed"].unique()), SymbolValidator().values[2::3]) } # for each trace update marker symbol to list of symbols that correspond to Breed for t, s in zip( fig.data, pca.groupby("Region")["Breed"].agg(lambda x: [symbol_map[v] for v in x]) ): t.update(marker_symbol=s) fig
{ "language": "en", "url": "https://stackoverflow.com/questions/71615678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: React state not being updated in Jest while working in the application When I click the button it increments the value by the amount written in the input, it works when I do that in the app but when I try to use Jest and first fireEvent.change() the value of an input to 10 and then fireEvent.click() on the button it doesnt increment it and the value stays at 0. Here is the error that Im getting: expect(received).toBe(expected) // Object.is equality Expected: 10 Received: 0 33 | fireEvent.click(btnPlus); 34 | > 35 | expect(parseInt(val.textContent)).toBe(10); | ^ 36 | }); 37 | }); 38 | Here is the test file: import React from 'react'; import Counter from './Counter'; import { render, fireEvent } from '@testing-library/react'; describe('Counter works', () => { let comp; let inp; let btnPlus; let val; beforeAll(() => { comp = render(<Counter />); inp = comp.getByTestId('inp'); btnPlus = comp.getByTestId('btn-+'); val = comp.getByTestId('counter-value'); }); it('Counter exists', () => { expect(comp).toBeTruthy(); }); it('Input works', () => { expect(inp.value).toBe(''); fireEvent.change(inp, { target: { value: 10, }, }); expect(parseInt(inp.value)).toBe(10); fireEvent.click(btnPlus); expect(parseInt(val.textContent)).toBe(10); }); }); The general Counter file: const Counter = () => { const [state, setState] = useState({ count: 0, inpText: '', }); const setNum = (num) => { setState((prev) => { return { ...prev, count: prev.count + num, }; }); }; const setInp = (e) => { setState((prev) => { return { ...prev, inpText: e?.target.value, }; }); }; return ( <> <h1 data-testid='counter-value' style={{ color: 'white', position: 'absolute', top: '45%', left: '50%', transform: 'translate(-50%,-60%)', }}> {state.count} </h1> <div id='flex'> <Button setNum={setNum} plus='+' num={parseInt(state.inpText)} /> <input data-testid='inp' value={state.inpText} onChange={setInp} /> <Button setNum={setNum} plus='-' num={-parseInt(state.inpText)} /> </div> </> ); }; And the Button: const Button = (props) => { return ( <button data-testid={`btn-${props.plus}`} onClick={() => { props.setNum(props.num); }}> {props.plus} </button> ); }; A: I would suggest avoiding initial component setup in beforeAll/beforeEach functions. Each test case should run in isolation and not be affected by operations executed in other tests. Instead, create a helper function with that logic and call it on every test. import React from 'react'; import Counter from './Counter'; import { render, fireEvent } from '@testing-library/react'; describe('Counter works', () => { let comp; let inp; let btnPlus; let val; const renderComponent = () => { comp = render(<Counter />); inp = comp.getByTestId('inp'); btnPlus = comp.getByTestId('btn-+'); val = comp.getByTestId('counter-value'); } it('Counter exists', () => { renderComponent(); expect(comp).toBeTruthy(); }); it('Input works', () => { renderComponent(); expect(inp.value).toBe(''); fireEvent.change(inp, { target: { value: 10 } }); expect(inp.value).toBe('10'); fireEvent.click(btnPlus); expect(val.textContent).toBe('10'); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/67211422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How is the btmgmt command used to set PHY? When I run the command: btmgmt phy LE2MTX LE2MRX It returns: Could not set PHY Configuration with status 0x0d (Invalid Parameters) btmon shows: @ MGMT Open: btmgmt @ MGMT Command: Set PHY Configuration (0x0045) plen 4 Selected PHYs: 0x1800 LE 2M TX LE 2M RX @ MGMT Event: Command Status (0x0002) plen 3 Set PHY Configuration (0x0045) Status: Invalid Parameters (0x0d) @ MGMT Close: btmgmt I'm very unfamiliar with btmgmt, how do I specify that I want LE 2M PHY whenever possible? If I run: btmgmt phy I get the available PHYs which incudes the LE2MTX and LE2MRX (which I am after). Supported phys: BR1M1SLOT BR1M3SLOT BR1M5SLOT EDR2M1SLOT EDR2M3SLOT EDR2M5SLOT EDR3M1SLOT EDR3M3SLOT EDR3M5SLOT LE1MTX LE1MRX LE2MTX LE2MRX Configurable phys: BR1M3SLOT BR1M5SLOT EDR2M1SLOT EDR2M3SLOT EDR2M5SLOT EDR3M1SLOT EDR3M3SLOT EDR3M5SLOT LE2MTX LE2MRX Selected phys: BR1M1SLOT BR1M3SLOT BR1M5SLOT EDR2M1SLOT EDR2M3SLOT EDR2M5SLOT EDR3M1SLOT EDR3M3SLOT EDR3M5SLOT LE2MTX LE2MRX These can also be seen in btmon: Get PHY Configuration (0x0044) plen 12 Status: Success (0x00) Supported PHYs: 0x1fff BR 1M 1SLOT BR 1M 3SLOT BR 1M 5SLOT EDR 2M 1SLOT EDR 2M 3SLOT EDR 2M 5SLOT EDR 3M 1SLOT EDR 3M 3SLOT EDR 3M 5SLOT LE 1M TX LE 1M RX LE 2M TX LE 2M RX Configurable PHYs: 0x19fe BR 1M 3SLOT BR 1M 5SLOT EDR 2M 1SLOT EDR 2M 3SLOT EDR 2M 5SLOT EDR 3M 1SLOT EDR 3M 3SLOT EDR 3M 5SLOT LE 2M TX LE 2M RX Selected PHYs: 0x19ff BR 1M 1SLOT BR 1M 3SLOT BR 1M 5SLOT EDR 2M 1SLOT EDR 2M 3SLOT EDR 2M 5SLOT EDR 3M 1SLOT EDR 3M 3SLOT EDR 3M 5SLOT LE 2M TX LE 2M RX
{ "language": "en", "url": "https://stackoverflow.com/questions/74279636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: find nth fibonacci number where n can vary till 10^9 // i was trying to find (n^n)%1000000007 where n is the nth fibonacci term of the series. example : n=3 ans 4 (2^2) public class Sol_Big { public static void main(String args[]) { int n =10000000; BigInteger a = BigInteger.ZERO; BigInteger b = BigInteger.ONE; BigInteger c = BigInteger.valueOf(1); BigInteger MOD = BigInteger.valueOf(1000000007); for (int j=2 ; j<=n ; j++) { c = a.add(b); c=c.mod( MOD); a = b.mod(MOD); b = c.mod(MOD); } System.out.println(c); BigInteger result = BigInteger.valueOf(1); result = c.modPow(c, MOD); int intval = result.intValue(); System.out.println( intval); } } // my code is working for 10^7 input but for 10^8 and onward it is exceeding time limit.... A: The trick is to notice that you can calculate the Fibonacci numbers using matrix multiplication: | 0 1 | | a | | b | | 1 1 | * | b | = | a + b | With this knowledge, we can calulate the n-th Fibonacci number: | 0 1 |^n | 0 | | 1 1 | * | 1 | Because matrix multiplication is associative, we can efficiently calculate m^n. * *If n is even, m^n = m^(n/2) * m^(n/2) *If n is odd, m^n = m^((n-1)/2)) * m^((n-1)/2)) * m Note that we need the same thing twice, but we only have to compute it once. This makes it possible to calculate the n-th Fibonacci number in O(log n). I leave it to you to write the code.
{ "language": "en", "url": "https://stackoverflow.com/questions/58053151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring XD stream status failed After creating stream in Spring XD using the below command *stream create foo --definition "jdbc --fixedDelay=1 --split=1 --url=jdbc:mysql://localhost:3306/test --query='select * from test_tutorials_tbl'|log" --deploy* we have got the status as 'Created and deployed new stream 'foo'. But when I checked with the stream list command, the status seems to be failed and no data. This is not with the case with MySql database alone but with a command like 'stream create --name stocks --definition "http --port=9090 | gemfire-json-server --regionName=Customers --keyExpression=payload.getField('lastname')" --deploy' is too failing. Could any one please help us as this work is very much critical. A: I have a solution for the question that i have posted. Try starting the Spring XD single node too. Then you won't face any stream creation failure. Status will be in deployed (when we try create stream to fetch mysql data for example). But stream creation will be in failed, if we are pointing to gemfire. I am looking into it.
{ "language": "en", "url": "https://stackoverflow.com/questions/37435518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why don't Spring actuator requests display in log? I have 6 Springboot apps. Each one is slightly different from another. All of them include Actuator (so I can hit /health, /env, etc). The problem is that in 3 of the apps I can see in the logs where the request was processed for each endpoint (see example below). In the other 3 apps I do not get this log info. I have tried to copy some config code and dependencies from one app to the other but have not figured out what is different or how to change the logging configuration. Has anyone discovered how to solve this problem? 2016-12-15 20:02:04.962 DEBUG 1 --- [nio-8080-exec-9] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/health]
{ "language": "en", "url": "https://stackoverflow.com/questions/41172465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Connections, edges, node: how to use a subtype of a node I'm following the Connection, Edges, Node, concept of relay in Apollo. I use a Node { id: ID! } interface. I have a collection of entities that are all kind of 'groups', with small differences. I would like to model these as a single Connection, but not really sure how to do that: # simplified for example interface Group { id: ID! type: String! } type WallGroup implements Node & Group { id: ID! type: String! } type Event implements Node & Group { id: ID! type: String! dteStart: DateTime! dteEnd: DateTime! } type GroupEdge implements Edge { cursor: String! node: Group! } type GroupConnection implements Connection { edges: [GroupEdge!]! pageInfo: PageInfo! totalCount: Int! } This will generate an error because GroupEdge expects node to a Node. It is, but the Group interface is not and it therefore fails. Another thing I tried was union AllGroup = WallGroup | Event type GroupEdge implements Edge { cursor: String! node: AllGroup! } But this leads to the same issue. Apparently, the union loses notion of the Node interface implemented on WallGroup and Event. Any ideas on hwo to model this or should I just duplicate everything? A: The Relay specification only requires that your schema include a Node interface -- when creating a Relay-compliant, normally you don't create interfaces for Connection and Edge. The reason Relay requires a Node interface is to allow us to query for any Node by id. However, typically there's no need for a field that returns one of many edges or one of many connections. Therefore, typically there's no need to need to make an interface for edges or connections. This is what you would normally do: interface Node { id: ID! } interface Group { id: ID! type: String! } type GroupA implements Node & Group { id: ID! type: String! # other fields } type GroupA implements Node & Group { id: ID! type: String! # other fields } type GroupEdge { cursor: String! node: Group! } type GroupConnection { edges: [GroupEdge!]! pageInfo: PageInfo! totalCount: Int! } According to the spec, "the [implementing] object type must include a field of the same name for every field defined in an interface." So, if an interface specifies that a field is of the type Foo, an implementing type cannot have the field be of type FooBar even if Foo is an interface and FooBar implements it. Unfortunately, that means it's not really possible to use interfaces like you're trying to do. If you would like to utilize interfaces to provide a safety-net of sorts and ensure that the implementing types are consistent, you can do something like this: interface Connection { pageInfo: PageInfo! # don't specify edges } interface Edge { cursor: String! # don't specify node } This way you can ensure that fields like pageInfo or cursor are present in the implementing types, have the correct type and are non-null. But this kind of schema-level validation is really the only benefit you get out adding and implementing these two interfaces.
{ "language": "en", "url": "https://stackoverflow.com/questions/55030554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Executing server side code (node.js) on click of a button from within an HTML page generated through Jade I am trying to develop a web application and I am stuck at a point where I need some server side code to be executed on click of a button (through the onClick event handler and not the Submit button. I learnt how to route traffic that way through a form action). I am using Node.js, Express and Jade. Can someone please help me. Here is my current code snapshot I have made the following changes with respect to app.js to route the on-click traffic to this node.js function app.post('/overview/delete-uni', uniappController.deleteUniversity); Within the appropriate controller file I have added the deletion code exports.deleteUniversity = function(req, res) { // Code logic // More code logic res.render('uniapp/university', { title: 'University' }); }; My Jade Template looks like this. Here when I click the Update button I need the deleteUniversity code to be executed extends ../layout block content .mdl-layout.mdl-js-layout.mdl-color--grey-100 main.mdl-layout__content .mdl-grid #user for application in user.applications form.form-card.form-horizontal(action='/overview/update-uni', method='POST') input(type='hidden', name='_csrf', value=_csrf) .mdl-card.mdl-shadow--2dp .mdl-card__supporting-text textarea#sample5.mdl-textfield__input(type='text', rows='1', name='universityName', readonly) if application.university.name | #{application.university.name} .mdl-textfield.mdl-js-textfield.mdl-textfield--floating-label textarea#sample5.mdl-textfield__input(type='text', rows='1', name='universityDescription') if application.university.description | #{application.university.description} label.mdl-textfield__label(for='sample5') Description of university... .mdl-card__actions.mdl-card--border button.mdl-button.mdl-button--colored.mdl-js-button.mdl-js-ripple-effect(type='submit') | Update .mdl-card__menu button.mdl-button.mdl-button--icon.mdl-js-button.mdl-js-ripple-effect i.material-icons delete P.S : I am a complete noob w.r.t Jade and hence please forgive me if this is something trivial. A: Create a javascript file deleteUni.js (or whatever you want to call it) and add this to your template script(src="/Scripts/deleteUni.js") //content of name.js $(function(){ var isButtonDisabled = false; $('#buttonId').click(function($event){ //this part handles multiple button clicks by the user, trust me on this one, it's really important to have it if (isButtonDisabled){ return $event.preventDefault(); } isButtonDisabled = true; var formData = $('#formId').serialize(); //serialize form to a variable $.post( "/overview/delete-uni",formData) .success(function(response){ //handle response }) .fail(function(error){ //handle error }) .always(function(){ //always execute . . . isButtonDisabled = false; }); return $event.preventDefault(); }) });
{ "language": "en", "url": "https://stackoverflow.com/questions/33985552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can dynamic import of @mdi/js icon work with tree-shaking in a vue template? I have the following component to dynamically import an icon from mdi/js. The only problem with this is that it doesn't do tree-shaking. Does anyone know how to make tree-shaking work with this kind of setup? I can use this anywhere like <Icon name='mdiMagnify'> Icon.vue <template> <v-icon v-bind="$attrs">{{ icon }}</v-icon> </template> <script> export default { name: 'Icon', props: { name: { required: true, type: String, }, }, data: () => ({ icon: null, }), async created() { const { [this.name]: icon } = await import('@mdi/js') this.icon = icon }, } </script> The reason behind this is, I won't be needing to import each and every icon that i need in all my components and passing it to a data variable to be able to be utilized in vue template. A: if you're using nuxt.js (which I suppose you do since you have the tag on your question), it's pretty easy, just add the following in your nuxt.config.js: vuetify: { defaultAssets: false, treeShake: true, icons: { iconfont: 'mdiSvg', // --> this should be enough // sideNote: you can also define custom values and have access to them // from your app and get rid of the imports in each component values: { plus: mdiPlus, // you have access to this like $vuetify.icons.values.plus from your component } } } for the values to work you just have to import the appropriate icon in the nuxt.config.js like: import { mdiPlus } from '@mdi/js' or if you don't like the custom values you can import the needed icons for each component in the component itself and use them there like: import { mdiPlus } from 'mdi/js' ... data() { return { plusIcon: mdiPlus } } A: What I ended up doing currently is to have all the svg in @mdi/svg package and use that as an img src. That way, I won't have to deal with dynamically importing it from @mdi/js and hoping for a treeshake.
{ "language": "en", "url": "https://stackoverflow.com/questions/68785341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I configure my Route config to get a URL Pattern like localhost/Product (Controller)/List (Action)/Category (Id)? As the title says all about what I want but to be kind of specific I would like to have a URL pattern like localhost/Product/List/Category/Page but I couldn't succeed finding a solution for it. I am sure it's belong to routing and as it is difficult topic in MVC I would need your help to find a solution for it. My route config is: public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute(null, "", new { controller = "Home", action = "Shop", }); routes.MapRoute(null, "", new { controller = "Product", action = "list", category = (string)null, page = 1 } ); routes.MapRoute(null, "Page{page}", new { controller = "Product", action = "List", category = (string)null, subcategory = (string)null }, new { page = @"\d+" } ); routes.MapRoute(null, "{category}", new { controller = "Product", action = "List", page = 1 } ); routes.MapRoute(null, "{category}/Page{page}", new { controller = "Product", action = "List" }, new { page = @"\d+" } ); routes.MapRoute(null, "{controller}/{action}"); } } My Controller product is: public class ProductController : Controller { EFDbContext db = new EFDbContext(); private IProductsRepository repository; public int PageSize = 4; public ProductController (IProductsRepository productrepository) { this.repository = productrepository; } public ViewResult List(string category, int page = 1) { ProductsListViewModel model = new ProductsListViewModel() { Products = repository.Products .Where(p => category == null || p.ProductCategory == category || p.MenSubCategory == category) .OrderBy(p => p.ProductID) .Skip((page - 1) * PageSize) .Take(PageSize), PagingInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = PageSize, TotalItems = category == null ? repository.Products.Count():repository.Products.Where(e => e.ProductCategory == category).Count() }, CurrentCategory = category }; return View(model); } public PartialViewResult Menu(string subcategory = null ) { ViewBag.SelectedCategory = subcategory; IEnumerable<string> categories = repository.MenSubCategories .Select(x => x.MenSubCategory) .Distinct() .OrderBy(x => x); return PartialView(categories); } } I hope I get answer for this as far as I really tried but couldn't find how to do it. A: With attribute routing, you just need to decorate your action method with your specific route pattern. public class ProductController : Controller { EFDbContext db = new EFDbContext(); private IProductsRepository repository; public int PageSize = 4; public ProductController (IProductsRepository productrepository) { this.repository = productrepository; } [Route("Product/list/{category}/{page}")] public ViewResult List(string category, int page = 1) { // to do : Return something } } The above route definition will send the request like yourSite/Product/list/phones and yourSite/Product/list/phones/1 to the List action method and the url segments for category and page will be mapped to the method parameters. To enable attribute routing, you need to call the method MapMvcAttributeRoutes method inside the RegisterRoutes method. public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapMvcAttributeRoutes(); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); A: To generate an URL like you want: localhost/Product/List/Cars you can create a custom route like this: routes.MapRoute( name: "ProductList", url: "Product/List/{category}", defaults: new { controller = "Product", action = "List" } ); Remember that custom routes have to come before the most general route (the one that comes with the default template). Regarding your page parameter, if you are comfortable with this URL: localhost:3288/Product/List/teste?page=10 the above already work. But if you want this: localhost:3288/Product/List/teste/10 10 meaning the page number, then the simplest solution would be create two different routes: routes.MapRoute( name: "ProductList", url: "Product/List/{category}", defaults: new { controller = "Product", action = "List" } ); routes.MapRoute( name: "ProductListPage", url: "Product/List/{category}/{page}", defaults: new { controller = "Product", action = "List" , page = UrlParameter.Optional} ); Another cleaner way, is to create a custom route constraint for your optional parameter. This question has a lot of answers to that: ASP.NET MVC: Route with optional parameter, but if supplied, must match \d+
{ "language": "en", "url": "https://stackoverflow.com/questions/35116865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }