Posts

Showing posts from August, 2007

Blue In Hex Color Code Example

Example: rgb yellow color rgb ( 255 , 255 , 0 ) /* yellow*/ Hex #FFFF00

Catching An Exception While Using A Python 'with' Statement

Answer : from __future__ import with_statement try: with open( "a.txt" ) as f : print f.readlines() except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available print 'oops' If you want different handling for errors from the open call vs the working code you could do: try: f = open('foo.txt') except IOError: print('error') else: with f: print f.readlines() The best "Pythonic" way to do this, exploiting the with statement, is listed as Example #6 in PEP 343, which gives the background of the statement. @contextmanager def opened_w_error(filename, mode="r"): try: f = open(filename, mode) except IOError, err: yield None, err else: try: yield f, None finally: f.close() Used as follows: with opened_w_error("/etc/passwd", "a") as (f, err): if err: print "IO

Add CSS Rule Via JQuery For Future Created Elements

Answer : This should work: var style = $('<style>.class { background-color: blue; }</style>'); $('html > head').append(style); When you plan to remove elements from the DOM to re-insert them later, then use .detach() instead of .remove() . Using .detach() will preserve your CSS when re-inserting later. From the documentation: The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time. Here is some JavaScript code I wrote before to let me add, remove and edit CSS: function CSS(sheet) { if (sheet.constructor.name === 'CSSStyleSheet' ) this.sheet = sheet; else if (sheet.constructor.name === 'HTMLStyleElement') this.sheet = sheet.sheet; else throw new TypeError(sheet + ' is not a StyleSheet'); } CSS.prototype = {

Bootstrap Image Left Code Example

Example 1: how to make image responsive bootstrap 4 < img src = " ... " class = " img-fluid " alt = " Responsive image " > Example 2: bootstrap Aligning images Align images with the helper float classes or text alignment classes. block-level images can be centered using the .mx-auto margin utility class. < img src = " ... " class = " rounded float-left " alt = " ... " > < img src = " ... " class = " rounded float-right " alt = " ... " > < img src = " ... " class = " rounded mx-auto d-block " alt = " ... " > Example 3: bootstrap left image right text < div class = " card " > < div class = " row no-gutters " > < div class = " col-auto " > < img src = " //placehold.it/200 " class = " img-fluid " alt = " &q

Cmd Restart Command Code Example

Example: restart windows from cmd shutdown /r

C++ Vs. The Arduino Language?

Answer : My personal experience as professor (programming, mechatronics) is that if you have previous programming experience and you are aware of concepts as OOP, it is better to go for C/C++. The arduino language is really great for beginners, but have some limitations (e.g. you must have all your files in the same folder). And it is basically a simplification of C/C++ (you can practically copy&paste arduino code to a C/C++ file, and it will work). Also it makes sense that you can go and use a full well known IDE as eclipse: http://playground.arduino.cc/Code/Eclipse Initially it is required a bit more of setup and configuration of your dev environment, but IMHO it is worth it for programmers with experience in any other language. In any case, it won't harm you to start using the arduino language and the arduino IDE for a few days to get familiar with the arduino hardware and then move to C/C++ with Eclipse for really developing your project. In theory... There isn&#

Add A React-bootstrap Alert To HandleSubmit In Formik

Answer : Use state and conditional rendering. Instead of returning a component set state to a variable, in your render use conditional rendering to check if the value is true. handleSubmit = (formState, { resetForm }) => { // Now, you're getting form state here! const payload = { ...formState, role: formState.role.value, createdAt: firebase.firestore.FieldValue.serverTimestamp() }; console.log('formvalues', payload); fsDB .collection('register') .add(payload) .then(docRef => { resetForm(initialValues); }) .then(e => this.setState({ alert: true })) .catch(error => { console.error('Error adding document: ', error); }); }; In your render render() { ... return( .... {this.state.alert && <AlertDismissible />} ... ) } Example Demo Complete form import React from 'react'; import { Link } from 'react-router-dom'; import { Formik, Form, F

(->) Arrow Operator And (.) Dot Operator , Class Pointer

Answer : you should read about difference between pointers and reference that might help you understand your problem. In short, the difference is: when you declare myclass *p it's a pointer and you can access it's members with -> , because p points to memory location. But as soon as you call p=new myclass[10]; p starts to point to array and when you call p[n] you get a reference, which members must be accessed using . . But if you use p->member = smth that would be the same as if you called p[0].member = smth , because number in [] is an offset from p to where search for the next array member, for example (p + 5)->member = smth would be same as p[5].member = smth Note that for a pointer variable x myclass *x; *x means "get the object that x points to" x->setdata(1, 2) is the same as (*x).setdata(1, 2) and finally x[n] means "get the n-th object in an array". So for example x->setdata(1, 2) is the same as x[

If Is Nan Matlab Code Example

Example 1: if is nan matlab A ( isnan ( A ) ) = 1 ; Example 2: if is nan matlab if any ( isnan ( PMatrix ) , 'all' )

Python Set Logging Level For All Loggers Code Example

Example 1: python logging to file import logging import sys logger = logging . getLogger ( ) logger . setLevel ( logging . INFO ) formatter = logging . Formatter ( '%(asctime)s | %(levelname)s | %(message)s' , '%m-%d-%Y %H:%M:%S' ) stdout_handler = logging . StreamHandler ( sys . stdout ) stdout_handler . setLevel ( logging . DEBUG ) stdout_handler . setFormatter ( formatter ) file_handler = logging . FileHandler ( 'logs.log' ) file_handler . setLevel ( logging . DEBUG ) file_handler . setFormatter ( formatter ) logger . addHandler ( file_handler ) logger . addHandler ( stdout_handler ) Example 2: pythong logging logger to string import logging try : from cStringIO import StringIO # Python 2 except ImportError : from io import StringIO class LevelFilter ( logging . Filter ) : def __init__ ( self , levels ) : self . levels = levels def filter ( self , record ) :

Advantages Of Using Arrays Instead Of Std::vector?

Answer : In general, I strongly prefer using a vector over an array for non-trivial work; however, there are some advantages of arrays: Arrays are slightly more compact: the size is implicit. Arrays are non-resizable; sometimes this is desirable. Arrays don't require parsing extra STL headers (compile time). It can be easier to interact with straight-C code with an array (e.g. if C is allocating and C++ is using). Fixed-size arrays can be embedded directly into a struct or object, which can improve memory locality and reducing the number of heap allocations needed. Because C++03 has no vector literals. Using arrays can sometime produce more succinct code. Compared to array initialization: char arr[4] = {'A', 'B', 'C', 'D'}; vector initialization can look somewhat verbose std::vector<char> v; v.push_back('A'); v.push_back('B'); ... I'd go for std::array available in C++0x instead of plain arrays which can

Are Session And SessionScope The Same In JSP EL?

Answer : With expression language (EL), the scope items are value maps of attributes in the objects that they refer to. For instance, the requestScope is a map representation of values in the request object. This is explained in pretty clear detail on this page: Java Servlet and JSP. If you read through the EL sections, you'll notice a point about request vs request scope here: The requestScope is NOT request object. I would recommend reading through this page to get a better understanding of servlet/jsp in general. As far as how the ActionContext relates to these items, it is really a wrapper used by struts to encapsulate the servlet. You can read more specifics about it here: Accessing application, session, request objects. There have been some references to implicit values given here, but I feel like just saying it's implicit doesn't really explain much. When you are using EL to access servlet variables, you can explicitly declare which scope you want to referen

Android Attaching A File To GMAIL - Can't Attach Empty File

Answer : Ok, got it to work now, after a lot of research and intercepting some Intents. What I had to do was change the file:/// to content://. I did this following this information from Android: https://developer.android.com/reference/android/support/v4/content/FileProvider.html The only major change was that I used a hard-coded path to /sdcard/file.ext. Also, the line getUriForFile(getContext(), "com.mydomain.fileprovider", newFile); was changed to Uri contentUri = FileProvider.getUriForFile(this, "com.mydomain.fileprovider", newFile); Also had to include: intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); i.setData(contentUri); I do not really understand why I had to change from File to Content , but after this, the file is now being attached again! See the link if you face this issue, and don't forget about the new .xml that needs to be created. See the following question:

Can't Change Default Nuxt Favicon

Answer : I found the solution, but it's kind of tricky and it's a little far from logic. the size of the favicon should be 32*32 pixels or nuxt will load the default favicon itself. and about my tries, it's enough to have a file in your static folder and give the path to nuxt.config.js . but I'm still confused with the solution. Have you tried replace type: 'image/x-icon' with type: 'image/png' ? The infos about this attribute and tag generally can be read here nuxt will convert object like { head: { link: [{ rel: 'icon', type: 'image/png', href: '/favicon.png' }] }} to <head> <link rel='icon' type='image/png' href='/favicon.png'> </head> So you can use any attributes listed in the article above.

325 F To C Code Example

Example 1: c to f let f = c * ( 9 / 5 ) + 32 ; let c = ( f - 32 ) * ( 5 / 9 ) ; Example 2: 14 f to c 14 °F = - 10 °C

Number Of Repitations In The Vector In Descending Order Code Example

Example: sort vector descending int main ( ) { // Get the vector vector < int > a = { 1 , 45 , 54 , 71 , 76 , 12 } ; // Print the vector cout << "Vector: " ; for ( int i = 0 ; i < a . size ( ) ; i ++ ) cout << a [ i ] << " " ; cout << endl ; // Sort the vector in descending order sort ( a . begin ( ) , a . end ( ) , greater < int > ( ) ) ; // Print the reversed vector cout << "Sorted Vector in descendiing order:n" ; for ( int i = 0 ; i < a . size ( ) ; i ++ ) cout << a [ i ] << " " ; cout << endl ; return 0 ; }

Ajax Cdn Code Example

Example 1: ajax cdn < script src = " https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js " > </ script > Example 2: jquery cdn google < script src = " https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js " > </ script > Example 3: jqeury cdn //Note: This is for version 3.5.0. You can change it here \/ < script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js " integrity = " sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ= " crossorigin = " anonymous " > </ script > Example 4: jquery script tag < script src = " https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js " > </ script > // Put this script in the head of your index.html to load jQuery // The Google Hosted Libraries is a stable, reliable, high-speed, // globally available content distribution network for the most popular, // open-source Jav

Angularjs Select Code Example

Example 1: angularjs dropdown < select ng-options = " v.name for v in variants | filter:{type:2} " ng-change = " calculateServicesSubTotal(item) " ng-model = " item.selectedVariant " ng-show = " item.id==8 " name = " posterVariants " ng-required = " item.id==8 && item.quantity > 0 " class = " ng-pristine ng-valid ng-valid-required " > < option value = " ? " selected = " selected " > </ option > < option value = " 0 " > set of 6 traits </ option > < option value = " 1 " > 5 complete sets </ option > </ select > Example 2: selectangularjs < select ng-model = " string " [name = " string " ] [multiple = " string " ] [required = " string " ] [ng-required = " string " ] [ng-change = " string " ] [ng-options = &

Bootstrap Facebook Linkedin Icons Code Example

Example: bootstrap social media icons Refer link : https://www.programmingquest.com/2020/04/create-social-media-icon-using-html-css.html < html > < head > < title > Social Media Icon Example </ title > <!-- Adding font awesome icon library --> < link rel = " stylesheet " href = " https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css " > < style > .fa { width : 25 px ; padding : 20 px ; font-size : 25 px ; text-align : center ; text-decoration : none ; margin : 5 px 2 px ; color : white ; border-radius : 50 % ; } .fa :hover { opacity : 0.7 ; } .fa-facebook { background : #3B5998 ; } .fa-twitter { background : #55ACEE ; } .fa-google { background : #dd4b39 ; } .fa-linkedin { background : #007bb5 ; } .fa-

Ahk Auto Clicker Code Example

Example: ahk autoclicker toggle = 0 #MaxThreadsPerHotkey 2 F1:: Toggle := !Toggle While Toggle{ Click sleep 100 } return

Change Keystore Password From No Password To A Non Blank Password

Answer : If you're trying to do stuff with the Java default system keystore ( cacerts ), then the default password is changeit . You can list keys without needing the password (even if it prompts you) so don't take that as an indication that it is blank. (Incidentally who in the history of Java ever has changed the default keystore password? They should have left it blank.) Add -storepass to keytool arguments. keytool -storepasswd -storepass '' -keystore mykeystore.jks But also notice that -list command does not always require a password. I could execute follow command in both cases: without password or with valid password $JAVA_HOME/bin/keytool -list -keystore $JAVA_HOME/jre/lib/security/cacerts

Android Dual SIM Signal Strength

Answer : For this particular version of TelephonyManager, instead of using TelephonyManager.listen (phoneStateListener, state) which only listens on the default SIM, you may try using 2 instances of your PhoneStateListener, and call TelephonyManager.listenGemini (phoneStateListener1, state, 0) for the 1st SIM, and TelephonyManager.listenGemini (phoneStateListener2, state, 1) for the 2nd SIM, where the third parameter for listenGemini is the SIM number. Thanks for the answer headuck! I have not tried your solution, but i found my own solution which worked. It is possible to use a different constructor for the TelephonyManager where you can pass in the sim card slot you want control over: MultiSimClass = Class.forName("android.telephony.MultiSimTelephonyManager"); for (Constructor<?> constructor : MultiSimClass.getConstructors()){ if (constructor.getParameterTypes().length == 2){ try { multiSimTeleph

Angle Bracket Latex Code Example

Example: latex angle brackets \langle \rangle