id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23531400
implicit class Rep(n: Int) { def times[A](f: => A): Seq[A] = { 1 to n map(_ => f) } } val myHis= 13849.times { println("2.4848911616270923")} this code which repeate value 2.484. How to save it in parquet file? A: import org.apache.spark.sql._ val myHis:Dataset[String] = ??? val path:String = ??? //the path you want myHis.write.mode(SaveMode.Overwrite).parquet(path) Try this
doc_23531401
A: = is not an operator. = is an assignment statement. Because it is a statement, it can't be part of an expression (expressions are instead part of certain statements, and never the other way around), so ordering is irrelevant. The expression is always executed to serve a statement. For assignments, the grammar specifies that specific types of expressions are permitted after the = symbol: assignment_stmt ::= (target_list "=")+ (starred_expression | yield_expression) and the documentation for that statement details what order things are executed in: An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.
doc_23531402
BlogData<T> { final Firestore _db = Firestore.instance; final String path; CollectionReference ref; BlogData({ this.path }) { ref = _db.collection(path); } Future<List<T>> getData() async { // get blog data and do a join here to a user document by uid (document/blog.uid) return a future of blogs with user data such as name, country added to each blog in the future list. } Stream<List<T>> streamData() { // get blog data and do a join here to the user document by uid (document/blog.uid) return a stream of blogs with user data such as name, country added to each blog in the stream. } } How can I achieve this?
doc_23531403
I am working on the models related to accelerometer data. Initially, whenever I got the model by edge impulse, it had nano_ble_accelerometer_continuous file. And with some tweaks it was working on Arduino RP2040. But today, when I was working on the new model, this new model library did,'t contain the nano_ble_accelerometer_continuous but only nano_ble_accelerometer. I thought I had some problems in my trained data. Hence, I went to the model which I created in the start of month for which I got nano_ble_accelerometer_continuous file back before then. But when I run it now, I again got nano_ble_accelerometer for that model too. Am I am going wrong anywhere or there is some major update? I need to have a accelerometer_continous code. A: Late to the party, but this was resolved a few weeks back, and the continuous sketch is now included again.
doc_23531404
Currently I am using a Postgres database where all my data resides in a single database in the default public schema. I would like to isolate each tenant to a separate Postgres schema. Ideally, my application's UI would make a call to my API using the tenant's subdomain. In before_request I would somehow be able to set all database queries during the current request context to only query that tenant's schema, is this possible? I envisage an ideal solution to be something similar to this contrived example: from flask import Flask, request, jsonify from pony.orm import Database, Required app = Flask(__name__) db = Database(**{<db_connection_dict>}) class User(db.Entity): email = Required(str) password = Required(str) @classmethod def login(cls, email: str, password: str) -> str: user = cls.get(lambda u: u.email.lower() == email.lower()) if not user: return None password_is_valid = <method_to_check_hashed_pasword> if not password_is_valid: return None return <method_to_generate_jwt> db.generate_mapping() @app.before_request def set_tenant(): tenant_subdomain = request.host.split(".")[0] // MISSING STEP.. set_schema is a fictitous method, does something similar to this exist? db.set_schema(schema=tenant_subdomain)?? @app.route("auth/login", methods=["POST"] def login_route(): data = request.get_json() jwt = User.login(data["email"], data["password"]) if not jwt: return make_response({}, 403) return make_response(jsonify(data=jwt), 200) I've come across an interesting/simple example using SQLAlchemy. If not possible with PonyORM I may consider porting my models over to SQLAlchemy but would miss the simplicity of Pony :( I thought about possibly using the Database.on_connect method to do something as such but not sure if if anyone has any other ideas or if this would even work properly in production. I suspect not because if I had two separate tenants querying the database they would overwrite the search path.. @db.on_connect() def set_request_context_tenant_schema(db, connection) -> None: subdomain = request.host.split(".")[0] cursor = connection.cursor() cursor.execute(f"SET search_path TO {subdomain}, public;")
doc_23531405
A: You say D3DXCompile "Texture" FromFile in your post body, I will assume you mean D3DXCompileShaderFromFile. That function compiles shader code, which is a variation of C that is compiled specifically to run on the GPU, per vertex or per pixel. D3DXCreateTextureFromFile creates a texture, which can be used by a shader for any number of purposes but is usually used for texturing, which is described quite well in this article.
doc_23531406
A: For a plain vanilla answer to your question, simply look at screen.height or screen.width. e.g. window.screen.height window.screen.width For browser dimensions, you can simply use window.height or window.width If you're looking at altering design/layout based on available space, you want to look at media queries or using a framework like Bootstrap, Foundation or Skel.js which introduce more accessible control over responsiveness. Media Queries is a CSS3 module allowing content rendering to adapt to conditions such as screen resolution (e.g. smartphone vs. high definition screen). It became a W3C recommended standard in June 2012. and is a cornerstone technology of Responsive Web Design. [...] Responsive Web Design (RWD) is a Web design approach aimed at crafting sites to provide an optimal viewing experience—easy reading and navigation with a minimum of resizing, panning, and scrolling—across a wide range of devices (from mobile phones to desktop computer monitors) A: Here is a code : document.write("Available Width: " + screen.availWidth); document.write("Available Height: " + screen.availHeight); Source : http://www.w3schools.com/js/js_window_screen.asp Cannot comment but here is solution for browser height : window.innerHeight/Width Provided by most browsers, but not Internet Explorer 8-, and even in Internet Explorer 9+, it is not available in quirks mode. document.body.clientHeight/Width Provided by many browsers, including Internet Explorer. document.documentElement.­clientHeight/Width Provided by most DOM browsers, including Internet Explorer. Source : http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
doc_23531407
Just to clarify, I am not talking about maintaining activity state (i.e. keeping track of textbox values, checkboxes, etc on a specific activity). Let's say for example my application has two activities A and B. When I start my app, it takes me to activity A, and pressing a button on it takes me to activity B. At this point, I press the home button on my phone to return to the main Android UI and exiting my app . However, if I choose to run my app again, it should take me to activity B, which is where I left off before pressing the home button, but instead it is taking me to activity A. Does anyone know how I can rectify this? (I am using a Samsung Vibrant in case if you need to know) A: "However, if I choose to run my app again, it should take me to activity B, which is where I left off before pressing the home button, but instead it is taking me to activity A." Yes, it should. If it isn't, you have done something in your app to tell the platform to modify its behavior. (Look at ApiDemos as an example, it uses the standard behavior, which is what it sounds like you are describing as what you expect.) Things to look out for: * *Don't use FLAG_ACTIVITY_NEW_TASK when launching activities. *Don't use the singleTask or singleInstance launch modes. *Don't see the clearTaskOnReset flag. A: You're imagining there's something called an "Application" but that's an illusion. Your application is just a collection of Activities, Services, Receivers, etc. If you look at the intent-filter tags in your manifest, you'll see that each icon in the home screen is associated with a filter like this: <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> You can put that same chunk of XML on both of your Activities, and you'll get two icons in the home screen, one that always launches Activity A, and one that always launches Activity B. What you may want to do instead is create a master Activity that launches one of the other Activities based on the shared state. As for where to actually store the shared state, that depends on how complex your state is. This is a good place to start: http://developer.android.com/guide/topics/data/data-storage.html A: As I understand the question you want to launch your application and have a different thing happen each time depending on where you left off the last time. http://developer.android.com/reference/android/app/Application.ActivityLifecycleCallbacks.html The activity lifecycle is in the link. Your onActivityDestroyed method somehow needs to persist the present state and the oncreate needs to pick it back up. Persistence can be achieved via shared preferences, stored in a file, database or over the network http://developer.android.com/guide/topics/data/data-storage.html This unpredictable behavior could cause confusion for the end user if poorly implemented so use good judgement.
doc_23531408
Problem is JTable should occupy entire space width but JTable always places in center and other components gets added to its right. If I make JTable occupy entire width by using table.setPreferredScrollableViewportSize(table.getPreferredSize()); scrollbar is not visible. How to make JTable occupy entire space and other components getting added to its bottom? A: If I make JTable occupy entire width by using table.setPreferredScrollableViewportSize(table.getPreferredSize()); This is for JTable with a few, fixed rows and columns, or in the case that on apps startup is there intialized JTable with fixed number of rows and columns. How to make JTable occupy entire space and other components getting added to its bottom? and your comment Using Grid Layout videopanel.setLayout( new GridLayout(1,1)); * *change GridLayout to BorderLayout (by assuming that there is JPanel placed in Tab) *put JScrollPane (contains JTable) to the BorderLayout.CENTER area *put other JComponents to separate JPanel, this JPanel (contains other JComponents) put to the BorderLayout.SOUTH area. A: Which layout are you using to place component on JPanel. please have a look into the following URL http://docs.oracle.com/javase/tutorial/uiswing/components/table.html
doc_23531409
msgStr = validate(...); document.getElementById("msgArea").innerHTML = msgStr; But if the user clicks submit again (possibly changing the data but getting the same validation error), there is no feedback to them that the submit actually did anything. The page sits there "frozen" (to the user). I tried to clear the area before calling validation with: document.getElementById("msgArea").innerHTML = ''; msgStr = validate(); document.getElementById("msgArea").innerHTML = msgStr; but this doesn't show any effect. I assume that either the browser doesn't have time to update the rendering before the same msgStr is set, or it happens so quickly that the user doesn't see the "flash". Any suggestions on how to provide feedback in this case? A: It's most likely that you don't see it change because the flash is too fast. If you're using a javascript library (jquery, yui, etc...), you can use a fade in function to make it more noticeable. If not, you can use a series of timers and style changes to make the change more noticeable. Here's a fiddle that demonstrates how to do that: http://jsfiddle.net/cbargren/S6ZjC/ A: Sounds like JavaScript might be dying somewhere. Open you page in Google Chrome and go to "tools > JavaScript Console." If it is breaking you will see red error messages. From there you have a better chance at knowing what the problem is. If you are still stumped tell us the errors you are getting along with any additional useful code. A: As stated previously, the problem is due to the idea that your steps are sequential but in actual fact occur near instantaneous from a user's perspective. I'd be looking to apply an "updated" state to the form (eg: a class) which changes in some small way the validation message. That way, upon validation the "udpated" state is removed (that is, the data is once again "stale") until such time as the user changes something again. This works better with focus and/or alterations to the data (so you need to hold the content until an update to a field occurs).
doc_23531410
- task: InstallAppleProvisioningProfile@1 displayName: 'Install an Apple provisioning profile' inputs: provisioningProfileLocation: 'sourceRepository' provProfileSecureFile: '$(System.ArtifactsDirectory)/ios_artifacts/InHouse_com.xxxx.xxxxx.mobileprovision' the file do exist in this path, but when executing the pipeline I'm getting this error/warning : when i manually press the button its continue, how can I avoid this? A: We should authorize the resource before we use it, we need click the button Authorize resources to authorize, then we can use the file in the pipeline. Or open project settings->Settings->check the option Limit job authorization scope to current project for non-release pipelines and Limit job authorization scope to referenced Azure DevOps repositories. Please refer this doc for more details.
doc_23531411
<hr /> If I render a collection of users for example then after each user it will render <hr />. Here's how I specify the spacer template in my view. render :partial => @users, :spacer_template => "users/user_separator" This works fine but I was wondering if there's a way to render the spacer template by itself from within my controller. Something like render_to_string but specifically for just the spacer template. I need this because I am doing an ajax request to add a user comment. Right now I can successfully render the comment with render_to_string but since it's not a collection the spacer template is not showing up.
doc_23531412
https://www.elastic.co/guide/en/elasticsearch/reference/current/security-basic-setup.html#generate-certificates where i need do below /bin/elasticsearch-keystore add xpack.security.transport.ssl.keystore.secure_password ./bin/elasticsearch-keystore add xpack.security.transport.ssl.truststore.secure_password Exception "Caused by: org.elasticsearch.ElasticsearchSecurityException: failed to load SSL configuration [xpack.security.transport.ssl]", "Caused by: org.elasticsearch.ElasticsearchException: failed to initialize SSL TrustManager", "Caused by: java.io.IOException: keystore password was incorrect", "Caused by: java.security.UnrecoverableKeyException: failed to decrypt safe contents entry: javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.", ElasticsearchSecurityException[failed to load SSL configuration [xpack.security.transport.ssl]]; nested: ElasticsearchException[failed to initialize SSL TrustManager]; nested: IOException[keystore password was incorrect]; nested: UnrecoverableKeyException[failed to decrypt safe contents entry: javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.]; Likely root cause: java.security.UnrecoverableKeyException: failed to decrypt safe contents entry: javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
doc_23531413
This is how my daylight cycle works (it is quite bad and the night is longer, but it is only for testing): #Setting up lighting game_alpha = 4 #Keeping it simple for now game_time = 15300 time_increment = -1 alpha_increment = 1 #Main Game Loop: if float(game_time)%game_alpha == 0: game_alpha += alpha_increment print "Game Alpha: ",game_alpha print "Game Time: ", game_time if game_time < 0: time_increment = 1 alpha_increment = -1 elif game_time >= 15300: time_increment = -1 alpha_increment = 1 game_shadow = pygame.Surface((640, 640)) game_shadow.fill(pygame.Color(0, 0, 0)) game_shadow.set_alpha(game_alpha) game_shadow.convert_alpha() screen.blit(game_shadow, (0, 0)) A: While there may be a way to assign different alpha channels to different pixels, this would be difficult and if you were doing it per-pixel it would significantly slow down your program (if you are really determined to do this, the closest thing I could find was pygame.Surface.set_at). It seems that you probably are best off just breaking down the screen into smaller surfaces. You could even achieve an easy gradient by making them overlap. This way you can set various brightnesses to areas, to get both effects. Below is a basic example of a tile grid used to achieve what you want: tiles = [] column = [] for row in range(10): for column in range(10): #These dimensions mean that the screen is broken up into a grid of ten by ten smaller tiles for lighting. tile = pygame.Surface((64, 64)) tile.fill(pygame.Color(0, 0, 0)) tile.set_alpha(game_alpha) tile.convert_alpha() column.append(tile) tiles.append(column) #this now gives you a matrix of surfaces to set alphas to def draw(): #this will draw the matrix on the screen to make a grid of tiles x = 0 y = 0 for column in tiles: for tile in column: screen.blit(tile,(x,y)) x += 64 y += 64 def set_all(alpha): for column in tiles: for tile in column: tile.set_alpha(alpha) def set_tile(x,y,alpha): #the x and y args refer to the location on the matrix, not on the screen. So the tile one to the right and one down from the topleft corner, with the topleft coordinates of (64,64), would be sent as 1, 1 Xindex = 0 Yindex = 0 for column in tiles: for tile in column: if Xindex == x and Yindex == y: tile.set_alpha(alpha) #when we find the correct tile in the coordinates, we set its alpha and end the function return x += 1 y += 1 This should give you what you want. I also included some functions to access the set of tiles. Set_all will change the alpha of the whole screen by a certain amount, set_tile will only change the alpha of one tile, and draw will draw all of the tiles. You could improve upon this model more by overlapping tiles to get more exact lighting and gradients, and by making a tile class to inherit pygame.Surface, that will manage things like the tile's position.
doc_23531414
<address name="STATUS_LOG.V01"> <anycast> <queue name="STATUS_LOG.V01" /> </anycast> </address> <address name="STATUS_LOG.V02"> <multicast> <queue name="STATUS_LOG.V01" /> </multicast> </address> When I send a message to the STATUS_LOG.V01 address I see it in the STATUS_LOG.V01 queue through the web UI as expected. When I publish a message to the STATUS_LOG.V02 address I expect to see the message in the STATUS_LOG.V01 queue, but I don't. We have an existing queue which receives status messages (STATUS_LOG.V01) from endpoint adapters. Ultimately, we would like to add another destination (STATUS_LOG.V02) (a topic destination - PUBSUB behavior) to be used for future releases. However, we want the messages received on the new topic to be routed to the existing queue. Is this doable in ActiveMQ Artemis? A: What you're seeing is the expected behavior since your configuration is not allowed. Queue names must be unique across the broker. You can't have the same queue bound to multiple addresses. You are trying to configure the queue STATUS_LOG.V01 on both addresses STATUS_LOG.V01 & STATUS_LOG.V02. When you start the broker you should see logging like this: INFO [org.apache.activemq.artemis.core.server] AMQ221080: Deploying address STATUS_LOG.V01 supporting [ANYCAST] INFO [org.apache.activemq.artemis.core.server] AMQ221003: Deploying ANYCAST queue STATUS_LOG.V01 on address STATUS_LOG.V01 INFO [org.apache.activemq.artemis.core.server] AMQ221080: Deploying address STATUS_LOG.V02 supporting [MULTICAST] INFO [org.apache.activemq.artemis.core.server] AMQ221003: Deploying MULTICAST queue STATUS_LOG.V01 on address STATUS_LOG.V02 WARN [org.apache.activemq.artemis.core.server] AMQ229019: Queue STATUS_LOG.V01 already exists on address STATUS_LOG.V01 Notice the last WARN logged. This indicates that the queue STATUS_LOG.V01 cannot be bound to address STATUS_LOG.V02 since it is already bound on address STATUS_LOG.V01. What you really need to do is create a divert to take messages sent to your STATUS_LOG.V02 address and forward them to your STATUS_LOG.V01 address. Use this instead of your original configuration: <address name="STATUS_LOG.V01"> <anycast> <queue name="STATUS_LOG.V01" /> </anycast> </address> <address name="STATUS_LOG.V02"> <multicast/> </address> <divert name="myDivert"> <address>STATUS_LOG.V02</address> <forwarding-address>STATUS_LOG.V01</forwarding-address> <exclusive>true</exclusive> </divert> It's not clear to me whether or not you'll want to set exclusive to true for your use-case or not. If exclusive is true then none of the JMS topic subscribers on STATUS_LOG.V02 will get the messages sent to STATUS_LOG.V02. All the messages sent to STATUS_LOG.V02 will be diverted exclusively to STATUS_LOG.V01. If exclusive is false then the JMS topic subscribers on STATUS_LOG.V02 will get messages sent to STATUS_LOG.V02 and the messages will also be diverted to STATUS_LOG.V01. You can read more about diverts in the documentation.
doc_23531415
Regards, j. A: To make changes in real time while scrolling you should use UIScrollView delegate method: -(void)scrollViewDidScroll:(UIScrollView *)scrollView; If you create 2 view controller and add their view as subviews of a scroll view, set the delegate property of your scroll view and add this code inside the delegate: -(void)scrollViewDidScroll:(UIScrollView *)scrollView { CGFloat offset = scrollView.contentOffset.x; CGFloat factor = offset / scrollView.bounds.size.width; _leftVC.view.backgroundColor = [UIColor colorWithHue:factor saturation:1.0 brightness:1.0 alpha:1.0]; _rightVC.view.backgroundColor = [UIColor colorWithHue:0.3 saturation:1.0 brightness:factor alpha:1.0]; } It just change the background color, but you can do everything you need synchronized with the scroll view offset.
doc_23531416
Here is the Material Design stuff: .form-group { position: relative; margin-bottom: 1.5rem; } .form-control-placeholder { position: absolute; top: 0; padding: 7px 0 0 13px; transition: all 200ms; opacity: 0.5; } .form-control:focus + .form-control-placeholder, .form-control:valid + .form-control-placeholder { font-size: 75%; transform: translate3d(0, -100%, 0); opacity: 1; } <div class="container my-5"> <div class="row"> <div class="col-md-6 mx-auto"> <div class="form-group"> <input type="text" id="name" class="form-control" required> <label class="form-control-placeholder" for="name">Name</label> </div> <div class="form-group"> <input type="password" id="password" class="form-control" required> <label class="form-control-placeholder" for="password">Password</label> </div> </div> </div> </div> A: Bootstrap 4 documentation has an example of Floating Labels, but it is considered an 'Experiment' https://getbootstrap.com/docs/4.1/examples/floating-labels/ Not quite 'all browsers' but specifically says 'Works in latest Chrome, Safari, and Firefox.' A: I've created an input floating label for Bootstrap 4 & 5: https://github.com/tkrotoff/bootstrap-floating-label Here is the online demo: https://codesandbox.io/s/github/tkrotoff/bootstrap-floating-label/tree/codesandbox.io
doc_23531417
<?php include '../dbc.php'; $tbl_name="image"; // Table name $sql="SELECT * FROM $tbl_name"; $result=mysql_query($sql); //detect file $directory = "../../Upload/"; $images = scandir($directory); $ignore = Array(".", ".."); ?> <table width="800px" style="background:white;margin:50px auto; font-size:13px;" border="1" cellpadding="3"> <tr> <td colspan="3"><strong>Delete:</strong> </td> </tr> <tr> <td width="40%" align="center"><strong>Name</strong></td> <td width="10%" align="center"><strong>Size</strong></td> <td width="5%" align="center"><strong>Delete</strong></td> </tr> <?php while($rows=mysql_fetch_array($result)){ ?> <tr id='del'> <td><?php echo $rows['name']; ?></td> <td><?php echo number_format($rows['imgSize'], 2) ?> MB</td> <td><a name="delete" href="delData1.php?id=<?php echo $rows['imgId']; ?>">Delete</a></td> </tr> <?php } ?> </table> <?php mysql_close(); ?> delData1.php <?php include '../dbc.php'; $tbl_name="image"; // Table name // get value of id that sent from address bar $id=$_GET['id']; $filename = $_POST['filename']; $path = $_POST['directory']; if(file_exists($path."/".$filename)) { unlink($path."/".$filename); //delete file } // Delete data in mysql from row that has this id $sql="DELETE FROM $tbl_name WHERE imgId='$id'"; $result=mysql_query($sql); // if successfully deleted if($result){ rmdir('$name'); echo "Deleted"; echo "<BR>"; header("Location:Data.php"); } else { echo "ERROR"; } ?> It's delete data from database, but file stay in folder.
doc_23531418
How does Apache Ignite distribute data? How can I control the distribution in Apache Ignite? For example, I want to distribute more data to some nodes (because they have more memory, and able to save more data), and less data to others nodes Thank you!! A: If you want to do this for one cache you can implement your version of affinity function (https://apacheignite.readme.io/docs/affinity-collocation#section-affinity-function), but this is not recommended because it will not be scalable. If you just want to specify mapping of node to the new cache you can try nodeFilter in CacheConfiguration.
doc_23531419
File "C:\Users\divya\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module> from tensorflow.python.pywrap_tensorflow_internal import * File "C:\Users\divya\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in <module> _pywrap_tensorflow_internal = swig_import_helper() File "C:\Users\divya\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 17, in swig_import_helper return importlib.import_module(mname) File "C:\ProgramData\Anaconda3\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "faceswap.py", line 33, in <module> ARGUMENTS.func(ARGUMENTS) File "D:\Projects\faceswap\lib\cli.py", line 36, in execute_script script = self.import_script() File "D:\Projects\faceswap\lib\cli.py", line 25, in import_script from scripts.train import Train as script File "D:\Projects\faceswap\scripts\train.py", line 9, in <module> import tensorflow as tf File "C:\Users\divya\AppData\Roaming\Python\Python36\site-packages\tensorflow\__init__.py", line 24, in <module> from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import File "C:\Users\divya\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\__init__.py", line 49, in <module> from tensorflow.python import pywrap_tensorflow File "C:\Users\divya\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in <module> raise ImportError(msg) ImportError: Traceback (most recent call last): File "C:\Users\divya\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module> from tensorflow.python.pywrap_tensorflow_internal import * File "C:\Users\divya\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in <module> _pywrap_tensorflow_internal = swig_import_helper() File "C:\Users\divya\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 17, in swig_import_helper return importlib.import_module(mname) File "C:\ProgramData\Anaconda3\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed. Failed to load the native TensorFlow runtime. link here A: The error is because of you might be using 32-bit Operating system or 32-bit Python. Also check does your CPU support AVX instruction set. Make sure all the dependencies given on Tensorflow are installed correctly.
doc_23531420
<?php class DatabaseConnect { protected $conn; protected $host, $username, $password, $database; public function __construct($host, $username, $password, $database){ // Create connection $this->conn = new mysqli($host, $username, $password,$database) OR die("There was a problem connecting to the database"); return true; } public function query($sql) { $result = $this->conn->query($sql); if (!$result) { die('Invalid query:'); } return $result; } public function __destruct(){ $this->conn->close() OR die("Problem disconnecting from the database"); } } class MemberModel extends DatabaseConnect { public function getAllMembers() { $result = $this->query("SELECT * FROM members"); return $result; } } To connect and retrieve from the database this is what I have been trying to do $db = new DatabaseConnect("localhost", "root", "", "pcaframework"); $allMembers = $db->getAllMembers(); while ($row = mysqli_fetch_assoc($allMembers)) { echo "First Name: " . $row['name'] ."<br />"; echo "Last Name: " . $row['email'] ."<br />"; echo "<hr />"; } but this is what I get "Fatal error: Call to undefined method DatabaseConnect::getAllMembers()". Can you point out the problem here. A: Your $db object should be an instance of MemberModel. The DatabaseConnect class does not contain the getAllMembers function. Change $db = new DatabaseConnect("localhost", "root", "", "pcaframework"); To $db = new MemberModel("localhost", "root", "", "pcaframework");
doc_23531421
... <properties> <certificate-manager.default-client-certDN>Default Client</certificate-manager.default-client-certDN> <certificate-manager.path-to-store>D:\Projects\PPP\apache-tomcat-7.0.29\</certificate-manager.path-to-store> <certificate-manager.store-password>12345</certificate-manager.store-password> <certificate-manager.alias>root</certificate-manager.alias> </properties> and properties file(my.properties): certificateManager.defaultClientCertDN=${certificate-manager.default-client-certDN} certificateManager.pathToStore=${certificate-manager.path-to-store} certificateManager.storePassword=${certificate-manager.store-password} certificateManager.alias=${certificate-manager.alias} and I want to use this properties in my spring context.xml(appContext.xml): <context:property-placeholder location="classpath:my.properties"/> <bean id="certificateManager" class="com.exadel.mdp.security.certificate.CertificateManagerImpl"> <constructor-arg name="defaultClientCertDN" value="${certificateManager.defaultClientCertDN}"/> <constructor-arg name="pathToStore" value="${certificateManager.pathToStore}"/> <constructor-arg name="storePassword" value="${certificateManager.storePassword}"/> <constructor-arg name="alias" value="${certificateManager.alias}"/> </bean> When I'm trying to run app, I get the next exception: ERROR: org.springframework.web.context.ContextLoader - Context initialization failed org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'certificateManager' defined in class path resource [appContext.xml]: Could not resolve placeholder 'certificateManager.defaultClientCertDN' in string value [${certificateManager.defaultClientCertDN}] at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.doProcessProperties(PlaceholderConfigurerSupport.java:209) at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.processProperties(PropertySourcesPlaceholderConfigurer.java:174) at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.postProcessBeanFactory(PropertySourcesPlaceholderConfigurer.java:151) at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:686) at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:661) A: I believe you use Maven Properties Plugin and configure it for initialization phase. Spring independently will read from the property file.
doc_23531422
1) Calculate some coordinates clicking button 1 2) Click button 2 to draw a line with the numbers from button 1 3) Click button 1 to get new coordinates 4) click button 2 to draw the previous line AND the new line. 5) click button 3 to clear the graph. So I decided to draw everthing on top of a Panel, called panel1. I have a routine that draws on screen called drawlines, Private Sub drawlines(ByVal g As Graphics, ByVal c As Color) Dim p As New Pen(c, 1) g.DrawLine(p, xStart, yStart, xEnd, yEnd) p.Dispose() End Sub and the other routines: Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load 'AddHandler Panel1.Paint, AddressOf DrawLine GraphicsHandler = Panel1.CreateGraphics End Sub Private Sub drawlines(ByVal g As Graphics, ByVal c As Color) Dim p As New Pen(c, 1) g.DrawLine(p, xStart, yStart, xEnd, yEnd) p.Dispose() End Sub Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click 'GraphicsHandler = Panel1.CreateGraphics GraphicsHandler.DrawLine(myPen, 10, 10, 200, 100) End Sub Private Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button2.Click xStart = CInt(Math.Ceiling(Rnd() * 200)) yStart = CInt(Math.Ceiling(Rnd() * 100)) xEnd = CInt(Math.Ceiling(Rnd() * 200)) yEnd = CInt(Math.Ceiling(Rnd() * 100)) Me.Panel1.Invalidate() End Sub Private Sub Panel1_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) Handles Panel1.Paint drawlines(e.Graphics, Color.Blue) End Sub Private Sub Button3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click GraphicsHandler.Clear(Color.White) End Sub So far, only using the GraphicsHandler thing is working, but everytime I try to minimize the window or draw a new line, the previous lines are erased. Can some kind soul explain to me proper way to do the simple 1-5 above? For example, how can I call drawlines()from the button? A: .NET implements a completely new graphics manipulation model with WinForms and GDI+. Your old VB6 skills will not serve you well in this brave new world. So start by ditching the GraphicsHandler. ALL your painting should be done via the Panel's Paint event. You should store each line in an array or List(Of Point) at the form level. Then each time the Paint event is called you draw all your lines again. .NET controls DO NOT REMEMBER their graphical state from one Paint event to the next, unlike VB6 controls. If you need to force a redraw at the end of your button Click event you would call your Panel.Invalidate() PSEUDOCODE: Private myCoordinates As List(Of Point) = New List(Of Point) Sub Button_click(sender, e) '' Store new coordinate myCoordinates.Add(New Point(x, y)) myCoordinates.Add(New Point(x, y)) myPanel.Invalidate() End Sub Sub Panel_Paint(sender, e) Handles myPanel.Paint For tIndex As Int32 = 0 To myCoordinates.Count - 1 Step 2 e.graphics.DrawLine(myCoordinate(tIndex), myCoordinates(tIndex+1)) Next End Sub
doc_23531423
Category Unit Default Unit --------------------------------------- Currency USD True Currency EURO False Currency AUS False Length Kilometer True Length Mile False Length Foot False Length Inch False Mass Kilogram True I want to set a table constraint so that there can be only one 'Default Unit' per Category. Can this be done using Group By in a constraint, perhaps? A: You can create a unique partial index: create unique index idx_table(category, default_unit) on table(category, default_unit) where default_unit;
doc_23531424
<form:checkbox path="someList" value ="someId" onload = "javascript:alert(1);"/> But the alert does not get called on page load. I am trying to call a javascript on load of the checkbox where i will execute some custom functionality. Is there something wrong with the syntax? A: This isn't a spring-mvc question as much as html. The form:checkbox will translate to an html input tag of type checkbox. The html input tag does not support the onload attribute. For a full list of attributes refer to http://www.w3schools.com/tags/tag_input.asp. A recommended step would be to initialize everything required onload with the body tag.
doc_23531425
template <typename... Args> struct tuple {}; template <typename> struct Test; template < typename... Types, template <Types> typename... Outer, // XXX Types... Inner > struct Test<tuple<Outer<Inner>...>> {}; template <long T> struct O1 {}; template <unsigned T> struct O2 {}; Test<tuple<O1<1>, O2<2>>> test; clang accepts the code, deducing Types = {long, unsigned}, Outer = {O1, O2}, Inner={1L, 2U}. Structurally, this seems correct. gcc rejects the code with a deduction failure. Interestingly, it does accept if O2 is changed to take a long non-type template parameter, which seems inconsistent to me. It suggests that Types can be expanded if Types = {long, long} but not if Types = {long, unsigned}. However, it's not clear to me from the standard which compiler is correct. The core question is: on the line denoted XXX, is it valid to have a parameter pack as the type of the template template parameter's non-type template parameter? Should it expand the way that clang claims it does? A: It is not valid because: a type parameter pack cannot be expanded in its own parameter clause. As from [temp.param]/17: If a template-parameter is a type-parameter with an ellipsis prior to its optional identifier or is a parameter-declaration that declares a pack ([dcl.fct]), then the template-parameter is a template parameter pack. A template parameter pack that is a parameter-declaration whose type contains one or more unexpanded packs is a pack expansion. ... A template parameter pack that is a pack expansion shall not expand a template parameter pack declared in the same template-parameter-list. So consider the following invalid example: template<typename... Ts, Ts... vals> struct mytuple {}; //invalid The above example is invalid because the template type parameter pack Ts cannot be expanded in its own parameter list. For the same reason, your code example is invalid.
doc_23531426
My question is: How Indexing Service remember what files was already indexed and what no, what files changed and need to reindex them? Also, I can stop this service and then start it after a few days, it continues to work. Does it have its own database with information about files? Thank you A: Usually the indexing-service stays in the background using WaitForSingleObject / WaitForMultipleObjects on Handles created by calls to FindFirstChangeNotification. If you want to support that the indexing service can be shut down (or be used for an already existent directory) you should definitely store the timestamp of your last index run on every file. You can compare this to the LastWriteTime of the given file. EDIT: you should use ReadDirectoryChangesW and another thread which asynchronously indexes the files to be sure to not miss any changes. You can either spawn new threads for every file to index(expensive) or use a job queue and a fixed amount of worker threads(1 or 2 preferably)
doc_23531427
But they are not. How to fix that? A: What causes the problem is probably one of those: * *line-ends converted / or not to CRLF (on the fly) *changed file mode *ignored / or not case Here is why that may happen: * *IntelliJ IDEA is using a different Git than the one that was used to check-out the files Check which Git is in the System Path and which is in Settings > Version Control > Git > Path to Git excutable. *git --version may be useful too to check versions in different contexts *Even if versions are the same, what makes the difference is the configuration git config --list shows what parameters were set In my case, the Git version was the same, but from two different paths (one came in the package, one was installed independently). The configuration was different (default vs adopted) and that was enough to make everything quite confusing. Especially check: core.autocrlf=true (mainly on Windows) core.filemode=true core.ignorecase=true
doc_23531428
require("caret") data("iris") fitControl <- trainControl(method = "repeatedcv", number = 10, repeats = 10, savePredictions = 'final') model.cv <- train(Sepal.Length ~ Sepal.Width, data = iris, method = "lm", trControl = fitControl) head(model.cv$pred) # intercept pred obs rowIndex Resample #1 TRUE 5.809386 4.7 3 Fold01.Rep01 #2 TRUE 5.838487 4.6 4 Fold01.Rep01 #3 TRUE 5.460174 5.7 16 Fold01.Rep01 #4 TRUE 5.634780 5.7 19 Fold01.Rep01 #5 TRUE 5.722083 5.2 28 Fold01.Rep01 #6 TRUE 6.071295 4.5 42 Fold01.Rep01 Now I would like to get the average of all the 10 predictions of each example. I can do it by iterating over the examples as follows but I think there has to be a better tidier way. mean(model.cv$pred[model.cv$pred$rowIndex==1, "pred"]) #[1] 5.745675 EDIT Following @Obim's answer, I tested the timings of the three proposed solutions. The dplyr version is way faster. Note that I slightly modified the sapply version by adding a sort over the unique rowINdex to keep its output consistent and interpretable. library("plyr") library("dplyr") library("tictoc") tic("plyr") for(i in 1:100) meansplyr = ddply(model.cv$pred, ~rowIndex, summarise, mean = mean(pred)) toc() #plyr: 5.56 sec elapsed tic("dplyr") for(i in 1:100) meansdplyr = model.cv$pred %>% group_by(rowIndex) %>% summarise(pred = mean(pred)) toc() #dplyr: 0.08 sec elapsed tic("sapply") for(i in 1:100) { meanssapply = sapply( X = sort(unique(model.cv$pred$rowIndex)), # added sort to keep the output consistent FUN = function(x){mean(model.cv$pred$pred[model.cv$pred$rowIndex %in% x])} ) } toc() #sapply: 0.73 sec elapsed # the outputs are exactly the same sum(abs(meansplyr$mean - meansdplyr$pred)) #[1] 0 sum(abs(meansplyr$mean - meanssapply)) #[1] 0 A: One liner with ddply: library(plyr) ddply(model.cv$pred, ~rowIndex, summarise, mean = mean(pred)) Or with dplyr: library(dplyr) model.cv$pred %>% group_by(rowIndex) %>% summarise(pred = mean(pred)) Another way with sapply (although still iterating over each rowIndex). As @DataD'Oh pointed out, the input should be sorted to allow interpretation of the output: sapply( X = sort(unique(model.cv$pred$rowIndex)), FUN = function(x){mean(model.cv$pred$pred[model.cv$pred$rowIndex %in% x])} )
doc_23531429
Question: How do I develop this library without including the other libraries inside that package? P.S: I understand that when ever I use this library that I will have to use Slick2D and lwjgl with it and I am ok with it. A: I would advise using maven as build infrastructure. There one can define dependencies and version management. Look into your IDE. A: You develop it as you normally would. Just include the library into your CLASSPATH so you can test it. Once is ready, you just build the jar and that's it, you can start distribute your library. When you distribute your library, the project that uses it, has to include into their CLASSPATH your library and their dependencies as well. So, all you have to do is let know the developers that will use your library, what are its dependencies and their versions. That's it. For example: You develop library.jar that depends on dep1.jar and dep2.jar When you are developing, you need to include your dependencies in your CLASSPATH, so you can test, right? But when you build library.jar, it will not include dep1.jar and dep2.jar. Meaning that if I'm going to use your library, I will have to include library.jar, dep1.jar, and dep2.jar into my CLASSPATH. The ClassLoader will load the libraries classes and when your classes make use of the dep1.jar/dep2.jar classes, they all will be loaded.
doc_23531430
def date_to_internal_stored_format(input_text, identify_only_4_digit_years = False, limit_numbers_immediately_after_date = True): #grupo de captura para fechas en donde el año tiene si o si 4 digitos if (identify_only_4_digit_years == True): if(limit_numbers_immediately_after_date == True): date_capture_pattern = r"([12]\d{3}-[01]\d-[0-3]\d)(\D*?)" elif(limit_numbers_immediately_after_date == False): date_capture_pattern = r"([12]\d{3}-[01]\d-[0-3]\d)" input_text = re.sub(date_capture_pattern, lambda m: m.group().replace("-", "_-_", 2), input_text) return input_text input_text = "el dia 2022-12-2344 o sino el dia 2022-09-23 10000-08-23" input_text = date_to_internal_stored_format(input_text, False, True) print(repr(input_text)) Why doesn't the limit imposed behind work so that after the last number of the date there can be no more numbers to be considered a group that must be captured? I need this output where 2022-12-23 is not captured I need this output where this is not captured, since there are more than 2 digits at the end of the date (\D*?) 'el dia 2022-12-2344 o sino el dia 2022_-_09_-_23 10000_-_08_-_23'
doc_23531431
For example i have content like this in my column "things": arbit t/obt t/comp t/dor cramp pod I only can type: pod, tdor, arbit, tcomp I have tried with "REGEXP_SUBSTR"-Expression, but maybe it is not appropriate for this issue. A: You could use simple replace to remove /: SELECT things, REPLACE(things, '/', '') FROM tab A: Imagine that you have the following table: $ select * from PERSONS; PersonID LastName FirstName ADDRESS CITY 1 arbit null null null 2 t/obt null null null 3 t/comp null null null 4 t/dor null null null 5 cramp null null null 6 pod null null null You can use the following simple replace that does not use regex: select Replace(Lastname,'/','') from persons; -- you can omit the replacement part select Replace(Lastname,'/') from persons; --Replace(Lastname,'/','')-- arbit tobt tcomp tdor cramp pod If you really need to do a complex search and replace that uses regex: (this is not necessary in your case) $ select REGEXP_REPLACE(Lastname, '/', '') from persons; --REGEXP_REPLACE(Lastname, '/', '')-- arbit tobt tcomp tdor cramp pod You can also omit the replacement part since it is empty: select REGEXP_REPLACE(Lastname, '/') from persons
doc_23531432
Django can also be configured to email errors about broken links (404 “page not found” errors). Django sends emails about 404 errors when: * *DEBUG is False; *Your MIDDLEWARE_CLASSES setting includes django.middleware.common.BrokenLinkEmailsMiddleware. If those conditions are met, Django will email the users listed in the MANAGERS setting whenever your code raises a 404 and the request has a referer. (It doesn’t bother to email for 404s that don’t have a referer – those are usually just people typing in broken URLs or broken Web ‘bots). I'm working on fixing up a web project that was poorly maintained by those that preceded me. One of the biggest problems is that there's no clear list of changed URIs, so there's a lot of people out there with bookmarks or links from pdfs/word docs that are likely leading going nowhere. Point is, I need a way to check for 404s with no referrers. Is there a way check for 404s with no referrers using this Middleware? I'm open to other software or even solutions that don't use Django. It just needs to work. A: You can just recycle Django's middleware and remove the conditional check for the referrer in the header: class BrokenLinkEmailsMiddleware(object): def process_response(self, request, response): """ Send broken link emails for relevant 404 NOT FOUND responses. """ if response.status_code == 404 and not settings.DEBUG: domain = request.get_host() path = request.get_full_path() referer = request.META.get('HTTP_REFERER', 'None') is_not_search_engine = '?' not in referer is_ignorable = self.is_ignorable_404(path) if is_not_search_engine and not is_ignorable: ua = request.META.get('HTTP_USER_AGENT', '<none>') ip = request.META.get('REMOTE_ADDR', '<none>') mail_managers( "Broken link on %s" % domain, "Referrer: %s\nRequested URL: %s\nUser agent: %s\nIP address: %s\n" % (referer, path, ua, ip), fail_silently=True) return response def is_ignorable_404(self, uri): """ Returns True if a 404 at the given URL *shouldn't* notify the site managers. """ return any(pattern.search(uri) for pattern in settings.IGNORABLE_404_URLS)
doc_23531433
Crop Activity starts smoothly but after cropping when I clicks to CROP button, my app reruns and opens MainActivity. It seems to me that there is no error in the code and also I have checked it 5-6 times. Thanks!!! Here is my code... public class AddActivity extends AppCompatActivity { private ImageButton add_image_button; private Uri imageUri; private String imageUrl; private String recordPermission = Manifest.permission.RECORD_AUDIO; private String readExternalStorage = Manifest.permission.READ_EXTERNAL_STORAGE; private String recordFile; private int PERMISSION_CODE = 7; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add); add_image_button = findViewById(R.id.add_image_button); CropImage.activity(imageUri).start(AddActivity.this); add_image_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { checkReadExternalStoragePermissions(); CropImage.activity(imageUri).start(AddActivity.this); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) { CropImage.ActivityResult result = CropImage.getActivityResult(data); imageUri = result.getUri(); add_audio_button.setImageURI(imageUri); }else { Toast.makeText(this, "Try again...", Toast.LENGTH_SHORT).show(); startActivity(new Intent(AddActivity.this, MainActivity.class)); finish(); } } private boolean checkRecordPermissions() { if (ActivityCompat.checkSelfPermission(this, recordPermission) == PackageManager.PERMISSION_GRANTED) { return true; } else { ActivityCompat.requestPermissions(this, new String[]{recordPermission}, PERMISSION_CODE); return false; } } private boolean checkReadExternalStoragePermissions() { if (ActivityCompat.checkSelfPermission(this, readExternalStorage) == PackageManager.PERMISSION_GRANTED) { return true; } else { ActivityCompat.requestPermissions(this, new String[]{readExternalStorage}, PERMISSION_CODE); return false; } } } A: I have found out the error, there was a slight mistake in the code. I used add_audio_button.setImageUri(imageUri) instead of add_image_button.setImageUri(imageUri); here: if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) { CropImage.ActivityResult result = CropImage.getActivityResult(data); imageUri = result.getUri(); add_audio_button.setImageURI(imageUri); A: implementation 'com.github.Drjacky:ImagePicker:1.8.4' use this library it is one of best for imagePicker it will be give functionality like 1)crop 2)zoom 3)rotate
doc_23531434
public interface IAssessmentDbContext { DatabaseFacade Database { get; } DbSet<Domain.Entities.Assessment> Assessments { get; } DbSet<AssessmentType> AssessmentTypes { get; } Task<int> SaveChangesAsync(CancellationToken cancellationToken); DbSet<AssessmentType> GetAssessmentTypes(); } and i'm trying to mock data as follows. public class AssessmentsControllerTests { private readonly IFixture _fixture; private readonly Mock<IAssessmentDbContext> dbContextMock; private readonly Mock<IRequestClient<GetCandidates>> requestClientMock; private readonly AssessmentsController controller; //private readonly Mock<CancellationToken> cancellationTokenMock; public AssessmentsControllerTests() { dbContextMock = _fixture.Freeze<Mock<IAssessmentDbContext>>(); var data1 = new List<Domain.Entities.AssessmentType>(); var data = new Domain.Entities.AssessmentType() { Id = new Guid("CD4FA15F-B882-4995-57A3-08DA9A133B59"), AssessmentTypeName = "Big50", AssessmentTypeText = "Big Fifty" }; data1.Add(data); DbSet<Domain.Entities.AssessmentType> myDbSet = GetQueryableMockDbSet(data1); var dataAssessment = new List<Domain.Entities.Assessment>(); Domain.Entities.Assessment obj = new Domain.Entities.Assessment() { AssessmentTypeId = new Guid("CD4FA15F-B882-4995-57A3-08DA9A133B59"), UserId = new Guid("1572EA1B-4CBD-4C05-D03C-08DA47BC4FD9"), CreatedAt = DateTime.Now, Id = Guid.NewGuid() }; dataAssessment.Add(obj); DbSet<Domain.Entities.Assessment> myDbSetAssessment = GetQueryableMockDbSet(dataAssessment); dbContextMock.Setup(x=>x.GetAssessmentTypes()).Returns(myDbSet); dbContextMock.Setup(x => x.Assessments).Returns(myDbSetAssessment); controller = new AssessmentsController(dbContextMock.Object); } [Fact] public void GetAssessments_ShouldReturnData_WhenWithUserId() { // Arrange var userIdMock = _fixture.Create<Guid>(); CancellationToken token = _fixture.Create<CancellationToken>(); // Act var result = controller.GetAssessments("1572EA1B-4CBD-4C05-D03C-08DA47BC4FD9", token); // Assert result.Should().NotBeNull(); result.Should().BeAssignableTo<IActionResult>(); } private static DbSet<T> GetQueryableMockDbSet<T>(List<T> sourceList) where T : class { var queryable = sourceList.AsQueryable(); var dbSet = new Mock<DbSet<T>>(); dbSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(queryable.Provider); dbSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(queryable.Expression); dbSet.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(queryable.ElementType); dbSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(() => queryable.GetEnumerator()); dbSet.Setup(d => d.Add(It.IsAny<T>())).Callback<T>((s) => sourceList.Add(s)); return dbSet.Object; } } } How can I mockup both Assessments and AssessmentType in IAssessmentDbContext
doc_23531435
Following python script returns the out as <?xml version='1.0' encoding='iso-8859-1'?> <Class><Domains>Domain name is &amp;quot;A&amp;quot;</Domains></Class> But I need output XML exactly like below. <?xml version='1.0' encoding='iso-8859-1'?> <Class><Domains>Domain name is &quot;A&quot;</Domains></Class> Code from xml.etree import ElementTree as etree def main(): etree.register_namespace("esri","http://www.esri.com/schemas/ArcGIS/10.0") root = etree.XML('<Class></Class>') root.append(etree.Element("Domains")) s = "Domain name is &quot;A&quot;" root[0].text = s print etree.tostring(root, encoding='iso-8859-1') if __name__ == '__main__': main() Thanks, Srav A: You handed ET a string with & that needed escaping, and that's what it did. Hand it the unescaped string instead. s = 'Domain name is "A"' If you want to encode the quote, you can use the cgi module >>> cgi.escape('Domain name is "A"', quote=True) 'Domain name is &quot;A&quot;' If the string already has &quot; in it, you can unescape it before you hand it to ET >>> HTMLParser.HTMLParser().unescape('Domain name is &quot;A&quot;') u'Domain name is "A"'
doc_23531436
I tried using input tag with text then it didn't workout. Text was being typed and not signature.
doc_23531437
If I pass values for postLoginUrl and alwaysUsePostLoginUrl as true then it is redirecting correctly to postLoginUrl as mentioned.After removing them Facebook is redirecting to application context URL as mentioned in Facebook console. My requirement is redirect to the page from which the authentication flow has started. So do I need to extend Authentication filter or do I need to use any other property to redirect to referer. A: Seems like there is no direct way to mention redirect URL dynamically. So I navigated all the responses from Facebook to a single URI, where in I handled to divert calls to specific pages of my interest.
doc_23531438
Problem is that when combination value is starting from 1 e.g. where combination='1001' then it retrieves correct value of flag from table but when it is starting from 0 e.g. where combination='0010' then nothing is retrieved from database. I debugged the code but not getting the reason for this. following is database image. -(void)fetchfromDatabase { sqlite3 *database; NSString *strPath = [[NSBundle mainBundle]pathForResource:@"ken" ofType:@"db"]; NSLog(@"DBPath : %@",strPath); const char *dbPath = [strPath UTF8String]; if(sqlite3_open(dbPath, &database)==SQLITE_OK) { NSLog(@"Database is Ok"); // const char *cConcate = [concate UTF8String]; NSString *query = [NSString stringWithFormat:@"select * from kentable where combination =%@",concate]; NSLog(@"final concate in database:%@",concate); NSLog(@"Query:%@",query); const char *sqlQuery =[query cStringUsingEncoding:NSASCIIStringEncoding]; NSLog(@"char query %s", sqlQuery); sqlite3_stmt *queryStatement; if(sqlite3_prepare_v2(database, sqlQuery,-1,&queryStatement, NULL)==SQLITE_OK) { NSLog(@"Conversion is Ok"); while (sqlite3_step(queryStatement)==SQLITE_ROW) { NSLog(@"in While Statement of row"); int flag=sqlite3_column_int(queryStatement, 1); NSLog(@"question 5:%d",flag); } sqlite3_reset(queryStatement); } else { NSLog(@"ERROR"); } sqlite3_close(database); } } A: Try changing code as following. Don't mind but preparing sql query as you did is bad practice better follow standard practice. You can bind string using sqlite3_bind_text function. if(sqlite3_open(dbPath, &database)==SQLITE_OK) { const char *sqlQuery = "select * from kentable where combination = ?"; sqlite3_stmt *queryStatement; if(sqlite3_prepare_v2(database, sqlQuery,-1,&queryStatement, NULL)==SQLITE_OK) { NSLog(@"Conversion is Ok"); sqlite3_bind_text(insertStmt,1, [concate UTF8String], -1, SQLITE_TRANSIENT); while (sqlite3_step(queryStatement)==SQLITE_ROW) { NSLog(@"in While Statement of row"); int flag=sqlite3_column_int(queryStatement, 1); NSLog(@"question 5:%d",flag); } sqlite3_reset(queryStatement); } else { NSLog(@"ERROR"); } sqlite3_close(database); } A: I am also having this kind of tasks.. it's works well...Just change your code by NSString * data=[self status:combination]; -(NSString *) status:(NSString *)concate { databasePath = [[NSString alloc] initWithString: [[NSBundle mainBundle] pathForResource:@"ken" ofType:@"db"]]; sqlite3_stmt *statement; NSString *aName; const char *dbpath = [databasePath UTF8String]; if (sqlite3_open(dbpath, &database) == SQLITE_OK) { NSString *querySQL = [NSString stringWithFormat: @"SELECT combination, flag FROM details WHERE combination =\"%@\"", concate]; const char *query_stmt = [querySQL UTF8String]; sqlite3_prepare_v2(database, query_stmt, -1, &statement, NULL); if (sqlite3_step(statement) == SQLITE_ROW) { // Read the data from the result row aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)]; NSLog(@"same %@" ,aName) ; } else { aName=nil; } sqlite3_finalize(statement); sqlite3_close(database); } [databasePath release]; return aName; }
doc_23531439
Here's the code of App.js import React from "react"; import Sidebar from "./Sidebar"; import Feed from "./Feed"; import Widgets from "./Widgets"; import "./App.css"; import { MongoClient } from "mongodb"; function App() { // Connection URI const uri = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // Create a new MongoClient const client = new MongoClient(uri); async function run() { try { // Connect the client to the server await client.connect(); // Establish and verify connection await client.db("posts").command({ ping: 1 }); console.log("Connected successfully to server"); } finally { // Ensures that the client will close when you finish/error await client.close(); } } run(); return ( <div className="app"> <Sidebar /> <Feed /> <Widgets /> </div> ); } export default App; Any help is greatly appreciated ! A: You need to create a backend for your React app and connect to database from there. Then expose an endpoint like /api/posts and call that in your React app with fetch or something similar, e.g. fetch('http://localhost:4000/api/posts') .then(response => response.json()) .then(posts => console.log(posts));
doc_23531440
import React, { Component } from "react"; import { render } from "react-dom"; import "jqwidgets-scripts/jqwidgets/styles/jqx.base.css"; import JqxButton from "jqwidgets-scripts/jqwidgets-react-tsx/jqxbuttons"; import * as ReactDOM from "react-dom"; import JqxWindow from "jqwidgets-scripts/jqwidgets-react-tsx/jqxwindow"; import JqxInput from "jqwidgets-scripts/jqwidgets-react-tsx/jqxinput"; import JqxChart, { IChartProps } from "jqwidgets-scripts/jqwidgets-react-tsx/jqxchart"; import JqxGrid, { IGridProps, jqx } from "jqwidgets-scripts/jqwidgets-react-tsx/jqxgrid"; import JqxTabs from "jqwidgets-scripts/jqwidgets-react-tsx/jqxtabs"; import JqxDropDownList, { IDropDownListProps } from "jqwidgets-scripts/jqwidgets-react-tsx/jqxdropdownlist"; interface AppProps {} interface AppState { name: string; } interface IProps extends IGridProps { rendertoolbar1: IGridProps["rendertoolbar"]; dropdownlistSource: IDropDownListProps["source"]; } class App extends Component<{}, IProps> { private myTabs = React.createRef<JqxTabs>(); private gridElement = React.createRef<HTMLDivElement>(); private gridElementTwo = React.createRef<HTMLDivElement>(); private myGrid = React.createRef<JqxGrid>(); private myGrid2 = React.createRef<JqxGrid>(); private myWindow = React.createRef<JqxWindow>(); private myWindowTWO = React.createRef<JqxWindow>(); private date = React.createRef<JqxInput>(); private sAndP500 = React.createRef<JqxInput>(); constructor(props: {}) { super(props); this.saveBtn = this.saveBtn.bind(this); this.cancelBtn = this.cancelBtn.bind(this); this.saveBtntwo = this.saveBtn.bind(this); this.cancelBtntwo = this.cancelBtn.bind(this); const rendertoolbar = (toolbar: any): void => { const addRowClick = () => { //const datarow = this.generaterow(); //this.myGrid.current!.addrow(null, datarow); this.myWindow.current!.open(); }; const addRowClickTwo = () => { //const datarow = this.generaterow(); //this.myGrid.current!.addrow(null, datarow); this.myWindowTWO.current!.open(); }; ReactDOM.render( <div style={{ margin: "5px" }}> <div id="buttonContainer2" style={{ float: "left", marginLeft: "5px" }} > <JqxButton onClick={addRowClickTwo} width={125} value={"Add New NASDAQ"} /> </div> </div>, toolbar[0] ); }; const rendertoolbar1 = (toolbar: any): void => { const addRowClick = () => { //const datarow = this.generaterow(); //this.myGrid.current!.addrow(null, datarow); this.myWindow.current!.open(); }; const addRowClickTwo = () => { //const datarow = this.generaterow(); //this.myGrid.current!.addrow(null, datarow); this.myWindowTWO.current!.open(); }; ReactDOM.render( <div style={{ margin: "5px" }}> <div id="buttonContainer1" style={{ float: "left" }}> <JqxButton onClick={addRowClick} width={135} value={"Add New Us Index"} /> </div> </div>, toolbar[0] ); }; this.state = { rendertoolbar, rendertoolbar1, // dropdownlistSource: ["Affogato", "Americano", "Bicerin", "Breve"] dropdownlistSource: [ { value: 0, label: "Affogato" }, { value: 1, label: "Americano" }, { value: 2, label: "Bicerin" }, { value: 3, label: "Breve" } ] //source: new jqx.dataAdapter(source) }; } public render() { return ( <JqxTabs ref={this.myTabs} // @ts-ignore width={400} height={560} initTabContent={this.initWidgets} onSelected={this.onTabSelected} > <JqxWindow ref={this.myWindow} width={250} height={230} resizable={false} isModal={false} autoOpen={false} modalOpacity={"0.01"} position={{ x: 68, y: 368 }} > <div>Add New US Indexes</div> <div style={{ overflow: "hidden" }}> <table> <tbody> <tr> <td align={"right"}>Date:</td> <td align={"left"}> <JqxInput ref={this.date} width={150} height={23} /> </td> </tr> <tr> <td align={"right"}>S & P 500:</td> <td align={"left"}> <JqxInput ref={this.sAndP500} width={150} height={23} /> </td> </tr> <tr> <td align={"right"}>DropDownList:</td> <td align={"left"}> <JqxDropDownList width={100} height={20} source={this.state.dropdownlistSource} selectedIndex={0} /> </td> </tr> <tr> <td align={"right"} /> <td style={{ paddingTop: "10px" }} align={"right"}> <JqxButton style={{ display: "inline-block", marginRight: "5px" }} onClick={this.saveBtn} width={50} > Save </JqxButton> <JqxButton style={{ display: "inline-block", marginRight: "5px" }} onClick={this.cancelBtn} width={50} > Cancel </JqxButton> </td> </tr> </tbody> </table> </div> </JqxWindow> <JqxWindow ref={this.myWindowTWO} width={250} height={230} resizable={false} isModal={false} autoOpen={false} modalOpacity={"0.01"} position={{ x: 68, y: 368 }} > <div>Add New NASDAQ</div> <div style={{ overflow: "hidden" }}> <table> <tbody> <tr> <td align={"right"}>Date:</td> <td align={"left"}> <JqxInput ref={this.date} width={150} height={23} /> </td> </tr> <tr> <td align={"right"}>S & P 500:</td> <td align={"left"}> <JqxInput ref={this.sAndP500} width={150} height={23} /> </td> </tr> <tr> <td align={"right"} /> <td style={{ paddingTop: "10px" }} align={"right"}> <JqxButton style={{ display: "inline-block", marginRight: "5px" }} onClick={this.saveBtntwo} width={50} > Save </JqxButton> <JqxButton style={{ display: "inline-block", marginRight: "5px" }} onClick={this.cancelBtntwo} width={50} > Cancel </JqxButton> </td> </tr> </tbody> </table> </div> </JqxWindow> <ul> <li style={{ marginLeft: 30 }}> <div style={{ height: 20, marginTop: 5 }}> <div style={{ float: "left" }}> <img width="16" height="16" src="./../images/catalogicon.png" /> </div> <div style={{ marginLeft: 4, verticalAlign: "middle", textAlign: "center", float: "left" }} > US Indexes </div> </div> </li> <li> <div style={{ height: 20, marginTop: 5 }}> <div style={{ float: "left" }}> <img width="16" height="16" src="./../images/pieicon.png" /> </div> <div style={{ marginLeft: 4, verticalAlign: "middle", textAlign: "center", float: "left" }} > NASDAQ compared to S&P 500 </div> </div> </li> </ul> <div style={{ overflow: "hidden" }}> <div id="jqxGrid" ref={this.gridElement} /> <div style={{ marginTop: 10, height: "15%" }} /> </div> <div style={{ overflow: "hidden" }}> <div id="jqxGrid2" ref={this.gridElementTwo} /> <div style={{ marginTop: 10, height: "15%" }} /> </div> </JqxTabs> ); } private initGrid = () => { const source = { datafields: [{ name: "Date" }, { name: "S&P 500" }, { name: "NASDAQ" }], datatype: "csv", //url: './assets/nasdaq_vs_sp500.txt' localdata: `1/2/2014,1831.98,4143.07 1/3/2014,1831.37,4131.91 1/6/2014,1826.77,4113.68 1/7/2014,1837.88,4153.18 1/8/2014,1837.49,4165.61 1/9/2014,1838.13,4156.19 1/10/2014,1842.37,4174.67 1/13/2014,1819.2,4113.3 1/14/2014,1838.88,4183.02 1/15/2014,1848.38,4214.88 1/16/2014,1845.89,4218.69 1/17/2014,1838.7,4197.58 1/21/2014,1843.8,4225.76 1/22/2014,1844.86,4243 1/23/2014,1828.46,4218.88 1/24/2014,1790.29,4128.17 1/27/2014,1781.56,4083.61 1/28/2014,1792.5,4097.96 1/29/2014,1774.2,4051.43 1/30/2014,1794.19,4123.13 1/31/2014,1782.59,4103.88 2/3/2014,1741.89,3996.96 2/4/2014,1755.2,4031.52 2/5/2014,1751.64,4011.55 2/6/2014,1773.43,4057.12 2/7/2014,1797.02,4125.86` }; const dataAdapter = new jqx.dataAdapter(source, { async: false, loadError: (xhr: any, status: any, error: any) => { console.log(xhr, status, error); //alert('Error loading "' + source.url + '" : ' + error); } }); const columns: IGridProps["columns"] = [ { cellsformat: "d", datafield: "Date", text: "Date", width: 250 }, { datafield: "S&P 500", text: "S&P 500", width: 150 }, { datafield: "NASDAQ", text: "NASDAQ" } ]; const grid = ( <JqxGrid ref={this.myGrid} width={"100%"} height={400} source={dataAdapter} columns={columns} showtoolbar={true} rendertoolbar={this.state.rendertoolbar1} /> ); render(grid, this.gridElement.current!); }; private saveBtn(): void { this.myWindow.current!.hide(); } private cancelBtn(): void { this.myWindow.current!.hide(); } private initGrid2 = () => { const source = { datafields: [{ name: "Date" }, { name: "S&P 500" }, { name: "NASDAQ" }], datatype: "csv", //url: './assets/nasdaq_vs_sp500.txt' localdata: `1/2/2014,1831.98,4143.07 1/3/2014,1831.37,4131.91 1/6/2014,1826.77,4113.68 1/7/2014,1837.88,4153.18 1/8/2014,1837.49,4165.61 1/9/2014,1838.13,4156.19 1/10/2014,1842.37,4174.67 1/13/2014,1819.2,4113.3 1/14/2014,1838.88,4183.02 1/15/2014,1848.38,4214.88 1/16/2014,1845.89,4218.69 1/17/2014,1838.7,4197.58 1/21/2014,1843.8,4225.76 1/22/2014,1844.86,4243 1/23/2014,1828.46,4218.88 1/24/2014,1790.29,4128.17 1/27/2014,1781.56,4083.61 1/28/2014,1792.5,4097.96 1/29/2014,1774.2,4051.43 1/30/2014,1794.19,4123.13 1/31/2014,1782.59,4103.88 2/3/2014,1741.89,3996.96 2/4/2014,1755.2,4031.52 2/5/2014,1751.64,4011.55 2/6/2014,1773.43,4057.12 2/7/2014,1797.02,4125.86` }; const dataAdapter = new jqx.dataAdapter(source, { async: false, loadError: (xhr: any, status: any, error: any) => { console.log(xhr, status, error); //alert('Error loading "' + source.url + '" : ' + error); } }); const columns: IGridProps["columns"] = [ { cellsformat: "d", datafield: "Date", text: "Date", width: 250 }, { datafield: "S&P 500", text: "S&P 500", width: 150 }, { datafield: "NASDAQ", text: "NASDAQ" } ]; const grid = ( <JqxGrid ref={this.myGrid2} width={"100%"} height={400} source={dataAdapter} columns={columns} showtoolbar={true} rendertoolbar={this.state.rendertoolbar} /> ); render(grid, this.gridElementTwo.current!); }; private saveBtntwo(): void { this.myWindowTWO.current!.hide(); } private cancelBtntwo(): void { this.myWindowTWO.current!.hide(); } private initWidgets = (tab: any) => { switch (tab) { case 0: this.initGrid(); break; case 1: this.initGrid2(); break; } }; private onTabSelected = (event: any) => { switch (event.args.item) { case 0: // this.hideButton(); break; case 1: // this.showButton(); break; } }; } render(<App />, document.getElementById("root")); I'm trying NOT to nest <JqxWindow></JqxWindow> inside <JqxTabs></JqxTabs> since this is not a good idea as per the jQXWidgets team for the proper functioning of react app. So, I've surrounded one <JqxTabs></JqxTabs> with the div tag and two <JqxWindow></JqxWindow> with two divs as shown in the code below and in the editor here: public render() { return ( <div> <JqxTabs ref={this.myTabs} // @ts-ignore width={400} height={560} initTabContent={this.initWidgets} onSelected={this.onTabSelected} > <ul> <li style={{ marginLeft: 30 }}> <div style={{ height: 20, marginTop: 5 }}> <div style={{ float: "left" }}> <img width="16" height="16" src="./../images/catalogicon.png" /> </div> <div style={{ marginLeft: 4, verticalAlign: "middle", textAlign: "center", float: "left" }} > US Indexes </div> </div> </li> <li> <div style={{ height: 20, marginTop: 5 }}> <div style={{ float: "left" }}> <img width="16" height="16" src="./../images/pieicon.png" /> </div> <div style={{ marginLeft: 4, verticalAlign: "middle", textAlign: "center", float: "left" }} > NASDAQ compared to S&P 500 </div> </div> </li> </ul> <div style={{ overflow: "hidden" }}> <div id="jqxGrid" ref={this.gridElement} /> <div style={{ marginTop: 10, height: "15%" }} /> </div> <div style={{ overflow: "hidden" }}> <div id="jqxGrid2" ref={this.gridElementTwo} /> <div style={{ marginTop: 10, height: "15%" }} /> </div> </JqxTabs> </div> <div> <JqxWindow ref={this.myWindow} width={250} height={230} resizable={false} isModal={false} autoOpen={false} modalOpacity={"0.01"} position={{ x: 68, y: 368 }} > <div>Add New US Indexes</div> <div style={{ overflow: "hidden" }}> <table> <tbody> <tr> <td align={"right"}>Date:</td> <td align={"left"}> <JqxInput ref={this.date} width={150} height={23} /> </td> </tr> <tr> <td align={"right"}>S & P 500:</td> <td align={"left"}> <JqxInput ref={this.sAndP500} width={150} height={23} /> </td> </tr> <tr> <td align={"right"}>DropDownList:</td> <td align={"left"}> <JqxDropDownList width={100} height={20} source={this.state.dropdownlistSource} selectedIndex={0} /> </td> </tr> <tr> <td align={"right"} /> <td style={{ paddingTop: "10px" }} align={"right"}> <JqxButton style={{ display: "inline-block", marginRight: "5px" }} onClick={this.saveBtn} width={50} > Save </JqxButton> <JqxButton style={{ display: "inline-block", marginRight: "5px" }} onClick={this.cancelBtn} width={50} > Cancel </JqxButton> </td> </tr> </tbody> </table> </div> </JqxWindow> </div> <div> <JqxWindow ref={this.myWindowTWO} width={250} height={230} resizable={false} isModal={false} autoOpen={false} modalOpacity={"0.01"} position={{ x: 68, y: 368 }} > <div>Add New NASDAQ</div> <div style={{ overflow: "hidden" }}> <table> <tbody> <tr> <td align={"right"}>Date:</td> <td align={"left"}> <JqxInput ref={this.date} width={150} height={23} /> </td> </tr> <tr> <td align={"right"}>S & P 500:</td> <td align={"left"}> <JqxInput ref={this.sAndP500} width={150} height={23} /> </td> </tr> <tr> <td align={"right"} /> <td style={{ paddingTop: "10px" }} align={"right"}> <JqxButton style={{ display: "inline-block", marginRight: "5px" }} onClick={this.saveBtntwo} width={50} > Save </JqxButton> <JqxButton style={{ display: "inline-block", marginRight: "5px" }} onClick={this.cancelBtntwo} width={50} > Cancel </JqxButton> </td> </tr> </tbody> </table> </div> </JqxWindow> </div> ); } And it keeps on complaining about the following : Am I not using the divs properly? Should I surround everything by fragment and not divs as shown here: How to fix JSX expression must have one parent element? A: Please wrap all elements with parent container. Please make sure you are rendering one single entity. i.e: <div> // parent container <JqxTabs/> <JqxWindow /> </div> You could use Fragment element too for parent element. import React, {Fragment} from 'react'; A: You will need to return a single element from a react component. To achieve this you can try one of these methods. Using Fragments import React, { Component,Fragment } from "react"; <Fragment> <JqxTabs/> <JqxWindow /> </Fragment> or <> <JqxTabs/> <JqxWindow /> </> or you can wrap every element by a div <div> <JqxTabs/> <JqxWindow /> </div> A: You can only return one element from a react component. Wrap everything in your render with another <div> or with a react fragment <React.Fragment> (or shorthand with <>...</>). See docs on fragments. Either a div or a fragment is acceptable, the issue is that you're returning several elements and not just one.
doc_23531441
Ex: we have different country like Japan, Russia, France, Germany And we don't need drill through for Germany. So how can I disable this for Germany country.
doc_23531442
var translationsEN = { USERNAME: 'Username', PASSWORD: 'Password', LOGIN: 'Login', CANCEL: 'Cancel' }; and my controller: .config(function ($routeProvider, $translateProvider) { ... $translateProvider.translations('en_US', translationsEN); $translateProvider.preferredLanguage('en_US'); ... I'm using the module angular-translate of Pascal Precht. When I updated my files, in the console is the message: "translationsEN is not defined" (in my controller) and the message from my language file: "translationsEN is defined but never used" How can I defined the variable in my Controller? Do I need to define the variable as a service? A: The Angular way to achieve your goal is indeed to use a service or, in the case of a simple and constant variable, a constant service: myModule.constant( 'myModule.translations.EN', { USERNAME: 'Username', PASSWORD: 'Password', LOGIN: 'Login', CANCEL: 'Cancel' } ); All you have to do then is to inject it in your configuration method: myModule.config([ '$routeProvider', '$translateProvider', 'myModule.translations.EN', function ($routeProvider, $translateProvider, translationsEN) { // … $translateProvider.translations('en_US', translationsEN); $translateProvider.preferredLanguage('en_US'); } ]); If, for some reasons, you absolutely need to use a classical variable, for instance because it's also used in a non-Angular script, simply be sure to declare it before your configuration method. A: As @Blackhole explained in his answer, the general way to achieve that in angular is to use a provider. However, in your specific use case of angular-translate, the way to achieve this would be to load your translation files with $translateProvider : Rename en.js to en_US.json and put it in a folder named, for example, /locales. Make sure your files are valid json, i.e. you want to remove var translationsEN =. Then configure $translateProvider like that : $translateProvider.useStaticFilesLoader({ prefix: '/locales/', suffix: '.json' }); This will load all your json translations files, located in the folder /locales. That way your translation files will be totally independent of your application logic.
doc_23531443
The option that is not selected should be disabled, but I can't seem to get this to work. Here is my code: HTML: <form> Choose a Profile Picture:<br> <select> <option onselect="upload()">Upload an Image <option onselect="link()">Load from URL </select><br> <input type="file" id="fileBrowse" accept="image/*"><br> <input type="url" id="enterUrl" placeholder="Enter in a URL." disabled> JS: function upload() { document.getElementById("enterUrl").disabled = true; document.getElementById("fileBrowse").disabled = false; } function link() { document.getElementById("fileBrowse").disabled = true; document.getElementById("enterUrl").disabled = false; } Here is the JSFiddle for the code. A: The problem is that onselect is not a valid event handler for an option element. You'll have to use onchange HTML <form> Choose a Profile Picture:<br> <select id="profilePictureType" onchange="onSelectChange()"> <option value="1">Upload an Image</option> <option value="2">Load from URL</option> </select><br> <input type="file" id="fileBrowse" accept="image/*"><br> <input type="url" id="enterUrl" placeholder="Enter in a URL." disabled="disabled"> </form> JS function onSelectChange() { var selectedValue = document.getElementById("profilePictureType").value; selectedValue == "1" ? upload() : link(); } function upload() { document.getElementById("enterUrl").disabled = true; document.getElementById("fileBrowse").disabled = false; } function link() { document.getElementById("fileBrowse").disabled = true; document.getElementById("enterUrl").disabled = false; } DEMO A short version of this solution would be function onSelectChange() { var selectedValue = document.getElementById("profilePictureType").value; var upload = selectedValue == "1"; document.getElementById("fileBrowse").disabled = upload; document.getElementById("enterUrl").disabled = !upload; } A: You need to put the onchange into the select (not the options) and disable it based on the selected value <form> Choose a Profile Picture:<br> <select id="choose" onchange="changed();"> <option value="upload">Upload an Image</option> <option value="link">Load from URL</option> </select><br> <input type="file" id="fileBrowse" accept="image/*"><br> <input type="url" id="enterUrl" placeholder="Enter in a URL." disabled="disabled"> </form> <script type="text/javascript"> function changed() { var chooser = document.getElementById("choose"); var chooseValue = chooser.options[chooser.selectedIndex].value; if(chooseValue == "upload") { document.getElementById("enterUrl").disabled = true; document.getElementById("fileBrowse").disabled = false; } else if(chooseValue == "link") { document.getElementById("fileBrowse").disabled = true; document.getElementById("enterUrl").disabled = false; } } </script>
doc_23531444
* with when using MDX with MUI (NextJS) Is there any way to wrap different MDX elements like ol or li in MUI components to get the MUI theme styles? The MDX gives out plain HTML without any styles; <ol> <li>One</li> </ol> MUI does have a <List> component, but I just want the font to match the which can be done by wrapping <li> in <Typography> like <ol> <li><Typography>One</Typography></li> </ol> Right now my MDX component looks like <MDXRemote {...source} components={{ wrapper: Container, p:Typography }} /> Is there any weird map method to wrap all items of a list in a custom component or is there an easy way to wrap all text in <Typography>? I'm trying to minimize most possible code from .md files. A: After some time, solved it using props. <MDXRemote {...source} components={{ ol: (props:any) => <Typography gutterBottom component="ol">{props.children}</Typography>, }} />
doc_23531445
For some simple function in a general form, we can transform it to a "deterministic form", then convert the math function into a Julia function (like ax + by + c = 0 to y = (ax + c)/(-b)). However, for some complex function, it is not easy to write a Julia function. For example: Is there a way I can plot this function using Gadfly? A: Mattriks suggests to use Geom.contour to plot functions in a general form in this issue. I have tried it in my example, and it works pretty good. For example, in the function on the question: Say the list of parameters is para=[1.27274,0.625272,1.18109,-2.01996,-0.917423,-1.43166,0.124006,-0.365534,-0.357239,-0.175131,-1.45816,-0.0509896,-0.615555,-0.274707,-1.19282,-0.242188,-0.206006,-0.0447305,-0.277784,-0.295378,-0.456357,-1.0432,0.0277715,-0.292431,0.0155668,-0.327379,-0.143887,-0.924652] In other words, a0 = 1.27274, a1 = 0.625272, etc. Then we can use the following code to plot the graph. function decision(x1::Float64, x2::Float64, a::Array{Float64}) dot(a, [1, x1^1*x2^0, x1^0*x2^1, x1^2*x2^0, x1^1*x2^1, x1^0*x2^2, x1^3*x2^0, x1^2*x2^1, x1^1*x2^2, x1^0*x2^3, x1^4*x2^0, x1^3*x2^1, x1^2*x2^2, x1^1*x2^3, x1^0*x2^4, x1^5*x2^0, x1^4*x2^1, x1^3*x2^2, x1^2*x2^3, x1^1*x2^4, x1^0*x2^5, x1^6*x2^0, x1^5*x2^1, x1^4*x2^2, x1^3*x2^3, x1^2*x2^4, x1^1*x2^5, x1^0*x2^6]) end plot(z = (x1,x2) -> decision(x1, x2, para), x = linspace(-1.0, 1.5, 100), y = linspace(-1.0, 1.5, 100), Geom.contour(levels = [0.0])) To make levels = [0.0] work, we need to explicitly provide arguments x, y, z.
doc_23531446
Is that a smart thing to do? I found a similar reports that import xml files into other data formats, such as dataframes or tm Corpus objects Parsing multiple xml files to a Single Dateframe in R, however keeping them in an XML format should keep them tidy, maintain access to context as annotated corpora can have deep trees and make processing simpler because of the nice query language? Many thanks for the consultation. A: I found this small program called mergex.exe useful. It merges several XML files into a single file at the command line, really intuitive and simple.
doc_23531447
public class MyImpersonation { WindowsImpersonationContext impersonationContext; [DllImport("advapi32.dll")] public static extern int LogonUserA(String lpszUserName, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern int DuplicateToken(IntPtr hToken, int impersonationLevel, ref IntPtr hNewToken); [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern bool RevertToSelf(); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public static extern bool CloseHandle(IntPtr handle); public bool impersonateValidUser(String userName, String domain, String password) { WindowsIdentity tempWindowsIdentity; IntPtr token = IntPtr.Zero; IntPtr tokenDuplicate = IntPtr.Zero; if (RevertToSelf()) { if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0) { if (DuplicateToken(token, 2, ref tokenDuplicate) != 0) { tempWindowsIdentity = new WindowsIdentity(tokenDuplicate); impersonationContext = tempWindowsIdentity.Impersonate(); if (impersonationContext != null) { CloseHandle(token); CloseHandle(tokenDuplicate); return true; } } } } if (token != IntPtr.Zero) CloseHandle(token); if (tokenDuplicate != IntPtr.Zero) CloseHandle(tokenDuplicate); return false; } } It worked really well until I used it with the BackgroundWorker class. In this case, I've added a impersonation in the the code that runs asynchronously. I have no errors, but the issue I'm having is that the impersonation does not work when it is used in the async method. In code this looks something like this: * *instantiate a BGWorker, and add an event handler to the DoWork event: _bgWorker = new BackgroundWorker(); _bgWorker.DoWork += new DoWorkEventHandler(_bgWorker_DoWork); *in the above handler, a impersonation is made before running some code. private void _bgWorker_DoWork(object sender, DoWorkEventArgs e) { MyImpersonation myImpersonation = new MyImpersonation(); myImpersonation.impersonateValidUser(user, domain, pass) //run some code... myImpersonation.undoImpersonation(); } *the code is launched with BGWorker.RunWorkerAsync(); As I said before, no error is thrown, only that the code acts as if I didn't run any impersonation, that is with its default credentials. Moreover, the impersonation method returns true, so the impersonation took place at a certain level, but probably not on the current thread. This must happen because the async code runs on another thread, so there must be something that needs to be added to the MyImpersonation class. But what? :) A: I'm having this same problem. I have a background worker that does impersonation with a static class in the DoWork event. I'm attempting to impersonate another Active Domain user in order to read a directory that the main user does not have access to. If I am running the application in the IDE, the impersonated user can read the files with no problem. If I run the application from the file system, the impersonation still happens, but an exception is thrown saying the impersonated user does not have access. From what I've read it's due to setting Assembly:SecurityPermissionAttribute and Assembly:PermissionSetAttribute. Before the class declaration I have the following: <Assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode:=True), _ Assembly: PermissionSetAttribute(SecurityAction.RequestMinimum, Name:="FullTrust")> Before my StartImpersonating() function, I have: <PermissionSetAttribute(SecurityAction.Demand, Name:="FullTrust")> _ I'm working with VB.NET and not C#, however. -D
doc_23531448
Following the example, and testing within the OAuth 2.0 Playground, here is my sample code: POST /m8/feeds/groups/default/full/ HTTP/1.1 Host: www.google.com Gdata-version: 3.0 Content-length: 355 Content-type: application/atom+xml Authorization: Bearer #{auth_code_goes_in_here}# <atom:entry xmlns:gd="http://schemas.google.com/g/2005"> <atom:category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/contact/2008#group"/> <atom:title type="text">Salsa group</atom:title> <gd:extendedProperty name="more info about the group"> <info>Nice people.</info> </gd:extendedProperty> </atom:entry> However, I keep getting the 400 error in the response: HTTP/1.1 400 Bad Request Alternate-protocol: 443:quic,p=1 Content-length: 236 X-xss-protection: 1; mode=block X-content-type-options: nosniff Transfer-encoding: chunked Expires: Fri, 11 Mar 2016 05:18:06 GMT Vary: Origin, X-Origin Server: GSE -content-encoding: gzip Cache-control: private, max-age=0 Date: Fri, 11 Mar 2016 05:18:06 GMT X-frame-options: SAMEORIGIN Alt-svc: quic=":443"; ma=2592000; v="31,30,29,28,27,26,25" Content-type: application/vnd.google.gdata.error+xml; charset=UTF-8 <?xml version="1.0" encoding="UTF-8"?> <errors xmlns="http://schemas.google.com/g/2005"> <error> <domain>GData</domain> <code>invalid</code> <internalReason>Entry does not have any fields set</internalReason> </error> </errors> Any ideas what I am doing wrong here? Further to this, I would like to create contacts in Google, with specific Group attached to it. Is this do-able from the 'creating contacts' method? I can't seem to find an example where I can specify the group directly to it. Thanks for any suggestions. Regards, Leroy A: After some painful research, I found the solution by changing the data from: <atom:entry xmlns:gd="http://schemas.google.com/g/2005"> to <atom:entry xmlns:atom="http://www.w3.org/2005/Atom" xmlns:gd="http://schemas.google.com/g/2005">
doc_23531449
val matrix = breeze.linalg.DenseMatrix((1.0,2.0),(3.0,4.0)) I want to scale this by a scalar Double (and add the result to another Matrix) using one of the *= and :*= operators: val scale = 2.0 val scaled = matrix * scale This works just fine (more details in my answer below). Update This code does work in isolation. I seem to have a problem elsewhere. Sorry for wasting your bandwidth... Update 2 However, the code fails to compile if I specifically assign the type Matrix to the variable matrix: val matrix: Matrix[Double] = breeze.linalg.DenseMatrix((1.0,2.0),(3.0,4.0)) val scaled = matrix * scale // does not compile The compiler keeps complaining that it "could not find implicit value for parameter op". Can anyone explain this please? Is this a bug in Breeze or intentional? TIA. A: For those of you who struggle with Scala and the Breeze library, I would like to detail some of the functions / operators available for Matrix instances here. Our starting point is a simple Double matrix (Matrix and the related operations also support Float and Int): scala> val matrix = breeze.linalg.DenseMatrix((1.0,2.0),(3.0,4.0)) You can easily pretty-print this using scala> println(matrix) 1.0 2.0 3.0 4.0 Breeze supports operators that leave the left operand intact and those that modify the left operand - e.g. * and *=: scala> val scaled1 = matrix * 2.0 // returns new matrix! scala> println(matrix) 1.0 2.0 3.0 4.0 scala> println(scaled1) 2.0 4.0 6.0 8.0 scala> println(matrix == scaled1) false scala> val scaled2 = matrix *= 2.0 // modifies and returns matrix! scala> println(matrix) 2.0 4.0 6.0 8.0 scala> println(scaled2) 2.0 4.0 6.0 8.0 scala> println(matrix == scaled2) // rough equivalent of calling Java's equals() true The hash codes of both variables indicate that they actually point to the same object (which true according to the javadoc and can be verified by looking at the sources): scala> println(matrix.##) 12345678 scala> println(scaled2.##) 12345678 This is further illustrated by: scala> val matrix2 = breeze.linalg.DenseMatrix((2.0,4.0),(6.0,8.0)) scala> println(matrix == matrix2) true scala> println(matrix2.##) 34567890
doc_23531450
import numpy as np array1 = np.array([1,2,3]) However, I get the error "No module named 'numpy'". The same goes for Tensorflow. But trying "pip install numpy" on terminal gives "Requirement already satisfied: numpy in /usr/local/lib/python3.9/site-packages (1.23.4)". And when I move the script to another directory, in which I already have ran Numpy in, it runs without error. Why does the Numpy module (also Tensorflow) work in that directory, but not in the new one I created? Tried to uninstall and install Numpy in Terminal A: Make sure you pip install and run scripts in the right python environment (can be python-venv or conda env), you can troubleshoot these with which python and which pip or pip --version You can create venv with python3 -m venv env and make sure you are in the correct python environment by activate it: source env/bin/activate only then you will install numpy and other library inside this virtualenv pip3 install numpy Later on, when you run scripts from this project, make sure you cd into its directory, then source env/bin/activate before running scripts or pip install <libraries>.
doc_23531451
**SEVERE: Error configuring application listener of class org.springframework.web.context.request.RequestContextListener java.lang.NoClassDefFoundError: javax/servlet/ServletRequestListener** at java.lang.ClassLoader.findBootstrapClass(Native Method) at java.lang.ClassLoader.findBootstrapClassOrNull(ClassLoader.java:927) at java.lang.ClassLoader.loadClass(ClassLoader.java:298) at java.lang.ClassLoader.loadClass(ClassLoader.java:296) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:248) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1626) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1556) at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:532) at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:514) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:133) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4727) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) at java.util.concurrent.FutureTask.run(FutureTask.java:138) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:662)
doc_23531452
cc -o parser parser.c ./parser I expect it to open a particular file, read from it, and parse it. However, it seems to expect me to provide input and I have to Ctrl-C to kill it. Am I using fgets wrong? I tried getline() with the same results. I added the puts() to make sure it was reading what I expected and it does. Any help is appreciated. #include <stdio.h> #include <string.h> #include <fcntl.h> #include <limits.h> #include <stdlib.h> int main(int argc, char *argv[]) { FILE *fp; char buf[1024]; char *tmp, *pattern, *dir; char *skip, *p; char *tok[5]; char **ap; size_t sz = 0; ssize_t len; int i; int action = 0; // placeholder int fileinto = 1; // placeholder char path[PATH_MAX] = "/home/edgar/.patfile"; fp = fopen(path, "r"); if (fp == NULL) fprintf(stderr, "fopen failed"); while (fgets(buf, sizeof(buf), fp) != NULL) { buf[strcspn(buf, "\n")] = '\0'; // skip comments for (skip = buf; *skip; ++skip) { if (*skip == '#') { *skip = '\0'; break; } } // skip empty lines if (strlen(buf) == 0) continue; puts(buf); // debug only // make a copy tmp = strdup(buf); for (i = 0, ap = tok; ap < &tok[4] && (*ap = strsep(&tmp, " ")) != NULL; i++) { if (**ap != '\0') ap++; } while (i >= 0) { if(tok[i] == "match") pattern = tok[i + 1]; if(tok[i] == "fileinto") { action = fileinto; dir = tok[i + 1]; } } } free(tmp); fclose(fp); exit(0); }
doc_23531453
boost-build C:/local/boost_1_54_0/tools/build/v2 ; but ultimately bjam gives me this error: % bjam notice: no Python configured in user-config.jam notice: will use default configuration C:/local/boost_1_54_0/tools/build/v2/build\project.jam:262: in find-jamfile from module project error: Unable to load Jamfile. error: Could not find a Jamfile in directory '/local/boost_1_54_0'. error: Attempted to find it with pattern '[Bb]uild.jam [Jj]amfile.v2 [Jj]amfile [Jj]amfile.jam'. error: Please consult the documentation at 'http://www.boost.org'. C:/local/boost_1_54_0/tools/build/v2/build\project.jam:280: in load-jamfile from module project C:/local/boost_1_54_0/tools/build/v2/build\project.jam:64: in load from module project C:/local/boost_1_54_0/tools/build/v2/build\project.jam:89: in load-used-projects from module project C:/local/boost_1_54_0/tools/build/v2/build\project.jam:75: in load from module project C:/local/boost_1_54_0/tools/build/v2/build\project.jam:145: in project.find from module project C:/local/boost_1_54_0/tools/build/v2\build-system.jam:535: in load from module build-system C:\local\boost_1_54_0\tools\build\v2/kernel\modules.jam:289: in import from module modules C:\local\boost_1_54_0\tools\build\v2/kernel/bootstrap.jam:139: in boost-build from module C:\tmp\tutorial\boost-build.jam:1: in module scope from module What else do I need to add, or what am I doing wrong? A: I ended up giving up on bjam for this, and just used SCons. A simple SConstruct was enough: # SConstruct for building boost python tutorial example import os boost_python_lib = 'boost_python-vc100-gd-1_54' boost_top = 'c:/boost' python_top = 'c:/python27' env=Environment(TARGET_ARCH='x86', CCFLAGS=['/MDd', '/DEBUG', '/EHsc'], CPPPATH=[os.path.join(boost_top,'include/boost-1_54'), os.path.join(python_top, 'include')], LIBPATH=[os.path.join(boost_top, 'lib/i386'), os.path.join(python_top, 'libs')]) dll=env.SharedLibrary('hello_ext', 'hello.cpp', LIBS=boost_python_lib) env.InstallAs('hello_ext.pyd', dll[0]) # Copy the boost python lib into this dir so hello_ext will find it at runtime env.Install('.', os.path.join(boost_top, 'lib/i386', '%s.dll'%boost_python_lib)) Of course you could make a real SCons Tool out of this, but that was enough to get me going. Hope it's useful to others.
doc_23531454
A: Instead of creating a completely separate theme, you can also override the front page template (page-front.tpl.php) in your current theme. I'm not saying that you should never use a separate front page theme, but overriding the template is often an easier solution with less overhead. A: You can try the Themekey module, that allows setting different themes to given paths (you can use the path to target the frontpage). A: You can also use the Context module.
doc_23531455
$.ajax({ type: 'GET', url: url, crossDomain: true, data: data, dataType: 'jsonp', success: function(responseData, textStatus, jqXHR) { console.log('success') }, error: function(xhr,status,error){ console.log('error') } }); When the request fails, I gets 'error in the console. Update : Headers Request URL:http://example.com:3000/request?callback=jQuery21309164826604537666_1429167109185&firstname=sdf&lastname=sdf&_=1429167109187 Request Headers Provisional headers are shown Accept:*/* Referer:http://localhost/widgets/form.html User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36 Query String Parameters view source view URL encoded callback:jQuery21309164826604537666_1429167109185 firstname:sdf lastname:sdf phone:sdf email:sdf _:1429167109187 A: I think your problem is that the jQuery with jsonp is expecting some JSON back. Your response body should then look like jQuery21309164826604537666_1429167109185({}); In PHP you can simply return a dummy function like this: $callback = isset($_GET["callback"]) ? $_GET["callback"] : "?"; header('Access-Control-Allow-Origin: *'); header("Content-type: application/json"); echo $callback . "({});"; For Node.js, you can just use res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader("Content-Type", "application/json"); res.jsonp({}); Ref: ExpressJS JSONP
doc_23531456
<form action="#" method="post" id="f"> <h3>Got a question? Post here for discussion!</h3> <input type="text" name="title" placeholder="Write a Title..." size="82" required="required" /> <br/> <textarea cols="83" rows="4" name="content" placeholder="Write description..." required="required"></textarea> <br /> <input type="submit" name="sub" value="Post to Timeline" /> </form> When I run the code above in Google Chrome, the length of the textarea and the input type="text" are the same but in mozilla firefox the the textarea becomes longer than the formal. Any help? A: Did you try specifying the width and height using CSS instead of the html? textarea { width: 600px; height: 100px; } See if that makes a difference. You can change the pixels if needed. I just chose something close. A: That's because: * *size and cols specify a number of characters, not a length. But the width of the characters depends on the font, and input and textarea use different fonts by default. Specify a common font to prevent this. *textarea can overflow, and then it reserves some additional space in case it needs scrollbars. Use overflow: hidden to prevent this. input, textarea { font-family: monospace; overflow: hidden; } <form action="#" method="post" id="f"> <h3>Got a question? Post here for discussion!</h3> <input type="text" name="title" placeholder="Write a Title..." size="32" required="required" /> <br/> <textarea cols="32" rows="4" name="content" placeholder="Write description..." required="required"></textarea> <br /> <input type="submit" name="sub" value="Post to Timeline" /> </form> That said, you might prefer using the CSS width property instead. A: Don't use cols and rows attributes. Use CSS width and height properties to ensure a consistent experience across browsers.
doc_23531457
If I take it out of a workflow it works, I was wondering if there's some incorrect syntax I'm missing or even if this is not allowed n a workflow. Apologies but my knowledge on workflows is limited (as you can probably tell). I'm ultimately trying to get the VMs to boot up in parallel. workflow Set-AzureRmTags-and-Start { [CmdletBinding()] Param( [Parameter(Mandatory=$True)] [string]$VmRG ) $Start = Get-Date Write-Output "Time is" $Start $VmRGs = Get-AzureRmResourceGroup | Where-Object { $_.ResourceGroupName -like "*$VmRG*" } foreach ($VmRG in $VmRGs) { $VMs = Get-AzureRmVM -ResourceGroupName $VmRG.ResourceGroupName ForEach ($vm in $vms) { $tags2 = $_.Tags $tags2 ['ShutdownSchedule_AllowStop'] = "$False"; } Set-AzureRmResource -ResourceName $vm.Name -ResourceGroupName $vm.ResourceGroupName -ResourceType "Microsoft.Compute/virtualMachines" -Tag $tags2 -Force -Verbose } $Middle = Get-Date Write-Output "Time Taken To Assign Tags" ($Middle - $Start).Minutes "Minutes" ForEach -Parallel ($vm in $vms) { Start-AzureRmVM -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName -Verbose -Confirm:$false } $End = Get-Date Write-Output "Time Taken To Start VMs" ($End - $Middle).Minutes "Minutes" Write-Output "Total Time Taken" ($End - $Start).Minutes "Minutes" } The error is around ['ShutdownSchedule_AllowStop'] = "$False"; } Error "Unexpected Token in Expression or Statement". Any ideas how I could correct this? Thanks in advance. A: $VmRGs = Get-AzureRmResourceGroup | Where-Object { $_.ResourceGroupName -like "*$VmRG*" } foreach ($VmRG in $VmRGs) { $VMs = Get-AzureRmVM -ResourceGroupName $VmRG.ResourceGroupName ForEach ($vm in $vms) { $tags2 = $_.Tags $tags2 ['ShutdownSchedule_AllowStop'] = "$False"; } Set-AzureRmResource -ResourceName $vm.Name -ResourceGroupName $vm.ResourceGroupName -ResourceType "Microsoft.Compute/virtualMachines" -Tag $tags2 -Force -Verbose } The line $tags2 = $_.Tags does not makes sense. There is no $_ at this point. I don't have any experience in Azure tags, but the documentation here contains sample code that your code should more closely emulate. Setting tags in their samples always seems to use a HashTable construct, like @{ShutdownSchedule_AllowStop=$false} This section seems relevant to what you're trying to accomplish: To add tags to a resource group that has existing tags, retrieve the existing tags, add the new tag, and reapply the tags: $tags = (Get-AzureRmResourceGroup -Name examplegroup).Tags $tags += @{Status="Approved"} Set-AzureRmResourceGroup -Tag $tags -Name examplegroup Up until now, I've never looked into workflows. After a little testing and a bit of research, it seems the 'unexpected Token' error is due the code existing in a workflow: function Test-ArraySubscriptFn { $tags2 = @{} $tags2['asdf'] = $false } workflow Test-ArraySubscriptWf { $tags2 = @{} $tags2['asdf'] = $false # error: Only variable names may be used as the target of an assignment statement $tags2.Add('asdf',$false) # error: Method invocation is not supported in a Windows Powershell Workflow... $tags2 += @{'asdf'=$false} # no error } This is consistent with google search results. I guess we both need to do a bit of research on how workflows differ from 'regular' powershell scripts.
doc_23531458
Unexpected error: java.nio.charset.spi.CharsetProvider: Provider com.ibm.mq.jmqi.CustomCharsetProvider not a subtype java.util.ServiceConfigurationError: java.nio.charset.spi.CharsetProvider: Provider com.ibm.mq.jmqi.CustomCharsetProvider not a subtype A: Short answer, point the classpath to the java/lib directory of the original IBM MQ install location which contains ALL required jar files. See my answer to "IBM MQ Java Error :: java.lang.ClassNotFoundException: com.ibm.mq.internal.MQCommonServices" for more details.
doc_23531459
Here's my code: GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestScopes(new Scope(Scopes.DRIVE_APPFOLDER)) .requestIdToken("685357920901-sfghh9b8heq89b3g1l7gun3csuilur5c.apps.googleusercontent.com") .requestEmail() .build(); mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this, null) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); mAuth = FirebaseAuth.getInstance(); mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid()); } else { Log.d(TAG, "onAuthStateChanged:signed_out"); } } }; } @Override public void onStart() { super.onStart(); mAuth.addAuthStateListener(mAuthListener); } @Override public void onStop() { super.onStop(); if (mAuthListener != null) { mAuth.removeAuthStateListener(mAuthListener); } } private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId()); AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful()); if (!task.isSuccessful()) { Log.d("here", "not"); Log.w(TAG, "signInWithCredential", task.getException()); Toast.makeText(MainActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); } else{ Log.d("here", "ohyeah"); Toast.makeText(MainActivity.this, "done", Toast.LENGTH_SHORT).show(); } } }); } public void SignIn(View view) { Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, RC_SIGN_IN); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RC_SIGN_IN) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); Log.d("here", "o "+result); Log.d("here", "o00000 "+result.isSuccess()); if (result.isSuccess()) { // Google Sign In was successful, authenticate with Firebase GoogleSignInAccount account = result.getSignInAccount(); firebaseAuthWithGoogle(account); Log.d("here", "success"); } else { Log.d("here", "fail"); } } } My result from: GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); is of the form : "com.google.android.gms.auth.api.signin.GoogleSignInResult@3fbdc9ad". Still, the isSuccess() method is returning false. Please help, I am stuck. I have added all the dependencies, as well as have got the Google JSON file. The request token is also correct, still I'm unable to detect the root of the problem.
doc_23531460
Using zip As New ZipFile() zip.AddDirectoryByName("Files") zip.AlternateEncoding = Encoding.UTF8 zip.AlternateEncodingUsage = Ionic.Zip.ZipOption.Always Dim row As Integer For row = 0 To ds.Tables("d").Rows.Count - 1 fileToDownload = Server.MapPath("~/.../Resources/Attachments/" + ds.Tables("d").Rows(row).Item(1).ToString) zip.AddFile(fileToDownload, "Files") Next Response.Clear() Response.BufferOutput = False Dim zipName As String = [String].Format(gvRow.Cells(8).Text.Trim + ".zip") Response.ContentType = "application/zip" Response.AddHeader("content-disposition", "attachment; filename=" + zipName) zip.Save(Response.OutputStream) Response.[End]() End Using I have used several listed Arabic encoding codes, but most of them produce '???' whereas this one produces names as the following: '¦ßs-¦ µ+++ ¦ß+pß.docx' What is the correct code to be used? Or am I missing something? A: Use UTF8 Encoding and pass it as parameter to the constructor: IO.File.Delete("D:/testZip.zip") Using zip As New Ionic.Zip.ZipFile(Encoding.UTF8) zip.AddDirectory("d:/out") zip.Save("D:/testZip.zip") End Using this code works with me with Arabic file names (windows 7). EDIT #1 : you must force DotNetZip to use the specified encoding by using Always option instead of AsNesseary : IO.File.Delete("D:/testZip.zip") Using zip As New Ionic.Zip.ZipFile() zip.AlternateEncoding = Encoding.UTF8 zip.AlternateEncodingUsage = Ionic.Zip.ZipOption.Always zip.AddDirectory("d:/out") zip.Save("D:/testZip.zip") End Using EDIT #2 : based on your comment, I think your operating system does not support Arabic UI,for windows 7 professional 32 bit, go to Control Panel -> Region and Language -> Administrative [tab] -> click "change System locale" button -> choose "Arabic Egypt" for Example -> OK -> OK (restart computer is needed) , Don't worry, the language of windows 7 still English. EDIT #3 : As I mentioned in EDIT #2, your system must support Arabic UI, for example, create a file called (ملف جديد) then add it to archive using WinZip or Winrar, then open the generated archive, if you can read file names correctly , then try to use one of the following encodings in your code : Encoding.Unicode Encoding.UTF7 Encoding.UTF8 Encoding.UTF32 If you are unable to read Arabic file names inside the generated archive, you must configure your system to support Arabic UI. Also, please use the following order for these lines, put the Encoding, then add files or folders : zip.AlternateEncoding = Encoding.UTF8 zip.AlternateEncodingUsage = Ionic.Zip.ZipOption.Always zip.AddDirectoryByName("Files") A: After using what seemed like a myriad of trials using code pages, simply replacing this: zip.AlternateEncoding = Encoding.UTF8 with this: zip.AlternateEncoding = Encoding.GetEncoding(720) worked.
doc_23531461
But I need to put it inside a dropdown menu (the ideia it's to display all the records of the selected table so the user can export that records from the table that he selected to an .csv file) Can anyone help me please? $pdo = Database::connect(); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $query = $pdo->prepare('Show Tables from filecleaner'); $query->execute(); while($rows = $query->fetch(PDO::FETCH_ASSOC)){ var_dump($rows); } A: You can display all tables name from filecleaner in a select box like $allTables = array(); // initialize your array while($rows = $query->fetch(PDO::FETCH_BOTH)){ $allTables[] = $rows[0]; // store all table name in an array. $rows[0] index will give you table name from filecleaner } then, display like: <select> <option>Select Table</option> <?php foreach ($allTables as $key => $value) { ?> <option><?=$value?></option> <?php } ?> </select> Edit: i think you are not getting $rows[0] due to FETCH_ASSOC, you need to use FETCH_BOTH here to get 0 indexed column number. Issue in your code is: FETCH_ASSOC returns an array indexed by column name, and you are trying to display with 0 indexed column number. Reference
doc_23531462
The information in the payload of messages are sensitive so I don't want it to be logged. I've removed all of the payloads from spring integration INFO logs but, when changing spring integration log level to DEBUG, the payload and headers of messages are logged when messages are sent on various components of spring integration. The question is how could I disable logging of payload of message in DEBUG mode? (Is there any way to extend logging facility of spring integration and introduce my own implementation to spring integration?) thanks in advance A: You could use a custom Appender (implementation depending on what logging subsystem you use). Or, you use a patched version of Apache Commons Logging to remove the payload in the logger before it gets to the appender).
doc_23531463
Things like this comes to my mind: urxvt -e 'zsh -c ". scriptname"' but instead of exiting zsh and the terminal once the script finishes, I want an interactive shell at the end. The idea is to simply save users from having to type ". scriptname" whenever they log in. Application: Several users are using the same account (strange but true) and I want to help in adjusting user specific settings. Yes, I know that one could use different accounts for that :-) A: Not really what you were asking for, but should have the desired result. You use an environment variable to pass the name of the user-specific script to source to .zshrc (or other appropriate startup file). urxvt -e 'USERSCRIPT=scriptname zsh' Then in .zshrc for the actual user, include . $USERSCRIPT (All of this is not to say that there isn't an option to run a command then remain in interactive mode; I just can't find a way to do it, so I offer this workaround.)
doc_23531464
Anyone know how to do this? Here's a page from my site with the 2 widgets: http://www.simonsayswebsites.com/how-we-get-you-more-customers/ You can see each one is within a widget that has the same class name. This is what I added to my page functions.php to add the widget: if ( function_exists('register_sidebar') ){ register_sidebar(array( 'name' => 'sidebarpage', 'before_widget' => '<div id="sidebarpage">', 'after_widget' => '</div>', 'before_title' => '', 'after_title' => '', )); } And here's the snippet from the page template itself for it to display: <?php /* Widgetized sidebar */ if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('sidebarpage') ) : ?><?php endif; ?> I could make it using different widgetized areas, but want to learn about having individual widget styles. A: You are mistaking name and id. Also, in before_widget, you shouldn't declare a fixed ID, in your site both Widgets have the same ID and that's... no good. If you follow the example in the Codex, your widget will receive an unique ID and a relevant class. http://codex.wordpress.org/Function_Reference/register_sidebar Default usage <?php $args = array( 'name' => __( 'Sidebar name', 'theme_text_domain' ), 'id' => 'unique-sidebar-id', 'description' => '', 'class' => '', 'before_widget' => '<li id="%1$s" class="widget %2$s">', 'after_widget' => '</li>', 'before_title' => '<h2 class="widgettitle">', 'after_title' => '</h2>' ); ?>
doc_23531465
if (file.getParent().equals("Care Compass\\js")) { System.out.println(Files.getNameWithoutExtension("$$$"+entry.getName())); } The sysout for file.getParent() is the string: Care Compass\js But the above If condition won;t hold true. What am i missing here? Thanks! Posting some more code as per the comments: try { ZipFile zipFileTemp = new ZipFile(zipFile); Enumeration<? extends ZipEntry> enumeration = zipFileTemp.entries(); while (enumeration.hasMoreElements()){ ZipEntry entry = enumeration.nextElement(); File file; if(Files.getFileExtension(entry.getName()).equals("js")){ jsFileName = entry.getName(); file = new File(entry.getName()); System.out.println("****%"+file.getAbsolutePath()); System.out.println("****%%"+file.getName()); System.out.println("****"+entry.getName()); System.out.println(entry.getName()); System.out.println("p="+file.getParent()); if (file.getParent().toString().equals("Care Compass\\js")) { System.out.println(Files.getNameWithoutExtension("$$$"+entry.getName())); } } } } and the output is this: ****%C:\Workspaces\CCQueryHotkey\sqlfindertoolMultiThreaded\Care Compass\js\carecompass-ui-1.3.0.6.min.js ****%%carecompass-ui-1.3.0.6.min.js ****Care Compass/js/carecompass-ui-1.3.0.6.min.js Care Compass/js/carecompass-ui-1.3.0.6.min.js p=Care Compass\js carecompass-ui-1.3.0.6.min A: Are you sure file.getParent( ) returns string? sysout would print the toString( ) value, so use file.getParent().toString().equals in your if condition A: I figured out what the issue is... sorry .. Files.getNameWithoutExtension("$$$"+entry.getName()) is stripping the $$$ .. this was working, it is just that the string was being stripped out by .getNameWithoutExtension()
doc_23531466
//This example was based on several examples which came in the c++ examples directory of the hdf5 package. #ifdef OLD_HEADER_FILENAME #include <iostream.h> #else #include <iostream> #endif #include <string> #include <new> #include "hdf5.h" #include "H5Cpp.h" #ifndef H5_NO_NAMESPACE using namespace H5; #endif const H5std_string FILE_NAME( "Test.h5" ); const H5std_string DATASET_NAME( "Identity" ); const int NX = 3; // dataset dimensions const int NY = 3; const int RANK = 2; using namespace std; int main (void) { int buffer[3][3]; // Make Identity Matrix for fill. for(int i=0; i<NX; i++){ for(int j=0; j<NY; j++){ if(i==j) buffer[i][j] = 1; else buffer[i][j]=0; } } cout << "Lets check we filled it correctly: " << endl; // First let's check we do have I matrix for(int i=0; i<NX; i++){ for(int j=0;j<NY;j++){ cout << buffer[i][j] << " "; } cout << endl; } // Now let's write into a file H5File file( FILE_NAME, H5F_ACC_TRUNC ); hsize_t dimsf[2]; dimsf[0] = NX; dimsf[1] = NY; DataSpace dataspace( RANK, dimsf ); IntType datatype( PredType::NATIVE_INT ); datatype.setOrder( H5T_ORDER_LE ); DataSet dataset = file.createDataSet( DATASET_NAME, datatype, dataspace ); dataset.write( buffer, PredType::NATIVE_INT ); // Ok great, now let's try opening this array using both static and dynamic(new) type arrays: H5File file1( FILE_NAME, H5F_ACC_RDONLY ); DataSet dataset1 = file1.openDataSet( DATASET_NAME ); /* * Get filespace for rank and dimension */ DataSpace filespace = dataset1.getSpace(); /* * Get number of dimensions in the file dataspace */ int rank = filespace.getSimpleExtentNdims(); /* * Get and print the dimension sizes of the file dataspace */ hsize_t dims[2]; // dataset dimensions rank = filespace.getSimpleExtentDims( dims ); /* * Define the memory space to read dataset. */ DataSpace mspace1(RANK, dims); int newbuffer[NX][NY]; //static array. int **p2DArray; p2DArray = new int*[NX]; for (uint i = 0; i < NX; ++i) { p2DArray[i] = new int[NY]; } dataset1.read( newbuffer, PredType::NATIVE_INT, mspace1, filespace ); dataset1.read( p2DArray, PredType::NATIVE_INT, mspace1, filespace ); // Lastly lets print the arrays to make sure we get the same thing: cout << "Ok and now for the static array:" << endl; for(uint i=0; i<NX; i++){ for(uint j=0;j<NY;j++){ cout << newbuffer[i][j] << " "; } cout << endl; } cout << "Ok and now for the dynamic array:" << endl; for(uint i=0; i<NX; i++){ for(uint j=0;j<NY;j++){ cout << p2DArray[i][j] << " "; } cout << endl; } return 0; } A: Your p2DArray must be a plain (1D) array of int, not an array of arrays. That's what a read method expects. Just allocate enough space to store NX*NY numbers: int *p2DArray = new int[NX*NY]; and then access the array using the following formula: p2DArray[i][j] = p2DArray[i*NY + j].
doc_23531467
'Total Value for 1st Load \xe2\x80\x93 approx. $75,200\n' 'Total Value for 2nd Load \xe2\x80\x93 approx. $74,300\n' And this error pops up when I run my script: SyntaxError: Non-ASCII character '\xe2' in file <filename> on line <line number>, but no encoding declared; see http://www.python.org/peps/pep-2063.html When I just print the lines containing the encoded characters I get this: 'Total Value for 2nd Load – approx. $74,300' The data looks like this when I copy it from the email: 'Total Value for 1st Load – approx. $75,200' 'Total Value for 2nd Load – approx. $74,300' From doing my searches, I believe it's encoded with utf-8, but I have no idea how to work with this data based on the fact that some characters are encoded, but most of them are not(maybe?). I have tried varying "solutions" I have found so far. Including adding # -*- coding: utf-8 -*- to the top of my script and the script just hangs... It doesn't do anything :( If someone could provide some information on how to deal with this scenario, that would be amazing. I have tried decoding and encoding using string.encode() and string.decode(), using different encoding based on what I could find on Google, but that hasn't solved the problem. I would really prefer a python solution because the project I'm working on requires people to paste data into a textfield in a GUI, and then that data will be processed. Other solutions suggested pasting the data into something like word, or notepad, saving it as plain text, then doing another copy/paste back from that file. This is a bit much. Does anybody know of a pythonic way of dealing with this issue? A: >>> msg = 'Total Value for 1st Load \xe2\x80\x93 approx. $75,200\n' >>> print msg.decode("utf-8") Total Value for 1st Load – approx. $75,200 make sure you use something like idle that can support these characters (IE dos terminal probably will not!)
doc_23531468
struct hostent { char *h_name; /* Official domain name of host */ char **h_aliases; /* Null-terminated array of domain names */ int h_addrtype; /* Host address type (AF_INET) */ int h_length; /* Length of an address, in bytes */ char **h_addr_list; /* Null-terminated array of in_addr structs */ }; A: Here is the example of code. The output address is in the format of digits.digits.digits.digits (it contains dotted) #include <stdio.h> #include <netdb.h> #include <string.h> #include <arpa/inet.h> struct hostent *he; struct in_addr a; int main () { he = gethostbyname ("localhost"); if (he) { printf("name: %s\n", he->h_name); while (*he->h_aliases) printf("alias: %s\n", *he->h_aliases++); while (*he->h_addr_list) { bcopy(*he->h_addr_list++, (char *) &a, sizeof(a)); printf("address: %s\n", inet_ntoa(a)); } } else printf("error"); return 0; } Output: name: localhost address: 127.0.0.1 A: Do want to do something like this: where Address is char* struct in_addr IpAddress; if(inet_aton(Address,&IpAddress)) { return(ntohl((int)IpAddress.s_addr)); } .
doc_23531469
This is for a research project, where I'm trying to take a thumbnail of google streetview so I can quickly scan which location I need to adjust. Note: We have a special ToS from google for this project (so please don't flame me for breaking their public ToS). This is the github of the webkit2png source: https://github.com/paulhammond/webkit2png/issues/?sort=created&direction=desc&_pjax=true&state=open The issue is open. Any ideas how to fix this? I was using bitpixels.com but their service is lacking. This will be running on a server that I work on everyday, so the other option is to use PyQt4, but I have issues with that spawning an x11 instance every shot it needs to take. That won't scale. Currently I'm rebuilding and updated version of webkit, trying to write some code that will remove the transform, but I wonder if this will screw things up. After that, I'm out of ideas. A: Answer submitted on github by https://github.com/Wevah If you can drop support for OS X < 10.4, you can replace bitmapdata = AppKit.NSBitmapImageRep.alloc() bitmapdata.initWithFocusedViewRect_(view.bounds()) view.unlockFocus() with bitmapdata = view.bitmapImageRepForCachingDisplayInRect_(view.bounds()) view.cacheDisplayInRect_toBitmapImageRep_(view.bounds(), bitmapdata) This works, at least, with the URL posted in the original issue. Alternatively, you could wrap this stuff in respondsToSelector_(), but I don't know how the Python/Cocoa stuff deals with weak linking issues.
doc_23531470
This looks a lot more intuitive than the regular error_bar / whisker. I checked a bit some reference - like https://www.datanovia.com/en/lessons/ggplot-error-bars/ - and tried to play with errorbar and line range.. my_df <- tibble::tribble(~response, ~estimate, ~lower_ci, ~upper_ci, "little_bit", 0.353477, 0.255625, 0.451747, "no", 0.307639, 0.250436, 0.375393, "very", 0.338883, 0.301007, 0.37572310) ggplot(my_df, aes(x = reorder(response, -estimate), y = estimate)) + geom_linerange(aes( ymin = lower_ci, ymax = upper_ci), width = 0.9, size = 45, color = "red", alpha = 0.7 ) + geom_errorbar(aes(ymin = estimate, ymax = estimate), width = 0.9, size = 2 , color = "#6EB3FF") Still not the nice shaded / gradient effects... Thanks for help! A: You'd probably need to do this "manually" ggplot(my_df, aes(x = reorder(response, -estimate))) + geom_linerange(data = my_df %>% group_by(response) %>% summarize(ymin = lead(seq(lower_ci, upper_ci, length = 100)), ymax = lag(seq(lower_ci, upper_ci, length = 100)), alpha = c(seq(0, 0.5, length = 50), seq(0.5, 0, length = 50)), estimate = estimate), aes(ymin = ymin, ymax = ymax, alpha = alpha, color = response), size = 45) + geom_errorbar(aes(ymin = estimate, ymax = estimate), width = 0.9, size = 2 , color = "#3453A2") + scale_alpha_identity() + guides(color = guide_none()) + xlab("Response") + theme_minimal(base_size = 20) + theme(plot.background = element_rect(fill = "#fff2e6", color = NA), panel.background = element_rect(fill = "#fff9f4", color = NA))
doc_23531471
This is my array: @newarray = ('Phe', 'Val', 'Asn', 'Gln', 'His', 'Leu', 'Cys', 'Asp', 'Ser', 'His'); The Question asks to Ask the user to enter a number between 1 and the number of amino acids in the polypeptide, and print the amino acid in that position (e.g. if the user enters "4" the program should print "Gln" This is what I have so far: @newarray = ('Phe', 'Val', 'Asn', 'Gln', 'His', 'Leu', 'Cys', 'Asp', 'Ser', 'His'); print "Please print a number between 1 and 10\n"; chomp ($variable_name = <STDIN>) A: To print the value at index ($variable_name - 1) from the array @newarray, you can do: print $newarray[$variable_name - 1], "\n"; See perlintro for more information.
doc_23531472
* *I get an AssertionError at the time of creation of the Kivy display. File "C:\Users\user\Anaconda3\lib\site-packages\kivy\lang\builder.py", line 554, in _apply_rule assert(rule not in self.rulectx) AssertionError *I get a warning that my Kivy language file is loaded multiple times I reduced my program down to the essential information that still causes the error and warning: from kivy.app import App from kivy.uix.floatlayout import FloatLayout from kivy.properties import ObjectProperty class TheBox(FloatLayout): Day3 = ObjectProperty() Day2 = ObjectProperty() LastUpdate = ObjectProperty() def updateData(self): self.Day3.text = SE_days[0] self.Day2.text = SE_days[1] self.LastUpdate.text = 'Last Updated at: ' + SO_lastUpdate timeInterval = 30 #minutes SE_days = ['4/3', '4/4'] SO_lastUpdate = '4/5 1:31 PM' class DisplayTestApp(App): def build(self): x = TheBox() x.updateData() Clock.schedule_interval(x.update, timeInterval*60) return TheBox() if __name__ == '__main__': DisplayTestApp().run() And my Kivy language file: #:kivy 1.11.1 <TheBox>: FloatLayout: FloatLayout: Label: id: Day3 size_hint: .4, .1 font_size: '24sp' color: (1, 1, 1) halign: 'right' pos_hint: {'right': .45, 'center_y': .5} text: Label: id: Day2 size_hint: .4, .1 font_size: '24sp' color: (1, 1, 1) halign: 'right' pos_hint: {'right': .45, 'center_y': .3} text: FloatLayout: Label: id: LastUpdate size_hint: .9, .2 pos_hint: {'center_x': .5, 'center_y': .3} font_size: '18sp' color: (1, 1, 1) halign: 'center' text: What am I doing wrong? A: Nevermind... Evidently I was having trouble with Spyder/Anaconda. I restarted the IDE and the AssertionError and warning are gone.
doc_23531473
I wanna get a list of supported voices with their language and country codes A: you can use flutter to get that text or voice record ad then you send this data to an API that do that job for you return text or what u want google has paid on you can have 60 min for free
doc_23531474
@objc protocol ListLanguageRoutingLogic { func routeToStartPage(segue: UIStoryboardSegue?) } protocol LangSelectedDataPassing { var dataStore: SelectLanguageDataStore? { get } } class RouterSelectLanguage: NSObject, ListLanguageRoutingLogic, LangSelectedDataPassing { weak var viewControllerSelectLanguage: ViewControllerSelectLanguage? var dataStore: SelectLanguageDataStore? func routeToStartPage(segue: UIStoryboardSegue?) { print("BBB") let destinationVC = viewControllerSelectLanguage?.storyboard?.instantiateViewController(withIdentifier: "ViewControllerStartPage") as! ViewControllerStartPage var destinationDS = destinationVC.router!.dataStore! passDataToStartPage(source: dataStore!, destination: &destinationDS) navigateToStartPage(source: viewControllerSelectLanguage!, destination: destinationVC) } // MARK: Navigation func navigateToStartPage(source: ViewControllerSelectLanguage, destination: ViewControllerStartPage) { source.show(destination, sender: nil) } // MARK: Passing data func passDataToStartPage(source: SelectLanguageDataStore, destination: inout StartPageDataStore) { print("CCC") let selectedRow = viewControllerSelectLanguage?.tblView.indexPathForSelectedRow?.row destination.langSelected = source.langs?[selectedRow!] } } And: A: Resolved my problem, I edited my source code like bellow and good work now: @objc protocol ListLanguageRoutingLogic { func routeToStartPage(segue: UIStoryboardSegue?) } protocol LangSelectedDataPassing { var dataStore: SelectLanguageDataStore? { get } } class RouterSelectLanguage: NSObject, ListLanguageRoutingLogic, LangSelectedDataPassing { weak var viewControllerSL: ViewControllerSelectLanguage? var dataStore: SelectLanguageDataStore? func routeToStartPage(segue: UIStoryboardSegue?) { let destinationVC = segue!.destination as! ViewControllerStartPage var destinationDS = destinationVC.startPageRouter!.dataStore! passDataToStartPage(source: dataStore!, destination: &destinationDS) } // MARK: Passing data func passDataToStartPage(source: SelectLanguageDataStore, destination: inout StartPageDataStore) { let selectedRow = viewControllerSL?.tblView.indexPathForSelectedRow?.row destination.langSelected = source.langs?[selectedRow!] } }
doc_23531475
[{"id":"e174a8ab-aead-4885-991c-c170ea799d71","securityResourceId":"f0adf525-3491-474f-9f13-9b5f2e2c14c5","name":"BPIM-bpimdmgr-idev4-01","active":true,"licensed":true,"licenseType":"AUTHORIZED","status":"ONLINE","version":"6.1.1.0.608443","workingDirectory":"\/fs\/misc\/bpim-local\/bpimdmgr-idev4-01\/uDeploy\/Agent2\/var\/work\/","impersonationPassword":"****","impersonationForce":false,"tags":[]},{"id":"70b84792-b80c-4728-bae5-08e06bed6c02","securityResourceId":"875bf8b1-4249-4894-9ddd-8deb94a6dae8","name":"CMIX-cmixdmgr-nprd3-01-xxappmgm","active":true,"licensed":true,"licenseType":"AUTHORIZED","status":"ONLINE","version":"6.1.1.0.608443","workingDirectory":"\/apps\/udeploy-agent\/CMIX-cmixdmgr-nprd3-01-xxappmgm\/var\/work\/","impersonationPassword":"****","impersonationForce":false,"tags":[]},{"id":"b6c6f10c-7199-48e8-b3f3-cff87e2ac1ea","securityResourceId":"d5601541-89a8-4cd5-8265-0ffdc81f464f","name":"CMIX-cmixuser-nprd3-01","active":true,"licensed":true,"licenseType":"AUTHORIZED","status":"ONLINE","version":"6.1.1.0.608443","workingDirectory":"\/apps\/udeploy-agent\/CMIX-cmixuser-nprd3-01\/var\/work\/", ....... Can you please tel me that how i ll get output like row Thanks Kalai A: your data is not unreadable, it's data formatted as JSON! you can view your data nicely using a firefox plugin such as: * *https://addons.mozilla.org/en-US/firefox/addon/jsonview/ or you can use a commandline tool such as: % curl http://example.org/json_data | python -m json.tool Zmo..How I convert into html or normal format ? This is as normal a format as possible! You can get the data in python to use it from any language, for example in python (with python-requests: import requests data = requests.get('http://example.org/json_data').json() # use data like a python object print(data) Unlike HTML, JSON has been designed for machine-to-machine processing, with no external formatting. It's up to you to write a code that downloads that data and shows it off in a nice way. A: This reads like JSON format response data to me.
doc_23531476
Below is my current code. I am not sure what self is suppose to be when I am trying to call it in views.py. When I try passing in my model name, which is User, it did not work. So what exactly is self suppose to be in the views.py? Thanks in advance:D User models.py def query_choice(self,query_choice): users_first_name = self.objects.values_list(query_choice) names = [] for u in users_first_name: names.append(u) return names views.py def login(request): users_first_name = User.query_name(*self*,'first_name') template = loader.get_template('registration/home.html') context = { 'output': users_first_name, } #return HttpResponse(output) return HttpResponse(template.render(context,request)) A: You should define query_choice as a class method using @classmethod decorator in your model: @classmethod def query_choice(cls, query_choice): return cls.objects.values_list(query_choice, flat=True) Then you can call it like below: names = User.query_choice("first_name") By they way, you can use render to save yourself the mess of loading template, then rendering it etc: from django.shortcuts import render def login(request): names = User.query_choice("first_name") return render(request, "registration/home.html", {"output": names})
doc_23531477
AJAX code success: function(data) { console.log(data); if (data !='') { var obj = $.parseJSON(data); if (obj.status == "ok") { location.reload(); } } Thank you A: Have you tried using the .RememberState function with your ajax call? Typically this might be applied to a form (so if the form is partially filled out and a user refreshes the page their changes are preserved), but in theory I don't see why you couldnt use it on the document itself. Check out this link it might explain it more clearly http://shaneriley.com/jquery/remember_state/ You'd want to do this before the call, and in the success callback, you should be able to use this RememberState to return to the active session you had before. If this isn't what you're referring to I apologize for misinterpreting your question.
doc_23531478
My function looks like this: openPdf(data: string): void { const base64String = btoa(data); const bufferArray = Uint8Array.from(atob(base64String), c => c.charCodeAt(0)); const pdfBlob = new Blob([bufferArray], { type: 'application/pdf' }); const url = window.URL.createObjectURL(pdfBlob); const link = document.createElement('a'); link.href = url; link.target = '_blank'; link.click(); window.URL.revokeObjectURL(url); } This is working fine in that no console errors are thrown and it does indeed open a new browser window but the problem is that the content is missing. Here is a screenshot of what it looks like in Chrome. Could it be because I'm simply converting a regular string and trying to convert that into a PDF? A: Yes, if you use base64 to convert a regular string into a PDF, it may not work because a pdf document has a proper structure and a format you need to follow base64 might not follow it. You can rather use jsPDF or pdfmake to create a pdf document from your own data, then use the same method to create a Blob and open it to a new window. This is an example using jsPDF import jsPDF from 'jspdf'; function openPdf(data: string): void { const doc = new jsPDF(); doc.text(data, 10, 10); const pdfBlob = doc.output('blob'); const url = window.URL.createObjectURL(pdfBlob); const link = document.createElement('a'); link.href = url; link.target = '_blank'; link.click(); window.URL.revokeObjectURL(url); }
doc_23531479
import { browser } from “protractor”; // this is the import I used browser.executeScript(‘arguments[0].click()’;, this.closeButton); // this is for button clicking browser.executeScript(‘localStorage.setItem(“example-boolean”, “false”)’); // this is for setting a value to false Is there a Cypress equivalent for these lines of code? A: Some inspiration: import "cypress-localstorage-commands"; cy.get('#yourCloseBtnId').click(); // Clicking on the element with an ID #yourCloseBtnId cy.setLocalStorage("example-boolean", false); // Setting an item in the local storage
doc_23531480
How do I encode the image together with the other properties and save it in NSUserDefaults? My understanding is that I can only encode NSStrings? For example, currently in my code, I am adding the avatar_url (string) in the encode/decode implementation. How can I convert the url to UIImage and then encode it? - (void)encodeWithCoder:(NSCoder *)encoder { [encoder encodeObject:self.uid forKey:@"uid"]; [encoder encodeObject:self.avatar_url forKey:@"avatar_url"]; } - (id)initWithCoder:(NSCoder *)decoder { self = [super init]; if( self != nil ){ self.uid = [decoder decodeObjectForKey:@"uid"]; self.avatar_url = [decoder decodeObjectForKey:@"avatar_url"]; } } A: UPDATE As pointed out in the comments, UIImage conforms to NSCoding, so you can just encode it directly, like this: [encoder encodeObject:image forKey:@"image"]; This has the advantage that it (should) store all the properties of the image, including scale and imageOrientation, which may be pretty important to preserve if they're not set to the defaults. However, it does have some risks you should be aware of. If the image was loaded directly from your app bundle, the archive will contain the image name, but not the image data. And if the archive does contain the image data, it will be in PNG format, while you might prefer JPEG format depending on the kind of image you're encoding. ORIGINAL Use UIImagePNGRepresentation or UIImageJPEGRepresentation to convert the UIImage to an NSData, then encode the NSData: [encoder encodeObject:UIImagePNGRepresentation(self.image) forKey:@"image"]; To decode the image later: self.image = [UIImage imageWithData:[decoder decodeObjectForKey:@"image"]];
doc_23531481
What is gain property on track? Max and min value? Is it possible/Is it good approach to adjust volume depends on gain property? A: It is a good idea to use the property gain, it defines the signal strength. The default value is 0, you can have lower and greater values that you will have to adjust around but I'm not sure that the method setVolume of the SDK will work fine with this value.
doc_23531482
Example: void foo() { struct bar { int baz() { return 0; } // allowed static const int qux = 0; // not allowed?!? }; } struct non_local_bar { int baz() { return 0; } // allowed static const int qux = 0; // allowed }; Quote from standard (9.8.4): A local class shall not have static data members. A: I dont think there is a.reason. Normal static datamembers are disallowed because there is no way to define them after being declared. Also dont forget you can create a local const variable outside the.class that you can use inside the class as long as you only read its value (that is, as long as you dont take.its.address). A: Static members of a class need to be defined in global scope, e.g. abc.h class myClass { static int number; }; abc.cpp int myClass::number = 314; Now, since the scope inside void abc(int x) is not global, there is no scope to define the static member. A: From the standard section 9.4.2: If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression. In that case, the member can appear in integral constant expressions within its scope. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer. Basically, local classes have no linkage, and static data members require a linkage. Since there's no way to define a static data member of a local class in namespace scope (a declaration with an initializer is not a definition), they are not allowed, whether they are of const integral type or not. On the surface it may seem like the compiler should just be able to inline the value, but then what happens if you try to access a pointer to the member? With namespace scoped classes you'd just get a linker error, but local classes have no linkage. I guess in theory they could just allow you to use static const integral types in local classes as long as they are only used in integral constant expressions, but it would probably just put too much of a burden on the standards body and compiler vendors to differentiate for very little practical value; local static variables are accessible from local classes, so using a local static const should be just as good. A: As things progress, we now have C++11 and with that you can define integral constants variable members in your classes. class test { public: const int FOO = 123; [...snip...] }; That works when you compile with C++11. Notice that the static keyword is not used. When compiling with optimizations turned on, those variables will likely all get optimized out. In debug, though, they appear in your structure as regular variable members. Note, however, that the size of the class/structure will still include that variable. So here it is likely 4 bytes for the variable FOO. However, in most cases, classes defined in a function will completely be optimized out so this is a great way of doing things (a good 50% of my classes have such variable members!)
doc_23531483
A: Please note, the official documentation will be updated shortly. In the meantime: What's changed SDN 4.1 uses the new Neo4j OGM 2.0 libraries. OGM 2.0 introduces API changes, largely due to the addition of support for Embedded as well as Remote Neo4j. Consequently, connection to a production database is now accomplished using an appropriate Driver, rather than using the RemoteServer or the InProcessServer which are deprecated. For testing, we recommend using the EmbeddedDriver. It is still possible to create an in-memory test server, but that is not covered in this answer. Available Drivers The following Driver implementations are currently provided * *http : org.neo4j.drivers.http.driver.HttpDriver *embedded : org.neo4j.drivers.embedded.driver.EmbeddedDriver A driver implementation for the Bolt protocol (Neo4j 3.0) will be available soon. Configuring a driver There are two ways to configure a driver - using a properties file or via Java configuration. Variations on these themes exist (particularly for passing credentials), but for now the following should get you going: Configuring the Http Driver The Http Driver connects to and communicates with a Neo4j server over Http. An Http Driver must be used if your application is running in client-server mode. Please note the Http Driver will attempt to connect to a server running in a separate process. It can't be used for spinning up an in-process server. Properties file configuration: The advantage of using a properties file is that it requires no changes to your Spring configuration. Create a file called ogm.properties somewhere on your classpath. It should contain the following entries: driver=org.neo4j.ogm.drivers.http.driver.HttpDriver URI=http://user:password@localhost:7474 Java configuration: The simplest way to configure the Driver is to create a Configuration bean and pass it as the first argument to the SessionFactory constructor in your Spring configuration: import org.neo4j.ogm.config.Configuration; ... @Bean public Configuration getConfiguration() { Configuration config = new Configuration(); config .driverConfiguration() .setDriverClassName ("org.neo4j.ogm.drivers.http.driver.HttpDriver") .setURI("http://user:password@localhost:7474"); return config; } @Bean public SessionFactory getSessionFactory() { return new SessionFactory(getConfiguration(), <packages> ); } Configuring the Embedded Driver The Embedded Driver connects directly to the Neo4j database engine. There is no server involved, therefore no network overhead between your application code and the database. You should use the Embedded driver if you don't want to use a client-server model, or if your application is running as a Neo4j Unmanaged Extension. You can specify a permanent data store location to provide durability of your data after your application shuts down, or you can use an impermanent data store, which will only exist while your application is running (ideal for testing). Create a file called ogm.properties somewhere on your classpath. It should contain the following entries: Properties file configuration (permanent data store) driver=org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver URI=file:///var/tmp/graph.db Properties file configuration (impermanent data store) driver=org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver To use an impermanent data store, simply omit the URI property. Java Configuration The same technique is used for configuring the Embedded driver as for the Http Driver. Set up a Configuration bean and pass it as the first argument to the SessionFactory constructor: import org.neo4j.ogm.config.Configuration; ... @Bean public Configuration getConfiguration() { Configuration config = new Configuration(); config .driverConfiguration() .setDriverClassName ("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver") .setURI("file:///var/tmp/graph.db"); return config; } @Bean public SessionFactory getSessionFactory() { return new SessionFactory(getConfiguration(), <packages> ); } If you want to use an impermanent data store (e.g. for testing) do not set the URI attribute on the Configuration: @Bean public Configuration getConfiguration() { Configuration config = new Configuration(); config .driverConfiguration() .setDriverClassName ("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver") return config; }
doc_23531484
Here is my sample code: import React, { FunctionComponent, useState, useEffect, useRef } from "react"; import { View } from "react-native" const Sample : FunctionComponent<any> = props => { // contains 250+ items const [list, setList] = useState<any[]>(); useEffect(() => { //updates the list everytime it catches a data myListener((somevalue) => setList(somevalue)) }; // very slow render(){ <FlatList data=[list] renderItem={renderItem} getItemLayout={getItemLayout} initialNumToRender={initialItemRender} maxToRenderPerBatch={5} keyExtractor={(item, index) => item.value} /> } } This is only my sample code. if you have an idea on better way optimizing the list. i'll appreciate it
doc_23531485
{ "userLog": { "properties": { "userInfo": { "userId": { "type": "text" }, "firstName": { "type": "text" }, "lastName": { "type": "text" }, "email": { "type": "text" } }, "violations": { "type": "integer" }, "malfunctions": { "type": "integer" }, "extensionsUsed": { "type": "integer" }, "date": { "type": "date", "format": "yyyy-MM-dd||yyyy/MM/dd||yyyyMMdd||epoch_millis" }, "events": { "type": "nested", "properties": { "editorId": { "type": "text" }, "editorRole": { "type": "text" }, "editedTimestamp": { "type": "date", "format": "epoch_millis" }, "createdTimestamp": { "type": "date", "format": "epoch_millis" }, "userId": { "type": "text" }, "timestamp": { "type": "date", "format": "epoch_millis" }, "eventType": { "type": "text" } } } } } } Some userLogs have events and some don't. My queries only return userLogs that have events, however, and I'm not sure why. There are definitely userLogs that exist without events in the index. I can see them in Kibana. They just aren't returned in the search. Here's what I'm running for a query: GET index_name/_search { "query": { "bool": { "must": [ { "range": { "date": { "gte": "20170913", "format": "yyyyMMdd" } } } ], "should": [ { "match_phrase": { "userInfo.userId": "Xvo9qblajOVaM3bQQMaV4GKk7S42" } } ], "minimum_number_should_match": 1 } } } based on this discussion I modified my query to be the following: GET one20_eld_portal/_search { "query": { "bool": { "must_not": [ { "nested": { "path": "events", "query": { "bool": { "filter": { "exists": { "field": "events.userId" } } } } } } ], "should": [ { "match_phrase": { "userInfo.uid": "Xvo9qblajOVaM3bQQMaV4GKk7S42" } } ], "minimum_should_match": 1 } } } but this doesn't return any results. Any help is greatly appreciated! A: Turns out the reason the "empty" logs weren't being returned is because the userId wasn't being set properly for empty logs.
doc_23531486
So the only one that was reliable and made sense was http://blog.bigbinary.com/2015/11/03/using-stripe-api-in-react-native-with-fetch.html . Here it lays out what's needed to be fully PCI-compliant, https://stripe.com/docs/security My question is, by following blog.bigbinary.com using fetch except hosting my secret key in the front-end, would I be fully PCI-compliant as if I was using Stripe.js? And how can I make sure to be using Transport Layer Security? Anyone who has already fully integrated Stripe using React Native can chime in, would really appreciate any insight or guidance. Will be accepting answer with upvote and thank you A: We've made wrapper around native Stripe SDK for both platforms here: https://github.com/tipsi/tipsi-stripe It's also contains usage guide on RN side.
doc_23531487
* *Port the ASPX page into the proper location within the content of a Sharepoint site *Properly register the CaptchaControl dll with Sharepoint and link allow the ASPX page to utilize it A: Set up application page The ASPX page would be called an 'application page' in SharePoint. You can copy the ASPX to the layouts folder under the "12 Hive". ("%CommonProgramFiles%\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS"). It would then be accessible from any SharePoint site under {URL}/_layouts/CustomPage.aspx (e.g. http://site/_layouts/CustomPage.aspx or http://site/subsite/_layouts/CustomPage.aspx). Add safe control entries It looks like you know to place any DLL for your aspx page as well as CaptchaControl.dll in the bin folder for the SharePoint site under IIS. The DLLs must be signed with a strong name key. You also need to add the strongly-named signature of the DLLs to the SafeControls list in the web.config file for the SharePoint site. If you open up the web.config you'll see examples, e.g.: <SafeControl Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" Namespace="Microsoft.SharePoint" TypeName="*" Safe="True" /> Configure code access security Assuming your controls actually do something, you need to mark them as trusted in the Code Access Security file that SharePoint uses. Change the trust level in web.config from WSS_Minimal to WSS_Custom. Go to "%CommonProgramFiles%\Microsoft Shared\web server extensions\12\CONFIG" and copy wss_minimaltrust.config to wss_customtrust.config. Edit wss_customtrust.config and make new CodeGroup entries using the public key of your DLLs. For example: <CodeGroup class="UnionCodeGroup" version="1" PermissionSetName="FullTrust"> <IMembershipCondition class="StrongNameMembershipCondition" version="1" PublicKeyBlob="002400000480435694000000060200000024245452534131000400000100453261002888e278243eb86b47eea4be1b23451177126fb9c847085e66e895a64b148c675dabda94d9301f4886a0126887bcd067356affb16a5112baf3198525fc96c45f4178a6263e1a1132bb6c0a4cdaeaccd97b0d4ab42139585700c41e8481feff03e13f30bb0a10ffa7746770d144be94954b7a908fb9bb680ebe611f50f6db" /> </CodeGroup> Note: This will make your DLLs fully trusted within the SharePoint web application. It is better practice to restrict permissions to those actually required.
doc_23531488
It just downloads files in 10MB chunks, there can be like 600 of them, but the NSOperationQueue has a limit of 6 concurrent tasks. How come the same app on Windows (written in C# eats only 2%, not 80%!), it is just a simple HTTP request! for (DownloadFile *downloadFile in [download filesInTheDownload]) { for (DownloadChunk *downloadChunk in [downloadFile chunksInTheFile]) { NSString *downloadPath = [[NSString stringWithFormat:@"%@/%@", [download downloadFolder], [download escapedTitle]] stringByExpandingTildeInPath]; NSString *chunkPath = [downloadPath stringByAppendingFormat:@"/%@.%i", [downloadFile fileName], [downloadChunk chunkId]]; NSError *attributesError = nil; NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:chunkPath error:&attributesError]; NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize]; uint64_t fileSize = [fileSizeNumber longLongValue]; NSLog(@"Chunk file size: %lli", fileSize); uint64_t expectedSize = ([downloadChunk endingByte] - [downloadChunk startingByte]) + 1; NSLog(@"Chunk expected size: %lli", expectedSize); uint64_t newStartingByte = [downloadChunk startingByte] + fileSize; if (fileSize == expectedSize) { NSLog(@"Chunk complete: %@.%i", [downloadFile fileName], [downloadChunk chunkId]); } else { NSURL *fileURL = [[NSURL alloc] initWithString:[downloadFile filePath]]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:fileURL]; NSLog(@"Normal range: %lli-%lli", [downloadChunk startingByte], [downloadChunk endingByte]); NSString *range = [NSString stringWithFormat:@"bytes=%lli-%lli", newStartingByte, [downloadChunk endingByte]]; [request setValue:range forHTTPHeaderField:@"Range"]; AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; operation.outputStream = [NSOutputStream outputStreamToFileAtPath:chunkPath append:YES]; [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"%@", [NSString stringWithFormat:@"Chunk complete: %@.%i", [downloadFile fileName], [downloadChunk chunkId]]); if (download.downloadedBytes == download.size) [[NSNotificationCenter defaultCenter] postNotificationName:@"downloadFinished" object:download]; } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", error); }]; [operation setDownloadProgressBlock:^(NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) { download.downloadedBytes += bytesRead; }]; [queue addOperation:operation]; } } } Here are some time profiler screenshots, seems everything is because RunLoops if I read it correctly. A: Seems like downgrading most of the properties to nonatomic seems to lower the usage from 80% to 20-30%. Now only downloadedBytes are atomic. What can I do also to make improvements? A: In assuming the last progress block completes the download, you're sort of shoving a round peg down a square hole. I'm not sure if that's causing your high CPU usage or not, but I'd certainly fix that. AFNetworking has a function just for this, [AFHTTPRequestOperation setCompletionBlockWithSuccess:failure:], documented here. The correct block will be called based on the HTTP status code returned. In other words, instead of this: AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; operation.outputStream = [NSOutputStream outputStreamToFileAtPath:chunkPath append:YES]; [operation setDownloadProgressBlock:^(NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) { download.downloadedBytes += bytesRead; if (download.downloadedBytes == download.size) [[NSNotificationCenter defaultCenter] postNotificationName:@"downloadFinished" object:download]; }]; [queue addOperation:operation]; chunkId++; Use this: AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; operation.outputStream = [NSOutputStream outputStreamToFileAtPath:chunkPath append:YES]; [output setCompletionBlockWithSuccess: ^(AFHTTPRequestOperation *operation, id responseObject) { [[NSNotificationCenter defaultCenter] postNotificationName:@"downloadFinished" object:download]; } failure: ^(AFHTTPRequestOperation *operation, NSError *error) { // you should probably do something here }]; After that, I doubt you'd even need downloadedBytes. That removes your last atomic property, which should improve things.
doc_23531489
I want the logos to appear as 2 per row, then 3, then 2, repeating so 2, 3, 2, etc. My code is mostly working but the first image isn't going into the first row. <div class="container"> <?php $args = array( 'post_type' => 'clients', 'post_status' => 'publish', ); $query = new WP_Query( $args ); $count = 0; while($query -> have_posts()) : $query -> the_post(); $client_image = get_field('client_logo'); $size = 'full'; if($count == 1){ echo '<div class="row up-to-2">'; } if($count == 2){ echo '</div><div class="row up-to-3">'; } if( $client_image ) { ?> <div class="col-md-<?php echo ($count == 1 ? 6 : 4); ?>"> <div class="client-logo"> <a class="news-post-title" href="<?php the_permalink(); ?>"> <?php echo wp_get_attachment_image( $client_image, $size ); ?> <h4><?php the_title(); ?></h4></a> </div> </div> <?php } $count++; endwhile; echo '</div>'; ?> </div> I've tried if($count == 1){ $count = 0; echo '<div class="row up-to-2">'; } But doing that causes a loop of rows going into row. I'm trying to better understand PHP and counts so an explanation would be very helpful! UPDATE I've managed to get the first item into the row but now the order is 2 1 2, instead of what I desire 2, 3, 2. <div class="container"> <?php $args = array( 'post_type' => 'clients', 'post_status' => 'publish', ); $query = new WP_Query( $args ); $count = 0; echo '<div class="row up-to-2">'; while($query -> have_posts()) : $query -> the_post(); $client_image = get_field('client_logo'); $size = 'full'; if($count == 2){ echo '</div><div class="row up-to-3">'; } else if($count == 3){ echo '</div><div class="row up-to-3">'; } if( $client_image ) { ?> <div class="col-md-<?php echo ($count == 1 ? 6 : 4); ?>"> <div class="client-logo"> <a class="news-post-title" href="<?php the_permalink(); ?>"> <?php echo wp_get_attachment_image( $client_image, $size ); ?> <h4><?php the_title(); ?></h4></a> </div> </div> <?php } $count++; endwhile; echo '</div>'; ?> </div> A: You need below logic to apply <?php $i = 0; echo '<div class="row up-to-2">'.PHP_EOL; foreach( range(0,10) as $key => $value ){ echo '$value='.$value.PHP_EOL; if($i == 1) { echo '</div>'.PHP_EOL.'<div class="row up-to-3">'.PHP_EOL; } $i ++; if($i == 5) { echo '</div>'.PHP_EOL.'<div class="row up-to-2">'.PHP_EOL; $i = 0; } } echo '</div>'; Output: <div class="row up-to-2"> $value=0 $value=1 </div> <div class="row up-to-3"> $value=2 $value=3 $value=4 </div> <div class="row up-to-2"> $value=5 $value=6 </div> <div class="row up-to-3"> $value=7 $value=8 $value=9 </div> <div class="row up-to-2"> $value=10 </div> Demo Go to demo link and hit Execute code button You need your while loop must be like below <?php $i = 0; echo '<div class="row up-to-2">' . PHP_EOL; while ($query->have_posts()) : $query->the_post(); $client_image = get_field('client_logo'); $size = 'full'; if ($client_image) { ?> <div class="col-md-<?php echo($count == 1 ? 6 : 4); ?>"> <div class="client-logo"> <a class="news-post-title" href="<?php the_permalink(); ?>"> <?php echo wp_get_attachment_image($client_image, $size); ?> <h4><?php the_title(); ?></h4></a> </div> </div> <?php } if ($i == 1) { echo '</div>' . PHP_EOL . '<div class="row up-to-3">' . PHP_EOL; } $i++; if ($i == 5) { echo '</div>' . PHP_EOL . '<div class="row up-to-2">' . PHP_EOL; $i = 0; } endwhile; echo '</div>'; ?>
doc_23531490
My problem is, is that I would like the option on top to slide up instead of down. My code for the menu <div class="additional-navigation-wrapper"> <div class="additional-navigation"> <a class="border-bottom-white padding-level-one inactive additional-nav-info1" href="javascript:void(0);"> <h4>info</h4> <img class="nav-arrow no-action floatright" src="images/nav-arrow-white.png" /> <span class="clearboth"></span> </a> <div class="additional-nav-info-wrapper1"> <div class="additional-nav-info-inner1" style="display: none;"> <ul> <h3>Some information</h3> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis tristique nisi et diam sagittis, scelerisque lacinia justo dictum. Maecenas neque dolor, sodales vel dolor eget, scelerisque molestie tellus. Aenean ut tristique quam. Nullam id convallis augue. Duis ut sem sed lorem tempor fermentum eget mattis ligula. Mauris cursus, dolor quis pellentesque porta, lacus ipsum ornare metus, nec volutpat arcu justo id turpis. Nunc tempus libero non lacus sagittis, nec condimentum nulla fringilla. Duis id ultrices velit. Nunc at sem quis mauris commodo tempor. Phasellus sit amet est rhoncus ipsum egestas varius quis et quam. Nulla in risus sit amet quam vulputate dapibus et non elit. Cras facilisis congue odio, sit amet posuere metus eleifend sed. </p> </ul> </div> </div> </div> <div class="additional-navigation-wrapper"> <div class="additional-navigation"> <a class="border-bottom-white padding-level-one inactive additional-nav-info2" href="javascript:void(0);">Lorem ipsum <img class="nav-arrow no-action floatright" src="images/nav-arrow-white.png" /> <span class="clearboth"></span> </a> <div class="additional-nav-info-wrapper2"> <div class="additional-nav-info-inner2" style="display: none;"> <ul> Praesent tempor eleifend nibh, nec rutrum est tristique at. Nulla fermentum posuere posuere. Suspendisse potenti. Phasellus dapibus tristique urna, quis eleifend quam dapibus vel. Sed tempor ipsum ipsum, a tristique est tincidunt ac. Curabitur eu erat semper purus lacinia dignissim. Proin pretium hendrerit nisl, vitae ultricies erat adipiscing vitae. Aliquam scelerisque nisl sit amet molestie euismod. </ul> </div> </div> </div> <div class="additional-navigation"> <a class="border-bottom-white padding-level-one inactive additional-nav-info3" href="javascript:void(0);">Lorem ipsum <img class="nav-arrow no-action inactive floatright" src="images/nav-arrow-white.png" /> <span class="clearboth"></span> </a> <div class="additional-nav-info-wrapper3"> <div class="additional-nav-info-inner3" style="display: none;"> <ul> Suspendisse potenti. Nulla facilisi. Curabitur volutpat quam ac pretium varius. Vivamus et commodo sapien. Praesent eu pulvinar neque. Etiam faucibus sapien sit amet odio adipiscing vestibulum. Aliquam in elit quis augue iaculis dictum id vel lacus. Curabitur vel ligula eget enim imperdiet dapibus id non lacus. Phasellus nec massa quis neque fermentum convallis ac at dolor. Nulla lacus velit, feugiat ut scelerisque sit amet, semper sit amet nibh. Ut auctor justo ligula, ac aliquam massa dictum a. Phasellus sed sapien tincidunt, dignissim turpis vitae, pretium elit. Nulla dictum ac diam id lobortis. </ul> </div> </div> </div> <div class="additional-navigation"> <a class="border-bottom-white padding-level-one inactive additional-nav-info4" href="javascript:void(0);">Lorem ipsum <img class="nav-arrow no-action floatright" src="images/nav-arrow-white.png" /> <span class="clearboth"></span> </a> <div class="additional-nav-info-wrapper4"> <div class="additional-nav-info-inner4" style="display: none;"> <ul> Maecenas sollicitudin et velit nec consectetur. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aliquam venenatis elit vel elit porta, ac pretium arcu commodo. Curabitur nec diam eu eros dignissim vestibulum. Donec tellus justo, aliquet non nunc vel, accumsan gravida ligula. Mauris eu consequat mi, sed euismod nulla. Vestibulum luctus tempor tortor suscipit ultrices. Vestibulum in justo vel purus tincidunt convallis. Integer varius facilisis urna in scelerisque. Aliquam mattis neque eget arcu blandit, a mollis ligula consectetur. </ul> </div> </div> </div> <div class="additional-navigation"> <a class="border-bottom-white padding-level-one inactive additional-nav-info5" href="javascript:void(0);">Lorem ipsum <img class="nav-arrow no-action floatright" src="images/nav-arrow-white.png" /> <span class="clearboth"></span> </a> <div class="additional-nav-info-wrapper5"> <div class="additional-nav-info-inner5" style="display: none;"> <ul> Aliquam sed tellus eget nunc ultricies pellentesque. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed fermentum, ante fermentum faucibus blandit, risus quam tristique justo, a feugiat odio nisl commodo augue. Nulla facilisi. Aenean hendrerit tortor vulputate cursus laoreet. Morbi libero leo, elementum eu lectus nec, fringilla imperdiet purus. Quisque eget odio tempus, ultricies orci eu, dictum dolor. Curabitur at lectus ac ipsum lobortis consectetur non a tellus. Donec vestibulum sapien et consequat venenatis. Sed in velit nulla. Nulla commodo, mi at lacinia blandit, tellus dui vestibulum dolor, ac interdum libero arcu a mi. Duis in neque a nulla varius laoreet. Etiam et purus adipiscing, adipiscing est vitae, porttitor nulla. </ul> </div> </div> </div> <div class="additional-navigation"> <a class="border-bottom-white padding-level-one inactive additional-nav-info6" href="javascript:void(0);">Lorem ipsum <img class="nav-arrow no-action floatright" src="images/nav-arrow-white.png" /> <span class="clearboth"></span> </a> <div class="additional-nav-info-wrapper6"> <div class="additional-nav-info-inner6" style="display: none;"> <ul> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eu ultrices turpis, at ornare tellus. Integer at gravida tellus. Fusce at aliquet sem. Suspendisse condimentum laoreet bibendum. Nam id aliquam arcu. Vivamus vulputate purus vitae ipsum elementum, vitae feugiat risus pellentesque. Nam vel turpis dolor. Phasellus turpis lacus, facilisis ac lectus sed, imperdiet tempor sem. Duis sed tortor ac urna ultrices sagittis id vitae dolor. Duis mattis venenatis dui sit amet luctus. Fusce eu felis sed dui blandit volutpat. Nullam pharetra pellentesque quam ut laoreet. </ul> </div> </div> </div> <div class="additional-navigation"> <a class="border-bottom-white padding-level-one active contact-details-onpage" href="javascript:void(0);">Lorem ipsum <img class="nav-arrow no-action floatright" src="images/nav-arrow-blue-one.png" /> <span class="clearboth"></span> </a> <div class="contact-details-onpage-wrapper"> <div class="contact-details-onpage-inner" style="display: block;"> <ul> <li> <a href="#">EMAIL US <img src="images/email-ico.png" /> <img style="display: none;" src="images/email-ico-active.png" /> </a> </li> <li> <a href="#">08000 58 24 50 <img src="images/telephone-ico.png" /> <img style="display: none;" src="images/telephone-ico-active.png" /> </a> </li> <li> <a href="#">OUR PORTFOLIO <img src="images/portfolio-ico.png" /> <img style="display: none;" src="images/portfolio-ico-active.png" /> </a> </li> <li> <a href="#">CONTACT FORM <img src="images/contact-form-ico.png" /> <img style="display: none;" src="images/contact-form-ico-active.png" /> </a> </li> <div class="clearboth"></div> </ul> <div class="clearboth"></div> </div> </div> </div> </div> and this is my css html, body { background: #FFFFFF; font-family: arial; font-size: 18px; margin: 0; padding: 0; color: #000000; } .border-bottom-blue { border-bottom: solid 1px #43b6cf; } .padding-level-one { padding: 0 22px; } .additional-navigation-wrapper { } .additional-navigation .nav-arrow { padding: 0; } .additional-navigation-wrapper a { color: #000; padding: 10px 22px; text-transform: uppercase; text-decoration: none; display: block; } .additional-navigation .active { color: #43b6cf; border-bottom: solid 1px #43b6cf; } .csstransitions .additional-navigation-wrapper a { -webkit-transition-duration: 0.5s; -moz-transition-duration: 0.5s; -o-transition-duration: 0.5s; transition-duration: 0.5s; } .additional-navigation-wrapper a:hover { color: #43b6cf; border-bottom: solid 1px #43b6cf; } .contact-details-onpage-inner { padding: 40px 22px 2px; } .contact-details-onpage-inner ul { font-size: 12px; } .contact-details-onpage-inner li { float: left; position: relative; list-style: none; height: 23px; margin: 0 40px 0 0; } .contact-details-onpage-inner li img { position: absolute; left: 0; top: 0; } .contact-details-onpage-inner li a { color: #ffffff; text-decoration: none; position: relative; padding: 10px 5px 2px 30px; } .contact-details-onpage-inner li a:hover { border: none; color: #ffffff; } and here is my jquery $(".additional-nav-info0").click(function () { if ($(".additional-nav-info-inner0").css("display") == "block") { $(this).removeClass("active"); $(this).addClass("inactive"); $(".additional-nav-info-inner0").stop().slideToggle(250); } else { $(this).removeClass("inactive"); $(this).addClass("active"); $(".additional-nav-info-inner0").stop().slideToggle(250); } }); $(".additional-nav-info-inner0 a").hover(function () { $(this).find("img").eq(0).fadeOut(250); $(this).find("img").eq(1).fadeIn(250); }, function () { $(this).find("img").eq(0).fadeIn(250); $(this).find("img").eq(1).fadeOut(250); }); $(".additional-nav-info1").click(function () { if ($(".additional-nav-info-inner1").css("display") == "block") { $(this).removeClass("active"); $(this).addClass("inactive"); $(".additional-nav-info-inner1").stop().slideToggle(250); } else { $(this).removeClass("inactive"); $(this).addClass("active"); $(".additional-nav-info-inner1").stop().slideToggle(250); } }); $(".additional-nav-info-inner1 a").hover(function () { $(this).find("img").eq(0).fadeOut(250); $(this).find("img").eq(1).fadeIn(250); }, function () { $(this).find("img").eq(0).fadeIn(250); $(this).find("img").eq(1).fadeOut(250); }); $(".additional-nav-info2").click(function () { if ($(".additional-nav-info-inner2").css("display") == "block") { $(this).removeClass("active"); $(this).addClass("inactive"); $(".additional-nav-info-inner2").stop().slideToggle(250); } else { $(this).removeClass("inactive"); $(this).addClass("active"); $(".additional-nav-info-inner2").stop().slideToggle(250); } }); $(".additional-nav-info-inner2 a").hover(function () { $(this).find("img").eq(0).fadeOut(250); $(this).find("img").eq(1).fadeIn(250); }, function () { $(this).find("img").eq(0).fadeIn(250); $(this).find("img").eq(1).fadeOut(250); }); $(".additional-nav-info3").click(function () { if ($(".additional-nav-info-inner3").css("display") == "block") { $(this).removeClass("active"); $(this).addClass("inactive"); $(".additional-nav-info-inner3").stop().slideToggle(250); } else { $(this).removeClass("inactive"); $(this).addClass("active"); $(".additional-nav-info-inner3").stop().slideToggle(250); } }); $(".additional-nav-info-inner3 a").hover(function () { $(this).find("img").eq(0).fadeOut(250); $(this).find("img").eq(1).fadeIn(250); }, function () { $(this).find("img").eq(0).fadeIn(250); $(this).find("img").eq(1).fadeOut(250); }); $(".additional-nav-info4").click(function () { if ($(".additional-nav-info-inner4").css("display") == "block") { $(this).removeClass("active"); $(this).addClass("inactive"); $(".additional-nav-info-inner4").stop().slideToggle(250); } else { $(this).removeClass("inactive"); $(this).addClass("active"); $(".additional-nav-info-inner4").stop().slideToggle(250); } }); $(".additional-nav-info-inner4 a").hover(function () { $(this).find("img").eq(0).fadeOut(250); $(this).find("img").eq(1).fadeIn(250); }, function () { $(this).find("img").eq(0).fadeIn(250); $(this).find("img").eq(1).fadeOut(250); }); $(".additional-nav-info5").click(function () { if ($(".additional-nav-info-inner5").css("display") == "block") { $(this).removeClass("active"); $(this).addClass("inactive"); $(".additional-nav-info-inner5").stop().slideToggle(250); } else { $(this).removeClass("inactive"); $(this).addClass("active"); $(".additional-nav-info-inner5").stop().slideToggle(250); } }); $(".additional-nav-info-inner5 a").hover(function () { $(this).find("img").eq(0).fadeOut(250); $(this).find("img").eq(1).fadeIn(250); }, function () { $(this).find("img").eq(0).fadeIn(250); $(this).find("img").eq(1).fadeOut(250); }); $(".additional-nav-info6").click(function () { if ($(".additional-nav-info-inner6").css("display") == "block") { $(this).removeClass("active"); $(this).addClass("inactive"); $(".additional-nav-info-inner6").stop().slideToggle(250); } else { $(this).removeClass("inactive"); $(this).addClass("active"); $(".additional-nav-info-inner6").stop().slideToggle(250); } }); Here is a link to JSFiddle http://jsfiddle.net/cerberus478/58Jm7/1/ A: .slideToggle({direction: 'up'}, 250); A: <script type="text/javascript"> $(".additional-nav-info1").click(function(){ if($(".additional-nav-info-inner1").css("display") == "block"){ $(this).removeClass("active"); $(this).addClass("inactive"); $(".additional-nav-info-inner1").stop().slideToggle(250); } else { $(this).removeClass("inactive"); $(this).addClass("active"); $(".additional-nav-info-inner1").stop().slideToggle({direction: 'up'}, 250); } }); </script> and now, you need add just add position:absolute; to .additional-nav-info1. A: $(".additional-nav-info1").click(function(){ if($(".additional-nav-info-inner1").css("display") == "block"){ $(this).removeClass("active"); $(this).addClass("inactive"); $(".additional-nav-info-inner1").stop().slideToggle(250); } else { $(this).removeClass("inactive"); $(this).addClass("active"); $(".additional-nav-info-inner1").stop().slideToggle(250); var dHeight = $(".additional-nav-info-inner1 ul").height(); $('html,body').animate({ scrollTop: '+=' + dHeight + 'px' }, 250); } }); fiddle
doc_23531491
<dependency org="org.springframework" name="org.springframework.core" rev="3.0.2.RELEASE" /> <dependency org="org.springframework" name="org.springframework.context" rev="3.0.2.RELEASE" /> <dependency org="org.springframework" name="org.springframework.jdbc" rev="3.0.2.RELEASE" /> <dependency org="org.springframework" name="org.springframework.beans" rev="3.0.2.RELEASE" /> <dependency org="org.springframework" name="org.springframework.jms" rev="3.0.2.RELEASE" /> Here's what I'd like it to look like: <dependency org="org.springframework" name="org.springframework.core" rev="${spring.version}" /> <dependency org="org.springframework" name="org.springframework.context" rev="${spring.version}" /> <dependency org="org.springframework" name="org.springframework.jdbc" rev="${spring.version}" /> <dependency org="org.springframework" name="org.springframework.beans" rev="${spring.version}" /> <dependency org="org.springframework" name="org.springframework.jms" rev="${spring.version}" /> Is this possible? What's the syntax? A: I ended up using XML entities to do the substitution. This keeps everything in the same file, which is important for my use case. <?xml version="1.0"?> <!DOCTYPE ivy-module [ <!ENTITY spring.version "3.0.2.RELEASE"> ]> <ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://incubator.apache.org/ivy/schemas/ivy.xsd"> <info organisation="org" module="mod"/> <dependencies> <dependency org="org.springframework" name="org.springframework.core" rev="&spring.version;" /> <dependency org="org.springframework" name="org.springframework.context" rev="&spring.version;" /> <dependency org="org.springframework" name="org.springframework.jdbc" rev="&spring.version;" /> <dependency org="org.springframework" name="org.springframework.beans" rev="&spring.version;" /> <dependency org="org.springframework" name="org.springframework.jms" rev="&spring.version;" /> </dependencies> </ivy-module> A: Syntax is correct. All you need to do is set the ANT property somewhere. For example ant -Dspring.version=3.0.2.RELEASE Another alternative is to add the property declaration into the ivysettings.xml file <ivysettings> <property name="spring.version" value="3.0.2.RELEASE"/> <settings defaultResolver="maven2"/> <resolvers> <ibiblio name="maven2" m2compatible="true"/> </resolvers> </ivysettings> A: You can use property files as explained here: http://apache-ivy.996301.n3.nabble.com/ivyde-properties-on-ivy-xml-td7484.html <properties file="${ivy.project.dir}/build.properties" /> insite ivysettings.xml
doc_23531492
Following the Desired capabilities and the first test @Test public void test0() throws MalformedURLException, InterruptedException { File app = new File("C:\\Users\\Samila\\Documents\\Mobile_Research\\Apk\\android-debug.apk"); DesiredCapabilities caps = DesiredCapabilities.android(); caps.setCapability(CapabilityType.BROWSER_NAME, ""); caps.setCapability("deviceName","samsung-sm_t530nu"); caps.setCapability("platformVersion", "5.0.2"); caps.setCapability("deviceOrientation", "landscape"); caps.setCapability("platformName", "Android"); caps.setCapability("app", app.getAbsolutePath()); aadr = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), caps); } @Test public void test1() throws Exception { //Wait until application open correctly WebDriverWait wait = new WebDriverWait(aadr, 40); //Locate URL , User Name and Password wait.until(ExpectedConditions.presenceOfElementLocated(By.className("android.widget.EditText"))); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("test.orangehrm.com"))); MobileElement url = (MobileElement) aadr.findElements(By.className("android.widget.EditText")).get(0); MobileElement userName = (MobileElement) aadr.findElements(By.className("android.widget.EditText")).get(1); MobileElement password = (MobileElement) aadr.findElements(By.className("android.widget.EditText")).get(2); System.out.println(url);System.out.println(userName);System.out.println(password);System.out.println(" "); for(int i=0;i<3;i++){ MobileElement test = (MobileElement) aadr.findElements(By.className("android.widget.EditText")).get(i); System.out.println(i+" "+ test.getId()); } System.out.println(" "); Thread.sleep(30000); //Test 1- Press Login button with the Empty URL, User Name & Password url.click(); Thread.sleep(30000); for(int i=0;i<20;i++){aadr.sendKeyEvent(67);} aadr.hideKeyboard(); //Wait till button is available on the screen wait.until(ExpectedConditions.presenceOfElementLocated(By.className("android.widget.Button"))); MobileElement loginBtn = (MobileElement)aadr.findElements(By.className("android.widget.Button")).get(1); //Tap the Login button TouchAction btn = new TouchAction(aadr); btn.tap(loginBtn).perform(); wait.until(ExpectedConditions.presenceOfElementLocated(By.className("android.view.View"))); Thread.sleep(1000); MobileElement warninigMsg = (MobileElement) aadr.findElements(By.className("android.view.View")).get(9); //Assert whether Username empty warning message is coming or not assertEquals("Username is Empty",warninigMsg.getAttribute("name"));
doc_23531493
let sentenceArr = [['Teachers', 'are', 'clever.'], ['Developers', 'are', 'more', 'clever,', 'because', 'of', 'her', 'practice', 'experience.']]; for(let i=0; i<sentenceArr.length;i++){ console.log('loop: ' + i +1); splitPunctuationMarks(sentenceArr[i]); } function splitPunctuationMarks(inSentence_As_Arr){ let punctuationMarks = ['.', '!', '?', ',', ';', ':']; let containsPunctuationMark = (-1); let splitParts = []; let parts = []; for(let i=0; i < inSentence_As_Arr.length; i++){ for(let j=0; j< punctuationMarks.length; j++){ containsPunctuationMark = inSentence_As_Arr[i].indexOf(punctuationMarks[j]); if(containsPunctuationMark >= 0){ console.log('### splitPunctuationMarks ' + inSentence_As_Arr[i]); console.log('parts 1: '); console.log(parts); parts[0] = i; parts[1] = inSentence_As_Arr[i].slice(0, containsPunctuationMark); parts[2] = inSentence_As_Arr[i].slice(containsPunctuationMark); console.log('parts 2: '); console.log(parts); console.log('splitParts1: '); console.log(splitParts); splitParts.push(parts); console.log('splitParts2: '); console.log(splitParts); containsPunctuationMark = (-1); //parts = []; } } } } I wrote a function that works in another way than I expect. I also found a solution, that delivers the result I want. Now I would like to understand, what's wrong with my expectation. That's my code: let sentenceArr = ['Teachers are clever.', 'Developers are more clever, because of her practice experience.']; for(let i=0; i<sentenceArr.length;i++){ console.log('loop: ' + i +1); splitPunctuationMarks(sentenceArr[i]); } function splitPunctuationMarks(inSentence_As_Arr){ let punctuationMarks = ['.', '!', '?', ',', ';', ':']; let containsPunctuationMark = (-1); let splitParts = []; let parts = []; for(let i=0; i < inSentence_As_Arr.length; i++){ for(let j=0; j< punctuationMarks.length; j++){ containsPunctuationMark = inSentence_As_Arr[i].indexOf(punctuationMarks[j]); if(containsPunctuationMark >= 0){ console.log('### splitPunctuationMarks ' + inSentence_As_Arr[i]); console.log('parts 1: '); console.log(parts); parts[0] = i; parts[1] = inSentence_As_Arr[i].slice(0, containsPunctuationMark); parts[2] = inSentence_As_Arr[i].slice(containsPunctuationMark); console.log('parts 2: '); console.log(parts); console.log('splitParts1: '); console.log(splitParts); splitParts.push(parts); console.log('splitParts2: '); console.log(splitParts); containsPunctuationMark = (-1); //parts = []; } } } } What I have expected: 1st loop: '### splitPunctuationMarks clever. parts1: [ ] //because the empty array has not been filled yet. parts2: [2, 'clever', '.'] //because that are the tracked data from the first sentence. splitParts1: [ ] //because the empty array has not been filled yet. splitParts2: [2, 'clever', '.'] //because that are the data from parts 2nd loop: '### splitPunctuationMarks clever, parts1: [ ] //because the empty array has not been filled yet. parts2: [3, 'clever', ','] //because that are the tracked data from the second sentence. splitParts1: [ ] //because the empty array has not been filled yet. splitParts2: [3, 'clever', ','] //because that are the data from parts '### splitPunctuationMarks experience. parts1: [3, 'clever', ','] //because the array has not been overwritten yet. parts2: [8, 'experience', '.'] //because that are the tracked data from the second sentence. splitParts1: I have expected: [3, 'clever', ','] //because of the first pushed content to the array But I get: [8, 'experience', '.'] //that's what I don't understand splitParts2: I have expected: [[3, 'clever', ','], [8, 'experience', '.']] But I get: [[8, 'experience', '.'], [8, 'experience', '.']] Why have I lost the first entry of my 2nd loop? A: It's because you're overriding parts in your loop. You push parts into the splitParts array, but actually a reference to the parts array will be stored there. When you then change the parts array, it will change the content in the splitParts array. If you make the parts variable local to the inner loop, you'll have the wanted result. A: The way Javascript works defines the behaviour why parts gets overwritten. Pass by Value In Javascript, the primitive types(int, boolean, String, null, undefined, Symbol) when passed to a function get passed by value which means a new memory space is created and a copy of them is stored in it. // demonstrating pass by value function passByValuePrimitive(x) { // a new variable space is allocated in memory which holds the value 5 initially x = 6;// here you change the value of x to be 6 which points to the new variable created within this execution context. console.log(x) } var x = 5; console.log(x); // value of x gets passed to the function. passByValuePrimitive(x); console.log(x); // here again in the global execution context, the value of x will be 5 Pass By Reference When we consider objects, they get passed by reference, which means the memory address of the object is passed and any change to the value is persistent throughout the execution context of the program. // demonstrating pass by reference function passByReference(x) { // the reference address of x is known to the function x.name = "Caesar";// here you change the value of x.name to be Caesar which points to the same memory address of the object x created in the global execution context. console.log(x) } var x = { name: "Julius"}; console.log(x); // Here the reference address of the object x in memory is passed to the function passByReference(x); console.log(x); // here in the global execution context, the value of x.name will be "Caesar" Hope it Helps. @SBylemans has given a crisp answer.
doc_23531494
I have successfully opened the dialer during a call with refrence of this LINK but not able to dial the number, and another issue is that code is not working above Android 2.2. is there any other way to make this working in all devices. Code : TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); Class c = Class.forName(tm.getClass().getName()); Method m = c.getDeclaredMethod("getITelephony"); m.setAccessible(true); ITelephony telephonyService; telephonyService = (ITelephony)m.invoke(tm); // Silence the ringer and answer the call! telephonyService.silenceRinger(); telephonyService.answerRingingCall(); telephonyService.showCallScreen(); telephonyService.showCallScreenWithDialpad(true); ERROR LOG: 01-09 17:35:41.065: W/Resources(367): Converting to string: TypedValue{t=0x10/d=0x2 a=-1} 01-09 17:38:23.446: W/System.err(367): java.lang.SecurityException: Neither user 10056 nor current process has android.permission.MODIFY_PHONE_STATE. 01-09 17:38:23.446: W/System.err(367): at android.os.Parcel.readException(Parcel.java:1322) 01-09 17:38:23.446: W/System.err(367): at android.os.Parcel.readException(Parcel.java:1276) 01-09 17:38:23.446: W/System.err(367): at com.android.internal.telephony.ITelephony$Stub$Proxy.silenceRinger(ITelephony.java:549) 01-09 17:38:23.446: W/System.err(367): at com.everysoft.autoanswer.AutoAnswerIntentService.answerPhoneAidl(AutoAnswerIntentService.java:137) 01-09 17:38:23.446: W/System.err(367): at com.everysoft.autoanswer.AutoAnswerIntentService.onHandleIntent(AutoAnswerIntentService.java:94) 01-09 17:38:23.446: W/System.err(367): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:59) 01-09 17:38:23.446: W/System.err(367): at android.os.Handler.dispatchMessage(Handler.java:99) 01-09 17:38:23.446: W/System.err(367): at android.os.Looper.loop(Looper.java:123) 01-09 17:38:23.446: W/System.err(367): at android.os.HandlerThread.run(HandlerThread.java:60) Manifest.xml <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" /> <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> EDIT I am able to auto answer the call in all devices but having problem with opening a dialpad only. A: Remove this line and your code should work: telephonyService.silenceRinger(); That is an invalid call after Android 2.2. A: Have you tried like bellow ? Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse("tel:1231231234")); startActivity(intent); A: MODIFY_PHONE_STATE permission used by system apps only not by third party apps. Instead of using answerRingingCall(), u can use key events Like: Intent buttonDown = new Intent(Intent.ACTION_MEDIA_BUTTON); buttonDown.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK)); context.sendOrderedBroadcast(buttonDown, "android.permission.CALL_PRIVILEGED"); A: Add in manifest permission MODIFY_PHONE_STATE A: I thing you use the hiden library com.android.internal.telephony I add this line in the manifest <uses-permission android:name="android.permission.INSTALL_PACKAGES"/> and I worked in my case I tried it in 4.4.2
doc_23531495
double variable; client.println("<head> <meta http-equiv='refresh' content='1; url=http://localhost/add.php?param="+ variable +" /></head>"); my error blink1:57: error: invalid operands of types 'const char [97]' and 'double' to binary 'operator+' client.println("<head> <meta http-equiv='refresh' content='1; url=http://localhost/add.php?param="+ variable +"' /></head>"); A: With the Arduino String object it's as simple as: client.println("<head><meta http-equiv='refresh' content='1; url=http://localhost/add.php?param="+ String(variable) +" /></head>"); As a side note, try not to calculate using floating-point types on Arduino, the processor lack hardware support for them and they are really slow.
doc_23531496
<dependencies> <!-- common dependencies --> </dependencies> <properties> <!-- ${versionToBuild} is defined by each profile --> <output.name>doc-${versionToBuild}</output.name> <!-- other common properties or based on a property defined by profile --> </properties> <build> <pluginManagement> <plugins> <!-- configuration for plugins based on $versionToBuild --> </plugins> </pluginManagement> </build> <profiles> <profile> <id>doc-for-1.1</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <versionToBuild>1.1-SNAPSHOT</versionToBuild> </properties> <dependencies> <!-- the artefacts of my project in v1.1 --> </dependencies> <build> <plugins> <plugin> <artifactId>maven-javadoc-plugin</artifactId> </plugin> <plugin> <groupId>com.sun.jersey.contribs</groupId> <artifactId>maven-wadl-plugin</artifactId> </plugin> <plugins> </build> </profile> <profile> <id>doc-for-1.2</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <versionToBuild>1.2-SNAPSHOT</versionToBuild> </properties> <dependencies> <!-- the artefacts of my project in v1.2 --> </dependencies> <build> <plugins> <plugin> <artifactId>maven-javadoc-plugin</artifactId> </plugin> <plugin> <groupId>com.sun.jersey.contribs</groupId> <artifactId>maven-wadl-plugin</artifactId> </plugin> <plugins> </build> </profile> </profiles> A: I don't think you can do what you want without going against the grain of how Maven works. It does trickery to merge overlapping plugin configurations such as yours. You could bind each plugin to different phase to its default (ensuring they are different for v1.1 and v1.2), but it's very hacky. Instead, I advise having separate branches on your source control for v1.1 and v1.2, instead of the POM being coupled so tightly to the version history. You would just build the doc for each version by checking out the appropriate branch.
doc_23531497
(At this point, I want to clarify that this is not an app for Play Store. This is an app with a specific purpose for internal usage where battery drain is not much of a problem - Also, if anyone knows another way to check if the user is walking, please let me know either) To achieve this, I created a BroadcastReceiver that listens to android.intent.action.BOOT_COMPLETED and starts a service that registers the SensorEventListener. The service acquires a PARTIAL_WAKE_LOCK and I was hoping that with this lock the SensorEventListener would still receive the onChange() callback, but that is not happening. However, with the FULL_WAKE_LOCK it works - but i do not want to keep the screen on and the user may also press the standby button... In my debug sessions, I never saw the service being destroyed, therefore, the wake lock should never be released. Here's the Service class that acquires the lock and registers the sensor: public class WalkingDetectorService extends Service { private static PowerManager.WakeLock wakeLock = null; private static final String LOCK_TAG = "WALKING_DETECTOR"; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); acquireLock(this); } @Override public int onStartCommand(Intent intent, int flags, int startId) { // started on boot from a BroadcastReceiver startMotionDetector(getApplication()); return START_STICKY; } @Override public void onDestroy() { releaseLock(); super.onDestroy(); } private void startMotionDetector(Application application) { int sensitivityIdx = SettingsManager.getInt(application, SettingsManager.SETTING_SENSOR_SENSITIVITY); if (sensitivityIdx == -1) { sensitivityIdx = MotionSensor.DEFAULT_SENSITITY_IDX; } float fSens = MotionSensor.getSensivity(sensitivityIdx); //SensorEventListener is registered here. It is properly done. Only stops listen when screen goes off (by timeout or user pressing the standby button) MotionSensor.startMotionSensor(application, fSens); } public static synchronized void acquireLock(Context ctx) { if (wakeLock == null) { PowerManager mgr = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE); wakeLock = mgr.newWakeLock(PowerManager.FULL_WAKE_LOCK, LOCK_TAG); wakeLock.setReferenceCounted(true); } wakeLock.acquire(); } public static synchronized void releaseLock() { if (wakeLock != null) { if (wakeLock.isHeld()) { wakeLock.release(); } } } } I think I provided all the information needed to get some help from you. If you feel like there's some piece of code that would be useful, I'll be happy to colaborate! Thank you
doc_23531498
The site seems to be running on an MVC framework (not 100% sure on which one unfortunately) and requests are being sent through a router class. I have a subdirectory which I want to exclude from the routing and have its files be executed directly. Here is my current htaccess file: RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?rt=$1 [L,QSA] I have tried excluding the subdirectory I want to execute directly with the following line but it made no difference: RewriteCond %{REQUEST_URI} !^subdir/(.*) Is there any way I can execute the php files in subdir directly? Any help would be much appreciated, thanks. A: Have you tried with RewriteCond %{REQUEST_URI} !^/subdir/ ? The REQUEST_URI may start with a /. A: RewriteCond %{REQUEST_FILENAME} !-f This line allows you to execute files directly. If you are getting error 500, check your scripts for fatal errors / uncaught exceptions
doc_23531499
I am working on a project with several tables of data in it. imagine the following structure: dictionary$table$variables$type In the last level (i.e., type), the values are FALSE and/or TRUE. I need to show for which variables across all the tables the value of type equals only TRUE or only FALSE or a combination of both. I found this function to suit my purpose: for instance for a table called HARIX, all values equal FALSE. unique(dictionary$HARIX$variables$type) [1] FALSE Now I need to turn it into a loop so that it does the job for all the tables included in the dictionary. I don't know how to write this command. I wrote the one below but it doesn't reach the write level I need (i.e., type). value <- list() for(table_name in project$name){ value[[table_name]] <- unique(dict[[table_name]]$variables$type) print(val[[table_name]]) } I really appreciate your help. If you also have any advice on how to use the lapply function for this purpose, I would love to learn that too. A: Get rid of the for loop and use the map function from the purrr package: Data sample Remember you have to provide a data sample in order to explain your problem better... v1 <- c(F, F, F) v2 <- c(F, T, F) v3 <- c(T, T, T) dictionary <- list( HARIX = list(var1 = list(type = v1), var2 = list(type = v2), var3 = list(type = v3)), OTHER = list(var4 = list(type = v3), var5 = list(type = v1), var6 = list(type = v2))) Solution require(purrr) map(dictionary, ~ map(., ~ map(., unique))) Output $HARIX $HARIX$var1 $HARIX$var1$type [1] FALSE $HARIX$var2 $HARIX$var2$type [1] FALSE TRUE $HARIX$var3 $HARIX$var3$type [1] TRUE $OTHER $OTHER$var4 $OTHER$var4$type [1] TRUE $OTHER$var5 $OTHER$var5$type [1] FALSE $OTHER$var6 $OTHER$var6$type [1] FALSE TRUE Here is the map function documentation lapply bonus You have requested a lapply solution: lapply(dictionary, function(word) lapply(word, function(var) lapply(var, unique))) Explanation You have to go down the list till you reach the right level. So you have to use nested map or nested lapply.