text
stringlengths
15
59.8k
meta
dict
Q: Pushing the content without it changing width when opening sidebar I have a sidebar which I open on smaller screens, When opening the sidebar, I want the content on its right to be pushed, but when I do that in the current code, the width of the div where the content is changes, making what's inside of it resize based on its width. Because it is responsive. I have several divs within it. This is the code in JSFiddle MyCode Here I've only put text as content, so you can see how the text also behaves when I close the sidebar. How do I make it so that the page-wrapper content to push be pushed left and right, but without it changing width ? My HTML Code : <div id="wrapper"> <div class="overlay"></div> <!-- Sidebar --> <nav class="navbar navbar-fixed-top set-height-nav flex-colum" id="sidebar-wrapper" role="navigation"> asdasdadas </nav> <!-- /#sidebar-wrapper --> <!-- Page Content --> <div id="page-content-wrapper"> <button type="button" class="hamburger is-closed" data-toggle="offcanvas"> <span class="hamb-top"></span> <span class="hamb-middle"></span> <span class="hamb-bottom"></span> </button> <div class="container-fluid"> <h3> Lorem ipsum dolor sit amet, quo ex graeco option, elit malis eam et. Probo solet lucilius ea pri. Civibus electram referrentur pri no, sea in brute adipisci eleifend. His at gubergren conclusionemque. </h3> </div> </div> <!-- /#page-content-wrapper --> My css : body { position: relative; overflow-x: hidden; } *-------------------------------*/ #wrapper { padding-left: 0; -webkit-transition: all 0.5s ease; -moz-transition: all 0.5s ease; -o-transition: all 0.5s ease; transition: all 0.5s ease; } #wrapper.toggled { padding-left: 220px; overflow: hidden; /* width:100%; */ width: 100%; /* position: absolute; */ } #sidebar-wrapper { z-index: 2000; left: 220px; width: 0; height: 100%; margin-left: -220px; overflow-y: auto; overflow-x: hidden; background: black; -webkit-transition: all 0.5s ease; -moz-transition: all 0.5s ease; -o-transition: all 0.5s ease; transition: all 0.5s ease; bottom: 0; padding: 0; display:block; } #wrapper a.nav-link.active { color: #1C2058; font-weight: bold; } #sidebar-wrapper::-webkit-scrollbar { display: none; } #wrapper.toggled #sidebar-wrapper { width: 220px; } #page-content-wrapper { width: 100%; padding-top: 25px; } #wrapper.toggled #page-content-wrapper { position:absolute; margin-right: -220px; } /* Custom Css on Sidebar */ ul.full-width-navigation { width: 220px; } .side .active { position: relative; } nav.set-top-zindex { background: #fff; min-height: 50px; /* display: none; */ } .overlay { position: fixed; display: none; width: 100%; height: 100%; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(250, 250, 250, .8); z-index: 1; } /*sidebar */ @media screen and (min-width: 576px) { #wrapper #sidebar-wrapper { width: 220px; } #wrapper.toggled #page-content-wrapper { padding-left: 0; } #wrapper #page-content-wrapper { padding-left: 220px; } button.hamburger.is-closed { display: none; } #sidebar-wrapper { z-index: 1; } } @media screen and (max-width: 576px) { #wrapper.toggled .overlay { height: 100%; width: 100%; position: fixed; background-color: rgba(0, 0, 0, .8); margin-top: 69px; z-index: 1500; display: block; } } Any help is appreciated ! Thanks! Edit : Current Fiddle When opening sidebar- it pushes the content for 220px. When pressing close on the sidebar, you can see how the letters within the content shuffle, and that happens because by padding padding, the width of the page-wrapper-content get smaller, and the content inside of it changes because it is responsive.. What I need is : Press sidebar - content seems to be pushed to the right for 220px. Close sidebar - content transition back to its initial state with left:0 as the sidebar closes. Need to transition back and forth between push and pull. A: I have created this simple example on CodePen which you may use to help solve your question and learn. In the demo, click the 'menu' button to toggle the sidebar. The method I think you need to use is to position your main content area 'absolutely', and 'left' by the width of your sidebar when it is expanded I demo this in my demo by toggling a CSS class containing these properties on the main content area. This allows your responsive grid cells to remain the same width whilst the menu is open. I find it easier to see examples on CodePen but I have also embedded my example here: $("button").on("click", function() { $(".sidebar").toggleClass('is-active'); }) body { margin: 0; overflow-x: hidden; } .sidebar { display: none; width: 220px; height: calc(100vh - 28px); background: #eee; border-right: #ccc; padding: 14px; position: relative; left: -220px; } .sidebar.is-active { display: block; left: 0; transition: all 2000ms ease; } .sidebar.is-active~.main-content { width: 100vw; height: calc(100vh - 28px); position: absolute; left: calc(220px + 28px); } .main-content { width: 100%; padding: 14px; } .row { display: flex; flex-wrap: no-wrap; flex-direction: row; justify-content: space; } .row .cell { width: 100%; background: #eee; padding: 14px; } .row .cell:nth-of-type(2) { border-right: 1px solid lightgray; border-left: 1px solid lightgray; } nav a { display: block; padding: 14px; } .menu-btn { position: absolute; right: 0; z-index: 9999; } .wrapper { width: 100%; height: 100vh; display: flex; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button type="button" class="menu-btn">Menu</button> <div class="wrapper"> <div class="sidebar"> <nav> <a href="#">Link #1</a> <a href="#">Link #2</a> <a href="#">Link #3</a> <a href="#">Link #4</a> </nav> </div> <div class="main-content"> <div class="row"> <h1>Main content</h1> </div> <div class="row"> <div class="cell"> Cell #1 </div> <div class="cell"> Cell #2 </div> <div class="cell"> Cell #3 </div> </div> </div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/47476061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Writing output to a single csv file in python I am new to programming. May requirement will be simple for core developer. I have 5 .log file which are log file of database. here I want to read these all files, check the error and success message in these files and write the error and success message to single csv file along with name of the file which I read. import glob file_list = glob.glob('C:\\Users\\Rahul\\AppData\\Roaming\\JetBrains\\PyCharmCE2021.3\\*.log') file_out = open('error.csv', "a") #creating a csv file for file in file_list: file_in = open(file, "r").readlines() count = 0 for line in file_in: # Loop every line if 'ERROR' in line: # Search for ERROR in line count += 1 file_out.write(str(count) +"error.csv"+ "," + line + "\n") #writing csv file elif 'SUCCESS' in line: # Search for SUCCESS in line print(line) # Print line file_out.close() I want output of file something like below to be written into single CSV file Filename:test.log Error: Compilation error Filename:test2.log Success: It is successful Any help or suggestions ? A: Here's a suggestion. There's a neat module in the standard library called fileinput that allows you to easily read several files in a row and also gives you access to the filenames, line numbers, etc. Try something like the following and see if it fits your needs: import glob import fileinput file_list = glob.glob(...) with fileinput.input(file_list) as fin,\ open("error.csv", "a") as fout: out = "Filename: {}, Line: {}, {}: {}\n" write = False for line in fin: line = line.rstrip() line_folded = line.casefold() if "error" in line_folded: write, var = True, "Error" elif "success" in line_folded: write, var = True, "Success" if write: fout.write(out.format(fin.filename(), fin.filelineno(), var, line)) write = False It's a bit unclear why you want to write a CSV-file: Your output doesn't look like it's in a csv-format?
{ "language": "en", "url": "https://stackoverflow.com/questions/71815189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: java cloneing error I have a method that tries to clone an instance of a class (B) i have writen.This method is being called in class A so this method is not in the same class as the class i'm trying to clone (B). The class i'm trying to clone impliments colneable. when i try to compile my code i get an error message that reads "clone() has protected access in Java.lang.Object. Why might this be happing? A: That may be happening because you are trying to call the clone() method outside its allowed access. For you to be able to call it, the class that is calling it should extend directly from Object, or belong to the Same Package, or be Object. More information here http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html A: If you want some code inside class A to clone an instance of class B, then either place A and B in the same package, or broaden the access to B.clone() by making it public (rather than leaving it protected-scope.) Furthermore, I would refer you to the book Effective Java by Josh Bloch. I found a PDF of Chapter three here A: You can only access protected members of a type in a different package if the compile-time type of the expression you're referencing it through is either your own class or a subclass. Check this link.
{ "language": "en", "url": "https://stackoverflow.com/questions/5944607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: kill -s SIGINT ps SHELL I am using this command kill -s SIGINT ps on the command line and it works (the process is eliminated), but when I use that command on a SHELL script it doesn´t work and it shows this error message kill: SIGNIT: invalid signal specification. How can I solve this. Thanks A: Error messages exist to give developers, and also users, a clue when something goes wrong. I suspect that you're mistyping SIGINT as SIGNIT. The error message you're getting is consistent with a typo in your statement. I feel like this shows poor research effort because if you had read the error message before asking help, you would have figured it out. A: I would like to answer this because I solved the similar problem recently. When you call kill -s SIGINT, you may use sh to run the script. Unfortunately, sh which is different from bash(linux shell kill signal SIGKILL && KILL) will run in compatibility mode and not recognize SIGINT. The best solution is to use /bin/bash explicitly. By the way, #!/bin/bash doesn't work when you sh the script, either. Hope it helps. A: It's possible that the shell executing the script is using a built-in "kill" command while your command-line shell is using an external binary, or vice-versa. Use /bin/kill explicitly and see if that helps be more consistent. kill -SIGINT is, I believe, the more common way of doing this (instead of "-s SIGINT"). Also, kill normally takes a process-id and not a process-name. Built-in vs external "kill" commands may also support (or not support) this differently.
{ "language": "en", "url": "https://stackoverflow.com/questions/12826991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Option Data from google finance in Json format not parse-able in Groovy I am trying to parse Option data from google finance using JsonSlurper in Groovy. I get an error and looking at the data, it seems it is not proper Json format. (It is missing quotes around values). Is this normal. Do I have to massage this data before JsonSlurper will parse it. I can see the data after puts would be in proper format. Here is the url that I get the data from : This is the error that I get in groovy: Encountered exception : Lexing failed on line: 1, column: 2, while reading 'e', no possible valid JSON value or punctuation could be recognized. - This is the the data that is returned from the url: {expiry:{y:2013,m:5,d:31},expirations:[{y:2013,m:5,d:31},{y:2013,m:6,d:7},{y:2013,m:6,d:14},{y:2013,m:6,d:22},{y:2013,m:6,d:28},{y:2013,m:7,d:20},{y:2013,m:8,d:17},{y:2013,m:9,d:21},{y:2013,m:12,d:21},{y:2014,m:1,d:18},{y:2015,m:1,d:17}],puts:[{cid:"861808824253659",name:"",s:"GOOG130531P00625000",e:"OPRA",p:"0.05",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.05",oi:"14",vol:"-",strike:"625.00",expiry:"May 31, 2013"},{cid:"90291598673294",name:"",s:"GOOG130531P00630000",e:"OPRA",p:"0.50",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.05",oi:"3",vol:"-",strike:"630.00",expiry:"May 31, 2013"},{cid:"883084064658290",name:"",s:"GOOG130531P00635000",e:"OPRA",p:"0.50",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.05",oi:"3",vol:"-",strike:"635.00",expiry:"May 31, 2013"},{cid:"550606621196196",name:"",s:"GOOG130531P00640000",e:"OPRA",p:"0.50",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.05",oi:"6",vol:"-",strike:"640.00",expiry:"May 31, 2013"},{cid:"907661465271381",name:"",s:"GOOG130531P00645000",e:"OPRA",p:"0.76",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.05",oi:"4",vol:"-",strike:"645.00",expiry:"May 31, 2013"},{cid:"312331955116595",name:"",s:"GOOG130531P00650000",e:"OPRA",p:"0.50",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.05",oi:"7",vol:"-",strike:"650.00",expiry:"May 31, 2013"},{cid:"1034371554903574",name:"",s:"GOOG130531P00655000",e:"OPRA",p:"0.05",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.05",oi:"138",vol:"-",strike:"655.00",expiry:"May 31, 2013"},{cid:"849038193044261",name:"",s:"GOOG130531P00660000",e:"OPRA",p:"0.05",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.05",oi:"221",vol:"-",strike:"660.00",expiry:"May 31, 2013"},{cid:"448843840017009",name:"",s:"GOOG130531P00665000",e:"OPRA",p:"0.05",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.05",oi:"17",vol:"-",strike:"665.00",expiry:"May 31, 2013"},{cid:"956560337544029",name:"",s:"GOOG130531P00670000",e:"OPRA",p:"0.05",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.05",oi:"89",vol:"-",strike:"670.00",expiry:"May 31, 2013"},{cid:"168619215452014",name:"",s:"GOOG130531P00675000",e:"OPRA",p:"0.20",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.05",oi:"4",vol:"-",strike:"675.00",expiry:"May 31, 2013"},{cid:"1117974573979659",name:"",s:"GOOG130531P00680000",e:"OPRA",p:"0.15",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.05",oi:"8",vol:"-",strike:"680.00",expiry:"May 31, 2013"},{cid:"753362057423145",name:"",s:"GOOG130531P00685000",e:"OPRA",p:"0.05",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.05",oi:"64",vol:"-",strike:"685.00",expiry:"May 31, 2013"},{cid:"764049961140541",name:"",s:"GOOG130531P00690000",e:"OPRA",p:"0.35",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.05",oi:"19",vol:"-",strike:"690.00",expiry:"May 31, 2013"},{cid:"856579959673404",name:"",s:"GOOG130531P00695000",e:"OPRA",p:"0.15",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.05",oi:"52",vol:"-",strike:"695.00",expiry:"May 31, 2013"},{cid:"824170367827899",name:"",s:"GOOG130531P00700000",e:"OPRA",p:"0.25",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.70",oi:"10",vol:"-",strike:"700.00",expiry:"May 31, 2013"},{cid:"414605646886183",name:"",s:"GOOG130531P00705000",e:"OPRA",p:"0.05",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.05",oi:"211",vol:"-",strike:"705.00",expiry:"May 31, 2013"},{cid:"1123808986964380",name:"",s:"GOOG130531P00710000",e:"OPRA",p:"0.35",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.65",oi:"28",vol:"-",strike:"710.00",expiry:"May 31, 2013"},{cid:"428007176517959",name:"",s:"GOOG130531P00715000",e:"OPRA",p:"0.05",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.05",oi:"96",vol:"-",strike:"715.00",expiry:"May 31, 2013"},{cid:"1004640940579345",name:"",s:"GOOG130531P00720000",e:"OPRA",p:"1.15",cs:"chb",c:"0.00",cp:"0.00",b:"0.05",a:"0.55",oi:"1",vol:"-",strike:"720.00",expiry:"May 31, 2013"},{cid:"547870112882747",name:"",s:"GOOG130531P00725000",e:"OPRA",p:"0.05",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.05",oi:"26",vol:"-",strike:"725.00",expiry:"May 31, 2013"},{cid:"713283828090500",name:"",s:"GOOG130531P00730000",e:"OPRA",p:"0.75",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.65",oi:"16",vol:"-",strike:"730.00",expiry:"May 31, 2013"},{cid:"330110346878283",name:"",s:"GOOG130531P00735000",e:"OPRA",p:"0.50",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.05",oi:"6",vol:"-",strike:"735.00",expiry:"May 31, 2013"},{cid:"741172786814707",name:"",s:"GOOG130531P00740000",e:"OPRA",p:"0.60",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.40",oi:"11",vol:"-",strike:"740.00",expiry:"May 31, 2013"},{cid:"305806735527325",name:"",s:"GOOG130531P00745000",e:"OPRA",p:"0.10",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.05",oi:"16",vol:"-",strike:"745.00",expiry:"May 31, 2013"},{cid:"836255382420185",name:"",s:"GOOG130531P00750000",e:"OPRA",p:"0.95",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.40",oi:"28",vol:"-",strike:"750.00",expiry:"May 31, 2013"},{cid:"10060751156355",name:"",s:"GOOG130531P00755000",e:"OPRA",p:"0.05",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.10",oi:"55",vol:"-",strike:"755.00",expiry:"May 31, 2013"},{cid:"184650813944442",name:"",s:"GOOG130531P00760000",e:"OPRA",p:"0.25",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.40",oi:"14",vol:"-",strike:"760.00",expiry:"May 31, 2013"},{cid:"439480549217736",name:"",s:"GOOG130531P00765000",e:"OPRA",p:"0.10",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.10",oi:"97",vol:"-",strike:"765.00",expiry:"May 31, 2013"},{cid:"308783986011504",name:"",s:"GOOG130531P00770000",e:"OPRA",p:"0.20",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.65",oi:"20",vol:"-",strike:"770.00",expiry:"May 31, 2013"},{cid:"51018175031907",name:"",s:"GOOG130531P00775000",e:"OPRA",p:"0.15",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.10",oi:"145",vol:"-",strike:"775.00",expiry:"May 31, 2013"},{cid:"917630774138659",name:"",s:"GOOG130531P00780000",e:"OPRA",p:"0.80",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.40",oi:"11",vol:"-",strike:"780.00",expiry:"May 31, 2013"},{cid:"1116428272838913",name:"",s:"GOOG130531P00785000",e:"OPRA",p:"0.05",cs:"chr",c:"-0.10",cp:"-66.67",b:"-",a:"0.10",oi:"71",vol:"3",strike:"785.00",expiry:"May 31, 2013"},{cid:"768225161293425",name:"",s:"GOOG130531P00790000",e:"OPRA",p:"0.25",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.60",oi:"16",vol:"-",strike:"790.00",expiry:"May 31, 2013"},{cid:"755499966485666",name:"",s:"GOOG130531P00795000",e:"OPRA",p:"0.21",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.05",oi:"107",vol:"-",strike:"795.00",expiry:"May 31, 2013"},{cid:"1013649638331262",name:"",s:"GOOG130531P00800000",e:"OPRA",p:"0.20",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.40",oi:"56",vol:"-",strike:"800.00",expiry:"May 31, 2013"},{cid:"357377673137695",name:"",s:"GOOG130531P00805000",e:"OPRA",p:"0.05",cs:"chr",c:"-0.23",cp:"-82.14",b:"0.05",a:"0.10",oi:"3615",vol:"123",strike:"805.00",expiry:"May 31, 2013"},{cid:"690708626756771",name:"",s:"GOOG130531P00810000",e:"OPRA",p:"0.75",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.25",oi:"28",vol:"-",strike:"810.00",expiry:"May 31, 2013"},{cid:"21150003535275",name:"",s:"GOOG130531P00815000",e:"OPRA",p:"0.05",cs:"chr",c:"-0.20",cp:"-80.00",b:"0.05",a:"0.15",oi:"177",vol:"6",strike:"815.00",expiry:"May 31, 2013"},{cid:"275905429065075",name:"",s:"GOOG130531P00820000",e:"OPRA",p:"0.08",cs:"chr",c:"-0.24",cp:"-75.00",b:"0.05",a:"0.15",oi:"1037",vol:"107",strike:"820.00",expiry:"May 31, 2013"},{cid:"1055025518544642",name:"",s:"GOOG130531P00825000",e:"OPRA",p:"0.70",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.40",oi:"3",vol:"-",strike:"825.00",expiry:"May 31, 2013"},{cid:"1035321415642280",name:"",s:"GOOG130531P00830000",e:"OPRA",p:"0.13",cs:"chr",c:"-0.40",cp:"-75.47",b:"0.10",a:"0.20",oi:"489",vol:"68",strike:"830.00",expiry:"May 31, 2013"},{cid:"70557296969979",name:"",s:"GOOG130531P00835000",e:"OPRA",p:"0.63",cs:"chb",c:"0.00",cp:"0.00",b:"0.10",a:"0.40",oi:"43",vol:"-",strike:"835.00",expiry:"May 31, 2013"},{cid:"29904266868370",name:"",s:"GOOG130531P00840000",e:"OPRA",p:"1.40",cs:"chb",c:"0.00",cp:"0.00",b:"0.05",a:"0.30",oi:"34",vol:"-",strike:"840.00",expiry:"May 31, 2013"},{cid:"60994034524162",name:"",s:"GOOG130531P00845000",e:"OPRA",p:"0.25",cs:"chr",c:"-0.95",cp:"-79.17",b:"0.25",a:"0.30",oi:"620",vol:"138",strike:"845.00",expiry:"May 31, 2013"},{cid:"1062537796162167",name:"",s:"GOOG130531P00850000",e:"OPRA",p:"1.80",cs:"chb",c:"0.00",cp:"0.00",b:"0.20",a:"0.65",oi:"116",vol:"-",strike:"850.00",expiry:"May 31, 2013"},{cid:"985844474705712",name:"",s:"GOOG130531P00855000",e:"OPRA",p:"0.51",cs:"chr",c:"-1.78",cp:"-77.73",b:"0.50",a:"0.55",oi:"578",vol:"377",strike:"855.00",expiry:"May 31, 2013"},{cid:"412696606024360",name:"",s:"GOOG130531P00860000",e:"OPRA",p:"3.50",cs:"chb",c:"0.00",cp:"0.00",b:"0.55",a:"0.90",oi:"150",vol:"-",strike:"860.00",expiry:"May 31, 2013"},{cid:"788760175384132",name:"",s:"GOOG130531P00865000",e:"OPRA",p:"5.50",cs:"chb",c:"0.00",cp:"0.00",b:"0.85",a:"1.30",oi:"169",vol:"-",strike:"865.00",expiry:"May 31, 2013"},{cid:"495262825571032",name:"",s:"GOOG130531P00870000",e:"OPRA",p:"1.60",cs:"chr",c:"-4.80",cp:"-75.00",b:"1.65",a:"1.75",oi:"1993",vol:"1044",strike:"870.00",expiry:"May 31, 2013"},{cid:"784479429576717",name:"",s:"GOOG130531P00875000",e:"OPRA",p:"3.00",cs:"chr",c:"-6.28",cp:"-67.67",b:"2.40",a:"2.65",oi:"172",vol:"127",strike:"875.00",expiry:"May 31, 2013"},{cid:"475018278612528",name:"",s:"GOOG130531P00880000",e:"OPRA",p:"3.30",cs:"chr",c:"-9.60",cp:"-74.42",b:"3.60",a:"4.00",oi:"304",vol:"92",strike:"880.00",expiry:"May 31, 2013"},{cid:"23479753271876",name:"",s:"GOOG130531P00885000",e:"OPRA",p:"5.60",cs:"chr",c:"-9.50",cp:"-62.91",b:"5.40",a:"5.70",oi:"911",vol:"1053",strike:"885.00",expiry:"May 31, 2013"},{cid:"752454851539195",name:"",s:"GOOG130531P00890000",e:"OPRA",p:"7.90",cs:"chr",c:"-10.49",cp:"-57.04",b:"7.60",a:"8.00",oi:"531",vol:"918",strike:"890.00",expiry:"May 31, 2013"},{cid:"70240546867537",name:"",s:"GOOG130531P00895000",e:"OPRA",p:"10.40",cs:"chr",c:"-12.33",cp:"-54.25",b:"10.10",a:"10.80",oi:"252",vol:"231",strike:"895.00",expiry:"May 31, 2013"},{cid:"897963621776473",name:"",s:"GOOG130531P00900000",e:"OPRA",p:"13.49",cs:"chr",c:"-14.14",cp:"-51.18",b:"12.00",a:"14.50",oi:"131",vol:"4",strike:"900.00",expiry:"May 31, 2013"},{cid:"85067464862382",name:"",s:"GOOG130531P00905000",e:"OPRA",p:"23.60",cs:"chb",c:"0.00",cp:"0.00",b:"15.80",a:"18.60",oi:"0",vol:"20",strike:"905.00",expiry:"May 31, 2013"},{cid:"805187710443767",name:"",s:"GOOG130531P00910000",e:"OPRA",p:"20.20",cs:"chr",c:"-18.50",cp:"-47.80",b:"21.50",a:"22.50",oi:"576",vol:"37",strike:"910.00",expiry:"May 31, 2013"},{cid:"885641012669822",name:"",s:"GOOG130531P00915000",e:"OPRA",p:"-",c:"-",b:"24.60",a:"27.30",oi:"0",vol:"-",strike:"915.00",expiry:"May 31, 2013"},{cid:"899858163597569",name:"",s:"GOOG130531P00920000",e:"OPRA",p:"31.00",cs:"chr",c:"-17.00",cp:"-35.42",b:"30.10",a:"32.00",oi:"127",vol:"9",strike:"920.00",expiry:"May 31, 2013"},{cid:"384946575665642",name:"",s:"GOOG130531P00925000",e:"OPRA",p:"-",c:"-",b:"34.10",a:"36.90",oi:"0",vol:"-",strike:"925.00",expiry:"May 31, 2013"},{cid:"195709831580001",name:"",s:"GOOG130531P00930000",e:"OPRA",p:"-",c:"-",b:"39.10",a:"41.80",oi:"0",vol:"-",strike:"930.00",expiry:"May 31, 2013"},{cid:"105979139287680",name:"",s:"GOOG130531P00935000",e:"OPRA",p:"-",c:"-",b:"44.10",a:"46.70",oi:"0",vol:"-",strike:"935.00",expiry:"May 31, 2013"},{cid:"178992314903890",name:"",s:"GOOG130531P00940000",e:"OPRA",p:"-",c:"-",b:"49.00",a:"51.70",oi:"0",vol:"-",strike:"940.00",expiry:"May 31, 2013"},{cid:"1081213298325092",name:"",s:"GOOG130531P00945000",e:"OPRA",p:"-",c:"-",b:"54.00",a:"57.00",oi:"0",vol:"-",strike:"945.00",expiry:"May 31, 2013"},{cid:"849137800680828",name:"",s:"GOOG130531P00950000",e:"OPRA",p:"-",c:"-",b:"59.40",a:"61.60",oi:"0",vol:"-",strike:"950.00",expiry:"May 31, 2013"},{cid:"252708185356048",name:"",s:"GOOG130531P00955000",e:"OPRA",p:"-",c:"-",b:"63.90",a:"67.60",oi:"0",vol:"-",strike:"955.00",expiry:"May 31, 2013"},{cid:"849787286766910",name:"",s:"GOOG130531P00960000",e:"OPRA",p:"-",c:"-",b:"68.90",a:"71.60",oi:"0",vol:"-",strike:"960.00",expiry:"May 31, 2013"},{cid:"39686410476830",name:"",s:"GOOG130531P00965000",e:"OPRA",p:"-",c:"-",b:"74.00",a:"77.20",oi:"0",vol:"-",strike:"965.00",expiry:"May 31, 2013"}],calls:[{cid:"897932155474025",name:"",s:"GOOG130531C00625000",e:"OPRA",p:"-",c:"-",b:"262.70",a:"265.60",oi:"0",vol:"-",strike:"625.00",expiry:"May 31, 2013"},{cid:"184287418485356",name:"",s:"GOOG130531C00630000",e:"OPRA",p:"248.20",cs:"chb",c:"0.00",cp:"0.00",b:"257.70",a:"260.60",oi:"5",vol:"-",strike:"630.00",expiry:"May 31, 2013"},{cid:"905931936433954",name:"",s:"GOOG130531C00635000",e:"OPRA",p:"-",c:"-",b:"252.70",a:"255.60",oi:"0",vol:"-",strike:"635.00",expiry:"May 31, 2013"},{cid:"135801183483562",name:"",s:"GOOG130531C00640000",e:"OPRA",p:"-",c:"-",b:"247.70",a:"250.60",oi:"0",vol:"-",strike:"640.00",expiry:"May 31, 2013"},{cid:"543749135131573",name:"",s:"GOOG130531C00645000",e:"OPRA",p:"-",c:"-",b:"242.70",a:"245.60",oi:"0",vol:"-",strike:"645.00",expiry:"May 31, 2013"},{cid:"430718357015828",name:"",s:"GOOG130531C00650000",e:"OPRA",p:"208.30",cs:"chb",c:"0.00",cp:"0.00",b:"237.70",a:"240.60",oi:"2",vol:"-",strike:"650.00",expiry:"May 31, 2013"},{cid:"188702697546621",name:"",s:"GOOG130531C00655000",e:"OPRA",p:"-",c:"-",b:"232.70",a:"235.60",oi:"0",vol:"-",strike:"655.00",expiry:"May 31, 2013"},{cid:"828515608830763",name:"",s:"GOOG130531C00660000",e:"OPRA",p:"-",c:"-",b:"227.70",a:"230.60",oi:"0",vol:"-",strike:"660.00",expiry:"May 31, 2013"},{cid:"999908579656355",name:"",s:"GOOG130531C00665000",e:"OPRA",p:"215.00",cs:"chb",c:"0.00",cp:"0.00",b:"222.70",a:"225.60",oi:"6",vol:"-",strike:"665.00",expiry:"May 31, 2013"},{cid:"543778324287872",name:"",s:"GOOG130531C00670000",e:"OPRA",p:"-",c:"-",b:"218.30",a:"220.60",oi:"0",vol:"-",strike:"670.00",expiry:"May 31, 2013"},{cid:"911061111100062",name:"",s:"GOOG130531C00675000",e:"OPRA",p:"-",c:"-",b:"213.30",a:"215.60",oi:"0",vol:"-",strike:"675.00",expiry:"May 31, 2013"},{cid:"530480483916026",name:"",s:"GOOG130531C00680000",e:"OPRA",p:"-",c:"-",b:"208.20",a:"210.60",oi:"0",vol:"-",strike:"680.00",expiry:"May 31, 2013"},{cid:"972896973547783",name:"",s:"GOOG130531C00685000",e:"OPRA",p:"-",c:"-",b:"202.70",a:"205.70",oi:"0",vol:"-",strike:"685.00",expiry:"May 31, 2013"},{cid:"703518576890345",name:"",s:"GOOG130531C00690000",e:"OPRA",p:"-",c:"-",b:"198.30",a:"200.60",oi:"0",vol:"-",strike:"690.00",expiry:"May 31, 2013"},{cid:"173645130459646",name:"",s:"GOOG130531C00695000",e:"OPRA",p:"-",c:"-",b:"193.30",a:"195.60",oi:"0",vol:"-",strike:"695.00",expiry:"May 31, 2013"},{cid:"252936815518459",name:"",s:"GOOG130531C00700000",e:"OPRA",p:"-",c:"-",b:"187.30",a:"191.50",oi:"0",vol:"-",strike:"700.00",expiry:"May 31, 2013"},{cid:"40857533404165",name:"",s:"GOOG130531C00705000",e:"OPRA",p:"-",c:"-",b:"183.30",a:"185.60",oi:"0",vol:"-",strike:"705.00",expiry:"May 31, 2013"},{cid:"957476173492076",name:"",s:"GOOG130531C00710000",e:"OPRA",p:"-",c:"-",b:"177.30",a:"181.50",oi:"0",vol:"-",strike:"710.00",expiry:"May 31, 2013"},{cid:"108863832559161",name:"",s:"GOOG130531C00715000",e:"OPRA",p:"-",c:"-",b:"173.20",a:"175.60",oi:"0",vol:"-",strike:"715.00",expiry:"May 31, 2013"},{cid:"98617325850106",name:"",s:"GOOG130531C00720000",e:"OPRA",p:"-",c:"-",b:"168.20",a:"170.60",oi:"0",vol:"-",strike:"720.00",expiry:"May 31, 2013"},{cid:"753686669907511",name:"",s:"GOOG130531C00725000",e:"OPRA",p:"-",c:"-",b:"163.30",a:"165.60",oi:"0",vol:"-",strike:"725.00",expiry:"May 31, 2013"},{cid:"489933059142682",name:"",s:"GOOG130531C00730000",e:"OPRA",p:"-",c:"-",b:"157.30",a:"161.50",oi:"0",vol:"-",strike:"730.00",expiry:"May 31, 2013"},{cid:"905425017312349",name:"",s:"GOOG130531C00735000",e:"OPRA",p:"174.80",cs:"chb",c:"0.00",cp:"0.00",b:"152.70",a:"155.70",oi:"1",vol:"-",strike:"735.00",expiry:"May 31, 2013"},{cid:"136536386201059",name:"",s:"GOOG130531C00740000",e:"OPRA",p:"-",c:"-",b:"147.30",a:"151.50",oi:"0",vol:"-",strike:"740.00",expiry:"May 31, 2013"},{cid:"147619908144017",name:"",s:"GOOG130531C00745000",e:"OPRA",p:"-",c:"-",b:"142.70",a:"145.70",oi:"0",vol:"-",strike:"745.00",expiry:"May 31, 2013"},{cid:"966255278051458",name:"",s:"GOOG130531C00750000",e:"OPRA",p:"-",c:"-",b:"137.30",a:"141.50",oi:"0",vol:"-",strike:"750.00",expiry:"May 31, 2013"},{cid:"91531149317385",name:"",s:"GOOG130531C00755000",e:"OPRA",p:"-",c:"-",b:"132.70",a:"135.70",oi:"0",vol:"-",strike:"755.00",expiry:"May 31, 2013"},{cid:"1073058963314671",name:"",s:"GOOG130531C00760000",e:"OPRA",p:"-",c:"-",b:"127.70",a:"130.70",oi:"0",vol:"-",strike:"760.00",expiry:"May 31, 2013"},{cid:"211715618356204",name:"",s:"GOOG130531C00765000",e:"OPRA",p:"-",c:"-",b:"122.90",a:"125.70",oi:"0",vol:"-",strike:"765.00",expiry:"May 31, 2013"},{cid:"864401376962645",name:"",s:"GOOG130531C00770000",e:"OPRA",p:"-",c:"-",b:"117.30",a:"121.60",oi:"0",vol:"-",strike:"770.00",expiry:"May 31, 2013"},{cid:"625513742158849",name:"",s:"GOOG130531C00775000",e:"OPRA",p:"-",c:"-",b:"113.30",a:"115.70",oi:"0",vol:"-",strike:"775.00",expiry:"May 31, 2013"},{cid:"150940569707753",name:"",s:"GOOG130531C00780000",e:"OPRA",p:"97.87",cs:"chb",c:"0.00",cp:"0.00",b:"108.30",a:"110.80",oi:"1",vol:"-",strike:"780.00",expiry:"May 31, 2013"},{cid:"1096966496977199",name:"",s:"GOOG130531C00785000",e:"OPRA",p:"-",c:"-",b:"102.70",a:"105.90",oi:"0",vol:"-",strike:"785.00",expiry:"May 31, 2013"},{cid:"596267655966317",name:"",s:"GOOG130531C00790000",e:"OPRA",p:"68.00",cs:"chb",c:"0.00",cp:"0.00",b:"97.30",a:"101.60",oi:"11",vol:"-",strike:"790.00",expiry:"May 31, 2013"},{cid:"797644140819446",name:"",s:"GOOG130531C00795000",e:"OPRA",p:"-",c:"-",b:"92.70",a:"95.90",oi:"0",vol:"-",strike:"795.00",expiry:"May 31, 2013"},{cid:"67114730428643",name:"",s:"GOOG130531C00800000",e:"OPRA",p:"90.20",cs:"chb",c:"0.00",cp:"0.00",b:"87.40",a:"91.10",oi:"48",vol:"-",strike:"800.00",expiry:"May 31, 2013"},{cid:"524083644435811",name:"",s:"GOOG130531C00805000",e:"OPRA",p:"76.20",cs:"chb",c:"0.00",cp:"0.00",b:"82.90",a:"85.80",oi:"10",vol:"-",strike:"805.00",expiry:"May 31, 2013"},{cid:"1027523638915015",name:"",s:"GOOG130531C00810000",e:"OPRA",p:"25.30",cs:"chb",c:"0.00",cp:"0.00",b:"78.50",a:"81.30",oi:"28",vol:"-",strike:"810.00",expiry:"May 31, 2013"},{cid:"731421388062365",name:"",s:"GOOG130531C00815000",e:"OPRA",p:"94.02",cs:"chb",c:"0.00",cp:"0.00",b:"73.10",a:"75.70",oi:"3",vol:"-",strike:"815.00",expiry:"May 31, 2013"},{cid:"201733430660498",name:"",s:"GOOG130531C00820000",e:"OPRA",p:"53.87",cs:"chb",c:"0.00",cp:"0.00",b:"68.60",a:"71.20",oi:"13",vol:"-",strike:"820.00",expiry:"May 31, 2013"},{cid:"424269582116081",name:"",s:"GOOG130531C00825000",e:"OPRA",p:"-",c:"-",b:"63.60",a:"66.30",oi:"0",vol:"-",strike:"825.00",expiry:"May 31, 2013"},{cid:"1108741066703867",name:"",s:"GOOG130531C00830000",e:"OPRA",p:"55.50",cs:"chb",c:"0.00",cp:"0.00",b:"58.40",a:"60.70",oi:"71",vol:"-",strike:"830.00",expiry:"May 31, 2013"},{cid:"665032675403725",name:"",s:"GOOG130531C00835000",e:"OPRA",p:"65.70",cs:"chb",c:"0.00",cp:"0.00",b:"53.50",a:"55.70",oi:"14",vol:"-",strike:"835.00",expiry:"May 31, 2013"},{cid:"870334633948548",name:"",s:"GOOG130531C00840000",e:"OPRA",p:"50.00",cs:"chb",c:"0.00",cp:"0.00",b:"48.70",a:"51.30",oi:"35",vol:"-",strike:"840.00",expiry:"May 31, 2013"},{cid:"607302185263535",name:"",s:"GOOG130531C00845000",e:"OPRA",p:"-",c:"-",b:"43.80",a:"46.40",oi:"0",vol:"-",strike:"845.00",expiry:"May 31, 2013"},{cid:"260537929897126",name:"",s:"GOOG130531C00850000",e:"OPRA",p:"24.20",cs:"chb",c:"0.00",cp:"0.00",b:"38.80",a:"41.50",oi:"60",vol:"-",strike:"850.00",expiry:"May 31, 2013"},{cid:"869025962460528",name:"",s:"GOOG130531C00855000",e:"OPRA",p:"-",c:"-",b:"33.90",a:"36.70",oi:"0",vol:"-",strike:"855.00",expiry:"May 31, 2013"},{cid:"271885603677647",name:"",s:"GOOG130531C00860000",e:"OPRA",p:"31.20",cs:"chb",c:"0.00",cp:"0.00",b:"29.20",a:"31.40",oi:"49",vol:"-",strike:"860.00",expiry:"May 31, 2013"},{cid:"328801446656020",name:"",s:"GOOG130531C00865000",e:"OPRA",p:"26.95",cs:"chg",c:"+14.95",cp:"124.58",b:"24.80",a:"25.80",oi:"178",vol:"34",strike:"865.00",expiry:"May 31, 2013"},{cid:"829450250741566",name:"",s:"GOOG130531C00870000",e:"OPRA",p:"19.10",cs:"chg",c:"+9.90",cp:"107.61",b:"20.20",a:"22.10",oi:"138",vol:"13",strike:"870.00",expiry:"May 31, 2013"},{cid:"989626103025718",name:"",s:"GOOG130531C00875000",e:"OPRA",p:"12.50",cs:"chg",c:"+5.71",cp:"84.09",b:"16.10",a:"17.90",oi:"61",vol:"10",strike:"875.00",expiry:"May 31, 2013"},{cid:"1105249690063656",name:"",s:"GOOG130531C00880000",e:"OPRA",p:"13.00",cs:"chg",c:"+8.20",cp:"170.83",b:"12.40",a:"14.90",oi:"252",vol:"35",strike:"880.00",expiry:"May 31, 2013"},{cid:"339698646824918",name:"",s:"GOOG130531C00885000",e:"OPRA",p:"9.70",cs:"chg",c:"+6.40",cp:"193.94",b:"9.60",a:"9.90",oi:"1126",vol:"1868",strike:"885.00",expiry:"May 31, 2013"},{cid:"280517630346946",name:"",s:"GOOG130531C00890000",e:"OPRA",p:"6.94",cs:"chg",c:"+5.09",cp:"275.14",b:"6.70",a:"7.20",oi:"262",vol:"432",strike:"890.00",expiry:"May 31, 2013"},{cid:"963465706946796",name:"",s:"GOOG130531C00895000",e:"OPRA",p:"4.75",cs:"chg",c:"+3.41",cp:"254.48",b:"4.60",a:"4.90",oi:"467",vol:"1408",strike:"895.00",expiry:"May 31, 2013"},{cid:"183457594845045",name:"",s:"GOOG130531C00900000",e:"OPRA",p:"3.13",cs:"chg",c:"+2.18",cp:"229.47",b:"3.10",a:"3.20",oi:"1627",vol:"2036",strike:"900.00",expiry:"May 31, 2013"},{cid:"646238429691215",name:"",s:"GOOG130531C00905000",e:"OPRA",p:"2.00",cs:"chg",c:"+1.36",cp:"212.50",b:"1.95",a:"2.05",oi:"793",vol:"951",strike:"905.00",expiry:"May 31, 2013"},{cid:"212732374141821",name:"",s:"GOOG130531C00910000",e:"OPRA",p:"0.65",cs:"chb",c:"0.00",cp:"0.00",b:"1.15",a:"1.45",oi:"78",vol:"-",strike:"910.00",expiry:"May 31, 2013"},{cid:"710257727382042",name:"",s:"GOOG130531C00915000",e:"OPRA",p:"0.95",cs:"chg",c:"+0.63",cp:"196.88",b:"0.65",a:"0.90",oi:"40",vol:"7",strike:"915.00",expiry:"May 31, 2013"},{cid:"563703158549966",name:"",s:"GOOG130531C00920000",e:"OPRA",p:"0.22",cs:"chb",c:"0.00",cp:"0.00",b:"0.20",a:"0.80",oi:"70",vol:"-",strike:"920.00",expiry:"May 31, 2013"},{cid:"834257765385117",name:"",s:"GOOG130531C00925000",e:"OPRA",p:"0.37",cs:"chg",c:"+0.22",cp:"146.67",b:"0.35",a:"0.40",oi:"280",vol:"262",strike:"925.00",expiry:"May 31, 2013"},{cid:"420529541878506",name:"",s:"GOOG130531C00930000",e:"OPRA",p:"0.95",cs:"chb",c:"0.00",cp:"0.00",b:"0.10",a:"0.40",oi:"8",vol:"-",strike:"930.00",expiry:"May 31, 2013"},{cid:"888055439268652",name:"",s:"GOOG130531C00935000",e:"OPRA",p:"0.75",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.40",oi:"14",vol:"-",strike:"935.00",expiry:"May 31, 2013"},{cid:"801449057323065",name:"",s:"GOOG130531C00940000",e:"OPRA",p:"0.45",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.40",oi:"88",vol:"-",strike:"940.00",expiry:"May 31, 2013"},{cid:"607038769941357",name:"",s:"GOOG130531C00945000",e:"OPRA",p:"0.55",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.40",oi:"14",vol:"-",strike:"945.00",expiry:"May 31, 2013"},{cid:"667068548867948",name:"",s:"GOOG130531C00950000",e:"OPRA",p:"0.45",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.40",oi:"60",vol:"-",strike:"950.00",expiry:"May 31, 2013"},{cid:"4937120138052",name:"",s:"GOOG130531C00955000",e:"OPRA",p:"0.55",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.40",oi:"2",vol:"-",strike:"955.00",expiry:"May 31, 2013"},{cid:"217861932232686",name:"",s:"GOOG130531C00960000",e:"OPRA",p:"0.40",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.40",oi:"3",vol:"-",strike:"960.00",expiry:"May 31, 2013"},{cid:"312327429834115",name:"",s:"GOOG130531C00965000",e:"OPRA",p:"0.40",cs:"chb",c:"0.00",cp:"0.00",b:"-",a:"0.40",oi:"2",vol:"-",strike:"965.00",expiry:"May 31, 2013"}],underlying_id:"694653",underlying_price:889.58002}
{ "language": "en", "url": "https://stackoverflow.com/questions/16819382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Extracting data embedded in an 8-bit array into different size array I am working on a project which receives a series of parameters condensed into an 8 bit array. These parameters can come in varying sizes, but are always sent in an 8 bit array. The goal is to extract these parameters into an array the size of the largest sized parameter (which is already known beforehand). For example, there could be two 4 bit parameters stored in the first index of the parameter array, then one 8 bit parameter, then one 16 bit parameter. The goal would then be to place each parameter separately in a 16 bit array of length 4, where extra space are just 0's. I am struggling finding a way to do this efficiently, especially since the i2c array could potentially have multiple parameters embedded within one byte of the array. Any suggestions would be greatly appreciated! To better illustrate this, take our 8-bit data array = [0011 1011, 0110 1111] and take our parameter lengths to be = [2, 2, 4, 8]. Then, I would want the result array to appear as [0000 0000, 0000 0011, 0000 1011, 0110 1111]. The bold numbers indicate the bits taken from the data array. A: I solved this kind of problem before by simply considering the received array of bytes as a bit flow. So it's quite easy to read 3 bits, then 7 bits, then 10 bits, then 2 bits, etc. until the end of the buffer. You simply need to keep an index to the current bit: struct bitflow { unsigned char* data ; // Received data size_t datasize ; // Data size, in bytes. size_t pc ; // Current bit pointer, initialize it to zero. } To get the next bit (0/1=bit, -1=error): int getnextbit (struct bitflow* b) { // Check if we didn't already reached the end of buffer. // "pc" must be stricly below (classic C indexes) than the number of bytes (datasize) multiplied by 8 (number of bits per byte). // A shift of 3 ranks to the left is the same as multiplying by 8, but is faster and will be faster even without any enabled optimization from compiler. if (pc>=(datasize<<3)) return -1 ; // Where is the bit: // - Targeted byte is the integer part of "pc/8". Again, a shift to accelerate that. // - Targeted bit is the remainder of "pc/8". A binary mask with 7 do the same, again faster than a modulo even without optimizations. // We then shift a bit (1) to the position of the remainder, and with a bitwise "AND", we extract the bit. // If the result is zero, the bit wasn't set, we return zero. // If non-zero (equal to (1<<((b->pc) & 7)), in fact), we return "1". int result = (((b->data[(b->pc)>>3]) & (1<<((b->pc) & 7))) ? 1 : 0) ; // We extracted a bit, so we increment the pointer to next bit. b->pc++ ; return result ; } To get the next N bits (max. 31 bits, >=0 = OK, <0=error): // l2m==0: read from LSB to MSB, otherwise, read from MSB to LSB. int getnextbits (struct bitflow* b, int nbbits, int l2m) { if ((nbbits<0) || (nbbits>31)) return -2 ; if ((pc+nbbits)>=(datasize<<3)) return -1 ; int result = 0 ; size_t j=b->pc ; // Alternatives for endianness (depends on both CPU used and I2C data format, read both datasheets and/or simply test): if (l2m) { // 1st read bit is LSB (least significant bit), last read bit is MSB (most significant bit). for (int i=0 ; i<nbbits ; i++, j++) result |= (((b->data[j>>3]) & (1<<(j & 7))) ? (1<<i) : 0) ; } else { // 1st read bit is MSB, last read bit is LSB. for (int i=(nbbits-1) ; i>=0 ; i--, j++) result |= (((b->data[j>>3]) & (1<<(j & 7))) ? (1<<i) : 0) ; } b->pc += nbbits ; return result ; } This last function can be heavily optimized by getting directly all possible remaining bits of the current byte, if nbbits (or the number of bits still to extract) is greater or equal to the number of bits left in the current byte. But it shouldn't be needed if you don't have a huge load of data, which is quite unlikely if you get these data from I²C. Endianness can complexify things a bit, but it's not impossible to solve - I usually do the endianness swap directly at reception when needed. Finally, you can read data this way: // Considering structure is filled by reception routine. struct bitflow b = getdatafromi2c() ; // Number of bits for each consecutive element. int format[10] = { 4, 4, 2, 2, 4, 16, 10, 2, 1, 1 } ; unsigned short int result[10] ; for (int i=0 ; i<10 ; i++ ) { int v = getnextbits(&b, format[i]) ; if (v<0) { // Error handling .... } result[i] = (unsigned short int)v ; } // Use result array normally from now. A: uint8_t input_array[4]; uint16_t output_array[4]; // I have to make an assumption that the two fours are filled little-endian. If it's wrong, it's wrong. // You will generally have this problem whenever parameters span bytes. You have to know. output_array[0] = input_array[0] & 0xF; output_array[1] = input_array[0] >> 4; output_array[2] = input_array[1]; // Similar story here. I assume that input_array's bytes are little endian. // You normally find bit-endian and byte-endian are the same but a contrary system could exist. output_array[3] = input_array[2] | (input_array[3] << 8); In the old days people used to do this with structs. Somebody's going to come by and tell me this is undefined, etc; it doesn't really matter. A compiler that emits terrible code for the above emits good code for the below. It's the modern optimizing compilers that an figure the most efficient way for the above that will mess up the below. This has all kinds of alignment and endian assumptions built into it; however where it works, it works well. Where it doesn't work it's undefined. union u { uint8_t input_array[4]; struct input { unsigned char param0 : 4; unsigned char param1 : 4; unsigned char param2 : 8; unsigned char param3 : 6; } } input_form; union input_form input; uint16_t output_array[4]; output_array[0] = input.input.param0; output_array[1] = input.input.param1; output_array[2] = input.input.param2; output_array[3] = input.input.param3;
{ "language": "en", "url": "https://stackoverflow.com/questions/71636912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create xib based interface with Xcode 5 I am trying to create a new app with Singe View template but there is no xib or storyboard option to make my interface as xib file !!! why does Apple remove xib from iOS 7 ?!! How can I create application with xib interface files ? A: Apple removed it because they just want to "force" everybody to use Storyboards, although from what I know, a big amount of people just don't find them useful. I'm afraid you'll have to do it yourself, just create an empty app and set yourself the view. Check an example: http://www.appcoda.com/hello-world-app-using-xcode-5-xib/ A: Apple remove it from xcode 5 . you have only one option to choose storyboard. if you want to xibs then remove storyboard after creating singleView application and add xib manually. another option is to create application in xcode 4.6 or earliar version then run it on xcode 5. A: * *Create a new project *Select Single View Application *Set ProjectName and other settings *Save Project at location *Select Project in Navigator Panel in Left *Remove Main.storyboard file from project *Add New .xib file in Project *Set Main Interface to your .xib file in "General Tab" on right panel. *Paste following code in didFinishLaunchingWithOptions method self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; self.window.rootViewController = [[UIViewController alloc] initWithNibName:@"YourViewController" bundle:nil]; [self.window makeKeyAndVisible];
{ "language": "en", "url": "https://stackoverflow.com/questions/19632797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Download and save static images in phone In my application when i query a http URL i get list of object, some times these object needs to be rendered on listview and sometimes in my custom view. Each of the object which i receive from server has image tag, most of the time images are always constant i.e same image URL only. I just want to download the images once, & also my app should have to download once in a while when the images got changed in server. What is the best way? I know like, we need to perform operation in thread, but not getting the exact idea of how to do?. how to check for change of image & efficient way of storing them. Any hint A: For storage, I recommend Internal Storage http://developer.android.com/guide/topics/data/data-storage.html#filesInternal And for downloading http://developer.android.com/reference/android/os/AsyncTask.html You can create a AsyncTask where you pass a ImageView, where you want to show the img, with the url as a tag. And check in the internal storage if you have that img already saved if not just download it.
{ "language": "en", "url": "https://stackoverflow.com/questions/17976411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is this ignoring the where clause? Why is the where clause being ignored in this code? It seems to be ignoring the where clause on the update which means every records has been written over. How can i fix this? Any help would be greatly appreciated. namespace ResitAssignment2 { public partial class HomeCareVisitEddit : Form { public HomeCareVisitEddit() { InitializeComponent(); } private void SubmitHCVA_Click(object sender, EventArgs e) { SqlConnection a = Database.GetConnection(); a.Open(); string sqltext; sqltext = @"update HomeCareVisit set PatientNo=@PatientNo, FurtherVisitRequired=@FurtherVisitRequired, AdvisoryNotes=@AdvisoryNotes, Prescription=@Prescription, TreatmentProvided=@TreatmentProvided, ActualVisitDateTime=@ActualVisitDateTime, Priority=@Priority, ScheduledDateTime=@ScheduledDateTime, TreatmentInstructions=@TreatmentInstructions, MedicalStaffID=@MedicalStaffID WHERE VisitRefNo=VisitRefNo"; SqlCommand command = new SqlCommand(sqltext, a); try { using (a) { command.Parameters.AddWithValue("@PatientNo", PatientNo.Text); command.Parameters.AddWithValue("@FurtherVisitRequired", FurtherVisitRequired.Text); command.Parameters.AddWithValue("@AdvisoryNotes", AdvisoryNotes.Text); command.Parameters.AddWithValue("@Prescription", Prescription.Text); command.Parameters.AddWithValue("@TreatmentProvided", TreatmentProvided.Text); command.Parameters.AddWithValue("@ActualVisitDateTime",SqlDbType.DateTime ); { DateTime.Parse(ActualVisitDateTime.Text); }; command.Parameters.AddWithValue("@Priority", Priority.Text); command.Parameters.AddWithValue("@ScheduledDateTime",SqlDbType.DateTime ); { DateTime.Parse(ScheduledDateTime.Text); }; command.Parameters.AddWithValue("@TreatmentInstructions", TreatmentInstructions.Text); command.Parameters.AddWithValue("@MedicalStaffID", MedicalStaffID.Text); command.Parameters.AddWithValue("@VisitRefNo", VisitRefNo.Text); command.ExecuteNonQuery(); MessageBox.Show("Record altered"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } a.Close(); } private void HomeCareVisitEddit_Load(object sender, EventArgs e) { SqlConnection a = Database.GetConnection(); a.Open(); string sqlText = "select * from HomeCareVisit where VisitRefNo =" + VisitRefNo; SqlCommand command = new SqlCommand(sqlText, a); SqlDataReader HomeCareVisitData = command.ExecuteReader(); while (HomeCareVisitData.Read()) { //DateTime actual = DateTime.Parse("ActualVisitDateTime"); //DateTime scheduled = DateTime.Parse("ActualVisitDateTieme"); PatientNo.Text = HomeCareVisitData["PatientNo"].ToString(); FurtherVisitRequired.Text = HomeCareVisitData["FurtherVisitRequired"].ToString(); AdvisoryNotes.Text = HomeCareVisitData["AdvisoryNotes"].ToString(); Prescription.Text = HomeCareVisitData["Prescription"].ToString(); TreatmentProvided.Text = HomeCareVisitData["TreatmentProvided"].ToString(); ActualVisitDateTime.Text = HomeCareVisitData["ActualVisitDateTime"].ToString(); Priority.Text = HomeCareVisitData["Priority"].ToString(); ScheduledDateTime.Text = HomeCareVisitData["ScheduledDateTime"].ToString(); TreatmentInstructions.Text = HomeCareVisitData["TreatmentInstructions"].ToString(); MedicalStaffID.Text = HomeCareVisitData["MedicalStaffID"].ToString(); } a.Close(); } } } A: WHERE VisitRefNo=VisitRefNo"; should be WHERE VisitRefNo=@VisitRefNo";. A: WHERE VisitRefNo=VisitRefNo Should be WHERE VisitRefNo=@VisitRefNo
{ "language": "en", "url": "https://stackoverflow.com/questions/18319029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using pointers in Class Templates with Subclasses I have a problem with using pointers with Class templates. I can't properly access vv from the B subclass if 'vv' stores pointers to vectors; if I simply store vectors it works. But what I'm trying to do requires me to store pointers. I honestly have no idea what I'm doing wrong so here is the code: template<typename T> class A{ public: std::vector<std::vector<T>*> vv; void add(std::vector<T> new_vec) { vv.push_back(&new_vec); } virtual void print(){} virtual ~A(){} }; template<typename T> class B : public A<T>{ public: void print() override{ std::cout << this->vv[0]->at(0) << std::endl; } }; int main(){ int i = 10; std::vector<int> v; v.push_back(i); A <int>*a = new B<int>(); a->add(v); a->print(); return 0; } a->print() prints 0 instead of 10. Also I can't change what is inside main(). I would be very thankful for some help! A: Here: void add(std::vector<T> new_vec) { vv.push_back(&new_vec); } You store a pointer to the local argument new_vec in vv. That local copy will only live till the method returns. Hence the pointers in the vector are useless. Dereferencing them later invokes undefined behavior. If you really want to store pointers you should pass a pointer (or reference) to add. Though, you should rather use smart pointers.
{ "language": "en", "url": "https://stackoverflow.com/questions/70406647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: is filter is replaceable of query in mongo queries using c#? I'm new to mongo in c# I found tow ways to find documents based on search critiria: the first using filter: var collection = _database.GetCollection<BsonDocument>("restaurants"); var filter = Builders<BsonDocument>.Filter.Eq("address.zipcode", "10075"); var result = await collection.Find(filter).ToListAsync(); The second using query: MongoCollection<BsonDocument> books; var query = Query.EQ("author", "Kurt Vonnegut"); foreach (BsonDocument book in books.Find(query)) { // do something with book } What's the best way to find documents based to what MongoDB recommendation? A: As far I know query builders (like your second example using Query.EQ) belong to old versions of C# drivers (1.X) (see Query class). Also I suggest you to see Builder section in this link that confirm query builders is the old way to consult data. After the release of the 2.0 version of the .NET driver, a lot of changes were made, including the way of consult the data (you can read more about that in this link). If you are using the last C# driver version you should use your first approach. A: The first way you mentioned is quite fine. You might want to incorporate using a mongo cursor as well to allow you to iterate through results var collection = _database.GetCollection<BsonDocument>("restaurants"); var filter = Builders<BsonDocument>.Filter.Eq("address.zipcode", "10075"); using(var _cursor = await collection.Find(filter).ToCursorAsync()) { while(await _cursor.MoveNextAsync()) { foreach(var _document in _cursor.Current) //gets current document { //you can do things like get the _id of the document var _id = _document["_id"]; } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/35279995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Java .wav get binary data I'm using the Microsoft Project Oxford Speaker Recognition API REST, in order to create an enrollment I need to send a Binary Data of a .wav file. I already have the class that records and saves the .wav file, now I have to POST it, I just dunno how do I kinda "decode" the .wav file I have to that Binary Data that I want... Appreciate any help. Here's the link to what I'm trying to do: Speaker Recognition Create Enrollment. A: In the documentation of the API, it is mentioned that the "body" of the request is the raw binary data for the *.wav file that you have recorded. This means you just need to send the file as is without any decoding.
{ "language": "en", "url": "https://stackoverflow.com/questions/36047605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How wrap every 3rd elements in to a div, xslt each I am quite newbie on XSLT. here is my XML <contact> <person> <name>Hannah</name> <phone>123-123-123</phone> <address>No.1 A St. city</address> <person> <person> <name>David</name> <phone>223-223-223</phone> <address>No.2 B BRC. city</address> <person> <person> <name>Tim</name> <phone>323-223-333</phone> <address>No.3 c BRC. city</address> <person> <person> <name>May</name> <phone>443-443-443</phone> <address>No.4 bb Rd. city</address> <person> <person> <name>Rose</name> <phone>7743-443-443</phone> <address>No.7 rolling Rd. city</address> <person> ..........more <contact> The OUTPUT I am trying to have <div class="group"> <div class="info"> <h2>Hannah<h2/> <h3>123-123-123</h3> <p>No.1 A St. city<p/> </div> <div class="info"> <h2>David<h2/> <h3>223-223-223</h3> <p>No.2 B BRC. city<p/> </div> <div class="info"> <h2>Tim<h2/> <h3>323-223-333</h3> <p>No.3 c BRC. city<p/> </div> </div> <div class="group"> <div class="info"> <h2>May</h2> <h3>443-443-443</h3> <p>No.4 bb Rd. city</p> </div> <div class="info"> <h2>Rose</h2> <h3>7743-443-443</h3> <p>No.7 rolling Rd. city</p> </div> ..... Loop if has more </div> Here is what I did, but there are many errors. how to select more for-each select? <xsl:template name="group"> <xsl:param name="name"/> <xsl:param name="phone"/> <xsl:param name="address"/> <div class="info"> <h2><xsl:value-of select="$name"/></h2> <h3><xsl:value-of select="$phone"/></h3> <p><xsl:value-of select="$address"/></p> </div> </xsl:template> <xsl:template match="/*"> <xsl:variable name="name" select="//name"/> <xsl:variable name="phone" select="//phone"/> <xsl:variable name="address" select="//address"/> <xsl:for-each select="$name"> <xsl:if test="(position() mod 4) = 1"> <xsl:variable name="position" select="position()"/> <div class="group"> <xsl:call-template name="group"> <xsl:with-param name="name" select="."/> <xsl:with-param name="phone" select="."/> <xsl:with-param name="address" select="."/> </xsl:call-template> </div> </xsl:if> </xsl:for-each> </xsl:template> </xsl:stylesheet> If someone could please correct my errors please? Many thanks A: I wouldn't use for-each at all. The following stylesheet solves your problem in a more idiomatic way: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- the number of items to include in each group --> <xsl:variable name="group" select="3" /> <xsl:template match="/"> <xsl:apply-templates select="contact/person[position() mod $group = 1]" /> </xsl:template> <xsl:template match="person"> <div class="group"> <xsl:apply-templates select=".|following-sibling::person[position() &lt; $group]" mode="inner" /> </div> </xsl:template> <xsl:template match="person" mode="inner"> <div class="info"> <xsl:apply-templates /> </div> </xsl:template> <xsl:template match="name"> <h2><xsl:apply-templates /></h2> </xsl:template> <xsl:template match="phone"> <h3><xsl:apply-templates /></h3> </xsl:template> <xsl:template match="address"> <p><xsl:apply-templates /></p> </xsl:template> </xsl:stylesheet> We select every third person (starting with the first one) and apply a special template (using modes) to that element and its next two siblings. A: If someone could please correct my errors please? I don't know if I can correct your errors, because I don't really understand where you're going with your stylesheet. You seem to have the right idea that a processing template is required here, but I lost you after that. Try the following approach: <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/> <xsl:template match="/"> <root> <xsl:call-template name="divide"> <xsl:with-param name="items" select="contact/person"/> </xsl:call-template> </root> </xsl:template> <xsl:template name="divide"> <xsl:param name="items" /> <xsl:param name="groupSize" select="3"/> <xsl:param name="i" select="1"/> <xsl:choose> <xsl:when test="$i > count($items)"/> <xsl:otherwise> <div class="group"> <xsl:for-each select="$items[$i &lt;= position() and position() &lt; $i+$groupSize]"> <div class="info"> <h2><xsl:value-of select="name"/></h2> <h3><xsl:value-of select="phone"/></h3> <p><xsl:value-of select="address"/></p> </div> </xsl:for-each> </div> <xsl:call-template name="divide"> <xsl:with-param name="items" select="$items"/> <xsl:with-param name="i" select="$i+$groupSize"/> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet> Note that I have added a <root> element to the output which is missing from your required output. While I am at it, your input is also invalid: the <person> tags are not closed.
{ "language": "en", "url": "https://stackoverflow.com/questions/21125794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: angular 2 - kendo datepicker max and min doesnt work Kendo datepicker doesn't work. Can anyone tell me where I made mistake? Min date suppose to be today's date. Here is sample code: app.html <div [class]="datePickerClass"> <kendo-datepicker class="kendo-datepicker" id="startDate" [ngModel]="_startValue" [min]="min" [max]="max" (ngModelChange)="startValueChanged($event)" [format]="formatDisplay"></kendo-datepicker> </div> <div [class]="datePickerClass"> <kendo-datepicker class="kendo-datepicker" id="endDate" [ngModel]="_endValue" [min]="min" [max]="max" (ngModelChange)="endValueChanged($event)" [format]="'d MMM yyyy'"></kendo-datepicker> </div> <ng-content> </ng-content> app.ts public min = new Date(); public max: Date = new Date(2017, 1, 1); File structure A: I had the same problem recently try the following : private today = new Date(); public min: Date = new Date(this.today.getFullYear(), this.today.getMonth(), this.today.getDate()); this worked for me, also change the "max" to some date after 11/7/2017 :)
{ "language": "en", "url": "https://stackoverflow.com/questions/47154269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's wrong with my rackup file? When i attempt to start my unicorn server I've got the next stack trace: Can't understand what's wrong with rackup file? Why it is not readable? sites@bck:~/fatfreecrm$ /home/sites/.rvm/gems/ruby-1.9.2-p180@fatfreecrm/bin/unicorn_rails -E -D production -c /home/sites/fatfreecrm/config/unicorn.rb /home/sites/.rvm/gems/ruby-1.9.2-p180@fatfreecrm/gems/unicorn-3.7.0/lib/unicorn/configurator.rb:600:in `parse_rackup_file': rackup file (production) not readable (ArgumentError) from /home/sites/.rvm/gems/ruby-1.9.2-p180@fatfreecrm/gems/unicorn-3.7.0/lib/unicorn/configurator.rb:74:in `reload' from /home/sites/.rvm/gems/ruby-1.9.2-p180@fatfreecrm/gems/unicorn-3.7.0/lib/unicorn/configurator.rb:65:in `initialize' from /home/sites/.rvm/gems/ruby-1.9.2-p180@fatfreecrm/gems/unicorn-3.7.0/lib/unicorn/http_server.rb:102:in `new' from /home/sites/.rvm/gems/ruby-1.9.2-p180@fatfreecrm/gems/unicorn-3.7.0/lib/unicorn/http_server.rb:102:in `initialize' from /home/sites/.rvm/gems/ruby-1.9.2-p180@fatfreecrm/gems/unicorn-3.7.0/lib/unicorn.rb:30:in `new' from /home/sites/.rvm/gems/ruby-1.9.2-p180@fatfreecrm/gems/unicorn-3.7.0/lib/unicorn.rb:30:in `run' from /home/sites/.rvm/gems/ruby-1.9.2-p180@fatfreecrm/gems/unicorn-3.7.0/bin/unicorn_rails:208:in `<top (required)>' from /home/sites/.rvm/gems/ruby-1.9.2-p180@fatfreecrm/bin/unicorn_rails:19:in `load' from /home/sites/.rvm/gems/ruby-1.9.2-p180@fatfreecrm/bin/unicorn_rails:19:in `<main>' A: The problem is the order of your arguments. Try to switch -E and -D.
{ "language": "en", "url": "https://stackoverflow.com/questions/6451085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Subtracting value across multiple lists in Sharepoint 2010 I am attempting to perform a simple subtraction function across two lists in Sharepoint 2010. I have one list called Inventory that has part number, part name, and quantity. I have a second list called Tasks that has title, description, status, used part, and quantity. I have a workflow rule that states the following: The issue is that it's just throwing an error when I run a test task with a status of completed, used part selected, and quantity field holding an integer value. I am creating the workflow and attached it to the Tasks lists, so all current item equal items in the tasks. The end of update item in Inventory I am setting the variable New Inventory to be the new value of quantity in the Inventory lists. Any help with this would be great. Thanks. A: Disregard, found out during the CurrentItem: Quantity lookup i had set the part name to string instead of lookup value.
{ "language": "en", "url": "https://stackoverflow.com/questions/45908360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OOP Javascript, get attribute of class not the event e In a event handler from my custom class, I want to use an attribute of my class in a private event method. Its more clearly with this simple example : class myClass { constructor() { this._customAtt = "hello"; } foo() { this._addListeners(); } _addListeners() { $("input.two").click(this._anEvent); } _anEvent(e) { console.log(this._customAtt); // print 'undefined' console.log(self._customAtt); // print 'undefined' } } var myIClass = new myClass(); $('input.one').on("click", function() { myIClass.foo(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='button' value='one' class='one'> <input type='button' value='two' class='two'> When I click on the button one, I add an handler to the button two. If I click on the button two the method _anEvent is called and from this method, I want use the private attribute class _customAtt. But, in the _anEvent method, this is the event e, not my class. So, how can I can the attribute _customAtt from the method _anEvent ? A: The reason for this is because the context of this varies depending on how the function is called, not what the function was originally attached to. One relatively easy way to do this is to bind _anEvent to the instance of the class. constructor() { this._customAtt = "hello"; this._anEvent = this._anEvent.bind(this); } This will ensure that this is always the instance of myClass within the _anEvent function.
{ "language": "en", "url": "https://stackoverflow.com/questions/53296243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Namespace issue class not found In my root folder I have a file folder that has my common files I use between different projects. /files I have a file redis.php that has Redis class that I want to use in one of my project in /var/www/html/project/example.php The Class Redis is in /file/library/storage/redis/redis.php my redis.php has <?php namespace file\library\storage\redis; class Redis{ public function init(){ $redis = new Redis(); $redis->connect('127.0.0.1', 6379); } } ?> and in my example.php I call that namespace like $redis = new \file\library\storage\redis\Redis(); $redis->init(); but it gives me an error [Mon May 27 12:25:48 2013] [error] [client 127.0.0.1] PHP Fatal error: Class 'file\\library\\storage\\redis\\Redis' not found Any help will be appreciated A: What you are looking for is an autoloader that can map your namespaces to actual paths and include the class files before you're creating an instance of them. Take a look at the commonly used PSR-0 autoloader. <?php function autoload($className) { $className = ltrim($className, '\\'); $fileName = ''; $namespace = ''; if ($lastNsPos = strrpos($className, '\\')) { $namespace = substr($className, 0, $lastNsPos); $className = substr($className, $lastNsPos + 1); $fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR; } $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; require $fileName; } spl_autoload_register('autoload'); If you include this code in /var/www/html/project/example.php, what happens then when you try to make an instance $redis = new \file\library\storage\redis\Redis(); Is that it will try to include this file first /var/www/html/project/file/library/storage/redis/Redis.php A: You should include the file that contains the class. You can do it manually using: require_once 'redis.php' OR create a rontina autoload as stated in the first answer
{ "language": "en", "url": "https://stackoverflow.com/questions/16779484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How i can create a simple search using MATCH/AGAINST? I have modified my mysql table from InnoDB to MyISAM and then i have added FULLTEXT using this sentence : ALTER TABLE personal ADD FULLTEXT(personal_name,surname,initials,email,telephone,adegree); In my application, i have 6 input fields like these: - id -personal_name -surname -initials -email -telephone and 1 select field like this: -adegree As you know , i have to retrieve information acording these fields, so how i can to do using MATCH/AGAINST ? , if not is possible using MATCH/AGAINS for a multiple search, i'm available to implement any other way. I have used the %LIKE% sentence, but it doesn't work good, here is the code: file: searchUser.php $(document).ready(function(){ $("#search").on("click",function(e){ e.preventDefault(); $.ajax({ dataType:'html', type: "POST", url: "processarSearchUser.php", data: dades , success: function(data){ $("#contenidor").show("500",function(){ $("#contenidor").html(data); }) }//succes });//ajax });//search });//document <form name="formulariFilter" id="formulariFilter" method="post" enctype="multipart/form-data"> <h1>Search User</h1> <tr> <td><b>id:</b></td> <td><input type="text" name="id" id="id"></td> </tr> <tr> <td><b>Personal name:</b></td> <td><input type="text" name="personalname" id="personalname" ></td> </tr> <tr> <td><b>Surname:</b></td> <td><input type="text" name="surname" id="surname" ></td> </tr> <tr> <td><b>Initials:</b></td> <td><input type="text" name="initials" id="initials" ></td> </tr> <tr> <td><b>Email:</b></td> <td><input type="text" name="email" id="email" ></td> </tr> <tr> <td><b>Telephone:</b></td> <td><input type="text" name="telephone" id="telephone" ></td> </tr> <tr> <td><b>Academic degree:</b></td> <td><select name="adegree" id="adegree"> <option value="0">---Select something---</option> <?php $consulta= mysqli_query($conexio, "SELECT adegree from personal" ); while($fila=mysqli_fetch_assoc($consulta)){ echo"<option value='".$fila['adegree']."'/>"."<b>".$fila['adegree']."</b>"."</option>"; } ?> </select></td> <!--<td><input type="text" name="adegree" id="adegree" ></td>--> </tr> <tr> <td colspan="2" id="td_boto"><input type="button" name="search" id="search" value="SEARCH" ></td> </tr> </form> file : processarSearchUser.php <?php if ($_SERVER['REQUEST_METHOD'] == 'POST'){ include("../Projecte Bonita/conectar.php"); $conexio=conectar_bd(); $id = mysqli_real_escape_string($conexio,addslashes($_POST['id'])); $personalname = mysqli_real_escape_string($conexio,addslashes($_POST['personalname'])); $surname = mysqli_real_escape_string($conexio,addslashes($_POST['surname'])); $initials = mysqli_real_escape_string($conexio,addslashes($_POST['initials'])); $email = mysqli_real_escape_string($conexio,addslashes($_POST['email'])); $telephone = mysqli_real_escape_string($conexio,addslashes($_POST['telephone'])); $adegree = mysqli_real_escape_string($conexio,addslashes($_POST['adegree'])); /*$sql="SELECT applus_code,personal_name,surname,initials,email,telephone,adegree from personal WHERE id LIKE '%".$id."%' or personal_name LIKE '%".$personalname."%' or surname LIKE '%".$surname."%' or initials LIKE '%".$initials."%' or email LIKE '%".$email."%' or telephone LIKE '%".$telephone."%' or adegree LIKE '%".$adegree."%'";*/ if($adegree != 0){ $sql="SELECT * from personal WHERE id LIKE '%".$id."%' and personal_name LIKE '%%' and surname LIKE '%".$surname."%' and initials LIKE '%".$initials."%' and email LIKE '%".$email."%' and telephone LIKE '%".$telephone."%' and adegree LIKE '%".$adegree."%'"; } else{ $sql="SELECT * from personal WHERE id LIKE '%".$id."%' and personal_name LIKE '%%' and surname LIKE '%".$surname."%' and initials LIKE '%".$initials."%' and email LIKE '%".$email."%' and telephone LIKE '%".$telephone."%' "; } $consulta= mysqli_query($conexio,$sql); $resultat=mysqli_fetch_assoc($consulta); if($consulta){ if(mysqli_num_rows($consulta) >0){ if(!empty($resultat)){ echo "<table id='reultat' class='taula'>"; echo"<thead>"; echo "<tr>"; echo"<th>id</th>"; echo"<th>Personal name</th>"; echo"<th>Surname</th>"; echo"<th>Initials</th>"; echo"<th>Email</th>"; echo"<th>Telephone</th>"; echo"<th>Adegree</th>"; echo"</tr>"; echo"</thead>"; echo"<tbody"; while($fila=mysqli_fetch_assoc($consulta)){ echo"<tr>"; echo "<td>".$fila['id']."</td>"; echo "<td>".$fila['personal_name']."</td>"; echo "<td>".$fila['surname']."</td>"; echo "<td>".$fila['initials']."</td>"; echo "<td>".$fila['email']."</td>"; echo "<td>".$fila['telephone']."</td>"; echo "<td>".$fila['adegree']."</td>"; echo"</tr>"; } echo "</tbody>"; echo "<table>"; liberar($consulta); desconectar_bd($conexio); } else{ echo"<table id='resultat'class='noResults' align='center'>"; echo"<tr>"; echo"<td>No results!</td>"; echo"</tr>"; echo"</table>"; } } else{ echo"<table id='resultat'class='noResults' align='center'>"; echo"<tr>"; echo"<td>No results!</td>"; echo"</tr>"; echo"</table>"; } } else{ echo"<table id='resultat'class='noResults' align='center'>"; echo"<tr>"; echo"<td>Query error!</td>"; echo"</tr>"; echo"</table>"; } } else{ echo"no post"; } ?> A: I recently added a search feature to one of my websites using the LIKE function. When I submit my search form via GET, I build the database query string based on those variables that are passed with the form. if(strcmp($_GET['SSeries'],'') != 0) { $searchString .= "Series LIKE '%".$_GET['SSeries']."%' AND "; $uFriend .= "Series CONTAINS '".$_GET['SSeries']."' AND "; } if(strcmp($_GET['SModel'],'') != 0) { $searchString .= "Model LIKE '%".$_GET['SModel']."%' AND "; $uFriend .= "Model CONTAINS '".$_GET['SModel']."' AND "; } if(strcmp($_GET['SSerial'],'') != 0) { $searchString .= "Serial LIKE '%".$_GET['SSerial']."%' AND "; $uFriend .= "Serial CONTAINS '".$_GET['SSerial']."' AND "; } $_SESSION['searchString'] = $searchString; then at the end, declare a variable that connects them all together. Then, I just use that variable in my search string like so: if(empty($_SESSION['searchString'])) { $sql = "SELECT * from identification;"; $sqluFriend = "Search ALL"; } else { $sql = "SELECT * from identification WHERE ".substr($_SESSION['searchString'], 0, -5).";"; $sqluFriend = "Search ".substr($_SESSION['uFriend'], 0, -5).""; } If the search string is empty, I create a query that has no where clause. Also, note the use of the substr() method used, as removes the last 5 symbols from the search string (Basically so the string doesn't end with AND as that would cause issues with the query.) Also, you can ignore the $sqluFriend variables, I use those to display a user friendly version of the query. Basically, as shown above, I build the search string depending on if the GET variable is posted, it makes it a dynamic search query. Another thing is you should wrap your $searchString builder with if statements that check if any of the data is posted, to avoid errors/return error codes etc. Here is how I did that: if((isSet($_GET['SSSeries'])) || (isSet($_GET['SSModel'])) || (isSet($_GET['SSSerial']))) { You can of course expand this to meet your needs fairly easily. What I did was connected my form to an ajax request every time an input was changed, so that when someone entered anything it would automatically reload the table with the results. Hope I could help.
{ "language": "en", "url": "https://stackoverflow.com/questions/37009862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use a class library DLL hosted on an ASPX webpage I'm developing a webpage using the ASP.net Framework 4.0, C# and I got a DLL from a class Library. The function of this DLL is to activate and read information from a hardware CARD-READER (Client side) then I want to send the information to the server. How can I use this DLL from a ASPX webpage? A: Copy the downloaded DLL file in a custom folder on your drive, hopefully at the root of your solution maybe in a libs folder, then add the reference to your project using the Browse button in the Add Reference dialog. Make sure that the new reference has Copy Local = True set within its properties once added to the solution, which is found when un-collapsing and right-clicking on the References item in your project within Solution Explorer. A: You can host it creating a XBAP, silverlight or clickonce application. The created application will run clientside. Hope this helps. Regards.
{ "language": "en", "url": "https://stackoverflow.com/questions/31330365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use .htaccess to restrict script access from external server i am trying to achieve this: i have a directory/folder in my primary domain example.com/scripts. the folder named script should only be accessed by websites that are subdomain of example.com which means that from any of these websites: admin.example.com, people.example.com, etc.example.com, example.com their pages should be able to call scripts or anything in the /scripts directory e.g <script src="https://example.com/scripts/js/demo.js" charset="utf-8"></script> or <link rel="stylesheet" href="https://example.com/scripts/css/demo.css"> if for instance a page from anotherdomain.com try to access the /scripts directory, the server responds with 404. Please help! thanks. A: You follow a completely wrong approach. Do not first publish something and then try to hold it back. You will never be able to really secure that. Instead use a routing endpoint in those "subdomain hosts", thus being able to limit the access to that folder to a single IP address, your own system. So that from a client side perspective the browser requests the script from the websites own "subdomain" which in turn internally re-routes the request to that folder / host / whatever. There are many solutions for that. Any many explanations of how to do that are found on the internet. According to your description you have a very simple setup, so do not require any special logic in such routing logic. Instead you want a simple and static mapping. Easiest would be to do that on the level of the http server itself. If you have the proxy module loaded, then you can do something like that to implement a simple forward proxy: ProxyPass /scripts/ http://example.com/scripts/ If it is not only scripts served from http://example.com/scripts/ but also something holding back references then you need to setup a reverse proxy: ProxyPass /scripts/ http://example.com/scripts/ ProxyPassReverse /scripts/ http://example.com/scripts/ Best is to place such definitions in the http server configurations of the "subdomains". You can also use dynamic configuration files for such stuff, but that has many disadvantages. As said there are other solutions. For example you can implement a simple router script, that allows fine tuned authorization management and the like. But you apparently don't need that. The main goal of all this is: * *do not publish anything from http://example.com directly, so block access to it except for the subdomains http server(s). *make all client side requests from your "webpages" point to the http host they were served from, so the subdomains http hosts. The official documentation of the apache http server contains all the information you need. It is of excellent quality and comes with good examples.
{ "language": "en", "url": "https://stackoverflow.com/questions/48963252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to have not formatted text block in Asciidoc? Does it exist in Asciidoc (rendered by Asciidoctor) a way to have a block of text where asciidoc formatting is not applied, but it keeps the asciidoc paragraph format (background color, font, font color, etc...) and not preformated format ? My specific problem I have a paragraph that I want to render "as I type it" Array(Element1, Element2, Element3) Currently, it renders as follow: And I want to render it as follow: What I've tried so far I tried to use code block or literal block, but text appears as preformated, which I don't want: ---- Array( Element1, Element2, Element3 ) ---- Or [literal] .... Array( Element1, Element2, Element3 ) .... Gives me the following output: A: I managed to get what I want by using [%hardbreaks] option to keeping line breaks and by using {nbsp} built-in attribute for non-breaking spaces. Here is the complete code: [%hardbreaks] Array( {nbsp}{nbsp}Element1, {nbsp}{nbsp}Element2, {nbsp}{nbsp}Element3 )
{ "language": "en", "url": "https://stackoverflow.com/questions/69480923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: React Router Redirect does not render the component Here is my App.js: function App() { return ( <BrowserRouter> <AuthProvider> <Switch> <PrivateRoute path="/" component={MainPage} /> <PrivateRoute path="/admin" component={MainPage} /> <Container className="d-flex align-items-center justify-content-center" style={{ minHeight: "100vh" }} > <div className="w-100" style={{ maxWidth: "400px" }}> <Route path="/signup" component={Signup} /> <Route path="/login" component={Login} /> //The component part <Route path="/forgot-password" component={ForgotPassword} /> </div> </Container> </Switch> </AuthProvider> </BrowserRouter> ); } Auth Context for PriveRoute Component from firebase: export default function PrivateRoute({ component: Component, ...rest }) { const { currentUser } = useAuth(); return ( <Route render={(props) => { return currentUser ? <Admin {...props} /> : <Redirect to="/login" />; // it redirects when the user does not log in. }} ></Route> ); Login Component: export default function Login() { const emailRef = useRef(); const passwordRef = useRef(); const { login, currentUser } = useAuth(); const [error, setError] = useState(""); const [loading, setLoading] = useState(false); const history = useHistory(); if (currentUser) { history.push("/admin/mainpage"); } async function handleSubmit(e) { e.preventDefault(); try { setError(""); setLoading(true); await login( emailRef.current.value + "@myosmail.com", passwordRef.current.value ); history.push("/admin/mainpage"); } catch { setError("Failed to log in"); } setLoading(false); } return ( <> <Card> <Card.Body> <h2 className="text-center mb-4">Log In</h2> {error && <Alert variant="danger">{error}</Alert>} <Form onSubmit={handleSubmit}> <Form.Group id="email"> <Form.Label>Username</Form.Label> <Form.Control ref={emailRef} required /> </Form.Group> <Form.Group id="password"> <Form.Label>Password</Form.Label> <Form.Control type="password" ref={passwordRef} required /> </Form.Group> <Button disabled={loading} className="w-100" type="submit"> Log In </Button> </Form> <div className="w-100 text-center mt-3"> <Link to="/forgot-password">Forgot Password?</Link> </div> </Card.Body> </Card> <div className="w-100 text-center mt-2"> Need an account? <Link to="/signup">Sign Up</Link> </div> </> ); } I want to build a component if the user does not logged in, it can not access to content of my web site so I build the component above. But the problem is that when I opened my page and does not logged in the page redirect me to "/login" but the Login component does not be rendered I do not understand what is the problem. I debugged my component and I saw that my code firstly goes to PrivateRoute component after that it redirected to "/login" but nothing rendered when the page redirected to Login. When I removed PrivateRoutes from App.js my code worked correctly. A: Issue My guess is that you've placed a "/" path first within the Switch component: <PrivateRoute path="/" component={MainPage} /> The redirect to "/login" works but then the Switch matches the "/" portion and tries rendering this private route again. Your private route is also malformed, it doesn't pass on all the Route props received. Solution Fix the private route component to pass on all props. export default function PrivateRoute({ component: Component, ...rest }) { const { currentUser } = useAuth(); return ( <Route {...rest} render={(props) => { return currentUser ? <Admin {...props} /> : <Redirect to="/login" />; }} /> ); } Within the Switch component path order and specificity matter, you want to order more specific paths before less specific paths. "/" is a path prefix for all paths, so you want that after other paths. Nested routes also need to be rendered within a Switch so only a single match is returned and rendered. <BrowserRouter> <AuthProvider> <Switch> <Container className="d-flex align-items-center justify-content-center" style={{ minHeight: "100vh" }} > <div className="w-100" style={{ maxWidth: "400px" }}> <Switch> <Route path="/signup" component={Signup} /> <Route path="/login" component={Login} /> //The component part <Route path="/forgot-password" component={ForgotPassword} /> </Switch> </div> </Container> <PrivateRoute path={["/admin", "/"]} component={MainPage} /> </Switch> </AuthProvider> </BrowserRouter> Update I'm a bit confused by your private route though, you specify the MainPage component on the component prop, but then render an Admin component within. Typically an more agnostic PrivateRoute component may look something more like: const PrivateRoute = props => { const { currentUser } = useAuth(); return currentUser ? <Route {...props} /> : <Redirect to="/login" />; } This allows you to use all the normal Route component props and doesn't limit to using just the component prop. Usages: * * <PrivateRoute path="/admin" component={Admin} /> * <PrivateRoute path="/admin" render={props => <Admin {...props} />} /> * <PrivateRoute path="/admin"> <Admin /> </PrivateRoute> A: I also had same problem once. This solved me. Wrap your three routes with a Switch. <Switch> <Route path="/signup" component={Signup} /> <Route path="/login" component={Login} /> <Route path="/forgot-password" component={ForgotPassword} /> </Switch> As the first private route has the root path it will always go to the route. You can use exact for the first private route. But the best way should be placing the first private route <PrivateRoute path={["/admin", "/"]} component={MainPage} /> at the bottom. So that when there is no match it goes there only. A: You are not passing the path to the Route in the ProtectedRoute . <Route {...rest} // spread the test here render={(props) => { return currentUser ? <Admin {...props} /> : <Redirect to="/login" />; // it redirects when the user does not log in. }} ></Route> Also switch the Route of the path as @Drew Reese mentioned .
{ "language": "en", "url": "https://stackoverflow.com/questions/67847161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: inserting data into table from text file with a foreign key I have two tables, people and registration. people table contains - idpeople, name and email columns registration table contains - idregistration, country, registered, people_idpeople I loaded data into the first table via text file and every thing went well. But when trying to add data into registration table I get "error 1452" which is a foreign key restraint. what does my text file need to look like so that I can load data into it and it relate to the people table? heres what the overall text data looks like, but i had to break it down for each table: Email,Full Name,Country,Date Registered Carley_Bahringer@destiny.com,Carley Bahringer,Papua New Guinea,1987-10-03 22:09:54 Patricia_Fadel@avis.com,Patricia Fadel,Saint Lucia,2012-05-10 11:07:49 Sedrick@godfrey.ca,Sedrick Kuphal,Chile,2007-11-12 00:09:53 Briana_Berge@axel.ca,Briana Berge,Nicaragua,2006-03-26 15:32:08 Lucy_Lockman@abby.org,Lucy Lockman,Iceland,2014-02-13 10:26:57 Lucy_Lockman@abby.org,Lucy Lockman,Germany,1999-02-12 00:14:54 Ayden_Flatley@colin.biz,Ayden Flatley,France,1987-01-23 21:43:22 Alec.Boyle@aurore.co.uk,Alec Boyle,Brazil,2007-08-23 13:42:41 Ozella_Feil@prudence.ca,Ozella Feil,Lesotho,2005-12-30 18:24:59 Ozella_Feil@prudence.ca,Ozella Feil,Sweden,2009-06-19 10:32:55 for the people table I edited the above info so it just contained name and email. What do i do to load the rest of the info into registration table? A: No, since you have people_idpeople as FK in Registration table; you need to provide that information as well else you will see the error you are facing currently. Your data should look like (Example) Email,Full Name,Country,Date Registered,idpeople Carley_Bahringer@destiny.com,Carley Bahringer,Papua New Guinea,1987-10-03 22:09:54, 1
{ "language": "en", "url": "https://stackoverflow.com/questions/34245335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to implement Queue in Java? I have a folder with 1 ThMapInfratab1-2.exe file and 3 .txt files. If you run .exe file in any way(through command prompt,just double click and through any language) one Icon will be appear on Taskbar. My .exe will be run 2-3 minutes. Know I want to run these .exe file using Java.I found How to run .exe from Java technology. My concept was, first I will find .txt file Names from the directory.finally I will get like this. List<File> fileNames={"File1.txt","File2.txt","File3.txt"}; Know I want to run my .exe file 3 times because my fileNames length is equals to 3.For this I wrote the following code. //ExeFileProcess Function public void ExeternalFileProcessing(String DirectoryPath,String exeFileName,String inputFileName) throws IOException { String executableFileName = DirectoryPath+"/"+exeFileName; String inputFile=inputFileName; ProcessBuilder processBuilderObject=new ProcessBuilder(executableFileName,inputFile); File absoluteDirectory = new File(DirectoryPath); processBuilderObject.directory(absoluteDirectory); processBuilderObject.start(); //processBuilderObject.wait(); } //Main Function code. public static void main(String[] args) throws IOException { ExternalFileExecutions ExternalFileExecutionsObject=new ExternalFileExecutions(); for (int fileIndex = 0; fileIndex < fileNames.size(); fileIndex++) { ExternalFileExecutionsObject.ExeternalFileProcessing("C:/Users/Infratab Bangalore/Desktop/Rod","ThMapInfratab1-2.exe",fileNames[fileIndex ]); } } I evaluated above code, at a time 3 .exe processes are started.But I don't want like that. I want to run .exe file one by one(we need to monitor, whether the previous .exe process was done or not. once it's done it allows to next Iteration). I tried with Wait().but it's not working. I guess, for this I need to add some code in my ExeternalFileProcessing(). But I didn't get anything. can anyone suggest me. I hope, you understand, what My problem. A: ProcessBuilder.start method returns an instance of Process class. YOu can use waitFor method to wait until created process stops: ... Process process = processBuilderObject.start(); process.waitFor(); } processBuilderObject.wait() is a invocation of Object's wait method. It is used for concurrency and doesn't relate to processes at all.
{ "language": "en", "url": "https://stackoverflow.com/questions/17836875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pact - contract testing - verify consumer and producer against contract I have made demo application for Pact-Contract testing. Following is the link, I referred. I have change few things out of that like patternmatcher and bodytype. https://www.javacodegeeks.com/2017/03/consumer-driven-testing-pact-spring-boot.html I am able to publish pact from consumer and verify it from provider side. I have been asked to verify pact from consumer end as well. E.g. consumer posts following json to provider for creating new user. { "address": { "city": "string", "houseNumber": 0, "postalCode": "string", "street": "string" }, "name": "string", "registrationId": 0, "surname": "string" } But now consumer changes the model classes. (as it is also provider for some other service. it might be possible to get request to change change contract). Following is the new request json that will be generated. { "address": { "city": "string", "houseNumber": 0, "postalCode": "string", "street": "string" }, "firstname": "string", "registrationId": 0, "surname": "string" } As the request object is changed. If I verify consumer against pact. It should fail. Problem: When I run mvn:verify from consumer, it is always OK. I want it to fail. P.S. Let me know if it is not correct way of doing it. A: The consumer test is analogous to a unit test. It will always pass if your code does what you expect it to in the test. It isn't dependent on prior state (such as a previous generated contract). The part of the process where you would check for a breaking change is in CI with the can I deploy tool (https://docs.pact.io/pact_broker/can_i_deploy).
{ "language": "en", "url": "https://stackoverflow.com/questions/63409498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to save the file that is being opened? I have a macro that works for one particular file. How can I make it work for all my files? Specifically how do I change the name of the file so that it saves the file that is being opened? Sub Macro1() ' ' Macro1 Macro ' ' Keyboard Shortcut: Ctrl+m ' Range("A:A,B:B").Select Range("B1").Activate ActiveSheet.Shapes.AddChart.Select ActiveChart.ChartType = xlLineStacked ActiveChart.SetSourceData Source:=Range( _ "'cwapp5_MemCPU-Date-Mem'!$A:$A,'cwapp5_MemCPU-Date-Mem'!$B:$B") ChDir "D:\WayneCSV" ActiveWorkbook.SaveAs Filename:="D:\WayneCSV\cwapp5_MemCPU-Date-Mem.xlsx", _ FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False End Sub A: With ActiveSheet.Shapes.AddChart .ChartType = xlLineStacked .SetSourceData Source:=Range( _ "'cwapp5_MemCPU-Date-Mem'!$A:$A,'cwapp5_MemCPU-Date-Mem'!$B:$B") End With ChDir "D:\WayneCSV" ActiveWorkbook.SaveAs Filename:="D:\WayneCSV\" & *YourFileNameHere* &".xlsx", _ FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False Replace the YourFileNameHere with the name you'd like to save the file with. Or if you want to simply save the active workbook with the change ActiveWorkbook.SaveAs Filename:=ThisWorkbook.FullName, _ FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False If you want to loop through all possible workbook or file inside of "D:\WayneCSV" just tell me what you mean by make it work for all my files? weather that means open excel sheets, or workbook, or all files with extension of *.xlsx inside of "D:\WayneCSV" Edit: Dim StrFile As String StrFile = Dir("D:\WayneCSV\*.CSV") ' Looks up each file with CSV extension Do While Len(StrFile) > 0 ' While the file name is greater then nothing Workbooks.Open Filename:= "D:\WayneCSV\" & StrFile ' Open current workbook ActiveSheet.Shapes.AddChart.Select ' Add a chart ActiveChart.ChartType = xlLineStacked ' Add a chart type ActiveChart.SetSourceData Source:=Range("$A1:$B1", Range("$A1:$B1").End(xlDown)) ' Set the source range to be the used cells in A:B on the open worksheet With ActiveChart.Parent .Height = .Height*1.5 'Increase Height by 50% .Width = .Width*1.5 'Increase Width by 50% End With 'Note the setting of the source will only work while there are no skipped blank if you 'have empty rows in the source data please tell me and i can provide you with another ' way to get the information ActiveWorkbook.SaveAs Filename:="D:\WayneCSV\" & StrFile & ".xlsx", _ FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False ' Save file as excel xlsx with current files name ActiveWorkbook.Close ' Close when finished before opening next file this can be removed if you'd like to keep all open for review at the end of loop. StrFile = Dir ' Next File in Dir Loop Let me know if it works as I can't test without your folders and data. But it should work. A: where it is written Filename:="D:\WayneCSV\cwapp5_MemCPU-Date-Mem.xlsx" that's your filename you could replace it with ThisWorkbook.FullName it should work So it should give you something like this. Filename:=ThisWorkbook.FullName, Also I don't understand that part ChDir "D:\WayneCSV" Why put the path then the full name I'm more an access programmer than an excel one so I could be wrong. A: Check out this SO link I think what you want to do is replace :="D:\WayneCSV\cwapp5_MemCPU-Date-Mem.xlsx" with ActiveWorkbook.FullName in ActiveWorkbook.SaveAs line A: Your macro, from what I can tell, is adding a chart based off of some data and saving the sheet. That is a very specialized Macro, but you would need to change the directory as others listed to a directory on your local drive but you also need to find out where the data you are creating a chart for is being stored. Sub Macro1() ' ' Macro1 Macro ' ' Keyboard Shortcut: Ctrl+m ' '<<< This is the naming convention and hotkey if you goto Tools > Macros in Excel 2003 or Developer > Macros in 2010 'Range("A:A,B:B").Select '<<< This is where you are selecting all data in columns A and B and is not needed so I commented it out 'Range("B1").Activate '<<< This code is 'activating' a cell, but not sure why, so I commented it out as it should not be needed ActiveSheet.Shapes.AddChart.Select '<<< You are adding a chart here ActiveChart.ChartType = xlLineStacked '<<<Defining a chart type ActiveChart.SetSourceData Source:=Range( _ "'cwapp5_MemCPU-Date-Mem'!$A:$A,'cwapp5_MemCPU-Date-Mem'!$B:$B") '<<< Setting it's source data from a worksheet called 'cwapp5_MemCPU-Date-Mem' with header information from Column B and Data from Column A ChDir "D:\WayneCSV" ActiveWorkbook.SaveAs Filename:="D:\WayneCSV\cwapp5_MemCPU-Date-Mem.xlsx", _ FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False '<<< You are saving a copy of your workbook End Sub To make this work for other workbooks you need to rename all of the ranges to where your data is, rename the tabs to what you have your tabs named, and rename the WorkBook to what you want it saved as and where.
{ "language": "en", "url": "https://stackoverflow.com/questions/15911284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to create a regular expression to search for a substring with numbers? There are lines with a title element and a value element, with a symbol --> is indicated what values I need to get: BATE Borisov BATE Borisov -0.5, -1.0 --> -0.5, -1.0 Under 2.5 --> 2.5 BATE Borisov BATE Borisov 0.0, -0.5 --> 0.0, -0.5 Over 1.0 --> 1.0 BATE Borisov -2.5 --> -2.5 Over 1.5 --> 1.5 Over 2.0, 2.5 --> 2.0, 2.5 Over 2.5 --> 2.5 Over 3.5 --> 3.5 Under 2.5 & yes I wrote the following expression: ((\s|\W)\d+?.+?)(^\..|$) In most cases, it works, except for the last line Under 2.5 & Yes, here it finds 2.5 & Yes, although this is also part of the header. Can I somehow indicate in the regular expression that all characters in it should be only numbers or not letters? A: You could get all the digits till you reach the end of the string $ which will prevent matching the line ending with & yes -?\d+(?:\.\d+)?(?:, -?\d+(?:\.\d+)?)*$ Explanation * *-?\d+(?:\.\d+)? Match 1+ digits with an optional decimal value *(?: Non capture group * *, -?\d+(?:\.\d+)? Match a comma, space and a digit with an optional decimal value *)* Close group and repeat 0+ times *$ End of string Regex demo | Python demo Example code import re strings = [ "BATE Borisov", "BATE Borisov -0.5, -1.0", "Under 2.5", "BATE Borisov", "BATE Borisov 0.0, -0.5", "Over 1.0", "BATE Borisov -2.5", "Over 1.5", "Over 2.0, 2.5", "Over 2.5", "Over 3.5", "Under 2.5 & yes" ] regex = r"-?\d+(?:\.\d+)?(?:, -?\d+(?:\.\d+)?)*$" for s in strings: matches = re.search(regex, s) if matches: print(matches.group()) Output -0.5, -1.0 2.5 0.0, -0.5 1.0 -2.5 1.5 2.0, 2.5 2.5 3.5 A: You may use the following regex to match a CSV list of positive/negative floats: \b-?\d+(?:\.\d+)?(?:, -?\d+(?:\.\d+)?)* Sample scripts: inp = "BATE Borisov -0.5, -1.0" matches = re.findall(r'\b-?\d+(?:\.\d+)?(?:, -?\d+(?:\.\d+)?)*', inp) print(matches) This prints: ['0.5, -1.0'] inp = "Under 2.5 & yes" matches = re.findall(r'\b-?\d+(?:\.\d+)?(?:, -?\d+(?:\.\d+)?)*', inp) print(matches) This prints: ['2.5']
{ "language": "en", "url": "https://stackoverflow.com/questions/61983474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use flex-wrap? I have some boxes which I want laid out 3 x 3 instead of 5 x 5. They are displayed using flex-wrap and I was was wondering if I could use adjust it somehow to alter the size and layout so that each box is the same size and in proportion-eg images all the same size etc. The following is pasted in my header.php so as to specify a specific page and not effect other elements. Css: <style> @media (min-width:768px) { .entry-content .event_listings { display: flex; flex-wrap: wrap; } } @media (min-width: 768px) { .entry-content .event_listings .event_listing { width: 20%; padding: 0 20px; } } @media (min-width: 768px) { .entry-content .event_listings .event_listing .box-layout { width: 100%; float: none; height: 100%; } } @media (min-width: 768px) { .entry-content .event_listings .event_listing .box-layout { display: flex; flex- direction: column; } } @media (min-width: 768px) { .entry. content .event_listings .event_listing .box-layout .event. title { flex-grow: 1; } } </style> Can this be adjusted to achieve what I want? Html: <div class="line-layout" style="display: none;"> <li class="event_listing post-6985 type-event_listing status-expired hentry" style="visibility: visible;" data-latitude="" data- longitude=""> <div class="event-info-row-listing"> <a href="https://adsler.co.uk/event/new-cross-and-deptford-free-film-festival/"> <div class="row"> <div class="col-md-1"> <div class="organizer-logo"> <img alt="Deptford Film Festival" src="https://adsler.co.uk/wp-content/uploads/event-manager. uploads/event_banner/2019/05/2456d41f16399aed538d25b1cd32ad14.jpg"> </div> </div> <div class="col-md-4"> <div class="event-title"> <h4>New Cross and Deptford Free Film Festival</h4> <div class="boxes-view-listing-registered- code"> </div> <div class="event-organizer-name"> <normal>Deptford Film Festival <normal></normal> </normal> </div> </div> <div class="col-md-2"> <div class="date" <date>2019-05- 26</date> </div> </div> <div class="col-md-3"> <div class="event-location"> <i class="glyphicon glyphicon-map-marker"></I> London </div> </div> <div class="col-md-2"> <div class="event ticket">#free</div> </div> <div class="col-md-3"></div> </div> </div> </a> </div> </li> <!-- Box Layout --> <a class="event_listing post-6985 type-event_listing status-expired hentry" href="https://adsler.co.uk/event/new-cross-and-deptford- free-film-festival/"> <div class="box-layout"> <div class="event-img"><img alt="Deptford Film Festival" src="https://adsler.co.uk/wp-content/uploads/event-manager. uploads/event_banner/2019/05/2456d41f16399aed538d25b1cd32ad14.jpg"> </div> <div class="boxes-view-box-registered-code"></div> <div class="event-title"> New Cross and Deptford Free Film Festival </div> <div class="event-start-date">2019- 05-26</div> <div class="event-location"> <i class="glyphicon glyphicon-map-marker"></i> London </div> <div class="box-footer"> <div class="event-ticket">#free</div> </div> </div> </a> </div> Page: https://adsler.co.uk/find-an-event/
{ "language": "en", "url": "https://stackoverflow.com/questions/56618954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is JavaMail not listing the emails even though mails are present in the mailbox? I'm using JavaMail API 1.5.3 version to fetch emails from a mailbox using IMAP. There are nearly 500 plus emails in the mailbox but the JavaMail API does not list any of them. I configured an outlook client and the emails are downloaded there properly. Below is the debug trace: DEBUG: JavaMail version 1.5.3 DEBUG: successfully loaded resource: /META-INF/javamail.default.providers DEBUG: Tables of loaded providers DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle]} DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]} DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map DEBUG: getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle] DEBUG IMAP: mail.imap.fetchsize: 16384 DEBUG IMAP: mail.imap.ignorebodystructuresize: false DEBUG IMAP: mail.imap.statuscachetimeout: 1000 DEBUG IMAP: mail.imap.appendbuffersize: -1 DEBUG IMAP: mail.imap.minidletime: 10 DEBUG IMAP: closeFoldersOnStoreFailure DEBUG: setDebug: JavaMail version 1.5.3 DEBUG IMAP: trying to connect to host "< mail server nane >", port 993, isSSL true * OK [CAPABILITY IMAP4rev1 LITERAL+ ID ENABLE AUTH=PLAIN SASL-IR] server ready DEBUG IMAP: AUTH: PLAIN DEBUG IMAP: protocolConnect login, host=<mail server name>, user=<username>, password=<non-null> DEBUG IMAP: AUTHENTICATE PLAIN command trace suppressed DEBUG IMAP: AUTHENTICATE PLAIN command result: A0 OK [CAPABILITY IMAP4rev1 LITERAL+ ID ENABLE ACL RIGHTS=kxte QUOTA MAILBOX-REFERRALS NAMESPACE UIDPLUS NO_ATOMIC_RENAME UNSELECT CHILDREN MULTIAPPEND BINARY CATENATE CONDSTORE ESEARCH SORT SORT=MODSEQ SORT=DISPLAY THREAD=ORDEREDSUBJECT THREAD=REFERENCES ANNOTATEMORE LIST-EXTENDED WITHIN QRESYNC SCAN XLIST URLAUTH URLAUTH=BINARY X-NETSCAPE LOGINDISABLED COMPRESS=DEFLATE IDLE] Success (tls protection) SESSIONID=<netserv-28720-1540905648-1> DEBUG IMAP: connection available -- size: 1 A1 SELECT INBOX * 0 EXISTS * 0 RECENT * FLAGS (\Answered \Flagged \Draft \Deleted \Seen) * OK [PERMANENTFLAGS (\Answered \Flagged \Draft \Deleted \Seen \*)] Ok * OK [UIDVALIDITY 1519903897] Ok * OK [UIDNEXT 274] Ok * OK [HIGHESTMODSEQ 437] Ok * OK [URLMECH INTERNAL] Ok A1 OK [READ-WRITE] Completed A2 SEARCH UNSEEN ALL * SEARCH A2 OK Completed (0 msgs in 0.000 secs) A3 SEARCH UNSEEN ALL * SEARCH A3 OK Completed (0 msgs in 0.000 secs) A4 CLOSE A4 OK Completed DEBUG IMAP: added an Authenticated connection -- size: 1 DEBUG IMAP: IMAPProtocol noop A5 NOOP A5 OK Completed A6 LOGOUT * BYE LOGOUT received A6 OK Completed DEBUG IMAP: IMAPStore connection dead DEBUG IMAP: IMAPStore cleanup, force false DEBUG IMAP: IMAPStore cleanup done Could someone point out what could be the issue? A: This pretty much unambiguously says the server says the server has no messages in the INBOX: A1 SELECT INBOX * 0 EXISTS * 0 RECENT Either they are in another folder, or they are in another account.
{ "language": "en", "url": "https://stackoverflow.com/questions/53067081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: react select - buffer onChange event I would need to pause the onChange for the react-select component until the data is loaded into options. How could that be? const handleSearch = () => { // call data to redux and add to function getOptions (THIS WORK OK - this doesn't interest me) } const handleSelect = () => { // need pause event while handleSearch is completed // **how to do this** } <Select ... isLoading={isSearching} onInputchange={handleSearch} onChange={handleSelect} options={getOptions} ... /> A: Create new state to detect whether handle search is completed or not. const [isHandleSearchComplete, markHandleSearchAsComplete] = useState(false); const handleSearch = () => { getOptions().then((res) => { // do something here markHandleSearchAsComplete(true) }) } const handleSelect = () => { // if handle search is complete then stop the process if (isHandleSearchComplete) { return } // otherwise, do something }
{ "language": "en", "url": "https://stackoverflow.com/questions/60325184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How do I write to Excel cells so that they are formatted correctly with hidden "tick" marks I have to replace a broken SSIS package that basically just combines the data from a number of different Excel files, and creates a single master file. My C# desktop application is putting all the data into the Excel file correctly, but the one problem is that the original file, which was of type .xls, has some kind of hidden formatting on the cells. When you just view the data in the cells, it looks normal, but when you click on a cell and view it in the edit box, there is a tick mark (it looks like this ') in front of the data. Editing it out does nothing, it just reappears. I am guessing it is a "cheater" way to force the data to be of type character, since Excel is such a stinker about turning text which is made up of only numbers into a cell of type number, even if you write it as a string. I wish we could do without it, but when we try to use a file without that formatting, it blows up the application. And I do not have the time or budget to rewrite the application. How can I duplicate this "tick" mark in the files which I am writing? Currently I'm using EPPlus for writing, but I can also use Microsoft.Office.Interop.Excel. If this is too difficult, I would also be open to someone telling me how to manually edit the file after I have created it programatically, and just add the cell formatting to the data.
{ "language": "en", "url": "https://stackoverflow.com/questions/46738384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Selecting from Sqlite db using NHIbernate returns nothing when data is actually present I have a simple app that uses a sqlite db in my data layer, nothing major. I have populated a few records for UI testing, but I can't pull the data back at all. The thing is that my my unit tests are able to CRUD without fail, but I'm concerned that something isn't right when I simply want to select all records from a table like to populate a gridview. I'm using NHibernate for the first time in a loooooong time so I can't tell if this s setup issue or something else. Base selection method: protected IList<T> SelectMultipleInternalALL() { // create session and select. using (ISession session = NBHelper.OpenSession()) return session.CreateCriteria<T>().List<T>(); } Helper class: public class NBHelper { private static ISessionFactory _sessionFactory; private static ISessionFactory SessionFactory { get { if (_sessionFactory == null) { var configuration = new Configuration(); configuration.Configure(); configuration.AddAssembly(Assembly.GetCallingAssembly()); new SchemaExport(configuration).Execute(false, true, false); _sessionFactory = configuration.BuildSessionFactory(); } return _sessionFactory; } } public static ISession OpenSession() { return SessionFactory.OpenSession(); } } Table config: <class name="UserData" table="User"> <id name="Id" type="System.Int32" column="Id" > <generator class="native"/> </id> <property name="Email" /> <property name="FirstName" /> <property name="LastName" /> <property name="Notes" /> <property name="Favorite" type="boolean" /> <bag name="Addresses" inverse="true" cascade="all" generic="true"> <key column="UserId" /> <one-to-many class="AddressData"/> </bag> <bag name="Tags" inverse="true" cascade="all" generic="true"> <key column="WhatId" /> <one-to-many class="TagData"/> </bag> NHibernate config: <session-factory> <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property> <property name="connection.driver_class">NHibernate.Driver.SQLiteDriver</property> <property name="connection.connection_string"> Data Source=C:\Documents and Settings\bryang\Desktop\AddressBook\AddressBook.DAL\addressbook.s3db </property> <property name="dialect">NHibernate.Dialect.SQLiteDialect</property> <property name="query.substitutions">true=1;false=0</property> <property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property> <property name="show_sql">true</property> The database location is totally valid, but I get no records. I think the issue might be in the CreateCriteria() call but my unit tests are 100% able to insert and read back the data. I'm missing something and I can't figure out what. EDIT I was also running into a lazy loading exception from my one-to-many relationships. I made the collection columns lazy="false" which cleared up the error. A side-effect is that now I return data everywhere, but it's unit test data from somewhere and when I open the sqlite db I still only see where my small set of data was created. Where is this data being held on to? I'm not managing my ISession manually, and I'm even flushing after simple things like a select. Where on earth is this data coming from? At this point I'll take some data over none, but it makes no sense to me if the db file I'm looking at has nothing in it. Thanks, Bryan A: First of all, change the Driver to the newer version of the driver, the SQLiteDriver is for the old finstar driver, and it has some quirks with the newer version of SQL Lite. Also, your database path needs to be changed, you can't reference a path with spaces without putting "'s around it. If you put your database in the same directory as your executable, you can just use the db name. This configuration works great for me : <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property> <property name="connection.driver_class">NHibernate.Driver.SQLite20Driver</property> <property name="connection.connection_string">Data Source=core.db3;Version=3</property> <property name="dialect">NHibernate.Dialect.SQLiteDialect</property> <property name="query.substitutions">true=1;false=0</property> <property name='proxyfactory.factory_class'>NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property> <property name="show_sql">true</property>
{ "language": "en", "url": "https://stackoverflow.com/questions/6653207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do we assign value for ng-model dynamically through a template url? I am new to angular js.I have written a directive to load the template url and tried changing the ng-model value. But the value doesnt change. I tried simulating this exmaple http://tinyurl.com/hg7ehge except that I was trying to load the html from url. Following is the plunker code: http://tinyurl.com/zwmleec A: To refere model by dynamic name you can isolate scope (scope: true) and use $parent reference to outer scope: .directive('dynamicmodel', function($templateRequest, $compile) { return { replace: true, restrict: 'E', scope: true, link: function(scope, element, attrs) { scope.name = attrs.comm; $templateRequest("template.html").then(function(html) { element.replaceWith($compile(html)(scope)); }); } }; }); and then in template use scope.comm: <input type="text" ng-model="$parent[name].subject" /> Demo: http://plnkr.co/edit/B4HgvxuT1jZJ2H3U9UO9?p=info
{ "language": "en", "url": "https://stackoverflow.com/questions/34472582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: HTTP Error 500 using CE_Image I've recently moved my working site to a staging environment, and now, some channels display an internal server error (500) while others work flawlessly. Nothing appears to have changed. Is there some setting I've missed or might this have to do with a different PHP version on the staging server? Something else? Edit 9/21: I think I've narrowed it down to a CE_Image issue...it occurs on every template using CE_Image Here's an example of some template code that, if removed, causes the errors to go away: {cf_home_slideshow limit="5"} <li data-slide="slide_{row_count}" style="background-image: url({exp:ce_img:pair allow_scale_larger="yes" src="{cf_image}" max_width="956" max_height="429" create_tag="no" crop="yes"}{made}{/exp:ce_img:pair})"> <a href="{cf_link}"><img src="{exp:ce_img:pair allow_scale_larger="yes" src="{cf_image}" max_width="956" max_height="429" create_tag="no" crop="yes"}{made}{/exp:ce_img:pair}" width="956" height="429" /></a> <div class="slide"> {if cf_link} <div class="view_project"> <a href="{cf_link}" class="button">View Project <img src="/assets/imgs/arrow_btn.png"></a> </div> {/if} </div> </li> {/cf_home_slideshow} A: D'oh! Resolved. GD Library wasn't installed. When I installed it, all was well!
{ "language": "en", "url": "https://stackoverflow.com/questions/12458906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# array within an object within an array Here is a simplified version of my code: class House { private string owner; private int[] roomArea = new int[10]; public string Owner { get; set; } public int[] RoomArea { get; set; } } class Program { static void Main(string[] args) { House[] london = new House[100]; for (int i = 0; i < 100; i++) { london[i] = new House(); } london[0].Owner = "Timmy"; london[0].RoomArea[0] = 15; // Error points to this line Console.WriteLine("Room 1 in " + london[0].Owner + "s house has the area of " + london[0].RoomArea[0] + "square meters"); } } I get the following error: Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. I've looked at this this question/solution, yet I can't pinpoint what's exactly wrong with my code. A: You need to initialize RoomArea. Even though you initialize inside the class it is creating it's own member , but in order to add values you need to initialize it london[0].RoomArea = new int[10]; london[0].RoomArea[0] = 15;
{ "language": "en", "url": "https://stackoverflow.com/questions/46781497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Design decision behind entry to an API I am new to creating an API for others to use. And I was thinking about the design decisions that go behind creating the entry to an API. Like JAXB uses a class called JAXBContext as an entry point to use its framework, Mockito uses the class Mockito itself as the entry point and has whole lots of static methods for that. So are there any thumb rules to be kept in mind when designing an API ? EDIT: The API does the work of reading and reloading the configurations from different sources. A: I would recommend to design your API as a service loadable with ServiceLoader, similar to DOM API. Thus, your API will be loadable as: Entry entry = ServiceLoader.load(Entry.class).next(); And it will be easy to have many implementations of the same API.
{ "language": "en", "url": "https://stackoverflow.com/questions/14623185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Measuring audio quality and appeal/aesthetic Is there any way to measure the quality and appeal/aesthetic of an audio clip? The quality quantifies how good the sound is, ie., the lower the noise the better the quality is. Whereas the appeal/aesthetic measures how appealing the sound is to the human. There exists some work for image quality and aesthetic assessment like NIMA, but not for sound/audio. Any method or references will be helpful. A: We recently published a PESQ variant for the PyTorch framework, you can find it here: https://github.com/audiolabs/torch-pesq This allows you to use an perceptual metric for wideband speech quality in context of deep learning and generate gradients for your training. A: Measurements of audio quality or asthetic is done both with and without machine learning. However most of the work focuses on speech reproduction, much less on general audio. One can conduct listening tests, where a panel of human asessors listen to audio and give their score, to establish a Mean Opinion Score (MOS). There exists several standards for conducting these, such as MUSHRA. Such subjective scores form the basis of developing "objective metrics", which are algorithmic ways to estimate qualities of the audio. Some early examples are PESQ for Speech Quality (ITU standard since 2001) and PEAQ for Audio Quality (ITU standard since 1998). More advanced include POLQA (ITU standard since 2011) and ViSQOLAudio (proposed in research). The last years several papers have shown that one can learn such metrics using deep neural networks. For speech quality, one recent paper (2019) is Intrusive and Non-Intrusive Perceptual Speech Quality Assessment Using a Convolutional Neural Network. The only learned evaluation I have found for general Audio Quality or music quality is Fréchet Audio Distance.
{ "language": "en", "url": "https://stackoverflow.com/questions/58887600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Accessing environment variables from client side app I want to access environment variables from my .env file, located in the root directory, and use them in my App.js React file using dotenv. However, I am not able to access them. on the client side (App.js). File Structure: The variables I want to use: root/.env The file I want to use them in: root/client/src/App.js .env file: PORT=5432 TEST=911 REACT_APP_WEATHER=12345678 App.js file import './App.css'; require("dotenv").config(); // Doesn't show the variables in the .env file console.log(process.env); function App() { return ( <div className="App"> Hello </div> ); } export default App; I read that dotenv (which is installed in my root directory) doesn't work on client-side and only on server-side Using environment variables in React. Do I need to install that webpack? I tried installing it in my client but it created many errors. Note: I want to store my server and client environment variables in the same .env file A: With create-react-app you don't have to use dotenv library of anything like that. To read from .env file all you have to do is prefix all the variables name with REACT_APP_. For example: REACT_APP_PORT=5432 REACT_APP_TEST=911 REACT_APP_WEATHER=12345678 create-react-app will automatically make it available to you during the build time. On your react app, from anywhere, you can console.log this: console.log(process.env.REACT_APP_PORT); //5432
{ "language": "en", "url": "https://stackoverflow.com/questions/64654842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: .Find not working and If statement based on results of .Find method. what expression can be passed into the .Find method? I use excel VBA to find a price in a contract saved in *.docx file. Later I assign the price into a variable and write it into the cell in a spreadsheet. The macro works fine, at least the first half of it. 50% cases I get a clean price with no additional trash words in it and I can save it in my price variable, which is declared as Long. The other half cases I get the price with the word I don't need. It's always the same word "lacznej" - it's a Polish word, therefore I omitted some Slavic letters, but for the sake of this question it's "lacznej" and I really need to get rid of it in order to write the price into my price variable, which is Long. Later I write this variable value into the cell in Excel spreadsheet. startPos = InStr(1, rng, textToFind6) endPos = InStr(startPos, rng, ",00zł") 'here we get 47380, we're looking 4 ",00zł" startPos = startPos + Len(textToFind6) ' + 21 characters 'now start position is reassigned at 47331. Debug.Print Replace(Mid(rng, startPos, endPos - startPos), ".", "") 'up to this moment macro works fine while customers buy appartment in shares, like 1/2 or 1/3, in the next line it crashes. Replace(Mid(rng, startPos, endPos - startPos), ".", "").Find why this line crashes?? .Text = "łącznej " 'if I find this superfluous word I want to replace it with "" .MatchWildcards = False .MatchCase = False .Forward = True .Execute If .Found = True Then Debug.Print Replace(Mid(rng, startPos, endPos - startPos), ".", "") price = Replace(Replace(Mid(rng, startPos, endPos - startPos), ".", ""), "łącznej ", "") Else price = Replace(Mid(rng, startPos, endPos - startPos), ".", "") price = Trim(price) End If Debug.Print price This is it. Replace(Mid(rng, startPos, endPos - startPos), ".", "").Find How to make this line run? I thought I'm passing string value into the .Find method. It should work with string values right?? What "invalid qualifier" means ?? The initial Replace(Mid(rng, startPos, endPos - startPos), ".", "") is because I have "." as a separator of millions and thousands, so the price of the house is 1.500.000 or 800.000 in word document, and I need to replace "." with "", to get a number I can read into my price variable. The last lines of the macro are: Debug.Print scndRng.Address scndRng.Offset(0, 1) = price 'these two lines work fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/61619052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Only output to first instance of the_content() I have this WordPress function: function content_before_after($content) { return 'something goes here'; } add_filter('the_content', 'content_before_after'); ...which works fine except for one small problem: If there is more than one instance of the_content() on any page template, the returned text will appear for each of them. For reasons I can't go into I won't be able to modify the templates. But the problem I need to be solved is: how can I change this function so that the returned text is only output into the first instance of the_content() of my page template? A: Here static variable will help you: function content_before_after($content) { // define variable as static static $content_shown; // if variable has __no__ value // it means we run function for the first time if (!$content_shown) { // change value and return required string $content_shown = true; return 'something goes here'; } // empty string will be returned in second and other function calls return ''; }
{ "language": "en", "url": "https://stackoverflow.com/questions/50876303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to validation input type from $.ajax How to validate input type in $.ajax, iam not set tag because form always reload an action before i used validation jquery but, $.ajax is not running because loaded by from (required, maxtlength or another ni html not working, must be set form) i must set required, maxtlengt, emailvalidate or another url:myconnection, type: "POST", cache: false, data: { account: $('#indi1').val(), password: $('#indi2').val(), register:'individual' }, success:function(data) { var usr = $('#indi1').val(); window.location.replace("sign-in.html?username="+usr); } And this is my simple html <p> <input type="text" name="firstname" placeholder="Account name" class="ipt-txt" id="indi1"> </p> <p> <input type="password" placeholder="Password" class="ipt-txt" id="indi2"> </p> <p> <input type="submit" value="Sign Up" style="background:green;" id="addindi" > </p> Sory about my english :D question
{ "language": "en", "url": "https://stackoverflow.com/questions/34781940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Proper technique for a contact form? I have a contact form at shantiyoga.ca/contact With the view def contact(request): template = 'contact.html' form = ContactForm(request.POST or None) if form.is_valid(): # All validation rules pass subject = form.cleaned_data['subject'] message = "%s\n\n%s" % (form.cleaned_data['message'], form.cleaned_data['sender']) cc_myself = form.cleaned_data['cc_myself'] recipients = ['contact@shantiyoga.ca'] sender = form.cleaned_data['sender'] if cc_myself: recipients.append(sender) headers = {'Reply-To': form.cleaned_data['sender']} from django.core.mail import send_mail send_mail(subject,message,sender,recipients,headers) return redirect('/thanks/') return render_to_response(template, {'form': form, 'current':'contact'}, context_instance=RequestContext(request)) Which works fairly well. I'm not terribly sophisticated with Django and my Python skills are not quite up to snuff, so please bear with me if I step through this in a basic fashion. I would like to clarify that there is no way for the form recipient (contact@shantiyoga.ca) to receive the contact form from the value of the email field (user entered). It will always be sent by the authenticated email in my settings.py, which at this point is my personal email? A user fills out the contact form and hits submit, an email is sent to contact@shantiyoga.ca from my personal email, and if the user decides to cc themself, a copy of the email is sent to them, also from my personal email. This is not ideal, should I create an email like contactform@shantiyoga.ca for my settings.py to send the email from? Also, the headers = {'Reply-To': form.cleaned_data['sender']} does not appear to be doing anything and I can't seem to find documentation describing its proper usage, has anyone had success using this technique? Thank you for your time, Noah A: I would like to clarify that there is no way for the form recipient (contact@shantiyoga.ca) to receive the contact form from the value of the email field (user entered). It will always be sent by the authenticated email in my settings.py, which at this point is my personal email? You're setting the sender of the email to sender but using EMAIL_HOST, correct? If this is the case, be careful that your SMTP account will let you send email from users other than your domain. Normally, providing you have an authenticated account on that server, you'll be able to set the From: field to whatever you like. So in short, this email will hit your inbox appearing to be from the sender variable. So when you hit reply, you'll be able to email them back, which is I think what you want. However, it will be sent using the SMTP server whose authentication details you provide. There is a disconnect between being able to send email (SMTP) and being able to receive it, which I think has got you confused. I've never tried it, but to add extra headers I believe you need to use the EmailMessage object. According to the docs, you would: e = EmailMessage(headers={'Reply-To':... e.send() Be careful doing this; specifically, be careful to strip out newlines in the reply to field. I do not know if the default clean methods would do this. Finally, there isn't much wrong with your django/python at all. The only thing I'd say, by way of awareness, is not to use this: return redirect('/thanks/') but instead: return HttpResponseRedirect(reverse('myapp.views.method',args=tuple,kwargs=dict)) This gives you the ability to not hardcode urls into your application. The reverse method will look them up from urls.py for you, so you can move your application around/change urls and it will still work. A: Here is signature of send_mail from django documentation: send_mail(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None) As you can see it does not have headers argument. You will need to use EmailMessage object directly. It would also be nice to remove email-formatting from view. I would write everything something more like this: from django.core.mail.message import EmailMessage from django.conf import settings class ContactsEmailMessage(EmailMessage): def __init__(self, sender, subject, message, cc_myself): super(ContactEmailMessage, self).__init__( subject=subject, body=self._get_message(self, sender, message), from=settings.DEFAULT_FROM_EMAIL, to=settings.CONTACT_RECIPIENTS, headers=self._get_headers(sender), cc=(sender, ) if cc_myself else None ) def _format_message(self, sender, message): return "%s\n\n%s" % (sender, message) def _get_headers(self, sender): return { 'reply-to': sender } Now you can write clean and easy to read view: from myproject.mail.message import ContactsEmailMessage, BadHeaderError from django.core.exceptions import SuspiciousOperation def contact(request): ... form = ContactForm(request.POST or None) if form.is_valid(): # All validation rules pass try: message = ContactsEmailMessage(**form.cleaned_data) message.send() except BadHeaderError: # django will raise this error if user will try to pass suspicious new-line # characters to "sender" or other fields. This is safe-guard from # header injections raise SuspiciousOperation() return redirect('/thanks/') ...
{ "language": "en", "url": "https://stackoverflow.com/questions/5264044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MIPS sorting and array I have this homework problem. I'm suppose to write a program that does the following: * *Sort the letters in the sentence into the ASCII collating sequence (i.e. alphabetically). Print the results and the total number of characters in the sentence. *Next, print out a list of the number of times each letter occurred in the sentence. *Finally, print out the total number of different characters in the sentence. When I try to test out the first requirement, I don't receive the output string. I also need help on doing the second two. I'm fairly new to MIPS, and I have some understanding of it, but having some difficulty. I modified some code for the sorting from example code I found. .data length: .word 0 buffer: .space 255 prompt1:.asciiz "Type in a sentence: " after: .asciiz "\nString after: " .text # Start of code section main: li $v0, 4 # Prompt user for a text string la $a0, prompt1 # address of string to print syscall li $v0, 8 # Read in text string la $a0, buffer li $a1, 255 syscall la $t0, buffer # Read character from text string lw $t1, length addu $t0, $t0, $t1 # Call on QuickSort la $a0, buffer # Constant pointer to string add $a1, $a0, 0 # Pointer to left end add $a2, $a0, 25 # Pointer to right end jal QS # The one call from main # Print out results la $a0, after li $v0, 4 syscall la $a0, buffer syscall # End main li $v0, 10 syscall QS: sub $sp, $sp, 16 # \ sw $a1, 0($sp) # \ sw $a2, 4($sp) # > Save registers sw $t2, 8($sp) # / sw $ra, 12($sp) # / and return address bge $a1, $a2, QSret # Nothing to sort sub $t3, $a1, $a0 # index i sub $t4, $a2, $a0 # index j add $t0, $t3, $t4 # t0 = i+j choose middle sra $t0, $t0, 1 # t0 = (i+j) div 2 add $t0, $t0, $a0 # t0 -> A[(i+j) div 2] lb $t5, 0($t0) # t5 = pivot value lb $t6, 0($a1) # t6 = A[i] = left element sb $t5, 0($a1) # Swap them so pivot sb $t6, 0($t0) # is first element # move $t1, $a1 # Initdially i -> first (pivot) item a1 add $t2, $a2, 1 # Initially j -> just past last item a2 lb $t0, 0($a1) # Pivot value in t0 (in $t5) # loop: # i_loop: add $t1, $t1, 1 # i=i+1; lb $t5, 0($t1) # t5 = A[i] bgt $t0, $t5, i_loop # until pivot <= A[i] j_loop: sub $t2, $t2, 1 # j=j-1; lb $t6, 0($t2) # t6 = A[j] blt $t0, $t6, j_loop # until pivot >= A[j] # bge $t1, $t2, test # if i<j swap # sb $t6, 0($t1) # A[i] and sb $t5, 0($t2) # A[j] # test: blt $t1, $t2, loop # until i >= j # lb $t5, 0($a1) # swap a[a1] = pivot lb $t6, 0($t2) # and a[j] sb $t5, 0($t2) # now a[j] is sb $t6, 0($a1) # in its final position # Done with partition lw $a1, 0($sp) sub $a2, $t2, 1 jal QS # Recursive call on left add $a1, $t2, 1 lw $a2, 4($sp) jal QS # Recursive call on right # QSret: lw $ra, 12($sp) # \Replace return address lw $t2, 8($sp) # \ lw $a2, 4($sp) # > and registers lw $a1, 0($sp) # / add $sp, $sp, 16 # / jr $ra A: buffer: .space 255 This fills buffer with zeroes. li $v0, 8 # Read in text string la $a0, buffer li $a1, 255 syscall I don't know what environment you're using, but this typically works just like fgets() in C, so if you enter hello, your buffer will end up as: +-----+-----+-----+-----+-----+-----+-----+-----+ more +-----+ | 'h' | 'e' | 'l' | 'l' | 'o' |'\n' | 0 | 0 |..zeroes...| 0 | +-----+-----+-----+-----+-----+-----+-----+-----+ +-----+ The code just after that doesn't seem to do anything useful: la $t0, buffer # Read character from text string lw $t1, length addu $t0, $t0, $t1 but length has never been written and $t0 isn't used again (until it's overwritten inside QS). The call to QS passes a fixed value in $a2 (25 - why?). Assuming that the QS routine actually works as advertised: if your original string is short, some of the zero bytes in the buffer will be included in the range that gets sorted, and so will end up at the beginning of the buffer - the range that gets sorted will look something like this: +-----+ more +-----+-----+-----+-----+-----+-----+-----+-----+ | 0 |..zeroes...| 0 | 0 |'\n' | 'e' | 'h' | 'l' | 'l' | 'o' | +-----+ +-----+-----+-----+-----+-----+-----+-----+-----+ i.e. if the range that gets sorted includes any zero bytes, the first byte of the result will be zero, and so you will print an empty string. Part 2: once you have a correctly sorted string, this should be straightforward, as all of the occurences of each character are adjacent. Just walk along the string, and consider whether each character is the same as the previous one, or different. Part 3: just needs an additional counter while doing the work for part 2.
{ "language": "en", "url": "https://stackoverflow.com/questions/4159237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Angular custom-control-input doesn't work correctly with formControlName inside loop i want to apply a custom theme style on angular but checkbox didn't work correctly. i have this part of code and worked very well : <tr *ngFor="let item of lists let i=index" [formGroupName]="i"> <td> <div class="form-group"> <div class="custom-control custom-switch"> <input type="checkbox" class="form-control" id="field_check" formControlName="checked"> <label class="form-control-label" for="field_check">check</label> </div> </div> </td> </tr> But when i try to add a custom class control not working : <tr *ngFor="let item of lists let i=index" [formGroupName]="i"> <td> <div class="form-group"> <div class="custom-control custom-switch"> <input type="checkbox" class="custom-control-input" id="field_check" formControlName="checked"> <label class="custom-control-label" for="field_check">check</label> </div> </div> </td> </tr> how to apply my class="custom-control-input" without losing the class="form-control" ? i have already tried this class="form-control custom-control-input" but didn't work UPDATE after inspect element i found this : so when here is the result i got : i have no access to css code custom-control-input and form-control how can i fix this ? A: It should work ideally, it is best if you can see which style is applying on control using inspect element. May be it is overrided by form-control class. You might have to use ! Important in class.
{ "language": "en", "url": "https://stackoverflow.com/questions/63644681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to automate a large number of txt files to be imported from Perl to a SQL Server using DBI? I have attempted to transfer one txt file into a SQL Server from Perl, but I now need to create a DB in SQL that combines hundreds of txt files. Is there an automated way of doing this to save manually transferring all the txt files? I will insert my attempt of coding one txt file. I believe I need to use Bulk Insert to achieve this but I am unsure what code to use. Any advice on the problem would be really appreciated, and if there is anymore code you wish to see or a specific thing I forgot to mention then please comment and I will edit. Thank you. #!/usr/bin/perl -w use strict; use DBI; use Carp; # Connect to the data source and get a handle for that connection. my $dbh = DBI->connect('dbi:ODBC:RegressionDBS') || confess "Connection Failed: $DBI::errstr"; # This query generates a result set with one record in it. my $sql = "SELECT 1 AS test_col"; my $tablename = "RegressionTable"; open(FH, "newregression.txt") || die "cant open file"; my $Sqlh = $dbh->prepare("INSERT INTO RegressionTable (Ticker, TradeDate, HighPrice, LowPrice, TradePrice, TotalVolume, TotalValue) VALUES (?,?,?,?,?,?,?);") || confess $DBI::errstr; while (my $line = <FH> ) { $line =~/^(.*)(..)(..)$/; my ($curTicker, $wTradeDate, $wHighPrice, $wLowPrice, $wTradePrice, $wTotalVolume, $wTotalValue); $curTicker=$1 #$wTradeDate= $wHighPrice=$2; $wLowPrice=$1; #$wTradePrice=$1; #$wTotalVolume=$1; #$wTotalValue=$4; $Sqlh->execute($curTicker, $wTradeDate, $wHighPrice, $wLowPrice, $wTradePrice, $wTotalVolume, $wTotalValue) || confess $DBI::errstr; } $Sqlh->finish(); $dbh->disconnect(); A: Ok, so you run INSERT INTO RegressionTable ( Ticker, TradeDate, HighPrice, LowPrice, TradePrice, TotalVolume, TotalValue ) VALUES (?, ?, ?, ?, ?, ?, ?) for every line in newregression.txt, and now you want to do it for multiple files. Why not wrap your code above in a subroutine, say insert_file(), then call it per file in a loop... my @files = qw(red.txt green.txt blue.txt); for my $file (@files) { insert_file($file); } Or if the target table varies per file, define a hash: my %files = ( 'red.txt' => 'RedTable', 'blue.txt' => 'BlueTable' ); while ( my ($file, $table) = each %files ) { insert_file($file, $table); }; Not sure how you'd use Bulk Insert given the field separator in your data file seems to be indeterminate (i.e. the regex /(.*)(..)(..)/ defines field boundaries). You may need to use the FORMATFILE option. Also, if you generate a BULK INSERT statement using DBI, be aware that the user your SQL Server runs as must be able to read your data files over the filesystem (networked, local or otherwise).
{ "language": "en", "url": "https://stackoverflow.com/questions/19226451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Div class nav bar I can’t post code here because it will fill up section but if someone could add me discord it would be much appreciated and much easier. Thank you! Kam#3585 Kam#3585 add me on discord thanks A: You can use this code to create navbar <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Navbar</a> <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="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> <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"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav>
{ "language": "en", "url": "https://stackoverflow.com/questions/74651628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: DLL uses another DLL in C++ I have a complex 3rd DLL by C++. (I compiled it and have .lib both). I want to write a new my simple DLL, that using a few function in the 3rd DLL. How to import a 3rd DLL in my DLL? (Now, i got an error, When importing 3rd to my DLL, i could not load my DLL in any other application) A: I found my issue, A stupid issue. My 3rd DLL uses too much another DLL. I missed a library, (I developed my App by C#, It did not notify me missed library)
{ "language": "en", "url": "https://stackoverflow.com/questions/33605436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Creating a URLretreive function using urllib2 in python I want to have a function which can save a page from the web into a designated path using urllib2. Problem with urllib is that it doesn't check for Error 404, but unfortunately urllib2 doesn't have such a function although it can check for http errors. How can i make a function to save the file permanently to a path? def save(url,path): g=urllib2.urlopen(url) *do something to save g to 'path'* A: Just use .read() to get the contents and write it to a file path. def save(url,path): g = urllib2.urlopen(url) with open(path, "w") as fH: fH.write(g.read())
{ "language": "en", "url": "https://stackoverflow.com/questions/7132892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: insmod: ERROR: could not insert module kernel.ko: Invalid parameters - Error related to naming scheme of kernel module I'm using C to create a custom kernel module to hook into the netfilter operation on my Ubuntu box. However, I'm running into a problem revolving around the module_param argument. When inserting the module, I'm attempting to add a custom field, specifically this will drop ICMP traffic when specified. The code compiles fine using a standard make file but when using insmod to insert it, I get the error insmod: ERROR: could not insert module kernel.ko: Invalid parameters I'm using the command insmod kernel.ko dropicmp=1 From what I've read, this should work with the module params argument, but nothing I've tried has fixed this. Please find my code below. #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/netdevice.h> #include <linux/netfilter.h> #include <linux/netfilter_ipv4.h> #include <linux/ip.h> #include <linux/tcp.h> static struct nf_hook_ops nfho; struct iphdr *iph; struct tcphdr *tcp_header; struct sk_buff *sock_buff; unsigned int sport, dport; // command line argument | called using insmod kernel_firewall.ko drop_icmp=1 static int dropicmp = 1; module_param(dropicmp, int , 0); // takes in an int from command line | (name, variable, permissions) unsigned int hook_func(unsigned int hooknum, struct sk_buff **skb, const struct net_device *in, const struct net_device *out, int (*okfn)(struct sk_buff *)){ sock_buff = skb; if (!sock_buff) { // if there is no socket buffer, accept return NF_ACCEPT; } iph = (struct iphdr *)skb_network_header(sock_buff); // using the socket buffer, create our ip header structure out of packets in it if (!iph) { printk(KERN_INFO "no ip header, dropping\n"); // self explanatory return NF_DROP; } if(iph->protocol==IPPROTO_TCP) { if(iph->saddr | 0x11000000){ // if the first prefix is in the 192 range | might need to change the if statement up | considering sprintf printk(KERN_INFO "192 subnet detected, dropping\n"); return NF_DROP; } else{ return NF_ACCEPT; } } if(iph->protocol==IPPROTO_ICMP) { // if ICMP if(dropicmp == 1){ return NF_DROP; // drop our ICMP traffic if required } else{ return NF_ACCEPT; } } return NF_ACCEPT; // default to accept } // initialize static int __init initialize(void) { nfho.hook = hook_func; nfho.hooknum = NF_INET_POST_ROUTING; nfho.pf = PF_INET; nfho.priority = NF_IP_PRI_FIRST; nf_register_hook(&nfho); return 0; } // rmmod static void __exit teardown(void) { nf_unregister_hook(&nfho); } module_init(initialize); module_exit(teardown); A: This was all due to my dumb naming scheme... I named the module kernel... Which is obviously already in use by the kernel...... So don't do that...
{ "language": "en", "url": "https://stackoverflow.com/questions/49243381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: karma test on angular 2 ag grid 'exports is not defined' Hey all I'm trying to test my table component that is a wrapper on the old and good ag grid. I added the path to karma.conf.js 'node_modules/ag-grid-ng2/main.js' Also I added the ag grid component in the test file: import { RgGridComponent } from "../../shared/grid-control/grid-control.component"; import { AgGridNg2 } from 'ag-grid-ng2/main'; ... ... declarations: [TracesTableComponent, RgGridComponent, AgGridNg2], But when I try to run the test I get the message : "exports is not defined" I can really use some help. thanks! A: found the answer! I needed to install @types/jasmine and then import it like this: import { } from 'jasmine';
{ "language": "en", "url": "https://stackoverflow.com/questions/40107115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ascx control visible false displaying issues My user control is displaying only the first ascx but when I'm navigating to other ascx the content is not displaying what am I doing wrong??! The idea is On my aspx page I have on the left hand side TreeView for each of every node in the TreeView I want to load a different ascx which going to change only the right hand side of the page. aspx: <%@ Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Masters/InternalReports.Master" CodeBehind="Reports.aspx.vb" Inherits="DispatchSoftware.Reports" %> <%@ Register TagPrefix="ReportsPrefix" TagName="rptReports" Src="~/Controls/Reports/rptReport.ascx" %> <%@ Register TagPrefix="ReportsPrefixTmeOfDay" TagName="rptTimeOfDay" Src="~/Controls/Reports/rptTimeOfDay.ascx" %> <%@ Register TagPrefix="ReportsPrefixTrending" TagName="rptTrending" Src="~/Controls/Reports/rptTrending.ascx" %> <%@ Register TagPrefix="ReportsPrefixTopSevenIncidents" TagName="rptTopSevenIncidents" Src="~/Controls/Reports/rptTopSevenIncidents.ascx" %> <%@ Register TagPrefix="ReportsPrefixTimeCategoriesComparison" TagName="rptTimeCategoriesComparison" Src="~/Controls/Reports/rptTimeCategoriesComparison.ascx" %> <%@ Register TagPrefix="ReportsPrefixIncidentPerCategory" TagName="rptIncidentPerCategory" Src="~/Controls/Reports/rptIncidentPerCategory.ascx" %> <%@ Register TagPrefix="ReportsPrefixMaps" TagName="rptMaps" Src="~/Controls/Reports/rptMaps.ascx" %> <asp:Content ID="Content1" ContentPlaceHolderID="LeftContent" runat="server"> <div id="leftCol"> <div class="elementHeader"> <span class="text"> <asp:Label ID="lblFilter" runat="server" Text="Filter"></asp:Label> </span> </div> <div id="filterWrapperDiv" runat="server" clientidmode="Static"> <telerik:RadPanelBar runat="server" ID="rpbMainMenu" Width="248px" Height="517px" ExpandMode="FullExpandedItem"> <Items> <telerik:RadPanelItem ImageUrl="~/Images/Layout/Reports.png" Expanded="true" Text="Reports"> <ContentTemplate> <div style="border: 0px solid red; height: 400px; padding: 10px 10px 10px 10px; overflow: auto;"> <telerik:RadTreeView runat="Server" ID="rtvReports" EnableDragAndDrop="false" Height="300px"> <Nodes> <telerik:RadTreeNode Text="Statistical Report" Value="StatisticalReport" Expanded="true" CssClass="GeneralFontShape"> <Nodes> <telerik:RadTreeNode Text="Time of Day" Value="TimeofDay" > </telerik:RadTreeNode> <telerik:RadTreeNode Text="Trending" Value="Trending"> </telerik:RadTreeNode> <telerik:RadTreeNode Text="Top 7 Incidents" Value="Top7Incidents"> </telerik:RadTreeNode> <telerik:RadTreeNode Text="Incidents Per Category" Value="IncidentsPerCategory"> </telerik:RadTreeNode> </Nodes> </telerik:RadTreeNode> <telerik:RadTreeNode Text="Incident Comparisons" Value="IncidentComparisons" Expanded="true" CssClass="GeneralFontShape"> <Nodes> <telerik:RadTreeNode Text="Incident Loss" Value="IncidentLoss"> </telerik:RadTreeNode> </Nodes> </telerik:RadTreeNode> <telerik:RadTreeNode Text="Geographic Locations" Value="GeographicLocations" Expanded="true" CssClass="GeneralFontShape"> <Nodes> <telerik:RadTreeNode Text="Maps" Value="Maps"> </telerik:RadTreeNode> </Nodes> </telerik:RadTreeNode> </Nodes> </telerik:RadTreeView> </div> </ContentTemplate> </telerik:RadPanelItem> </Items> </telerik:RadPanelBar> </div> <div class="elementFooter"></div> </div> </asp:Content> <%--Right Handside--%> <asp:Content ID="Content2" ContentPlaceHolderID="RightContent" runat="server"> <ReportsPrefix:rptReports ID="ucReports" runat="server" Visible="True" /> <ReportsPrefixTmeOfDay:rptTimeOfDay ID="ucTimeOfDay" runat="server" Visible="False" /> <ReportsPrefixTrending:rptTrending ID="ucTrending" runat="server" Visible="False" /> <ReportsPrefixTopSevenIncidents:rptTopSevenIncidents ID="ucTopSevenIncidents" runat="server" Visible="False" /> <ReportsPrefixTimeCategoriesComparison:rptTimeCategoriesComparison ID="ucTimeCategoriesComparison" runat="server" Visible="False" /> <ReportsPrefixIncidentPerCategory:rptIncidentPerCategory ID="ucIncidentPerCategory" runat="server" Visible="False" /> <ReportsPrefixMaps:rptMaps ID="ucMaps" runat="server" Visible="False" /> </asp:Content> VB Code: Imports Telerik.Web.UI Imports System.Drawing Public Class Reports Inherits System.Web.UI.Page Private m_User As UserInfo = Nothing Private m_SessionID As String Private m_qrptTOD As String Private m_qrptTRN As String Private m_qrptTOS As String Private m_qrptIPC As String Private m_qrptCIL As String Private m_qrptGEO As String Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init m_User = New UserInfo() If m_User.UserID = 0 Then Response.Redirect(Globals.gRootRelativeSecureURL("/QuickLogOut.aspx?SessionID=" + m_User.SessionID + "&qCC=" & m_User.CompanyCode)) End If End Sub Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load RetrieveAllQueryStringParams() If Not IsPostBack Then GenerateDataSets() GenerateLabels() GenerateLinks() GenerateControls() GenerateOther() End If End Sub Private Sub RetrieveAllQueryStringParams() Try If Not String.IsNullOrEmpty(Request.QueryString("SessionID")) Then m_SessionID = Request.QueryString("SessionID") m_qrptTOD = Request.QueryString("qrptTOD") m_qrptTRN = Request.QueryString("qrptTRN") m_qrptTOS = Request.QueryString("qrptTOS") m_qrptIPC = Request.QueryString("qrptIPC") m_qrptCIL = Request.QueryString("qrptCIL") m_qrptGEO = Request.QueryString("qrptGEO") ElseIf Not String.IsNullOrEmpty(Session("SessionID")) Then m_SessionID = Session("SessionID") End If If m_qrptTOD = "tod" Then '=== Clearing the right hand side and loading the new ascx. Me.Master.FindControl("RightContent").Controls.Clear() Me.Master.FindControl("RightContent").Controls.Add(Page.LoadControl(("/Controls/Reports/rptTimeOfDay.ascx"))) End If If m_qrptTRN = "trn" Then Me.Master.FindControl("RightContent").Controls.Clear() Me.Master.FindControl("RightContent").Controls.Add(Page.LoadControl(("/Controls/Reports/rptTrending.ascx"))) End If If m_qrptTOS = "tos" Then Me.Master.FindControl("RightContent").Controls.Clear() Me.Master.FindControl("RightContent").Controls.Add(Page.LoadControl(("/Controls/Reports/rptTopSevenIncidents.ascx"))) End If If m_qrptIPC = "ipc" Then Me.Master.FindControl("RightContent").Controls.Clear() Me.Master.FindControl("RightContent").Controls.Add(Page.LoadControl(("/Controls/Reports/rptIncidentPerCategory.ascx"))) End If If m_qrptCIL = "cil" Then Me.Master.FindControl("RightContent").Controls.Clear() Me.Master.FindControl("RightContent").Controls.Add(Page.LoadControl(("/Controls/Reports/rptTimeCategoriesComparison.ascx"))) End If If m_qrptGEO = "geo" Then Me.Master.FindControl("RightContent").Controls.Clear() Me.Master.FindControl("RightContent").Controls.Add(Page.LoadControl(("/Controls/Reports/rptMaps.ascx"))) End If Catch ex As Exception End Try End Sub Protected Sub GenerateDataSets() Try Catch ex As Exception End Try End Sub Protected Sub GenerateLabels() End Sub Protected Sub GenerateLinks() Dim subTreeStatisticalReport As RadTreeNode = rtvReports.Nodes.FindNodeByValue("StatisticalReport") Dim subTreeIncidentComparisons As RadTreeNode = rtvReports.Nodes.FindNodeByValue("IncidentComparisons") Dim subTreeGeographicLocations As RadTreeNode = rtvReports.Nodes.FindNodeByValue("GeographicLocations") Dim statTimeOfDayNode As RadTreeNode = subTreeStatisticalReport.Nodes.FindNodeByValue("TimeofDay") Dim statTrendsNode As RadTreeNode = subTreeStatisticalReport.Nodes.FindNodeByValue("Trending") Dim statTopSevenIncidents As RadTreeNode = subTreeStatisticalReport.Nodes.FindNodeByValue("Top7Incidents") Dim statIncidentPerCategory As RadTreeNode = subTreeStatisticalReport.Nodes.FindNodeByValue("IncidentsPerCategory") Dim compIncidentLoss As RadTreeNode = subTreeIncidentComparisons.Nodes.FindNodeByValue("IncidentLoss") Dim GeoMaps As RadTreeNode = subTreeGeographicLocations.Nodes.FindNodeByValue("Maps") statTimeOfDayNode.NavigateUrl = Globals.gRootRelativeSecureURL("/Reports/Reports.aspx?SessionID=" + m_SessionID + "&qrptTOD=tod") statTrendsNode.NavigateUrl = Globals.gRootRelativeSecureURL("/Reports/Reports.aspx?SessionID=" + m_SessionID + "&qrptTRN=trn") statTopSevenIncidents.NavigateUrl = Globals.gRootRelativeSecureURL("/Reports/Reports.aspx?SessionID=" + m_SessionID + "&qrptTOS=tos") statIncidentPerCategory.NavigateUrl = Globals.gRootRelativeSecureURL("/Reports/Reports.aspx?SessionID=" + m_SessionID + "&qrptIPC=ipc") compIncidentLoss.NavigateUrl = Globals.gRootRelativeSecureURL("/Reports/Reports.aspx?SessionID=" + m_SessionID + "&qrptCIL=cil") GeoMaps.NavigateUrl = Globals.gRootRelativeSecureURL("/Reports/Reports.aspx?SessionID=" + m_SessionID + "&qrptGEO=geo") End Sub Protected Sub GenerateControls() End Sub Protected Sub GenerateOther() End Sub End Class
{ "language": "en", "url": "https://stackoverflow.com/questions/28774046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Server side rendering using reactjs I have started to work on react server side rendering, Having some questions i.e how about routing and can i implement server side rendering for all pages in application,Please provide any example on server side rendering in reactjs,Thanks A: for plain implementation in server side rendering you need to have different app entry point with StaticRouter instead of BrowserRouter react-routed-dom documentation with implementation: https://reacttraining.com/react-router/web/guides/server-rendering/putting-it-all-together
{ "language": "en", "url": "https://stackoverflow.com/questions/61379761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: android emulator access server in local network i am having difficulties to have my android app running in the emulator to connect to servers in my local network. i am getting a java.net.UnknownHostException but the servers are resolvable fine from the machine where the emulator is run. thanks for any help on this topic! A: Try adding <uses-permission android:name="android.permission.INTERNET" /> to your manifest. This allows your application network access. More can be found here. A: You have to use 10.0.2.2 to access local server.
{ "language": "en", "url": "https://stackoverflow.com/questions/3574365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Failing to capture process name and exit code in Exited eventhadler I have a pretty straight forward event handler on process exit that wants to log the process name and exit code. This code runs perfectly in my local machine (Windows 10 pro, 64 bit) no matter how I end the process (calling Kill(), End Task from Task Manager or closing the app). However the deployed version of the same code in Integration env (Windows Server 2016 DC, 64 bit) is failing with below error. System.InvalidOperationException: Process has exited, so the requested information is not available. at System.Diagnostics.Process.EnsureState(State state) at System.Diagnostics.Process.get_ProcessName() Any resolutions/pointers in troubleshooting this will be helpful. Event handler looks like below: private static void MyProcess_Exited(object sender, EventArgs e) { var process = sender as Process; var processExitLog = new StringBuilder() .AppendLine($"{process.ProcessName} exited with code {process.ExitCode} at {process.ExitTime.ToString("s")}.") .AppendLine($"Total uptime: {(process.ExitTime - process.StartTime).ToString("c")}") .AppendLine($"Running threads: {process.Threads.Count}") .AppendLine($"Peak physical memory utilization was: {process.PeakWorkingSet64}.") .ToString(); Console.WriteLine(processExitLog); Console.WriteLine(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/65394418", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Enter text into the Chrome's address bar via Selenium is it possible to enter a text to the address bar in Chrome with Selenium? I would like to resolve domains and get the final URL. E.g. enter freshfruits.com resolves https://www.freshfruits.com. A: Selenium does not support sending keys to the browser address bar, unfortunately. Someone suggested a solution with win32com.client library here Haven't tried it myself as I haven't been faced with this situation. The idea is you may need to consider workarounds, as this is outside the scope of Selenium.
{ "language": "en", "url": "https://stackoverflow.com/questions/60396807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Reduce Object Array to Single Object Working with an array of objects like: const objArr = [ { k: 'row 1', v: '111' }, { k: 'row 2', v: '222' }, { k: 'row 3', v: null }, { k: 'row 4', v: null }, ]; What is the most efficient way to reduce into a single object using the value of k for the key and the value of v for the value? Desired Outcome: const obj = { 'row 1': '111', 'row 2': '222', 'row 3': null, 'row 4': null, }; I have attempted to accomplish with a one-liner like: const obj = objArr.reduce((obj, key) => ({ ...{ [key]: objArr.v[key] } }), {});
{ "language": "en", "url": "https://stackoverflow.com/questions/52824983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Database design for time series Approximately every 10 min I insert ~50 records with the same timestamp. It means ~600 records per hour or 7.200 records per day or 2.592.000 records per year. User wants to retrieve all records for the timestamp closest to the asked time. Design #1 - one table with index on timestamp column: CREATE TABLE A (t timestamp, value int); CREATE a_idx ON A (t); Single insert statement creates ~50 records with the same timestamp: INSERT INTO A VALUES ( (‘2019-01-02 10:00’, 5), (‘2019-01-02 10:00’, 12), (‘2019-01-02 10:00’, 7), …. ) Get all records which are closest to the asked time (I use the function greatest() available in PostgreSQL): SELECT * FROM A WHERE t = (SELECT t FROM A ORDER BY greatest(t - asked_time, asked_time - t) LIMIT 1) I think this query is not efficient because it requires the full table scan. I plan to partition the A table by timestamp to have 1 partition per year, but the approximate match above still will be slow. Design #2 - create 2 tables: 1st table: to keep the unique timestamps and auto-incremented PK, 2nd table: to keep data and the foreign key on 1st table PK CREATE TABLE UNIQ_TIMESTAMP (id SERIAL PRIMARY KEY, t timestamp); CREATE TABLE DATA (id INTEGER REFERENCES UNIQ_TIMESTAMP (id), value int); CREATE INDEX data_time_idx ON DATA (id); Get all records which are closest to the asked time: SELECT * FROM DATA WHERE id = (SELECT id FROM UNIQ_TIMESTAMP ORDER BY greatest(t - asked_time, asked_time - t) LIMIT 1) It should run faster compared to Design #1 because the nested select scans the smaller table. Disadvantage of this approach: - I have to insert into 2 tables instead just one - I lost the ability to partition the DATA table by timestamp What you could recommend? A: I'd go with tje single table approach, perhaps partitioned by year so that it becomes easy to get rid of old data. Create an index like CREATE INDEX ON a (date_trunc('hour', t + INTERVAL '30 minutes')); Then use your query like you wrote it, but add AND date_trunc('hour', t + INTERVAL '30 minutes') = date_trunc('hour', asked_time + INTERVAL '30 minutes') The additional condition acts as a filter and can use the index. A: You can use a UNION of two queries to find all timestamps closest to a given one: ( select t from a where t >= timestamp '2019-03-01 17:00:00' order by t limit 1 ) union all ( select t from a where t <= timestamp '2019-03-01 17:00:00' order by t desc limit 1 ) That will efficiently make use of an index on t. On a table with 10 million rows (~3 years of data), I get the following execution plan: Append (cost=0.57..1.16 rows=2 width=8) (actual time=0.381..0.407 rows=2 loops=1) Buffers: shared hit=6 read=4 I/O Timings: read=0.050 -> Limit (cost=0.57..0.58 rows=1 width=8) (actual time=0.380..0.381 rows=1 loops=1) Output: a.t Buffers: shared hit=1 read=4 I/O Timings: read=0.050 -> Index Only Scan using a_t_idx on stuff.a (cost=0.57..253023.35 rows=30699415 width=8) (actual time=0.380..0.380 rows=1 loops=1) Output: a.t Index Cond: (a.t >= '2019-03-01 17:00:00'::timestamp without time zone) Heap Fetches: 0 Buffers: shared hit=1 read=4 I/O Timings: read=0.050 -> Limit (cost=0.57..0.58 rows=1 width=8) (actual time=0.024..0.025 rows=1 loops=1) Output: a_1.t Buffers: shared hit=5 -> Index Only Scan Backward using a_t_idx on stuff.a a_1 (cost=0.57..649469.88 rows=78800603 width=8) (actual time=0.024..0.024 rows=1 loops=1) Output: a_1.t Index Cond: (a_1.t <= '2019-03-01 17:00:00'::timestamp without time zone) Heap Fetches: 0 Buffers: shared hit=5 Planning Time: 1.823 ms Execution Time: 0.425 ms As you can see it only requires very few I/O operations and that is pretty much independent of the table size. The above can be used for an IN condition: select * from a where t in ( (select t from a where t >= timestamp '2019-03-01 17:00:00' order by t limit 1) union all (select t from a where t <= timestamp '2019-03-01 17:00:00' order by t desc limit 1) ); If you know you will never have more than 100 values close to that requested timestamp, you could remove the IN query completely and simply use a limit 100 in both parts of the union. That makes the query a bit more efficient as there is no second step for evaluating the IN condition, but might return more rows than you want. If you always look for timestamps in the same year, then partitioning by year will indeed help with this. You can put that into a function if it is too complicated as a query: create or replace function get_closest(p_tocheck timestamp) returns timestamp as $$ select * from ( (select t from a where t >= p_tocheck order by t limit 1) union all (select t from a where t <= p_tocheck order by t desc limit 1) ) x order by greatest(t - p_tocheck, p_tocheck - t) limit 1; $$ language sql stable; The the query gets as simple as: select * from a where t = get_closest(timestamp '2019-03-01 17:00:00'); Another solution is to use the btree_gist extension which provides a "distance" operator <-> Then you can create a GiST index on the timestamp: create index on a using gist (t) ; and use the following query: select * from a where t in (select t from a order by t <-> timestamp '2019-03-01 17:00:00' limit 1);
{ "language": "en", "url": "https://stackoverflow.com/questions/56863332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Elastic4s ngram mapping I have to create an ElasticSearch mapping like this using elastic4s: "mappings": { "properties": { "id": { "type": "keyword" }, "name": { "type": "text", "analyzer": "ngram_analyzer", "fielddata": true }, "lang": { "type": "keyword" }, "order": { "type": "long" }, "active": { "type": "boolean" } "description": { "type": "text" } } } I can do def mapping: Option[MappingDefinition] = Some( properties( KeywordField("id"), KeywordField("lang"), BasicField("order", "long"), BasicField("active", "boolean"), TextField("description") ) ) for id, lang, order, active and description. But, how can I do such mapping for name. the problem is analyzer and fielddata inside it. A: You should use this: TextField("name").fielddata(true).analyzer("ngram_analyzer") You also need to make sure to properly create the ngram_analyzer in your index settings.
{ "language": "en", "url": "https://stackoverflow.com/questions/59964776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: spark - where is spark.sql.legacy.timeParserPolicy documented? Migration Guide: SQL, Datasets and DataFram refers to spark.sql.legacy.timeParserPolicy Parsing/formatting of timestamp/date strings. This effects on CSV/JSON datasources and on the unix_timestamp, date_format, to_unix_timestamp, from_unixtime, to_date, to_timestamp functions when patterns specified by users is used for parsing and formatting. In Spark 3.0, we define our own pattern strings in Datetime Patterns for Formatting and Parsing, which is implemented via DateTimeFormatter under the hood. New implementation performs strict checking of its input. For example, the 2015-07-22 10:00:00 timestamp cannot be parse if pattern is yyyy-MM-dd because the parser does not consume whole input. Another example is the 31/01/2015 00:00 input cannot be parsed by the dd/MM/yyyy hh:mm pattern because hh supposes hours in the range 1-12. In Spark version 2.4 and below, java.text.SimpleDateFormat is used for timestamp/date string conversions, and the supported patterns are described in SimpleDateFormat. The old behavior can be restored by setting spark.sql.legacy.timeParserPolicy to LEGACY. Spark Application Properties does not have the explanation. Where is it documented and what values are available to specify? A: For some reason it does not appear it Spark configurations docs but you can find it in SQLConf.scala: When LEGACY, java.text.SimpleDateFormat is used for formatting and parsing dates/timestamps in a locale-sensitive manner, which is the approach before Spark 3.0. When set to CORRECTED, classes from java.time.* packages are used for the same purpose. The default value is EXCEPTION, RuntimeException is thrown when we will get different results.
{ "language": "en", "url": "https://stackoverflow.com/questions/71190476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Generating relative paths with Jersey UriBuilder Using UriBuilder as follows: UriBuilder.fromResource(My.class).path("resource").build().toString() generates /my/resource. I was wondering if there was a way to tell UriBuilder that I want to generate a relative path like so my/resource. This is useful in cases where I want to advertise resource URIs relative to the root URI (/my/resource being an absolute path and a relative URI to the root scheme + domain + port). Does my question even make sense?
{ "language": "en", "url": "https://stackoverflow.com/questions/19941874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: cycling Ranksum on Stata I have some data with two different groupd of patients automatically exported from a diagnostic tool. Variables are automatically nominated by the diagnostic tool (e.g. L1DensityWholeImage, L1WholeImageSHemi, L1WholeImageIHemi , L1WholeETDRS ,[...], DeepL2StartLayer, L2Startoffsetum, L2EndLayer, [...], Perimeter, AcircularityIndex ) I have to perform a Rank-sum test (or Mann-Whitney U test) with all the variables (> of 80) by group. Normally, I should write each single analysis like that: ranksum L1DensityWholeImage, by(Group) ranksum L1WholeImageSHemi, by(Group) ranksum L1WholeImageIHemi, by(Group) ranksum L1WholeETDRS, by(Group) Is there any way or code to write the command with a varlist? And maybe to obtain only 1 output result with all the p value? e.g.: ranksum L1DensityWholeImage L1WholeImageSHemi L1WholeImageIHemi L1WholeETDRS, DeepL2StartLayer L2Startoffsetum L2EndLayer Perimeter AcircularityIndex, by(Group) A: A short answer is write a loop and customise output. Here is a token example which you can run. sysuse auto, clear foreach v of var mpg price weight length displacement { quietly ranksum `v', by(foreign) porder scalar pval = 2*normprob(-abs(r(z))) di "`v'{col 14}" %05.3f pval " " %6.4e pval " " %05.3f r(porder) } Output is mpg 0.002 1.9e-03 0.271 price 0.298 3.0e-01 0.423 weight 0.000 3.8e-07 0.875 length 0.000 9.4e-07 0.862 displacement 0.000 1.1e-08 0.921 Notes: * *If your variable names are longer, they will need more space. *Displaying P-values with fixed numbers of decimal places won't prepare you for the circumstance in which all displayed digits are zero. The code exemplifies two forms of output. *The probability that values for the first group exceed those for the second group is very helpful in interpretation. Further summary statistics could be added. *Naturally a presentable table needs more header lines, best given with display.
{ "language": "en", "url": "https://stackoverflow.com/questions/49844265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Executing external programs via commandline in a Grails application I am attempting to create a Java source file which will interface with my Grails application. When a certain action is performed, I want this Java file to execute a program via commandline. I am attempting to do this via the Runtime.getRuntime().exec() command, however I keep getting an error about the Runtime object being undefined. Is it not possible to get a handle on this object through Grails? A: If you are using Java 5 or later you are better off using ProcessBuilder rather than Runtime.exec. See here for more information.
{ "language": "en", "url": "https://stackoverflow.com/questions/1131469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Find shortest path from s to every v with a limit on length Let G(V,E) a directed graph with weights w:E->R. Let's assume |V| is dividable by 10. Let s in V. Describe an algorithm to find a shortest path from s to every v such that it contains exactly |V|/10 edges. So at first I thought about using dynamic programming but I ended up with complexity of O(|V|^3) which apparently not optimal for this exercise. We can't use Bellman-Ford (As far as I understand) since there might be negative cycles. What could be an optimal algorithm for this problem? Thanks EDIT I forgot to mention a crucial information; Path can be not-simple. i.e. we may repeat edges in our path. A: You can perform a depth limited search with limit of |V|/10 on your graph. It will help you find the path with the least cost. limit = v_size / 10 best[v_size] initialize to MAX_INT depth_limited(node, length, cost) if length == limit if cost < best[node] best[node] = cost return for each u connected to node depth_limited(u, length+1, cost + w[node][u]) depth_limited(start_node, 0, 0) A: According to me Bellman Ford's algorithm SHOULD be applicable here with a slight modification. After iteration k, the distances to each node u_j(k) would be the shortest distance from source s having exactly k edges. Initialize u_j(0) = infinity for all u_j, and 0 for s. Then recurrence relation would be, u_j(k) = min {u_p(k-1) + w_{pj} | There is an edge from u_p to u_j} Note that in this case u_j(k) may be greater than u_j(k-1). The complexity of the above algorithm shall be O(|E|.|V|/10) = O(|E|.|V|). Also, the negative cycles won't matter in this case because we shall stop after |V|/10 iterations. Whether cost can be further decreased by adding more edges is irrelevant.
{ "language": "en", "url": "https://stackoverflow.com/questions/39531556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How Can I Embed A Browser Window In Tkinter? I originally wondered about scraping the image from a site, however, somewhat giving up on that idea I am looking to embed a browser window into a Tkinter window, Ideally, it would be able to support multiple browsers for cross-platform support. I have looked into the usage of Selenium but I am not entirely sure if it is possible to embed the Selenium browser instance into a Tkinter window. I have found no real solutions to this online and have no prior knowledge of embedding any sort of browser into Tkinter so I am really stuck and any help would be appreciated.
{ "language": "en", "url": "https://stackoverflow.com/questions/70703630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Aligning an Image and text within a Div CSS I am trying to align an image and text within a div so it looks like the following IMAGE TEXT However when I get them aligned as such, the background colour of the div no longer appears. Can anyone suggest what I am doing wrong? HTML: <div class="introduction"> <div class="image"> <img src=""> </div> <div class="text"> <p>Text</p> <p>Good luck!!</p> </div> </div> css: .introduction { margin: 0 50px; padding: 20px; background-color: #FFFFFF; color: #000000; -moz-border-radius: 10px; border-radius: 10px; } .image { width: 30%; float: left; } .text { width: 70%; float: left; } A: Putting the two floats in there side by side makes the parent container's height effectively 0. You can put a div with a style="clear:both;" before the parent's closing tag and you will get your background back. <div class="introduction"> <div class="image"> <img src="" /> </div> <div class="text"> <p> Text </p> <p>Good luck!!</p> </div><div style="clear:both;"></div></div> A: Something like this may achieve what you want: <style> .introduction{ margin:0px; padding:5px; background-color:orange; } .introduction img{ float:left; padding:10px; } .introduction p{ padding-left:50px; background-color:blue; } </style> <div class="introduction"> <img src="img/can_25.png" /> <p>Text</p> <p>Good Luck</p> </div> Since your p's aren't floated, they will hold your div open .. depending on the size of your image. A: I would suggest you 2 solutions: 1) If you want to your output look like this: IMAGE TEXT IMAGE TEXT TEXT HTML: <div class="whole"> <img class="ib" src="myimg.png" alt="my img" /> <p class="ib">my text my text my text my text my text my text my text is so short I will die alone</p> </div> CSS: .ib{ display:inline-block;} .whole{ vertical-align:top} .ib img{width:30%; border:0;} .ib p{width:70%;margin:0;padding:0;} 2) or like this: IMAGE TEXT TEXT TEXT TEXT HTML: <img src="myimg.png" alt="my img" class="leftimg" /> <p>my text my text my text is so short I will die alone</p> CSS: .leftimg { float:left; margin-right:5px; } DEMO: http://jsfiddle.net/goodfriend/b66J8/37/
{ "language": "en", "url": "https://stackoverflow.com/questions/17836193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create groupings on data I have input data like this: The output I require is grouping all the elements and giving distinct customers and total sales for each group. I have tried cross matrix, group by, and cube functions until now, but however, I am not getting the desired results. Output expected: Any help will highly appreciated.
{ "language": "en", "url": "https://stackoverflow.com/questions/73875981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python script as linux service/daemon Hallo, I'm trying to let a python script run as service (daemon) on (ubuntu) linux. On the web there exist several solutions like: http://pypi.python.org/pypi/python-daemon/ A well-behaved Unix daemon process is tricky to get right, but the required steps are much the same for every daemon program. A DaemonContext instance holds the behaviour and configured process environment for the program; use the instance as a context manager to enter a daemon state. http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/ However as I want to integrate my python script specifically with ubuntu linux my solution is a combination with an init.d script #!/bin/bash WORK_DIR="/var/lib/foo" DAEMON="/usr/bin/python" ARGS="/opt/foo/linux_service.py" PIDFILE="/var/run/foo.pid" USER="foo" case "$1" in start) echo "Starting server" mkdir -p "$WORK_DIR" /sbin/start-stop-daemon --start --pidfile $PIDFILE \ --user $USER --group $USER \ -b --make-pidfile \ --chuid $USER \ --exec $DAEMON $ARGS ;; stop) echo "Stopping server" /sbin/start-stop-daemon --stop --pidfile $PIDFILE --verbose ;; *) echo "Usage: /etc/init.d/$USER {start|stop}" exit 1 ;; esac exit 0 and in python: import signal import time import multiprocessing stop_event = multiprocessing.Event() def stop(signum, frame): stop_event.set() signal.signal(signal.SIGTERM, stop) if __name__ == '__main__': while not stop_event.is_set(): time.sleep(3) My question now is if this approach is correct. Do I have to handle any additional signals? Will it be a "well-behaved Unix daemon process"? A: Assuming your daemon has some way of continually running (some event loop, twisted, whatever), you can try to use upstart. Here's an example upstart config for a hypothetical Python service: description "My service" author "Some Dude <blah@foo.com>" start on runlevel [234] stop on runlevel [0156] chdir /some/dir exec /some/dir/script.py respawn If you save this as script.conf to /etc/init you simple do a one-time $ sudo initctl reload-configuration $ sudo start script You can stop it with stop script. What the above upstart conf says is to start this service on reboots and also restart it if it dies. As for signal handling - your process should naturally respond to SIGTERM. By default this should be handled unless you've specifically installed your own signal handler. A: Rloton's answer is good. Here is a light refinement, just because I spent a ton of time debugging. And I need to do a new answer so I can format properly. A couple other points that took me forever to debug: * *When it fails, first check /var/log/upstart/.log *If your script implements a daemon with python-daemon, you do NOT use the 'expect daemon' stanza. Having no 'expect' works. I don't know why. (If anyone knows why - please post!) *Also, keep checking "initctl status script" to make sure you are up (start/running). (and do a reload when you update your conf file) Here is my version: description "My service" author "Some Dude <blah@foo.com>" env PYTHON_HOME=/<pathtovirtualenv> env PATH=$PYTHON_HOME:$PATH start on runlevel [2345] stop on runlevel [016] chdir <directory> # NO expect stanza if your script uses python-daemon exec $PYTHON_HOME/bin/python script.py # Only turn on respawn after you've debugged getting it to start and stop properly respawn
{ "language": "en", "url": "https://stackoverflow.com/questions/4705564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "72" }
Q: When to call File.Dispose() I am trying to use a text writer to write text to a file in .NET Core. The below code doesn't output anything to the file: TextWriter writer = File.CreateText(@"...txt"); writer.Write("Hello World"); However, this does: TextWriter writer = File.CreateText(@"...txt"); writer.Write("Hello World"); writer.Dispose(); Why is that? What does that extra line tell the program to do differently? I don't want to close the TextWriter because it is going to be writing logs, which are running constantly and indefinitely whilst my application is running. How can I keep it open until the application stops running? UPDATE So the reason I want to do this, is I am using an SDK that writes its logs to a TextWriter: TextWriterLogger(textWriter); //Creates a logger that writes to a TextWriter. User is responsible for providing an instance of TextWriter that is thread safe. But if I just enclose this in a using statement, logs won't be written because by the time they are ready to be written, the using statement will have executed and the TextWriter disposed. Thanks A: Dispose calls Flush, which writes the internal bytes stored in a buffer to disk Without closing or disposing a file, you are leaving unmanaged resources around and will potentially lock the file, not to mention memory leaks. Instead always use a using statement using (TextWriter writer = File.CreateText(@"...txt")) { writer.Write("Hello World"); } However if you want to continually write to the file, you will have to flush it FileStream.Flush Method Clears buffers for this stream and causes any buffered data to be written to the file. TextWriter writer = File.CreateText(@"...txt"); ... writer.Write("Hello World"); ... writer.Flush(); // at this point the bytes are flushed to disk ... ... writer.Dispose(); In short most streams are backed by an internal array (buffer), so you dont thrash writes. The Default size is 4k, when it hits the buffer size then it automatically flushes. If you want to see immediate writes, the you have to flush it every time Lastly some streams have an auto flush feature, which can do this job for you AutoFlush Gets or sets a value indicating whether the StreamWriter will flush its buffer to the underlying stream after every call to Write(Char) When you are finished with the stream always dispose it
{ "language": "en", "url": "https://stackoverflow.com/questions/54016413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: gdb layout asm doesn't work on mac? $ gdb test (gdb) start Breakpoint 1 at 0x100000ec8 Starting program: /private/tmp/test Reading symbols for shared libraries +. done Breakpoint 1, 0x0000000100000ec8 in main () (gdb) layout asm Undefined command: "layout". Try "help". $ gdbtui -bash: gdbtui: command not found Is layout and gdbtui not available for Mac OS X? What are some alternatives? A: According to this question there is no tui support on mac by default. So you have to compile gdb yourself with TUI enabled.
{ "language": "en", "url": "https://stackoverflow.com/questions/6706838", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Assembly 8088 - converting to hexadecimal I am trying to write an assembly code to do a file hexdump, just like in Linux when you do "hexdump -C sample.txt" from the command line. I got as far as opening the file and reading the contents into a buffer, but I can't get beyond, trying to convert those bytes to hexadecimal. Any help would be greatly appreciated. _WRITE = 4 !System call number for WRITE _READ = 3 !System call number for READ _OPEN = 5 !System call number for OPEN _EXIT = 1 !System call number for EXIT _GETCHAR = 117 !System call number for GETCHAR _PUTCHAR = 122 !System call number for PUTCHAR _PRINTF = 127 !System call number for PRINTF _SPRINTF = 121 !System call number for SPRINTF _SSCANF = 125 !System call number for SSCANF _OPEN = 5 !System call number for OPEN bufsiz = 512 !bufsiz = 512 .SECT .TEXT !Start label start: MOV BP, SP !System trap instruction MOV CX, de-greet PUSH CX PUSH greet PUSH _PRINTF SYS ADD SP, 8 CALL GetFileInput Byte2Hexadecimal: !Conversion needs to take place here Word2Hexadecimal: !From Word to Hexadecimal needs to take place here GetFileInput: PUSH BP MOV BP,SP MOV DI, buf PUSH _GETCHAR next_char:SYS CMPB AL, '\n' STOSB JNE next_char JL 9f JE 1f MOVB (DI),0 POP AX POP BP RET PUSH 0 PUSH buf PUSH _OPEN SYS CMP AX,0 JL 9f MOV (fildes),AX MOV SI,linh+2 MOV BX,0 1: CALL fillbuf CMP CX, 0 JLE 3f 2: MOV 9: MOV SP,BP PUSH buf PUSH errmess PUSH _PRINTF SYS PUSH _EXIT PUSH _EXIT SYS OpenFile: fillbuf: PUSH bufsiz PUSH buf PUSH (fildes) PUSH _READ SYS ADD SP,8 MOV CX,AX ADD BX,CX MOV DI,buf RET .EXIT: PUSH 0 !Return code PUSH _EXIT !Return to OS SYS !System trap instruction .SECT .DATA errmess: .ASCIZ "Open %s failed\n" numfmt: .ASCIZ "%d" greet: .ASCIZ "Welcome to our program, please enter the file name: \n" de: .BYTE 0 .SECT .BSS linh: .SPACE 8192 ! fildes: .SPACE 2 !Memory location for the fildes byte1: .SPACE 8 !Memory location for the Byte addr: .SPACE 8 !Memory location for the address word: .BYTE 2 !Memory location for the byte buf: .SPACE 80 !Memory location for the BUFF buffer: .SPACE bufsiz+2 A: There is no such thing as "converting the bytes into hexadecimal". The actual data is invariant and consists from binary ones and zeros. Your interpretation to these bits can be different, according to your needs. E.g., it can be interpreted as text character or decimal or hexadecimal or whatever value. E.g.: Binary 01010101 = decimal 85 = hexadecimal 55 = octal 125 = 'U' ASCII character. A: A crude and simple implementation is to split the byte into two nibbles and then use each nibble as an index into a hex character "table". ; cdecl calling convention (google if you're not familiar with) HEX_CHARSET db '0123456789ABCDEF' ; void byteToHex(byte val, char* buffer) proc byteToHex push bp mov bp,sp push di mov dx,[word ptr ss:bp + 4] ; the address of val mov di,[word ptr ss:bp + 6] ; the address of buffer ; high nibble first mov ax,dx mov cl,4 shr al,cl push ax call nibbleToHex add sp,4 stosb ; low nibble second mov ax,dx push ax call nibbleToHex add esp,4 stosb pop di mov sp,bp pop bp ret endp byteToHex ; char nibbleToHex(byte nibble) proc nibbleToHex push bp mov bp,sp push si mov ax,[word ptr ss:bp + 4] and ax,0Fh ; Sanitizing input param lea si,[ds:HEX_CHARSET] add si,ax lodsb pop si mov sp,bp pop bp ret endp nibbleToHex A: A hexadecimal digit has 4 bits in it. A byte has 8 bits in it or 2 hex digits. To display a byte in hex, you need to separate each of those two 4-bit halves and then convert the resultant value of each (which, unsurprisingly, will be from 0 to 24-1, IOW, from 0 to 15 or from 0 to 0FH) to the corresponding ASCII code: 0 -> 48 (or 30H or '0') 1 -> 49 (or 31H or '1') ... 9 -> 57 (or 39H or '9') 10 (or 0AH) -> 65 (or 41H or 'A') 11 (or 0BH) -> 66 (or 42H or 'B') ... 15 (or 0FH) -> 70 (or 46H or 'F') Once you've converted a byte into two ASCII characters you can call the appropriate API (system call) of your OS to display those characters either one by one or as a string (you'll probably need to append a zero byte after those two characters to make a string). That's all. A: The instructions explicitly say you're supposed to write this yourself! ; push ax ; byte in al ; push outbuf ; call Byte2Hexadecimal ; add sp, 4 Byte2Hexadecimal: push bp mov bp, sp push di mov di, [bp + 4] ; buffer to put it mov ax, [bp + 6] ; we're only interested in al mov ah, al ; make a copy mov cl, 4 ; ASSume literal 8086 shr al, cl ; isolate high nibble first add al, '0' ; '0'..'9' cmp al, '9' ; or... jbe skip add al, 7 ; 'A'..'F' skip: stosb mov al, ah ; restore our al from copy and al, 0Fh ; isolate low nibble add al, '0' ; etc... cmp al, '9' jbe skip2 add al, 7 skip2: stosb pop di mov sp, bp pop bp ret Untested(!)... something like that... (probably want to zero-terminate (or '$' terminate?) your buffer). Insanely short way to convert nibble to hex ascii cmp al, 0Ah sbb al, 69h das You probably don't want to figure that one out... and das is dog slow anyway... Now: What assembler? What OS?
{ "language": "en", "url": "https://stackoverflow.com/questions/15940164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: jQuery Add/Delete This snippet does what I want it to do with 1 exception. It works correctly if the user presses "Add" over and over again - it removes the empty row and adds the new row. If the user types something into the input field, that field is converted into table data. The only problem I have is when the user presses "Add" twice, and the second "Add" is below the first. It works if the second "Add" is above the first. I'm sure it has something to do with the fact that I removed the row if the input value was empty. <!DOCTYPE HTML> <html> <head> <script src="http://www.google.com/jsapi"></script> <script type="text/javascript"> function OnLoad() { $('input[name="myid"]').live('focusout', function() { var myValue = $(this).val(); if (myValue == '') { $(this).parents("tr").remove(); } else { $(this).parents("td").empty().append(myValue); } }); $('.insert').live('click', function() { var currentRow = $(this).parents("tr:first"); var newRow = currentRow.clone(true); newRow.children('td:last').empty().append('<input name="myid" />'); currentRow.after(newRow); document.myForm.myid.focus(); }); $('.delete').live('click', function() { if (confirm("Are you sure?")) { $(this).parents("tr").remove(); } }); } google.load("jquery", "1"); google.setOnLoadCallback(OnLoad); </script> </head> <body> <form name="myForm"> <table border="1"> <tr> <td class="insert">Add</td> <td class="delete">Erase</td> <td>One</td> </tr> <tr> <td class="insert">Add</td> <td class="delete">Erase</td> <td>Two</td> </tr> <tr> <td class="insert">Add</td> <td class="delete">Erase</td> <td>Three</td> </tr> </table> <input name="Other"> </form> </body> </html> A: This is happening because blur happens before click, in your code $(this).parents("tr").remove(); is executing before the click happens, so there's actually nothing to click on (and bubble up to trigger the .live() event). In your case, I would remove the add option from the currently being added row.
{ "language": "en", "url": "https://stackoverflow.com/questions/2329883", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: android- handler.postDelayed how does it achieve the Delay for any task that had to be delayed I had been using: Handler.postDelayed(Runnable r,Long Delay) , but I just recently came across the documentation and it says this: Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses. The runnable will be run on the thread to which this handler is attached. The time-base is SystemClock.uptimeMillis(). Time spent in deep sleep will add an additional delay to execution. I have two confusions in this: * *Is the delay achieved by adding the Runnable to the MessageQueue after a specified delay of time? Or, *Is the Runnable added immediately and the function is delayed for a specified time. If this is so there must be mechanism that the Runnable is dequeued and put somewhere else so that other items in the queue can be processed. How is the Runnable delayed and how is the MessageQueue maintained during this delay? A: runnable is immediately added to the message queue which can be seen in source code of the handler class postDelayed->sendMessageDelayed->sendMessageAtTime public boolean sendMessageAtTime(Message msg, long uptimeMillis) { boolean sent = false; MessageQueue queue = mQueue; if (queue != null) { msg.target = this; sent = queue.enqueueMessage(msg, uptimeMillis); } else { RuntimeException e = new RuntimeException( this + " sendMessageAtTime() called with no mQueue"); Log.w("Looper", e.getMessage(), e); } return sent; } queue.enqueueMessage runs a for (;;) to delay the callback. In this continuous loop message's time is checked for execution. you can see this in the source code A: The structure we call Handler runs with a Looper which contains a MessageQueue inside it. A call to Handler.post(runnable) creates a new message for MessageQueue and puts it at the last of the queue, where its time is set as SystemClock.uptimeMillis(). Looper always loops for checking messages and if there is a message and the target time has been passed, it executes the Runnable inside it. To clarify: Handler.post(runnable) sends a message with SystemClock.uptimeMillis() where on the next check, the new SystemClock.uptimeMillis() becomes bigger than the message's execution time, allowing the Looper to fetch the runnable and execute it. Now, if you use Handler.postDelayed(runnable, delay) it posts the message with SystemClock.uptimeMillis() + delay where the delay is in milliseconds, which we will call messageTime for now. What does the looper do? It checks the message, if SystemClock.uptimeMillis() is smaller than messageTime, it skips the execution. Looper always loops, so there becomes a time where SystemClock.uptimeMillis() actually becomes bigger than messageTime where the runnable becomes eligible for execution. Unless you call Handler.postAtFrontOfQueue(runnable), the calls are always put to the bottom of the queue, not the top. Finalize: Handler.post(runnable) --> messageTime = SystemClock.uptimeMillis() Handler.postDelayed(runnable, delay) --> messageTime = SystemClock.uptimeMillis() + delay. Looper executes the runnables where SystemClock.uptimeMillis() >= messageTime. That's the gist of it.
{ "language": "en", "url": "https://stackoverflow.com/questions/60545934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: os.platform() Not Working Correctly In Website I'm using the built-in 'os.platform()' function in Node.js to get the home directory of a user when they sign in to a website so they can import files. In order to specify which path to look for those files in, I need to know the OS of the user's PC. When I run the code in my local server, it runs fine, returning "win32". However, when I deploy the website, it always reads "linux", which I can only assume is the operating system of the server. How can I make sure that "os.platform()" returns the client's OS and nothing else? I should also mention that I am running this code with a console.log(os.platform()) in getInitialProps(). I've tried using navigator, window, and process.env.HOME but none of those have worked for me, as they always return undefined inside of getInitialProps().
{ "language": "en", "url": "https://stackoverflow.com/questions/62644715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: angularjs: if statement for displaying one image versus another i am new to angularjs. i am trying to display a table with some data read from a db. one of the pieces of data i receive from DB is called IS_LOCKED. if it's 1, i want to display an image of a locked padlock, else display an image of an unlocked padlock. if i do the following in angular where i write out "LOCKED" and "UNLOCKED", the output table is correct: <tr ng-repeat="x in retData.projects | orderBy:'NAME'"> <td>{{ x.NAME }}</td> <td>{{ x.IS_LOCKED==1 ? "LOCKED" : "UNLOCKED" }}</td> </tr> if i do the if statement and print out the url, it doesn't work....i get the code back and both images display, ie: "{{ x.IS_LOCKED===1 ? (locked padlock image here) : (unlocked padlock image here)}}" <tr ng-repeat="x in retData.projects | orderBy:'NAME'"> <td>{{ x.NAME }}</td> <td>{{ x.IS_LOCKED==1 ? <img src=./images/padlock_locked.png width=20 height=20> : <img src=./images/padlock_unlocked.png width=20 height=20>}}</td> </tr> tried doing some ng-switch and other things, but kept getting compile errors. sorry, new to angular...not sure if i am doing this correctly. anyone know how to do this right? A: Use ng-src <td><img ng-src="{{(x.IS_LOCKED == 1) ? './images/padlock_locked.png' : './images/padlock_unlocked.png'}}" width=20 height=20></td>
{ "language": "en", "url": "https://stackoverflow.com/questions/27893485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: toggle class content on click from nav I have a simple page with 15 elements in the Nav bar (only 4 in the jsfiddle example to keep the code short). I have a javascript that moves the border-bottom display on click on the nav bar elements but I would also like the content of the div underneath to change based on which nabber item is clicks. This is the jsfiddle. Ive tried getElementByID but I somehow cant seem to change the class under my #tabs-content div... I would like a javascript loop that changes the content of each section element's class from hide to show or show to hide depending on what the content is. This is the o'clock event in my * <li class="tab-current"><a href="#section1" onclick="display(section1) class="icon icon-dash"><span>Dashboard</span></a></li> and I would like it to change the class from hide to show for id=section2 and from show to hide for section2: <div id="tabs-content"> <section id="section1" class="show"> <p>1</p> </section> <section id="section2" class="hide"> <p>2</p> </section> </div> Any ideas please? Cheers, M. A: Is this what you are looking for? Since you have the id of each section in the href you can pull that to load the appropriate one: JS var currentTab = $(this).find("a").attr("href"); $(currentTab).show().siblings("section").hide(); Change CSS (unless you want the elements to take up space on the page its better to set to display: none): #tabs-content section.show { display: block } #tabs-content section.hide { display: none; } JSFIDDLE
{ "language": "en", "url": "https://stackoverflow.com/questions/26261525", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unit testing the obvious While trying to write test cases for a class whose functionality deals more with boiler plate code than business logic. I started wondering if unit testing is really worth for this class. But then again, when using TDD, we are advised to write test for any piece of logic we add. As an example the below class, just uses DI to inject dependencies and get config parameters to set up the running of the application. Other than unit testing if dependencies are correctly injected, or if destroy is called when running finishes(which would be unit testing the java CDI framework than my own code), what else I can unit test? import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.inject.Inject; @Singleton @Startup @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public class PipsAlprConnectionRunner { @Inject private PipsAlprConfiguration config; @Inject private PipsAlprConnector connector; @Inject private Scheduler scheduler; @Inject @PipsAlprAdapterService private ServiceStatus status; private Timer connectorTimer = null; @PostConstruct public void initialized() { status.started(); connectorTimer = scheduler.schedule(connector, 0, 1000 * config.getPollPeriodSeconds()); status.operational(); } @PreDestroy public void destroy() { connectorTimer.cancel(); connector.shutdown(); status.stopped(); } } I was unable to think of any testing scenarios to utilize TDD, on the above class, so just came up with the code, and now i am wondering what exactly can i unit test here. A: Well, a case can be made that the class does something. It changes a status, it starts a timer. You can inject mocks of these objects into the class via Mockito and then make sure, that initialized() and destroy() both do what you expect them to do to these mocks. @RunWith(MockitoJUnitRunner.class) public class PipsAlprConnectionRunner { @Mock private PipsAlprConfiguration config; @Mock private PipsAlprConnector connector; @Mock private Scheduler scheduler; @Mock private ServiceStatus status; @InjectMocks private PipsAlprConnectionRunner pipsAlprConnectionRunner ; @Test public void initialized_should_set_status_started() { pipsAlprConnectionRunner.initialized(); Mockito.verify(status).started(); } // etc. } It's pretty much a question of personal taste if you want to create one method per "point of failure" or one method per method/test. Personally, I would say that the goal is 100% coverage, so even pretty simple classes that mainly delegate should be covered. What happens if someone changes anything? The test ensures that such changes will not break existing functionality.
{ "language": "en", "url": "https://stackoverflow.com/questions/39217084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get all the categories and sub categories in PostgreSQL? I am creating a small ecommerce demo app using .net core 5 with EF core and postgres 10. I am trying to get all the categories and sub categories on my home page. Here is my category hierarchy: Men (Parent category) * *Topwear (Sub Category) * *Formal Shirts (leaf level category) *T-Shirts (leaf level category) Women * *India & Fusion Wear * *Kurtas & Suits *Sarees *FootWear * *Flat *Heels Here is my create table and insert script: CREATE TABLE category ( id uuid DEFAULT uuid_generate_v4() PRIMARY KEY NOT NULL, parent_id uuid NULL, name character varying(255) NOT NULL, short_description character varying(255) NOT NULL, activate_on date NULL, deactivate_on date NULL, url_segment character varying(255) NOT NULL, meta_keywords character varying NOT NULL, meta_description character varying NOT NULL, sort_order integer NOT NULL, created_on timestamp DEFAULT CURRENT_TIMESTAMP, created_by character varying(100), modified_on timestamp DEFAULT CURRENT_TIMESTAMP, modified_by character varying(100), is_active boolean ); INSERT INTO public.category (id, parent_id, name, short_description, activate_on, deactivate_on, url_segment, meta_keywords, meta_description, sort_order, created_on, created_by, modified_on, modified_by, is_active) VALUES ('0ca0c27c-f45b-4768-a3cb-958bfbf6df26', '6dfdf5e4-673b-4134-b4a9-3a0b14b50e6a', 'T-Shirts', 'T-Shirts', '2021-02-21', NULL, 'men-tshirts', 't shirt for mens india, t shirt for men online, polo t shirts, sport t shirt, black t shirt, blue t shirt, white t shirt', 'Men''s T-shirts - Buy T-shirts for men online in India. Choose from a wide range of polo, round, V neck & more Men''s T-shirts in various designs at Myntra.', 1, '2021-02-21 13:17:15.652506', 'glenn', NULL, '', TRUE); INSERT INTO public.category (id, parent_id, name, short_description, activate_on, deactivate_on, url_segment, meta_keywords, meta_description, sort_order, created_on, created_by, modified_on, modified_by, is_active) VALUES ('6927198d-9240-43b0-853a-0507cad3b529', '6dfdf5e4-673b-4134-b4a9-3a0b14b50e6a', 'Formal Shirts', 'Formal Shirts', '2021-02-21', NULL, 'men-formal-shirts', 'Men''s formal shirts, formal shirts for men, slim fit formal shirts for men, latest formal shirts for men, formal shirts for men online, formal shirts for men India', 'Formal Shirts for Men - Shop for trendy men''s formal shirts online in India at Myntra. ✯Free Shipping ✯Easy returns and exchanges ✯COD', 2, '2021-02-21 13:21:16.125333', 'glenn', NULL, '', TRUE); INSERT INTO public.category (id, parent_id, name, short_description, activate_on, deactivate_on, url_segment, meta_keywords, meta_description, sort_order, created_on, created_by, modified_on, modified_by, is_active) VALUES ('0d3f9e43-12a2-4f8c-a008-a45cbf15fedd', NULL, 'Women', 'Women', '2021-02-21', NULL, 'women', 'women online shopping, online shopping for women, women clothing, women dresses online', 'Online Shopping for Women. Shop Online from a wide range of womens clothing, shoes, Ladies bags & more in India @ Myntra ✯Free Shipping ✯COD ✯Easy returns and exchanges.', 0, '2021-02-21 13:26:04.447031', 'glenn', NULL, '', TRUE); INSERT INTO public.category (id, parent_id, name, short_description, activate_on, deactivate_on, url_segment, meta_keywords, meta_description, sort_order, created_on, created_by, modified_on, modified_by, is_active) VALUES ('6dfdf5e4-673b-4134-b4a9-3a0b14b50e6a', 'eb81c712-0643-45a2-b597-129a1f9892e2', 'Topwear', 'Topwear', '2021-02-21', NULL, 'top-wear', 'mens topwear', 'mens topwear', 1, '2021-02-21 13:12:30.518814', 'glenn', NULL, '', TRUE); INSERT INTO public.category (id, parent_id, name, short_description, activate_on, deactivate_on, url_segment, meta_keywords, meta_description, sort_order, created_on, created_by, modified_on, modified_by, is_active) VALUES ('eb81c712-0643-45a2-b597-129a1f9892e2', NULL, 'Men', 'Men', '2021-02-21', NULL, 'men', 'Men Topwear, Men Topwear in India, buy Men Topwear online in india, online store for Men Topwear, Shop online for Men Topwear, online shopping for Men Topwear, Online shopping for Men Topwear in India, reviews and prices', 'Men Topwear Online. Shop for Men Topwear in India ? Buy latest range of Men Topwear at Myntra ? Free Shipping ? COD ? Easy returns and exchanges', 0, '2021-02-21 13:10:29.204689', 'glenn', NULL, '', TRUE); INSERT INTO public.category (id, parent_id, name, short_description, activate_on, deactivate_on, url_segment, meta_keywords, meta_description, sort_order, created_on, created_by, modified_on, modified_by, is_active) VALUES ('731b01bd-fab7-475e-adb2-6322eb9eac68', '0d3f9e43-12a2-4f8c-a008-a45cbf15fedd', 'India & Fusion Wear', 'India & Fusion Wear', '2021-02-21', NULL, 'fusion-wear', 'indo western fusion dresses, fusion kurtis, fusion saree, fusion dress, designer fusion wear, ethnic fusion wear, fusion wear online, indo western fusion, fusion outfits', 'Buy Latest Collection of Women Fusion Wear online in India. Choose From Kurtas, Designer Sarees, Dresses, Lehenga Choli & more of brands like Mitera, Anouk, Biba & more at Myntra Fashion store ✯ COD ✯ Discounts', 1, '2021-02-21 13:32:52.616545', 'glenn', NULL, '', TRUE); INSERT INTO public.category (id, parent_id, name, short_description, activate_on, deactivate_on, url_segment, meta_keywords, meta_description, sort_order, created_on, created_by, modified_on, modified_by, is_active) VALUES ('3715c7fc-3c0e-4ee4-8fa0-dfd48e8e3a3a', '731b01bd-fab7-475e-adb2-6322eb9eac68', 'Sarees', 'Sarees', '2021-02-21', NULL, 'saree', 'saree, sarees, women saree, new saree collection, fancy saree, online saree shopping, saree blouse designs,latest saree,new saree design,latest saree design, sari online', 'Saree - Pick from the designer range of Saris online for ladies & girls. Buy formal, partywear, casual Sarees in various prints, patterns, types & more at Myntra store.', 1, '2021-02-21 13:35:26.166935', 'glenn', NULL, '', TRUE); INSERT INTO public.category (id, parent_id, name, short_description, activate_on, deactivate_on, url_segment, meta_keywords, meta_description, sort_order, created_on, created_by, modified_on, modified_by, is_active) VALUES ('34c0d8ef-19a0-4f3a-8439-6d0510cfba04', '731b01bd-fab7-475e-adb2-6322eb9eac68', 'Kurtas & Suits', 'Kurtas & Suits', '2021-02-21', NULL, 'women-kurtas-kurtis-suits', 'kurtis online, designer kurti, ladies designers kurtis, designers kurtis, designer kurtis online, designers kurtis, suits online', 'Women Kurtis & Kurtas Suits - Buy Designer Kurtas & Kurtis for Ladies online. Pick from Huge range kurtis, kurtas sets & suits for Women at Myntra ✯ COD ✯ Easy returns and exchanges', 2, '2021-02-21 13:36:59.067196', 'glenn', NULL, '', TRUE); I want to bring all the categories from my database in such a way that it is easy to bind on UI side like the above category hierarchy. Can anybody help me with the query? A: ---------- Revised The determination of Parent, Sub, Leaf is relative simple: * *Row Child id is null then Parent. *Row child id is not null and row has child row then Sub. *Otherwise leaf. The only difficultly is 2 above. Now this can be flushed out a couple ways: * *With the same basic recursive CTE apply both lead and lag functions in the main query then check for nulls. But with a hierarchy this gets messy in a hurry. So lets reject that idea. *With slight modification to the CTE the non-recursive select is Parents. In the recursive select see if the current has a child row then Sub Category. Modifying the CTE is not terribly bad, but select for it being a parent is still somewhat nasty looking. So the following abstracts this into a simple SQL function that returns the appropriate type (given that the id is known to be a child). create or replace function category_sub_or_leaf(id_in uuid) returns text language sql strict as $$ select case when exists (select null from category where parent_id = id_in ) then '(Sub Category)' else '(leaf level category)' end ; $$; And the resulting query as: with recursive heir (id, parent_id, name, short_description, sort_order, root_path, lev, cat_level) as ( select id, parent_id, name, short_description, sort_order,(name)::text, 1, '(Parent Category)' from category where parent_id is null union all select c.id, c.parent_id, c.name, c.short_description, c.sort_order, root_path || '>'||(c.name)::text, lev+1 , category_sub_or_leaf(c.id) from category c join heir h on c.parent_id = h.id ) --select * from heir; select (rpad(' ', 4*(lev-1),' ') || short_description) || ' ' || cat_level description from heir order by root_path,lev,sort_order; See revised demo: Demo also flushes out Women's Foot Ware to provide and extra layer in Sub Category. I.E 2 layers of sub category. But as I did not want that much typing I modified table to not require anything but the necessary columns. ---------- Orig What you are looking for is a recursive cte. Here the first (non-recursive term) select gets the rows which do not have parent_id defined. Then the recursive term (after union) looks back to the previous row and retrieves the child rows. (A poor description at best.) The query builds the path back to the first parent and the current depth. These generated columns are then used to provide order and indentation of the results. See Demo. with recursive heir as ( select id, parent_id, name, short_description, (name)::text path, 1 lev from category where parent_id is null union all select c.id, c.parent_id, c.name, c.short_description, path ||'>'||(c.name)::text, lev+1 from category c join heir h on c.parent_id = h.id ) select (rpad(' ', 4*(lev-1),' ') || short_description) short_description from heir order by path, lev ; Note: Demo built with Postgres 13 so function gen_random_uuid() substituted for uuid_generate_v4().
{ "language": "en", "url": "https://stackoverflow.com/questions/66624127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use ContactsContract as a Table in ContentProvider While setting the table viasetTable method in the query method of my ContentProvider, I am doing something like this : queryBuilder.settable(getTable()); where my getTable() is : private String gettable(){ String table; StringBuilder sb = new StringBuilder(); sb.append(Table_1_Name); sb.append(" LEFT JOIN "); sb.append(Table_1_Name); sb.append(" ON ("); sb.append(Table_1_Name.ID); sb.append(" = "); sb.append(Table_1_Name.ID); sb.append(")"); table = sb.toString(); return table; } Now instead of using Table_2_Name , i need to use ContactsContract.CommonDataKinds.Phone table. How can i do this. I need to filter some records in my where clause but first i dnt know how to use ContactsContract.CommonDataKinds.Phone as a Table.
{ "language": "en", "url": "https://stackoverflow.com/questions/24798716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Django how to use distinct() How to use distinct() in django what i tried: views.py def gradescales(request): grade = gradeScalesSetting.objects.all().values_list('Rounding','Configuration').distinct() print(grade) return render(request, 'Homepage/gradescale.html',{"gradeScalesSetting":grade}) the result i got: UPDATE this is data from my admin site A: Probably the way you are using won't work. Because, you are sending a list but you are probably iterating through a queryset in template. Also, the way you are using distinct won't work. Because you are using 'Rounding','Configuration' togather, hence it will generate something like this: <QuerySet [('Use Percentage Only', 'Up'), ('Use Percentage Only', 'Down'), ('Use Percentage Only', 'Half'), ...> So you can try like this(without distinct): grade = list(gradeScalesSetting.objects.all()) # < DB hit once rounding = [] configuration = [] for i in grade: if i.Rounding not in rounding: rounding.append(i.Rounding) if i.Configuration not in configuration: configuration.append(i.Configuration) return render(request, 'Homepage/gradescale.html',{"rounding":rounding, "configuration":configuration}) // in template <select> {% for r in rounding %} <option value={{r}}>{{r}}</option> {% endfor %} </select> But with distinct you might have to hit the DB twice: rounding = gradeScalesSetting.objects.all().values_list('Rounding', flat=True).distinct() configuration = gradeScalesSetting.objects.all().values_list('Configuration', flat=True).distinct()
{ "language": "en", "url": "https://stackoverflow.com/questions/59062839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Micro-Service Simulator - Dapr pubsub I am trying to create a micro-service simulator using Dapr. Currently I can publish a message to a topic and another service subscribes to it. I want to able able to simulate a process where, once the subscriber receives the message, it will make an api call to another micro-service. These services do not do anything, since it is a simulator I just want to orchestrate service calls based on the topic each micro service subscribes to.This is the flow I am after : * *[Service - A ] publishes a message to a topic *[Service - B ] Subscribes to the message published by service A and call another service, [ Service - C] publisher code --> Service -A @RestController public class ServiceAController { String TOPIC_NAME = "test"; String PUBSUB_NAME = "simulatorpubsub"; //publish a topic in redis pubsub broker @RequestMapping(path = "/hello") public String someMethod() { String str = "hello"; DaprClient client = new DaprClientBuilder().build(); client.publishEvent( PUBSUB_NAME, TOPIC_NAME, str).block(); return "Message Delivered"; } } Subscriber Code-->Service - B this is where i want to call another service , lets say C with url localhost:8091/hello-there @RequestMapping public class ServiceBController { private static final Logger logger = LoggerFactory.getLogger(ServiceBController.class); private static final HttpClient httpClient = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_2) .connectTimeout(Duration.ofSeconds(10)) .build(); RestTemplate restTemplate = new RestTemplate(); @Topic(name = "test", pubsubName = "simulatorpubsub") @PostMapping(path = "/test") public ResponseEntity<String> getCheckout(@RequestBody(required = false) CloudEvent<String> cloudEvent) throws IOException, InterruptedException { **I think this is where i am messing things up** // String url = "localhost:8091/hello-there"; // HttpRequest request = HttpRequest.newBuilder() // .GET() // .uri(URI.create(url)) // .build(); // HttpResponse response = // httpClient.send(request,HttpResponse.BodyHandlers.ofString()); logger.info("Received :" + cloudEvent.getData()); return ResponseEntity.ok("SUCCESS"); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/72093789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery Cookies not being set in Safari and IE Im using the jquery.cookie plugin to save my application data like this: $.cookie('cookieTest', 'appDataHere', { expires: 7, path: '/' }); alert( $.cookie("cookieTest") ); But for some reason the above outputs "undefined" in Safari and IE.. Any ideas? Works fine in FF and Chrome..
{ "language": "en", "url": "https://stackoverflow.com/questions/14692529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Find duplicate in data frame and change identified value I am stuck with probably a stupid and easy to solve issue. I have a trigger that code 1 when the computer key is pressed (and) and 0 when the key is released. I need to identify each trigger start and stop (i.e., first and last 1) and replace the 1 in between by 0. The data record is time (continuous, t below) and value (electrodermal activity, value). To process the data more quickly, I need to preprocess it, that is identify the 1 corresponding to the beginning and the end of the window of interest. Please find an exemple of the code: t <- seq(0.1,10,0.1) value <- rnorm(length(t), mean=1, sd=2) trig <- c(rep(0,20),rep(c(rep(1,10), rep(0,10)),4)) id <- 1:length(t) the expected output is trig_result <- c(rep(0,20), rep(c(1, rep(0,8),1,rep(0,10)),4)); length(trig_result) The use of duplicate only identify the first 1 and the last one but not the intermediate value. I have seen similar post, but none solve the identification issue. I look into dplyr function but I cannot figure out how to replace the 1 in 0 to end the preprocessing phase. Your help will be greatly appreciated. Sincerely your, A: Here's a base R solution with rle and cumsum: result <- rep(0,length(trig)) result[head(cumsum(rle(trig)$lengths)+c(1,0),-1)] <- 1 all.equal(result,trig_result) #[1] TRUE Note that this solution assumes the data begins and ends with 0. A: Here is another base R solution, using logical vectors. borders <- function(x, b = 1){ n <- length(x) d1 <- c(x[1] == b, diff(x) != 0 & x[-1] == b) d2 <- c(rev(diff(rev(x)) != 0 & rev(x[-n]) == b), x[n] == b) d1 + d2 } trig <- c(rep(0,20),rep(c(rep(1,10), rep(0,10)),4)) tr <- borders(trig) The result is not identical() to the expected output because its class is different but the values are all.equal(). trig_result <- c(rep(0,20), rep(c(1, rep(0,8),1,rep(0,10)),4)) identical(trig_result, tr) # FALSE all.equal(trig_result, tr) # TRUE class(trig_result) #[1] "numeric" class(tr) #[1] "integer" A: One option is to create a grouping index with rle or rleid (from data.table) library(data.table) out <- ave(trig, rleid(trig), FUN = function(x) x == 1 & (!duplicated(x) | !duplicated(x, fromLast = TRUE))) identical(trig_result, out) #[1] TRUE A: You'd like to find the starts and ends of runs of 1s, and remove all 1s that aren't the start or end of a run. The start of a run of ones is where the value of the current row is a 1, and the value of the previous row is a 0. You can access the value of previous row using the lag function. The end of a run of 1s is where the current row is a 1, and the next row is a zero. You can access the value of the next row using the lead function. library(tidyverse) result = tibble(Trig = trig) %>% mutate(StartOfRun = Trig == 1 & lag(Trig == 0), EndOfRun = Trig == 1 & lead(Trig == 0), Result = ifelse(StartOfRun | EndOfRun, 1, 0)) %>% pull(Result)
{ "language": "en", "url": "https://stackoverflow.com/questions/62417452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Error while adding Application Component in Worklight 6.1 I am trying to create and add application components to WL 6.1 project I am able to create the component from a WL Project as per steps given in http://goo.gl/eJ7Rq7 But when I am trying to add the same component back to some other WL Project as per steps given in http://goo.gl/U1Aipp, I dont find my component in the list of components. I get the following message on Add and Remove Application Components Pop Up window No application components are available Application components folder path can be set in - Preferences > Worklight > Templates and Components > Download Folder And also the console throws the following error Component = Sample.wlc Found component.wcp Found Image Problem while reading the File= C:\Users...\IBM\templates\Sample.wlc What might be the possibilities for the above error. Any suggestions? A: If you have added additional hooks make sure they adhere to the structure given on the link Additional hooks structure Table 1 lists the inner elements that are supported on Android and the order in which they must appear in your component.wcp Table 1. Order of inner elements for the Android environment Order Inner element 1 CordovaPlugin 2 Activities 3 UserPermissions 4 Receivers 5 Strings 6 ExternalLibraries 7 Libraries Table 2 lists the inner elements that are supported on iOS and the order in which they must appear in the schema. Table 2. Order of inner elements for the iPhone and iPad environments Order Inner element 1 CordovaPlugin 2 Files 3 Libraries Note: Some hooks result in the insertion of properties in the config.xml file or the AndroidManifest.xml file when the associated application component is added to a Worklight project. Every insertion is enclosed in comments that mention the element and application component unique name
{ "language": "en", "url": "https://stackoverflow.com/questions/23948879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pushing a Specific ViewController When Tapping on a NotificationAction Programmatically in Swift 5 I want to tap approve and go to a ViewController when app is in the background and tap decline to go another. I can fetch that tap action is successfully done but cannot figure out how to open the app and push a specific ViewController. Right now my code is like this in App Delegate: func configureNotification(){ let notificationCenter = UNUserNotificationCenter.current() let approve = UNNotificationAction(identifier: "approve", title: "Approve", options: []) let decline = UNNotificationAction(identifier: "decline", title: "Decline", options: []) let category = UNNotificationCategory(identifier: "Action Buttons", actions: [approve, decline], intentIdentifiers: [], options: []) notificationCenter.setNotificationCategories([category]) } if response.actionIdentifier == "approve" { print("approve pressed") //self.navigationController.pushViewController(PNMainVC(), animated: true) } else if response.actionIdentifier == "decline" { print("decline pressed") //self.navigationController.pushViewController(PNWelcomeScreen(), animated: true) } else { print("No custom action identifiers chosen") } completionHandler()
{ "language": "en", "url": "https://stackoverflow.com/questions/71435327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rendering a component on SelectOneMenu value - JSF PrimeFaces With PrimeFaces I'd like to render a second component if the selected value on a SelectOneMenu is equal to a given value. Possibly without sending the value of the SelecOneMenu to the server to avoid useless traffic. What do I do wrong here? I suppse should be something similar... <p:selectOneMenu value="#{helpRequest.helpKind}" id="selectList"> <f:selectItem itemLabel="One Time" itemValue="1" /> <f:selectItem itemLabel="Recurrent" itemValue="2" /> <p:ajax update="dependingComponent" /> </p:selectOneMenu> <h:panelGroup id="dependingComponent" rendered="selectlist.value== 2" > <p:outputLabel>Label: </p:outputLabel> <p:calendar value="#{calendarView.date1}" pattern="MM/dd/yyyy" /> </h:panelGroup>
{ "language": "en", "url": "https://stackoverflow.com/questions/26855227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Node JS Heroku Build Error - 'MODULE_NOT_FOUND' I hadn't made any changes to my build (all the same dependencies) and yet all of a sudden now it's crashing when I push to my staging environment. At first I was getting this - 2022-02-10T03:42:49.245470+00:00 app[web.1]: > node server.js 2022-02-10T03:42:49.245471+00:00 app[web.1]: 2022-02-10T03:42:49.311176+00:00 app[web.1]: node:internal/modules/cjs/loader:936 2022-02-10T03:42:49.311177+00:00 app[web.1]: throw err; 2022-02-10T03:42:49.311177+00:00 app[web.1]: ^ 2022-02-10T03:42:49.311178+00:00 app[web.1]: 2022-02-10T03:42:49.311181+00:00 app[web.1]: Error: Cannot find module './internal/streams/buffer_list' 2022-02-10T03:42:49.311181+00:00 app[web.1]: Require stack: 2022-02-10T03:42:49.311182+00:00 app[web.1]: - /app/node_modules/readable-stream/lib/_stream_readable.js 2022-02-10T03:42:49.311182+00:00 app[web.1]: - /app/node_modules/readable-stream/readable.js 2022-02-10T03:42:49.311182+00:00 app[web.1]: - /app/node_modules/newrelic/lib/util/logger.js 2022-02-10T03:42:49.311182+00:00 app[web.1]: - /app/node_modules/newrelic/lib/logger.js 2022-02-10T03:42:49.311183+00:00 app[web.1]: - /app/node_modules/newrelic/index.js 2022-02-10T03:42:49.311183+00:00 app[web.1]: - /app/server.js 2022-02-10T03:42:49.311186+00:00 app[web.1]: at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15) 2022-02-10T03:42:49.311190+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:778:27) 2022-02-10T03:42:49.311190+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1005:19) 2022-02-10T03:42:49.311190+00:00 app[web.1]: at require (node:internal/modules/cjs/helpers:102:18) 2022-02-10T03:42:49.311190+00:00 app[web.1]: at Object.<anonymous> (/app/node_modules/readable-stream/lib/_stream_readable.js:72:18) 2022-02-10T03:42:49.311191+00:00 app[web.1]: at Module._compile (node:internal/modules/cjs/loader:1103:14) 2022-02-10T03:42:49.311191+00:00 app[web.1]: at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10) 2022-02-10T03:42:49.311191+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:981:32) 2022-02-10T03:42:49.311191+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:822:12) 2022-02-10T03:42:49.311192+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1005:19) { 2022-02-10T03:42:49.311192+00:00 app[web.1]: code: 'MODULE_NOT_FOUND', 2022-02-10T03:42:49.311192+00:00 app[web.1]: requireStack: [ 2022-02-10T03:42:49.311192+00:00 app[web.1]: '/app/node_modules/readable-stream/lib/_stream_readable.js', 2022-02-10T03:42:49.311193+00:00 app[web.1]: '/app/node_modules/readable-stream/readable.js', 2022-02-10T03:42:49.311193+00:00 app[web.1]: '/app/node_modules/newrelic/lib/util/logger.js', 2022-02-10T03:42:49.311193+00:00 app[web.1]: '/app/node_modules/newrelic/lib/logger.js', 2022-02-10T03:42:49.311194+00:00 app[web.1]: '/app/node_modules/newrelic/index.js', 2022-02-10T03:42:49.311194+00:00 app[web.1]: '/app/server.js' 2022-02-10T03:42:49.311194+00:00 app[web.1]: ] 2022-02-10T03:42:49.311194+00:00 app[web.1]: } So I thought maybe Heroku was cracking down on newrelic or something so I uninstalled that and then now I'm getting - 2022-02-10T04:17:31.000789+00:00 app[web.1]: > node server.js 2022-02-10T04:17:31.000789+00:00 app[web.1]: 2022-02-10T04:17:31.222303+00:00 app[web.1]: node:internal/modules/cjs/loader:936 2022-02-10T04:17:31.222304+00:00 app[web.1]: throw err; 2022-02-10T04:17:31.222305+00:00 app[web.1]: ^ 2022-02-10T04:17:31.222305+00:00 app[web.1]: 2022-02-10T04:17:31.222306+00:00 app[web.1]: Error: Cannot find module '../../helpers/getConstructorName' 2022-02-10T04:17:31.222309+00:00 app[web.1]: Require stack: 2022-02-10T04:17:31.222310+00:00 app[web.1]: - /app/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js 2022-02-10T04:17:31.222310+00:00 app[web.1]: - /app/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js 2022-02-10T04:17:31.222310+00:00 app[web.1]: - /app/node_modules/mongoose/lib/index.js 2022-02-10T04:17:31.222310+00:00 app[web.1]: - /app/node_modules/mongoose/index.js 2022-02-10T04:17:31.222311+00:00 app[web.1]: - /app/server.js 2022-02-10T04:17:31.222311+00:00 app[web.1]: at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15) 2022-02-10T04:17:31.222312+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:778:27) 2022-02-10T04:17:31.222312+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1005:19) 2022-02-10T04:17:31.222312+00:00 app[web.1]: at require (node:internal/modules/cjs/helpers:102:18) 2022-02-10T04:17:31.222326+00:00 app[web.1]: at Object.<anonymous> (/app/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:12:28) 2022-02-10T04:17:31.222326+00:00 app[web.1]: at Module._compile (node:internal/modules/cjs/loader:1103:14) 2022-02-10T04:17:31.222326+00:00 app[web.1]: at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10) 2022-02-10T04:17:31.222326+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:981:32) 2022-02-10T04:17:31.222327+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:822:12) 2022-02-10T04:17:31.222327+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1005:19) { 2022-02-10T04:17:31.222327+00:00 app[web.1]: code: 'MODULE_NOT_FOUND', 2022-02-10T04:17:31.222328+00:00 app[web.1]: requireStack: [ 2022-02-10T04:17:31.222328+00:00 app[web.1]: '/app/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js', 2022-02-10T04:17:31.222328+00:00 app[web.1]: '/app/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js', 2022-02-10T04:17:31.222329+00:00 app[web.1]: '/app/node_modules/mongoose/lib/index.js', 2022-02-10T04:17:31.222329+00:00 app[web.1]: '/app/node_modules/mongoose/index.js', 2022-02-10T04:17:31.222329+00:00 app[web.1]: '/app/server.js' 2022-02-10T04:17:31.222330+00:00 app[web.1]: ] 2022-02-10T04:17:31.222330+00:00 app[web.1]: } I tried cleaning npm cache, removing node_modules folder, and npm install with both errors but they persisted. It also boots up no issue when I use npm start on my commandline, so something is up with Heroku? Any recommendations for what else I should try? Could it be the node version? I'm not 100% on this but I feel like before in the build I would notice Node 14.x and now it's 16.x. Also, package.json - { "name": "CSQ", "version": "1.0.0", "description": "", "main": "server.js", "scripts": { "devStart": "nodemon server.js" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "@sendgrid/mail": "^7.4.6", "@slack/events-api": "^3.0.1", "@slack/web-api": "^6.5.1", "base-64": "^1.0.0", "base64-stream": "^1.0.0", "concat-stream": "^2.0.0", "excel4node": "^1.7.2", "express": "^4.17.1", "form-data": "^4.0.0", "googleapis": "^89.0.0", "https": "^1.0.0", "intuit-oauth": "^4.0.0", "mailgun-js": "^0.22.0", "mongodb": "^3.6.2", "mongoose": "^6.0.12", "node-fetch": "^2.6.1", "node-geocoder": "^3.27.0", "node-quickbooks": "^2.0.39", "pdf-forms": "^0.1.1", "pdf-lib": "^1.17.0", "pdfform.js": "^1.0.14", "plotly": "^1.0.6", "popsicle": "^10.0.0", "uuid": "^8.3.2", "xmlhttprequest": "^1.8.0" }, "devDependencies": { "dotenv": "^10.0.0", "nodemon": "^2.0.12" } } A: Fix came from Heroku article https://devcenter.heroku.com/articles/troubleshooting-node-deploys This part - Don’t check in generated directories The app’s node_modules directory is generated at build time from the dependencies listed in package.json and the lockfile. Therefore, node_modules (and other generated directories like bower_components) shouldn’t be included in source control. Check with the following: git ls-files | grep node_modules If there are results, then instruct git to stop tracking node_modules: echo "node_modules" >> .gitignore git rm -r --cached node_modules git commit -am 'untracked node_modules' That did it. I don't really get why that did it when node_modules is in my gitignore AND when I've had this project up for almost a year without having this issue , but it did.
{ "language": "en", "url": "https://stackoverflow.com/questions/71059887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java code inspection show a null returning method as never null I found an interesting Lint inspection that I can't explain. I know Java crazy hidden stuff, so I'd like to understand what's going on here. Maybe I can impress my friends with super nerdy knowledge. Here's a snippet of the offending code: public void awesomeMethod() { final int[] hungryPeople = getHungryPeople(); if ( hungryPeople != null ) // <---- Lint says that this can never be null? { solveWorldHunger( true ); tellEveryone( false ); } } Here's the related (relevant) method: public int[] getHungryPeople() { // Get hungry people data from the class's Android Intent field final int[] values = mIntent.getIntArrayExtra( HUNGRY_PEOPLE ); if ( null != values ) { return Arrays.copyOf( values, values.length ); } return null; } Is there something I'm missing here? A: You are returning null outside the method, you need to return inside getHungryPeople() in case values is null. public int[] getHungryPeople() { // Get hungry people data from the class's Android Intent field final int[] values = mIntent.getIntArrayExtra( HUNGRY_PEOPLE ); if ( null != values ) { return Arrays.copyOf( values, values.length ); } // if values is null, return null return null; }
{ "language": "en", "url": "https://stackoverflow.com/questions/27005835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Talend Cloud Studio : Issue with look up mapping Good day, I’m new with Talend Cloud Studio and I’m getting stuck with the job I’m working on. Context: My company uses an API directory (Genesys). So far, we use a .csv file to insert / update contacts. This file is generated from a database extract. We want to automatize this process with a Talend Job. (A) is my Contacts database extract. (B) is my API (feeded from A) and used as look up component. Because there is not a unique field that we can use like a proper foreign key between (A) and (B), we map most of (A) fields to (B)’s so input datas can be « filtered » and redirected to two disctincs output « Inserted » and « Updated ». Please find my schema attached My issue is the following : I know for a fact that 9 rows should be considered as "to be inserted" and one row should be considered as "to be updated",yet, every output are considered as « inserted » (aka new contacts in the directory) and not « updated ». Please find my result attached If anyone as any clue about what’s happening or need more details, feel free to ask me ! Thanks by advance for your help. Regards
{ "language": "en", "url": "https://stackoverflow.com/questions/69641585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AVAssetDownloadURLSession never inited We have strange problem with background AVAssetDownloadURLSession. If you cancel downloading task and then fast close application and restart it the AVAssetDownloadURLSession will be never inited. Only restart of device will help. This problem is repeated on iOS 16.1 and 15.7, may be on the others device, but i have only this. May be there is some solution to destroy freeze background task ? I created AVAssetDownloadURLSession on the real device. let configuration = URLSessionConfiguration.background(withIdentifier: "My_HLS_DOWNLOADER") configuration.sessionSendsLaunchEvents = true self.downloadSession = AVAssetDownloadURLSession(configuration: configuration, assetDownloadDelegate: self, delegateQueue: .main) In the normal flow the download session created and everything is ok. But in the case, in which I described above session never be created.
{ "language": "en", "url": "https://stackoverflow.com/questions/74652542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Eval-when uses? After reading a lot of documentation regarding Lisp eval-when operator I still can't understand its uses, I know with this operator I can control the evaluation time of my expressions but I can't figure out any example where this may be applicable ? Best Regards, utxeee. A: Compilation of a Lisp file Take for example the compilation of a Lisp file. The Lisp compiler processes the top-level forms. These can be arbitrary Lisp forms, DEFUNs, DEFMACROS, DEFCLASS, function calls,... The whole story how the file compiler works is too complex to explain here, but a few things: * *the file compiler generates code for a (DEFUN foo () ) form. But it does not execute the defun form. Thus during compilation it is known that there is a function FOO, but the code of ˋFOOˋ is not available during the compilation. The compiler generates the code for the compiled file, but does not keep it in memory. You can't call such a function at compile time. *for macros this works slightly different: (DEFMACRO BAZ ...). The file compiler will not only compile the macro and note that it is there, but it will also make the macro available at compilation time. It is loaded into the compiler environment. Thus imagine the sequence of forms in a file: (defmacro baz ...) (defun foo () (baz ...)) This works because the file compiler knows the macro BAZ and when it compiles the code for FOO, then it can expand the macro form. Now let's look at the following example: (defun bar (form) ...) (defmacro baz (form) (bar form)) (defun foo () (baz ...)) Above will not work. Now the macro BAZ uses the function BAR by calling it. When the compiler tries to compile the function FOO, it can't expand the BAZ macro, because BAR can't be called, because the code of BAR is not loaded into the compile-time environment. There are two solutions to this: * *compile and load BAR earlier using a separate file. *Use EVAL-WHEN Example for EVAL-WHEN: (eval-when (:compile-toplevel :execute :load-toplevel) (defun bar (form) ...) ) (defmacro baz (form) (bar form)) (defun foo () (baz ...)) Now the EVAL-WHEN instructs the file compiler to actually run the DEFUN form during compilation. The effect of this is: the file compiler now knows the definition of BAR at compile time. Thus it is available later, when the file compiler need to call BAR during macro expansion of the usage of BAZ. One could use only :compile-toplevel, when the function would not be needed after the compilation of the file. If it is used later, then we need to make sure that it gets loaded. So EVAL-WHEN allows to specify if a particular piece of code should be run * *during compilation of a file *during loading of a file *during execution EVAL-WHEN is not used that often in user code. If you use it, then you should ask yourself if you really need it.
{ "language": "en", "url": "https://stackoverflow.com/questions/10674650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: The code block is missing a closing "}" character. MVC razor View I need to show the data on the basis on below condition. Need to show 5 columns and then next data in next row. I am new for MVC. Please help. @{ int count = 0; @foreach (var item in Model) { if (count == 0) { @:<tr> } <td> <p align="center">item.WeekNumber</p> </td> <td> item.OpenFirst<br> item.OpenSecond<br> item.OpenThird </td> <td><font size="6">OpenResult</font></td> <td> item.CloseFirst<br> item.CloseSecond<br> item.CloseThird </td> if (count == 5) { count = -1; @:</tr> } count++; } } A: Hello I think the problem is @ on the first foreach loop. Please remove it and try. And one more thing if you want to use html in the Razor code then you can use @Html.Raw(). (Example @Html.Raw("<tr>"))
{ "language": "en", "url": "https://stackoverflow.com/questions/36769053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Examples for using radix parameter Last step for me when finishing a JS code is letting it run trough JSLint. I forgot a few semicolons and the radix parameters at parseInt(). Well, these issues were solved quickly. But now I'm curious: Why would we need binary, octal or hexadecimal radixes? I couldn't find anything in Google. Can anyone probably give an example? Note: I'm not asking what are these radixes based on or how they look like, I'm actually looking for a scenario where you would need others than the decimal. Thanks. A: Well, let me sum this up: I guess you won't need most of them in JavaScript, which I am most familiar to and therefore it's "the language I'm thinking in". Where you probably will need the hexadecimal radix is, when you want to convert a hexadecimal color code like #ffffff to an RGB color code. The octal radix is useful regarding the Unix file permissions, but I read somewhere that it's deprecated in JavaScript. I can't imagine to have permission stuff running in JS anyway because would be a huge security issue. Or maybe just read only to output the permissions in the frontend. I couldn't find anything why we should use a binary radix though. Maybe someone can add a comment.
{ "language": "en", "url": "https://stackoverflow.com/questions/31201371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How could one to merge resource dictionaries either dynamically or in compile time? Let's say we have a resource dictionary defined like <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Resources/Styles/Colors.xaml" /> <ResourceDictionary Source="Resources/Styles/Styles.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> If I would like to switch Android specific libraries, as for the sake of example define this like <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <!-- There seem to be no way to choose based on platform. <ResourceDictionary Source="Resources/Styles/Colors.xaml" /> <ResourceDictionary Source="Resources/Styles/Styles.xaml" /> --> <ResourceDictionary Source="Resources/Styles/Android/Colors.xaml" /> <ResourceDictionary Source="Resources/Styles/Android/Styles.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> Is there an official way to do it on compile time based on target (so, multitargeting and compiling to Android)? If I try multitargeting via MSBuild, it requires the whole path to be present. Also multitargeting using OnPlatform is not available (even if not compile-time now, but maybe in the future). I could imagine some kind of a regex in MSBuild that reads this App.xaml file paths, switches files before the steps operating on this file and then back (so that version control is not affected). But seems a laborious path to figure out how to do... And maybe there is a better way? Or is there? This is related to How to properly add Microsoft Fluent Design colors to Maui application?. It appears Material definitions are quite different from Fluent ones, so it would make sense not to create fat resources that have them all but ship only those that are actually needed. A: Multi-targeting is a valid approach here, actually. You just need to merge the dictionaries during runtime, just like you would when setting a custom color theme. In your application's .csproj file, add the following <ItemGroup> elements (showing Android and Windows only, but the same applies for iOS, etc.): <!-- Platform specific XAML Android --> <ItemGroup Condition="$(TargetFramework.StartsWith('net')) == true AND $(TargetFramework.Contains('-android')) == true"> <MauiXaml Update="Resources\Styles\Platform\SpecialStyles.android.xaml"> <Generator>MSBuild:Compile</Generator> </MauiXaml> </ItemGroup> <ItemGroup Condition="$(TargetFramework.StartsWith('net')) == true AND $(TargetFramework.Contains('-android')) != true"> <MauiXaml Remove="Resources\Styles\Platform\SpecialStyles.android.xaml" /> <None Include="Resources\Styles\Platform\SpecialStyles.android.xaml" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" /> <Compile Remove="Resources\Styles\Platform\SpecialStyles.android.xaml.cs" /> <None Include="Resources\Styles\Platform\SpecialStyles.android.xaml.cs" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" /> </ItemGroup> <!-- Platform specific XAML Windows --> <ItemGroup Condition="$(TargetFramework.StartsWith('net')) == true AND $(TargetFramework.Contains('-windows')) == true"> <MauiXaml Update="Resources\Styles\Platform\SpecialStyles.windows.xaml"> <Generator>MSBuild:Compile</Generator> </MauiXaml> </ItemGroup> <ItemGroup Condition="$(TargetFramework.StartsWith('net')) == true AND $(TargetFramework.Contains('-windows')) != true"> <MauiXaml Remove="Resources\Styles\Platform\SpecialStyles.windows.xaml" /> <None Include="Resources\Styles\Platform\SpecialStyles.windows.xaml" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" /> <Compile Remove="Resources\Styles\Platform\SpecialStyles.windows.xaml.cs" /> <None Include="Resources\Styles\Platform\SpecialStyles.windows.xaml.cs" Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)" /> </ItemGroup> Then, under the Resources/Styles folder, you could create a new folder called Platform or similar and add a new Resource XAML file, e.g. SpecialStyles.android.xaml (and SpecialStyles.android.xaml.cs). Make sure to rename the class and remove the "android" from the name and add some special style you want to apply only on Android, e.g. red background for a Button: <?xml version="1.0" encoding="utf-8" ?> <ResourceDictionary xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="MauiSamples.Resources.Styles.SpecialStyles"> <Style ApplyToDerivedTypes="True" TargetType="Button"> <Setter Property="BackgroundColor" Value="Red" /> </Style> </ResourceDictionary> Also rename the class in the code-behind: namespace MauiSamples.Resources.Styles; public partial class SpecialStyles : ResourceDictionary { public SpecialStyles() { InitializeComponent(); } } Do the same for Windows but make the Button green instead: <?xml version="1.0" encoding="utf-8" ?> <ResourceDictionary xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="MauiSamples.Resources.Styles.SpecialStyles"> <Style ApplyToDerivedTypes="True" TargetType="Button"> <Setter Property="BackgroundColor" Value="Green" /> </Style> </ResourceDictionary> Finally, in your App.xaml.cs, you can merge the resource dictionary with the default resource dictionary as follows: #if ANDROID || WINDOWS ICollection<ResourceDictionary> mergedDictionaries = Current.Resources.MergedDictionaries; if (mergedDictionaries != null) { mergedDictionaries.Clear(); mergedDictionaries.Add(new MauiSamples.Resources.Styles.SpecialStyles()); } #endif Attention: Mind the preprocessor directive, this is only necessary, if the SpecialStyles class only exists for Android or Windows. If you provide a SpecialStyles class for each platform respectively with their own suffix (e.g. SpecialStyles.ios.xaml, etc.), then you wouldn't need the preprocessor directive. As I was curious about this, I quickly implemented the full sample in my open source MAUI samples GitHub repo: https://github.com/ewerspej/maui-samples Result on Android: Result on Windows: UPDATE This approach works, I only noticed that the newly created XAML files might disappear from the Solution Explorer, but they still get processed during the build. Apparently, the <MauiXaml> build action does not get reevaluated in the Solution Explorer according to the selected target framework. I regard this as an inconvenience and I'm happy to update the answer if I find a better solution or if someone has suggestions to improve it.
{ "language": "en", "url": "https://stackoverflow.com/questions/74331106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Use the controller name from Javascript in the Url.Action I am retrieving controller name from a javascript function as a string, and need to pass controller name in Url.Action. Any suggestion would be helpful. var controllerName = "MyController"; var id=1; @Url.Action("LoadAction","'"+ controllerName +"'")?id=' + id // Here i am unable to pass controllerName, defined using javascript. Thanks. A: If you want to send data from a js script to a C# controller, then you can use a Jquery-ajax call instead of @Url.Action, if I'm not mistaken, you can't even use @Url.Action on a js source code. const sendId = () => { const controllerName = 'MyController'; const id = 1; $.ajax({ contentType: 'application/json', data: { myId: id }, url: `${controllerName}/methodName`, //template string type: 'POST', success: function (data) { //... }, failed: function () { //... } }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/57186892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to pass $scope.value inside json object in Angularjs controller? I have a var data with json object defined. I want to dynamically change json fields from html and call slightly different POST APIs. e.g: var data={ $scope.value:'25', 'speciality':$scope.speciality, 'field2':'something', 'field3':'something else' } How can I change $scope.value can have 10 to 15 different values. I tried doing, var example=$scope.value; var data={ example:'25', 'speciality':$scope.speciality, 'field2':'something', 'field3':'something else' } But this too doesn't work and sends example as json field. Any help is apprciated. Thanks A: No, you cannot have a key that dynamically changes. Your best bet is to build the object at the time you need it: var obj = {}; obj[$scope.value] = 25; ... A: If you want to use a variable as a property name, then you must create an object first, then assign the data using square bracket notation. var data = { 'speciality':$scope.speciality, 'field2':'something', 'field3':'something else' } data[$scope.value] ='25'; A: var data = { 'field2':'something', 'field3':'something else' }; $scope.value.forEach(function(value) { data[value] = '25'; });
{ "language": "en", "url": "https://stackoverflow.com/questions/41837866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery random Background Color not working in Firefox? I need some help here. Checkout this fiddle: http://jsfiddle.net/ydNn6/5/ my Code: $('.start').each(function () { var color = (Math.floor(Math.random() * 256)); var hue = 'rgb(' + color + ',' + color + ',' + color + ')'; $(this).css('backgroundColor', hue); }); I want every div to be in a random greyscale color, however this is not working in Firefox, works fine in Chrome though. The funny thing is I got inspired to do this from this site: http://noemi.ro/draw.html which works fine in Firefox despite having almost the same code. Any help appreciated, thanks M EDIT: What the hell, now it's working, but not in my html, just in the fiddle... A: You forgot to include jQuery on your JS Fiddle. Add it and it works. A: I guess there´s just an order problem...just a guess * *Include jquery *Include your script at the bottom of your page in $(document).ready(function(){}) *Should work as expected.
{ "language": "en", "url": "https://stackoverflow.com/questions/23651248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to decrease the "bounce" rate when a rigidbody hits another? I have a racket and a ball, both have rigidbodies. Ball has a physics material in it, which has bounce set to 0.8. When I hit the ball with the racket, the ball goes too high up. Setting bounce to 0.0 and "Bounce Combine" to "minimum" helps it pretty much, but then it doesn't bounce at all. How can I adjust it?
{ "language": "en", "url": "https://stackoverflow.com/questions/52558346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Return plain text from a web service to Angular Typescript Please see the typescript code below: get(url: string, params?: any): Observable<Response> { let options = { }; this.setHeaders(options); return this.http.get(let url = this.configurationService.serverSettings.webservice + 'api/Product/Get', options) .pipe( // retry(3), // retry a failed request up to 3 times map((res: Response) => { return res; }), catchError(this.handleError) ); } private setHeaders(options: any, needId?: boolean){ if (needId && this.securityService) { options["headers"] = new HttpHeaders() .append('authorization', 'Bearer ' + this.securityService.GetToken()) .append('x-requestid', Guid.newGuid()); } else if (this.securityService) { options["headers"] = new HttpHeaders() .append('authorization', 'Bearer ' + this.securityService.GetToken()); } } and the web service below, (which is called by the typescript): [Route("Get")] public ActionResult<string> SayHello() { return Json("Hello Bert"); } The code works as expected i.e. "Hello Bert" is returned to the Typescript. I want to return text instead of Json. Therefore I tried changing the web service to: return "Hello Bert" and the Typescript - I added the following line before the last closing bracket of SetHeaders: options["headers"].append('Accept', 'text/plain'); Now the web service is called, however the callback in the Typescript is not reached at all. What is the problem?
{ "language": "en", "url": "https://stackoverflow.com/questions/59696771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reading a message in inbox from a particular contact I want to read sms from my inbox. Here i want to read a specific message. Suppose mark has sent me a message i just want to make a query which will return the cursor indicating only Mark message .i have tried something like this but it is not working for me Cursor cursor = contentResolverSender.query( Uri.parse("content://sms/inbox"), null,"address =?" ,smsNo, null);
{ "language": "en", "url": "https://stackoverflow.com/questions/15056419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }