id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_4600
after error.Why this is happening? class signupform(ModelForm): prmqpass=forms.CharField(widget=forms.PasswordInput()) prmqpass1=forms.CharField(widget=forms.PasswordInput()) class Meta: model=prmqsignup exclude=['prmqactivated'] def clean_prmqpass(self): cd=self.cleaned_data pwd=cd.get("prmqpass") if len(str(pwd))<6: raise ValidationError("Password must be at least of six characters") if not passstrength(pwd): raise ValidationError("For stronger security password must contain at least one uppercase,lowercase,number and special character") return pwd def clean_prmquname(self): cd=self.cleaned_data usrname=cd.get("prmquname") if len(usrname)<5: raise ValidationError("Username too short choose more than four characters") if prmqsignup.objects.exclude(pk=self.instance.pk).filter(prmquname=usrname).exists(): raise ValidationError('Username "%s" is already in use.' % usrname) return usrname def clean(self): cd=self.cleaned_data pwd=cd.get("prmqpass") pwd1=cd.get("prmqpass1") if not pwd==pwd1: raise ValidationError("Passwords don't match.") return cd Why username value(staying in form) and password value(flashing away) after error.See validation logic is same. A: From the documentation: Password input: <input type='password' ...> Takes one optional argument: render_value: Determines whether the widget will have a value filled in when the form is re-displayed after a validation error (default is False). So you need to initialise your inputs like so: prmqpass = forms.CharField(widget=forms.PasswordInput(render_value=True))
doc_4601
The way I'm doing it now is simply generating SQL Text Statements from parameters using string concatenation. I have also played with stored procedures in the main application database (Access), but it was too inflexible. I'm very limited in what I can do. I cannot change Oracle and SQL Server databases. Alone the Access database that is owned by the application. The Oracle and SQL Server databases are quite slow, so I'm not sure if data binding is a good idea, as it would slow down the application (and user experience) each time data is queried. But again: I don't know much about data binding features. A: If the back-end databases are not properly indexed, as you say in your comments, there's little you can do on the front-end to improve performance of the modules that pull data from the back-end, especially if those back-end databases are dynamic, changing frequently. If you are allowed to write stored procedures on the back-end Oracle and SQL Server engines, you can improve performance somewhat by using SP's with parameters, and executing those SP's and passing the parameters via the Command object's Parameters collection. This approach eliminates the overhead of your engines having to parse and compile SQL statements. With respect to MS-Access, that too is a weak link. Access is not a bona-fide back-end engine but uses a shared-file architecture. Where-clause conditions are applied client-side, IIRC. So you end up sucking a lot of data across the wire only to discard it at the client because it does not meet the conditions of the where clause. You could improve performance by replacing Access with SQL Server Express, if your organization will have to use this application long enough into the future that the cost of such a port could be justified. P.S. "Tedium" is subjective. I cannot help you there. Some people find ADO.NET tedious. Some people find Linq tedious. Some people are exhilirated by perl, others despise working with it. A: that being the case ... you can create a layer in which you access all the databases open close the active connection ... you can make your columns and value as Dictionary .... In this class expose methods where all you have to pass is db type , table name , Dictionary having col_name\value,query type (select/update/delete/insert/SP) ... For the Dictionary you could create models/entities/or even xml to the corresponding table, if you don't want them to be hard coded ..... But the Db layer class you will have to spend some time to make it as generic as possible ....
doc_4602
The CSharpCodeCompiler doesn't throw an error if my properties of class do not use the custom Attribute. this is my String: string _string = @" using System; using System.Collections.Generic; namespace Generator { public class ExampleClass { public int id { get; set; } } }" var csc = new CSharpCodeProvider(); var cc = csc.CreateCompiler(); CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add("mscorlib.dll"); cp.ReferencedAssemblies.Add("System.dll"); cp.ReferencedAssemblies.Add("System.ComponentModel.DataAnnotations.dll"); cp.ReferencedAssemblies.Add("System.ComponentModel.dll"); cp.ReferencedAssemblies.Add("System.Runtime.InteropServices.dll"); cp.ReferencedAssemblies.Add(typeof(GUID).Assembly.Location); CompilerResults results = csc.CompileAssemblyFromSource(cp, _string); System.Reflection.Assembly _assembly = results.CompiledAssembly; Type[] _types = _assembly.GetTypes(); Type eType = _assembly.GetType(namespaceAndClass); It is perfectly compiled with the above code. But if I use my custom Attribute it will throw an error. My attribute class: using System; namespace Generator { [AttributeUsage(AttributeTargets.All)] class GUID : Attribute { private string guid { get; set; } public GUID() { this.guid = Guid.NewGuid().ToString(); } public GUID(string value) { this.guid = value; } public string getGuid() { return guid; } } } I need the string to be compiled with my custom Attributes ... [GUID()] public int id { get; set; } When I try this, I get this error: Exception thrown: 'System.IO.FileNotFoundException' in mscorlib.dll
doc_4603
How to decode HTML entities using jQuery? <?php $test = htmlspecialchars( '<img src="https://google.com" ></img>',ENT_HTML401,'utf-8'); ?> <html> <head> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> </head> <body> <div id="asd"></div> <script type='text/javascript'> var decodeEntities = (function() { // this prevents any overhead from creating the object each time var element = document.createElement('textarea'); function decodeHTMLEntities (str) { if(str && typeof str === 'string') { // strip script/html tags str = str.replace(/<img[^>]*>([\S\s]*?)<\/img>/gmi, ''); str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, ''); str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, ''); element.innerHTML = str; str = element.textContent; element.textContent = ''; } return str; } return decodeHTMLEntities; })(); document.getElementById('asd').innerHTML = decodeEntities('<?php echo $asd; ?>'); </script> </body> </html>
doc_4604
The application being used is a C# application running on windows. The question is how to do that and do I need Facebook application ID ? even though I do not need to pull user info ? A: Yes, you have to get an app ID as you will be using facebook's API. The only way to integrate with facebook without app ID is to use social plugins but they don't support posting images nor c#
doc_4605
<?php $sport = get_terms( 'team_category' ); if($sport){ ?><ul><?php foreach($sport as $s){ ?> <li><a href="<?php echo get_term_link( $s->slug, 'team_category' ) ?>"><?php echo $s->name; ?></a></li> <?php } ?></ul><?php } ?> A: Something like this should work. <?php $sport = get_terms( 'team_category' ); ?> <?php if($sport): ?> <ul> <?php foreach($sport as $s): ?> <li class="<?php if($current_team == $s): ?>active<?php endif; ?>"> <a href="<?php echo get_term_link( $s->slug, 'team_category' ) ?>"><?php echo $s->name; ?></a> </li> <?php endforeach; ?> </ul> <?php endif; ?>
doc_4606
i have downgraded the php version on my server to 5.4 but still no luck. this is the part of the script that returns the error string: $test = mysql_query("INSERT INTO users(fname,lname,email,city,gender,password) VALUES('$fname','$lname','$email','$city','$gender','$passwordhash')"); if($test) { echo "Registration successful"; $last_id = mysql_insert_id(); Registration_WelcomeMessage($fname,$email); }else{echo "failure!";} and this is the full code: <?php require_once 'db.php'; require_once 'utilities/cleaner.php'; require_once 'reg_welcome_message.php'; if(isset($_POST)){ $broom = new cleaner(); $fname = $broom->clean($_POST['fname']); $lname = $broom->clean($_POST['lname']); $email = $broom->clean($_POST['email']); $city = $broom->clean($_POST['city']); $gender = $broom->clean($_POST['gender']); $password = $broom->clean($_POST['password']); $cpassword = $broom->clean($_POST['cpassword']); $count = 2; if ($fname && $lname && $email && $city && $gender && $password && $cpassword) { if (preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email)) { if (strlen($password) > 5) { if ($password == $cpassword) { $remail = mysql_query("SELECT email FROM users WHERE email='$email'"); $checkemail = mysql_num_rows($remail); if ($checkemail > 0) { echo "This email is already registered! Please type another email..."; } else { $passwordhash = hash('sha1',$password); $test = mysql_query("INSERT INTO users(fname,lname,email,city,gender,password) VALUES('$fname','$lname','$email','$city','$gender','$passwordhash')"); if($test) { echo "Registration successful"; $last_id = mysql_insert_id(); Registration_WelcomeMessage($fname,$email); }else{echo "failure!";} } } else { echo "Your passwords don't match!"; } } else { echo "Your password is too short! A password between 6 and 15 charachters is required!"; } }else{ echo "Please use a valid email!"; } } else { echo "You have to complete the form!"; } }else{echo "NO data sent";} ?>
doc_4607
A: The ODBC is a driver layer that is used to connect programs to your data sources. The SQL used is primarily determined by your database. For example, if you are in Excel and using an ODBC to connect to an Oracle database, then your sql queries should use Oracle PL/SQL. If you are in Excel using an ODBC to connect to a MySql Database, then MySql commands will work. The ODBC Driver itself can also be a factor. Ideally you should be using an ODBC designed to work with the specific type of Database you are using, and the specific version of it. Oracle 9i will have a different ODBC driver than Oracle 10g. But there are different Drivers from different sources for some database types. For example, Microsoft Makes a 'Microsoft ODBC for Oracle' which works with many oracle databases. But there are also ODBC drivers created by Oracle. Each ODBC will have different settings, but for the most part the SQL queries you write are processed on the Database itself. So determine what type of database (or data source) you are using, then you can determine how to write your sql.
doc_4608
I tried to make it so that logging is configured in only 1 location, but something seems wrong. Here is the code. # main.py import logging import mymodule logger = logging.getLogger(__name__) def setup_logging(): # only cofnigure logger if script is main module # configuring logger in multiple places is bad # only top-level module should configure logger if not len(logger.handlers): logger.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(levelname)s: %(asctime)s %(funcName)s(%(lineno)d) -- %(message)s', datefmt = '%Y-%m-%d %H:%M:%S') ch.setFormatter(formatter) logger.addHandler(ch) if __name__ == '__main__': setup_logging() logger.info('calling mymodule.myfunc()') mymodule.myfunc() and the imported module: # mymodule.py import logging logger = logging.getLogger(__name__) def myfunc(): msg = 'myfunc is being called' logger.info(msg) print('done with myfunc') if __name__ == '__main__': # only cofnigure logger if script is main module # configuring logger in multiple places is bad # only top-level module should configure logger if not len(logger.handlers): logger.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(levelname)s: %(asctime)s %(funcName)s(%(lineno)d) -- %(message)s', datefmt = '%Y-%m-%d %H:%M:%S') ch.setFormatter(formatter) logger.addHandler(ch) logger.info('myfunc was executed directly') myfunc() When I run the code, I see this output: $>python main.py INFO: 2016-07-14 18:13:04 <module>(22) -- calling mymodule.myfunc() done with myfunc But I expect to see this: $>python main.py INFO: 2016-07-14 18:13:04 <module>(22) -- calling mymodule.myfunc() INFO: 2016-07-14 18:15:09 myfunc(8) -- myfunc is being called done with myfunc Anybody have any idea why the second logging.info call doesn't print to screen? thanks in advance! A: Loggers exist in a hierarchy, with a root logger (retrieved with logging.getLogger(), no arguments) at the top. Each logger inherits configuration from its parent, with any configuration on the logger itself overriding the inherited configuration. In this case, you are never configuring the root logger, only the module-specific logger in main.py. As a result, the module-specific logger in mymodule.py is never configured. The simplest fix is probably to use logging.basicConfig in main.py to set options you want shared by all loggers. A: Chepner is correct. I got absorbed into this problem. The problem is simply in your main script 16 log = logging.getLogger() # use this form to initialize the root logger 17 #log = logging.getLogger(__name__) # never use this one If you use line 17, then your imported python modules will not log any messages In you submodule.py import logging logger = logging.getLogger() logger.debug("You will not see this message if you use line 17 in main") Hope this posting can help someone who got stuck on this problem. A: While the logging-package is conceptually arranged in a namespace hierarchy using dots as separators, all loggers implicitly inherit from the root logger (like every class in Python 3 silently inherits from object). Each logger passes log messages on to its parent. In your case, your loggers are incorrectly chained. Try adding print(logger.name) in your both modules and you'll realize, that your instantiation of logger in main.py is equivalent to logger = logging.getLogger('__main__') while in mymodule.py, you effectively produce logger = logging.getLogger('mymodule') The call to log INFO-message from myfunc() passes directly the root logger (as the logger in main.py is not among its ancestors), which has no handler set up (in this case the default message dispatch will be triggered, see here)
doc_4609
If not then is there any other way to implement this feature in ui-grid? A: You are looking for the ui-grid directive: uiGridGrouping
doc_4610
It worked when I just needed to check the type of the object ("Group" or "Organization") However I need to get more specific now and need to find objects by ID and remove / re-add them into the Array. However when I try to adapt the code to check for an Object's id, I either can't find and remove the ID or I end up removing all the Objects from the Array. // re-add Group to networks (This works great) if (isChecked === 'checked') { var group_obj = { 'id': name } networks.push(group_obj); // remove Group from networks (Problem exist in the else if) } else if (isChecked === undefined) { var group_obj = { 'id': name } var removeItem = group_obj; var obj; networks = $.grep(networks, function(o,i) { console.log('removeItem.id = '+removeItem.id); console.log('name = '+name); if (removeItem.id === name) { obj = o; return true; } return false; }, true); } console.log(networks); Console What my networks Array looks like before I take action on the checkboxes: [Object, Object, Object] 0: Object count: 1 id: 6 label: "Who" type: "Organization" 1: Object id: 12622 2: Object id: 13452 When the checkbox to the corresponding group is unchecked, the current code above will remove all Objects from the Array are removed instead of just the specified group object. [] When the checkbox is then checked again, the selected group will enter the Array. I also tried this at first: var obj; networks = $.grep(networks, function(o,i) { return o.id === name ? ((obj = o), true) : false; }, true); However again it does not find and remove the Object in the array with the specified id (name) but it leaves the networks Array untouched. How would you write the else if statement to correct remove just the Object with the specified id and leave the rest of the Objects in the Array? A: You should u se filter instead of the grep, like this : networks = networks.filter(function (o,i) { return o.id !== name ? ((obj = o), true) : false; });
doc_4611
<Players> <Player> <Name>C.Ronaldo</Name> <Team>Man Utd</Team> <Position>Midfielder</Position> </Player> </Players> The problem is that the xml file which is created is not what I expect .How can fix this code Thanks in advance XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-16", null)); XElement root = new XElement("Players"); xdoc.Add(root); XElement player = new XElement("Player"); XElement[] el = { new XElement("Name","xxx"), new XElement("Team","dfdf"), new XElement("Position","dsds") }; xdoc.Root.Add(el); xdoc.Save("myxml.xml", SaveOptions.None); MessageBox.Show("ok"); A: The simpliest solution for your code would be to replace xdoc.Root.Add(el); with this: player.Add(el); xdoc.Root.Add(player);
doc_4612
1>Bettle_Dice.obj : error LNK2019: unresolved external symbol "public: int __thiscall Beetle::checkcom(void)" (?checkcom@Beetle@@QAEHXZ) referenced in function _main I have include other header files and cpp files, I don understand why only this file have problem please help Below is my code main.cpp #include "stdafx.h" #include "beetle.h" #include "dice.h" #include "player.h" #include <iostream> using namespace std; int main() { Player p; //declare Class to a variable Dice d; Beetle btle; int temp; cout << "Number of players?" << endl; cin >> temp; p.Num(temp); //store the number of player into class //cout << p.getNumPlayers() <<endl; cout << "Start game!!" <<endl; temp = btle.checkcom(); while(temp != 1) { for(int i=0;i<p.getNumPlayers();i++) { temp = d.roll(); cout <<"Your roll number:"<< temp; } } return 0; } beetle.h class Beetle { private: int body,head,ante,leg,eye,tail; public: int completion(); int checkcom(); int getBody() { return body;}; int getHead() { return head;}; int getAnte() { return ante;}; int getLeg() { return leg;}; int getEye() { return eye;}; int getTail() { return tail;}; }; Beetle.cpp #include "stdafx.h" #include "beetle.h" int completion() { return 0; } int checkcom() { Beetle btle; int flag = 0; if(btle.getBody() == 1 && btle.getHead() == 1 && btle.getAnte() == 2 && btle.getEye() == 2 && btle.getLeg() ==6 && btle.getTail() == 1) flag = 1; return flag; } I checked some solution on the internet, some are saying is the library problem, but this file is not a built-in function. I guess it is not the problem of the library. I tried to include the beetle.obj file to it and the debugger said it is included already and duplicate definition. In the other file, i do not have "bettle" this word. It should not be the problem of double declaration or duplicate class. I have no idea what the problem is. Please help. A: You need to prefix the signature of your class functions with the class name Beetle:: Otherwise the compiler just thinks those functions are global functions, not member functions.
doc_4613
But, My image is responsive as below, My Jquery, $(document).ready(function () { $("body").prepend('<div id="thumbnailcontainer" class="container-fluid"><div class="row"><img id="llthumbnail" class="img-fluid" style = "position: fixed;width: 100%;height: 100%;top: 0;left: 0; right: 0;bottom: 0;cursor: pointer;background:black;padding:0px 100px 0px 100px;" src = "http://w3.org/Icons/valid-xhtml10" ></div></div>'); $('#thumbnailPlayIcon').on("click", function () { thumbnailClick($(this)); }); $('#llthumbnail').on("click", function () { thumbnailClick($(this)); }); }); <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta charset="utf-8" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script> </head> <body> <div id="myDiv"> </div> <div class="skycap-caption" style="display:none"></div> </body> </html> can any one please help me to resolve the issue? A: To position the image container in the middle of the page use following style (note that you need to remove position: fixed; from image). #thumbnailcontainer { position: relative; transform: translateY(-50%); top: 50%; } In the snippet (view in full screen) I added a <div style="height:100vh;">to emulate a larger page, which you should probably remove for your own page. Also you should keep the styles in a css file and HTML in html file, since it is hard to maintain a big blob in javascript. $(document).ready(function () { $("body").prepend('<div style="height:100vh;"><div id="thumbnailcontainer" class="container-fluid"><div class="row"><img id="llthumbnail" class="img-fluid" style = "width: 100%;height: 100%;top: 0;left: 0; right: 0;bottom: 0;cursor: pointer;background:black;padding:0px 100px 0px 100px;" src = "http://w3.org/Icons/valid-xhtml10" ></div></div></div>'); $('#thumbnailPlayIcon').on("click", function () { thumbnailClick($(this)); }); $('#llthumbnail').on("click", function () { thumbnailClick($(this)); }); }); #thumbnailcontainer { position: relative; transform: translateY(-50%); top: 50%; } <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta charset="utf-8" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script> </head> <body> <div id="myDiv"> </div> <div class="skycap-caption" style="display:none"></div> </body> </html>
doc_4614
class FooSerializer(ModelSerializer): class Meta: model = Foo fields = '__all__' I want to intercept the request, and perform a check on it (against a method of the model, if it matters) before allowing the creation to continue. In vanilla django forms, I would override the form_valid method, do the check, and then call super().form_valid(...). I am trying to do the same here: class BookingView(ModelViewSet): queryset = DirectBooking.objects.all() serializer_class = DirectBookingSerializer def create(self, request): print(request.data) #Perform check here super().create(request) This works, in the sense that it creates an object in the DB, but the trace shows an error: AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>` This seems strange, as I would expect the super().save to return the appropriate response. I am aware that I will need to return a response myself if the check fails (probably a 400), but I would still like to understand why it is failing here. A: A view should return a HttpResponse. In a ViewSet, you do not implement .get(..) and .post(..) directly, but these perform some processing, and redirect to other functions like .create(..), and .list(..). These views thus should then return a HttpResponse (or "friends"), here you call the super().create(request), but you forget to return the response of this call as the result of your create(..) version. You should thus add a return statement, like: class BookingView(ModelViewSet): queryset = DirectBooking.objects.all() serializer_class = DirectBookingSerializer def create(self, request): print(request.data) #Perform check here return super().create(request)
doc_4615
<esri:LineSymbol x:Key="tunnelSymbol"> <esri:LineSymbol.ControlTemplate> <ControlTemplate> <Canvas> <Path x:Name="Element" StrokeStartLineCap="Round" StrokeEndLineCap="Round" StrokeDashCap="Round" StrokeLineJoin="Round" Opacity="0.5" RenderTransformOrigin="2,0" StrokeThickness="5" Stroke="#FF05AA05"> <Path.Effect> <DropShadowEffect/> </Path.Effect> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="SelectionStates"> <VisualState x:Name="Selected"> </VisualState> <VisualState x:Name="Unselected"/> </VisualStateGroup> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal"> <Storyboard> <DoubleAnimation BeginTime="0" Duration="0:0:0.1" Storyboard.TargetName="Element" Storyboard.TargetProperty="(Path.StrokeThickness)" To="5"/> </Storyboard> </VisualState> <VisualState x:Name="MouseOver"> <Storyboard> <DoubleAnimation BeginTime="0" Duration="0:0:0.1" Storyboard.TargetName="Element" Storyboard.TargetProperty="(Path.StrokeThickness)" To="10"/> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> </Path> <Path x:Name="Arrow" Stretch="Fill" Width="16" Height="16" StrokeLineJoin="Miter" Data="M 0 -5 L 10 -5 M 5 0 L 10 -5 L 5 -10" Stroke="Black" StrokeThickness="3"> <Path.RenderTransform> <TransformGroup> <TranslateTransform X="-8" Y="-8"/> <MatrixTransform> <MatrixTransform.Matrix> <Matrix/> </MatrixTransform.Matrix> </MatrixTransform> </TransformGroup> </Path.RenderTransform> <Path.Triggers> <EventTrigger RoutedEvent="Path.Loaded"> <BeginStoryboard> <Storyboard> <MatrixAnimationUsingPath x:Name="MatrixAnimation" Storyboard.TargetName="Arrow" Storyboard.TargetProperty="RenderTransform.Children[1].Matrix" DoesRotateWithTangent="True" Duration="0:0:5" BeginTime="0:0:0" RepeatBehavior="Forever" PathGeometry="{Binding Data, Source=Element, BindsDirectlyToSource=True}"> </MatrixAnimationUsingPath> </Storyboard> </BeginStoryboard> </EventTrigger> </Path.Triggers> </Path> </Canvas> </ControlTemplate> </esri:LineSymbol.ControlTemplate> </esri:LineSymbol>
doc_4616
My question is this: has anyone found any decent resources specifically regarding Android offline web apps? Or is this simply a hack? The iOS devices seems to support this in a more intuitive way. UPDATE: I had forgotten about this issue that I posted about. This seems to have been resolved for a while. I think it may have been fixed in Android 2.1. I just seemed to have not noticed that there was no error message. However, it still does not run HTML 5 webapps as cleanly as iOS in that the nav bar is still present when running from a desktop bookmark. A: After messing with this stuff for a bit, the iPhone/iOS stuff seems to work fine. It might be because the android browser is webkit based. But for whatever reason, the file manifest is respected Bottom line, iPhone HTML5 mobile app documentation seems to work fine for Android. Here's a quick example that runs on both: http://www.davidgranado.com/demos/make_a_set_mobile/ Here are the rules: http://www.davidgranado.com/2010/11/make-a-set-game/
doc_4617
i have two layout folders layout-small and layout When i change rendering device on preview when editing layout to Nexus S (It have "normal" screen) Android studio will open the layout-small and let me edit small screen layout which is displayed on Nexus S. Same issues with other "normal" screen devices thank you for your answers. A: I had the same problem. Try to rename your "layout" in "layout-normal". In this way Android Studio recognizes the right layout type for "normal-sized" devices and assigns the "layout-small" just to Android Wear devices. My advice to set a well formatted "layout-normal" is to design it on the smallest device available for "layout-normal" (Nexus One 3,7"). A: From android documentation: Supporting Multiple Screens As you can see in this image, a device's actual size is not certain to belong to either small or normal. Some sizes belong to both categories. Also please note that on android's manifest setting targetSdk may affect the judgement.
doc_4618
doc_4619
To do this, I've written the following code: f = open(program, "wb") f.seek(offset, 0) # absolute #print(f.read(1)) f.write(bytes([cval])) f.close() The code works perfectly when reading the byte at offset, but writing to this position results in objdump cannot recognize the ELF binary. mfo@mfo-Ubuntu:~/llvm-ir-obfuscation/checker$ objdump -dF fac_c objdump: fac_c: File format not recognized I don't see what I do wrong? A: You opened your file with w mode, which truncates the file when opening it. So your final file will only consist of the one byte you wrote. Just open it in update mode: f = open(program, "r+b") and it should be fine. A: See this tutorial on Python File I/O: https://www.tutorialspoint.com/python/python_files_io.htm rb+: Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file. What confuses you is probably that you think of rb+ as reading and wb+ as writing. However, both modes open the file for reading and writing, while the latter also overwrites the file. Because the latter mode overwrites the file, the ELF binary is effectively destroyed (the headers are gone).
doc_4620
TicketID - ID of the Ticket CreateTime - Time when the ticket is created FinishTime - Time when the ticket is finished handled My objective is to find these values based on hour Number of Tickets Received per hour Number of Tickets handled per hour So far I have come with 2 separate queries Select count(Receipt.ID) as ReceiveCount, Receipt.hours as PST, (Receipt.hours+12.5) as IST from (Select ReceiptScanRequestTable.ReceiptScanRequestID as ID, from_unixtime(CreateTime/1000 , '%H') as hours from ReceiptScanRequestTable where CreateTime>{hour_filter_value} ) as Receipt Group By Receipt.hours This will return Number of tickets received per hour Select count(Receipt.ID) as FinishCount, Receipt.hours as PST, (Receipt.hours+12.5) as IST from (Select ReceiptScanRequestTable.ReceiptScanRequestID as ID, from_unixtime(FinisheTime/1000 , '%H') as hours from ReceiptScanRequestTable where CreateTime>{hour_filter_value} ) as Receipt Group By Receipt.hours This will return Number of tickets finished per hour My objective is to combine the two queries into a single one! A: Try this: select receivecount, finishcount from (Select count(Receipt.ID) as ReceiveCount, Receipt.hours as PST, (Receipt.hours+12.5) as IST from (Select ReceiptScanRequestTable.ReceiptScanRequestID as ID, from_unixtime(CreateTime/1000 , '%H') as hours from ReceiptScanRequestTable where CreateTime>{hour_filter_value} ) as Receipt Group By Receipt.hours) a cross apply (Select count(Receipt.ID) as FinishCount, Receipt.hours as PST, (Receipt.hours+12.5) as IST from (Select ReceiptScanRequestTable.ReceiptScanRequestID as ID, from_unixtime(FinisheTime/1000 , '%H') as hours from ReceiptScanRequestTable where CreateTime>{hour_filter_value} ) as Receipt Group By Receipt.hours)b A: You can use union all and then aggregate: select hours, sum(receive) as numreceived, sum(finish) as numfinished, (hours + 12.5) as IST from ((Select from_unixtime(CreateTime/1000 , '%H') as hours, 1 as receive, 0 as finish from ReceiptScanRequestTable where CreateTime > {hour_filter_value} ) union all (Select from_unixtime(FinisheTime/1000 , '%H') as hours, 0, 1 from ReceiptScanRequestTable where CreateTime>{hour_filter_value} ) ) r group by hours;
doc_4621
here is some of my code import react, {useState, useRef, createElement} from "react"; import PixelPainterBtns from './PixelPainterBtns'; import '../styles/pixelpainter.css'; function PixelPainter() { //number of cells use state that holds the number of cells needed to be added in the grid const [numberOfCells, setNumberOfCells] = useState(16); //useRef that's being used to access grid container div in the html/jsx const gridContainerElement = useRef(); //create grid function const createGrid = (rows, cols) => { for(let c = 0; c < (rows * cols); c++){ let newCells = document.createElement("div"); gridContainerElement.current.appendChild(newCells) } } createGrid(numberOfCells, numberOfCells); return ( <> {/* pixel painter button components */} <PixelPainterBtns /> <main className='pixel-painter-main'> <div className='pixel-container'> <div className='frame'> {/*grid container div I'm trying accses and add new divs to. */} <div className='grid-container' ref={gridContainerElement}> </div> </div> </div> </main> </> ); } export default PixelPainter; as you can see I'm using the useRef react hook to access the div html, but when I test the app out in the browser I get this error in the console log "Uncaught TypeError: Cannot read properties of undefined (reading 'appendChild')" I've tried googling answers to my problem but, can't find anything that solves it. can someone help me? here is a live link to my app where Iam at currently. https://rsteward117.github.io/pixel-painter/ here is my github repo with all of my current code the only thing that's different is the name of use state from 'grid' to 'numberOfCells' in pixelpainter.js. https://github.com/rsteward117/pixel-painter/tree/main/src/components
doc_4622
create (lpam:Isbn{ident:"La physique avec Maple",name:"La physique avec Maple",type:"isbn",isbnValue:"2-7298-7948-X",isbnCanonique:"",sumUp:"Physique, Chimie, Fractales et Chaos"}); create (p138:Page{ident:"La physique avec Maplep138",name:"p138",,type:"page"}); MATCH (a), (b) WHERE a.ident = "La physique avec Maple" AND b.ident = "La physique avec Maplep138" CREATE (a)-[r:CONTAINS]->(b) RETURN r. ident strings are too long, whereas lpam p138 are shorter, best for me. 1)Can't I match based on the node variable lpam ? something like MATCH (a), (b) WHERE var(a) = "lpam" AND b.ident = "La physique avec Maplep138" CREATE (a)-[r:CONTAINS]->(b) RETURN r * create (p138:Page..... What is the role of the variable (p138) if I can not match it ? A: You don't need to match again for creating relationships. You can use the variables directly to create relationships like: CREATE (lpam:Isbn{ident:"La physique avec Maple",name:"La physique avec Maple",type:"isbn",isbnValue:"2-7298-7948-X",isbnCanonique:"",sumUp:"Physique, Chimie, Fractales et Chaos"}); CREATE (p138:Page{ident:"La physique avec Maplep138",name:"p138",,type:"page"}); CREATE (lpam)-[r:CONTAINS]->(p138) RETURN r;
doc_4623
At the moment I'm getting a compilation error ReadAsync is not a member of System.Threading.Tasks.Task(Of System.Data.Common.DbDataReader) I believe I'm doing something wrong, maybe in the GetReaderAsync function. Using reader As Task(Of Common.DbDataReader) = ConnectionController.GetReaderAsync(command) ' CType(Await command.ExecuteReaderAsync(CommandBehavior.SequentialAccess), Oracle.DataAccess.Client.OracleDataReader) While Await reader.ReadAsync() '<-- Compilation Error If reader.HasRows Then End If End While End Using Public Shared Async Function GetReaderAsync(command As DbCommand) As Threading.Tasks.Task(Of DbDataReader) 'Depending on the XML value provided in the [Provider], then select the appropriate connection from 'the object oSettings of the SettingsController. The SettingsController provides a structure called Provider to choose from If SettingsController.oSettings.Connection.provider.ToLower = SettingsController.Provider.Oracle Then Using reader As Oracle.DataAccess.Client.OracleDataReader = CType(Await command.ExecuteReaderAsync(CommandBehavior.SequentialAccess), Oracle.DataAccess.Client.OracleDataReader) command.ExecuteReader() Return reader End Using Else Using reader As SqlClient.SqlDataReader = CType(Await command.ExecuteReaderAsync(CommandBehavior.SequentialAccess), SqlClient.SqlDataReader) command.ExecuteReader() Return reader End Using End If End Function A: works like this: Using reader As Common.DbDataReader = Await command.ExecuteReaderAsync(CommandBehavior.SequentialAccess) A: You can use the Interface "System.Data.IDataReader". I use it for MySql, MSSql and Sqlite. It works very fine.
doc_4624
Please enter a 7-bit binary number: 0010011 Your number with a parity bit is: 00100111 This is my code that I have come up with, its probably wrong please can you correct it so it is alright? { Console.WriteLine("Please enter a 7- bit binary number"); string number = Console.ReadLine(); int count1 = 0; int count2 = 0; for(int i = 0; i < number.Length; i++) { count1++; } else { count2++; } if (count1 < count2) Console.WriteLine("Your number with parity bit is "+ number+ "1"); } else { Console.WriteLine("Your number with parity bit is "+ number + "0"); } } } } Thx in advance for the help A: This should do it: Console.WriteLine("Please enter a 7- bit binary number"); string number = Console.ReadLine(); int count = 0; for(int i = 0; i < number.Length; i++) { if(number[i] == '1') { count++; } } Console.WriteLine("Your number with parity bit is "+ number + (count % 2).ToString()); I'd imagine this is beyond your current level, but this should also work: Console.WriteLine("Please enter a 7- bit binary number"); string number = Console.ReadLine(); string parityBit = (number.Where(c => c == '1').Count() % 2).ToString(); Console.WriteLine("Your number with parity bit is "+ number + parityBit); A: So, the parity bit indicates whether or not the input has an even number of one-bits. So if your input string is in binary (which you normally shouldn’t safely assume, but we’ll ignore that for now), you need to simply count the number of 1s in the binary string. Following your initial idea (I think?), you could do it like this: int numberOfOnes = 0; for (int i = 0; i < bitstring.length; i++) { if (bitstring[i] == '1') numberOfOnes++; } if (numbersOfOnes % 2 == 0) // even number of ones else // uneven number of ones Note that there are two different versions of the parity bit, depending on if you have a 1 if the parity is even, or a 0 if the parity is even. Which you choose is up to you. A: The algorithm: * *Convert the string to integer. *Find the parity bit value. *"Append" parity bit value to the source integer => the result integer. *Convert the result integer to string and write the string to output. Source code: Console.Write("Please enter a 7-bit binary number: "); string numberString = Console.ReadLine(); // Convert to integer representation. int number = Convert.ToInt32(numberString, 2); // Find parity bit value for the integer. bool parity = false; int tempNumber = number; while (tempNumber > 0) { parity ^= tempNumber % 2 != 0; tempNumber >>= 1; } // "Append" parity bit. int numberWithParity = number << 1 | (parity ? 1 : 0); // Convert the result to string representation. numberString = Convert.ToString(numberWithParity, 2).PadLeft(8, '0'); Console.WriteLine("Your number with parity bit is {0}", numberString);
doc_4625
Here's the Python Code: #!/usr/bin/env python import cgi, cgitb import os import loadXML import display from xml.etree import ElementTree form = cgi.FieldStorage() # instantiate only once! #import file file_name = 'testrecords.xml' full_name = os.path.abspath(os.path.join('xml', file_name)) # get variables from html htmlName = 'lewis' #form.getfirst('name', 'empty') htmlNumber = 1 #form.getvalue('searchcrit') #htmlName = cgi.escape(htmlName) # initialize variables search = ['blank','name','activity','year','title'] searchnumber = ['1','2','3','4'] searchXML = loadXML.searchingall(full_name) #finds all xml entries (name, activity, record, num, year) = display.display(searchXML,htmlName,int(htmlNumber),search) #all vars coming out of the line above are arrays x = 0 addedArrays = ["None"] while name[x] != "Empty": addedArrays[x] = (str(name[x])+ "," + str(activity[x]) +","+ str(record[x]) +","+ str(num[x])+","+ str(year[x])) x = x + 1 addedArrays.append(x) with open('/home/ubuntu/workspace/test.html') as f: htmlFile=(f.read()) print("""\ Content-Type: text/html\n """+ htmlFile % addedArrays) #print("""\ #Content-Type: text/html\n #<html> #<body> #<p class="page-description">The returned items were "%s"</p> #</body> #</html> #""" % addedArrays) Here's the HTML code: <html> <body> <p class="page-description">The returned items were "%s"</p> </body> </html> Here's the HTML file: <!DOCTYPE html> <html> <head> <!--under the black menu line in large text saying CLHS Records--> <title>CLHS Records</title> <link rel="stylesheet" type="text/css" href="Stylesheet.css"> <!--This connects your stylesheet.css to html--> </head> <body> <!--this is the start of your body of the page--> <div class="nav"> <!--This is what keeps seachbar in line with your names--> <div class="nav_wrapper"> <!--This is what holds the search bar in place--> <form method="get" action="/cgi-bin/pyHandler.py" /> <form class="form-wrapper"> <input type="text" name="name" placeholder="Enter Name"> <input type="radio" name="searchcrit" value="1">Name <input type="radio" name="searchcrit" value="3">Year <input type="radio" name="searchcrit" value="2">Activity <input type="radio" name="searchcrit" value="4">Records <input type="submit" value="Submit" a href="https://schoolrecordproject-jasonchristenson.c9users.io/html/Results.html" /> </form> </div> <img class="lionimage" width="12%" src="http://clearlakeschools.org/wp-content/uploads/2016/12/Charging-Lion.png" /> <!--this is the lion image above the title clhs records--> <h1 class="page-title">CLHS Records</h1> <p class="page-description"> On this webpage you will be able to view record holders over the various years at Clear Lake High school. You will be able to search the file by name,year,activity, and record. </p> <!--discription in middle of page describing--> <div class="navigation"> <nav> <ul> <li><a href="#"><b> Clear Lake Athletics </b></a></li> <li><a href="http://clearlakeschools.org/about/"><b> About Clear Lake District </b></a></li> </ul> <div class="contact-btn"> <a href="mailto:">Contact</a> </div> </nav> </div> </body> </html> We just have a basic XML file that this is referencing as well as all the python files like the display file. Basically my problem is on the Python file, if I uncomment the last 8 lines, everything works great, but I need this to import another HTML file to do what the last eight lines do, but we need it to be able to externally update the html file and change formatting etc. If I run the last eight lines, it works fine, but if I run this: with open('/home/ubuntu/workspace/test.html') as f: htmlFile=(f.read()) print("""\ Content-Type: text/html\n """+ htmlFile % addedArrays) then it doesn't work. What do I need to do to make it work? Thanks!
doc_4626
data = { labels: [ "RP.800,000", "RP.400,000", "RP.200,000"], datasets: [{ label: "", data: [ "800000", "400000", "200000"], borderColor: "#744c7e", lineTension: 0, pointBorderColor: "#bfc766", pointBackgroundColor: "#bfc766" }] }; Chart.pluginService.register({ beforeRender: function (chart) { if (chart.config.options.showAllTooltips) { // create an array of tooltips // we can't use the chart tooltip because there is only one tooltip per chart chart.pluginTooltips = []; chart.config.data.datasets.forEach(function (dataset, i) { chart.getDatasetMeta(i).data.forEach(function (sector, j) { chart.pluginTooltips.push(new Chart.Tooltip({ _chart: chart.chart, _chartInstance: chart, _data: chart.data, _options: chart.options, _active: [sector] }, chart)); }); }); // turn off normal tooltips chart.options.tooltips.enabled = false; } }, afterDraw: function (chart, easing) { if (chart.config.options.showAllTooltips) { // we don't want the permanent tooltips to animate, so don't do anything till the animation runs atleast once if (!chart.allTooltipsOnce) { if (easing !== 1) return; chart.allTooltipsOnce = true; } // turn on tooltips chart.options.tooltips.enabled = true; Chart.helpers.each(chart.pluginTooltips, function (tooltip) { tooltip.initialize(); tooltip.update(); // we don't actually need this since we are not animating tooltips tooltip.pivot(); tooltip.transition(easing).draw(); }); chart.options.tooltips.enabled = false; } } }); var lineChart = new Chart(ctx, { type: 'line', data: data, options: { legend: { display: false }, elements: { line: { fill: false } }, showAllTooltips: true, scales: { gridLines: { offsetGridLines: true }, xAxes: [{ display: false }], yAxes: [{ display: true, ticks: { min: 100000, max: 900000, fixedStepSize: 100000, callback: function (value) { return ''; } } }] }, tooltips: { backgroundColor: '#92b95e', titleColor: '#FFF', titleFontStyle: 'normal', xAlign: 'bottom', callbacks: { label: function () { } } }, } }); https://jsfiddle.net/k4pty0ds/ As you can see, the last tooltip got cut off. According to the Chart.js doc, I would like to add paddingRight and I do not know how. Please help. I tried adding to scales and it doesn't work. When i followed the documentation and used registerScaleType also failed.
doc_4627
Now I am creating the event from 15:30 to 16:30 hours. Now I when I resize the event and stretch it and end it to 17:30, which is out of the business hours, I want it to revert the changes. Following is how I have initialised the fullcalendar: $('#calendar').fullCalendar({ header: { left: '', center: '', right: '', }, firstDay: 0, editable: true, selectable: true, defaultView: 'agendaWeek', columnFormat: 'dddd', events: events_data, eventResize: function(event, delta, revertFunc) { console.log($(this).businessHours); } }); A: In your eventResize function, you can check the event parameter and check the input. function isBusinessHour(event) { // Check if your event.start and event.end is in business hours // Using moment functions such as isBetween() } eventResize: function(event, delta, revertFunc) { if (!isBusinessHour(event)) revertFunc(); } A: To achieve this you can set the "eventConstraint" option to "businessHours": eventConstraint: "businessHours" The documentation for this setting says: If "businessHours" is given, events being dragged or resized must be fully contained within the week’s business hours (Monday-Friday 9am-5pm by default). A custom businessHours value will be respected. See https://fullcalendar.io/docs/eventConstraint for more details. A: It does not work, even with the version 4. You need to compare values for event and those of business Hours:` eventDrop: function(info) { var format = 'HH:mm'; // get moment as time:min only var ies = moment(info.event.start); var tes = ies.hours()+':'+ies.minutes(); var event_start = moment(tes,format); var iee = moment(info.event.end); var tee = iee.hours()+':'+iee.minutes(); var event_end = moment(tee,format); // get business hours var bh_start = moment(calendar.getOption('businessHours')['startTime'],format); var bh_end = moment(calendar.getOption('businessHours')['endTime'],format); if ( event_start.isBefore( bh_start ) || event_end.isAfter( bh_end )) { console.log(' out of busqiness hours'); info.revert(); return false; } }
doc_4628
public class MainActivity extends AppCompatActivity { RecyclerView recyclerView; DatabaseReference reference; FirebaseRecyclerAdapter<Bookdeets,Bkhomeholder>adapter; FirebaseRecyclerOptions<Bookdeets> options; ProgressBar loading; FloatingActionButton searchbtn; TextView logout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); reference = FirebaseDatabase.getInstance().getReference().child("books"); reference.keepSynced(true); recyclerView = (RecyclerView) findViewById(R.id.rv); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL)); loading=(ProgressBar)findViewById(R.id.loading); searchbtn=(FloatingActionButton)findViewById(R.id.searchbtn); logout = (TextView) findViewById(R.id.Logout); logout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Logout(); } }); searchbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Opensearchpage(); } }); options = new FirebaseRecyclerOptions.Builder<Bookdeets>() .setQuery(reference, Bookdeets.class).build(); adapter = new FirebaseRecyclerAdapter<Bookdeets, Bkhomeholder>(options) { @Override protected void onBindViewHolder(@NonNull Bkhomeholder holder, int position, @NonNull Bookdeets model) { Picasso.get().load(model.getImage()).into(holder.bookimg, new Callback() { @Override public void onSuccess() { loading.setVisibility(View.GONE); } @Override public void onError(Exception e) { Toast.makeText(getApplicationContext(), "could not get the image", Toast.LENGTH_LONG).show(); loading.setVisibility(View.GONE); } }); holder.title.setText(model.getBookname()); } @NonNull @Override public Bkhomeholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardviewlay, parent, false); return new Bkhomeholder(view); } }; GridLayoutManager gridLayoutManager=new GridLayoutManager(getApplicationContext(),3); recyclerView.setLayoutManager(gridLayoutManager); adapter.startListening(); recyclerView.setAdapter(adapter); } @Override protected void onStart() { super.onStart(); if(adapter!=null) adapter.startListening(); loading.setVisibility(View.VISIBLE); } @Override protected void onStop() { super.onStop(); if(adapter!=null) adapter.stopListening(); } @Override protected void onResume() { super.onResume(); if(adapter!=null) adapter.startListening(); } public void Opensearchpage(){ Intent intent=new Intent(this, SearchPage.class); startActivity(intent); } public void Logout() { FirebaseAuth.getInstance().signOut(); startActivity(new Intent(getApplicationContext(), Login.class)); finish(); } Bkhomeholder.java public class Bkhomeholder extends RecyclerView.ViewHolder { public TextView title; public ImageView bookimg; public Bkhomeholder(@NonNull View itemView) { super(itemView); title = itemView.findViewById(R.id.bkdettitle); bookimg = itemView.findViewById(R.id.bkdetimg); } activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".homepage.MainActivity" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="60dp" android:layout_marginTop="4dp" android:layout_marginStart="8dp" android:layout_marginEnd="8dp" android:text="Library App" android:textAlignment="center" android:textColor="#E21B1B" android:textSize="32dp" android:textStyle="bold" /> <androidx.recyclerview.widget.RecyclerView android:clipChildren="true" android:id="@+id/rv" android:layout_width="match_parent" android:layout_height="525dp" android:layout_marginStart="8dp" android:layout_marginTop="75dp" android:layout_marginEnd="8dp" android:layout_marginBottom="8dp" android:clickable="true" android:foreground="?android:attr/selectableItemBackground"/> <com.google.android.material.floatingactionbutton.FloatingActionButton android:id="@+id/searchbtn" android:layout_width="100dp" android:layout_height="100dp" android:layout_marginStart="345dp" android:layout_marginTop="480dp" android:layout_marginEnd="12dp" android:background="#B3E5FC" android:clickable="true" app:srcCompat="@drawable/customicon" /> <ProgressBar android:id="@+id/loading" style="?android:attr/progressBarStyle" android:layout_width="76dp" android:layout_height="76dp" android:layout_marginStart="163dp" android:layout_marginTop="253dp" android:layout_marginEnd="163dp" android:layout_marginBottom="253dp" android:visibility="invisible" /> <TextView android:layout_width="match_parent" android:layout_height="25dp" android:id="@+id/Logout" android:layout_centerHorizontal="true" android:text="Logout" android:textAlignment="center" android:textSize="14sp" android:layout_marginBottom="8dp" android:layout_marginTop="565dp" cardview xml <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:cardview="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:clickable="true" android:foreground="?android:attr/selectableItemBackground" android:id="@+id/bookcardview" android:layout_width="120dp" android:layout_height="190dp" android:layout_margin="5dp" cardview:cardCornerRadius="4dp"> <LinearLayout android:id="@+id/bkdetlinear" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:ignore="ExtraText" android:clickable="true" android:foreground="?android:attr/selectableItemBackground" android:layout_marginEnd="4dp" > <ImageView android:id="@+id/bkdetimg" android:layout_width="match_parent" android:layout_height="160dp" android:background="#2d2d2d" android:clickable="true" android:scaleType="fitXY" /> <TextView android:id="@+id/bkdettitle" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:text="Book title" android:textColor="#2d2d2d" android:textSize="12sp" /> </LinearLayout> </androidx.cardview.widget.CardView> </RelativeLayout> i tried setting on click on the cardviewholder that is separate xml file which is inflated in my mainactivity oncreate and set the onclick listener under onBindViewHolder but i got a error regarding null object refference as if the activity could not detect the cardview A: You can set OnClickListener on RecyclerView item inside onBindViewHolder like below: @Override protected void onBindViewHolder(@NonNull Bkhomeholder holder, int position, @NonNull Bookdeets model) { .... holder.title.setText(model.getBookname()); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Do your operation here } }); } Update: Remove android:clickable="true" from cardview layout like below: <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:cardview="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:foreground="?android:attr/selectableItemBackground" android:id="@+id/bookcardview" android:layout_width="120dp" android:layout_height="190dp" android:layout_margin="5dp" cardview:cardCornerRadius="4dp"> <LinearLayout android:id="@+id/bkdetlinear" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:ignore="ExtraText" android:foreground="?android:attr/selectableItemBackground" android:layout_marginEnd="4dp" > <ImageView android:id="@+id/bkdetimg" android:layout_width="match_parent" android:layout_height="160dp" android:background="#2d2d2d" android:scaleType="fitXY" /> <TextView android:id="@+id/bkdettitle" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:text="Book title" android:textColor="#2d2d2d" android:textSize="12sp" /> </LinearLayout> </androidx.cardview.widget.CardView>
doc_4629
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" > <PreferenceCategory android:title="@string/security_setting_edittext_hint" > <EditTextPreference android:dialogTitle="@string/security_setting_button" android:key="set_password_preference" android:summary="@string/set_password_summary" android:title="@string/security_setting_button" android:inputType="number" android:icon="@drawable/lock" /> </PreferenceCategory> </PreferenceScreen> My Java file looks like public class Settings extends PreferenceActivity { Dialog setPasswordDialog; EditText setPassword; EditTextPreference editPreference; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setTitle("Settings"); addPreferencesFromResource(R.xml.preference_authentication); editPreference=(EditTextPreference) findPreference("set_password_preference"); } There is no issue in displaying the dialog but now i want tho get event when Ok and Cancel button from dialog box is pressed to do something. Please provide me solution. A: If I get your question correctly, you want to handle the "Ok" and "Cancel" event and then perform some action based on the response. // This is using code: AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("TITLE HERE"); alert.setMessage("MESSAGE"); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { //Do something here where "ok" clicked } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { //So sth here when "cancel" clicked. } }); alert.show(); A: You will need to create your custom edit text preference as follows. public class MyEditTextPreference extends EditTextPreference { public MyEditTextPreference(Context context) { super(context); } public MyEditTextPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public MyEditTextPreference(Context context, AttributeSet attrs) { super(context, attrs); } @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: // Put your logic here for Ok button press break; case DialogInterface.BUTTON_NEGATIVE: // Put your logic here for Cancel button press break; } super.onClick(dialog, which); } } Then use it in xml file as follows: <com.package.MyEditTextPreference android:dialogTitle="@string/security_setting_button" android:key="set_password_preference" android:summary="@string/set_password_summary" android:title="@string/security_setting_button" android:inputType="number" android:icon="@drawable/lock" /> where com.package should be replaced by the actual package in your project where you create MyEditTextPreference A: DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which){ case DialogInterface.BUTTON_POSITIVE: //Yes button clicked break; case DialogInterface.BUTTON_NEGATIVE: //No button clicked break; } } }; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener) .setNegativeButton("No", dialogClickListener).show();
doc_4630
Any suggestions of setting an extension method? I know to provide checking the culture name and set the direction as right to left only for say hebrew, arabic etc. Is this the only way??? Thanks
doc_4631
Uses IF ( A = TargetPerson, C) to generate an array which is false A is not the TargetPerson and is the count (C) if it is the TargetPerson. Takes the MAX of the above. Uses MATCH to look up the above determined max, where the lookup range is the same array calculated in the first step above. Uses INDEX to return column B for the matched row. The problems with this: * *It seems slow. *I am struggling to generalize it to identify the n-th most frequently occurring person; I tried LARGE in lieu of MAX but it breaks down if you have two equally frequently occurring individuals - in that case I would like to be able to return them both based on an an alpha sort for example. Grateful for any tips. Was asked for reproducible example. No idea how to provide data through this... Data: A B C = count of person B for the full column B Location Person New York Luke Skywalker New York Darth Vader New York Carrie Fisher London Carrie Fisher Cairo Mark Hammill Dublin Mark Hammill Sydney Mark Hammill Melbourne Carrie Fisher Formula in Sheet2, which has rows for each unique location (col A) and tries to return the person associated with that location who is also most frequently associated with any location (in col B): =INDEX(Sheet1!$B$2:$B$9,MATCH(MAX(IF(Sheet1!$A$2:$A$9=Sheet2!A4,Sheet1!$C$2:$C$9)),IF(Sheet1!$A$2:$A$9=Sheet2!A4,Sheet1!$C$2:$C$9),0),1) A: You can do it as a fairly quick function BUT you need to park an intermediate result somewhere. For some reason I cant pass the result of FILTER into a second FILTER So I put the first FILTER into E5 and then pass that into the second filter E5 =FILTER(A5:C12, A5:A12=$B$1) and I5 =FILTER(E5#, G5:G7=LARGE(OFFSET(E5#, 0, 2, COUNTIF(A5:A12, B1), 1), B2)) Steps are: * *Filter the input list based on location *Isolate the counts (the filter output, what was the original column C) using offset and identify the value of the nth largest using LARGE and user input Person Rank *Filter the intermediate array based on the value associated with the nth largest
doc_4632
An existential sentence is a sentence which consists of a string of existential quantifiers followed by a quantifier-free formula. How can I show that if a first-order theory T is closed under extension, then it can be axiomatised using existential sentences? I think the proof might involve the method of diagrams, the compactness theorem and even Loewenheim-Skolem theorem, but I don't know how to connect the dots.
doc_4633
A: Try push a PageRouteBuilder rathe than a MaterialPageRoute. Navigator.push(context, PageRouteBuilder(opaque: false, pageBuilder: (_, __, ___) => DismissableScreen()));
doc_4634
I want the same application to be run on iPhone. For android we write permissions for accessing camera in manifest file. How do you access the camera in iPhone. Where do we need to set up it. Can anyone please help me? Thanks in advance A: Use the Media Capture API in the latest code, or wait for 0.9.6: http://docs.phonegap.com/phonegap_media_capture_capture.md.html A: For accessing the camera in iPhone, you can use following code. // Camera UIImagePickerController *imgPicker = [[UIImagePickerController alloc] init]; imgPicker.delegate = self; imgPicker.allowsImageEditing = YES; imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera; //[self presentModalViewController:imgPicker animated:YES]; [objParent presentModalViewController:imgPicker animated:YES]; [imgPicker release]; Let me know in case of any difficulty. Below are the delegate method for camera. Delegate Name: UIImagePickerControllerDelegate, UINavigationControllerDelegate Methods: #pragma mark UIImagePickerController delegate -(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { // Access the uncropped image from info dictionary UIImage *imgCapturePhoto = [info objectForKey:@"UIImagePickerControllerOriginalImage"]; [imgPhoto setImage:imgCapturePhoto]; [self dismissModalViewControllerAnimated:YES]; } -(void)imagePickerControllerDidCancel:(UIImagePickerController *) picker { [picker dismissModalViewControllerAnimated:YES]; } Cheers
doc_4635
Failover times are pretty good when shutting down one node gracefully, however, when killing a node (by shutting down the VM) the latency during the tests is about 12 seconds. I guess this has something to do with the tcp timeout? Is there any way to tweak this? Edit: At the moment we are using Cassandra Version 2.0.10. We are using the java client driver, version 2.1.9. To describe the situation in more detail: The write/read operations are performed using the QUROUM Consistency Level with a replication factor of 3. The cluster consists of 3 nodes (c1,c2,c3), each on a different host (VM). The client driver is connected to c1. During the tests I shutdown the host for c2. From then on we observe that the client is blocking for > 12 seconds, until the other nodes realize that c2 is gone. So i think this is not a client issue, since the client is connected to node c1, which is still running in this scenario. Edit: I don't believe that the fact that running cassandra inside a VM affects the network stack. In fact, killing the VM has the effect, that the TCP connections are not terminated. In this case, a remote host can notice this only through some time out mechanism (either a timeout on the application level protocol or a TCP timeout). If the process is killed on OS level, the TCP stack of the OS will take care of terminating the TCP connection (IMHO with a TCP reset) enabling a remote host to immediately be notified about the failure.  However, it might be important that even in situations, where a host crashes due to a hardware failure, or where a host is disconnected due to an unplugged network cable (in both cases the TCP connection will not be terminated immediately) the failover time is low.  I've tried to sigkill the cassandra process inside the VM. In this case the failover time is about 600ms, which is fine. kind regards A: Failover times are pretty good when shutting down one node gracefully, however, when killing a node (by shutting down the VM) the latency during the tests is about 12 seconds 12 secs is a pretty huge value. Some questions before investigating further * *what is your Cassandra version ? Since version 2.0.2 there is a speculative retry mechanism that help reducing the latency for such failover scenario: http://www.datastax.com/dev/blog/rapid-read-protection-in-cassandra-2-0-2 *what is the client driver you're using (java ? c# ? version ?). Normally with a properly configured load balancing policy, when a node is down the client will retry automatically the query by re-routing to another replica. There is also speculative retry implemented at the driver-side : http://datastax.github.io/java-driver/manual/speculative_execution/ Edit: for a node to be marked down, the gossip protocol is using the phi accrual detector. Instead of having a binary state (UP/DOWN), the algorithm adjust the suspicion level and if the value is above a threshold, the node is considered down This algorithm is necessary to avoid marking down a node because of a micro network issue. Look in the cassandra.yaml file for this config: # phi value that must be reached for a host to be marked down. # most users should never need to adjust this. # phi_convict_threshold: 8 Another question is: what load balancing strategy are you using from the driver ? And did you use the speculative retry policy ?
doc_4636
Below is my code for AddFragment.java from which I choose photo and MainAcitivity. I checked all forums and websites and nobody has such problem. Thank you in advice :) I don't know what to do :( public class AddFragment extends Fragment{ private Button addPhoto; private ImageView imageView; private Uri imageUri; private final int PICK_IMAGE_REQUEST = 1; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_add,container,false); imageView=v.findViewById(R.id.imgView); addPhoto=v.findViewById(R.id.button_addphoto); addPhoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openFileChooser(); } }); return v; } private void openFileChooser(){ Intent intent=new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); Log.d(TAG, "OPENFILECHOOSER"); startActivityForResult(Intent.createChooser(intent, "Select Picture"),PICK_IMAGE_REQUEST); Log.d(TAG, "OPENFILECHOOSER2"); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(TAG, "OPENFILECHOOSER3"); if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK &&data != null && data.getData() !=null){ imageUri = data.getData(); Picasso.get().load(imageUri).resize(50,50).into(imageView); } } } MainActivity.java public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private DrawerLayout drawer; NavigationView navigationView; private FragmentManager fragmentManager; private FirebaseAuth mAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar=findViewById(R.id.toolbar); setSupportActionBar(toolbar); drawer = findViewById(R.id.drawer_layout); navigationView=findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); ActionBarDrawerToggle toogle=new ActionBarDrawerToggle(this,drawer,toolbar, R.string.navigation_drawer_open,R.string.navigation_drawer_close); drawer.addDrawerListener(toogle); toogle.syncState(); if(savedInstanceState==null) { getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new HomeFragment()).commit(); navigationView.setCheckedItem(R.id.nav_home); } fragmentManager = getFragmentManager(); } @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch(item.getItemId()){ case R.id.nav_home: getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new HomeFragment()).commit(); break; case R.id.nav_add_new: getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new AddFragment()).commit(); break; case R.id.nav_login: getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new LoginFragment()).commit(); break; case R.id.nav_browse: getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new BrowseFragment()).commit(); break; case R.id.nav_logout: getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new HomeFragment()).commit(); signOut(FirebaseAuth.getInstance()); break; case R.id.nav_profile: getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new HomeFragment()).commit(); break; } drawer.closeDrawer(GravityCompat.START); return true; } @Override public void onBackPressed() { if(drawer.isDrawerOpen(GravityCompat.START)){ drawer.closeDrawer(GravityCompat.START); } else if (fragmentManager.getBackStackEntryCount() > 0) { fragmentManager.popBackStack(); } else { //super.onBackPressed(); } } private void signOut(FirebaseAuth mAuth) { if (mAuth != null) { mAuth.signOut(); navigationView.getMenu().findItem(R.id.nav_login).setVisible(true); navigationView.getMenu().findItem(R.id.nav_logout).setVisible(false); navigationView.getMenu().findItem(R.id.nav_profile).setVisible(false); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(TAG, "OPENFILECHOOSER4"); Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container); fragment.onActivityResult(requestCode,resultCode,data); } } // In your MainActivity.java @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(TAG, "OPENFILECHOOSER4"); super.onActivityResult(requestCode, resultCode, data); } Nothing appears in logcat. I can see that method onActivityResult() don't get call A: You must always call super.onActivityResult() in your Activity's onActivityResult. That is what dispatches onActivityResult callbacks to Fragments that called startActivityForResult with the correct requestCodes - your method of manually dispatching it does not do the remapping of request code: // In your MainActivity.java @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(TAG, "OPENFILECHOOSER4"); super.onActivityResult(requestCode, resultCode, data); } This issue was filed to add @CallSuper to catch exactly this problem and it is scheduled to be released in Fragments 1.1.0-alpha06.
doc_4637
in index[0] "Test 0 Length 32 [41 - 73]" in index[1] "Test 1 Length 22 [81 - 103]" And so on. I need to get the all the numbers from each index. For example in the new List i need to have: 41,42,43,44,45,46,47....73 then to take the numbers from index[1] and after the 73 in he new List to continue 81,82,83,84,85....103 So the new List wich will be will contain all the numbers. To calculate the Length for example 32 or 22 im doing: int len = LR[i].end - LR[i].start; Lr[i].end is 73 and Lr[i].start is 41 So i need to calculate and get all the numbers between 41 and 73 including 41 and 73 and add them to a new List then to the next itertion where LR[i].end is 103 and start is 81 and again get the numbers and add them to the List So in the end the List will contain all the numbers in one big row. How can i do it ? A: List<string> list = new List<string>() { "Test 0 Length 32 [41 - 73]", "Test 1 Length 22 [81 - 103]" }; var numbers = list.SelectMany( s => Regex.Matches(s, @"\[(\d+)[ -]+(\d+)\]") .Cast<Match>() .Select(m => m.Groups.Cast<Group>().Skip(1).Select(x=>x.Value) .ToArray()) .Select(x => new {start=int.Parse(x[0]), end=int.Parse(x[1]) }) .SelectMany(x => Enumerable.Range(x.start, x.end- x.start + 1)) ) .ToList(); A: I'm not sure what the contents of LR is, but I assume that you have your range numbers as a valid ints (otherwise, you will have to use regex or String.IndexOf to find them). But, if you have list of object where object looks like this: class pairs { int item1; int item2; } then you can easily do the following (see Enumerable.Range) Enumerable.Range accepts two parameters: start and count. To get the count we have to subtract upper-bound from lower bound and add one to include upper-bound value.: var values = new List<int>(); list.ForEach(x =>values.AddRange(Enumerable.Range(x.Item1, x.Item2 - x.Item1 + 1))); Working console app using Tuple: var list = new List<Tuple<int, int>>(); list.Add(Tuple.Create(41, 73)); list.Add(Tuple.Create(81, 103)); list.Add(Tuple.Create(120, 150)); // So, now we have three pair of values. 41-73, 81-103, 120-150 //Now we can loop through the list and generate sequence using Enumerable.Range like this: var values = new List<int>(); list.ForEach(x =>values.AddRange(Enumerable.Range(x.Item1, x.Item2 - x.Item1 + 1))); //And print out items. values.ForEach(x => Console.WriteLine(x)); //will print 41,42,43......73, 81,82,83....,103, 120, 121,.....150 A: SelectMany will give you a concatenated sequence of subsequences, so the following would give you a list of all the numbers in each range. ranges.SelectMany(r => Enumerable.Range(r.start, r.end - r.start + 1)).ToList();
doc_4638
class GenericClass<T> {} protocol Protocol { associatedtype A associatedtype C : GenericClass<A> } class IntClass : GenericClass<Int> {} struct Adopter : Protocol { typealias A = Int typealias C = IntClass } everything is ok but if I add a method to Protocol that uses the C associated type: protocol Protocol { ... func f(c: C) } and implement it in Adopter: struct Adopter : Protocol { ... func f(c: C) {} } everything brakes! The compiler tells me: "Protocol requires function 'use(c:)' with type '(Adopter.C) -> ()'..." My best guess is that this has something to do with the fact that C is a class and that the type signature f(c: C) would allow subclasses of C being passed but I can't see how that would be a problem... Here's a gist illustrating the problem that you can paste into a playground I'm wondering if this is a bug? I hope I'm not *again* fundamentally misunderstanding something with the type system update I think I am getting to the root of the problem by just declaring the protocol like this: protocol Protocol { associatedtype A associatedtype C : GenericClass<A> func f(c: C) } putting this into a playground, I get the error: Playground execution failed: error: generic parameter 'C' cannot be a subclass of both 'GenericClass<<< error type >>>' and 'GenericClass' just because, I tried mimicking a similar type relationship with a struct: struct Struct< A, C : GenericClass<A> > { func f(c: C) {} } This compiles just fine.
doc_4639
Why does my unpackaged C# application show its icon when I launch it but not when my Windows service launches it? How can I make my app's toasts always show the app's icon? Details: I have a C++ Windows Service that launches a C# Win32 application for toast functionality, since toasts cannot be launched directly from a service to a user. It is an absolute requirement that the service launches the toast app. To my frustration, however, the app's icon (i.e. the icon shown on the .exe in Explorer) refuses to show only when launched by my service. Here is an example of what I see when my service launches the app (Note the three squares. This is the Windows 10 default icon): When I manually launch the app (i.e. click it), this is what I see instead: The only difference between the above two screenshots is the launch method. The most succinct way I can describe my issue is that I want the launch method (launched from a service) that yields the first screenshot to yield the second screenshot instead. I can provide the code snippet I used to generate these toasts, although I doubt its usefulness for finding a solution: var notifier = ToastNotificationManagerCompat.CreateToastNotifier(); var xml = new Windows.Data.Xml.Dom.XmlDocument(); xml.LoadXml("<toast><visual><binding template=\"ToastGeneric\"><text>Foo</text<text>Bar</text></binding></visual></toast>"); var notif = new Windows.UI.Notifications.ToastNotification(xml); notifier.Show(notif); The most useful code sample I believe I can provide is the code that the service uses to launch the app: void SpawnToastApp() { constexpr int nProcFlags = DETACHED_PROCESS | NORMAL_PRIORITY_CLASS; constexpr wchar_t* wcsDesktop = L"WinSta0\\Default"; constexpr wchar_t* wcsToastApp = L"ToastApp\\Toast App (WIP).exe"; HANDLE hUser = NULL; STARTUPINFOW si{ 0 }; wchar_t wcsCmdLine[MAX_PATH]{ 0 }; _snwprintf_s(wcsCmdLine, _TRUNCATE, L"\"%S\\%s\" %lu", _strInstallDir, wcsToastApp, GetCurrentProcessId()); _sessionCanToast = WTSQueryUserToken(_sessionId, &hUser); if (_sessionCanToast) { ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); si.lpDesktop = wcsDesktop; _sessionCanToast = CreateProcessAsUserW(hUser, NULL, wcsCmdLine, NULL, NULL, FALSE, nProcFlags, NULL, NULL, &si, &_toastHandlerProcessInformation); } if(!_sessionCanToast) { /// Log it } if (hUser) { CloseHandle(hUser); }; } I include the C++ code because I believe that I have narrowed the problem down to the launch method but am unsure the specific cause beyond that. Additional Information: These screenshots utilize Windows.UI.Notifications.ToastNotifications created from raw XML, but I have also tried using the Microsoft.Toolkit.Uwp.Notifications NuGet Package as recommended by Microsoft to the same effect. I believe this project is a Windows Form App. I am not using any sort of package--no APPX, MSIX, or sparse package. This is meant to be a lightweight app whose sole function is for toasts. While using a package isn't out of the question, suffice it to say that the number of hurdles and implementation issues make packaging this app undesirable. Indeed, the only reason I would want to package this app is for the icon in the upper left-hand corner of it, which it evidently does already, just not in the way I desire. Similar to but NOT a duplicate of: * *Change toast notification icon in wpf * *I have already done this. My issue pertains to the icon's inconsistency rather than the lack of it entirely. *Why is app icon missing for toast notifications in action center on desktop? * *I am using a Release build of my app *Cannot override notification app logo for Windows 10/11 VSTO app * *Using AppOverrideLogo gets my icon to show under all circumstances, but it's more like a picture in the body of the toast rather than the small icon in the upper left-hand corner of the toast. Essentially, it's not the style I want. EDIT 1: I followed a sparse packaging guide found here to more or less the same result, the main difference being that now no icon not shows up at all anywhere. I used the asset generator in Visual Studio and then used the MSIX unpackaging tool to inspect the contents of the sparse package and confirmed it contained the generated assets. I had to comment out the reference to the splash screen because the app failed to register with that line included in the manifest. EDIT 2: I have decided to proceed with this app as if I am not having this issue, and so I used Visual Studio's Performance Profiler to analyze my app's resources. The Performance Profiler launched my toast app, and the toasts had the correct icon, so at this point I am 100% certain it has something to do with my service's launch method. Unfortunately, I am no closer to understanding why the icon does not show only when launched from my service.
doc_4640
After researching I found somewhere that we might need to bake the texture using software like Blender. Can anyone please let me know if the baking of textures is a mandatory step for using 3d objects with metaio sdk? If yes, Is there any android plugin that could probably automate this process? A: when you get the model as white texture, it's because your 3d model .obj has to many polygons to get renderized in your device, or that your 3d model is to big to get renderized properly. the solution is to reduce the number of polygons and texture of your 3d model. make it simplest possible. hope to help
doc_4641
I have two viewcontrollers in this UITabBarController. In each of the views, lets call them view1 and view2, i have the following code: self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if(self) { UITabBarItem *tbi = self.tabBarItem; tbi.title = @"title"; UIImage *i = [UIImage imageNamed:@"picture.png"]; tbi.image = i; tbi.tag = 0; } This makes me able to freely navigate between two viewcontrollers. Now, to the question: I want to have an event when i click each of the tabs. I have googled for 4 hours now and tried a lot of things. I'm close to going insane. Where do i put what kind of code to be able to execute something when i click each tab? Please dont say " you need to implement UITabBarDelegate and then use -void(didselectitem) " without explaining exactly how :) EDIT: My AppDelegate.h file: #import <UIKit/UIKit.h> @interface PETTAppDelegate : UIResponder <UIApplicationDelegate, UITabBarControllerDelegate, UITabBarDelegate> @property (strong, nonatomic) UIWindow *window; @end My AppDelegate.m file: @implementation PETTAppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions: (NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. NSBundle *appBundle = [NSBundle mainBundle]; PETTSoundBoardPage *sbP = [[PETTSoundBoardPage alloc]initWithNibName:@"PETTSoundBoardPage" bundle:appBundle]; PETTNPage * nP = [[PETTNPage alloc]initWithNibName:@"PETTNPage" bundle:appBundle]; UITabBarController *tBC = [[UITabBarController alloc]init]; tBC.tabBarController.delegate = self; tBC.viewControllers = @[sbP,nP]; self.window.rootViewController = tBC; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; return YES; } sbP and nP file (almost identical code except for title and picture): -(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if(self) { UITabBarItem *tbi = self.tabBarItem; tbi.title = @"Soundboard"; UIImage *i = [UIImage imageNamed:@"picture.png"]; tbi.image = i; tbi.tag = 0; A: Use the UITabBarControllerDelegate method, didSelectViewController:. I'm assuming that you have already prepared the sound playing method, so implement it as such in your AppDelegate. Of course, you have to add the UITabBarControllerDelegate to your interface as well by doing this: @interface AppDelegate : UIResponder <UIApplicationDelegate, UITabBarControllerDelegate> Add this code to your .m file of your app delegate. - (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController { //Play your sound here } Info here EDIT: You need to set your tabBarController's delegate to yourself. To do that do this: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. //get reference to your view controller, myViewController.tabBarController.delegate = self; return YES; }
doc_4642
Is this some property or a compiler malfunction? Code: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> void hi(int a[], int n) { a[n] = 3; n++; return; } int main() { int n = 2, i; int a[2] = { 1, 2 }; hi(a, n); printf("%d\n", n); return 0; } A: Array a has 2 elements : a[0] and a[1]. Function hi() receives a pointer to a, so it will change array a[] in the main(). Now, the local variables in main() are using consecutive memory location: a[0], a[1], n, i When you change a[2] in hi() you change what is just after a[1], so you change n in this case. If you swap declarations of n and i you will change i instead. This is by design of the compiler. Other compilers may order local variables otherwise. Also the C language does not check out-of-bound indices of passed-in arrays.
doc_4643
Preparing: IIf([tblCustomers!OrderId]=([tblCustomers!OrderId]+1) AND [tblCustomers!OrderStatus]="Preparing","Preparing","") This didn't work as I hoped, but I wasn't too surprised, as it would have to return data from the field initially tested. So, the argument that adds 1 is actually doing nothing. Is there a way to target the next record in the table, test if it matches one of two or three strings, then return which one it is? Edit: Following @mazoula's solution, it seems a correlated subquery is indeed the answer here. Following the guide on allenbrowne.com (linked by June7), I seemed to be on the right track. Here is my code for retrieving the status of a previous record: SELECT tblCustomers.AccountId, tblCustomers.OrderId, tblCustomers.OrderStatus, tblCustomers.OrderShipped, tblCustomers.OrderNotes, (SELECT TOP 1 Dupe.OrderStatus FROM tblCustomers AS Dupe WHERE Dupe.AccountId = tblCustomers.AccountId AND Dupe.OrderId > tblCustomers.OrderId ORDER BY Dupe.AccountId DESC, Dupe.OrderId) AS NextStatus FROM tblCustomers WHERE (((tblCustomers.OrderShipped)="N") AND ((tblCustomers.OrderNotes) Is Null)) ORDER BY tblCustomers.AccountId DESC; Unfortunately, I am met with the following error: At most one record can be returned by this subquery Doing a little more research, I found that incorporating an INNER JOIN expression should solve this. ... FROM tblCustomers INNER JOIN OrderStatus Dupe ON Dupe.AccountId = tblCustomers.AccountId WHERE ... This is where I've hit another roadblock and, when the syntax is at least correct, I receive the error: Join expression not supported. Is this a simple syntax issue, or have misunderstood the role of a Join expression? A: in Access 2016 I do this in two parts because access throws the error: must use an updateable query when I try to update based on a subquery. For instance, if I want to replace the Null Values in TableA.Field3 with 'a' if the next record's Field3 is 'a' tableA: ------------------------------------------------------------------------------------- | ID | Field1 | Field2 | Field3 | ------------------------------------------------------------------------------------- | 1 | a | 1 | | ------------------------------------------------------------------------------------- | 2 | b | 2 | | ------------------------------------------------------------------------------------- | 3 | c | 3 | a | ------------------------------------------------------------------------------------- | 4 | d | 4 | b | ------------------------------------------------------------------------------------- | 5 | e | 5 | | ------------------------------------------------------------------------------------- | 6 | f | 6 | b | ------------------------------------------------------------------------------------- I make a table on which to base the update query: Replacement: (SELECT TOP 1 Dupe.Field3 FROM [TableA] as Dupe WHERE Dupe.ID > [TableA].[ID]) 'SQL PANE' SELECT TableA.ID, TableA.Field1, TableA.Field2, TableA.Field3, (SELECT TOP 1 Dupe.Field3 FROM [TableA] as Dupe WHERE Dupe.ID > [TableA].[ID]) AS Replacement INTO TempTable FROM TableA; TempTable: ---------------------------------------------------------------------------------------------------------- | ID | Field1 | Field2 | Field3 | Replacement | ---------------------------------------------------------------------------------------------------------- | 1 | a | 1 | | | ---------------------------------------------------------------------------------------------------------- | 2 | b | 2 | | a | ---------------------------------------------------------------------------------------------------------- | 3 | c | 3 | a | b | ---------------------------------------------------------------------------------------------------------- | 4 | d | 4 | b | | ---------------------------------------------------------------------------------------------------------- | 5 | e | 5 | | b | ---------------------------------------------------------------------------------------------------------- | 6 | f | 6 | b | | ---------------------------------------------------------------------------------------------------------- Finally do the Update UPDATE TempTable INNER JOIN TableA ON TempTable.ID = TableA.ID SET TableA.Field3 = [TempTable].[Replacement] WHERE (((TempTable.Replacement)='a')); TableA after update ------------------------------------------------------------------------------------- | ID | Field1 | Field2 | Field3 | ------------------------------------------------------------------------------------- | 1 | a | 1 | | ------------------------------------------------------------------------------------- | 2 | b | 2 | a | ------------------------------------------------------------------------------------- | 3 | c | 3 | a | ------------------------------------------------------------------------------------- | 4 | d | 4 | b | ------------------------------------------------------------------------------------- | 5 | e | 5 | | ------------------------------------------------------------------------------------- | 6 | f | 6 | b | notes: In the Make Table query remember to sort TableA and Dupe in the same way. Here we use the default sort of increasing ID for TableA then grab the first record with a higher ID using the default sort again. the only reason I did the filtering to 'a' in the update query is it made the Make Table query simpler.
doc_4644
sqlite3 progressapp.db CREATE TABLE Z_Type(_Z_T_ID INTEGER PRIMARY KEY NOT NULL, Description TEXT NOT NULL, Unit TEXT NOT NULL); But now I want to refference the PK of T_Type in my other table: CREATE TABLE goals (_Z_id INTEGER PRIMARY KEY NOT NULL, Title TEXT NOT NULL, Type INTEGER NOT NULL, FOREIGN KEY(Type) REFERENCES Z_Type(_Z_T_ID), Timeframe TEXT, Goaldate INTEGER); Is Type INTEGER NOT NULL, FOREIGN KEY(Type) REFERENCES Z_Type(_Z_T_ID) a valid SQLite Statement in Android? It says "Error: near "Timeframe": syntax error" But I simply can't find it due to lack with SQL Experience I guess. Is there a better way to reference the FK maybe? A: Try this: CREATE TABLE goals (_Z_id INTEGER PRIMARY KEY NOT NULL, Title TEXT NOT NULL, Type INTEGER NOT NULL,Timeframe TEXT, Goaldate INTEGER, FOREIGN KEY(Type) REFERENCES Z_Type(_Z_T_ID)); I think that the order is important. For further documentation you could visit sqlite.org/foreignkeys.html A: You can define the reference as part of the column definition CREATE TABLE goals (_Z_id INTEGER PRIMARY KEY NOT NULL, Title TEXT NOT NULL, Type INTEGER NOT NULL REFERENCES Z_Type(_Z_T_ID), Timeframe TEXT, Goaldate INTEGER); A: In a sqlite CREATE TABLE statement, column definitions come first and table constraints only after that. FOREIGN KEY(Type) REFERENCES Z_Type(_Z_T_ID) is a table constraint that should go at the end.
doc_4645
Get a row data cv::Mat dst = src.row(); If I want to get data from column 4 to 1085, I do this way. for(int i = 0; i < 11000; i++) for(int j = 3; j < 1085; j++) dst.at<double>(i,j-3) = src.at<double>(i,j); Is there another way to do that faster? A: It depends if you want to make a deep copy of the data or not. You may want to construct a region of interest (ROI) as described on this helpful tutorial, which describes other methods to work with the cv::Mat to structure your data: http://docs.opencv.org/doc/tutorials/core/mat_the_basic_image_container/mat_the_basic_image_container.html To create a region of interest (ROI) for a rectangle: Mat Dst (src, Rect(3, 0, 11000, 1085) ); If you want copy the data: Mat Clone = Dst.clone(); A: You could use Mat::colRange cv::Mat dst = src.colRange(3, 1085);
doc_4646
But when I check the running container via bin/bash I cannot find /app directory in a container While building image no errors are being displayed This is my docker image file FROM node:15.7.0 as build-stage WORKDIR /app COPY package*.json /app/ RUN npm install COPY ./ /app/ ARG configuration=production RUN npm run build -- --output-path=./dist/out --configuration $configuration FROM nginx:1.18 COPY --from=build-stage /app/dist/out/ /usr/share/nginx/html COPY ./nginx-custom.conf /etc/nginx/conf.d/default.conf A: Sèdjro has the correct answer, but I wanted to expand on it briefly. You're using what is called a multi-stage build. If you haven't seen them already, the linked docs are a good read. Each FROM ... line in your Dockerfile starts a new build stage, and only the contents of the final stage are relevant to the generated Docker image. Other stages in the file are available as sources of the COPY --from=... directive. In other words, as soon as you add a second FROM ... line, as in... FROM node:15.7.0 as build-stage . . . FROM nginx:1.18 ...then the contents of the first stage are effectively discarded, unless you explicitly copy them into the final image using COPY --from=.... Your /app directory only exists in the first stage, since you're copying it into a different location in the final stage. A: The /app directory is not inside of your docker image. It's in your build stage image. Check the /usr/share/nginx/html directory or don't use build stage.
doc_4647
I have written a simple grammar using ANTLR plugin for Eclipse . Someone told me that there is something known as a method node on the AST generated by Antlr, and that has to be called. I am planning to use ASM to generate the bytecode. So what is the method node and How do I call it from ASM and make it visit method instructions? Also what about the semantic analyzer of a compiler. Should that be manually written or are there any generators for it? A: You ask many unrelated questions in here. Depending on the language you define, there may be a method node in your language or there won't be any, say, if your language compiles to a main(String[]) method unconditionally. There are multiple approaches to transform an AST to a target language. Mostly you would not generate code directly, but generate an AST for your target platform and have a pretty printer generate code out of it, using a treewalker. The semantic analysis is the programming of a compiler. Reading and understanding the input on a syntactically level is the parsing. You will need to write the semantic analyzer on your own or you would not have written a compiler at all. ;-) I presume you use Jasmin to compile the assembly code? A very good start would be writing grammars for your input language and the target language (Jasmin) and think about, which input structures would render what output. How would one write a for i := 1 to 10 loop in Jasmin? Tackle small problems and expand your compiler as needed, but slowly, testing newly implemented transformations early and thoroughly. A very good reading: Let's Build a Compiler, by Jack Crenshaw.
doc_4648
So now my folder structure looks like this: MyWebsite\ MyWebsite.sln bower.json gruntfile.js node_modules\ bower_components\ wwwroot\ app\ bower_components\ ... (all my other Angular files) I think the bower_components folder is now duplicated but I'm not really sure which one should be removed (and if I do, where should the bower.json be)? A: Normally you would put everything INSIDE the (relative to) www-root. Images in www-root/images, javascript in www-root/js, and so on. Or even inside www-root/app.
doc_4649
var value = [1,2,3]; What I'm trying to get: var newobject = {'unit1' : 1 'unit2': 2 'unit3' : 3}; How can I accomplish this? A: Assuming these are parallel arrays (the first entry in eenhedennamen uses the first entry in value), you can loop through with jQuery's $.each, which gives you the index and the entry for each entry, and build the object from the loop. var obj = {}; $.each(eenhedennamen, function(index, entry) { obj[entry] = value[index]; }); This works because in JavaScript, you can access properties using either dot notation and a property name literal (obj.foo = "bar"), or bracketed notation with a string property name (obj["foo"] = "bar"). In the latter case, the string can be the result of any expression. So in the above, we're using entry as the property name, which will be each name in eenhedennamen. Then of course, we get the corresponding value from value using the index. A: var eenhedennamen = [ 'unit1', 'unit2', 'unit3' ]; var value = [ 1, 2, 3 ]; var z = new Array(); for ( var i = 0; i < eenhedennamen.length; i++) { z[eenhedennamen[i]]=value[i]; } The previous answer is better. A: You can use Array.prototype.reduce Try this: var eenhedennamen = ['unit1', 'unit2', 'unit3']; var value = [1,2,3]; var arr3 = eenhedennamen.reduce(function(obj, val, i) { obj[val] = value[i]; return obj; }, {}); console.log(JSON.stringify(arr3)); Try in fiddle Reference
doc_4650
The right click menu seems to be called class = context menu, and the values are class = context_item (See attached screenshots) (html included also) I know that this part works, but the rest below it is having an issue - col = row.find_element(By.XPATH, '//a[contains(text() , "Luke Wilson")]') ### OUTPUT Traceback (most recent call last): File "C:\Users\AppData\Local\Programs\Python\Python36\ffox_Change_Create_Save_Stay_v2.py", line 182, in get_all_rows_approval() File "C:\Users\AppData\Local\Programs\Python\Python36\ffox_Change_Create_Save_Stay_v2.py", line 164, in get_all_rows_approval menu = col.find_element_by_class_name("context_menu") File "C:\Users\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webelement.py", line 398, in find_element_by_class_name return self.find_element(by=By.CLASS_NAME, value=name) File "C:\Users\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webelement.py", line 654, in find_element {"using": by, "value": value})['value'] File "C:\Users\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webelement.py", line 628, in _execute return self._parent.execute(command, params) File "C:\Users\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 320, in execute self.error_handler.check_response(response) File "C:\Users\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: .context_menu # Code snippet def get_all_rows_approval(): approval_table = driver.find_element(By.XPATH, '//*[@id="change_request.sysapproval_approver.sysapproval_table"]/tbody') rows = approval_table.find_elements(By.XPATH, "//*[contains(@id,'row_change_request.sysapproval_approver.sysapproval')]") for row in rows: col = row.find_element(By.XPATH, '//a[contains(text() , "Luke Wilson")]') menu = col.find_element_by_class_name("context_menu") actions = ActionChains(menu) actions.move_to_element(menu) actions.click(menu) actions.perform() #### html for the table <tbody class="list2_body"> <tr id="row_change_request.sysapproval_approver.sysapproval_30f168b2dbeb5300b58ad360cf961998" class="list_row list_odd" style="" sys_id="30f168b2dbeb5300b58ad360cf961998" record_class="sysapproval_approver" data-updated-on="2018-07-30 13:36:23" collapsed="true" data-type="list2_row" data-list_id="change_request.sysapproval_approver.sysapproval"> <td class="list_decoration_cell col-control col-small col-center " style="white-space:nowrap;" rowspan="1"><span class="input-group-checkbox"><input title="Mark record for List Action" id="check_change_request.sysapproval_approver.sysapproval_30f168b2dbeb5300b58ad360cf961998" name="check_change_request.sysapproval_approver.sysapproval" class="checkbox " data-type="list2_checkbox" data-list_id="change_request.sysapproval_approver.sysapproval" data-original-title="Mark record for List Action" type="checkbox"><label for="check_change_request.sysapproval_approver.sysapproval_30f168b2dbeb5300b58ad360cf961998" style="" class="checkbox-label"><span class="sr-only">Select record for action</span></label></span></td> <td class="list_decoration_cell col-small col-center " rowspan="1"><a href="sysapproval_approver.do?sys_id=30f168b2dbeb5300b58ad360cf961998&amp;sysparm_view=&amp;sysparm_record_target=task_ci&amp;sysparm_record_row=1&amp;sysparm_record_list=sysapproval%3De6d1ac72dbeb5300b58ad360cf96193e%5EORDERBYorder&amp;sysparm_record_rows=5" class="btn btn-icon table-btn-lg icon-info list_popup" data-type="list2_popup" data-list_id="change_request.sysapproval_approver.sysapproval" style="margin-left:0px"><span class="sr-only">Preview</span></a></td> <td class="vt" ng-non-bindable=""> <span class="sr-only"></span> <div class="list2_cell_background" style="background-color: khaki"></div> <a class="linked formlink" href="sysapproval_approver.do?sys_id=30f168b2dbeb5300b58ad360cf961998&amp;sysparm_record_target=sysapproval_approver&amp;sysparm_record_row=1&amp;sysparm_record_rows=5&amp;sysparm_record_list=sysapproval%3De6d1ac72dbeb5300b58ad360cf96193e%5EORDERBYorder">Requested</a> </td> <td class="vt" ng-non-bindable=""><a class="linked" sys_id="97000fcc0a0a0a6e0104ca999f619e5b" href="sys_user.do?sys_id=97000fcc0a0a0a6e0104ca999f619e5b">Christen Mitchell</a></td> <td class="vt" ng-non-bindable=""><a class="linked" sys_id="b85d44954a3623120004689b2d5dd60a" href="sys_user_group.do?sys_id=b85d44954a3623120004689b2d5dd60a">CAB Approval</a></td> <td class="vt" ng-non-bindable=""></td> <td class="vt" ng-non-bindable=""> <div class="datex date-calendar" title="" timeago="2018-07-30 13:36:23" timeago-attrs="title" data-original-title="5m ago">2018-07-30 06:36:23</div> <div class="datex date-calendar-short" title="just now" timeago="2018-07-30 13:36:23" timeago-attrs="title" data-original-title="5m ago">07-30 06:36</div> <div class="datex date-timeago" title="2018-07-30 06:36:23" timeago="2018-07-30 13:36:23" data-original-title="2018-07-30 06:36:23" null="5m ago">5m ago</div> </td> <td class="vt vt-spacer" style="padding: 0"></td> </tr> <tr id="row_change_request.sysapproval_approver.sysapproval_34f168b2dbeb5300b58ad360cf961997" class="list_row list_even" style="" sys_id="34f168b2dbeb5300b58ad360cf961997" record_class="sysapproval_approver" data-updated-on="2018-07-30 13:36:23" collapsed="true" data-type="list2_row" data-list_id="change_request.sysapproval_approver.sysapproval"> <td class="list_decoration_cell col-control col-small col-center " style="white-space:nowrap;" rowspan="1"><span class="input-group-checkbox"><input title="Mark record for List Action" id="check_change_request.sysapproval_approver.sysapproval_34f168b2dbeb5300b58ad360cf961997" name="check_change_request.sysapproval_approver.sysapproval" class="checkbox " data-type="list2_checkbox" data-list_id="change_request.sysapproval_approver.sysapproval" data-original-title="Mark record for List Action" type="checkbox"><label for="check_change_request.sysapproval_approver.sysapproval_34f168b2dbeb5300b58ad360cf961997" style="" class="checkbox-label"><span class="sr-only">Select record for action</span></label></span></td> <td class="list_decoration_cell col-small col-center " rowspan="1"><a href="sysapproval_approver.do?sys_id=34f168b2dbeb5300b58ad360cf961997&amp;sysparm_view=&amp;sysparm_record_target=sysapproval_approver&amp;sysparm_record_row=2&amp;sysparm_record_list=sysapproval%3De6d1ac72dbeb5300b58ad360cf96193e%5EORDERBYorder&amp;sysparm_record_rows=5" class="btn btn-icon table-btn-lg icon-info list_popup" data-type="list2_popup" data-list_id="change_request.sysapproval_approver.sysapproval" style="margin-left:0px"><span class="sr-only">Preview</span></a></td> <td class="vt" ng-non-bindable=""> <span class="sr-only"></span> <div class="list2_cell_background" style="background-color: khaki"></div> <a class="linked formlink" href="sysapproval_approver.do?sys_id=34f168b2dbeb5300b58ad360cf961997&amp;sysparm_record_target=sysapproval_approver&amp;sysparm_record_row=2&amp;sysparm_record_rows=5&amp;sysparm_record_list=sysapproval%3De6d1ac72dbeb5300b58ad360cf96193e%5EORDERBYorder">Requested</a> </td> <td class="vt" ng-non-bindable=""><a class="linked" sys_id="46d96f57a9fe198101947a9620895886" href="sys_user.do?sys_id=46d96f57a9fe198101947a9620895886">Luke Wilson</a></td> <td class="vt" ng-non-bindable=""><a class="linked" sys_id="b85d44954a3623120004689b2d5dd60a" href="sys_user_group.do?sys_id=b85d44954a3623120004689b2d5dd60a">CAB Approval</a></td> <td class="vt" ng-non-bindable=""></td> <td class="vt" ng-non-bindable=""> <div class="datex date-calendar" title="" timeago="2018-07-30 13:36:23" timeago-attrs="title" data-original-title="5m ago">2018-07-30 06:36:23</div> <div class="datex date-calendar-short" title="just now" timeago="2018-07-30 13:36:23" timeago-attrs="title" data-original-title="5m ago">07-30 06:36</div> <div class="datex date-timeago" title="2018-07-30 06:36:23" timeago="2018-07-30 13:36:23" data-original-title="2018-07-30 06:36:23" null="5m ago">5m ago</div> </td> <td class="vt vt-spacer" style="padding: 0"></td> </tr> <tr id="row_change_request.sysapproval_approver.sysapproval_b4f168b2dbeb5300b58ad360cf961998" class="list_row list_odd" style="" sys_id="b4f168b2dbeb5300b58ad360cf961998" record_class="sysapproval_approver" data-updated-on="2018-07-30 13:36:23" collapsed="true" data-type="list2_row" data-list_id="change_request.sysapproval_approver.sysapproval"> <td class="list_decoration_cell col-control col-small col-center " style="white-space:nowrap;" rowspan="1"><span class="input-group-checkbox"><input title="Mark record for List Action" id="check_change_request.sysapproval_approver.sysapproval_b4f168b2dbeb5300b58ad360cf961998" name="check_change_request.sysapproval_approver.sysapproval" class="checkbox " data-type="list2_checkbox" data-list_id="change_request.sysapproval_approver.sysapproval" data-original-title="Mark record for List Action" type="checkbox"><label for="check_change_request.sysapproval_approver.sysapproval_b4f168b2dbeb5300b58ad360cf961998" style="" class="checkbox-label"><span class="sr-only">Select record for action</span></label></span></td> <td class="list_decoration_cell col-small col-center " rowspan="1"><a href="sysapproval_approver.do?sys_id=b4f168b2dbeb5300b58ad360cf961998&amp;sysparm_view=&amp;sysparm_record_target=sysapproval_approver&amp;sysparm_record_row=3&amp;sysparm_record_list=sysapproval%3De6d1ac72dbeb5300b58ad360cf96193e%5EORDERBYorder&amp;sysparm_record_rows=5" class="btn btn-icon table-btn-lg icon-info list_popup" data-type="list2_popup" data-list_id="change_request.sysapproval_approver.sysapproval" style="margin-left:0px"><span class="sr-only">Preview</span></a></td> <td class="vt" ng-non-bindable=""> <span class="sr-only"></span> <div class="list2_cell_background" style="background-color: khaki"></div> <a class="linked formlink" href="sysapproval_approver.do?sys_id=b4f168b2dbeb5300b58ad360cf961998&amp;sysparm_record_target=sysapproval_approver&amp;sysparm_record_row=3&amp;sysparm_record_rows=5&amp;sysparm_record_list=sysapproval%3De6d1ac72dbeb5300b58ad360cf96193e%5EORDERBYorder">Requested</a> </td> <td class="vt" ng-non-bindable=""><a class="linked" sys_id="ee826bf03710200044e0bfc8bcbe5de6" href="sys_user.do?sys_id=ee826bf03710200044e0bfc8bcbe5de6">Bernard Laboy</a></td> <td class="vt" ng-non-bindable=""><a class="linked" sys_id="b85d44954a3623120004689b2d5dd60a" href="sys_user_group.do?sys_id=b85d44954a3623120004689b2d5dd60a">CAB Approval</a></td> <td class="vt" ng-non-bindable=""></td> <td class="vt" ng-non-bindable=""> <div class="datex date-calendar" title="" timeago="2018-07-30 13:36:23" timeago-attrs="title" data-original-title="5m ago">2018-07-30 06:36:23</div> <div class="datex date-calendar-short" title="just now" timeago="2018-07-30 13:36:23" timeago-attrs="title" data-original-title="5m ago">07-30 06:36</div> <div class="datex date-timeago" title="2018-07-30 06:36:23" timeago="2018-07-30 13:36:23" data-original-title="2018-07-30 06:36:23" null="5m ago">5m ago</div> </td> <td class="vt vt-spacer" style="padding: 0"></td> </tr> <tr id="row_change_request.sysapproval_approver.sysapproval_b8f168b2dbeb5300b58ad360cf961997" class="list_row list_even" style="" sys_id="b8f168b2dbeb5300b58ad360cf961997" record_class="sysapproval_approver" data-updated-on="2018-07-30 13:36:23" collapsed="true" data-type="list2_row" data-list_id="change_request.sysapproval_approver.sysapproval"> <td class="list_decoration_cell col-control col-small col-center " style="white-space:nowrap;" rowspan="1"><span class="input-group-checkbox"><input title="Mark record for List Action" id="check_change_request.sysapproval_approver.sysapproval_b8f168b2dbeb5300b58ad360cf961997" name="check_change_request.sysapproval_approver.sysapproval" class="checkbox " data-type="list2_checkbox" data-list_id="change_request.sysapproval_approver.sysapproval" data-original-title="Mark record for List Action" type="checkbox"><label for="check_change_request.sysapproval_approver.sysapproval_b8f168b2dbeb5300b58ad360cf961997" style="" class="checkbox-label"><span class="sr-only">Select record for action</span></label></span></td> <td class="list_decoration_cell col-small col-center " rowspan="1"><a href="sysapproval_approver.do?sys_id=b8f168b2dbeb5300b58ad360cf961997&amp;sysparm_view=&amp;sysparm_record_target=sysapproval_approver&amp;sysparm_record_row=4&amp;sysparm_record_list=sysapproval%3De6d1ac72dbeb5300b58ad360cf96193e%5EORDERBYorder&amp;sysparm_record_rows=5" class="btn btn-icon table-btn-lg icon-info list_popup" data-type="list2_popup" data-list_id="change_request.sysapproval_approver.sysapproval" style="margin-left:0px"><span class="sr-only">Preview</span></a></td> <td class="vt" ng-non-bindable=""> <span class="sr-only"></span> <div class="list2_cell_background" style="background-color: khaki"></div> <a class="linked formlink" href="sysapproval_approver.do?sys_id=b8f168b2dbeb5300b58ad360cf961997&amp;sysparm_record_target=sysapproval_approver&amp;sysparm_record_row=4&amp;sysparm_record_rows=5&amp;sysparm_record_list=sysapproval%3De6d1ac72dbeb5300b58ad360cf96193e%5EORDERBYorder">Requested</a> </td> <td class="vt" ng-non-bindable=""><a class="linked" sys_id="62d78687c0a8010e00b3d84178adc913" href="sys_user.do?sys_id=62d78687c0a8010e00b3d84178adc913">Ron Kettering</a></td> <td class="vt" ng-non-bindable=""><a class="linked" sys_id="b85d44954a3623120004689b2d5dd60a" href="sys_user_group.do?sys_id=b85d44954a3623120004689b2d5dd60a">CAB Approval</a></td> <td class="vt" ng-non-bindable=""></td> <td class="vt" ng-non-bindable=""> <div class="datex date-calendar" title="just now" timeago="2018-07-30 13:36:23" timeago-attrs="title" data-original-title="5m ago">2018-07-30 06:36:23</div> <div class="datex date-calendar-short" title="just now" timeago="2018-07-30 13:36:23" timeago-attrs="title" data-original-title="5m ago">07-30 06:36</div> <div class="datex date-timeago" title="2018-07-30 06:36:23" timeago="2018-07-30 13:36:23" data-original-title="2018-07-30 06:36:23" null="5m ago">5m ago</div> </td> <td class="vt vt-spacer" style="padding: 0"></td> </tr> </tbody> </table> <a id="change_request.sysapproval_approver.sysapproval_bottom" href="javascript:function(evt){if(evt){evt.stopPropagation();}}"><span class="sr-only">Bottom of table</span></a> </div> </td> </tr> </tbody> </table> </html> A: Note that click() will not do right click, it is context_click() If you want to right click on based on name, then you can use this code : ActionChains(driver).context_click(driver.find_element_by_xpath("//a[text()='Luke Wilson']").perform() You can try with this also : action = ActionChains(driver) action.move_to_element(driver.find_element_by_xpath("//a[text()='Luke Wilson']")).perform(); action.context_click().perform()
doc_4651
select count(code) from table1 It works well on the local system but becomes very slow on the network. Other queries like select * from table execute quickly, but select count(code) from table1 is very slow. I can't change the database's structure. My database is Foxpro and I use VB.NET. Is there a solution? Edit: Should I write code like this? dim ds as new dataset dim da as new datadapter("select count(*) from table ", connection) da.fill(ds,"tbl1") Then how can I get select count(code) from table1 from the dataset? Or do I have to use LINQ? Edit 2: I mean the comparison between select count(*) and select count(code). What is the solution? A: It will be faster to do select count(*) from table1 then to use count(code). A: The select count(code) selects the column 'code' from the table, and then counts them, but select * just selects them, but does not do the count. So if you are comparing these two then logically select * is fast. For my table which has more than 1,000,000 records the execution time is: select * = 0.9818625 select count(column_name) = 1.571275
doc_4652
This is the code in the controller: public function addAppointment(Request $request) { $user = auth()->user(); $booking = new Booking(); $booking->vac_center_id = $request->get('vaccination_center'); $booking->vac_id = $request->get('vaccination_id'); $booking->date_of_shot = $request->get('date_of_shot'); $booking->time = $request->get('time'); $booking->shot_number = $request->get('shot_number'); $booking->isDone = 0; $booking->isCancelled = 0; $booking->user_id = $user->id; $booking->save(); $booking = new BookingHasVaccinationCenters(); //here below I want to get the auto increment id $booking->booking_id->id; $booking->vac_center_id = $request->get('vaccination_center'); $booking->save(); return redirect('/home'); } This is the error that I had last time when I try to do this: Attempt to read property "id" on null A: instead of this $booking = new BookingHasVaccinationCenters(); //here below I want to get the auto increment id $booking->booking_id->id; $booking->vac_center_id = $request->get('vaccination_center'); $booking->save(); use below code $bookingHasVaccination = new BookingHasVaccinationCenters(); //change here $bookingHasVaccination->booking_id = $booking->id; $bookingHasVaccination->vac_center_id = $request->get('vaccination_center'); $bookingHasVaccination->save(); Note : always try to define variable with the name same as model class while crud operations A: Your error is that you declare with the same name the variable $booking , when you save the $booking you should declare a instance of object with other name for example $bookingvaccine->booking_id = $booking->id; A: I know your questions has already been answered, but let me share another way of doing what you are doing, so you prevent this errors and your code is better. If you have relations between this tables/models (relations functions created) then you can use the relation to create new models between them, without the need of sharing or passing the parent model's ID. Assuming your User's relation name with Booking is bookings and for Booking -> BookingHasVaccinationCenters relation (strange name) is bookingHasVaccinationCenters, you should be able to do this: public function addAppointment(Request $request) { $booking = $request->user() ->booking() ->create([ 'vac_center_id' => $request->input('vaccination_center'), 'vac_id' => $request->input('vaccination_id'), 'date_of_shot' => $request->input('date_of_shot'), 'time' => $request->input('time'), 'shot_number' => $request->input('shot_number'), 'isDone' => false, 'isCancelled' => false, ]); $booking->bookingHasVaccinationCenters()->create([ 'vac_center_id' => $request->input('vaccination_center'), ]); return redirect('/home'); } Another super small tip, remember to cast isDone and isCancelled to boolean, so you can use those fields as boolean so you can do true or false instead of 1 or 0. And last tip, try to always stick to the Laravel's conventions: snake_case column names, isDone and isCancelled should be is_done and is_cancelled.
doc_4653
Response: responseCode: 400, graphObject: null, error: {HttpStatus: 400, errorCode: 15, errorType: OAuthException, errorMessage: (#15) Requires session when calling from a desktop app}, isFromCache:false} My steps: 1) get access token via https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=[APP_ID]&client_secret=[APP_SECRET] 2) create instance of AccessToken class: AccessToken token = AccessToken.createFromExistingAccessToken([TOKEN_FROM_STEP1], new Date(2015,3,2), new Date(), null, permissions); 3) open new session session = Session.openActiveSessionWithAccessToken(this, token, callback); 4) and make request: new Request(session, "/[PUBLIC_PAGE_ID]/feed", null, HttpMethod.GET, new Request.Callback() { public void onCompleted(Response response) { //check response } }).executeAsync(); Where is mistake? What is the right way? The "Native or Desktop app" setting is disabled for this app.
doc_4654
I am using Volley to send a JSON POST request to the .NET service (TODO CRUD) based on https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api When I run my application and click the add button to send the request nothing seems to happen. When I am running the Android Studio debugger on the application I get the following message in the debug tab: D/Volley: [385] WaitingRequestManager.maybeAddToWaitingRequests: new request, sending to network 1-http://localhost:5189/api/TodoItems I/Choreographer: Skipped 446 frames! The application may be doing too much work on its main thread. I/OpenGLRenderer: Davey! duration=7453ms; Flags=0, IntendedVsync=2170633487240, Vsync=2178066820276, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=2178072087746, AnimationStart=2178072102538, PerformTraversalsStart=2178074784371, DrawStart=2178077250746, SyncQueued=2178083361329, SyncStart=2178083687746, IssueDrawCommandsStart=2178083730038, SwapBuffers=2178084406954, FrameCompleted=2178087638788, DequeueBufferDuration=92125, QueueBufferDuration=115083, GpuCompleted=-647501342139744405, D/CompatibilityChangeReporter: Compat change id reported: 147798919; UID 10155; state: ENABLED D/Volley: [2] MarkerLog.finish: (36 ms) [ ] http://localhost:5189/api/TodoItems 0xb8332793 NORMAL 1 D/Volley: [2] MarkerLog.finish: (+0 ) [ 2] add-to-queue D/Volley: [2] MarkerLog.finish: (+1 ) [385] cache-queue-take D/Volley: [2] MarkerLog.finish: (+0 ) [385] cache-miss D/Volley: [2] MarkerLog.finish: (+4 ) [387] network-queue-take D/Volley: [2] MarkerLog.finish: (+27 ) [387] post-error D/Volley: [2] MarkerLog.finish: (+4 ) [ 2] done Here is what logcat reports on Volley: 2022-07-17 14:13:17.390 9044-9077/com.example.programming.todocrud V/Volley: [391] CacheDispatcher.run: start new dispatcher 2022-07-17 14:13:17.392 9044-9077/com.example.programming.todocrud D/Volley: [391] WaitingRequestManager.maybeAddToWaitingRequests: new request, sending to network 1-http://localhost:5189/api/TodoItems 2022-07-17 14:13:17.399 9044-9044/com.example.programming.todocrud D/Volley: [2] MarkerLog.finish: (7 ms) [ ] http://localhost:5189/api/TodoItems 0xb8332793 NORMAL 1 2022-07-17 14:13:17.399 9044-9044/com.example.programming.todocrud D/Volley: [2] MarkerLog.finish: (+0 ) [ 2] add-to-queue 2022-07-17 14:13:17.400 9044-9044/com.example.programming.todocrud D/Volley: [2] MarkerLog.finish: (+0 ) [391] cache-queue-take 2022-07-17 14:13:17.400 9044-9044/com.example.programming.todocrud D/Volley: [2] MarkerLog.finish: (+0 ) [391] cache-miss 2022-07-17 14:13:17.401 9044-9044/com.example.programming.todocrud D/Volley: [2] MarkerLog.finish: (+1 ) [394] network-queue-take 2022-07-17 14:13:17.401 9044-9044/com.example.programming.todocrud D/Volley: [2] MarkerLog.finish: (+4 ) [394] post-error 2022-07-17 14:13:17.401 9044-9044/com.example.programming.todocrud D/Volley: [2] MarkerLog.finish: (+2 ) [ 2] done I don't have anymore information to work on other than this. I tried to check on Wireshark but it seems that the error is happening on the app and does no message is sent to network interface. Here is the code, where I am using Volley to send out the POST request: addButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String textVal = todoInputText.getText().toString(); try { RequestQueue queue = Volley.newRequestQueue(MainActivity.this); //String url = "https://localhost:7009/api/TodoItems"; String url = "http://localhost:5189/api/TodoItems"; JSONObject jsonBody = new JSONObject(); jsonBody.put("id", 0); jsonBody.put("name", textVal); jsonBody.put("isComplete", false); final String requestBody = jsonBody.toString(); StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // response Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // error Toast.makeText(MainActivity.this, "That didn't work!", Toast.LENGTH_LONG); } } ) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("id", "0"); params.put("name", textVal); params.put("isComplete", "false"); return params; } }; // Add the request to the RequestQueue. queue.add(stringRequest); } catch (JSONException je) { je.printStackTrace(); } } }); None of this code is very complicated and I feel that the issue is something very simple but not sure where to look. I would like to know what else I can do to debug this issue? Thank you!
doc_4655
function input_text($elem, $val) { print '<input type = "test" name="' . $elem .'" val="'; print htmlentities($val[elem]) . '"/>'; I m confused about the code: name="' . $elem .'" val="'; print htmlentities($val[elem]) . '"/>' 1) why put single quotes and dot inside double quotes around $elem? Can i just use double quotes like name="$elem". 2) what is the meaning of these code: val="'; print htmlentities($val[elem]) . '"/>' A: The single quotes in this case denote a string in PHP. $var = 'This is a String'; The reason they are used in conjunction with the double quotes is because the double quotes must be printed to get the correct HTML output of <input type="test" name="someName" val="someValue" /> The . operator in PHP is the concatenation operator meaning combine 2 strings into 1. $var = 'This' . ' and that'; //Evaluates to 'This and that' A: 1) Since the string being printed is surrounded with single quotes, variables are not expanded inside it; variables are only expanded inside double-quoted strings. So concatenation is necessary. If you change it to use double quotes, you could do variable interpolation: print "<input type='test' name='$elem' val='"; 2) There's no special meaning to it. The programmer simply chose to split up the commands to print this piece of HTML into two PHP print statements. So first he prints val=", then he prints htmlentities($val[elem]) . "">>' The function could be rewritten as: function input_text($elem, $val) { print "<input type='test' name='$elem' val='" . htmlentities($val[elem]) . "'/>"; } You have to use concatenation around htmlentities() -- only variables can be interpolated into strings, not function calls. However, you could assign the value to a variable first if you want: function input_text($elem, $val) { $valent = htmlentities($val[elem]); print "<input type='test' name='$elem' val='$valent'/>"; } BTW, $val[elem] looks like a typo, it probably should be $val[$elem].
doc_4656
i get the following equations V1 V2 V3 V4 V5 r1 1 0 1.9321781 0.21719257 -0.002287466 r2 0 1 0.0695936 -0.01783993 -0.001467253 I now want to be able to mainpulate the 1 & 0 coefficients and place them under the variable i choose, i understand that this will get me different results, however, i want to test the effect i did some reading and got that i should be using cajorls function where i should place a matrix incluing my restrictions but i cant make it work can someone show me an example of the matrix i should be using ? and in the matrix, some variables will have 1 and 0 coefficients, but others should be free for the model estimation, how can i make a matrix for this purpose ?? thanks
doc_4657
I cannot have a list with a detail view and multiple selections on macOS. In more detail: For demonstration purposes of my issue, I made a small example project. The UI looks as follows: This is the "app" when launched, with a list on top and a detail representation below. Because I am using the List's initialiser init(_:selection:rowContent:), where selection is of type Binding<SelectionValue?>? according to Apple's documentation, I get selecting items with the keyboard arrow keys for free. Here's the complete code: import SwiftUI @main struct UseCurorsInLisstApp: App { var body: some Scene { WindowGroup { ContentView() .environmentObject(ViewModel()) } } } class ViewModel: ObservableObject { @Published var items = [Item(), Item(), Item(), Item(), Item()] @Published var selectedItem: Item? = nil } struct Item: Identifiable, Hashable { let id = UUID() } struct ContentView: View { @EnvironmentObject var vm: ViewModel var body: some View { VStack { List(vm.items, id: \.self, selection: $vm.selectedItem) { item in VStack { Text("Item \(item.id.uuidString)") Divider() } } Divider() Group { if let item = vm.selectedItem { Text("Detail item \(item.id.uuidString)") } else { Text("No selection…") } } .frame(minHeight: 200.0, maxHeight: .infinity) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } Now, having had success with this so far, I figured being able to select more than one row would be useful, so I took a closer look into List(_:selection:rowContent:), where selection is of type Binding<Set<SelectionValue>>?. To be able to have a detail view, I just made a few minor changes to the ViewModel: class ViewModel: ObservableObject { @Published var items = [Item(), Item(), Item(), Item(), Item()] @Published var selectedItem: Item? = nil @Published var selectedItems: Set<Item>? = nil { didSet { if selectedItems?.count == 1, let item = selectedItems?.first { selectedItem = item } } } } and the ContentView: struct ContentView: View { @EnvironmentObject var vm: ViewModel var body: some View { VStack { List(vm.items, id: \.self, selection: $vm.selectedItems) { item in VStack { Text("Item \(item.id.uuidString)") Divider() } } Divider() Group { if vm.selectedItems?.count == 1, let item = vm.selectedItems?.first { Text("Detail item \(item.id.uuidString)") } else { Text("No or multiple selection…") } } .frame(minHeight: 200.0, maxHeight: .infinity) } } } The problem now is that I cannot select an item of the row any more, neither by clicking, nor by arrow keys. Is this a limitation I am running into or am I "holding it wrong"? A: Use the button and insert it into the set. Keyboard selection also works with shift + (up/down arrow) class ViewModel: ObservableObject { @Published var items = [Item(), Item(), Item(), Item(), Item()] @Published var selectedItem: Item? = nil @Published var selectedItems: Set<Item> = [] } struct ContentView: View { @EnvironmentObject var vm: ViewModel var body: some View { VStack { List(vm.items, id: \.self, selection: $vm.selectedItems) { item in Button { vm.selectedItem = item vm.selectedItems.insert(item) } label: { VStack { Text("Item \(item.id.uuidString)") Divider() } } .buttonStyle(PlainButtonStyle()) } Divider() Group { if let item = vm.selectedItem { Text("Detail item \(item.id.uuidString)") } else { Text("No or multiple selection…") } } .frame(minHeight: 200.0, maxHeight: .infinity) } } } Add remove: Button { vm.selectedItem = item if vm.selectedItems.contains(item) { vm.selectedItems.remove(item) } else { vm.selectedItems.insert(item) } } Edit In simple need to give a blank default value to set. because in nil it will never append to set need initialization. @Published var selectedItems: Set<Item> = [] { A: Actually my error was pretty dumb – making the selectedItems-set optional prevents the list from working correctly. Shoutout to @Raja Kishan, who pushed me into the right direction with his proposal. Here's the complete working code: import SwiftUI @main struct UseCurorsInLisstApp: App { var body: some Scene { WindowGroup { ContentView() .environmentObject(ViewModel()) } } } class ViewModel: ObservableObject { @Published var items = [Item(), Item(), Item(), Item(), Item()] @Published var selectedItems = Set<Item>() } struct Item: Identifiable, Hashable { let id = UUID() } struct ContentView: View { @EnvironmentObject var vm: ViewModel var body: some View { VStack { List(vm.items, id: \.self, selection: $vm.selectedItems) { item in VStack { Text("Item \(item.id.uuidString)") Divider() } } Divider() Group { if vm.selectedItems.count == 1, let item = vm.selectedItems.first { Text("Detail item \(item.id.uuidString)") } else { Text("No or multiple selection…") } } .frame(minHeight: 200.0, maxHeight: .infinity) } } }
doc_4658
So i check my system variables, the ANDROID_HOME is exist. Anyone who knows how to solve this problem? A: Please once check your environmental variable path and android studio SDK path should be same. Consider this case, If you are having two SDK folders one is target to Android studio another one for environmental variable, At the time this kind of problems may occur. Any way once reset both places path (i.e Android Studio, Environmental Variable) properly then restart PC and check. for setting ANDROID_HOME Follow this link A: for windows: set ANDROID_HOME=C:\\android-sdk-windows set PATH=%PATH%;%ANDROID_HOME%\tools;%ANDROID_HOME%\platform-tools
doc_4659
timestamp Status 05-01-2020 12:07:08 0 05-01-2020 12:36:05 1 05-01-2020 23:45:02 0 05-01-2020 13:44:33 1 06-01-2020 01:07:08 1 06-01-2020 10:23:05 1 06-01-2020 12:11:08 1 06-01-2020 22:06:12 1 07-01-2020 00:01:05 0 07-01-2020 02:17:09 1 07-01-2020 12:36:05 1 07-01-2020 12:07:08 1 07-01-2020 12:36:05 1 07-01-2020 12:36:05 0 08-01-2020 12:36:05 1 08-01-2020 12:36:05 0 08-01-2020 12:36:05 0 09-01-2020 12:36:05 1 09-01-2020 12:07:08 0 09-01-2020 12:36:05 1 11-01-2020 12:07:08 0 11-01-2020 12:36:05 1 The first condition in ifelse is not working. Is it because of me trying to use lag in shift function? Here is my code. df[, difference := ifelse((df$Status == 0 & shift(df$Status,type='lag') == 1) & (as.Date(df$timestamp) != shift(as.Date(df$timestamp),type = 'lag')), as.numeric(df$timestamp - as.POSIXct(paste0(as.Date(timestamp)," ","00:00:00"),tz="UTC"),units='mins'),ifelse((df$Status == 1 & shift(df$Status,type='lead') == 0) & as.Date(df$timestamp) != shift(as.Date(df$timestamp),type = 'lead'),as.numeric(as.POSIXct(paste0(as.Date(timestamp)," ","23:59:59"),tz="UTC") - df$timestamp,units='mins'), as.numeric(shift(df$timestamp,type = 'lead') - df$timestamp,units='mins')))] A: We could first consider to create the 'date' column by specifying the correct format library(data.table) setDT(df)[, date := as.IDate(timestamp, "%m-%d-%Y")] df[, timestamp := as.POSIXct(timestamp, format = "%m-%d-%Y %H:%M:%S")] then, create the ifelse or fifelse, make sure the NA from shift is changed by making use of fill df[, i1 := Status == 0 & shift(Status, fill = first(Status)) == 1] df[, i2 := date != shift(date, fill = first(date))] df[, i3 := Status == 0 & shift(Status, fill = last(Status), type = 'lead') == 0] df[, i4 := date != shift(date, fill = last(date), type = 'lead')] and then use the fifelse/ifelse df[, difference := fifelse(i1 &i2, as.numeric(difftime(timestamp, as.POSIXct(date), units = 'mins')), fifelse(i3 & i4, as.numeric(difftime(as.POSIXct(paste(date, "23:59:59"),tz="UTC"), timestamp, units = 'mins')), as.numeric(difftime(shift(timestamp, type = 'lead', fill = last(timestamp)), timestamp, units = 'mins')))) ] data df <- structure(list(timestamp = c("05-01-2020 12:07:08", "05-01-2020 12:36:05", "05-01-2020 23:45:02", "05-01-2020 13:44:33", "06-01-2020 01:07:08", "06-01-2020 10:23:05", "06-01-2020 12:11:08", "06-01-2020 22:06:12", "07-01-2020 00:01:05", "07-01-2020 02:17:09", "07-01-2020 12:36:05", "07-01-2020 12:07:08", "07-01-2020 12:36:05", "07-01-2020 12:36:05", "08-01-2020 12:36:05", "08-01-2020 12:36:05", "08-01-2020 12:36:05", "09-01-2020 12:36:05", "09-01-2020 12:07:08", "09-01-2020 12:36:05", "11-01-2020 12:07:08", "11-01-2020 12:36:05"), Status = c(0L, 1L, 0L, 1L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L, 0L, 1L, 0L, 0L, 1L, 0L, 1L, 0L, 1L)), class = "data.frame", row.names = c(NA, -22L))
doc_4660
1.) curl -L http://cpanel.net/showip.cgi (shows my ip address on the server for use on the verify.cpanel.net script), this can be verified also here... (http://verify.cpanel.net/index.cgi?ip=xxx.xxx.xxx.xx) (I don't like showing my IP, but trust me it was verified.) 2.) /usr/local/cpanel/cpkeyclt Updating cPanel license...Done. Update Failed! Error message: A License check appears to already be running. Building global cache for cpanel...Done So the above didn't work. I then tried these commands. 3.) /usr/local/cpanel/etc/init/stopcpsrvd and then /usr/local/cpanel/scripts/upcp --sync to attempt to resynchronize. This appears to successfully run but I still get the same error. Attached below is the error message I get when I attempt to login to WHM. 4.) I then tried running rdate -s rdate.cpanel.net as suggested in some other posts to have the times match up and then when I run (/usr/local/cpanel/cpkeyclt) it seems to time out and nothing ever happens. Looking at the logs for the cpanel license (/usr/local/cpanel/logs/license_log) I see this. Tue Jul 26 16:23:30 2016: Trying server 208.74.125.22 Tue Jul 26 16:23:45 2016: Timed out while connecting to port 2089 Tue Jul 26 16:24:00 2016: Timed out while connecting to port 80 Tue Jul 26 16:24:15 2016: Timed out while connecting to port 110 Tue Jul 26 16:24:30 2016: Timed out while connecting to port 143 Tue Jul 26 16:24:45 2016: Timed out while connecting to port 25 Tue Jul 26 16:25:00 2016: Timed out while connecting to port 23 Tue Jul 26 16:25:15 2016: Timed out while connecting to port 993 Tue Jul 26 16:25:30 2016: Timed out while connecting to port 995 Tue Jul 26 16:30:14 2016: License Update Request Tue Jul 26 16:30:14 2016: Using full manual DNS resolution Tue Jul 26 16:30:14 2016: Trying server 208.74.121.85 Tue Jul 26 16:30:29 2016: Timed out while connecting to port 2089 Any help is appreciated! Notes Results of running /usr/local/cpanel/etc/init/stopcpsrvd /usr/local/cpanel/etc/init/stopcpsrvd Waiting for “cpsrvd” to stop ……Gracefully Terminating processes: cpsrvd: with pids 20842 and owner root.......waited 1 second(s) for 1 process(es) to terminate....Done …finished. Startup Log Starting PID 20839: /usr/local/cpanel/libexec/cpsrvd-dormant Results of running /usr/local/cpanel/scripts/upcp –sync (Couldn't show everything because of text character limitations) [2016-07-26 15:39:39 -0400] Detected cron=0 (Terminal detected) ---------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------- => Log opened from cPanel Update (upcp) - Slave (21620) at Tue Jul 26 15:41:53 2016 [2016-07-26 15:41:53 -0400] Maintenance completed successfully [2016-07-26 15:41:54 -0400] 95% complete [2016-07-26 15:41:54 -0400] Running Standardized hooks [2016-07-26 15:41:54 -0400] 100% complete [2016-07-26 15:41:54 -0400] [2016-07-26 15:41:54 -0400] cPanel update completed [2016-07-26 15:41:54 -0400] A log of this update is available at /var/cpanel/updatelogs/update.1469561979.log [2016-07-26 15:41:54 -0400] Removing upcp pidfile [2016-07-26 15:41:54 -0400] [2016-07-26 15:41:54 -0400] Completed all updates => Log closed Tue Jul 26 15:41:54 2016 A: It turns out the answer was IPTables. Before that it was the rDate command that was necessary to fix it, but my IPTables was blocking the connections. To temporarily disable your firewall do this. iptables-save > /root/current.ipt iptables -P INPUT ACCEPT; iptables -P OUTPUT ACCEPT iptables -F INPUT; iptables -F OUTPUT ping -c 3 google.com iptables-restore < /root/current.ipt rm -f /root/current.ipt The first command saves a copy of your firewall settings. The next 2 commands make it so all input/output are allowed (for outgoing and incoming connections) Finally test by pinging the ip address that was giving the issue for cPanel in your log file. If it works that means the update license command will work. Simply run: /usr/local/cpanel/cpkeyclt and you are good to go. You can restore back your rules by using the last 2 commands if you want: iptables-restore < /root/current.ipt rm -f /root/current.ipt Be warned that you will be blocked again, unless you fix the firewall.
doc_4661
Style url: mapbox://styles/gustavsvensson/cin1hwd9a00bncznomsx507se A: You'll need to get your Mapbox ID by uploading to Mapbox online or using their enterprise system Atlas Server. They have a free account where you can put it and get your style ID. Here's an example snippet I've tested with one of my map styles created in Studio and it worked. Notice that I need to provide the key, my username, and Mapbox ID to get the tiles to render properly. <!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>Add styles made with Mapbox Studio to a Leaflet map</title> <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' /> <script src='https://api.mapbox.com/mapbox.js/v2.4.0/mapbox.js'></script> <link href='https://api.mapbox.com/mapbox.js/v2.4.0/mapbox.css' rel='stylesheet' /> <style> body { margin:0; padding:0; } #map { position:absolute; top:0; bottom:0; width:100%; } </style> </head> <body> <div id='map'></div> <script> L.mapbox.accessToken = '<Your access token here'; var map = L.map('map').setView([38.97416, -95.23252], 15); // Add tiles from Mapbox Style API(https://www.mapbox.com/developers/api/styles/) // Tiles are 512x512 pixels and are offset by 1 zoom level L.tileLayer( 'https://api.mapbox.com/styles/v1/<mapbox username>/<style ID>/tiles/{z}/{x}/{y}?access_token=' + L.mapbox.accessToken, { tileSize: 512, zoomOffset: -1, attribution: '© <a href="https://www.mapbox.com/map-feedback/">Mapbox</a> © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>' }).addTo(map); </script> </body> </html>
doc_4662
<form id="loginform" class="form-vertical" method="post"> <div class="control-group normal_text"> <h3><img src="~/Content/img/logo.png" alt="Logo" /></h3></div> <div class="control-group"> <div class="controls"> <div class="main_input_box"> <span class="add-on bg_lg"><i class="icon-user"> </i></span> <input type="text" id="txtusername" class="form-control required" placeholder="Username" name="username" required /> </div> </div> </div> <div class="control-group"> <div class="controls"> <div class="main_input_box"> <span class="add-on bg_ly"><i class="icon-lock"></i></span> <input type="password" id="txtpassword" class="form-control" name="password" placeholder="Password" required /> <br /> <label style="color:red;font-size:15px;display:none;" id="errormsg">Incorrect Username or Password</label> </div> </div> </div> <div class="form-actions"> <span class="pull-left"><a href="#" class="flip-link btn btn-info" id="to-recover">Lost password?</a></span> <span class="pull-right"><input type="submit" value="Login" id="btnlogin" class="flip-link btn btn-success" /></span> </div> </form> <script type = "text/javascript" src = "https://code.jquery.com/jquery-1.12.4.js" > </script> <script type = "text/javascript" > $(document).ready(function() { $("#btnlogin").click(function () { var user = new Object(); user.Username = $('#txtusername').val(); user.Password = $('#txtpassword').val(); if (user != null) { $.ajax({ type: "POST", url: "/Admin/Login", data: JSON.stringify(user), contentType: "application/json; charset=utf-8", dataType: "json", success: function (recordcount) { if (recordcount != null) { alert(recordcount); if (recordcount <= 0) { document.getElementById("errormsg").style.display = 'block'; } else { document.getElementById("errormsg").style.display = 'none'; } } else { alert("Something went wrong"); } }, failure: function (response) { alert(response.responseText); }, error: function (response) { alert(response.responseText); } }); } }); }); </script> A: <html> <head> <title>a</title> </head> <body> <form id="loginform" class="form-vertical" method="post"> <div class="control-group normal_text"> <h3> <!-- <img src="~/Content/img/logo.png" alt="Logo" /> --> </h3> </div> <div class="control-group"> <div class="controls"> <div class="main_input_box"> <span class="add-on bg_lg"> <i class="icon-user"> </i> </span> <input type="text" id="txtusername" class="form-control required" placeholder="Username" name="username" required /> </div> </div> </div> <div class="control-group"> <div class="controls"> <div class="main_input_box"> <span class="add-on bg_ly"> <i class="icon-lock"></i> </span> <input type="password" id="txtpassword" class="form-control" name="password" placeholder="Password" required /> <br /> <label style="color:red;font-size:15px;display:none;" id="errormsg">Incorrect Username or Password</label> </div> </div> </div> <div class="form-actions"> <span class="pull-left"> <a href="#" class="flip-link btn btn-info" id="to-recover">Lost password?</a> </span> <span class="pull-right"> <input type="submit" value="Login" id="btnlogin" class="flip-link btn btn-success" /> </span> </div> </form> <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"> </script> <script type="text/javascript"> $(document).ready(function () { $("#loginform").submit(function (e) { var user = new Object(); user.Username = $('#txtusername').val(); user.Password = $('#txtpassword').val(); if (user != null) { $.ajax({ type: "POST", url: "/Admin/Login", data: JSON.stringify(user), contentType: "application/json; charset=utf-8", dataType: "json", success: function (recordcount) { if (recordcount != null) { alert(recordcount); if (recordcount <= 0) { document.getElementById("errormsg").style.display = 'block'; } else { document.getElementById("errormsg").style.display = 'none'; } } else { alert("Something went wrong"); } }, failure: function (response) { alert(response.responseText); }, error: function (response) { alert(response.responseText); } }); } debugger return false; //e.preventDefault(); }); }); </script> </body> </html> A: You have to add onFocusOut() method in textbox, so when you entered the text in the textbox and goes to next textbox, focusout() method will call, and in the focusout() method, you have to write your validation logic. For example, you can enable your login button, if text entered in the textbox is validated. Otherwise your button remain disabled.
doc_4663
For example: (Supposing my function is called common(a,b)) common([1,3,3,3],[1,3,3,3,3,4]) => [1,3,3,3] Thank you for your help! A: A simple way is sort the two list first and compare the first element one by one. The code is like this: def common(a, b): sorted_a, sorted_b = sorted(a), sorted(b) numa, numb = len(a), len(b) rv = [] i, j = 0, 0 while i < numa and j < numb: if sorted_a[i] == sorted_b[j]: rv.append(sorted_a[i]) i += 1 j += 1 elif sorted_a[i] < sorted_b[j]: i += 1 else: j += 1 return rv A: Three steps to resolve this problem: * *Find out those elements should be in the final list, which is the intersection of two lists *For each element found in step #1, find out how many times it should be in final list *Generate final list based on the info found by previous two steps And then translate these 3 steps to three lines of code: def common(l1, l2): intersection = [e for e in l1 if e in l2] elemnts_counters = {e: min(l1.count(e), l2.count(e)) for e in intersection} return sum([[e] * c for e, c in elemnts_counters.items()], []) Then print common([1,3,3,3], [1,3,3,3,3,4]) will give you: [1, 3, 3, 3] A: def common(lista=None,listb=None): result_list=list() inter_dict=dict() lista_count=dict() listb_count=dict() for i in lista: lista_count[i]=lista_count.get(i,0)+1 #convert lista to dict with frequency for i in listb: listb_count[i]=lista_count.get(i,0)+1 #convert listb to dict with frequency for key in set(lista_count).intersection(set(listb_count)): inter_dict[key]=min(lista_count[key],listb_count[key]) # get intersection of two dicts for k,v in inter_dict.items(): result_list.extend([k]*v) #extend to the output list return result_list The output will give you when invoke the function common([1,3,3,3],[1,3,3,3,3,4]): [1, 3, 3, 3] A: def common(l1,l2): totalElements = l1 + l2 resultList = [] for num in totalElements: if num in l1 and num in l2: resultList.append(num) l1.remove(num) l2.remove(num) return resultList l1 = [1,3,3,3,5] l2 = [1,3,3,3,5,3,4] result = common(l1 , l2) print(result) [1, 3, 3, 3, 5]
doc_4664
ul .sub-menu { display: none; } .sub-menu.open { display: block; flex-direction: column; background-color: $footer-text; width: 50%; color: $darkblue-headingtext; border-radius: 5px; text-align: center; position: absolute; top: 35px; left: 25%; z-index: 1; margin: 0 auto; } .parent { position: relative; } <div class="navbar-links"> <ul> <li class="parent"> <a href="#">Product</a> <img class="menu-arrow mobile-arrow" src="images/icon-arrow-dark.svg" alt="arrow" /> <img class="menu-arrow desktop-arrow" src="./images/icon-arrow-light.svg" alt="arrow" /> </li> <ul class="sub-menu"> <li>Overview</li> <li>Pricing</li> <li>Marketplace</li> <li>Features</li> <li>Integrations</li> </ul> </li> <li class="parent"> <a href="#">Company</a> <img class="menu-arrow mobile-arrow" src="images/icon-arrow-dark.svg" alt="arrow" /> <img class="menu-arrow desktop-arrow" src="./images/icon-arrow-light.svg" alt="arrow" /> <ul class="sub-menu"> <li>About</li> <li>Team</li> <li>Blog</li> <li>Careers</li> </ul> </li> <li class="parent"> <a href="#">Connect</a> <img class="menu-arrow mobile-arrow" src="images/icon-arrow-dark.svg" alt="arrow" /> <img class="menu-arrow desktop-arrow" src="./images/icon-arrow-light.svg" alt="arrow" /> <ul class="sub-menu"> <li>Contact</li> <li>Newsletter</li> <li>LinkedIn</li> </ul> </li> </ul> A: If you want the elements below the submenu to be pushed down, then you don't need position - display: block; is enough to show the submenu and push the other elements down. Working example: $('.menu-arrow').on('click', function() { $(this).parent().find('.sub-menu').toggleClass('open'); }); ul .sub-menu { display: none; } .sub-menu.open { display: block; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="navbar-links"> <ul> <li class="parent"> <a href="#">Product</a> <img class="menu-arrow mobile-arrow" src="images/icon-arrow-dark.svg" alt="arrow" /> <img class="menu-arrow desktop-arrow" src="./images/icon-arrow-light.svg" alt="arrow" /> <ul class="sub-menu"> <li>Overview</li> <li>Pricing</li> <li>Marketplace</li> <li>Features</li> <li>Integrations</li> </ul> </li> <li class="parent"> <a href="#">Company</a> <img class="menu-arrow mobile-arrow" src="images/icon-arrow-dark.svg" alt="arrow" /> <img class="menu-arrow desktop-arrow" src="./images/icon-arrow-light.svg" alt="arrow" /> <ul class="sub-menu"> <li>About</li> <li>Team</li> <li>Blog</li> <li>Careers</li> </ul> </li> <li class="parent"> <a href="#">Connect</a> <img class="menu-arrow mobile-arrow" src="images/icon-arrow-dark.svg" alt="arrow" /> <img class="menu-arrow desktop-arrow" src="./images/icon-arrow-light.svg" alt="arrow" /> <ul class="sub-menu"> <li>Contact</li> <li>Newsletter</li> <li>LinkedIn</li> </ul> </li> </ul> </div>
doc_4665
A: You can specify which ORM you need to create your model like this: rails g active_record:model MyModel or rails g mongoid:model MyModel You can use for it for other generators (migrations at least) A: You can force your generator to use specific ORM rails g model MyModel --orm=postgresql Note: that might be postgres not postgresql. Can't remember exactly. Try both.
doc_4666
At the moment everything is in view on my computer, but on iPhone the pictures are getting cut off. It's letting me scroll horizontally and vertically my pictures, but need to resize the wrapper so my pictures are smaller. Any help would be amazing. Cheers in advance A: You didn't provide any codes, so these maybe help you: * *Set proper width/height to your wrapper when browser resizes and window.onload. Because we don't know device is in landscape or portrait mode until window.onload. Here better explained how to get resized browser width/height. *Check your images width/height. Maybe images' dimensions wider than wrapper. You can set width/height to image in percent. *And don't forget refresh iScroll when browser resizes. You can do it like that: setTimeout(function(){myScroller.refresh()}, 400); // browser need time to rotate
doc_4667
A schedule where, for each pair of transactions Ti and Tj, if Tj reads a data item previously written by Ti, then the commit operation of Ti precedes the commit operation of Tj. T1 T2 T3 w(x) w(x) r(x) commit commit commit In this case, T2 commits before T1, so is it non-recoverable? I understand T3 have to commit before T2 to make it recoverable. However, T3 has override T1's written value, does T1 have to commit before T2 to achieve a recoverable schedule? Please help me! Thank you so much!
doc_4668
Here is my code (a bit simplified) HTML: <nav class="navbar navbar-expand-lg navbar-green"> <div class="navbar-top-bg"></div> <div class="container"> <div class="navbar-top-fg"></div> </div> </nav> CSS: .navbar-top-bg { position: absolute; content: ""; width: 100%; height: 10px; background: rgba(67, 107, 65, 0.5); margin: 0 auto; z-index: 111111; border-bottom: 1px solid rgba(87, 136, 89, 0.4); vertical-align: top; } .navbar-top-fg { position: relative; content: ""; width: 288px; height: 10px; -webkit-transform: perspective(40px) rotateX(-16deg); transform: perspective(40px) rotateX(-16deg); background: rgba(0, 0, 0, 0.5); margin: 0 auto; z-index: 1111111; /*border-bottom: 2px solid rgba(234, 234, 234, 0.4);*/ border-right: 2px solid rgb(65, 100, 62); border-left: 2px solid rgb(65, 100, 62); vertical-align: top; } .navbar-green { padding-left: 0; padding-right: 0; background: rgba(37, 48, 27, 1); background: -moz-linear-gradient(top, rgba(39, 41, 37, 1) 0%, rgba(0, 0, 0, 0.60) 100%); background: -webkit-gradient(left top, left bottom, color-stop(0%, rgba(39, 41, 37, 1)), color-stop(100%, rgba(0, 0, 0, 0.60))); background: -webkit-linear-gradient(top, rgba(39, 41, 37, 1) 0%, rgba(0, 0, 0, 0.60) 100%); background: -o-linear-gradient(top, rgba(39, 41, 37, 1) 0%, rgba(0, 0, 0, 0.60) 100%); background: -ms-linear-gradient(top, rgba(39, 41, 37, 1) 0%, rgba(0, 0, 0, 0.60) 100%); background: linear-gradient(to bottom, rgba(39, 41, 37, 1) 0%, rgba(0, 0, 0, 0.60) 100%); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#25301b', endColorstr='#79bd64', GradientType=0); border-bottom: 1px solid rgba(91, 115, 89, 0.08) !important; -webkit-box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.75); -moz-box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.75); box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.75); height: 75px; position: fixed; top: 0; right: 0; left: 0; z-index: 1030; } As you can see, the 2 green stripes are in the center of the navbar (vertically) but i want them on top (to see that layout just remove the navbar and navbar-expand-lg classes) but i also want to use the common "navbar" features to add links and so on. Here also a link to jsfiddle: https://jsfiddle.net/Insax/apzb42b9/ A: Use position: absolute on both parts of the "stripe" and use top: 0 to position them to the top. Use left: 0 and right: 0 to center them. JSFiddle .navbar-top-bg { width: 100%; height: 10px; background: rgba(67, 107, 65, 0.5); margin: 0 auto; z-index: 111111; border-bottom: 1px solid rgba(87, 136, 89, 0.4); } .navbar-top-fg { width: 288px; height: 10px; -webkit-transform: perspective(40px) rotateX(-16deg); transform: perspective(40px) rotateX(-16deg); background: rgba(0, 0, 0, 0.5); margin: 0 auto; z-index: 1111111; /*border-bottom: 2px solid rgba(234, 234, 234, 0.4);*/ border-right: 2px solid rgb(65, 100, 62); border-left: 2px solid rgb(65, 100, 62); } .navbar-top-bg, .navbar-top-fg { position: absolute; top: 0; left: 0; right: 0; }
doc_4669
Example image A: Got it! var colors = ["#eb5945", "#f8e71c", "#67c60b"]; nv.addGraph(function() { var chart = nv.models.pieChart() .x(function(d) { return d.label }) .y(function(d) { return d.value }) .showLabels(true) .showLegend(false) .labelThreshold(.05) .tooltips(false) .color(colors) .donutLabelsOutside(true) .donut(true) .donutRatio(0.7); d3.select("#chart svg") .datum(data) .transition().duration(1200) .call(chart); d3.selectAll('.nv-label text') .each(function(d,i){ d3.select(this).style('fill',colors[i]) d3.select(this).style('font-weight', 700) d3.select(this).style('font-size', 16) }) return chart; });
doc_4670
What should i write in the code to make this happen. How can i refer static cells inside the code without firing error. A: With static cells, you can still implement - tableView:didSelectRowAtIndexPath: and check the indexPath. One approach, is that you define the particular indexPath with #define, and check to see whether the seleted row is at that indexPath, and if yes, call [self myMethod]. A: In the viewController add: @property (nonatomic, weak) IBOutlet UITableViewCell *theStaticCell; Connect that outlet to the cell in the storyboard. Now in tableView:didSelectRowAtIndexPath method: UITableViewCell *theCellClicked = [self.tableView cellForRowAtIndexPath:indexPath]; if (theCellClicked == theStaticCell) { //Do stuff } A: Here is my take when mixing static and dynamic cells, override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let staticIndexPath = tableView.indexPathForCell(self.staticCell) where staticIndexPath == indexPath { // ADD CODE HERE } } this avoids creating a new cell. We all are used to create the cell and configure it in cellForRowAtIndexPath A: Following CiNN answer, this is the Swift 3 version that solves the issue. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let staticIndexPath = tableView.indexPath(for: OUTLET_TO_YOUR_CELL), staticIndexPath == indexPath { // ADD CODE HERE } } this approach allow to not necessary implement cellForRow method, specially if you are using static cells on storyboard. A: I think you were having the same problem I was. I kept getting an error when overriding tableView:didSelectRowAt, and the reason was that I'm used to just calling super.tableView:didSelectRowAt, but in this case we don't want to do that. So just remove the call to the super class method to avoid the run-time error.
doc_4671
$('#addButton').click(function(){ $("#incomplete-tasks").append('<li><input type="checkbox"><label>' + $('#new-task').val() + '</label><input type="text"><button class="edit">Edit</button><button class="delete">Delete</button></li>') }); $(".edit").on('click', function(){ $(this).parent().toggleClass('editMode'); }); <p> <label for="new-task">Add Item</label> <input id="new-task" type="text"> <button id="addButton">Add</button> </p> <h3>Todo</h3> <ul id="incomplete-tasks"> <li> <input type="checkbox"> <label>Pay Bills</label> <input type="text"> <button class="edit">Edit</button> <button class="delete">Delete</button> </li> A: You'd need event delegation. Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future. $("#incomplete-tasks").on("click", ".edit", function() { ... }); There is a good example here: https://learn.jquery.com/events/event-delegation/ A: Checkout this fiddle demo. editMode class is adding dynamically upon edit button click on li tag. Code: Html: <p> <label for="new-task">Add Item</label> <input id="new-task" type="text" /> <button id="addButton">Add</button> </p> <h3>Todo</h3> <ul id="incomplete-tasks"> <li id='dfdf'> <input type="checkbox" /> <label>Pay Bills</label> <input type="text" /> <button class="edit">Edit</button> <button class="delete">Delete</button> </li> </ul> JS: $(document).ready(function () { $('#addButton').on('click', function () { $("#incomplete-tasks").append('<li><input type="checkbox"/><label>' + $('#new-task').val() + '</label><input type="text"/><button class="edit">Edit</button><button class="delete">Delete</button></li>') }); $("#incomplete-tasks").on("click", ".edit", function () { $(this).parent().toggleClass('editMode'); }); });
doc_4672
* *Get the total mail list - List<Message> totalMessageList = Arrays .asList(folder.getMessages()); *Create a list out of this which has only unread mails. (I had to do this coz I could not find a any direct API to get list of new mails. One question which helped in finding whether a message is unread or not was posted here) List<Message> unreadMessageList = new ArrayList<Message>(); For sake of brevity I have not posted entire logic of building the list of unread mail from list of total mails. *Iterate through the list of unread mails > Check if any mail has desired subject then read content of mail > If no such mail found then throw IllegalStateExcepton Now my question is - Could I improve on this approach? A: Can you use Folder.search(SearchTerm): Message[] http://javamail.kenai.com/nonav/javadocs/javax/mail/Folder.html#search%28javax.mail.search.SearchTerm%29 with the relevant SearchTerm, e.g. FlagTerm for the unread flag http://javamail.kenai.com/nonav/javadocs/javax/mail/search/FlagTerm.html Quick search on Google found this http://www.java2s.com/Code/Java/Email/Searchthegivenfolderformessagesmatchingthegivencriteria.htm which might be useful, but I haven't tried it
doc_4673
so could you please help me with the possible fixes! This is My Code: public void createTables(SQLiteDatabase database) { String subscriber_table_sql = "create table " + Database.SUBSCRIBE_TABLE_NAME + " ( " + Database.SUBSCRIBE_ID + " integer primary key autoincrement," + Database.SUBSCRIBE_NAME + " TEXT," + Database.SUBSCRIBE_PHONE + " TEXT," + Database.SUBSCRIBE_DEVICEID + " TEXT," + Database.SUBSCRIBE_AREA + " TEXT," + Database.SUBSCRIBE_CITY + " TEXT)"; String friends_table_sql = "create table " + Database.FRIENDS_TABLE_NAME + " ( " + Database.FRIENDS_ID + " integer primary key autoincrement," + Database.FRIENDS_NAME + " TEXT," + Database.FRIENDS_PHONE + " TEXT," + Database.FRIENDS_AREA+ " TEXT," + Database.FRIENDS_CITY + " TEXT)"; A: create a separate class called database inside the same package and declare the string variables such as FRIENDS_ID,FRIENDS_NAME public class Database { static String FRIENDS_ID="friend_id",FRIENDS_NAME="friend_name",FRIENDS_PHONE="friend_phone",FRIENDS_AREA="friend_area",FRIENDS_CITY="friend_city"; static String SUBSCRIBE_ID="subscribe_id",SUBSCRIBE_NAME="subscribe_name",SUBSCRIBE_PHONE="subscribe_phone",SUBSCRIBE_DEVICEID="subscribe_deviceid",SUBSCRIBE_AREA="subscribe_area",SUBSCRIBE_CITY="subscribe_city"; }
doc_4674
public static void main(String args[]) { try { String addServerURL = "rmi://" + "127.0.0.1" + "/AddServer"; AddServerIntf addServerIntf = (AddServerIntf) Naming.lookup(addServerURL); System.out.println("msg from inside"+addServerIntf.register(new AddClient())); } catch (Exception e) { System.out.println("Exception: " + e); } } } I have this class and its working its task properly, but when I want this add a method to it like public void retrive(String msg) { System.out.println(msg); } It generates Exception: java.rmi.ServerException: RemoteException occurred in server thread; nested exception is: java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is: java.io.InvalidClassException: rmi.AddClient; local class incompatible: stream classdesc serialVersionUID = 7584986215301760999, local class serialVersionUID = 9065682220695232722 But I didn't even use call the method from anywhere but there comes the exception. I have never encountered this kind of problem so can any one tell me what I should do. A: The exception is describing the problem: the client is trying to unmarshal the serialized object, but it cannot because the serial version identifiers do not match. That means that the server has serialized a different version of the AddClient class than the client is unmarshalling. @duffymo is correct - to solve the problem both the client and server must have the same version of the AddClient class on their classpath.
doc_4675
Then I saw the import function, and I'm hoping that'll save me some time. I think I can pass the package I want to one or two particular functions, have those function import the package, and then things will work the way I want--if the functions that those functions call fall into the scope of that import statement. E.g, if I set something up like function foo(var1, var2, ..., packagename) eval(sprintf('import %s.*', packagename)); ... bar1(var1, var2); ... bar2(var2); ... then I'm hoping bar1 and bar2 will use the package imported with the import statement. The documentation says that import statements in conditionals and functions are limited to that block of code, but I don't know if "that block of code" means that text only, or "that block of code" being the code and everything that evaluates as a result. I have a feeling it's the former, but I figured I'd ask in the hopes that it is the latter. So, what is the scope of an import statement? Alternatively, is there another way to deal with this problem? A: The best approach for you is likely to take the pain of renaming until the "multiple functions with same name" problem is gone. It will make the code much easier for both you and future maintainers to understand. Two options that are different than your package idea (which I like): * *You can just append (or prepend) the directory name to the function name and put them all into a new (better-named) directory. Might make more sense, depending on the situation. *If you have two functions foo defined in directories bar and car, and both functions take the same arguments, you can unify them in a single function that takes bar or car as an additional argument: function foo(parm1, parm2, parm3, version) if strcmp(version, 'bar') // bar code else // car code end This isn't great, but it's much better than munging the path, and it sort-of follows a MATLAB pattern (passing in a string argument to change the detailed behavior of the function). Even if the two foo functions have different arguments you can make this work, but you'll have to do annoying parsing of the arguments, at which point your packing idea looks much easier to me. A: I wrote some test code to try it out for myself, and indeed, the import statement is limited to only the function that called it, which makes sense but I guess my hope clouded my judgement. For the record, I wrote the following short functions to test it: function package_test(package_name) eval(sprintf('import %s.*;', package_name)); test_function(); end   function test_function() nested_function() end and then put function nested_function() disp('I\'m in the original folder :('); end in the same folder as the first two functions, and function nested_function() disp('I\'m in the package! :)'); end in a folder named +trial. Of course, when I ran package_test('trial'), I saw "I'm in the original folder :(" displayed in the window, while trial.nested_function() gave me the string I hoped to see. Furthermore, the eval function poses a problem to the compiler, and replacing it with import(sprintf('%s.*', package_name)); doesn't seem to help either. So it looks like I'm back to duplicating files.
doc_4676
* *shared_product==1 *exclusive_product_storeA ==1 *exclusive_product_storeB ==1 Main df date product_id shared_product exclusive_product_storeA exclusive_product_storeB 2019-01-01 34434 1 0 0 2019-01-01 43546 1 0 0 2019-01-01 53288 1 0 0 2019-01-01 23444 0 1 0 2019-01-01 25344 0 1 0 2019-01-01 42344 0 0 1 Output DF date count_shared_product count_exclusive_product_storeA count_exclusive_product_storeB 2019-01-01 3 2 1 This is what I have tried - but this does not give me the desired output df: df.pivot_table(index=['shared_product','exclusive_product_storeA','exclusive_product_storeB'],aggfunc=['count'],values='product_id') A: The idea here is to exclude rows that have a value of 0, groupby date and the resulting column, and finally unstack to get your final result ( df.drop("product_id", axis=1) .set_index("date") .stack() .loc[lambda x: x == 1] .groupby(level=[0, 1]) .sum() .unstack() .rename_axis(index=None) ) exclusive_product_storeA exclusive_product_storeB shared_product 2019-01-01 2 1 3 A shorter path would be to exclude the product_id, groupby date and sum the columns : df.drop("product_id", axis=1).groupby("date").sum().rename_axis(None)
doc_4677
I want to assign to the payment table by id (and date) the last collection officer that made the agreement with the debtor. For example: On id 1111 there were two promises made: by Morticia Adams and Gulliver; But i choose Gulliver because he made the last promise in that date range taking in account the date of payment. Likewise for id 5425 the last promise made was made by Marie Anne because 23.10.2016 (date of payment) is between 12.10.2016 and 26.10.2016 (promise dates). This is already done here in Excel but in need this to be done in Microsoft Access since I have a huge table and Excel takes a long time to process the information. As an idea it must satisfy the following conditions: * *The payment ID of the row in the promises table is equal to the payment id of the payments table. *The date of the payment is greater than or equal to the conversation date. *The date of the payment is less than or equal to the agreed payment date. I would be really grateful if someone could give me a hint. A: Ideally you'd split the query into two queries using inner joins, but you can do it with one. Using this: SELECT [Payments Table].ID, [Payments Table].[Date of Payment], [Payment Promises Table].[Collection Officer] FROM ([Payments Table] INNER JOIN ( SELECT [Payments Table].ID, Max([Payment Promises Table].[Date of conversation]) AS LastDate FROM [Payments Table] INNER JOIN [Payment Promises Table] ON [Payments Table].ID = [Payment Promises Table].ID WHERE ((([Payments Table].[Date of Payment]) Between [Date of Conversation] And [Date Agreed to Pay])) GROUP BY [Payments Table].ID) AS FindOfficer ON [Payments Table].ID = FindOfficer.ID) INNER JOIN [Payment Promises Table] ON (FindOfficer.LastDate = [Payment Promises Table].[Date of conversation]) AND (FindOfficer.ID = [Payment Promises Table].ID); Comes up with this:
doc_4678
$ cat /proc/sys/net/ipv4/tcp_max_orphans 262144 As per one of the presentations by Rick Reed (from WhatsApp), these guys took it up to 2 million concurrent connections on a "single server" using FreeBSD and ErLang. My understanding is that we will always need some support from the kernel. And yes, looks like the tweaked the FreeBSD to have this capability: hw.machine: amd64 hw.model: Intel(R) Xeon(R) CPU X5675 @ 3.07GHz hw.ncpu: 24 hw.physmem: 103062118400 hw.usermem: 100556451840 kb@c123$ uname -rps FreeBSD 8.2-STABLE amd64 jkb@c123$ cat /boot/loader.conf.local kern.ipc.maxsockets=2400000 kern.maxfiles=3000000 kern.maxfilesperproc=2700000 So, looks like kernel can be tweaked to support so many physical connections, given that we have sufficient amount of memory, correct? If yes, then it looks pretty simple, then what is the hype about it? Or I am missing something? Thanks. A: If you have enough RAM it's not too hard to handle 1M or more connections on linux. These guys handled 10 million connections with a java application on a single box using regular CentOS kernel with a few sysctl tweaks: sysctl -w fs.file-max=12000500 sysctl -w fs.nr_open=20000500 ulimit -n 20000000 sysctl -w net.ipv4.tcp_mem='10000000 10000000 10000000' sysctl -w net.ipv4.tcp_rmem='1024 4096 16384' sysctl -w net.ipv4.tcp_wmem='1024 4096 16384' sysctl -w net.core.rmem_max=16384 sysctl -w net.core.wmem_max=16384 Also they balanced /proc/irq/'s of the network adapter and added a tweak for better JVM work with huge pages: sysctl -w vm.nr_hugepages=30720 Having two 6-core CPUs 57% loaded they served 1Gbps over 12M connections in 2013. But you need HUGE amount of RAM for that. The above test was on a server with 96GB RAM, and 36GB of those were used by the kernel for buffers of 12M sockets. To serve 1M connections with similar settings you'll need a server with at least 8GB RAM and 3-4GB of them would be used just for socket buffers. A: Note there are three things here: * *Getting the server to support two million connections. This is usually just tweaking the kernel such that the number of simultaneous connections are allowed and such that the context associated with each connection fit in (wired) main memory. The latter means you can't have a megabyte buffer space allocated for each connection. *Doing something with each connection. You map them into userspace in a process (Erlang in this case). Now, if each connection allocates too much data at the user space level we are back to square one. We can't do it. *Getting multiple cores to do something with the connections. This is necessary due to the sheer amount of work to be done. It is also the point where you want to avoid locking too much and so on. You seem to be focused on 1. alone.
doc_4679
Servlet-A is web application that has no access to the DB. It has a filter to forward certain requests to Servlet-B. Servlet-B is a Spring/Hibernate application with access to the DB (using Hibernate). When Servlet-A forwards a request to a controller in Servlet-B, the latter cannot create Hibernate session for that request, giving me error: Caused by: org.hibernate.HibernateException: No Session found for current thread 12:04:29,802 ERROR [STDERR] at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97) 12:04:29,803 ERROR [STDERR] at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:990) It looks like the root context of the forwarded request is not recognized by Servlet-B and hence cannot grant it access to it's resources. Here is what I am doing in Servlet-A (1) Filter setup <filter> <filter-name>CandidateProxyFilter</filter-name> <filter-class>com.candidate.filter.CandidateProxyFilter</filter-class> </filter> <filter-mapping> <filter-name>CandidateProxyFilter</filter-name> <url-pattern>*.html</url-pattern> <dispatcher>REQUEST</dispatcher> </filter-mapping> (2) Servlet-B filter code: public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { final RequestDispatcher proxyDispatcher = createProxyDispatcher(request); proxyDispatcher.forward(request, response); } Here the relevant controller code on the Servlet-B: @RequestMapping(method = RequestMethod.GET) public String invokeView() { final Candidate candidate = candidateService.getCandidate(); // Crash !!! ... } CandidateService accessed the DB using Hibernate session, but for requests forwarded from Servlet-A it throws the above error. For requests fired from Servlet-B context it is fine. I just want to understand what is going on and how to fix the problem? A: I fixed it! It turned up that the configuration of OpenSessionInViewFilter in Servlet-B was ignoring all FORWARD request types by default: <filter> <filter-name>hibernateFilter</filter-name> <filter-class> org.springframework.orm.hibernate4.support.OpenSessionInViewFilter </filter-class> </filter> <filter-mapping> <filter-name>hibernateFilter</filter-name> <url-pattern>*</url-pattern> </filter-mapping> All I had to do is to add the following to the filter: <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> The final setup is like that: <filter> <filter-name>hibernateFilter</filter-name> <filter-class> org.springframework.orm.hibernate4.support.OpenSessionInViewFilter </filter-class> </filter> <filter-mapping> <filter-name>hibernateFilter</filter-name> <url-pattern>*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> </filter-mapping>
doc_4680
I wonder why my code doesn't work properly. What I'm expecting: wait wait wait wait wait something wait wait wait wait wait something wait etc. but I don't have any idea what's wrong with my code, look at this: getText: function() { console.log("something"); }, setDelay: function(callback) { var that = this; setTimeout(function() { callback(); },5000); }, play: function() { var that = this; setInterval(function(){ console.log("wait"); that.setDelay(that.getText); },1000); }, I'm getting something like this: wait wait wait wait wait something wait something wait something etc. any ideas will be appreciated. A: It's because you're calling setDelay() every second: getText: function() { console.log("something"); }, setDelay: function(callback) { var that = this; setTimeout(function () { callback(); }, 5000); }, play: function() { var that = this; setInterval(function () { console.log("wait"); that.setDelay(that.getText); // << here }, 1000); }, What happens: 1s -> setDelay() -> timeout1 is created 2s -> setDelay() -> timeout2 is created 3s -> setDelay() -> timeout3 is created 4s -> setDelay() -> timeout4 is created 5s -> setDelay() -> timeout5 is created 6s -> setDelay() -> timeout6 is created // timeout1's 5s are done, so it fires 7s -> setDelay() -> timeout7 is created // timeout2's 5s are done, so it fires 8s -> setDelay() -> timeout8 is created // timeout3's 5s are done, so it fires and so on... A: Inside of your play function, every second, you're running that.setDelay, which then waits five seconds before running console.log("something");. What you could do instead is have two setInterval's running: play: function() { var that = this; setInterval(function () { console.log("wait"); }, 1000); setInterval(function () { that.getText(); }, 5000); }, This way, every second you'll get the output "wait", and every five seconds, the output "something". Merry Christmas! A: I would try to unpick the two intermingled timeouts/intervals and have just one that you clear/reset once you've reached the loop limit. It makes it a little easier to follow. Something like this: function play(count) { var count = count || 1; var t; console.log(count); if (count !== 0 && count % 5 === 0) { clearTimeout(t); console.log('something'); t = setTimeout(play, 5000, 1); } else { t = setTimeout(play, 1000, ++count); } } play(); DEMO Or, in line with your own code: var obj = { delay: 5000, timer: 1000, getText: function () { console.log('something'); }, play: function(count) { var count = count || 1; var t; if (count !== 0 && count % 5 === 0) { clearTimeout(t); this.getText(); t = setTimeout(this.play.bind(this), this.delay, 1); } else { t = setTimeout(this.play.bind(this), this.timer, ++count); } } } obj.play(); DEMO
doc_4681
I don't really know much so from the errors to me it looks like something wrong with the camera code in kivy itself, but i have no idea what to do and am kind of just stuck here, any help appreciated, very begginer still so hope this isn't a very dumb post. .py: from kivy.app import App from kivy.uix.camera import Camera from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from android.permissions import request_permissions, Permission request_permissions([Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE, Permission.CAMERA]) class PhotoApp(App): def build(self): self.camera_obj = Camera(resolution=(800, 800)) # self.camera_obj.pos_hint = {'x': .15, 'y':.15} button_obj = Button(text="Take Photo") button_obj.size_hint = (.5,.2) button_obj.pos_hint = {'x':.25, 'y':.25} button_obj.bind(on_press=self.photo_take) layout = BoxLayout() layout.add_widget(self.camera_obj) layout.add_widget(button_obj) return layout def photo_take(self, *args): print("Photo Taken") self.camera_obj.export_to_png("./demopng.png") if __name__ == '__main__': PhotoApp().run() logcat: --------- beginning of crash --------- beginning of system --------- beginning of main 05-06 01:20:59.447 15787 15828 I python : Initializing Python for Android 05-06 01:20:59.447 15787 15828 I python : Setting additional env vars from p4a_env_vars.txt 05-06 01:20:59.449 15787 15828 I python : Changing directory to the one provided by ANDROID_ARGUMENT 05-06 01:20:59.449 15787 15828 I python : /data/user/0/org.test.myapp/files/app 05-06 01:20:59.453 15787 15828 I python : Preparing to initialize python 05-06 01:20:59.453 15787 15828 I python : _python_bundle dir exists 05-06 01:20:59.453 15787 15828 I python : calculated paths to be... 05-06 01:20:59.453 15787 15828 I python : /data/user/0/org.test.myapp/files/app/_python_bundle/stdlib.zip:/data/user/0/org.test.myapp/files/app/_python_bundle/modules 05-06 01:20:59.460 15787 15828 I python : set wchar paths... 05-06 01:20:59.595 15787 15828 I python : Initialized python 05-06 01:20:59.595 15787 15828 I python : AND: Init threads 05-06 01:20:59.597 15787 15828 I python : testing python print redirection 05-06 01:20:59.599 15787 15828 I python : Android path ['.', '/data/user/0/org.test.myapp/files/app/_python_bundle/stdlib.zip', '/data/user/0/org.test.myapp/files/app/_python_bundle/modules', '/data/user/0/org.test.myapp/files/app/_python_bundle/site-packages'] 05-06 01:20:59.600 15787 15828 I python : os.environ is environ({'PATH': '/sbin:/system/sbin:/system/bin:/system/xbin:/vendor/bin:/vendor/xbin:/system/vendor/bin:/system/vendor/xbin:/product/bin:/product/xbin:/odm/bin:/odm/xbin', 'DOWNLOAD_CACHE': '/data/cache', 'ANDROID_BOOTLOGO': '1', 'ANDROID_ROOT': '/system', 'ANDROID_ASSETS': '/system/app', 'ANDROID_DATA': '/data', 'ANDROID_STORAGE': '/storage', 'EXTERNAL_STORAGE': '/sdcard', 'ASEC_MOUNTPOINT': '/mnt/asec', 'BOOTCLASSPATH': '/system/framework/core-oj.jar:/system/framework/core-libart.jar:/system/framework/conscrypt.jar:/system/framework/okhttp.jar:/system/framework/bouncycastle.jar:/system/framework/apache-xml.jar:/system/framework/legacy-test.jar:/system/framework/ext.jar:/system/framework/framework.jar:/system/framework/telephony-common.jar:/system/framework/voip-common.jar:/system/framework/ims-common.jar:/system/framework/org.apache.http.legacy.boot.jar:/system/framework/android.hidl.base-V1.0-java.jar:/system/framework/android.hidl.manager-V1.0-java.jar:/system/framework/featurelayer-widget.jar:/system/framework/hwEmui.jar:/system/framework/hwTelephony-common.jar:/system/framework/hwframework.jar:/system/framework/org.simalliance.openmobileapi.jar:/system/framework/org.ifaa.android.manager.jar:/system/framework/hwaps.jar:/system/framework/hwcustEmui.jar:/system/framework/hwcustframework.jar:/system/framework/hwcustTelephony-common.jar:/system/framework/servicehost.jar:/system/framework/tcmiface.jar:/system/framework/telephony-ext.jar:/system/framework/QPerformance.jar:/system/framework/WfdCommon.jar:/system/framework/oem-services.jar:/system/framework/qcom.fmradio.jar', 'SYSTEMSERVERCLASSPATH': '/system/framework/services.jar:/system/framework/ethernet-service.jar:/system/framework/com.android.location.provider.jar:/system/framework/wifi-service.jar:/system/framework/hwServices.jar:/system/framework/hwWifi-service.jar:/system/framework/hwcustServices.jar:/system/framework/hwcustwifi-service.jar', 'OEM_ROOT': '/hw_oem', 'ODM_PRODUCT': '/hw_odm', 'CUST_POLICY_DIRS': '/system/emui/base:/system/emui/oversea:/system/emui/lite:/vendor/etc:/odm/etc:/product/etc:/preas/oversea:/prets:/hw_oem:/cust/hw/normal:/data/cust:/version/region_comm/oversea:/cust_spec', 'ANDROID_SOCKET_zygote': '9', 'ANDROID_ENTRYPOINT': 'main.pyc', 'ANDROID_ARGUMENT': '/data/user/0/org.test.myapp/files/app', 'ANDROID_APP_PATH': '/data/user/0/org.test.myapp/files/app', 'ANDROID_PRIVATE': '/data/user/0/org.test.myapp/files', 'ANDROID_UNPACK': '/data/user/0/org.test.myapp/files/app', 'PYTHONHOME': '/data/user/0/org.test.myapp/files/app', 'PYTHONPATH': '/data/user/0/org.test.myapp/files/app:/data/user/0/org.test.myapp/files/app/lib', 'PYTHONOPTIMIZE': '2', 'P4A_BOOTSTRAP': 'SDL2', 'PYTHON_NAME': 'python', 'P4A_IS_WINDOWED': 'True', 'P4A_ORIENTATION': 'portrait', 'P4A_NUMERIC_VERSION': 'None', 'P4A_MINSDK': '21', 'LC_CTYPE': 'C.UTF-8'}) 05-06 01:20:59.600 15787 15828 I python : Android kivy bootstrap done. __name__ is __main__ 05-06 01:20:59.600 15787 15828 I python : AND: Ran string 05-06 01:20:59.600 15787 15828 I python : Run user program, change dir and execute entrypoint 05-06 01:20:59.910 15787 15828 I python : [INFO ] [Logger ] Record log in /data/user/0/org.test.myapp/files/app/.kivy/logs/kivy_22-05-06_0.txt 05-06 01:20:59.911 15787 15828 I python : [INFO ] [Kivy ] v2.1.0 05-06 01:20:59.911 15787 15828 I python : [INFO ] [Kivy ] Installed at "/data/user/0/org.test.myapp/files/app/_python_bundle/site-packages/kivy/__init__.pyc" 05-06 01:20:59.912 15787 15828 I python : [INFO ] [Python ] v3.8.9 (default, May 5 2022, 21:21:34) 05-06 01:20:59.912 15787 15828 I python : [Clang 8.0.2 (https://android.googlesource.com/toolchain/clang 40173bab62ec7462 05-06 01:20:59.913 15787 15828 I python : [INFO ] [Python ] Interpreter at "" 05-06 01:20:59.913 15787 15828 I python : [INFO ] [Logger ] Purge log fired. Processing... 05-06 01:20:59.916 15787 15828 I python : [INFO ] [Logger ] Purge finished! 05-06 01:21:02.422 15787 15828 I python : [INFO ] [Factory ] 189 symbols loaded 05-06 01:21:03.092 15787 15828 I python : [INFO ] [Image ] Providers: img_tex, img_dds, img_sdl2 (img_pil, img_ffpyplayer ignored) 05-06 01:21:03.463 15787 15828 I python : [INFO ] [Camera ] Provider: android 05-06 01:21:03.482 15787 15828 I python : [INFO ] [Text ] Provider: sdl2 05-06 01:21:03.874 15787 15828 I python : [INFO ] [Window ] Provider: sdl2 05-06 01:21:03.928 15787 15828 I python : [INFO ] [GL ] Using the "OpenGL ES 2" graphics system 05-06 01:21:03.932 15787 15828 I python : [INFO ] [GL ] Backend used <sdl2> 05-06 01:21:03.933 15787 15828 I python : [INFO ] [GL ] OpenGL version <b'OpenGL ES 3.2 V@269.0 (GIT@6ac4b6f, Ia11ce2d146) (Date:12/16/20)'> 05-06 01:21:03.934 15787 15828 I python : [INFO ] [GL ] OpenGL vendor <b'Qualcomm'> 05-06 01:21:03.936 15787 15828 I python : [INFO ] [GL ] OpenGL renderer <b'Adreno (TM) 506'> 05-06 01:21:03.937 15787 15828 I python : [INFO ] [GL ] OpenGL parsed version: 3, 2 05-06 01:21:03.939 15787 15828 I python : [INFO ] [GL ] Texture max size <16384> 05-06 01:21:03.940 15787 15828 I python : [INFO ] [GL ] Texture max units <16> 05-06 01:21:04.010 15787 15828 I python : [INFO ] [Window ] auto add sdl2 input provider 05-06 01:21:04.013 15787 15828 I python : [INFO ] [Window ] virtual keyboard not allowed, single mode, not docked 05-06 01:21:04.403 15787 15828 I python : Traceback (most recent call last): 05-06 01:21:04.404 15787 15828 I python : File "/home/potatomantiger/testing-app/.buildozer/android/app/main.py", line 30, in <module> 05-06 01:21:04.405 15787 15828 I python : File "/home/potatomantiger/testing-app/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/python-installs/myapp/arm64-v8a/kivy/app.py", line 954, in run 05-06 01:21:04.406 15787 15828 I python : File "/home/potatomantiger/testing-app/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/python-installs/myapp/arm64-v8a/kivy/app.py", line 924, in _run_prepare 05-06 01:21:04.407 15787 15828 I python : File "/home/potatomantiger/testing-app/.buildozer/android/app/main.py", line 11, in build 05-06 01:21:04.407 15787 15828 I python : File "/home/potatomantiger/testing-app/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/python-installs/myapp/arm64-v8a/kivy/uix/camera.py", line 91, in __init__ 05-06 01:21:04.408 15787 15828 I python : File "/home/potatomantiger/testing-app/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/python-installs/myapp/arm64-v8a/kivy/uix/camera.py", line 105, in _on_index 05-06 01:21:04.409 15787 15828 I python : File "/home/potatomantiger/testing-app/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/python-installs/myapp/arm64-v8a/kivy/core/camera/camera_android.py", line 42, in __init__ 05-06 01:21:04.410 15787 15828 I python : File "/home/potatomantiger/testing-app/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/python-installs/myapp/arm64-v8a/kivy/core/camera/__init__.py", line 70, in __init__ 05-06 01:21:04.411 15787 15828 I python : File "/home/potatomantiger/testing-app/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/python-installs/myapp/arm64-v8a/kivy/core/camera/camera_android.py", line 57, in init_camera 05-06 01:21:04.412 15787 15828 I python : File "jnius/jnius_export_class.pxi", line 857, in jnius.jnius.JavaMethod.__call__ 05-06 01:21:04.413 15787 15828 I python : File "jnius/jnius_export_class.pxi", line 954, in jnius.jnius.JavaMethod.call_method 05-06 01:21:04.414 15787 15828 I python : File "jnius/jnius_utils.pxi", line 91, in jnius.jnius.check_exception 05-06 01:21:04.415 15787 15828 I python : jnius.jnius.JavaException: JVM exception occurred: setParameters failed java.lang.RuntimeException 05-06 01:21:04.415 15787 15828 I python : Python for android ended.
doc_4682
function products() { $order='music_id'; if (isset($_GET['album'])){ $order='music_album' ; header('Location: '. $page); } switch($order){ case 'music_album': $get = mysql_query('SELECT music_id, music_artist, music_album, music_genre, music_price FROM music WHERE music_stock > 0 ORDER BY music_album'); if (mysql_num_rows($get) == 0) { echo "There are no products avaliable, sorry."; } else { echo '<table width="100%" border="0px" class="msc"><tr><td><b>Album</b>&nbsp;<a href="cart.php?album">[Sort]</a></td><td><b>Artist</b>&nbsp;<a href="cart.php?artist">[Sort]</a></td><td><b>Genre</b>&nbsp;<a href="cart.php?genre">[Sort]</a></td><td><b>Price</b>&nbsp;<a href="cart.php?price">[Sort]</a></td></tr>'; while ($get_row = mysql_fetch_assoc ($get)) { echo '<tr> <td> <i>'. $get_row['music_album'] . '</i></td><td>' .$get_row['music_artist'] . '</td><td>' . $get_row['music_genre']. '</td><td>$' . $get_row['music_price'] .'</td><td> <a class="btn" href="cart.php?add='. $get_row['music_id'] . ' ">Add<a></td></tr>'; }} break; using a case for each sort, and a default using music_id, but when the<a href="cart.php?album">[Sort]</a> is clicked it neither redirects back to music.php, or changes the sort. Is there a. a better way to perform this task or b. a way I can get this to work? EDIT New code, heres the whole function. This gets called on the actual music page, could that be why the sort isn't working? function products() { $possible_orders= ['music_album', 'music_artist', 'music_genre', 'music_price']; if (isset ($_GET['order'])){ if (! in_array($order, $possible_orders)){ $order=$_GET['order']; } header('Location: '. $page); } else{ $order='music_id'; } $get = mysql_query('SELECT music_id, music_artist, music_album, music_genre, music_price FROM music WHERE music_stock > 0 ORDER BY '.$order); if (mysql_num_rows($get) == 0) { echo "There are no products avaliable, sorry."; } else { echo '<table width="100%" border="0px" class="msc"><tr><td><b>Album</b>&nbsp;<a href="cart.php?order=music_album">[Sort]</a></td><td><b>Artist</b>&nbsp;<a href="cart.php?order=music_artist">[Sort]</a></td><td><b>Genre</b>&nbsp;<a href="cart.php?order=music_genre">[Sort]</a></td><td><b>Price</b>&nbsp;<a href="cart.php?order=music_price">[Sort]</a></td></tr>'; while ($get_row = mysql_fetch_assoc ($get)) { echo '<tr> <td> <i>'. $get_row['music_album'] . '</i></td><td>' .$get_row['music_artist'] . '</td><td>' . $get_row['music_genre']. '</td><td>$' . $get_row['music_price'] .'</td><td><hr> <a class="btn" href="cart.php?add='. $get_row['music_id'] . ' ">Add<a><hr></td></tr>'; } } } A: From the snippet you provided, it could be the function products() is not called on page reload for some reason. Additionally, you don't really need a switch() statement there. What would be ways better is to provide the value of order in order variable directly at page. 1) fix the links from 'cart.php?album' to 'cart.php?order=album' (and of course the rest of the orderings) then do sonething like this instead of switch(): function products() { $possible_orders=['music_album', 'music_artist', ... ]; $order=$_GET['order']; if (! in_array($order, $possible_orders)) $order='music_id'; // rudimentary safety check $get=mysql_query(.... ' ORDER BY '.$order); ...
doc_4683
interface IGrouping<out TKey, out IEnumerable<TElement>> ^^^^^^^^^^^^^ Originally, it implements IEnumerable<TElement> and IEnumerable for backward compatibility. Does this accomplish the same task? If yes, how? I don't understand. public interface ILookup<TKey,TElement> : IEnumerable<IGrouping<TKey,TElement>> Does the followed mean ILookup used by Join/GroupJoin has multiple keys with the association of multiple values? Could you exemplify? I've looked the question, but don't understand the difference, except that their lazy evaluation vs immediate evaluation semantics. Not to do complicate matter further, but the output may help for everyone. A: If you look at the declaration of IGrouping, public interface IGrouping<out TKey,out TElement> : System.Collections.Generic.IEnumerable<out TElement> You can see that it says "IGrouping<TKey, TElement> is a kind of IEnumerable<TElement>". It's a special kind of IEnumerable<TElement>. Special in what way? It has a Key associated. And no, this is not valid C# syntax: interface IGrouping<out TKey, out IEnumerable<TElement>> Remember that this is an interface declaration, and in the <>, it is declaring the type parameters, which are identifiers, for the interface. IEnumerable<TElement> is not a valid identifier. You also seem to want to refer to the existing interface System.Collections.Generic.IEnumerable<T>, but it makes no sense to put it in this place in the declaration, the same way that it wouldn't make sense to write interface Foo<List<T>> as an interface declaration in Java. If you mean: interface IGrouping<out TKey, out TElement> where TElement : IEnumerable that could work, and there are many ways in which you can design this IGrouping interface. The following way probably makes sense to you the most? interface IMyGrouping<TKey, TElement> { TKey Key { get; } IEnumerable<TElement> Elements { get; } } But what's really great about .NET framework's design is that it implements an existing interface, and that allows it to be used as an IEnumerable<TElement> directly, which is a very powerful thing. If your class have the ability that the interface promises, implement that interface. See also. Does the followed mean ILookup used by GroupBy has multiple keys with the association of multiple values? Yes. Since ILookup implements IEnumerable<IGrouping>, and IGrouping implements IEnumerable, ILookup is kind of like a IEnumerable<IEnumerable> (forgive me using the generics notation very loosely here). So an ILookup an enumerable of enumerables, i.e. like a 2D array. The difference is, that each inner "array" has a Key, since the inner "arrays" are actually IGroupings.
doc_4684
When do I need use %a to print float and double type data ? Can you please show me an example. A: As far as an example of why you would want to use the hex representation, you may want to use %a to precisely represent a floating point value being sent to another machine for processing. We're using this currently for unit testing an embedded controller by sending data from a simulated plant model that is emulating sensors and actuators to the embedded processor via a UART where the embedded processor does it's control processing and returns feedback (again, float represented as %a) back to the plant model to close the loop. A: The %a formatting specifier is new in C99. It prints the floating-point number in hexadecimal form. This is not something you would use to present numbers to users, but it's very handy for under-the-hood/technical use cases. As an example, this code: printf("pi=%a\n", 3.14); prints: pi=0x1.91eb86p+1 The excellent article linked in the comments explains that this should be read "1.91EB8616 * 21" (that is, the p is for power-of-two the floating-point number is raised to). In this case, "1.91EB8616" is "1.570000052452087410". Multiply this by the "21", and you get "3.14000010490417510". Note that this also has the useful property of preserving all bits of precision, and presenting them in a robust way. For instance you could use this to serialize floating point numbers as text, and not have to worry about repeating/infinite decimals. Also note that strtod() can convert floating point numbers in hexadecimal form back to actual numbers. Not 100% sure about sscanf() and friends, the documentation was not very clear and I've never used that. A: When do I need use %a to print float and double type data ? In addition to guaranteed exact representation, printing with %a is also much faster. When you are printing only a few numbers, that is not much of an issue, but if you are forced to format-print many floating-point numbers, this may well speed your work up. Switching to base 10 and handling rounding each take a not-insignificant amount of work. Caveat: The I/O may take even more time than the formatting of characters, which may eat away at these benefits; and you might, instead, get away with just printing the raw bytes with no formatting.
doc_4685
<td *ngIf="r.Num_Of_Days !== 0 "(click)="getCTData(r.Name,'Num_Of_Days','high')" class="rd"> {{r.Num_Of_Days}} </td> <td *ngIf="r.Num_Of_Days === 0 "></td> I had to change to using Angular Material since the column names will be dynamic and I had to use the columnstodisplay directive to identify which columns to show. I tried using *matCellDef and *ngIf in the but it threw an error. I did some searching and saw that I needed to use <ng-container, so I came up with the following: <td mat-cell *matCellDef="let r"> <ng-container *ngIf="r.Num_Of_Days !== 0;else conditionNotMet" (click)="getCTData(r.Name,'Num_Of_Days','high')" class="rd"> {{r.Num_Of_Days}} </ng-container> </td> <ng-template #conditionNotMet></ng-template> This populates the data ok, BUT it doesn't apply the function or the css to the cell. How can I get the css and function applied correctly so that when the value is 0 there is no click event and the cell is not colored AND if the value is greater than 0 than the function and formatting are applied? A: * *You can't use two structural directives on one element, so YES! you should put *ngIf on another element. *Your styles and event listener function did't work because you have used ng-container which is not beeing created in the final result. SOLUTION. Just put the logic into a div element <td mat-cell *matCellDef="let r"> <ng-container *ngIf="r.Num_Of_Days !== 0;else conditionNotMet"> <div (click)="getCTData(r.Name,'Num_Of_Days','high')" class="rd"> {{r.Num_Of_Days}} </div> </ng-container> </td> OR use *ngIf on a div <td mat-cell *matCellDef="let r"> <div *ngIf="r.Num_Of_Days !== 0;else conditionNotMet" (click)="getCTData(r.Name,'Num_Of_Days','high')" class="rd"> {{r.Num_Of_Days}} </div> </td>
doc_4686
Now i have learned how to make a form in laravel. But i have some trouble to echo a variable. What i want to do is: i want to echo a variable as the value of an input-field if this variable exists, otherwise it should echo nothing. so my form line looks like this {{Form::text( 'league_name', '@if(isset($varialble) {{$variable}} @else {{$nothing}} @endif)' )}} How can i echo a variable in a form? i am using blade btw. A: This is the right way to do it: {!! Form::text('league_name', isset($varialble) ? $variable : '') !!} If you're using PHP7, you can do this: {!! Form::text('league_name', $varialble) ?? '') !!} Update To add placeholder, pass it in an array as third parameter. Also, you usually want to pass a class: {!! Form::text('league_name', isset($varialble) ? $variable : '', ['placeholder' => 'My placeholder', 'class' => 'form-control']) !!} A: Try This. Here You can use null instead of $nothing and $variable is your variable {{Form::text('league_name',$varialble ? $variable : $nothing)')}} A: In Laravel use can use normal PHP code also {!! Form::text('league_name', !empty($varialble) ? $variable : '') !!} here you can use {!! data/variables !!} or {{ data/variables }} above will resolve your problem.
doc_4687
I'll try to break down the setup into it's simplest form, (this issue is occuring in large enterprise application) We have an MVC application with 2 pages, home and app. Both have controllers and views. The home index.cshtml is a simple Razor view and the app index.cshtml only has the <app-root></app-root> element defined on it. Both views are using a base layout page that defines the navigation menu for the entire app. In the Menu we have 4 anchor tags with: * *href="/home" *href="/app/#/page1" *href="/app/#/page2" *href="/app/#/page3" On the Angular side we have 3 pages (page1, page2 and page3). The routing is also fairly simple: Routes = [ { path: 'page1', component: Page1Component, }, { path: 'page2', component: Page2Component, }, { path: 'page3', component: Page3Component, }, ]; @NgModule({ imports: [RouterModule.forRoot(routes , { useHash: true, enableTracing: true } )], exports: [RouterModule] }) Now if I am on the home page and click the link to Page 1 everything works. The page changes, the angular app loads and everything is great. If I now click on the link for Page 2, the URL changes but the angular app does not load the new component. (Looking at the console the router tracing doesn't show). Now that it is in this "error" state, I can click on Page 3 and it works. URL changes and page 3 component loads. If I now click on Page 2, it works as well. The app will now navigate correctly until I move back to the home (MVC) page. From that point on we return to the above situation, first nav works, second nav doesn't (but URL updates) and all further navs work. Note: If I add links on the angular pages (Page1, Page2 and Page3) and use the routerLink attribute then I don't see the issue. Only when using anchor tags with HRef does the issue arise. Unfortunately as the navigation menu is on MVC base page (and it is a very large enterprise app) I can't rewrite this as Angular component. Any help would be appreciated. A: try changing href="/app/#/pageX" to href="/pageX" A: For the moment I have worked around this problem by adding an onclick handler to the links. This simply sets the window.location.href value to be the same as the href value of the a tag. Not sure why but it now navigates on first click and is smart enough not to do a full page refresh if navigating within the Angular app. Doesn't feel like the right solution but the one that is working for now
doc_4688
{ "Version": "2012-10-17", "Id": "Policy1610615475618", "Statement": [ { "Sid": "Stmt1610615465140", "Effect": "Deny", "Principal": { "AWS": "arn:aws:iam::<acc_name>:user/<user_name>" }, "Action": "s3:PutObject", "NotResource": [ "arn:aws:s3:::<bucket-name>/*.PNG", "arn:aws:s3:::<bucket-name>/*.JPG", "arn:aws:s3:::<bucket-name>/*.txt", "arn:aws:s3:::<bucket-name>/*.mp3", "arn:aws:s3:::<bucket-name>/*.Docx" ] } ] } A: Sadly there is no such variable. Usually in a situation like this you would create and manage your buckets and their policies using Infrastructure as Code tools such as AWS CloudFormation or Terraform. This would allow you to programmatically parametrize and generate the buckets and their policies in a reproducible and easy to manage manner. A: You haven't mentioned how do you create the policy. But if you use IaC this is possible in both terraform and CloudFormation (I would assume that it's possible with other tools like cdk as well) In CloudFormation you can use Ref and Fn:GetAtt. And this is how it looks like in practice. Take a look at the examples section. With terraform you can do something similar: { "Sid": "AllowSSLRequestsOnly", "Action": "s3:*", "Effect": "Deny", "Resource": [ "arn:aws:s3:::${s3-bucket-name}", "arn:aws:s3:::${s3-bucket-name}/*" ], "Condition": { "Bool": { "aws:SecureTransport": "false" } }, "Principal": "*" } And then pass the account_id (or in your case $bucket_name) from outside during the policy creation: data "template_file" "s3-bucket-policy" { template = file("${path.module}/policies/bucket.json") vars = { s3-bucket-name = aws_s3_bucket.my-bucket.bucket } } A: You can use jq to pipe and modify the bucket arn as a variable
doc_4689
What I am trying to acheive: Normally, when you hover over a button, there is an hovered over effect where the color of the button slightly changes. I want this effect to be applied when the user hovers over the parent div of this button. In this case the divs with classes ''serviceContent'' are the parents divs. Inside these parent divs are the buttons. These are the blue buttons which say ''Find out more'' So far, I have tried using this: $('.serviceContent').mouseover(function() { $(this).find('.btn').trigger('mouseover') }) It doesn't seem to work - is there something else that can be triggered which will give the same effect as if the user hovers over the button? Thanks in advance A: Try this $(document).ready(function(){ $(".serviceContent").mouseover(function(){ $("button").addClass("button-hover"); }); $(".serviceContent").mouseout(function(){ $("button").removeClass("button-hover"); }); }); Add class in css .button-hover{color: red;} A: Just use the below given css to hover child elements css: #bestServiceBike:hover .btn.btn-primary{ background-color:#2639ff; } .serviceContent:hover .btn.btn-primary{ background-color:#2639ff; color:#fff; } check out this fiddle:https://jsfiddle.net/vn6txgyc/
doc_4690
I would like to know if there is any way that I can save the data of the remote notification to realm without entering the app or to the notification. I know that Whatsapp does that - even if Whatsapp app is close, when you are connected to the internet and you get a new messages or images, they saved the data to their local db.
doc_4691
<mx:Image id="image" width="100%" height="100%" source="@Embed('../assets/Test.swf')" complete="completeHandler(event)" progress="progressHandler(event)"/> But for some reason my completeHandler / progressHandler functions aren't being called. The reason I need the complete event is because I want to manipulate the bitmap data once the image has loaded. In creationComplete the bitmap data is still null. Why aren't these events firing? Edit: The asset is correctly showing in my application - so I know the asset is in the right location (the embed guarantees that at compile time anyway). A: Check your asset path. Most probably, the swf is not at the right path or is not getting copied to an assets folder in the debug-build/release-build directory. A: If you're using an embedded asset, the width / height properties are available immediately on the source object: var mySource:Object = new embeddedClass(); m_myWidth = mySource.width; m_myHeight = mySource.height; m_image = new Image(); m_image.source = mySource; So, you have to create an instance of the source first, then set the source on your image object. A: So, you just have to add the Event.COMPLETE listener to the loader.contentLoaderInfo directly instead of to the loader. I can't believe this isn't int he docs. A: That seems to be the expected behavior here! From the documentation: The progress event is not guaranteed to be dispatched. The complete event may be received, without any progress events being dispatched. This can happen when the loaded content is a local file. So I think this part can explain why no progress events are being caught in your example. Dispatched when content loading is complete. Unlike the complete event, this event is dispatched for all source types. Note that for content loaded via Loader, both ready and complete events are dispatched. For other source types such as embeds, only ready is dispatched. It clearly says that you should listen for READY events instead of COMPLETE when dealing with embedded sources ;)
doc_4692
You can delete objects in the graph by issuing HTTP DELETE requests to the object URLs, i.e, DELETE https://graph.facebook.com/ID?access_token=... HTTP/1.1 But since Im such a noob, I dont fully understand the short explanation of deleting with an HTTP request. Since it did not work when I tried, I assume that simply redirecting to the formed url in the example above does not delete anything. This means theres some new area of web development that I now have to understand... HTTP requests. How are these done in php? The php manual isnt helping much either. Additional Information: I have tried many different variations of: $facebook->api($post_url, 'DELETE', array('method'=> 'delete') ); The URL I am passing is '/post_id'. The post_id is being captured at post creation and stored into the database. This id matched the $_GET['story_fbid'] that can be found on any post permalink. Perhaps this is not the correct id? I am retrieving the id with the following: //post to wall $postResult = $facebook->api($post_url, 'post', $msg_body ); //capture the id of the post $this->fb_post_id = $postResult['id']; When I run the code above, no errors are thrown. It is being touched because a diagnostic echo after it is running. These are the different combinations of strings I have passed to api with $post_url: /postid api returns true, nothing is deleted from Facebook /userid_postid api returns false, Error: (#100) Invalid parameter /postid_userid api returns false, Error: (#1705) : Selected wall post for deletion does not exist /accesstoken_postid api returns false, Error: (#803) Some of the aliases you requested do not exist /postid_accestoken api returns false, Error: (#803) Some of the aliases you requested do not exist A: This should work: $facebook->api("/YOUR_POST_ID","DELETE"); will return a boolean value, true if successed and false if failed. Try prepending userid to the object ID when deleting, like: $facebook->api("/USER-ID_YOUR-POST-ID","DELETE"); like: $facebook->api("/12345132_5645465465454","DELETE"); //where 12345132 is fb userid and //5645465465454 is object id --> post id A: I have had success deleting posts from a page using the page access token with read_stream and manage_pages permissions. try { $args = array( 'access_token' => $page_token ); $deleted = $facebook->api('/'.$post_id, 'DELETE', $args); } catch (FacebookApiException $e) { echo 'Delete review page wall error: ' . $e->getType() . ' ' . $e->getMessage(); } A: Updated answer: Based on your comment "this is a page" I had a look at the Graph API's Page details. If I understand the details right, Delete is unsupported for Page Posts. Each connection in the details (Events, Posts, Question etc) have a Create section and if the Connection supports Delete it has a Delete description. The Posts (to feed) section only mentions Create, not Delete. A: You cannot "unpublish" a post but this isn't the same as deleting a post. Deleting a post is quite easy. You only need to get the COMMENT_ID and post it to Facebook. $post_url = 'https://graph.facebook.com/'. $COMMENT_ID .'?access_token=' . $page_access_token . '&method=delete'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $post_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $return = curl_exec($ch); curl_close($ch); To clarify this: this works outside of the Page API if you have the rights to manage the posts. A: I was able to delete post from page using php SDK 5.4 using this $post = $fb->request('DELETE', '/'.$post_id,[], $page['accesstoken'])
doc_4693
It contains a list of columns with true/false fields of the same nature and also has a field containing a comma-delimited list of abbreviations. Both of these could be candidates for forming extra tables. For the abbreviations What I'm currently doing is manually entering a PK as follows (notice the static integer on the select): INSERT recipe_ingredients( recipe_id, ingredient_id ) SELECT uid, "1" FROM ingredients -- ANCHO = Anchovies WHERE ingredients_abbrev LIKE "%ANCHO%" ON DUPLICATE KEY UPDATE recipe_id = recipe_id Is there a way I could run a query that uses all three tables so the intermediary table is filled in one go?
doc_4694
I did almost everything until now, but cannot get four images to be responsive and stay where the should be. This is the end result I want to achieve: What I have: I've used the: class="img-responsive center-block" class. This is my Bootply: http://www.bootply.com/ksrPd5iBSR I would be very grateful for any hint. A: center-block has a property display: block which is aligning the images vertically as default behavior of block is to occupy full width of space. Add a text-center class to the parent container to align it in center. Add a custom class with display: inline-block for the images. Updated Bootply
doc_4695
I can view this test customers orders in Admin, all old orders and new orders show up normally. This lack of order history happens with old and newly created customers. I feel there is something weird going on with how the customer account relates/configured to the store. If so where in the DB should I be looking to validate this hunch? Has anyone seen anything like this, Thanks for your help! I have tested this using old imported customers from 1.9.4 and new customers. No change in order history shown. I expect to see the full history of my customers orders. instead, I'm greeted with a "You have placed no orders." message.
doc_4696
https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[API_KEY] I have pass correct token and param same as in documentation but still, it returns 400 OPERATION_NOT_ALLOWED https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[API_KEY] Param:- { "email": "test@test.com", "password": "123123", "returnSecureToken": true } Response { "error": { "code": 400, "message": "OPERATION_NOT_ALLOWED", "errors": [ { "message": "OPERATION_NOT_ALLOWED", "domain": "global", "reason": "invalid" } ] } } A: Go to firebase console -> authentication -> sign-in method and then enable email/password providers
doc_4697
Is it possible to use authentication by OIDC and provisioning of users/groups by SCIM at the same time? We are developing a scratch application and would like to use Open ID Connect for authentication, but we would like to store user/group information within the application and would like to use SCIM provisioning to solve this issue. We wanted to solve this problem by provisioning with SCIM. However, it appears that if we want to use SCIM provisioning, we need to register our own application as an enterprise application. On the other hand, if I register it as an enterprise application, I can't seem to use OIDC as a single sign-on method. Based on the above, it seems to me that OIDC and SCIM cannot be used together, is that correct? Regards, Keiichi Hikita * *I wanted to register my own application as an enterprise application, so I chose to register an enterprise application *Select SSO method *Only SAML is shown *Register as just an application *Authentication with OIDC seems to work. *But this time, I can't register provisioning settings by SCIM in the provisioning menu. These are the reasons for the above question. A: I believe you will need to create two applications - one for OIDC-based SSO, and a second one that is marked as SAML but does not have any SAML/SSO configured, but instead is just used for the SCIM provisioning configuration.
doc_4698
I am looking for a model which doesn't require too much special coding in my app code. I understand there are two async worker types, gevent and gthread, which can solve this problem. What is the difference between these two and and does my app need to be thread safe to use these? UPDATE - I did some reading on gevent it seems it works by monkey patching std library functions so I would think that in the case of a database query in general it probably wouldn't patch whatever db library I am using so if I would need to program my app to cooperatively yield control when I waiting on the database. Is this correct? A: If you use threads, you must write your application to behave well, e.g. by always using locks to coordinate access to shared resources. If you use events (e.g. gevent), then you generally don't need to worry about accessing shared resources, because your application is effectively single-threaded. To answer your second question: if you use a pure python library to access your database, then gevent's monkey patching should successfully render that library nonblocking, which is what you want. But if you use a C library wrapped in Python, then monkey patching is of no use and your application will block when accessing the database.
doc_4699
(doStuff2() will be called through a Class1 pointer. That will call doStuff() in a loop. There are multiple classes like Class3 so Class2 will have multiple template instances.) struct Class1{ virtual void doStuff2() = 0; }; template<typename T> struct Class2 : public Class1{ virtual void doStuff() { /*code*/}; void doStuff2() override { // Call this in a huge loop. doStuff(); } }; struct Class3 : public Class2<SomeType>{ void doStuff() override final { /*code*/}; }; //... void someFunc(Class1 *p_class1){ p_class1->doStuff2(); } My questions: Is there a way to call doStuff() in a non-virtual way so there is no overhead? Would making it pure-virtual in Class2 and final in Class3 help? Does calling the same virtual function in such loop have all the performance problems of virtual functions? A: The comments have some good advice on why this might be premature optimization, but to answer your question directly: Is there a way to call doStuff() in a non-virtual way so there is no overhead? If you have a fixed set of types, then you can runtime-dispatch non-virtual methods by way of a tagged union, ala std::variant: using Class1 = std::variant<Class2<SomeType1>, Class2<SomeType2>>; /*...*/ std::visit([](auto&& c) { c.doStuff(); }, p_class1); Which roughly optimizes down to some good-ol' C-style switching: switch (p_class1.class_type) { case CLASS2_SOMETYPE1: ((Class2<SomeType1>)p_class1).doStuff(); break; /*...*/ } Does calling the same virtual function in such loop have all the performance problems of virtual functions? Modern processors are pretty good at indirect branch prediction, so you probably won't see much overhead calling a virtual method in a loop.