id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23529800
double someVal = 25.03; return (someVal * 3) - 50; For Reasons (mostly rounding errors) I would like to change all these snippets to use BigDecimal instead of double, modifying the math functions along the way, like this: MathContext mc = MathContext.DECIMAL32; BigDecimal someVal = new BigDecimal("25.03", mc); return someVal.multiply(BigDecimal.valueOf(3), mc).subtract(BigDecimal.valueOf(50), mc); The snippets are mostly pretty simple, but I would prefer to avoid a fragile solution (eg, regex) if I can. Is there a relatively straightforward way to do this? Note I want to have a program or code perform these modifications (metaprogramming). Clearly I'm capable of making the changes by hand, but life is too short. A: You could try Google's "Refaster", which, according to the paper, is "a tool that uses normal, compilable before-and-after examples of Java code to specify a Java refactoring." The code lives under core/src/main/java/com/google/errorprone/refaster in Google's error-prone github project. (It used to live in its own github project.) This is more of a hint than an answer, though, since I've never worked directly with Refaster and don't know how well it does on primitive expressions like the ones in your example. I also don't know how well-suited it is for toolchain use like yours, vs. one-time refactors (which is how Google tends to use it). But it's actively maintained, and I've seen it used really effectively in the past. A: We use BigDecimal for financial calculation. As per other comments, you going to have some performance degradation and the code will be very hard to read. The performance impact depends on how many operation you going to have. Usually, you facing rounding issues with doubles when your calculation chain is long. You wouldn't have many issues if you do c=a+b but will if you have c+=a+b million times. And with a thousand of operations, you will notice how bigDecimal are slower than double, so do performance testing. Be careful when changing your code especially with the division, you will have to specify rounding mode and scale of the result, this what people usually wouldn't do and it leads to the errors. I assume it not only about replacing calculation logic but also you'll need to change your domain model so I doubt you can come up with a script to do it in a reasonable time, so do it by hands. Good IDE will help you a lot. No matter how you going to convert your code I suggest to firstly make sure that all your calculation logic covered by unit tests and do unit test conversion before changing the logic. I.e replace assertion of the values by wrapping them with bigDecimals. In that case, you will avoid silly typing/algorithm mistakes. I would not answer your question how to convert from double to BigDecimal just want to share some notes regaridng to the A: Don't do this. * *It's a huge readability hit. Your example turned "25.03 * 3 - 50" into 4 lines of code. *Financial code usually uses double, or long for cents. It's precise enough that it's just a question of proper programming to avoid rounding errors: What to do with Java BigDecimal performance? *It's, likely, a huge performance hit, in particular with erratic garbage collections, which is not acceptable for HFT and the like: https://stackoverflow.com/a/1378156/1339987 *I don't know how much code you are talking about but I do expect you will have to make lots of small decisions. This reduces the chance there is an openly available tool (which I'm all but sure does not exist) and increases the amount of configuration work you would have to do should you find one. *This will introduce bugs for the same reason you expect it to be an improvement, unless you have extremely good test coverage. Programmatically manipulating Java source is covered here: Automatically generating Java source code You don't need to accept this answer but I believe my advice is correct and think other readers of this question need to see up-front the case for not making this transformation, which is my rationale for posting this somewhat nonanswer.
doc_23529801
$production_item_product_update = []; $production_item_inventory_update = []; for ($code = 0; $code < count($data->product_id); $code++) { $production_item_product_create[] = $data->product_id[$code]; $production_item_inventory_create[] = [ 'qty' => calculate_inventory_qty($data->product_id[$code], 0, Auth::user()->store_id), 'buy_price' => number_patch($data->buy_price_small[$code]), 'average_price' => calculate_inventory_average($data->product_id[$code], Auth::user()->store_id), ]; } then update by this code inventory::where('store_id', Auth::user()->store_id) ->whereIn('product_id', $production_item_product_update) ->update($production_item_inventory_update); give me this error SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' (SQL: update `inventories` set `0` = {\"qty\":10,\"buy_price\":\"1.2574\",\"average_price\":32,\"single_price\":\"34\",\"multi_price\":\"34\",\"vip_price\":\"34\"} where `store_id` = 3 and `product_id` in (84)) A: You could try this in your for loop for ($code = 0; $code < count($data->product_id); $code++) { $data = inventory::where('store_id', Auth::user()->store_id) ->whereIn('product_id', $production_item_product_update) ->update( 'qty' => calculate_inventory_qty($data->product_id[$code], 0, Auth::user()->store_id), 'buy_price' => number_patch($data->buy_price_small[$code]), 'average_price' => calculate_inventory_average($data->product_id[$code], Auth::user()->store_id)); }
doc_23529802
funct functionNAME (Object o) { o+1 }; The point is that The user has to use the identifier 'o' within the curly braces and not some other identifier. This is of course specified by the input in the (Object o) part where 'o' can be anything. Basically the identifier within the curly braces must be the same as the identifier defined in the parameter. I know I can store the matched token and print it out to screen but is it possible to use it as a lexical token itself? Thanks. A: Yes there is a better way to do this. You need a symbol table. The job of a symbol table is to keep track of which identifiers can be used at each point in the program. Generally the symbol table also contains other information about the identifiers, such as what they represent (e.g. variable or function name) and what their types are. Using a symbol table you can detect the use of variables that are not in scope during parsing for many languages but not all. E.g. C and Pascal are languages where identifiers must be declared before they are used (with a few exceptions). But other languages (e.g. Java) allow identifiers to be declared after they are used and in that case it is best not to try to detect errors such as use of an undeclared variable until after the program is parsed. (Indeed in Java you need to wait until all files are parsed, as identifiers might be declared in another file.) I'll assume a simple scenario, which is that you only need to record information about variables, that there is no type information, and that things must be declared before use. That will get you started. I haven't bothered about adding the function name to the symbol table. Suppose a symbol table is a stack of things called frames. Each frame is a mutable set of strings. (Later you may want to change that to a mutable map from strings to some additional information.) void Start(): { } { <FUNCTION> <IDENTIFIER> {symttab.pushNewFrame() ;} <LBRACKET> Parameters() <RBRACKET> <LBRACE> Expression() <RBRACE> {symtab.popFrame() ; } } void Parameters() : {} { ( Parameter() (<COMMA> Parameter() )* )? } void Parameter() : { Token x ; } <OBJECT> x=<IDENTIFIER> { if( symtab.topFrame().contains(x.image) ) reportError( ... ) ; } { symtab.topFrame().add(x.image) ; } } void Expression() : { } { Exp1() ( <PLUS> Exp1() )* } void Exp1() : { Token y ; } { y = <IDENTIFIER> { if( ! symtab.topFrame().contains(y.image) ) reportError( ... ) ; } | <NUMBER> } A: you can store the value of the identifier matchin o, and then check in the curly brace if the identifier there is the same, and, if not, throw an Exception. A: Okay I have worked out a way to get what I want based on the example I gave in OP. It is a simple variant of the solution I have implemented in mine just to give a proof of concept. Trivial things such as token definitions will be left out for simplicity. void Start(): { Token x, y; } { <FUNCTION> <FUNCTION_NAME> <LBRACKET> <OBJECT> x = <PARAMETER> <RBRACKET> <LBRACE> y = <PARAMETER> { if (x.image.equals(y.image) == false) { System.out.println("Identifier must be specified in the parameters."); System.exit(0); } } <PLUS> <DIGIT> <RBRACE> <COLON> } Is there a better way to do this?
doc_23529803
For v4.x, utilize worker-loader For v5.x, just use URL constructor I'd like my library to work with either of Webpack version so I'd like to make some of the code bundlable only for Webpack v4, and some only for Webpack v5. How to do it? Something like: // # Code for Webpack 4 # const BackLayerSharedWorker = require("../BackLayer/index.sharedworker.js").default; this.worker = new BackLayerSharedWorker(); // # Code for Webpack 4 - END # // # Code for Webpack 5 # this.worker = new SharedWorker( new URL("../BackLayer/index.sharedworker.js", __dirname) ); // # Code for Webpack 5 - END #
doc_23529804
Can anyone help me with this validation? see what I'm doing wrong ?? my model package br.com.nextinfo.multimedia.web.model; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotBlank; @Table @Entity(name="slideshow") public class SlideShow { private Long condigo; private String titulo; private String subTitulo; private ImagemSlider imagemSlider; @Id @GeneratedValue(generator="codigo",strategy=GenerationType.AUTO) @SequenceGenerator(name = "codigo", sequenceName = "codigo_slideshow") @Column(name = "CODIGO") public Long getCondigo() { return condigo; } @NotNull @NotBlank @Column(name = "TITULO" ,nullable = false) public String getTitulo() { return titulo; } @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name ="CODIGO_IMAGEM") public ImagemSlider getImagemSlider() { return imagemSlider; } @NotNull @NotBlank @Column(name = "SUBTITULO" ,nullable = false) public String getSubTitulo() { return subTitulo; } public void setTitulo(String titulo) { this.titulo = titulo; } public void setSubTitulo(String subTitulo) { this.subTitulo = subTitulo; } public void setImagemSlider(ImagemSlider imagemSlider) { this.imagemSlider = imagemSlider; } public void setCondigo(Long condigo) { this.condigo = condigo; } } my controller package br.com.nextinfo.multimedia.web.controller; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import br.com.nextinfo.multimedia.web.model.ImagemSlider; import br.com.nextinfo.multimedia.web.model.SlideShow; import br.com.nextinfo.multimedia.web.services.AbstractFactoryService; import br.com.nextinfo.multimedia.web.services.CreateSlideShowService; import br.com.nextinfo.multimedia.web.services.ImagemServiceDatabase; @Controller @RequestMapping("/arquivosbanco/") public class FilesDatabaseController implements AbstractControllerApp ,PadraoCrudMetodos<ImagemSlider> { @Autowired private ImagemServiceDatabase imagemService; @Autowired private CreateSlideShowService slideShowService; @Override public String getRequisicaoPadrao(Model model) { List<ImagemSlider> lista = this.getAbstractService().realizaPaginacao("0", "10" ,null).getContent(); model.addAttribute("listaObjetoPageStart", lista); model.addAttribute("img", new ImagemSlider()); return this.getUrlInicial(); } @Override public String getUrlInicial() { return "arquivos/database/listarquivosbancodedados"; } @ResponseBody @RequestMapping(value = "/img", method = RequestMethod.GET) public void showImage(@RequestParam("id") Long id, HttpServletResponse response,HttpServletRequest request) throws ServletException, IOException { response.setContentType("image/jpeg, image/jpg, image/png, image/gif"); ImagemSlider imgdatabase = imagemService.getAbstractService().getBean(id); if (imgdatabase!=null ) { response.getOutputStream().write(imgdatabase.getImage()); response.getOutputStream().close(); } } @Override public AbstractFactoryService<ImagemSlider> getAbstractService() { return imagemService; } @RequestMapping(value = "/createslideshow/{imagemid}" ,method=RequestMethod.GET) public String createslider(@PathVariable("imagemid") Long image,Model model){ final ImagemSlider img = this.imagemService.getBean(image); model.addAttribute("imgslider", img); model.addAttribute("slideshow", new SlideShow()); return "arquivos/createdisplay"; } @RequestMapping(value = "/save" ,method=RequestMethod.POST) public String saveSlideShowr( @RequestParam Long imagemid ,@Valid final SlideShow slideshow,final BindingResult result ,RedirectAttributes redirectAttrs){ ImagemSlider img = this.imagemService.getBean(imagemid); if (result.hasErrors()) { redirectAttrs.addFlashAttribute("org.springframework.validation.BindingResult.strategy", result); redirectAttrs.addFlashAttribute("slideshow", slideshow); return "redirect:/arquivosbanco/createslideshow/"+imagemid; }else{ this.slideShowService.salva(slideshow); if (img != null) { slideshow.setImagemSlider(img); this.slideShowService.salva(slideshow); } } return this.getUrlInicial(); } } <html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorator="/templates/layouts/principal"> <head> <title>Criacao slideshow</title> </head> <body> <div class="container-fluid" layout:fragment="corpopagina"> <h3 class="page-header text-center">Criacao slide show</h3> <form id="registration-form" class="form-horizontal" th:object="${slideShow}" th:action="@{/arquivosbanco/save/?imagemid=}+${imgslider.codigo}" method="post"> <!-- Print all errors here!--> <div class="col-md-4 col-xs-12"> <div class="thumbnail"> <img class="img-responsive" th:attr="src=@{'/upload/img?codigo='+${imgslider.codigo}}" width="400" height="400" /> <span class="text-center"></span> </div> <div class="caption"> <h5>Codigo <span th:text="${imgslider.codigo}" class="badge" style="margin-left:20px">5</span></h5> <h5>Nome <span th:text="${imgslider.nome}" class="badge" style="margin-left:20px">5</span></h5> </div> </div> <div class="col-md-8 col-xs-12"> <div class="form-group"> <label class="col-xs-3 control-label">Titulo principal</label> <div class="col-md-8"> <input type="text" class="form-control" name="titulo" /> </div> </div> <div class="form-group"> <label class="col-xs-3 control-label">Sub titulo</label> <div class="col-md-8"> <input type="text" class="form-control input-xs" name="subTitulo" /> </div> </div> <div class="form-actions"> <label class="col-md-3 control-label"></label> <div class="col-md-7"> <button type="submit" class="btn btn-success btn-large">Salvar</button> </div> <div class="col-md-1"></div> </div> </div> </form> </div> </body> in my controller is validating usually more in view does not show anything how can I solve? I am quite some time on stackoverflow, most can not find the solution ... A: Your view is not showing anything as you have not included the error messages in your template. Here is an example below. <td th:if="${#fields.hasErrors('age')}" th:errors="*{age}">Name Error</td>
doc_23529805
How do I access the host/domain the client is on in my lambda function? Can I move the Host header to X-Forwarded-Host? e.g. abc.com (cloudfront) -> API gateway -> lambda (Host: abc.com) A: In order to propagate Host header through Cloudfront and API Gateway, follow these steps: Configure Cloudfront to forward Host header Step-by-step guide Key points: Choose the Behaviors tab, and then choose the path that you want to forward the Host header to. Choose Edit. Under Cache key and origin requests, confirm that Legacy cache settings is selected. If it's not selected, then follow the steps in the preceding section to create a cache policy. If Legacy cache settings is selected, then complete the following: For Headers, select Include the following headers. From the Add header dropdown list, select Host. Configure API Gateway request to relay Host header Detailed docs here Key point: Edit your API Gateway resource(s) and for each method you need the Host header edit the Method Request by adding Host header in the HTTP Request Headers list. You can also move the Host header to X-Forwarded-Host using a Cloudfront function but you would still need to follow the steps above to propagate X-Forwarded-Host header. You can try this out starting with this sample function.
doc_23529806
What i would want him to do, is to convert any text into NA's while importing. I have seen that you can use na.strings = ..., but that would apply to all columns, right? I only want to exclude characters from one column, not from the whole csv. Is there an easy solution to this, or do i have to manually check each column for such values and convert them to NA's? EDIT: Additional information: this is what my code looks like: df <- read.csv(text=capture.output(write.csv(d.xxx,row.names=FALSE)), colClasses=d.yyy, header = TRUE) where d.xxx is a data frame containing the values and d.yyy is a list containing "integer","character",etc. in the correct order EDIT2: This is the error i get: Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, : scan() expected 'a real', got '"2"' A: just import the column as strings and then run as.numeric() on the column in the data.frame. That will return a vector of numeric values for actual numbers and NAs for elements that are strings.
doc_23529807
int N = AudioRecord.getMinBufferSize(8000,AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT); recorder = new AudioRecord(AudioSource.MIC, 8000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, N*10); track = new AudioTrack(AudioManager.STREAM_MUSIC, 8000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, N*10, AudioTrack.MODE_STREAM); recorder.startRecording(); /* * Loops until something outside of this thread stops it. * Reads the data from the recorder and writes it to the audio track f */ while(!stopped) { //Log.i("Map", "Writing new data to buffer"); short[] buffer = buffers[ix++ % buffers.length]; N = recorder.read(buffer,0,buffer.length); for(int i = 0; i < buffer.length; i ++) { System.out.println(String.valueOf(buffer[i])); } } I would like to either 1) have the pcm data be matched to previous pcm data or 2) have it be recognized as a word. For example. If I say 'hello' inside the mic, it turns the pcm data into the word hello and I can process according to the word or if I record a 'hello' and a 'world' in two separate buffers, then say 'hello' again, it can determine that I repeated the 'hello' and not the world. Help Please. A: Android has built in speech recognition. However, I don't believe it supports recorded PCM data. To use it, I believe, you must take voice input directly. See http://android-developers.blogspot.com/2010/03/speech-input-api-for-android.html to get started. If you must have recorded data, you could use other services to do speech recognition. For an intro to some of the choices see https://stackoverflow.com/a/6351055/90236. If you are just playing (and not building a production app), you could also try using the Google services for speech recognition that Chrome uses. You'd have to convert from PCM to FLAC. See Google's voice search speech recognition service If you want to compare PCM buffers without doing recognition, signal processing is a deep and interesting field. Sorry, I'm too rusty to give any advice in that realm.
doc_23529808
public static void printSubSets(Set set){ int n = set.size(); ArrayList<String> strings = new ArrayList<>(); Object[] chars = set.toArray(); for (int i = 0; i < (1<<n); i++) { String string = ""; string += "{"; for (int j = 0; j < n; j++) if ((i & (1 << j)) > 0) string += chars[j].toString() + ","; string+= "}"; if (string.length() > 2){ StringBuilder stringBuilder = new StringBuilder(string); stringBuilder.deleteCharAt(string.lastIndexOf(",")); strings.add(stringBuilder.toString()); } else { strings.add(string); } } strings.sort((s1, s2) -> s1.length() - s2.length()); for (int i = 0; i < strings.size(); i++) { if (i == strings.size() - 1){ System.out.println(strings.get(i) + ""); } else{ System.out.print(strings.get(i) + " , "); } } } I used the above function to find all the subsets and it works fine and here is my main method : public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int row1 = 0; int row2 = 0; Set A = new TreeSet(); Set B = new TreeSet(); row1 = scanner.nextInt(); for (int i = 0; i < row1; i++) { A.add(scanner.nextInt()); } row2 = scanner.nextInt(); for (int i = 0; i < row2; i++) { B.add(scanner.nextInt()); } System.out.print("A -> "); Main.printSubSets(A); System.out.print("B -> "); Main.printSubSets(B); } for input : 4 1 2 3 4 3 3 5 7 and the output is : A -> {} , {1} , {2} , {3} , {4} , {1,2} , {1,3} , {2,3} , {1,4} , {2,4} , {3,4} , {1,2,3} , {1,2,4} , {1,3,4} , {2,3,4} , {1,2,3,4} B -> {} , {3} , {5} , {7} , {3,5} , {3,7} , {5,7} , {3,5,7} but there is a problem. I want it to be like this : A -> {} , {1} , {2} , {3} , {4} , {1,2} , {1,3} , {1,4} , {2,3} , {2,4} , {3,4} , {1,2,3} , {1,2,4} , {1,3,4} , {2,3,4} , {1,2,3,4} I mean that I want {1,4} to precede the {2,3} I will be glad if you help solve this A: May I suggest a different solution to find all the subsets of a Set: Set<Integer> mySet = new HashSet<Integer>(); mySet.add(1); mySet.add(2); mySet.add(3); Set<Set<Integer>> powerSet = powerSet(mySet); LinkedList<Set<Integer>> ans = new LinkedList<>(); for(Set<Integer> element : powerSet){ for(Set<Integer> el : powerSet){ if(el.size() == element.size() && !ans.contains(el)){ ans.add(el); } } } System.out.println(ans.toString()); and public static <Integer> Set<Set<Integer>> powerSet(Set<Integer> pSet) { Set<Set<Integer>> sets = new HashSet<Set<Integer>>(); if (pSet.isEmpty()) { sets.add(new HashSet<Integer>()); return sets; } List<Integer> integersList = new ArrayList<Integer>(pSet); Integer head = integersList.get(0); Set<Integer> restSet = new HashSet<Integer>(integersList.subList(1, integersList.size())); for (Set<Integer> set : powerSet(restSet)) { Set<Integer> newSet = new HashSet<Integer>(); newSet.add(head); newSet.addAll(set); sets.add(newSet); sets.add(set); } return sets; } And the output is: [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]] You can try it with more integers. The method is the same even if you read integers from the console.
doc_23529809
Here is the important my content script: var dataObject = { "searches": [], "links": [], "time": [] }; var key = 'myKey'; chrome.storage.sync.set({ key: dataObject }, function() { console.log('Value is set to:'); console.log(dataObject); }); chrome.storage.sync.get(['key'], function(result) { console.log("Value is:"); console.log(result.key); }); A: Content script runs each-time the page is refreshed and in your content script your are first saving a pre defined object in the chrome storage. It will reset on each page refresh even if it is changed on some events. Solution: You will need to check first if the object(myKey) is saved in storage than you should just add new values to it. Please note: Your extension's content scripts can directly access user data without the need for a background page. Read more here.
doc_23529810
$r = new WP_Query( array( 'tax_query' => array( 'relation' => 'OR', array( 'taxonomy' => 'custcategory', 'field' => 'term_id', 'terms' => array(10)), ), 'category__in'=>array(10), 'post_type'=> $post_type , 'posts_per_page' => $number, 'meta_key' => 'post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC' ) ); if ($r->have_posts()) : // Enters this block in home page and detail page while ( $r->have_posts() ) : $r->the_post(); else: // Enters this block in category page Anyone know why this strange behavior is? A: Maybe you have some filter that is affecting categories page, add this to your query args: 'suppress_filters' => true You can also try adding wp_reset_query() after your main query, but this should not be necessary because you are declaring a new WP_Query. A: I just realize that your query args are wrong. You have set a relation, but you only have one taxonomy array. Also you don't need the 'category__in'=>array(10) argument, it is only for the default taxonomy "category" and you want only posts from your custom taxonomy "custcategory", isn't it? Your query should be: $r = new WP_Query( array( 'tax_query' => array( array( 'taxonomy' => 'custcategory', 'field' => 'term_id', 'terms' => array(10) ), ), 'post_type'=> $post_type , 'posts_per_page' => $number, 'meta_key' => 'post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC' ));
doc_23529811
task = JSON.parse(request.body.read) puts task.inspect puts 'description hash: ' puts task[:description] When this block of code runs, I get: {"completed" => false, "task_type" => 0, "description"=> "second task"} description hash: nil Is there a different way to access this hash? Because from what I see the inspection shows a description value. A: The Problem In the example you gave, you are defining a hash key of "description" but looking up the :description key instead, which doesn't exist. The reason is that the first is a String, and the second is a Symbol. "description".class => String :description.class => Symbol The Solution Either look up your key with a string, or call #to_s on your subscript if you know your keys are always a String, but your subscript may not be. task['description'] => "second task" task[:description.to_s] => "second task" A: :description isn't the same as 'description'. This should work: puts task['description']
doc_23529812
if(?){ print_r(array_values($parcels)[0]); } else{} tried multiple statements but all lead to error or invalid. If a new order comes in array[0] gets replaced with that info. So only when that info has changed execute this.. Is this Possible? A: You need to store the old value in an other variable to compare it. So you are able to consider if the value has changed. $oldValue = $parcels[0]; //------- //Code that eventually changes the array //------- if($oldValue != $parcels[0]) { print_r(array_values($parcels)[0]); $oldValue = $parcels[0]; } else{}
doc_23529813
`case 39: scrollAmount = scrollAmount + 200 $('.carousel-cars').animate({scrollLeft:scrollAmount}, 'fast'); // seta direita break; case 37: scrollAmount = scrollAmount - 200 $('.carousel-cars').animate({scrollLeft:scrollAmount}, 'fast'); // seta esquerda break;` I tried reducing scrollAmount
doc_23529814
originalfilename.renameTo(new File("C")); It's giving me that renameTo is undefined for type String. Why am I getting this? Is there any other simpler API or statements to acheive this? EDIT:How to move to different directory rather than creating a new file? A: renameTo is a method of the File class, you are trying to use it on a String. File original = new File(originalfilename); original.renameTo(new File("C"));
doc_23529815
The images table has a target_id, target_type and target_column, three pieces of information which identify it with any number of content tables. The target_type just references the table name of the piece of content that is associated to the image. target_column is the name of a virtual column (not actually in the content table) that is used to look up the image. This enables any arbitrary piece of content to have several associated images, each by a different name. When you have a piece of content and want to find what image is associated to a particular name, you do a select * from images where target_id = content.id and target_type = "content" and target_column = "image"; All of these pieces of information are available when you have a reference to a particular piece of content. What I want to do instead is REVERSE all of these, so that the images table knows nothing about the particular pieces of content that reference it, and instead that burden is carried by each of the content tables. So far I know I can add a column to the content table and then select the information I need from the images table: select id, target_id from images where target_type = "content"; What I want to do is use this as a subquery and do a mass update of the content table. Is something like this possible? update content set image_id = (select id from images where target_type = "content") as image_ids where id = (select target_id from images where target_type = "content") as content_ids; I know this fails, but I want to do some kind of mass assignment of target_ids back to image_ids. Is this madness? How do I do this? A: you might want to use the Mysql multiple-table update mechanism. (cf http://dev.mysql.com/doc/refman/5.0/en/update.html) in your case, this would be update content, images set content.image_id = images.id where images.target_id = content.id and images.target_type = 'content' and images.target_column = 'images' I hope this will help you Jerome Wagner A: You can join in the images table to do the update: update content inner join images on images.target_id = content.id and images.target_type = 'content' and images.target_column = 'images' set content.image_id = images.id
doc_23529816
Following is the code. j('#infoTableId').jtable({ paging : true, //Enable paging pageSize : 10, //Set page size (default: 10) cache: false, sorting:true, actions : { listAction: '${baseURL}/myListPaginationDataTablesAjaxCall.html' }, recordsLoaded: function(event, data) { buildPendCodesDropDown(); }, fields: { MyId : { title : 'My Id', width : '15%', key : true, list : true, edit : false, create : false }, myPoolName : { title : 'My Pool', width : '20%', list : true, edit : false, sorting:true, create : false, display:function(data){ return data.record.myPool.myPoolName; } } } }); j('#infoTableId').jtable('load'); A: Without code, all I can guess is that jTable field name differs from database column name. There are many possibilities. In your case, as you are using display function to show the data, it should be enough if you declare the name column exactly as the database column And if this field depends on the joining of other table, you should put 'tableName.columnName', with the quotes. I use it for Spring, and the pretty solution should be calling the variables of the form which store the data(and display in the table) the same as the columns table in database. If you do this last option, you don't need to use display function. EDIT: After reading again I have a question. The table display any record in the first request? If the answer is No (and it display an error message), in your table declaration put the variable defaultSorting: 'columnName' after your sorting: true. A: Brother, you just have to add this in your query at the listing page. if($_GET["jtSorting"]!=null &&$_GET["jtSorting"]!="") { $query_s =$query_s. " ORDER BY ".$_GET["jtSorting"]." "; } Use this after your WHERE clause and before LIMIT condition. hope this will work, also "MyId" and "myPoolName" must match the field names in DB. title doesn't matter. Hope this will work
doc_23529817
class que { public: que operator++(int) {} // 1 que &operator++() {} que &operator+=(int n) { que& (que::*go)(); go = 0; if(n > 0) go = &que::operator++ ; // 2 //go = (n > 0) ? (&que::operator++) : 0 ; // 3 } }; int main() { que iter; iter += 3; return 0; } I want to replace line 2 by line 3("if" statement for "?:"). If I uncomment 3, compiler gives me an error. If I delete line 1, then line 3 works. Question is: what does compiler want from me? Error: error: address of overloaded function with no contextual type information Compiler: gcc-4.5.2 A: error: address of overloaded function with no contextual type information There are two functions with the operator++ name (that's the 'overloaded function' bit of the message), you need to specify which one you want (that's the 'contextual type information' one): n > 0 ? (que& (que::*)())&que::operator++ : 0 You have to consider that the above subexpression is independent from the enclosing full expression, the assignment to go. So it must be correct on its own, i.e. it can't use the type of go to pick the correct overload because it's not part of this particular subexpression.
doc_23529818
I want to create a constructor which takes std::wstring and return a std::string. is it possible and how? Thanks. A: Can I overload the std::string constructor? Nope, it would require changing std::string declaration. I want to create a constructor which takes std::wstring and return a std::string. is it possible and how? You can have a conversion function instead, like: std::string to_string(std::wstring const& src); However, you need to decide what to do with symbols that can't be represented using 8-bit encoding of std::string: whether to convert them to multi-byte symbols or throw an exception. See wcsrtombs function. A: Rather define a free function: std::string func(const std::wstring &) { } A: No, you cannot add any new constructors to std::string. What you can do is create a standalone conversion function: std::string wstring_to_string(const wstring& input) { // Your logic to throw away data here. } If you (think you) want this to happen automatically, I strongly suggest re-evaluating that idea. You'll cause yourself a significant amount of headaches as wstrings are automatically treated as string when you least expect it. A: This is not the Right True Way of doing it, and I think that I had smoked something when I coded this, but it solves the problem. Check the last function, `convert_str'. #pragma once #include <memory> #include <string> #include <vector> #include <boost/utility/enable_if.hpp> #include <boost/type_traits/remove_const.hpp> #include <boost/type_traits/remove_pointer.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/mpl/logical.hpp> template <typename Target, typename Source, typename cond> struct uni_convert { }; template <typename Target, typename Source > struct uni_convert<Target,Source, typename boost::enable_if< boost::is_same<Target, Source>, int >::type > { static Target doit(Source const& src) { return src; } }; template <typename Cond > struct uni_convert<std::string,std::wstring, Cond > { static std::string doit(std::wstring const& src) { std::vector<char> space(src.size()*2, 0); wcstombs( &(*( space.begin() )), src.c_str(), src.size()*2 ); std::string result( &(*( space.begin() )) ); return result; } }; template <typename Cond > struct uni_convert<std::wstring,std::string, Cond > { static std::wstring doit(std::string const& src) { std::vector<wchar_t> space(src.size()*2, 0); mbstowcs( &(*( space.begin() )), src.c_str(), src.size()*2 ); std::wstring result( &(*( space.begin() )) ); return result; } }; template< typename TargetChar > std::basic_string< TargetChar > convert_str( std::string const& arg) { typedef std::basic_string< TargetChar > result_t; typedef uni_convert< result_t, std::string, int > convertor_t; return convertor_t::doit( arg ); }
doc_23529819
A: There is nothing magic about the Dispose method, it's just like any other method. Calling the Dispose method doesn't do any cleanup in the background or change the state of the object, it just does what you have put in the method. What is special about it is that it's defined in the IDisposable interface, so it's the standard way of telling an object to clean up it's resources. In the Dispose method the object should take care of all unmanaged resources, like database connections and Font objects. When you free an object you don't have to bother about any managed resources. A structure like a byte array is completely handled by the garbage collector, and you can just leave it in the object when you let it go. You don't need to set any references to null, when you don't use an object any more, the garbage collector will find the best time to remove it and any objects that it references. The garbage collector normally works best when you leave it alone, there is no need to tell it when it should collect unused object. It will figure out by itself when that should be done, and usually it does that better than you, as it has access to a lot of information about the state of the memory and the state of the machine that your code doesn't have. You might feel that you should try to keep the memory usage low, but there is no advantage of that in itself. A computer doesn't work better because it has more free memory left. On the contrary, if your code tries to do cleanup, or forces to garbage collector to do anyhting, it is doing the cleanup when it should be busy doing something more important. The garbage collector will clean up unused object if it's needed. A: An object is elligible for GC when it has no references held against it. If it has references held against it for a certain time period (managed by the garbage collector) it starts to get promoted through what are known as "generations". The Dispose method is simply a pattern (not a language-imposed object deletion mechanism) to say that the object can now clean up any unmanaged resources, close off any connections etc. The actions performed by the Dispose method are entirely controlled by the programmer, for all you know, it could be doing nothing. The garbage collector has no interest in the Dispose methods - but through the Finalizer, its likely that an object's Dispose logic will be called anyway - people following the IDisposable pattern implement the finalizer as a last ditch "you forgot to call Dispose so I'll do it just before the GC kills me" way to clean up resources. Note that any managed resources will eventually be GC'd (unless references are held) if Dispose is not called. However, unmanaged resources will only be reclaimed when your entire application process finishes (as well as any managed resources with references still held). A: Dispose normally frees unmanaged resources owned by the object. Calling Dispose doesn't trigger garbage collection; your object is collected when there are no longer any references to it, the same as if you'd never called Dispose. Setting an object reference to null just causes that reference to no longer point to that object; you shouldn't normally need to do this (for instance, you almost never need to set local variables to null). You almost never need to trigger garbage collection yourself, either. Are you seeing a problem that suggests that you need to run garbage collection every 5 minutes, instead of at the point when the runtime chooses to? A: Other folks here have sufficiently answered the "how does IDisposable interact with the garbage collector" and "when should I call GC.Collect" parts of the question. I have a blog post that goes into detail about when you should set variables to null to help the garbage collector (the third part of the question). The short answer is "almost never, unless it's a static variable." A: The point of automatic garbage collection is that you don't have to worry about freeing objects. Don't try to "help" the garbage collector. Objects are garbage collected eventually after they go out of scope. There is no way to "free" an object manually or mark it for faster garbage collection. Just keep in mind which objects are in scope (or referenced from objects in scope). The Dispose method is just a method. It does nothing related to garbage collection. "Dispose" happens to be the name of the method that is called by the using statement: using (var x = expr) { ... } is basically equivalent to var x = expr; try { ... } finally { x.Dispose(); } A: For your class objects you are defining what Dispose will do. You implement IDisposable interface which contains method Dispose and depends from implementation. But generally the purpose of Dispose is to release resources (managed/unmanaged) and make object as candidate for GC. Concerning setting null we can say it is useless. It just notes that there is no reference to the object thus it becomes candidate for GC, but again that there is no need for setting null as GC can find that there are no references to the object without that.. For calling Collect it is not suggested(until you have extreme need and arguments for that) as GC optimized to know what is the right time for Collection. A: Dispose, if implemented correctly, will dispose of any managed resources it has that implement IDisposable and immediately release any unmanaged resources. The object itself will be marked for collection when there are no references to it. Typically the object is used in a using block and the Dispose method is called at the end of the block automatically, with the object falling out of scope and being eligible for collection at that time. In the general case you are going to cause more problems than you solve by interacting directly with the garbage collector. If you feel that you must do this, it's more likely a signal that you need to refactor your solution -- i.e., you have too much coupling between your classes, resulting in object being kept alive longer than necessary. A cleaner architecture may result in better object lifetime management by the system. See MSDN for a discussion on how to implement the IDisposable pattern. A: The object is only marked for garbage collection, when Dispose() is called. <- Update: this is wrong. Dispose() doesn't really do anything, unless it is called either by you or by the compiler (when used in a 'using' construct). From MSDN - In most cases, the garbage collector can determine the best time to perform a collection and you should let it run independently. There are rare situations when a forced collection might improve your application’s performance. In these cases, you can induce garbage collection by using the Collect method to force a garbage collection See this article - http://msdn.microsoft.com/en-us/library/bb384155.aspx A: If you actually want to force a Garbage Collection use: GC.Collect(); Please see this post for reasons why you shouldn't use it: What's so wrong about using GC.Collect()?
doc_23529820
The problem I have is that when I finish downloading all the packages to my computer, I have to edit the path but Ubuntu doesn't recognize it. The lines are the following: PATH=/usr/local/texlive/2005/bin/i386-linux:$PATH export PATH I run echo $PATH and as long as I don't close the terminal, the path appears with the echoing, but if I close it, the path disappears. Nevertheless (whether I close the terminal or not), I'm supposed to run texhash but I am told that the command is not found. I already tried editing the path by adding the two lines above to both .bashrc in my home directory and to bash.bashrc in /etc/ directory. I'm just following the instructions linked above, but I'm a linux rookie. Could anyone help, please? A: in order to permanently change any environment variable under Ubuntu/Linux, you must modify the files you mentioned (for example ~/.profile). If you simply issue an export via the terminal, its effect will end once the terminal is closed. Sometime it is needed to perform a logout/login for the changes to take effect. Also, mind the syntax of what you write in the above mentioned file(s), like "'s around $PATH. Refer to this question: https://serverfault.com/questions/44275/how-to-add-a-directory-to-my-path-in-ubuntu
doc_23529821
In file included from /home/rtbkit/local/include/boost/tuple/tuple.hpp:33:0, from ./jml/boosting/tools/boosting_tool_common.h:16, from ./jml/boosting/tools/boosting_tool_common.cc:10: /home/rtbkit/local/include/boost/tuple/detail/tuple_basic.hpp: In function 'typename boost::tuples::access_traits<typename boost::tuples::element<N, boost::tuples::cons<HT, TT> >::type>::const_type boost::tuples::get(const boost::tuples::cons<HT, TT>&)': /home/rtbkit/local/include/boost/tuple/detail/tuple_basic.hpp:228:31: error: typedef 'cons_element' locally defined but not used [-Werror=unused-local-typedefs] typedef BOOST_DEDUCED_TYPENAME impl::type cons_element; ^ In file included from /home/rtbkit/local/include/boost/multi_array/concept_checks.hpp:21:0, from /home/rtbkit/local/include/boost/multi_array/base.hpp:28, from /home/rtbkit/local/include/boost/multi_array.hpp:21, from ./jml/boosting/classifier.h:20, from ./jml/boosting/tools/boosting_tool_common.cc:14: /home/rtbkit/local/include/boost/concept_check.hpp: In function 'void boost::function_requires (Model*)': /home/rtbkit/local/include/boost/concept_check.hpp:45:113: error: typedef 'boost_concept_check45' locally defined but not used [-Werror=unused-local-typedefs] BOOST_CONCEPT_ASSERT((Model)); ^ typedef typename Array::index_range index_range; ^ /home/rtbkit/local/include/boost/multi_array/concept_checks.hpp:43:37: error: typedef 'index' locally defined but not used [-Werror=unused-local-typedefs] typedef typename Array::index index; ^ /home/rtbkit/local/include/boost/multi_array/concept_checks.hpp: In static member function 'static void boost::multi_array_concepts::detail::idgen_helper<0ul>::call(Array&, const IdxGen&, Call_Type)': ^ In file included from /home/rtbkit/local/include/boost/regex/v4/regex.hpp:79:0, from /home/rtbkit/local/include/boost/regex.hpp:31, from ./jml/boosting/tools/boosting_tool_common.cc:18: /home/rtbkit/local/include/boost/regex/v4/regex_format.hpp: In member function 'OutputIter boost::re_detail::format_functor_c_string<charT, Match, Traits>::operator()(const Match&, , boost::regex_constants::match_flag_type, const Traits&)': /home/rtbkit/local/include/boost/regex/v4/regex_format.hpp:1086:41: error: typedef 'char_type' locally defined but not used [-Werror=unused-local-typedefs] typedef typename Match::char_type char_type; ^ In file included from /home/rtbkit/local/include/boost/regex/v4/regex.hpp:166:0, from /home/rtbkit/local/include/boost/regex.hpp:31, from ./jml/boosting/tools/boosting_tool_common.cc:18: /home/rtbkit/local/include/boost/regex/v4/regex_split.hpp: In function 'std::size_t boost::regex_split(OutputIterator, std::basic_string<charT, Traits1, Alloc1>&, const boost::basic_regex<charT, Traits2>&, boost::regex_constants::match_flag_type, std::size_t)': /home/rtbkit/local/include/boost/regex/v4/regex_split.hpp:110:57: error: typedef 'match_allocator' locally defined but not used [-Werror=unused-local-typedefs] typedef typename match_results<ci_t>::allocator_type match_allocator; ^ cc1plus: all warnings being treated as errors make: *** [build/x86_64/obj/jml/boosting/tools/boosting_tool_common.3ec7a8f7cea9a8b0de95729f9e9210cd.lo] Error 1 What is wrong with my libraries? I checked the version of gfortran is 4.8. A: This error happens when compiling rtbkit with GCC 4.8. Finally worked for me: nano /home/rtbkit/rtbkit/Makefile add compiler flag -Wno-unused-local-typedefs to CXXFLAGS CXXFLAGS += -Wno-unused-local-typedefs -Wno-deprecated ...
doc_23529822
RewriteEngine On RewriteBase / RewriteRule ^([\w-]+)\.html$ index.php?ID=$1 http://example.com/ipad.html but i have a problem when the the url ( id) Contains slashes for example id=1/4ABCD Which gives this url (http://example.com/1/4ABCD.html) Please how resolve this problem?
doc_23529823
So better do uniq = set() _ = [uniq.add('%s %s' % (k,hn)) for hn in v if '%s %s' % (k,hn) not in uniq ] Or better: uniq = set() _ = [uniq.add('%s %s' % (k,hn)) for hn in v] Is there an advantage choosing one approach over the other? A: There is no point in testing membership if all you are doing is adding values. You are doing extra work the .add() method already does for you. You should never use a list comprehension for the side effects; you created a list object full of None references, then discard it again. A simple for loop would have been far more efficient and better to understand and maintain. In this case, you don't need to call set.add() in a loop even, just use set.update() with a generator expresion: uniq = set() uniq.update('%s %s' % (k,hn) for hn in v) where uniq is presumably an existing set simplified down to an example. If not, you could use a set comprehension to create your set from scratch, using one line of code: uniq = {'%s %s' % (k,hn) for hn in v}
doc_23529824
When I try to add a Decodable extension I get an error extension UIColor : Decodable { public required init(from decoder: Decoder) throws { self.init(red: 1, green: 1, blue: 1, alpha: 1) } } error: ColorStuff.playground:98:21: error: initializer requirement 'init(from:)' can only be satisfied by a required initializer in the definition of non-final class 'UIColor' public required init(from decoder: Decoder) throws { Am I missing something obvious here? I have no issues with the Encodable extension - it seems its a Decodable issue. The error message implies to me that I cannot do this due to not having access to the UIColor class definition A: You cannot make UIColor conform to Decodable in an extension because of the error given by the compiler. One solution is to make a Codable wrapper type and use that instead. Since UIColor already conforms to NSCoding, let's just write a generic type so we can encode and decode anything that conforms to NSCoding. import UIKit struct WrapperOfNSCoding<Wrapped>: Codable where Wrapped: NSCoding { var wrapped: Wrapped init(_ wrapped: Wrapped) { self.wrapped = wrapped } init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let data = try container.decode(Data.self) guard let object = NSKeyedUnarchiver.unarchiveObject(with: data) else { throw DecodingError.dataCorruptedError(in: container, debugDescription: "failed to unarchive an object") } guard let wrapped = object as? Wrapped else { throw DecodingError.typeMismatch(Wrapped.self, DecodingError.Context(codingPath: container.codingPath, debugDescription: "unarchived object type was \(type(of: object))")) } self.wrapped = wrapped } func encode(to encoder: Encoder) throws { let data = NSKeyedArchiver.archivedData(withRootObject: wrapped) var container = try encoder.singleValueContainer() try container.encode(data) } } let colors = [UIColor.red, UIColor.brown] print(colors) let jsonData = try! JSONEncoder().encode(colors.map({ WrapperOfNSCoding($0) })) let colors2 = try! JSONDecoder().decode([WrapperOfNSCoding<UIColor>].self, from: jsonData).map({ $0.wrapped }) print(colors2) A: There is as way to make UIColor Codable despite that required init. You can extend Codable itself, so that UIColor starts conforming it automatically. import UIKit extension Decodable where Self: NSSecureCoding { public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let data = try container.decode(Data.self) guard let object = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? Self else { throw DecodingError.dataCorruptedError( in: container, debugDescription: "Invalid object" ) } self = object } } extension Encodable where Self: NSSecureCoding { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() let data = try NSKeyedArchiver.archivedData(withRootObject: self, requiringSecureCoding: true) try container.encode(data) } } extension UIColor: Codable { } Check it import XCTest class CodingTextCase: XCTestCase { let encoder = JSONEncoder() let decoder = JSONDecoder() func testUIColor() throws { let colorAsJSON = try encoder.encode(UIColor.red) print(String(data: colorAsJSON, encoding: .utf8)!) let uiColor = try? decoder.decode(UIColor.self, from: colorAsJSON) XCTAssertEqual(uiColor!, UIColor.red) } } CodingTextCase.defaultTestSuite.run() But please note that in this case data for instance of UIColor will take about 5 hundred bytes and storing it as RGBA can be more compact.
doc_23529825
I am working on a solution to obtain the rpo index of the Kafka cluster in the dual-center computer room. Use kafka-python to obtain the largest timestamp of the Kafka cluster, and take the difference between the maximum timestamps of the Kafka cluster in the two computer rooms. Use seek() to reset the offset to the maximum offset-1 of the partition, and then poll() to get the latest message, but the message can’t be gotten in the loop, check the offset of the current consumer group, and find that the message is stacked Is 0 #reset offset to (max_offset-1) for tp,offset in offsets_dict.items(): offset = offset - 1 if (offset)<0: effective_partition = effective_partition-1 continue consumer.seek(tp,offset) kafkaoffset = consumer.position(tp) if effective_partition==0: consumer.close() return max_timestamp try: Counter=0 while(True): message = consumer.poll(max_records=1) if not message: continue for partition, msgs in six.iteritems(message): for msg in msgs: max_timestamp = max(max_timestamp,int(msg.timestamp)) self.logger.debug(f"{max_timestamp}") Counter = Counter +1 if Counter == effective_partition: break except Exception as ex: raise ex finally: consumer.close() return max_timestamp A: If you commit after a seek, then that will be the new offset for the group, yes. enable_auto_commit defaults to True, and if you set that to False, there is a KafkaConsumer.commit(offsets) function that you can use to manually control this behaviour Calling .close() also defaults to do a commit, which you should probably leave alone unless you really only wanted to seek and read a handful of messages out-of-process with a normal linear consumer process
doc_23529826
Issue: I opened 2 tabs in my browser. If i type the first character example "a", nothing happens: Tab1 textarea: "a" tab2 textarea: NOTHING Then i proceed to type the second character "b" Tab1 textarea: "ab" tab2 textarea: "a" Conclude: Its always not updating the latest character i typed! SignalR Class public class DocHub : Hub { public void Update(String text) { this.Clients.Others.updateText(text); } } index.aspx <body> <form id="form1" runat="server"> <div style="font-size:50px;"> New Document</div> <textarea rows="4" cols="50" id="ta"></textarea> <script src="Scripts/jquery-1.10.2.js"></script> <script src="Scripts/jquery.signalR-2.1.2.js"></script> <script src="signalr/hubs"></script> <script type="text/javascript"> $(function () { var hubProxy = $.connection.docHub; hubProxy.client.updateText = function (msg) { $("#ta").val(msg); }; $("#ta").keydown(function () { hubProxy.server.update($("#ta").val()); }); $.connection.hub.start(); }); </script> </form> </body> A: I really would try to use keyup instead
doc_23529827
doc_23529828
Thanks Lee Tedstone. A: Lee, I am quite sure there is no such migration tool available at the moment (one that can translate Ingres stored procedures to adequate SQL server ones). Such tool is not trivial to do - one needs to code a language-to-language translator in order to accomplish this. However, there is a nice (Ingres) project called "Idiom" - http://community.ingres.com/wiki/Idiom - which can give you some clue how to write such translator. Idiom is used in the Ingres Migration ToolSet project - http://community.ingres.com/wiki/IngresMigrationToolSet - which successfully translates Oracle and MySQL procedures to Ingres.
doc_23529829
And while I have read a lot about these programming languages. Unfortunately, most tutorials spend most of their time talking about syntax. But I haven't found any tutorials that explains the domains or any turorials that give a typical practical application of these languages. I am stuck with a lot of questions, here follows a short list of simple questions that go on in my mind. Are they standalone languages? * *Are functional languages to be used from within another programming languages. The same way as Java/C# use other languages such as SQL, Regex, HQL, XQL, ... ? *If used standalone, do they use compilers ? How powerful are their frameworks ? * *Is there support for graphical components such as windows or dialogs ? *Is there support for multi-threading ? *Is there support for socket interaction, webservices ? Summary: Can somebody quickly answer the questions that I mentioned, or maybe even better, can you provide me some links to tutorials with practical examples ? Thank you in advance. EDIT: simplified/ removed some questions A: Are functional languages to be called from within another programming languages. The same way as Java/C# use other languages such as SQL, Regex, HQL, XQL, ... ? They can be, but needn't be limited to such a convention. Can a functional language use a framework like the java framework or .net framework ? If so, do these frameworks use graphical components such as windows or dialogs ? Yes - F# is a good example here. Can a functional language only be used for console applications and websites that simply echo output to some kind of stream ? No. Can a functional language be used standalone. If so, do they use compilers ? Yes, they can be standalone. Yes, they can use a compiler - these are just languages - the manner of execution is entirely up to the implementer. There are interpreters and compilers for many functional languages. I use java for multithreaded client-server applications with a front-end that acts as a desktop application (thick client). Could I replace all my java code by code written in a functional language? You can write mutlithreaded programs in functional languages, you can write desktop applications, and you can implement any arbitrary algorithm in one of these languages just like you have in Java. Are you trying to ask something more particular with this question? Are functional languages a subcategory of the procedural languages ? No. Is it just a matter of syntax or is there more to it ? More to it. I'd say that a functional language is one that encourages you to program in a functional style. This is far-afield of the focus of Stack Overflow. I suggest you see pre-existing material on the subject, such as the Haskell wiki.
doc_23529830
It's more of a jquery plugin. It works great on desktop and I even managed to add my custom controls on the ipad. So far so good. The problem is that I am creating and inserting dynamically the video element, fact that messes up the ipad a bit. I followed this approach because I found out (after a few long hours) that if you try to wrap ($.wrap) the video into a container, the video will crash. After inserting the video, it acts almost as normal (it is playable and responds to events), but it's position/display properties are messed up: I can't add any overlay on top of it. This is an issue, because I want my controls to be able to be displayed on top of the video. Moreover, the video itself does not respond to the normal touchmove touchstart touchend events. After some research, it turns out that if you do not have the default controls turned on, the video captures all the events (iPad touch events on <video> tag). My second problem is that after including the default controls, the video element still seems to ignore my event-handlers. So, my questions are (both only in Ipad cases): * *have you ever faced this problem, and of course if you did, how did you fix it? *do only hard-coded video elements trigger events? A: After some more digging I've found the answer. Looks like the unmarked answer in this stackoverflow question holds the key. So, as Jaffa The Cake (who I ow a bucket of thanks) sais : "You can fix z-index on dynamically created videos by giving the video element -webkit-transform-style: preserve-3d", the only workaround is to use the css3 property -webkit-transform-style: preserve-3d. This way, one can put an overlay on top of the video which can handle all the events (such as play/pause). A: No Ipad can handle dynamic inserted video by Jquery, on the Ipad videos do not respond to touch or move as by default you have to click on a link like play button to trigger the video audio so you can just use Jquery to do this like below video var vid = $('video').get(0); $('#someselector').click(function() { vid.play(); }); $('#someselector').click(function() { vid.stop(); }); audio var aud = $('audio').get(0); $('#someselector').click(function() { aud.play(); }); $('#someselector').click(function() { aud.stop(); }); Hope this helped. A: The solution for me was to remove the controls using jQuery for all videos like this $('video').each(function() { $(this).removeAttr("controls"); }); Then, the overlay elements also respond to the corresponding events. To make the video working again, I've added jquery click event that plays/pause the video: $('video').click(function() { $(this).trigger('play'); }); Hope that helps.
doc_23529831
==> view.php <script type="text/javascript"> $(document).ready(function(){ var html =""; html += "<tr id=" +id+ ">"; html += "<td>" +'<input type= "checkbox" name="update[]" value= "<?=" +id+ "?>"/>' + "</td>" ; }); $('input[name="update[]"]').click(function(){ alert("h2"); }); </script> A: Can you provide the whole code. Right the code is not provided completely. There are many parameter missing. Meanwhile You can also try to use on click method $('input[name="update[]"]').on("click", function(){ alert("h2"); }); A: Your input is added by JS. It means that this element wasn't in the DOM initially. You should try the following code: $(document).on('click', 'input[name="update[]"]', function(){ alert("h2"); });
doc_23529832
This is how I load Django: from tensorflow.keras.models import load_model model = load_model('test/models/test', compile=False) model.predict(padded) I read that compile=False might speed things up, but it doesn't. My Django app only uses the predict function as the model is simply handed to me and trained elsewhere. Simply importing tensorflow.keras.models is where it takes all the time. Why is this taking so long? Is importing tensorflow.keras.models slow? Can I do something to speed this up?
doc_23529833
so i try to build my first project which is backup tool but from many dir so the problem as always with me in windows path and backslash here is the code import os def list(): AO = True while AO: list_files = [] user_input = input("please put path of the file : ") list_files.append(user_input) so when i try to print the list i get path with double backslash so is there any way to get input as raw string
doc_23529834
When I open the data in QGIS they do appear on top of each other, so the coordinate systems do check out. Then I have an additional bonus question: I have to create multiple precipitation maps, on for a visual analysis it would be ideal if I could have the same legend (thus the same min/max for the colorbar) for each map. Anyone an idea how to proceed further? My code so far: def chirps_to_map(input1, input2, title): projection = input1 + input2 plt.figure(figsize=(9, 9)) projection['pr'].plot() watershed.plot() plt.title(title) plt.show() plt.close() projection.to_netcdf(str(path)+str(title)+".nc") return projection A: This is a case where it's simpler to use the Matplotlib object-oriented API. A nice general workflow might be fig, ax = plt.subplot() gdf.plot(ax=ax) # Plot the vector data on the subplot raster.plot(ax=ax) # Plot the raster data on the same subplot Example First, we get some sample raster+vector data import xarray as xr import geopandas as gpd import matplotlib.pyplot as plt da = xr.tutorial.load_dataset('ROMS_example').zeta.isel(ocean_time=0) gdf = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) usa = gdf.loc[gdf['name'].eq('United States of America')] Next, we plot both of the data on the same AxesSubplot fig, ax = plt.subplots(figsize=(15, 10)) da.plot.pcolormesh(x='lon_rho', y='lat_rho', ax=ax) usa.plot(ax=ax, edgecolor='red', color='none') # Focus on the raster extent ax.set_xlim(-95, -87) ax.set_ylim(26, 32) Bonus: hvPlot way hvPlot provides a nice unified API for interactive plotting with pandas, xarray, and many other libraries, and might be of interest to people stumbling upon this answer. Plotting both vector and raster data is rather easy, simply use the * operator. import hvplot.pandas import hvplot.xarray usa.hvplot(geo=True) * da.hvplot.quadmesh(x='lon_rho', y='lat_rho', geo=True)
doc_23529835
I must create a blob node now and i was wondering how to do it with a procedure like CR_BLOB_ELEMENT. Can someone give me a hint on how to do it ? Regards, Pierre PS : I'm using Oracle Database 11g Release 11.2.0.4.0 CR_BLOB_ELEMENT(l_domdoc in out dbms_xmldom.DOMDocument, ref_node in dbms_xmldom.DOMNode, nomel in varchar2, blobtobeadded in blob) procedure CR_ELEMENT(l_domdoc in out dbms_xmldom.DOMDocument, ref_node in dbms_xmldom.DOMNode, nomel in varchar2, vnomel in varchar2) as element dbms_xmldom.DOMElement; node dbms_xmldom.DOMNode; text dbms_xmldom.DOMText; textnode dbms_xmldom.DOMNode; begin element := dbms_xmldom.createElement(l_domdoc, nomel); node := dbms_xmldom.appendChild(ref_node, dbms_xmldom.makeNode(element)); text := dbms_xmldom.createTextNode(l_domdoc, vnomel); textnode := dbms_xmldom.appendChild(node, dbms_xmldom.makeNode(text)); end; A: If useful to someone. Please find below an answer given written by odie_63 in community.oracle.com. This is working perfectly. Regards, Pierre SQL> create table images ( 2 id integer 3 , name varchar2(256) 4 , content blob 5 ); Table created SQL> SQL> declare 2 3 bf bfile := bfilename('XML_DIR','base64.bin'); 4 lob_ptr blob; 5 dest_offs integer := 1; 6 src_offs integer := 1; 7 8 begin 9 10 insert into images (id, name, content) 11 values (1, 'Koala.jpg', empty_blob()) 12 returning content into lob_ptr; 13 14 dbms_lob.open(bf, dbms_lob.lob_readonly); 15 dbms_lob.loadblobfromfile(lob_ptr, bf, dbms_lob.getlength(bf), dest_offs, src_offs); 16 dbms_lob.close(bf); 17 18 end; 19 / PL/SQL procedure successfully completed SQL> commit; Commit complete SQL> SQL> select id 2 , name 3 , utl_raw.cast_to_varchar2(dbms_lob.substr(content, 30)) as first_bytes 4 , dbms_lob.getlength(content) as lob_size 5 from images 6 / ID NAME FIRST_BYTES LOB_SIZE ----- ------------ -------------------------------- ---------- 1 Koala.jpg /9j/4AAQSkZJRgABAgEAYABgAAD/7g 1068504 SQL> SQL> declare 2 3 x_doc xmltype; 4 domdoc dbms_xmldom.DOMDocument; 5 domnode dbms_xmldom.DOMNode; 6 domtext dbms_xmldom.DOMText; 7 ostream sys.utl_BinaryOutputStream; 8 chunksize pls_integer; 9 offset pls_integer := 1; 10 buf raw(32767); 11 image blob; 12 13 begin 14 15 select xmlelement("image", 16 xmlelement("id", t.id) 17 , xmlelement("name", t.name) 18 , xmlelement("content") 19 ) 20 , t.content 21 into x_doc 22 , image 23 from images t 24 where t.id = 1 ; 25 26 domdoc := dbms_xmldom.newDOMDocument(x_doc); 27 28 -- get /image/content node so that we can append a text node and stream the BLOB to it : 29 domnode := dbms_xslprocessor.selectSingleNode(dbms_xmldom.makeNode(domdoc), '/image/content'); 30 domtext := dbms_xmldom.createTextNode(domdoc, null); 31 domnode := dbms_xmldom.appendChild(domnode, dbms_xmldom.makeNode(domtext)); 32 33 ostream := DBMS_XMLDOM.setNodeValueAsBinaryStream(domnode); 34 chunksize := dbms_lob.getchunksize(image); 35 36 loop 37 begin 38 -- read BLOB in chunk of <chunksize> : 39 dbms_lob.read(image, chunksize, offset, buf); 40 exception 41 when no_data_found then 42 exit; 43 end; 44 -- write chunk to DOM node : 45 ostream.write(buf, chunksize); 46 offset := offset + chunksize; 47 end loop; 48 49 ostream.flush(); 50 ostream.close(); 51 52 dbms_xmldom.writeToFile(domdoc, 'XML_DIR/image.xml'); 53 dbms_xmldom.freeDocument(domdoc); 54 55 end; 56 / PL/SQL procedure successfully completed Output in image.xml : <image> <id>1</id> <name>Koala.jpg</name> <content>/9j/4AAQSkZJRgABAgEAYABgAAD/7gAOQWRvYmUAZAAAAAAB/+EUI0V4aWYAAE1NACoAAAAIAAcB MgACAAAAFAAAAGIBOwACAAAABwAAAHZHRgADAAAAAQAEAABHSQADAAAAAQA/AACcnQABAAAADgAA AADqHAAHAAAH9AAAAACHaQAEAAAAAQAAAH0AAADnMjAwOTowMzoxMiAxMzo0ODoyOABDb3JiaXMA ... aWpkRY6dqaJY42qFjs8ZZ5nlkjZpmJUiJ1+ijn3dVeTtb4B1R5NJVaEkn/V8+u4Xijpp6SFlimp6 qNHgjlVIgrtLCyxll1NpaT6An6W92mA8HwkyadMeEZJjEDmvE/t/1f5uv//Z</content> </image>
doc_23529836
GoogleCredential gc = GoogleCredential.FromFile(bq_json_path); BigQueryClient bq_client = BigQueryClient.Create(bq_project_id, gc); string query = "SELECT " + columns2select + " FROM " + project_dataset_table + ";"; BigQueryResults bqr = bq_client.ExecuteQuery(query, parameters: null); IEnumerator<BigQueryRow> itr = bqr.GetEnumerator(); while(itr.MoveNext()) { //do something (even if I comment it and do nothing, it save only 2 seconds) } That way it process 100k rows for 26 seconds. That's ultimate slow. I tried using bqr.ReadPage(100000);, but it also took ~26 seconds to retrieve the rows just by that call. I doing the program to transfer data from BigQuery into ClickHouse for DataLens analysis purpose. And 100k rows insertion into cloud hosted ClickHouse (not on my local PC) takes just 1-2 seconds. That's weird imbalance. I think selecting rows should be way more faster. P.S. 100k rows per 26 seconds is not a problem... The problem is that I need to transfer many tables with ~60 millions records and some tables can have even 1 billion of records.
doc_23529837
I guess I have to use the following but I can't make it. grid.getEditor().isOpen(); grid.getEditor().getItem() Can you help me? A: You could look up the item in your grid's collection: grid.getEditor().addOpenListener(event -> { System.out.println("Opened editor on item " + myItems.indexOf(event.getItem())); }); Although the 'index' will be the index in that collection rather than the index in the displayed grid, which is influenced by the sort order and filtering. I believe that not exposing an index on the EditorOpenEvent is intentional, as the concept of an index is presentation specific and abstracted away from the server-side initialization of the grid. If you really needed to get to the index of the row in the current grid presentation (which respects sort order), you could make a Javascript call. Given this isn't part of the documented API, it's likely subject to change. PendingJavaScriptResult pendingJavaScriptResult = grid.getElement().executeJs("return this._focusedItemIndex"); pendingJavaScriptResult.then(jsonValue -> { System.out.println("From JS:" + jsonValue.asNumber()); });
doc_23529838
<div class="holder"> <h2 *ngIf="!this.userHomeService.cards"> You haven't created any cards. </h2> <div class="card-div" *ngFor="let c of this.userHomeService.cards"> <h3 (click)="onSelect(c)">{{c.title}}</h3> </div> A: You didn't post your controller, but I can guess what it contains. * *this.userHomeService.cards is undefined or null. So !this.userHomeService.cards is true, and "You haven't created any cards." is displayed on the page. The ngFor doesn't display anything, since there is nothing to iterate on. *A response to some asynchronous request, probably a HTTP request, comes back, and it's an empty array. So the ngFor still doesn't display anything, since the array is empty, but !this.userHomeService.cards becomes false, and the message disappears from the page. A: You have to add *ngIf="this.userHomeService.cards" for the second div to avoid any errors for undefined value. <div *ngIf="this.userHomeService.cards"> <div class="card-div" *ngFor="let c of this.userHomeService.cards"> <h3 (click)="onSelect(c)">{{c.title}}</h3> </div> </div> To avoid displaying You haven't created any cards. message initially on the page (wile fetching data) you have to have some kind of flag indicating that you data is still loading from server. For example: <h2 *ngIf="this.finished && !this.userHomeService.cards"> You haven't created any cards. </h2> And add finished variable to your controller and set it to true when your http request is finished. So this message will be shown only when you data fetching is finished. (this is one of possible solutions of your problem, the simplest one I suppose)
doc_23529839
rescue Exceptions::LogoNotCroppable => ex logger.error "Logo was not croppable LogoID: #{self.id}. Exception message: #{ex.message}" ex.backtrace.each { |line| logger.debug line } # Send email with notification that something did not go as expected ExceptionNotifier.notify_exception(ex) But how would I do it, if I want to pass something extra to that notification? For, example if I want to pass the self.id of the object that created the exception? A: Using the data hash: ExceptionNotifier.notify_exception(ex, :data => {:object_id => self.id})
doc_23529840
I have a jQuery tab table set up with four tabs, like so: <ul class="tabs"> <li> <a rel="tab_1">Education Insurance</a> </li> <li> <a rel="tab_2">Home Insurance</a> </li> <li> <a rel="tab_3">Car Insurance</a> </li> <li> <a rel="tab_4">Business Insurance</a> </li> </ul> The content for each tab is in a separate div tag below it, like so: <div class="panes"> <div id="tab_1" class="tab-content"> <p>Tab content goes here.</p> </div> What I'm trying to do is create a link on the homepage that can link directly to tab 2 or tab 3, which are on a separate page. Can anyone help with this? A: You can use jQuery UI tabs, thats does that automatically. Here is a Working Fiddle Tab Links First tab Second tab Third Tab Reference: JQuery UI tabs Even better you can change the hash on select so that users can copy the url themselves like this $('#tabs').tabs({ select: function(event, ui) { window.location.hash = ui.tab.hash; } }); ​ A: It's in the documentation :) quite a simple snippet, I've used it myself. var $tabs = $('#example').tabs(); // first tab selected $('#my-text-link').click(function() { // bind click event to link $tabs.tabs('select', 2); // switch to third tab return false; }); If you want to do it "on load" of the page (i.e. the link on the homepage takes you to a different tabbed screen) you'd just want to pass something across in the request that the document load can decypher and use the .tabs("select", tabNo) as shown above. Again, I've done this in production code and it's reliable. A: I am assuming that all the content divs are visible and you need to scroll to that particular div when the user clicks on it. You just need to bind the button to a scroll event. $(document).ready(function() { $('button2').click = function (){ $(document).scrollTo('#tab2'); } }); $(document).ready(function() { $('button3').click = function (){ $(document).scrollTo('#tab3'); } }); Now create two buttons with id 'button1' and 'button2'. For example. <div id='button2'>Tab2</div> or <a href='#' id='button2'>Tab2</a> When the user clicks on them he is taken to the content div.
doc_23529841
So I discovered for myself Metal Performance Shaders framework. Description of that framework got me psyched, because I can find fine-tuned and optimized kernel shaders for math operations my GPU algorithm does. I decided to first use MPSMatrixVectorMultiplication because I have a big multiplication of 11000x500 matrix on 11000 vector with the output of 500 vector. So that's how I'm using it. Declare MPS wrappers for MTLBuffers and the operation itself: MPSMatrix *model; MPSVector *vector; id<MTLBuffer> resultBuffer; MPSVector *resultVector; MPSMatrixVectorMultiplication *matrixVectorMultiplication; Init those MPS wrappers: matrixVectorMultiplication = [[MPSMatrixVectorMultiplication alloc] initWithDevice:_ctx.device transpose:true rows:500 columns:11000 alpha:1 beta:0]; //......// MPSVectorDescriptor *desc = [MPSVectorDescriptor vectorDescriptorWithLength:11000 dataType:MPSDataTypeFloat32]; vector = [[MPSVector alloc] initWithBuffer:vecBuffer descriptor:desc]; MPSVectorDescriptor *desc_out = [MPSVectorDescriptor vectorDescriptorWithLength:500 dataType:MPSDataTypeFloat32]; resultVector = [[MPSVector alloc] initWithBuffer:resultBuffer descriptor:desc_out]; //......// MPSMatrixDescriptor *desc = [MPSMatrixDescriptor matrixDescriptorWithRows:11000 columns:500 rowBytes:500 * sizeof(float) dataType:MPSDataTypeFloat32]; //I need to transpose the matrix model = [[MPSMatrix alloc] initWithBuffer:testBuffer descriptor:desc]; And do the multiplication: id<MTLCommandBuffer> cmdBuffer = [_ctx.commandQueue commandBuffer]; id<MTLComputeCommandEncoder> encoder = [cmdBuffer computeCommandEncoder]; // work with my own encoder, execute some commands [encoder endEncoding]; [matrixVectorMultiplication encodeToCommandBuffer:cmdBuffer inputMatrix:model inputVector:vector resultVector:resultVector]; [cmdBuffer commit]; [cmdBuffer waitUntilCompleted]; // I have to wait because my algorithm is sequential at this point Now, the kernel function I wrote does exact same multiplication in around 0.8-1.1 ms. And I was very sad to find out that MPSMatrixVectorMultiplication did it in 18-19 ms! That is waaaay too slow and I can not believe in such result. Clearly, I'm missing some tiny detail which steals so much of the performance. Is there anyone who used MPS solutions in performance-sensitive code? I would be happy to hear some tips which I can apply in my GPU routine. Thanks in advance! A: There are additional things you need to do: * *pad the matrices with zeroes so their sizes are divisible by 8 *on MacOS (not available on iOS) use managed memory buffer See these links for more details: * *Minimum matrix sizes to benefit from matrix multiplication on GPU *https://developer.apple.com/forums/thread/105534 Since the memory is shared on iOS you might not get the same speedup, but it should be much faster with the right matrix sizes!
doc_23529842
/server/frontend/wsn.py Line 866: netid = hextransform(int(nid), 16) Line 156: def hextransform(data, length): data = hex(data)[2:] assert(len(data) <= length) # zero-padding data = ('0' * (length - len(data))) + data # Swap 'bytes' in the network ID data = list(data) for i in range(0, length, 2): tmp = data[i] data[i] = data[i + 1] data[i + 1] = tmp # Reverse the whole string (TODO: CHECK) data.reverse() #data = "".join(data) return data My problem is when I have a nid = 15579202759033880576 for example. Is it too long? The error I receive from Tornado is this: Traceback (most recent call last): File "/usr/lib/python2.6/site-packages/tornado/web.py", line 988, in _execute getattr(self, self.request.method.lower())(*args, **kwargs) File "/usr/lib/python2.6/site-packages/tornado/web.py", line 1739, in wrapper return method(self, *args, **kwargs) File "./wsn.py", line 866, in get netid = hextransform(int(nid), 16) File "./wsn.py", line 158, in hextransform assert(len(data) <= length) AssertionError But netid in hex is 0xd834725e00000000 and len(nid) = 16. I don't know what the problem is. A: Python adds a L for long numbers: >>> hex(int(15579202759033880576)) '0xd834725e00000000L' adding one more character. Use a different method to create a hex number: format(data, '016x') instead. The format() function lets you use the format spec mini language to transform your data; x is a lower-cased hex representation in this case, and you don't need to slice anything: >>> format(15579202759033880576, '016x') 'd834725e00000000' Note the 016 in the format there; if your number is smaller than 16 hex digits, it'll be padded with zeros for you: >>> format(1557920, '016x') '000000000017c5a0' Your byte swapping can be done more easily too; python supports multiple assignments letting you swap two values without the need for a temporary variable: for i in range(0, length, 2): data[i], data[i + 1] = data[i + 1], data[i] Thus, your hextransform method can be simplified to: def hextransform(data, length): data = format(data, '0{0}x'.format(length)) assert(len(data) == length), '{0!r}, {1}'.format(data, length) # Swap 'bytes' in the network ID data = list(data) for i in range(0, length, 2): data[i], data[i + 1] = data[i + 1], data[i] data.reverse() return data resulting in: >>> hextransform(15579202759033880576, 16) ['0', '0', '0', '0', '0', '0', '0', '0', '5', 'e', '7', '2', '3', '4', 'd', '8'] A: The 'L' from the hex(int(num)) is your problem: >>> hex(int(15579202759033880576))[2:] 'd834725e00000000L' <-- 17 with the L The quickest fix for this is just to update your substring chop to get rid of that L as well: data = hex(data)[2:].split('L')[0] This will split your string around the L (if present) and give you the hex part. It's safe since 'L' isn't a hex character so it will only show up if you have a long string.
doc_23529843
string nextEvent = "[[\"nextData\", \"RANDOM MESSAGE\"], [\"moreInfo\", {\"num\": 3204}]]" I need to get "RANDOM MESSAGE" (without the quotes) into a seperate string. Now, it would be easy if RANDOM MESSAGE was a constant, but it's not. Let's say that it's generated through user input, and is different in value and length every time. How would I go about extracting that message from there? I've tried using Substring with IndexOf, but I got wrong results every time, it's quite confusing. A: You can use regex to get it: string input = "[[\\\"nextData\\\", \\\"RANDOM MESSAGE\\\"], [\\\"moreInfo\\\", {\\\"num\\\": 3204}]]"; string pattern = "^\\[\\[\\\\\"nextData\\\\\",\\s*\\\\\"(?<message>[\\S ]+)\\\\\"\\],\\s*\\[\\\\\"moreInfo\\\\\",\\s*\\{\\\\\"num\\\\\":\\s*\\d+\\}\\]\\]$"; Regex r1 = new Regex(pattern); Match match = r1.Match(input); if (match.Success) Console.WriteLine(match.Groups["message"].Value); A: If you'd like a 'brute force' method: String nextEvent = "[[\"nextData\", \"RANDOM MESSAGE\"], [\"moreInfo\", {\"num\": 3204}]]"; String tmp = nextEvent.Trim(new Char[] { '[', ']' }); String[] sa = tmp.Split(','); String rndMsg = sa[1].Trim().Trim(new Char[] { '[', ']', '\"' }); A: you can use simple splits like this: string nextEvent = "[[\"nextData\", \"RANDOM MESSAGE\"], [\"moreInfo\", {\"num\": 3204}]]"; var strs = nextEvent.Split(']'); var ds = strs[0].Split(','); var m = ds[1].TrimStart('"', ' '); m = m.TrimEnd('"'); A: The third possible solution, although not very performing is this: Take you string and parse it as a Dictionary: String nextEvent="[[\"nextData\",\"RANDOM MESSAGE\"],[\"moreInfo\",{\"num:\": 3204}]]"; Dictionary<string, object> dict = JSON.Parse<Dictionary<string,object>>(nextEvent); String randomMessage = dict("nextData"); this becomes relevant, when you have a very long string in this format and have to extract multiple "fields" from it A: If the strings before/after are constant you can get the random message part simply by doing: int startIndex = ("[[\"nextData\", \"").Length; int endIndex = nextEvent.IndexOf(", [\"moreInfo\""); string randomMessage = nextEvent.Substring(startIndex, endIndex - startIndex ); You might also use Split to get a string starting from the target area: string[] temp = nextEvent.Split(new string[] { "[[\"nextData\", \"" }, StringSplitOptions.None); //temp[1] = "RANDOM MESSAGE..." A: Using JSON.NET using Newtonsoft.Json; using Newtonsoft.Json.Linq; class Test { static void Main() { string nextEvent = "[[\"nextData\", \"RANDOM MESSAGE\"], [\"moreInfo\", {\"num\": 3204}]]"; JObject json = JObject.Parse("{\"j\":" + nextEvent + "}"); string randomMessage = (string)json["j"][0][1]; Console.WriteLine(randomMessage); // gives "RANDOM MESSAGE" } }
doc_23529844
My question is in this line of code ** if ( ( zipcode.getText().toString().trim().equals("33314"))) ** How do i list multiple values such as, 33314,33328,33354 as i cannot separate by commas. This is my Code... zipbtn= (Button)findViewById(R.id.zipbtn); zipbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { insertValues(); EditText zipcode = (EditText) findViewById(R.id.zipcode); if ( ( zipcode.getText().toString().trim().equals("33314"))) { Intent secondpage = new Intent(MainActivity.this,Activity2.class); startActivity(secondpage); } else { { Toast.makeText(getApplicationContext(), "User name is empty", Toast.LENGTH_SHORT).show(); A: Put the allowed String values in an HashSet like: HashSet<String> values = new HashSet<>(); values.add("11111"); values.add("22222"); and then check with if (values.contains(zipcode.getText().toString().trim()))
doc_23529845
Everything works correctly however the query is getting all posts under development instead of only child pages under the currently viewed development. I've tried using WP_Query however that bugs out when run in the backend. function data_feed() { $i = 0; $map_builder = array(); $args = array( 'post_type'=> 'developments', 'child_of' => $post->ID, ); $the_query = get_pages($args); foreach ( $the_query as $post_f ) : setup_postdata( $post ); if($i == 0){ $lat = 50; $long = 50; } else { $lat = ''; $long = ''; } $map_builder[$i] = array( 'title' => get_the_title($post->ID), 'excerpt' => get_the_excerpt($post->ID), 'price' => '9999999', 'status' => 'available', 'coords' => array( 'lat' => $lat, 'long' => $long ) ); $i++; endforeach; wp_reset_postdata(); $jqa = array('map-pin'=> $map_builder + array( 'canvas' => array( 'src' => 'http://localhost/acf-property-manager-app/wp-content/uploads/2018/12/the-avenues-site-plan-new.png', 'width'=> 1000, 'height' => 562 ))); return json_encode( $jqa ); } Right now it returns all posts under developments. What it should return is only the child posts of the currently viewed development. A: Adding :- global $post; Passes the correct ID to the query and results are now correct!
doc_23529846
import sqlite3 class database: def __init__(self, name): self.name = name def connect(name): db = sqlite3.connect("%s.db" % self.name) c = db.cursor() def test(self): print (3) If I run database('name').test(), I get 3, so that works. But if I try database('name').connect(), I get, "NameError: name 'sqlite3' is not defined" Classes are relatively new to me and I'm still trying to figure out how they work. Thanks much for any help. EDIT: See the comments in the answer the the solution. The problem seems to be that I was importing sqlite3 in both the file and the notebook. The solution was to import the module only in the file. A: You may have a typo somewhere in your description, because I think you would get another error first when doing data = database() data.test() data.connect('name') You need to add the self to the connect def to make it a proper class method. There's also a typo in the connect call. The following should work import sqlite3 class database: def __init__(self, name): self.name = name def connect(self): db = sqlite3.connect("%s.db" % self.name) c = db.cursor() def test(self): print(3) then do data = database('test') data.connect()
doc_23529847
doc_23529848
I have dragover and drop addEventListeners, but for some reason I can't get the image data to preview in the "prev-img" div. Any help would be apriciated. function multiUploader(config){ this.config = config; this.items = ""; this.all = [] var self = this; multiUploader.prototype._init = function(){ if (window.File && window.FileReader && window.FileList && window.Blob) { var inputId = $("#"+this.config.form).find("input[type='file']").eq(0).attr("id"); document.getElementById(inputId).addEventListener("change", this._read, false); document.getElementById(this.config.dragArea).addEventListener("dragover", function(e){ e.stopPropagation(); e.preventDefault(); }, false); document.getElementById(this.config.dragArea).addEventListener("drop", this._dropFiles, false); document.getElementById(this.config.form).addEventListener("submit", this._submit, false); } else console.log("Browser supports failed"); } multiUploader.prototype._submit = function(e){ e.stopPropagation(); e.preventDefault(); self._startUpload(); } multiUploader.prototype._preview = function(data){ this.items = data; if(this.items.length > 0){ var html = ""; var uId = ""; for(var i = 0; i<this.items.length; i++){ uId = this.items[i].name._unique(); let iMg = this.items[i]; // This is where I thought I'd be able to preview var sampleIcon = '<img src="images/image.png" />'; var errorClass = ""; if(typeof this.items[i] != undefined){ if(self._validate(this.items[i].type) <= 0) { sampleIcon = '<img src="images/unknown.png" />'; errorClass =" invalid"; } html += '<div class="dfiles'+errorClass+'" rel="'+uId+'"><div class="prev-img"><img src='+iMg+' /></div><button onclick="closeprev(this);" type="button" class="close">×</button><h5>'+sampleIcon+this.items[i].name+'</h5><div id="'+uId+'" class="progress" style="display:none;"><img src="images/ajax-loader.gif" /></div></div>'; } } $("#dragAndDropFiles").append(html); } } multiUploader.prototype._read = function(evt){ if(evt.target.files){ self._preview(evt.target.files); self.all.push(evt.target.files); } else console.log("Failed file reading"); } multiUploader.prototype._validate = function(format){ var arr = this.config.support.split(","); return arr.indexOf(format); } multiUploader.prototype._dropFiles = function(e){ e.stopPropagation(); e.preventDefault(); self._preview(e.dataTransfer.files); self.all.push(e.dataTransfer.files); }
doc_23529849
var styles = { ... } export default class App extends React.Component { ... render() { return( <View style={styles.container}> <View style={{width: this.state.widthA}} /> <View style={{width: this.state.widthB}} /> </View> ); } } when the state widthA changes, the render() function is called again. Will the sibling View (widthB) also re-render? Would there be any performance boost to define class PureView extends React.PureComponent { constructor(props) { super(props); } render() { return <View {...this.props} /> } } and replace both Views with PureView? A: Actually yes re-render will occur because re-render in react belongs to two things. 1. The props of the parent is changed. 2. The state of a component changed. So in your case state of a component is changing that's why your sibling will also re-render because the state of the parent of these two siblings is been changed. To avoid this, There are two doing this. 1. Use Pure component Pure component looked at previous state and next state and handle your re-render smartly but the pure component is not applicable or useful in every case. 2. ShouldComponentUpdate This method is used for handling re-renders manually like as in your case you don't want to re-render your second sibling so you can return false according to your prop in the lifecycle method of your sibling so this component will not re-render by this change. The View is just a UI container re-rendering depends on component props or state, So View can't control the re-render of a component.
doc_23529850
$(document).ready(function () { $("[name='my-checkbox']" ).bootstrapSwitch({ onText: "Yes", offText: "No", onColor: "success", offColor: "danger", animate: false, onSwitchChange: function (event, state) { $ajax({ url: '/ProposalWork/ChangeActivityStatus/', data: { id: @ViewBag.Activity.id, state: state } }).done(function () { alert('Status Changed'); }); } }); }); A: You missed a . in your ajax call. $.ajax({ })
doc_23529851
In SQL select * from house where door< 2 or room=>2 In firebase How I do it? A: You can't do this type of query with Firebase realtime database, but you can do it with Firestore. Check this doc to know how to query your data. // Create a reference to door collection CollectionReference home = db.collection("home"); // Create a query against the collection. Query query = home.whereLessThan("door", 2); And you can do the same with rooms, but you can't use the same query to query the two things together. For all query examples, check this.
doc_23529852
1 finger touches the screen and I use the event.getX()/Y() to get its cords. Another finger touches the screen and I'm still getting the X/Y of the first finger. Now the first finger is removed from the screen, however the second finger has yet to move and so it doesn't trigger the ACTION_MOVE and I can't get the event.getX()/Y() yet. I want to know, how can I make it so even if the second finger hasn't moved yet how I can get it's X and Y as soon as the first finger releases from the screen. As of right now I'm having my character move towards the finger, and I have found it is quite common for this to happen and when it does the character continues to move towards the location of where the first finger left off until you move your finger slightly. It happens enough to make it a problem, especially for what I'm trying to do. A: MotionEvent has more details for the second finger. Do review the documentation. look at the values in event.getX(1) and event.getY(1) methods. A: I had the same problem when I was retrieving the position touched like this: CGPoint touchLocation = CGPoint.make(event.getX(), event.getY(); Fixed it by using: CGPoint touchLocation = CGPoint.make(event.getX(event.getPointerCount()-1), event.getY(event.getPointerCount()-1));
doc_23529853
I tried to click on button by mouse movement but no success my outer html is as below : <button class="btn btn-alt btn-small" type="button" ng-click="ecdapp.uploadBlueprintModalPopup();"> Create </button> button xpath is: //*[@id="page-content"]/div[3]/button A: Not seeing the full page source it's hard to tell where your XPath expression is good or not, you can try locating the button using its text instead //button[normalize-space(text())='Create'] the normalize-space() function is used to discard heading/trailing whitespaces It might also be the case the button is not immediately available, I would recommend considering using Explicit Wait approach via WebDriverWait class WebElement myButton = new WebDriverWait(driver, 10) .until(ExpectedConditions .elementToBeClickable(By.xpath("//button[normalize-space(text())='Create']"))); myButton.click(); the above code will try to locate the aforementioned button for 10 seconds and click it as soon as it will be present/visible/clickable. Otherwise it will fail with NoSuchElementException A: May be the Xpath is wrong. Try the below xpath: //button[contains(text(),'Create')] A: As you can see on the screenshot this Xpath 100% works, if you still won't be able to click on that button, then problem is not with xpath. Let me know if its still fails. By.xpath("//button[@class = 'btn btn-alt btn-small' and @type = 'button']") Based on your comment: I tried this code , but unable to click . element click intercepted: Element ... is not clickable at point (293, 97). Other element would receive the click: ... (Session info: chrome=74.0.3729.169) I pretty sure I know whats your problem, before u click on this element, something going on the page: It says - Other element would receive the click, means there is other element above(overlapping) your button(pop up window, page is greyed out(disabled while loading, Some JS running)), so when Selenium trying to click on your button its actually clicking on that blocking element. Try to click after Thread.Sleep(); wait 5-10 sec. If this is the case then u need to add condition before find your button to check that element that prevent from clicking on button is disappeared then u click on it. A: Try JavaScript executors as below, WebElement element = driver.findElement(By.xpath("<xpath of button>")); JavascriptExecutor js= (JavascriptExecutor) driver; js.executeScript("arguments[0].click();", element);
doc_23529854
Anyone can help? A: It doesnt seem the OneDrive connector offers a delete folder option. You would need to build something custom to achieve this.
doc_23529855
I accept suggestions Thank you A: You can use vaderSentiment which is a python package to perform unsupervised English Sentiment Analysis using dictionary and rules. There is some example on their github. This option might be more effective than an unsupervised clustering.
doc_23529856
The csv will not need header, the content in the array will print in column by column. I'm facing problem to make the mapping through the nested array. Input payload [ { "Invoice": { "Invoice Number*": "Test", "Supplier Number": "1201", "Submit For Approval?": "Yes", "Invoice Date*": "20190828", "Line Level Taxation*": "Yes", "Payment Date": "00/00/0000", "Original invoice number": "", "Original invoice date": "" }, "Invoice Line": [ { "Invoice Number*": "Test1", "Line Number": "1", "Description*": "Test1", "Price*": "500", "Quantity": null, "Unit of Measure*": null, "PO Number": "001", "PO Line Number": "1" }, { "Invoice Number*": "Test2", "Line Number": "2", "Description*": "Test2", "Price*": "500", "Quantity": null, "Unit of Measure*": null, "PO Number": "001", "PO Line Number": "2" } ], "Invoice Tax Line": [ { "Tax Amount": "500", "Invoice Line Number": "1", "Line Number": "1" }, { "Tax Amount": "50", "Invoice Line Number": "2", "Line Number": "2" } ] } ] Expected Output column_0, column_1, column_2 ... //no header "Invoice Number*","Supplier Number","Submit For Approval?"... //Invoice "Invoice Number*","Line Number*"... //InvoiceLine[0] "Tax Amount","Invoice Line Number","Line Number"... //Tax Line[0] "Invoice Number*","Line Number*"... //InvoiceLine[1] "Tax Amount","Invoice Line Number","Line Number"... //Tax Line[1] How can i write the dataweave mapping to archive the result like above? A: This is the solution I found for your use case. Basically there are two functions to that dispatches on the right method according to the type. And then you also want to use zip function to mix one "Invoice Line" with one "Invoice Tax Line" so they are mixed correctly. %dw 2.0 output application/csv headers=false import * from dw::core::Objects fun collectKeyNames(obj: {}): Array<{}> = [ obj ] fun collectKeyNames(arr: Array): Array<{}> = arr flatMap ((obj, index) -> collectKeyNames(obj)) --- payload flatMap ((item, index) -> collectKeyNames(item.Invoice) ++ (collectKeyNames(item."Invoice Line" zip item."Invoice Tax Line")) )
doc_23529857
private void Search_OnTyping(object sender, System.Windows.Input.KeyEventArgs e) { if (ObjectToSearch is FrameworkElement fe) { foreach (var control in fe.ChildrenOfType<TextBlock>()) { if (control.Text.IndexOf(TextBoxSearch.Text, StringComparison.OrdinalIgnoreCase) >= 0 || string.IsNullOrWhiteSpace(TextBoxSearch.Text)) { control.Background = Brushes.Yellow; } } } } I'm checking if it's a FrameworkElement because I want to be able to go through the Grid, StackPanel etc. But I want to color only the exact text and not the entire TextBlock that contains the text. I would appreciate help on how to do this and if there is a better way to do it
doc_23529858
So far, I created an application with a login button, that's all. However, I would like to know what kind of things I am doing wrong or should be doing different (or better). I am using Adobe Flex Builder 3. The main actionscript file is Client2.as: package { //import required libraries import flash.display.Sprite; //set project properties [SWF(width="800", height="600", frameRate="31", backgroundColor="#C0C0C0")] //launch main class public class Client2 extends Sprite { public function Client2() { //the constructor trace("Client launched."); var loginGui:LoginInterface = new LoginInterface(); //load the login interface object loginGui.init(); //initialize the login interface (load it) addChild(loginGui); //add login gui to the display tree } } } It is loading the login interface object. Is that a good thing, and am I doing it the right way? Then there's the LoginInterface.as class file: package { //import required libraries import flash.display.Sprite; //the LoginInterface class public class LoginInterface extends Sprite { public function LoginInterface() //the constructor { trace("LoginInterface object loaded."); } public function init():void //initialize the login interface (load it) { trace("LoginInterface init method was called."); var loginButton:CustomButton = new CustomButton(300, 300, 100, 30, 3, 18, "Login!"); //create a new custom button addChild(loginButton); //add the custom button to the display tree } } } What about that? Any comments? To make the creation of simple buttons a bit easier, I then created another class file called CustomButton.as --> package { import flash.display.SimpleButton; import flash.display.Sprite; import flash.text.TextField; import flash.text.TextFormat; import flash.text.TextFormatAlign; public class CustomButton extends Sprite { public function CustomButton(xLoc:int, yLoc:int, width:int, height:int, iLabelOffset:int, fontsize:uint, label:String) { //create new simple button instance var myButton:SimpleButton = new SimpleButton(); //create the look of the states var normal:Sprite = new Sprite(); normal.graphics.lineStyle(1, 0x000000); normal.graphics.beginFill(0x6D7B8D); normal.graphics.drawRect(xLoc, yLoc, width, height); //the mouseover sprite var over:Sprite = new Sprite(); over.graphics.lineStyle(1, 0x000000); over.graphics.beginFill(0x616D7E); over.graphics.drawRect(xLoc, yLoc, width, height); // assign the sprites myButton.upState = normal; myButton.downState = normal; myButton.hitTestState = normal; myButton.overState = over; //add the button to the display tree addChild(myButton); //create button label var tText:TextField = new TextField(); tText.mouseEnabled = false, tText.x = xLoc; tText.y = yLoc + iLabelOffset; tText.width = width; tText.selectable = false var Format:TextFormat = new TextFormat(); Format.font = "Arial"; Format.color = 0x000000; Format.size = fontsize; Format.bold = false; Format.align = TextFormatAlign.CENTER; tText.defaultTextFormat = Format; tText.text = label; addChild(tText) } } } Is there anything to comment on this? I am sure that I'm doing a lot of things wrong, maybe I didn't really get the whole object oriented thing? Also, I have a bad feeling about the way I am using the "extends ..." after a class declaration, mainly because I'm just using Sprite all the time and don't really understand why or what it does (having trouble finding out on the internet aswell). Another thing I am unsure about is the naming of variables in AS3. Should I really be using names such as xLoc, or iLabelOffset? I think I am not being very consistent in my variable naming atleast? I hope someone can give me a push to a better track than the one I am on now, as I am sure that I should improve my AS3 coding before I continue working on this beast. Thanks a lot. A: My opinion: A class called Client2 is probably a bad naming choice. Client2 isn't telling me much. How much will it tell you in a year's time? In CustomButton, initialization is taken care of in the constructor. In LoginInterface, using an instance of the class requires an explicit call to init(). Easy to forget and unnecessary. Unless there's a good reason not to, call init from the constructor. What does iLabelOffset mean? better to use a less confusing name in a parameter list. The parameter list of the CustomButton constructor is pretty long. It's not necessary to pass in the x and y. Sprite has an x and y property already, so put everything back to a zero offset and manipulate the x and y properties of the CustomButton once it's constructed. Of the remaining parameters to the CustomButton constructor, consider reordering them so that you can provide default parameters (which can only go at the end of the parameter list). labelOffset and fontSize seem like good candidates. Keep function size small by removing repeated code. Create a function to create the button state Sprites that takes a color in its parameters (or better yet, move this functionality into a new type of Sprite derived class), and also add a createLabel function so that you can move that code out of the constructor. Your code will become easier to read and maintain if you try to keep function size small. It also means you have to write less comments ;-) A: Spender hit the nail on the head. Those are definitely the issues that are raised when I looked over your code. The things he mentioned are not nessesarly Actionscript issues, (issue's not quite the right word, perhaps "areas to note"), these are issues general to all programing languages. Descriptive naming for example is extremely important. There are few books that focus on this side of programming, and even fewer that do it well. I would highly recommend picking up the following two books if you want to grow more in this area, (I'll recommend it even if you don't want too :) Code Complete The pragmatic programmer There both books that every programmer should read, so check them out. You're code from an Actionscript point of view is fine, but that's just syntax. It's important to note that these skill will never develop unless you actually write code, so by all means "continue working on this beast" and the rest will follow suit. A: Just as a matter of style, I like to declare my variables outside of the constructor. It helps me to feel that I won't have any surprises with public vs private or scope. Also notice the added white space, which can improve readability. public class CustomButton extends Sprite { private var myButton:SimpleButton; private var normal:Sprite; private var over:Sprite; // etc ... public function CustomButton(xLoc:int, yLoc:int, width:int, height:int, iLabelOffset:int, fontsize:uint, label:String) { //create new simple button instance myButton = new SimpleButton(); //create the look of the states normal = new Sprite(); normal.graphics.lineStyle(1, 0x000000); normal.graphics.beginFill(0x6D7B8D); normal.graphics.drawRect(xLoc, yLoc, width, height); //the mouseover sprite over = new Sprite(); over.graphics.lineStyle(1, 0x000000); over.graphics.beginFill(0x616D7E); over.graphics.drawRect(xLoc, yLoc, width, height); // etc ...
doc_23529859
This is how I created a class for constants, "Keys" public class Keys { public static class SQLite { public static final int DB_VERSION = 8; public static final String DB_NAME = "my_db.sqlite"; public static final String TABLE_NAME = "table_name"; public enum Column { NAME("name"), PHONE("phone"), ADDRESS("address"); private String value; Column(String value) { this.value = value; } public String toString() { return value; } } } public static class Constants { public static final String CONST1 = "const1"; public static final String CONST2 = "const2"; public enum Random { ONE("one"), TWO("two"), THREE("three"); private String value; Random(String value) { this.value = value; } public String toString() { return value; } } } } Now, inside a class called "MyActivity", I know I can use enums like this: String name = Keys.SQLite.Column.NAME.toString(); But is there a way to shorten the prefix? so that I can access it in a simpler way: Column.Name.toString(); instead of: Keys.SQLite.Column.Name.toString(); A: You can import the enum in MyActivity class: import Keys.SQLite.Column; and just use String name = Column.NAME.toString(); A: As Azodious already stated, you can import it via import Keys.SQLite.Column; If that does not suffice your needs, you may also use a static import, like: import static Keys.SQLite.Column.NAME; This way you can now use String name = NAME.toString(); A: Directly import the enum in your class: import Keys.SQLite.Column; and then type Enum name and enum which you want to get : Column.NAME;
doc_23529860
I was thinking of making the transform static but that doesn't seem achievable. I also can't place them in one object and move it since it would change their position. Do you have any advices? Any help is highly appreciated. EDIT: Thanks for the replies. My goal is to rotate the objects with the same value but not the common way. I don't want to use the transform in every object. void Update() { if (Input.GetMouseButton(0)) { rotX = Input.GetAxis("Mouse X") * sensitivity * Mathf.Deg2Rad; transform.Rotate(Vector3.forward, rotX); } } I want them to have the same transform.rotation with different transform.position and transform.scale. This way transform.Rotate() would only be used once, not the times of the number of objects. I want to avoid having to access the transform of every object. A: Can you give us a more detailed example? When it comes to perfomance, it is really hard to tell which approach would be better in your case without a sample code. Here you can find some insights about using the physics engine (using RigidBody.MoveRotation() ) to accomplish a better performance vs Transform.Rotate: https://answers.unity.com/questions/294452/rotation-performance.html A: Create a script named controller . There use UnityEngine.Object.FindObjectsOfType<GameObject>(); Now you have an array of GameObjects. Use foreach or a loop and set transform.rotation. Now you have all objects moving at once. GameObject[] allObjects = UnityEngine.Object.FindObjectsOfType<GameObject>() ; foreach(object go in allObjects) if (go.activeInHierarchy) print(thisObject+" is an active object");
doc_23529861
Hi all, I want to achieve the below requirement in Terraform. Requirement: I want to create object (with key_name) in s3 bucket. Before creating the object need to check whether the object with same key already exists or not using data source. If it is already exists, do not create object. If not do create the object in s3 bucket. Source Code variable "key_name" { default = "test.txt" } variable "bucket_name" { default = "test-bucket-654321" } data "aws_s3_bucket_objects" "my_objects" { bucket = var.bucket_name } locals { key_present = anytrue([ for key in data.aws_s3_bucket_objects.my_objects.keys: key == var.key_name ]) } resource "aws_s3_bucket_object" "examplebucket_object" { count = local.key_present ? 0 : 1 key = var.key_name bucket = var.bucket_name content = "Test Value" } output "my_objects" { value = data.aws_s3_bucket_objects.my_objects.keys } output "key_present" { value = local.key_present } Let's assume, key is does not exists in the bucket (For example, it is a new bucket with no objects) * *On applying 1st time, it creates the object in bucket. *On applying 2ns time, it destroy the created object in bucket. *On applying 3rd time, it creates the object in bucket. On 1st time, data source returns empty value. so it creates the object in bucket. On 2nd time, data source returns created object name. so the key is already exists and it destroys the object in bucket. Likewise every odd number of times it creates the objects and every even number of times it destroys the created object. Output: ubuntu@test-instance:~$ terraform apply --auto-approve aws_s3_bucket_object.examplebucket_object[0]: Creating... aws_s3_bucket_object.examplebucket_object[0]: Creation complete after 0s [id=test.txt] Apply complete! Resources: 1 added, 0 changed, 0 destroyed. Outputs: key_present = false my_objects = tolist([]) ubuntu@test-instance:~$ terraform apply --auto-approve aws_s3_bucket_object.examplebucket_object[0]: Refreshing state... [id=test.txt] aws_s3_bucket_object.examplebucket_object[0]: Destroying... [id=test.txt] aws_s3_bucket_object.examplebucket_object[0]: Destruction complete after 0s Apply complete! Resources: 0 added, 0 changed, 1 destroyed. Outputs: key_present = true my_objects = tolist([ "test.txt", ]) Could anyone give me the solution for creating a terraform resource based on the data source output ? A: What your code above is doing is that in every even iteration the conditional meta-argument expression count = local.key_present ? 0 : 1 evaluates to 0 and thus you are commanding terraform to create explicitly 0 quantity of the resource. Every even iteration, you terraform configuration for examplebucket_object effectively becomes: resource "aws_s3_bucket_object" "examplebucket_object" { count = 0 key = var.key_name bucket = var.bucket_name content = "Test Value" } The logic above is effectively commanding Terraform to remove examplebucket_object. Terraform is designed to be idempotent, that it, if a resource is already under Terraform management (part of the state), Terraform will figure that out and it will not re-provision the same resource (assuming the same configuration is being applied, which is not in your case.) So, in your case, your Terraform configuration is changing the intended target state depending on the previous state found, and this explains your conundrum. In general you have to consider this situation: * *If you're expecting to manage the lifecycle of a resource via Terraform from the beginning, then you don't need to do any data source queries and conditional checks. *If you are expecting to occasionally encounter existing resources and want to bring them under Terraform management, what you need to do is to import those resources into the state, via terraform import. * *Currently aws_s3_bucket_object does not support terraform import, but there is a pull-request open. Note: I'd recommend you implement a Dependency Inversion approach as described in Conditional Creation of Objects from the official Terraform documentation: Rather than trying to write a module that itself tries to detect whether something exists and create it if not, we recommend applying the dependency inversion approach: making the module accept the object it needs as an argument, via an input variable. This is consistent with Terraform's declarative style: rather than creating modules with complex conditional branches, we directly describe what should already exist and what we want Terraform to manage itself.
doc_23529862
ImportError Traceback (most recent call last) <ipython-input-12-4f7ed86c5a6a> in <module> 2 import os 3 from IPython.display import Image ----> 4 import easyocr ~\AppData\Local\Continuum\anaconda3\lib\site-packages\easyocr\__init__.py in <module> ----> 1 from .easyocr import Reader 2 3 __version__ = '1.3.1' ~\AppData\Local\Continuum\anaconda3\lib\site-packages\easyocr\easyocr.py in <module> 1 # -*- coding: utf-8 -*- 2 ----> 3 from .detection import get_detector, get_textbox 4 from .recognition import get_recognizer, get_text 5 from .utils import group_text_box, get_image_list, calculate_md5, get_paragraph,\ ~\AppData\Local\Continuum\anaconda3\lib\site-packages\easyocr\detection.py in <module> 9 from .craft_utils import getDetBoxes, adjustResultCoordinates 10 from .imgproc import resize_aspect_ratio, normalizeMeanVariance ---> 11 from .craft import CRAFT 12 13 def copyStateDict(state_dict): ~\AppData\Local\Continuum\anaconda3\lib\site-packages\easyocr\craft.py in <module> 9 import torch.nn.functional as F 10 ---> 11 from .model.modules import vgg16_bn, init_weights 12 13 class double_conv(nn.Module): ~\AppData\Local\Continuum\anaconda3\lib\site-packages\easyocr\model\modules.py in <module> 4 import torch.nn.init as init 5 from torchvision import models ----> 6 from torchvision.models.vgg import model_urls 7 from collections import namedtuple 8 ImportError: cannot import name 'model_urls' from 'torchvision.models.vgg' (C:\Users\name\AppData\Local\Continuum\anaconda3\lib\site-packages\torchvision\models\vgg.py) A: Can't believe this question no one come to answer. First of all, for all torchvision > 0.13 users, the model_urls are gone, you shouldn't use it. TL, DR: solution is simple: # change from your model_urls to this from torchvision.models.resnet import ResNet50_Weights org_resnet = torch.utils.model_zoo.load_url(ResNet50_Weights.IMAGENET1K_V2) If you want using other resnet arch, just replace with ResNet101_Weights etc. Mine torchvision version tested: '0.13.0.dev20220419+cu115'
doc_23529863
if I wrap the input(the toggle) inside to get record's id using $_GET method for making necessary changes in the articles.php then it does not fetch data of is_public into the toggle. is there any other way to get the id of a specific record? screenshot of the article list table this is all-articles.php code: <table id="datatable" class="table table-hover" style="width:100%"> <thead> <tr> <th>#</th> <th>Title</th> <th>Author</th> <th>Abstract</th> <th>category</th> <th>Date</th> <th>Action</th> <th>Publish</th> </tr> </thead> <tbody> <?php foreach($articles as $key => $article): ?> <tr> <td><?php echo $key+1 ?></td> <td><?php echo $article['title'] ?></td> <td><?php echo $article['author_id'] ?></td> <td><?php echo $article['abstract'] ?></td> <td><?php echo $article['category_id'] ?></td> <td><?php echo $article['entry_date'] ?></td> <td> <div class="btn-group" role="group" aria-label="Basic example"> <button type="button" class="btn btn-primary btn-sm">Edit</button> <button type="button" class="btn btn-success btn-sm">Show</button> <button type="button" class="btn btn-danger btn-sm">Delete</button> </div> </td> <td> <form action="all-articles.php" method="post"> <label class="custom-toggle"> <?php if($article['is_public']): ?> <input type="checkbox" checked name="check"> <?php else: ?> <input type="checkbox" name="uncheck"> <?php endif; ?> <span class="custom-toggle-slider rounded-circle"></span> </label> </form> </td> </tr> <?php endforeach; ?> </tbody> </table> A: Well, You can send the article id in your form and then listen to it and do what you want with it. So, // As you are already in foreach loop so, <form action="all-articles.php" method="post"> <label class="custom-toggle"> <?php if($article['is_public']): ?> <input type="checkbox" checked name="published" value="<?php echo $article['id']; ?>> <?php else: ?> <input type="checkbox" name="published" value="<?php echo $article['id']; ?>> <?php endif; ?> <span class="custom-toggle-slider rounded-circle"></span> </label> </form> Then in your /all-articles.php check for the $_POST['check'] which should give article id. query your database with that id and toggle the is_public column Another way would be to send a hidden field, some thing like // As you are already in foreach loop so, <form action="all-articles.php" method="post"> <label class="custom-toggle"> <?php if($article['is_public']): ?> <input type="checkbox" checked name="published" value="<?php echo $article['id']; ?>> <input type="hidden" name="is_published" value="yes"> or 1 <?php else: ?> <input type="hidden" name="is_published" value="no"> or 0 <input type="checkbox" name="published" value="<?php echo $article['id']; ?>> <?php endif; ?> <span class="custom-toggle-slider rounded-circle"></span> </label> </form>
doc_23529864
x <- c(0,0,1,1,0,0,1,1,0,0,1,1,1,1,0,1,0,1,0,1) I want x to be like this: y = c(0,0,1,1,0,0,2,2,0,0,3,3,3,3,0,4,0,5,0,6) Could anyone help me solve this question? A: An option would be rle inverse.rle(within.list(rle(x), values[values!=0] <- seq_along(values[values!=0]))) #[1] 0 0 1 1 0 0 2 2 0 0 3 3 3 3 0 4 0 5 0 6 Or with rleid from data.table library(data.table) x1 <- x*rleid(x) match(x1, unique(x1[x1!=0]), nomatch = 0) #[1] 0 0 1 1 0 0 2 2 0 0 3 3 3 3 0 4 0 5 0 6
doc_23529865
% Matlab code: Create a 1500-by-1500 sparse matrix from the triplets i, j, and v i = [900 1000]; j = [900 1000]; v = [10 100]; S = sparse(i,j,v,1500,1500) %result S = (900,900) 10 (1000,1000) 100 I want to do the same thing in C++, i saw in different posts that we can handle sparse matrices with Eigen Library, but i didn't really understand how to do this. Can you help me ? Thanks A: Create a vector of triplets typedef Eigen::Triplet<int> Trip; std::vector<Trip> trp; Create the triplets trp.push_back(Trip(900,900,10)); // (index, index, value) trp.push_back(Trip(1000,1000,100)); Assign them to the sparse Eigen matrix int rows, cols; rows = cols = 1500; Eigen::SparseMatrix<int> A(rows,cols); A.setFromTriplets(trp.begin(), trp.end()); Print the entire (dense) matrix std::cout << A << std::endl; or print just the indices and values std::cout << "Row\tCol\tVal" <<std::endl; for (int k=0; k < A.outerSize(); ++k) { for (SparseMatrix<int>::InnerIterator it(A,k); it; ++it) { std::cout << it.row() << "\t"; // row index std::cout << it.col() << "\t"; // col index (here it is equal to k) std::cout << it.value() << std::endl; } }
doc_23529866
A: The easiest way is to write a quick Mac app to do the editing, using the same data model file. If you're using Xcode 3, do this. Create a new Mac app that uses Core Data, and drag in your data model (removing the default data model it creates for you). Then, open the .xib file for the Mac app's main window in Interface Builder. Switch back to Xcode and open the data model. Pick the entity you want an editor for. Then hold down option (alt), and drag the entity from the data model editor into Interface Builder. It automatically creates a user interface for editing the database, which you can then save and run through Xcode. Make sure that your Mac app is creating an sqlite data store (look through the code that Xcode created for you by default, it may have defaulted to XML and you'll have to change it). The file that app creates can then be dropped straight into an iPhone app. Sadly, Xcode 4 can't do the automatic laying out of a database editing UI. If you're using Xcode 4, you'd have to lay out the UI manually.
doc_23529867
package sample.calendar; public class OutlookToGmailCalendarSync { public static void main(String[] args) { System.out.println("hi"); } } This is my build.xml file: <project name="MyCalendarSample" default="run" basedir="."> <description> simple example build file </description> <!-- set global properties for this build --> <property name="src" location="src"/> <property name="build" location="build"/> <property name="dist" location="dist"/> <path id="path.class"> <pathelement location="build/sample/calendar"/> </path> <target name="run" depends="compile" description="Runs the complied project"> <!-- Run --> <java fork="true" classname="OutlookToGmailCalendarSync"> <classpath> <path refid="path.class"/> </classpath> </java> </target> <target name="compile" depends="init" description="compile the source " > <!-- Compile the java code from ${src} into ${build} --> <javac srcdir="${src}" destdir="${build}"/> </target> <target name="init"> <!-- Create the time stamp --> <tstamp/> <!-- Create the build directory structure used by compile --> <mkdir dir="${build}"/> </target> <target name="clean" description="clean up" > <!-- Delete the ${build} directory trees --> <delete dir="${build}"/> </target> </project> And this is the result: C:\java\my>ant Buildfile: C:\java\my\build.xml init: compile: [javac] C:\java\my\build.xml:30: warning: 'includeantruntime' was not set, d efaulting to build.sysclasspath=last; set to false for repeatable builds [javac] Compiling 1 source file to C:\java\my\build run: [java] java.lang.NoClassDefFoundError: OutlookToGmailCalendarSync (wrong na me: sample/calendar/OutlookToGmailCalendarSync) [java] at java.lang.ClassLoader.defineClass1(Native Method) [java] at java.lang.ClassLoader.defineClass(ClassLoader.java:791) [java] at java.security.SecureClassLoader.defineClass(SecureClassLoader .java:142) [java] at java.net.URLClassLoader.defineClass(URLClassLoader.java:449) [java] at java.net.URLClassLoader.access$100(URLClassLoader.java:71) [java] at java.net.URLClassLoader$1.run(URLClassLoader.java:361) [java] at java.net.URLClassLoader$1.run(URLClassLoader.java:355) [java] at java.security.AccessController.doPrivileged(Native Method) [java] at java.net.URLClassLoader.findClass(URLClassLoader.java:354) [java] at java.lang.ClassLoader.loadClass(ClassLoader.java:423) [java] at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) [java] at java.lang.ClassLoader.loadClass(ClassLoader.java:356) [java] at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.j ava:482) [java] Exception in thread "main" [java] Java Result: 1 BUILD SUCCESSFUL Total time: 1 second C:\java\my> Even after reading other forum posts, I still don't understand why this is happening to me. At runtime, the compiled class is in build/sample/calendar, which is what the classpath is set to, so I don't see the problem. A: Try with the below change: The Classpath is set to the root directory where the classes are generated and class's packaged name is provided for java command. <path id="path.class"> <pathelement location="build"/> </path> <target name="run" depends="compile" description="Runs the complied project"> <!-- Run --> <java fork="true" classname="sample.calendar.OutlookToGmailCalendarSync" > <classpath refid="path.class"/> </java> </target> Hope this would help.
doc_23529868
The response is an object like this: { "html_attributions": [], "results": [ { "address": "Wood Quay, Dublin, Ireland", "name": "Christ Church Cathedral", "place_id": "ChIJGw9ASiYMZ0gRy9yiaCZxNZI", }, { ... }, { ... }, ], "status": "OK" } Inside the Response.Listener I need to access the "results" array. I try to get the JSONArray with name "results" as follows: JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, API_URL, null, new Response.Listener <JSONObject> () { @Override public void onResponse(JSONObject response) { // THE PROBLEM IS HERE - WON'T COMPILE !!! JSONArray array = response.getJSONArray("results"); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // } }); But I see an error: A: Seems like response.getJSONArray("results"); throws the JSONException. You need to handle that exception by wrapping response.getJSONArray("results"); with a try-catch block. Something like this: try { JSONArray array = response.getJSONArray("results"); } catch (org.json.JSONException exception) { // handle the exception }
doc_23529869
A: printf and putchar are both stdio functions, so they both write to the same FILE handle (rather than directly to the file descriptor). However, printf is far heavier since the first argument is a format string that needs to be scanned for replacement expressions and escapes. So, both printf("\n") and putchar('\n') will do the same thing, but the latter will be faster. A: It doesn't really matter. I never encountered a case were printing to the console ever matter to someone in terms functions choice or effiency. A: printf is much slower because the format string is parsed at runtime. Of course, the average homework program or simple Project Euler solution is so small that wasting a few CPU cycles doesn't matter anyway. A: I would go with putchar as the string in printf needs to be parsed. Should be slightly quicker - but probably not a lot in it. A: It will make no difference which one you chose if you're using a modern compiler[1]. Take for example the following C code. #include <stdlib.h> #include <stdio.h> void foo(void) { putchar('\n'); } void bar(void) { printf("\n"); } When compiled with gcc -O1 (optimizations enabled), we get the following (identical) machine code in both foo and bar: movl $10, %edi popq %rbp jmp _putchar ## TAILCALL Both foo and bar end up calling putchar('\n'). In other words, modern C compilers are smart enough to optimize printf calls very efficiently. Just use whichever one you think is more clear and readable. * *I do not consider MS's cl to be a modern compiler. A: Are there any best practices for using one over the other? Let style drives the decision. Since efficiency of execution is the same or nearly identical, use the style that best conveys the larger code's function. If the function had lots of printf(), stay with printf("\n"). Likewise for putchar('\n') and puts("")
doc_23529870
div.tooltip { position: absolute; text-align: left; width: 500px; color:white; padding: 8px; font: 13px sans-serif; background: black; border: solid 1px #aaa; pointer-events: none; } var div = d3.select("body").append("div") .attr("class", "tooltip") .style("opacity", 0); function mousemove(d) { div .html("Tooltip is here") .style("left", (d3.event.pageX) + "px") .style("top", (d3.event.pageY) + "px") } function mouseover(p) { div.transition() .duration(300) .style("opacity", 1); d3.selectAll(".row text").classed("active", function(d, i) { return i == p.y; }); d3.selectAll(".column text").classed("active", function(d, i) { return i == p.x; }); } function mouseout() { div.transition() .duration(300) .style("opacity", 1e-6); d3.selectAll("text").classed("active", false); } Then my elements call the functions mousemove, mouseover, and mouseout. This all works fine and the tooltip is displayed perfectly. What I want to do now though is generate a table when I hover over an entry, and have that table be inside the tooltip. The code I have right now generates the table properly, but it does not put it into the tooltip, instead the table is generated either above or below the matrix. I'm using this function to generate the table: function tabulate(data, columns) { var table = d3.select("body").append("table"), thead = table.append("thead"), tbody = table.append("tbody"); // append the header row thead.append("tr") .selectAll("th") .data(columns) .enter() .append("th") .text(function(column) { return column; }); // create a row for each object in the data var rows = tbody.selectAll("tr") .data(data) .enter() .append("tr"); // create a cell in each row for each column var cells = rows.selectAll("td") .data(function(row) { return columns.map(function(column) { return {column: column, value: row[column]}; }); }) .enter() .append("td") .text(function(d) { return d.value; }); return table; } Could anyone give me some help on how I could get the table to generate inside the tooltip? A: Currently, var table = d3.select("body").append("table") Selects the entire body of your page and appends a table element, making the table appear appear at the bottom of your page. Making a small change, var table = div.append("table") will take your tooltip element and append the table so it appears inside the tooltip. (naming the tooltip something a little more descriptive than 'div' might be a good idea) Normally tooltip also need to update their contents when different elements are moused over; I don't think you're trying to do that here though?
doc_23529871
In particular, I have a question regarding the output channel. It provides a method for a single output of a byte array, and the output itself is asynchronous after the method is called. One of the devices implements interrupts which can be caught via OS utilities (WaitForSingleObject in Windows). So in this particular case I have an object which implements IArinc429Device, it: * *implements method CaptureInterrupt that invokes a particular channel's callback when interrupt occurs; *holds a thread that runs CaptureInterrupt; void ArincPCI429_3::CaptureInterrupt() { HANDLE hEvent = CreateEvent(nullptr, TRUE, FALSE, "PCI429_3Interrupt"); // register event handle within device via DeviceIoControl while (true) { DWORD waitRes = WaitForSingleObject(hEvent, INFINITE); ResetEvent(hEvent); // get output channel index which has generated an interrupt size_t channelIndex = ...; // private implementation holds pointers to output channels pImpl_->GetChannelOut(channelIndex)->InvokeInterrupCallback(); } } But another device does not implement interrupts, so I have to "busy-wait" (sleep for the calculated expected time, then loop sleeping for small periods of time to adjust possible inaccuracies). An object that implements interface IArinc429ChannelOutput: * *implements method SingleOutput, that initiates asynchronous output; *implements method WaitOutputFinished, that waits until channel is running, then modifies its state to stopped; *holds a thread that runs WaitOutputFinished; void ArincECE206_1ChannelOutput::WaitOutputFinished(size_t words) { // calculate expected period of time to sleep, using amount of words to transfer and channel output speed std::chrono::microseconds timeToSleep = ...; // 99% is enough std::this_thread::sleep_for(timeToSleep); // if channel is still running, wait for 1 more word. timeToSleep = Arinc429Values::TimeToTransfer( refImpl_.outputFreqs[ChannelIndex()], 1); while(IsRunning()) { std::this_thread::sleep_for(timeToSleep); ++additionalWords; } mode_ = Arinc429OutMode::stopped; if (callbackOnFinishedOutput_) callbackOnFinishedOutput_(); } Here is part of an API for output channel struct ARINC429_API IArinc429ChannelOutput { // 0 based index virtual size_t ChannelIndex() const = 0; virtual Arinc429OutMode OutputMode() const = 0; virtual Arinc429Freq Frequency() const = 0; virtual size_t BufferSize() const = 0; virtual void SetFinishOutputCallback(std::function<void()>&& fCallBack) = 0; // elements exceeding BufferSize are ignored // TODO: return future? virtual bool SingleOutput(array_view<const uint32_t> wordArray) = 0; virtual void StopOutput() = 0; virtual ~IArinc429ChannelOutput() = default; }; Given the asynchronous nature of output, I think it would be convenient to return std::future from SingleOutput. And I see no problem in doing so for the second type of an Arinc429 device, since separate channel objects own their own separate waiting threads. I chose to add a callback on finished output from the beginning since interrupts are implemented for the first device. Also callbacks are convenient to emit Qt signals from. But std::future is more handy for synchronization and can be used to wait for an output to finish. Though it is also manageable using callbacks and condition variables, I do not find that approach rather convenient. What option to choose? a. Define routine that registers and uses callbacks. b. Define std::future as a return type for SingleOutput. c. Define both. Is this reasonable or even possible? It implies calling std::promise<R>::set_value and than calling. Another question is about implementation. I don't see a clear and simple way to implement returning std::future in case of a device that implements interrupts, since there is a common interrupt event and capturing thread for all the channels. How to provide futures for multiple output channel objects which all reside in different threads? See ArincPCI429_3::CaptureInterrupt() A: I've asked this question before I got familiar with ASIO and Executors. They provide a Universal Asynchronous Model API. That is, a template function can be both synchronous and asynchronous depending on a completion token. Basically, a function would look like template <typename CompletionT> auto do_stuff(CompletionT &&token); Depending on the type of a token, there result can be returned via a simple callback: do_stuff([](bool res){ return res;}); If an synchronous behavior is needed, a special tag can be passed instead: auto boolFuture = do_stuff(use_future); bool res = boolFuture.get();
doc_23529872
(set! *unchecked-math* true) (defn add-up ^long [^long n] (loop [n n i 0 sum 0] (if (< n i) sum (recur n (inc i) (+ i sum))))) So, just out of curiosity, I've tried it in lein repl and, to my surprise, found this code running ~20 times slower that expected (Clojure 1.6.0 on Oracle JDK 1.8.0_11 x64): user=> (time (add-up 1e8)) "Elapsed time: 2719.188432 msecs" 5000000050000000 Equivalent code in Scala 2.10.4 (same JVM) runs in ~90ms: def addup(n: Long) = { @annotation.tailrec def sum(s: Long, i: Long): Long = if (i == 0) s else sum(s + i, i - 1) sum(0, n) } So, what am I missing in the Clojure code sample? Why is it so slow (should theoretically be roughly the same speed)? A: Further to @dnolen's answer, a few observations: Though it turns out to make no real difference, we should make the Clojure function the same shape as the Scala one. In (defn add-up ^long [^long n] (loop [n n i 0 sum 0] (if (< n i) sum (recur n (inc i) (+ i sum))))) * *n is not changed by the recur, so need not be bound in the loop. *The two remaining arguments are in the opposite order to the Scala function. *It runs up the numbers, whereas the Scala runs down. Mending these inconsistencies, we get defn add-up [^long n] (loop [sum 0, i n] (if (zero? i) sum (recur (+ sum i) (dec i))))) (The Scala type system ensures that the argument n is converted to a Long on call. As I understand it (please correct me if I'm wrong), the Clojure ^long type hint promises to treat a Long argument well, but does not promise to convert a Double like 1e8 to a Long. But I got very inconsistent results when I made the corresponding changes.) On my laptop, the above gives (time (add-up 100000000)) "Elapsed time: 103.636782 msecs" 5000000050000000 If you remove the type hint (defn add-up [n] ... ) ... the elapsed time multiplies by about twenty: (time (add-up 100000000)) "Elapsed time: 2374.399915 msecs" 5000000050000000 * *This has more effect than removing unchecked math, which roughly triples the elapsed time. *Type hinting the return type has no discernible effect. All this on Clojure 1.5.0 on OpenJDK Java 7. A: Benchmarking with lein repl is generally a bad idea as it specifically sets non-server JVM settings. Using the Clojure JAR directly I see ~40ms on a 3.5ghz i7 iMac running JDK 8 under OS X 10.9. A: On a three year-old mac book, I get the following: (time (add-up 1e8)) "Elapsed time: 68.536 msecs" and (time (add-up 1e9)) "Elapsed time: 771.157 msecs" => 500000000500000000 What would be the version of Lein you are using, can you check the clojure Version with: (clojure-version)
doc_23529873
I have tried servlet to fetch record and jsp to display it. My jsp code is as below <ul> <% Iterator itr;%> <% List data=(List)request.getAttribute("data"); for(itr=data.iterator(); itr.hasNext(); ){ %> <li><a href=""><%=itr.next()%></a></li> <%}%> </ul> With above method I can get category properly but the problem is that I want sub category which are store in anather table named as tbl_subcategory. With above method I can get output as below: Home Aboutus Sports Kitchen Baby-Toys Now I want to display sub menus of each category on mouse over. But it shows only category not subcategory. A: I don't know what's stored inside "data" but let's say it's loaded with Strings: String data[] = new String[] { "Array 1", "Array 2", "Array 3" }; And the JSP-page would look something like this to print out all strings inside "data": <ul> <% Iterator<String> iterator = request.getAttribute("data"); while (iterator.hasNext()) { %> <li> <a href=""><%=iterator.next()%></a> </li> <%}%> </ul> And the generated HTML-page would look something like this: <ul> <li><a href="">Array 1</a></li> <li><a href="">Array 2</a></li> <li><a href="">Array 3</a></li> </ul> Or you can use JSTL to iterate through "data". Add this declaration in your HTML-Header: <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> And then iterate through "data": <% String data[] = request.getAttribute("data"); %> <ul> <c:forEach var="d" items="${data}"> <li><a href=""><c:out value="${d}" /></a></li> </c:forEach> </ul> As for your dropdown menu take a look at THIS TUTORIAL WITH A SIMPLE DROPDOWN MENU which is for free. If you're looking for a more advanced dropdown menu look at THIS TUTORIAL WITH A ADVANCED DROPDOWN MENU but keep in mind though that this advanced dropdown menu costs money I don't know where you're getting your submenuitems from but all I can say is that you should enter your submenu values inside the <a> tags to create submenuitems when you're using these tutorials. like this: <li><a href="#" onmouseover="mopen('m1')" onmouseout="mclosetime()">Array 1</a> <div id="m1" onmouseover="mcancelclosetime()" onmouseout="mclosetime()"> <a href="#">Array 1.1</a> <a href="#">Array 1.2</a> <a href="#">Array 1.3</a> </div> </li> <li><a href="#" onmouseover="mopen('m2')" onmouseout="mclosetime()">Array 2</a> <div id="m2" onmouseover="mcancelclosetime()" onmouseout="mclosetime()"> <a href="#">Array 2.1</a> <a href="#">Array 2.2</a> <a href="#">Array 2.3</a> </div> </li> Just follow the steps in the tutorials and you'll be fine
doc_23529874
I have some macros that define functions that have special characters. Specifically ":" and ".". Is it possible to write a spec definition for functions with those characters in it? defmodule UniqueCharacters do defmacro make_wild_function_name do function_name = String.to_atom("baz:foo.bar") quote do def unquote(function_name)(), do: :ok end end end defmodule TestSpec do import UniqueCharacters #This next line doesn't work @spec baz:foo.bar() :: :ok make_wild_function_name() end This produces the following error: ** (SyntaxError) lib/unique_characters.ex:14: keyword argument must be followed by space after: baz: (elixir) lib/kernel/parallel_compiler.ex:229: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/7 Is there a way to escape the characters in the function spec so that this will compile without removing the spec? I can change the ":" to "_" or something more well behaved but the "." is basically non-negotiable. A: Can you specify the typespec in your macro? If so, this seems to work fine: defmodule UniqueCharacters do defmacro make_wild_function_name do function_name = String.to_atom("baz:foo.bar") quote do @spec unquote(function_name)() :: :ok def unquote(function_name)(), do: :ok end end end defmodule TestSpec do import UniqueCharacters make_wild_function_name() end I feel like bundling the typespec with the definition makes the most sense; is that enough? Edit: Looks like this also works, although kinda messy: defmodule UniqueCharacters do defmacro make_wild_function_name do function_name = String.to_atom("baz:foo.bar") quote do def unquote(function_name)(), do: :ok end end end defmodule TestSpec do import UniqueCharacters @spec unquote(:'baz:foo.bar')() :: :ok make_wild_function_name() end
doc_23529875
HTML: <div class="master-container"> <div class="container"> <div class="fixed"> </div> </div> </div> CSS: .master-container { max-width: 1200px; margin: 0 auto; } .container { width: 30%; } .fixed { position: fixed; } I've looked at a few other SO posts: Set width of a "Position: fixed" div relative to parent div Set width of fixed positioned div relative to his parent having max-width With the general answer being to set width: inherit on the fixed element. The issue is it still inherits the width from the body rather than its percentage (unless I set a fixed width on the parent). So, how can I get a fixed div to size to its immediate parent when the parent's width is set to a percentage. I am seeking CSS solutions only - is it possible or will I have to JS it? Edit Most solutions so far inherit the width of the page where I need to get the fixed div to take 30% of the mastered centered container that center's the web page, it has a max width of 1200px. A: You can achieve this using width: inherit; .container { width: 30%; background: #444; height: 50px; } .fixed { width: inherit; height: 40px; position: fixed; background: #ccc; } <div class="container"> <div class="fixed"> </div> </div> You can also check Fiddle A: This "works" fine if your parent div is the same width as the body. Of course, it is only working in appearance, not reality. This div takes 30% of the browser's width, like its parent div. html, body { margin: 0; } .container { width: 30%; height: 400px; background: linear-gradient(green, white) } .fixed { position: fixed; background: red; width: inherit; height: 10px; } <div class="container"> <div class="fixed"></div> </div> Otherwise, to accomplish this in CSS, you have a couple options, depending on your structure. We know based on your question that the direct parent of the fixed div has a percentage width (we'll use 30%). That .container div must have one or more parent divs that have: * *A fixed width in pixels *A width in percentage *A width in vw, em, etc. This will (probably) be calculated in CSS. Otherwise, I don't know why you would want a CSS-only solution. So if you have a parent of the container div with a width of 500px, you can make your fixed div the same width as the .container by giving it 30% of 500px: html, body { margin: 0; } .parent { width: 500px; height: 400px; background: linear-gradient(blue, white) } .container { width: 30%; height: 400px; background: linear-gradient(green, white) } .fixed { position: fixed; background: red; width: calc(500px * .3); height: 10px; } <div class="parent"> <div class="container"> <div class="fixed"></div> </div> </div> This would also work if the .parent div has a width in % or vw, or anything else: html, body { margin: 0; } .parent { width: 50%; height: 400px; background: linear-gradient(blue, white) } .container { width: 30%; height: 400px; background: linear-gradient(green, white) } .fixed { position: fixed; background: red; width: calc(50% * .3); height: 10px; } <div class="parent"> <div class="container"> <div class="fixed"></div> </div> </div> Obviously, you will have to know the widths of all the parents up to either the body or the nearest div with a fixed width and do the math in the CSS calc to adjust. But again, assuming no JS and that all parent div widths are defined in CSS, this could be done. Edit: based on your updated question: html, body { margin: 0; } .master-container { width: 100%; max-width: 1200px; margin: 0 auto; background: linear-gradient(blue, white) } .container { width: 30%; height: 400px; background: linear-gradient(green, white) } .fixed { position: fixed; background: red; width: calc(1200px * .3); height: 10px; } @media (max-width: 1200px) { .fixed { width: 30%; } } <div class="master-container"> <div class="container"> <div class="fixed"></div> </div> </div> A: You can't do this with percentage-based widths. As soon as you make an element fixed, its size and position attributes become relative to the viewport, not the parent element. It effectively 'breaks out' of its parent and becomes a new stacking context so even though the CSS properties can still be inherited, it's calculated completely differently. Your only option is to use a fixed width in pixels and use JS to sync the two if necessary. A: You have to set width in pixels to the .container or add width to .container parent. .container { width: 100px; } or <div class="containerparent"> <div class="container"> <div class="fixed"> </div> </div> </div> and .container-parent { width: 100px; } .container { width: 30%; }
doc_23529876
main package com.example.androidlistview; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.SimpleAdapter; public class MainActivity extends Activity { String[] smily = new String[] {"Angry","Basic","Cool","Cry","Err","Evil","Kiss","Laugh","Shame" ,"Toungh","Wink","Wonder"}; int[] pic =new int[]{ R.drawable.ic_action_emo_angry, R.drawable.ic_action_emo_basic, R.drawable.ic_action_emo_cool, R.drawable.ic_action_emo_cry, R.drawable.ic_action_emo_err, R.drawable.ic_action_emo_evil, R.drawable.ic_action_emo_kiss, R.drawable.ic_action_emo_laugh, R.drawable.ic_action_emo_shame, R.drawable.ic_action_emo_tongue, R.drawable.ic_action_emo_wink, R.drawable.ic_action_emo_wonder }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>(); for(int i=0;i<10;i++){ HashMap<String, String> hm = new HashMap<String,String>(); hm.put("sml", " " + smily[i]); hm.put("pic", Integer.toString(pic[i]) ); aList.add(hm); } String[] from = { "pic","sml" }; int[] to = { R.id.smily,R.id.txt}; SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.list_layout, from, to); final ListView listView = ( ListView ) findViewById(R.id.listView1); listView.setAdapter(adapter); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub Intent intent = new Intent(MainActivity.this,Descripsn.class); String smiley=(String)listView.getSelectedItem(); Bundle b =new Bundle(); intent.putExtra("smily", smiley); intent.putExtra("image", smily[arg2]); startActivity(intent); } }); } } desc.java package com.example.androidlistview; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.widget.ImageView; import android.widget.TextView; public class Descripsn extends Activity { TextView tv; ImageView im; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_descripsn); tv=(TextView)findViewById(R.id.textView1); im=(ImageView)findViewById(R.id.imagedesc); Intent i =getIntent(); Bundle b=getIntent().getExtras(); String smily = b.getString("smiley"); int img = b.getInt(smily); tv.setText(smily); } } Log 06-21 09:44:38.263: I/Choreographer(4029): Skipped 53 frames! The application may be doing too much work on its main thread. 06-21 09:44:39.523: I/Choreographer(4029): Skipped 58 frames! The application may be doing too much work on its main thread. 06-21 09:44:48.243: I/Choreographer(4029): Skipped 74 frames! The application may be doing too much work on its main thread. 06-21 09:44:48.633: I/Choreographer(4029): Skipped 200 frames! The application may be doing too much work on its main thread. 06-21 09:44:48.853: I/Choreographer(4029): Skipped 46 frames! The application may be doing too much work on its main thread. 06-21 09:44:49.685: I/Choreographer(4029): Skipped 43 frames! The application may be doing too much work on its main thread. 06-21 09:44:54.079: I/Choreographer(4029): Skipped 44 frames! The application may be doing too much work on its main thread. 06-21 09:44:54.733: I/Choreographer(4029): Skipped 46 frames! The application may be doing too much work on its main thread. A: try this @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Intent intent = new Intent(MainActivity.this,Descripsn.class); intent.putExtra("smily", smily[arg2].toString()); intent.putExtra("image", pic[arg2]); intent.putExtra("pos", arg2); startActivity(intent); } and get in other activity Bundle b=getIntent().getExtras(); String smily = b.getString("smily"); int img = b.getInt("image"); int imgpos = b.getInt("pos"); A: Inside your Descripsn class you must use the same identifier for getExtras.. try like this.. Intent i =getIntent(); Bundle b=getIntent().getExtras(); String smily = b.getString("smily"); String img = b.getString("image"); tv.setText(smily); EDIT:- you will get the text passed as you desired .. but for image, well you can send the selected list position as an identifier to your next intent like this.. @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub Intent intent = new Intent(MainActivity.this,Descripsn.class); String smiley=(String)listView.getSelectedItem(); Bundle b =new Bundle(); intent.putExtra("smily", smiley); intent.putExtra("image", smily[arg2]); intent.putExtra("pos", arg2); startActivity(intent); } and then get extras like this,, Intent i =getIntent(); Bundle b=getIntent().getExtras(); String smily = b.getString("smily"); String img = b.getString("image"); int imgpos = b.getInt("pos"); tv.setText(smily); A: String smily = b.getString("smiley"); Wrong)) try this: String smily = b.getString("smily"); A: main.java package com.example.androidlistview; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; public class MainActivity extends Activity { String[] smily = new String[] {"Angry","Basic","Cool","Cry","Err","Evil","Kiss","Laugh","Shame" ,"Toungh","Wink","Wonder"}; public int[] pic =new int[]{ R.drawable.ic_action_emo_angry, R.drawable.ic_action_emo_basic, R.drawable.ic_action_emo_cool, R.drawable.ic_action_emo_cry, R.drawable.ic_action_emo_err, R.drawable.ic_action_emo_evil, R.drawable.ic_action_emo_kiss, R.drawable.ic_action_emo_laugh, R.drawable.ic_action_emo_shame, R.drawable.ic_action_emo_tongue, R.drawable.ic_action_emo_wink, R.drawable.ic_action_emo_wonder }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>(); for(int i=0;i<10;i++){ HashMap<String, String> hm = new HashMap<String,String>(); hm.put("sml", " " + smily[i]); hm.put("pic", Integer.toString(pic[i]) ); aList.add(hm); } String[] from = { "pic","sml" }; int[] to = { R.id.smily,R.id.txt}; SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.list_layout, from, to); final ListView listView = ( ListView ) findViewById(R.id.listView1); listView.setAdapter(adapter); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub Intent intent = new Intent(MainActivity.this,Descripsn.class); Bundle b =new Bundle(); intent.putExtra("smily", smily[arg2]); intent.putExtra("image", pic[arg2]); startActivity(intent); } }); } } desc.jav package com.example.androidlistview; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.widget.ImageView; import android.widget.TextView; public class Descripsn extends Activity { TextView tv; ImageView im; private MainActivity main = new MainActivity(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_descripsn); tv=(TextView)findViewById(R.id.textView1); im=(ImageView)findViewById(R.id.imagedesc); Intent i =getIntent(); Bundle b= getIntent().getExtras(); String smily = b.getString("smily"); int img = b.getInt("image"); String imgpos = b.getString("pos"); System.out.println("Image value"+img); //System.out.println("======Posi::::::"+smily); tv.setText(smily); im.setBackgroundResource(img); } }
doc_23529877
Step 1) Global setup: Set up git git config --global user.name "MyName" git config --global user.email MyName@gmail.com Next steps: mkdir Java cd Java git init touch README git add README git commit -m 'first commit' git remote add origin git@github.com:MyName/Java.git git push -u origin master Existing Git Repo? cd existing_git_repo git remote add origin git@github.com:MyName/Java.git git push -u origin master Step 2) NetBeans IDE trying to setup the link as git@github.com:MyName/Java.git Now it gives error as you can see above. How do i setup this? Follow up: (above process did not worked) $ create a project > cd /var/tmp/newproject $ sudo git remote add origin git@github.com:me/newproject.git $ ls -a . .. build build.xml dist .git .gitignore manifest.mf nbproject src $ Open netbeans > Automatically it detects > origin:git@github.com:me/newproject.git > press next > local branch > select master > press next > press finish Works! A: Open your terminal, enter your project root fold, and add your remote: $ cd path/to/your/projcet $ git remote add origin git@github.com:me/java.git I think it should detect your setting, then check how your IDE set your github repository. A: Github setup is so easy with netbeans IDE. Follow the steps.. 1 - Go github and create a repository, and copy URL like https://github.com/akatkar/.... 2 - Open Netbeans IDE. If GIT plugin is not installed, install from tools/plugin 3 - From Netbeans Team menu click clone 4 - Paste your URL as repository URL, provide your github user name and password 5 - Netbeans IDE will clone your repository and will ask to create a new application 6 - Create an application and copy or create your source files in this application 7 - Commit changes and push to the remote 8 - DONE. Check from github your changes and enjoy... A: Try prefixing ssh:// to the repository url, but I suspect the real reason is that you have not configured the private key (the one that matches the public key which you should have added to your github account) for authentication. A: You have to select the private key, not the public one. A: For anyone at this page with similar issues common problems with netbeans ide: If you have two factor authentication switched on in your github security settings netbeans can not handle this. If you use git bash cli it will popup with a login box and two factor code entry. Also check your config file in the .git/ folder as netbeans can change git@github to [yourusername]@github.com in the url path which you can edit in this config file back to git@github.com. These changes should allow you to push to a remote repository. A: As of Friday the 13th in August 2021, github changed some of the authentication rules. This can foul up IDEs. Update your installed version of git if you haven't already. Test for authentication problems by opening a command prompt, changing to the directory with your repository (it has a hidden '.git' directory), and attempting to manually push as described in the help from the original post: git push -u origin master. If there is an authentication issue, you should see a GUI prompting for credentials.
doc_23529878
I have gone through some of the posts related to this: Python subprocess - run a second command in the new command prompt created How to run multiple commands synchronously from one subprocess.Popen command? Even I have tried with os command as: https://www.quora.com/How-do-I-control-command-prompt-by-using-python-scripts With proc = subprocess.Popen(['cli', '--log=cli.log', '--log-level=debug2'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) It seems that 'cli' is running in background and some input is awaited but when I check with ps command, no cli command exist in background and also I get error: tcgetattr: Inappropriate ioctl for device at command line. If I add stderr=subprocess.PIPE, the process gets existed immediately.
doc_23529879
doc_23529880
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll Additional information: Conversion from string "Holden 308" to type 'Integer' is not valid. Additional information: Conversion from string "JD Catepillar Track" to type 'Integer' is not valid. So both errors are happening in the HeavyStockItem class with the overloading New classes. Wondering if anyone can help me out with understanding why it's doing that. Option Strict On Public Class Form1 Dim StockItem1 As StockItem Dim StockItem2 As CarEngine Dim StockItem3 As CarEngine Dim StockItem4 As StockItem Dim StockItem5 As HeavyStockItem Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load StockItem1 = New StockItem("Screwdriver Set", 42) StockItem2 = New CarEngine(8025, "Madza B6T", 1252, 800, "Z4537298D") 'StockItem3 = New CarEngine("Holden 308", 958, 1104, "P74623854S") StockItem4 = New StockItem(8002, "Trolley Jack", 127) 'StockItem5 = New HeavyStockItem("JD Catepillar Track", 3820, 2830) End Sub Private Sub btnListStock_Click(sender As Object, e As EventArgs) Handles btnListStock.Click txtOutput.Clear() ShowOutput(StockItem1) ShowOutput(StockItem2) 'ShowOutput(StockItem3) ShowOutput(StockItem4) 'ShowOutput(StockItem5) End Sub Public Sub ShowOutput(ByVal Output As StockItem) txtOutput.Text &= Output.Print() txtOutput.Text &= vbCrLf End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnEnd.Click End End Sub End Class Public Class StockItem Friend CostPrice As Integer Friend LastStockNumber As Integer Friend StockNumber As Integer Friend Description As String Friend Shared LastStockItem As Integer = 10000 Overridable Function Print() As String Dim Result As String = "" Result &= "Stock No: " & StockNumber Result &= vbCrLf Result &= "Description: " & Description Result &= vbCrLf Result &= "Cost Price: " & CostPrice Result &= vbCrLf Return Result End Function Public Sub New(ByVal StockNumber As Integer, Description As String, ByVal CostPrice As Integer) Me.New(Description, CostPrice) Me.StockNumber = StockNumber End Sub Public Sub New(ByVal Description As String, ByVal CostPrice As Integer) LastStockNumber += Rnd() Me.StockNumber = LastStockNumber Me.Description = Description Me.CostPrice = CostPrice End Sub Public Sub GetCostPrice() End Sub End Class Public Class HeavyStockItem Inherits Assessment3.StockItem Friend Weight As Integer Public Function GetWeight() As String Return Me.GetWeight End Function Public Sub New(ByVal StockNumber As Integer, ByVal Description As String, ByVal CostPrice As Integer, ByVal Weight As Integer) MyBase.New(StockNumber, Description, CostPrice) Me.Weight = Weight End Sub Public Sub New(ByVal Description As String, ByVal CostPrice As Integer, ByVal Weight As Integer) MyBase.New(Description, CostPrice, Weight)'' Where the error is occurring LastStockNumber += Rnd() Me.StockNumber = LastStockNumber End Sub End Class Public Class CarEngine Inherits Assessment3.HeavyStockItem Friend EngineNumber As String Overrides Function Print() As String Dim Result As String = "" Result &= "Stock No: " & StockNumber Result &= vbCrLf Result &= "Description: " & Description Result &= vbCrLf Result &= "Cost Price: " & CostPrice Result &= vbCrLf Result &= "Weight: " & Weight Result &= vbCrLf Result &= "Engine Number: " & EngineNumber Result &= vbCrLf Return Result End Function Public Sub New(ByVal StockNumber As Integer, ByVal Description As String, ByVal CostPrice As Integer, ByVal Weight As Integer, ByVal EngineNumber As String) MyBase.New(StockNumber, Description, CostPrice, Weight) Me.EngineNumber = EngineNumber End Sub Public Sub New(ByVal Description As String, ByVal CostPrice As Integer, ByVal Weight As Integer, ByVal EngineNumber As String) MyBase.New(Description, CostPrice, Weight) LastStockNumber += Rnd() Me.StockNumber = LastStockNumber End Sub End Class Any help provided would be great. Just thought it'd be easier to provide the full code instead of just putting only the little bits that I really needed, incase if people asked about the other parts of the code. Thanks for reading and providing help if you provided help. A: Since your code was confusing to me I relied mostly on the exception. It basically says that it cant convert the string into an integer. Here's something that could cause the same problem. Dim Number As String = "10" 'Few Lines of code. Number = 11 whats basically happening is that when you declare a variable as a string the value of it HAS to be in double quotes as you see when it was declared. Now then we try to change the value to 11 while adding no double quotes, therefor it thought you were changing it to an integer and gave the error. I looked through the code and saw this, maybe this is causing it: Me.Description = Description <--- No quotes!!! I'm probably wrong though since i didn't really understand the code.
doc_23529881
Inside the form, i need to access the scroll down inside the div of the request travel form. I tried using: browser.executeScript("window.scrollTo(0,10000);").then(callback); However, the scrollbar that it access is the browser itself not the div i intended to scroll down. Any leads or suggestion is greatly appreciate. Thanks! A: I had same issue with my application. There is no direct way using which you can scroll inside scrollbar but I achieved it using javacript executor. Option 1:- You can select element till which you wanted to scroll. example:- (replace with your actual identifier) browser.executeScript('arguments[0].scrollIntoView(true)', <yourelement>.getWebElement()); Option 2:- Find the identifier of element on which scrollbar is applied and use below code. var objDiv = document.getElementById("divExample"); objDiv.scrollTop = objDiv.scrollHeight; let me know if still facing issue.
doc_23529882
MY_Controlle.php <?php class MY_Controller extends MX_Controller { function __construct() { parent::__construct(); $this->load->module('Template'); } } Admin.php <?php class Admin extends MY_Controller { function __construct() { parent::__construct(); } function index() { $data['content_view'] = 'admin/admin_v'; $this->Template->sample_template($data); } function about() { $data['content_view'] = 'admin/about_v'; $this->Template->sample_template($data); } } Template.php <?php class Template extends MY_Controller { function __construct() { parent::__construct(); } function sample_template($data = NULL) { $this->load->view('Template/sample_template_v', $data); } } sample_template_v.php file----> <h5>This is the main Template.</h5> <?php $this->load->view($content_view); ?> Error: A: If you want to call a method from the object you need to initiaze the object and then call a method. Make sure $this->template is set in your case it isn't. $this->template = new Template(); $this->template->sample_template($data);
doc_23529883
I'm trying to graph two data sets (One is in Feet and one is in degrees) in such a way that they can be compared (they do share a common x-axis value). As you can see my data seems to be interlaced correctly but I'm having trouble getting the yAxises to behave as I'd like. I would like the X-Axis Max/Min to actually line up with both Y-Axises. My code is as follows: - (void)initPlot { [self loadCoreData]; [self configureHost]; [self configureGraph]; [self configurePlots]; [self configureAxes]; } - (void)configureHost { self.hostView = [(CPTGraphHostingView *) [CPTGraphHostingView alloc] initWithFrame:self.view.bounds]; self.hostView.allowPinchScaling = YES; [self.view addSubview:self.hostView]; } - (void)configureGraph { // 1 - Create the graph CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:self.hostView.bounds]; [graph applyTheme:[CPTTheme themeNamed:kCPTDarkGradientTheme]]; self.hostView.hostedGraph = graph; // 2 - Set graph title NSString *title = [NSString stringWithFormat:@"Altitude Plot [%@ to %@]", self.flightRecording.originAirport, self.flightRecording.destinationAirport]; graph.title = title; // 3 - Create and set text style CPTMutableTextStyle *titleStyle = [CPTMutableTextStyle textStyle]; titleStyle.color = [CPTColor whiteColor]; titleStyle.fontName = @"Helvetica-Bold"; titleStyle.fontSize = 16.0f; graph.titleTextStyle = titleStyle; graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop; graph.titleDisplacement = CGPointMake(0.0f, -20.0f); // 4 - Set padding for plot area float padding = 10.0f; [graph.plotAreaFrame setPaddingLeft:padding]; [graph.plotAreaFrame setPaddingBottom:50.0f]; [graph.plotAreaFrame setPaddingRight:padding]; [graph.plotAreaFrame setPaddingTop:padding]; // 5 - Enable user interactions for plot space altSpace= (CPTXYPlotSpace *) graph.defaultPlotSpace; altSpace.allowsUserInteraction = NO; rollSpace = [[CPTXYPlotSpace alloc] init]; rollSpace.allowsUserInteraction = NO; [self.hostView.hostedGraph addPlotSpace:rollSpace]; // // pitchSpace = [[CPTXYPlotSpace alloc] init]; // pitchSpace.allowsUserInteraction = NO; // [self.hostView.hostedGraph addPlotSpace:pitchSpace]; // // // slipSpace = [[CPTXYPlotSpace alloc] init]; // slipSpace.allowsUserInteraction = NO; // [self.hostView.hostedGraph addPlotSpace:slipSpace]; // // // gSpace = [[CPTXYPlotSpace alloc] init]; // gSpace.allowsUserInteraction = NO; // [self.hostView.hostedGraph addPlotSpace:gSpace]; } - (void)configurePlots { // 1 - Get graph and plot space CPTGraph *graph = self.hostView.hostedGraph; // 2 - Create the three plots // Custom AHRS Plot CPTScatterPlot *ahrsAltPlot = [[CPTScatterPlot alloc] init]; ahrsAltPlot.dataSource = self; ahrsAltPlot.identifier = @"AHRSALT"; CPTColor *ahrsAltColor = [CPTColor yellowColor]; [graph addPlot:ahrsAltPlot toPlotSpace:altSpace]; CPTScatterPlot *rollPlot = [[CPTScatterPlot alloc] init]; rollPlot.dataSource = self; rollPlot.identifier = @"ROLL"; CPTColor *rollColor = [CPTColor greenColor]; [graph addPlot:rollPlot toPlotSpace:rollSpace]; // 3 - Set up plot space CPTMutablePlotRange *xRange = [altSpace.xRange mutableCopy]; xRange=[CPTMutablePlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0f ) length:CPTDecimalFromFloat(maxEpoch + 300.0f )]; // [xRange expandRangeByFactor:CPTDecimalFromCGFloat(1.1f)]; altSpace.xRange = xRange; CPTMutablePlotRange *yRange = [altSpace.yRange mutableCopy]; yRange = [CPTMutablePlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0f) length:CPTDecimalFromFloat(maxAlt)]; [yRange expandRangeByFactor:CPTDecimalFromCGFloat(1.2f)]; altSpace.yRange = yRange; rollSpace.xRange = xRange; CPTMutablePlotRange *yRangeRoll =[CPTMutablePlotRange plotRangeWithLocation:CPTDecimalFromFloat(0 ) length:CPTDecimalFromFloat(40 )]; [yRangeRoll expandRangeByFactor:CPTDecimalFromCGFloat(1.2f)]; rollSpace.yRange = yRangeRoll; [altSpace scaleToFitPlots:[NSArray arrayWithObjects:ahrsAltPlot, nil] ]; [rollSpace scaleToFitPlots:[NSArray arrayWithObjects:rollPlot, nil] ]; [rollSpace setYRange:yRangeRoll]; // 4 - Create styles and symbols // AHRS Style CPTMutableLineStyle *ahrsLineStyle = [ahrsAltPlot.dataLineStyle mutableCopy]; ahrsLineStyle.lineWidth = 2.5; ahrsLineStyle.lineColor = [CPTColor blueColor]; ahrsAltPlot.dataLineStyle = ahrsLineStyle; } - (void)configureAxes { // 1 - Create styles CPTMutableTextStyle *axisTitleStyle = [CPTMutableTextStyle textStyle]; axisTitleStyle.color = [CPTColor whiteColor]; axisTitleStyle.fontName = @"Helvetica-Bold"; axisTitleStyle.fontSize = 12.0f; CPTMutableLineStyle *axisLineStyle = [CPTMutableLineStyle lineStyle]; axisLineStyle.lineWidth = 2.0f; axisLineStyle.lineColor = [CPTColor whiteColor]; CPTMutableTextStyle *axisTextStyle = [[CPTMutableTextStyle alloc] init]; axisTextStyle.color = [CPTColor whiteColor]; axisTextStyle.fontName = @"Helvetica-Bold"; axisTextStyle.fontSize = 11.0f; CPTMutableLineStyle *tickLineStyle = [CPTMutableLineStyle lineStyle]; tickLineStyle.lineColor = [CPTColor whiteColor]; tickLineStyle.lineWidth = 2.0f; CPTMutableLineStyle *gridLineStyle = [CPTMutableLineStyle lineStyle]; tickLineStyle.lineColor = [CPTColor blackColor]; tickLineStyle.lineWidth = 1.0f; // 2 - Get axis set CPTXYAxisSet *axisSet = (CPTXYAxisSet *) self.hostView.hostedGraph.axisSet; // 3 - Configure x-axis CPTAxis *x = axisSet.xAxis; x.title = @"Flight Time"; x.titleTextStyle = axisTitleStyle; x.titleOffset = 15.0f; x.axisLineStyle = axisLineStyle; x.labelingPolicy = CPTAxisLabelingPolicyNone; x.labelTextStyle = axisTextStyle; x.majorTickLineStyle = axisLineStyle; x.majorTickLength = 4.0f; x.tickDirection = CPTSignNegative; NSMutableSet *xLabels = [NSMutableSet new]; NSMutableSet *xLocations = [NSMutableSet new]; NSInteger i = 0; for (i; i < maxEpoch; i += 600) { int hour = i / (68 * 60); int min = i / 60; CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:[NSString stringWithFormat:@"%02d:%02d", hour, min] textStyle:x.labelTextStyle]; CGFloat location = i++; label.tickLocation = CPTDecimalFromCGFloat(location); label.offset = x.majorTickLength; if (label) { [xLabels addObject:label]; [xLocations addObject:[NSNumber numberWithInteger:i]]; } } x.axisLabels = xLabels; x.majorTickLocations = xLocations; // 4 - Configure y-axis CPTAxis *y = axisSet.yAxis; y.title = @"Altitude in Feet"; y.titleTextStyle = axisTitleStyle; y.titleOffset = 20.0f; y.axisLineStyle = axisLineStyle; y.majorGridLineStyle = gridLineStyle; y.labelingPolicy = CPTAxisLabelingPolicyNone; y.labelTextStyle = axisTextStyle; y.labelOffset = 21.0f; y.majorTickLineStyle = axisLineStyle; y.majorTickLength = 20.0f; y.minorTickLength = 10.0f; y.tickDirection = CPTSignNegative; // Axis #2 CPTXYAxis *yRoll = [[CPTXYAxis alloc] init]; yRoll.title = @"Degrees"; // Styling yRoll.titleTextStyle = axisTitleStyle; yRoll.labelTextStyle = axisTextStyle; yRoll.axisLineStyle = axisLineStyle; yRoll.majorTickLineStyle = axisLineStyle; yRoll.plotSpace = rollSpace; yRoll.delegate = self; yRoll.labelingPolicy = CPTAxisLabelingPolicyNone; yRoll.coordinate = CPTCoordinateY; yRoll.tickDirection = CPTSignNone; yRoll.separateLayers = NO; yRoll.tickDirection = CPTSignNegative; yRoll.labelOffset = 21.0f; yRoll.axisConstraints = [CPTConstraints constraintWithLowerOffset:40.0]; yRoll.orthogonalCoordinateDecimal = CPTDecimalFromFloat(0.0f); NSMutableSet *rollLabels = [NSMutableSet new]; NSMutableSet *rollLocations = [NSMutableSet new]; for (int i =0; i <= 40; i+= 5) { CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:[NSString stringWithFormat:@"%02d˚", (i - 20)] textStyle:yRoll.labelTextStyle]; CGFloat location = i; label.tickLocation = CPTDecimalFromCGFloat(location); label.offset = -16.0f; if (label) { [rollLabels addObject:label]; [rollLocations addObject:[NSNumber numberWithInteger:i]]; } } yRoll.axisLabels = rollLabels; yRoll.majorTickLocations = rollLocations; NSInteger majorIncrement = 500; NSInteger minorIncrement = 100; CGFloat yMax = maxAlt; // should determine dynamically based on max price NSMutableSet *yLabels = [NSMutableSet set]; NSMutableSet *yMajorLocations = [NSMutableSet set]; NSMutableSet *yMinorLocations = [NSMutableSet set]; for (NSInteger j = minorIncrement; j <= yMax; j += minorIncrement) { NSUInteger mod = j % majorIncrement; if (mod == 0) { CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:[NSString stringWithFormat:@"%i ft", j] textStyle:y.labelTextStyle]; NSDecimal location = CPTDecimalFromInteger(j); label.tickLocation = location; label.offset = -y.majorTickLength - y.labelOffset; if (label) { [yLabels addObject:label]; } [yMajorLocations addObject:[NSDecimalNumber decimalNumberWithDecimal:location]]; } else { [yMinorLocations addObject:[NSDecimalNumber decimalNumberWithDecimal:CPTDecimalFromInteger(j)]]; } } // Position the y2 axis // y2.axisConstraints = [CPTConstraints constraintWithUpperOffset:40.0]; axisSet.yAxis.axisConstraints = [CPTConstraints constraintWithUpperOffset:40.0]; y.axisLabels = yLabels; y.majorTickLocations = yMajorLocations; y.minorTickLocations = yMinorLocations; self.hostView.hostedGraph.axisSet.axes = [NSArray arrayWithObjects:x,y,yRoll,nil]; // Position floating YAxis // y2.axisConstraints = [CPTConstraints constraintWithUpperOffset:150.0]; } EDIT:: I tried adding the following lines and they did nothing either y.orthogonalCoordinateDecimal = CPTDecimalFromFloat(0.0f); x.orthogonalCoordinateDecimal = CPTDecimalFromFloat(0.0f); I seem to be making progress actually: It appears that if I remove yAxis2.axisConstraints = [CPTConstraints constraintWithLowerOffset:40.0]; Then my axis actually seems to pin to the x-axis (although its off the screen) now but its a start. A: Problem Solved: I had some conflicting directives going on. In order to achieve what I needed I had to use the two calls: yAxis2.orthogonalCoordinateDecimal = CPTDecimalFromFloat(0.0f); y.orthogonalCoordinateDecimal = CPTDecimalFromFloat(maxEpoch); // maximum X value x.orthogonalCoordinateDecimal = CPTDecimalFromFloat(0.0f); Then in order to make sure everything could be seen correctly I had to play with the padding values: float padding = 50.0f; [graph.plotAreaFrame setPaddingLeft:padding]; [graph.plotAreaFrame setPaddingBottom:50.0f]; [graph.plotAreaFrame setPaddingRight:padding]; [graph.plotAreaFrame setPaddingTop:padding]; And I had to remove all the constraints that were messing with things: // yAxis2.axisConstraints = [CPTConstraints constraintWithLowerOffset:40.0]; // y.axisConstraints = [CPTConstraints constraintWithUpperOffset:150.0];
doc_23529884
Setting UNICODE is presumably the way forward but will require a massive code change, whereas quite a lot seems to work simply by setting System Locale to Japan (in “Window’s Language for non-Unicode programs” setting). I have no idea how Windows does this, but some Japanese character things now work on my English Windows PC, e.g. I can open and save Japanese filenames with no code changes. And in Japan they set System Locale to English and again much works, but not everything. I get the impression the problems are due to using a font that doesn’t include Japanese characters. Currently I am using Arial / MS Sans Serif and charset set to ANSI_CHARSET or DEFAULT_CHARSET. Is there a different font I should be using, or can I extend these fonts to include Japanese characters? Or am I barking up the wrong tree in which case what do I do next? Am very new to all this unfortunately … A: That's a common question (OK I guess not so common any more in 2015, as MBCS programs luckily are a dying breed - I still maintain several though...) Either way, I'm afraid that, depending on your definition of 'working', to get this working you'll have to bite the bullet and convert to a Unicode build. If you can't make a business case for that, then you'll have to set the right locale (well, worse, have the user set the 'right' one) and test what works and what doesn't, and ask more specific questions on what doesn't. If your goal is to make one application that correctly displays strings in various encodings in the 'right' way regardless of the locale settings on the computer, and compatible with every input data set / database content without the user having to be aware of encoding issues, then you're out of luck with an MBCS build. The font missing characters is most likely not the problem. Before you go any further and/or ask further questions, you should read http://www.joelonsoftware.com/articles/Unicode.html, read it again, sleep on it, read it again, explain to somebody else what the relationship is between 'encoding', 'locale', 'character set', 'font' and 'Unicode code point', because only after you can do that, you can decide on how to progress with your application. Sorry, it's not what you want to hear, but it's the reality if you've been tasked with handling internationalization.
doc_23529885
A: This also might be useful - http://tympanus.net/codrops/2010/06/02/smooth-vertical-or-horizontal-page-scrolling-with-jquery/ A: A long time ago I used this effect here: http://tudimojemesto.si/ Apparently the script I used was jquery.localscroll.js --> http://flesler.blogspot.com/2007/10/jquerylocalscroll-10.html From what I remember (been a few years) this wasn't very complicated to implement even though this was probably my first or second jQuery project.
doc_23529886
app.UseFacebookAuthentication(new FacebookAuthenticationOptions() { AppId = "xx", AppSecret = "xxx", Scope = { "email", "public_profile" } }); This code was working fine and returning me the email address with older facebook app with api version 2.3. But now with the api version2.4, it is not returning email. It is asking user for permission to share email bur not returning email in login info. Is there any modification with api 2.4 which I am missing ?? Please suggest. Thanks in advance . . A: I would imagine that the Owin Facebook authentication needs an update. The current version was updated in Feb 2015, prior to v2.4 of the Graph API. With v2.3 and below calling https://graph.facebook.com/v2.3/me would have returned email, name, id, gender etc. In v2.4 this will just return name and in v2.4 this will just return name and id. https://graph.facebook.com/v2.4/me { "name": "Name Returned", "id": "1343143144321" } Therefore If you require the email address you will need to implement your own fix in your code. In your server side implementation request the email address to be specifically returned https://graph.facebook.com/v2.4/me?fields=email&access_token=
doc_23529887
Edit Wanted to make it more concrete Dataframe x: Id year var1 1 2010 100 1 2011 105 1 2012 110 2 2010 100 2 2011 105 2 2012 106 Dataframe y: Id year var2 var3 1 2010 5 7 1 2011 10 8 2 2010 9 6 Desired merge: Id year var1 var2 var3 1 2010 100 5 7 1 2011 105 10 8 1 2012 110 10 8 2 2010 100 9 6 2 2011 105 9 6 2 2012 106 9 6 A: I'd do this in two steps: > out <- merge(x, y, all.x=T) > out Id year var1 var2 var3 1 1 2010 100 5 7 2 1 2011 105 10 8 3 1 2012 110 NA NA 4 2 2010 100 9 6 5 2 2011 105 NA NA 6 2 2012 106 NA NA Then use na.locf from the zoo package: library(zoo) > apply(out, 2, na.locf) Id year var1 var2 var3 [1,] 1 2010 100 5 7 [2,] 1 2011 105 10 8 [3,] 1 2012 110 10 8 [4,] 2 2010 100 9 6 [5,] 2 2011 105 9 6 [6,] 2 2012 106 9 6 and this can be coerced to a data.frame easily enough. > as.data.frame(apply(out, 2, na.locf)) Id year var1 var2 var3 1 1 2010 100 5 7 2 1 2011 105 10 8 3 1 2012 110 10 8 4 2 2010 100 9 6 5 2 2011 105 9 6 6 2 2012 106 9 6 A: This doesn't use merge, but loops through the rows of x one at a time to find the appropriate match in y. Probably not efficient, but it works. do.call(rbind, lapply(seq(length=nrow(x)), function(r) { yid <- y[y$Id==x$Id[r],] yeardiff <- x$year[r] - yid$year yeardiff[yeardiff < 0] <- NA cbind(x[r,], yid[which.min(yeardiff),]) })) The result is Id year var1 Id year var2 var3 1 1 2010 100 1 2010 5 7 2 1 2011 105 1 2011 10 8 3 1 2012 110 1 2011 10 8 4 2 2010 100 2 2010 9 6 5 2 2011 105 2 2010 9 6 6 2 2012 106 2 2010 9 6
doc_23529888
and how represent three proxies servers of ims in one node ?
doc_23529889
Before: After: I change the content of my button "Browse file" to "Replace File" This is my html code. <div id="uploadModal" class="upload-modal"> <div class="modal-content"> <h2 style="font-size: 24px;">Choose file</h2> <p> Choose the csv file containing the data you want to create a forecast for. </p> <div class="browse-file"> <div id="filename"></div> <input type="file" id="file-upload" multiple required /> <label for="file-upload">Browse file</label> </div> <div class="options"> <button class="cancel"><h4>Cancel</h4></button> <button class="proceed"><h4>Proceed</h4></button> </div> </div> </div> Here is my CSS .upload-modal { display: none; position: fixed; padding-top: 100px; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0, 34, 2, 0.3); } input[type="file"] { position: absolute; opacity: 0; z-index: -1; } input + label { padding: 10px 24px; background: #D4E8CF; border-radius: 100px; position: static; width: 119px; height: 40px; border: none; cursor: pointer; z-index: 1; } #filename{ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 100px; justify-content: left; align-items: flex-start; } What's happening here is that my button moves according to the length of the file so I added max-width but no luck. Thanks! EDIT: I added css for upload-modal A: I'm not sure you need to use absolute positioning for what you want. You could set div#upload-modal or div.modal-content to position: relative; and then position the button element with left: or right: or use float: right; https://developer.mozilla.org/en-US/docs/Web/CSS/position https://developer.mozilla.org/en-US/docs/Web/CSS/float A: This alternate version uses CSS's Flexbox and JavaScript's Event Listeners. It probably doesn't do precisely what you want but should come close enough that reading through the comments a few times and playing around with the code should make clear how you can get to where you want to go using just a few lines of JavaScript to grab the file name and show it on the screen. MDN (linked above) is a great place to get more clarity about any particular front-end feature that you're interested in using. Happy coding! // Unnamed function runs as soon as the DOM elements are ready window.addEventListener('DOMContentLoaded', () => { // Identifies some of the DOM elements const filenameSpan = document.getElementById("filename-span"), fileInput = document.getElementById("file-input"), chooseBtn = document.getElementById("choose-btn"); // When the input changes (when a file is chosen), calls `updateDisplay` fileInput.addEventListener("change", updateDisplay); // Defines `updateDisplay` function updateDisplay(){ // Puts first fiename in span and "unhides" it const filename = fileInput.files[0]?.name; filenameSpan.textContent = filename || "(choose file)"; filenameSpan.classList.remove("hidden"); }; }); *{ margin: 0; } #container{ width: 18rem; /* "rem" unit is the base character height */ padding: 2rem; border-radius: 1.5rem; background-color: lightgrey; } #header{ margin-bottom: 2rem; } #chooser{ /* flex w/ space-around makes choose-btn shift right when filename appears */ display: flex; justify-content: space-around; margin-bottom: 4rem; } #options{ text-align: right; } #filename-span{ padding: 1rem 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 6rem; } button{ /* the "options" buttons */ border: none; font-weight: bold; color: darkgreen; background-color: lightgrey; } #choose-btn{ /* Not a true "button" element -- the "label" for file-input */ padding: 1rem 1.5rem; background-color: darkseagreen; border-radius: 2rem; border: none; font-weight: bold; } .hidden{ /* Uses a class so all styling happens thru CSS */ display: none; } <div id="container"> <div id="header"> <h2>Choose file</h2> <p> Choose the csv file containing the data you want to create a forecast for</p> </div> <div id="chooser"> <!-- The span and input elements are initially "hidden" via CSS --> <span id="filename-span" class="hidden"></span> <label id="choose-btn"> <!-- input element is inside its stylable & clickable label --> Browse File <input id="file-input" type="file" class="hidden" /> </label> </div> <div id="options"> <button id="cancel-btn">Cancel</button> <button id="proceed-btn">Proceed</button> </div> </div>
doc_23529890
In airflow2, I am using the operator BeamRunPythonPipelineOperator, and one of the requirements is to store data in GCS, following this pattern: gs://datalate/data_source/YYYY/MM/model. partition_sessions_unlimited = BeamRunPythonPipelineOperator( task_id="partition_sessions_unlimited", dag=aggregation_dag, py_file=os.path.join( BEAM_SRC_DIR, "streaming_sessions", "streaming_session_aggregation_pipeline.py", ), runner="DataflowRunner", dataflow_config=DataflowConfiguration( job_name="%s_partition_sessions_unlimited" % ds_env, project_id=GCP_PROJECT_ID, location="us-central1", ), pipeline_options={ "temp_location": "gs://dataflow-temp/{}/{}/amazon_sessions/amz_unlimited".format( sch_date, ds_env ), "staging_location": "gs://dataflow-staging/{}/{}/amazon_sessions/amz_unlimited".format( sch_date, ds_env ), "disk_size_gb": "100", "num_workers": "10", "num_max_workers": "25", "worker_machine_type": "n1-highcpu-64", "setup_file": os.path.join( BEAM_SRC_DIR, "streaming_sessions", "setup.py" ), "input": "gs://{}/amazon_sessions/{{ ds_nodash[:4] }}/{{ ds_nodash[4:6] }}/amz_unlimited/input/listens_*".format( w_datalake, ), "output": "gs://{}/amazon_sessions/{{ ds_nodash[:4] }}/{{ ds_nodash[4:6] }}/amz_unlimited/output/sessions_".format( w_datalake ), }, ) however, I get 'output': 'gs://datalake/amazon_sessions/{ ds_nodash[:4] }/{ ds_nodash[4:6] }/amz_prime/output/sessions_', instead of 'output': 'gs://datalake/amazon_sessions/2022/02/amz_prime/output/sessions_', How can I achieve this? A: First, you are using a format string for jinja templated field. format() will replace {var} to value from params that are passed, if it exists. "gs://{}/.../{{ ds_nodash[:4] }}...".format(w_datalake) First {} is replaced with "datalake" and 2nd part doesn't have any equivalent param that is passed, so resulted in the literal "ds_nodash[:4]". "gs://datalake/.../{ds_nodash[:4]}..." In order to use jinja template within the formatted string, you can escape the { and } for part you are intended to get value from jinja. To escape { you add another {, and for } you add another }. Original one has 2 {{ so add 2 { on each side like this; "gs://{}/.../{{{{ ds_nodash[:4] }}}}...".format(w_datalake) With this, format will be applied first (replacing the value and take out the escape symbol) and turned this string to gs://datalake/.../{{ ds_nodash[:4] }}... then this string is passed to BeamRunPythonPipelineOperator where this part is converted with jinja fields. Secondly, instead of using ds_nodash twice with slicing, you can use execution_date to format as you like {{ execution_date.strftime('%Y/%m') }}
doc_23529891
The jsp fragment is: <div class="col-sm-12"> <div class="col-xs-12 col-sm-4"> <arch:fondoListerGridItem serie="${serie}" fondo="${fondoPageData}" /> </div> <div class="col-sm-4 "> <div style="display: table;position: absolute;height: 33%;width: 100%;"> <div style="display: table-cell;vertical-align: middle;"> <p> <b><spring:theme code="text.fondo" />:</b> ${fondoPageData.fondo}<br> <b><spring:theme code="text.serie" />:</b> ${serie.titolo} </p> </div></div> </div> </div> In Chrome and IE browsers the result is this: with the image and the text aligned in the middle of the table. In Firefox instead the result is: and the text is aligned on the top. I saw from the developer consolle that the solution could be: <div style="display: table;position: relative;height: 33%;width: 100%;"> <div style="display: table-cell;vertical-align: middle;"> for Chrome and IE, but <div style="display: table;position: relative;height: 33%;width: 100%;"> <div style="display: table-cell;vertical-align: bottom;"> for Firefox. How could I do this in the JSP file? A: I resolved replacing vertical-align: middle; with padding-top: 50%; This works on both browsers!
doc_23529892
<script type="text/html" id="dropDownTextBoxTemplate"> <div class="top-level-div-class"> <p class="paragraph-class"> <div> <label data-bind="text: DisplayValue"></label> </div> <div> <select data-bind="attr: { id: Name, name: Name }, options: Comparisons, optionsValue: 'Name', optionsText: 'DisplayValue', optionsCaption: 'Unselected', value: SelectedComparison"></select> <!-- ko if: SelectedComparison() === undefined --> <input type="text" disabled="disabled" data-bind="attr: { id: Name + '-value', name: Name + '-value', 'data-min-value': TextboxMinValue, 'data-max-value': TextboxMaxValue, 'data-format': TextboxFormat }, value: TextboxValue" /> <!-- /ko --> <!-- ko ifnot: SelectedComparison() === undefined --> <input type="text" data-bind="attr: { id: Name + '-value', name: Name + '-value', 'data-min-value': TextboxMinValue, 'data-max-value': TextboxMaxValue, 'data-format': TextboxFormat }, value: TextboxValue" /> <!-- /ko --> </div> </p> </div> </script> The change I made was to add the div tags around the label, select and input controls. Here is the HTML that is rendered. <div class="top-level-div-class"> <p class="paragraph-class"></p> <div> <label data-bind="text: DisplayValue">My Display Value:</label> </div> <div> <select data-bind="attr: { id: Name, name: Name }, options: Comparisons, optionsValue: 'Name', optionsText: 'DisplayValue', optionsCaption: 'Unselected', value: SelectedComparison" id="attendence" name="attendence"> <option value="">Unselected</option> <option value="gtet">Greater than or equal to</option> <option value="ltet">Less than or equal to</option> </select> <!-- ko if: SelectedComparison() === undefined --> <input type="text" disabled="disabled" data-bind="attr: { id: Name + '-value', name: Name + '-value', 'data-min-value': TextboxMinValue, 'data-max-value': TextboxMaxValue, 'data-format': TextboxFormat }, value: TextboxValue" id="attendence-value" name="attendence-value" data-min-value="0" data-max-value="99" data-format="range"> <!-- /ko --> <!-- ko ifnot: SelectedComparison() === undefined --> <!-- /ko --> </div> <p></p> </div> As you can see the paragraph tag is rendered by itself instead of being around the content as it is in the template. When the extra div's are removed the paragraph tag renders around all of the other content, which is the desired HTML output, but when I do that the UI elements don't align properly. I have tried replacing the extra div's with span tags and the HTML does render properly but once again the UI controls are out of alignment. Any help would be appreciated. A: Try using the paragraph tag as div. Its not allowed to enclose divs inside paragraph tags. here is the change you should try. <script type="text/html" id="dropDownTextBoxTemplate"> <div class="top-level-div-class"> <div class="paragraph-class"> <div> <label data-bind="text: DisplayValue"></label> </div> <div> <select data-bind="attr: { id: Name, name: Name }, options: Comparisons, optionsValue: 'Name', optionsText: 'DisplayValue', optionsCaption: 'Unselected', value: SelectedComparison"></select> <!-- ko if: SelectedComparison() === undefined --> <input type="text" disabled="disabled" data-bind="attr: { id: Name + '-value', name: Name + '-value', 'data-min-value': TextboxMinValue, 'data-max-value': TextboxMaxValue, 'data-format': TextboxFormat }, value: TextboxValue" /> <!-- /ko --> <!-- ko ifnot: SelectedComparison() === undefined --> <input type="text" data-bind="attr: { id: Name + '-value', name: Name + '-value', 'data-min-value': TextboxMinValue, 'data-max-value': TextboxMaxValue, 'data-format': TextboxFormat }, value: TextboxValue" /> <!-- /ko --> </div> </div> </div> </script>
doc_23529893
I am able to map protected properties in entity and compoment mappings for single value objects, it is just protected properties do not appear to be supported when mapping collections of value objects. public class MyEntity { public virtual int Id { get; protected set; } protected virtual MyValueObject MyValueObject { get; set; } } public class MyValueObject { protected string SomeString { get; set; } protected ISet<NestedValueObject> NestedValueObjects { get; set; } // Constructor, Equals/GetHashcode overrides, etc. } public class NestedValueObject { public string Name { get; set; } protected DateTime CreatedOn { get; set; } // Audit only property // Constructor, Equals/GetHashcode overrides, etc. } public MyEntityMap() { Table("MyEntityTable"); Id(x => x.Id, map => { map.Column("Id"); }); Component<MyValueObject>("MyValueObject", c => { // Protected property maps correctly c.Property("SomeString", map => { map.NotNullable(true); }); c.Set<NestedValueObject>("NestedValueObjects", map => { map.Table("NestedValueObjectsTable"); map.Key(k => k.Column("MyEntityId")); }, r => r.Component(n => { // Public property maps correctly n.Property(x => x.Name); // Compilation fail - there is no method that supports protected properties in component mappings n.Property<DateTime>("CreatedOn", map => { map.NotNullable(true); }); })); }); } This is because IMinimalPlainPropertyContainerMapper<TContainer> supports protected properties, while IComponentElementMapper<TComponent> doesn't. Is there a reason for this? It seems reasonable that a value object should be allowed to have protected properties which are for auditing purposes only and do not form a part of its conceptual identity, and protected properties are supported with the component mapping for single value objects. A: It looks like this is missing feature, rather than a design decision, and will be fixed in a future release of NHibernate: https://nhibernate.jira.com/browse/NH-3993 As a workaround until this release, the alternatives would be to make the properties public or to map the value object as an entity with a composite id using a one-to-many mapping, since these support protected variables.
doc_23529894
Current XML: <?xml version="1.0" encoding="utf-8"?> <Employees> <Employee> <ManagerFirstName>Joe</ManagerFirstName> <ManagerLastName>Schmoe</ManagerLastName> </Employee> </Employees> Desired Output: <?xml version="1.0" encoding="utf-8"?> <Employees> <Employee> <supervisorName>Schmoe, Joe</supervisorName> </Employee> </Employees> Current XSL: <?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0" > <xsl:template match="/"> <xsl:apply-templates select="*"/> </xsl:template> <xsl:template match="node()"> <xsl:copy><xsl:apply-templates select="node()"/></xsl:copy> </xsl:template> <xsl:template match="ManagerFirstName"> <supervisorName> <xsl:apply-templates select="node()"/> <xsl:value-of select="/ManagerLastName"/> <xsl:text>, </xsl:text> <xsl:value-of select="/ManagerFirstName"/> </supervisorName> </xsl:template> </xsl:stylesheet> This is not working and I can not figure it out. The XML it is outputting at the moment looks like this: <?xml version="1.0" encoding="utf-8"?> <Employees> <Employee> <supervisorName>Joe, </supervisorName> <ManagerLastName>Schmoe/ManagerLastName> </Employee> </Employees> I feel like I'm so close... UPDATE How would I go about making sure that if ManagerFirstName and ManagerLastName are blank, that supervisorName does not have the comma inside of it? UPDATE 2 <?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"> <xsl:output indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="/"> <xsl:apply-templates select="*"/> </xsl:template> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="Employee"> <tbl_EmployeeList><xsl:apply-templates select="@*|node()"/></tbl_EmployeeList> </xsl:template> <xsl:template match="tbl_EmployeeList"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> <supervisorName> <xsl:value-of select="(ManagerLastName,ManagerFirstName)" separator=", "/> </supervisorName> </xsl:copy> </xsl:template> </xsl:stylesheet> A: Since you're using XSLT 2.0 you can use the separator attribute in xsl:value-of... XML Input <Employees> <Employee> <ManagerFirstName>Joe</ManagerFirstName> <ManagerLastName>Schmoe</ManagerLastName> </Employee> </Employees> XSLT 2.0 <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="Employee"> <xsl:copy> <xsl:apply-templates select="@*"/> <supervisorName> <xsl:value-of select="(ManagerLastName,ManagerFirstName)" separator=", "/> </supervisorName> </xsl:copy> </xsl:template> </xsl:stylesheet> XML Output <Employees> <Employee> <supervisorName>Schmoe, Joe</supervisorName> </Employee> </Employees> Note: If there is no ManagerLastName or ManagerFirstName, no separator will be output. A: You can do this in the following way: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="Employee"> <Employee> <supervisorName><xsl:value-of select="concat(ManagerLastName, ', ', ManagerFirstName)"/></supervisorName> </Employee> </xsl:template> </xsl:stylesheet> A: You are close. In the ManagerFirstName template you need a slightly different XPath to pull out the last name: <xsl:template match="ManagerFirstName"> <supervisorName> <xsl:value-of select="../ManagerLastName"/> <xsl:text>, </xsl:text> <xsl:apply-templates select="node()"/> </supervisorName> </xsl:template> (the apply-templates is sufficient to give you the value of the ManagerFirstName, you don't need a specific value-of for that). You then need a no-op template to stop it copying the last name independently <xsl:template match="ManagerLastName" /> Also note that the usual identity template would match and apply-templates to @*|node() rather than just node() - it makes no difference in your example document because you're not using any attributes, but if your original XML had attributes then your version of the identity template would drop them. A: Here is a fully "push style" solution: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <xsl:template match="Employee"> <supervisorName><xsl:apply-templates/></supervisorName> </xsl:template> <xsl:template match="Employee/*"> <xsl:value-of select="concat(', ', .)"/> </xsl:template> <xsl:template match="Employee/*[1]"><xsl:apply-templates/></xsl:template> </xsl:stylesheet> A: All responses seem good, but I think that this approach is cleaner (Just replace your ManagerFirstName template by this one): <xsl:template match="Employee"> <supervisorName> <xsl:value-of select="concat(ManagerLastName,', ',ManagerFirstName)"/> </supervisorName> </xsl:template> UPDATE: If you want to make the comma appear only if both nodes exist and are not empty you can use an if with string-length for that: <xsl:template match="Employee"> <supervisorName> <xsl:value-of select="ManagerLastName"/> <xsl:if test="string-length(ManagerLastName) and string-length(ManagerFirstName)"> <xsl:text> ,</xsl:text> </xsl:if> <xsl:value-of select="ManagerFirstName"/> </supervisorName> </xsl:template> UPDATE 2: Yet a cleaner solution following xslt 2.0 approach, but which also covers the case of an empty node. <xsl:template match="Employee"> <supervisorName> <xsl:value-of select="(ManagerLastName[text()],ManagerFirstName[text()])" separator=", "/> </supervisorName> </xsl:template>
doc_23529895
<div class="some classes"> Some Text </div> <br> <a href="somwhere"> <div class="some classes float-left"> <img src="http://someimage" height="200px" alt="An image"/> <br> <div class="some other classes"> some image text </div> </div> </a> <a href="somwhere"> <div class="some classes float-left"> <img src="http://someimage" height="200px" alt="An image"/> <br> <div class="some other classes"> some image text </div> </div> </a> ... many times <footer> some footer </footer> With CSS .float-left { float:left; } and other CSS classes are just placeholders without any meaning. I do not know how many such divs are created since it is done automatically through a build tool according some variable parameters. I have been using float:left which seemed to fit the case but as as soon as I add a footer it gets embedded right inside some other classes. I suspect this is due to the usage of float. It would be helpful if someone could show me an alternate way with or without using float or even some other CSS tool but I would prefer a non-JS solution and a responsive solution. A: Like I already said, you can use auto-fit or auto-fill in combination with minmax to create a responsive grid that doesnt care how many items are present. for that you can apply to the wrapping element (it also can be the body): grid-template-columns: repeat(auto-fill, minmax(minimum width value, maximum width value)); To have the footer always below all the images and span the entire width you can use: footer { grid-column: 1 / -1; } This approach will fit as many images or other elements in a row as the screen fits. I added a resize property to the snippet so you can resize the element and see how the grid responds to it: .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(100px, 1fr)); } footer { grid-column: 1 / -1; } /* for demonstration purpose only */ .grid { resize: horizontal; overflow-x: auto; border: 2px solid black; box-sizing: border-box; min-width: 104px; max-width: 100%; } .grid > * { display: flex; justify-content: center; align-items: center; min-height: 20vh; color: white; } .grid > div:nth-of-type(3n+1) { background-color: red; } .grid > div:nth-of-type(3n+2) { background-color: darkblue; } .grid > div:nth-of-type(3n+3) { background-color: darkgreen; } .grid > footer { background-color: orange; } <div class="grid"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> <div>9</div> <footer>Footer</footer> </div> A: In CSS you need to write .float-left { float: left; } instead of .float-left:{ float: left; } You have to remove the extra :. A: Here's how I would do it. In your wrapper div you want to add this CSS .wrapper { display: grid; grid-template-columns: repeat(8, 1fr); gap: 10px; grid-auto-rows: 100px; grid-template-areas: "a b" "c d"; align-items: start; } Then for each of your grid 'div's you can add this CSS to each of them .item1 { grid-area: a; } .item2 { grid-area: b; } .item3 { grid-area: c; } .item4 { grid-area: d; } A: You can simply add all your elements in a div and use align attribute your_elements that is the best and simplest way if you don't want to use float
doc_23529896
builder.RegisterType<FooRequest>().AsSelf().InstancePerRequest(); After that I resolve FooRequest in two locations. First is global.asax Application_BeginRequest(): protected void Application_BeginRequest(object sender, EventArgs e) { var fooRequest = DependencyResolver.Current.GetService<FooRequest>(); } A second time in another services constructer. The other service has InstancePerLifetimeScope: public class FooService { public FooService(FooRequest fooRequest) { ... } } My problem is that those two resolves in different instances of FooService and the one used in constructor injection of service does not call Dispose[Async] on the end of the request. What am I doing wrong? Btw. using DependencyResolver.Current.GetService<FooRequest>() outside the constructor does resolve the proper instance of FooRequest in FooService. Additional requested information OWIN & Container configuration: [assembly: OwinStartup(typeof(Project.Web.Startup))] namespace Project.Web { public partial class Startup { public void Configuration(IAppBuilder app) { var builder = new ContainerBuilder(); // REGISTER CONTROLLERS SO DEPENDENCIES ARE CONSTRUCTOR INJECTED builder.RegisterControllers(typeof(MvcApplication).Assembly); builder.RegisterApiControllers(typeof(MvcApplication).Assembly); // REGISTER DEPENDENCIES builder.RegisterModule(new ProjectWebModule()); builder.Register(c => new IdentityFactoryOptions<ApplicationUserManager> { DataProtectionProvider = app.GetDataProtectionProvider() }); // REGISTER FILTERS SO DEPENDENCIES ARE PROPERTY INJECTED builder.RegisterFilterProvider(); // BUILD THE CONTAINER var container = builder.Build(); // REPLACE THE MVC DEPENDENCY RESOLVER WITH AUTOFAC DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); // REPLACE THE WEBAPI DEPENDENCY RESOLVER WITH AUTOFAC GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container); // REGISTER WITH OWIN app.UseAutofacMiddleware(container); app.UseAutofacMvc(); app.Use((context, next) => { var httpContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName); httpContext.SetSessionStateBehavior(SessionStateBehavior.Required); return next(); }); // STANDARD MVC SETUP RouteConfig.RegisterRoutes(RouteTable.Routes); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); // immer nach RouteConfig.RegisterRoutes ausführen! BundleConfig.RegisterBundles(BundleTable.Bundles); // PLACE ConfigureAuth AFTER RegisterGlobalFilters ConfigureAuth(app); } } } ProjectWebModule namespace Project.Web.Autofac { public class ProjectWebModule : Module { protected override void Load(ContainerBuilder builder) { builder.RegisterType<FooRequest>().AsSelf().InstancePerRequest(); builder.RegisterType<FooService>().AsSelf().InstancePerLifetimeScope(); builder.Register(c => HttpContext.Current.GetOwinContext().Authentication).As<IAuthenticationManager>(); builder.Register(c => //register FakeHttpContext when HttpContext is not available HttpContext.Current != null ? new HttpContextWrapper(HttpContext.Current) as HttpContextBase : new FakeHttpContext("~/") as HttpContextBase) .As<HttpContextBase>() .InstancePerLifetimeScope() .OnActivated(e => { Toolbox.HttpContext = e.Instance; }); builder.Register(c => c.Resolve<HttpContextBase>().Request) .As<HttpRequestBase>() .InstancePerLifetimeScope(); builder.Register(c => c.Resolve<HttpContextBase>().Response) .As<HttpResponseBase>() .InstancePerLifetimeScope(); builder.Register(c => c.Resolve<HttpContextBase>().Server) .As<HttpServerUtilityBase>() .InstancePerLifetimeScope(); builder.Register(c => c.Resolve<HttpContextBase>().Session) .As<HttpSessionStateBase>() .InstancePerLifetimeScope(); base.Load(builder); } } } A: I mention in the comments on the question that there's not enough info here to really tell, but here's my guess: you have a race condition. As you know from the Autofac.Mvc.Owin README and the MVC/OWIN integration docs, ASP.NET MVC doesn't actually fully run in the OWIN pipeline. Trying to make the two work creates some weird issues that aren't of Autofac's creation. For example (again, from the Autofac docs): Minor gotcha: MVC doesn’t run 100% in the OWIN pipeline. It still needs HttpContext.Current and some other non-OWIN things. At application startup, when MVC registers routes, it instantiates an IControllerFactory that ends up creating two request lifetime scopes. It only happens during app startup at route registration time, not once requests start getting handled, but it’s something to be aware of. This is an artifact of the two pipelines being mangled together. We looked into ways to try working around it but were unable to do so in a clean fashion. But that also means there's a sort of order around when Application_BeginRequest handlers run that could cause oddness like what you're seeing. For example, the Autofac OWIN MVC integration tries to set up a request lifetime (if it's not already set up) when you put app.UseAutofacMvc() in the pipeline, but the ASP.NET MVC framework also tries to set up a request lifetime internally (using DependencyResolver.Current), so those things have to work together. It's not entirely impossible that your Application_BeginRequest handler is resolving from a different lifetime scope than what the MVC framework is trying to set up as the request lifetime, for example if the MVC framework hasn't had a chance to set it up before you've tried resolving from it. I would recommend if you're trying to use OWIN with MVC, give in to OWIN and actually use OWIN middleware in the pipeline rather than event handlers in MVC. It'll remove the race condition for Application_BeginRequest and give you greater control over the order of operations. It'll also get you closer to where ASP.NET Core is so if/when it's time to migrate your application you won't have to deal with the event handlers that aren't there anymore. Of course, again, this is totally a guess based on what I could gather from the question. Hopefully it helps. Edit after new info was added to question: I think my guess is still correct, but it also looks like you're not setting up OWIN right for WebAPI, which could contribute to the problem. You shouldn't be using GlobalConfiguration. Also, again, MVC doesn't really run in OWIN, so you may see weirdness trying to get two app types (MVC, WebAPI) with two different pipelines to mash together. It's why they unified it in ASP.NET Core.
doc_23529897
CREATE CERTIFICATE ZZZZ_Certificate ENCRYPTION BY PASSWORD = 'pGFD4bb925DGvbd2439587y' WITH SUBJECT = 'ZZZ Information', EXPIRY_DATE = '20221231'; I went through MSFT document and did not find anything. Is it possible to retrieve secret information from Azure key vault and use them in T SQL in synapse? Regards, Rajib A: "I want to retrieve the password from Azure Key Vault and use it in the below statement. For the time being, you can retrieve the credentials from the Azure Key Vault but not use them to generate a certificate. and here is the reference document for my answer. I want to retrieve password from azure key vault and use the password in the below statement. If you want to retrieve credentials from the Azure Key Vault, try to follow this reference. reference link for Use Azure Key Vault secrets in pipeline activities
doc_23529898
I see from some online docs that this command is limited to "short-lived events" triggered by users, for security reasons (which I completely support!). However - what actually counts as a "short-lived event," and how variable is the behavior across browsers? I can't seem to find definitive answers.
doc_23529899
* *the menu_div should be the same width as the screen: $("#menu").css({width: (theWidth - 10)}); *the gallery_img should be at the left side of this div, the contact_img should be on the right side: $("#gallery_img").css({left: 0 + 'px'}); $("#contact_img").css({right: 0 + 'px'); The menu-div and the images both have position: absolute. What am I doing wrong? All images are displayed on top of each other. A: You have a syntax error in your code: $("#contact_img").css({right: 0 + 'px'); // ^ missing closing brace } Also, your CSS width assignment for the #menu element isn't followed by "px", which invalidates the rule and may cause it to fail in some browsers: // Incorrect $("#menu").css({width: (theWidth - 10)}); // Corrent $("#menu").css({width: (theWidth - 10) + "px" }); Note that, if you're planning on using a numeric literal you may as well just use a string on its own and avoid the concatenation. You can also pass the css property and value as separate arguments: $("#contact_img").css({right: '0px'}); $("#contact_img").css('right', '0px'); A: You have some missing braces, perhaps a simpler way to do it would be: $(document).ready(function () { var theWidth = $(window).width(); $("#menu").css('width', theWidth - 10); $("#gallery_img").css('left', 0); $("#contact_img").css('right', 0); }) A: Position absolute will do that. your left for the gallery_img should be 0px... then your contact img's left attribute should be the left for the #menu + #menu's width in px. if you do not specify the left attribute with a position absolute you will ultimately just stack everything.