_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d5601
train
I solved the same problem with below commands docker run --mount type=bind,source="$(pwd)"/data,target=/home/data -it <name_of_container> Note "-it conainter_name" should be the last flags. A: It sounds like mounting a host directory in the container is what you're looking for. You won't have to restart the container to pick up changes to the mounted directory. Link to relevant docs. A: I wonder if the ADD command could help you accomplish your goal. For instance, given the Dockerfile line: ADD /Users/userX/myappfiles /appfiles and the command line: docker run myapp --input /myappfiles myapp would be able to access /Users/userX/myappfiles on the local filesystem to fetch its inputs.
unknown
d5602
train
I was able to achieve the functionality of limiting the number of sessions for the same user. However, my solution (code below) doesn't provide any data-protected layer in order to restrict CRUD operation performed from another session. I think you can achieve this if you restrict operation based on user_id and session_id DB id user_id client_id 00m5nqcvpk9bhqv7rbllq5hsi4 198 14 34ssnqcvpk9xxqv7rbll4354fdf 123 42 id will be session_id (PHP SID) Method /** * * @param int $userId * @param int $clientId * @return type */ public function validateActiveSession($userId, $clientId) { if (empty($userId)) { $userId = $this->getResourceManager()->getIdentity()->getId(); } if (empty($clientId)) { $clientId = $this->getResourceManager()->getIdentity()->getClientId(); } $sessionManager = $this->getServiceLocator()->get('Zend\Session\SessionManager'); $id = $sessionManager->getId(); $userModel = $this->getResourceManager()->getuserModel(); $sIdUserExist = $userModel->getUserActiveSession('', '', $id); if (empty($sIdUserExist)) { $userModel->addUserSessionBySidAndUserClientId($id, $userId, $clientId); } } Repository public function addUserSessionBySidAndUserClientId($sessionId, $userId, $clientId) { $em = $this->_em->getConnection(); $sql = "INSERT INTO `user_session`(`id`, `user_id`, `client_id`) VALUES (:id,:user_id,:client_id)"; $params = array('id' => $sessionId, 'user_id' => $userId, 'client_id' => $clientId); $stmt = $em->prepare($sql); return $stmt->execute($params); } public function getActiveUserSession($userId, $clientId, $sessionId) { $rsm = new ResultSetMapping(); $rsm->addScalarResult('id', 'id'); $rsm->addScalarResult('user_id', 'user_id'); $userIdClause = $clientIdClause = $andClause = $sessionIdClause = ''; if (!empty($userId)) { $userIdClause = 'user_id = :user_id'; } if (!empty($clientId)) { $clientIdClause = ' and client_id = :client_id'; } if (!empty($userId) && !empty($sessionId)) { $andClause = ' and '; } if (!empty($sessionId)) { $sessionIdClause = 'id = :id'; } $query = $this->_em->createNativeQuery('SELECT id,user_id FROM user_session WHERE ' . $userIdClause . $clientIdClause . $andClause . $sessionIdClause, $rsm); if (!empty($userId)) { $query->setParameter('user_id', $userId); } if (!empty($clientId)) { $query->setParameter('client_id', $clientId); } if (!empty($sessionId)) { $query->setParameter('id', $sessionId); } return $query->getResult(); } once user logged-in check for active sessions $sameActiveUser = count($userModel->getActiveUserSession($userId, $clientId, '')); if ($sameActiveUser == 2) { //already 2 active session than restrict 3rd return "session already present"; } else { $this->validateActiveSession($userId, $clientId); }
unknown
d5603
train
In this code, you are using several packages: express-session, which manages the session itself but delegates how the session is saved to connect-session-sequelize. So the problem is that connect-session-sequelize is trying to save session data in the database, but it cannot because there is no table for sessions. As written in the documentation of this package (https://www.npmjs.com/package/connect-session-sequelize): If you want SequelizeStore to create/sync the database table for you, you can call sync() against an instance of SequelizeStore along with options if needed. So try creating the store, attaching it to the session manager, and then initializing it (I did not test this code): // Setting up session var myStore = new SequelizeStore({ db: db }); app.use( session({ secret: "shhh", store: myStore, resave: false, saveUninitialized: true, cookie: { maxAge: 1000000 } }) ); myStore.sync();
unknown
d5604
train
I seemed to have fixed the problem by setting a trigger in the control template, which binds to the RadioButton's IsMouseOver, and sets a custom DependencyProperty on the UserControl. Something like: <ControlTemplate TargetType="{x:Type RadioButton}"> <WPFTest:TestUC x:Name="UC" /> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="ShowCancel" Value="True" TargetName="UC"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> I'm still confused as to why the Mouse Capture falsifies IsMouseOver on the UserControl child of the RadioButton however. Can anyone shed some light on this? A: After the event is handled by the RadioButton , it is only set as handled but in reality it still bubbles up. So you just need to specify that you want to handle handled events too. For that you need to look at handledEventsToo. Unfortunately I don't think it can be set in xaml. only code. A: Very interesting problem. I myself would like to know more of why the UserControl IsMouseOver changes to false when the TextBlock(s) in its visuals are mouse downed upon. However, here is another way to solve it ... maybe you will like this approach better. Instead of using RadioButton (since you are retemplating it) why don't you just use Control? (I think IsMouseOver is getting changed to false due to the fact that it is a Button derived control.) Following is the xaml for the Window ... <Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication1" Title="Window1" Width="300" Height="300" > <Window.Resources> <Style TargetType="{x:Type Control}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type Control}"> <local:UserControl1/> </ControlTemplate> </Setter.Value> </Setter> </Style> </Window.Resources> <Border BorderBrush="Black" BorderThickness="2"> <StackPanel> <Control x:Name="OptionButton" Height="100"/> <TextBlock Text="{Binding ElementName=OptionButton, Path=IsMouseOver}"/> </StackPanel> </Border> </Window> EDIT: I just wanted to add ... that if you're okay with the above approach ... then, the right thing to do is probably to just use the UserControl in the Window's visual tree versus retemplating a Control. So ... like this: <Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication1" Title="Window1" Width="300" Height="300" > <Border BorderBrush="Black" BorderThickness="2"> <StackPanel> <local:UserControl1 x:Name="OptionButton" Height="100"/> <TextBlock Text="{Binding ElementName=OptionButton, Path=IsMouseOver}"/> </StackPanel> </Border> </Window>
unknown
d5605
train
I found another way around to accomplish what I wanted, so instead of using weight I used the screen width in order to get a relative width. and to add margin, I just added an empty row before the row that contains the button and text. Here is the full code for the interested. private fun addRow(content: Editable) { val tl = findViewById<TableLayout>(R.id.main_table) val margin = TableRow(this) val tr_head = TableRow(this) margin.id = View.generateViewId() tr_head.id = View.generateViewId() val tabParams = TableRow.LayoutParams( TableRow.LayoutParams.MATCH_PARENT, 84 ) tr_head.setLayoutParams(tabParams) val label = TextView(this) label.id = View.generateViewId() label.text = content label.setTextColor(Color.WHITE) val displayMetrics = DisplayMetrics() windowManager.defaultDisplay.getMetrics(displayMetrics) label.width = (displayMetrics.widthPixels / 3)*2 label.setPadding(50, 0,0,0) tr_head.addView(label) val btn = Button(this) btn.id = View.generateViewId() btn.width = (displayMetrics.widthPixels / 3) - 50 btn.setBackgroundColor(Color.RED) btn.setText("Remove") btn.setOnClickListener { tl.removeView(tr_head) tl.removeView(margin) } label.id = View.generateViewId() val filler = TextView(this) filler.id = View.generateViewId() margin.addView(filler) tr_head.addView(btn) tl.addView( margin, TableLayout.LayoutParams( TableRow.LayoutParams.MATCH_PARENT, 20 ) ) tl.addView( tr_head, tabParams ) }
unknown
d5606
train
My understanding is that this is expected. Because you are copying files, the copy includes not only the file itself but also its metadata. If the file in the source folder doesn't have values in those columns, it does make sense that if you copy it to a destination folder, those same columns shouldn't have values either. Now, why some files (docx, pptx, etc.) do have values in the destination? Probably because of the SharePoint document parser feature (Document Property Promotion and Demotion). So in your case what you can do is, instead of copying the files, download/upload them using for instance code like this.
unknown
d5607
train
Obtain a DataFrame from your XML source and save into a Row or Column table in SnappyData. Something like this if SQL is your preferred choice .... (Refer to docs for DF API) snappy> CREATE external TABLE myXMLTable USING com.databricks.spark.xml OPTIONS (path "pathToYourXML.xml", rowTag "Refer to docs link below"); snappy> create table myInMemoryTable using column as (select * from myXMLTable); https://github.com/databricks/spark-xml
unknown
d5608
train
Are you doing this on the main thread? You can either use the main queue for the delegate (undesirable, because you're doing processing first) or: dispatch_async(dispatch_get_main_queue(), ^{ imageView.image = ...; }); A: Is imageView set correctly? If imageView is actually nil, your call to [imageView setImage:image]; will silently do nothing.
unknown
d5609
train
XD I'm really understanding your situation but I think that the solution will be one of two :) : 1-make a program with any programming language you can use and try to load the files one by one to do what you want 2-(the easiest one)Try to find a good converter to convert all your files to SQL tables then come here to this site and ask how to delete duplicated rows from different SQL tables after doing that reconvert the SQL tables to EXCEL files again and it will be done (y) ;)
unknown
d5610
train
This is how you would do that: list1 = [['[x]homework', '[x]eat','stretch'], ['[x]final', 'school'], ['sleep','midterm']] for x in range(0,len(list1)-1): lst = list1[x] count = 0 to_be_removed = [] for str in lst: if str[0:3] == "[x]": to_be_removed.append(str) list1[-1].append(str[3:]) count += 1 for str in to_be_removed: lst.remove(str) print(f"{count} items were removed from list {x+1}" ) print(list1) A: list1 = [['[x]homework', '[x]eat','stretch'], ['[x]final', 'school'], ['sleep','midterm']] new_list = [list() for i in range(len(list1))] new_list[2] = list1[2] items = 0 for i in range(len(list1)-1): for j in list1[i]: if "[x]" in j: new_list[2].append(j.replace("[x]", "")) items += 1 else: new_list[i].append(j) print(list1, new_list, items) A: I think you have a data structure problem. Your code shouldn't match user input, you should get away from that as soon as possible, and separate display and storage. That being said, you can take a step towards those changes by still discarding the silliness asap: Example of running: $ python code.py [['[x]homework', '[x]eat', 'stretch'], ['[x]final', 'school'], ['sleep', 'midterm']] changed count is 0 [['stretch'], ['school'], ['sleep', 'midterm', 'homework', 'eat', 'final']] with source code like below def main(): list1 = [['[x]homework', '[x]eat','stretch'], ['[x]final', 'school'], ['sleep','midterm']] print(list1) count, list2 = process(list1) print(f'changed count is {count}') print(list2) def parse(silly_item): if silly_item.startswith('[x]'): finished = True raw_item = silly_item[3:] else: finished = False raw_item = silly_item return finished, raw_item def process(silly_data_format): todos, done = silly_data_format[:-1], silly_data_format[-1] count = 0 new_todos = [] new_done = done[:] for todo in todos: new_todo = [] for silly_item in todo: finished, raw_item = parse(silly_item) target = new_done if finished else new_todo target.append(raw_item) new_todos.append(new_todo) new_silly_data_format = new_todos + [new_done] return count, new_silly_data_format if __name__ == '__main__': main()
unknown
d5611
train
You need to call changeView on the reference to the calendar object itself. In the example below that would be named calendar var calendarEl = document.getElementById('calendar'); var calendar = new FullCalendar.Calendar(calendarEl, { initialView: 'dayGridMonth' }); calendar.render(); }); This needs to be a global variable, not local to a setup function So the code you want would be, in this case, would be dateClick: function(info) { if(info.view.type=="dayGridMonth"){ calendar.changeView("timeGridDay",info.dateStr); } }
unknown
d5612
train
Try adding Application.DisplayAlerts = False prior to the main code, and set it back to Application.DisplayAlerts = True after.
unknown
d5613
train
Solved it. I did include id repackage to plugin spring-boot-maven-plugin on module pet-clinic-data. I did include the dependency mockito-core to plugin wro4j-maven-plugin on module pet-clinic-web. A: I'm on the same project pet-clinic-web, and for me was enough to add the dependency mockito-core to wro4j-maven-plugin. Though when the project was on jdk 8 I didn't have this problem. The problem started when I update to jdk 11.
unknown
d5614
train
Many of which are guaranteed to impact our codebase. I wouldn't be so sure. We are building not just Roslyn with itself, but the rest of Visual Studio, the entire .NET Framework, Windows, ASP.NET, and more with Roslyn, and have been doing so for two years now. We did test passes where we literally downloaded thousands of projects from GitHub so we could verify that code that built with the old compiler would build with the new compiler. We take compatibility with the old compilers very, very seriously. with so many bugs out in the open. There's a few things to know about that bug count: * *That includes not just the compiler, but also IDE, refactorings, debugger, and a lot of other components. *That count includes bugs for features that haven't shipped yet. For example, a few days ago we started testing a new compiler feature that we hope to ship in C# 7, and filed 30-40 bugs on various IDE features that need to be updated to know about it. *We file bugs for things that don't affect you. For example, any time we have a problem with one of our automated tests, we file a bug. Any time somebody realizes "huh, we could clean this up", we file a bug. We even use "issues" to discuss future language proposals as a forum, rather than a bug itself. Right now I have an issue against me which is to write a blog post that needs to be written. *Some of these aren't actually bad bugs; they include issues like "I wish the compiler gave better error messages." *Many of them involve running Roslyn on Linux or Mac, which is still actively under development. If we filter to the actual list of "compiler" bugs and filter out compiler bugs for features that haven't shipped, the count is much much smaller. And the most important bit: *There were always bugs, in every release of the compiler. The compiler is a piece of software being written by humans, so it is by definition not perfect. We're just choosing to air our dirty laundry on GitHub instead of hiding it behind our firewall! This is of course not to say that you won't hit a bug, but we've tried our best to make Roslyn as best a compiler as we can, with the best compatibility we can. If we had to write a document that said "here's all the ways your code isn't compatible", that would mean we failed at that. As usual, always test a bit of stuff before deploying, but that's no different than anything else.
unknown
d5615
train
Have you tried using a templates folder inside your app? Something like this: my_project/ |-- new_app/ |-- templates/ |-- new_app/ |-- admin/ |-- change_list.html |-- templates/ A: When several applications provide different versions of the same resource (template, static file, management command, translation), the application listed first in INSTALLED_APPS has precedence. See docs. Change: INSTALLED_APPS = ( 'django.contrib.admin', ... 'new_app', ) To: INSTALLED_APPS = ( 'new_app', 'django.contrib.admin', ... ) Your templates in new_app should now be found before the templates in contrib.admin. A: I know this is old but I came here because I was having a very similar problem. James Parker got me on the right track by looking at extended versions of ModelAdmin. I had a Mixin and an overloaded Admin like so: class EvaluationAdmin(ExportMixin, MarkdownxModelAdmin):. It turned out the ExportMixin was hardcoding the template preventing the normal template override from working. I did not find a solution mentioned anywhere and this might not be the most elegant but I fixed it by subclassing ExportMixin and hardcoding the template to my overridden one instead. Just be sure to start with the copy the mixin was using to keep any additional features it was providing ('admin/import_export/change_list_export.html' in this case). class EvaluationExportMixin(ExportMixin): change_list_template = 'admin/eval/evaluation/change_list_export.html' class EvaluationAdmin(EvaluationExportMixin, MarkdownxModelAdmin): ... Hopefully this might point someone else to where to look and one possible work-around. A: Go to page 607. Custom template options The Overriding admin templates section describes how to override or extend the default admin templates. Use the following options to override the default templates used by the ModelAdmin views: And there you will got options how to override templates for specific models with ModelAdmin. The same(i didn't compare, but seems similar) docs can be found on django site: Custom template options
unknown
d5616
train
As previous answers mentioned you can use the command: kubectl delete pod --field-selector=status.phase=={{phase}} To delete pods in a certain "phase", What's still missing is a quick summary of what phases exist, so the valid values for a "pod phase" are: Pending, Running, Succeeded, Failed, Unknown And in this specific case to delete "error" pods: kubectl delete pod --field-selector=status.phase==Failed A: If this pods created by CronJob, you can use spec.failedJobsHistoryLimit and spec.successfulJobsHistoryLimit Example: apiVersion: batch/v1 kind: CronJob metadata: name: my-cron-job spec: schedule: "*/10 * * * *" failedJobsHistoryLimit: 1 successfulJobsHistoryLimit: 3 jobTemplate: spec: template: ... A: Here's a one liner which will delete all pods which aren't in the Running or Pending state (note that if a pod name has Running or Pending in it, it won't get deleted ever with this one liner): kubectl get pods --no-headers=true |grep -v "Running" | grep -v "Pending" | sed -E 's/([a-z0-9-]+).*/\1/g' | xargs kubectl delete pod Here's an explanation: * *get all pods without any of the headers *filter out pods which are Running *filter out pods which are Pending *pull out the name of the pod using a sed regex *use xargs to delete each of the pods by name Note, this doesn't account for all pod states. For example, if a pod is in the state ContainerCreating this one liner will delete that pod too. A: You can do it on two ways. $ kubectl delete pod $(kubectl get pods | grep Completed | awk '{print $1}') or $ kubectl get pods | grep Completed | awk '{print $1}' | xargs kubectl delete pod Both solutions will do the job. A: You can do this a bit easier, now. You can list all completed pods by: kubectl get pod --field-selector=status.phase==Succeeded delete all completed pods by: kubectl delete pod --field-selector=status.phase==Succeeded and delete all errored pods by: kubectl delete pod --field-selector=status.phase==Failed A: If you would like to delete pods not Running, it could be done with one command kubectl get pods --field-selector=status.phase!=Running Updated command to delete pods kubectl delete pods --field-selector=status.phase!=Running A: Here you go: kubectl get pods --all-namespaces |grep -i completed|awk '{print "kubectl delete pod "$2" -n "$1}'|bash you can replace completed with CrashLoopBackOff or any other state... A: I think pjincz handled your question well regarding deleting the completed pods manually. However, I popped in here to introduce a new feature of Kubernetes, which may remove finished pods automatically on your behalf. You should just define a time to live to auto clean up finished Jobs like below: apiVersion: batch/v1 kind: Job metadata: name: remove-after-ttl spec: ttlSecondsAfterFinished: 86400 template: ... A: Here is a single command to delete all pods that are terminated, Completed, in Error, etc. kubectl delete pods --field-selector status.phase=Failed -A --ignore-not-found=true If you are using preemptive GKE nodes, you often see those pods hanging around. Here is an automated solution I setup to cleanup: https://stackoverflow.com/a/72872547/4185100
unknown
d5617
train
the code {ReactDom.createPortal(<Navbar />, document.getElementById('navbarRoot'))} goes inside the return statement. eg: import Navbar from "component" function MainPage(){ ... ... return( <> ... {ReactDom.createPortal(<Navbar />, document.getElementById('navbarRoot'))} </> ); } A: If you meant to render the whole NavBar component as a portal then return in the Navbar should be like below. import { useState } from "react"; import ReactDOM from "react-dom"; const domNode = document.getElementById("navbarRoot"); const Navbar = () => { const [isOpen, setIsOpen] = useState(false); const navButtonHandler = () => { setIsOpen(!isOpen); }; const navContent = ( <> <nav className="navbar"> <span>{/* <img src={logo} alt="home" className="logo" /> */}</span> <div className={`menuMask ${isOpen && "open"}`} onClick={navButtonHandler} ></div> <div className={`menuContainer ${isOpen && "open"}`}> <ul className={`navitems ${isOpen && "open"}`}> <a href="/" className="home"> <li>Home</li> </a> ... ... </ul> </div> <div className={`navToggle ${isOpen && "open"}`} onClick={navButtonHandler} > <div className="bar"></div> </div> </nav> </> ); return ReactDOM.createPortal(navContent, domNode); }; Use Navbar in any other place. In spite of where you try to render it in your component tree, it will always appear in the div with navbarRoot as the id. export default function App() { return ( <div className="App"> <Navbar /> </div> ); }
unknown
d5618
train
Not a flutter guy. But I'll try to help you. If you look into flutter source and search your error message you'll get a clue what to do. So at text.dart we can find that dart check that you fill data field with a String when you call a constructor. So my bet is that you misplace toString here mydata[0][i.toString()] A: Text widget needs a string to be initialized. As vsenik mentioned, you are probably giving a null instead of string to a text widget. The problem is in one of the below lines. mydata[1][i.toString()][k] mydata[0][i.toString()] You could use debug or insert a print statement before these lines. A: I think Yalin is perfectly right, but I would add: Dart has some very useful operators to prevent that kind of errors, which can be catastrofic on real world usage. You can check them here. In particular you could use mydata[0][i.toString()] ?? "Default text" to prevent this kind of problem when an object is null
unknown
d5619
train
The Vavr.io library (former Javaslang) also have the Option class which is serializable: public interface Option<T> extends Value<T>, Serializable { ... } A: It's a curious omission. You would have to mark the field as transient and provide your own custom writeObject() method that wrote the get() result itself, and a readObject() method that restored the Optional by reading that result from the stream. Not forgetting to call defaultWriteObject() and defaultReadObject() respectively. A: This answer is in response to the question in the title, "Shouldn't Optional be Serializable?" The short answer is that the Java Lambda (JSR-335) expert group considered and rejected it. That note, and this one and this one indicate that the primary design goal for Optional is to be used as the return value of functions when a return value might be absent. The intent is that the caller immediately check the Optional and extract the actual value if it's present. If the value is absent, the caller can substitute a default value, throw an exception, or apply some other policy. This is typically done by chaining fluent method calls off the end of a stream pipeline (or other methods) that return Optional values. It was never intended for Optional to be used other ways, such as for optional method arguments or to be stored as a field in an object. And by extension, making Optional serializable would enable it to be stored persistently or transmitted across a network, both of which encourage uses far beyond its original design goal. Usually there are better ways to organize the data than to store an Optional in a field. If a getter (such as the getValue method in the question) returns the actual Optional from the field, it forces every caller to implement some policy for dealing with an empty value. This will likely lead to inconsisent behavior across callers. It's often better to have whatever code sets that field apply some policy at the time it's set. Sometimes people want to put Optional into collections, like List<Optional<X>> or Map<Key,Optional<Value>>. This too is usually a bad idea. It's often better to replace these usages of Optional with Null-Object values (not actual null references), or simply to omit these entries from the collection entirely. A: A lot of Serialization related problems can be solved by decoupling the persistent serialized form from the actual runtime implementation you operate on. /** The class you work with in your runtime */ public class My implements Serializable { private static final long serialVersionUID = 1L; Optional<Integer> value = Optional.empty(); public void setValue(Integer i) { this.value = Optional.ofNullable(i); } public Optional<Integer> getValue() { return value; } private Object writeReplace() throws ObjectStreamException { return new MySerialized(this); } } /** The persistent representation which exists in bytestreams only */ final class MySerialized implements Serializable { private final Integer value; MySerialized(My my) { value=my.getValue().orElse(null); } private Object readResolve() throws ObjectStreamException { My my=new My(); my.setValue(value); return my; } } The class Optional implements behavior which allows to write good code when dealing with possibly absent values (compared to the use of null). But it does not add any benefit to a persistent representation of your data. It would just make your serialized data bigger… The sketch above might look complicated but that’s because it demonstrates the pattern with one property only. The more properties your class has the more its simplicity should be revealed. And not to forget, the possibility to change the implementation of My completely without any need to adapt the persistent form… A: If you would like a serializable optional, consider instead using guava's optional which is serializable. A: If you want to maintain a more consistent type list and avoid using null there's one kooky alternative. You can store the value using an intersection of types. Coupled with a lambda, this allows something like: private final Supplier<Optional<Integer>> suppValue; .... List<Integer> temp = value .map(v -> v.map(Arrays::asList).orElseGet(ArrayList::new)) .orElse(null); this.suppValue = (Supplier<Optional<Integer>> & Serializable)() -> temp==null ? Optional.empty() : temp.stream().findFirst(); Having the temp variable separate avoids closing over the owner of the value member and thus serialising too much. A: Just copy Optional class to your project and create your own custom Optional that implements Serializable. I am doing it because I just realized this sh*t too late. A: the problem is you have used variables with optional. the basic solution to avoid this, provide the variable without optional and get them as optional when you call the getter like below. Optional<Integer> value = Optional.empty(); to Integer value = null; public class My implements Serializable { private static final long serialVersionUID = 1L; //Optional<Integer> value = Optional.empty(); //old code Integer value = null; //solution code without optional. public void setValue(Integer value ) { //this.value = Optional.of(value); //old code with Optional this.value = value ; //solution code without optional. } public Optional<Integer> getValue() { //solution code - return the value by using Optional. return Optional.ofNullable(value); } }
unknown
d5620
train
You need to find the first weekday (eg. Wednesday) from your data and set ticks according to that. It can be achived using the following code: var weekday = new Array(7); weekday[0]= 'sunday'; weekday[1] = 'monday'; weekday[2] = 'tuesday'; weekday[3] = 'wednesday'; weekday[4] = 'thursday'; weekday[5] = 'friday'; weekday[6] = 'saturday'; var startDay = weekday[new Date(chartData[0].timestamp).getDay()]; var week = 1; var xAxis = d3.svg.axis() .scale(xScale) .orient('bottom') .tickFormat(function() { return 'week ' + week++ }) .ticks(d3.time[startDay]); <!DOCTYPE html> <body> <style> path { fill: #CCC; } .line { fill: none; stroke: #000; stroke-width: 5px;} </style> <div id="chart-container"> <svg id="chart"></svg> </div> <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.min.js"></script> <script src="//d3js.org/d3.v3.min.js"></script> <script> var now = moment(); var chartData = [ { timestamp: moment(now).subtract(27, 'days').format('DD-MMM-YY'), value: 40 }, { timestamp: moment(now).subtract(25, 'days').format('DD-MMM-YY'), value: 36 }, { timestamp: moment(now).subtract(24, 'days').format('DD-MMM-YY'), value: 33 }, { timestamp: moment(now).subtract(21, 'days').format('DD-MMM-YY'), value: 35 }, { timestamp: moment(now).subtract(20, 'days').format('DD-MMM-YY'), value: 35 }, { timestamp: moment(now).subtract(18, 'days').format('DD-MMM-YY'), value: 33 }, { timestamp: moment(now).subtract(17, 'days').format('DD-MMM-YY'), value: 33 }, { timestamp: moment(now).subtract(16, 'days').format('DD-MMM-YY'), value: 33 }, { timestamp: moment(now).subtract(15, 'days').format('DD-MMM-YY'), value: 32 }, { timestamp: moment(now).subtract(13, 'days').format('DD-MMM-YY'), value: 35 }, { timestamp: moment(now).subtract(11, 'days').format('DD-MMM-YY'), value: 31 }, { timestamp: moment(now).subtract(10, 'days').format('DD-MMM-YY'), value: 28 }, { timestamp: moment(now).subtract(9, 'days').format('DD-MMM-YY'), value: 32 }, { timestamp: moment(now).subtract(8, 'days').format('DD-MMM-YY'), value: 30 }, { timestamp: moment(now).subtract(7, 'days').format('DD-MMM-YY'), value: 33 }, { timestamp: moment(now).subtract(6, 'days').format('DD-MMM-YY'), value: 36 } ]; //data could have a shorter date range of eg, 1 or 2 weeks //ideally we want to still display 'week 1, 2, 3, 4' etc in the axis. //alternatively display dates instead // var chartData = [ // { timestamp: moment(now).subtract(27, 'days').format('DD-MMM-YY'), value: 40 }, // { timestamp: moment(now).subtract(25, 'days').format('DD-MMM-YY'), value: 36 }, // { timestamp: moment(now).subtract(24, 'days').format('DD-MMM-YY'), value: 33 }, // { timestamp: moment(now).subtract(21, 'days').format('DD-MMM-YY'), value: 35 }, // { timestamp: moment(now).subtract(20, 'days').format('DD-MMM-YY'), value: 35 } // ]; let lastObj = chartData[chartData.length - 1]; let lastObjTimestamp = lastObj.timestamp; let lastAndNow = moment(lastObjTimestamp).diff(now, 'days'); console.log('difference between last entry ' + lastObjTimestamp + ' and today: ' + lastAndNow); var chartWrapperDomId = 'chart-container'; var chartDomId = 'chart'; var chartWrapperWidth = document.getElementById(chartWrapperDomId).clientWidth; var margin = 40; var width = chartWrapperWidth - margin; var height = 500 - margin * 2; var xMin = d3.time.format('%d-%b-%y').parse(chartData[0].timestamp); var xMax = d3.time.format('%d-%b-%y').parse(chartData[chartData.length-1].timestamp); //set the scale for the x axis var xScale = d3.time.scale(); xScale.domain([xMin, xMax]); xScale.range([0, width]); var yScale = d3.scale.linear() .range([height, 0]) .nice(); console.log('no5 ', chartData[5].timestamp) var weekday = new Array(7); weekday[0]= 'sunday'; weekday[1] = 'monday'; weekday[2] = 'tuesday'; weekday[3] = 'wednesday'; weekday[4] = 'thursday'; weekday[5] = 'friday'; weekday[6] = 'saturday'; var startDay = weekday[new Date(chartData[0].timestamp).getDay()]; var week = 1; var xAxis = d3.svg.axis() .scale(xScale) .orient('bottom') //.tickFormat(d3.time.format('%d-%b')); //.tickFormat(d3.time.format('%b')) //tickFormat(d3.time.format('%W')); .tickFormat(function() { return 'week ' + week++ }) .ticks(d3.time[startDay]); var yAxis = d3.svg.axis() .scale(yScale) .orient('left'); var line = d3.svg.line() .x(function(d) { return xScale(d.timestamp); }) .y(function(d) { return yScale(d.value); }); var svg = d3.select('#' + chartDomId) .attr('width', width + margin * 2) .attr('height', height + margin * 2) .append('g') .attr('transform', 'translate(' + margin + ',' + margin + ')'); chartData.forEach(function(d) { d.timestamp = d3.time.format('%d-%b-%y').parse(d.timestamp); d.value = +d.value; }); yScale.domain(d3.extent(chartData, function(d) { return d.value; })); svg.append('g') .attr('class', 'axis x-axis') .attr('transform', 'translate(0,' + height + ')') .call(xAxis); svg.append('g') .attr('class', 'axis y-axis') .call(yAxis) .append('text') .attr('transform', 'rotate(-90)') .attr('y', 6) .attr('dy', '.71em') .style('text-anchor', 'end'); svg.append('path') .datum(chartData) .attr('class', 'line') .attr('d', line); </script> </body> A: Since in many cases d3 forces judgments on how many ticks to place along your axes regardless of how many you specify, this is how I went about defining the specific ticks that I wanted: var tickLabels = ['Week 1', 'Week 2', 'Week 3', 'Week 4', 'Week 5']; d3.svg.axis() .scale(x) .orient("bottom") .tickValues([0, 7, 14, 21, 28]) .tickFormat(function(d, i) { return tickLabels[i] }); .tickValues specifies the data points (aka dates) where I want my ticks to be placed, while tickFormat changes each of those respective numbers to "Week 1", "Week 2", etc.
unknown
d5621
train
if you only want it to run once the value is changed you need to set up a BOOL. Within your if pitch > 5 statement setup another if that checks that BOOL if((pitchfloat >= basePitch+5) || (pitchfloat <= basePitch-5)) { if (firstTimeBOOLCheckisTrue == NO) { firstTimeBOOLCheckisTrue = YES; [self doSomething]; } } (void *)doSomething{ if (imReadytoCheckPitchAgain == YES){ firstTimeBOOLCheckisTrue = NO; }
unknown
d5622
train
You are mixing double-quote " and single-quote '. Replace last line of your code inside while loop with following and it should work as expected. '</td><td><a href="Test.php?name='.$Row['Name'].'&begin='.$begin.'&finish='.$finish.'">'.$Row['Items On Sale'].'</a></td></tr>'; From your post edit, try this: '</td><td><a href="Test.php?name='.$Row['Name'].'&begin='.$begin.'&finish='.$end.'">'.$Row['Items On Sale'].'</a></td></tr>';
unknown
d5623
train
The IQueryable is just that a queryable object not the actual data. You need to run the ToList to get the data out. You can do what you are trying to do if you can keep the Context open and use transactionscope. In most cases however this is not possible. This would also lock the database leading to other probelms. A better way to do it would be: * *Read the data from the database *Dispose of the context *Client makes any changes needed *Open new context *Read the data again. *make changes by copying data from changed data to second set *commit the changes *dispose of the context A: Call .ToList() on your IQueryable results from the database. To then start refining into other queries use .AsQueryable(). This should solve your first problem. As for your second problem, I'm also searching for a solution. As I understand the underlying implementation of the relationship parts of Entity Framework revolves around the ObjectStateManager in the System.Data.Objects namespace of the System.Data.Entity assembly. This in turn uses the MetadataWorkspace class in the System.Data.Metadata.Edm namespace to lookup the relationship mappings. These might be able to be used without an underlying database connection, and if so, would provide some very groovy tools to update complex object graphs. It would be nice if the context had a Detach and Attach in a similar way to individual Entities. It looks like the next version of the Entity Framework is going to focus on these specific type of issues; more freedom when dealing with Entities and Contexts.
unknown
d5624
train
See if this works:- @FindBy(how=How.ID, using="inline-search-submit") WebElement logUser; @FindBy(how=How.NAME, using="user") WebElement userName; @FindBy(how=How.NAME, using="pass") WebElement passWord; A: The issue is resolved after initialising the webelements of the POM class using initElements: LoginPage login=PageFactory.initElements(driver, LoginPage.class); A: Use below line in your constructor PageFactory.initElements( driver, this); ---------------------------------------------- public LoginPage(WebDriver driver) { this.driver=driver; PageFactory.initElements( driver, this); } This should solve your problem.
unknown
d5625
train
Your idea of protecting from injections is quite wrong. It is not PDO just by it's presence (which can be interfered by some wrapper) protects your queries, but prepared statements. As long as you are using prepared statements, your queries are safe, no matter if it's PDO or wrapper, or even poor old mysql ext. But if you are putting your data in the query directly, like in your example, there is no protection at all
unknown
d5626
train
As the input will only contain one of them, you can use concat to join the results. concat( substring('Midway Games', 1, 12*contains(//p[@class='product-summary'], 'Midway Games')), substring('Line Cinema', 1, 11*contains(//p[@class='product-summary'], 'Line Cinema')), substring('NetherRealm Studios', 1, 19*contains(//p[@class='product-summary'], 'NetherRealm Studios')) ) You can remove the line breaks that I added for readability as you want. I had to fix the query you provided: the text nodes are no following-siblings, but children. Your XPath processor will query the (concatenated) text nodes below that element anyway as contains works on strings.
unknown
d5627
train
For the second form, you can put your custom tag at the beginning of a javadoc line. /** * This is a class of Foo<br/> * * @version * * @configVersion. */ Then use command javadoc -version -tag configVersion.:a:"2.2.2" to generate your javadoc, the custom tag should be handled in this way. Note the last dot(.) character in custom tag name, as the command javadoc suggests Note: Custom tags that could override future standard tags: @configVersion. To avoid potential overrides, use at least one period character (.) in custom tag names.
unknown
d5628
train
Why are you doing this? There are several one- and two-way encryption solutions you could be using instead, if this is for actual use and not just an academic exercise: One-Way: crypt() Two-Way: mcrypt Encryption is pretty much a solved problem.
unknown
d5629
train
Use change() event handler to handle the change event and toggle the element state using toggle() method with a boolean argument. $(document).ready(function() { // attach change event handler $("#r1,#r2").change(function() { // toggle based on the id $(".text").toggle(this.id == 'r1'); $(".text1").toggle(this.id == 'r2'); // trigger change event to hide initially }).first().change(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <p>Show textboxes <input type="radio" name="radio1" id="r1" checked value="Show">Do nothing <input type="radio" name="radio1" id="r2" value="Show"> </p> Wonderful textboxes: <div class="text"> <p>Textbox #1 <input type="text" name="text" maxlength="30"> </p> <p>Textbox #2 <input type="text" name="text" maxlength="30"> </p> </div> <div class="text1"> <p>Textbox #3 <input type="text" name="text1" maxlength="30"> </p> <p>Textbox #4 <input type="text" name="text2" maxlength="30"> </p> </div> FYI : The attribute should be unique on the page, for a group of elements use class attribute otherwise only the first element with the id get selected while using id selector. A: Your Code is looking fine. make it sure that you add JQuery Properly like <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script> $(document).ready(function() { $(".text").show(); $(".text1").hide(); $("#r1").click(function() { $(".text").show(); $(".text1").hide(); }); $("#r2").click(function() { $(".text1").show(); $(".text").hide(); }); }); </script> A: your code is working fine after added the jquery reference. <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> A: use toggle method for hide and show go to following link https://www.w3schools.com/jquery/eff_toggle.asp
unknown
d5630
train
instead of directly highligt them add class "match" and work with it $(selector).html($(selector).html() .replace(searchTermRegEx, "<span class='match'>"+searchTerm+"</span>")); //to highlighted specific index $('.match:first').addClass('highlighted'); //to work with index you need you var matches to know what indexes exist $('.match').eq(3).addClass('highlighted'); demo A: I looked at http://jsfiddle.net/ruddog2003/z7fjW/141/, and it was a great starting point. I modified the logic a bit to allow both next and previous, and to be a bit more robust. Its not perfect, but here follows my code in AJAX format HTML > <div data-role="content"> > <div id="fulltext-search"> > <input type="text" name="search-input" value="" placeholder="Type text here..."/> > <input type="button" name="search-action" value="Search"/> > <button id="searchPrevious"> &lt;&lt; </button> > <button id="searchNext"> &gt;&gt; </button> > </div> > </div> CSS #document_fulltext [data-role="content"] #fulltext-search { width: 100%; text-align: center; position: fixed; top: 0px; background-color: rgba(255,255,255, 0.8); z-index: 10000; border-bottom: 1px solid #000; } .highlighted { color: white; background-color: rgba(255,20,0,0.5); padding: 3px; border: 1px solid red; -moz-border-radius: 15px; border-radius: 15px; } JAVASCRIPT EVENT $(document).ready(function( ) { loadFulltext(); //Load full text into the designated div function loadFulltext(searchString){ //reset $("#fulltext").html(''); filePath = 'http://localhost/income_tax_act_58_of_1962.html'; $.ajax({ url: filePath, beforeSend: function( xhr ) { xhr.overrideMimeType( "text/html; charset=UTF-8;" ); }, cache: false, success: function(html){ $("#fulltext").html(html); // if search string was defined, perform a search if ((searchString != undefined) && (searchString != '') && (searchString != null)){ if(!searchAndHighlight(searchString, '#fulltext')) { alert("No results found"); } } }, fail: function(){ alert('FAIL'); } }); } /* ------------------------------ CLICK - REFRESH DOCUMENTS LIST --- */ $(document).on('click', 'input[name="search-action"]', function ( event ){ // load fresh copy of full text into the div and perform a search once it is successfully completed loadFulltext($('input[name="search-input"]').val()); }); }); JAVASCRIPT FUNCTION function searchAndHighlight(searchTerm, selector) { if(searchTerm) { $('.highlighted').removeClass('highlighted'); //Remove old search highlights $('.match').removeClass('match'); //Remove old matches //var wholeWordOnly = new RegExp("\\g"+searchTerm+"\\g","ig"); //matches whole word only //var anyCharacter = new RegExp("\\g["+searchTerm+"]\\g","ig"); //matches any word with any of search chars characters var selector = selector || "body"; //use body as selector if none provided var searchTermRegEx = new RegExp(searchTerm,"ig"); var matches = $(selector).text().match(searchTermRegEx); // count amount of matches found if(matches) { alert('['+matches.length+'] matches found'); // replace new matches $(selector).html($(selector).html().replace(searchTermRegEx, "<span class='match'>"+searchTerm+"</span>")); // add highligt to first matched class $('.match:first').addClass('highlighted'); // keep track of next and previous. Start at one because on SEARCH the forst one was already highlightes var matchIndex = 1; // look out for user click on NEXT $('#searchNext').on('click', function() { //Re-set match index to create a wrap effect if the amount if next clicks exceeds the amount of matches found if (matchIndex >= matches.length){ matchIndex = 0; } var currentMatch = $('.match'); currentMatch.removeClass('highlighted'); var nextMatch = $('.match').eq(matchIndex); matchIndex += 1; nextMatch.addClass('highlighted'); // scroll to the top of the next found instance -n to allow easy viewing $(window).scrollTop(nextMatch.offset().top-30); }); // look out for user click on PREVIOUS $('#searchPrevious').on('click', function() { //Re-set match index to create a wrap effect if the amount if next clicks exceeds the amount of matches found if (matchIndex < 0){ matchIndex = matches.length-1; } var currentMatch = $('.match'); currentMatch.removeClass('highlighted'); var previousMatch = $('.match').eq(matchIndex-2); matchIndex -= 1; previousMatch.addClass('highlighted'); // scroll to the top of the next found instance -n to allow easy viewing $(window).scrollTop(previousMatch.offset().top-30); }); // if match found, scroll to where the first one appears if($('.highlighted:first').length) { $(window).scrollTop($('.highlighted:first').position().top); } return true; } } return false; }
unknown
d5631
train
I was getting the post data but it was not in event["payloadData"]. It was inside event["body"] which is base64 encoded. So i use this to get the posted data base64.b64decode(str(event["body"])).decode('utf-8')
unknown
d5632
train
Please use global $wpdb; before your query. A: I've replicated your issue, you should be using the prefix object. $post_id = $wpdb->get_results( "SELECT post_id FROM " . $wpdb->prefix . "postmeta WHERE meta_value LIKE '%,".$searchTag.",%'OR meta_value LIKE '%,".$searchTag."' OR meta_value LIKE '".$searchTag.",%' OR meta_value='".$searchTag."' " );
unknown
d5633
train
See this example (note it is separate classes): Fluent NHibernate automap inheritance with subclass relationship One easy approach might be: public class Customer { [Key, Required] public string Code { get; set; } public string Domain { get; set; } public virtual ICollection<Address> Addresses{ get; set; } public virtual Address BillToAddress { get { Addresses.Where(n=>n.Type = Address.BillingAddress)).Single(); } public virtual ICollection<Address> ShipToAddresses { get { Addresses.Where(n=>n.Type = Address.ShipToAddress)); } } One additional comment - this is not implicitly forcing your one Billing address business logic as the example you start with does, so you either need to enforce that elsewhere with the above approach. Also, creating two classes and using TPH as described in the example I link to is the approach I would likely take anyway - which would meet your described goal above directly. Also, in between the two, this may work, using the discriminator in the getter of each property directly.
unknown
d5634
train
AD stroes the password in an attribute called unicodepwd. This is a one way hash. Even if you can view it,you can not retrieve the password. Also this attribute can not be viewed with regular ldap searches. You have to use ldapi interface to retrieve it. Which means you have to be on the local machine.
unknown
d5635
train
Why not just use a List<Map.Entry<String,String>> ? This works right out of the box and if you really want to use a MuliValuedMap you can convert the List into one with the following sniped: var map = new ArrayListValuedHashMap<String, String>(); result.property2.stream() .collect(Collectors.groupingBy(Map.Entry::getKey)) .entrySet() .forEach(entry -> map.putAll(entry.getKey(), entry.getValue().stream().map(Map.Entry::getValue).toList()));
unknown
d5636
train
Given your data is in df: library(data.table) dt <- as.data.table(df) dt[, count := .N, by = list(Attribute1, Attribute2)] A: We can try library(dplyr) df1 %>% group_by(attribute1, attribute2) %>% mutate(Count= n())
unknown
d5637
train
Flickr's API supports JSONP, whereas the one you're connecting to does not. jQuery sees that =? and understands there's a request for a JSONP callback and creates one. You can see it on line 5003 of the jQuery library your sample page uses. So, you need to change two things * *Add a callback parameter to your request. Whatever you (or your developer) wants to call it. Let's say you choose cb - so add this to the AJAX request: &cb=? (this way we let jQuery handle the creation of a callback for us) *Have your developer that made the service accept this new parameter, and "pad" the result with it before returning it. A: Have you considered using the more flexible $.ajax? I would break it down there and see if the default $.getJSON is not providing you with exactly what you need. $.ajax({ url: 'results.json', type: 'GET', dataType: 'json', success: function(data, status) { alert(data); } }); Would be the equivalent ajax 'parent' implementation. Try mucking around and see if there is a specific property you need to set. A: Is the content served as "application/json"? A: if one url (the flickr url) works, while another doesnt (your own), i would say the problem is with your url. It looks like you are using a relative path, is that your intention? have you used firebug's net panel to see what the request looks like? A: This is a case of Crossdomain request error. Flickr Works , because it is JSONP , while the other url does not work because it is not JSONP enabled. 1. Check if the url supports JsonP 2. if not, create a proxy web service in your local domain (the same domain as the web page is) 3. Call that proxy webservice which in turn calls the external url from the server side.
unknown
d5638
train
Instead of using ISessionFactory.Statistics, just use ISession.Statistics. class Program { static void Main(string[] args) { ISession session = NHibernateHelper.GetSession(); var stats = session.Statistics; Console.WriteLine("Entity count: {0}", stats.EntityCount); Console.WriteLine("Collection count: {0}", stats.CollectionCount); Console.ReadLine(); } } Statistics at the session level are limited when compared with the session factory level though.
unknown
d5639
train
Afaik no, signed pdfs can't be merged, cause the signature is applied to the document, not to its range. Changing the document invalidates the signature. A: If you are not concerned about invalidating the signature you can always print to Adobe PDF again and then combine with other PDFs.
unknown
d5640
train
Take a look at the NSFetchRequest and its controls over batches. You can set the batch size and the offset which will allow you to "page" through the data.
unknown
d5641
train
MoveTree is an incomplete type inside its definition. The standard does not guarantee instantiation of STL templates with incomplete types. A: Use a pointer to the type in the Vector, this will be portable. struct Move { int src; int dst; }; struct MoveTree; struct MoveTree { Move move; std::vector<MoveTree*> variation; }; A: The C++ Standard (2003) clearly says that instantiating a standard container with an incomplete type invokes undefined-behavior. The spec says in §17.4.3.6/2, In particular, the effects are undefined in the following cases: __ [..] — if an incomplete type (3.9) is used as a template argument when instantiating a template component. __ [..] Things have changed with the C++17 standard, which explicitely allows this types of recursion for std::list, std::vector and std::forward_list. For reference, see http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4510.html and this answer: How can I declare a member vector of the same class? A: The MoveTree elements in std::vector are in an allocated (as in new []) array. Only the control information (the pointer to the array, the size, etc) are stored within the std::vector within MoveTree. A: No, it's not portable. codepad.org does not compile it. t.cpp:14: instantiated from here Line 215: error: '__gnu_cxx::_SGIAssignableConcept<_Tp>::__a' has incomplete type compilation terminated due to -Wfatal-errors. A: You should define copy constructors and assignment operators for both Move and MoveTree when using vector, otherwise it will use the compiler generated ones, which may cause problems.
unknown
d5642
train
Passing list as arguments: Passing the list as argument can be good practice, if you make your function tail-recursive. Otherwise it's pointless. With BST where there are two potential recursive function calls to be done, it's a bit of a tall ask. Else you can just return the list. I don't see the necessity of variable i. Anyway if you absolutely need to return multiples values, you can always use tuples like this return i, stack and this i, stack = root.find_smallest_at_k(k). Fast-forwarding: For the fast-forwarding, note the right nodes of a BST parent node are always bigger than the parent. Thus if you descend the tree always on the right children, you'll end up with a growing sequence of values. Thus the first k values of that sequence are necessarily the smallest, so it's pointless to go right k times or more in a sequence. Even in the middle of you descend you go left at times, it's pointless to go more than k times on the right. The BST properties ensures that if you go right, ALL subsequent numbers below in the hierarchy will be greater than the parent. Thus going right k times or more is useless. Code: Here is a pseudo-python code quickly made. It's not tested. def findKSmallest( self, k, rightSteps=0 ): if rightSteps >= k: #We went right more than k times return [] leftSmallest = self.left.findKSmallest( k, rightSteps ) if self.left != None else [] rightSmallest = self.right.findKSmallest( k, rightSteps + 1 ) if self.right != None else [] mySmallest = sorted( leftSmallest + [self.data] + rightSmallest ) return mySmallest[:k] EDIT The other version, following my comment. def findKSmallest( self, k ): if k == 0: return [] leftSmallest = self.left.findKSmallest( k ) if self.left != None else [] rightSmallest = self.right.findKSmallest( k - 1 ) if self.right != None else [] mySmallest = sorted( leftSmallest + [self.data] + rightSmallest ) return mySmallest[:k] Note that if k==1, this is indeed the search of the smallest element. Any move to the right, will immediately returns [], which contributes to nothing. A: As said Lærne, you have to care about turning your function into a tail-recursive one; then you may be interested by using a continuation-passing style. Thus your function could be able to call either itself or the "escape" function. I wrote a module called tco for optimizing tail-calls; see https://github.com/baruchel/tco Hope it can help. A: Here is another approach: it doesn't exit recursion early, instead it prevents additional function calls if not needed, which is essentially what you're trying to achieve. class Node: def __init__(self, v): self.v = v self.left = None self.right = None def find_smallest_at_k(root, k): res = [None] count = [k] def helper(root): if root is None: return helper(root.left) count[0] -= 1 if count[0] == 0: print("found it!") res[0] = root return if count[0] > 0: print("visiting right") find(root.right) helper(root) return res[0].v A: If you want to exit as soon as earlier possible, then use exit(0). This will make your task easy!
unknown
d5643
train
You can use data attribute on delete button to keep reference on added items when you want to delete them. function update(e) { var selObj = document.getElementById("skill_tags"); var selVal = selObj.options[selObj.selectedIndex].text; let counter = 0; document.getElementById("textarea").innerHTML += `<div class="tags_inline" id="${e.value}"><li class="list-inline-item"><span class="badge badge-dark">"${selVal}"<button data-select-id="${e.value}" class="fa fa-times-circle text-white" id="delete" onclick=remove_tag(this) >remove</button></span></li></div>`; } function remove_tag(e) { document.getElementById(e.dataset["selectId"]).remove(); } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="resume-skill-item"> <h5> <ul class="list-inline"> <div align="right"> <select id="skill_tags" onchange="update(this)"> <option selected="true" disabled="disabled">*Select All That Applies</option> <option value="mechanic">Mechanic</option> <option value="appliance_repairer">Appliance Repairer</option> <option value="carpenter">Carpenter</option> <option value="plumber">Plumber</option> <option value="technician">Technician</option> </select> </div> </ul> <div id="textarea" class="large-single-textarea"> </div> </h5> </div> A: You can do it by sending the element itself thru args to the remove_tag function: function update() { var selObj = document.getElementById("skill_tags"); var selVal = selObj.options[selObj.selectedIndex].text; //add tag with a remove_tag(this) onclick action document.getElementById("textarea").innerHTML += "<div class='tags_inline' id='tag'><li class='list-inline-item'><span class='badge badge-dark'>" + selVal + "<button class='fa fa-times-circle text-white' id='delete' onclick=remove_tag(this);></button></span></li></div>"; } Then by DOM tree we can access and remove the element. The DOM tree for this looks like div > li > span > button The click event is triggered on the button so the function will look like this: function remove_tag(element) { //Here we grab the node that tag is on at the DOM tree let tag = element.parentNode.parentNode; //Same with the father div let div = tag.parentNode; //Then from that div we remove the selected element div.removeChild(tag); } I recommend you to read more about the DOM
unknown
d5644
train
I found that AliasToBean has changed in Hibernate 5. For me adding getter for my field fixed the problem. A: This exception occurs when the setters and getters are not mapped correctly to the column names. Make sure you have the correct getters and setters for the query(Correct names and correct datatypes). Read more about it here: http://javahonk.com/java-lang-classcastexception-com-wfs-otc-datamodels-imagineexpirymodel-cannot-cast-java-util-map/ A: I do some investigation on this question. The problem is that Hibernate converts aliases for column names to upper case — cdFact becomesCDFACT. Read for a more deeply explanation and workaround here: mapping Hibernate query results to custom class? A: In the end it wasn't so hard to find a solution, I just created my own (custom) ResultTransformer and specified that in the setResultTransformer method: private Query createHibernateQueryForUnmappedTypeFactDto(String sqlQuery) throws HibernateException { return FactCodeQueries.addScalars(createSQLQuery(sqlQuery)).setResultTransformer(new FactCodeDtoResultTransformer()); //return FactCodeQueries.addScalars(createSQLQuery(sqlQuery)).setResultTransformer(Transformers.aliasToBean(FactCodeDto.class)); } the code of the custom result transformer: package org.bamboomy.cjr.dao.factcode; import org.bamboomy.cjr.dto.FactCodeDto; import java.util.Date; import java.util.List; /** * Created by a162299 on 3-11-2015. */ public class FactCodeDtoResultTransformer implements org.hibernate.transform.ResultTransformer { @Override public Object transformTuple(Object[] objects, String[] strings) { FactCodeDto result = new FactCodeDto(); for (int i = 0; i < objects.length; i++) { setField(result, strings[i], objects[i]); } return result; } private void setField(FactCodeDto result, String string, Object object) { if (string.equalsIgnoreCase("cdFact")) { result.setCdFact((String) object); } else if (string.equalsIgnoreCase("cdFactSuffix")) { result.setCdFactSuffix((String) object); } else if (string.equalsIgnoreCase("isSupplementCode")) { result.setIsSupplementCode((Boolean) object); } else if (string.equalsIgnoreCase("isTitleCode")) { result.setIsTitleCode((Boolean) object); } else if (string.equalsIgnoreCase("mustBeFollowed")) { result.setMustBeFollowed((Boolean) object); } else if (string.equalsIgnoreCase("activeFrom")) { result.setActiveFrom((Date) object); } else if (string.equalsIgnoreCase("activeTo")) { result.setActiveTo((Date) object); } else if (string.equalsIgnoreCase("descFr")) { result.setDescFr((String) object); } else if (string.equalsIgnoreCase("descNl")) { result.setDescNl((String) object); } else if (string.equalsIgnoreCase("descDe")) { result.setDescDe((String) object); } else if (string.equalsIgnoreCase("type")) { result.setType((String) object); } else if (string.equalsIgnoreCase("idFact")) { result.setIdFact((Long) object); } else if (string.equalsIgnoreCase("idParent")) { result.setIdParent((Long) object); } else if (string.equalsIgnoreCase("isCode")) { result.setIsCode((Boolean) object); } else { throw new RuntimeException("unknown field"); } } @Override public List transformList(List list) { return list; } } in hibernate 3 you could set Aliasses to queries but you can't do that anymore in hibernate 5 (correct me if I'm wrong) hence the aliasToBean is something you only can use when actually using aliasses; which I didn't, hence the exception. A: Im my case : => write sql query and try to map result to Class List => Use "Transformers.aliasToBean" => get Error "cannot be cast to java.util.Map" Solution : => just put \" before and after query aliases ex: "select first_name as \"firstName\" from test" The problem is that Hibernate converts aliases for column names to upper case or lower case A: I solved it by defining my own custom transformer as given below - import org.hibernate.transform.BasicTransformerAdapter; public class FluentHibernateResultTransformer extends BasicTransformerAdapter { private static final long serialVersionUID = 6825154815776629666L; private final Class<?> resultClass; private NestedSetter[] setters; public FluentHibernateResultTransformer(Class<?> resultClass) { this.resultClass = resultClass; } @Override public Object transformTuple(Object[] tuple, String[] aliases) { createCachedSetters(resultClass, aliases); Object result = ClassUtils.newInstance(resultClass); for (int i = 0; i < aliases.length; i++) { setters[i].set(result, tuple[i]); } return result; } private void createCachedSetters(Class<?> resultClass, String[] aliases) { if (setters == null) { setters = createSetters(resultClass, aliases); } } private static NestedSetter[] createSetters(Class<?> resultClass, String[] aliases) { NestedSetter[] result = new NestedSetter[aliases.length]; for (int i = 0; i < aliases.length; i++) { result[i] = NestedSetter.create(resultClass, aliases[i]); } return result; } } And used this way inside the repository method - @Override public List<WalletVO> getWalletRelatedData(WalletRequest walletRequest, Set<String> requiredVariablesSet) throws GenericBusinessException { String query = getWalletQuery(requiredVariablesSet); try { if (query != null && !query.isEmpty()) { SQLQuery sqlQuery = mEntityManager.unwrap(Session.class).createSQLQuery(query); return sqlQuery.setResultTransformer(new FluentHibernateResultTransformer(WalletVO.class)) .list(); } } catch (Exception ex) { exceptionThrower.throwDatabaseException(null, false); } return Collections.emptyList(); } It worked perfectly !!! A: Try putting Column names and field names both in capital letters. A: This exception occurs when the class that you specified in the AliasToBeanResultTransformer does not have getter for the corresponding columns. Although the exception details from the hibernate are misleading.
unknown
d5645
train
Set the default values you want to initialize in (~/.Rprofile) under user directory options(shiny.port = 9999) options(shiny.host= xx.xx.xx.xx)
unknown
d5646
train
As i mentioned in comment, the code is working as expected const drinks = [ { label: "Coffee", name: "a" }, { label: "Tea", name: "a" }, { label: "Water", name: "a", disabled: true } ]; the name attribute is used to group radio buttons,and only one radio button in the group can be selected at a time. A: It is working as expected. If it's a radio button, then it's ONE name and multiple possible values. Only one of them can be selected at a time. const drinks = [ { label: "Coffee", name: "drinkType" }, { label: "Tea", name: "drinkType" }, { label: "Water", name: "drinkType", disabled: true } ];
unknown
d5647
train
The connection must be made in the MainWindow constructor, but you must use a lambda method since the signal does not pass the text to it. form.h class Form : public QDialog { Q_OBJECT public: explicit Form(); public slots: void processingFunction(const QString & text); }; form.cpp Form::Form() : QDialog(parent), ui(new Ui::Form) { ui->setupUi(this); } void Form::processingFunction(const QString & text) { // some processing } MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); connect(ui->pushButton, &QPushButton::clicked, [this](){ f.processingFunction(ui->lineEdit->text()); }); } A: [UPDATE] Class Form is not emiting clicked signal. You should connect a QPushButton (or similar) instead the class Form. Otherwise you should declare signal clicked() in your class and emit it somewhere in your code: class Form : public QDialog { Q_OBJECT public: explicit Form(); signals: void clicked(); public slots: void onPushButton(void); }; void Form::someFunction(/* parameters */) { emit clicked(); } Also, if you want to make the connection you mention at the end, you should do it in the MainWindow class, because you can't access MainWindow from Form, unless you make MainWindow the parent of Form and then call parent() function to access MainWindow through a pointer. But that is an insane and discouraged programming practice because Form must not know about the existence of MainWindow. Although Qt4-style connect() (using SIGNAL and SLOT macros) is still supported in Qt5, it's deprecated and may be removed from Qt6 in 2019, so you must switch to Qt5-style connect(): QObject::connect(lineEdit, &QLineEdit::textChanged, label, &QLabel::setText); This has several pros: * *Errors can be raised at compilation-time, rather than execution time. *C++11 Lambdas can be used. See this: connect(sender, &QPushButton::clicked, [=]() { // Code here. Do whatever you want. }); * *Are a lot faster to resolve. Take a look at: Qt5 Signals and Slots
unknown
d5648
train
Representational State Transfer is just a general style of client-server architecture. It doesn't specify anything nearly so detailed such the appropriate handling of floating point values. The only constraints it imposes are things like the communication should be "stateless". So the concepts of REST exist on a higher level of abstraction and the issue you are seeing must be something specific to the implementation of the service that is providing the floating point values.
unknown
d5649
train
It looks like the latest version of npm has introduced a bug for the electron make process. Issue is being tracked here. Github Issue Try this workaround for a possible fix(untested): rm -rf node_modules npm install --production --ignore-scripts npm install --no-save electron-rebuild --ignore-scripts node_modules/.bin/electron-rebuild npm remove electron-rebuild --ignore-scripts Or downgrade your npm to a version less than 5.3(tested, works). npm i -g [email protected] A: Problem is solved in later versions of npm, please consider upgrading to the latest v ( > 5.4.2) instead of downgrading to 5.2: npm i -g npm
unknown
d5650
train
The problem is with setting not instantiated class as an attribute in a subclass of tf.keras.layers.Layer. If you remove following line self.keras_layer = keras_layer the code would work: import tensorflow as tf class CoderLayer(tf.keras.layers.Layer): def __init__(self, name, keras_layer): super(CoderLayer, self).__init__(name=name) self.out = keras_layer(12, [3, 3]) def call(self, inputs): return self.out(inputs) inputs = tf.keras.Input(shape=(200, 200, 3), batch_size=12) layer = CoderLayer("minimal_example", tf.keras.layers.Conv2D) print(layer(inputs)) # Tensor("minimal_example_3/conv2d_12/BiasAdd:0", shape=(12, 198, 198, 12), dtype=float32) It is probably a bug. This is a similar issue that had been raised (if you put your not instantiated class into list and try to __setattr__() you will get the same exception). This could be possible workaround if you want to use multiple layers: class CoderLayer(tf.keras.layers.Layer): def __init__(self, name, layername): super(CoderLayer, self).__init__(name=name) self.layer = layername self.out = tf.keras.layers.__dict__[layername](1, 2) def call(self, inputs): return self.out(inputs) inputs = tf.random.normal([1, 3, 3, 1]) layer = CoderLayer("mylayer", 'Conv2D') layer(inputs).numpy()
unknown
d5651
train
Do you have a startup image for your web app? The last time i worked on a web app (some years ago) I discovered that the startup image resolution decides the resolution for the rest of the app(!). See this SO question for startup image HTML syntax for multiple devices. I hope this helps. A: So apparently when you add a Homescreen bookmark - you get a simple iOS app (with a single WebView probably) which is not converted when you restore if from backup on a device with bigger screen. In my case I had to reinstall it on my new device in order to have a full screen app version.
unknown
d5652
train
The asset and withdrawal tables do not have a column called Username. So add that column to these tables or change WHERE condition in the sql statement related to these tables.These sql statements refer to the Username column in the WHERE clause that does not exist: SELECT * FROM **asset** WHERE **Username** SELECT * FROM **withdrawal** WHERE **Username** New CREATE statements including Username column: CREATE TABLE asset ( Asset varchar(100) NOT NULL, optiontype varchar(200) NOT NULL, Invested varchar(200) NOT NULL, Username varchar(100) NOT NULL, Entry Rate varchar(200) NOT NULL, Rate varchar(200) NOT NULL, Entry Time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, Expiration Time varchar(200) NOT NULL, Status varchar(200) NOT NULL, Returns varchar(200) NOT NULL, Customer varchar(200) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=armscii8; CREATE TABLE withdrawal ( id varchar(100) NOT NULL, Username varchar(100) NOT NULL, Date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, Customer varchar(200) NOT NULL, Amount varchar(100) NOT NULL, currency varchar(100) NOT NULL, email varchar(100) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=armscii8;
unknown
d5653
train
You should use proxy() jquery's method to apply specific context: $('.btn').on('click', $.proxy( this.doAlert, this )); DEMO A: There are a number of ways to do this. I prefer to define the object inside an IIFE (immediately invoked function expression) so that it can use a private variable to keep track of itself: var nms = (function () { var myownself = { doAlert: function () { alert('doing alert'); console.log(myownself); }, bindBtn: function () { $('.btn').on('click', myownself.doAlert); } }; return myownself; })(); nms.bindBtn(); Demo: http://jsfiddle.net/Yu5Mx/ That way, all of the methods of that object can just refer to the myownself variable but they don't need to know about the nms variable by which the object is known to the rest of your code. And if you do something like: var temp = nms.bindBtn; temp(); ...which "messes up" the value of this within bindBtn() then it doesn't matter, because bindBtn() will still use myownself. Note that this pattern assumes that nms will be a singleton object. If you want to be able to instantiate multiple copies you can still use the same general idea, but use a factory function or a conventional constructor function with new (rather than an IIFE). A: var nms = { doAlert: function(){ alert('doing alert'); console.log(this); }, bindBtn: function(){ $('.btn').on('click', nms.doAlert.bind(nms)); } } To support bind for IE you can use this A: Try this var nms = { doAlert: function(){ alert('doing alert'); console.log(this); }, bindBtn: function(){ var that = this; $('.btn').on('click', function(){ nms.doAlert.apply(that); }); } } nms.bindBtn(); Demo This passes that through the function as this You can use call() for this too Some links apply() call(); Or Without using call or apply var nms = { doAlert: function(){ var _this = nms; alert('doing alert'); console.log(_this); }, bindBtn: function(){ var that = this; $('.btn').on('click', nms.doAlert); } } nms.bindBtn(); Demo
unknown
d5654
train
The htmlDecode function only decodes the < > & ' symbols as shown in documentation http://dev.sencha.com/deploy/ext-1.1.1/docs/output/Ext.util.Format.html. You can try setting the autoEncode: true property as shown in http://all-docs.info/extjs4/docs/api/Ext.grid.Editing.html. To decode something that is html encoded with jquery you can use val = $('<\div>').html(val).text(); With javascript you can use var textArea = document.createElement("textarea"); textArea.innerHTML =val; val = textArea.value;
unknown
d5655
train
AUI's io request is ajax request only. You can get parameters in serveResource method using code below: ParamUtil.get(resourceRequest, "NAMEOFPARAMETER"); Modify your javascript function and provide data attribute as below: data: { '<portlet:namespace />title': title, '<portlet:namespace />description': description, } A: I assume both title and description are textfields. If so, description is missing a .val() call, or more appropriately, .get('value'). I didn't use a dialog/modal in my source, but the overall approach should be the same. <script> AUI().use('aui-base', 'aui-io-request', function(A){ A.one('#<portlet:namespace />save').on('click', function(event) { var title= A.one('#<portlet:namespace />title').get('value'); var description=A.one('#<portlet:namespace />description').get('value'); var url = '<%=myResourceURL.toString()%>'; A.io.request(url, { method:'POST', data: { title: title, description: description, }, }); }); }); </script> I'm still relatively new to Liferay and have had trouble with this as well. I've noticed that the data parameters are not in the parametersMap of the default ResourceRequest, as you have stated. Out of curiosity, I decided to use UploadPortletRequest req = PortalUtil.getUploadPortletRequest(resourceRequest); in the serveResource method and check it's parametersMap. The title and description parameters are available therein. I'm still learning where and how to access data from Liferay objects, but it would seem that for the UploadPortletRequest to have the data, it would be plucked from somewhere within the default ResourceRequest ... where still remains elusive to me. After inserting blank values in database I have to reload the page to see the inserted values? You have to reload the page because a resource action does not trigger a page refresh. If you are manipulating data that you want reflected in some other "view" you'll need to configure the appropriate communication or use one of the other available url types that does trigger the doView method of your other "view".
unknown
d5656
train
If "ERROR_DESC" is too long to fit on a line (together with "ERROR_CODE" and "ERROR_COUNT"), you have a few options to try: * *return just a substring, *TRIM the value, or *change the data type for "ERROR_DESC". What's working and appropriate, depends on your overall context. After all, the display in SQLPlus is usually not the most important aspect.
unknown
d5657
train
Firestore`s queries run asyncronously, not one after another. So the second query may start earlier than the first is completed. If you want to run them one by one you need to put 2nd query into 1st. Try this: func readAirplanes() { var airplaneArray = [String]() var arrayPosition = 1 db.collection("airplane").whereField("Userid", isEqualTo: userID).getDocuments() { (querySnapshot, err) in if let err = err { print("Error getting documents: \(err)") return } else { self.lbNext.isHidden = false self.btEdit.isUserInteractionEnabled = true self.btDelete.isUserInteractionEnabled = true for document in querySnapshot!.documents { airplaneArray.append(document.documentID) } db.collection("airplane").document(airplaneArray[arrayPosition]).getDocument() { (document, error) in if let document = document, document.exists { self.tfPrefix.text = document.get("Prefix") as? String self.tfIcao.text = document.get("Icao") as? String self.tfModel.text = document.get("Model") as? String self.tfSerial.text = document.get("Serial") as? String self.tfManifacture.text = document.get("Manifacture") as? String self.tfYear.text = document.get("Year") as? String self.tfRules.text = document.get("Rules") as? String self.tfOperator.text = document.get("Operator") as? String self.tfCVA.text = document.get("CVA") as? String } else { print("Document does not exist") } } } } }
unknown
d5658
train
After googling so many thins, I found a solution to this issue. I had to add an additional configuration class that is OpenApiConfig.java to make it work. @Configuration @EnableWebMvc @ComponentScan(basePackages = {"org.springdoc"}) @Import({org.springdoc.core.SpringDocConfiguration.class, org.springdoc.webmvc.core.SpringDocWebMvcConfiguration.class, org.springdoc.webmvc.ui.SwaggerConfig.class, org.springdoc.core.SwaggerUiConfigProperties.class, org.springdoc.core.SwaggerOAuthProperties.class, org.springframework.autoconfigure.jackson.JacksonAutoConfiguration.class}) class OpenApiConfig implements WebMvcConfigurer { }
unknown
d5659
train
In JPA you should add some annotations about the type of inheritence. @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "USER") @Entity public class User ... @Table(name = "PART_TIME_USER") @Entity public class PartTimeUser extends User ... P.S. The @Table annotation is not necessary. Nevertheless I prefer to define it. It makes the code and its connection to database objects more readable.
unknown
d5660
train
Flycheck depends on dash, let-alist, and seq. Download the files 84766 dash.el 381142 flycheck.el 6136 let-alist.el 17589 seq-24.el 17684 seq-25.el 1540 seq.el and put them in ~/.concise-elisp. You need three files for seq because it has alternative implementations for Emacs 24 & 25. Put the following lines in your ~/.emacs: ;; Even if you are not using packages, you need the following ;; commented-out line, or else Emacs 25 will insert one for you. ;; (package-initialize) (setq load-path (cons "~/.concise-elisp" load-path)) (require 'flycheck) (add-hook 'after-init-hook #'global-flycheck-mode) (setq exec-path (append exec-path '("/opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin"))) The last line points to where MacPorts would have put flake8. Flake8 is one of the programs to which flycheck delegates PEP8 checking. Next exercise: Hook flycheck just for Python (and perhaps C/C++/Java/JS/..). In particular, don't worry about making elisp files kosher. Selectively activate flycheck for languages as needed.
unknown
d5661
train
You need to do df = df.rename(columns = {'Nom restaurant ':'Names', 'x_coor':'X_coor','y_coor':'Y_coor','Weight':'Weights'})
unknown
d5662
train
* *def password=(new_password) In Ruby, all the things you normally think of as operators (+, -, =, etc) are implemented as methods and you can do the same thing for your own methods. That's what this is: just a method for password=. That means anytime some other code calls user.password =, it's really calling this method. *||= This is essentially saying "return this user instance's password, but create one first if it doesn't exist". If user.password is there, it just returns that; otherwise, it creates a new Password and returns that. *I'm not sure why you're getting this error, but my guess is that params[:user] isn't what it's supposed to be. (Is it a string, instead of a hash?) The error is complaining that it can't process your params, so have a look at what params[:user] is. It should look something like this: { password: 'password' } *Absolutely, there's no reason for you to implement this. Devise is a widely used authentication gem that will do all of this (and much, much more) for you. You could also use ActiveRecord's has_secure_password feature, which also uses BCrypt, but that also requires some setup work and is much less flexible than Devise.
unknown
d5663
train
Maybe you are missing a "" return "<button onClick={this.addW}>Add</button>" A: I've determined that I need to '.bind(this)' <button onClick={this.addW.bind(this)}>Add</button> It would help for someone to help explain this.
unknown
d5664
train
I would structure the first two selectors like this: html, body { margin: 0; padding: 0; overflow-x: hidden; box-sizing: border-box; /* put these last two in a 'html {}' only selector if they are intended to be different */ scroll-behavior: smooth; } body { min-height: 100vh; background: linear-gradient(#2b1055,#7597de); } Btw, changed the type-o of box-sixing to the right property :). Never used that one before, will come very handy, thanks.
unknown
d5665
train
Consider the best practice of SQL parameterization which is supported with ADO library. This approach which is not limited to VBA or MS Access but any programming language connecting to any backend database allows for binding of values to a prepared SQL query to safely bind literal values and properly align data types: ... Public cmd As ADODB.Command ' AVOID DECLARING OBJECT WITH New ... Sub TestDateIntoDB() Dim SQLString As String Dim ADate As Date Const adDate = 7, adParamInput = 1 'option 1 ADate = CDate("12/29/2022") ' PREPARED STATEMENT WITH QMARK PLACEHOLDER SQLString = "INSERT INTO Table1 (TheDate) Values(?)" ' CONFIGURE ADO COMMAND Set cmd = New ADODB.Command With cmd .ActiveConnection = Conn .CommandText = SQLString .CommandType = adCmdText ' BIND VALUES .Parameters.Append .CreateParameter("paramDate", adDate, adParamInput, , ADate) End With ' EXECUTE ACTION QUERY cmd.Execute Set cmd = Nothing Debug.Print "Date IN: " & CStr(ADate) End Sub A: Force a format of the string expression for the date value: Sub TestDateIntoDB() Dim SQLString As String Dim ADate As Date ' Option 0. ADate = DateSerial(2022, 12, 29) SQLString = _ "INSERT INTO Table1 (TheDate) " & _ "VALUES (#" & Format(ADate, "yyyy\/mm\/dd") & "#)" ' <snip> End Sub
unknown
d5666
train
Steps to figure out the problem 1) Put a break point in prepareForSegue 2) Try to see it displays correct segue id as it should be(there might be making spelling mistake). 3) see where it's crashing in - In prepareForSegue? - Is this calling initname()? - has it started it viewDidLoad(). If you do this mostly you will figure out what the problem is. If you can not then let me know. A: Bind segue from UIViewController to UIViewController rather then cell to UIViewController. Implement following code for navigation. -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { NSLog(@"%ld",aIntSelected); NSLog(@"%@",segue.destinationViewController); } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { aIntSelected=indexPath.row; NSLog(@"didSelectRowAtIndexPath called"); [self performSegueWithIdentifier:@"pushSecond" sender:self]; } A: NSArray *names = @[@"Label 1", @"Label2", @"Label 3"]; NSArray *descs = @[@"Description 1", @"Description", @"Description 3"]; - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([segue.identifier isEqualToString:@"PushAppDetailsSegue"]) { NSIndexPath *indexPath = [self.yourTableView indexPathForSelectedRow]; AppDetailsViewController *controller = segue.destinationViewController; controller.appDetails = [[AppDetails alloc] initWithName:names[indexPath.row] description:descs[indexPath.row]]; } } Drag a segue from your ViewController to SecondViewController and name it "PushAppDetailsSegue".
unknown
d5667
train
There was a library that I did not need to define in R that was needed in Python: ro.r('library(rgdal)')
unknown
d5668
train
Two suggestions: download the latest version of the package; Try deleting the entire "Library" folder, after having dubbed it to another location for safety.
unknown
d5669
train
Look at extending log4j classes http://logging.apache.org/log4j/2.x/manual/extending.html In you custom loggers you can also write to the web page as well as keeping normal log4j functionality and configuration.
unknown
d5670
train
I solved in this way. I created two image with two different colors, and then paste them in another one image. width = 400 height = 300 img = Image.new( mode = "RGB", size = (width, height), color = (209, 123, 193) ) #First IMG img2 = Image.new( mode = "RGB", size = (width, height + 400), color = (255, 255, 255) ) #Second IMG img3 = Image.new('RGB', (img.width, img.height + img2.height)) img3.paste(img, (0, 0)) img3.paste(img2, (img.width, 0)) #IMG + IMG2 I got my result.
unknown
d5671
train
Okay, after looking into this further, I think I answered my own question: Apparently, instead of running the flask development server and trying to proxy it through Apache httpd, it's best to deploy the app directly to Apache using mod_wsgi. Guidelines on how to do this are well documented here. In fact, for production, the dev server is not at all recommended (see here.) As for deploying the jQuery Flask example itself, here's what you do (assuming your DocumentRoot is /var/www/html): # Get the example code. git clone http://github.com/mitsuhiko/flask cd flask/examples/jqueryexample/ # Create WSGI file. echo "\ import sys\ sys.path.insert(0, '/var/www/html/jqueryexample')\ from jqueryexample import app as application\ " > jqueryexample.wsgi # Deploy to httpd. sudo mkdir /var/www/html/jqueryexample sudo cp -r * /var/www/html/jqueryexample/ Now add this to your VirtualHost: WSGIScriptAlias /jqueryexample /var/www/html/jqueryexample/jqueryexample.wsgi <Location /var/www/html/jqueryexample> Allow from all Order allow,deny </Location> Then restart httpd. Now check out the running app at http://localhost/jqueryexample. Voila! A: I don't have an Apache install in front of me but if you are proxying the app shouldn't you change line 6 of the index.html from $.getJSON($SCRIPT_ROOT + '/_add_numbers', { to $.getJSON($SCRIPT_ROOT + '/jqueryexample/_add_numbers', {
unknown
d5672
train
You were close. You need to update Wrapper component a bit. First of all, you need to get rid FC. Instead you need to add extra generic type to infer query result. Consider this example: import React from 'react' import { useQuery, UseQueryResult } from 'react-query' interface WrapperProps<T> { result: UseQueryResult<T, unknown> render: (data: T) => JSX.Element; } const Wrapper = <T,>({ result, render }: WrapperProps<T>) => { if (result.isLoading) { return <div>spinner</div> } if (result.isSuccess) { return render(result.data) } return <div>otherwise</div> } const App: React.FC = () => { const responseString = useQuery( ['string'], async () => Promise.resolve("string") ) const responseNumber = useQuery( ['number'], async () => Promise.resolve(3) ) return ( <div> <Wrapper result={responseString} render={(data /** string */) => (<div>successfully loaded string {data}</div>)} /> <Wrapper result={responseNumber} render={(data /** number */) => (<div>successfully loaded int {data}</div>)} /> </div> ) } Playground Please keep in mind that it is impossible to infer component props with extra generic and FC explicit type. Please be aware that TS since 2.9 supports explicit generics for react components
unknown
d5673
train
The constructor does not exist. Use ZonedDateTime.now() or one of the equivalents. See the relevant JavaDoc.
unknown
d5674
train
Overview Certainly you can, in fact clojure.core namespace itself is split up this way and provides a good model which you can follow by looking in src/clj/clojure: core.clj core_deftype.clj core_print.clj core_proxy.clj ..etc.. All these files participate to build up the single clojure.core namespace. Primary File One of these is the primary file, named to match the namespace name so that it will be found when someone mentions it in a :use or :require. In this case the main file is clojure/core.clj, and it starts with an ns form. This is where you should put all your namespace configuration, regardless of which of your other files may need them. This normally includes :gen-class as well, so something like: (ns my.lib.of.excellence (:use [clojure.java.io :as io :only [reader]]) (:gen-class :main true)) Then at appropriate places in your primary file (most commonly all at the end) use load to bring in your helper files. In clojure.core it looks like this: (load "core_proxy") (load "core_print") (load "genclass") (load "core_deftype") (load "core/protocols") (load "gvec") Note that you don't need the current directory as a prefix, nor do you need the .clj suffix. Helper files Each of the helper files should start by declaring which namespace they're helping, but should do so using the in-ns function. So for the example namespace above, the helper files would all start with: (in-ns 'my.lib.of.excellence) That's all it takes. gen-class Because all these files are building a single namespace, each function you define can be in any of the primary or helper files. This of course means you can define your gen-class functions in any file you'd like: (defn -main [& args] ...) Note that Clojure's normal order-of-definition rules still apply for all functions, so you need to make sure that whatever file defines a function is loaded before you try to use that function. Private Vars You also asked about the (defn- foo ...) form which defines a namespace-private function. Functions defined like this as well as other :private vars are visible from within the namespace where they're defined, so the primary and all helper files will have access to private vars defined in any of the files loaded so far.
unknown
d5675
train
You get the segmentation fault because you are using uninitialized pointers. In other words: *(args+i) is uninitialized. Let's look at your memory: char **args = malloc(argc * sizeof(char *)); This will give a local variable args that points to a dynamic allocated memory area consisting of argc pointers to char. Looks like this: But the argc pointers to char are uninitialized (i.e. malloc doesn't initialized anything) so the real picture is: That is - the argc pointers to char may point anywhere. So when you do strcpy(*(args+i), argv[i+1]); ^^^^^^^^^ Read uninitialized pointer you read the i'th uninitialized pointer and copy the string at argv[i+1] to that location. In other words - to a location that we can't know where is and most like doesn't belong to your program. This is likely to result in a seg fault. So before you copy anything you want those char-pointers to point to some chars. Like: So basically you need to do additional malloc. Now one problem is: How many chars do you need to malloc? Well, you can't know until you know the length of the input strings. So you need to put the malloc inside the loop. Like: int main (int argc, char * argv[]) { char **args = malloc(argc * sizeof(char *)); for (int i = 0; i < argc - 1; ++i) { *(args+i) = malloc(strlen(argv[i+1]) + 1); // Allocate memory strcpy(*(args+i), argv[i+1]); } } Note: * *You don't need to write sizeof(char) as it is always 1 *You have to add 1 to the string length of the input string in order to reserve memory for the string termination. *You should always check that malloc doesn't return NULL *Instead of *(args+i) you can use the more readable form args[i] So after a real execution the picture could be: A: The problem lies in this part of your code: malloc(argc * sizeof(char *)); Don't think that sizeof(char*) would give you the size of a string. What is the size of a pointer? Solution: int main(int argc, char* argv[]) { char* copyOfArgv; copyOfArgv = strdup(argv[1]); } strdup() - what does it do in C? A: The problem is you allocated memory for the pointers not for the string (arguments from argv itself) hence the strcpy is invalid - causing segmentation fault. It would've been better to just: Allocate memory for the pointers (as you have done) then make those pointers point to the arguments passed. Example: #include <string.h> #include <stdlib.h> #include <unistd.h> int main (int argc, char * argv[]) { char **args = malloc(argc*sizeof(char *)); //allocated memory for the pointers only int i=0; for(;i<argc;i++) { args[i]=argv[i]; //making the pointers POINT to the arguments including the 0th argument as well i++; } return 0; } For using strcpy you should've allocated memory for the arguments itself and then copied those.
unknown
d5676
train
Return exits the function, you can't have it in the loop. Store it separately and then reuse the function. function allmyshortcodesloopfunction() { $output = ''; $alltheshortcodes = 'thistextshouldbehere4times'; for ($i=0; $i < 4; $i++) { $output .= "<p>$alltheshortcodes</p>"; } return $output; } A: function allmyshortcodesloopfunction() { $alltheshortcodes = 'thistextshouldbehere4times'; for ($i = 0; $i < 4; $i++) { echo "<p>$alltheshortcodes</p>"; } } allmyshortcodesloopfunction();
unknown
d5677
train
If your project use an external library, you may want to use git submodule to include it in your repository, then go in that directory to git checkout the tag (or branch, or sha1) you want to use. git init newproject cd newproject git submodule add https://url-or-path/to/base/ee-repository target_dir cd target_dir git checkout sometag cd - git add target_dir git commit
unknown
d5678
train
setTimeout with clearTimeout will accomplish this. Each click would do var timeout = null; $(element).click(function(){ if(timeout) { clearTimeout(timeout); } timeout = setTimeout([some code to call AJAX], 500); }) On each click, if there is a timeout it is cleared and restarted at 500 milliseconds. That way, the ajax can never fire until the user has stopped clicking for 500 milliseconds. A: // set vars $Checkbox = $('input.SomeClass'); $ProductInfoDiv = $('div#ProductInfoDiv'); // listen for click $Checkbox.click(getProductInfo); var timeout; var timeoutDone = function () { $ProductInfoDiv.load('SomePage.cfm?'+QString); } // check which boxes are checked and load product info div getProductInfo = function() { // create list of product id from boxes that are checked var QString = $Checkbox.filter(":checked"); // LOAD THE PRODUCT DIV clearTimeout(timeout); timeout = setTimeout(timeoutDone, 4000); } A: var clickTimer = false; // listen for click $Checkbox.click(function(){ if(clickTimer) { // abort previous request if 800ms have not passed clearTimeout(clickTimer); } clickTimer = setTimeout(function() { getProductInfo(); },800); // wait 800ms }); Working example here: http://jsfiddle.net/Th9sb/ A: Would it be possible to disable the checkboxes until the ajax request has been completed? $('.SomeClass').on('click', function(e) { $('.SomeClass').attr('disabled', true); //-- ajax request that enables checkboxes on success/error $.ajax({ url: "http://www.yoururl.com/", success: function (data) { $('.SomeClass').removeAttr('disabled'); }, error: function(jqXHR, textStatus, errorThrown) { $('.SomeClass').removeAttr('disabled'); } }); }); A: i think you have to put it here $Checkbox.click(getProductInfo); it should be like this : working example is here--> http://jsbin.com/umojib/1/edit $Checkbox.one("click", function() { setTimeout(function() { getProductInfo(); },200); }); A: If you are allowed to add another library. Underscore has a debounce function which fits perfect on what you want. function callback(){ // some code to call AJAX } $(element).click(_.debounce(callback, 500)) ```
unknown
d5679
train
Your HTTPRequest object will be having setAttribute, getAttribute & removeAttribute methods, it will internally hold a map [Map<String,Object>] to keep the attributes, you can set the key & value pair and get it in the JSP using the implicit request object A: If categoryelements contains plain string then set the request attribute like this, request.setAttribute("categoryelements", categoryelements.toString()); And in JSPfetch the value in for example a div like this, <div>${categoryelements}</div> Edit:- To access the request attribute in dropdownlist you can use the JSTL library which is helpful in handling the flow of execution in JSP or HTML. You can add this library in your JSP page like this, <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%> And then use them to iterate the list as follows, <select name="selectFieldName"> // following line of code works as Java for loop and here 'listRequestAttribute' can be any list type object e.g. List<String> <c:forEach items="${listRequestAttribute}" var="currentListItem"> // '${currentListItem}' will hold the current object in the loop iteration. <option value="${currentListItem}" > ${currentListItem} </option> </c:forEach> </select> A: in Java: Object categoryelements; List<String> result = new ArrayList<String>(); Iterator it=elements.iterator(); while (it.hasNext()) { JSONObject innerObj= (JSONObject)it.next(); result.add(innerObj.get("category")); } request.setAttribute("result", result); in JSP: <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <jsp:useBean id="result" class="java.lang.List" scope="request" /> ... <c:forEach var="item" items="${result}" > <c:out value="${item}"/> </c:forEach> This is just a simple example. You might consider using classes other than Object to provide better control over your output. The Gson library might help you here.
unknown
d5680
train
No extra strain on other people servers. The server will get your simple HTML GET request, it won't even be aware that you're then parsing the page/html. Have you checked this: JSoup? A: Consider doing the parsing and the crawling/scraping in separate steps. If you do that, you can probably use an existing open-source crawler such as crawler4j that already has support for politeness delays, robots.txt, etc. If you just blindly go grabbing content from somebody's site with a bot, the odds are good that you're going to get banned (or worse, if the admin is feeling particularly vindictive or creative that day). A: Depends on the website. If you do this to Google then most likely you will be on a hold for a day. If you parse Wikipedia, (which I have done myself) it won't be a problem because its already a huge, huge website. If you want to do it the right way, first respect robots.txt, then try to scatter your requests. Also try to do it when the traffic is low. Like around midnight and not at 8AM or 6PM when people get to computers. A: Besides Hank Gay's recommendation, I can only suggest that you can also re-use some open-source HTML parser, such as Jsoup, for parsing/processing the downloaded HTML files. A: You could use htmlunit. It gives you virtual gui less browser. A: Your Java program hitting other people's server to download the content of a URL won't put any more strain on the server than a web browser doing so-- essentially they're precisely the same operation. In fact, you probably put less strain on them, because your program probably won't be bothered about downloading images, scripts etc that a web browser would. BUT: * *if you start bombarding a server of a company with moderate resources with downloads or start exhibiting obvious "robot" patterns (e.g. downloading precisely every second), they'll probably block you; so put some sensible constraints on what you do (e.g. every consecutive download to the same server happens at random intervals of between 10 and 20 seconds); *when you make your request, you probably want to set the "referer" request header either to mimic an actual browser, or to be open about what it is (invent a name for your "robot", create a page explaining what it does and include a URL to that page in the referer header)-- many server owners will let through legitimate, well-behaved robots, but block "suspicious" ones where it's not clear what they're doing; *on a similar note, if you're doing things "legally", don't fetch pages that the site's "robot.txt" files prohibits you from fetching. Of course, within some bounds of "non-malicious activity", in general it's perfectly legal for you to make whatever request you want whenever you want to whatever server. But equally, that server has a right to serve or deny you that page. So to prevent yourself from being blocked, one way or another, you need to either get approval from the server owners, or "keep a low profile" in your requests.
unknown
d5681
train
PropTypes are for runtime type checking, while Flow is for static type checking. Both serve their own purpose, not all type errors can be caught during compilation, so PropTypes helps you with those; Flow can catch some errors early - before you interact with your app, or even load it to the browser.
unknown
d5682
train
Edit: I'm sorry, I misread your question originally. What you really want is collections.Counter and a list comprehension: >>> from collections import Counter >>> li= [11, 11, 2, 3, 4] >>> [k for k, v in Counter(li).iteritems() if v == 1] [3, 2, 4] >>> This will only keep the items that appear exactly once in the list. If order does not matter, then you can simply use set: >>> li = [11, 11, 2, 3, 4] >>> list(set(li)) [3, 2, 11, 4] >>> Otherwise, you can use the .fromkeys method of collections.OrderedDict: >>> from collections import OrderedDict >>> li= [11, 11, 2, 3, 4] >>> list(OrderedDict.fromkeys(li)) [11, 2, 3, 4] >>>
unknown
d5683
train
One of the reasons of the HTTP/1.1 403 forbidden is which the server doesn't recognizes the user agent of the client, so try setting the useragent property like so . Request.UserAgent:='Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0';
unknown
d5684
train
You can do the following: public function index(Request $request) { $users = User::all(); $pages = Page::all(); return [ 'users' => new UserCollection($users), 'pages' => new PageCollection($pages), ]; } A: laravel 6.. This should work 100% if you do like the below, you actually helped me sort out a problem i was having and this is a return on that favour :3. changes the below: 'advertisements' => new AdvertisementCollection(Advertisement::latest()->get()), to (Will work with a vatiable or just the strait db query) 'advertisements' => AdvertisementCollection::collection(Advertisement::latest()->get()) class HomeController extends Controller { public function index() { $ads = Advertisement::latest()->get(); $banners = Banner::latest()->get(); $sliders = Slider::latest()->get() return [ 'advertisements' => AdvertisementCollection::collection($ads), 'banners' => BannerCollection::collection($banners), 'sliders' => SliderCollection::collection($sliders), ]; } } A: I am using laravel 6.x, And i don't know laravel is converting the response or doing something but i am getting the response as JSON in following condition also: class HomeController extends Controller { public function index() { return [ 'advertisements' => new AdvertisementCollection(Advertisement::latest()->get()), 'banners' => new BannerCollection(Banner::latest()->get()), 'sliders' => new SliderCollection(Slider::latest()->get()) ]; } }
unknown
d5685
train
here you go.Add a lable in tableview row and set it according to your own desire var self = Ti.UI.createWindow({ backgroundColor : 'white', title : 'Saved Locations' }); var data = []; var tabLoc = Ti.UI.createTableView({ }); self.add(tabLoc); var row = Titanium.UI.createTableViewRow({ height : '60dp', className : "tableRow", }); var labTitle = Ti.UI.createLabel({ color : 'black', font : { fontSize : '12dp', fontWeight : 'bold' }, height : Ti.UI.SIZE, text : 'There is no location yet saved', textAlign : 'center' }); row.add(labTitle); data.push(row) tabLoc.setData(data); self.open() Thanks
unknown
d5686
train
Just modify your if statement to if my_tree is None: return 0 The error arises since you are trying to access get_data property for a NULL data object on recursive call for leaf nodes of the binary tree. Instead what you actually need to do is return 0 when you reach a NoneType node. A: What happens if my_tree is None? Then you can't call get_data()... Try this if my_tree is None: return 0 Worth pointing out that you don't care about the node data to find the size of the tree The more optimal method is to not recurse, and keep the size updated as you insert/remove elements A: Assuming you pass in a valid root object and recursion occurs as expected, then at what point can you hit upon a NoneType error? Certainly, when my_tree is None, and you try to access an attribute of None. When can my_tree be None? At the leaves. In other words, your base case is malformed. Note that testing the return value of get_data is completely redundant here, because self.data has nothing to do with the height of the node, or the node itself. def size(my_tree): if not my_tree: return 0 return 1 + size(my_tree.get_left()) + size(my_tree.get_right()) Further nitpicks: * *You don't need else; that's implied by control flow. *You don't need an extra variable to store the count, because you don't do anything else besides return it. A: You are getting this error because you are calling get_data() on non-existent object. So, you are calling get_data() on a NoneType object. def size(my_tree): count = 0 if my_tree is None: return 0 count += 1 + size(my_tree.get_left()) + size(my_tree.get_right()) return count The else clause is not needed. Another suggestion to count the binary tree nodes is to have a attribute size on the class, and increase / decrease it as items are added / removed from the tree.
unknown
d5687
train
I think this 60 second thing is you polling the server every 60 seconds to fetch new data, then if there is new data post a local notification? This is kinda possible with iOS7 but not exactly every 60 seconds, sometimes not at all, But in general it is strongly frowned upon. Instead the webserver should send push notifications when new data is available, It saves the user battery life. On iOS7 there are silent push notifications (just don't include the alert) that can ask the client to do the validation you mentioned, and If the user needs a notification you can create a Local Notification to alert the user in a change You should give this documentation a long look, it isn't trivial work for a new iOS programmer: https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Introduction.html And here is a relevant Apple documentation quote "Local and push notifications serve different design needs. A local notification is local to an application on an iPhone, iPad, or iPod touch. Push notifications—also known as remote notifications—arrive from outside a device. They originate on a remote server—the application’s provider—and are pushed to applications on devices (via the Apple Push Notification service) when there are messages to see or data to download." A: If you are trying to achieve this functionality to happen automatically/polling (i.e without user interaction like, clicking on the view details button)- the answer is a big NO at least not till iOS6.x Your application cannot run for infinite length in background at-not till ios6.x. You may have to consider using APNS service to achieve this. Otherwise, your approach on scheduling a local notification for ever 60 sec - The user clicks in the view option - the application comes up - You make a web-service call - Get the data - Validate the received data - Uploading to the server, looks fine to happen. Will it not be annoying to the user getting notification for ever 60 sec & operating on the app to do whatever you intended to do? - Just curious.
unknown
d5688
train
I have no experience with tflearn, but I do have some basic background in Python and sklearn. Judging from the error in your StackOverflow screenshot, tflearn **models **do not have the same methods or attributes as scikit-learn estimators. This is understandable as they are not, well, scikit-learn estimators. Sklearn’s grid search CV only works on objects that have the same methods and attributes as scikit-learn estimators (e.g. has fit() and predict() methods). If you are intent on using sklearn’s grid search, you will have to write your own wrapper around the tflearn model to make it work as a drop in replacement for an sklearn estimator, meaning you’ll have to write your own class that has the same methods as any other scikit-learn estimator, but uses the tflearn library to actually implement these methods. To do that, understand the code for a basic scikit-learn estimator (preferably one you know well) and see what the methods fit(), predict(), get_params(), etc. actually do to the object and its internals. Then write your own class using the tflearn library. To get started, a quick Google search reveals that this repository is “a thin scikit-learn style wrapper for tensorflow framework”: DSLituiev/tflearn (https://github.com/DSLituiev/tflearn). I have no idea if this will work as a drop in replacement for Grid Search, but it’s worth a look.
unknown
d5689
train
Simple enabling of Cors for allow any origin/method etc(Personal project): 1. nuget: Microsoft.AspNetCore.Cors *In configure method, add this before useMvc: app.UseCors(o =>o.AllowAnyOrigin().AllowAnyMethod().AllowAnyMethod().AllowCredentials()); *in ConfigureServices, before AddMvc, Add this: services.AddCors();
unknown
d5690
train
It's completely possible to take any IPA and resign it with your own details, modifying the Info.plist, bundle ID, etc. in the process. I do this all the time with IPAs that have been signed by other developers using their own provisioning profiles and signing identities. If they aren't familiar with the codesign command line tool and all the details of replacing embedded.mobileprovision files and entitlements, the easiest way for them to do this is for you to "Archive" the app via Xcode, and send them the generated archive file (*.xcarchive). They can import that into Xcode so it is visible in the Organizer, and from there they can choose "Distribute" and sign it with their enterprise identity. To import the .xcarchive file into Xcode, they just need to copy the file into the ~/Library/Developer/Xcode/Archives directory and it should appear in the Xcode organizer. Then they click "Distribute" and follow the instructions:
unknown
d5691
train
After digging through pom files, .m2/repository/repository.xml and several maven-metadata.xml files, I found the root cause. The maven-metadata.xml file in Maven repository http://repo.adobe.com for org.eclipse.osgi seems to have been changed on 20th August. For some reason the date of this file was reset now to 11th of July, but the change remains: The metadata file changed from <metadata> <groupId>org.eclipse</groupId> <artifactId>osgi</artifactId> <version>3.3.0-v20070530</version> <versioning> <versions> ... </versions> <lastUpdated>20071127073207</lastUpdated> </versioning> </metadata> to <metadata modelVersion="1.1.0"> <groupId>org.eclipse</groupId> <artifactId>osgi</artifactId> <version>3.3.0-v20070530</version> <versioning> <latest>3.8.2.v20130124-134944</latest> <release>3.8.2.v20130124-134944</release> <versions> ... </versions> <lastUpdated>20130711152942</lastUpdated> </versioning> </metadata> Obviously, the latest version was provided after the change, which is now 3.8.2 and not 3.3.0 anymore. A: The problem is likely caused by version ranges. These ranges do not even have to be used for the Eclipse artifacts. Assume you depend on [1,2) and 1.1, and 1.2 are available. At a moment in time, 1.3 is added that has different dependencies. If it finds multiple groupId:artifactId with a different version then it picks the first it finds. Maven follows a breadth first strategy to find dependencies so that you can override it in your top level pom. This is of course very obscure and error prone. A better way is to specify all your app dependencies in one pom so you can ensure valid versions.
unknown
d5692
train
Fix mentioned in https://gist.github.com/jankovd/891d96f476f7a9ce24e2 worked for me. public class ActivityUsingVideoView extends Activity { @Override protected void attachBaseContext(Context base) { super.attachBaseContext(AudioServiceActivityLeak.preventLeakOf(base)); } } /** * Fixes a leak caused by AudioManager using an Activity context. * Tracked at https://android-review.googlesource.com/#/c/140481/1 and * https://github.com/square/leakcanary/issues/205 */ public class AudioServiceActivityLeak extends ContextWrapper { AudioServiceActivityLeak(Context base) { super(base); } public static ContextWrapper preventLeakOf(Context base) { return new AudioServiceActivityLeak(base); } @Override public Object getSystemService(String name) { if (Context.AUDIO_SERVICE.equals(name)) { return getApplicationContext().getSystemService(name); } return super.getSystemService(name); } } Thanks to Dejan Jankov :) A: You can avoid memory leak using application context to get audio service. A: I found in another post that the AudioManager does keep a strong reference, but will still be properly garbage collected. See this google group conversation. Here's what I get out of it: This means that if you manually launch a couple of garbage collections through the DDMS tab in Eclipse just before taking the head dump, this reference should not be there anymore. This indeed solved the "problem" for me, as it turned out not to be a problem after all... It was also mentionned that the debugger should not be on hook (i.e. use Run As... instead of Debug As...). The debugger being active could cause the references to be held by the AudioManager, thus creating a heap overflow (I have not tested this affirmation).
unknown
d5693
train
@ReneVanDerLende After thoroughly checking my project due to css properties set for mat-drawer-content as { width: 100% ; height: 100% } it interfered with the styles of box-empty-container, hence shifting that slightly towards right.
unknown
d5694
train
* *I don't know why, but using subplots=True with numeric column names seems to be causing the issue. *The resolution is to convert the column names to strings import pandas as pd # load the data df = pd.read_csv("sonar_all-data.csv", header=None) # check the column name type print(type(df.columns[0])) [out]: numpy.int64 # convert the column names to strings df.columns = [f'{v}' for v in df.columns] # check the column name type print(type(df.columns[0])) [out]: str # plot the dataframe df.plot(kind='box', layout=(10, 6), figsize=(20, 20), subplots=True) plt.show() * *With subplots=False the plot works with numeric column names
unknown
d5695
train
You need to change the elements .textwidget, .extra-info and the col-md-2 columns inside .extra-info to flex items and then vertically center the columns using the css flex property align-items:center. Add the following to your CSS: .textwidget { display: flex; } .extra-info { display: flex; } .extra-info .col-md-2 { display: flex; align-items: center; } N.B. Your site has a lot of elements using a common ID (e.g. all your <aside> elements in your header uses the same #text-3 ID). You should not use the same ID for more than one elements. Replace them with a common class-name or use a different ID for each element instead.
unknown
d5696
train
Use the concept of SELF JOIN, in which we will join same table again if we have a field which is a reference to the same table. Here dwEnemyGuildID is reference to the same table. A trivial example of the same is finding Manager for an employee from employees table. Reference: Find the employee id, name along with their manager_id and name SELECT g.wPos as wPos, g.szGuildName as szGuildName, g.dwGuildExpWeek as dwGuildExpWeek, g.dwEnemyGuildID as dwEnemyGuildID, enemy_g.szGuildName as szEnemyGuildName, -- pick name from self joined table gm.wPower as wPower, gd.szName as szName FROM guild as g LEFT JOIN guild_member AS gm ON gm.dwGuildID = g.dwGuildID AND gm.wPower = '1' LEFT JOIN guild AS enemy_g ON g.dwEnemyGuildID = enemy_g.dwGuildID -- Use self join LEFT JOIN gamedata AS gd ON gd.dwID = gm.dwRoleID WHERE g.wPos = '1';
unknown
d5697
train
When you create an array of Objects, you create an array full of null objects. The array is full of "nothingness". An Employee will not be created until you explicitly create one. Employee[] staff = new Employee[3]; At this point your array looks like: [null] [null] [null] You can then create an Employee by doing: staff[0] = new Employee(); At this point, your default Employee constructor is called and your array now has an Employee object in the first position: [Employee1][null][null] Now that you have an actual Employee in the first position, you should be able to call: staff[0].setName("Test"); Update: In regard to the question: what was the purpose of using new operator? Doesn't it already allocate memory for the array? How come this doesn't happen with int array? Similar questions were already asked here and here. In short, when you create the array of Objects, you really create an array of references. At first, all these references just point to null objects. When you do staff[0] = new Employee();, you are in essence doing two things: * *Creating and allocating memory for a "new" Employee *Telling staff[0] to now point to the new Employee object instead of null A: In Java, all "objects" are actually just references (pointers, sort of). So you are correct in assuming that Java auto-initializes the values in the array, but in your second array, you have an array of references, which are basically memory addresses, and therefore are initialized to null. You are getting your exception because you are calling a method on a null reference. Also, notice that when you created an array of primitives, you are using the assignment operator with the different indices in the array. In your example with objects, you are just immediately using the values in the array, not assigning them. So technically, what you were doing in the primitive array example can be done with object arrays, since it is simple assignment. A: In Java, when you create an array of objects, the default values of every entry in the array is null. There are no constructors being called. You'll have to loop over the array and create an object for each entry. for example for(int i=0; i<staff.length; i++){ staff[i] = new Employee("name" + i, 20); }
unknown
d5698
train
private String selecteditem; spinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView adapter, View v, int i, long lng) { selecteditem = adapter.getItemAtPosition(i).toString(); //or this can be also right: selecteditem = level[i]; } @Override public void onNothingSelected(AdapterView<?> parentView) { } }); A: IIRC, you should be using a selected listener, not click: spinner.setOnItemSelectedListener(new OnItemSelectedListener() Then you can add the override tag to your selected method. A: spinner3.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View v, int postion, long arg3) { // TODO Auto-generated method stub String SpinerValue3 = parent.getItemAtPosition(postion).toString(); Toast.makeText(getBaseContext(), "You have selected 222 : " + SpinerValue3, Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }); A: Yes you can use some OnItemSelectedListener for work with selected item. But sometimes we would like to handle exactly click for spinner. For example hide keyboard or send some analytics etc. In this case we should use TouchListener because OnClickListener doesn't work properly with Spinner and you can get error. So I suggest to use TouchListener like: someSpinner.setOnTouchListener { _, event -> onTouchSomeSpinner(event)} fun onTouchSomeSpinner(event: MotionEvent): Boolean { if(event.action == MotionEvent.ACTION_UP) { view.hideKeyBoard() ... } return false } A: you should have this in the listener(OnItemSelectedListener) public void onNothingSelected(AdapterView<?> arg0) { } It might works without it but put it to be consistent but there might be other errors also, can you provide the error log ?
unknown
d5699
train
You can do something like this: from tkinter import Tk, Button class MainWindow(Tk): def __init__(self): super().__init__() self.buttons = list() for i in range(4): button = Button(self, text=f'Button {i}') button.bind('<ButtonPress-1>', self.press) button.bind('<ButtonRelease-1>', self.release) button.pack(fill='both') self.buttons.append(button) def press(self, event=None): for btn in self.buttons: btn.config(relief='sunken') def release(self, event=None): for btn in self.buttons: btn.config(relief='raised') if __name__ == '__main__': MainWindow().mainloop() It will visually make them appear to be clicked at once. You can simply inherit from Tk and it will reduce the code written a bit since instead of self.root it would simply be just self and the features would be inherited and other stuff, for example, don't need to define mainloop as it is already inherited. Also: I strongly suggest following PEP 8 - Style Guide for Python Code. Function and variable names should be in snake_case, class names in CapitalCase. Have two blank lines around function and class declarations. I strongly advise against using wildcard (*) when importing something, You should either import what You need, e.g. from module import Class1, func_1, var_2 and so on or import the whole module: import module then You can also use an alias: import module as md or sth like that, the point is that don't import everything unless You actually know what You are doing; name clashes are the issue.
unknown
d5700
train
I guess the validform should be 2016-03-01 instead of 2016-3-01 because it is not converted into date before compare. A: I am totally agree with the point made in the accepted answer (+1 for that). But, even if op somehow convert validfrom from string to DateTime, his attempt won't give him the desired result. Let's examine the query given in question: SELECT entrykey, user_key, MAX(STR_TO_DATE(validfrom, '%Y-%c-%e')) as date1 FROM table Group by user_key; Now, this query will return user_key with maximum value of validfrom for that particular user_key. But the entrykey won't be the entrykey with max validfrom. (Check the first result in demo link) In order to achieve above task, following query will work just fine! SELECT t1.entrykey, t1.user_key, t2.maxdate as MaxDate FROM t t1 inner join (select user_key,MAX(STR_TO_DATE(validfrom, '%Y-%c-%e')) as maxdate from t Group by user_key ) t2 on t1.user_key = t2.user_key and t1.validfrom = t2.maxdate; Click here for Demo with DateTime as datatype of validfrom Click here for Demo with STR_TO_DATE() function Hope it helps!
unknown