_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
21
37k
language
stringclasses
1 value
title
stringclasses
1 value
d18757
test
Employee.java @Entity public class Employee { @Id @Column(name = "emp_id", length = 8) @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer emp_id; @Column(name = "emp_name", length = 20, nullable = false) private String emp_name; @ManyToOne private Position position; Position.java @Entity public class Position { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int pos_id; @Column(name = "pos_name", length = 16) private String pos_name; @OneToMany(mappedBy = "position") private List<Employee> employees; Thank you.I can join two tables!
unknown
d18759
test
sys.argv[x] is string. Multiplying string by number casue that string repeated. >>> '2' * 5 # str * int '22222' >>> int('2') * 5 # int * int 10 To get multiplied number, first convert sys.argv[1] to numeric object using int or float, .... import sys st_run_time_1 = int(sys.argv[1]) * 60 # <--- print ("Station 1 : %s" % st_run_time_1) A: You are multiplying a string with an integer, and that always means repetition. Python won't ever auto-coerce a string to an integer, and sys.argv is always a list of strings. If you wanted integer arithmetic, convert the sys.argv[1] string to an integer first: st_run_time_1 = int(sys.argv[1]) * 60
unknown
d18763
test
Clearing emulator logs by running adb logcat -c in did the trick for me!!!
unknown
d18765
test
You have to use ClientID var change = document.getElementById("<%= lblPercentageDifferenceToFillReqCurrentVsPreviousMonth.ClientID %>").value; Assuming that it is an actual Control like <asp:TextBox ID="lblPercentageDifferenceToFillReqCurrentVsPreviousMonth" runat="server"></asp:TextBox>
unknown
d18769
test
you can: g++ name.cpp && ./a.out && gnuplot -e "plot 'name2.dat'; pause -1" gnuplot exits when you hit return (see help pause for more options) if you want to start an interactive gnuplot session there is a dirty way I implemented. g++ name.cpp && ./a.out && gnuplot -e "plot 'name2.dat' - (pay attention to the final minus sign)
unknown
d18775
test
You should be getting an IPN when the profile is created, each time the recurring profile bills, and when the profile is cancelled. Check your IPN history in your account to make sure the IPN's are being sent out, and check to see if there is any type of error being returned to PayPal. Check your server access logs to see PayPal is calling your script and check your error logs to see if anything is being triggered. Try adding www. to your URL, and the ext to the end of your URL for the type of file it is. Also, there are some IPN troubleshooting tips I posted for IPN on this forum POST. A: The IPN will only be sent to the account on which the profile was created. Here's how I would do it. * *Store the Paypal ProfileID and e-mail address in a database. *Receive all of the IPN notifications yourself, and in the case of a failure, send an e-mail to the specific user based on their ProfileID, or perform other actions.
unknown
d18777
test
You create "classes" in Javascript as functions. Using this.x inside the function is like creating a member variable named x: var Blood = function() { this.x = 0; this.y = 0; } var blood = new Blood() console.log(blood.x); These aren't classes or types in the sense of OO languages like Java, just a way of mimicking them by using Javascript's scoping rules. So far there isn't really much useful here -- a simple object map would work just as well. But this approach may be useful if you need more logic in the Blood "class", like member functions, etc. You create those by modifying the object's prototype: Blood.prototype.createSplatter = function() { return [this.x-1, this.y+1]; // (idk, however you create a splatter) }; blood.createSplatter(); (Fiddle) For more details on Javascript classes, I suggest taking a look at CoffeeScript syntax (scroll down to "Classes, Inheritance, and Super"). They have some side-by-side examples of classes in the simplified CS syntax, and the JS translation.
unknown
d18779
test
Quoting Wikipedia: HTML Components (HTCs) are a nonstandard mechanism to implement components in script as Dynamic HTML (DHTML) "behaviors"[1] in the Microsoft Internet Explorer web browser. Such files typically use an .htc extension. An HTC is typically an HTML file (with JScript / VBScript) and a set of elements that define the component. This helps to organize behavior encapsulated script modules that can be attached to parts of a Webpage DOM. In two paragraphs, the following are mentioned: * *Internet Explorer *JScript *VBScript *nonstandard I think it's obvious why not everybody is using this technology. A: How to use border-radius.htc with IE to make rounded corners The server has to server the HTC with the correct MIME type (text/x-component) That alone is enough to stop JavaScript frameworks such as jQuery or MooTools from being able to use them. The dependency on configuring anything a server in order to get client-side functionality working is beyond unacceptable. It's a real pity though, htc files really are capable of a lot of interesting things.
unknown
d18781
test
Your requirement isn't valid. The only way to get the text nil to appear in the text field is to assign the actual text @"nil" to the text field. It makes no sense that you to see nil without using @"nil" to do so. Perhaps setting the placeholder to @"nil" is a compromise. A: i think you can use only myTextField.text = @"nil"; or instead of showing nil you can show proper message inside uitextfield or bellow textfiled input is not valid. showing nil is doesn't helps to user. you can use alert to show no input. A: As others have said, this seems like a strange requirement, but you could create a subclass of UITextField that overrides the getter of the text property so that it returns @"nil" if text was actually nil. A: Try This self.textFieldName.placeholder = @"nil";
unknown
d18785
test
You can use a construction called "MEMBER OF". class MembreFamilleRepository extends EntityRepository { public function getMembres($emp) { return $this->createQueryBuilder('a'); ->where(':employee MEMBER OF a.employees') ->setParameter('employee', $emp) ->getQuery() ->getResult() ; } } You can use a construction called "MEMBER OF" A: You need to add a JoinTable for your ManyToMany association and set the owning and inverse sides: /** * @ORM\ManyToMany(targetEntity="PFE\EmployeesBundle\Entity\MembreFamille", * cascade={"persist"}, mapped="employees") */ private $membreFamilles; ................................. /** * @ORM\ManyToMany(targetEntity="PFE\UserBundle\Entity\Employee", cascade={"persist"}, inversedBy="membreFamilles") * @ORM\JoinTable(name="membre_familles_employees") */ private $employees;
unknown
d18789
test
There are a lot of bugs in your code: * *<p> not closed! *Using tables for layout. *More worse: Using nested tables. Going ahead with your layout, I was able to make these corrections to make it work in CSS. tr{ display:table; width:100%; } .lfttbl .td1, .td2{ display:table-row; border-bottom: solid 1px #2b9ed5 !important; } .td1 { display: block; background: #f00; } <table class="out"> <tr><td> <table class="outtbl"> <tr> <td> <table class="lfttbl"> <tr> <td class= td1> <p> hihi hii</p> </td> <td class= td2> <table class = rttbl""> </table> </td> </tr> </table> </td> </tr> </table> A: You must close your <p>hihi hi and use display: block; on the td. Check this: tr{ display:table; width:100%; } .lfttbl .td1, .td2{ display:block; border-bottom: solid 1px #2b9ed5 !important; } <table class="out"> <tr><td> <table class="outtbl"> <tr> <td> <table class="lfttbl"> <tr> <td class= td1> <p> hihi hii</p> </td> <td class= td2> <table class = rttbl""> <p>Lorem ipsum</p> </table> </td> </tr> </table> </td> </tr> </table> A: So, here is what I was struggling on. After several trials and errors, I came to know it works in desktop version now but not in mobile devices. I had attached my code and css on which I was working (Initially "edit" and "delete" were in different td). Now I don't know why its not working on mobo device. I know I can't use if else statement in css (either for desktop or for mobile). #shipIMtd, #shipIMrighttd1, #shipIMrighttd2{display:block;} <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0;"> <link href="mno.css" rel="stylesheet" type="text/css" /> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <META Name="Robots" Content="noindex"> </head> <table id="shipIMmaintbl" width="100%" cellpadding="0" cellspacing="0"> <tr><td align="center"> <table id= "shipIMsubtbl" border="0" width="940"> <tr> <td valign="top" align="center" width="80%"> <div id="shipIMmidacdiv" class="account-mid"><br /> <table width="95%" border="0" cellspacing="0" cellpadding="0" id="table12"> <tr> <td> <table id="shipIMshipadtbl" width="735px" style="width:735px;border:solid 1px #D4D6D8;margin-bottom:15px;"> <tr> <td id="shipIMsubtitle" valign="top" style="border-right: solid 1px #E7E4E4;padding:5px;"><span style="font:600 18px verdana;#2972B6"><strong> Addresses</strong></span></td> <td height="35" align="left" bgcolor="#F6F4F4" class="padd-top-lt">&nbsp;</td> <div id="shipIMtitlediv" class="floatright newAddrBtn"><a href="uvx.asp"><input id="shipIMtitlebtn" type="button" value="+ Add"></a></div> </div> </tr> <tr id="shipIMshipaddtr"> <td id="shipIMtd" valign="top" style="border-right: solid 1px #E7E4E4;width:200px;padding:15px;"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi.</p> </td> <td id="shipIMrighttd1" align="left" class="padd-15 border-tbt1"> <table id="shipIMeditship" cellpadding=3 cellspacing=0 border=0 width=80><tr><td> <form name="editship" action="abc.asp" method="post" /> <input type="hidden" name="shipID" value="shpid"> <input id="shipIMeditbtn" type="submit" value="Edit"> </form> </td><td id="shipIMrighttd2"> <form name="deleteship" action="xyz.asp" method="post"> <input type="hidden" name="shipID" value="shpid" /> <input type="hidden" name="asktype" value="firstask"> <input id="shipIMdelbtn" type="submit" value="Delete"> </form> </td></tr></table> </td> </tr> </table> </td> </tr> </table> </div> </td> </tr> </table> </body> </html> .
unknown
d18795
test
The null makes this tricky. I'm not sure if it should be considered "high" or "low". Let me assume "low": select t.* from t where coalesce(t.position, -1) = (select min(coalesce(t2.position, -1)) from t t2 where t2.name = t.name ); A: SELECT f.* FROM ( SELECT name, MIN(IFNULL(position,0)) as min_position FROM fruits GROUP BY name ) tmp LEFT JOIN fruits f ON f.name = tmp.name AND IFNULL(f.position,0) = min_position -- GROUP BY name -- optional if multiple (name, position) are possible for example -- [apple,fruit,5], [apple,red,5]
unknown
d18797
test
This is an antipattern you want to send an action to the controller and do you work with the store in the controller. However if you have to inject the store into the view you would do this. Ember.onLoad('Ember.Application', function(Application) { Application.initializer({ name: "store", initialize: function(container, application) { application.register('store:main', application.Store); ... } container.lookup('store:main'); } }); Application.initializer({ name: "injectingTheStore", initialize: function(container, application) { application.inject('view', 'store', 'store:main'); } });
unknown
d18799
test
Assuming that: class Product < ApplicationRecord has_one :product_detail end and class ProductDetail < ApplicationRecord belongs_to :product end You can use simple single-line query to fetch expired products or products without details: Product.select { |p| p.product_detail.nil? || p.product_detail.expires_on <= Date.today }
unknown
d18803
test
Use the Environ function to retrieve the environment variables that are set in Windows. Sub TfrSec() Dim argh As Double argh = Shell(Environ("USERPROFILE") & "\Desktop\Transfer Rates File.bat", vbNormalFocus) End Sub See here for a list of available variables in Windows 10.
unknown
d18805
test
/home/user/dev/project/ needs to be in your PYTHONPATH to be able to be imported. If your testing_utils is meant to be local only, the easiest way to accomplish this is to add: import sys sys.path.append('/home/user/dev/project/') ... in dummy_factory.py before importing the module. Solutions that would be more proper would be to install users (how exactly you'd make your package installable depends on your system and what version of Python and Pip you need to support), or to use a virtualenv that automatically adds the right directories to PYTHONPATH.
unknown
d18809
test
If you're looking to turn Azure Service Bus into a Storage Blob, that's probably easy to achieve. You need a Service Bus trigger to retrieve the message payload and its ID to use as a blob name, storing the payload (message body) using whatever mechanism you want. Could be using Storage SDK to write the contents into a blob. Or a blob output binding with a random blob name. Or the message ID as the blob name. Below is an example of a function that will be triggered by a new message in Service bus queue called myqueue and will generate a blob named after message's ID in the messages container. In-process SDK public static class MessageTriggeredFunction { [FunctionName(nameof(MessageTriggeredFunction))] public static async Task Run( [ServiceBusTrigger("myqueue", Connection = "ServiceBusConnectionString")]string payload, string messageId, [Blob("messages/{messageId}.txt", FileAccess.Write, Connection = "StorageAccountConnectionString")] Stream output) { await output.WriteAsync(Encoding.UTF8.GetBytes(payload)); } } Isolated worker SDK public class MessageTriggeredFunctionIsolated { [Function(nameof(MessageTriggeredFunctionIsolated))] [BlobOutput("messages/{messageId}.txt", Connection = "StorageAccountConnectionString")] public string Run( [ServiceBusTrigger("myqueue", Connection = "ServiceBusConnectionString")] string payload, string messageId) { return payload; } }
unknown
d18811
test
I assume that you did specify your EMAIL_HOST, EMAIL_PORT, EMAIL_HOST_USER and EMAIL_HOST_PASSWORD in your settings.py right? A detailed explanation of how the default django.core.mail.backends.smtp.EmailBackend works is explained - https://docs.djangoproject.com/en/dev/topics/email/ https://docs.djangoproject.com/en/dev/topics/email/#smtp-backend And specifically for your email port, you did open your port for smtp under EC2's security group? SMTP port usually defaults to 25 if you left it as default during your postfix configuration and it is important that you have opened up that port when you created your EC2 instance.
unknown
d18813
test
:defaultM); } } When running the above code the list.stream().forEach(A::defaultM); throws the below exception. Why? Why can't the method reference access the methods defined in the package-private interface while the lambda expression can? I'm running this in Eclipse (Version: 2018-12 (4.10.0)) with Java version 1.8.0_191. imp1 imp2 Exception in thread "main" java.lang.BootstrapMethodError: call site initialization exception at java.lang.invoke.CallSite.makeSite(CallSite.java:341) at java.lang.invoke.MethodHandleNatives.linkCallSiteImpl(MethodHandleNatives.java:307) at java.lang.invoke.MethodHandleNatives.linkCallSite(MethodHandleNatives.java:297) at pkg.Test.main(Test.java:14) Caused by: java.lang.IllegalArgumentException: java.lang.IllegalAccessException: class is not public: pkg.a.AA.defaultM()void/invokeInterface, from pkg.Test at java.lang.invoke.MethodHandles$Lookup.revealDirect(MethodHandles.java:1360) at java.lang.invoke.AbstractValidatingLambdaMetafactory.<init>(AbstractValidatingLambdaMetafactory.java:131) at java.lang.invoke.InnerClassLambdaMetafactory.<init>(InnerClassLambdaMetafactory.java:155) at java.lang.invoke.LambdaMetafactory.metafactory(LambdaMetafactory.java:299) at java.lang.invoke.CallSite.makeSite(CallSite.java:302) ... 3 more Caused by: java.lang.IllegalAccessException: class is not public: pkg.a.AA.defaultM()void/invokeInterface, from pkg.Test at java.lang.invoke.MemberName.makeAccessException(MemberName.java:850) at java.lang.invoke.MethodHandles$Lookup.checkAccess(MethodHandles.java:1536) at java.lang.invoke.MethodHandles$Lookup.revealDirect(MethodHandles.java:1357) ... 7 more A: This appears to be a bug in certain Java versions. I can replicate it if I compile and run it with JDK 8, specifically: tj$ javac -version javac 1.8.0_74 tj$ java -version java version "1.8.0_74" Java(TM) SE Runtime Environment (build 1.8.0_74-b02) Java HotSpot(TM) 64-Bit Server VM (build 25.74-b02, mixed mode) ...but not with JDK 11 or 12, specifically: tj$ javac -version javac 11.0.1 tj$ java -version openjdk version "11.0.1" 2018-10-16 OpenJDK Runtime Environment 18.9 (build 11.0.1+13) OpenJDK 64-Bit Server VM 18.9 (build 11.0.1+13, mixed mode) and tj$ javac -version javac 12.0.2 tj$ java -version java version "12.0.2" 2019-07-16 Java(TM) SE Runtime Environment (build 12.0.2+10) Java HotSpot(TM) 64-Bit Server VM (build 12.0.2+10, mixed mode, sharing) I can also replicate it if I compile with JDK 8 but run it with JDK 12's runtime, suggesting a compilation problem. A: This is a bug: Method reference uses wrong qualifying type. A reference to a method declared in a package-access class (via a public subtype) compiles to a lambda bridge; the qualifying type in the bridge method is the declaring class, not the referenced class. This leads to an IllegalAccessError. Fixed in Java 9.
unknown
d18815
test
Presumably, you have configured VS Code to run the code through Node.js and not through a remote debug session on a Chrome instance. Node.js isn't a web browser. It doesn't have a window.
unknown
d18817
test
You can do this by command prompt. First git checkout master git merge page-switcher-fix at the end git branch -d page-switcher-fix I hope I could have helped A: Seems it's possible to delete removed branch .git\refs\heads in cause I step back by timemachine and bug fixed. Anyway, best choise is step back by timemachine or same like snapshots in Virtual Machine A: A distinction is made between remote and local branches. As you describe your case you deleted your branch remotely. For further context please see the code below for the command prompt: # delete branch remotely git push origin --delete page-switcher-fix And as the solution of @Mohammad Afshar correctly suggests you can delete your branch locally as follows: # delete branch locally git branch -d page-switcher-fix
unknown
d18825
test
One way to achieve the desired result: IN = load 'data.txt' using PigStorage(',') as (name:chararray, type:chararray, date:int, region:chararray, op:chararray, value:int); A = order IN by op asc; B = group A by (name, type, date, region); C = foreach B { bs = STRSPLIT(BagToString(A.value, ','),',',3); generate flatten(group) as (name, type, date, region), bs.$2 as OpX:chararray, bs.$0 as OpC:chararray, bs.$1 as OpT:chararray; } describe C; C: {name: chararray,type: chararray,date: int,region: chararray,OpX: chararray,OpC: chararray,OpT: chararray} dump C; (john,ab,20130106,D,20,19,8) (john,ab,20130106,E,98,854,67) Update: If you want to skip order by which adds an additional reduce phase to the computation, you can prefix each value with its corresponding op in tuple v. Then sort the tuple fields by using a custom UDF to have the desired OpX, OpC, OpT order: register 'myjar.jar'; A = load 'data.txt' using PigStorage(',') as (name:chararray, type:chararray, date:int, region:chararray, op:chararray, value:int); B = group A by (name, type, date, region); C = foreach B { v = foreach A generate CONCAT(op, (chararray)value); bs = STRSPLIT(BagToString(v, ','),',',3); generate flatten(group) as (name, type, date, region), flatten(TupleArrange(bs)) as (OpX:chararray, OpC:chararray, OpT:chararray); } where TupleArrange in mjar.jar is something like this: .. import org.apache.pig.EvalFunc; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.schema.Schema; public class TupleArrange extends EvalFunc<Tuple> { private static final TupleFactory tupleFactory = TupleFactory.getInstance(); @Override public Tuple exec(Tuple input) throws IOException { try { Tuple result = tupleFactory.newTuple(3); Tuple inputTuple = (Tuple) input.get(0); String[] tupleArr = new String[] { (String) inputTuple.get(0), (String) inputTuple.get(1), (String) inputTuple.get(2) }; Arrays.sort(tupleArr); //ascending result.set(0, tupleArr[2].substring(1)); result.set(1, tupleArr[0].substring(1)); result.set(2, tupleArr[1].substring(1)); return result; } catch (Exception e) { throw new RuntimeException("TupleArrange error", e); } } @Override public Schema outputSchema(Schema input) { return input; } }
unknown
d18829
test
This is a really old question, sorry it never got answered, but it's also very broad is some portions. I would recommend asking shorter, more specific questions, and making multiple StackOverflow questions for them. That said, here's some brief answers for people reading this entry: * *Yes, this is possible. Check out the REST connector. *I would probably use multiple parent models that are internal and then a single exposed REST model (not "persisted") that collates that data together. *Sure, you could do that. Writing a connector isn't too difficult, check out our docs on building a connector.
unknown
d18835
test
You need covariant return types. The return type from the derived class needs to be a pointer or reference derived from the return type of the base class. This can be accomplished by wrapping HWND and HMENU in a class hierarchy making a parallel of the API's organization. Templates may help if it's all generic.
unknown
d18837
test
If you only have a hand full of result sets, it might be easiest to sort them in java, using a Comparator. If you have to do it in oracle you can use a statement like the following: select * // never do that in production from someTable where id in (10121005444, 206700013, 208700013, 30216118005, 30616118005) order by decode(id, 10121005444, 1, 206700013, 2, 208700013, 3, 30216118005, 4, 30616118005, 5) A: You can't specify the order using the IN clause. I think you have two options: * *perform the query using IN, and sort your result set upon receipt *issue a separate query for each specified id in order. This is obviously less efficient but a trivial implementation. A: you can use this query -- SELECT id FROM table WHERE id in (10121005444, 206700013, 208700013, 30216118005, 30616118005) ORDER BY FIND_IN_SET(id, "10121005444, 206700013, 208700013, 30216118005, 30616118005"); second list define the order in which you want your result set to be
unknown
d18841
test
am i adding the driver correctly I don't think so. There is something very odd going on here. According to the official MySQL source code repo for Connector/J on Github, there is no com.mysql.jdbc.DocsConnectionPropsHelper class in Connector/J version 8.0.28. But this class does exist in Connector/J 5.1.x. So it looks like you must somehow be using Connector/J 5.x rather than 8.0.x as the IDE screenshot seems to suggest. Check the dependencies on the actual runtime classpath you are using to run this code. (Note that the screenshot shows the project's build classpath not its runtime classpath.) Certainly you should not be mixing the two generations of driver. Calling RegisterDriver with the (8.0.x) com.mysql.cj.jdbc.Driver class when you have the 5.x driver on the classpath is wrong. A: you can try like this Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
unknown
d18843
test
You can get the ado.net driver (+ python, java, etc..) from this address: https://tools.hana.ondemand.com/#hanatools A: It is part of the SAP HANA client package. Go to https://service.sap.com/hana, login, then click "Software download", and select your edition. Proceed with "SAP HANA Client 1.00", not with the proposed "Studio".
unknown
d18847
test
I have investigated a bit this problem and I can see two solutions: Easy way Use a private boolean variable instead of using the IsEnabled property. Then when the clicked event is handled, check the switch's status with the variable. Hard way Overwrite the Switch control to get this behaviour. You can follow this guide. A: As seen from the Switch for Xamarin.Forms, there is currently no option of specifying the color. Conclusively, you will have to create your own renderer for both iOS and Android. Android Essentially, what you need to do is to override the OnElementChanged and OnCheckChanged events and check for the Checked Property of the Control. Afterwards, you can set the ThumbDrawable of the Control and execute SetColorFilter with the color you want to apply. Doing so although requires Android 5.1+. An example is given here. You could also create utilise the StateListDrawable and add new ColorDrawables for the StateChecked, StateEnabled and lastly, a default value as well. This is supported for Android 4.1+. An example of using the StateListDrawable is provided in detail here. iOS iOS is somewhat more simple. Simply create your own SwitchRenderer, override the OnElementChanged event and set the OnTintColor and ThumbTintColor. I hope this helps. A: You need to make custom renderer for your control in this case switch like that and set color when it changes: class CustomSwitchRenderer : SwitchRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Switch> e) { base.OnElementChanged(e); this.Control.ThumbDrawable.SetColorFilter(this.Control.Checked ? Color.DarkGreen : Color.Red, PorterDuff.Mode.SrcAtop); this.Control.TrackDrawable.SetColorFilter(this.Control.Checked ? Color.Green : Color.Red, PorterDuff.Mode.SrcAtop); this.Control.CheckedChange += this.OnCheckedChange; } private void OnCheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e) { this.Control.ThumbDrawable.SetColorFilter(this.Control.Checked ? Color.DarkGreen : Color.Red, PorterDuff.Mode.SrcAtop); this.Control.TrackDrawable.SetColorFilter(this.Control.Checked ? Color.Green : Color.Red, PorterDuff.Mode.SrcAtop); } }
unknown
d18851
test
You can use isinstance(angle, list) to check if it is a list. But it won't help you achieve what you really want to do. The following code will help you with that. question = """Please enter the angle you want to convert. If you wish to convert degree in radiant or vice-versa. Follow this format: 'angle/D or R' """ while 1: angle=input(question).split('/') if not isinstance(angle, list): break # This will never happen # It will never happen because string.split() always returns a list # Instead you should use something like this: if len(angle) != 2 or angle[1] not in ['D', 'R']: break try: angle[0]=float(angle[0]) except ValueError: break if (angle[0]>=0 or angle[0]<=360) and angle[1] is 'D': # You could also improve this by taking modulo 360 of the angle. print((angle[0]*np.pi)/180, 'radiants') else: # Just an else is enough because we already checked that angle[1] is either D or R print((angle[0]*180)/np.pi, 'degrees') A: What you want: if not isinstance(angle, list): break What you've done: if angle is not list():break will always evaluate to True as no object will ever have the same identity as the list list(); since is is a check for identity. Even this: >>> list() is not list() True A: break statements are used to get out of for and while loops. Try using a while loop after the input statement to evaluate the input. Use a possible set as a conditional. You do not need to break from an if statement because it will just be bypassed if the the conditional is not met. Sometimes you might see an if statement followed by a break statement. The break statement, however, is not breaking from the if statement. It is breaking from a previous for or while loop.
unknown
d18853
test
you have string iden, convert it to int like this: int devId= Convert.ToInt32(iden);
unknown
d18855
test
You do not have to install WSO2 Private PaaS to have API Manager. From WSO2 site, you can download stand-alone API Manager or use the hosted version - WSO2 API Cloud. Once you are familiar with API Manager or API Cloud, if you do decide that you want to spawn it within Private PaaS, you can follow this document to locate the corresponding cartridge and subscribe to it. A: Before getting started with WSO2 Private PaaS, it is worth to watch these well-organized, 6-steps video tutorials on "Getting Started With WSO2 Private PaaS". After watching these, you will have a basic understanding, from there you can move forward without any issues. Step 0 - Finding the Documentation Step 1 - Provisioning an EC2 Instance from WSO2 Private PaaS AMI Step 2 - Provisioning the WSO2 Private Platform as a Service Environment Step 3 - Configuring Private Platform as a Service with Tenants Step 4 - Provisioning Application Platform Services Step 5 - Deploying a Web Application on a Private Platform as a Service Environment running on Amazon EC2
unknown
d18857
test
I don't know what Supabase does but the problem seems to be Promise related Try to change your app.js as follow const { supabase } = require('./client') function signOut() { /* sign the user out */ supabase.auth.signOut(); } function signInWithGithub() { /* authenticate with GitHub */ return supabase.auth.signIn({ provider: 'github' }); } function printUser() { const user = supabase.auth.user() console.log(user.email) } signInWithGithub().then(() => { printUser() return signOut() })
unknown
d18861
test
yes there are some examples of using Pure Java, no J2EE. http://bastide.org/2014/01/28/how-to-develop-a-simple-java-integration-with-the-ibm-social-business-toolkit-sdk/ and https://github.com/OpenNTF/SocialSDK/blob/master/samples/java/sbt.sample.app/src/com/ibm/sbt/sample/app/BlogServiceApp.java Essentially, you'll need the dependent jar files. once, you have the jar files you need to configure your class so you can get an Endpoint once you have the endpoint you can use the endpoint in one of the top level services such as ForumsService then you can use the ForumsService to call back to Connections
unknown
d18863
test
Look at the url http://www.noncode.org/show_rna.php?id=NONHSAT000002 The search is just passed as a get parameter. So to access the side just set the start url to something like: import requests from bs4 import * id = "NONHSAT146018" page = requests.get("http://www.noncode.org/show_rna.php?id=" + id) soup = BeautifulSoup(page.content, "html.parser") element = soup.findAll('table', class_="table-1")[1] element2 = element.findAll('tr')[1] element3 = element2.findNext('td') your_data = str(element3.renderContents(), "utf-8") print(your_data)
unknown
d18867
test
The smartest to do would be to implement a solve function like Stanislav recommended. You can't just iterate over values of x until the equation reaches 0 due to Floating Point Arithmetic. You would have to .floor or .ceil your value to avoid an infinity loop. An example of this would be something like: x = 0 while True: x += 0.1 print(x) if x == 10: break Here you'd think that x eventually reaches 10 when it adds 0.1 to 9.9, but this will continue forever. Now, I don't know if your values are integers or floats, but what I'm getting at is: Don't iterate. Use already built solve libraries.
unknown
d18879
test
Is there a way to refresh the cursor? Call restartLoader() to have it reload the data. I don't want to have to create a new Cursor each time a checkbox is checked, which happens a lot Used properly, a ListView maintains the checked state for you. You would do this via android:choiceMode="multipleChoice" and row Views that implement Checkable. The objective is to not modify the database until the user has indicated they are done messing with the checklist by one means or another (e.g., "Save" action bar item). I'm also unsure of how calling restartLoader() several times would work, performance-wise, especially since I use onLoadFinish() to perform some animations. Don't call it several times. Ideally, call it zero times, by not updating the database until the user is done, at which point you are probably transitioning to some other portion of your UI. Or, call it just once per requested database I/O (e.g., at the point of clicking "Save"). Or, switch from using a CursorAdapter to something else, such as an ArrayAdapter on a set of POJOs you populate from the Cursor, so that the in-memory representation is modifiable in addition to being separately persistable.
unknown
d18883
test
I figured it out, in case anyone needs to know this in the future.Simply add the following line under "onValueSelected": @Override public void onValueSelected(Entry e, Highlight h) { String label = dataSets.get(h.getDataSetIndex()).getLabel(); //add this } In this case, dataSets is the "ILineDataSet" used to populate the line chart
unknown
d18885
test
Here's a parser subclass that implements the latest suggestion on the https://bugs.python.org/issue9334. Feel free to test it. class ArgumentParserOpt(ArgumentParser): def _match_argument(self, action, arg_strings_pattern): # match the pattern for this action to the arg strings nargs_pattern = self._get_nargs_pattern(action) match = _re.match(nargs_pattern, arg_strings_pattern) # if no match, see if we can emulate optparse and return the # required number of arguments regardless of their values # if match is None: import numbers nargs = action.nargs if action.nargs is not None else 1 if isinstance(nargs, numbers.Number) and len(arg_strings_pattern) >= nargs: return nargs # raise an exception if we weren't able to find a match if match is None: nargs_errors = { None: _('expected one argument'), OPTIONAL: _('expected at most one argument'), ONE_OR_MORE: _('expected at least one argument'), } default = ngettext('expected %s argument', 'expected %s arguments', action.nargs) % action.nargs msg = nargs_errors.get(action.nargs, default) raise ArgumentError(action, msg) # return the number of arguments matched return len(match.group(1)) It replaces one method providing a fall back option when the regular argument matching fails. If you and your users can live with it, the long flag fix is best --arg=-a is simplest. This unambiguously specifies -a as an argument to the --arg Action.
unknown
d18889
test
Firstly, if your platform is 64-bit, then why are you casting your pointer values to int? Is int 64-bit wide on your platform? If not, your subtraction is likely to produce a meaningless result. Use intptr_t or ptrdiff_t for that purpose, not int. Secondly, in a typical implementation a 1-byte type will typically be aligned at 1-byte boundary, regardless of whether your platform is 64-bit or not. To see a 8-byte alignment you'd need a 8-byte type. And in order to see how it is aligned you have to inspect the physical value of the address (i.e. whether it is divisible by 1, 2, 4, 8 etc.), not analyze how far apart two variables are spaced. Thirdly, how far apart c1 and c2 are in memory has little to do with alignment requirements of char type. It is determined by how char values are passed (or stored locally) on your platform. In your case they are apparently allocated 4-byte storage cells each. That's perfectly fine. Nobody every promised you that two unrelated objects with 1-byte alignment will be packed next to each other as tightly as possible. If you want to determine alignment by measuring how far from each other two objects are stored, declare an array. Do not try to measure the distance between two independent objects - this is meaningless. A: To determine the greatest fundamental alignment in your C implementation, use: #include <stdio.h> #include <stddef.h> int main(void) { printf("%zd bytes\n", _Alignof(max_align_t)); } To determine the alignment requirement of any particular type, replace max_align_t above with that type. Alignment is not purely a function of the processor or other hardware. Hardware might support aligned or unaligned accesses with different performance effects, and some instructions might support unaligned access while others do not. A particular C implementation might choose to require or not require certain alignment in combination with choosing to use or not use various instructions. Additionally, on some hardware, whether unaligned access is supported is configurable by the operating system.
unknown
d18891
test
This seems to be an old question, but I was running into the same thing today. I am rather new to git and npm, but I did find something that may be of help to someone. If the git repo does not have a .gitignore, the .git folder is not downloaded / created. If the git repo does have a .gitignore, the .git folder is downloaded / created. I had two repos, one without a .gitignore (because when I made it I was not aware of what .gitignore was or did), and one with a .gitignore. I included both as npm packages in a project, and noticed that the one without the .gitignore was not giving me the EISGIT error (because of the .git folder). So, after I found this question, I removed the .gitignore from that repo and now it too does not create a .git folder. Later on, I discovered that adding both a .gitignore and a .npmignore to the project now stops the .git folder from appearing. I did not add .git in my .npmignore.
unknown
d18899
test
You should not make your factory class generic but the method GetObject should be generic: public T GetObject<T>() where T: IMyInterface, new() Then: static void Main(string[] args) { var factory = new MyFactory(); var obj = factory.GetObject<MyClass>(); obj.Method1(); Console.ReadKey(); } So all in all you should get rid of your generic code and simply modify your MyFactory class public class MyFactory : IClassFactory { public T GetObject<T>() { //TODO - get object of T type and return it return new T(); } } By the way - I am not sure what is the purpose of having this generic implementation? Does it make any sense from the perspective of the usage of Factory pattern?
unknown
d18903
test
There is no way to change the typeface of TextView in RemoteView. To check properties that can be changed in RemoteView, in your case just go to Button and TextView classes and check all methods with annotation @android.view.RemotableViewMethod. As you can see, setTypeface don't have an annotation, so it can not be changed in RemoteView anyhow
unknown
d18905
test
I think the problem might be that you were trying to register GF 3.1.2 to use Java SE 5. Java EE 6 requires a Java SE 6 JDK to run successfully. A: Okay I don't know what was wrong with it. Just tried it one more time and it worked! Sry for taking your times.
unknown
d18907
test
I think the problem is: $result = implode(",", $data); $nr = randWithout(500, 550, array($result)); while you should do is remove the implode and send the $data array directly. $randWithout(500, 550, $data); A: Tim is right, do not implode results in a string. But that is the quite odd function for getting random number with exceptions. Try something like: function getRndWithExceptions($from, $to, array $ex = array()) { $i = 0; do { $result = rand($from, $to); } while( in_array($result, $ex) && ++$i < ($to - $from) ); if($i == ($to - $from)) return null; return $result; } <...> $nr = getRndWithExceptions(500, 550, $data); // $data is array
unknown
d18909
test
Check http://api.jquery.com/on/ You could do something like this: $("body").on({ click: function() { //... } mouseleave: function() { //... }, //other event, etc }, "#yourthing"); A: You can try this and can use any other mouse events according to your need: $("#mainContainer").on('hover', function(){ $(selector).slideDown("slow"); }), function(){ $(selector).slideUp("slow"); }); A: Maybe something like this? You might not need any JavaScript for the mouseover effect. #mainConatiner { width: 300px; height: 30px; border: 1px solid #000; } ul { opacity: 0; transition: opacity 250ms ease; } #mainContainer:hover ul { opacity: 1; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="mainContainer"> Hover me! <ul> <li>User 1</li> <li>User 2</li> </ul> </div> Let me know if it helps! Good luck. A: JQuery has mouse based events. See here. See this fiddle where I have adapted the w3schools example to work on mouseenter and mouseleave A: You could use it like this, by calling the same function for multiple events: $("mainContainer").on('click mouseenter',function (event) { //This gives you what event happened, might be 'click' or 'mouseenter' var type = event.type; });
unknown
d18913
test
Is this what you're looking for? (sorry had to change up the classes a bit). What I did was added a display:grid; and align-items:center; on all parents of the p tags. HTML: <div class="flex"> <div class="flex-item"> <section> <p class="text-center">Section</p> </section> <article> <p class="text-center">Article</p> </article> </div> <aside class="center flex-item"> <p>Aside</p> </aside> </div> CSS body { background-color: silver; } div { background-color: white; } header, nav, section, article, aside, footer { background-color: white; padding: 10px; border: solid; } .flex { display: flex; } .flex-item { flex: 1; } .flex-item section, .flex-item article, .center { display: grid; align-items: center; text-align: center; } .flex-item section, .flex-item article { height: 200px; /* this is just to see the vertical layout */ } You should now be able to freely align, left, center and right, but there are more ways to do this. If you're worried about using grid, it has good support and it works fine on most major browsers :) A: This is my first answer every, I hope this helps! This happens because you put flex: 1; on the parent of the "aside" text, changing the size of the parent but not the child. Try changing flex: initial; on the "aside" text parent and you'll see what I mean. You can fix this in a ton of ways, one way is to put width: 100%; on the "aside" text <p></p> A: you can put either p {flex-grow: 1} or p {min-width: 100%}
unknown
d18915
test
You don't write anything to terminal because there's no terminal. You pass name of a program to run and its arguments as arguments of the QProcess::start method. If you only need to know if ping was successful or not it's enough to check the exit code of the process which you started earlier using QProcess::start; you don't have to read its output. from ping(8) - Linux man page If ping does not receive any reply packets at all it will exit with code 1. If a packet count and deadline are both specified, and fewer than count packets are received by the time the deadline has arrived, it will also exit with code 1. On other error it exits with code 2. Otherwise it exits with code 0. This makes it possible to use the exit code to see if a host is alive or not. By default ping under Linux runs until you stop it. You can however use -c X option to send only X packets and -w X option to set timeout of the whole process to X seconds. This way you can limit the time ping will take to run. Below is a working example of using QProcess to run ping program on Windows. For Linux you have to change ping options accordingly (for example -n to -c). In the example, ping is run up to X times, where X is the option you give to Ping class constructor. As soon as any of these executions returns with exit code 0 (meaning success) the result signal is emitted with value true. If no execution is successful the result signal is emitted with value false. #include <QCoreApplication> #include <QObject> #include <QProcess> #include <QTimer> #include <QDebug> class Ping : public QObject { Q_OBJECT public: Ping(int count) : QObject(), count_(count) { arguments_ << "-n" << "1" << "example.com"; QObject::connect(&process_, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(handlePingOutput(int, QProcess::ExitStatus))); }; public slots: void handlePingOutput(int exitCode, QProcess::ExitStatus exitStatus) { qDebug() << exitCode; qDebug() << exitStatus; qDebug() << static_cast<QIODevice*>(QObject::sender())->readAll(); if (!exitCode) { emit result(true); } else { if (--count_) { QTimer::singleShot(1000, this, SLOT(ping())); } else { emit result(false); } } } void ping() { process_.start("ping", arguments_); } signals: void result(bool res); private: QProcess process_; QStringList arguments_; int count_; }; class Test : public QObject { Q_OBJECT public: Test() : QObject() {}; public slots: void handle(bool result) { if (result) qDebug() << "Ping suceeded"; else qDebug() << "Ping failed"; } }; int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); Test test; Ping ping(3); QObject::connect(&ping, SIGNAL(result(bool)), &test, SLOT(handle(bool))); ping.ping(); app.exec(); } #include "main.moc"
unknown
d18919
test
If you want to overwrite based on the last modified date, then the File object has the property you want: DateLastModified. (You can check all properties of the File object here.) You already have access to the source file objects (your code's Photo variable) so you just need to get the target's file object. Something like this should work: Dim Photo Dim targetFile, bmpTargetFilename, jpgTargetFilename SourceFolder = "C:\Photo1" DistinationFolder = "C:\Photo2" Set ObjPhoto = CreateObject("Scripting.FileSystemObject") For Each Photo In ObjPhoto.GetFolder(SourceFolder).Files bmpTargetFilename = ObjPhoto.BuildPath(DistinationFolder, Replace(Photo.Name, ".jpg", ".bmp")) jpgTargetFilename = ObjPhoto.BuildPath(DistinationFolder, Photo.Name) If ObjPhoto.FileExists(bmpTargetFilename) Then ' Get the target file object Set targetFile = ObjPhoto.GetFile(jpgTargetFilename) ' Now compare the last modified dates of both files If Photo.DateLastModified > targetFile.DateLastModified Then Photo.Copy jpgTargetFilename, True End If Else Photo.Copy jpgTargetFilename, True End If Next A couple of notes: * *It seems you are checking for the existence of a .BMP file yet copying a .JPG file, so I made it explicit by using two variables. *I am also assuming you want to compare the JPG files, since those are the ones being copied.
unknown
d18923
test
Nevermind folks -- problem solved, but haven't quite figured out why. File encoding is my guess.
unknown
d18927
test
If "yourImageView" is the ImageView and you want to set background of it and the name of image is "imageName" yourImageView.setImageResource(context.getResources(). getIdentifier("drawable/" + imageName, null,context.getPackageName())); But i should say sorry as it doesn't really give you drawable but it gives Resource, But i hope this will help you use the string name of drawable file.
unknown
d18931
test
You refer to an Objective-C example, but you have not done what it says to do! Your second method is the wrong method. You want to say this: override func tableView(tableView: UITableView, canPerformAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool { return action == #selector(copy(_:)) } You will also need a third override: override func tableView(tableView: UITableView, performAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) { // ... }
unknown
d18933
test
Use a temporary string in strcat instead of strcat(out[0],*pa);. Also, make sure that you allocate enough memory for out. int main() { char a[10]="abcdefg123"; char temp[2] = {0}; char *pa=a; // This is not good for `strcat`. // char *out[2]={"",""}; // Use this instead. char out[2][20]={"",""}; int counter=0; while(*pa != '\0'){ temp[0] = *pa; if (counter%2==0){ strcat(out[0], temp); } else{ strcat(out[1], temp); } counter++; pa++; } printf("%s,%s\n",out[0],out[1]); return 0; } A: Point 1. As per the man page of strcat() . .. the dest string must have enough space for the result. Point 2. The second argument for strcat() is const char *, so the call cannot be strcat(out[0],*pa);. You need to use a temporary array for that, which will hold only the value *pa. Otherwise, you can make use of strncat() like strncat(out[0], pa, 1); // copy only 1 char In later case, you don't need to have any temporary array. Reference: From man page, again, The strncat() function is similar, except that it will use at most n bytes from src and src does not need to be null-terminated if it contains n or more bytes. A: strcat() requires a pointer to a null-terminated string. You are dereferencing a pointer (with the * operator) which gives a char. You cannot simply cast a char to a pointer to sting. You might want to be using memcpy() instead of strcat(), but for copying single bytes a simple assignment using * operators on both the left and right sides would be fine. But as others have pointed out your code isn't allocating space for you to copy the chars into, so you're going to need to make additional changes to fix that. Also, you'll have to remember to copy a final null byte to the end of both your output strings. A: In C, a "string" is really just a pointer to a character; the string runs from that character to the terminating 0 byte (the NUL). If you dereference a string pointer, you get the character at that position. If the pointer is pointing to the start of the string, you get the first character of the string. Your program has some problems. For one, you need to allocate space for the new strings. strcat() will try to copy characters wherever you tell it to, but it's your job to make sure that there is room there and that it's okay to write there. The declaration of out just declares two pointers, and initializes them to point to a zero-length constant string. Instead, you need to allocate storage, something like: char out0[64], out1[64]; char *out[]={out0, out1}; This makes two output buffers of 64 characters each, then sets up out with pointers to them. Another problem: you declared a length of 10 for your char array, but then you initialize it with a length-10 string. This means there is no room for a terminating NUL byte and C won't put one. Then strcpy() or strcat() will copy extra garbage from the string, until there happens to be a NUL byte. If you are lucky there will be one right away and you won't spot the error, but if you aren't lucky you will get weird garbage. Just let the compiler count how many bytes in your string and do the right thing. Leave out the length: char a[]="abcdefg123";
unknown
d18935
test
Sets would appear to be the obvious solution. The following approach reads each column into its own set(). It then simply uses the difference() function to give you entries that are in col1 but not in col2 (which is the same as simply using the - operator): import csv col1 = set() col2 = set() with open('input.csv') as f_input: for row in csv.reader(f_input): if len(row) == 2: col1.add(row[0]) col2.add(row[1]) elif len(row) == 1: col1.add(row[0]) print col1 print col2 print sorted(col2 - col1) So if your CSV file had the following entries: aaa,aaa bbb,111 ccc,bbb ddd,222 eee fff The required output would be: ['111', '222'] The data in your CSV file might need sanitizing before being added to the set, for example EXAMPLE.COM and example.com would currently be considered different.
unknown
d18937
test
Play Protect Appeals Submission Form can solve your problem. Just send your apk details to Google and wait for appeal process. When you enter your apk's URL, Google will control your apk. Just enter your URL to URL to download your APK file section. You do not need publish your app.
unknown
d18939
test
IIUC, you have a pandas DataFrame and want to drop all rows that contain at least one string that ends with the letter 'A'. One fast way to accomplish this is by creating a mask via numpy: import pandas as pd import numpy as np Suppose our df looks like this: 0 1 2 3 4 5 0 ADFC FDGA HECH AFAB BHDH 0 1 AHBD BABG CBCA AHDF BCAG 1 2 HEFH GEHH CBEF DGEC DGFE 2 3 HEDE BBHE CCCB DDGB DCAG 3 4 BGEC HACB ACHH GEBC GEEG 4 5 HFCC CHCD FCBC DEDF AECB 5 6 DEFE AHCH CHFB BBAA BAGC 6 7 HFEC DACC FEDA CBAG GEDD 7 Goal: we want to get rid of rows with index 0, 1, 6, 7. Try: mask = np.char.endswith(df.to_numpy(dtype=str),'A') # create ndarray with booleans indices_true = df[mask].index.unique() # Int64Index([0, 1, 6, 7], dtype='int64') df.drop(indices_true, inplace=True) # drop indices_true print(df) out: 0 1 2 3 4 5 2 HEFH GEHH CBEF DGEC DGFE 2 3 HEDE BBHE CCCB DDGB DCAG 3 4 BGEC HACB ACHH GEBC GEEG 4 5 HFCC CHCD FCBC DEDF AECB 5 A: A bit unclear on your requirements but maybe this fits. Generate some words in columns for which end in 'A'. If any string in the designated columns ends with 'A' then delete the row. nb_cols = 9 nb_vals = 6 def wgen(): return ''.join(random.choices(string.ascii_lowercase, k=5)) + random.choice('ABCDEFGH') df = pd.DataFrame({'Col'+str(c): [wgen() for c in range(1,nb_vals)] for c in range(1,nb_cols+1)}) print(df) Col1 Col2 Col3 Col4 Col5 Col6 Col7 Col8 Col9 0 aawivA qorjeA qfjuoD nkwgzF auablC aehnqE cwuvzF diqwaF qlnpzG 1 aidjuH ljalaB ldhgsC zaangH mdtgkF lypfnB kynrxG qlnygH zzqyrC 2 pzqibD jdumcF ddufmG xstdcH vqpbkG rjnqxD ugscrA kmvyaE cykutE 3 gqpycH ynaeeA onirjE mnbtyH swjuzF dyvmvC tpxgsH ssnhbD spsojD 4 isptdF qzpitH akzwgE klgqpH pqpcqH psryiD tjaurC daaieC piduzE Say that we are looking for the "ending A" in Col4-Col7. Then row with index 2 needs to be deleted: df[~df[['Col'+str(c) for c in range(4,7+1)]] .apply(lambda x: x.str.match('.*A$').any(), axis=1)] Col1 Col2 Col3 Col4 Col5 Col6 Col7 Col8 Col9 0 aawivA qorjeA qfjuoD nkwgzF auablC aehnqE cwuvzF diqwaF qlnpzG 1 aidjuH ljalaB ldhgsC zaangH mdtgkF lypfnB kynrxG qlnygH zzqyrC 3 gqpycH ynaeeA onirjE mnbtyH swjuzF dyvmvC tpxgsH ssnhbD spsojD 4 isptdF qzpitH akzwgE klgqpH pqpcqH psryiD tjaurC daaieC piduzE
unknown
d18941
test
I think ArgumentOutOfRangeException occurred because you're not setting DataKeyNames attribute property on the grid, hence the row index is still out of bounds when calling e.RowIndex. You should set it to ID/primary key column name like this: DataKeyNames="[ID or PK column name]" Here is an example usage: <asp:GridView ID="GridView1" runat="server" DataKeyNames="id" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" Width="1650px" AutoGenerateDeleteButton="True" OnRowDeleting="GridView1_RowDeleting"> </asp:GridView> Update 1 Additionally, I found parameter name mismatch on this query: string query = "DELETE FROM mainpage WHERE id=@ID"; NpgsqlCommand cmd = new NpgsqlCommand(query, cn); cmd.Parameters.Add("@ID2", NpgsqlDbType.Integer).Value = ID2; The correct one should be like example below: string query = "DELETE FROM mainpage WHERE id=@ID"; NpgsqlCommand cmd = new NpgsqlCommand(query, cn); cmd.Parameters.Add("@ID", NpgsqlDbType.Integer).Value = ID2; Reference: GridView.DataKeyNames Property
unknown
d18949
test
having the [{ngModel}] in there was bad. the code below allowed me to make it so that: 'clientsClone' is an array of objects returned from the server and the [value]="clnt.id" with the formControlName="clientId" lets me say "hey this id int is what you need for that form's value!" code here: <select formControlName="clientId" (change)="onOptionsChanged(2)"> <option *ngFor="let clnt of clientsClone" [value]="clnt.id">{{clnt.id}} - {{clnt.pointOfContact}} </option> </select>
unknown
d18951
test
your title says "index" but your example shows you wanting to return a string. If, in fact, you are wanting to return the string, try this: if(initString.includes('/digital/collection/')) { var components = initString.split('/'); return components[3]; } A: If the path is always the same, and the field you want is the after the third /, then you can use split. var initString = '/digital/collection/music/bunch/of/other/stuff'; var collection = initString.split("/")[2]; // third index In the real world, you will want to check if the index exists first before using it. var collections = initString.split("/"); var collection = ""; if (collections.length > 2) { collection = collections[2]; } A: You can use const desiredString = initString.slice(19, 24); if its always music you are looking for. A: If you need to find the next path param that comes after '/digital/collection/' regardless where '/digital/collection/' lies in the path * *first use split to get an path array *then use find to return the element whose 2 prior elements are digital and collection respectively const initString = '/digital/collection/music/bunch/of/other/stuff' const pathArray = initString.split('/') const path = pathArray.length >= 3 ? pathArray.find((elm, index)=> pathArray[index-2] === 'digital' && pathArray[index-1] === 'collection') : 'path is too short' console.log(path) A: Think about this logically: the "end index" is just the "start index" plus the length of the substring, right? So... do that :) const sub = '/digital/collection/'; const startIndex = initString.indexOf(sub); if (startIndex >= 0) { let desiredString = initString.substring(startIndex + sub.length); } That'll give you from the end of the substring to the end of the full string; you can always split at / and take index 0 to get just the first directory name form what remains. A: You can also use regular expression for the purpose. const initString = '/digital/collection/music/bunch/of/other/stuff'; const result = initString.match(/\/digital\/collection\/([a-zA-Z]+)\//)[1]; console.log(result); The console output is: music A: If you know the initial string, and you have the part before the string you seek, then the following snippet returns you the string you seek. You need not calculate indices, or anything like that. // getting the last index of searchString // we should get: music const initString = '/digital/collection/music/bunch/of/other/stuff' const firstPart = '/digital/collection/' const lastIndexOf = (s1, s2) => { return s1.replace(s2, '').split('/')[0] } console.log(lastIndexOf(initString, firstPart))
unknown
d18953
test
A possible solution is to override the drawForeground() method to paint the vertical line, to calculate the positions you must use the mapToPosition() method: import sys from PyQt5.QtCore import Qt, QPointF from PyQt5.QtGui import QColor, QPainter, QPen from PyQt5.QtWidgets import QApplication, QMainWindow from PyQt5.QtChart import ( QBarCategoryAxis, QBarSet, QChart, QHorizontalBarSeries, QChartView, QValueAxis, ) class ChartView(QChartView): _x = None @property def x(self): return self._x @x.setter def x(self, x): self._x = x self.update() def drawForeground(self, painter, rect): if self.x is None: return painter.save() pen = QPen(QColor("indigo")) pen.setWidth(3) painter.setPen(pen) p = self.chart().mapToPosition(QPointF(self.x, 0)) r = self.chart().plotArea() p1 = QPointF(p.x(), r.top()) p2 = QPointF(p.x(), r.bottom()) painter.drawLine(p1, p2) painter.restore() def main(): app = QApplication(sys.argv) set0 = QBarSet("Jane") set1 = QBarSet("John") set2 = QBarSet("Axel") set3 = QBarSet("Mary") set4 = QBarSet("Samantha") set0 << 1 << 2 << 3 << 4 << 5 << 6 set1 << 5 << 0 << 0 << 4 << 0 << 7 set2 << 3 << 5 << 8 << 13 << 8 << 5 set3 << 5 << 6 << 7 << 3 << 4 << 5 set4 << 9 << 7 << 5 << 3 << 1 << 2 series = QHorizontalBarSeries() series.append(set0) series.append(set1) series.append(set2) series.append(set3) series.append(set4) chart = QChart() chart.addSeries(series) chart.setTitle("Simple horizontal barchart example") chart.setAnimationOptions(QChart.SeriesAnimations) categories = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"] axisY = QBarCategoryAxis() axisY.append(categories) chart.addAxis(axisY, Qt.AlignLeft) series.attachAxis(axisY) axisX = QValueAxis() chart.addAxis(axisX, Qt.AlignBottom) series.attachAxis(axisX) axisX.applyNiceNumbers() chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartView = ChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) chartView.x = 11.5 window = QMainWindow() window.setCentralWidget(chartView) window.resize(420, 300) window.show() app.exec() if __name__ == "__main__": main()
unknown
d18955
test
Happened to me after I updated one of the packages in node_modules. Probably integrity/checksum-related issue. The cure was to flush node_modules and run $ npm install again.
unknown
d18957
test
You don't really need to do that: .NET BCL already has everything you need. A: Take a look at App.Config and the ConfigurationManager class. A: If you expand the Properties folder in the SolutionExplorer you should find a Settings.Settings item. Double clicking on this will open the settings editor. This enables you to declare and provide initial values for settings that can either be scoped to the application or the current user. Since the values are persisted in Isolated storage you do not need to worry about what privileges the user is executing under. For a wee example: I created a new string setting with the name Drink and a TextBox named drinkTextBox. The code to assign the current value to the text box is: drinkTextBox.Text = Properties.Settings.Default.Drink; and to update the value persisted: Properties.Settings.Default.Drink = drinkTextBox.Text; Properties.Settings.Default.Save(); A: Depending on how flexible you want it to be, you can use the build in Settings designer (go to Project Properties > Settings) and you can add settings there. These are strongly typed and accessible through code. It has built in features like Save, Load and Reload A: We'll often create a sealed class that has a number of properties that wrap calls to the the System.Configuration.ConfigurationManager class. This allows us to use the standard configuration managagement capabilities offered by the class and the app/web.config file but make the data very easy to access by other classes. For example we might create a property to expose the connection string to a database as public static string NorthwindConnectionString { get{return ConfigurationManager.ConnectionStrings["Northwind"].ConnectionString } While it creates a wrapper around one line of code, which we usually try to avoid, it does make certain confiuration properties accessible via intellisense and provides some insullation around changes to the location of underlying configuration data. If we wanted to move the connection string to the registry, we could do so without major impact to the application. We find this most helpful when we have larger teams or when we need to hand off code from one team to another. It keeps people from needing to remember what the various settings were named in the config files and even where configuration information is stored (config file, database, registry, ini file, etc.) A: For noddy apps I use appSettings. For enterprise apps I usually create some custom config sections. CodeProject has some excellent articles on this. For your scenario of key/value pairs I'd probably use something like this. A: Building a dictionary in the standard settings Using the standard Settings, it isn't possible to store dictionary style settings. To emulate the System.Collections.Specialized.StringDictionary, what I've done in the past is used two of the System.Collections.Specialized.StringCollection typed settings (this is one of your options for the setting type). I created one called Keys, and another called values. In a class that needs these settings I've created a static constructor and looped through the two StringCollections and built the StringDictionary into a public static property. The dictionary is then available when needed. public static StringDictionary NamedValues = new StringDictionary(); public static ClassName() // static construtor { StringCollection keys = Properties.Settings.Default.Keys; StringCollection vals = Properties.Settings.Default.Values; for(int i = 0; i < keys.Count(); i++) { NamedValues.Add(keys[i], vals[i]); } }
unknown
d18959
test
It's probably because the rec.dedication = tot_late / 8 is outside the for rec in self loop. Which means the value is only set on the last record it computes. Also, the pass value seems unnecessary here.
unknown
d18961
test
RxJS has a timeout operator. Probably you can use that to increase the timeout getBookingInfo(dateType: string) { ... return this.ServiceHandler.getTxnInfo([], params).pipe( timeout(10*60*1000) // 10 minutes ); } And then you can update the calling function to getBookingDetails() { this.getBookingInfo('BOOKING').subscribe( bookings => { console.log(bookings); }); } A: You can use the timeout operator of rxjs, including it in a pipe with timeout: import { timeout, catchError } from 'rxjs/operators'; import { of } from 'rxjs/observable/of'; ... getTxnInfo(headers: any[], params: any[]) { this.apiService.get(environment.rm_url + 'rm-analytics-api/dashboard/txn-info', headers, params) .pipe( timeout(20000), catchError(e => { return of(null); }) ); } Using it: this.ServiceHandler.getTxnInfo([], params).subscribe( txnInfos => { console.log(txnInfos ); });
unknown
d18963
test
IIUC: you need value_counts()+reset_index() out=df.value_counts(subset=['c2','c1']).reset_index(name='count') output of out: c2 c1 count 0 p1 q1 2 1 p1 q2 1 2 p1 q3 1 3 p2 q1 1 4 p2 q2 1 If you need piechart(decorate it according to your need): df.value_counts(subset=['c2','c1']).plot(kind='pie',autopct='%.2f%%') output:
unknown
d18965
test
To solve this problem: * *We can use the method overloading to capture all data *Each method will use a different data type but will have the same name - data() *The number of null values of each array should be found out. *the variable n will determine which is the largest size among all the 3 integers. *n will be the test expression limit when printing the table public class overLoadEg { //array that will store integers static int[] intArray = new int[10]; //array that will store doubles static double[] doubleArray = new double[10]; //array that will store strings static String[] stringArray = new String[10]; static int i = 0, j = 0, k = 0, m, n; public static void main(String[] args) { //input values data(23); data(23.4554); data("Hello"); data("world"); data("help"); data(2355); data(52.56); data("val"); data("kkj"); data(34); data(3); data(2); data(4); data(5); data(6); data(7); data(8); display(); } public static void data(int val){ //add int value to int array intArray[i] = val; System.out.println("Int " + intArray[i] + " added to IntArray"); i++; } public static void data(Double val){ //add double value to double array doubleArray[j] = val; System.out.println("Double " + doubleArray[j] + " added to doubleArray"); j++; } public static void data(String val){ //add string value to stringarray stringArray[k] = val; System.out.println("String " + stringArray[k] + " added to stringArray"); k++; } public static void max(){ //To get the maximum number of values in each array int x, y, z; x = y = z = 0; //counting all the null values in each array and storing in x, y and z for(m=0;m<10;m++){ if(intArray[m] == 0){ ++x; } if(doubleArray[m] == 0){ ++y; } if(stringArray[m] == null){ ++z; } } //subtracting the null/0 count from the array size //this gives the active number of values in each array x = 10 - x; y = 10 - y; z = 10 - z; //comparing all 3 arrays and check which has the max number of values //the max numbe is stored in n if(x > y){ if(x > z){ n = x; } else{ n = z; } } else{ if(y > z){ n = y; } else{ n = z; } } } public static void display(){ //printing the arrays in table //All the null/0 values are excluded System.out.println("\n\nInt\tDouble\t\tString"); max(); for(m = 0; m < n; m++){ System.out.println(intArray[m] + "\t" + doubleArray[m] + "\t\t" + stringArray[m]); } System.out.println("Count : " + m); } }
unknown
d18967
test
This extra space is because of margin-right applied to links in Bootstrap's default styles. You can fix this by overriding that styles or remove width and use left: 0 and right: 2px to stretch line. jQuery(function () { jQuery('#myTab a:last').tab('show') }) @import url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css'); li.active:after { position: absolute; padding: 1px; top: -1px; content: ''; background: #000; height: 4px; right: 2px; left: 0; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <ul class="nav nav-tabs" id="myTab"> <li class="active"><a data-target="#home" data-toggle="tab">Home</a></li> <li><a data-target="#profile" data-toggle="tab">Profile</a></li> <li><a data-target="#messages" data-toggle="tab">Messages</a></li> <li><a data-target="#settings" data-toggle="tab">Settings</a></li> </ul> <div class="tab-content"> <div class="tab-pane active" id="home">Home</div> <div class="tab-pane" id="profile">Profile</div> <div class="tab-pane" id="messages">Message</div> <div class="tab-pane" id="settings">Settings</div> </div>
unknown
d18969
test
Tell the static part of the graph that the shape is unknown from the start as well. a = tf.Variable([3,3,3], validate_shape=False) Now, to get the shape, you cannot know statically, so you have to ask the session, which makes perfect sense: print(sess.run(tf.shape(a)))
unknown
d18971
test
It doesn't look like the coremltools Keras converter lets you specify which inputs are optional. However, the proto files that contain the MLModel definition say that a Model object has a ModelDescription, which has an array of FeatureDescription object for the inputs, which has a FeatureType object, which has an isOptional boolean. So something like this should work: mlmodel = keras.convert(...) spec = mlmodel._spec spec.description.input[1].type.isOptional = True mlmodel.save(...) I didn't actually try this, so the exact syntax may be different, but this is the general idea.
unknown
d18973
test
UserController is session-scoped, but the producer is not. I.e. the producer has @Dependent scope, so the User bean gets injected once when the servlet is initialized. Try adding @SessionScoped to your producer method.
unknown
d18975
test
You could change the \w to \B to verify that there is not a word boundary. console.log('entities '.replace(/\Bies\b/g, 'y')); A: Just capture the character before the "ies": 'entities '.replace(/(\w)(ies)(?:[\W|$|_])+/g, '$1y'); Now your question asked about using a function; you can do that too: 'entities '.replace(/(\w)(ies)(?:[\W|$|_])+/g, function(_, before, repl) { return before + "y"; }); I don't know what you want to do with the subsequent stuff after "ies"; you can either capture it and glue it back into the replacement, or else use positive look-ahead. Portions of the input text matched by look-ahead are not part of the match involved with the replacement operation. In other words, the look-ahead does succeed or fail based on the pattern, but the characters matched are not made part of the "to be replaced" grouping.
unknown
d18977
test
I read the article that the OP code is originally from and I believe it's overkill. What should be done to avoid so much work is to setup the elements angles initially so you know what to start from or reset the elements to 0. Example A features a <form> that allows the user to rotate an element by adding positive and/or negative numbers (min -360, max 360). Example B features a function that operates the same as the event handler (spin(e)) in Example A. Details are commented in both examples Example A <form> as User Interface // Bind <form> to the submit event document.forms.spin.onsubmit = spin; function spin(e) { // Stop normal behavior when submit is triggered e.preventDefault(); // Reference all form controls const IO = this.elements; // Reference <output> const comp = IO.compass; // Reference <input> const turn = IO.turn; // Get <input> value and convert it into a number let deg = +turn.value; // Add comp value with turn value and assign to comp value comp.value = +comp.value +(deg); // If comp value is ever over 360, reset it if (+comp.value > 360) { comp.value = +comp.value - 360; } // .cssText is like .textContent for the style property comp.style.cssText = `transform: rotate(${comp.value}deg)`; } fieldset { display: flex; justify-content: center; align-items: center; } #turn { width: 3rem; text-align: center; } #compass { position: relative; display: flex; justify-content: center; align-items: center; width: 100px; height: 100px; border-radius: 50%; background: rgba(0, 0, 255, 0.3); } #compass::before { content: '➤'; position: absolute; z-index: 1; transform: rotate(-90deg) translate(55%, -5%); transform-origin: center center; font-size: 3rem; } <form id='spin'> <fieldset> <input id='turn' type='number' min='-360' max='360' step='any'><input id='add' type='submit' value='Add'> </fieldset> <fieldset> <output id='compass' value='0'></output> </fieldset> </form> Example B No <form>, Only a Function // Declare variable to track angle let degree; /** * @desc - Rotates a given element by a given number of * degrees. * @param {object<DOM>} node - The element to rotate * @param {number} deg - The number of degrees to rotate * @param {boolean} init - If true the element's rotate value * will be 0 and degree = 0 @default is false */ function turn(node, deg, init = false) { // If true reset node rotate and degree to 0 if (init) { node.style.cssText = `transform: rotate(0deg)`; degree = 0; } /* Simple arithmatic Reset degrees when more than 360 */ degree = degree + deg; if (degree > 360) { degree = degree - 360; } // .cssText is like .textContent for the style property node.style.cssText = `transform: rotate(${degree}deg)`; console.log(node.id + ': ' + degree); } const c = document.getElementById('compass'); turn(c, 320, true); fieldset { display: flex; justify-content: center; align-items: center; } #compass { position: relative; display: flex; justify-content: center; align-items: center; width: 100px; height: 100px; border-radius: 50%; background: rgba(0, 0, 255, 0.3); } #compass::before { content: '➤'; position: absolute; z-index: 1; transform: rotate(-90deg) translate(55%, -5%); transform-origin: center center; font-size: 3rem; } <fieldset> <output id='compass' value='0'></output> </fieldset>
unknown
d18983
test
If you are using Kubernetes, here are the high level steps: * *Create your micro-service Deployments/Workloads using your docker images *Create Services pointing to these deployments *Create Ingress using Path Based rules pointing to the services Here is sample manifest/yaml files: (change docker images, ports etc as needed) apiVersion: v1 kind: Service metadata: name: svc-gateway spec: ports: - port: 80 selector: app: gateway --- apiVersion: v1 kind: Service metadata: name: svc-messaging spec: ports: - port: 80 selector: app: messaging --- apiVersion: extensions/v1beta1 kind: Deployment metadata: name: deployment-gateway spec: replicas: 1 template: metadata: labels: app: gateway spec: containers: - name: gateway image: gateway/image:v1.0 ports: - containerPort: 80 --- apiVersion: extensions/v1beta1 kind: Deployment metadata: name: deployment-messaging spec: replicas: 1 template: metadata: labels: app: messaging spec: containers: - name: messaging image: messaging/image:v1.0 ports: - containerPort: 80 --- apiVersion: extensions/v1beta1 kind: Ingress metadata: name: ingress-for-chat-application spec: rules: - host: chat.example.com http: paths: - backend: serviceName: svc-gateway servicePort: 80 path: /api/v1/users - backend: serviceName: svc-messaging servicePort: 80 path: /api/v1/messages If you have other containers running in the same namespace and would like to communicate with these services you can directly use their service names. For example: curl http://svc-messaging or curl http://svc-gateway You don't need to run your own service discovery, that's taken care by Kubernetes! Some visuals: Step 1: Step 2: Step 3:
unknown
d18987
test
Did you check this: File Docs as per this doc you can do this as follow: $request->file('photo')->move($destinationPath, $fileName); where $fileName is an optional parameter that renames the file. so you can use this like: $fileName = str_random(30); // any random string then pass this as above.
unknown
d18991
test
The documentation for NEST 2.18 and 2.20 is misleading in this respect. The binary option has no effect (it sets the ios::binary flag when opening the file, but that has no significant consequences). If you want to write spikes in binary format, you need to switch to NEST 3.0 and use the sionlib recording backend by setting the recorder's record_to property: neurons = nest.Create('iaf_psc_alpha', 5) sr = nest.Create('spike_recorder') nest.Connect(neurons, sr) sr.SetStatus({'record_to': 'sionlib'}) A guide for recording from simulations is available in the docs.
unknown
d18995
test
Well...here is how you would do it. It looks like the data for some of the things in wmi needs to be converted to be readable. $Monitors = Get-WmiObject -Namespace root\wmi -Class wmiMonitorID $obj = Foreach ($Monitor in $Monitors) { [pscustomobject] @{ 'MonitorMFG' = [char[]]$Monitor.ManufacturerName -join '' 'MonitorSerial' = [char[]]$monitor.SerialNumberID -join '' 'MonitorMFGDate' = $Monitor.YearOfManufacture } } $obj $obj | export-csv Edit...alternative that more closely matches the formatting you are wanting...I think the above is better though personally. $Monitors = Get-WmiObject -Namespace root\wmi -Class wmiMonitorID $i = 1 $obj = new-object -type psobject Foreach ($Monitor in $Monitors) { $obj | add-member -Name ("Monitor$i" +"MFG") -Value ([char[]]$Monitor.ManufacturerName -join '') -MemberType NoteProperty -Force $obj | add-member -Name ("Monitor$i" + "Serial") -Value ([char[]]$monitor.SerialNumberID -join '') -MemberType NoteProperty -Force $obj | add-member -Name ("Monitor$i" + "MFGDate") -Value ($Monitor.YearOfManufacture) -MemberType NoteProperty -Force $i++ } $obj $obj | export-csv
unknown
d18997
test
Try the steps below to see if that could help: 1) From Outlook, click File from the top left > Options > Advanced 2) Scroll down until you see "International Options" 3) Check "Automatically Select Encoding for Outgoing..." 4) Select UTF-8 encoding from the drop down menu. A: Try changing (or setting) the encoding in the html template. If it doesn't help, convert characters to html entities - that works in all email clients.
unknown
d18999
test
Here are some overviews on the topic: * *https://sweetcode.io/using-html5-server-sent-events/ *https://juxt.pro/blog/posts/course-notes.html *https://www.lucagrulla.com/posts/server-sent-events-with-ring-and-compojure/ *Server push of data from Clojure to ClojureScript *https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events Here is a highly voted comparison on StackOverflow between Server Sent Events and WebSockets (my favorite): * *WebSockets vs. Server-Sent events/EventSource And here is a nice comparison from IBM (2017): * *https://www.ibm.com/developerworks/library/wa-http-server-push-with-websocket-sse/index.html A: immutant.web has support for SSE built in: http://immutant.org/documentation/current/apidoc/guide-web.html#h3155 There is also this middleware for other web servers: https://github.com/kumarshantanu/ring-sse-middleware, although I have not tried it myself.
unknown
d19003
test
You first file is overwritten by the second call to the function
unknown
d19007
test
It does not appear so. From here (emphasis mine): For 35mm digital capture, we strongly recommend use of a professional-quality digital SLR using RAW or uncompressed TIFF format. RAW or uncompressed TIFF images will tend to be very large, which could make uploading them via an API problematic. Instead, contributors would use the upload portal to supply content to Getty images. Further, your images must go through a submission process, which would suggest the API could not be used. Getty Images do have a Flickr collection that anyone can submit to, though once again there is submission process.
unknown
d19009
test
Why not to join two tables, master one with id,type,name fields and nested with id,master_id,lang,value. For the given example that will be looking like: ID TYPE NAME 1 text question ID MASTER_ID LANG TRANSLATION 1 1 en question 2 1 nl vraag The translation set for one language is given by SQL query: SELECT * FROM `nested` WHERE `lang` = 'nl' -- vraag -- ..... The translation for the given term (e.g. question, having id=1): SELECT * FROM `nested` WHERE `master_id` = 1 AND `lang` = 'nl' -- vraag A: The downside of the second idea is that for every new language you want to add you have to change your database structure (following code changes to reflect that structure change) whereas the first only needs new rows (which keeps the same structure). another plus for the first idea is that you really only need the space/memory for translations you add to the database. in the second approach you could have lots of empty fields in case you won't translate all texts. a way to do it could be (an addition to the answer above from @mudasobwa): Master Table: | id | type | master_name | |----+------+-------------| |853 | text | question | |854 | text | answer | Language Table: | id | language_name | |----+---------------| | 1 | english | | 2 | german | Translation Table: | id | master_id | language_id | translation | |----+-----------+-------------+--------------------| | 1 | 853 | 1 | question | | 1 | 854 | 2 | Frage | | 2 | 853 | 1 | answer | | 2 | 854 | 2 | Antwort | So if you have another language, add it to the language table and add the translations for your master texts for that language. Adding indexes to the ids will help speeding up queries for the texts. A: Second way is much better: * *Keeps less place in Database. *Loads faster. *Easy to edit.
unknown
d19013
test
As it stands, there isn't much to choose between them. However, the @classmethod has one major plus point; it is available to subclasses of MyClass. This is far more Pythonic than having separate functions for each type of object you might instantiate in a list. A: I would argue that the first method would be better (list comprehension) since you will always be initializing the data from a list. This makes things explicit.
unknown
d19015
test
Then don't put the scroll on the main window. Put ScrollViewer only on the content (rows) that you want to scroll. Careful not to use an auto for the height of the rows with the ScrollViewer or the container will grow to support all the content and the Scroll does not come into play. A: One way: <Window x:Class="Sample.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Grid> <ListBox> <!--Hardcoded listbox items just to force the scrollbar for demonstration purposes --> <ListBoxItem>Item1</ListBoxItem> <ListBoxItem>Item2</ListBoxItem> <ListBoxItem>Item3</ListBoxItem> <ListBoxItem>Item4</ListBoxItem> <ListBoxItem>Item5</ListBoxItem> <ListBoxItem>Item6</ListBoxItem> <ListBoxItem>Item7</ListBoxItem> <ListBoxItem>Item8</ListBoxItem> <ListBoxItem>Item9</ListBoxItem> <ListBoxItem>Item10</ListBoxItem> <ListBoxItem>Item11</ListBoxItem> <ListBoxItem>Item12</ListBoxItem> <ListBoxItem>Item14</ListBoxItem> <ListBoxItem>Item15</ListBoxItem> <ListBoxItem>Item16</ListBoxItem> <ListBoxItem>Item17</ListBoxItem> <ListBoxItem>Item18</ListBoxItem> <ListBoxItem>Item19</ListBoxItem> <ListBoxItem>Item20</ListBoxItem> <ListBoxItem>Item21</ListBoxItem> <ListBoxItem>Item22</ListBoxItem> </ListBox> <Grid Panel.ZIndex="5" VerticalAlignment="Bottom" Background="DarkGray"> <StackPanel> <TextBox HorizontalAlignment="Left" VerticalAlignment="Center">Text box 1</TextBox> <TextBox HorizontalAlignment="Left" VerticalAlignment="Center">Text box 2</TextBox> <TextBox HorizontalAlignment="Left" VerticalAlignment="Center">Text box 3</TextBox> </StackPanel> </Grid> </Grid>
unknown
d19017
test
The code is passing the return value of the method call, not the method itself. Pass a callback function using like following: self.ins9 = Tk.Button(self.numbuts, text="9", width=3, command=lambda: self.fins(9)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
unknown
d19019
test
What you actually want to do here is get the text inside the div class but not the text in the nested tags within it. You can use soup.find with option text = True and recursive = False Creating the data from bs4 import BeautifulSoup html_doc = '''<span class="job-search-key-1hbqxax elwijj240" data-test="detailsalary"> ₹362,870 - ₹955,252 <span class="job-search-key- elwijj242">(Glassdoor Est.)</span> <span class="SVGInline greyInfoIcon" data-test="salaryIcon"> <svg class="SVGInline-svg greyInforcon-svg" height="16" viewbox="0 @ 16 16" width="16" xmlns="http://www.w3.org/2000/svg"> <g fill="none" fill-rule="evenodd" id="prefix__info-16-px" stroke="none" stroke-width="1"> <path d="M8 14A6 6 @ 118 2a6 6 @ 010 12zme- 1A5 5 @ 108 3a5 5 @ 880 18zm-.6-5.60.6.6 8 111.2 8v11a.6.6 @ 01-1.2 8v7.42MS 5.62.6.6 110-1.2.6.6 @ 810 1.2z" fill="#505863" id="prefix_a"></path> </svg> </span> <div class="d-none"></div> </span>''' soup = BeautifulSoup(html_doc, 'html.parser') Generating the output soup.find(class_='job-search-key-1hbqxax elwijj240').find(text=True, recursive=False).strip() Output This gives us '₹362,870 - ₹955,252'
unknown
d19021
test
You can achieve that by: window?.toolbar?.showsBaselineSeparator = false
unknown
d19023
test
A few issues ... * *You should have .section .text before .global _start so that _start ends up in the .text section *Add -g to get debug infomation Unfortunately, adding -g to a .c compilation would be fine. But, it doesn't work too well for a .s file Here's a simple C program, similar to yours: int value1; short value2; unsigned char value3; We can compile this with -S to get a .s file. We can do this with and without -g. Without -g the .s file is 7 lines. Adding -g increases this to 150 lines. The debug information has to be added with special asm directives (e.g. .loc and .section .debug_info,"",@progbits). Then, gdb has enough information to allow p (or x) to work. To get p to work without debug information, we have to cast the values to the correct type. For example, in your program: p (int) value1 p (short) value2 p (char) value3 Here is the .s output for the sample .c file without -g: .file "short.c" .text .comm value1,4,4 .comm value2,2,2 .comm value3,1,1 .ident "GCC: (GNU) 8.3.1 20190223 (Red Hat 8.3.1-2)" .section .note.GNU-stack,"",@progbits Here is the .s output with -g: .file "short.c" .text .Ltext0: .comm value1,4,4 .comm value2,2,2 .comm value3,1,1 .Letext0: .file 1 "short.c" .section .debug_info,"",@progbits .Ldebug_info0: .long 0x71 .value 0x4 .long .Ldebug_abbrev0 .byte 0x8 .uleb128 0x1 .long .LASF5 .byte 0xc .long .LASF6 .long .LASF7 .long .Ldebug_line0 .uleb128 0x2 .long .LASF0 .byte 0x1 .byte 0x1 .byte 0x5 .long 0x33 .uleb128 0x9 .byte 0x3 .quad value1 .uleb128 0x3 .byte 0x4 .byte 0x5 .string "int" .uleb128 0x2 .long .LASF1 .byte 0x1 .byte 0x2 .byte 0x7 .long 0x50 .uleb128 0x9 .byte 0x3 .quad value2 .uleb128 0x4 .byte 0x2 .byte 0x5 .long .LASF2 .uleb128 0x2 .long .LASF3 .byte 0x1 .byte 0x3 .byte 0xf .long 0x6d .uleb128 0x9 .byte 0x3 .quad value3 .uleb128 0x4 .byte 0x1 .byte 0x8 .long .LASF4 .byte 0 .section .debug_abbrev,"",@progbits .Ldebug_abbrev0: .uleb128 0x1 .uleb128 0x11 .byte 0x1 .uleb128 0x25 .uleb128 0xe .uleb128 0x13 .uleb128 0xb .uleb128 0x3 .uleb128 0xe .uleb128 0x1b .uleb128 0xe .uleb128 0x10 .uleb128 0x17 .byte 0 .byte 0 .uleb128 0x2 .uleb128 0x34 .byte 0 .uleb128 0x3 .uleb128 0xe .uleb128 0x3a .uleb128 0xb .uleb128 0x3b .uleb128 0xb .uleb128 0x39 .uleb128 0xb .uleb128 0x49 .uleb128 0x13 .uleb128 0x3f .uleb128 0x19 .uleb128 0x2 .uleb128 0x18 .byte 0 .byte 0 .uleb128 0x3 .uleb128 0x24 .byte 0 .uleb128 0xb .uleb128 0xb .uleb128 0x3e .uleb128 0xb .uleb128 0x3 .uleb128 0x8 .byte 0 .byte 0 .uleb128 0x4 .uleb128 0x24 .byte 0 .uleb128 0xb .uleb128 0xb .uleb128 0x3e .uleb128 0xb .uleb128 0x3 .uleb128 0xe .byte 0 .byte 0 .byte 0 .section .debug_aranges,"",@progbits .long 0x1c .value 0x2 .long .Ldebug_info0 .byte 0x8 .byte 0 .value 0 .value 0 .quad 0 .quad 0 .section .debug_line,"",@progbits .Ldebug_line0: .section .debug_str,"MS",@progbits,1 .LASF1: .string "value2" .LASF5: .string "GNU C17 8.3.1 20190223 (Red Hat 8.3.1-2) -mtune=generic -march=x86-64 -g" .LASF0: .string "value1" .LASF6: .string "short.c" .LASF2: .string "short int" .LASF3: .string "value3" .LASF4: .string "unsigned char" .LASF7: .string "/tmp/asm" .ident "GCC: (GNU) 8.3.1 20190223 (Red Hat 8.3.1-2)" .section .note.GNU-stack,"",@progbits
unknown
d19029
test
you can use the unicode character ‘U+221E’ to represent the large infinity symbol. To use this unicode in your plot, you can use the following code: import matplotlib.pyplot as plt fig = plt.figure(figsize=(10,10)) plt.rcParams.update({'font.size':16}) plt.title(u'U\u221E') plt.show()
unknown
d19031
test
Form onSubmit handler To answer your immediate question, what's happening is input type submit in Angular calls the onSubmit method of the form (instead of submitting the form like in plain HTML). And because you don't have a handler for onSubmit in your class, nothing is happening. For a quick test, follow this link to create a simple onSubmit handler method to test that your submit button works. Here's a Stackblitz example which logs to console when you click the submit button: https://stackblitz.com/edit/angular-uy481f File upload To make file upload work, you would need to make a few things. This touches the component class, creating a new service and injecting it, and updating your form to bind it to the class. * *Create a proper Angular form. Here's an example. *Create a method that will handle the onSubmit() of the form. *Create a service that will handle Http calls to upload files. *Inject the service into your class, and call the file upload method of that class. As you can see, there's a lot involved in making this work unlike having a simple post form in the template. As such, it will be too much for a single answer. But hopefully, the initial paragraph answered your question and the rest of the answer pointed you in the right direction.
unknown
d19033
test
yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/TheWindowsClub?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/TheWindowsClub?a=tjWEu-9hLFk:Jv9oVdSsx2A:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/TheWindowsClub?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/TheWindowsClub?a=tjWEu-9hLFk:Jv9oVdSsx2A:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/TheWindowsClub?i=tjWEu-9hLFk:Jv9oVdSsx2A:gIN9vFwOqvQ" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/TheWindowsClub?a=tjWEu-9hLFk:Jv9oVdSsx2A:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/TheWindowsClub?d=I9og5sOYxJI" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/TheWindowsClub?a=tjWEu-9hLFk:Jv9oVdSsx2A:cGdyc7Q-1BI"><img src="http://feeds.feedburner.com/~ff/TheWindowsClub?d=cGdyc7Q-1BI" border="0"></img></a></div><img src="http://feeds.feedburner.com/~r/TheWindowsClub/~4/tjWEu-9hLFk" height="1" width="1" alt=""/> Unlike last time I can't use quotation marks or other such character. I have to delete the whole line. One thing I thought about was to do something like this: $html = preg_replace('/<a href=".*?(alt=""/>)/', '', $html); I thought that using the above code would find the last portion in this segment and replace everything inside but it replaces nothing. Please suggest what should I do? After running above line of code the output should be nothing. It should remove all this code block. A: <a\s+href.*(alt="[^"]*")?> or without quotation mark : <a\s+href.*(alt="[^"]*"){0,1}> We match everything that starts by <a, is followed by at least one space, then by any character until the character >, before which you may have zero or one iteration of the string alt="" containing anything but a ".
unknown
d19035
test
Replace container.internalList.Add(item); by Dispatcher.BeginInvoke(new Action(() => container.internalList.Add(item))); This way the Add is executed on the Dispatcher thread. A: You can just get your data from a background thread as a List and then cast this list to an ObservableCollection as follows List<SomeViewModel> someViewModelList = await GetYourDataAsListAsync(); ObservableCollection<SomeViewModel> Resources = new TypedListObservableCollection<SomeViewModel>(someViewModelList); I hope this helps. A: Make sure that you set the properties of UI objects on the UI thread: Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate() { MyDataGrid.ItemsSource = container.internalList; }); This will add the code within the curly braces onto the work items queue of the UI thread Dispatcher. A: The problem is not in the Collection on your class but in the Control that is binding to this collection from UI Thread. There is something new in WPF 4.5: http://www.jonathanantoine.com/2011/09/24/wpf-4-5-part-7-accessing-collections-on-non-ui-threads/ //Creates the lock object somewhere private static object _lock = new object(); //Enable the cross acces to this collection elsewhere BindingOperations.EnableCollectionSynchronization(_persons, _lock); MSDN: http://msdn.microsoft.com/en-us/library/hh198845(v=vs.110).aspx
unknown
d19039
test
It depends on what you want to do with birth.month later. If you have no intention of changing it, then the first is better (quicker, no memory cleanup requirement required, and each Date_t object shares the same data). But if that is the case, I would change the definition of month to const char *. In fact, any attempt to write to *birth.month will cause undefined behaviour. The second approach will cause a memory leak unless you remember to free(birth.month) before birth goes out of scope. A: You're correct, the second variant is the "good" one. Here's the difference: With 1, birth->month ends up pointing to the string literal "Nov". It is an error to try to modify the contents of birth->month in this case, and so birth->month should really be a const char* (many modern compilers will warn about the assignment for this reason). With 2, birth->month ends up pointing to an allocated block of memory whose contents are "Nov". You are then free to modify the contents of birth->month, and the type char* is accurate. The caveat is that you are also now required to free(birth->month) in order to release this memory when you are done with it. The reason that 2 is the correct way to do it in general, even though 1 seems simpler in this case, is that 1 in general is misleading. In C, there is no string type (just sequences of characters), and so there is no assignment operation defined on strings. For two char*s, s1 and s2, s1 = s2 does not change the string value pointed to by s1 to be the same as s2, it makes s1 point at exactly the same string as s2. This means that any change to s1 will affect the contents of s2, and vice-versa. Also, you now need to be careful when deallocating that string, since free(s1); free(s2); will double-free and cause an error. That said, if in your program birth->month will only ever be one of several constant strings ("Jan", "Feb", etc.) variant 1 is acceptable, however you should change the type of birth->month to const char* for clarity and correctness. A: Neither is correct. Everyone's missing the fact that this structure is inherently broken. Month should be an integer ranging from 1 to 12, used as an index into a static const string array when you need to print the month as a string. A: I suggest either: const char* month; ... birth->month = "Nov"; or: char month[4]; ... strcpy(birth->month, "Nov"); avoiding the memory allocation altogether. A: With option 1 you never allocate memory to store "Nov", which is okay because it's a static string. A fixed amount of memory was allocated for it automatically. This will be fine so long as it's a string that appears literally in the source and you never try to modify it. If you wanted to read a value in from the user, or from a file, then you'd need to allocate first. A: In the first case your cannot do something like birth->month[i]= 'c'. In other words you cannot modify the string literal "Mov" pointed to by birth->month because it is stored in the read only section of memory. In the second case you can modify the contents of p->month because "Mov" resides on the heap. Also you need to deallocate the allocated memory using free in this case. A: Seperate to your question; why is struct Date typedefed? it has a type already - "struct Date". You can use an incomplete type if you want to hide the structure decleration. In my experience, people seem to typedef because they think they should - without actually thinking about the effect of doing so. A: For this example, it doesn't matter too much. If you have a lot of Date_t variables (in, say, an in-memory database), the first methow will lead to less memory usage over-all, with the gotcha that you should not, under any circumstances, change any of the characters in the strings, as all "Nov" strings would be "the same" string (a pointer to the same 4 chars). So, to an extent, both variants are good, but the best one would depend on expected usage pattern(s).
unknown
d19047
test
As an alternative to using the :substitute command (the usage of which is already covered in @Peter’s answer), I can suggest automating the editing commands for performing the replacement by means of a self-referring macro. A straightforward way of overwriting occurrences of the search pattern with a certain character by hand would the following sequence of Normal-mode commands. * *Search for the start of the next occurrence. /\(hello\)\+ *Select matching text till the end. v//e *Replace selected text. r- *Repeat from step 1. Thus, to automate this routine, one can run the command :let[@/,@s]=['\(hello\)\+',"//\rv//e\rr-@s"] and execute the contents of that s register starting from the beginning of the buffer (or anther appropriate location) by gg@s A: %s/\v(hello)*/\=repeat('-',strlen(submatch(0)))/g
unknown
d19051
test
You can call the procedure from a function just as you'd call any other PL/SQL block CREATE OR REPLACE FUNCTION my_function RETURN integer IS l_parameter VARCHAR2(100) := 'foo'; BEGIN insert_into_table_a( l_parameter ); RETURN 1 END; That being said, it doesn't make sense to call this procedure from a function. Procedures should manipulate data. Functions should return values. If you call a procedure that manipulates data from a function, you can no longer use that function in a SQL statement, which is one of the primary reasons to create a function in the first place. You also make managing security more complicated-- if you use functions and procedures properly, DBAs can give read-only users execute privileges on the functions without worrying that they'll be giving them the ability to manipulate data. The procedure itself seems highly suspicious as well. A column named address_id in the address table should be the primary key and the name implies that it is a number. The same applies for the contact_id column in the contact table and the telephone_id column in the telephone table. The fact that you are inserting a string rather than a number and the fact that you are inserting the same value in the three tables implies that neither of these implications are actually true. That's going to be very confusing for whoever has to work with your system in the future.
unknown
d19053
test
Using a robust HTML parser (see http://htmlparsing.com/ for why): use strictures; use Web::Query qw(); my $w = Web::Query->new_from_html(<<'HTML'); <div class="name"><a href="/v/name/idlike123123ksajdfk">name</a></div> <div class="name"><a href="/v/name/idlike123123ksajdfk">name</a></div> <div class="name"><a href="/v/name/idlike123123ksajdfk">name</a></div> <div class="name"><a href="/v/name/idlike123123ksajdfk">name</a></div> <div class="name"><a href="/v/name/idlike123123ksajdfk">name</a></div> HTML my @v_links = $w->find('div.name > a[href^="/v/"]')->attr('href'); A: There are plenty of Perl modules that extract links from HTML. WWW::Mechanize, Mojo::DOM, HTML::LinkExtor, and HTML::SimpleLinkExtor can do it. A: Web scraping with Mojolicious is probably simplest way to do it in Perl nowadays http://mojolicio.us/perldoc/Mojolicious/Guides/Cookbook#Web_scraping A: You should not use regex for parsing HTML, as there are many libraries for such parsing. Daxim's answer is good example. However if you want to use regex anyway and you have your text assigned to $_, then my @list = m{<div class="name"><a href="(/v/.*?)">}g; will get you a list of all findings.
unknown
d19055
test
PNG is a compressed image format, so the IDAT chunk(s) contain a zlib-compressed representation of the RGB pixels. Probably the easiest way for you to access the pixel data is to use a converter such as ImageMagick or GraphicsMagick to decompress the image into the Netpbm "PPM" format. magick image.png image.ppm or gm convert image.png image.ppm Then read the "image.ppm" in the same way you tried to read the PNG. Just skip over the short header, which in the case of your image is P 6 \n 6 6 0 3 3 0 \n 2 5 5 \n where "P6" is the magic number, 660 and 330 are the dimensions, and 255 is the image depth (maximum value for R,G,and B is 255, or 0xff). The remainder of the file is just the R,G,B values you were expecting.
unknown
d19059
test
You can extract a file name from a path using basename like this: basename($imagePath); // output: 123.jpeg or without the extension: basename($imagePath, ".jpeg"); // output: 123 A: <?php $path = "index.php"; //type file path with extension $title = basename($path,".php"); // get only title without extension /remove (,".php") if u want display extension echo $title; ?> A: Try it with two way.. First : base_path unlink(base_url("uploads/".$image_name)); getcwd : Some times absolute path not working. unlink(getcwd()."/uploads/".$image_name);
unknown
d19061
test
You might also try fixing your app so it always saves the same base date with the time (like '01/01/1900' or whatever) and then you do not have to do all these slow and inefficient date stripping operations every time you need to do a query. Or as Joel said, truncate or strip off the date portion before you do the insert or update. A: from d in dates orderby d.TimeOfDay select d; or dates.OrderBy(d => d.TimeOfDay); Note: This will work as long as this is plain LINQ and not LINQ-to-SQL. If you're using LINQ-to-SQL to query your database, you'll need something that will translate to SQL. A: Well, you can't really store a datetime without a date, but you could just store the total seconds as an double (using @florian's method). You'd have to add a second method to convert this back to a date in your object, if you still need a date, such as: public class BusinessObjectWithDate { private string _someOtherDbField = ""; private double _timeInMS = 0; // save this to the database // sort by this? in sql or in code. You don't really need this // property, since TimeWithDate actually saves the _timeInMS field public double TimeInMS { get { return _timeInMS; } } public DateTime TimeWithDate { // sort by this too, if you want get { return (new DateTime(1900,1,1).AddMilliseconds(_timeInMS)); } set { _timeInMS = value.TimeOfDay.TotalMilliseconds; } } } var f = new BusinessObjectWithDate(); MessageBox.Show( f.TimeWithDate.ToString() ); // 1/1/1900 12:00:00 AM f.TimeWithDate = DateTime.Now; MessageBox.Show( f.TimeWithDate.ToString() ); // 1/1/1900 1:14:57 PM You could also just store the real date time, but always overwrite with 1/1/1900 when the value gets set. This would also work in sql public class BusinessObjectWithDate { private DateTime _msStoredInDate; public DateTime TimeWithDate { get { return _msStoredInDate; } set { var ms = value.TimeOfDay.TotalMilliseconds; _msStoredInDate = (new DateTime(1900, 1, 1).AddMilliseconds(ms)); } } } A: Try this in your sql: ORDER BY startTime - CAST(FLOOR(CAST(startTime AS Float)) AS DateTime)
unknown
d19063
test
You should iterate over $datas['0']['costs'] foreach ($datas['0']['costs'] as $key =$value){ echo $value['service'] . ' - ' $value['cost'][0]['value']; }
unknown
d19067
test
The Artist property is not automatically created - you have to create an instance of the artist first: var s = new Song(); s.SongTitle = SongName; s.Artist = new Artist(); s.Artist.ArtistName = artistName;
unknown
d19073
test
I found this: When we want to use transition for display:none to display:block, transition properties do not work. The reason for this is, display:none property is used for removing block and display:block property is used for displaying block. A block cannot be partly displayed. Either it is available or unavailable. That is why the transition property does not work. form this link. I hope this help.
unknown