id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23534100
And while this works perfectly in any online IDE I have tried, in Code::Blocks I receive error: expected declaration specifiers or '...' before string constant This is the main file: #include <stdio.h> int main(void) { #include "null.h" } And this is the included null.h: printf("Hello, world\n"); I have tried #include <stdio.h> above printf() function call as well as calling the file null.c however nothing seems to work. I have searched Google but can't wrap my head around what this error has to do with any of the explanations provided. edit: I now use gcc via cmd in order to compile which works for me.
doc_23534101
SELECT f.author, f.thumbnail_url, f.feed_id FROM feed_item f JOIN ( SELECT f2.feed_item_id, f2.like_count AS count FROM feed_item_counts f2 WHERE f2.like_count > 0) t2 ON f.feed_id = t2.feed_item_id ORDER BY t2.count DESC; When I run this query against the database (PGAdmin View Data - View All Rows) I get the desired results author | thumbnail_url | feed_id | user1 | thumb 1 | feed_id 1 | user1 | thumb 2 | feed_id 2 | user1 | thumb 3 | feed_id 3 | user2 | thumb 1 | feed_id 1 | user2 | thumb 2 | feed_id 2 | and so on... However with my REST (Spring Boot) when I attempt to get the results back I get the following { "username" : "user1", "popularPhotos" : [ { "feedId" : feed_id 3, "thumbnailUrl" : "thumb 3" }, { "feedId" : feed_id 3, "thumbnailUrl" : "thumb 3" }, { "feedId" : feed_id 3, "thumbnailUrl" : "thumb 3" } ] } Which is generated via the following; User.Java @Entity @Table(name = "user_details") public class User { @Id @NotNull @NotEmpty @JsonView(UserView.Summary.class) private String username; @JsonView(UserView.Summary.class) @OneToMany(fetch = FetchType.LAZY, mappedBy = "username") public List<UserPopularPhotos> popularPhotos; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public List<UserPopularPhotos> getPopularPhotos(){ return popularPhotos; } public void setPopularPhotos(List<UserPopularPhotos> popularPhotos){ this.popularPhotos = popularPhotos; } UserPopularPhotos @Entity @Table(name = "user_popular_photos") @Immutable public class UserPopularPhotos { @Id @Column(name = "author", insertable = false, updatable = false) @JsonIgnore public String username; @JsonView(UserView.Summary.class) @Column(name = "id", insertable = false, updatable = false) public Integer feedId; @JsonView(UserView.Summary.class) @Column(name = "thumbnail_url", insertable = false, updatable = false) public String thumbnailUrl; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Integer getFeedId(){ return feedId; } public void setFeedId(Integer feedId){ this.feedId = feedId; } public String getThumbnailUrl() { return thumbnailUrl; } public void setThumbnailUrl(String thumbnailUrl) { this.thumbnailUrl = thumbnailUrl; } } What am I missing here, I can't put a finger on why the query in PGAdmin returns correct results but the API query returns the same result (top entry for that user) multiple times? A: The @Id annotation is not on the unique identifier for the user_popular_photos view. Removed it from the username and added to the feedId. UserPopularPhotos.java @Entity @Table(name = "user_popular_photos") @Immutable public class UserPopularPhotos { @Column(name = "author", insertable = false, updatable = false) @JsonIgnore public String username; @Id @JsonView(UserView.Summary.class) @Column(name = "id", insertable = false, updatable = false) public Integer feedId; @JsonView(UserView.Summary.class) @Column(name = "thumbnail_url", insertable = false, updatable = false) public String thumbnailUrl; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Integer getFeedId(){ return feedId; } public void setFeedId(Integer feedId){ this.feedId = feedId; } public String getThumbnailUrl() { return thumbnailUrl; } public void setThumbnailUrl(String thumbnailUrl) { this.thumbnailUrl = thumbnailUrl; } } Making this change gives the desired return result from the API
doc_23534102
AMDeviceInstallApplication failed: -402620395 I think this is related to provisioning profile used while creating build. Do I need to send them UDID of my device and ask them to add it their provisioning profile? Thanks & Regards Changdeo A: Yes, you have to provide dev team with UDID of your device. Dev team will than add your UDID in ADHOC Provisioning profile. AMDeviceInstallApplication failed: -402620395 is mostly provisioning profile issue. A: If their developer account is a standard Apple Developer Program (individual or company), they have to provision your UDID in their Provisioning Portal, regenerate the MobileProvisioning file and sign the app again using this file. If their developer account is an Apple Enterprise Developer Program account, provisioning UDIDs is not necessary, but App Store distribution is not possible. A: I was having this issue and none of the aforementioned solutions helped. The app was building fine on xcode but not when launching via my code. Turned out my DesiredCapabilities were wrong. Reduced them to the basic values only and it all worked correctly: capabilities.setCapability("deviceName", "iPhone"); // Doesnt seem to care about actual name capabilities.setCapability("udid", "88111111111111111111111438"); capabilities.setCapability("bundleId", "/Users/charlies/Library/Developer/Xcode/DerivedData/SafariLauncher-emehinyoruvvntgoasdscogolux/Build/Products/Debug-iphoneos/SafariLauncher.app");
doc_23534103
criteria.addOrder(Order.desc("myField")); How can I write this statement in Hibernate without using hsql? select * from my_table order by (deletion_date - creation_date) asc; A: Hibernate queries through objects generated by mapping to the database, each table in your database will become a class, so when we consult with Hibernate we refer to the object and not directly to the table. Example : FROM Class1 c However, it is also possible implemetanción Querys Native within the same Hibernate, which means a common query in Hibernate. Example : SELECT * FROM table Practically, it depends how you want to work, but in my opinion, if you're using Hibernate, then works with the mappings generated, working with objects.
doc_23534104
Totally at loss here. I have 2 clients (phone and tablet) which connect to a signalR hub where I register them each as a group: public class OrderHub : Hub { public string GetConnectionId() { return Context.ConnectionId; } public async void RegisterDeviceOnGroup() { //for example purposes just using tablet await Groups.AddToGroupAsync(Context.ConnectionId, 'tablet'); } } Then when I communicate between the 2, I call a method on a controller where the hub as been injected: private readonly IHubContext<OrderHub> _hubContext; public CustomerRepository(IHubContext<OrderHub> hubContext) { _hubContext = hubContext; } private async Task<bool> BroadcastOrder() { //Broadcast to tablet await _hubContext.Clients.Group('tablet).SendAsync("Message"); } This works fine for a few minutes and then stops. I can 't see anything in logs or any reason why it would. Can the injected hub context lose groups? A: I guess the problem is in sending parameters , naming ... However, you can use Custom hub filters to view the communication between the client and the server public class CustomFilter : IHubFilter { public async ValueTask<object> InvokeMethodAsync( HubInvocationContext invocationContext, Func<HubInvocationContext, ValueTask<object>> next) { Console.WriteLine($"Calling hub method '{invocationContext.HubMethodName}'"); try { return await next(invocationContext); } catch (Exception ex) { Console.WriteLine($"Exception calling '{invocationContext.HubMethodName}': {ex}"); throw new HubException(ex.Message); throw; } } // Optional method public Task OnConnectedAsync(HubLifetimeContext context, Func<HubLifetimeContext, Task> next) { return next(context); } // Optional method public Task OnDisconnectedAsync( HubLifetimeContext context, Exception exception, Func<HubLifetimeContext, Exception, Task> next) { return next(context, exception); } } and add IServiceCollection hubOptions.AddFilter<CustomFilter>(); you can see enter link description here I hope that help
doc_23534105
The code that needs to be tested uses MongoDB (mongoid), and has a pattern similar to this: objects = Database::MyTable.active.where(object_id: object_id).to_a I want my rspec code to provide the objects hard-coded in the test. How can I do that? A: Because of the "chain" of methods, stubbing is a little awkward, but it can be done. allow(Database::MyTable).to( receive(:active).and_return(double( where: [{ id: 1 }, { id: 2 }] )) ) We have stubbed active to return a mock (a double) on which we stub where. Docs: rspec-mocks PS: There are many other ways to write these stubs, some objectively better, some subjectively better. There are also ways to refactor your code to make stubbing easier. PPS: Welcome to ruby! A: I would separate the code that retrieves the data (including the line you mentioned) into one method and the code that consumes/operates on the data into another method, then mock the entire retrieval method. This way you don't need to muck with the exact queries used.
doc_23534106
I am not talking about the double window menu (on the right) I know that this is due to a bug in the WinForms control and that if you add MdiChild elements in the Load event instead of the Constructor, this behaviour resolves itsef (see this post for details). Here I am talking about the menu strip itself, I don't want it! How do I get rid of it? Any advice is much appreciated... Note: I am adding MdiChild forms in the following way: foreach (Form mdiChild in MdiChildForms) { mdiChild.MdiParent = this; mdiChild.Show(); } where MdiChildForms is a List<Form>. A: Here is the possible solution: public MainForm() { IsMdiContainer = true; InitializeComponent(); this.MainMenuStrip = new MenuStrip(); // create our own menu strip this.MainMenuStrip.Visible = false; }
doc_23534107
but i had clutterred all functions with external functions calls like this: function a() { b = new mynewpage.cfc.functionb(arguments); } function c() { c = new mynewpage.cfc.pages.functionc(arguments); } so i am trying to focus on creating one function called as invokeme function invokeme() { c = new mynewpage.cfc.pages.functionc(arguments); b = new mynewpage.cfc.functionb(arguments); } nut my question is how can use the invokeme function to use in function a and function b should i use invokeme.b.a() A: I think something like this should work. I'm not 100% sure though in your context because I don't know what those other functions are doing. function invokeme(args) { return { b = new mynewpage.cfc.functionb(argumentCollection=arguments.args); } } invokeme(someArguments).b.a; //Assuming b returns a component or object. For example: https://cffiddle.org/app/file?filepath=0def2e60-5ae3-466e-96de-f80bbbd2d78a/302995b7-ed73-48eb-bf97-598d4a825058/9184f40d-05b5-464e-ae49-45450787edf5.cfm Essentially you nee to return the instance out of the function for use so the result of invokeme will be keys which are references to those instances. Then you can call them. I think this slightly complicates your code. I think it's cleaner to assign the instances explicitly instead of hidden in a function.
doc_23534108
function getCharactersComic(character){ var charactersComics; return axios.get('https://gateway.marvel.com:443/v1/public/characters/' + character[0].id + '/comics?limit=10', { params:{ ts: timeStamp, apikey: marvelKey.pubKey, hash: marvelHash } }) .then(response =>{ charactersComics = response.data.data.results; console.log("comics" + charactersComics); return charactersComics; }) .catch(err => { console.log('This is the error from comics: ', err.response); }) router.get("/:id", function(req,res){ axios.get('https://gateway.marvel.com:443/v1/public/characters/' + req.params.id,{ params: { ts: timeStamp, apikey: marvelKey.pubKey, hash: marvelHash } }) .then(response =>{ let character = response.data.data.results; let comics = getCharactersComic(character); console.log('inside call ' + comics); res.render('character', {character: character , comics:comics}); }) .catch(error => console.log('This is the error from id: ', error)); });
doc_23534109
@IBAction func showScores(x : UIButton) { var gameCenterController : GKGameCenterViewController! if (gameCenterController != nil) { gameCenterController.gameCenterDelegate = self self.presentViewController(gameCenterController, animated: true, completion: nil) } } But I get an error on this line: gameCenterController.gameCenterDelegate = self That reads, Type 'MenuViewController' does not conform to protocol `GKGameCenterControllerDelegate` What am I doing wrong? How can I implement GameCenter into my game so that users' high scores are added to the leaderboards where they can be viewed by pressing a button? A: It says you didn't implement the delegate method. // Called when the player is done interacting with the view controller’s content. (required) - (void)gameCenterViewControllerDidFinish:(GKGameCenterViewController *)gameCenterViewController then you class may implement like this: class YourViewController : GKGameCenterControllerDelegate { func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController!) { // do somthing } } A: Make sure to declare that your presenting view controller conforms GKGameCenterControllerDelegate like so: class MenuViewController: GKGameCenterControllerDelegate Then In Swift, add the function below to your MenuViewController: func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController!) { //code to dismiss your gameCenterViewController // for example: gameCenterViewController.dismissViewControllerAnimated(true, completion: nil) } Lastly, be sure that the gameCenterDelegate gets set on your game center view controller before you present it. For example: var gcViewController: GKGameCenterViewController = GKGameCenterViewController() gcViewController.gameCenterDelegate = self Note that the delegate is gameCenterDelegate and not just delegate. Also, here is an example on how to show your leaderboard from MenuViewController. (This code would be in MenuViewController): func showLeaderboard() { var gcViewController: GKGameCenterViewController = GKGameCenterViewController() gcViewController.gameCenterDelegate = self gcViewController.viewState = GKGameCenterViewControllerState.Leaderboards gcViewController.leaderboardIdentifier = "yourleaderboardid" self.presentViewController(gcViewController, animated: true, completion: nil) }
doc_23534110
I found Executors pretty useful and I am using a ThreadPoolExecutor to maintain a number of worker threads. Though, those workers run 3rd party code which needs to run as isolated as possible, avoiding sharing static properties. My question: is there any Java library/framework that provides features similar to Executors, like: * *worker pools *automatically adjusted pool size ..but spawning processes instead of threads? A: I understand that you have 3rd party libraries that you want to run isolated somehow -- so they do not have access to static variables for example. I would run your tasks in another ClassLoader. There are web frameworks that use this mechanism to isolate web requests. Passing data between the classloaders is a bit tricky. I'm not sure how Jetty does it. Maybe using some sort of socket? Here's an interesting article about using System.out to share objects. Certainly a hack. My question is: is there any Java library/framework that provides features similar to Executors... but spawning processes instead of threads? Modern operating systems will utilize modern multi-processor architectures to get the most out of Java threads. Spawning another thread inside of your current process will run on another processor if available and will be much more efficient that running that task in a completely separate process, especially something as heavy as another JVM process. A: There is project in github to create process pool. Have a look. https://github.com/shri30/ProcessPool Here is an example: Sample code: public class UsageExample implements JTask{ public static void main(String args[]) throws Exception{ //Create a pool with name : UsageExample-Process and number of processes : 3 ExecutorService pool = ProcessPool.createProcessPool("UsageExample-Process", 3); ProcessFuture<TaskStatus> pf1 = pool.submit(Task.class, args); ProcessFuture<TaskStatus> pf2 =pool.submit(Task.class, args); ProcessFuture<TaskStatus> pf3 =pool.submit(Task.class, args); ProcessFuture<TaskStatus> pf4 =pool.submit(Task.class, args); ProcessFuture<TaskStatus> pf5 =pool.submit(Task.class, args); //the get method blocks the call to get the result TaskStatus ts= pf1.get(); Status status = ts.getStatus(); if(status == Status.SUCESS){ //code goes here } TaskStatus ts2= pf2.get(); Status status2 = ts.getStatus(); if(status == Status.SUCESS){ //code goes here } TaskStatus ts3= pf3.get(); Status status3 = ts.getStatus(); if(status == Status.SUCESS){ //code goes here } TaskStatus ts4= pf4.get(); Status status4 = ts.getStatus(); if(status == Status.SUCESS){ //code goes here } //terminate the pool - pass true for graceful termination, the second parameter is minutes //wait for task completion pool.terminate(true, 3000); } } class Task implements JTask{ public static void main(String[] args) { System.out.println("Executing the sample task"); } } A: Have you considered something like using the ProcessBuilder to manage your isolated process? String myJar = MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath()); ProcessBuilder pb = new ProcessBuilder("java", "-classpath", myJar, "package.MainClass"); Process p = pb.start(); I don't know if it's a good idea to submit Runnable tasks that manage sub-processes to an Executor, but it may be a solution to isolate your workers.
doc_23534111
JSON looks like this: { "0": "15", "1": "dfgdfg", "2": "fgdfg", "3": "MyApp", "4": "0", "5": "2015-09-16 13:09:48", "6": "0000-00-00 00:00:00", "RequestId": "15", "RequestEmail": "dfgdfg", "RequestName": "fgdfg", "RequestApp": "MyApp", "RequestGranted": "0", "RequestTime": "2015-09-16 13:09:48", "RequestGrantedTime": "0000-00-00 00:00:00" }, { "0": "16", "1": "dfghfg", "2": "sdfsfg", "3": "MyApp", "4": "0", "5": "2015-09-16 13:10:43", "6": "0000-00-00 00:00:00", "RequestId": "16", "RequestEmail": "dfghfg", "RequestName": "sdfsfg", "RequestApp": "MyApp", "RequestGranted": "0", "RequestTime": "2015-09-16 13:10:43", "RequestGrantedTime": "0000-00-00 00:00:00" } I don't need first 0-6 nodes for each field. I've tried several ways to convert data row to json in my PHP file to no avail. these records with "0" : "15" still show up. I'm using phpMyAdmin for MySQL database. Any way I can fix this? Right now its ok because data is less. But thats 100% overload to read for my clients. Php code: function fetchDataForUser($userString){ $selectQuery = "SELECT * FROM `Invitations`"; $result = mysql_query($selectQuery); if($result == FALSE){ echo mysql_error(); } echo "["; if(mysql_num_rows($result)){ $first = true; $data = array(); while ($row = mysql_fetch_array($result)) { $data[] = $row; if($first) { $first = false; } else { echo ','; } echo json_encode($row); //echo $row[0]. $row[1]. $row[2]. $row[3]. "\r"; //echo "{\"".$row[3][0]."\", \"".$row[1]."\", \"".$row[2] ."\"}"; } echo "]"; } else { echo '[]'; } } A: According to the mysql_fetch_array docs, $row will contain both number indices and associative indices by default. Try using $row =mysql_fetch_assoc($result) instead.
doc_23534112
main.xul <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <?xml-stylesheet href="main.css" type="text/css"?> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <box id="num" class="labeledbutton" title="Number of Things:" value="52"/> <button label="Show" oncommand="document.getElementById('num').showTitle(true)"/> <button label="Hide" oncommand="document.getElementById('num').showTitle(false)"/> </window> main.css box.okcancelbuttons { -moz-binding: url('main.xml#labeledbutton'); } main.xml <?xml version="1.0"?> <binding id="labeledbutton"> <content> <xul:label xbl:inherits="value=title"/> <xul:label xbl:inherits="value"/> </content> <implementation> <method name="showTitle"> <parameter name="state"/> <body> if (state) document.getAnonymousNodes(this)[0]. setAttribute("style","visibility: visible"); else document.getAnonymousNodes(this)[0]. setAttribute("style","visibility: collapse"); </body> </method> </implementation> </binding> Why it is not showing the box when I click the button? A: Just try it out XUL(main.xul) <box id="num" class="labeledbutton" title="Number of Things:" value="52"/> <button label="Show" oncommand="document.getElementById('num').showTitle(true)"/> <button label="Hide" oncommand="document.getElementById('num').showTitle(false)"/> CSS(main.css) box.okcancelbuttons { -moz-binding: url('main.xbl#labeledbutton'); } XBL(main.xbl) <?xml version="1.0"?> <bindings xmlns="http://www.mozilla.org/xbl" xmlns:xbl="http://www.mozilla.org/xbl" xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <binding id="labeledbutton"> <content> <xul:label xbl:inherits="value=title"/> <xul:label xbl:inherits="value"/> </content> <implementation> <method name="showTitle"> <parameter name="state"/> <body> if (state) document.getAnonymousNodes(this)[0]. setAttribute("style","visibility: visible"); else document.getAnonymousNodes(this)[0]. setAttribute("style","visibility: collapse"); </body> </method> </implementation> </binding> </bindings> A: There are a few problems : First of all in main.css you define a class okcancelbuttons yet in main.xul you refer to a labeledbutton class. The class can be called the same as the binding. Secondly main.xml is just not valid xml (simplest way to validate is to load it up in firefox and it'll spit out errors). It needs xmlns attributes for each namespaces you use. In this case the "main" namespace, xbl and xul. They should be defined in the missing <bindings> element around the <binding> element. It'll end up like this : main.xml <?xml version="1.0"?> <bindings xmlns="http://www.mozilla.org/xbl" xmlns:xbl="http://www.mozilla.org/xbl" xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <binding id="labeledbutton"> <content> <xul:label xbl:inherits="value=title"/> <xul:label xbl:inherits="value"/> </content> <implementation> <method name="showTitle"> <parameter name="state"/> <body> if (state) document.getAnonymousNodes(this)[0]. setAttribute("style","visibility: visible"); else document.getAnonymousNodes(this)[0]. setAttribute("style","visibility: collapse"); </body> </method> </implementation> </binding> </bindings>
doc_23534113
ProGuard: [] Warning: com.google.android.gms.auth.GoogleAuthUtil: can't find referenced class com.google.android.gms.R ProGuard: [] Warning: com.google.android.gms.auth.GoogleAuthUtil: can't find referenced class com.google.android.gms.R$string ... etc. If set -dontwarn com.google.android.gms.** compiling is OK. But after run I get error many reports like this (from many devices): Caused by: android.view.InflateException: Binary XML file line #32: Error inflating class com.google.android.gms.common.SignInButton On my devices all ok. Before update I have not ProGuard warnings and all work perfectly. How it fix? A: You need to ignore like you are compiling but you also need to keep the class so it can find it during runtime. Add these two lines to your proguard configuration file: -keep class com.google.android.gms.** { *; } -dontwarn com.google.android.gms.** A: I came across a similar issue and eventually discovered that I had updated the Google Play Services module however I hadn't re-added the module to my main module in Android Studio. Adding that back in resolved my issues. A: If you use proguard, you need to keep some GMS (Google Play Services) classes. Hopefully they are annotated with @com.google.android.gms.common.annotation.KeepName. # Proguard config for project using GMS -keepnames @com.google.android.gms.common.annotation.KeepName class com.google.android.gms.**, com.google.ads.** -keepclassmembernames class com.google.android.gms.**, com.google.ads.** { @com.google.android.gms.common.annotation.KeepName *; } # Called by introspection -keep class com.google.android.gms.**, com.google.ads.** extends java.util.ListResourceBundle { protected java.lang.Object[][] getContents(); } # This keeps the class name as well as the creator field, because the # "safe parcelable" can require them during unmarshalling. -keepnames class com.google.android.gms.**, com.google.ads.** implements android.os.Parcelable { public static final ** CREATOR; } # com.google.android.gms.auth.api.signin.SignInApiOptions$Builder # references these classes but no implementation is provided. -dontnote com.facebook.Session -dontnote com.facebook.FacebookSdk -keepnames class com.facebook.Session {} -keepnames class com.facebook.FacebookSdk {} # android.app.Notification.setLatestEventInfo() was removed in # Marsmallow, but is still referenced (safely) -dontwarn com.google.android.gms.common.GooglePlayServicesUtil A: Although adding this to proguard-project.txt file works, it keeps all classes. -keep class com.google.android.gms.** { *; } -dontwarn com.google.android.gms.** I prefer this, which makes apk file size much smaller: -keep public class com.google.android.gms.* { public *; } -dontwarn com.google.android.gms.** Also note up to date Google Play Proguard notification here: http://developer.android.com/google/play-services/setup.html#Proguard -keep class * extends java.util.ListResourceBundle { protected Object[][] getContents(); } -keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable { public static final *** NULL; } -keepnames @com.google.android.gms.common.annotation.KeepName class * -keepclassmembernames class * { @com.google.android.gms.common.annotation.KeepName *; } -keepnames class * implements android.os.Parcelable { public static final ** CREATOR; }
doc_23534114
name = ["pete","ben","bill","bob"] example output (41.12, [1,2,3,0], ["ben","bill","bob","pete"]) code so far: getnames :: (Double, [Int]) -> (Double, [Int] -> [[Char]]) getnames ( nil , []) = error "List is empty" getnames xs = [(doublevalue , listofints, listofstrings)) | x <- xs] How do i use the int list to get a value from the name list and put it in the tuple (i know when i add this to the tulle it isn't a tuple anymore) What method would i use to do this? A: The operator (!!) can be used to index a list. Given a pair, you can use something along the lines of: getnames :: (Double, [Int]) -> [String] -> (Double, [Int], [String]) getnames (dbl, ixes) names = let namesLst = map (names !!) ixes in (dbl, ixes, namesLst) Live demo To get what you want, I've fixed your signature to be able to pass the names and fixed the return value type (which was returning a triple with a function at the end). Also notice that [Char] and String are exactly the same type. So inside the body of the function you have dbl which is your double and is directly forwarded to the final triple. Then you have ixes which are the indexes of the elements you have to take from ixes. At this point we calculate the namesLst by mapping the index function over the indexes to get the names in the correct order. Once we have this list, we just have to put it in the third element of the triple. If you want it to fail on empty index list (even if the names list is empty) then you can add: getnames (_, []) _ = error "..." where _ means "I don't care enough to name this argument". And can be seen as a placeholder for an argument you'll not use.
doc_23534115
But many of them are about getting user profile pictures, those are answered with "/<userid>/picture" or anything similar. I need to know how to get posted images from a page feed, so this is not what I'm looking for. Then there are questions answered with "use full_image in your search query". Well, at this point my problem begins. full_image actually isn't the full image. It's limited to 720x720 pixels. Let's have a look at an example: explore this picture from SPIEGEL ONLINE in Facebook's Graph API explorer. The given path for the Graph API request is: /38246844868_10154299256109869?fields=full_picture,picture,permalink_url,type,object_id The response is the following: { "full_picture": "https://scontent.xx.fbcdn.net/v/t1.0-9/s720x720/13450864_1068539139897737_5236884236245491903_n.jpg?oh=20cc415e7931b8eb8a6228ab253bfa53&oe=57E23B8B", "picture": "https://scontent.xx.fbcdn.net/v/t1.0-0/s130x130/13450864_1068539139897737_5236884236245491903_n.jpg?oh=37c4263e047f841da7243c040a4f279d&oe=57C6469E", "permalink_url": "https://www.facebook.com/spiegelonline/posts/10154299256109869", "type": "photo", "object_id": "1068539139897737", "id": "38246844868_10154299256109869" } As you can see I requested the picture (which is just a thumb) and the full size image indexed by full_picture. Unfortunately this picture is not full, but a resized one instead. It's even mentioned in the image's URL that it's only 720x720 at max. Here it is: https://scontent.xx.fbcdn.net/v/t1.0-9/s720x720/13450864_1068539139897737_5236884236245491903_n.jpg?oh=20cc415e7931b8eb8a6228ab253bfa53&oe=57E23B8B When visiting the Facebook page behind the permalink_url you get to the image post. Here we go: https://www.facebook.com/spiegelonline/posts/10154299256109869 When opening the posted image in fullscreen mode and then right-clicking it to show the image file you will see that the image will be much larger that 720x720. There it is: https://scontent-frt3-1.xx.fbcdn.net/t31.0-8/13422344_1068539139897737_5236884236245491903_o.jpg Please, compare the URL with the one responded by the API endpoint as shown above. Even the servers are different. So, there isn't an easy solution by replacing "_n" with "_o" as mention in several other questions here on SO. My question is: How do I get the full size image URL using Graph API? TL;DR: Facebook's Graph API seems to deliver resized images posted to a page's feed by accessing them with full_image. So, how to retrieve the actual full (meaning non-resized) image. A: I finally found a solution after playing around again with the Graph API Explorer. And it's much simpler than I thought. All you need to do is the following few steps: * *Just request this path (this time without the full_picture accessor, only the object_id is important here): /38246844868_10154299256109869?fields=object_id *Grab the object_id from the API's response: { "object_id": "1068539139897737", "id": "38246844868_10154299256109869" } In this example it's "1068539139897737". *Now, request all images for the above object_id: /1068539139897737?fields=images *The response is a JSON like this: { "images": [ { "height": 2048, "source": "https://scontent.xx.fbcdn.net/v/t31.0-8/13422344_1068539139897737_5236884236245491903_o.jpg?oh=e923e167d258e77c12caf422d98b44aa&oe=59968118", "width": 1536 }, { "height": 1280, "source": "https://scontent.xx.fbcdn.net/v/t31.0-8/p960x960/13422344_1068539139897737_5236884236245491903_o.jpg?oh=7a5086e29957b222c2fd1136f3640c98&oe=598633CD", "width": 960 }, // … many others in between here … { "height": 225, "source": "https://scontent.xx.fbcdn.net/v/t1.0-0/p75x225/13450864_1068539139897737_5236884236245491903_n.jpg?oh=26d94247c4e34a69fb0db3fb1ae213b5&oe=599353F9", "width": 168 } ], "id": "1068539139897737" } *From the images list which is down-sorted by size just grab the very first entry. Get its source – et voilà – this is the full picture.
doc_23534116
Sample: http://laktak.github.io/js-graphy/ I already specified charset="utf-8" as suggested by this answer. A: This is caused by textarea { white-space: nowrap; } css rule in graphy.css. Disabling that fixes the issue.
doc_23534117
But what I want is to place a link or button on the Woocommerce Checkout page saying "Return to Cart" (obviously linking to the cart page) but I want it placed just after the "Your Order" section, (the section where you review your order). I want it there because I want it along with a text saying something like "If you want to change your order return to Cart". If I edit the actual checkout page and add the link there, it shows all the way to the bottom so maybe I have to add code to the theme's functions file? Any guidance will be greatly appreciated. Thank you. EDIT: Ok, I've found a very crappy way of doing it. I just added this line to the review-order.php file located in woocommerce/templates/checkout/ , right after the shop_table class: <?php echo "<strong>If you'd like to change your order, go back to <a href='http://www.mysite.com/cart/'>My Cart</a></strong><br />"; ?> This does the trick, but everytime I update woocommerce I will have to added it again. Any suggestion of a more practical and intelligent way of doing it? A: Create a child theme. Put this in the child theme's functions.php /** * Add link back to cart after order review on Checkout */ add_action( 'woocommerce_review_order_before_payment', 'my_back_to_cart_link' ); function my_back_to_cart_link(){ //get the cart link global $woocommerce; $cartUrl = $woocommerce->cart->get_cart_url(); //the HTML markup to add $backToCartLink="<p class='backtocart'><a class='button alt' href='".$cartUrl."'>".__('Edit Cart','wooint')."</a></p>"; echo $backToCartLink; } A: Well, if you created a child theme you could have put that line in your child's functions.php and then the only way an update would affect it is if they changed the coding.
doc_23534118
from pyspark.context import SparkContext sc = SparkContext.getOrCreate() conf = sc.getConf() print(conf.toDebugString()) The Job is created with a Redshift connection enabled. When executing the Job I get: No module named pyspark.context The public documentations all seem to mention, point, and imply the availability of pyspark, but why is my environment complaining that it doesn't have pyspark? What steps am I missing? Best Regards, Lim A: Python Shell jobs only support Python and libraries like pandas, Scikit-learn, etc. They don't have support for PySpark, so you should create one with job type = Spark and ETL language = Python in order to make it work. A: I use: from pyspark.context import SparkContext from awsglue.context import GlueContext sc = SparkContext() glueContext = GlueContext(sc) spark = glueContext.spark_session
doc_23534119
CODE public class ScannedDocument : Csla.BusinessBase<ScannedDocument> { private string _documentId = string.Empty; private BarcodeList _barcodeList = null; public string DocumentId { get { return _documentId; } } public BarcodeList Barcodes { get { return _barcodeList; } set { if (_barcodeList.Equals(value)) { _barcodeList = value; PropertyHasChanged("Barcodes"); } } } } public class BarcodeList : Csla.BusinessListBase<BarcodeList, Barcode> { public static BarcodeList NewBarcodeList() { return new BarcodeList(); } private BarcodeList() {} } public class Barcode : Csla.BusinessBase<Barcode> { public string Value { get { return GetBarcodeValue(); } } public static Barcode NewBarcode() { return new Barcode(); } private Barcode() {} } XAML <dg:DataGrid GridLinesVisibility="None" AutoGenerateColumns="False" Name="ScannedDocumentsListView"> <dg:DataGrid.Columns> <dg:DataGridTextColumn Header="Document Name" IsReadOnly="True" Binding="{Binding Path=DocumentId}"/> <dg:DataGridTextColumn Header="Index 1" Width="80" IsReadOnly="True" Binding="{Binding Path=Barcodes[0].Value}" /> <dg:DataGridTextColumn Header="Index 2" Width="80" IsReadOnly="True" Binding="{Binding Path=Barcodes[1].Value}" /> <dg:DataGridTextColumn Header="Index 3" Width="80" IsReadOnly="True" Binding="{Binding Path=Barcodes[2].Value}" /> <dg:DataGridTextColumn Header="Index 4" Width="80" IsReadOnly="True" Binding="{Binding Path=Barcodes[3].Value}" /> <dg:DataGridTextColumn Header="Index 5" Width="80" IsReadOnly="True" Binding="{Binding Path=Barcodes[4].Value}" /> <dg:DataGridTextColumn Header="Index 6" Width="80" IsReadOnly="True" Binding="{Binding Path=Barcodes[5].Value}" /> </dg:DataGrid.Columns> PROBLEM When I execute this code, I am able to bind the DocumentId successfully to the grid, but the barcode list doesn't seem to be binding correctly. I have verified that there is data in the list. What am I doing wrong? A: The usual pattern to use in these cases is to implement INotifyPropertyChanged for your BarCode objects and expose them to the DataGridControl with a ObservableCollection. The DataGrid would then show one Barcode object per row with each column displaying the public properties of the BarCode. Changes in either the Barcode or the the collection would then be propagated to the DataGrid and vice-versa (depending on the DataGrid properties).
doc_23534120
$('nav .dropdown').hover( function(e) { e.stopPropagation(); $('.dropdown-menu', this).stop( true, true ).fadeIn("fast"); $(this).toggleClass('open'); $('b', this).toggleClass("caret caret-up"); }, function(e) { e.stopPropagation(); $('.dropdown-menu', this).stop( true, true ).fadeOut("fast"); $(this).toggleClass('open'); $('b', this).toggleClass("caret caret-up"); }); $('#dropdown04').on('show.bs.dropdown', function (e) { console.log('show'); }); $('.dropdown a').on('click', function (event) { e.stopPropagation(); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <nav class="navbar navbar-expand-lg navbar-dark ftco_navbar bg-dark ftco-navbar-light" id="ftco-navbar"> <div class="container"> <a class="navbar-brand" href="index.html">Vegefoods</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#ftco-nav" aria-controls="ftco-nav" aria-expanded="false" aria-label="Toggle navigation"> <span class="oi oi-menu"></span> Menu </button> <div class="collapse navbar-collapse" id="ftco-nav"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"><a href="index.html" class="nav-link">Home</a></li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="dropdown04" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Shop</a> <div class="dropdown-menu" aria-labelledby="dropdown04"> <a class="dropdown-item" href="shop.html">Shop</a> <a class="dropdown-item" href="cart.html">Cart</a> <a class="dropdown-item" href="checkout.html">Checkout</a> </div> </li> <li class="nav-item"><a href="about.html" class="nav-link">About</a></li> <li class="nav-item"><a href="contact.html" class="nav-link">Contact</a></li> <li class="nav-item cta cta-colored"><a href="cart.html" class="nav-link"><span class="icon-shopping_cart"></span>[0]</a></li> </ul> </div> </div> </nav> <!-- END nav --> Thanks for your help. A: Remove the attribute data-toggle="dropdown" and then, first handle the click to open/close the dropdown like this; $('a.dropdown').on('click', function () { $(this).parent().toggleClass('open'); }); and then wait for the clicks outside of the dropdown to close it with this; $('a.dropdown').on('click', function () { $(this).parent().toggleClass('open'); });
doc_23534121
def read_raw_spec(infile): ## to be filled later rw_spec = [] ## loop over all files for file in infile: ## Extract metadata with open(file, "r") as f: lines = f.readlines()[0:38] element = str(lines[11][(lines[11].find(":")+2):(len(lines[11])-1)]) edge = str(lines[10][(lines[10].find(":")+2):(len(lines[10])-1)]) E_zero_load = float(lines[12][(lines[12].find(":")+2):(len(lines[12])-1)]) filename = str([os.path.basename(file)]) rw_specdat = pd.read_csv(file,delim_whitespace = True, skiprows = 39, engine = "python") rw_specdat = rw_specdat.loc[:,'#':'e'] rw_specdat = (rw_specdat.rename(index=str, columns={"#":"Energy", "e":"raw_abs"}), E_zero_load) rw_spectemp = [{'name':filename, 'element' : element, 'edge' : edge, 'data' : list(rw_specdat)}] if rw_spec is None: rw_spec = rw_spectemp else: rw_spec = rw_spec.append(rw_spectemp) return rw_spec Nevertheless, when I run the Code it only takes the last item and adds it to the list. When I would expect a several nested lists, from each file. This Approach works with Pandas but guess lists appending while Looping is different? A: In python, list.append() is an operation and thus returns None. if rw_spec is None: rw_spec = rw_spectemp else: rw_spec = rw_spec.append(rw_spectemp) # This makes rw_spec None Presumably you have even number of files, which leads second last iteration to make rw_spec None, then at the last iteration, rw_spec gets assigned rw_spectemp of the last file, returned it. As opposed to list, pandas.DataFrame.append returns appended DataFrame, not None. Thus reassigning works. Simply changing the above chunk as below will fix the problem: if rw_spec is None: rw_spec = rw_spectemp else: rw_spec.append(rw_spectemp) # This makes rw_spec None
doc_23534122
object @item attributes :id, :name code :is_liked do |this_item| if current_user this_item.is_liked current_user else false end end and in my model: class Item < ActiveRecord::Base ... def is_liked user if user if user.liked_item_ids.include?(self.id) return true else return false end end end .... end but it isn't working. I'm not sure what a proper way of outputting this would be. Any idea how to get this to work correctly? edit 1 Here's the error that I'm getting: Failure/Error: Unable to find matching line from backtrace ActionView::Template::Error: stack level too deep A: Your rabl seems to be fine, however, when your find yourself adding some logic in your views (rabl can be compared to a view) you might want to consider refactor the logic in a presenter. More information about presenters with rabl here Regarding your error, like @apneadiving just said, there is a recursion issue in your codebase somewhere. Just by curiosity, have you try to rename the code block into something else than your method's name ? Depending on which version on rabl you are using, this could be the issue. Finaly, you should consider refactoring your is_liked method: def is_liked user return user.liked_item_ids.include?(id) if user false end A: Try: node(:is_liked) {|this_item| this_item.is_liked(current_user) } You already have the method, you can simply invoke here within a node instead of recreating logic.
doc_23534123
export interface Criteria { fieldValue: any; fieldName: string; childItems?: Criteria[]; } // function to build my array of objects: setCriteria() { // parent object 1 // to be reused / reassigned to array below const criteriaLevel1: Criteria = { fieldName: 'Criteria name', fieldValue: 'Crit-Level-1', childItems: [] }; // parent object 2 - child of object 1 // to be reused / reassigned to array below // into - childItems[0] const criteriaLevel2: Criteria = { fieldName: 'Criteria name', fieldValue: 'Crit-Level-2', childItems: [] }; // list of 3 different items to be assigned to array // into - childItems[0].childItems[0] of each array record. const itemsABC: string[] = [ 'item AAA', 'item BBB', 'item CCC' ]; const criteriaArray = []; let ix = 0; itemsABC.forEach(item => { console.log('item: ' + item); criteriaArray[ix] = []; criteriaArray[ix][0] = criteriaLevel1; criteriaArray[ix][0].childItems[0] = criteriaLevel2; criteriaArray[ix][0].childItems[0].childItems[0] = { fieldName: 'name', fieldValue: item + '-' + ix }; ix++; }); // output test for (let i = 0; i < 3; i++) { console.log('ix: ' + i); for (const itemA of criteriaArray[i]) { console.log('a: ' + itemA.fieldName + ' - ' + itemA.fieldValue); for (const itemB of itemA.childItems) { console.log('b: ' + itemB.fieldName + ' - ' + itemB.fieldValue); for (const itemC of itemB.childItems) { console.log('c: ' + itemC.fieldName + ' - ' + itemC.fieldValue); } } } } } I get this output: index: 0 - inserting item: item AAA index: 1 - inserting item: item BBB index: 2 - inserting item: item CCC ix: 0 a: Criteria name - Crit-Level-1 b: Criteria name - Crit-Level-2 c: name - item CCC-2 // BUT I am expecting here: item AAA-0 ix: 1 a: Criteria name - Crit-Level-1 b: Criteria name - Crit-Level-2 c: name - item CCC-2 // BUT I am expecting here: item BBB-1 ix: 2 a: Criteria name - Crit-Level-1 b: Criteria name - Crit-Level-2 c: name - item CCC-2 // YES as expected here: item CCC-2 What am I doing wrong ? A: You're assigning references to the objects, so all three elements of criteriaArray are pointing to the same instances of criteriaLevel1 and criteriaLevel2. You have a few options to maintain the same pattern: Spread syntax (but note the compatibility matrix) criteriaArray[ix][0] = {...criteriaLevel1, childItems: []}; criteriaArray[ix][0].childItems[0] = {...criteriaLevel2, childItems: []}; const criteriaLevel1 = { fieldName: 'Criteria name', fieldValue: 'Crit-Level-1', childItems: [] }; const criteriaLevel2 = { fieldName: 'Criteria name', fieldValue: 'Crit-Level-2', childItems: [] }; const itemsABC = [ 'item AAA', 'item BBB', 'item CCC' ]; const criteriaArray = []; let ix = 0; itemsABC.forEach(item => { console.log('item: ' + item); criteriaArray[ix] = []; criteriaArray[ix][0] = {...criteriaLevel1, childItems: []}; criteriaArray[ix][0].childItems[0] = {...criteriaLevel2, childItems: []}; criteriaArray[ix][0].childItems[0].childItems[0] = { fieldName: 'name', fieldValue: item + '-' + ix }; ix++; }); for (let i = 0; i < 3; i++) { console.log('ix: ' + i); for (const itemA of criteriaArray[i]) { console.log('a: ' + itemA.fieldName + ' - ' + itemA.fieldValue); for (const itemB of itemA.childItems) { console.log('b: ' + itemB.fieldName + ' - ' + itemB.fieldValue); for (const itemC of itemB.childItems) { console.log('c: ' + itemC.fieldName + ' - ' + itemC.fieldValue); } } } } Object.assign() criteriaArray[ix][0] = Object.assign({}, criteriaLevel1, {childItems: []}); criteriaArray[ix][0].childItems[0] = Object.assign({}, criteriaLevel2, {childItems: []}); const criteriaLevel1 = { fieldName: 'Criteria name', fieldValue: 'Crit-Level-1', childItems: [] }; const criteriaLevel2 = { fieldName: 'Criteria name', fieldValue: 'Crit-Level-2', childItems: [] }; const itemsABC = [ 'item AAA', 'item BBB', 'item CCC' ]; const criteriaArray = []; let ix = 0; itemsABC.forEach(item => { console.log('item: ' + item); criteriaArray[ix] = []; criteriaArray[ix][0] = Object.assign({}, criteriaLevel1, {childItems: []}); criteriaArray[ix][0].childItems[0] = Object.assign({}, criteriaLevel2, {childItems: []}); criteriaArray[ix][0].childItems[0].childItems[0] = { fieldName: 'name', fieldValue: item + '-' + ix }; ix++; }); for (let i = 0; i < 3; i++) { console.log('ix: ' + i); for (const itemA of criteriaArray[i]) { console.log('a: ' + itemA.fieldName + ' - ' + itemA.fieldValue); for (const itemB of itemA.childItems) { console.log('b: ' + itemB.fieldName + ' - ' + itemB.fieldValue); for (const itemC of itemB.childItems) { console.log('c: ' + itemC.fieldName + ' - ' + itemC.fieldValue); } } } } Note that both methods perform a shallow copy, so you have to manually account for nested object references. An alternative approach is creating a helper function to instantiate a new object. function generateCriteria(fieldName, fieldValue) { return () => ({ fieldName: fieldName, fieldValue: fieldValue, childItems: [] }); } const criteriaLevel1 = generateCriteria('Criteria name', 'Crit-Level-1'); const criteriaLevel2 = generateCriteria('Criteria name', 'Crit-Level-2'); const itemsABC = [ 'item AAA', 'item BBB', 'item CCC' ]; const criteriaArray = []; let ix = 0; itemsABC.forEach(item => { console.log('item: ' + item); criteriaArray[ix] = []; criteriaArray[ix][0] = criteriaLevel1(); criteriaArray[ix][0].childItems[0] = criteriaLevel2(); criteriaArray[ix][0].childItems[0].childItems[0] = { fieldName: 'name', fieldValue: item + '-' + ix }; ix++; }); for (let i = 0; i < 3; i++) { console.log('ix: ' + i); for (const itemA of criteriaArray[i]) { console.log('a: ' + itemA.fieldName + ' - ' + itemA.fieldValue); for (const itemB of itemA.childItems) { console.log('b: ' + itemB.fieldName + ' - ' + itemB.fieldValue); for (const itemC of itemB.childItems) { console.log('c: ' + itemC.fieldName + ' - ' + itemC.fieldValue); } } } } A: Object by value and Object by reference is a tricky thing. When you assign criterialLevel1 in 1st iteration , in the next iteration you are actually updating the reference of criteriaLeve1 variable all the time. criteriaArray[ix] = []; criteriaArray[ix][0] = {...criteriaLevel1, childItems: []}; // creating a new object and spreading it, Note the child Items created new else as it is an array would have been passed by reference as well. criteriaArray[ix][0].childItems[0] = {...criteriaLevel2, childItems: []}; criteriaArray[ix][0].childItems[0].childItems[0] = { fieldName: 'name', fieldValue: item + '-' + ix }; I would recommend that rather defining those variable why not assign them directly and you can do it in a single line: criteriaArray[ix] = [{ fieldName: 'Criteria name', fieldValue: 'Crit-Level-1', childItems: [{ fieldName: 'Criteria name', fieldValue: 'Crit-Level-2', childItems: [{ fieldName: 'name', fieldValue: item + '-' + ix }] }] }];
doc_23534124
Here is JSFiddle <section id="items"> <div class="item">Monitor <span class="price">100$</span></div> <div class="item">Mouse <span class="price">20$</span></div> <div class="item">Keyboard <span class="price">60$</span></div> </section> <section id="basket"> <p>Total price:<span class="total_price"></span></p> </section>` A: var total = 0; $("#items").on('click', ".item", function() { $(this).appendTo("#basket"); total += parseInt($(this).children().text(), 10); $('.total_price').text(total); }); $("#basket").on('click', ".item", function() { $(this).appendTo("#items"); total -= parseInt($(this).children().text(), 10); $('.total_price').text(total); }); JSFiddle A: This code will work dynamically. Even if you add or remove items, it should work. var priceList = $('#items').find('.price'); var totalPrice = 0; $.each(priceList, function(i, price){ totalPrice += parseInt($(price).text()) }); $('.total_price').text(totalPrice); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <section id="items"> <div class="item">Monitor <span class="price">100$</span></div> <div class="item">Mouse <span class="price">20$</span></div> <div class="item">Keyboard <span class="price">60$</span></div> </section> <section id="basket"> <p>Total price:<span class="total_price"></span></p> </section> A: check demo var total = 0; $("#items").on('click', ".item", function() { $(this).appendTo("#basket"); getTotal() }); $("#basket").on('click', ".item", function() { $(this).appendTo("#items"); getTotal() }); function getTotal(){ total = 0; $("#basket").find('.price').each(function(i){ total += parseInt($(this).text().slice(0,-1)); if(i + 1 === $("#basket").find('.item').length){ $('.total_price').text(total+'$'); } }); } A: I have moved '$' outside of the .total_price span $("#items, #basket").on('click', ".item", function(){ $($(this).parent().is('#items')?'#basket':'#items').append(this); $(".total_price").text(getTotal()); }); function getTotal(){ var t = 0; $('.price', "#basket").each(function(){ t+=parseInt($(this).text()); }); return t; } JSFiddle
doc_23534125
Can anyone tell me if it is possible to optimise the CSS classes and minimise the amount of code. I cannot utilize the already used id's, and class='imga p0' doesn't work (where p0 just holds the background-position, becoming p1, p2, p3 .. for each image position). Thanks in advance for any advice. a.imga0 {background:url(../images/sprite.png) no-repeat;background-color:transparent; display:block;width:24px;height:24px;background-position:-288px 0;} /* tick green */ a.imga1 {background:url(../images/sprite.png) no-repeat;background-color:transparent; display:block;width:24px;height:24px;background-position:-312px 0;} /* cross grey */ a.imga2 { ..... and so on. A: Edit: So this should eliminate the repetition /* template */ a.imag0, a.imag1, a.imag2 { display: block; width: 24px; height: 24px; background:url(../images/sprite.png) no-repeat;background-color:transparent; } /* specifications */ a.imag0 { background-position:-288px 0; } a.imag1 { background-position:-312px 0; } For one you could create a general selector a { background:url(../images/sprite.png) no-repeat;background-color:transparent; display: block; } Which would apply the general style, such as the sprite image. You could also create a separate class (specify more classes with spaces) So for example, you could have <a class="imag0 spriteclass">something</a> <a class="imag1 spriteclass">something</a> <a class="imag2 spriteclass">something</a> And a.spriteclass { //again the template, such as the sprite and display type and width } Your second option is to list out the selectors you want the css to apply to, a.imag0, a.imag1, a.imag2... { // your general css } And then like above specify the specific sprite positions and details separately A: Adding this just in case some one refers to this post later. You can generate the most optimized CSS using this below tool. http://www.spritecss.com/
doc_23534126
tl;dr I cannot put an image on a semi-transparent window; it gives "Bad Match". I can successfully create a semi-transparent window using XCreateWindow and XMatchVisualInfo : XSetWindowAttributes attr; attr.colormap = XCreateColormap(display, DefaultRootWindow(display), vinfo.visual, AllocNone); attr.border_pixel = 0; attr.background_pixel = 0x80800000; // Red, semi-transparent Window window = XCreateWindow(display, DefaultRootWindow(display), 0, 0, width, height, 0, vinfo.depth, InputOutput, vinfo.visual, CWColormap | CWBorderPixel | CWBackPixel, &attr); (Full source code below) I then create an image using : // "image32" is a generated image - see source code below XImage *ximage = XCreateImage(display, visual, DefaultDepth(display,DefaultScreen(display)), ZPixmap, 0, image32, width, height, 32, 0); And display the image during the Expose event : XPutImage(display, window, DefaultGC(display, 0), ximage, 0, 0, 0, 0, width, height); I compile with gcc test.c -L/usr/X11R6/lib -lX11 -lXrandr -o test and run with ./test : X Error of failed request: BadMatch (invalid parameter attributes) Major opcode of failed request: 72 (X_PutImage) Serial number of failed request: 11 Current serial number in output stream: 12 Note : If I replace the lines creating the window (XCreateWindow) with these : Window window = XCreateSimpleWindow(display, RootWindow(display, 0), 0, 0, width, height, 1, 0, 0); It displays a window correctly; however, there is no transparency. I read the docs about XCreateWindow, XPutImage, XCreateImage and tried playing around with multiple parameters, unsuccessfully. I have read this SO question and tried playing around with color depth; since the docs mentionned "Bad Match" can be also thrown for incorrect visual, I have checked that the same visual was sent at all places in my code. Any help is appreciated. Thanks! Full source code : #include <stdio.h> #include <stdlib.h> #include <string.h> #include <X11/Xlib.h> #include <X11/Xutil.h> // Window size int height = 256, width = 256; XImage *CreateTrueColorImage(Display *display, Visual *visual) { int i, j; unsigned char *image32=(unsigned char *)malloc(width*height*4); unsigned char *p=image32; for(i=0; i<width; i++) { for(j=0; j<height;j++) { *p++ = i; *p++ = i; *p++ = j; *p++ = j; // alpha channel (should progressively get transparent towards left) } } // Replacing "DefaultDepth(display,DefaultScreen(display))" with a hardcoded // 24 or 32 still doesn't work with XCreateWindow. XCreateSimpleWindow works // with hardcoded 24, but not 32. return XCreateImage(display, visual, DefaultDepth(display,DefaultScreen(display)), ZPixmap, 0, image32, width, height, 32, 0); } int main(int argc, char **argv) { XImage *ximage; Display *display = XOpenDisplay(NULL); Visual *visual = DefaultVisual(display, 0); XVisualInfo vinfo; XMatchVisualInfo(display, DefaultScreen(display), 32, TrueColor, &vinfo); XSetWindowAttributes attr; attr.colormap = XCreateColormap(display, DefaultRootWindow(display), vinfo.visual, AllocNone); attr.border_pixel = 0; attr.background_pixel = 0x80800000; // Red, semi-transparent //Window window = XCreateSimpleWindow(display, RootWindow(display, 0), 0, 0, // width, height, 1, 0, 0); Window window = XCreateWindow(display, DefaultRootWindow(display), 0, 0, width, height, 0, vinfo.depth, InputOutput, vinfo.visual, CWColormap | CWBorderPixel | CWBackPixel, &attr); ximage = CreateTrueColorImage(display, vinfo.visual); XSelectInput(display, window, ButtonPressMask|ExposureMask); XMapWindow(display, window); while(1) { XEvent event; XNextEvent(display, &event); switch(event.type) { case Expose: XPutImage(display, window, DefaultGC(display, 0), ximage, 0, 0, 0, 0, width, height); break; case ButtonPress: exit(0); } } } A: I managed to make it work by making two changes. First, instead of using DefaultGC(display, 0) you should create a GC for your specific window. GC gc = XCreateGC(display, window, 0, 0); With that if you hardcode the depth of XCreateImage to 32 it should work correctly. And you can also use the depth provided by XVisualInfo like so XCreateImage(display, vinfo.visual, vinfo.depth, ZPixmap, 0, image32, width, height, 32, 0);
doc_23534127
I try to launch a logspout container and set the log format (an ENV variable) via a docker-compose file. Not too difficult, and if I launch it with docker-compose up, everything works fine. But when I try to launch it with docker swarm init and docker stack deploy -c docker-compose.yml mystack, I get an error: Error response from daemon: rpc error: code = InvalidArgument desc = expanding env failed: expanding env "RAW_FORMAT={ \"container\" : \"{{ .Container.Name }}\", \"labels\": {{ toJSON .Container.Config.Labels }}, \"timestamp\": \"{{ .Time.Format \"2006-01-02T15:04:05Z07:00\" }}\", \"source\" : \"{{ .Source }}\", \"message\": {{ toJSON .Data }} }": template: expansion:1: function "toJSON" not defined What I understand I think I have the error only with swarm and not docker-compose, because the ENV variable I want to pass to logspout is: RAW_FORMAT: '{ "container" : "{{ .Container.Name }}", "labels": {{ toJSON .Container.Config.Labels }}, "timestamp": "{{ .Time.Format "2006-01-02T15:04:05Z07:00" }}", "source" : "{{ .Source }}", "message": {{ toJSON .Data }} }' This ENV variable contains a go template. But with swarm mode, you can create services using go-templates. So it seems that swarm tries (and fails) to parse the value of the ENV variable that I just want to pass to the logspout container. My question * *Is it a way to tell swarm not to parse the go-template in my RAW_FORMAT variable? *If not, is there an other way to set this variable to the correct value? More... If you want to reproduce this problem, here is a minimal docker-compose file: version: "3.3" services: logspout: image: gliderlabs/logspout:latest volumes: - /etc/hostname:/etc/host_hostname:ro - /var/run/docker.sock:/var/run/docker.sock environment: RAW_FORMAT: '{ "container" : "{{ .Container.Name }}", "labels": {{ toJSON .Container.Config.Labels }}, "timestamp": "{{ .Time.Format "2006-01-02T15:04:05Z07:00" }}", "source" : "{{ .Source }}", "message": {{ toJSON .Data }} }' If you are on windows, you have to execute $Env:COMPOSE_CONVERT_WINDOWS_PATHS=1 first. A: In go templates, escaping {{ can be done with {{"{{"}}, so your yml file should look like this: version: "3.3" services: logspout: image: gliderlabs/logspout:latest volumes: - /etc/hostname:/etc/host_hostname:ro - /var/run/docker.sock:/var/run/docker.sock environment: RAW_FORMAT: '{ "container" : "{{"{{"}} .Container.Name }}", "labels": {{"{{"}} toJSON .Container.Config.Labels }}, "timestamp": "{{"{{"}} .Time.Format "2006-01-02T15:04:05Z07:00" }}", "source" : "{{"{{"}} .Source }}", "message": {{"{{"}} toJSON .Data }} }' A: You can warp by {{` string `}} environment: RAW_FORMAT: '{{`{ "container" : "{{ .Container.Name }}`}}", "labels": {{ toJSON .Container.Config.Labels }}, "timestamp": "{{ .Time.Format "2006-01-02T15:04:05Z07:00" }}", "source" : "{{ .Source }}", "message": {{ toJSON .Data }} }`}}' Another example LDAP_SEARCH_FILTER={{`(sAMAccountName={{username}})`}}
doc_23534128
PLEASE Don't mind the markup :) its just to visually display the structure <page> <post id="25"></post> <post id="26"></post> and etc... </page> So i am looking for a way where I can grab that particular ID and store it in a li item. At the moment I can get all post ID's' but not related to that page. I don't want a hardcoded solution. This sidebar must be flexible as all pages will have the same sidebar but li items will be related only to their page. is there any WP way around it?
doc_23534129
A: You can iterate through each byte of each color with getImageData, so you could apply some math functions to it to e.g. represent 8-bit colors: http://jsfiddle.net/pimvdb/eGjak/191/. var imgdata = ctx.getImageData(0, 0, 400, 400); // get data var data = imgdata.data; // bytes // 8-bit: rrr ggg bb for(var i = 0; i < data.length; i += 4) { data[i] = nearest(data[i], 8); // set value to nearest of 8 possibilities data[i + 1] = nearest(data[i + 1], 8); data[i + 2] = nearest(data[i + 2], 4); } ctx.putImageData(imgdata, 0, 0); // put image data to canvas function nearest(x, a) { // will round down to nearest of a possibilities // in the range 0 <= x <= 255 return Math.floor(x / (255 / a)) * (255 / a); } A: I don't think there is built in setting for this. But you should be able to reduce each pixel channel value to a more limited set of values. Something like: var ctx, width, height; var factor = 8; var pixels = ctx.getImageData(0, 0, width, height).data; function reduce(val) { return Math.round(val/factor)*factor; } for(var i = 0, l = pixels.length; i < l; i+=4) { pixels[i] = reduce(pixels[i]); pixels[i+1] = reduce(pixels[i+1]); pixels[i+2] = reduce(pixels[i+2]); } ctx.putImageData(pixels, 0, 0) A: Yes it can be done, and isn't too difficult. See my answer here: How can I use a gradient map to tone a HTML5 canvas with an image in the canvas. Just like in tinting, simply all you must do is go over each pixel and change the RGB values to be lesser (steps of 8 or 16 instead of steps of 1) So for 8 steps you could do: redValue = redValue - (redValue % 32) // 155 would become 128, etc Which ought to work, but you should check the edge cases. Example: http://jsfiddle.net/gbBz7/
doc_23534130
I have a c++ application(main) that is located on the server in /var/www/cpp. In my php part im trying to see if the c++ application is running. exec("pidof /var/www/cpp/main 2>&1", $output,$return); if ($return == 0) { $isProcessRunning=true; } else { $isProcessRunning=false; } This work's very good if i open my page from localhost, but when i open the page from another pc inside my network i have this error: 'pidof' is not recognized as an internal or external command, operable program or batch file I have a felling that the php page is executed on the pc where i open the page. I have tried many solution but none seems to work. What is the best solution to run a command inside my server with php? A: Please look at the command which pidof. Change the command inside the exec to include this full path: which pidof /bin/pidof The resulting code will be: exec("/bin/pidof /var/www/cpp/main 2>&1", $output,$return); if ($return == 0) { $isProcessRunning=true; } else { $isProcessRunning=false; }
doc_23534131
LocalDateTime localDateTime = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM); System.out.println(localDateTime.format(formatter)); That prints a nicely readable date of Oct 20, 2021 1:00:02 PM. But I would like to also add the time zone. My understanding is I need to use ZonedDateTime: ZonedDateTime zdt = localDateTime.atZone(ZoneId.of("America/New_York")); System.out.println(zdt); But that produces the not so readable 2021-10-20T13:00:02.921-04:00[America/New_York]. Is there some way to format a ZonedDateTime so it's concise and readable like that produced by FormatStyle.MEDIUM, but also appended by the timezone (e.g: Oct 20, 2021 1:00:02 PM EST)? Note: I gather from this answer that I should not actually use "pseudo-zones", such as EST, due to their non-standardized nature. A: tl;dr If you want a hint as to the time zone in use, use the LONG format for time-of-day portion. Optionally specify a different format such as MEDIUM for the date portion. ZonedDateTime .now( ZoneId.of( "America/New_York" ) ) .format( DateTimeFormatter .ofLocalizedDateTime( FormatStyle.MEDIUM , // Date portion style. FormatStyle.LONG // Time-of-day portion style. ) .withLocale( Locale.US ) // Locale determines the human language and cultural norms used in localizing. ) See this code run live at IdeOne.com. Oct 20, 2021, 4:48:46 PM EDT Never use EDT, CST, IST, and such for data-exchange. Do not attempt parsing of such values. These are not real time zones, are not standardized, and are not even unique! Avoid LocalDateTime.now I cannot imagine any scenario where calling LocalDateTime.now is the right thing to do. You capture the date and time-of-day but lack the context of a time zone or offset-from-UTC. So a LocalDateTime by definition cannot represent a moment, is not a point on the timeline. If you want to capture the current moment without committing to a particular time zone, capture the current moment as seen with an offset-from-UTC of zero hours-minutes-seconds. Instant instant = Instant.now() ; // Current moment as seen in UTC. Use ZonedDateTime.now If you want to capture the current moment as seen in America/New_York time zone, start with a ZonedDateTime. ZonedDateTime.now( ZoneId.of( "America/New_York" ) ) To generate text representing a java.time object, use toString method to get text in standard ISO 8601 format. While such output may seem less readable at first glance, the standard formats are designed to be maximally readable by people across cultures. To get a localized format, I suggest you let java.time automatically localize. ZoneId z = ZoneId.of( "America/New_York" ); ZonedDateTime zdt = ZonedDateTime.now( z ); System.out.println( "zdt represented in standard ISO 8601 format: " + zdt.toString() ); Locale locale = Locale.US ; DateTimeFormatter f_US = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM ).withLocale( locale ) ; String outputLocalized_US = zdt.format( f_US ) ; String outputLocalized_CA_fr = zdt.format( f_US.withLocale( Locale.CANADA_FRENCH ) ) ; System.out.println( outputLocalized_US ) ; System.out.println( outputLocalized_CA_fr ) ; When run. zdt represented in standard ISO 8601 format: 2021-10-20T16:37:57.752554-04:00[America/New_York] Oct 20, 2021, 4:37:57 PM 20 oct. 2021 16 h 37 min 57 s Separate formats for date & time You can specify different formats for the date versus time-of-day portions. Use a longer format for time-of-day portion to get a hint of the time zone while using a shorter format for date portion, if you so desire. DateTimeFormatter .ofLocalizedDateTime( FormatStyle.MEDIUM , // Date portion format. FormatStyle.LONG // Time-of-day portion format. ) A: Is there some way to format a ZonedDateTime so it reads similar to that produced by FormatStyle.MEDIUM, but is appended by the timezone - say, something like: Oct 20, 2021 4:05:13 PM EST? You can use the format, MMM d, uuuu h:mm:ss a zzz with the DateTimeFormatter. Demo: import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Locale; public class Main { public static void main(String[] args) { ZonedDateTime now = ZonedDateTime.now(ZoneId.of("America/New_York")); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM d, uuuu h:mm:ss a zzz", Locale.ENGLISH); System.out.println(now.format(dtf)); } } Output: Oct 20, 2021 6:41:45 PM EDT ONLINE DEMO A: the ZonedDateTime can retrieve the current ZoneId. With the Zone, you can just use the getDisplayName(TextStyle style, Locale locale) getter. Just experiment which TextStyle is the best for you. zdt.getZone().getDisplayName(TextStyle.SHORT, Locale.ENGLISH) ==> ET A: Note that if you use LONG or FULL for the time style, the zone will be included: ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("America/New_York")); DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.LONG); System.out.println(zdt.format(formatter)); In the US locale, this prints: Oct 20, 2021, 4:34:16 PM EDT This is documented here: The FULL and LONG styles typically require a time-zone. When formatting using these styles, a ZoneId must be available, either by using ZonedDateTime or withZone(java.time.ZoneId). In this case, a time style of LONG happens to be the same as MEDIUM, but if you have to use MEDIUM for some reason, you can use a DateTimeFormatterBuilder and add the zone by hand: ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("America/New_York")); DateTimeFormatter formatter = new DateTimeFormatterBuilder() .append(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)) .appendLiteral(" ") .appendZoneText(TextStyle.SHORT).toFormatter(); System.out.println(zdt.format(formatter)); The advantage of this is that you can choose what style of timezone name you want. On the other hand, you might run into localisation issues, because I'm not sure if it is natural in all locales to put the timezone last.
doc_23534132
When I add function import, whats should be selected in returns a collection of, I selected string for now. And then what should be the return type of the function that would return this data to wpf view, XmlDocument? A: So you have an arbitrary block of XML? Then yes, XmlDocument should make that available. The problem with just using a string is that it would get further encoded by WCF. If the layout of the XML is known, another option is deserializing it into an object model and returning that, which might make it easier to consume at the client. But XmlDocument should work. XElement etc may also be worth a try if that is more convenient.
doc_23534133
The scenario : When i go on my server URL -> http:\domain-server.local : I got the Apache windows "it works". if i try https://domain-server.local/redmine : error : Ruby on Rails application could not be started A source file that the application requires, is missing. It is possible that you didn't upload your application files correctly. Please check whether all your application files are uploaded. A required library may not installed. Please install all libraries that this application requires. Further information about the error may have been written to the application's log file. Please check it in order to analyse the problem. Error message: cannot load such file -- /opt/config/environment Exception class: LoadError Application root: /opt Now i try that : domain-server.local/redmine: i got that error : Passenger error #2 An error occurred while trying to access '/var/www/redmine/public/redmine': Cannot resolve possible symlink '/var/www/redmine/public/redmine': No such file or directory (2) even more strange : when i remove the http:\ from my URL and the /redmine i got my redmine working : Environment: Redmine version 3.0.1.stable Ruby version 1.9.3-p194 (2012-04-20) [x86_64-linux] Rails version 4.2.0 Environment production Database adapter PostgreSQL SCM: Subversion 1.6.17 Git 1.7.10.4 Filesystem Redmine plugins: no plugin installed but i want to access to redmin from http:\domain-server.local/redmine Here is my apache2.conf file : # Include the virtual host configurations: Include sites-enabled/ RailsBaseURI /redmine PassengerUserSwitching on PassengerUser www-data PassengerGroup www-data <VirtualHost *:80> ServerName domain-server.local # !!! Be sure to point DocumentRoot to 'public'! DocumentRoot /var/www/redmine/public RailsEnv production RailsBaseURI /redmine <Directory /var/www/redmine> # This relaxes Apache security settings. AllowOverride all # MultiViews must be turned off. Options -MultiViews # Uncomment this if you're on Apache >= 2.4: #Require all granted </Directory> What's wrong with my install ? A: I solved my problem. I removed the apache2.conf file's content. I also had 2 different Phusion_Passenger version, so i deleted the oldest and used Phusion_Passenger 5.0.5. I changed my symlink /var/www/redmine -> /opt/redmine-3.0.1 to /opt/redmine-3.0.1/public i created the files passenger.load and passenger.conf in /etc/apache2/mods-available/ with the passenger-install-apache2-module instructions . Then restart apache and it's done !
doc_23534134
A: If you want to resume ? Just Re-enable vm backup? Reference: Enable backup for an Azure VM and Back up a virtual machine in Azure with PowerShell You enable backup for an Azure VM, and specify a backup policy. The policy defines when backups run, and how long recovery points created by the backups should be retained. The default protection policy runs a backup once a day for the VM, and retains the created recovery points for 30 days. You can use this default policy to quickly protect your VM. Enable backup as follows: First, set the default policy with Get-AzRecoveryServicesBackupProtectionPolicy: $policy = Get-AzRecoveryServicesBackupProtectionPolicy -Name "DefaultPolicy" Enable VM backup with Enable-AzRecoveryServicesBackupProtection. Specify the policy, the resource group and the VM name. Enable-AzRecoveryServicesBackupProtection ` -ResourceGroupName "myResourceGroup" ` -Name "myVM" ` -Policy $policy A: As you know there is enable or disable operation for Azure VM backup. I think there is no such resume backup operation. Per my understanding, I suppose what you want is to continue backups the Azure VM in the existing recovery service vault after you move the Azure VM to another subscription. If so, please note that Recovery Services vault doesn't support cross subscription backups. If you move a vault with virtual machine backup data across subscriptions, you must move your virtual machines to the same subscription, and use the same target resource group to continue backups. To move a virtual machine to a new subscription without moving the Recovery Services vault: * *Temporarily stop backup *Delete the restore point. This operation deletes only the instant recovery points, not the backed-up data in the vault. *Move the virtual machines to the new subscription *Reprotect it under a new vault in that subscription In this case, you have to create a new vault for Azure VM backup after you move the VM to another subscription, so you will use Enable-AzRecoveryServicesBackupProtection to enable backup for an Azure VM then start a backup job with Backup-AzRecoveryServicesBackupItem. Otherwise, you can move a Recovery Services vault and its associated resources to another subscription. Currently, you can move one Recovery Services vault, per region, at a time. You can't move vaults that back up Azure Files, Azure File Sync, or SQL in IaaS virtual machines. To move a Recovery Services vault, you must enroll in a limited public preview. You also could get more details from the recovery service limitation.
doc_23534135
private void button2_Click(object sender, EventArgs e) { Process game = new Process(); game.StartInfo.FileName = "ShovelShovel.exe"; game.Start(); } I figured it would launch the game and close, but if I click the button, it just launches my program again. If I click No on that form, then I get a huge list of unhandled exceptions. Whether I do this.Close(); or Application.Exit(); the program still opens itself. Can anyone tell me why it would open again? I haven't altered Program.cs in anyway. Thank you very much. A: Try this: (assuming that the program you are working from is "ShovelShovel Settings.exe" and is the launcher for "ShovelShovel.exe") //launch game ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = "ShovelShovel.exe"; Process p = Process.Start(startInfo); //close this.Close(); Or even just Process.Start("ShovelShovel.exe"); If this is still starting the same application, you either have the wrong path, or the exe's are the same. To double check, why dont you go into the directory and execute "ShovelShovel.exe" manually from WindowsExplorer.
doc_23534136
I'm then trying to save these dates and times in a table to keep a record of check in times for the users. Can this be done through Ajax? As it is, when the user signs in, the current date and time will be displayed on the page. var rootURL = "http://localhost:8080/SCC/rest/checkin"; $(document).ready(function() { // on click Sign In Button checks that username =='admin' // and password == 'password' //var newD = newDate(); $("#login").click(function() { if ($("#loginUserName").val() == 'admin' && $("#loginPassword").val() == 'pass') { $("#signIn").hide(); newDate(); addCheckIn(); } else { alert("Please try again") } $("#logout").click(function() { $("form")[0].reset(); $("#signIn").show(); $("#second").hide(); }); navigator.geolocation; const successfulLookup = (position) => { const { latitude, longitude } = position.coords; fetch('https://api.opencagedata.com/geocode/v1/json?q=${latitude}+${longitude}&key=42815d59fd754ae0a68c6efcdc90d09e') .then(response => response.json()) .then(console.log); }; navigator.geolocation.getCurrentPosition(successfulLookup, console.log); }); var newDate = function(){ exd = new Date(); var hours=exd.getHours(); var min=exd.getMinutes(); var sec=exd.getSeconds(); var dat=exd.getDate(); var month=exd.getMonth(); var year=exd.getFullYear(); var dn="AM"; if(hours==12){ dn="PM"; } if(hours>12){ dn="PM"; hours=hours-12; } if(hours<10){ hours="0"+hours; } if(min<10){ min="0"+min; } if(sec<10){ sec="0"+sec; } if(dat<10){ dat="0"+dat; } if(month<10){ month="0"+month; } var clock = hours+":"+min+":"+sec+""+dn; var datee = dat+"-"+ month+"-"+year; $("#second").append("<p>Your Login Time is </p> " + clock + "<p>Your Login Date is </p> " + datee); } var addCheckIn = function() { console.log('addCheckIn'); $.ajax({ type : 'POST', contentType : 'application/json', url : rootURL, dataType : "json", data : formToJSON(), success : function(data, textStatus, jqXHR) { alert('CheckIn Time Added'); }, error : function(jqXHR, textStatus, errorThrown) { alert('CheckIn error: ' + textStatus); } }); }; var formToJSON = function(){ return JSON.stringify({ "checkInTime" : clock, "checkInDate" : datee }); }; });
doc_23534137
I'm trying to use custom fonts in my app without success. This is the fonts section of my pubspec.yaml file: fonts: - family: Muli fonts: - asset: fonts/Muli-Light.ttf - family: LibreBaskerville fonts: - asset: fonts/LibreBaskerville-Regular.ttf And in my app: Widget _sectionTitle(String text) { return Container( padding: EdgeInsets.fromLTRB(25.0, 0.0, 25.0, 5.0), child: Text(text, style: new TextStyle(fontFamily: 'Muli', fontSize: 50.0), )); } Widget _sectionText(String text){ return Container ( padding: EdgeInsets.fromLTRB(25.0, 0.0, 25.0, 15.0), child: Text(text, style: TextStyle(fontFamily: 'LibreBaskerville', fontSize: 20.0)), ); } Among the things I've tried (multiple times): * *Deleting the installed file from the emulator *running from Android Studio vs running from VSCode *moving the .ttf files to different folders *downloading other fonts *using an online YAML validator *flutter clean I'm assuming there's something amiss with the pubspec.yaml file, but I can't see what it might be. Any suggestions would be much appreciated. Thx. EDIT: Just tried creating a new default Flutter app with the same Pubspec.yaml font info. I added the custom font to the MaterialApp widget and it works ... so maybe the problem is not the yaml. A: If you are using vs code, you can run the following command at the terminal: flutter run --enable-software-rendering. That should solve the issue. A: remove the app from the test device then do flutter clean, re-run flutter clean A: These are the steps you need to follow while you add custom fonts to your app. Step-1: Place your fonts file (Abc.ttf) in assets folder (if you don't have one you may have to create it by yourself) Step-2: Open your pubspec.yaml file and add this (Keep track of spaces) fonts: - family: MyFont fonts: - asset: assets/Abc.ttf Step-3: Run flutter packages get in terminal (Or use Packages get option in the IDE) Step-4: Use your custom font in your code like this Text("Example", style:TextStyle(fontFamily: "MyFont")) A: I know this quite old, but just in case someone comes across this: I had a similar issue where asset images would not load in one project while it loaded another without issues in another project, everything appparently configured the same way. The problem was that the one where it did not work properly was a flutter package project. Here you explicitly need to specify the packagename for asset images and also asset fonts. Check my detailed answert here: https://stackoverflow.com/a/67526610/8539278 A: I came across the same issue, and I found my answer to it. It seems like ios folder and android folder is required to use font for somehow. I don't know why it is needed but that's the only difference between the one 'font works' and 'doesn't'. Currently, I am focusing on WEB only so I deleted ios folder and android folder. I think, from now on, I keep those folder as a talisman. A: You may run into this problem when using VS Code. If so create a new project and copy the files over. How to create a new project on VS Code? You create a new folder, open the new folder on VS Code and run on terminal 'Flutter create .' Then just transfer your files to the new directory. This worked for me for some reason A: i removed menu -> run ->edit configuration -> main.dart -> additional run args -> --web-renderer html A: Try to reinstall the apk in emulator
doc_23534138
.section .rodata # Read only data section. .align 8 # Aline address to multiple of 8. format_i: .string "%d %d" .text .globl run_func .type run_func, @function run_func: mov $0, %eax push %rbp # Keep stack aligned movq $0, (%rbp) movq %rsp, %rbp movq $format_i, %rdi # Load format string sub $16, %rsp # Allocating memory in the stack leaq -8(%rbp), %rsi # Adress to store i leaq -16(%rbp), %rdx # Adress to store j xorq %rax, %rax call scanf movq -8(%rbp), %rsi # Passing the first value of scanf movq -16(%rbp), %rdx # Passing the second value of scanf movq %rbp, %rsp pop %rbp I entered "2 4", what I get in rsi is 0x7fff00000002 and in rdx 0x4. How can I make rsi get 0x2 instead? A: %d is for reading 4-byte signed integers on most systems. So you can either: * *allocate only 4 bytes in the stack frame and load those 4 bytes into %rsi with sign extension -- movslq -8(%rbp), %rsi *use %ld or %lld format, depending on what your library uses for an 8-byte integer type.
doc_23534139
Just assume this is my index.php file //index.php <?php include_once "fbmain.php";//Here I do all facebook Authentication parts ?> <html> <body> <form action="http://localhost/test/test.php" method="POST"> <input type="submit" value="Upload"/><br/> </form> </body> </html> When a user click the "Upload" button,'test.php' file is loaded.In 'test.php' file I want to display the id of the fan page, //test.php <?php echo "Hello".$ID_OF_THE_FAN_PAGE; ?> //output eg: Hello 228276387189141 Can anyone tell me is there a way to do this?(I am using graph api and php to develop this app) A: When your app is running as a page tab, an encoded signed_request parameter is sent to your app, which includes details about the page the app is installed on See the documentation here: https://developers.facebook.com/docs/authentication/signed_request/ There's an example of how to decode the request and obtain the relevant fields. The 'page' field in the signed_request includes the page ID, whether the current user likes that page, and whether the current user is an admin of that page
doc_23534140
<div id="column-left"> <%= render :partial => "car_gallery" %> </div> <div id="column-right"> <%= render :partial => "vehicle_info" %> </div> In the car_gallery I can see only 12 photos of the car. The problem: What I want to do is to have a link near car_gallery div, and when the user clicks on it the partial vehicle_info in the left side will be replaced by the partial car_gallery_all (this partial contains all the photos for that car, not limited to 12). Is there any short way to do this? Please help. A: Edit due to lack of rep: This will work in rails 3.1, not sure about 3.0 or below.. Also, davidb's answer would, if I understand it correctly, load all of the images regardless of whether the user wants to view them or not - this solution would only load them if the user clicks on the link to view them.. .............................................................................. controller def all_car_photos ... respond_to do |format| format.js end end view <div id="column-left"> <%= render :partial => "car_gallery" %> </div> <div id="column-right"> <%= render :partial => "vehicle_info" %> </div> <%= link_to "Show All Photos", path_to_controller_action(@car), { :method => :get, :remote => true} %> all_car_photos.js.erb $('#column-right').html("<%= escape_javascript(render "car_gallery_all") %>"); Ok so, the view contains the link_to method which points to the all_car_photos controller action. The key thing here is that the link_to contains :remote => true - this submits the request using the baked in Rails AJAX functionality. The controller action does what it needs to do, but responds with the .js view - all_car_photos.js.erb - This contains a line of jQuery which will replace the content of the 'column-right' div with the 'car_gallery_all' partial.. It's late, but that setup should work.. A: Add the link and give an id to it. You use the "#" because it does not link to anything effectifly. <%= link_to "my link text", "#", :id => "replace_vehicle_info" %> Then you add some jQuery to your public/javascript/application.js (I except you use rails 3 not 3.1 because your question is tagged like that) to replace the content of that div. $("#replace_vehicle_info").click(function() { $("#vehicle_info").replaceWith(<your html here>) })
doc_23534141
The name of these PDF-files stay the same, but the data changes. Currently I'm using: <object id="men" data="seasons/S2223/Men2023.pdf?" type="application/pdf" width="100%" height="750px"> <p>The file could not be read in the browser <a href="seasons/S2223/Men2023.pdf?"> Click here to download</a> </p> </object> When I update the PDF I'm expecting the data="seasons/S2223/Men2023.pdf?" to be reading the latest PDF however it stays the same as before. I added the ? at the end of the filename which should check for the latest version but it doesn't seem to work. When I clear my browser's cache it's updated but ofcourse this isn't a suitable option for users. All help is appreciated. A: Caching, in this context, is where the browser has loaded the data from a URL in the past and still has a local copy of it. To speed things up and save bandwidth, it uses its local copy instead of asking the server for a fresh copy. If you want the browser to fetch a fresh copy then you need to do something to make it think that the copy it has in the cache is no good. Cache Busting Query String You are trying to use this approach, but it isn't really suitable for your needs and your implementation is broken. This technique is designed for resources that change infrequently and unpredictable such as the stylesheet for a website. (Since your resources change weekly, this isn't a good option for you.) It works by changing the URL to the resource whenever the resource changes. This means that the URL doesn't match the one the browser has cached data for. Since the browser doesn't know about the new URL it has to ask for it fresh. Since you have hardcoded the query to n=1, it never changes which defeats the object. Common approaches are to set the value of the query to a time stamp or a checksum of the file. (This is usually done with the website's build tool as part of the deployment process.) Cache Control Headers HTTP provides mechanisms to tell the browser when it should get a new copy. There are a variety of headers and I encourage you to read this Caching Tutorial for Web Authors and Webmasters as it covers the topic well. Since your documents expire weekly, I think the best approach for you would be to set an Expires header on the HTTP resource for the PDF's URL. You could programmatically set it to (for example) one hour after the time a new version is expected to be uploaded. How you go about this would depend on the HTTP server and/or server-side programming capabilities of the host where you deploy the PDF.
doc_23534142
However, although the ggplot figure comes out correctly, the plotly does not. I am using the following versions and show a MWE below: ggplot2: version 2.0.0.9000, plotly: version 2.0.19 library(plotly) g <- ggplot(mtcars, aes(x = factor(cyl), y = mpg, fill = interaction(factor(cyl),carb))) + geom_boxplot() (gg <- ggplotly(g)) Any ideas why g and gg differs above? A: Not a complete solution. Include the interaction to your x term: # use lex.order to obtain correct ordered levels a <- ggplot(mtcars, aes(x = interaction(cyl, carb, lex.order = T), y = mpg,fill = interaction(cyl, carb, lex.order = T))) + geom_boxplot() # check the plot a # plotly ggplotly(a) A: actually there is an alternative that will give you exactly what you want. mtcars$intec <- interaction(factor(cyl),carb) mtcars %>% plot_ly(x = cyl, y = mpg, type = "box", color = as.factor(intec), fill=as.factor(intec)) %>% layout(boxmode = "group")
doc_23534143
How? <div class="thumb thumb-rounded thumb-slide"> <img src="<?php echo $result['staff_signature'];?>" alt="Signature IS BLANK"> <div class="caption"> <input type="file" class="file-input" data-show-caption="false" data- show-upload="false" accept="image/*" id="signature" name="signature"> </div> </div> A: You can upload user files to the server with AJAX from a form with field, but if you want to be nice to the user and show a preview, you HAVE to do the round trip and upload the file to the server first A: As far i understand from ur question i think u need this.. <div class="thumb thumb-rounded thumb-slide"> <img src="<?php echo $result['staff_signature'];?>" alt="Signature IS BLANK"> <div class="caption"> <input type="file" class="file-input" data-show-caption="false" data- show-upload="false" accept="image/*" id="signature" name="signature"> </div> </div> <input type="hidden" name="imgsrc" id="imgsrc" value="<?php echo $result['staff_signature'];?>"> upload section if($_FILES[signature]['name']!="") { //file upload code } else { $imgsrc=$_POST['imgsrc']; //get the imgsrc value using GET/POST ..whatever u are using the form } Let me know your feedback
doc_23534144
Host A and B are exchanging messages in a conversation through a broker. When host B receives a messages it sends back a delivery token to Host A so that it can show the user that B has received his messages. This may also happen the other way around. At any point A or B may be offline and the broker will hold on to the messages until they come online and then deliver them. Each host stores it's own and the other hosts messages in a database table: ID | From | To | Msg | Type | Uid I figured using the naive table primary key id would have been a bad choice to identify the messages (as it's dependent in order of insertion) so I defined a custom unique id field (uid). My question is: How can I make sure that the current message id stays synchronized between host A and B so that only one message has that id? So that I can use delivery token id to identify which message was received, and it wouldn't be possible if I had more than one message with the same Id. If I do this naively incrementing it every time we send/receive a message at first it looks ok: Host A sends message with ID 1 and increases it's current ID to 2 Host B receives a message and increases it's current ID to 2 Host B sends message with ID 2 and increases it's current ID to 3 Host A receives message and increases it's current ID to 3 ... But it may very easily break: Host A sends message with ID 1 and increases it's current ID to 2 Host B sends a message (before receiving the previous one) with ID 1 clash.. two messages with ID 1 received by both hosts I thought of generating a large UUID every time (with extremely low chance of collision) but it introduces a large overhead as every message would need both to carry and store one. Unfortunately any solution regarding the broker is not viable because I can't touch the code of the broker. A: This is a typical problem of Distributed Systems (class exercise?). I suppose you are trying to keep the same ID in order to determine an absolute order among all messages exchanged between Alice and Bob. If this is not the case, the solution provided in the comment by john1020 should be enough. Other possibility is to have ID stored in one node that can be accessed by both A and B and a distributed locks mechanism synchronizes access. In that way, you always define an order even in face of collisions. But this is not always possible and sometimes not efficient. Unfortunately, there is no way of keeping an absolute order (except having that unique counter with distributed locks). If you have one ID that can be modified by both A and B, you will have a problem of eventual consistency and risk of collisions. A collision is basically the problem you described. Now, imagine both Bob and Alice send a message at the same time, both set ID in 2. What would be the order in which you would store the messages? Actually it doesn't matter, it's like the situation when two people spoke at the phone at the same time. There is a collision. However, what is interesting is to identify messages that actually have a sequence or cause-effect: so you could keep an order between messages that are caused by other messages: Bob invites Alice to dance and Alice says yes, two messages with an order. For keeping such order you can apply some techniques like vector clocks (based on a Leslie Lamport's timestamps vector algorithm): https://en.wikipedia.org/wiki/Vector_clock . You can also read about AWS' DynamoDB: http://the-paper-trail.org/blog/consistency-and-availability-in-amazons-dynamo/ Also you can use the same mechanism Cassandra uses for distributed counters. This is a nice description: http://www.datastax.com/wp-content/uploads/2011/07/cassandra_sf_counters.pdf
doc_23534145
When I upload an image as any blob type to container in storage account and try to write a path to it I get the following error: “Invalid VHD blob path. Please make sure the path to the VHD is valid’ The path looks like this: “https://storageAccountName.blob.core.windows.net/containerName/filename” What am I doing wrong and how to fix it? A: Please make sure you have a VHD path with .vhd format like this: https://storageAccountName.blob.core.windows.net/containerName/myUploadedVHD.vhd Also, it's recommended to upload .vhd files to the page blob, For more references: * *Prepare a Windows VHD or VHDX to upload to Azure *Create a Windows VM from a specialized disk by using PowerShell *Creating An Azure VM From The VHDX/VHD File
doc_23534146
If there are no values in the textfield, the program should ignore the statement and move to the other. Sorry for my english. My code: try{dishCarbonara = Double.parseDouble(dishCarbonaraTF.getText());} catch(NumberFormatException e){dishCarbonaraTF.setText("0");} dishes += dishCarbonara * 35 ; listItems += "Carbonara: 35 * "+dishCarbonara+"\n"; try{dishChickenWing = Double.parseDouble(dshChickenWIngsTF.getText());} catch(NumberFormatException e){dshChickenWIngsTF.setText("0");} dishes += 50 * dishChickenWing; listItems += "Chicken Wings: 30 * "+dishChickenWing+"\n"; try{dishPotatoFries = Double.parseDouble(dishPotatoFriesTF.getText());} catch(NumberFormatException e){dishPotatoFriesTF.setText("0");} dishes += 25 * dishPotatoFries; listItems += "Potato Fries: 25 * "+dishPotatoFries+"\n"; A: How about a simple if check? if (!dishCarbonaraTF.getText().equals("")) { // text field is not empty do something with the value } You would do this for each TextField of course. You could also do the below to ensure there aren't just whitespaces being entered: if (!dishCarbonaraTF.getText().trim().equals("")) { // textfield is not empty and doesn't contain any white spaces }
doc_23534147
@JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) public class ObjectOfMonitoring { private BigInteger id; private Map<String, Object> properties = new HashMap<>(); @JsonAnySetter public void add(String key, Object value) { properties.put(key, value); } @JsonAnyGetter public Map<String, Object> getProperties() { return properties; } I test it in the following code: ObjectOfMonitoring objectOfMonitoring = new ObjectOfMonitoring(); objectOfMonitoring.setId(BigInteger.ONE); objectOfMonitoring.add("key1", "value1"); String jsonInString = mapper.writeValueAsString(objectOfMonitoring); System.out.println(jsonInString); I want to get result: {"id":1,"key2":"value2","key1":"value1"} But actual result is: {"id":1,"properties":{"key2":"value2","key1":"value1"}} What do I do incorrectly? And how to get the expected result? A: Make sure that ObjectMapper and @JsonAnySetter/@JsonAnyGetter annotations are from the same packages. All should be: * *either from org.codehaus.jackson - which is the older version of jackson *or from com.fasterxml.jackson - which is newer (Jackson has moved from Codehaus when releasing Jackson 2 - see here) If you have both dependencies in your project and you are using them interchangeably you may have such hard to notice problems. The best would be to just get rid of org.codehaus.jackson from your project dependencies. A: Might be late to the party but thought of posting the answer as it can be helpful to someone in the future. This is the sample code which you can configure accordingly for your class. The main class which will read the JSON and associates with the class: public class Main { public static void main(String[] args) throws Exception { File jsonFile = new File("test.json").getAbsoluteFile(); final ObjectMapper mapper = new ObjectMapper(); MyObject myObject = mapper.readValue(jsonFile, MyPojo.class); } } Your custom POJO: class MyObject { private int id; private Map<String,String> customField; //Getter and Setter for POJO fields ommited @JsonAnySetter public void setCustomField(String key, Object value) { System.out.println(" Key : " + key + " Value : " + value); if(customField == null){ customField = new HashMap<String,Object>(); } customField.put(key,value); } @JsonAnyGetter public Map<String,String> getCustomField(){ return customField; } } This will work if even for duplicate keys within the JSON if you are using the readValue from ObjectMapper but if you are using the treeToValue method from ObjectMapper then this would fail for the duplicate keys and you will have only the last value for the duplicated field. I am still figuring out a way to access the duplicate field while using the treeToValue method
doc_23534148
$ echo "2014-10-26 23:24:38.3123123" | date -d - Sun Oct 26 00:00:00 EDT 2014 $ date -d "2014-10-26 23:24:38.3123123" Sun Oct 26 23:24:38 EDT 2014 As you can see, the hour/min/seconds information is not picked up when I pipe in data with echo, but it is picked up when I use it as a command line argument. I am sure that there is something dumb I am not noticing, but if anyone can enlighten me on what that is it would be much appreciated! A: When you write: $ echo "2014-10-26 23:24:38.3123123" | date -d - The space character between 2014-10-26 and 23:24:38.3123123 is treated like an argument separator and the date command takes the date string as two different arguments. You can simply escape this space character: $ echo "2014-10-26\ 23:24:38.3123123" | date -d - and it works; Sun Oct 26 23:24:38 EDT 2014
doc_23534149
import numpy as np import pandas as pd # TODO: data = pd.DataFrame({"Data 1": [3,4,1]}) data Output: Data 1 0 3 1 4 2 1 The output I wanted: Data 1 0 1 1 3 2 4
doc_23534150
I'd prefer to have passive ID's, but the reader itself would be able to have a fixed power source that doesn't need to be changed. I've done a lot of searching on google and there are RFiD scanners that read cars to open tolls booths, but those are commercial grade products and much more expensive than anything I'm trying to make. Should I continue looking into RFiD's, or is there a more efficient method of approaching this? Also, if my tags are active, and powerful enough, would that compensate for a low frequency reader? A: You'll easily achieve to read passive tags from a distance of a few meters (up to 10m) by using any industrial UHF RFID reader (Impinj, ThingMagic, Stid, ...). Some tags are similar to labels that can be directly stuck on the windscreen of the cars. Tags are rather inexpensive. But in that case you will need to spend a few hundreds of dollars to buy a single reader with its antenna. That is what makes me think that any RFID based system is an option only when the number of users of the system is quite important (i.e: check the access to a company park or to a residence). In that case, the investment of the reader is dispatched on all the users, whereas the global investment for the tags stay low.
doc_23534151
<form id="formrandom1473" name="formrandom1473" method="post" action="ajax_process.php?case=add_product_ajax&amp;pid=1473"> <input type="hidden" value="1473" name="products_id"> <input type="hidden" value="1" name="qty"> <div class="add_to_cart_div"> <input type="image" border="0" id="add-to-cart-1473" title=" Add to Cart " alt="Add to Cart" src="includes/languages/english/images/buttons/button_in_cart.gif"> </div> </form> <script type="text/javascript"> $(document).ready(function() { $("#add-to-cart-1473").click(function () { var formrandom1473 = $("#formrandom1473"); formrandom1473.submit(function () { $.ajax({ type: formrandom1473.attr("method"), url: formrandom1473.attr("action"), data: formrandom1473.serialize(), success: function (data) { $("#output").html(data); $(".message_div").addClass("message_success").slideDown().delay(6000).slideUp(); // Div success $(".cart_counter").load("ajax_process.php?case=cart_counter"); // Load new quantity / by quantity $(".shopping_cart_box").load("ajax_process.php?case=shopping_cart_box"); // Load new shopping cart box / by product $(".cart_dropdown").load("ajax_process.php?case=cart_dropdown"); // Load new shopping cart box / by product } }); $("formrandom1473").unbind(); return false; }); /* Effect */ var productX = $("#cart-image-1473").offset().left; var productY = $("#cart-image-1473").offset().top; var basketX = $("#boxcart-content").offset().left; var basketY = $("#boxcart-content").offset().top; var gotoX = basketX - productX; var gotoY = basketY - productY; var newImageWidth = $("#cart-image-1473").width() / 3; var newImageHeight = $("#cart-image-1473").height() / 3; $("#wrapper").html(""); $("#wrapper").css({"position":"absolute","top": productY,"left": productX}); $("#cart-image-1473").clone() .prependTo("#wrapper") .css({"position" : "absolute", "border" : "1px dashed black"}) .animate({opacity: 0.6}) .animate({opacity: 0.0, marginLeft: gotoX, marginTop: gotoY, width: newImageWidth, height: newImageHeight}, 1200, function() { }); /* Effect */ }); //click }); //ready </script> <script type="text/javascript"> $(document).ready(function() { $('.mycarousel').jcarousel(); }); </script> i tried to use $("formrandom1473").unbind(); but the problem still same. A: Did you mean to use $("#formrandom1473").unbind(); with the # instead? Or, since you already stored the jQuery object earlier: formrandom1473.unbind(); If unbind doesn't work for you, try this instead, but move it BEFORE the $.ajax: formrandom1473.submit(function() { return false; }); Also, check your JS console for any errors. A: After refer this comment .. the form finally can submit like normal after i'm using e.stopImmediatePropagation(); formrandom1473.submit(function (e) { $.ajax({ type: formrandom1473.attr("method"), url: formrandom1473.attr("action"), data: formrandom1473.serialize(), success: function (data) { $("#output").html(data); $(".message_div").addClass("message_success").slideDown().delay(6000).slideUp(); // Div success $(".cart_counter").load("ajax_process.php?case=cart_counter"); // Load new quantity / by quantity $(".shopping_cart_box").load("ajax_process.php?case=shopping_cart_box"); // Load new shopping cart box / by product $(".cart_dropdown").load("ajax_process.php?case=cart_dropdown"); // Load new shopping cart box / by product } }); e.stopImmediatePropagation(); return false;
doc_23534152
Example : 16515134 3 first numbers is faculty code (In the example : 165) 2 numbers after that is year you enter the university (In the example : 15) 3 last numbers is personal number (In the example : 134) I have about 100 hundred IDs in 100 rows in one cell. I want to count the specific 4th and 5th number position (year you enter the university). Example : 16515134 16515145 13216124 I want to count the "15" (the 4th dan 5th number). So it will give 2 as the answer. So how to do that ? I'm already tried use =COUNTIFS(A1:A6,"***15*") but it only works when it is a text not a number. A: Something like: =SUMPRODUCT(--(MID(A1:A20,4,2)="15"))
doc_23534153
When should one use a Panel vs. nested directories in an HDF5? I'm writing and reading many small tables/dataframes of the same size, generated with different set of parameters. I have been organizing them with Panels and Panel4Ds, then saving the whole Panel to a table in an HDF5 file. When reading back the data, I generally want to eventually use all of the dataframes, but at any one time I'm actually only using one of the dataframes. For my current purposes it seems none of this matters; the dataframes are small, so reading in the whole Panel is not troublesome. But if anyone else who doesn't use pandas tries to read the HDF5 file, they will have more trouble accessing and understanding the data. What other factors should I be considering?
doc_23534154
Basically I have a class and two methods inside it like so: Is this possible? class MyClass{ private cleanup(str:String):String{ //clean up the string return str; //return sanitized string } //I want to do this insertString(this.cleanup(text_1:String), this.cleanup(text_2:String)){ console.log(text_1 + text_2); } } Instead of this? class MyClass{ private cleanup(str:String):String{ //clean up the string return str; //return sanitized string } //might get to long if I have to cleanup to many strings insertString(text_1:String, text_2:String){ text_1 = this.cleanup(text_1) text_2 = this.cleanup(text_2) console.log(text_1 + text_2); } } A: What you're trying to achieve is not actually calling a method from another method signature. It's more about processing your list of arguments. 1: arguments hack You can modify the provided arguments array and the corresponding named parameters will also change. insertString(text_1:String, text_2:String) { // here text_1 and text_2 are not cleaned up yet for (var i = 0; i < arguments.length; i++) { arguments[i] = this.cleanup(arguments[i]) } // text_1 and text_2 are now cleaned up } However, this approach is hackish, and you can go with #2: 2: Decorators We declare two decorators: one parameter decorator named cleanup: function cleanup(target: Object, propertyKey: string | symbol, parameterIndex: number) { let cleanupParams: number[] = Reflect.getOwnMetadata("MyClass:cleanup", target, propertyKey) || []; cleanupParams.push(parameterIndex); Reflect.defineMetadata("MyClass:cleanup", cleanupParams, target, propertyKey); } And one method decorator named CleanupMethod (it's actually a decorator factory): function CleanupMethod(func){ return function (target: any, propertyName: string, descriptor: TypedPropertyDescriptor<Function>) { let method = descriptor.value; descriptor.value = function () { let requiredParameters: number[] = Reflect.getOwnMetadata("MyClass:cleanup", target, propertyName); if (requiredParameters) { for (let parameterIndex of requiredParameters) { arguments[parameterIndex] = func(arguments[parameterIndex]); } } return method.apply(this, arguments); } } } In the decorators we save a list of which parameters should be sanitized on function enter and then on every call we sanitize them. Usage: class MyClass{ private cleanup(str:string):string{ //clean up the string return '[sanitized ' + str + ']'; //return sanitized string } @CleanupMethod(MyClass.prototype.cleanup) insertString(text_1:string, @cleanup text_2:string){ console.log(text_1 + text_2); } @CleanupMethod(MyClass.prototype.cleanup) insertNumber(n1: number, n2: number, @cleanup n3: number, n4: number, n5: number){ console.log(`${n1} + ${n2} + ${n3} + ${n4} + ${n5}`) } } var m = new MyClass(); m.insertString('a', 'b') // outputs `a[sanitized b]` m.insertNumber(10,20,30,40,50) // outputs `10 + 20 + [sanitized 30] + 40 + 50` Cleanup function is passed as a parameter to CleanupMethod factory. That way you can have different cleanup functions, e.g.: @CleanupMethod(cleanupString) insertString( @cleanup str1: string, @cleanup str2: string2 ){ /*...*/ } @CleanupMethod(cleanupNumber) insertNumber( @cleanup n1: number ){ /*...*/ } If you want, you can rewrite the decorator code and move cleanup function to parameter decorator, but that will increase the amount of code needed: @CleanupMethod insertString( @cleanup(cleanupString) str1: string, @cleanup(cleanupNumber) n1: number ){ /*...*/ } More on decorators
doc_23534155
First shut off the Red Pitaya, remove the memory card and connect it to a PC (I used the adapter that came with the memory card and inserted into the memory card slot in my laptop). Edit the file /etc/network/wpa_supplicant.conf and insert the ssid and psk strings: # WPA2 configuration example network={ ssid="ssid-string" psk="password-string" proto=WPA2 key_mgmt=WPA-PSK pairwise=CCMP group=CCMP auth_alg=OPEN } Save the file and put the memory card back into Red Pitaya and restart. In my console I can see that the wlan0 interface is initialized and that the DHCP client gets an IP address: ++ Bringing up wlan0 Successfully initialized wpa_supplicant rfkill: Cannot open RFKILL control device ioctl[SIOCSIWAP]: Operation not permitted udhcpc (v1.20.1) started Sending discover... Sending discover... Sending discover... Sending select for 192.168.11.115... Lease of 192.168.11.115 obtained, lease time 43200 You can check the interface status with iwconfig: redpitaya> iwconfig wlan0 IEEE 802.11bgn ESSID:"my-ssid" Nickname:"<WIFI@REALTEK>" Mode:Managed Frequency:2.412 GHz Access Point: 20:C9:D0:1D:AB:CD Bit Rate:150 Mb/s Sensitivity:0/0 Retry:off RTS thr:off Fragment thr:off Encryption key:****-****-****-****-****-****-****-**** Security mode:open Power Management:off Link Quality=100/100 Signal level=83/100 Noise level=0/100 Rx invalid nwid:0 Rx invalid crypt:0 Rx invalid frag:0 Tx excessive retries:0 Invalid misc:0 Missed beacon:0
doc_23534156
In the Codebehind I create a UserControl I have and add it to the Placeholder. protected void Page_Load(object sender, EventArgs e) { UserControl uc = new ChartUserControl(); myForm.Controls.Add(uc); } The UserControl in turn has a Placeholder, but in the Page_Load (for the UserControl) when I do: protected void Page_Load(object sender, EventArgs e) { WebControl x = new WebControl(); userControlPlaceholder.Controls.Add(x); } It gives me the ubiquitous "Object reference not set to an instance of an object" exception. I've tried forcing instantiation by calling a constructor, but that has gotten me into other trouble. Any help would be appreciated. A: I just spent 4 hours on this myself. The problem is that you're creating the user controls with ChartUserControl chart = new ChartUserControl(); but you have to use LoadControl: ChartUserControl chart = (ChartUserControl)LoadControl("~/path/to/control/ChartUserControl.ascx"); Apparently, LoadControl initializes the user control so that its PlaceHolders (and I would assume, other controls it contains), won't be null when you use them. A: Instead of adding the control in the Page_Load, Override the CreateChildControls method and add it there.
doc_23534157
at :1:1 inside the conditional statement. If I take the console.log outside the conditional statement it works fine. Is it because of function scope? const video = document.getElementById('video'); const caption = document.getElementsByTagName('span'); video.addEventListener('timeupdate', () => { for (i = 0; i < caption.length; i += 1) { let captionTime = caption[i].getAttribute('data-time'); if (captionTime === video.currentTime) { caption.style.backgroundColor = 'yellow'; console.log(captionTime); } } }); <video id="video" width="400" height="225"> <source type="video/mp4" src="video/video.mp4"> <source type="video/ogg" src="video/video.ogg"> </video> </div> <div class="transcript-wrapper"> <p> <span data-time = "0.240"> Now that we've looked at the architecture of the internet, let's see how you might</span> <span data-time ="4.130"> connect your personal devices to the internet inside your house.</span> <span data-time="7.535"> Well there are many ways to connect to the internet, and <span data-time="11.270"> most often people connect wirelessly.</span> </p> <p> <span data-time="13.960"> Let's look at an example of how you can connect to the internet.</span> <span data-time="17.940"> If you live in a city or a town, you probably have a coaxial cable for</span> <span data-time="22.370"> cable Internet, or a phone line if you have DSL, running to the outside of</span> <span data-time="26.880"> your house, that connects you to the Internet Service Provider, or ISP.</span> <span data-time="32.100"> If you live far out in the country, you'll more likely have</span> <span data-time="34.730"> a dish outside your house, connecting you wirelessly to your closest ISP, or</span> <span data-time="39.430"> you might also use the telephone system.</span> </p> <p> <span data-time="42.350"> Whether a wire comes straight from the ISP hookup outside your house, or</span> <span data-time="46.300"> it travels over radio waves from your roof,</span> <span data-time="49.270"> the first stop a wire will make once inside your house, is at your modem.</span> <span data-time="53.760"> A modem is what connects the internet to your network at home.</span> <span data-time="57.780"> A few common residential modems are DSL or</span> </p> </div> <script src="jquery-3.2.1.min"></script> <script src="mediaelementplayer/mediaelement-and-player.min.js"></script> <script src="main.js"></script> A: It's because of let scoping rules. From the JS MDN: function varTest() { var x = 1; if (true) { var x = 2; // same variable! console.log(x); // 2 } console.log(x); // 2 } function letTest() { let x = 1; if (true) { let x = 2; // different variable console.log(x); // 2 } console.log(x); // 1 } You can read more about this in this SO question: What's the difference between using “let” and “var” to declare a variable?
doc_23534158
pre : n >= 1 post : return S_n (recursive function) if n <= 2 return n; return 2 * func(n -1) + 3 * func (n -2); I think I got the height for the side of the tree that finishes first h = n/2. But I'm struggling to calculate the cost (the other element to calculate the lower bound for the runtime). Can someone please help me with this?
doc_23534159
<?php $age = '{"Peter":"Good", "Ben":37, "Joe":43}'; header('Content-Type: application/json'); sleep(5); echo $age; ?> When I call the API (http://<server_IP>:80/test.php) in postman, it returns the exact same php code back. When I run the php code on the server using php test.php, it gets compiled correctly and returns expected output. {"Peter":"Good", "Ben":37, "Joe":43} Why don't I get this output when the API is invoked? How can I resolve this?
doc_23534160
See the OK button in the lower right corner here: http://imgur.com/SZtIcHr I already tried android:fitsSystemWindows="true" but no success. Here is the relevant code in the ShowcaseView.java that I found: mEndButton = (Button) LayoutInflater.from(context).inflate(R.layout.showcase_button, null); (Warning: Avoid passing null as the view root (needed to resolve layout parameters on the inflated layout's root element)) [..] if (!mOptions.noButton && mEndButton.getParent() == null) { RelativeLayout.LayoutParams lps = (LayoutParams) generateDefaultLayoutParams(); lps.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); if (getConfigOptions().showcaseId==3) lps.addRule(RelativeLayout.ALIGN_PARENT_LEFT); else lps.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); int margin = ((Number) (metricScale * 12)).intValue(); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) // TODO: LOLLIPOP workaround lps.setMargins(margin, margin, margin, margin*5); else lps.setMargins(margin, margin, margin, margin); lps.height = LayoutParams.WRAP_CONTENT; lps.width = LayoutParams.WRAP_CONTENT; mEndButton.setLayoutParams(lps); mEndButton.setText(buttonText != null ? buttonText : getResources().getString(R.string.positive)); if (!hasCustomClickListener) mEndButton.setOnClickListener(this); addView(mEndButton); I don't know how to change this or how Android 5 / material design has caused this behaviour. I would be happy for a hint! :) A: For me works set manually the margin bottom without use the margin returned from the method to obtain int margin. RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); int margin = ((Number) (context.getResources().getDisplayMetrics().density * 12)).intValue(); layoutParams.setMargins(margin, margin, margin, 120); Hope it works... The problem has been fixed here... A: I found very easy fix for this in one of pull requests Add: <item name="android:windowDrawsSystemBarBackgrounds">false</item> to your style/theme in values-v21/styles.xml. Works well for me, checked on a real device - Nexus 5.
doc_23534161
But if I change the file (even if I just add one single space). I get this below error. Any idea why is this happening? { "errorMessage": "Cannot find module '/var/task/index'", "errorType": "Error", "stackTrace": [ "Function.Module._load (module.js:276:25)", "Module.require (module.js:353:17)", "require (internal/module.js:12:17)" ] } A: It happens because you have to named your main file as index.js, and it should contains the next code: exports.handler = (event, context, callback) => { callback(null, "Success")}; Probably, when you uploaded your file from GitHub, it had another name.
doc_23534162
var x=$('#x').text(); In my second .js I'm doing some handling on this var that ensure my text i'll have less char than max-length, here is: var limitMaxLength = function(element) { var maxLength = $(element).data("max-length"); if (maxLength) { $(element).on("keypress", function(event){ if (event.target.innerText.length > maxLength || event.keyCode === 13) { event.preventDefault(); } }); } }; So I having some issues on Firefox getting this error: [TypeError: event.target.innerText is undefined] In IE, Opera, Chrome and Safari my code works fine, i'm getting error only on Firefox. *Sorry for my bad english. A: innerText was a Microsoft Creation, left over from the days of old. Firefox decided not to support it in favour of the w3 compliant, textContent. However, IE8 & below do not support textContent, therefore, if you wish to support Legacy browsers, you're in a bit of a bind. var text = elem.textContent || elem.innerText; or elem.innerHTML // eww, but it works, eh? or, just ditch IE8 (easier said than done, especially at work) A: innerText is not supported in FF. You can fix the issue by using dynamic property names. At first, check which property is supported: var textContent = ('textContent' in document) ? 'textContent' : 'innerText'; Define textContent as a global variable (or within the outmost scope), then you can use it like this: var someText = elem[textContent]; This snippet gives you textContent if it's available, innerText otherwise. Notice also, that there's a small difference between these two properties. A live demo at jsFiddle. Though when you're using jQuery, why not just: $(event.target).text()
doc_23534163
(based on an excellent post: http://onehungrymind.com/build-better-angular-2-application-redux-ngrx/) There is an Angular component - container component (it contains behavior). It has a reference to a service which uses to load data. Component loads data. Once the data arrives there is an action dispatched to the store (in service) PAGE_LOADED. The component is subscribed to store for items: Component: @Component({ selector: 'list', templateUrl: './list.component.html' }) export class ListComponent { private list$: Observable; private items: Item[]; constructor(private client: RestClient, private store: Store) { this.list$ = this.store.select('items'); this.list$.subscribe( list => this.items = (list ? list : [])); this.client.loadItems(new PageInfo(0, 10)); // load first page on init, 10 items } onPageChanged(pageInfo: PageInfo) { this.store.dispatch({action: 'PAGE_CHANGED', payload: pageInfo}); this.client.loadList(pageInfo); // load next page } } And the service: @Injectable() export class RestClient { constructor(private http: HttpClient, private store: Store) {} public loadItems(pageInfo: PageInfo): void { this.http.get('items', {params: {page: pageInfo.page, itemsPerPage: page.size}}) .map(payload => ({ type: 'PAGE_LOADED', payload: payload })) .subscribe(action => this.store.dispatch(action)); } } The component has a child component - pagination presentational component (does not contain behavior, or reference to store - its Bootstrap implementation), that emmits page changes using Angular @Output() and EventEmitter. The parent component implements onPageChanged(pageInfo) function that receives the page changes events emitted by the child component. And now the question, or confusion: On page change new value has to be dispatched to store and new data has to be loaded. What should be done in onPageChange function: onPageChanged(pageInfo: PageInfo) { this.store.dispatch({action: 'PAGE_CHANGED', payload: pageInfo}); this.client.loadList(pageInfo); // load next page } * *paging has been changed so an action is dispatched to store: PAGE_CHANGED with PageInfo - current page a and page size *next page has to be loaded: so next step is to call the RestClient service for next page: this.client.loadList(pageInfo); This call in turn (asynchronously) dispatches a new action that next page has been loaded. In sum the page change in UI emitts two actions: - PAGE_CHANGE - PAGE_LOADED Is it correct that there are two actions dispatched on onPageChange action? Should these two be chained in sense that: store.select('pageInfo') .subscribe(pageInfo => this.client.loadList(pageInfo)); Or is there other and better solution to this issue? A: My solution is as bryan60 suggested, using ngrx effects library: onPageChanged(pageInfo: PageInfo) { this.store.dispatch({action: 'PAGE_CHANGED', payload: pageInfo}); } onPageChange dispatches action PAGE_CHANGED which updates store with new paging information. There is a side effect registered, that on PAGE_CHANGE loads a new page and asynchronously triggers LOAD_SUCCESS or LOAD_ERROR: @Effect() changePage$ = this.actions$ .ofType(applications.CHANGE_PAGE) .switchMap(action => this.client.loadItems(page, itemsPerPage) .map(payload => (new applications.LoadSuccessAction(payload))) // If request fails, dispatch failed action .catch(error => Observable.of(new applications.LoadErrorAction(error))) ); Rest client does not dispatch actions any more: @Injectable() export class RestClient { constructor(private http: HttpClient, private store: Store) {} public loadItems(pageInfo: PageInfo): Observable { return this.http.get('items', {params: {page: pageInfo.page, itemsPerPage: page.size}}); } } Register effects in app.module.ts: @NgModule({ imports: [ ... EffectsModule.run(ApplicationEffects), ...
doc_23534164
#define T2(x) M#x #define T1(x) T2(x) T1(xxx) Invocations: $ gcc t2.c -std=c11 -E -DM= | grep xxx -w "xxx" $ gcc t2.c -std=c11 -E -DM=1 | grep xxx -w 1"xxx" $ gcc t2.c -std=c11 -E -DM=L | grep xxx -w L "xxx" // <== why extra space ?? $ gcc t2.c -std=c11 -E -DM=K | grep xxx -w K "xxx" // <== why extra space ?? $ clang t2.c -std=c11 -E -DM= | grep xxx -w "xxx" $ clang t2.c -std=c11 -E -DM=1 | grep xxx -w 1"xxx" $ clang t2.c -std=c11 -E -DM=L | grep xxx -w L "xxx" // <== why extra space ?? $ clang t2.c -std=c11 -E -DM=K | grep xxx -w K"xxx" // <== why behavior for K is different from behavior for L ?? $ cl t2.c /std:c11 /E /DM= 2>&1 | grep xxx -w "xxx" $ cl t2.c /std:c11 /E /DM=1 2>&1 | grep xxx -w 1"xxx" $ cl t2.c /std:c11 /E /DM=L 2>&1 | grep xxx -w L "xxx" // <== why extra space ?? $ cl t2.c /std:c11 /E /DM=K 2>&1 | grep xxx -w K"xxx" // <== why behavior for K is different from behavior for L ?? Versions: $ gcc --version gcc (GCC) 10.2.0 clang --version clang version 11.0.1 Target: x86_64-pc-windows-msvc $ cl Microsoft (R) C/C++ Optimizing Compiler Version 19.28.29913 for x64 Please help to understand the behavior and the difference.
doc_23534165
but I have done everything. I have also set my gmail account to access third party apps. Now I don't understand where is the problem is. Exception in thread "main" javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted. Learn more at 535 5.7.8 https://support.google.com/mail/?p=BadCredentials d8sm6051763pfd.159 - gsmtp at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:965) at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:876) at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:780) at javax.mail.Service.connect(Service.java:388) at javax.mail.Service.connect(Service.java:246) at javax.mail.Service.connect(Service.java:195) at javax.mail.Transport.send0(Transport.java:254) at javax.mail.Transport.send(Transport.java:124) at com.mirajhossain.TransMail.sendMail(Main.java:37) at com.mirajhossain.Main.main(Main.java:52)][1] Here is my code. class TransMail{ public static void sendMail(String recepient) throws MessagingException { Properties properties=new Properties(); properties.put("mail.from","REDACTED"); properties.put(" mail.user","REDACTED"); properties.put(" mail.passr","REDACTED"); properties.put("mail.smtp.auth","true"); properties.put("mail.smtp.starttls.enable","true"); properties.put("mail.smtp.host","smtp.gmail.com"); properties.put("mail.smtp.ssl.trust", "smtp.gmail.com"); properties.put("mail.smtp.port","587"); String myAccount="miraj98hossain@gmail.com"; String pwd="69miraj69hossain69shawon69"; Session session= Session.getInstance(properties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(myAccount,pwd); } }); Message message= preparemessage(session,myAccount,recepient); Transport.send(message); System.out.println("yes"); } private static Message preparemessage(Session session, String myAccount,String recepient) throws MessagingException { Message message=new MimeMessage(session); message.setFrom(new InternetAddress(myAccount)); message.setRecipient(Message.RecipientType.TO,new InternetAddress(recepient)); message.setSubject("Verification"); message.setText("1254562"); return message; } } public class Main{ public static void main(String[] args) throws MessagingException { TransMail.sendMail("miraj09hossain@gmail.com"); } } A: Make sure you have to turn on less secure app access from your gmail account settings. public class Main { public static void main(String [] args) { // Sender's email ID needs to be mentioned String from = "test@gmail.com"; String pass ="xxxxxxx"; // Recipient's email ID needs to be mentioned. String to = "test313@gmail.com"; String host = "smtp.gmail.com"; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.host", host); properties.put("mail.smtp.user", from); properties.put("mail.smtp.password", pass); properties.put("mail.smtp.port", "587"); properties.put("mail.smtp.auth", "true"); // Get the default Session object. Session session = Session.getDefaultInstance(properties); int Vcode=(int)(10000+Math.random()*(20000-10000+1)); try{ // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject("Email Verification"); // Now set the actual message message.setText("Your verification code for our app is"+Vcode+".\n"+"Enter this code for complete your sign up process"); // Send message Transport transport = session.getTransport("smtp"); transport.connect(host, from, pass); transport.sendMessage(message, message.getAllRecipients()); transport.close(); System.out.println("Sent message successfully...."); }catch (MessagingException mex) { mex.printStackTrace(); } } } A: I am using JavaMail library. Look how it looks: Configure: JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost(host); // for example smtp.gmail.com mailSender.setPort(port); // 465 mailSender.setUsername(username); // your email mailSender.setPassword(password); // your password Properties properties = mailSender.getJavaMailProperties(); properties.setProperty("mail.transport.protocol", protocol); // smtps properties.setProperty("mail.debug", debug); // as you wish properties.setProperty("mail.smtp.auth", auth); // true properties.setProperty("mail.smtp.starttls.enable", enable); // true } Send message: private void send(String subject, String message) { SimpleMailMessage mailMessage = new SimpleMailMessage(); mailMessage.setFrom(emailFrom); mailMessage.setTo(emailTo); // receiver mailMessage.setSubject(subject); mailMessage.setText(message); mailSender.send(mailMessage); } Try this.
doc_23534166
This approach works fine on windows: var fullBuffer string for { // If we're not connected, attempt reconnect if this.conn == nil { if this.IsSecure() { this.conn, err = tls.Dial("tcp", this.GetHostOnly(), nil) } else { this.conn, err = net.Dial("tcp", this.GetHostOnly()) } if err == nil { // log and continue } } // Read from socket into our local buffer (blocking) if this.conn != nil { readBuff := make([]byte, 4096) nbytes, err = this.conn.Read(readBuff) if nbytes > 0 { fullBuffer += string(readBuff[0:nbytes]) } } Pretty straightforward - and it works fine on win64. But when i try to run it on Linux (debian 8 - both i386 and amd64 - both golang 1.5 native and 1.6 crosscompiled from windows) i get the following panic: panic: runtime error: invalid memory address or nil pointer dereference [signal 0xb code=0x1 addr=0x0 pc=0x4ec8b4] goroutine 8 [running]: panic(0x8237780, 0x18522030) C:/Go/src/runtime/panic.go:464 +0x326 crypto/tls.(*Conn).Handshake(0x0, 0x0, 0x0) C:/Go/src/crypto/tls/conn.go:1023 +0x198 crypto/tls.(*Conn).Read(0x0, 0x18597000, 0x1000, 0x1000, 0x0, 0x0, 0x0) C:/Go/src/crypto/tls/conn.go:922 +0x5e mylib.(*MyConnection).worker(0x18512480) C:/gopath/src/mylib/mylib.go:342 +0x200 The Read call is failing because it's somehow passing nil to the TLS handshake. What's going wrong here? And, why is the problem isolated to linux? A: OK, linux builds are producing the error x509: certificate signed by unknown authority. But * *the certificate is valid * *crypto/x509/root_unix.go looks in /etc/ssl/certs which is world-readable *but openssl s_client is hanging on -showcerts -verify, pointing to some issue with my OS network configuration *for some reason the if block below is being entered regardless of the error * *but i was storing it as a net.Conn instead of a pointer, so it's not nil-able. Calling this solved, sorry for the noise. Hopefully this debugging story helps someone else in the future
doc_23534167
A: As noted by my buddy Jonathan Stark, you should be able to use attributes like autocorrect and autocomplete to achieve the effect you're looking for: <input type="text" placeholder="My Field" name="myfield" autocapitalize="none" autocorrect="off" autocomplete="off" /> Just tested in OS4 and it's working. UPDATE: As of iOS5 on and off values in autocapitalize have been deprecated. Use none to completely disable automatic capitalization. A: Actually there is literally a spell check attribute in HTML5: <textarea spellcheck="false"> Re: http://blog.whatwg.org/the-road-to-html-5-spellchecking Browser support is, of course, limited.
doc_23534168
stripe.rb StripeEvent.configure do |events| # The case transfer created events.subscribe( 'payout.paid', Events::PayoutPaid.new ) end apps/services/events/payout_paid.rb class Events::PayoutPaid def call(event) source = event.data.object # Fetch balence information account = source.destination balance = Stripe::Balance.retrieve( {stripe_account: account} ) @user = User.find_by({ stripe_account_id: account }) @user.balance = balance["available"][0]["amount"] @user.save # create receipt @receipt = Receipt.new @receipt.user = @user @receipt.amount = source.amount @receipt.save end end Although other stripe webhook would work. A: That is because you havent loaded the signing secrets to StripeEvent Lest say you create 2 webhooks on the Stripe dashboard, one subscribed to invoices events, the other to customer events. You first need to copy each of the Signing secret (click on reveal) and then store them in the config/credentials.yml.enc file First, run the command EDITOR="atom --wait" rails credentials:edit (using the editor of your choosing). Then, add the following values: stripe: development: secret_key: MY_SECRET_KEY publishable_key: MY_PUBLISHABLE_KEY signing_secret_customer_endpoint: MY_SIGNING_SECRET_CUSTOMERS signing_secrets_invoice_endpoint: MY_SIGNING_SECRET_INVOICES Save the file. Now edit the initializer for stripeEvent. In my case, it was config/initializers/stripe.rb and add: StripeEvent.signing_secrets = [ Rails.application.credentials[:stripe][Rails.env.to_sym][:signing_secret_customer_endpoint], Rails.application.credentials[:stripe][Rails.env.to_sym][:signing_secrets_invoice_endpoint]] Now the signing secrets are loaded and the webhooks should work A: I was having the same problem, and the solution was to: * *log into Stripe *go to the page for the webhook that was failing *get the Signing secret from the middle of that page *and set an env VAR called STRIPE_SIGNING_SECRET with the Signing secret as its value. This is mentioned in the Stripe docs, here.
doc_23534169
var myVar1 = "Hello"; var myVar2 = true; When put it into object way, it will look like this: var globalVar = { myVar1: "Hello", myVar2: true } How can I declare a variable without assigning anything, e.g. var myVar3; in the object way? Thank you. A: How can I declare a variable without assigning anything, e.g. var myVar3; in the object way? You can't. But you can get the same result: var globalVar = { myVar1: undefined, myVar2: undefined }; When you declare a variable with var, the variable's initial value is undefined. So the above does the same for object properties. A: Using undefined is technically correct, but has little to no point, you'd be better off declaring the variable with a NULL consider this code: var obj = { oUn : undefined, oNull : null }; document.body.appendChild(document.createTextNode( typeof obj.oUn + ' ' + typeof obj.oNull + ' ' + typeof obj.doesNotExist )); Although yes, in FireBug, and maybe other debuggers (did not check) obj.oUn does come up, but if you try to check it within JS you get the same result as if its not even defined. (Note that the "typeof obj.doesNotExist" returned the same value as "typeof obj.oUn" although, it was not defined). Though that said if you check it within a for loop you do get it i.e. this will display the obj.Un var obj = { oUn : undefined, oNull : null }; document.body.appendChild(document.createTextNode( typeof obj.oUn + ' ' + typeof obj.oNull + ' ' + typeof obj.doesNotExist )); document.body.appendChild(document.createElement('br')); var name; for(name in obj) { document.body.appendChild(document.createTextNode(name)); document.body.appendChild(document.createElement('br')); } So I guess it depends on why you need it. By in large I would say if you do not need the name per say (i.e. your code already knows the name) then do not even declare it and simply use var globalVar = {}; You can always extend on it latter once you need it or if you need it, then use NULL, because you can actually check in JS if its in use by checking if the value is NULL or not. With undefined you'd have no way of knowing, because it does not differ at all from a value that is not in use and you'd need to make a cumbersome helper function in order to find out.
doc_23534170
Only my dataset is much larger with many more columns and rows. I can always make a unique ID for each data frame. I was thinking a loop but I'm not certain how to even begin with that. For example: Categorized Dataframe DOGS CATS BIRDS St. Bernard Tabby Robin Lab Siamese Humming Pitbull Hairless Blue Jay Numeric Dataframe DOGS CATS BIRDS 1 7 3 5 38 4 15 17 10 After containing or merging, I'd like to end up with DOGS DOGS St. Bernard 1 Lab 5 Pitbull 17 CATS BIRDS Tabby 7 Siamese 38 Hairless 17 BIRDS BIRDS Robin 3 Humming 4 Blue Jay 10 Thanks for your help! edit: I just realized I didn't make it clear thanks @Quang Hoang that I also need to be able to save each frame as separate tables like: DOGS_df = DOGS DOGS St. Bernard 1 Lab 5 Pitbull 17 CATS_df = CATS BIRDS Tabby 7 Siamese 38 Hairless 17 BIRDS_df = BIRDS BIRDS Robin 3 Humming 4 Blue Jay 10
doc_23534171
authors = [ %{name: "José", language: "Elixir"}, %{name: "Matz", language: "Ruby"}, %{name: "Larry", language: "Perl"} ] languages_with_an_r = fn (:get, collection, next_fn) -> for row <- collection do if String.contains?(row.language, "r") do next_fn.(row) end end end IO.inspect get_in(authors, [languages_with_an_r, :name]) #=> ["José", nil, "Larry"] I have some questions about the example: * *The function that you pass to get_in() is called by Elixir and the first argument that Elixir passes to the function is the atom :get. How is that useful? *The third argument that Elixir passes to the function is a function that gets bound to next_fn. Where in the docs does it say how many arguments that function takes? What does that function do? How are we supposed to use next_fn? It seems to me that the for construct is already iterating over each map in the list, so what does the name next_fn even mean? Is next_fn used to somehow tag a row for further consideration? *Where does nil in the result list come from? And, I'll say this: that example is one of the poorest examples I've seen in any programming book--because there's not adequate discussion of the example, and the docs for get_in() suck. That means there are at least three people who don't understand get_in(): me, Dave Thomas, and whoever wrote the docs--because if you can't explain something, then you don't understand it yourself. Edit: I found this in the source code: def get_in(data, [h | t]) when is_function(h), do: h.(:get, data, &get_in(&1, t)) What does &1 refer to there? data? Why not just use data, then? A: Well, I've been playing around in iex a bit: iex(13)> mymax = fn x -> &max(&1, x) end #Function<6.99386804/1 in :erl_eval.expr/5> iex(15)> max_versus_3 = mymax.(3) #Function<6.99386804/1 in :erl_eval.expr/5> iex(16)> max_versus_3.(4) 4 iex(17)> max_versus_3.(2) 3 It looks like the syntax &max(&1, 3) returns the anonymous function: fn (arg) -> max(&1, 3) and when x=3 in the surrounding scope, the syntax &max(&1, x) will also return the function: fn (arg) -> max(&1, 3) and &1 will become whatever single arg that the anonymous function is called with. In this example: authors = [ %{name: "José", language: "Elixir"}, %{name: "Matz", language: "Ruby"}, %{name: "Larry", language: "Perl"} ] languages_with_an_r = fn (:get, collection, next_fn) -> for row <- collection do if String.contains?(row.language, "r") do next_fn.(row) end end end IO.inspect get_in(authors, [languages_with_an_r, :name]) #=> ["José", nil, "Larry"] The call to get_in() here: IO.inspect get_in(authors, [languages_with_an_r, :name]) matches the following function definition in the source code: def get_in(data, [h | t]) when is_function(h), do: h.(:get, data, &get_in(&1, t)) which creates the following bindings: data = authors h = languages_with_an_r t = [:name] Then Elixir executes the body of the function and calls: h.(:get, data, &get_in(&1, t)) which is equivalent to: languages_with_an_r.( :get, authors, fn (arg) -> get_in(&1, [:name]) That creates the binding: next_fn = fn (arg) -> get_in(&1, [:name]) Therefore, in the authors example the line: next_fn.(row) is equivalent to calling: fn (row) -> get_in(&1, [:name]) which causes get_in() to execute with these arguments: get_in(row, [:name]) and that call to get_in() returns the value corresponding to the :name key in row. I think the authors example would be clearer if the parameter variables in the definition of languages_with_an_r() were renamed: languages_with_an_r = fn (:get, collection, search_for_next_key_in) -> for row <- collection do if String.contains?(row.language, "r") do search_for_next_key_in.(row) end end end That code will only search for the :name key in row if row.language contains an "r". Finally, the following snippet shows where nil comes from: iex(5)> for x <- [1, 2, 3] do ...(5)> if x == 1_000_000, do: x+1 ...(5)> end [nil, nil, nil] Like in Ruby, it appears that a do block in Elixir returns the value of the last expression that was evaluated. And, when a do block doesn't evaluate an expression, then the do block returns nil by default. Therefore, if row.language does not contain an "r", then the if statement is skipped, and the do block doesn't evaluate any expressions, so by default the do block returns nil.
doc_23534172
In linux there is the file '/proc/mounts' which displays the mounted drives with the type of partition and the mount options, in mac OS is there something similar? In linux I use it like this: #!/usr/bin/env python3 # -*- coding: UTF-8 -*- from pathlib import Path import getpass def get_lst_writable_linux_disks(): this_user = getpass.getuser() lst_available_linux_disks = [str(Path.home())] with open('/proc/mounts','r') as f: data = f.readlines() for line in data: item = line.split(' ') mount_point = item[1] fs_type = item[2] options = item[3] if mount_point.startswith('/mnt') or (mount_point.startswith(f'/media/{this_user}') and fs_type != 'vfat' and 'rw' in options): lst_available_linux_disks.append(mount_point) return lst_available_linux_disks print(get_lst_writable_linux_disks()) How would I do the same on Mac OS? A: For a more bullet-proof method than parsing the human-readable output of diskutil info -all, you could do something like this... (I don't quite like Apple's XML plist format; you'd think there was a better way to represent a dict than a flat key-value-key-value-... structure...) import subprocess import xml.etree.ElementTree as ET from typing import Tuple, List, Dict def plist_dict_to_dict(node: ET.Element) -> Dict[str, ET.Element]: assert node.tag == "dict" dct = {} current_key = None for i, el in enumerate(node): if i % 2 == 0: assert el.tag == "key" current_key = el.text else: assert current_key dct[current_key] = el return dct def get_volume_names() -> List[str]: command = ["/usr/sbin/diskutil", "list", "-plist"] volumes_xml = ET.fromstring(subprocess.check_output(command, encoding="utf-8")) volumes_info = plist_dict_to_dict(volumes_xml.find("dict")) vfd_array = volumes_info["VolumesFromDisks"] assert vfd_array.tag == "array" return [v.text for v in vfd_array.findall("string")] def get_volume_info(volume_name: str) -> Dict[str, ET.Element]: command = ["/usr/sbin/diskutil", "info", "-plist", volume_name] vol_info_xml = ET.fromstring(subprocess.check_output(command, encoding="utf-8")) return plist_dict_to_dict(vol_info_xml.find("dict")) def get_volume_flags(volume_name: str) -> Dict[str, bool]: vol_info = get_volume_info(volume_name) flags = {} for key, value in vol_info.items(): if value.tag in ("true", "false"): flags[key] = value.tag == "true" return flags if __name__ == "__main__": for volume_name in get_volume_names(): print(volume_name, ":", get_volume_flags(volume_name)) On my machine, this prints out Volume Macintosh HD : {'AESHardware': True, 'Bootable': True, 'CanBeMadeBootable': False, 'CanBeMadeBootableRequiresDestroy': False, 'Ejectable': False, 'EjectableMediaAutomaticUnderSoftwareControl': False, 'EjectableOnly': False, 'Encryption': True, 'FileVault': True, 'Fusion': False, 'GlobalPermissionsEnabled': True, 'Internal': True, 'Locked': False, 'PartitionMapPartition': False, 'RAIDMaster': False, 'RAIDSlice': False, 'Removable': False, 'RemovableMedia': False, 'RemovableMediaOrExternalDevice': False, 'SolidState': True, 'SupportsGlobalPermissionsDisable': True, 'SystemImage': False, 'WholeDisk': False, 'Writable': False, 'WritableMedia': True, 'WritableVolume': False} Volume Macintosh HD - Data : {'AESHardware': True, 'Bootable': True, 'CanBeMadeBootable': False, 'CanBeMadeBootableRequiresDestroy': False, 'Ejectable': False, 'EjectableMediaAutomaticUnderSoftwareControl': False, 'EjectableOnly': False, 'Encryption': True, 'FileVault': True, 'Fusion': False, 'GlobalPermissionsEnabled': True, 'Internal': True, 'Locked': False, 'PartitionMapPartition': False, 'RAIDMaster': False, 'RAIDSlice': False, 'Removable': False, 'RemovableMedia': False, 'RemovableMediaOrExternalDevice': False, 'SolidState': True, 'SupportsGlobalPermissionsDisable': True, 'SystemImage': False, 'WholeDisk': False, 'Writable': True, 'WritableMedia': True, 'WritableVolume': True} Volume Recovery : {'AESHardware': True, 'Bootable': False, 'CanBeMadeBootable': False, 'CanBeMadeBootableRequiresDestroy': False, 'Ejectable': False, 'EjectableMediaAutomaticUnderSoftwareControl': False, 'EjectableOnly': False, 'Encryption': False, 'FileVault': False, 'Fusion': False, 'GlobalPermissionsEnabled': True, 'Internal': True, 'Locked': False, 'PartitionMapPartition': False, 'RAIDMaster': False, 'RAIDSlice': False, 'Removable': False, 'RemovableMedia': False, 'RemovableMediaOrExternalDevice': False, 'SolidState': True, 'SupportsGlobalPermissionsDisable': True, 'SystemImage': False, 'WholeDisk': False, 'Writable': True, 'WritableMedia': True, 'WritableVolume': True} Volume VM : {'AESHardware': True, 'Bootable': False, 'CanBeMadeBootable': False, 'CanBeMadeBootableRequiresDestroy': False, 'Ejectable': False, 'EjectableMediaAutomaticUnderSoftwareControl': False, 'EjectableOnly': False, 'Encryption': True, 'FileVault': False, 'Fusion': False, 'GlobalPermissionsEnabled': True, 'Internal': True, 'Locked': False, 'PartitionMapPartition': False, 'RAIDMaster': False, 'RAIDSlice': False, 'Removable': False, 'RemovableMedia': False, 'RemovableMediaOrExternalDevice': False, 'SolidState': True, 'SupportsGlobalPermissionsDisable': True, 'SystemImage': False, 'WholeDisk': False, 'Writable': True, 'WritableMedia': True, 'WritableVolume': True} so besides "Writable" you will probably want to look at "Internal"...
doc_23534173
Here's my graph: The open char tag of above chart: <chart caption='' palette='2' animation='1' showValues='0' formatNumberScale='0' numberPrefix='' slantLabels='1' showLabels='1' rotateValues='0' placeValuesInside='0' labelDisplay='ROTATE' seriesNameInToolTip='1' anchorBorderColor='339966' decimalSeparator=',' thousandSeparator='.' syAxisMaxValue='$maximo' pyAxisMaxValue='$maximo'> A chart with the correct align I am after: And it's chart tag: <chart caption='' PYAxisName='Quantidade' SYAxisName='Valores (Em R$/Mil)' palette='2' animation='1' showValues='0' formatNumberScale='0' numberPrefix='' slantLabels='1' showLabels='1' rotateValues='0' placeValuesInside='0' labelDisplay='ROTATE' seriesNameInToolTip='1' anchorBorderColor='FFFF33' decimalSeparator=',' thousandSeparator='.' baseFontSize='8'>` They are almost the same! A: Seems you have a blank <dataset> in your data. Please check. The anchors aligns to the center. If you have 2 column datasets of which one is blank or invisible, the anchors would be aligned to the center of these possible columns and hence this.
doc_23534174
I have column A filled with 10 names, column B filled with numbers that range from 1 to 3, and a folder with 10 text files that have numbers as names (from 1 to 10). I need to create a text file for each name in the A column that considers the value in B column with text from the text files. The text files content contains 3 different lines: 1content1 2content2 3content3 For the first name if the value in column b same row is 1 the newly created text file would need to contain only the first row of the first text file (1): "1content1" and so on. Is this possible? How would I go about it. Thank you! A: I am assuming your data is as in the image below. Here, * *Column A contains the file name to be created *Column B has the line number ranging from 1 to 3 Few things for consideration: * *As you said mentioned that you already have 10 text files in a folder having names 1 to 10, I am picking those files for each row in data. For example row 1 will create a new file by name File_A where data will be Line no. 1 of file with name 1.txtin your specified folder. Then for row 2 new file by name File_B will be created where data will be Line no. 2 of file with name 2.txt and so on.(I guess this is clear) *Code will save newly created file in the same folder where you 10 files are already saved. Sub CreateTextFile() Dim hf As Integer: hf = FreeFile Dim lines() As String Dim i As Long, LastRow As Long, FileLine As Long, LineNum As Long, lineCntr As Long Dim FileName As String, FilePath As String Dim ws As Worksheet Dim fso As Object, oFile As Object Set fso = CreateObject("Scripting.FileSystemObject") Set ws = ThisWorkbook.Worksheets("Sheet1") '---->change Sheet1 to your worksheet name FilePath = "C:\test_folder\" '---->change filepath as required LastRow = Cells(Rows.Count, "A").End(xlUp).Row For i = 1 To LastRow FileName = FilePath & i & ".txt" LineNum = ws.Cells(i, 2).Value 'reading text file line by line Open FileName For Input As #hf lines = Split(Input$(LOF(hf), #hf), vbNewLine) Close #hf 'writing particular line to new text file For lineCntr = 0 To UBound(lines) If lineCntr + 1 = LineNum Then Set oFile = fso.CreateTextFile(FilePath & ws.Cells(i, 1) & ".txt") oFile.WriteLine lines(lineCntr) oFile.Close End If Next lineCntr Next i Set fso = Nothing Set oFile = Nothing End Sub Let me know if anything is not clear.
doc_23534175
gcc -S b.c gcc -c b.c gcc b.o -o b My question is, how to specify inside scons SConstruct, with all these steps, to make sure I get b.s, b.o and 'b' executable? Seems scons only support functions like Program, Object, Library, so I only get b.o and 'b'. But how to make out 'b.s', while I don't wish to introduce any duplicated work by the compiler(to save time). Thanks.
doc_23534176
Now I've wanted to add asterisk as input possibility like python myPythonScript.py -i folder/* If I print the the argument to option -i right when I access it the first time I get folder/firstFileInFolder.txt But if I call my script with python myPythonScript.py -i someFolder/someFile,folder/* it works just fine. Does anyone have an idea, why python might behave that way? A: Try to run this script import sys for arg in sys.argv: print arg python script.py * your shell expands the asterisk before python sees it. A: As mentioned in the comments, your shell is expanding the asterisk for the non-comma separated case. If you know that the user may specify an asterisk as part of a file name as in your second example, you can have Python do the path expansion by using the glob module. from glob import glob glob('*') code which would allow either the shell or Python to do asterisk expansion may look something like this: import glob file_list = [] for pattern in sys.argv[1:]: file_list.extend(glob.glob(pattern)) In your case, using a comma as a separator would then prevent you from using a comma as part of a filename.
doc_23534177
first, i scan the barcode then put it on a list. using this Future _scanQR() async { try { String barcode = await BarcodeScanner.scan(); setState(() { this.barcode = barcode; list.insert( 0, barcode, ); }); } on PlatformException catch (ex) { if (ex.code == BarcodeScanner.CameraAccessDenied) { setState(() { this.barcode = 'The user did not grant the camera permission!'; }); } else { setState(() { this.barcode = "Unknown Error $ex"; }); } } on FormatException { setState(() { this.barcode = "You pressed the back button before scanning anything"; }); } catch (ex) { setState(() { this.barcode = "Unknown Error $ex"; }); } } then, print the list using this: Expanded( child: ListView.builder( padding: const EdgeInsets.all(8), itemCount: list.length, itemBuilder: (BuildContext context, int index) { return Container( height: 50.0, margin: EdgeInsets.all(2), child: Center( child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Text('${list[index]}'), TextButton( onPressed: () { getInfo(); }, child: Text("Get Info"), ), ], see here, that the list is being generated with the "get info" in each result. example is, i scanned two barcodes. 4912548796616 and 8998666001719 so they are inserted in the "list" List. when i print "list" my output is: I/flutter (16927): [4912548796616, 8998666001719], so that means our list creation is working, now my question is, how can i get them individually? i tried creating a "getInfo()" to print them but it only shows the latest barcode that i scanned. i hope you can help me. thanks! this is my getInfo function, i am readying it up to have a query, to get the full info attached to the barcode. this is the one that is not working, as it only prints the latest barcode scanned. Future<List> getInfo() async { print(this.barcode); } A: Thanks craig for the answer.. so i changed the Future<List> getInfo() async { print(this.barcode); } to this Future<List> getInfo(index) async { print(list[index]); }
doc_23534178
class x(model.Models): name = models.CharField(max_length=50, unique=True) y = models.ManyToManyField(Y, related_name='y', db_table='x_y', blank=False,null=False) and this serializer: class Serializer(DynamicFieldsModelSerializer): class Meta: model = models.x fields = '__all__' when I post data to this model I need to set this fields: 'name':['some name'],'y':['1','2'] this will make a row in database x with: id | name 1 | some name and two row in database x_y with: id| x_id | y_id 1 | 1 | 1 2 | 1 | 2 the problem is that front end dose not send me 'name' and 'y' ,but send me 'name' and 'y[]', so in order to get data I needed to add this to my serializer class: y= serializers.DictField(child=serializers.IntegerField(min_value=0, max_value=2)) but the result is that no data will save in x_y table.I dont know how to solve this A: One issue that stands out to me is that you're using a DictField to handle a list of integers. Presuming the integers are actually the primary key of your Y model, have you tried using y = PrimaryKeyRelatedField(many=True)? This seems like what you would be after.
doc_23534179
This is the code I would like to implement this into, so that on the far right of each listview item I can press an icon button and execute the aforementioned code. If anyone has any ideas on how to achieve this, I would be grateful for any advice. Widget _cryptoWidget() { return new Container( child: new Column( children: <Widget>[ new Flexible( child: new ListView.builder( itemCount: _currencies.length, itemBuilder: (BuildContext context, int index) { final int i = index ~/ 2; final Crypto currency = _currencies[i]; final MaterialColor color = _colors[i % _colors.length]; if (index.isOdd) { return new Divider(); } return _getListItemUi(currency, color); }, ), ) ], ) ); } Thank you for your time. Edit: ListTile _getListItemUi(Crypto currency, MaterialColor color) { return new ListTile( leading: new Image.network("http://cryptoicons.co/32@2x/color/"+currency.symbol.toLowerCase()+"@2x.png"), title: new Text(currency.name, style: new TextStyle(fontWeight: FontWeight.bold)), subtitle: _getSubtitleText(currency.price_usd, currency.percent_change_1h), isThreeLine: true, ); } Second Edit: Widget _getSaveValueButton() { new IconButton( icon: new Icon(Icons.add), onPressed: () { Directory appDocDir = await getApplicationDocumentsDirectory(); String appDocPath = appDocDir.path; new File('$appDocPath/my_file.txt').writeAsStringSync('myVar: $_currencies'); } A: You can use https://pub.dartlang.org/packages/path_provider to get a temp or app docs directory and then just create a file there String someVal = 'some value to write to the file'; Directory appDocDir = await getApplicationDocumentsDirectory(); String appDocPath = appDocDir.path; new File('$appDocPath/my_file.txt').writeAsStringSync('myVar: $someVal');
doc_23534180
Cheers Nik A: Annotations / EntityManager will be bundled with Hibernate Core 3.5.x release; either beta1 does not clarify as release or somehow it got screwed up but it does NOT contain annotations or EntityManager. You'll need to download them separately: * *Hibernate Annotations 3.4.0.GA *Hibernate Entity Manager 3.4.0.GA and add appropriate JARs to your classpath. A: I think you need the hibernate-annotations jar I did with 3.2.1 so perhaps you need it with 3.5-beta1 too A: Hibernate allows to keep foreign key name. Hibernate overrides the foreign key name by @ForeignKey. It has the attribute name that should be defined. @Entity @Table(name = "state") public class State { @Id @Column(name = "id") private int id; @Column(name = "name") private String name; @ManyToOne @ForeignKey(name="FK_COUNTRY") private Country country; }
doc_23534181
Example 1 -- highlight the whole enchilada, including both variables: {\code_one*[variable_one]{variable_two}} Example 2 -- highlight the whole enchilada, less either or both variables: {\code_two*[variable_three]{variable_four}} A: include_variable_text -- e.g., \hspace*{3.45in}; \begin{singlespace*}; \end{document}. .tmLanguage <!-- BEGIN include_variable_text --> <dict> <key>begin</key> <string>\\makebox\[|\\hspace\*\{|\\begin\{|\\end\{</string> <key>beginCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>lawlist.include_variable_text.begin.latex</string> </dict> </dict> <key>end</key> <string>\}|\]</string> <key>endCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>lawlist.include_variable_text.end.latex</string> </dict> </dict> <key>name</key> <string>lawlist.include_variable_text.latex</string> <key>patterns</key> <array> <dict> <key>include</key> <string>$base</string> </dict> </array> </dict> <!-- END --> tm.Theme <!-- BEGIN lawlist.include_variable_text --> <dict> <key>name</key> <string>Grayed-Out</string> <key>scope</key> <string>lawlist.include_variable_text.latex</string> <key>settings</key> <dict> <key>fontStyle</key> <string>italic</string> <key>foreground</key> <string>#E3E3E3</string> <key>background</key> <string>#FFFFFF</string> </dict> </dict> <!-- END --> exclude_variable_text {\bf\uline{excluded_variable_text}} .tmLanguage -- This code contains an extra three (3) keys for future use -- e.g., [anything] <!-- BEGIN exclude_text --> <dict> <key>match</key> <string>(?=\s)(?&lt;=\\[\w@]|\\[\w@]{2}|\\[\w@]{3}|\\[\w@]{4}|\\[\w@]{5}|\\[\w@]{6})\s</string> <key>name</key> <string>meta.space-after-command.latex</string> </dict> <dict> <key>begin</key> <string>((\{\\bf)(?:\\uline|code_two|code_three))(?:(\[)([^\]]*)(\]))?(\{)</string> <key>beginCaptures</key> <dict> <key>1</key> <dict> <key>name</key> <string>lawlist.base.latex</string> </dict> <key>2</key> <dict> <key>name</key> <string>lawlist.prefix.latex</string> </dict> <key>3</key> <dict> <key>name</key> <string>lawlist.open_square_bracket.latex</string> </dict> <key>4</key> <dict> <key>name</key> <string>lawlist.first_variable.latex</string> </dict> <key>5</key> <dict> <key>name</key> <string>lawlist.close_square_bracket.latex</string> </dict> <key>6</key> <dict> <key>name</key> <string>lawlist.open_wavy_bracket.latex</string> </dict> </dict> <key>contentName</key> <string>lawlist.second_variable.latex</string> <key>end</key> <string>\}\}</string> <key>endCaptures</key> <dict> <key>0</key> <dict> <key>name</key> <string>lawlist_close_wavy_bracket.latex</string> </dict> </dict> <key>name</key> <string>lawlist.whole_enchilada.latex</string> <key>patterns</key> <array> <dict> <key>include</key> <string>$self</string> </dict> </array> </dict> <!-- END exclude_text --> *.tmTheme <!-- BEGIN strong blue #0000FF -- uline exclude_text --> <dict> <key>name</key> <string>Bold / Underline</string> <key>scope</key> <string>lawlist.base.latex|lawlist.open_square_bracket.latex|lawlist.first_variable.latex|lawlist.close_square_bracket.latex|lawlist.pen_wavy_bracket.latex|lawlist_close_wavy_bracket.latex</string> <key>settings</key> <dict> <key>fontStyle</key> <string></string> <key>foreground</key> <string>#E3E3E3</string> </dict> </dict> <!-- END -->
doc_23534182
I am still developing the app locally. I have been running grunt sass and watch to minify the scss file to css as I'm working on it. However, I've set the static url, etc to be my Amazon S3 bucket. This means when I run collectstatic, I have to wait ages for it to upload to S3 so I can see my changes. I am wanting to eventually deploy this to Heroku, but in the meantime, how do I set my static content to work locally and setup production settings to use S3? This is in settings.py: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.6/howto/static-files/ STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage' AWS_ACCESS_KEY_ID = 'XXXXXXXXXXXXXX' AWS_SECRET_ACCESS_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx' AWS_STORAGE_BUCKET_NAME = 'ingledow' STATIC_URL = 'http://ingledow.s3.amazonaws.com/' A: You could mess with the DEBUG settings. In local development, set DEBUG to True, and Django will handle serving all the static files. Once you push to production, set DEBUG to False and the S3 settings will kick in. You could have different settings files or you could set an environment variable both locally and on Heroku and call it in your settings (i.e.: `DEBUG = os.environ['DEBUG']. A: In your bashrc, set a environment flag: alias DJANGO_ENV=local (Alternatively, just do this in your local shell: export DJANGO_ENV=local) Then in settings.py: import os if os.environ.get( 'DJANGO_ENV', '' ) == 'local': # SETUP LOCAL SETTINGS else: STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage' AWS_ACCESS_KEY_ID = 'XXXXXXXXXXXXXX' AWS_SECRET_ACCESS_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx' AWS_STORAGE_BUCKET_NAME = 'ingledow' STATIC_URL = 'http://ingledow.s3.amazonaws.com/' Turn off the local settings when doing pushstatic (eg. "unset DJANGO_ENV"). On production (ie. Heroku), you won't have the DJANGO_ENV system variable, so it will default to AWS files.
doc_23534183
A: Performance. Consider this tiny benchmark: #lang racket/base (require racket/sequence) (define len 10000) (define vec (make-vector len)) (collect-garbage) (collect-garbage) (collect-garbage) (time (void (for/list ([i (in-range len)]) (vector-ref vec i)))) (collect-garbage) (collect-garbage) (collect-garbage) (time (void (for/list ([i (in-range len)]) (sequence-ref vec i)))) This is the output on my machine: ; vectors (vector-ref vs sequence-ref) cpu time: 1 real time: 1 gc time: 0 cpu time: 2082 real time: 2081 gc time: 0 Yes, that’s a difference of 3 orders of magnitude. Why? Well, racket/sequence is not a terribly “smart” API, and even though vectors are random access, sequence-ref is not. Combined with the ability of the Racket optimizer to heavily optimize primitive operations, the sequence API is a pretty poor interface. Of course, this is a little unfair, because vectors are random access while things like lists are not. However, performing the exact same test as the one above but using lists instead of vectors still yields a pretty grim result: ; lists (list-ref vs sequence-ref) cpu time: 113 real time: 113 gc time: 0 cpu time: 1733 real time: 1732 gc time: 0 The sequence API is slow, mostly because of a high level of indirection. Now, performance alone is not a reason to reject an API outright, since there are concrete advantages to working at a higher level of abstraction. That said, I think the sequence API is not a good abstraction, because it: * *…is needlessly stateful in its implementation, which puts an unnecessary burden on implementors of the interface. *…does not accommodate things that do not resemble lists, such as random-access vectors or hash tables. If you want to work with a higher level API, one possible option is to use the collections package, which attempts to provide an API similar to racket/sequence, but accommodating more kinds of data structures and also having a more complete set of functions. Disclaimer: I am the author of the collections package. Given the above benchmark once more, the performance is still worse than using the underlying functions directly, but it’s at least a bit more manageable: ; vectors (vector-ref vs ref) cpu time: 2 real time: 1 gc time: 0 cpu time: 97 real time: 98 gc time: 10 ; lists (list-ref vs ref) cpu time: 104 real time: 103 gc time: 0 cpu time: 481 real time: 482 gc time: 0 Whether or not you can afford the overhead depends on what exactly you’re doing, and it’s up to you to make the call for yourself. The specialized operations will always be at least somewhat faster than the ones that defer to them as long as some sort of dynamic dispatch is being performed. As always, remember the rule of performance optimization: don’t guess, measure.
doc_23534184
import MainScene from "./main-scene.js"; import MainScene2 from "./main-scene2.js"; let config = { type: Phaser.AUTO, width: 1280, height: 720, backgroundColor: "#000c1f", parent: "game-container", scene: [MainScene, MainScene2], pixelArt: true, physics: { default: "matter" }, plugins: { scene: [ { plugin: PhaserMatterCollisionPlugin, // The plugin class key: "matterCollision", // Where to store in Scene.Systems, e.g. scene.sys.matterCollision mapping: "matterCollision" // Where to store in the Scene, e.g. scene.matterCollision } ] } }; let game = new Phaser.Game(config); The two scenes begin like this: export default class MainScene extends Phaser.Scene And export default class MainScene2 extends Phaser.Scene and at the end of the MainScene scene there is the code that triggers the scene transition: if(this.player.sprite.x > 15400){ this.scene.start(MainScene2); } The problem that I find myself into is that when I try to run the game it shows a black screen saying: Uncaught Error: Cannot add a Scene with duplicate key: default So I've tried removing the default in the second scene, then receiving the error: Uncaught SyntaxError: The requested module './main-scene2.js' does not provide an export named 'default' I've tried searching all the scenes tutorials on the phaser labs example page (https://labs.phaser.io/index.html?dir=&q=) but all of them don't show a default in the scene code. I've tried to read again the first tutorial that I used as a framework as he wrote the export code that I've used in the game but he doesn't say how can I add another level as a scene or how to not use the default export, which I've seen in other codes online but never fully understood. I even tried to merge all the three .js files together so putting the two scenes & the config file in the same file, but the error was the same. I'm sure that the two scenes work fine when they are played alone, I just don't know how to connect them as first and second level. I'm sure that the answer is really stupid and I'm doing something really wrong but I've tried searching a lot online but finding nothing similiar to this. It's the first time I write a question here so I'm not sure if I'm giving enough informations, so I'm linking three code sandbox links here; the first one has the index.html and index.js to make only the first level work, the second one makes the second level work and the third one is the way that I tried to connect the two levels: 1: https://codesandbox.io/s/xv42ww7joo 2: https://codesandbox.io/s/l9zr5yqm49 3: https://codesandbox.io/s/2p22o6rnly Thank you so much for your help in advance, it's only been a month or so since I've been using phaser and I'm having a hard time understanding some things, but since now I've always found an answer online but this has been troubling me for some time and I've found nothing. A: You need to add a constructor to both scenes and call super with a key name. So in MainScene it will be constructor() { super("main"); } In MainScene2 it will be constructor() { super("main2"); } A: What tontheman answered is correct. Just want to add to that if you want to extend a Phaser.Scene you need to either pass a string as the key or an Object as the config. You can refer to Phaser 3 API Documentation - Class:Scene for more guidance.
doc_23534185
int zero = 0; int oneA = zero++; // Compiles int oneB = 0++; // Doesn't compile int oneC = getInt()++; // Doesn't compile } private int getInt(){ return 0; } They are all int's, why won't B & C compile? Is it to do with the way ++ operator differs from = 0 + 1;? Invalid argument to operation ++/-- A: Both B and C make the compiler say: unexpected type, required: variable, found: value So you can't increment a value, only a variable. A: Why doesn't the post increment operator work on a method that returns an int? Because it is a getter method, and it doesn't make sense to change a value via getter. int z = x + y++; is equivalent to: int z = x + y; y = y + 1; so it is not valid to have something like: int z = x + getY()++; which is equivalent to: int z = x + getY(); getY() = getY() + 1; // invalid! A: 0++ It is equivalent to 0 = 0 + 1; and certainly it is not possible. i.e. it has to be l-value to assign to it. getInt()++; Similar reason here. A: Because as stated in JLS: The result of the postfix expression must be a variable of a type that is convertible (§5.1.8) to a numeric type, or a compile-time error occurs. A: Because 0 is a rValue (i.e. You can use it only from right of the assignment operator) not a lValue. ++ operator increments the value and sets it to itself therefore 0++ will give You an error. A: i++ is an assignment to a variable i. In your case, zero++ is an equivalent to zero = zero + 1. So 0++ would mean 0 = 0 + 1, which makes no sense, as well as getInt() = getInt() + 1. More accurately : int oneA = zero++; means int oneA = zero; zero = zero + 1; // OK, oneA == 0, zero == 1 int oneB = 0++; means int oneB = 0; 0 = 0 + 1; // wrong, can't assign value to a value. int oneC = getInt()++; means int oneC = getInt(); getInt() = getInt() + 1; // wrong, can't assign value to a method return value. From a more general point of view, a variable is a L-value, meaning that it refers to a memory location, and can therefore be assigned. L in L-value stands for left side of the assignment operator (i.e. =), even if L-values can be found either on the left side or the right side of the assignment operator (x = y for instance). The opposite is R-value (R stands for right side of the assignment operator). R-values can be used only on the right side of assignment statements, to assign something to a L-value. Typically, R-values are literals (numbers, characters strings...) and methods. A: getInt() is not int getInt() returns int ++ operator does two things increment + assignment So for ++ operator to work you need a variable to store the result of increment operation which 0 and getInt() both are not. A: The pre- and post- operators only operate on variables or lvalues as they are called. lvalue is short for left value, i.e. something that can stand to the left in an assignment. In your example: zero = 1; // OK 0 = 1; // Meaningless getInt() = 1; // Also meaningless //jk A: My answer its kind of "out of the box". When I have doubt about an operator usage, I think "which its the overloaded function equivalent" of this operator ? I, know, that Java operators doesn't have operator overloading, its just an alternative way to make a solution. In this case: ... x++; ... should be read as: ... int /* function */ postincrement (/* ref */ int avalue) { int Result = avalue; // reference value, avalue = avalue + 1; return Result; } ... postincrement(/* ref */ x); ... And: ... ++x; ... ... int /* function */ preincrement (/* ref */ int avalue) { // reference value, avalue = avalue + 1; int Result = avalue; return Result; } ... preincrement(/* ref */ x); ... So, both, versions of "++", work as a function that receives a variable parameter by reference. So, a literal value like "0++" or a function result like "getInt()++", are not a variable references. Cheers. A: postincrement and preincrement can apply only with the help of variable.So the first case compile. A: Since function return is RHS expression and pre/post increment/decrement operations can be applied to LHS expressions only.
doc_23534186
Consider this Python3 code: import mysql.connector as mc connection = mc.connect (host = db_host, user = db_user, passwd = db_password, db = db_name) cursor = connection.cursor() cursor.execute("SELECT * FROM veryLongTable;") result = cursor.fetchall() cursor.close() connection.close() The whole thing spends a few seconds in the execute line and a few minutes in the fetchall line. What is happening there after all? Is the DB server executing the query and transmitting the "raw" result to me in execute and doing nothing at the fetchall (and the latter is just "read the result I got from the server"), or is it storing the result and only transmitting it when I call fetchall? Or is the query just "prepared" in execute and almost all work is done in fetchall? A: execute executes the query on the server and returns an iterator. fetchall returns the rows. The server returns an iterator and stores it in the cursor with execute. Then the server returns multiple rows with fetchall. Both operations require a connection to the server. Almost all work is done in execute. The statement is executed and the data is prepared on the server to be fetched by the client. With fetchall the cursor iterates over the list of prepared rows and transfers them multiple of them at a time to the client. "or is it storing the result and only transmitting it when I call fetchall" Yes, this is how it works.
doc_23534187
I am in need of help. It has been a painful weekend. I have been trying to look for good articles on how to do testing on controllers using MVC contrib. And no one has any decent answers for me. I want to know what do I need to test on a view and in controllers? Is this unit testing or integration testing? Let me describe my basic scenario: I have an Index view that has a grid on it. In this grid I have a list of news items. In this grid, in the last column of every row, is an Edit link that takes the user to the EditNews view to edit the selected news item. Also on this Index view is an Add News button that takes the user to the CreateNews view. Now given the current scenario, what tests do I need to write? Could you guys please also indicate if they are unit tests or integration tests. Do I need to write a test for the Edit link? Do I need to write a test for the Add News button? Do I need to write a test to check if the user is allowed on this Index page? This is what I currently have: [Test] public void Index_Should_Redirect_To_Error_View_When_User_Does_Not_Have_Permission() { } [Test] public void Index_Should_Log_Exception_When_User_Does_Not_Have_Permission() { } [Test] public void Index_Should_Return_Default_View() { // Act var result = newsController.Index(); // Assert result .AssertViewRendered() .ForView("Index"); } UPDATED: Here is my Index action method: public ActionResult Index() { IEnumerable<News> news = newsRepository.FindAll(); return View(news); } Any decent articles or sample code would be appreciated. Also on MVC contrib, the code samples aren't of much use. I would like to hear as much opinions as possible. Thanks. A: You need to make the distinction between unit tests, integration tests and web tests. Unit tests are for testing different components of your code such as controller actions in isolation. Integration tests are for testing the integration between your code and external components such as a repository which reads and writes data from a database and a web test is for testing an entire user scenario of your application such as the user typing some address in the address bar of his browser, clicking on some button, ... MVCContrib.TestHelper and Rhino Mocks are intended to simplify your unit tests. So in your scenario you should test your Index controller action. Without showing the code this controller action contains it is difficult to say what exactly do you need to test. In general what you could unit test in a controller action is that it validates the input, calls the proper methods on the repository and according to the results it returns the proper view. So let's suppose that you have the following Index action you are willing to test: public class HomeController: Controller { private readony INewRepository _repository; public HomeController(INewRepository repository) { _repository = repository; } public ActionResult Index() { var news = _repository.GetNews(); return View(news); } } And the corresponding unit test: [TestClass] public class HomeControllerTests : TestControllerBuilder { private HomeController _sut; private INewsRepository _repositoryStub; [TestInitialize()] public void MyTestInitialize() { _repositoryStub = MockRepository.GenerateStub<INewsRepository>(); _sut = new UsersController(_repositoryStub); InitializeController(_sut); } [TestMethod] public void UsersController_Index_Should_Fetch_News_From_Repository() { // arrange var news = new News[0]; _repositoryStub.Stub(x => x.GetNews()).Return(news); // act var actual = _sut.Index(); // assert actual .AssertViewRendered() .WithViewData<News[]>() .ShouldBe(news); } } As far as your views are concerned you will need to write web tests to verify that they behave as expected. There are different tools that might help you here such as Selenium or directly use Web Tests if you have the Ultimate version of Visual Studio. Steven Sanderson also proposed an interesting approach for testing views you might take a look at.
doc_23534188
I have been working in this for a while and haven't come out with the answer someone could lead me in the right direction? I was able to sum all the elements together but when diving by the array's length I realized this changes every time it gets in the method in a smaller value. Here the code so far: public static double findAverage(int[] classRoom) { if(classRoom.length > 0) { int grade = classRoom[0]; int[] newArray = new int[classRoom.length-1]; //create newArray with array length -1 System.arraycopy(classRoom, 1, newArray, 0, newArray.length); //copy array into array length -1 return grade + findAverage(newArray); } else return 0; } A: I think this is what you need: public static double findAverage(int[] classRoom) { if (classRoom.length == 0) return 0; int grade = classRoom[0]; if (classRoom.length == 1) return grade; int[] newArray = new int[classRoom.length-1]; //create newArray with array length -1 System.arraycopy(classRoom, 1, newArray, 0, newArray.length);//copy array into array length -1 return (grade + findAverage(newArray) * newArray.length) / classRoom.length; } In that last line, you are doing average * length to get the sum, so you can then sum your current value and then divide by the overall length (which is of course newArray.length + 1. Again, this would not make sense at all in a real-world scenario, but just as an academic challenge. As a final note, "find" usually refers to finding an element in the array. In this case, you are not finding anything but rather calculating the average, so the function name doesn't seem right to me either.
doc_23534189
id | field_id_16| img_src 1 | 2 | a.jpg 2 | 1 | b.jpg 3 | 3 | c.jpg table pin_info as pi: id | look_week | member_id | is_pinned 1 | 2 | 2 | yes 2 | 1 | 2 | yes 3 | 3 | 1 | yes What I want to do: get an array of img src from table ecd for a member(lets say 2) and is_pinned=yes.The only common field i have is field_id_16 and look_week. What I have done: $sql=" SELECT ecd.field_id_17 as pin_img FROM exp_channel_data ecd WHERE ecd.field_id_16=( SELECT look_week FROM pin_info pi WHERE pi.member_id='$member_id' AND is_pinned='yes' ) "; I am unable to get the array.The error is Subquery returns more than 1 row A: SELECT ecd.field_id_17 as pin_img FROM exp_channel_data ecd WHERE ecd.field_id_16 IN ( SELECT look_week FROM pin_info pi WHERE pi.member_id='$member_id' AND is_pinned='yes') A: It is saying correct because you have two rows with member id 2 try with join SELECT ecd.img_src as pin_img FROM exp_channel_data ecd JOIN pin_info pi ON (ecd.field_id_16 = pi.look_week ) WHEHER pi.member_id='$member_id' AND pi.is_pinned='yes' i guess you don't have field_id_17 in exp_channel_data
doc_23534190
Anyone has any idea how to remove this window (application is safe, all jars are signed, jar).? A: You could try the solution suggested in this links below and see if it helps get past the error http://java.com/en/download/help/error_mixedcode.xml https://service.parachat.com/knowledgebase/113/Why-do-I-see-Error-Java-has-discovered-application-components-that-could-indicate-a-security-concern.html
doc_23534191
My solution is to send this event every day by some time service which will monitor for day changes but I think there could be better solution to this problem and you can tell me about it
doc_23534192
Scenario public class A extends FlexLayout implements RouterLayout {} @Route(value = "b", layout = A.class) public class B extends FlexLayout{} @Route(value = "c", layout = A.class) public class C extends FlexLayout{} Attempts * *To do so I tried to call UI.getCurrent().getPage().setTitle("demo title") during afterNavigation. Unfortunately this does not work for the initial navigation (and neither worked adding an attachListener). *I also tried configuring it using the PageConfigurator on the outermost RouterLayout like this: @Override public void configurePage(InitialPageSettings settings) { settings.addMetaTag("title", "demo title"); settings.addMetaTag("og:title", "demo title"); settings.addFavIcon("icon", "frontend/images/favicon.ico", "48x48"); } *HasDynamicTitle only seems to work if the implementing class also defines the @Route but not the encapsulating RouterLayout Issue For some reason the Router itself sets the title during navigation. The Router defines the title using JS and redefining document.title while Page.setTitle seems to only modify the html.head.title tag. Question How does one set the title in a single spot? How does one prevent the Router form setting the title to the value of the current URL? Note Using the @PageTitle annotation is not an option as in my case the title is not known at compiletime. A: Fixed title If you have an unchanging page title you can just set it with an annotation @PageTitle. @PageTitle("home") class HomeView extends Div { HomeView(){ setText("This is the home view"); } } Dynamic title The official Vaadin Flow documentation suggests to use the HasDynamicTitle. Example: @Route(value = "blog") class BlogPost extends implements HasDynamicTitle, HasUrlParameter<Long> { private String title = ""; @Override public String getPageTitle() { return title; } @Override public void setParameter(BeforeEvent event, @OptionalParameter Long parameter) { if (parameter != null) { title = "Blog Post #" + parameter; } else { title = "Blog Home"; } } } Source
doc_23534193
This causes the column heading to not align with the values. I get the same result regardless if set trim on or set trim off. I get the same result regardless if set wrap on or set wrap off. Is this a bug in PowerShell, Oracle InstantClient, or am I using SQL*Plus incorrectly? Using Oracle 19c Enterprise Edition, Oracle InstantClient 19c 64-bit, Windows PowerShell Desktop 5.1.19041.1320, Microsoft Windows 10.0 build 19042. PowerShell screen buffer size of 31. Column heading B is aligned with its data. SQL> create table wrap (a varchar2(20), b varchar2(10)); Table created. SQL> insert into wrap (a, b) values ('12345678901234567890', 'abcdefghij'); 1 row created. SQL> commit; Commit complete. SQL> set linesize 31 SQL> select * from wrap; A B -------------------- ---------- 12345678901234567890 abcdefghij PowerShell screen buffer size of 17. There are 16 spaces after column heading A and 0 spaces after column heading B. Column heading B is aligned with its data. SQL> select * fro m wrap; A B ----------------- --- ---------- 12345678901234567 890 abcdefghij PowerShell screen buffer size of 16. There are 0 spaces after column heading A and 2 spaces after column heading B. Column heading B is not aligned with its data. SQL> select * fr om wrap; A B ---------------- ---- ---------- 1234567890123456 7890 abcdefghij PS C:\> $PSVersionTable Name Value ---- ----- PSVersion 5.1.19041.1320 PSEdition Desktop PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...} BuildVersion 10.0.19041.1320 CLRVersion 4.0.30319.42000 WSManStackVersion 3.0 PSRemotingProtocolVersion 2.3 SerializationVersion 1.1.0.1 Thank you in advance.
doc_23534194
{ //it is not a TWOs nor a FIVEs and not 1.0 g: if(x%2 !=0 && x%5 !=0 && x!=1 ) return 0; // make sure it is 1.0 if(x%2 !=0 && x%5 !=0 && x==1 ) return 1; //check if it is a two if(x%2==0){ x/=2; goto g; } if(x%5==0) { x/=5; goto g; } } A: From the looks of it, you want to check whether 1/x is terminating or not. Your code looks somewhat confusing. You'll want to check whether all your primefactors are 2 or 5: int is_ter(unsigned int x) { while (x>1) { if (x%2==0) x=x/2; else if (x%5==0) x=x/5; else return 0; } return 1; } should do the trick (ok, it says 1/0 is terminating, whatever that means. It's going to terminate the program, so it's not exactly wrong...) A: No, not at all. First of all, your decimal is an int. Second, you should probably be multiplying instead of dividing. Third, when working with decimals, rounding errors occur all the time, so you need to take that into account when comparing decimals to something. And most importantly, all decimals stored on a computer are 'terminating', because in a computer, a decimal fraction is not much more than a rational number M/N, with N being a power of 2. You should do some reading about floating point numbers.
doc_23534195
How do I find the client with more transactions? Im using PHP and Mysql, but im sure there is a way to do this inside the SQL query. Thanks. A: There's lots of ways to do it, here's one SELECT COUNT(client_id) AS transaction_count, client_id FROM transactions GROUP BY client_id ORDER BY COUNT(client_id) DESC LIMIT 1 A: SELECT * FROM Transactions ORDER BY amount DESC LIMIT 1 A: One solution is: SELECT `client_id`, COUNT(*) AS c_num FROM `transaction` GROUP BY `client_id` ORDER BY `c_num` ASC LIMIT 1
doc_23534196
MY code in index.html <!-- Ionic's root component and where the app will load --> <ion-app> <!-- custom splash screen (non-angular component) --> <div id="splash-screen" class="splash"> <video autoplay muted loop webkit-playsinline playsinline src="assets/splash/Splash_Reduced.mp4"></video> </div> </ion-app> The splash screen is present but the video is broken or not available. A: It looks like IONIC does not let us remove the default splash screen. The white blank screen will display for a while in android and the default splash screen is required for IOS. SO, THE ONLY OPTION I FOUND IS USING TWO SPLASH SCREENS. The default static splash screen and then the animated splash screen for the same logo. :) I know it is not good practice. But after long searching and trying, I got to this solution.
doc_23534197
For example or being more specific., I've a button in one of the tabs that when clicked opens another tab and i used chrome.createtabs for this in Background.html. I also created a variable which will save the tab id of the new tab created (say tab1). I want to use tab1 in myscript.js(content script) to place the information in parent tab. So how can i send the request from background.html to content script? Or Is there any way to post the content to the webpage using background.html? btw I used localStorage['tab1'] to save the new Tab ID. Lemme know if i'm not clear. Thanks A: It's all described in Message Passing with examples. To send a message from a background page to a content script: background.html =============== chrome.tabs.getSelected(null, function(tab) { chrome.tabs.sendRequest(tab.id, {greeting: "hello"}, function(response) { console.log(response.farewell); }); }); content_script.js ================= chrome.extension.onRequest.addListener( function(request, sender, sendResponse) { console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension"); if (request.greeting == "hello") sendResponse({farewell: "goodbye"}); else sendResponse({}); // snub them. });
doc_23534198
# creating a node base FROM node:16-slim as node-base ENV CI=true # builder-base is used to build dependencies FROM node-base as builder-base COPY ./package-lock.json ./package.json ./ RUN npm ci --production # 'development' stage installs all dev deps and can be used to develop code. FROM builder-base as development WORKDIR /app COPY . . RUN npm ci EXPOSE 4001 CMD ["npm", "start"] # 'unit-tests' stage FROM development AS unit-tests RUN npm test -- --coverage --testNamePattern=UT: # 'integration-tests' stage FROM development AS integration-tests RUN npm test -- --coverage --testNamePattern=IT: In my Azure DevOps CI pipeline I'd like to "cache" the development stage by sending it to my Azure Container Registry (ACR). That way when I run unit-tests and integration-tests stages, I can just pull from ACR and hopefully save some time by not building development twice. I can modify my Dockerfile to pull from ACR which would work for CI, but I'm pretty sure this would screw up running those stages locally. Locally, I wouldn't want to pull from ACR, and for it to be built locally since that has the most recent code the developer is working on. Is there a way to do this with devspace without having multiple Dockerfile, modifying them, etc? EDIT: Actually, I might be able to accomplish what I'm after on the Azure DevOps side with --cache-from in the build command, and not have to modify the Dockerfile or DevSpace.yaml locally. Idea came from here: How to Enable Docker layer caching in Azure DevOps Have to test it out yet. A: You could use the appendDockerfileInstructions option in combination with multi-stage builds (i.e. multiple FROM statements in the Dockerfile added in-memory via devspace): https://devspace.sh/cli/docs/configuration/images/append-dockerfile-instructions
doc_23534199
that is supposed to execute a slidebar. The function looks like this function LoadSideBar() { document.getElementById("sideBarDiv").innerHTML = "<div data-role="panel" data-position="left" data-position-fixed="false" data-display="reveal" id="nav-panel" data-theme="a"> <a href="index.html" data-role="button" data-theme="e" data-icon="home" > 1</a><br/> <a href="NewTask.html" data-role="button" data-theme="b" data-icon="plus" > 2</a><br/> <a href="JoinGroups.html" data-role="button" data-theme="b" data-icon="search" > 3</a><br/> <a href="Groups.html" data-role="button" data-theme="b" data-icon="grid" > 4</a><br/> <a href="Settings.html" data-role="button" data-theme="b" data-icon="gear" > 5</a><br/> <a href="" data-role="button" data-theme="b" data-icon="info" > 6 </a><br/> <a href="" data-role="button" data-theme="b" data-icon="arrow-r" > 7 Us </a><br/> <a href="" data-role="button" data-theme="b" data-icon="minus" > 8 </a> </div>"; } The HTML executing code is <script src="GeneralJS.js"> </script> <script> LoadSideBar() </script> The problem seems to be that after the .innerHTML = i put a lot of HTML code inside the quotes because when I change the HTML code to "<h1> Hi </h1>" everything works. Does anyone have a clue? A: The problem is you're defining this long string enclosed with double quotes ("), which are also in the html code you're trying to put in the string, and so the string is stopped after the first quote in the html code. This can be easily fixed by defining the string using single quotes (') because the html code doesn't use them: function LoadSideBar() { document.getElementById("sideBarDiv").innerHTML = '<div data-role="panel" data-position="left" data-position-fixed="false" data-display="reveal" id="nav-panel" data-theme="a"> <a href="index.html" data-role="button" data-theme="e" data-icon="home" > 1</a><br/> <a href="NewTask.html" data-role="button" data-theme="b" data-icon="plus" > 2</a><br/> <a href="JoinGroups.html" data-role="button" data-theme="b" data-icon="search" > 3</a><br/> <a href="Groups.html" data-role="button" data-theme="b" data-icon="grid" > 4</a><br/> <a href="Settings.html" data-role="button" data-theme="b" data-icon="gear" > 5</a><br/> <a href="" data-role="button" data-theme="b" data-icon="info" > 6 </a><br/> <a href="" data-role="button" data-theme="b" data-icon="arrow-r" > 7 Us </a><br/> <a href="" data-role="button" data-theme="b" data-icon="minus" > 8 </a> </div>'; }