id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23536400
The code: #!/usr/bin/env python from matplotlib import pyplot as plt sizes = [1400, 1600, 1700, 1875, 1100, 1550, 2350, 2450, 1425, 1700] prices = [245, 312, 279, 308, 199, 219, 405, 324, 319, 255] plt.xlim([1000, 2500]) plt.ylim([0, 500]) plt.xlabel("sizes") plt.ylabel("prices") plt.scatter(sizes, prices) plt.show() How it looks: How I want it to look: So the distance between each two neighboring points is equal. A: So, it seems your graph is just for representation purpose. The numbers on the x-axis do not need to be on a scale. To plot this, you must create a x axis list which is actually to scale and just replace its labels by the elements of your sizes list. The following code shows how to do this #!/usr/bin/env python from matplotlib import pyplot as plt sizes = [1400, 1600, 1700, 1875, 1100, 1550, 2350, 2450, 1425, 1700] prices = [245, 312, 279, 308, 199, 219, 405, 324, 319, 255] plt.ylim([0, 500]) plt.xlabel("sizes") plt.ylabel("prices") x = [a for a in range(len(sizes))] plt.scatter(x,prices) plt.xticks(x, sizes) plt.show()
doc_23536401
@WebMethod(operationName = "getDrops") public Dropslog[] getDrops(@WebParam(name = "User") Users user, @WebParam(name = "MonsterID") int monsterID){ return dbmg.getDrops(user, monsterID); } As you can see this method returns a variable of type Dropslog[] by calling this method from another class: public Dropslog[] getDrops(Users user, int monsterID){ Dropslog drop; Criteria criteria = session.createCriteria(Dropslog.class); criteria.add(Restrictions.eq("monsterId", monsterID)); drop = (Dropslog) criteria.uniqueResult(); List<Dropslog> drops = (List<Dropslog>) criteria.list(); Dropslog[] dropsArray = new Dropslog[drops.size()]; dropsArray = drops.toArray(dropsArray); return dropsArray; } This method previously returned drops which is of type List<Dropslog> but I changed it as I read here that SOAP webservices cannot return lists. Now the application on the client side calls the webmethod getDrops using this code: public static Dropslog[] getDrops(webservice.Users user, int monsterID){ webservice.PvmWs service = new webservice.PvmWs(); webservice.ClientHandler port = service.getClientHandlerPort(); return port.getDrops(user, monsterID); } So from what you've seen this should work perfectly, however it does not, instead I get an incompatible type error tip on NetBeans marked on the return line of that last method: incompatible types required: Dropslog[] found: List<Dropslog> Surprisingly when I change it as NetBeans suggests it does compile and work. I was wondering why this happens and if its some sort of bug or somehow netbeans is using an old file to compile the code or if java does some sort of autocasting? A: The default ouput type for an array in JAXB is a list. From what I know, List<T> and Array doesn't make any difference in JAXB. Internally, even you declare your WS operation like this: public Shape[] echoShapes(Shape[] input) JAXB will create a List<Shape> instance to hold the Unmarshal results, then use List.toArray() to convert it into array type. OTN Discussion Forums : Webservices ...Array or List ...
doc_23536402
yy {{ utilityService.isNotNumber(option.selectedSubject) }} yy zz {{ !grid.pristine }} zz aa {{ fetching != 0 }} aa <button class="small" data-ng-disabled="utilityService.isNotNumber(option.selectedSubject) || !grid.pristine || grid.fetching" When this outputs this is what I get: yy false yy zz false zz aa true aa and a button that's not disabled. Can someone give me some advice. I do not understand why the button doesn't get disabled as one of the three conditions is True. A: fetching != 0 is true What you are actually ORing is grid.fetching. Try using data-ng-disabled="utilityService.isNotNumber(option.selectedSubject) || !grid.pristine || fetching != 0"
doc_23536403
LOAD DATA INFILE 'filename.csv' INTO TABLE zt_accubid FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\r\n' IGNORE 4 LINES I need to be able to end the process once a field with value="xyz" is encountered. Is this possible? A: LOAD DATA INFILE has no such option. There are a couple of workaraounds, though * *You could solve the problem outside MySQL by manipulating the file first *As Alain Collins mentioned, if the column containing you marker has only unique values, and you don't have the LOAD DATA inside a transcation, you can use a unique key as a stopper. *You can use a trigger on the table as a stopper *If the marker is near the end of the table or the overhead is not important to you, you can do a full LOAD DATA into an interims table, then use INSERT INTO ... SELECT to move only the relevant data into your final table *Similarily you can load all data, then delete the irellevant part A: Sure - put a row in the database before the load, and put a unique key on it. The LOAD should fail when it hits the duplicate.
doc_23536404
api.service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { environment } from 'src/environments/environment'; const localMockInput = 'assets/mock-input.json'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': 'Basic ' + btoa(environment.api.username+':'+environment.api.password) }) }; @Injectable({ providedIn: 'root' }) export class ApiService { constructor(private http: HttpClient) {} fetchRealData(_pid: any, _extUserId: any){ return this.http.get('XXXXX/XXXXX?product='+_pid+'&externalUserId='+_extUserId, httpOptions); } collectMockRounds(){ return this.http.get(localMockInput) } } app.component.ts import { Component, OnInit } from '@angular/core'; import { ApiService } from './api.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit { realData: any = []; mockInput: any = []; constructor(private api: ApiService) {} ngOnInit(){ this.doArray(); } collectMockInput(){ this.api.collectMockRounds() .subscribe(data => { for (const e of (data as any)) { this.mockInput.push({ pId: e.PID, extUserId: e.extUserID, }); } // console.log('Mock Input Successfully Collected:'); // console.log(this.mockInput); }); } doArray(){ this.collectMockInput(); for(let i = 0; i < this.mockInput.length; i++){ console.log(this.mockInput.length) this.api.fetchRealData(this.mockInput[i].pId, this.mockInput[i].extUserId) .subscribe(data => { for (const d of (data as any)) { this.realData.push({ x: d.x, y: d.y, }); } }, error => { console.log(error.error.errorMessage); }); } } } So when I've fetched the mockdata and its length, I want to loop it with my API call. It seems like I'm doing something wrong here; I do not receive any errors or even the console.log within the loop: console.log(this.mockInput.length). Any advice or hints would be highly appreciated. Thanks in advance A: Try something like this: import { combineLatest } from 'rxjs' import { switchMap, tap } from 'rxjs/operators' .... doArray() { this.api.collectMockRounds().pipe( // this is an array so it should work tap(data => console.log(data)), // can you see what the log is here, make sure data is an array... // switch to a new observable switchMap(data => { console.log(data); // make sure this is an array return combineLatest( // combine all of the requests ...data.map(input => this.api.fetchRealData(input.PID, input.extUserID)), })), ).subscribe(data => { for (const d of (data as any)) { this.realData.push({ x: d.x, y: d.y, }); } }, error => { // handle error }); }
doc_23536405
Private Declare PtrSafe Function IsIconic Lib "user32" (ByVal hWnd As LongPtr) As Integer and inside the module where we have declared the API I have the following function: Function IsMinimized(hWndAccessApp As Long) As Boolean IsMinimized = IsIconic(hWndAccessApp) * -1 End Function In addition to that I also have a form that has a button and a click event on that button that looks like: Private Sub btn_one_Click() Dim test As Boolean test = IsMinimized(hWndAccessApp) MsgBox test End Sub And everything is working perfectly. However, I was wondering if there is a way to skip the function inside the module and call the "IsIconic" API directly from the Private Sub associated with the button inside the form? A: a) There is no way to avoid the Declare-Statement for an API function. b) You have defined your IsIconic-declaration as Private, therefore it is known only in that module. If the code of btn_one_Click is not in that module, it cannot access the function - but that has nothing to do with being an API function. Just remove the Private-keyword, and you can access it from "everywhere". c) As already mentioned in the comments, I think it is a good idea to use a wrapper function that hides the details of the API-call (and the conversion of the integer value that is returned into an boolean). d) Using IsIconic(hWndAccessApp) * -1 to convert an Integer-Value 1 to a boolean looks dirty to me. To avoid a calculation to get a boolean, I would suggest to use IsMinimized = (IsIconic(hWndAccessApp) <> 0) ' Or = 1 In almost all cases, you should forget about the fact that a boolean is stored as 0 and -1 for False and True. Let VBA do the conversion from 1 to True for you.
doc_23536406
I want take two variables from @route like this: class MultimediaController extends Controller { /** * @return \Symfony\Component\HttpFoundation\Response * @Route("/{sku}/{dimension}") * @Method({"GET"}) */ public function indexAction($sku, $dimension) { $sku = {sku}; return $this->render('ExampleFrontMultimediaBundle:Default:index.html.twig'); } } How can I do? A: Just use $sku. If the parameter is defined in the route declaration and passed as argument to the function, the argument (i.e. $sku) will take the value of the route parameter. So if you browse /test/123, $sku will be equal to "test" and $dimension will be equal to 123. This is the first paragraph of the Routing documentation.
doc_23536407
Here is my XML: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/main_layout"> <LinearLayout android:layout_height="wrap_content" android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:background="@drawable/header"> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Chapter-1" android:textColor="#FFFFFF" android:layout_marginLeft="170dp" android:layout_marginTop="15dp"></TextView> </LinearLayout> <VideoView android:id="@+id/videoView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/linearLayout1" android:layout_centerHorizontal="true"></VideoView> <LinearLayout android:layout_alignParentTop="@+id/videoView1" android:layout_centerInParent="true" android:layout_height="wrap_content" android:id="@+id/linearLayout2" android:layout_width="fill_parent" android:gravity="right"> <TextView android:id="@+id/overTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=" text" android:textColor="#FFFFFF"></TextView> </LinearLayout> <LinearLayout android:layout_alignParentTop="@+id/videoView1" android:background="@drawable/footer" android:layout_alignParentBottom="true" android:layout_height="wrap_content" android:id="@+id/linearLayout2" android:layout_width="fill_parent" android:gravity="center"> <Button android:id="@+id/menu_btn" android:layout_below="@+id/videoView1" android:layout_width="wrap_content" android:text="Menu" android:textColor="#FFFFFF" android:layout_height="wrap_content" android:layout_alignLeft="@+id/videoView1" android:layout_alignRight="@+id/videoView1" android:background="@drawable/menu"></Button> <Button android:id="@+id/button2" android:layout_below="@+id/videoView1" android:layout_width="wrap_content" android:text="High" android:textColor="#FFFFFF" android:layout_height="wrap_content" android:layout_alignLeft="@+id/videoView1" android:layout_alignRight="@+id/videoView1" android:background="@drawable/menu"></Button> <Button android:id="@+id/button2" android:layout_below="@+id/videoView1" android:layout_width="wrap_content" android:text="CC" android:textColor="#FFFFFF" android:layout_height="wrap_content" android:layout_alignLeft="@+id/videoView1" android:layout_alignRight="@+id/videoView1" android:background="@drawable/menu"></Button> <Button android:id="@+id/exit_btn" android:layout_below="@+id/videoView1" android:layout_width="wrap_content" android:text="Exit" android:textColor="#FFFFFF" android:layout_height="wrap_content" android:layout_alignLeft="@+id/videoView1" android:layout_alignRight="@+id/videoView1" android:background="@drawable/menu"></Button> </LinearLayout> </RelativeLayout> A: you can adapt the size of your video view to the video frame size. so you don't have the black stripes on the left and right side. if you set a background image you have to set the video view on the top of the layer model. otherwise the image covers your video view and you cannot see the video. EDIT to set the size of the video view you have to declare it as an object in your layout and not as layout itself. here is an example: <LinearLayout android:id="@+id/LinearLayout01" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" ...> <VideoView android:id="@+id/VideoView" android:layout_width="50dp" android:layout_height="50dp" ...(here you can set further setting of the video view)></VideoView> <Button android:text= ...></Button> <Button android:text=...></Button> </LinearLayout>
doc_23536408
JSON file [ { "id": 0, "first_name": "Tony", "last_name": "Stark", "date": "2008-07-06" }, { "id": 1, "first_name": "David", "last_name": "Guetta", "date": "2008-08-05" }, ... Model public class Person { [Key] public int Id { get; set; } [Required] public string FirstName{ get; set; } [Required] public string LastName{ get; set; } [Required] public DateTime Date { get; set; } } Controller Index method: public async Task<IActionResult> Index() { string json; using (HttpClient client = new HttpClient()) { json = client.GetStringAsync(Url).Result; } var people = JsonConvert.DeserializeObject<List<Person>>(json); if (people is not null) { await _context.AddRangeAsync(people); await _context.SaveChangesAsync(); } return _context.People != null ? View(await _context.People.ToListAsync()) : Problem("Entity set 'ApplicationDbContext.People' is null."); } After loading this page, the error shows up, problem with the key and id. I know that the problem is that json data has the id values, but I don't know how to avoid that. Is there any solution. How to keep id values from json and tell the database "please, don't generate the id values, take the id values from my converted json file" InvalidOperationException: The instance of entity type 'Person' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values. Thanks a lot A: I have finally found the solution. It has been required another data annotation. So the Sql server will not increment the Id [DatabaseGenerated(DatabaseGeneratedOption.None)] Model public class Person { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int Id { get; set; } [Required] public string? FirstName { get; set; } [Required] public string? LastName { get; set; } [Required] public DateTime Date { get; set; } } And then the method that actually do the add or update data, because if the table is already populated it truncate the table first. public async Task<IActionResult> GetUpToDateData() { string json; using (HttpClient client = new()) { json = client.GetStringAsync(Url).Result; } var people = JsonConvert.DeserializeObject<List<Person>>(json); if (people is not null) { await _context.Database.ExecuteSqlRawAsync("TRUNCATE TABLE [People]"); await _context.AddRangeAsync(people); await _context.SaveChangesAsync(); } return RedirectToAction(nameof(Index)); }
doc_23536409
For example: Request:: http://192.168.1.1:8080/sum?number1=X&number2=Y Answer: X + Y = W A: You can use the requests utility to do what you would like. import requests url = "http://192.168.1.1:8080/sum?number1=X&number2=Y" response = requests.get(url) print(response.text) W = response.text Note: This example assumes that the response information you want comes back as the value of the page and is not needing to be decoded. Also note, W will be returned as a string so you may need to perform verification and type checking on it before using it.
doc_23536410
For example: var cars = db.Cars.ToList(); foreach (var car in cars) { var owners = db.Owners.Where(x => x.CarID == car.ID).Count(); } So, i want to have the cars and the owners in the same result of a query. I will apreciate an answer. A: You can use a projection: var carsAndOwnerCounts = db.Cars .Select(c => new { Car = c, OwnerCount = db.Owners.Where(o => o.CarID == c.ID).Count() }) .ToList(); The result is a list of anonymous objects where each element has a Car and an OwnerCount property.
doc_23536411
The content area is entirely filled with a (vertical) NSSplitView; on the left is an NSOutlineView source list. When the user selects an item on the left, the relevant view appears on the right side of the splitter. I can make it work well enough by putting everything in one NIB file and putting a borderless NSTabView to the right of the splitter; to switch views, I just have to change the selected tab. But putting all the views in one NIB is bad practice, so I'm trying to move each of the subviews into their own NIB files. I have a pretty good idea of most of this process — I've created an NSViewController subclass for each of these views (EntityDetailViewController, GroupDetailViewController, and so on), set the File's Owner of each new NIB to the relevant controller class, set the view connection in each NIB, and reworked the bindings. What I don't know is how to actually change which subview is being shown on screen. I've tried using the default generic NSView on the right side and sending it addSubview: messages; I've tried connecting to it as the first subview and calling NSView *newSubview = /* get subview from the new subview controller */ [[subview superview] replaceSubview:subview with:newSubview]; [self setSubview:newSubview]; But everything just leaves the space blank. How do I display a subview loaded from a separate NIB? A: Your general approach seems sound. Have you verified that the newSubview from the loaded view controller is non-nil? Does the frame of newSubview look correct before and after it is added to the view hierarchy? Lastly, at what point are you using the replaceSubview: code? It should be in awakeFromNib or later.
doc_23536412
Private Function GetData() As PagedDataSource ' Declarations Dim dt As New DataTable Dim dr As DataRow Dim pg As New PagedDataSource ' Add some columns dt.Columns.Add("Column1") dt.Columns.Add("Column2") ' Add some test data For i As Integer = 0 To 10 dr = dt.NewRow dr("Column1") = i dr("Column2") = "Some Text " & (i * 5) dt.Rows.Add(dr) Next ' Add a DataView from the DataTable to the PagedDataSource pg.DataSource = dt.DefaultView ' Return the DataTable Return pg End Function It returns the DataTable as "pg" What changes must I make to this GET method to get the records from a table in my database? C# examples will also do but would be great to see a reply with my code and then the changes.... A: If Linq to SQL is not an option then you can fall back to ADO.NET. Essentially you will need to create a connection to your database and create and run a command to retrieve the data you require and populate a DataTable. Here is an example if C#: // Create a connection to the database SqlConnection conn = new SqlConnection("Data Source=MyDBServer;Initial Catalog=MyDB;Integrated Security=True"); // Create a command to extract the required data and assign it the connection string SqlCommand cmd = new SqlCommand("SELECT Column1, Colum2 FROM MyTable", conn); cmd.CommandType = CommandType.Text; // Create a DataAdapter to run the command and fill the DataTable SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = cmd; DataTable dt = new DataTable(); da.Fill(dt);
doc_23536413
Create a model that can be used in two ways; * *Use it as a standalone model (fit it using some data) *Use it as a subgraph in another model Ideally I want to have a class MyModel that I can initialize model=MyModel(hyperparameters) and which supports model.fit(X, Y), model.predict(X) and model.evaluate(X, Y) methods. At the same time I want to be able to feed it tf.Variables in order to use it as part in a bigger graph latent_variable = model(x) where x is a tf.Variable Is there any way this is possible to do in tensorflow? Using tf.keras.Model doesn't work because it always returns a tf.Tensor, but not tf.Variable even if a tf.Variable is fed in.
doc_23536414
Error: MatDatepicker: No provider found for DateAdapter. You must import one of the following modules at your application root: MatNativeDateModule, MatMomentDateModule, or provide a custom implementation. Obviously I added the module to my TestBed config which gives my the nest error: Error: Unexpected value 'MatMomentDateModule' imported by the module 'DynamicTestModule'. Please add an @NgModule annotation. This is my setup: beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [RhvCriteriaComponent], imports: [ MaterialModule, MatMomentDateModule ], // schemas: [NO_ERRORS_SCHEMA], providers: [ FormBuilder, { provide: LandenService, useValue: landenService }, { provide: AutoriteitService, useValue: autoriteitenService }, { provide: RhvSoortService, useValue: rhvSoortService }, { provide: MAT_DATE_LOCALE, useValue: 'nl-NL' }, { provide: MAT_AUTOCOMPLETE_DEFAULT_OPTIONS, useValue: { autoActiveFirstOption: true } } ] }) .compileComponents(); })); What am I missing?
doc_23536415
Anyway, somewhere I must have forgotten to comment an error_log out because I am continuously getting an error_log message of 'post_type=' and for the life of me I just cannot track it down, I have done a search for 'post_type=' in all of my files and also been through every error_log I can find and checked that it is commented out but just cannot track this darn thing down... SO what I was wondering is if anyone knows how I can trace the source of the last error_logged message so I can find the file that is sending it. I tried error_get_last() but this isn't returning anything I think because its not actually an error that is getting logged but a message I am outputting manually... Failing that, I see that in Dreamweaver there is a way to search using regular expressions and was just wondering if anyone knows how I can make it search for error_log that not preceded by '//' Thanks in advance :) A: You can change your error log file permissions to nothing, so only "root" user has access to it. Then navigate on your website, and hopefully at some point you'll trigger that error, and as Apache won't have the rights to write in this file, php will trigger an error, giving you the opportunity to know from where it comes. Also, if you are willing to see the content of a variable, you can use var_dump($myVar).
doc_23536416
My application has a GUI and I was wondering if I want to switch to c++ for a cross platform application, what should I do with GUI? My questions are: * *If I use Qt framework, is my application going to be significantly faster? *If I deploy my jar file to native os executable (.exe, .app, etc) is my application going to be significantly faster? p.s. Mac OSx, Windows and Ubuntu are target platforms for my software. A: This Article may Help You, I Face the same questions a couple of years ago. I decided to stick with Java for my own programming experience, since I'm not that good in C++ and my project was to be honest, very simple. As you know, Java is a very spread / wide around the world, tons of docs and libraries ready for you to use, Qt is faster, but you will need to get your hands dirty to do the job. If performance is your goal, Go Qt. Or redesign your application to hava Java/Swing GUI and C++ programs server side. Anyways here's the link. http://turing.iimas.unam.mx/~elena/PDI-Lic/qt-vs-java-whitepaper.pdf Java/Swing may be appropriate for certain projects, especially those without GUIs or with limited GUI functionality. C++/Qt is an overall superior solution, particularly for GUI applications. A: Using C++ instead of Java improves CPU performance, sometimes as much as 10-30%. However using multiple threads also increases the amount of CPU you have available. Given using multiple threads didn't help, I suspect your bottleneck is not in CPU and switching language is unlikely to help. Where C can help is in programming graphics cards, e.g. CUDA. You can get dramatically faster results for certain types of problems using a high performance processing card. http://www.nvidia.co.uk/object/cuda_home_new_uk.html There are JOCL libraries to use CUDA from Java, but the code which does the real work is in a C-like language. I suggest you determine where your bottle neck really is as switching to C++ will not increase the size of your cache, your memory bandwidth, IO bandwidth or the size of your main memory.
doc_23536417
is said to be false in one of my thread exercise; why is that not correct? A: That's an odd question. "Dies as an object" is not a conventional term. The instance of the Thread object behaves just like any other Java object. It will be garbage collected as soon as it's not reachable any more. See https://stackoverflow.com/a/5690468/3765428 for more about garbace collection. A: Need to define 'dies', In general - objects which are being pointed at by variables AKA: Object thread = new Thread() are alive as long as some other object holds or points to the thread object. e.g. Object[] threads = [thread, ...] //Psudo code so, as long as threads object is pointing/holding/etc the thread object and it's not being disposed, it's still be 'alive'. And even when no one points to the object, it still has to wait for the GarbageCollector (GC) cycle in order for it to call the Dispose() method (which exists in every object) to 'kill' it
doc_23536418
Is there any supportive lib which can handle point labels on its own. Or Is there any smart logic that can identify closest points and set the location of label accordingly?? A: Maybe try the IsPreventLabelOverlap property to true. Unfortunately this usually just erases the labels that overlap and doesn't simply spread them out. So with that in mind, see below. There is not a library which does what you asked, but there is the postpaint option. Zedgraph unfortunately does not fix overlapping labels (I tried for a long time and with no luck). However there is a work around but it is tedious and you have to put some real thought into where to place your graphic labels. See code below for a simple way to add a label: protected void Chart1_PostPaint(object sender, ChartPaintEventArgs e) { if (e.ChartElement is Chart) { // create text to draw String TextToDraw; TextToDraw = "Chart Label" // get graphics tools Graphics g = e.ChartGraphics.Graphics; Font DrawFont = System.Drawing.SystemFonts.CaptionFont; Brush DrawBrush = Brushes.Black; // see how big the text will be int TxtWidth = (int)g.MeasureString(TextToDraw, DrawFont).Width; int TxtHeight = (int)g.MeasureString(TextToDraw, DrawFont).Height; // where to draw int x = 5; // a few pixels from the left border int y = (int)e.Chart.Height.Value; y = y - TxtHeight - 5; // a few pixels off the bottom // draw the string g.DrawString(TextToDraw, DrawFont, DrawBrush, x, y); } This will create a label for you and you can choose where to draw it. However that is the tricky part. You need to basically find out where your graph is on your screen and where the point is on that graph. Very cumbersome but if it is a static graph then it shouldn't be an issue. It's a hack, I know, but it works and it's all anyone has seemed to come up with.
doc_23536419
All I am looking for exposing same endpoint with different vendors having access to different AWS S3 buckets to upload their files to designated AWS S3 buckets. Appreciate all your thoughts and response at the earliest. Thanks A: Setting up separate buckets and AWS Transfer instances for each vendor is a best practice for workload separation. I would recommend setting up a custom URL in Route53 for each of your vendors and not attempt to consolidate on a single URL (it isn't natively supported). https://docs.aws.amazon.com/transfer/latest/userguide/requirements-dns.html A: While setting up separate AWS Transfer Family instances will work, it comes at a higher cost (remember you are charged even if you stop until the time you delete, you are billed $0.30 per hour which is ~ $216 per month). The other way is to create different users (one per vendor) and use different home directories (one per vendor) and lock down permissions through IAM role for that user (also there is provision to use a scope-down policy along with AD). If using service managed users see this link https://docs.aws.amazon.com/transfer/latest/userguide/service-managed-users.html.
doc_23536420
I'm trying to increase performance of my CV search database. 30,000 records and growing and we are seeing some performance issues. I have created an index of the field that is slowing things down, which is the body of text of their CV(All duplicate words and stop word already removed). I created a fulltext index of that field and it works GREAT on single word queries like 'DRILLER', or two word queries like 'DRILLER AND PAINTER'. I can see on the EXPLAIN that the index is firing, and things are fast - happy days. My question. When I perform a search say 'DRILLER OR CLEANER' then the index doesn't fire, and the query time drags out to 6 or so seconds. My SQL queries; FAST - uses index SELECT nl_id FROM CV WHERE ( ( MATCH (nl_striptext) AGAINST ('driller' IN BOOLEAN MODE) AND MATCH (nl_striptext) AGAINST ('cleaner' IN BOOLEAN MODE) ) ) SLOW - index not firing SELECT nl_id FROM CV WHERE ( ( MATCH (nl_striptext) AGAINST ('driller' IN BOOLEAN MODE) OR MATCH (nl_striptext) AGAINST ('cleaner' IN BOOLEAN MODE) ) ) LIMIT 15 OFFSET 0 I'm scratching my head here, and your help is appreciated. A: OR can cause problems with the optimization of queries. You can fix this by writing the query as: (SELECT nl_id FROM CV WHERE MATCH (nl_striptext) AGAINST ('driller' IN BOOLEAN MODE) ) UNION (SELECT nl_id FROM CV WHERE MATCH (nl_striptext) AGAINST ('cleaner' IN BOOLEAN MODE) ) LIMIT 15 OFFSET 0; With a LIMIT clause, you should use ORDER BY. Otherwise the results are indeterminate, because the results of the query are in no guaranteed order. Also, note the use of UNION. This will remove duplicates where both words appear. A: You have a couple of choices here, to fix this OR problem. Keep in mind that OR casts a wider net -- matches more things -- than AND does. AND narrows down your search and OR broadens it. One is to take better advantage of the BOOLEAN MODE in your MATCH clause, by searching for both terms in a single search. MATCH (nl_striptext) AGAINST ('driller cleaner' IN BOOLEAN MODE) This is probably your best bet. It's fast. You can also use the SQL UNION of two searches to implement your OR operation. Gordon offers that approach in another answer.
doc_23536421
intall pip pip.main(['install','numpy]) however, when the code runs the command, I get an error informing me that I must have python 2.7 or python 3.4 installed. It looks as if it tries to install a version of numpy that was meant for an actual python3 installation and not qpython. I also tried navigating to http://qpypi.qpython.org to download the zip file directly, but when I clicked on the link for numpy-qpython, nothing happens.
doc_23536422
server.py import socket import sys HOST = 'localhost' PORT = 3820 socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.bind((HOST, PORT)) socket.listen(1) while (1): conn, addr = socket.accept() print 'New client connected ..' reqCommand = conn.recv(1024) print 'Client> %s' %(reqCommand) if (reqCommand == 'quit'): break #elif (reqCommand == lls): #list file in server directory else: string = reqCommand.split(' ', 1) #in case of 'put' and 'get' method reqFile = string[1] if (string[0] == 'put'): with open(reqFile, 'wb') as file_to_write: data=conn.recv(1024) while True: if not data: break else: file_to_write.write(data) data=conn.recv(1024) file_to_write.close() break print 'Receive Successful' elif (string[0] == 'get'): with open(reqFile, 'rb') as file_to_send: for data in file_to_send: conn.sendall(data) print 'Send Successful' conn.close() socket.close() client.py import socket import sys HOST = 'localhost' # server name goes in here PORT = 3820 def put(commandName): socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket1.connect((HOST, PORT)) socket1.send(commandName) string = commandName.split(' ', 1) inputFile = string[1] with open('clientfolder/'+inputFile, 'rb') as file_to_send: data=file_to_send.read(1024) while(data): socket1.send(data) data=file_to_send.read(1024) file_to_send.close() print 'PUT Successful' socket1.close() return def get(commandName): socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket1.connect((HOST, PORT)) socket1.send(commandName) string = commandName.split(' ', 1) inputFile = string[1] with open('clientfolder/'+inputFile, 'wb') as file_to_write: while True: data = socket1.recv(1024) # print data if not data: break # print data file_to_write.write(data) file_to_write.close() print 'GET Successful' socket1.close() return msg = raw_input('Enter your name: ') while(1): print 'Instruction' print '"put [filename]" to send the file the server ' print '"get [filename]" to download the file from the server ' print '"ls" to list all files in this directory' print '"lls" to list all files in the server' print '"quit" to exit' sys.stdout.write('%s> ' % msg) inputCommand = sys.stdin.readline().strip() if (inputCommand == 'quit'): socket.send('quit') break # elif (inputCommand == 'ls') # elif (inputCommand == 'lls') else: string = inputCommand.split(' ', 1) if (string[0] == 'put'): put(inputCommand) elif (string[0] == 'get'): get(inputCommand) #current working directory is server location #get will get file from current directory to clientfolder directory. A: TCP is a streaming protocol, so you have to design message breaks into your protocol. For example: s.send('put filename') s.send('data') Can be received as: s.recv(1024) # 'put filenamedata' So buffer data received and only extract full messages. One way is to send the size of a message before the message.
doc_23536423
Whenever I test it, it errors with: NoMethodError (undefined method print_it for #<Class:0x007f7b7b092f20>): In Model: project.rb class Project < ApplicationRecord def print_it self.as_json end end In controller: projects_controller.rb class Api::V1::ProjectsController < Api::ApiController def index render json: Project.print_it end end How can I use print_it on an object? A: Project.print_it is calling print_it on the class Project. But, you define print_it as an instance method, not a class method, here: class Project < ApplicationRecord def print_it self.as_json end end You probably want something more like: class Api::V1::ProjectsController < Api::ApiController def index render json: @project.print_it end end Naturally, you'll need to set @project. To use print_it on an ActiveRecord_Relation called @projects, you could do something like: @projects.map{|p| p.print_it} You'll end up with an array. But that might be expensive, depending on the number of projects and the nature of print_it. How can I use print_it on an object? You are 'using' (calling) print_it on an object. Project is an object. Just like @project is an object. You just happen to be calling print_it on an object that doesn't have print_it defined (thus the undefined method error). I will also note that Jörg W Mittag wishes to say: I am one of those Ruby Purists who likes to point out that there is no such thing as a class method in Ruby. I am perfectly fine, though, with using the term class method colloquially, as long as it is fully understood by all parties that it is a colloquial usage. In other words, if you know that there is no such thing as a class method and that the term "class method" is just short for "instance method of the singleton class of an object that is an instance of Class", then there is no problem. But otherwise, I have only seen it obstruct understanding. Let it be fully understood by all parties that the term class method is used above in its colloquial sense.
doc_23536424
Though, before I start developing all this, I want to know if there is a good practice to send all these notifications. I was thinking : if each message on my app sends a push notif, the "trivial" way to carry out this would be to create a socket within my PHP server and send a request to Apple for each request my client app does. We respond to our client app only when Apple responds to our push notif request. However this solution may slow down tremendously my app, as each HTTP request from my client apps to my server has to wait until Apple responds. Then, I was wondering if it would be better to just queue push notifs (in the database) when a request is done from my client to my server, and do a job each second that takes all the new push notifs that was queued the last second, in order to send them grouped to Apple, in one single request. Is it something commonly done ? Or maybe I overestimate the time Apple responds to each request ?
doc_23536425
**parent.html** <financial-data [finData]="financialData$ | async" [finFactors]="financialFactors$ | async" [franchiseData]="franchiseData$ | async"></financial-data> **parent.component** financialData$: Observable<financialData[]>; financialFactors$: Observable<financialFactors[]>; franchiseData$: Observable<franchiseData> ngOnInit() { this.financialData$ = this.store.select(getFinancialData); this.financialFactors$ = this.store.select(getFinancialFactors); this.franchiseData$ = this.store.select(getFranchiseData); } **child.component** @Input() finData: FinancialData[]; @Input() finFactors: FinancialFactors[]; @Input() franchiseData: FranchiseData; ngOnChanges(changes) { if(this.finData && this.franchiseData && this.finFactors) { <--- this usually comes back with finFactors as undefined so it never runs this.getFinancials() but it never re-runs this.getFinancials(); } } getFromStoreOrAPI(): Observable<any> { return combineLatest([ this.store.select(getFinancialFactors), this.store.select(getFinancialData), this.store.select(getFranchiseData) ]).pipe( map(([financialFactors, financialData, franchiseData]) => ({ financialFactors, financialData, franchiseData })) ); } canActivate(route: ActivatedRouteSnapshot): Observable<boolean> | boolean { let tranId = this.router.getCurrentNavigation().extras.state.tranId; let modelId = this.outer.getCurrentNavigation().extras.state.modelId; this.store.dispatch(ScorecardActions.loadFinancialData({tranId: tranId})); this.store.dispatch(ScorecardActions.loadFranchiseData({tranId: tranId})); this.store.dispatch(ScorecardActions.loadFinancialFactors({modelId: modelId})); return this.getFromStoreOrAPI() .pipe( mapTo(true), <--- Neither one of these ever gets hit, I believe because it returning an array?? catchError(() => of(false)) ); } }
doc_23536426
<?xml version="1.0" encoding="UTF-8"?> <root> <data name="LogIn">Log In</data> <data name="Password">Password</data> </root> I success to do that without Linq, any one can help me to convert the following code to Linq: using (XmlReader reader = XmlReader.Create(_xml)) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "data") { reader.MoveToAttribute("name"); string key = reader.Value; reader.MoveToContent(); string value = reader.ReadElementContentAsString(); _dictionary.Add(key, value); } } reader.Close(); } A: var xdoc = XDocument.Load(path_to_xml); _dictionary = xdoc.Descendants("data") .ToDictionary(d => (string)d.Attribute("name"), d => (string)d); A: XDocument xdoc = XDocument.Load("test.XML"); var query = xdoc.Descendants("root") .Elements() .ToDictionary(r => r.Attribute("name").Value, r => r.Value); Remeber to include : using System.Linq; using System.Xml.Linq; A: This is an old question, but in case someone comes across a 'Typed' xml (e.g from a SharedPreference file of an android app), you can handle it as below: Here is a sample of such an xml I took from an Instagram app. <?xml version='1.0' encoding='utf-8' standalone='yes' ?> <map> <boolean name="pinnable_stickers" value="false" /> <string name="phone_number">+254711339900</string> <int name="score" value="0" /> <string name="subscription_list">[]</string> <long name="last_address_book_updated_timestamp" value="1499326818875" /> //...other properties </map> Note the inconsistency in the value property. Some fields(e.g of type string) don't have it explicitly defined. var elements = XElement.Load(filePath) .Elements() .ToList(); var dict = new Dictionary<string, string>(); var _dict = elements.ToDictionary(key => key.Attribute("name").Value, val => val.Attribute("value") != null ? val.Attribute("value").Value : val.Value);
doc_23536427
z - y = x ? Are there any research formulas? Another question is if apply CIElab tranformation to get hue saturation brightness then how do I apply these to subtract colors? A: You mean additive colour mixing? In this case, just the light is added. So, it is just addition and subtraction of intensities of light, so RGB is fine. But you need linear colour space. So you need to "unapply" gamma, add or subtract, and apply again gamma. See https://en.wikipedia.org/wiki/SRGB#Specification_of_the_transformation for the formula to apply Gamma and unapply it: C is channel (R, G, B, each), C_linear is linear space (where you can add and subtract intensities) and C_srgb is the channel value as we use on computers. Note: you should divide and multiply with 255, to normalize values from 0 to 1. For normal colour mixing (paints, inks, dyes, etc.), this is complex, but one could in such case, CIExyz is preferred: In fact on such space, the result of mixing is in the line between the two original chromacities. Unfortunately, the model do not tell you where the result will be within such line. Usually more data about each colour is needed (often instead of the RGB triplet, a vector of about 60 items [so a data every 5nm])
doc_23536428
I'm generated this param setOAuthAccessToken() in graph api explorer copy and it paste in setOAuthAccessToken(). How right set and get token? How create authentication in my web application via facebook4j? Exception #1 FacebookException{ statusCode=400, errorType='OAuthException', errorMessage='Errorvalidatingaccesstoken: SessionhasexpiredonFriday, 25-Sep-1511: 00: 00PDT.ThecurrenttimeisFriday, 25-Sep-1513: 55: 17PDT.', errorCode=190, errorSubcode=463, version=2.3.0 } This is my code: private final String TOKEN_VALUE = "CAACEdEose0cBAN5JHf6qs85DCcqKndE3N9XxjnMye3m7G7Re4VpSCqn4IzWXXoYeQe3QlUOH0NGucIWJbqfZBpFoHTUZA60YcZCZBwd4kCWD4g1qwZCyxy1ihpoiVuxZCV1u9ydjnhZCkNOoSqiqPpkzDWPfAc8ZBEDFtCvW78gZCbkZChrzfsMxpA3LZC08pZA5HrqaOe1BnrU1PiZAHJz4ZAEm3M"; private FacebookFactory facebookFactory; private Facebook facebook; private ConfigurationBuilder configurationBuilder; private Configuration configuration; public ConfigurationBuilder getConfigurationBuilder(){ configurationBuilder = new ConfigurationBuilder(); configurationBuilder.setDebugEnabled(true); configurationBuilder.setOAuthAppId("746931638784611"); configurationBuilder.setOAuthAppSecret("07e2df67b4fe40e3f2051d79f40387c2"); configurationBuilder.setOAuthAccessToken(token); configurationBuilder.setUseSSL(true); configurationBuilder.setJSONStoreEnabled(true); return configurationBuilder; } public Configuration getConfiguration(){ return getConfigurationBuilder().build(); } public FacebookFactory getFacebookFactory(){ return new FacebookFactory(getConfiguration()); } @Override public String getFriends() { facebook = getFacebookFactory().getInstance(); try { ResponseList<Friend> friends = facebook.getFriends(); return friends.toString(); }catch (FacebookException e) { e.printStackTrace(); } return null; }
doc_23536429
At first I just installed the msysgit normally (Full Installer) and the TortoiseGIT. In tortoiseGIT configurations I couldn't set it up to work properly because I couldn't finde the git.exe file. After some search I found out that I needed to run the initialize.sh script on the msysgit console mode. So i finally got the git.exe under bin folder in the msysgit. The msysgit folder is something around 1.46 GB, and I realized that tis process downloaded the entire git source code. In linux, the git-core debian package is much smaller and the process is much quickier. I was wondering, is that really it? It's really this big? Some info on versioning: msysgit: 1.7.8-preview20111206 git: 1.7.8 tortoiseGIT: 1.7.6.0 A: My MSysGit installation directory is under 80MB and I've put a bunch of additional tools in there. I suspect you've downloaded the development package (for working on MSysGit itself) rather than the package for if you just want to use git, which is Git For Windows. A: Full Installer is the whole source code for (Linux) git, and the Windows git variant, and the compilers, and everything for the Msys environment, etc. My V1.7.8 (full install) directory is 1.48 GB, while the Git for Windows C:\Program Files\ executables are just 205 MB (size on disc). Like Barend said, get the Git for Windows for regular work, and have the Full Install to satisfy your inquisitiveness about what's really going on ;-) It needs to be eaten like a melon though, one chunk at a time.
doc_23536430
A: As what I have understood your question: you want to place new application(your friend's application) in your account and also want to add your friend Google account(Testing account for the application) into Google play console. My Answer: Yes, it is possible for both cases. 1) you can add more then one application into your Google developer console. That means you can also add your friend application's signed apk file into your account by creating new application. And one more thing you have to add into console that is his Google account(Google id for testing application), you can simply add it from the settings tag. 2) you can also add more then one Google account(Google id for testing the application) for the single application by using commas. That means one application can be test by the two different accounts. Let me know if I am not understood your question properly or may you want to explain something else. Hope it will help you.
doc_23536431
Challenges: * *Get the path to the .APK file on the device. *Iterate through all of the files, recursing through the subdirectories. A: You should be able to treat the apk file as if they are zip files. Since you're working within NDK, you can try using a C++ library like 7-zip to help you browse through the zip file entries. A: For the first part of your question, the path to the .apk on the device, refer to this question (it's on StackOverflow, so I won't bother recopying it). For the second part your question, unzipping an .apk file on the device, download the source for Terminal IDE (Terminal IDE also works on non-rooted devices). Download its source from the download tab, not the browse source tab (which for some reason doesn't work right now). It's a huge project mostly in Java (it's not exactly the language you're looking for), but it's well organized and remarkably readable.
doc_23536432
* *301_1.txt *301_2.txt *301_3.txt I would like to create a new file with all the content of the files that have the same number before the "_". In this instance, the new file should be 301.txt. What is the best way to do this in Python? Thank you A: This is my approach: (hope it helps :) ) Firstly, we need to store the files starting with "301": import os files = [] directory = os.fsencode(directory of files) for file in os.listdir(directory): filename = os.fsdecode(file) if filename.startswith("301"): files.append(filename) The directory of files is the directory of where your files go. Now we need to fetch the data from the files: data = [] for f in files: with open(f) as file: for i,row in enumerate(file): data.append(row) Finally we need to write the "301.txt" file: with open("301.txt",'w') as newfile: for row in data: newfile.write(row) A: You could so something like this. # populated by os.listdir or something FILES = ['301_1.txt', '301_2.txt', '301_3.txt', '302_1.txt', '302_2.txt'] def concat_files(base='301'): with open(base + '.txt', 'a+') as basefile: for file in [f for f in FILES if f.startswith(base + '_')]: with open(file) as content: basefile.write(content.read()) concat_files(base='301') A: import glob import os pwd=os.getcwd() os.chdir('path_to_your_directory') for i in glob.glob('*.txt'): new_name=i.split('_')[0] #fetch the name before '_' write_file=open(new_name+'.txt','a') #open file in append mode read_file=open(i) lines=read_file.read() write_file.write(lines) write_file.close() read_file.close() #close the files os.chdir(pwd) glob.glob('*.txt') will return a list of all files with extension .txt in the current directory. First, we store the present directory in pwd, then to get to the current directory we use os.chdir() from os module and at last, we return to our starting directory by os.chdir(pwd). If you don't want newline characters then use read_file.read().rstrip() instead.
doc_23536433
I am basically trying to solve this for days now, and I really do not know how to get further. I have the impression that the css selector is not actually capturing the underlying link (as it extracts the title without problems), but the class has a compounded name ("ep-a_heading ep-layout_level2") so it is not possible to go via this way either. I tried Rvest as well (ignoring the problem I would then have for the load more--button) but I still do not get to those links. ```{r} library(RSelenium) library(wdman) library(rvest, warn.conflicts=FALSE) library(stringr) server <- phantomjs(port=7005L) browser <- remoteDriver(browserName = "phantomjs", port=7005L) ## this is one of the urls I will use, there are others, constructed all ##the same way and all with the same problem url <- 'http://www.europarl.europa.eu/meps/en/124936/MARIA_ARENA/all- activities/plenary-speeches/8' browser$open() browser$navigate(url) ## now I identify the load more button and click on it as long as there ##is a "load more" button on the page more <- browser$findElement(using = "css", value=".erpl-activities- loadmore-button .ep_name") while (!is.null(more)){ more$clickElement() Sys.sleep(1)} ## I get an error message doing this in the end but it is working anyway ##(yes, I really am a beginner!) ##Now, what I want to extract are the title of the speech and most ##importantly: the URL. links <- browser$findElements(using="css", ".ep-layout_level2 .ep_title") length(links) ## there are 128 Speeches listed on the page URL <- rep(NA, length(links)) Title <- rep(NA, length(links)) ## after having created vectors to store the results, I apply the loop ##function that had worked fine already many times to extract the data I ##want for (i in 1:length(links)){ URL[i] <- links[[i]]$getElementAttribute('href')[[1]] Title[i] <- links[[i]]$getElementText()[[1]] } speeches <- data.frame(Title, URL) For this example there 128 speeches on the page, so in the end I would need a table with 128 titles and links. The code works fine when I only try for the title but for the URLs I get: `"Error in links[[i]]$getElementAttribute("href")[[1]] : subscript out of bounds"` Thank you very much for your help, I already read many posts on subscript out of bounds issues in this forum, but unfortunately I still couldn't solve the problem. Have a great day! A: I don't seem to have a problem using rvest to get that info. No need for overhead of using selenium. You want to target the a tag child of that class i.e. .ep-layout_level2 a in order to be able to access an href attribute. Same selector would apply for selenium. library(rvest) library(magrittr) page <- read_html('https://www.europarl.europa.eu/meps/en/124936/MARIA_ARENA/all-activities/plenary-speeches/8') titles <- page %>% html_nodes('.ep-layout_level2 .ep_title') %>% html_text() %>% gsub("\\r\\n\\t+", "", .) links <- page %>% html_nodes('.ep-layout_level2 a') %>% html_attr(., "href") results <- data.frame(titles,links) A: Here you have a working solution based on the code you provided: library(RSelenium) library(wdman) library(rvest, warn.conflicts=FALSE) library(stringr) server <- phantomjs(port=7005L) browser <- remoteDriver(browserName = "phantomjs", port=7005L) ## this is one of the urls I will use, there are others, constructed all ##the same way and all with the same problem url <- 'http://www.europarl.europa.eu/meps/en/124936/MARIA_ARENA/all-activities/plenary-speeches/8' browser$open() browser$navigate(url) ## now I identify the load more button and click on it as long as there ##is a "load more" button on the page more <- browser$findElement(using = "class",value= "erpl-activity-loadmore-button") while ((grepl("erpl-activity-loadmore-button",more$getPageSource(),fixed=TRUE)){ more$clickElement() Sys.sleep(1)} ## I get an error message doing this in the end but it is working anyway ##(yes, I really am a beginner!) ##Now, what I want to extract are the title of the speech and most ##importantly: the URL. links <- browser$findElements(using="class", "ep-layout_level2") ## there are 128 Speeches listed on the page URL <- rep(NA, length(links)) Title <- rep(NA, length(links)) ## after having created vectors to store the results, I apply the loop ##function that had worked fine already many times to extract the data I ##want for (i in 1:length(links)){ l=links[[i]]$findChildElement(using="css","a") URL[i] <-l$getElementAttribute('href')[[1]] Title[i] <- links[[i]]$getElementText()[[1]] } speeches <- data.frame(Title, URL) speeches The main differences are: * *In the first findElement I use value= erpl-activity-loadmore-button. Indeed the documentation says that you can not look at multiple class values at once *Same when it comes to look for the links *In the final loop, you need fist to select the link element in the div you selected and then read the href attribute To answer your question about the error message in comments after the while loop: When you pressed enough time the "Load more" buttons it become invisible, but still exists. So when you check for !is.null(more)it is TRUE because the button still exists, but when you try to click it you get and error message because it is invisible. So you can fix it by checking it it is visible or note.
doc_23536434
struct Vertex; typedef struct Vertex Vertex; struct Vertex { int sides[2][LENGTH]; int ends[2]; Vertex *children; Vertex *parent; }; void move(Vertex *node, int side, int place) { (38) int handfull = (*node).sides[side][place]; ..... } int blah(Vertex *node, int side) { ..... (103) *((*node).children + i) = init_child(node); (104) move((*node).children + i, side, i); (105) blah((*node).children + i, opposingside); ..... } gdb tells me the following: (gdb) print (*node) $7 = {sides = {{5, 5}, {0, 5}}, ends = {0, 1}, children = 0x7fffffffdfa0, parent = 0x7fffffffe110} (gdb) print node $8 = (Vertex *) 0x7fffffffe0c0 (gdb) print ((*node).children + i) $9 = (Vertex *) 0x7fffffffdfa0 (gdb) print *((*node).children + i) $10 = {sides = {{5, 5}, {0, 5}}, ends = {0, 1}, children = 0x7fffffffdf20, parent = 0x7fffffffe0c0} (gdb) step move (node=0x7fffffffdfa0, place=0, side=0) at mancala.c:38 38 int handfull = (*node).sides[side][place]; (gdb) print node $11 = (Vertex *) 0x7fffffffdfa0 (gdb) print (*node) $12 = {sides = {{-8160, 32767}, {4196818, 0}}, ends = {0, 1}, children = 0x7fffffffdf20, parent = 0x7fffffffe0c0} I break at line 104 (called move). After, (*node).children + i points to a Vertex structure as evidenced by $9 and $10. I make one step into the move function. This should push my Vertex address, the return address, etc. onto the stack and start working in the move function. Looking at $11, we see that the Vertex address is the same as in $9, which is fine. However, in $12, the array .sides is now full of garbage. Everything else is fine, but just that array is full of trash. How has this happened in one step? I can't debug any further than one step at a time, so I don't know what to do now. EDIT: Here's the init_child function: Vertex init_child(Vertex *node) { Vertex children[LENGTH]; int i; int j; Vertex child = (*node); for (j = 0; j < 2; j++) { for (i = 0; i < LENGTH; i++) child.sides[j][i] = (*node).sides[j][i]; child.ends[j] = (*node).ends[j]; } child.children = children; child.parent = node; return child; } And here is the main() function that initializes the first Vertex: int main(int argc, char **argv) { Vertex children[LENGTH]; Vertex head = {.sides = {{4,4}, {4,4}}, .ends = {0}, .children = children, .parent = NULL}; blah(&head, 1); return 0; } A: The problem is that init_child() is initializing children with the address of an array that was created at function scope. When the function returns, the array is no longer valid, and so the child structure returned is pointing to an invalid object. Vertex init_child(Vertex *node) { Vertex children[LENGTH]; /* array variable on the stack */ /*...*/ child.children = children; /* child pointing to local variable */ child.parent = node; return child; } Instead, the routine should dynamically allocate the memory so that the child points to memory with a lifespan that continues to survive after the function returns. Vertex init_child(Vertex *node) { /*...*/ child.children = malloc(LENGTH*sizeof(*child.children)); child.parent = node; return child; }
doc_23536435
I use timer to convert to next page if user login success, but timer is not work and no error message... do { if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary { // Print out dictionary print("convertedJsonIntoDict=\(convertedJsonIntoDict)") print("convertedJsonIntoDict.長度=\(convertedJsonIntoDict.count)") // Get value by key if convertedJsonIntoDict.count > 1{ let cc_account = convertedJsonIntoDict["Account"] as! String self.NPaccount = cc_account print("工號=\(self.NPaccount)") let cc_account_2 = convertedJsonIntoDict["Account2"] as! String self.Account = cc_account_2 print("帳號=\(self.Account)") let cname = convertedJsonIntoDict["CName"] as! String self.Name = cname print("姓名=\(self.Name)") self.Member.account = self.Account self.Member.password = self.PasswordTextvield.text! self.Member.npaccount = self.NPaccount self.Member.name = self.Name self.Member.uuid = self.UUID self.Member.creatdate = self.now print("Saving data to context...") appDelegate.saveContext() self.segueflag = true EZLoadingActivity.hide(true, animated: true) _ = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(self.nextBtn(sender:)), userInfo: nil, repeats: false) }else{ self.segueflag = false print("segueflag...\(self.segueflag)") if !self.segueflag{ print("無此帳號資料...") EZLoadingActivity.hide(false, animated: true) //self.AccoubtTextvield.text = "" //self.PasswordTextvield.text = "" } } } else{ print("here") } } catch let error as NSError { print(error.localizedDescription) } @IBAction func nextBtn(sender: AnyObject) { print("--------Go to next page!--------") if members.count == 0{ SCLAlertView().showError("請先登入~~!!",subTitle:"") return } if !segueflag{ SCLAlertView().showError("登入的帳號或密碼有誤~~!!",subTitle:"") return } self.performSegue(withIdentifier: "login", sender: self) } Can any one tell me possible answer. Thank you in advance.... A: Timer method is change for ios10. If you are checking in ios10 you can use following code. let systemVersion = UIDevice.current.systemVersion if Int(systemVersion)! >= 10 { _ = Timer.scheduledTimer(withTimeInterval: 1.5, repeats: false) { timer in //Put the code that be called by the timer here. print("Testing data") } }else{ _ = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(self.nextBtn(sender:)), userInfo: nil, repeats: false) }
doc_23536436
For (simplified) example let's suppose a simple DoFn<Key, Long> with a ValueState<Long>. @ProcessElement public void processElement( final ProcessContext c, @StateId(STATE_ID) final ValueState<Long> someState) { final long val = c.element().value(); final long currentSum = Optional.ofNullable(someState.read()).orElse(0L); final long newSum = currentSum + val; someState.write(newSum); } This state is outputted intermittently on some timer. My question is in the case where there are 2 elements A and B which both have the same Key and timestamp. The value in state is 5, the value of A is 3, and the value of B is 4. One would expect the value in someState after processing both elements to be 12. My question is this guaranteed? That is, will some ordering be applied elements to A and B - or does there possibly exist a race condition whereby the value in state can intermittently either be 8 or 9 depending on whether A or B are processed first. (Note: This is a simplified version of what I am dealing with but I believe this is undeterministic behavior is happening our pipleine). If this assumption is correct what approaches could I take in order to resolve this issue? Thanks everyone in advance! A: There is no race condition caused by identical timestamps. You'll get called twice, once for each element.
doc_23536437
ondrej@vostro-ov:/mnt/web_x1/aou511/chrootwww$ npm run build > vue@0.0.0 build > vite build vite v3.1.0 building for production... ✓ 0 modules transformed. Could not resolve entry module (chroootwww/index.html). error during build: Error: Could not resolve entry module (chroootwww/index.html). at error (file:///mnt/web_x1/aou511/chrootwww/node_modules/rollup/dist/es/shared/rollup.js:1858:30) at ModuleLoader.loadEntryModule (file:///mnt/web_x1/aou511/chrootwww/node_modules/rollup/dist/es/shared/rollup.js:22369:20) at async Promise.all (index 0) File vite.config.js is: // https://vitejs.dev/config/ export default defineConfig({ plugins: [vue()], resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) } }, root: 'chroootwww/', build: { sourcemap: true, outDir: 'www/dist', }, }) File index.html exist Does anyone know what the problem is, please? Thanks for your reply :-)
doc_23536438
import sys def main(): plaintext="abcdefgh" print(threeRailEncrypt(plaintext)) print(threeRailDecrypt(threeRailEncrypt(plaintext))) def threeRailEncrypt(plaintext): ciphertext="" rail1="" rail2="" rail3="" for i in range(len(plaintext)): if i%3 == 0: rail1=rail1+plaintext[i] elif i%3 == 1: rail2=rail2+plaintext[i] else: rail3=rail3+plaintext[i] ciphertext=rail1+rail2+rail3 return(ciphertext) def threeRailDecrypt(msg): if len(msg)%3==0: third=len(msg)//3 print(third) rail1=msg[:third] rail2=msg[third:third*2] rail3=msg[third*2:] print(rail1,rail2,rail3) dm="" for i in range(third): dm=dm+rail1[i] dm=dm+rail2[i] dm=dm+rail3[i] else: third=(len(msg)//3)+1 print(third) rail1=msg[:third] rail2=msg[third:third*2] rail3=msg[third*2:] print(rail1,rail2,rail3) dm="" for i in range(third): dm=dm+rail1[i] print(dm) dm=dm+rail2[i] print(dm) dm=dm+rail3[i] print(dm) if len(rail2)>len(rail3): dm=dm+rail2[-1] return(dm) main() Progress- def threeRailDecrypt(cypher, rails = 3): length = len (cypher) for i in range(rails): lens=(length//rails) if length % rails > i: lens=lens+1 print(lens) A: New: You just have to split up the strings again as you did in your encryption function and then iterate over them to put each character back at it's real place. def decrypt(crypt): rails = [] result = "" rails.append(crypt[:(len(crypt)+2)/3]) rails.append(crypt[(len(crypt)+2)/3:-(len(crypt)-2)/3]) rails.append(crypt[-(len(crypt)/3):]) for x in range(len(crypt)): result += rails[x%3][:1] rails[x%3] = rails[x%3][1:] return(result) I think Hyperboreus second solution is cooler though! OLD(Interesting thought connected to the comments, didn't work as expected for longer strings though): You will just have to reverse what you do in the encryption, so in the encryption you scramble the text by splitting them up with modulo 3. The simplest way to get the plaintext back again is to simply run the encryption method the length of the string minus two times on the encrypted string and it will be back to plain text. def threeRailDecrypt(crypt): for i in range(len(crypt)-2): crypt = threeRailEncrypt(crypt) return(crypt) Hyperboreus solution is the proper one, but this is a bit simpler to understand I reckon. Example with the string test: test - untouched ttes - first iteration (encryption) tste - second iteration test - third iteration A: I will add a second answer with a completely different approach and more explicit code: def dec2 (cypher): length = len (cypher) if length < 4: return cypher third = length // 3 + (1 if length % 3 else 0) cypher = list (cypher) if length % 3 == 1: cypher.insert (third * 2 - 1, '') return ''.join (''.join (cypher [i::third] ) for i in range (third) ) Or just shock your teacher: enc = lambda p:''.join(p[_::3]for _ in range(3)) dec = lambda c:c if len(c)<4 else(lambda *a:(lambda c,t: ''.join(''.join(c[i::t])for i in range(t)))((lambda c,t, l:c[:t*2-1]+(['']if l%3==1 else[])+c[t*2-1:])(*a),a [2]) )(*(lambda c:(list(c),len(c),len(c)//3+(1 if len(c)%3 else 0)))(c)) A: This should work. You just need to figure out how long the different rails are: from itertools import zip_longest as zip def enc (plain, rails = 3): return ''.join (plain [i::rails] for i in range (rails) ) def dec (cypher, rails = 3): length = len (cypher) lens = [length // rails + (1 if length % rails > i else 0) for i in range (rails) ] paths = [cypher [sum (lens [:i] ):sum (lens [:i + 1] ) ] for i in range (rails) ] return ''.join (''.join (x for x in x if x) for x in zip (*paths) ) plain = 'abcdefghijk' for i in range (10): a = plain [:i] b = enc (a) c = dec (b) print (a, b, c) Should work for arbitrary (>0) number of rails used. EDIT: Without zip_longest: def enc (plain, rails = 3): return ''.join (plain [i::rails] for i in range (rails) ) def dec (cypher, rails = 3): length = len (cypher) lens = [length // rails + (1 if length % rails > i else 0) for i in range (rails) ] paths = [cypher [sum (lens [:i]):sum (lens [:i + 1] ) ] for i in range (rails) ] maxLen = len (paths [0] ) paths = [list (path) + ( [] if len (path) == maxLen else [''] ) for path in paths] return ''.join (''.join (x) for x in zip (*paths) ) Explanation of the decryption: length = len (cypher) Store the length of the cypher text in a local variable for convenience. lens = [length // rails + (1 if length % rails > i else 0) for i in range (rails) ] Now we calculate the length of each rail. The length of each rail is the length of the cypher text divided by the number of rails (in your case 3), and maybe (the if part) plus 1 if the length is not exactly divisible. paths = [cypher [sum (lens [:i] ):sum (lens [:i + 1] ) ] for i in range (rails) ] Now slice the cypher text into the different rails, according to the rail lengths we have just calculated. maxLen = len (paths [0] ) The maximum length of a rail is equal to the length of the first rail. paths = [list (path) + ( [] if len (path) == maxLen else [''] ) for path in paths] Now add an empty character to the end of each rail which is too short, so all rails have the same length and can be zipped. return ''.join (''.join (x) for x in zip (*paths) ) Zip the rails, join each resulting tuple into a string, then join all those strings into one long string and return it.
doc_23536439
doc_23536440
From RHEL: mpath114 (3600507680283095ea8000000000004fa) dm-28 IBM,2145 [size=200G][features=1 queue_if_no_path][hwhandler=0][rw] \_ round-robin 0 [prio=50][active] \_ 19:0:0:40 sdea 128:32 [active][ready] \_ 20:0:1:40 sdeb 128:48 [active][ready] \_ 20:0:1:41 sdec 128:16 [failed][faulty] \_ round-robin 0 [prio=10][enabled] \_ 20:0:0:40 sdba 67:64 [active][ready] \_ 19:0:1:40 sdgg 131:192 [active][ready] mpath131 (3600507680283095ea800000000000504) dm-39 IBM,2145 [size=10G][features=1 queue_if_no_path][hwhandler=0][rw] \_ round-robin 0 [prio=50][active] \_ 20:0:1:1 sdbl 67:240 [active][ready] \_ 19:0:0:1 sdc 8:32 [active][ready] \_ round-robin 0 [prio=10][enabled] \_ 19:0:1:1 sdet 129:80 [active][ready] \_ 20:0:0:1 sdk 8:160 [active][ready] [..] Or from SLES server: mpathmzp (36005076801c7061ef800000000000089) dm-0 IBM,2145 size=10G features='1 queue_if_no_path' hwhandler='0' wp=rw |-+- policy='round-robin 0' prio=50 status=enabled | `- 67:0:2:0 sde 8:64 active ready running | `- 68:0:0:1 sdl 8:76 failed faulty running `-+- policy='round-robin 0' prio=10 status=enabled |- 67:0:3:0 sdc 8:32 active ready running `- 68:0:0:0 sdd 8:48 active ready running [..] I would like to parse it (preferably with awk or bash), to display summary of the configuration. It should print the pseudo multipath device and the number of active paths and the failed (if any) Sample: dm-39, 10G, Total: 4 paths, active: 4, failed: 0 dm-28, 200G, Total: 5 paths, active: 4, failed: 1 Same for the SLES: dm-0, 10G, Total: 4 paths, active: 3, failed: 1 If also possible, I'd like to sort the output so that the paths with no failed and most active paths are on top, and end with the devicess with the failed paths. Thanks for helping! A: This awk should do: multipath -ll | awk 'NR>1 {r=f=0;for (i=1;i<=NF;i++) if ($i~/ready/) r++; else if ($i~/faulty/) f++;split($5,a,"=|]");print $3,a[2]"\tTotal: "r+f" paths, active: "r,"failed: "f}' RS="mpath" OFS=", " dm-28, 200G Total: 5 paths, active: 4, failed: 1 dm-39, 10G Total: 4 paths, active: 4, failed: 0
doc_23536441
$logoUrl = $this->getLogoUrl(); <img style="width: 100%;" src="<?php echo $logoUrl; ?>" alt="Logo"> how can i find out from console (ssh) the output of $this->getLogoUrl() ? i need to replace that logo and i cannot find the file. i tried the below statement but it outputs nothing: <?php $logoUrl = $this->getLogoUrl(); echo $logoUrl; ?> A: Use Mage::log('', null, 'mylog.log', true); Where is what gets printed in your log file. That should work all the time. Note: that your logs should be open from the admin section
doc_23536442
Here is a link to a codeSandBox having the code: https://codesandbox.io/s/material-demo-forked-chy0d?file=/demo.js Code: export default function MediaCard() { const classes = useStyles(); return ( <Card className={classes.root}> <a href="sdfs"> <CardActionArea style={{ paddingTop: 50 }}> <div style={{ position: "absolute", color: "white", top: 8, right: 8 }} > <Button style={{ background: "green", color: "white" }} onMouseDown={(e) => e.stopPropagation()} size="small" color="primary" > BUTTON </Button> </div> <CardMedia className={classes.media} image="https://media.tarkett-image.com/large/TH_25121916_25131916_25126916_25136916_001.jpg" title="Contemplative Reptile" /> <CardContent> <Typography gutterBottom variant="h5" component="h2"> jnikn </Typography> <Typography variant="body2" color="textSecondary" component="p"> ijneodsk ipknv onfp o nf onopndsfc on pnojnc olpnoinoi hbib iubn iujno nouno oijipj onoin ioio </Typography> </CardContent> </CardActionArea> </a> </Card> ); A: try this import React from "react"; import { makeStyles } from "@material-ui/core/styles"; import Card from "@material-ui/core/Card"; import CardActionArea from "@material-ui/core/CardActionArea"; import CardActions from "@material-ui/core/CardActions"; import CardContent from "@material-ui/core/CardContent"; import CardMedia from "@material-ui/core/CardMedia"; import Button from "@material-ui/core/Button"; import Typography from "@material-ui/core/Typography"; const useStyles = makeStyles({ root: { maxWidth: 345, position: "relative" }, media: { height: 140 // marginTop: 50 } }); export default function MediaCard() { const classes = useStyles(); return ( <Card className={classes.root}> <Button style={{ zIndex:'1000', position: "absolute", top: 8, right: 8,background: "green", color: "white",width:'70px',height:'30px' }} onMouseDown={(e) => e.stopPropagation()} size="small" color="primary" > BUTTON </Button> <a href="sdfs"> <CardActionArea style={{ paddingTop: 50 }}> <CardMedia className={classes.media} image="https://media.tarkett-image.com/large/TH_25121916_25131916_25126916_25136916_001.jpg" title="Contemplative Reptile" /> <CardContent> <Typography gutterBottom variant="h5" component="h2"> jnikn </Typography> <Typography variant="body2" color="textSecondary" component="p"> ijneodsk ipknv onfp o nf onopndsfc on pnojnc olpnoinoi hbib iubn iujno nouno oijipj onoin ioio </Typography> </CardContent> </CardActionArea> </a> </Card> ); }
doc_23536443
and on the part with the query: SELECT node.name FROM nested_category AS node, nested_category AS parent WHERE node.lft BETWEEN parent.lft AND parent.rgt AND parent.name = 'ELECTRONICS' ORDER BY node.lft; I'm wondering how is it travered? What happens step by step? I'm confused, please help. A: Well, the database system could execute the query several different ways with the same result, but here's one way to understand what's going on: Take 2 copies of the nested_category table, one named parent and the other named node. Find the row in parent named ELECTRONICS (the article you link to implies there's only one). The range parent.lft to parent.rgt gives any nodes with ELECTRONICS as an ancestor in the tree, at any depth. Sorting by node.lft means you'll get the sub-nodes of ELECTRONICS along the left side of the sub-tree first, in an pre-order traversal. It might be easier to walk through a simpler example to understand this: what if we choose TELEVISIONS instead of ELECTRONICS as the parent: The 'parent' set has only 1 row, because of [parent.name = 'TELEVISIONS']: { name: "TELEVISIONS", lft: 2, rgt: 9 } The 'node' set has the 4 rows that satisfy [node.lft between 2 and 9] because we can substitute the single lft/rgt values from parent: { name: "TELEVISIONS", lft: 2, rgt: 9 } { name: "TUBE", lft: 3, rgt: 4 } { name: "LCD", lft: 5, rgt: 6 } { name: "PLASMA", lft: 7, rgt: 8 } And, as you can see, the above 4 rows are alread sorted by "lft" values, so to satisfy the query, we just take the name values and we're done.
doc_23536444
Required String parameter 'email' is not present I've tried getting the params from HttpServletRequest and they are actually missing, but I have no clue why? Can anyone help me out please? Here is my html : <div id="form"> <form action="/authentication" method="post"> <input type="email" value="Email" id="email" onfocus=labelsOnFocus(this) onblur=labelOnDefocus(this) onchange=emailErrorOnTyping(this)> <p id = "emailError">Email not valide</p> <input type="password" value="Password" id="password" onfocus=labelsOnFocus(this) onblur=labelOnDefocus(this) onchange=passwordErrorOnTyping(this)> <p id="passwordError">Password to short</p> <div class="buttons"> <input type="submit" value="Login" class="submit"> <input type="button" value="Register" class="submit" onclick=register()> </div> </form> And here is my controller: public String authentication(@RequestParam("email") String email,@RequestParam("password") String password, Model model){ Map<String,String> map = new HashMap<>(); map.put("email",email); ..... A: When you use form with method="post", data send in post body, not in request params. https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_and_retrieving_form_data A: The @RequestParam annotation is for web request parameters not for the body of a POST. Try the @RequestBody parameter. Also, consider using the @ModelAttribute in your HTML and controller method to bind the form body to a POJO (see Baeldung's MVC Form tutorial). Lastly, with Spring Boot you should not have to implement the /authentication controller yourself. If you @EnableWebSecurity and correctly wire up an AuthenticationManager with your UserService you should get authentication "for free" (see Baeldung's Spring Security Tutorial). A: This is not the way POST request works. When you do a post request then the data is sent in RequestBody, not in RequestParam. You can change your code as public String authentication(@RequestBody Login login){ Map<String,String> map = new HashMap<>(); map.put("email",login.email); .....
doc_23536445
gulp.task('my-task', function() { return gulp.src(options.SCSS_SOURCE) .pipe(sass({style:'nested'})) .pipe(autoprefixer('last 10 version')) .pipe(concat('style.css')) .pipe(gulp.dest(options.SCSS_DEST)); }); Is it possible to pass a command line flag to gulp (that's not a task) and have it run tasks conditionally based on that? For instance $ gulp my-task -a 1 And then in my gulpfile.js: gulp.task('my-task', function() { if (a == 1) { var source = options.SCSS_SOURCE; } else { var source = options.OTHER_SOURCE; } return gulp.src(source) .pipe(sass({style:'nested'})) .pipe(autoprefixer('last 10 version')) .pipe(concat('style.css')) .pipe(gulp.dest(options.SCSS_DEST)); }); A: I built a plugin to inject parameters from the commandline into the task callback. gulp.task('mytask', function (production) { console.log(production); // => true }); // gulp mytask --production https://github.com/stoeffel/gulp-param If someone finds a bug or has a improvement to it, I am happy to merge PRs. A: Here's a quick recipe I found: gulpfile.js var gulp = require('gulp'); // npm install gulp yargs gulp-if gulp-uglify var args = require('yargs').argv; var gulpif = require('gulp-if'); var uglify = require('gulp-uglify'); var isProduction = args.env === 'production'; gulp.task('scripts', function() { return gulp.src('**/*.js') .pipe(gulpif(isProduction, uglify())) // only minify if production .pipe(gulp.dest('dist')); }); CLI gulp scripts --env production Original Ref (not available anymore): https://github.com/gulpjs/gulp/blob/master/docs/recipes/pass-params-from-cli.md Alternative with minimist From Updated Ref: https://github.com/gulpjs/gulp/blob/master/docs/recipes/pass-arguments-from-cli.md gulpfile.js // npm install --save-dev gulp gulp-if gulp-uglify minimist var gulp = require('gulp'); var gulpif = require('gulp-if'); var uglify = require('gulp-uglify'); var minimist = require('minimist'); var knownOptions = { string: 'env', default: { env: process.env.NODE_ENV || 'production' } }; var options = minimist(process.argv.slice(2), knownOptions); gulp.task('scripts', function() { return gulp.src('**/*.js') .pipe(gulpif(options.env === 'production', uglify())) // only minify if production .pipe(gulp.dest('dist')); }); CLI gulp scripts --env production A: Gulp doesn't offer any kind of util for that, but you can use one of the many command args parsers. I like yargs. Should be: var argv = require('yargs').argv; gulp.task('my-task', function() { return gulp.src(argv.a == 1 ? options.SCSS_SOURCE : options.OTHER_SOURCE) .pipe(sass({style:'nested'})) .pipe(autoprefixer('last 10 version')) .pipe(concat('style.css')) .pipe(gulp.dest(options.SCSS_DEST)); }); You can also combine it with gulp-if to conditionally pipe the stream, very useful for dev vs. prod building: var argv = require('yargs').argv, gulpif = require('gulp-if'), rename = require('gulp-rename'), uglify = require('gulp-uglify'); gulp.task('my-js-task', function() { gulp.src('src/**/*.js') .pipe(concat('out.js')) .pipe(gulpif(argv.production, uglify())) .pipe(gulpif(argv.production, rename({suffix: '.min'}))) .pipe(gulp.dest('dist/')); }); And call with gulp my-js-task or gulp my-js-task --production. A: There's a very simple way to do on/off flags without parsing the arguments. gulpfile.js is just a file that's executed like any other, so you can do: var flags = { production: false }; gulp.task('production', function () { flags.production = true; }); And use something like gulp-if to conditionally execute a step gulp.task('build', function () { gulp.src('*.html') .pipe(gulp_if(flags.production, minify_html())) .pipe(gulp.dest('build/')); }); Executing gulp build will produce a nice html, while gulp production build will minify it. A: And if you are using typescript (gulpfile.ts) then do this for yargs (building on @Caio Cunha's excellent answer https://stackoverflow.com/a/23038290/1019307 and other comments above): Install npm install --save-dev yargs typings install dt~yargs --global --save .ts files Add this to the .ts files: import { argv } from 'yargs'; ... let debug: boolean = argv.debug; This has to be done in each .ts file individually (even the tools/tasks/project files that are imported into the gulpfile.ts/js). Run gulp build.dev --debug Or under npm pass the arg through to gulp: npm run build.dev -- --debug A: If you've some strict (ordered!) arguments, then you can get them simply by checking process.argv. var args = process.argv.slice(2); if (args[0] === "--env" && args[1] === "production"); Execute it: gulp --env production ...however, I think that this is tooo strict and not bulletproof! So, I fiddled a bit around... and ended up with this utility function: function getArg(key) { var index = process.argv.indexOf(key); var next = process.argv[index + 1]; return (index < 0) ? null : (!next || next[0] === "-") ? true : next; } It eats an argument-name and will search for this in process.argv. If nothing was found it spits out null. Otherwise if their is no next argument or the next argument is a command and not a value (we differ with a dash) true gets returned. (That's because the key exist, but there's just no value). If all the cases before will fail, the next argument-value is what we get. > gulp watch --foo --bar 1337 -boom "Foo isn't equal to bar." getArg("--foo") // => true getArg("--bar") // => "1337" getArg("-boom") // => "Foo isn't equal to bar." getArg("--404") // => null Ok, enough for now... Here's a simple example using gulp: var gulp = require("gulp"); var sass = require("gulp-sass"); var rename = require("gulp-rename"); var env = getArg("--env"); gulp.task("styles", function () { return gulp.src("./index.scss") .pipe(sass({ style: env === "production" ? "compressed" : "nested" })) .pipe(rename({ extname: env === "production" ? ".min.css" : ".css" })) .pipe(gulp.dest("./build")); }); Run it gulp --env production A: Pass arguments from the command line // npm install --save-dev gulp gulp-if gulp-uglify minimist var gulp = require('gulp'); var gulpif = require('gulp-if'); var uglify = require('gulp-uglify'); var minimist = require('minimist'); var knownOptions = { string: 'env', default: { env: process.env.NODE_ENV || 'production' } }; var options = minimist(process.argv.slice(2), knownOptions); gulp.task('scripts', function() { return gulp.src('**/*.js') .pipe(gulpif(options.env === 'production', uglify())) // only minify in production .pipe(gulp.dest('dist')); }); Then run gulp with: $ gulp scripts --env development Source A: var isProduction = (process.argv.indexOf("production")>-1); CLI gulp production calls my production task and sets a flag for any conditionals. A: Edit gulp-util is deprecated and should be avoid, so it's recommended to use minimist instead, which gulp-util already used. So I've changed some lines in my gulpfile to remove gulp-util: var argv = require('minimist')(process.argv.slice(2)); gulp.task('styles', function() { return gulp.src(['src/styles/' + (argv.theme || 'main') + '.scss']) … }); Original In my project I use the following flag: gulp styles --theme literature Gulp offers an object gulp.env for that. It's deprecated in newer versions, so you must use gulp-util for that. The tasks looks like this: var util = require('gulp-util'); gulp.task('styles', function() { return gulp.src(['src/styles/' + (util.env.theme ? util.env.theme : 'main') + '.scss']) .pipe(compass({ config_file: './config.rb', sass : 'src/styles', css : 'dist/styles', style : 'expanded' })) .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'ff 17', 'opera 12.1', 'ios 6', 'android 4')) .pipe(livereload(server)) .pipe(gulp.dest('dist/styles')) .pipe(notify({ message: 'Styles task complete' })); }); The environment setting is available during all subtasks. So I can use this flag on the watch task too: gulp watch --theme literature And my styles task also works. Ciao Ralf A: We wanted to pass a different config file for different environments -- one for production, dev and testing. This is the code in the gulp file: //passing in flag to gulp to set environment //var env = gutil.env.env; if (typeof gutil.env.env === 'string') { process.env.NODE_ENV = gutil.env.env; } This is the code in the app.js file: if(env === 'testing'){ var Config = require('./config.testing.js'); var Api = require('./api/testing.js')(Config.web); } else if(env === 'dev'){ Config = require('./config.dev.js'); Api = require('./api/dev.js').Api; } else{ Config = require('./config.production.js'); Api = require('./api/production.js')(Config.web); } And then to run it gulp --env=testing A: It has been some time since this question has been posted, but maybe it will help someone. I am using GULP CLI 2.0.1 (installed globally) and GULP 4.0.0 (installed locally) here is how you do it without any additional plugin. I think the code is quite self-explanatory. var cp = require('child_process'), { src, dest, series, parallel, watch } = require('gulp'); // == availableTasks: log available tasks to console function availableTasks(done) { var command = 'gulp --tasks-simple'; if (process.argv.indexOf('--verbose') > -1) { command = 'gulp --tasks'; } cp.exec(command, function(err, stdout, stderr) { done(console.log('Available tasks are:\n' + stdout)); }); } availableTasks.displayName = 'tasks'; availableTasks.description = 'Log available tasks to console as plain text list.'; availableTasks.flags = { '--verbose': 'Display tasks dependency tree instead of plain text list.' }; exports.availableTasks = availableTasks; And run from the console: gulp availableTasks Then run and see the differences: gulp availableTasks --verbose
doc_23536446
The requested behavior is that the border-style that was selected would appear when the dropdown is closed, and when opened, the selected option will be marked. The best way was to add styling on a native select, if that was possible. So it led me to the naive solution of images as the options element, but I was wondering if there was anything better that could be achieved using css. I tried using bootstrap in order to create it, but bootstrap dropdown opens through a button, and then I lose the "show selected" requirement. A: You can try this: p.dotted {border-style: dotted;} p.dashed {border-style: dashed;} p.solid {border-style: solid;} p.double {border-style: double;} p.groove {border-style: groove;} p.ridge {border-style: ridge;} p.inset {border-style: inset;} p.outset {border-style: outset;} p.none {border-style: none;} p.hidden {border-style: hidden;} p.mix {border-style: dotted dashed solid double;} <p>This property specifies what kind of border to display:</p> <p class="dotted">A dotted border.</p> <p class="dashed">A dashed border.</p> <p class="solid">A solid border.</p> <p class="double">A double border.</p> <p class="groove">A groove border.</p> <p class="ridge">A ridge border.</p> <p class="inset">An inset border.</p> <p class="outset">An outset border.</p> <p class="none">No border.</p> <p class="hidden">A hidden border.</p> <p class="mix">A mixed border.</p> link:-http://www.w3schools.com/css/css_border.asp A: It's a bit complicated, but here's a working codepen: http://codepen.io/krabbypattified/pen/pEBAgP It uses a custom-made dropdown and passes values to an HTML5 dropdown (which you can hide) Let me know if you have questions and I'll revise my answer accordingly. HTML <div class="dropdown"> <button onclick="showHide()" class="dropbtn">Dropdown</button> <div id="borderList"> <!-- See CSS --> <p><span></span></p> <p><span></span></p> <p><span></span></p> <p><span></span></p> </div> </div> <form> <select id="selector"> <option value="solid">This form will be hidden.</option> <option value="dashed">Dashed (words not required here, just values)</option> <option value="dotted" /> <option value="double" /> <option value="groove" /> </select> </form> SCSS /* Border styles */ $borders: solid, dashed, dotted, double, groove; #borderList p span { border-top: 5px solid black; display: block; } @for $i from 1 through length($borders) { #borderList p:nth-child(#{$i}) span { border-top-style: nth($borders, $i); } } /* Dropdown styles */ .hide { display: none !important } .show { display: block !important } .dropdown { position: relative; display: inline-block; } .dropbtn { background-color: #4CAF50; color: white; padding: 16px; font-size: 16px; border: none; cursor: pointer; &:hover, &:focus { background-color: #3e8e41 } } #borderList { display: none; position: absolute; background-color: #f9f9f9; min-width: 110px; box-shadow: 0px 8px 5px 0px rgba(0, 0, 0, 0.2); p { cursor: pointer; margin: 0; height: 0; padding: 18px 0 24px 0; &:hover { background-color: #ddd } } } JS // Added jQuery // Pass the selected option to a hidden form $('#borderList').children().each(function(index) { this.addEventListener('click', function(){syncToForm(index)}); }); function syncToForm(index) { var selector = document.getElementById("selector"); selector.options.selectedIndex = index; } // Toggle show/hide dropdown function showHide() { $('#borderList').toggleClass('show'); } // Close the dropdown if clicked elsewhere on page window.onclick = function(e) { if (!e.target.matches('.dropbtn') && $('#borderList').hasClass('show')) { $('#borderList').removeClass('show'); } } A: Thanks everyone, I found what I was looking for (select with thumbnails): http://thdoan.github.io/bootstrap-select/examples.html
doc_23536447
I've successfully followed the instructions at https://pypi.python.org/pypi/mod_wsgi to set things up so I have an empty Django project being served over port 80 on an AWS Linux AMI EC2 server using mod_wsgi. I use this command to start serving the Django project: python manage.py runmodwsgi --setup-only --port=80 --user apache --group apache --server-root=/etc/mod_wsgi-express-80 This seems to create a separate Apache instance with its own configuration that only serves the Django project, independent of the system Apache installation. However, I also want to be able to serve phpMyAdmin, say on port 81, but I'm not sure which Apache instance I'm supposed to modify (and the httpd.conf for the mod_wsgi instance is very different from the default). How should I configure my virtual hosts (and which instance should I be modifying) so that going to <ip-address>:81/phpmyadmin gives me access to phpMyAdmin? Currently, going to that address just times out. Going to <ip-address> gives me the "It worked!" page as expected. My current modifications to my main httpd.conf: Listen 81 Include sites-enabled/*.conf WSGIScriptAlias /process /home/ec2-user/test/test_site/test_site/wsgi.py WSGIPythonPath /home/ec2-user/test:/home/ec2-user/.virtualenvs/venv/lib/python3.5/site-\packages <Directory /home/ec2-user/test/test_site/test_site> <Files wsgi.py> Order deny,allow Allow from all Require all granted </Files> </Directory> ExtendedStatus On Options -Indexes FollowSymLinks The .conf file to serve phpMyAdmin (is there just something missing here?) <VirtualHost *:81> ServerName phpmyadmin DocumentRoot /var/www-81 #symlinked to '/usr/share/phpMyAdmin' </VirtualHost> A: Read the blog post which talks about using mod_wsgi and PHP at same time: * *http://blog.dscpl.com.au/2014/09/hosting-php-web-applications-in.html
doc_23536448
It wouldn't have to be nearly as feature-rich (nor specifically for VS2010), just as long as one could do it without typing up sample data in xaml files. I just want a sample data generator of some sort that can generate the data in xaml data files. Bonuses: * *friendly UI *usable within Visual Studio 2010 *sample data works between Expression Blend 4 and VS2010 (not as important)
doc_23536449
SELECT DISTINCT FunctionNbr,FunctionDesc, MAX(date_altered) FROM Persontable WHERE FunctionNbr IN ('00000001','00000002','00000003') AND LEN(RTRIM(FunctionDesc)) > 0 GROUP BY FunctionNbr,FunctionDesc the persontable contains all the employees with their respective function. the date_altered may vary depending on changes made on SAP. My expected output would be that i get a record for every employee with one of those functionNbr and with the same date_altered. example of expected output: FunctionNbr | FunctionDesc | date_altered -------------------------------------------- 00000001 | Function A | 2014-01-01 (=row from employee 001 with functionNbr = 0000001 and date_altered = 2013-12-20) 00000001 | Function A | 2014-01-01 (=row from employee 002 with functionNbr = 0000001 and date_altered = 2013-12-24) 00000001 | Function A | 2014-01-01 (=row from employee 003 with functionNbr = 0000001 and date_altered = 2014-01-01) 00000002 | Function B | 2013-12-13 (=row from employee 004 with functionNbr = 0000002 and date_altered = 2013-12-13) 00000002 | Function B | 2013-12-13 (=row from employee 005 with functionNbr = 0000002 and date_altered = 2013-12-11) yet my output looks as follows: FunctionNbr | FunctionDesc | date_altered -------------------------------------------- 00000001 | Function A | 2013-12-20 (=row from employee 001 with functionNbr = 0000001 and date_altered = 2013-12-20) 00000001 | Function A | 2013-12-24 (=row from employee 002 with functionNbr = 0000001 and date_altered = 2013-12-24) 00000001 | Function A | 2014-01-01 (=row from employee 003 with functionNbr = 0000001 and date_altered = 2014-01-01) 00000002 | Function B | 2013-12-13 (=row from employee 004 with functionNbr = 0000002 and date_altered = 2013-12-13) 00000002 | Function B | 2013-12-11 (=row from employee 005 with functionNbr = 0000002 and date_altered = 2013-12-11) Question: In this case, Why doensn't the MAX() function always take the last date_altered Note: For every employee there is only 1 row A: It is very possible that the table's dates are stored as text. Try this; SELECT FunctionNbr,FunctionDesc, MAX(CAST(date_altered AS DATETIME) FROM Persontable WHERE FunctionNbr IN ('00000001','00000002','00000003') AND LEN(RTRIM(FunctionDesc)) > 0 GROUP BY FunctionNbr,FunctionDesc I've removed the DISTINCT as correctly suggested by RBarryYoung
doc_23536450
code to get pagereference from parent component: var pageReference = component.get("v.pageReference"); console.log('getpropertyDetails pageReference'+JSON.stringify(pageReference)); A: This is probably because you are trying to access an attribute from an object which is null. In the getSelectedProperty method object associated with the state attribute is null.
doc_23536451
Thanks in advance for all helps protected void Page_Load(object sender, EventArgs e) {... foreach (Gift g in bonusGifts) { ImageButton ib = new ImageButton(); ib.ImageUrl = g.GiftBanner; ib.ID = g.GiftID.ToString(); ib.Click += Purchase(g); BonusGiftPanel.Controls.Add(ib); } } private ImageClickEventHandler Purchase(Gift g) { _giftRep.Purchase(g, _userSession.CurrentUser); lblGifts.Text = "You have purcased " + g.GiftName + " for " + g.BonusPoints; return null; } A: Add controls in your Page_Init, not in your Page_Load. [1] Furthermore, you are not doing this the way it should. Consider this code //your collection of objects goes here. It might be something different than //this, but basically a Dictionary<int, YourType> goes fine public Dictionary<Int32, string> Ids { get { return (ViewState["ids"] ?? new Dictionary<Int32, string>()) as Dictionary<Int32, string>; } set { ViewState["ids"] = new Dictionary<Int32, string>(); } } protected void Page_Init(object sender, EventArgs e) { //load the data using your DAO Ids = new Dictionary<int, string>(); Ids.Add(1, "http://www.huddletogether.com/projects/lightbox2/images/image-2.jpg"); Ids.Add(2, "http://helios.gsfc.nasa.gov/image_euv_press.jpg"); foreach (var item in Ids) { ImageButton imb = new ImageButton() { ImageUrl = item.Value, CommandArgument = item.Key.ToString(), CommandName = "open" }; imb.Click += new ImageClickEventHandler(imb_Click); PH1.Controls.Add(imb); } } void imb_Click(object sender, ImageClickEventArgs e) { Response.Write("You purchased " + Ids[int.Parse(((ImageButton)sender).CommandArgument)]); } [1] (CTRL+C/CTRL+V from some other question I answered last week): Everything that has to be maintained between page cycles should be declared in Page_Init, not Page_Load. All the initialization, like adding event handlers, and adding controls should be added during initialization, as the state is saved between page cycles. Handling with the content of controls and the viewstate, should be done in Load. Check also http://msdn.microsoft.com/en-us/library/ms178472.aspx. Init Raised after all controls have been initialized and any skin settings have been applied. Use this event to read or initialize control properties. . Load The Page calls the OnLoad event method on the Page, then recursively does the same for each child control, which does the same for each of its child controls until the page and all controls are loaded. Use the OnLoad event method to set properties in controls and establish database connections. A: You need to take a look at the Page Lifecycle - http://msdn.microsoft.com/en-us/library/ms178472.aspx A: You should add the controls in the Page Init event, as other have said. Your image click event handler does not conform to the ImageButton Click event handler signature. That should look something like this: private void ImageButton_Click(ByVal sender As Object, ByVal e As ImageClickEventArgs) { } Note that you can't pass your "Gift" object directly to the ImageButton_Click. You will have to find another method of doing that.
doc_23536452
<form name="myForm" novalidate> <input type="number" ng-model="age" name="age" ng-pattern="/^[0-9]+$/" /> <h3>Valid Status : {{myForm.age.$valid}}</h3> </form> Input: 123 Output: myForm.age.$valid - true Input: -123 Output: myForm.age.$valid - false Input: +123 Output: myForm.age.$valid - true (shouldn't be true) https://plnkr.co/edit/3OVE6qiWgJozUb3hyFQ5?p=preview A: If you want to make the pattern work, you need to set the type attribute to text. Since you also want to let users type only digits into the input field, add an onkeypress validation: <input type="text" onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57" ng-model="age" name="age" ng-pattern="/^[0-9]+$/" /> Actually, you won't even need the ng-pattern regex then. A: You can just use: ng-pattern="/^[0-9]+$/" Without setting the input type to number (as default it is text and it should work fine). Here JSFiddle: https://jsfiddle.net/3ju3b2tu/1/
doc_23536453
The component I'm working on is a small collection of filter components: One input text field and two buttons, all filtering a list of entities. I've tried two approaches: First approach: Single component containing three instances of two types of containers, containers connected to corresponding components. This was what I first made. Here, the root component looks like the following: import React, { PropTypes, Component } from 'react'; import Config from '../../config'; import FilterInput from '../containers/FilterInput'; import FilterLink from '../containers/FilterLink' class FilterController extends Component { render() { return ( <div className='filterController'> <FilterInput displayName="Search" filterName={Config.filters.WITH_TEXT} /> <FilterLink displayName="Today" filterName={Config.filters.IS_TODAY} /> <FilterLink displayName="On TV" filterName={Config.filters.ON_TV} /> </div> ) } } export default FilterController; The two containers referenced here look pretty much as expected, as do the connected components. I'll show the FilterLink as an example: import React, { PropTypes, Component } from 'react'; import {connect} from 'react-redux'; import {toggleFilter} from '../actions'; import FilterButton from '../components/filterbutton' const mapStateToProps = (state, ownProps) => { return { active: !!state.program.filters[ownProps.filterName] } } const mapDispatchToProps = (dispatch, ownProps) => { return { onClick: () => { dispatch(toggleFilter(ownProps.filterName, ownProps.input)) } } } const FilterLink = connect( mapStateToProps, mapDispatchToProps )(FilterButton) export default FilterLink And the corresponding FilterButton component: import React, { PropTypes, Component } from 'react'; class FilterButton extends Component { render() { return ( <button className={this.props.active ? 'active' : ''} onClick={this.props.onClick}> {this.props.displayName} </button> ) } } FilterButton.propTypes = { active: PropTypes.bool.isRequired, displayName: PropTypes.string.isRequired, onClick: PropTypes.func.isRequired, filterName: PropTypes.string.isRequired }; export default FilterButton; This approach works, but I'm thinking that it shouldn't be necessary to create two different containers. Which again lead me to my second attempt. Second approach: single container containing multiple components. Here, I made a larger container: import React, { PropTypes, Component } from 'react'; import Config from '../../config'; import {connect} from 'react-redux'; import {toggleFilter} from '../actions'; import FilterButton from '../components/filterbutton' import FilterInput from '../components/filterinput' class FilterContainer extends Component { render() { const { active, currentInput, onChange, onClick } = this.props; return ( <div className='filterController'> <FilterInput displayName="Search" filterName={Config.filters.WITH_TEXT} currentInput={currentInput} onChange={onChange} /> <FilterButton displayName="Today" filterName={Config.filters.IS_TODAY} active={active} onClick={onClick}/> <FilterButton displayName="On TV" filterName={Config.filters.ON_TV} active={active} onClick={onClick}/> </div> ) } } const mapStateToProps = (state, ownProps) => { return { active: !!state.program.filters[ownProps.filterName], currentInput: state.program.filters[ownProps.filterName] ? state.program.filters[ownProps.filterName].input : '' } } const mapDispatchToProps = (dispatch, ownProps) => { return { onClick: () => { dispatch(toggleFilter(ownProps.filterName, ownProps.input)) }, onChange: newValue => { dispatch(toggleFilter(ownProps.filterName, newValue.target.value)) } } } export default connect( mapStateToProps, mapDispatchToProps )(FilterContainer); Here, all state interaction for the entire component is gathered in a single compoment. The components are the same here as in the first approach. This doesn't, however, really work: ownProps is empty in both mapStateToProps and mapDispathToProps. I may have misunderstood how the react-redux connection works. So, given these things I have two questions: What's the best way to structure this component, in terms of containers and components? And secondly, why won't ownProps work similarily in the second approach as in the first? Thank you for your time. A: Not sure I have a specific answer regarding structure at the moment. As for "ownProps", that represents props that are specifically being passed in to a given component by its parent. Since you're connect()-ing FilterController, that means that "ownProps" would be coming from wherever you render that component, like: return <FilterController prop1="a" prop2={someVariable} />. Based on how you have those map functions written, it looks like you really want to be connecting the FilterInput and FilterButton components rather than FilterController.
doc_23536454
Here is the template in use: <source> @type forward port 24224 bind 0.0.0.0 tag GELF_TAG </source> <filter GELF_TAG.**> @type parser key_name log reserve_data false <parse> @type json </parse> </filter> <match GELF_TAG.**> @type copy <store> @type gelf host {{ graylog_server_fqdn }} port 12201 protocol tcp flush_interval 5s </store> <store> @type stdout </store> </match> How do I set up the config to be able to capture the entrypoint.sh output and the json output from the containers after they start? EDIT. The filter is rejecting messages sent to the docker containers stdout up until the application starts logging in json. [warn]: #0 dump an error event: error_class=Fluent::Plugin::Parser::ParserError error="pattern not matched with data So I tried to capture everything that was being drooped into the ERROR tag and I can see the missing messages but they still fail to parse using this config: # Ansible <source> @type forward port 24224 bind 0.0.0.0 tag GELF_TAG </source> <filter GELF_TAG.**> @type parser emit_invalid_record_to_error true key_name log reserve_data false <parse> @type json </parse> </filter> <match {GELF_TAG.**,@ERROR}> @type copy <store> @type gelf host {{ graylog_server_fqdn }} port 12201 protocol tcp flush_interval 5s </store> <store> @type stdout </store> </match> A: Install the multi-format parser: td-agent-gem install fluent-plugin-multi-format-parser -v 1.0.0 # Ansible <source> @type forward port 24224 bind 0.0.0.0 tag GELF_TAG </source> <filter GELF_TAG.**> @type parser key_name log reserve_data false <parse> @type multi_format <pattern> format json time_key timestamp </pattern> <pattern> format none </pattern> </parse> </filter> <match GELF_TAG.**> @type copy <store> @type gelf host {{ graylog_server_fqdn }} port 12201 protocol tcp flush_interval 5s </store> <store> @type stdout </store> </match> A: You can also use the 'rewrite_tag_filter' which is an output plugin. Using that you can change the tag for the different patterns, and then use the parsers/filters.
doc_23536455
Here's my code try { JSONArray jArray = new JSONArray(result); String s=""; Log.w("Lengh",""+jArray.length()); for(int i=0;i<jArray.length();i++){ ListView lv=getListView(); JSONObject json_data = jArray.getJSONObject(i); s=json_data.getString("Cname"); HashMap<String, String> map = new HashMap<String, String>(); map.put("Zname",s/*json_data.getString("Cname")*/); val.add(map); ListAdapter ad=new SimpleAdapter(Second.this,val,R.layout.v,new String[]{"Zname","Zname"},new int[]{R.id.textView1,R.id.textView2}); setListAdapter(ad); Log.i("cname",s); } A: Simply set the adapter to your ListView as defined in layout xml. SimpleAdapter adapter = new SimpleAdapter(Second.this,val,R.layout.v,new String[]{"Zname","Zname"},new int[]{R.id.textView1,R.id.textView2}); ListView list = (ListView) findViewById(R.id.list); list.setAdapter(adapter); and in your activity layout xml file would be: <ListView android:id="@+id/list" ... /> A: Try something like this Adapter adapter = new SimpleAdapter(Second.this,val,R.layout.v,new String[]{"Zname","Zname"},new int[]{R.id.textView1,R.id.textView2}); ListView listView = (ListView) findViewById(R.id.listView1); listView.setAdapter(adapter); You can also make custom adapter. A: Check the below link Android ListView with Adapter Example Also check Android ListView – Tutorial and basic example
doc_23536456
<header - 2 rows> <data> <footer - 1 row> I am having an external hive table build on top of this dataset. Below is my hive ddl: create external table ext_test ( id string, name string, age string ) row format DELIMITED FIELDS TERMINATED BY ',' STORED AS TEXTFILE LOCATION '<hdfs file location>' TBLPROPERTIES ('skip.footer.line.count'='1', 'skip.header.line.count'='2') When i query select * from ext_test in HIVE; i am getting the exact number of rows as expected from the external table. But when i run the exact same query in IMPALA, i receive one additional row which is basically the footer property. e.g: The below example will clear out the scenario: Sample Data in the Feed: Header,Sample-03122018, ID,NAME,AGE 1,R,10 2,RR,11 3,RRR,12 Footer,End of Report, Output when i run select command in HIVE using the above DDL [Expected Output]: 1,R,10 2,RR,11 3,RRR,12 Output when i run select command in IMPALA using the above DDL: [Issue] 1,R,10 2,RR,11 3,RRR,12 Footer,End of Report,Null Did you face similar issue? If yes, please advice me of the suitable solution. A: This feature is not implemented in Impala yet, see this Jira IMPALA-7196. Impala doesn't recognize skip.footer.line.count, so it is effectively ignored. The workaround is to query using filter WHERE ID <> 'Footer', or cut the file footers before loading files into table directory.
doc_23536457
A: Try something like this for Xamarin.Forms : public class SamplePage : ContentPage { public SamplePage () { var editText = new Entry { Placeholder = "Select Date.", }; var date = new DatePicker { IsVisible = false, IsEnabled = false, }; var stack = new StackLayout { Orientation = StackOrientation.Vertical, Children = {editText, date} }; editText.Focused += (sender, e) => { date.Focus(); }; date.DateSelected += (sender, e) => { editText.Text = date.Date.ToString(); }; Content = stack; } } Edit : Try something like this for Xamarin.Android : MyLayout.axml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/editText" /> </LinearLayout> MyLayoutActivity.cs using System; using Android.App; using Android.OS; using Android.Widget; namespace AndiNative { [Activity (Label = "MyLayoutActivity", MainLauncher = true)] public class MyLayoutActivity: Activity { private static EditText editText; protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); SetContentView (Resource.Layout.DatePickerTest); editText = FindViewById<EditText> (Resource.Id.editText); editText.Click += (sender, e) => { DateTime today = DateTime.Today; DatePickerDialog dialog = new DatePickerDialog(this, OnDateSet, today.Year, today.Month - 1, today.Day); dialog.DatePicker.MinDate = today.Millisecond; dialog.Show(); }; } void OnDateSet(object sender, DatePickerDialog.DateSetEventArgs e) { editText.Text = e.Date.ToLongDateString(); } } } A: For those of you who like MVVM. This is the MVVM implementation in Xamarin Forms. I've used Event to Command behavior here. You can get more on that from this link Xamarin Event to Command Behaviors Xaml <Entry Text="{Binding DateOfBirth, Mode=TwoWay}" /> <Image Source="button.png" WidthRequest="39"> <Image.GestureRecognizers> <TapGestureRecognizer Command="{Binding OnSelectDOBCommand}" CommandParameter="{Binding ., Source={Reference DOBPicker}}" /> </Image.GestureRecognizers> </Image> <DatePicker x:Name="DOBPicker" Date="{Binding SelectedDOB}" IsEnabled="True" IsVisible="False"> <DatePicker.Behaviors> <behaviors:DatePickerSelectedBehavior Command="{Binding DateSelectedCommand}" EventName="DateSelected" /> </DatePicker.Behaviors> </DatePicker> View Model Code OnSelectDOBCommand = new RelayCommand<DatePicker>(FocusDatePicker); DateSelectedCommand = new RelayCommand(SetDateOfBirth); Now the function definitions private void FocusDatePicker(DatePicker obj) { obj.Focus(); } private void SetDateOfBirth() { DateOfBirth = SelectedDOB; } Hope this helps someone Update 11/11/2016 The other alternative is to to use ACR.Userdialogs simple and straightforward. Declare your ICommand OnSelectDOBCommand = new RelayCommand(ShowDatePicker); Next define the function ShowDatePicker private void ShowDatePicker() { UserDialogs.Instance.DatePrompt(new DatePromptConfig { MaximumDate = MaxDate, OnAction = (result) => SetDateOfBirth(result), IsCancellable = true }); } And the set date of birth function private void SetDateOfBirth(DatePromptResult result) { if(result.Ok) { DateOfBirth = result.SelectedDate.ToString("dd MMM yyyy"); } } The best part, you dont need any special Xaml at all. You can hook it to any button. Allan should be given an award or something A: <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginBottom="15dp" android:id="@+id/datePickerText" android:textColor="@color/textColor" android:textColorHint="@color/textColor" android:textSize="14dp" local:MvxBind="Value Format('{0:dd MMM yyyy}',Date)" /> property in viewmodel- private DateTime _date = DateTime.Today; public DateTime Date { get { return _date; } set { _date = value; RaisePropertyChanged(() => Date); } } Inside my Class- private EditText datePickerText; private DatePickerDialogFragment dialog; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.report); var dp = new MvxDatePicker(this); dp.SpinnersShown = true; dp.DateTime = DateTime.Now; datePickerText.Focusable = false; datePickerText.Text = ViewModel.Date.ToString("dd-MMM-yyyy"); datePickerText.Click += (sender, args) => { if(datePickerText.Text == "") dialog = new DatePickerDialogFragment(this, DateTime.Now,this); else dialog = new DatePickerDialogFragment(this,Convert.ToDateTime(datePickerText.Text), this); dialog.Show(this.SupportFragmentManager, "date"); }; datePickerText.TextChanged += (sender, args) => { ViewModel.Date = Convert.ToDateTime(datePickerText.Text); }; } public void OnDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { datePickerText.Text = new DateTime(year, monthOfYear + 1, dayOfMonth).ToString("dd-MMM-yyyy"); } here it takes the default date for today orelse it changes to date selected by user A: Whilst I found all the answers interesting and useful to varying degrees, nothing quite covered it. Here's how to do it for plain old Xamarin.Android. public class MyActivity : MyActivityBase { private int _dateViewId { get; set; } private DateTime _myDate { get; set; } protected override void OnCreate (Bundle savedInstanceState) { base.OnCreate (savedInstanceState); SetContentView (Resource.Layout.activity_my); InitDateField (); } private void InitDateField () { var rootLayout = FindViewById (Resource.Id.your_root_xaml_layout); rootLayout.AddView (GetNewDateView ()); } private View GetNewDateView () { var view = new EditText (this); view.InputType = InputTypes.DatetimeVariationDate; view.Hint = "Insert date"; view.Id = View.GenerateViewId (); view.FocusChange += DateField_Click; view.Click += DateField_Click; return view; } private void DateField_Click (object sender, EventArgs e) { var view = (sender as EditText); if (view.IsFocused) { _dateViewId = view.Id; var date = DateTime.Today; // NB. The month needs translating here for the datepicker. var dialog = new DatePickerDialog (this, OnDateSet, date.Year, date.Month - 1, date.Day); dialog.Show (); } } private void OnDateSet (object sender, DatePickerDialog.DateSetEventArgs e) { // Store the date value for use in code. _myDate = e.Date; // Display the date in the desired format. var dateView = FindViewById<EditText> (_dateViewId); dateView.Text = e.Date.ToString ("dd/MM/yyyy"); } } The datepicker dialog is triggered in either of two ways: - 1. Tap directly on the date field. 2. Arrival by tabbing Next in the keyboard whilst focused on the previous field. Because the OnDateSet() method doesn't have prior knowledge of the EditText.Id, the Id is stored when triggering the datepicker ready to be used when updating its value afterwards.
doc_23536458
When I am trying to create the hover DropDownMenu It just won't work with the other stuff goes on my CSS file. it shows the button itself (half of it) and when you hover. it does change his color but nothing really happends. No list opened. Picture of it (The CSS copied from the w3s School code they offer) Thanks for helping! Hope to hear from you guys soon. The MasterPage Code: <%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Nua </title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="assets/css/main.css" /> <asp:ContentPlaceHolder id="head" runat="server"> </asp:ContentPlaceHolder> </head> <body> <style> .topleft { position: absolute; top: 0px; left: 9%; font-size: 16px; } .topLeftSecond { position: absolute; top: 0px; left: 17.5%; font-size: 16px; } </style> <form id="form1" runat="server"> <% if (Session["Level"].ToString().Equals("-1")) { %> <div class="icon-bar"> <a class="active" href="HomePage.aspx"><i class="fa fa-home"></i></a> <a href="Login.aspx">Login <i class="fa fa-sign-in"></i></a> <a href="Register.aspx">Register <i class="fa fa-pencil"></i></a> <a class="more" href="HomePage.aspx#main">About <i class="fa fa-info-circle"> </i></a> </div> <%} %> <%-- This is the Drop down menu code--%> <%if (Session["Level"].ToString().Equals("1")) { %> <div class="dropdown"> <button class="dropbtn">Here</button> <div class="dropdown-content"> <a href="AdminArea.aspx">Link 1</a> <a href="WorkersPage.aspx">Link 2</a> </div> </div> <%} %> <div> <!-- Scripts --> <script src="assets/js/jquery.min.js"></script> <script src="assets/js/jquery.scrolly.min.js"></script> <script src="assets/js/jquery.poptrox.min.js"></script> <script src="assets/js/skel.min.js"></script> <script src="assets/js/util.js"></script> <script src="assets/js/main.js"></script> <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server"> </asp:ContentPlaceHolder> </div> </form> </body> </html> i hope I posted it right O-o A: Three things: * *For .dropdown set display: inline-block - now it has full page width *For .dropdown .dropbtn set height: auto - now it gets 32px from styles for button *You lost below code, which shows menu on hover: .dropdown:hover .dropdown-content { display: block; } A: Lost you my friend. * *.dropdown Display : inline-block - is already exist (?) *what .dropdown .dropbtn? *I lost code? This is the DropdownMenu CSS code. ul { list-style-type: none; margin: 0; padding: 0; background-color: #555; } li { float: left; } li a, .dropbtn { display: inline-block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; } li a:hover, .dropdown:hover .dropbtn { background-color: red; } li.dropdown { display: inline-block; } .dropdown-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; text-align: left; } You mean the code you just write down .dropdown:hover .dropdown-content { display: block; } I need to add that to this code above ^^? Thanks for help tho! please explain.
doc_23536459
This is basically the code around the error (I removed the unimportant parts to make it clearer): package ui.levelSelect { import flash.display.MovieClip; public class LevelsContainer extends MovieClip { public var levelThumbs:Array; public var levels:Array = [{name:'level1'},{name:'level2'}]; public function LevelsContainer(){ for(var i:String in levels) { var index:int = int(index); levelThumbs[index] = new MovieClip; //This is the line where I get the error } } } } What causes this error? levelThumbs is already declared right? Changing it to this.levelThumbs doesn't work either... A: Simply declaring a variable does not allocate any memory for the object, and thus have the value null. You have to actually allocate memory for levelThumbs array by calling new Array or []. public var levelThumbs:Array = new Array; or public var levelThumbs:Array = [];
doc_23536460
I have WPS office as application to run these. But the problem is that when i use the below code then directly file is opened in WPS office application. And if i change to target.setDataAndType(Uri.fromFile(open), "application/pdf"); then it show adobe reader and WPS office as option. Is there any way that i get best possible option to open the file without specifying specifically /pdf or /msword? such that i get possible app list according to input type. Intent target = new Intent(Intent.ACTION_VIEW); target.setDataAndType(Uri.fromFile(open), "application/msword"); target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); Intent intent = Intent.createChooser(target, "Open File"); try { startActivity(intent); } catch (ActivityNotFoundException e) { // Instruct the user to install a PDF reader here, or // something Toast.makeText( getApplicationContext(), "Please install proper document reader in your device to open this file", Toast.LENGTH_SHORT).show(); } A: I am assuming that you want to open applications using the extension of the file, without specifying the application/*. File file = new File(filePath); MimeTypeMap map = MimeTypeMap.getSingleton(); String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName()); String type = map.getMimeTypeFromExtension(ext); if (type == null) type = "*/*"; Intent intent = new Intent(Intent.ACTION_VIEW); Uri data = Uri.fromFile(file); intent.setDataAndType(data, type); startActivity(intent); This should get the extension and open the 'best possible' application
doc_23536461
I tried .each to loop and check the form for empty inputs but even when the form is filled up it still returns as empty. My html form: <form id="register_form" role="form" > <label >First Name</label> <input id="inN"data-error="Enter first name." required> <div class="help-block with-errors"></div> </div> <label>Last Name</label> <input id="inL" data-error="Enter last name." required> <div class="help-block with-errors"></div> </div> </div> <label for="inputEmail" class="control-label">Email</label> <input type="email" class="form-control" id="inputEmail" data-error="Enter email." required> <div class="help-block with-errors"></div> </div> </div> </form> This is my javascript: $('#register_form').each(function() { if ( $(this).val() === '' ){ console.log($(this).val()); // empty even when form is not vm.message = 'One or Two fields are empty. Please fill up all fields' document.getElementById("message").textContent=vm.message; // message on the modal }; }); A: You have to use $('#register_form input').each instead of $('#register_form').each to loop through all the input fields present in form. Please note that, if you have select box or textarea fields in your real form then this code needs to be modified accordingly. I will also suggest you to look at JQuery Validate plugin which do all these work for you. $(document).ready(function() { $("#submitButton").click(function() { ValidateForm(); }); }); function ValidateForm() { var formInvalid = false; $('#register_form input').each(function() { if ($(this).val() === '') { formInvalid = true; } }); if (formInvalid) alert('One or Two fields are empty. Please fill up all fields'); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <form id="register_form" role="form"> <label>First Name</label> <input id="inN" data-error="Enter first name." required> <div class="help-block with-errors"></div> </div> <label>Last Name</label> <input id="inL" data-error="Enter last name." required> <div class="help-block with-errors"></div> </div> </div> <label for="inputEmail" class="control-label">Email</label> <input type="email" class="form-control" id="inputEmail" data-error="Enter email." required> <div class="help-block with-errors"></div> </div> </div> <button id="submitButton">Submit</button> </form> A: try below code replace jquery selector with below code $('#register_form input') you can simply fix it. A: var allInput = $('input'); $.each(allInput,function(){ //looping through all input assuming u have one form in the page u can pass form id and grab input too if($(this).val() == ""){ alert('empty'); //do something append error msgs etc } else { alert('you can go'); } }); A: It always show you blank value in text box, because when your JavaScript code execute that time all text box reset, check below image for more details. A: <script> $(document).ready(function() { $('#signupForm') .formValidation({ framework: 'bootstrap', err: { container: '#errors' }, icon: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, fields: { firstName: { row: '.col-xs-4', validators: { notEmpty: { message: 'The first name is required' } } }, lastName: { row: '.col-xs-4', validators: { notEmpty: { message: 'The last name is required' } } }, username: { validators: { notEmpty: { message: 'The username is required' }, stringLength: { min: 6, max: 30, message: 'The username must be more than 5 and less than 31 characters long' }, regexp: { regexp: /^[a-zA-Z0-9_\.]+$/, message: 'The username can only consist of alphabetical, number, dot and underscore' } } }, email: { validators: { notEmpty: { message: 'The email address is required' }, emailAddress: { message: 'The email address is not valid' } } }, password: { validators: { notEmpty: { message: 'The password is required' }, different: { field: 'username', message: 'The password cannot be the same as username' } } }, gender: { validators: { notEmpty: { message: 'The gender is required' } } }, bio: { validators: { stringLength: { max: 300, message: 'The bio must be less than 300 characters long' } } } } }) .on('err.form.fv', function(e) { // Show the message modal $('#messageModal').modal('show'); }); }); </script> Demo
doc_23536462
The HTML looks like this. It uses Bootstrap & JQuery, but I'm omitting that to avoid bloat. <input type="file" class="upload-input" name="imageFile" accept="image/*" style="display:none;" id="input-1"> <div class="input-group mb-3"> <input type="text" class="form-control" id="filename-1" readonly placeholder="Upload your show image (Required)" style="width:100%;"> <div class="input-group-btn"> <button class="btn btn-outline-secondary upload-button" type="button" data-ratio="1/1">Select</button> </div> </div> <!-- Modal For Cropper --> <div class="modal fade photo-cropper" tabindex="-1" aria-labelledby="cropperModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="cropperModalLabel">Crop your image</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div class="upload-preview"> <img class="upload-image-preview" style="display: block; max-width: 100%;"> <div class="photo-cropper-controls"> <i class="fa fa-check-square" id="crop-confirm" aria-hidden="true"></i> <i class="fa fa-window-close" id="crop-cancel" aria-hidden="true"></i> </div> </div> </div> </div> </div> </div> Here's the JS that controls Cropper $(document).on('click', '.upload-button', function(e) { var ratio = $(this).data('ratio'); var activeInput = $('#input-1'); activeInput.click(); $(activeInput).change(function() { if(this.files && this.files[0]) { var imageFile = this.files[0]; var reader = new FileReader(); reader.onload = function (e) { $('.photo-cropper').modal('show'); $(document).on('shown.bs.modal', function (f) { $('.upload-image-preview').attr('src', e.target.result); $('.photo-cropper-controls').show(); $('.upload-image-preview').data('target', '#input-1'); $('.upload-image-preview').cropper('destroy'); $('.upload-image-preview').cropper({ aspectRatio: eval(ratio), viewMode: 1 }); }); } reader.readAsDataURL(imageFile); } }); }); $(document).on('click', '#crop-confirm', function() { var target = $('.upload-image-preview').data('target'); var imageData = $('.upload-image-preview').cropper('getCroppedCanvas', {maxWidth: 990}).toDataURL('image/jpeg'); $('.photo-cropper').modal('hide'); $(document).on('hidden.bs.modal', function (f) { $('.upload-image-preview').cropper('destroy'); }); $(target).attr('src', imageData); var filename = $(target).val().split('\\').pop(); $('#filename-1').val(filename); }); And finally, the PHP that deals with the posted form if(!empty($_FILES['imageFile'])) { require_once('assets/plugins/class.upload.php'); $handle = new upload($_FILES['imageFile']); if ($handle->uploaded) { $handle->file_safe_name = true; $handle->allowed = array('image/*'); $handle->image_ratio_y = true; $handle->image_x = 800; $handle->process('/upload/path/'); if ($handle->processed) { $image = $handle->file_dst_name; } } } The basic method is click the .upload-button which clicks the hiding file input, then opens a Bootstrap modal and initialises Cropper with the selected image. When you've finished cropping, clicking #crop-confirm creates the DataURL, closes the modal, and puts the imageData in the file input. Submitting the form sends the data to the PHP with the image in the imageFile field. All ok so far? So why is the file it saves the original uncropped image? I'm clearly missing something really obvious...
doc_23536463
I have a vague idea on how basic formats work such as $#,##0.00 producing outputs like $1,000.00 as described here. However upon looking at this example I saw something this: wb.createDataFormat().getFormat("_($* #,##0.00_);_($* (#,##0.00);_($* \"-\"??_);_(@_)") which I cant make heads or tails of. A: Maybe too late, but it might help someone else. You find more details and examples here: CellFormat javadoc - https://poi.apache.org/apidocs/org/apache/poi/ss/format/CellFormat.html DataFormatter - https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/DataFormatter.html A: as stated by @Gagravarr above, these are not poi specific. this link should help anyone else having problems with this
doc_23536464
var voters = [ {name:'Bob' , age: 30, voted: true}, {name:'Jake' , age: 32, voted: true}, {name:'Kate' , age: 25, voted: false}, {name:'Sam' , age: 20, voted: false}, {name:'Phil' , age: 21, voted: true}, {name:'Ed' , age:55, voted:true}, {name:'Tami' , age: 54, voted:true}, {name: 'Mary', age: 31, voted: false}, {name: 'Becky', age: 43, voted: false}, {name: 'Joey', age: 41, voted: true}, {name: 'Jeff', age: 30, voted: true}, {name: 'Zack', age: 19, voted: false} ]; I used reduce to count number of people who voted: function totalVotes(arr) { return arr.reduce(function voteCount(acc,cur){ return acc+cur.voted; },0) } The function return correct answer which make me confuse. It doesn't has any condition to check whether that person is voted or not so how can it return the right answer? A: By doing acc+cur.voted you implicitly cast the boolean cur.voted to a number (false -> 0, true -> 1). Therefore by "adding up" those booleans, you'll receive the count of booleans being true: console.log( true + false, true + true ); A: Javascript has a dynamic type system that uses type coercion. When you have an expression with a two variables where one is an integer and the is boolean type coercion happens. The bool value will be interpreted as 1 or 0. Try this in an interactive JS (eg node, repl.it): 0 + true it returns 1. In your reduce callback function you start with an initial value of 0 for the accumulator acc. Then you add the boolean values cur.voted to it. This will return acc + 1 for a list element with voted = true and acc for a list element with voted = false.
doc_23536465
//Warrior Class public class Warrior extends Adventurer{ private final int MAX_HP = 150; public void sleep(){ setHp(MAX_HP); System.out.println(getName() + "fully restored HP!"); } } //Mage Class public class Mage extends Adventurer{ private final int MAX_HP = 100; public void sleep(){ setHp(MAX_HP); System.out.println(getName() + "fully restored HP!"); } } //Adventurer Class public abstract class Adventurer{ private int hp; public Adventurer(int hp){ this.hp = hp; } public int getHp(){ return this.hp; } public void setHp(int hp){ this.hp = hp; } A: Yes, you can. Inside the abstract class Adventurer add an abstract method: public abstract int getChildHP(); and have Warrior and Mage implement it: public int getChildHP() { return MAX_HP }; (MAX_HP is different for each one of them of course). Move the sleep() method (delete it from the children) to the abstract class and implement it: public void sleep() { setHp(getChildHP()); System.out.println(getName() + "fully restored HP!"); } When this method is called, the relevant getChildHP() will be called according to the instance. Now sleep() exists only once in the parent class ==> no code duplication. Hope it helps.
doc_23536466
$scope.electionDetails = { id : 1, election_type: "CityCouncil", election_name: "City A City Council Elections candidates : [{ id: 1, election_id: 1, position_id: 1, first_name: "John", last_name: "Doe" }, { id:2, election_id:1, position_id:1, first_name: "Jane", last_name: "Doe" }, { id:3, election_id:1, position_id:2, first_name: "Mike", last_name: "Doe" }, { id:4, election_id:1, position_id:2, first_name: "Mary", last_name: "Doe" }], positions : [{ id:1, election_id: 1, position: "Seat 1" }, { id:2, election_id:1, position: "Seat 2" }] } I want to display this data grouped, using angular like so: City A City Council Elections Seat 1 * *John Doe *Jane Doe Seat 2 * *Mike Doe *Mary Doe A: Here you go. The HTML structure may not be exactly what you want, so you can change up what tags you use, but this is the basic idea using ng-if and ng-repeat to create lists of candidates for a given seat. DEMO
doc_23536467
I referred to the docs of the boto3 under mobile subsection and I can't find any thing substantial that can help me with it. I want to know whether there is any way to update the mobile hub based database using cron task. A: AWS Mobile Hub's database feature is create an Amazon DynamoDB on your behalf. You could just using it as regular Amazon DynamoDB tables. You find the Amazon DynamoDB table name under AWS Mobile Hub > your project > resources > Amazon DynamoDB. https://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html Hope this helps.
doc_23536468
const winPrint = window.open('', '', 'width=900,height=650'); let el = document.getElementsByClassName('testing')[0] winPrint.document.write(el.innerHTML); // winPrint.document.write(this.globalMap.nativeElement.innerHTML); winPrint.document.close(); winPrint.focus(); winPrint.print(); winPrint.close(); html, body, svg { height: 100% } path { fill: orange; background-color: orange; } <!-- Learn about this code on MDN: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/path --> <div class="testing"> <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">   <path d="M 10,30 A 20,20 0,0,1 50,30 A 20,20 0,0,1 90,30 Q 90,60 50,90 Q 10,60 10,30 z"/> </svg> </div> A: The reason the color is missing from the SVG is because you're opening a new window and only writing the element to said window not the CSS stylings. You will need to copy the CSS to the new window as well. There's multiple methods on how to do so. Some are simpler than others. If you simply want all style elements copied over you can do as follows (there's a lot of cases where this wont work): const winPrint = window.open('', '', 'width=900,height=650'); let el = document.getElementsByClassName('testing')[0]; winPrint.document.write(Array.from(document.querySelectorAll("style")).map(x => x.outerHTML).join("") + el.innerHTML); winPrint.document.close(); winPrint.focus(); winPrint.print(); winPrint.close(); Another option is to go through all elements and copy their computed CSS values. I would recommend you to take a look at Get a CSS value with JavaScript as to how to actually do this. Below I've written an example of how to clone an element and its computed CSS values. I've only tested this with your example. Therefore, I can't guarantee that it will work everywhere, but it might be good to start from. function cloneElement(el) { const clone = el.cloneNode(true); copyCSS(el, clone); return clone; } function copyCSS(source, dest) { const computedStyle = window.getComputedStyle(source); const cssProperties = Object.keys(computedStyle); for (const cssProperty of cssProperties) { dest.style[cssProperty] = computedStyle[cssProperty]; } for (let i = 0; i < source.children.length; i++) { copyCSS(source.children[i], dest.children[i]); } } function printElement(el) { const clone = cloneElement(el); const winPrint = window.open('', '', 'width=900,height=650'); winPrint.document.write(clone.outerHTML); winPrint.document.close(); winPrint.focus(); winPrint.print(); winPrint.close(); } printElement(document.querySelector(".testing"));
doc_23536469
var until = new Date( 2012, 8 - 1, 29, 19, 0, 0); A: You could use the timezone-js library, example usage : var dt = new timezoneJS.Date(2008, 9, 31, 11, 45, 'America/Los_Angeles');
doc_23536470
In my Python file: class login: ... def POST(self): ... cursor.execute("SELECT password FROM tbl WHERE username = %s", (f['username'].value, )) realpassword = cursor.fetchone() realpassword = realpassword[0] ... return realpassword The password appears correctly in the text file that downloads, but how do I display the password as text on the webpage? A: Python string.printable includes both vertical-tab \x0b and form-feed \x0c, neither of which are friends to browsers. Browsers assume they're receiving a file and offer to download it. (string.printable isn't the same as ASCII.) Instead of returning the raw realpassword, return repr(realpassword). Built-in repr() returns a "string containing a printable representation...", escaping control characters. >>> import string >>> print string.printable[-20:] =>?@[\]^_`{|}~ >>> print repr(string.printable[-20:]) '=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
doc_23536471
static circle This is my code to add text node.enter().append("circle") .attr("class", "node") .attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }) .attr("r", function(d) { return Math.sqrt(d.size) / 10 || 4.5; }) .style("fill", color) .on("click", click) .call(force.drag); node.enter().append("text") .attr("x", function(d) { return d.x; }) .attr("y", function(d) { return d.y; }) .text(function(d) { return d.name; }); I already tried this code too but it didn't work. var circle = node.enter().append("circle") .attr("class", "node") .attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }) .attr("r", function(d) { return Math.sqrt(d.size) / 10 || 4.5; }) .style("fill", color) .on("click", click) .call(force.drag); circle.append("text") .attr("x", function(d) { return d.x; }) .attr("y", function(d) { return d.y; }) .text(function(d) { return d.name; });
doc_23536472
// gets button from page var checkButton = document.getElementById('saveCheck'); // initiates check fucntion when clicked checkButton.addEventListener('click', check); // starts when youtube setting is saved function check() { console.log('Check starts'); //initiates if checkbox is checked if (check.checked) { console.log('its checked'); localStorage.youtube = 1; } else { console.log('it isnt checked'); localStorage.youtube = 0; } } console.log(localStorage.youtube); This parts works perfectly, but when I try accessing the data stored in the local storage through my background.js page of my extension, it doesn't returns null for the values BACKGROUND.JS var ytcheck = localStorage.getItem('youtube'); console.log(ytcheck);
doc_23536473
@ActionMapping(params = { "action=create" }) public void create(ActionRequest request, ActionResponse response, @Valid @ModelAttribute("formObject") FormObject formObject, BindingResult result) throws IOException, RepositoryException, PortalException, SystemException { // do some stuff and then response.setParameter("action", "myAction"); response.sendRedirect("/next-portlet"); } myAction doesn't get passed to the next portlet unfortunately. How can I achieve this, please? A: you can use session actionRequest.getPortletSession().setAttribute("action", "myaction"); A: I've managed to make it work. I had to use response.setRenderParameter("action", "myAction"); Now it finally adds the parameters.
doc_23536474
The error is: Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. *************************** APPLICATION FAILED TO START *************************** Description: The bean 'dataSource', defined in BeanDefinition defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class], could not be registered. A bean with that name has already been defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class] and overriding is disabled. Action: Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true A kinda similar question (Trouble when changing Spring Boot version from 2.0.3.RELEASE to 2.1.0.BUILD-SNAPSHOT) was already asked but no proper answer was given. Following is my POM.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>***.***.***</groupId> <artifactId>******</artifactId> <version>1.0.0</version> <relativePath /> <!-- lookup parent from repository --> </parent> <artifactId>*****</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>${project.artifactId}</name> <description>TEST</description> <prerequisites> <maven>${maven.version}</maven> </prerequisites> <properties> <start-class>c*.*.Application</start-class> <junit.jupiter.version>5.2.0</junit.jupiter.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-reactor-netty --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-reactor-netty</artifactId> <version>2.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-rsa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- Sql server driver --> <dependency> <groupId>com.microsoft.sqlserver</groupId> <artifactId>mssql-jdbc</artifactId> </dependency> <!-- Lombok dependencies --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>provided</scope> </dependency> <!-- Commons dependencies --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency> <dependency> <groupId>commons-validator</groupId> <artifactId>commons-validator</artifactId> </dependency> <!-- Logging dependencies --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-sleuth</artifactId> </dependency> <dependency> <groupId>net.logstash.logback</groupId> <artifactId>logstash-logback-encoder</artifactId> </dependency> <!-- Swagger dependencies --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-bean-validators</artifactId> </dependency> <!-- Test dependencies --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>com.vaadin.external.google</groupId> <artifactId>android-json</artifactId> </exclusion> </exclusions> </dependency> <!-- Spring REST Docs dependencies --> <dependency> <groupId>org.springframework.restdocs</groupId> <artifactId>spring-restdocs-core</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.restdocs</groupId> <artifactId>spring-restdocs-webtestclient</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.restdocs</groupId> <artifactId>spring-restdocs-asciidoctor</artifactId> <scope>test</scope> </dependency> <!-- Spring Auto REST Docs dependencies --> <dependency> <groupId>capital.scalable</groupId> <artifactId>spring-auto-restdocs-core</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.hsqldb</groupId> <artifactId>hsqldb</artifactId> <scope>test</scope> </dependency> <!-- JUnit Jupiter API and Engine --> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>${junit.jupiter.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>${junit.jupiter.version}</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/mockwebserver --> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>mockwebserver</artifactId> <version>3.10.0</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> </dependency> <!-- https://mvnrepository.com/artifact/io.projectreactor/reactor-test --> <dependency> <groupId>io.projectreactor</groupId> <artifactId>reactor-test</artifactId> <version>3.1.8.RELEASE</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mock-server</groupId> <artifactId>mockserver-netty</artifactId> <version>5.4.1</version> </dependency> </dependencies> <build> <resources> <resource> <filtering>true</filtering> <directory>src/main/resources</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> <include>**/*.yml</include> </includes> <excludes> <exclude>**/*.jks</exclude> </excludes> </resource> <resource> <filtering>false</filtering> <directory>src/main/resources</directory> <includes> <include>**/*.jks</include> </includes> <excludes> <exclude>**/*.xml</exclude> <exclude>**/*.properties</exclude> <exclude>**/*.yml</exclude> </excludes> </resource> </resources> <plugins> <plugin> <groupId>com.github.ekryd.sortpom</groupId> <artifactId>sortpom-maven-plugin</artifactId> </plugin> <plugin> <groupId>com.github.spotbugs</groupId> <artifactId>spotbugs-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-enforcer-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-pmd-plugin</artifactId> <configuration> <excludeFromFailureFile>${project.basedir}/exclude-pmd.properties</excludeFromFailureFile> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> </plugin> <plugin> <groupId>org.asciidoctor</groupId> <artifactId>asciidoctor-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.eclipse.m2e</groupId> <artifactId>lifecycle-mapping</artifactId> </plugin> <plugin> <groupId>org.gaul</groupId> <artifactId>modernizer-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>pl.project13.maven</groupId> <artifactId>git-commit-id-plugin</artifactId> </plugin> </plugins> </build> <profiles> <profile> <id>dev</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <spring.profiles.active>dev</spring.profiles.active> </properties> </profile> <profile> <id>qa</id> <properties> <spring.profiles.active>qa</spring.profiles.active> </properties> </profile> <profile> <id>prod</id> <properties> <spring.profiles.active>prod</spring.profiles.active> </properties> </profile> <profile> <id>eclipse</id> <dependencyManagement> <dependencies> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>${junit.jupiter.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-launcher</artifactId> <version>1.1.1</version> <scope>test</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> </dependency> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-launcher</artifactId> </dependency> </dependencies> </profile> </profiles> </project> I have asterisked few parts. The parent BOM has a parent element in its POM as below: <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.0.M4</version> <relativePath /> <!-- lookup parent from repository --> </parent> Progress From the spring 2.1.0 M1 release notes (https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.1.0-M1-Release-Notes) I see that Bean Overriding has been disabled. The error goes away when I add a property allow-bean-definition-overriding: true in my application.yml file but then I get the following error: java.lang.ClassNotFoundException: reactor.netty.http.client.HttpClient at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... 115 common frames omitted Wrapped by: java.lang.NoClassDefFoundError: reactor/netty/http/client/HttpClient ... 115 common frames omitted Wrapped by: java.lang.BootstrapMethodError: java.lang.NoClassDefFoundError: reactor/netty/http/client/HttpClient at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [9 skipped] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) A: It seems your application is mixing two incompatible versions of Spring Boot. Your main pom.xml seems to be importing spring-boot-starter-reactor-netty with the 2.0.5.RELEASE version. * *You should not override versions of Spring Boot libraries, as it's all taken care of by the dependency management in the parent POM *You don't need the reactor-netty starter at all, as it's transitively brought by the webflux one. A: Please don't change Spring Boot version once your project is in between development. Try to add latest version when you start project. Once development started don't change any thing in version. I have faced same problem and wasted 4-5 hours and again went back to previous version everything working perfectly. Delete .project file and update maven.
doc_23536475
(pseudocode) result = SELECT blah1, blah2, foreign_key FROM foo WHERE key=bar if foreign_key > 0 other_result = SELECT something FROM foo2 WHERE key=foreign_key end The code needs to branch if there is no related row in the other table, but couldn't this be done better by doing a LEFT JOIN in a single SELECT statement? Am I missing some performance benefit? Portability issue? Or am I just nitpicking? A: This is definitely wrong. You are going over the wire a second time for no reason. DBs are very fast at their problem space. Joining tables is one of those and you'll see more of a performance degradation from the second query then the join. Unless your tablespace is hundreds of millions of records, this is not a good idea. A: There is not enough information to really answer the question. I've worked on applications where decreasing the query count for one reason and increasing the query count for another reason both gave performance improvements. In the same application! For certain combinations of table size, database configuration and how often the foreign table would be queried, doing the two queries can be much faster than a LEFT JOIN. But experience and testing is the only thing that will tell you that. MySQL with moderately large tables seems to be susceptable to this, IME. Performing three queries on one table can often be much faster than one query JOINing the three. I've seen speedups of an order of magnitude. A: I'm with you - a single SQL would be better A: There's a danger of treating your SQL DBMS as if it was a ISAM file system, selecting from a single table at a time. It might be cleaner to use a single SELECT with the outer join. On the other hand, detecting null in the application code and deciding what to do based on null vs non-null is also not completely clean. One advantage of a single statement - you have fewer round trips to the server - especially if the SQL is prepared dynamically each time the other result is needed. On average, then, a single SELECT statement is better. It gives the optimizer something to do and saves it getting too bored as well. A: It seems to me that what you're saying is fairly valid - why fire off two calls to the database when one will do - unless both records are needed independently as objects(?) Of course while it might not be as simple code wise to pull it all back in one call from the database and separate out the fields into the two separate objects, it does mean that you're only dependent on the database for one call rather than two... This would be nicer to read as a query: Select a.blah1, a.blah2, b.something From foo a Left Join foo2 b On a.foreign_key = b.key Where a.Key = bar; And this way you can check you got a result in one go and have the database do all the heavy lifting in one query rather than two... Yeah, I think it seems like what you're saying is correct. A: The most likely explanation is that the developer simply doesn't know how outer joins work. This is very common, even among developers who are quite experienced in their own specialty. There's also a widespread myth that "queries with joins are slow." So many developers blindly avoid joins at all costs, even to the extreme of running multiple queries where one would be better. The myth of avoiding joins is like saying we should avoid writing loops in our application code, because running a line of code multiple times is obviously slower than running it once. To say nothing of the "overhead" of ++i and testing i<20 during every iteration! A: You are completely correct that the single query is the way to go. To add some value to the other answers offered let me add this axiom: "Use the right tool for the job, the Database server should handle the querying work, the code should handle the procedural work." The key idea behind this concept is that the compiler/query optimizers can do a better job if they know the entire problem domain instead of half of it. A: Considering that in one database hit you have all the data you need having one single SQL statement would be better performance 99% of the time. Not sure if the connections is being creating dynamically in this case or not but if so doing so is expensive. Even if the process if reusing existing connections the DBMS is not getting optimize the queries be best way and not really making use of the relationships. The only way I could ever see doing the calls like this for performance reasons is if the data being retrieved by the foreign key is a large amount and it is only needed in some cases. But in the sample you describe it just grabs it if it exists so this is not the case and therefore not gaining any performance. A: The only "gotcha" to all of this is if the result set to work with contains a lot of joins, or even nested joins. I've had two or three instances now where the original query I was inheriting consisted of a single query that had so a lot of joins in it and it would take the SQL a good minute to prepare the statement. I went back into the procedure, leveraged some table variables (or temporary tables) and broke the query down into a lot of the smaller single select type statements and constructed the final result set in this manner. This update dramatically fixed the response time, down to a few seconds, because it was easier to do a lot of simple "one shots" to retrieve the necessary data. I'm not trying to object for objections sake here, but just to point out that the code may have been broken down to such a granular level to address a similar issue. A: A single SQL query would lead in more performance as the SQL server (Which sometimes doesn't share the same location) just needs to handle one request, if you would use multiple SQL queries then you introduce a lot of overhead: Executing more CPU instructions, sending a second query to the server, create a second thread on the server, execute possible more CPU instructions on the sever, destroy a second thread on the server, send the second results back. There might be exceptional cases where the performance could be better, but for simple things you can't reach better performance by doing a bit more work. A: Doing a simple two table join is usually the best way to go after this problem domain, however depending on the state of the tables and indexing, there are certain cases where it may be better to do the two select statements, but typically I haven't run into this problem until I started approaching 3-5 joined tables, not just 2. Just make sure you have covering indexes on both tables to ensure you aren't scanning the disk for all records, that is the biggest performance hit a database gets (in my limited experience) A: You should always try to minimize the number of query to the database when you can. Your example is perfect for only 1 query. This way you will be able later to cache more easily or to handle more request in same time because instead of always using 2-3 query that require a connexion, you will have only 1 each time. A: There are many cases that will require different solutions and it isn't possible to explain all together. Join scans both the tables and loops to match the first table record in second table. Simple select query will work faster in many cases as It only take cares for the primary/unique key(if exists) to search the data internally.
doc_23536476
Validation doesn't matter at this point, there is already some fairly robust validation down the line, but I'm struggling with how to get this information in SQL. Ideally I would end up with a table structure that would have only the value (Ie 1010 for BusinessUnit) and the corresponding name (ie BU1). I can pull the display value and the segment name from the DefaultDimensionView, but, not the name associated with the particular segment value. Am I overlooking a simple way to expose this information? (Given financial dimensions, probably not, but one can hope) A: There is no easy way to get the description for a dimension in SQL, because it requires knowledge of the backing entity table that stores the description. In AX it is easy, just use the DefaultDimensionView.dimensionDiscription display method: display String50 dimensionDiscription() { Common common; DictTable d; if (this.BackingEntityType) { d = new DictTable(this.BackingEntityType); common = d.makeRecord(); select common where common.(this.KeyAttribute) == this.EntityInstance; return DimensionAttribute::getLocalizedNameByEntityAndInstance(this.DimensionAttributeId, this.EntityInstance, common.(this.NameAttribute)); } return ''; } It simply makes a lookup on the backing table and field (stored in the DimensionAttriube table).
doc_23536477
var modal = document.getElementById("myModal"); var btn = document.getElementById("myBtn"); var span = document.getElementsByClassName("close")[0]; btn.onclick = function() { modal.style.display = "block"; } span.onclick = function() { modal.style.display = "none"; } window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } <p style="margin: -5% 0;"> <a id="myBtn" style="cursor: pointer;"><img src="someimages.jpg" /></a> pop up will appear upon clicking the image</p> <div id="myModal" class="modal"> <!-- Modal content --> <div class="modal-content"> <span class="close" onclick="testVids.pause();">&times;</span> <iframe id="testVids" controls src="https://www.youtube.com/embed/" frameborder="0" allow="accelerometer; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </div> </div>
doc_23536478
H : forall m n : nat, f 0 n = S n /\ f (S m) 0 = f m 1 /\ f (S m) (S n) = f m (f (S m) n) My goal is to break it up into it components. However, trying intros m n in H or destruct H doesn't work. How do I proceed? I would like something like H0 : f 0 n = S n, H1 : f (S m) 0 = f m 1 and H2 : f (S m) (S n) = f m (f (S m) n) with m and n introduced. A: You first need to specialize the hypothesis to be able to destruct it. If you already know to which variables you want to apply this hypothesis (let's say you have n and m already introduced in your environment), you could do the following: specialize (H n m). destruct H as (H0 & H1 & H2). or shorter: destruct (H n m) as (H0 & H1 & H2). (which also keeps the original hypothesis H, while the first solution clears it). Finally, if you don't know yet to what you are going to apply this hypothesis, you can use the edestruct tactic: edestruct H as (H0 & H1 & H2). (* And you get: H0 : f 0 ?n = S ?n H1 : f (S ?m) 0 = f ?m 1 H2 : f (S ?m) (S ?n) = f ?m (f (S ?m) ?n) *)
doc_23536479
public static string FromGZipToString( this byte[] source ) { using( MemoryStream stream = new MemoryStream( ) ) { stream.Write( source, 0, source.Length ); using (var gzipstream = new GZipStream(stream, CompressionMode.Decompress)) using (var reader = new StreamReader(gzipstream)) { return reader.ReadToEnd( ); } } } here is the compress code by the way.... public static byte[] ToGZip( this string source ) { using( var stream = new MemoryStream( ) ) using( var compressor = new GZipStream( stream, CompressionMode.Compress ) ) { var bytes = System.Text.UTF8Encoding.UTF8.GetBytes( source ); compressor.Write( bytes, 0, bytes.Length ); return stream.ToArray( ); } } A: Your compression routine is faulty. It shouldn't be reading from stream until the compressor has been closed (or disposed), allowing the compressor to finish writing all bytes to the steam. Check out my answer to this question: compressing and decompressing source data gives result different than source data
doc_23536480
$(function() { $('#add').click(function() { return !$('#select1 option:selected').appendTo('#select2'); }); $('#remove').click(function() { return !$('#select2 option:selected').appendTo('#select1'); }); }); HTML :: <SELECT id="select1" name="select1" size="3"><OPTION value="1">Test 1</option><OPTION value="2">Test 2</option></select> <SELECT id="select2" name="select2"></select> <br><input type="button" id="add" value="Add >>"><input type="button" id="remove" value="<< Remove"> Its basically just a piece of JS interchanging a select values. But what I don't understand is the usage of the ! operator(not operator). Now I understand that the not operator inverses the result, but in the above code what is it really doing? I am not understanding what the not operator is doing in the above fiddle and what impact it is having on the end result? Can anybody explain? A: It's a fancy way of doing: $('#add').click(function() { $('#select1 option:selected').appendTo('#select2'); return false; }); the return false prevents default behavior of the button by cancelling the event. Since an object will always be truthy, !object will be false and $(selector) returns an object
doc_23536481
We have created a sample procedure delimiter // Create Procedure proc_check (OUT count INT) begin select count(*) into count from lg_office ; end// In default.xml,containing custom queries,we have used <sql id="de.uhh.l2g.plugins.service.persistence.ProducerFinder.findOfficeCount"> <![CDATA[ Call proc_check(@output) ]]> </sql> In the respective Finder method,we used the below snippet to call the stored proc,passing -1 for both begin and end. String sql = CustomSQLUtil.get(FIND_OFFICE_COUNT); SQLQuery q = session.createSQLQuery(sql); QueryPos qPos = QueryPos.getInstance(q); //qPos.add(lectureseriesId); List <Integer> sl = (List<Integer>) QueryUtil.list(q, getDialect(), begin, end); return sl; In QueryUtil,we could not find other applicable methods to execute the call. Post this we get the below error ERROR [RuntimePageImpl-5][JDBCExceptionReporter:82] ResultSet is from UPDATE. No Data. Is this approach correct with something missing or if not,please suggest approach to achieve the same. A: there isn't any utility built-in in liferay to call stored procedure but you can just get the connection with DataAccess.getConnection(); and use the jdbc api like this way Connection connection =DataAccess.getConnection(); CallableStatement cs = connection.prepareCall("{Call proc_check(@output)}"); ResultSet rs = cs.executeQuery(); A: Look at this, try it. session = openSession(); String sql = CustomSQLUtil.get(DELETE_BY_PROJETID); SQLQuery query = session.createSQLQuery(sql); query.setCacheable(false); QueryPos qPos = QueryPos.getInstance(query); qPos.add(projectId); query.executeUpdate(); https://web.liferay.com/it/community/forums/-/message_boards/message/37490823
doc_23536482
A simple question but no clear answer yet. Can I add my button to standard UIActivityController so that when user goes to Photos/Notes/Safari he can also along with twitter/facebook post it to my destination ? I'm sure I can do that while calling UIActivityViewController from within my app. And looks like there is a way to do that for mail attachments. Box app can do that here, probably via CFBundleDocumentTypes in plist. But is there a way to do that with e.g. photos? Hopefully anybody can give me any useful links with examples of such implementation. Thanks a lot --Dannie A: As of iOS 6, there is no way to add a custom UIActivity item to built-in apps like Photos, Notes, or Safari. Custom UIActivity items can only be added to third-party apps.
doc_23536483
File 1- #include <iostream> #include "fileTwo.h" using namespace std; int main() { return 0; } someFunction(); File 2- #include <iostream> using namespace std; int someFunction() { cout << "Hello" << endl; return 0; } File 2 header- #ifndef FILETWO_H_INCLUDED #define FILETWO_H_INCLUDED int someFunction(); #endif // FILETWO_H_INCLUDED Note that file 2 and the header file for file 2 have the same name, fileTwo.cpp and fileTwo.h A: I am attempting to call that function You should do this, then: int main() { someFunction(); return 0; } When you put the "call" globally, the compiler expects a defintiion or declaration.
doc_23536484
Usuario > UID > Mensagem > Key creating with push > Data of mensagem. For better verification follows image of the database on firebase. Can help me, please? Hugs. A: database.child("usuario").addValueEventListener(new ValueEventListener() { public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot snapshot: dataSnapshot.getChildren()) { for (DataSnapshot messageSnapshot: snapshot.child("mensagem").getChildren()) { listView.add(messageSnapshot.child("textoMensagem").getValue().toString()); } } } ... As you can see I add a ValueEventListener to retrieve all children nodes of "usuario" and then loop through its children to get to your messages. Tip: Think about (at least) posting your code/database structure etc. in English, it could make reading your question a lot easier.
doc_23536485
public class DataContext : IdentityDbContext<User, IdentityRole<int>, int, IdentityUserClaim<int>, IdentityUserRole<int>, IdentityUserLogin<int>, IdentityRoleClaim<int>, IdentityUserToken<int>>, IDataContext { private readonly string _dbName; public DataContext(string dbName) { this._dbName = dbName; } public virtual DbSet<Container> Containers { get; set; } public virtual DbSet<Note> Notes { get; set; } public virtual DbSet<Post> Posts { get; set; } public virtual DbSet<Email> Emails { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(ConnectionStrings.DataContext.Replace(":dbname", this._dbName)); base.OnConfiguring(optionsBuilder); } } Interface: public interface IDataContext { DbSet<Container> Containers { get; set; } DbSet<Note> Notes { get; set; } DbSet<Post> Posts { get; set; } DbSet<Email> Emails { get; set; } } In Startup.cs I have the follwoing line: services.AddDbContext<DataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DataContext"))); But that connection string doesn't contain db name. Should I include into interface such tables as: AspNetUsers, AspNetRoles, ...? And I want to write in Startup.cs something like that: services.AddScoped<IDataContext, DataContext>(); And use interface everywhere instead the whole class. Can I do that? And how can I do that? A: When you use Entity Framework's AddDbContext method it will register the context in the service collection for you. services.AddDbContext<DataContext>(ServiceLifetime.Scoped); But you could register your interface like the following. services.AddScoped(typeof(IDataContext), provider => provider.GetService<DataContext>()); Then you can work with the interface. But the Identity Services will still use the concrete type. PS: Do you know the repository pattern? It enables you to easely seperate the data layer from the service layer. This helps a lot for example for unit tests. The problem with your DataContext constructor is that the dependency container doesn't know how to resolve the string in the constructor. Generally when you work with configurations in asp.net core you can use the IOptions type and its infrastructure. In the startup you can add the options and configure it. public class DatabaseOptions { public string DbName { get; set; } } services.AddOptions(); services.Configure<DatabaseOptions>(options => options.DbName = "myDbName"); And then you can change the constuctor of your DataContext to the following. public DataContext(IOptions<DatabaseOptions> options) If you do not know the configuration values at the startup you could write an context type which you configure in a middleware or an action filter. public class DbConfigurationContext { public string DbName { get; set; } } public class DbConfigurationContextFilter : IAsyncActionFilter { private readonly DbConfigurationContext _dbConfiguration; public DbConfigurationContextFilter(DbConfigurationContext dbConfiguration) { _dbConfiguration = dbConfiguration; } public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { _dbConfiguration.DbName = context.HttpContext.Request.Query["DbName"]; await next(); } } services.AddTransient<DbConfigurationContext>(); services.AddTransient<DbConfigurationContextFilter>(); services.AddMvc(setup => { setup.Filters.AddService(typeof(DbConfigurationContextFilter)); }) And then you could resolve this DbConfigurationContext in your DbContext. Of corse you could also use an interface. public DataContext(DbConfigurationContext configurationContext)
doc_23536486
of parallelizing for loops. begin_parallel_region( chunk_size=100 , num_proc=10 ); for( int i=0 ; i<1000 ; i++ ) { //some computation } end_parallel_region(); The code above distributes computation inside the for loop to 10 slave MPI processors. Upon entering the parallel region, the chunk size and number of slave processors are provided. Upon leaving the parallel region, the MPI processors are synched and are put idle. EDITED in response to High Performance Mark. I have no intention to simulate the OpenMP's shared memory model. I propose this because I need it. I am developing a library that is required to build graphs from mathetical functions. In these mathetical functions, there often exist for loops like the one below. for( int i=0 ; i<n ; i++ ) { s = s + sin(x[i]); } So I want to first be able to distribute sin(x[i]) to slave processors and at the end reduce to the single varible just like in OpenMP. I was wondering if there is such a wrapper out there so that I don't have to reinvent the wheel. Thanks. A: There is no such wrapper out there which has escaped from the research labs into widespread use. What you propose is not so much re-inventing the wheel as inventing the flying car. I can see how you propose to write MPI code which simulates OpenMP's approach to sharing the burden of loops, what is much less clear is how you propose to have MPI simulate OpenMP's shared memory model ? In a simple OpenMP program one might have, as you suggest, 10 threads each perform 10% of the iterations of a large loop, perhaps updating the values of a large (shared) data structure. To simulate that inside your cunning wrapper in MPI you'll either have to (i) persuade single-sided communications to behave like shared memory (this might be doable and will certainly be difficult) or (ii) distribute the data to all processes, have each process independently compute 10% of the results, then broadcast the results all-to-all so that at the end of execution each process has all the data that the others have. Simulating shared memory computing on distributed memory hardware is a hot topic in parallel computing, always has been, always will be. Google for distributed shared memory computing and join the fun. EDIT Well, if you've distributed x across processes then individual processes can compute sin(x[i]) and you can reduce the sum on to one process using MPI_Reduce. I must be missing something about your requirements because I just can't see why you want to build any superstructure on top of what MPI already provides. Nevertheless, my answer to your original question remains No, there is no such wrapper as you seek and all the rest of my answer is mere commentary. A: Yes, you could do this, for specific tasks. But you shouldn't. Consider how you might implement this; the begin part would distribute the data, and the end part would bring the answer back: #include <stdio.h> #include <stdlib.h> #include <math.h> #include <mpi.h> typedef struct state_t { int globaln; int localn; int *locals; int *offsets; double *localin; double *localout; double (*map)(double); } state; state *begin_parallel_mapandsum(double *in, int n, double (*map)(double)) { state *s = malloc(sizeof(state)); s->globaln = n; s->map = map; /* figure out decomposition */ int size, rank; MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); s->locals = malloc(size * sizeof(int)); s->offsets = malloc(size * sizeof(int)); s->offsets[0] = 0; for (int i=0; i<size; i++) { s->locals[i] = (n+i)/size; if (i < size-1) s->offsets[i+1] = s->offsets[i] + s->locals[i]; } /* allocate local arrays */ s->localn = s->locals[rank]; s->localin = malloc(s->localn*sizeof(double)); s->localout = malloc(s->localn*sizeof(double)); /* distribute */ MPI_Scatterv( in, s->locals, s->offsets, MPI_DOUBLE, s->localin, s->locals[rank], MPI_DOUBLE, 0, MPI_COMM_WORLD); return s; } double end_parallel_mapandsum(state **s) { double localanswer=0., answer; /* sum up local answers */ for (int i=0; i<((*s)->localn); i++) { localanswer += ((*s)->localout)[i]; } /* and get global result. Everyone gets answer */ MPI_Allreduce(&localanswer, &answer, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); free( (*s)->localin ); free( (*s)->localout ); free( (*s)->locals ); free( (*s)->offsets ); free( (*s) ); return answer; } int main(int argc, char **argv) { int rank; double *inputs; double result; int n=100; const double pi=4.*atan(1.); MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 0) { inputs = malloc(n * sizeof(double)); for (int i=0; i<n; i++) { inputs[i] = 2.*pi/n*i; } } state *s=begin_parallel_mapandsum(inputs, n, sin); for (int i=0; i<s->localn; i++) { s->localout[i] = (s->map)(s->localin[i]); } result = end_parallel_mapandsum(&s); if (rank == 0) { printf("Calculated result: %lf\n", result); double trueresult = 0.; for (int i=0; i<n; i++) trueresult += sin(inputs[i]); printf("True result: %lf\n", trueresult); } MPI_Finalize(); } That constant distribute/gather is a terrible communications burden to sum up a few numbers, and is antithetical to the entire distributed-memory computing model. To a first approximation, shared memory approaches - OpenMP, pthreads, IPP, what have you - are about scaling computations faster; about throwing more processors at the same chunk of memory. On the other hand, distributed-memory computing is about scaling a computation bigger; about using more resourses, particularly memory, than can be found on a single computer. The big win of using MPI is when you're dealing with problem sets which can't fit on any one node's memory, ever. So when doing distributed-memory computing, you avoid having all the data in any one place. It's important to keep that basic approach in mind even when you are just using MPI on-node to use all the processors. The above scatter/gather approach will just kill performance. The more idiomatic distributed-memory computing approach is for the logic of the program to already have distributed the data - that is, your begin_parallel_region and end_parallel_region above would have already been built into the code above your loop at the very beginning. Then, every loop is just for( int i=0 ; i<localn ; i++ ) { s = s + sin(x[i]); } and when you need to exchange data between tasks (or reduce a result, or what have you) then you call the MPI functions to do those specific tasks. A: Is MPI a must or are you just trying to run your OpenMP-like code on a cluster? In the latter case, I propose you to take a look at Intel's Cluster OpenMP: http://www.hpcwire.com/hpcwire/2006-05-19/openmp_on_clusters-1.html
doc_23536487
www.domain.com/1234 subscriber1 www.domain.com/2345 subscriber2 now the db connection is configured in a class in config/database.php. I want to be able to change the database used based on the url (eg. /1234 = db_1234). How would I achieve this? Thanks BTW I am using CakePHP 2.0 A: My previous solution was a load of rubbish. So I thought about attacking the problem from a different angle. My DATABASE_CONFIG class (/app/Config/database.php) now looks like this: class DATABASE_CONFIG { public $default = array( 'datasource' => 'Database/Mysql', 'persistent' => false, 'host' => '127.0.0.1', 'login' => 'xxxx', 'password' => 'xxxx', 'database' => 'xxxx', 'prefix' => '', 'encoding' => 'utf8', ); public $site_one = array( 'datasource' => 'Database/Mysql', 'host' => '127.0.0.1', // ... ); public $site_two = array( 'datasource' => 'Database/Mysql', 'host' => '127.0.0.1', // ... ); public function __construct() { if (strpos(env('HTTP_HOST'), 'site_one') !== false) { // use site_one database config $this->default = $this->site_one; // elseif site_two } elseif (strpos(env('HTTP_HOST'), 'site_two') !== false) { // use site_two database config $this->default = $this->site_two; } } } When Cake loads, the construct is now called automatically, and this sets the 'default' database connection dependent on the host. A: Ah I got it now, I thought DATABASE_CONFIG was called statically so didn't think to use the construct. www.domain.com/12345678 function __construct() { // get folder if(substr(php_sapi_name(), 0, 3) == "cli") { $j = explode("/", $_SERVER['PWD']); $this->default['database'] = "sa_".$j[count($j)-1]; } else { $j = explode("/", $_SERVER['REQUEST_URI']); $this->default['database'] = "sa_".$j[1]; } } but commandline bake must be done in folder eg. 12345678/
doc_23536488
Issue 1: My app registers for broadcast push notification sucessfully. And while invoking adapter to send broadcast notification, when application is in foreground it works perfectly fine. When i press home key and then invoke adapter for broadcast notification notification, notification is not recieved on android emulator. It shows below error in logcat. Seems like GCM has pushed notification but its not sent to client. 07-20 06:40:21.748: V/GCMBroadcastReceiver(1899): onReceive: com.google.android.c2dm.intent.RECEIVE 07-20 06:40:21.748: V/GCMBroadcastReceiver(1899): GCM IntentService class: com.FinacleMobileApp.GCMIntentService 07-20 06:40:21.748: V/GCMBaseIntentService(1899): Acquiring wakelock 07-20 06:40:21.789: V/GCMBaseIntentService(1899): Intent service name: GCMIntentService-DynamicSenderIds-2 07-20 06:40:21.848: D/GCMIntentService(1899): GCMIntentService.onMessage in GCMIntentService.java:107 :: WLGCMIntentService: Received a message from the GCM server 07-20 06:40:21.848: V/GCMBaseIntentService(1899): Releasing wakelock 07-20 06:40:21.888: W/GCMIntentService(1899): GCMIntentService.onMessage in GCMIntentService.java:114 :: Unable to update badge while received push notification, becasue failed to parse badge number null, badge must be an integer number. 07-20 06:40:21.918: D/GCMIntentService(1899): GCMIntentService.addToIntentQueue in GCMIntentService.java:147 :: WLGCMIntentService: App is on foreground but init is not comeplete. Queue the intent for later re-sending when app is back on foreground. 07-20 06:40:21.748: V/GCMBroadcastReceiver(1899): onReceive: com.google.android.c2dm.intent.RECEIVE 07-20 06:40:21.748: V/GCMBroadcastReceiver(1899): GCM IntentService class: com.FinacleMobileApp.GCMIntentService 07-20 06:40:21.748: V/GCMBaseIntentService(1899): Acquiring wakelock 07-20 06:40:21.789: V/GCMBaseIntentService(1899): Intent service name: GCMIntentService-DynamicSenderIds-2 07-20 06:40:21.848: D/GCMIntentService(1899): GCMIntentService.onMessage in GCMIntentService.java:107 :: WLGCMIntentService: Received a message from the GCM server 07-20 06:40:21.848: V/GCMBaseIntentService(1899): Releasing wakelock 07-20 06:40:21.888: W/GCMIntentService(1899): GCMIntentService.onMessage in GCMIntentService.java:114 :: Unable to update badge while received push notification, becasue failed to parse badge number null, badge must be an integer number. 07-20 06:40:21.918: D/GCMIntentService(1899): GCMIntentService.addToIntentQueue in GCMIntentService.java:147 :: WLGCMIntentService: **App is on foreground but init is not comeplete.Queue the intent for later re-sending when app is back on foreground. Issue 2: In same application i am trying to register a Tag(OFFERS) for notification. I am invoking subscribe method for this tag. Code is as follows.NotificationCenter.js is used. when i invoke subscribeForTagNotification (higlighted below) function from my appcontroller. I get Cant Subscribe, notification token is not updated on the server. Kindly let me know if i am missing anything. SubscribeforTagNotification function is called immediately after MF server connection call is initiated. My app used WL.client.init to make a connection with connectOnStartUp as true. AppController.factory('NotificationCenter', ['$http', '$rootScope', '$q', '$location', '$timeout', function($http, $rootScope, $q, $location, $timeout) { if (WL.Client.Push) { WL.Logger.debug("Ganesh Notification center on ready to subscribe"); //WL.Client.connect({onSuccess: connectSuccess, onFailure: connectFailure}); WL.Logger.debug("Ganesh connection waiting complete"); WL.Client.Push.onReadyToSubscribe = function() { WL.SimpleDialog.show("Tag Notifications", "Ready to subscribe", [ { text : 'Close', handler : function() {} } ]); }; } function doSubscribeSuccess() { WL.Logger.debug("Ganesh doSubscribeSuccess"); WL.SimpleDialog.show("Tag Notifications", "Subscribed to tag",[{ text:'Close',handler :function(){} }]); } function doSubscribeFailure() { WL.Logger.debug("Ganesh doSubscribeFailure"); WL.SimpleDialog.show("Tag Notifications", "Subscribed to tag",[{ text:'Close',handler :function(){} }]); } WL.Client.Push.onMessage = function (props, payload) { WL.SimpleDialog.show("Tag Notifications", "Provider notification data: " + JSON.stringify(props), [ { text : 'Close', handler : function() { WL.SimpleDialog.show("Tag Notifications", "Application notification data: " + JSON.stringify(payload), [ { text : 'Close', handler : function() {} }]); } }]); }; return { init: function() { }, **subscribeForTagNotification:function()**{ WL.Logger.debug("Ganesh doSubscribe feature"+WL.Client.Push.isTagSubscribed("OFFERS")); if (WL.Client.Push && !WL.Client.Push.isTagSubscribed("OFFERS")) { WL.Logger.debug("Ganesh doSubscribe feature entered"); WL.Client.Push.subscribeTag("OFFERS", { onSuccess: doSubscribeSuccess, onFailure: doSubscribeFailure }); } } }; }]); IBM MobileFirst version: 6.3.0.00-20141127-1357 Platform:Android A: For Push notification to be working on Emulator you need to have Target : Google API else it wont work on you Emulator. i hope you get what i am trying to say target refers to the AVD (Anddroid Virtual Device Target) for your created Virtual device. A: If your organization has a firewall that restricts the traffic to or from the Internet, you must go through the following steps: Configure the firewall to allow connectivity with GCM so that your GCM client apps can receive messages. The ports to open are 5228, 5229, and 5230. GCM typically uses only 5228, but it sometimes uses 5229 and 5230. GCM does not provide specific IP, so you must allow your firewall to accept outgoing connections to all IP addresses that are contained in the IP blocks listed in Google ASN of 15169. For more information, see Implementing an HTTP Connection Server. Ensure that your firewall accepts outgoing connections from MobileFirst Server to android.googleapis.com on port 443.
doc_23536489
The problem is, that the resource im exporting has quite a few joins and when I export it like this ( pseudo code ) foreach( myResources as resource ) { convertToExcelRow(resource); convertToAnotherExcelRow(resource->joinedTable); } Laravel creates half a million queries + another that much to make the joins. Now, for most situations, I could use eager loading, which will load everything in one query(much faster) but for such large queries, laravel will trigger a mysql error(plus it is very slow) because the list of row ids that goes into WHERE id IN( hundreds of thousands of ids) Is there a Laravel way to eager load using batches ? E.g break that 100 000 id list down into 10 queries, each 10 000 ids or something similar. A: Consider using the chunk method to break the task down in to manageable parts like so: Resource::with(['relationship1','relationship2'])->chunk(500, function($resources) { $resources->each(function($resource) { $this->convertToExcelRow($resource); $this->convertToAnotherExcelRow($resource->joinedTable); }); }); Note: Play around with the chunk sizes (500 is just an example). In this case you should get 2 queries for every 500 rows in your table. If you choose 5000, your query could would decrease by a factor of 10 but you load time may not improve due to the increased amount of joins being requested.
doc_23536490
Django Rest Framework comes with a renderer for returning a HTML form from a serializer[1]. After poring through the docs and then through the code, I still cannot figure out how to get it to render a blank form. What I think the problem might be: I can't figure out how to instantiate a blank serializer. In the docs for DRF they say the serializer has a very similar API to django's forms. When you want a blank form in a template, you instantiate one with MyForm() and pass it to the template context. However when I try that with a serializer, the .data attribute is just {'detail': 'Not Found.'} Please help I feel like I must be missing something blindingly obvious because rendering a blank form seems like a pretty major use case for an HTMLFormRenderer. Some Source Code class CustomViewSet(ModelViewSet): lookup_field = 'id' pagination_class = MyCustomPagination serializer_class = MyModelSerializer renderer_classes = (JSONRenderer, BrowsableAPIRenderer, HTMLFormRenderer) def create(self, request, *args, **kwargs): # return an html form for GET requests to /api/my_model/create/.form I'm pretty sure I have the urlconf wired up right that the request ends up in the right place, because when I GET /api/my_model/<pk>/.form I get a form in response, with the model attributes pre-entered. I just want a way to get a blank form... A: I managed to return an html snippet for a form using the following method on my viewset: class CustomViewSet(ModelViewSet): @list_route() def form(self, request, *args, **kwargs): serializer = self.get_serializer() renderer = HTMLFormRenderer() form_html = renderer.render(serializer.data, renderer_context={ 'template': 'rest_framework/api_form.html', 'request': request }) return HttpResponse(form_html) I needed to use a vanilla django HttpResponse, rather than rest framework's Response object, to prevent the Response object trying to re-render the form_html with the viewset's default renderer. Also, the list_route decorator is needed to get rest_framework's DefaultRouter to add a my_model/form/ endpoint, it doesn't mean the view has to return a list. A: I can't figure out how to instantiate a blank serializer. DRF allows you to initialize a serializer with no data and no instance attached to it. So in your case, your view code would just look like serializer = self.get_serializer() I feel like I must be missing something blindingly obvious because rendering a blank form seems like a pretty major use case for an HTMLFormRenderer. From that point, serializer should contain all of the information required to render a form. If you want to stick with the default forms as they are rendered by Django REST framework, you can use the HTMLFormRenderer that they provide. serializer = self.get_serializer() renderer = HTMLFormRenderer() form_html = renderer.render(serializer.data) It's important to note that the HTMLFormRenderer is not subject to standard deprecation policies. So if you do actually use it, make sure to follow any release notes closely when upgrading to make sure that things don't unexpectedly break. A: A serializer must declare at least one field in order to work with it. To create a absolutely blank serializer just add a custom SerializerMethodField that returns None or a hidden field that accepts null values: class EmptySerialiser(serializers.Serializer): empty = serializers.SerializerMethodField() def get_empty(self): return None or class EmptySerialiser(serializers.Serializer): empty = serializers.HiddenField(default=None,allow_null=True)
doc_23536491
But a jQuery accordion is not working now that my client uploaded the website in her server.The accordion is not opening. I don't know what to do. here you can check the section of the website which the accordion working in DropBox: https://dl.dropboxusercontent.com/u/100800235/EMC-%20web%20caleidoscopio%202/temas.html and here you can download the files I gave to my client: https://dl.dropboxusercontent.com/u/100800235/EMC-%20web%20caleidoscopio%202.zip Any clue or tips will be more than welcome. A: [1]: http://i.stack.imgur.com/C7C0a.jpg Here is a screenshot of the errors in the console. This will be why nothing is working
doc_23536492
I know very little about VBA, and am working through a macro. Macro for Printing Training Checklist report So, I'm printing a [Report]. The report name is "R Training Checklist". The variable filename is "filename" The end result would be a .pdf file saved with the data entered into field "filename" at the identified location. If I use Output File "C:\Users\mabanes\Creative Cloud Files\Training Checklists\test2.pdf" ...I have no problems. But, I don't want 1k records names "test2.pdf" where I have to go and individual rename each record. It seems I have something wrong in the expression, but can't seem to figure it out. "C:\Users\mabanes\Creative Cloud Files\Training Checklists\" & Reports![R Training Checklist].[Filename] & ".pdf" A: Private Sub Create_PDF_Report() Dim myPath As String Dim strReportName As String DoCmd.OpenQuery "QUERYNAME", acViewPreview myPath = "C:\Users\mabanes\Creative Cloud Files\Training Checklists\" strReportName = Report_Name.[Whatever you want here] + "etc." + ".pdf" DoCmd.OutputTo acOutputReport, "", acFormatPDF, myPath + strReportName, True DoCmd.Close acReport, "Reports" End Sub Should work for you with a bit of configuring to match your desired filename/path.
doc_23536493
The following simplified usage: class Foo(val bar: String) object Foo { implicit class Enrich(foo: Foo) { def clone(x: Int, y: Int): Int = x + y } } object Main extends App { val foo = new Foo("hello") println(foo.clone(1, 2)) // <- does not compile } generated the following error: method clone in class Object cannot be accessed in Foo Access to protected method clone not permitted because prefix type Foo does not conform to object Main where the access take place However, I can manually apply the implicit class and it successfully compiles: println(Foo.Enrich(foo).clone(1, 2)) // <- OK If I rename the method to something else (clone2, for example) the code compiles as expected. I assume this is somehow related to the magic around java.lang.Cloneable, but that method does not expect to parameters. So what is going on here? A: This has to do with the fact Object (or AnyRef in Scala) posses a protected method clone() which takes precedence in overload resolution of Foo. SI-6760 partially talks about this problem, although clone there has an identical signature while in this case it is different. This feels like a bug (and now open as SI-10206). When we expand the typer tree with -Ytyper-debug, you can see that it finds a suitable candidate for def clone(int, int), but then fails in the immediate subsequent search: |-- foo.clone(1, 2) : pt=Unit EXPRmode (site: method main in Main) | | | | |-- foo.clone BYVALmode-EXPRmode-FUNmode-POLYmode (silent: method main in Main) | | | | | |-- foo EXPRmode-POLYmode-QUALmode (silent: method main in Main) | | | | | | \-> foo.type (with underlying type my.awesome.pkg.Foo) | | | | | [search #1] start `my.awesome.pkg.Foo`, searching for adaptation to pt=foo.type => ?{def clone: ?} (silent: method main in Main) implicits disabled | | | | | |-- my.awesome.pkg.Foo.Enrich TYPEmode (site: method Enrich in Foo) | | | | | | \-> my.awesome.pkg.Foo.Enrich | | | | | |-- Foo TYPEmode (site: value foo in Foo) | | | | | | \-> my.awesome.pkg.Foo | | | | | |-- Int TYPEmode (site: method clone in Enrich) | | | | | | \-> Int | | | | | |-- Int TYPEmode (site: value x in Enrich) | | | | | | \-> Int | | | | | |-- Int TYPEmode (site: value y in Enrich) | | | | | | \-> Int | | | | | [search #1] considering pkg.this.Foo.Enrich | | | | | |-- pkg.this.Foo.Enrich BYVALmode-EXPRmode-FUNmode-POLYmode (silent: method main in Main) implicits disabled | | | | | | \-> (foo: my.awesome.pkg.Foo)my.awesome.pkg.Foo.Enrich | | | | | [search #1] success inferred value of type foo.type => ?{def clone: ?} is SearchResult(pkg.this.Foo.Enrich, ) | | | | | [search #2] start `my.awesome.pkg.Foo`, searching for adaptation to pt=(=> foo.type) => ?{def clone: ?} (silent: method main in Main) implicits disabled | | | | | \-> <error> Main.scala:6: error: method clone in class Object cannot be accessed in my.awesome.pkg.Foo Access to protected method clone not permitted because prefix type my.awesome.pkg.Foo does not conform to object Main in package pkg where the access take place foo.clone(1, 2) // <- does not compile Edit This does compile under 2.10.6 A: Seems like a bug with the way Scala masks java.lang.Object with AnyRef. I was tempted to say the difference between protected for Scala and Java could be the culprit (Java's being more visible), but this example works just fine: public abstract class Bar { protected Object method() { return null; } } case class Foo(bar: String) extends Bar object Example { implicit class Enrich(foo: Foo) { def method(x: Int, y: Int): Int = x + y } Foo("abc").method(1, 3) } You an work around this issue by overriding clone() to make it public, presuming you don't really need it. class Foo(val bar: String) { override def clone() = this } implicit class Enrich(foo: Foo) { def clone(x: Int, y: Int): Int = x + y } scala> new Foo("abc").clone(1, 2) res0: Int = 3
doc_23536494
$(document).ready(function(){ $( 'button' ).click(function() { $('#load').load('page1.html'); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="load"></div> <button>Click to load a new page</button> Please need help. A: Your Jquery code is correct. check in console error i think your page1.html is not found. So, set correct page1.html file path. If Page1.html path is correct then try this. it's work for me in chrome. $(function() { $( 'button' ).on('click', function() { $('#load').load('page1.html'); }); }); Html code. <div id="load"></div> <button>Click me</button> A: I have moved javascript code to the end of page and it works: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>load demo</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> </head> <body> <div id="load"></div> <button>Click to load a new page</button> <script> $('button').click(function() { $('#load').load('page1.html'); }); </script> </body> </html> A: Try This $(document).ready(function(){ $( 'button' ).on('click', function() { $('#load').load('page1.html'); }); }); Add button type button to your button tag <button type="button">Click to load a new page</button> A: A couple of things - * *Place your JS after your HTML to ensure all elements with the referenced IDs are loaded, or your code may not work. *You don't even need JQuery to do what you want. See the following snippet which uses the fetch() API built into all modern browsers (note you'll get an error displayed if you run the snippet below on this page because page1.html isn't available on StackOverflow)" <html> <head> <title>Hello</title> </head> <body> <div id="load" ></div> <button id="clickme">Click to load a new page</button> <script type="text/javascript"> (function() { document.getElementById("clickme").onclick = function() { fetch("page1.html") .then(function(response) { response.text().then(function (text) { document.getElementById("load").innerHTML = text; }) }) .catch(function(e) { document.getElementById("load").innerHTML = `Error loading: ${e.message}`; }) } }()); </script> </body> </html> A: Try to install any web server and try it.. it must work
doc_23536495
predictor variables in the surgical data set considering pindex as a confounding variable. I aim to plot the response variable(y) against the experimentally determined values of the predictor variables and to this end, I am Successful. However, could not able to indicate the estimated regression and p-value in the ggplot2. In the code below, trying to do the analysis and the plot. It would be much appreciated if someone could show me how to indicate the estimated regression and p-values inside the ggplot2. library(olsrr) library(tidyverse) library(reshape2) data(surgical) ## Regression pre1 <-setdiff(names(surgical), c("y", "pindex")) mod_dres<-NULL for (j in pre1) { model <- lm(y ~ pindex + get(j), data = surgical) bmodel <- broom::tidy(model) bmodel$term[3]<-j bmodel<-bmodel[3,] mod_dres<-rbind(mod_dres,bmodel) } mod_dres ## Matching the significant variables with the orginal data and reshaping pre1.plot = melt(surgical[,-c(2)], id.vars='y') %>% dplyr::filter(variable %in% mod_dres$term) ## plot the predictors varaibles ggplot(pre1.plot) + geom_jitter(aes(value,y, colour=variable), colour="darkorange", size = 3) + geom_smooth(aes(value,y, colour=variable), method=lm, se=FALSE, colour="darkorange") + theme_minimal() + theme(axis.title = element_text(size = 16,face="bold", colour = "black"), axis.text = element_text(size = 16,face="bold", colour = "black"), axis.line = element_line(colour='black'), axis.ticks = element_line(colour='black'), plot.title = element_text(hjust = 0.5,size=18,face="bold"), legend.position = "bottom", legend.title = element_text(color = "Black", size = 9, face = "bold"), legend.text=element_text(color = "Black", size = 9, face = "bold"), strip.text.x = element_text(size = 16,face="bold", colour = "black")) + labs(x = "value",title = " ") + facet_wrap(~variable, scales="free_x",nrow = 2, ncol = 4) + theme(panel.background = element_rect(fill = "white", colour = "black"), strip.background = element_rect(fill = "white", colour = "black"), legend.key = element_blank(), legend.title = element_blank()) Thank you! A: You can add the equation and p-value to the plot using the "stat_poly_eq" function from the ggpmisc package: library(tidyverse) library(olsrr) library(reshape2) library(ggpmisc) data(surgical) ## Regression pre1 <-setdiff(names(surgical), c("y", "pindex")) mod_dres<-NULL for (j in pre1) { model <- lm(y ~ pindex + get(j), data = surgical) bmodel <- broom::tidy(model) bmodel$term[3]<-j bmodel<-bmodel[3,] mod_dres<-rbind(mod_dres,bmodel) } mod_dres ## Matching the significant variables with the orginal data and reshaping pre1.plot = melt(surgical[,-c(2)], id.vars='y') %>% dplyr::filter(variable %in% mod_dres$term) ## plot the predictors varaibles ggplot(pre1.plot) + geom_jitter(aes(value, y, colour=variable), colour="darkorange", size = 3) + geom_smooth(aes(value, y, colour=variable), formula = y ~ x, method="lm", se=FALSE, colour="darkorange") + stat_poly_eq(formula = y ~ x, aes(x = value, y = y, label = paste(..eq.label.., ..p.value.label.., sep = "~~~~")), parse = TRUE) + theme_minimal() + theme(axis.title = element_text(size = 16,face="bold", colour = "black"), axis.text = element_text(size = 16,face="bold", colour = "black"), axis.line = element_line(colour='black'), axis.ticks = element_line(colour='black'), plot.title = element_text(hjust = 0.5,size=18,face="bold"), legend.position = "bottom", legend.title = element_text(color = "Black", size = 9, face = "bold"), legend.text=element_text(color = "Black", size = 9, face = "bold"), strip.text.x = element_text(size = 16,face="bold", colour = "black")) + labs(x = "value",title = " ") + facet_wrap(~variable, scales="free_x",nrow = 2, ncol = 4) + theme(panel.background = element_rect(fill = "white", colour = "black"), strip.background = element_rect(fill = "white", colour = "black"), legend.key = element_blank(), legend.title = element_blank()) Edit And you can add other statistics, like the R^2 value: ggplot(pre1.plot) + geom_jitter(aes(value, y, colour=variable), colour="darkorange", size = 3) + geom_smooth(aes(value, y, colour=variable), formula = y ~ x, method="lm", se=FALSE, colour="darkorange") + stat_poly_eq(formula = y ~ x, aes(x = value, y = y, label = paste(..rr.label.., ..p.value.label.., sep = "~~~~")), parse = TRUE) + theme_minimal() + theme(axis.title = element_text(size = 16,face="bold", colour = "black"), axis.text = element_text(size = 16,face="bold", colour = "black"), axis.line = element_line(colour='black'), axis.ticks = element_line(colour='black'), plot.title = element_text(hjust = 0.5,size=18,face="bold"), legend.position = "bottom", legend.title = element_text(color = "Black", size = 9, face = "bold"), legend.text=element_text(color = "Black", size = 9, face = "bold"), strip.text.x = element_text(size = 16,face="bold", colour = "black")) + labs(x = "value",title = " ") + facet_wrap(~variable, scales="free_x",nrow = 2, ncol = 4) + theme(panel.background = element_rect(fill = "white", colour = "black"), strip.background = element_rect(fill = "white", colour = "black"), legend.key = element_blank(), legend.title = element_blank()) See the docs for other statistics that can be included, e.g. "adj.rr.label", "f.value.label" etc: https://rdrr.io/cran/ggpmisc/man/stat_poly_eq.html
doc_23536496
const weeks = []; const daysInWeek = []; numberOfDays = 35; for (let i = 1; i <= numberOfDays; i ++) { if (i % 7 === 0){ weeks.push(i) } // output [7, 14, 21, 28, 35] for (logic here...) { daysInWeek.push([?]) } } I would like daysInWeek to look something like this : [[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14], [15,......], ...] It is the first time I work with nested loops and I can't really grasp the idea and therefor I am unsure how to use the second loop. Any help would be greatly appreciated. A: Create a new array inside of the if (i % 7 === 0){ statement. That array is going to be created for every week and is going to hold your days. Now start the second loop by subtracting 6 from the current value of i. i will always be a multitude of 7. So by subtracting 6 you get the first day in that week. Store that result in j. Then for the evaluation part of the loop, check if j is equal or lower than i, we never want to go higher than the last day in the current week. Also check if j is equal or lower than numberOfDays. You don't want to add more days than you indicated. Add each day to the days array. Then after the loop add the days array to daysInWeek. Now you got this nested array structure. const weeks = []; const daysInWeek = []; numberOfDays = 35; for (let i = 1; i <= numberOfDays; i ++) { if (i % 7 === 0){ weeks.push(i) const days = []; for (let j = i - 6; j <= i && j <= numberOfDays; j++) { days.push(j); } daysInWeek.push(days); } } console.log(daysInWeek); A: Your loop is wrong. Please try this also. Within a single loop we can create both all arrays and add them together like this. const weeks = []; const daysInWeek = []; numberOfDays = 35; for (let i = 1; i <= numberOfDays; i ++) { const weekid = parseInt(((i-1)/7)); // used i-1 because in the loop i started as 1. if we use i/7 we loose a day record from the first week. Test it. if(!weeks.includes(weekid) ){ weeks.push(weekid); } let tempArray = []; if(daysInWeek[weekid] === undefined){ daysInWeek[weekid] = []; } daysInWeek[weekid].push(i); } console.log(daysInWeek); A: Math.floor((i - 1) / 7) give you the key of the table to push your days <script type="text/javascript"> const weeks = []; const daysInWeek = [[]]; numberOfDays = 35; for (let i = 1; i <= numberOfDays; i ++) { if (i % 7 === 0){ weeks.push(i) daysInWeek.push([]) } daysInWeek[Math.floor((i - 1) / 7)].push(i) } console.log(daysInWeek); </script>
doc_23536497
#include <stdio.h> #include <stdlib.h> #include <curl/curl.h> function_pt(void *ptr, size_t size, size_t nmemb, void *stream){ char **response_ptr = (char**)stream; *response_ptr = strndup(ptr, (size_t)(size *nmemb)); } int main(void) { CURL *curl; CURLcode res; char *response =calloc(1,sizeof(char)); curl = curl_easy_init(); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, "http://example.com"); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, function_pt); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); res=curl_easy_perform(curl); curl_easy_cleanup(curl); printf("%s\n",response); } return 0; } The data I get form http get request is real time,so i need to continue with the get request and store value in a variable in an iterative manner,only so that I can use the data in all other parts of the program.But the following code works only once and then exit. How can I do it? Are there any other methods to generate http get request? A: You don't need to calloc() the pointer if you are going to strndup() the original string, assuming that the response is a string is not good because that is not necessarily true. I would suggest a structure where you can also store the length of the response, so if it's not text but for example a jpeg file nothing bad will happen, and you should not call printf() unless you check from the response headers that the response is indeed text, and it will be nul terminated afaik.
doc_23536498
$imageFile = imagecreatefromstring($image); if ($imageFile !== false) { $width = ImageSX($imageFile); $height = ImageSY($imageFile); } if ($this->isExifInstalled) { @$type = exif_imagetype($source); $mime = image_type_to_mime_type($type); } if ($mime === "application/octet-stream") { $mime = $this->image_file_type_from_binary($image); } if ($mime === "application/octet-stream") { $mime = $this->getMimeTypeFromUrl($source); } imagedestroy($imageFile); A: Extending the memory limit from available to double did the job, but the problem seems to be with the method "imagecreatefromstring" there must be an issue causing exhaust or false error. can modify php.ini "memory_limit" or use ini_set("memory_limit","512M"); ini_set is preferable as using that you can identify the memory usage in future, better explore the reason how can the code be optimized without unnecessarily exceeding the limit.
doc_23536499
i want to make a button to automaticly save the image please help, thanks A: you need a canvas element which will get draw with the video data by using drawImage(videoelement,0,0,videowidth,videoheigth) (being the canvas as big as the video) and then use canvas.toDataURL(); which will give you a base64 png image of the frame in the canvas then convert the data to a blob so you can save it then you just need to make the blob a url and by opening the url it shall be saved Example var v = document.getElementById("video1"); var canvas = document.getElementById("myCanvas"); ctx = canvas.getContext("2d"); var interval; function canvasdrawvideo() { ctx.drawImage(v, 0, 0, 270, 135); } function savecanvasimage(fileName) { var dataURL = canvas.toDataURL("image/png"); var data = atob(dataURL.substring("data:image/png;base64,".length)), asArray = new Uint8Array(data.length); for (var i = 0, len = data.length; i < len; ++i) { asArray[i] = data.charCodeAt(i); } var blob = new Blob([asArray.buffer], { type: "octet/stream" }); var a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none"; var url = window.URL.createObjectURL(blob); a.href = url; a.download = fileName; a.click(); window.URL.revokeObjectURL(url); } v.addEventListener("play", function() { interval = setInterval(canvasdrawvideo, 20); }); v.addEventListener("pause", function() { clearInterval(interval); }, false); v.addEventListener("ended", function() { clearInterval(interval); }, false); <html> <body> <p>Video to use:</p> <video id="video1" controls width="270" autoplay> <source src="http://www.w3schools.com/tags/mov_bbb.mp4" type='video/mp4' /> <source src="http://www.w3schools.com/tags/mov_bbb.ogg" type='video/ogg' /> <source src="http://www.w3schools.com/tags/mov_bbb.webm" type='video/webm' /> </video> <canvas id="myCanvas" width="270" height="135" style="border:1px solid #d3d3d3;"> Your browser does not support the HTML5 canvas tag.</canvas> <button onclick="savecanvasimage('image.png')">ScreenShot</button> </body> </html> only problem is that the video must to be on the same server and the code needs to run on a server otherwise it gives error but it works perfectly in my apache server here