_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d15301
val
Set in application/config/autoload.php $autoload['libraries'] = array('config_loader'); Create application/libraries/Config_loader.php defined('BASEPATH') OR exit('No direct script access allowed.'); class Config_loader { protected $CI; public function __construct() { $this->CI =& get_instance(); //read manual: create libraries $dataX = array(); // set here all your vars to views $dataX['titlePage'] = 'my app title'; $dataX['urlAssets'] = base_url().'assets/'; $dataX['urlBootstrap'] = $dataX['urlAssets'].'bootstrap-3.3.5-dist/'; $this->CI->load->vars($dataX); } } on your views <title><?php echo $titlePage; ?></title> <!-- Bootstrap core CSS --> <link href="<?php echo $urlBootstrap; ?>css/bootstrap.min.css" rel="stylesheet"> <!-- Bootstrap theme --> <link href="<?php echo $urlBootstrap; ?>css/bootstrap-theme.min.css" rel="stylesheet"> A: Create a MY_Controller.php file and save it inside the application/core folder. In it, something like: class MY_Controller extends CI_Controller { public $site_data; function __construct() { parent::__construct(); $this->site_data = array('key' => 'value'); } } Throughout your controllers, views, $this->site_datais now available. Note that for this to work, all your other controllers need to extend MY_Controllerinstead of CI_Controller. A: You need to extend CI_Controller to create a Base Controller: https://www.codeigniter.com/user_guide/general/core_classes.html core/MY_Controller.php <?php class MY_Controller extend CI_Controller { public function __construct() { parent::__construct(); //get your data $global_data = array('some_var'=>'some_data'); //Send the data into the current view //http://ellislab.com/codeigniter/user-guide/libraries/loader.html $this->load->vars($global_data); } } controllers/welcome.php class Welcome extend MY_Controller { public function index() { $this->load->view('welcome'); } } views/welcome.php var_dump($some_var); Note: to get this vars in your functions or controllers, you can use $this->load->get_var('some_var') A: If this is not an Variable(value keep changing) then I would suggest to create a constant in the constant.php file under the config directory in the apps directory, if it's an variable keep changing then I would suggest to create a custom controller in the core folder (if not exist, go ahead an create folder "core") under apps folder. Need to do some changes in other controller as mentioned here : extend your new controller with the "CI_Controller" class. Example open-php-tag if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class LD_Controller extends CI_Controller { } close-php-tag Here LD_ is my custom keyword, if you want to change you can change it in config.php file under line# 112 as shown here : $config['subclass_prefix'] = 'LD_'; and extend this class in all your controllers as "class Mynewclass extends LD_Controller.. And in LD_controller you've to write the method in which you want to define the variable/array of values & call that array in all over the application as shown here : defining variable : var $data = array(); Method to get values from db through the Model class: function getbooks() { $books = $this->mybooks_model->getbooks(); //array of records $this->data = array('books'=>$books); } to call this variable in the views : print_r($this->data['books']);); you will get all the array values... here we've to make sure atleast one "$data" parameter needs to be passed if not no problem you can define this $data param into the view as shown here : $this->load->view('mybookstore',$data); then it works absolutely fine,,, love to share... have a fun working friends A: you can use $this->load->vars('varname', $data);[ or load data at 1st view only] onse and use in any loaded views after this A: Use sessions in your controllers $this->session->set_userdata('data'); then display them in your view $this->session->userdata('data'); Or include a page in base view file e.g index.php include "page.php"; then in page.php, add $this->session->userdata('data'); to any element or div then this will show on all your views A: I read all answers, but imho the best approch is via hook: * *Create hook, let's get new messages for example: class NewMessages { public function contact() { // Get CI instance CI_Base::get_instance(); $CI = &get_instance(); // <-- this is contoller in the matter of fact $CI->load->database(); // Is there new messages? $CI->db->where(array('new' => 1)); $r = $CI->db->count_all_results('utf_contact_requests'); $CI->load->vars(array('new_message' => $r)); } } *Attach it to some of the flow point, for example on 'post_controller_constructor'. This way, it will be loaded every time any of your controller is instantiated. $hook['post_controller_constructor'][] = array( 'class' => 'NewMessages', 'function' => 'contact', 'filename' => 'NewMessages.php', 'filepath' => 'hooks', 'params' => array(), ); *Now, we can access to our variable $new_message in every view or template. As easy as that :) A: You could override the view loader with a MY_loader. I use it on a legacy system to add csrf tokens to the page where some of the forms in views don't use the builtin form generator. This way you don't have to retrospectively change all your controllers to call MY_Controller from CI_Controller. Save the below as application/core/MY_Loader.php <?php class MY_Loader extends CI_Loader { /** * View Loader * * Overides the core view function to add csrf token hash into every page. * * @author Tony Dunlop * * @param string $view View name * @param array $vars An associative array of data * to be extracted for use in the view * @param bool $return Whether to return the view output * or leave it to the Output class * @return object|string */ public function view($view, $vars = array(), $return = FALSE) { $CI =& get_instance(); $vars['csrf_token'] = $CI->security->get_csrf_hash(); return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_prepare_view_vars($vars), '_ci_return' => $return)); } }
unknown
d15302
val
You can tag your test cases and maven will be able to run them by these tags. For example, When I have Login cases with @Login tags and I want to run them with Maven, I am using the following terminal script : mvn clean test -Dcucumber.options="--tags @Login"
unknown
d15303
val
A few issues with your code: * *You are using test set for validation and validation set for testing. This may be a problem or not, depending on your data and how it was split. *Augmentation should be applied only to training set. Use separate instance of ImageDataGenerator(rescale=1/255) for testing and validation. Your test results look like they were got from untrained model. Check if the model object you are running test on is the same one you were training. You may want to use model.save() and load_model() functions to preserve model weights after training. A: I replaced : val_image_gen = image_gen.flow_from_directory( val_path, target_size=image_shape[:2], color_mode='rgb', class_mode='binary', ) by: val_image_gen = image_gen.flow_from_directory( val_path, target_size=image_shape[:2], color_mode='rgb', batch_size=batch_size, class_mode='binary', shuffle=False ) I obtain nice results : [[269 48] [ 3 314]]
unknown
d15304
val
I'm not sure exactly what you are trying to achieve. Why would you prefer to use a static call instead of accessing data from the ValueStack (which is where the action properties are accessed from)? It really is best to avoid static calls if possible and stick to the intended design of the framework and access data from the ValueStack/action. If you just wish to separate the logic from your action, you could change your method to: public String getTranslatedType() { return Utility.getTranslatedText(getMessageBean().getMessageType()); } Or are you wishing to have the translated text appear on the page dynamically? If so, perhaps you could use Javascript and JSON to achieve your goal with something along the lines of the following steps: * *Place your messageType integers (as the keys) and your translatedText Strings (as the values) into a map along the lines of messageTypeText.put(12, "Message for frequent callers."); *Convert this to JSON using something like (new JSONObject(messageTypeText)).toString(); *Then expose this to the client by any of a number of ways such as var messageTypeText = <s:property value="messageTypeText"/>; *Bind a javascript method to the messageType radio button that then displays the translated text by accessing it from the javascript map/array using the value of the currently selected radio/messageType. I could give more detail on this approach, but I don't want to waste my time if its not what you're looking for! :)
unknown
d15305
val
After a little bit of digging, it turns out that the platform on which the library can run on is indeed specified in the binary. In fact, you can edit the binary in your favorite Hex editor and make the linker skip this check entirely. This information is not specified in the Mach-O header (as you have already realized). Instead, it is specified as a load command type. You can see the available types by digging through the LLVM sources. Specifically, the enum values LC_VERSION_MIN_MACOSX and LC_VERSION_MIN_IPHONEOS look interesting. Now, find the offset for this in our binary. Open the same in MachOView (or any other editor/viewer or your choice) and note the offset: Once the offset is noted, jump to the same in a Hex editor and update it. I modified LC_VERSION_MIN_IPHONEOS (25) to LC_VERSION_MIN_MACOSX (24) Save the updates and try linking again. The error should go away. Of course, you will hit other issues when you try to actually run your example. Have fun with LLDB then :)
unknown
d15306
val
I believe the problem lies in the actual number of FPUs you have as suggested by @Aconcagua. "logical processors" aka "hyper threading" is not the same as having twice the cores. 8 cores in hyper threading are still 4 "real" cores. If you look closely at your timings, you will see that the execution times are almost the same until you use more than 4 threads. When you use more than 4 threads, you may start running out of FPUs. However, to have a better understanding of the issue I would suggest to have a look at the actual assembly code produced. When we want to measure raw performance, we must keep in mind that our C++ code is just an higher level representation, and the actual executable may be quite different than what we would expect. The compiler will perform its optimizations, the CPU will execute things out of order, etc... Therefore, first of all I would recommend to avoid the use of constant limits in your loops. Depending on the case, the compiler may unroll the loop or even replace it entirely with the result of its calculation. As an example, the code: int main() { int z = 0; for(int k=0; k < 1000; k++) z += k; return z; } is compiled by GCC 8.1 with optimizations -O2 as: main: mov eax, 499500 ret As you can see the loop just disappeared! The compiler replaced it with the actual end result. Using an example like this to measure performance is dangerous. With the example above, iterating 1000 times or 80000 times is exactly the same, because the loop is replaced with a constant in both cases (of course, if you overflow your loop variabile the compiler can't replace it anymore). MSVC is not that aggressive, but you never know exactly what the optimizer does, unless you look at the assembly code. The problem with looking at the produced assembly code is that it can be massive... A simple way to solve the issue is to use the great compiler explorer. Just type in your C/C++ code, select the compiler you want to use and see the result. Now, back to your code, I tested it with compiler explorer using MSVC2015 for x86_64. Without optimizations they assembly code looks almost the same, except for the intrinsic at the end to convert to double (cvtsi2sd). However, things start to get interesting when we enable optimizations (which is the default when compiling in release mode). Compiling with the flag -O2, the assembly code produced when mDummy is a long variable (32 bit) is: Algorithm::runAlgorithm, COMDAT PROC xor r8d, r8d mov r9d, r8d npad 10 $LL4@runAlgorit: mov rax, r9 mov edx, 100000 ; 000186a0H npad 8 $LL7@runAlgorit: dec r8 add r8, rax add rax, -4 sub rdx, 1 jne SHORT $LL7@runAlgorit add r9, 2 cmp r9, 400000 ; 00061a80H jl SHORT $LL4@runAlgorit mov DWORD PTR [rcx], r8d ret 0 Algorithm::runAlgorithm ENDP end when mDummy is a float: Algorithm::runAlgorithm, COMDAT PROC mov QWORD PTR [rsp+8], rbx mov QWORD PTR [rsp+16], rdi xor r10d, r10d xor r8d, r8d $LL4@runAlgorit: xor edx, edx xor r11d, r11d xor ebx, ebx mov r9, r8 xor edi, edi npad 4 $LL7@runAlgorit: add r11, -3 add r10, r9 mov rax, r8 sub r9, 4 sub rax, rdx dec rax add rdi, rax mov rax, r8 sub rax, rdx add rax, -2 add rbx, rax mov rax, r8 sub rax, rdx add rdx, 4 add r11, rax cmp rdx, 200000 ; 00030d40H jl SHORT $LL7@runAlgorit lea rax, QWORD PTR [r11+rbx] inc r8 add rax, rdi add r10, rax cmp r8, 200000 ; 00030d40H jl SHORT $LL4@runAlgorit mov rbx, QWORD PTR [rsp+8] xorps xmm0, xmm0 mov rdi, QWORD PTR [rsp+16] cvtsi2ss xmm0, r10 movss DWORD PTR [rcx], xmm0 ret 0 Algorithm::runAlgorithm ENDP Without getting into the details of how these two codes work or why the optimizer behaves differently in the two cases, we can clearly see some differences. In particular, the second version (the one with mDummy being float): * *is slightly longer *uses more registers *access memory more often So aside from the hyper threading issue, the second version is more likely to produce cache misses, and since cache is shared, this can also affect the final execution times. Moreover, things like turbo boost may kick in as well. Your CPU may be throttling down when stressing it, causing an increase in the overall execution time. For the records, this is what clang produces with optimizations turned on: Algorithm::runAlgorithm(): # @Algorithm::runAlgorithm() mov dword ptr [rdi], 0 ret Confused? Well... nobody is using mDummy elsewhere so clang decided to remove the whole thing entirely... :)
unknown
d15307
val
01, stockB:02 so on and so forth. My desired data frame would be Date stockA stockB stockC stockD stockE 2020-01-01 011 021 032 041 053 2020-01-01 011 022 032 041 052 2020-01-01 011 021 033 042 051 2020-01-01 013 021 032 041 052 I have 25 columns likewise. How can I do it in pandas? A: Try with df.radd: m = df.set_index('Date') #add prefix 0X if less than 10 else add prefix X m = m.astype(str).radd([f"0{i}" if i<10 else f"{i}" for i in range(1,m.shape[1]+1)]).reset_index() print(m) Date stockA stockB stockC stockD stockE 0 2020-01-01 011 021 032 041 053 1 2020-01-01 011 022 032 041 052 2 2020-01-01 011 021 033 042 051 3 2020-01-01 013 021 032 041 052 A: A somewhat more cumbersome but perhaps more readable solution: v = [1,23,33] cols = {'A': v, 'B': v, 'C': v, 'D': v, 'E': v, 'F': v, 'G': v, 'H': v, 'I': v, 'J': v} df = pd.DataFrame(data = cols, index = ['2020-01-01']*3, columns = cols) for n, col in enumerate(df.columns, 1): df[col] = str(n).zfill(2) + df[col].astype(str) >> A B C D E F G H I J 2020-01-01 011 021 031 041 051 061 071 081 091 101 2020-01-01 0123 0223 0323 0423 0523 0623 0723 0823 0923 1023 2020-01-01 0133 0233 0333 0433 0533 0633 0733 0833 0933 1033 A: Use: m = df.columns.str.contains('stock') cols_change = df.columns[m] num = ('0'+pd.Index(range(1,len(cols_change)+1)).astype(str)).str[-2:] df.columns = df.columns[~m].tolist()+[f'{name}:{n}' for n,name in zip(num,cols_change)] print(df) Date stockA:01 stockB:02 stockC:03 stockD:04 stockE:05 0 2020-01-01 1 1 2 1 3 1 2020-01-01 1 2 2 1 2 2 2020-01-01 1 1 3 2 1 3 2020-01-01 3 1 2 1 2 or with pd.Index.difference cols_change = df.columns.difference(['Date']) num = ('0'+pd.Index(range(1,len(cols_change)+1)).astype(str)).str[-2:] df.columns = ['Date']+[f'{name}:{n}' for n,name in zip(num,cols_change)]
unknown
d15308
val
cmd.Parameters.Add("@Name", SqlDbType.VarChar, 50, "fileFields(3)") will pass "filefields(3)" as a string when you're really trying to pass the actual field. When your insert is called, you're going to have to write some sort of a loop through your code and then you can insert it like: INSERT INTO Table ( Column1, Column2 ) VALUES ( Value1, Value2 ), ( Value1, Value2 ) Where your value and columns correspond. Now to get the CSV, save it as a variable (parse it from the text box included in this) or pass it back from the webpage. Once you have it back, I'd create a class which holds your file field so you can read your code later then stick that into a list. Iterate through that list and make a string. I'd use a string builder because I think it's more readable. Then you can drop your creating parameters and just call the strSql directly. Does this make sense? If this answer still helps you / you're curious about the actual code, comment and I'll write it but as it's a month old I'm assuming you solved your problem.
unknown
d15309
val
We can use str_detect with case_when/ifelse to retrieve the row element and then use fill to fill the NA values with the previous non-NA library(dplyr) library(tidyr) library(stringr) df <- df %>% mutate(col3 = case_when(str_detect(col2, "DOI_") ~ col2)) %>% fill(col3) -output df col1 col2 col3 1 Elem_A DOI_1 DOI_1 2 String String DOI_1 3 String String DOI_1 4 String String DOI_1 5 Elem_A DOI_2 DOI_2 6 String String DOI_2 7 String String DOI_2 8 Elem_A DOI_3 DOI_3 9 String String DOI_3 10 String String DOI_3 11 String String DOI_3 12 String String DOI_3 If 'DOI_\\d+' is a substring, then use str_extract to extract the substring df <- df %>% mutate(col3 = str_extract(col2, "DOI_\\d+")) %>% fill(col3) -output df col1 col2 col3 1 Elem_A DOI_1 DOI_1 2 String String DOI_1 3 String String DOI_1 4 String String DOI_1 5 Elem_A DOI_2 DOI_2 6 String String DOI_2 7 String String DOI_2 8 Elem_A DOI_3 DOI_3 9 String String DOI_3 10 String String DOI_3 11 String String DOI_3 12 String String DOI_3 A: With Base R way s <- unlist(gregexpr("DOI_\\d+" , df$col2)) df$col3 <- unlist(Map(\(x,y) rep(df$col2[x] ,length.out = y + 1) , which(s > -1) , rle(s)$lengths[which(rle(s)$values == -1)])) * *output col1 col2 col3 1 Elem_A DOI_1 DOI_1 2 String String DOI_1 3 String String DOI_1 4 String String DOI_1 5 Elem_A DOI_2 DOI_2 6 String String DOI_2 7 String String DOI_2 8 Elem_A DOI_3 DOI_3 9 String String DOI_3 10 String String DOI_3 11 String String DOI_3 12 String String DOI_3
unknown
d15310
val
you are initializing the marker again in ajax, remove first and then initialize it again this should work function ShowCurrentTime() { var obj = {}; obj.device_id = $.trim($("\[id*=txtdevice_id\]").val()); var marker = null; var mapOptions; $.ajax({ url: "TRACKING.aspx/GetData", data: JSON.stringify(obj), type: "POST", dataType: "json", contentType: "application/json; charset=utf-8", success: function(data) { if (data.d != '') { var lat = data.d\[1\]; var lng = data.d\[2\]; } $.each(data, function(index, value) { var zoom = 13; if (marker != null) map.removeLayer(marker); marker = new OpenLayers.Layer.Markers("Markers"); var lonLat = new OpenLayers.LonLat(lng, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject()); map.addLayer(marker); marker.addMarker(new OpenLayers.Marker(lonLat)); map.setCenter(lonLat, zoom); }); } }); }
unknown
d15311
val
You can try this way $json='{ "custClass": [ { "code": "50824109d3b1947c9d9390ac5caae0ef", "desc": "e1f96b98047adbc39f8baf8f4aa36f41" }, { "code": "dab6cc0ed3688f96333d91fd979c5f74", "desc": "d0e850f728b2febee79e1e7d1186c126" }, { "code": "bc4050f8f891296528ad6a292b615e86", "desc": "bee3120e77092d889c3b9e27cbee75bd" }, { "code": "f13fc8c35dfe206a641207c6054dd9a0", "desc": "32a81cb610805d9255d5f11354177414" }, { "code": "2117c346d9b3dfebf18acc8b022326d4", "desc": "88a8e85db11976082fed831c4c83838e" }, { "code": "95c0674fc0e0434f52a60afce74571d2", "desc": "39c4d4bca1578194801f44339998e382" }, { "code": "c8ad6f709612d2a91bb9f14c16798338", "desc": "6b4c4d5f4ae609742c1b6e62e16f8650" } ], "sourceData": [ { "sourceId": "ff64060a40fc629abf24eb03a863fd55", "sourceName": "92aa69979215a2bf6290c9a312c5891f" } ] }'; $decode=json_decode($json,true); $desc=[]; foreach($decode['custClass'] as $cust){ $desc[]=$cust['desc']; } var_dump($desc); A: You can decode data and loop it $s = '[ { "custClass": [ { "code": "50824109d3b1947c9d9390ac5caae0ef", "desc": "e1f96b98047adbc39f8baf8f4aa36f41" }, { "code": "dab6cc0ed3688f96333d91fd979c5f74", "desc": "d0e850f728b2febee79e1e7d1186c126" }, { "code": "bc4050f8f891296528ad6a292b615e86", "desc": "bee3120e77092d889c3b9e27cbee75bd" }, { "code": "f13fc8c35dfe206a641207c6054dd9a0", "desc": "32a81cb610805d9255d5f11354177414" }, { "code": "2117c346d9b3dfebf18acc8b022326d4", "desc": "88a8e85db11976082fed831c4c83838e" }, { "code": "95c0674fc0e0434f52a60afce74571d2", "desc": "39c4d4bca1578194801f44339998e382" }, { "code": "c8ad6f709612d2a91bb9f14c16798338", "desc": "6b4c4d5f4ae609742c1b6e62e16f8650" } ], "sourceData": [ { "sourceId": "ff64060a40fc629abf24eb03a863fd55", "sourceName": "92aa69979215a2bf6290c9a312c5891f" } ] } ]'; $data =json_decode($s,true); foreach($data as $obj){ foreach($obj['custClass'] as $val){ echo "Desc ".$val['desc']."<br/>"; } } A: Try decoding data and retrieve it using foreach: $your_data = your_data; $decoded_data = json_decode($your_data [0], true); $final_data = []; foreach($decoded_data['custClass'] as $data) { $final_data[] = $data['desc']; } print_r($final_data); A: try this code loop this array like below foreach(json_decode($data) as $key=>$value){ foreach($value->custClass as $key1=>$value1){ echo $value1->desc; } } json_decode() the data <?php $data= '[ { "custClass": [ { "code": "50824109d3b1947c9d9390ac5caae0ef", "desc": "e1f96b98047adbc39f8baf8f4aa36f41" }, { "code": "dab6cc0ed3688f96333d91fd979c5f74", "desc": "d0e850f728b2febee79e1e7d1186c126" }, { "code": "bc4050f8f891296528ad6a292b615e86", "desc": "bee3120e77092d889c3b9e27cbee75bd" }, { "code": "f13fc8c35dfe206a641207c6054dd9a0", "desc": "32a81cb610805d9255d5f11354177414" }, { "code": "2117c346d9b3dfebf18acc8b022326d4", "desc": "88a8e85db11976082fed831c4c83838e" }, { "code": "95c0674fc0e0434f52a60afce74571d2", "desc": "39c4d4bca1578194801f44339998e382" }, { "code": "c8ad6f709612d2a91bb9f14c16798338", "desc": "6b4c4d5f4ae609742c1b6e62e16f8650" } ], "sourceData": [ { "sourceId": "ff64060a40fc629abf24eb03a863fd55", "sourceName": "92aa69979215a2bf6290c9a312c5891f" } ] } ]'; foreach(json_decode($data) as $key=>$value){ foreach($value->custClass as $key1=>$value1){ echo $value1->desc; } } ?> A: You can loop through all JSON Arrays by using a recursive algorithm. $myJsonArray = '<as-your-above-json-array>'; # Convert $myJsonArray into an associative array $myJsonArray = json_decode($myJsonArray, true); recursiveArray($myJsonArray); # A recursive function to traverse the $myJsonArray array function recursiveArray(array $myJsonArray) { foreach ($myJsonArray as $key => $hitElement) { # If there is a element left if (is_array($hitElement)) { # call recursive structure to parse the jsonArray recursiveArray($hitElement); } else { if ($key === 'desc') { echo $hitElement . PHP_EOL; } } } } /** OUTPUT e1f96b98047adbc39f8baf8f4aa36f41 d0e850f728b2febee79e1e7d1186c126 bee3120e77092d889c3b9e27cbee75bd 32a81cb610805d9255d5f11354177414 88a8e85db11976082fed831c4c83838e 39c4d4bca1578194801f44339998e382 6b4c4d5f4ae609742c1b6e62e16f8650 */ Live code -> https://wtools.io/php-sandbox/bFEJ OR use the RecursiveArrayIterator to traverse the $myJsonArray array $myJsonArray = json_decode($myJsonArray, true); $myIterator = new RecursiveArrayIterator($myJsonArray); recursiveArray($myIterator); function recursiveArray(RecursiveArrayIterator $myIterator) { while ($myIterator->valid()) { if ($myIterator->hasChildren()) { recursiveArray($myIterator->getChildren()); } else { if ($myIterator->key() === 'desc') { echo $myIterator->current() . PHP_EOL; } } $myIterator->next(); } } Live code -> https://wtools.io/php-sandbox/bFEL
unknown
d15312
val
A New Algorithm to Represent a Given k-ary Tree into Its Equivalent Binary Tree. Refer This Paper In Simple words: 1. Create L to R sibling pointers at each level 2. Remove all but the leftmost child pointer of each node 3. Make the sibling pointer the right pointer.
unknown
d15313
val
class A { String name; A(); A.withName(this.name); } I'd like to create a JavaScript object using the exported API with: var a = new A(); An answer to my previous question pointed me to js-interop. However, I'm not able to get the expected result when working through the README example. It appears that my Dart library isn't being exported into JavaScript. pubspec.yaml: name: interop description: > A library useful for applications or for sharing on pub.dartlang.org. version: 0.0.1 dev_dependencies: unittest: any dependencies: js: git: url: git://github.com/dart-lang/js-interop.git transformers: - js - js/initializer example/main.dart library main: import 'package:js/js.dart'; main() { initializeJavaScript(); } lib/a.dart library a; import 'package:js/js.dart'; @Export() class A { String name; A(); A.withName(this.name); } index.html <html> <head> <script src="packages/js/interop.js"></script> </head> <body> <script type="application/dart" src="build/example/main.dart"></script> </body> </html> (It's not clear where the src attribute of that last script tag should point. I've tried using /example/main.dart as well, which doesn't change my result.) I expected to be able to open a console after compiling (Tool -> Pub Build) and loading index.html, and then do this: var a = new dart.a.A(); However, I get this instead: "Cannot read property 'A' of undefined". In other words, dart.a is undefined. The inclusion of raw Dart script in index.html suggests that js-interop is intended for a browser with a Dart VM. I tried running index.html on Dartium with the same result. What am I missing? A: The src attribute of the script tag still has to point to a file with a Dart script that contains a main() method. When the application is built to JavaScript using pub build Dart is compiled to JavaScript and can be run in browsers without a Dart VM. A: Yes, it does work on a JavaScript only browser. It turns out the documentation doesn't give all of the steps. Here's what worked for me, starting with a new project. Create a new package project called 'jsout' using (File-> New Project/package). Delete these files: * *test/all_test.dart *example/jsout.dart Edit these files: pubspec.yaml name: jsout description: > A library useful for applications or for sharing on pub.dartlang.org. version: 0.0.1 dev_dependencies: unittest: any dependencies: js: git: url: git://github.com/dart-lang/js-interop.git transformers: - js - js/initializer lib/main.dart part of main; @Export() class A { String name; A(); A.withName(this.name); talk() { print(name); } } Create folder web, and add these files: web/main.dart library main; import 'package:js/js.dart'; part '../lib/jsout.dart'; main() { initializeJavaScript(); } web/index.html <!DOCTYPE html> <html> <head></head> <body> <script src="main.dart_initialize.js"></script> <script src="main.dart.js"></script> </body> </html> After updating these files, load index.html, and open a console: var a = new dart.main.A.withName('foo'); a.talk(); // returns 'foo' This procedure worked as of revision 7afdb.
unknown
d15314
val
You could set the disabled key value for each option to True when the max number of options has been reached so the remaining options can't be selected anymore. When you have not reached the threshold you can return your original list of options (Which are implicitly enabled). from dash import Dash, html, dcc from dash.dependencies import Output, Input default_options = [ {"label": "A", "value": "A"}, {"label": "B", "value": "B"}, {"label": "C", "value": "C"}, {"label": "D", "value": "D"}, {"label": "E", "value": "E"}, {"label": "F", "value": "F"}, ] app = Dash(__name__) app.layout = html.Div( [ dcc.Dropdown( id="dropdown", options=default_options, value=["MTL", "NYC"], multi=True, ), html.Div(id="warning"), ] ) @app.callback( Output("dropdown", "options"), Output("warning", "children"), Input("dropdown", "value"), ) def update_multi_options(value): options = default_options input_warning = None if len(value) >= 4: input_warning = html.P(id="warning", children="Limit reached") options = [ {"label": option["label"], "value": option["value"], "disabled": True} for option in options ] return options, input_warning if __name__ == "__main__": app.run_server()
unknown
d15315
val
You need to use a FormDigestValue. Make a GET call to .../_api/contextinfo and store the value of 'FormDigestValue'. Then for all your other calls, add a header of X-RequestDigest: <FormDigestValue>
unknown
d15316
val
Try following code and let me know in case of any issues: WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//input[@type="file"][@name="qqfile"]'))).send_keys("/path/to/Gandalf.jpg") P.S. You should replace string "/path/to/Gandalf.jpg" with actual path to file
unknown
d15317
val
You have to add viewport-fit=cover to the viewport meta tag of your index.html <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, viewport-fit=cover">
unknown
d15318
val
No. You'd have to add your own wrapper code around NSURLSession to do that. You should probably have an analytics singleton class that handles merging multiple requests where needed, retries, etc. so that all the caller has to do is [MyAnalyticsClass updateAnalyticsWithParameters: @{...}] or whatever. Then, in that call, you should check to see if there's a request in progress. If not, start the request immediately. If so, enqueue the new request. When the current request completes, look through the queue and decide which ones to send, which ones to merge, etc. and start the next one.
unknown
d15319
val
The message received is correct. There have been issues with misuse of Dreamspark accounts that were causing severe issues with the Store. However, we realize that many of you are not part of this activity and as such we can help you by contacting Developer Support. Please contact them directly so that they have your account information and can get your apps set up for success! Thanks Jo Windows App and Catalog Operations
unknown
d15320
val
You can do it with jQuery like this: $('table td').mouseover(function() { $('table td').removeClass('highlight') var text = $(this).text(); $('table td').filter(function() { return $(this).text() == text; }).addClass('highlight'); }) Check this jsFiddle A: using jQuery.data Always to know how something works, the first step is to read the source code Check this: EXAMPLE $('.interactive_table .cell_word') .hover(function(){ var word = $(this).data('word'); $(this).parent().parent() .find('.word_'+word) .addClass('highlighted'); },function(){ var word = $(this).data('word'); $(this).parent().parent() .find('.word_'+word) .removeClass('highlighted'); }); $('.interactive_table .cell_rank_number') .hover(function(){ $(this).parent() .find('.cell_word') .addClass('highlighted'); },function(){ $(this).parent() .find('.cell_word') .removeClass('highlighted'); });
unknown
d15321
val
I would try to extract this: + $9.49 You can use following regex: @"(?<=\+\s\$)(\d+\.?\d*) * *(?<=\+\s\$) match but don't include a + followed by a whitespace, followed by a $ *(\d+\.?\d*) match and put in a group at least one digit, followed by an optional . followed by any number of digits. The + . $ signs are special regex characters which have to be escaped with a backslash.
unknown
d15322
val
Assuming that you're using CommonsMultipartResolver, then you can use its maxUploadSize property to limit this. See docs for an example. A: In order to catch that MaxUploadSizeExceededException, I use the following : In the controller, you should implement the HandlerExceptionResolver interface. Then, implement the resolveException method : // Catch file too big exception @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) { if (exception instanceof MaxUploadSizeExceededException) { // Do something with exception here } // Goes back to original view here Map<String, Object> model = new HashMap<String, Object>(); model.put("uploadFile", new UploadFile()); return new ModelAndView(associatedView,model); }
unknown
d15323
val
Avery Lee of VirtualDub states that it's a box filter for downscaling and linear for upscaling. If I'm not mistaken, "box filter" here means basically that each output pixel is a "flat" average of several input pixels. In practice, it's a lot more blurry for downscaling than GDI's cubic downscaling, so the theory about averaging sounds about right. A: I know what it is, but I couldn't find much on Google either :( http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=4056711 is the appropriate paper I think; behind a pay-wall. You don't need to understand the algorithm to use it. You should explicitly make the choice each time you create a bitmap control that is scaled whether you want it high-quality scaled or low quality scaled.
unknown
d15324
val
You should do it in accessor, not in Cell. accessor: d => d.roles.map(role => role.name).join(', ')
unknown
d15325
val
As well you can use: mysql> show status like '%onn%'; +--------------------------+-------+ | Variable_name | Value | +--------------------------+-------+ | Aborted_connects | 0 | | Connections | 303 | | Max_used_connections | 127 | | Ssl_client_connects | 0 | | Ssl_connect_renegotiates | 0 | | Ssl_finished_connects | 0 | | Threads_connected | 127 | +--------------------------+-------+ 7 rows in set (0.01 sec) Feel free to use Mysql-server-status-variables or Too-many-connections-problem A: SQL: show full processlist; This is what the MySQL Workbench does. A: In MySql,the following query shall show the total number of open connections: show status like 'Threads_connected'; A: That should do the trick for the newest MySQL versions: SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE DB like "%DBName%"; A: The command is SHOW PROCESSLIST Unfortunately, it has no narrowing parameters. If you need them you can do it from the command line: mysqladmin processlist | grep database-name A: If you're running a *nix system, also consider mytop. To limit the results to one database, press "d" when it's running then type in the database name. A: You can invoke MySQL show status command show status like 'Conn%'; For more info read Show open database connections A: From the monitoring context here is how you can easily view the connections to all databases sorted by database. With that data easily monitor. SELECT DB,USER,HOST,STATE FROM INFORMATION_SCHEMA.PROCESSLIST ORDER BY DB DESC; +------+-------+---------------------+-----------+ | DB | USER | HOST | STATE | +------+-------+---------------------+-----------+ | web | tommy | 201.29.120.10:41146 | executing | +------+-------+---------------------+-----------+ If we encounter any hosts hots max connections and then not able to connect, then we can reset host tables by flushing it and is as follows: FLUSH HOSTS; A: In query browser right click on database and select processlist
unknown
d15326
val
This kind of DataFrame is based on more plain DataFrame where ids and counts are not grouped to arrays. It is more convenient to use non grouped DataFrame to build that with Bokeh: https://discourse.bokeh.org/t/cant-render-heatmap-data-for-apache-zeppelins-pyspark-dataframe/8844/8 instead of grouped to list columns ids/counts we have raw table with one line per unique id ('value') and value of count ('index') and each line has its 'write_time' rowIDs = pdf['values'] colIDs = pdf['window_time'] A = pdf.pivot_table('index', 'values', 'window_time', fill_value=0) source = ColumnDataSource(data={'x':[pd.to_datetime('Jan 24 2022')] #left most ,'y':[0] #bottom most ,'dw':[pdf['window_time'].max()-pdf['window_time'].min()] #TOTAL width of image #,'dh':[pdf['delayWindowEnd'].max()] #TOTAL height of image ,'dh':[1000] #TOTAL height of image ,'im':[A.to_numpy()] #2D array using to_numpy() method on pivotted df }) color_mapper = LogColorMapper(palette="Viridis256", low=1, high=20) plot = figure(toolbar_location=None,x_axis_type='datetime') plot.image(x='x', y='y', source=source, image='im',dw='dw',dh='dh', color_mapper=color_mapper) color_bar = ColorBar(color_mapper=color_mapper, label_standoff=12) plot.add_layout(color_bar, 'right') #show(plot) show(gridplot([plot], ncols=1, plot_width=1000, high=pdf['index'].max())) And the result:
unknown
d15327
val
var y = Flags.findOne({_id: "flagsone"}); var props = {}; props["score20130901." + y.flag1] = 222; Books.update({_id:book}, {$set: props});
unknown
d15328
val
In PostgreSQL 9.1 and later, the best solution for this is https://github.com/omniti-labs/pgtreats/tree/master/contrib/pg_dirtyread which is an extension that provides a functional interface in sql to access old, unvacuumed versions of rows. Other tools may exist for other dbs. This works well for a number of cases data recovery, just exploring the utility of mvcc, and the like. With some effort it might work on earlier versions.
unknown
d15329
val
It isn't the BufferedReader. You can read millions of lines per second with BufferedReader.readLine(). It's your code. For example, the f.read() calls are not correct. They will deliver character values, not digit values, and from the next line, without consuming the line terminator, so you will get a blank line next readLine(), so you will be totally out of sync with your input. Basically your code doesn't even work yet, so timing it now is futile. A: Your first for-loop is probably testing with the wrong value. Instead of : for(int i = 0; i < ppl-1; ++i ) { try using: for(int i = 0; i < ppl; ++i ) { [UPDATE] Since you are looping too few times in this loop, the subsequent loop will be using the remaining input data inappropriately. For example, ppl_given would be some garbage number, which could be very big.
unknown
d15330
val
You could use RegisterObjectTransformation, introduced in NLog 4.7. For example: LogManager.Setup().SetupSerialization(s => s.RegisterObjectTransformation<object>(o => { var props = o.GetType().GetProperties(); var propsDict = props.ToDictionary(p => p.Name, p => p.GetValue(o)); propsDict.Remove("password"); return propsDict; })); Please note, in terms of performance you maybe need something like a reflection cache and smart optimizations. A: I suggest that you wrap the secret password in an object like this: public class SecretWrapper : IFormatable { private readonly string _secret; public SecretWrapper(string secret) { _secret = secret; } public string GetSecret() => _secret; // Not a property to avoid basic reflection public override string ToString() => "******" public string ToString (string format, IFormatProvider formatProvider) => ToString(); } NLog will never output the secret-value: logger.Info("User's Password is {Password}", new SecretWrapper("1234567890"));
unknown
d15331
val
When you have multiple tables in a query, always use qualified table names. You think the query is doing: SELECT t1.col_a FROM test_1 t1 WHERE t1.col_a IN (SELECT t2.col_a FROM test_2 t2); This would generate an error, because t2.col_a does not exist. However, the scoping rules for subqueries say that if the column is not in the subquery, look in the outer query. So, if t2.col_a does not exist, then the query turns into: SELECT t1.col_a FROM test_1 t1 WHERE t1.col_a IN (SELECT t1.col_a FROM test_2 t2); The solution is to qualify all column references so there is no ambiguity.
unknown
d15332
val
For each of your examples, this is what is happening: <c:out value="${java.lang.Math.PI}" /> This is looking for the variable or bean named java and trying to execute a method on it called lang. There is probably no variable or bean in your JSP page called Java so there is no output. ${java.lang.Math.PI} This is the same as above, just written using EL only. It's the same in that it's looking for a variable or bean named java. <%= java.lang.Math.PI %> What this is doing is during the JSP compile, java.lang.Math.PI is being calculated and written into the JSP. If you look at the compiled JSP you will see the value written there. The third example is evaluating the expression as if you were in a Java class. The first two examples expect 'java' to be a variable name.
unknown
d15333
val
What about server { listen 80; server_name admin.website.com; ... location / { return 301 $scheme://website.com$request_uri; } location /login { # processing URL here root </path/to/root>; ... } }
unknown
d15334
val
As mentioned here, We recommend that the params you pass are JSON-serializable. That way, you'll be able to use state persistence and your screen components will have the right contract for implementing deep linking. React Navigation parameters work like query parameters in websites in 6.x I believe, the ideal way to do this now is to use Context API where you have a single source of information. You can also use a state management library such as redux or mobx in cases where you have a large number of stores and actions to manipulate them.
unknown
d15335
val
First of all insert a contact form shortcode into your template file directly. You will need to pass the code into do_shortcode() function. For Example: <?php echo do_shortcode('[contact-form-7 id="345"]'); ?>
unknown
d15336
val
Elements with visibility: hidden; don't receive any mouse events, so :hover never triggers on such an element. Instead of visibility, you can work with opacity: div { background-color: orange; height: 200px; width: 400px; padding: 50px; } .visible-on-hover { opacity: 0; transition: opacity .3s ease; } .visible-on-hover:hover { opacity: 1; } <div class="visible-on-hover">visible only on hover</div> A: you can not hover, focus or select a hidden element. you can use opacity .visible-on-hover { opacity: 0; } .visible-on-hover:hover { opacity: 1; }
unknown
d15337
val
Did you tried this.... job_no not in instead of data_job_t.JobCode INSERT INTO [Datamaxx].[dbo].[data_job_t] (JobCode, Description) SELECT job_no, description FROM OPENDATASOURCE('SQLNCLI', 'Data Source=server\server;Integrated Security=SSPI') .cas_tekworks.dbo.jobs WHERE Job_Status ='A' and job_no not in (select Jobcode from [Datamaxx].[dbo].[data_job_t])
unknown
d15338
val
* *Go to Xcode Preferences. *Choose Text Editing tab. *Switch to the Editing page underneath. *Check both "Automatically trim trailing whitespace" and "Including whitespace-only lines". This works both in Vim mode and the normal mode.
unknown
d15339
val
I'm not sure how you've been able to have it print even one random number. In your case, %checker% should evaluate to an empty string, unless you run your script more than once from the same cmd session. Basically, the reason your script doesn't work as intended is because the variables in the loop body are parsed and evaluated before the loop executes. When the body executes, the vars have already been evaluated and the same values are used in all iterations. What you need, therefore, is a delayed evaluation, otherwise called delayed expansion. You need first to enable it, then use a special syntax for it. Here's your script modified so as to use the delayed expansion: @echo off setlocal EnableDelayedExpansion for %%i in (*.txt) do ( set checker=!Random! echo !checker! echo %%i% >> backupF ) endlocal echo Complete As you can see, setlocal EnableDelayedExpansion enables special processing for the delayed expansion syntax, which is !s around the variable names instead of %s. You can still use immediate expansion (using %) where it can work correctly (basically, outside the bracketed command blocks). A: Try by calling a method. @echo off pause for %%i in (*.txt) do ( call :makeRandom %%i ) echo Complete pause :makeRandom set /a y = %random% echo %y% echo %~1 >> backupF A: on my system I have to write set checker=Random instead of set checker=!Random!
unknown
d15340
val
Your event has to be data-dojo-attach-event="onClick:_onClick" On the button. Also for the returns on the request, your going to have to use dojo.hitch to hitch this. http://jsfiddle.net/theinnkeeper/qum452gm/
unknown
d15341
val
OK, here is the answer :) Spectral data from most spectrophotometers is already corrected in so far that the hardware illuminant and angle dont matter. What you do is just use the observer functions for every single angle/illuminant, as written in ASTM E308, to convert the spectral data to XYZ instead of only using the table which corresponds to the hardware illuminant/angle. Thats a lot of reference values but it works perfect.
unknown
d15342
val
After you've parsed your character string into an R expression, use match.call() to match supplied to formal arguments. f <- function(x,y,z) {} x <- "f(1,2,3)" ee <- parse(text = x)[[1]] cc <- match.call(match.fun(ee[[1]]), ee) as.list(cc)[-1] # $x # [1] 1 # # $y # [1] 2 # # $z # [1] 3 A: Alternatively: f <- function(x,y,z) {...} s <- "f(x = 2, y = 1, z = 3)" c <- as.list(str2lang(s)) c[-1] # $x # [1] 2 # # $y # [1] 1 # # $z # [1] 3 I was looking for a solution to this a while ago in order to reconstruct a function call from a string. Hopefully this will be of use to someone who is looking for a solution to a similar problem.
unknown
d15343
val
One option would be to create a CTE containing the ration_card_id values and the orders which you are imposing, and the join to this table: WITH cte AS ( SELECT 1247881 AS ration_card_id, 1 AS position UNION ALL SELECT 174772, 2 UNION ALL SELECT 808454, 3 UNION ALL SELECT 2326154, 4 ) SELECT t1.* FROM [MemberBackup].[dbo].[OriginalBackup] t1 INNER JOIN cte t2 ON t1.ration_card_id = t2.ration_card_id ORDER BY t2.position DESC Edit: If you have many IDs, then neither the answer above nor the answer given using a CASE expression will suffice. In this case, your best bet would be to load the list of IDs into a table, containing an auto increment ID column. Then, each number would be labelled with a position as its record is being loaded into your database. After this, you can join as I have done above. A: If the desired order does not reflect a sequential ordering of some preexisting data, you will have to specify the ordering yourself. One way to do this is with a case statement: SELECT * FROM [MemberBackup].[dbo].[OriginalBackup] where ration_card_id in ( 1247881,174772, 808454,2326154 ) ORDER BY CASE ration_card_id WHEN 1247881 THEN 0 WHEN 174772 THEN 1 WHEN 808454 THEN 2 WHEN 2326154 THEN 3 END Stating the obvious but note that this ordering most likely is not represented by any indexes, and will therefore not be indexed. A: Insert your ration_card_id's in #temp table with one identity column. Re-write your sql query as: SELECT a.* FROM [MemberBackup].[dbo].[OriginalBackup] a JOIN #temps b on a.ration_card_id = b.ration_card_id order by b.id
unknown
d15344
val
If you hang on the video device, you should read frames as soon as camera has them; you should either query the camera hardware for supported FPS, or get this information from the codec. If no information is available, you have to guess. It is suspicious that you get a crash when you don't read the frame in time; the worst which should happen in this case would be a lost frame. Depending on the camera colorspace you may also need to convert it before showing it on a screen. I don't see you doing that.
unknown
d15345
val
According to the JAX-WS specification, section 8.4.1, you don’t need an XPath to specify a package for JAX-WS classes like the service and port classes: <jaxws:bindings wsdlLocation="http://example.org/foo.wsdl"> <jaxws:package name="com.acme.foo"/>
unknown
d15346
val
Use the tool for the job: an HTML parser, like BeautifulSoup. You can pass a function as an attribute value to find_all() and check whether href starts with http: from bs4 import BeautifulSoup data = """ <div> <a href="http://google.com">test1</a> <a href="test2">test2</a> <a href="http://amazon.com">test3</a> <a href="here/we/go">test4</a> </div> """ soup = BeautifulSoup(data) print soup.find_all('a', href=lambda x: not x.startswith('http')) Or, using urlparse and checking for network location part: def is_relative(url): return not bool(urlparse.urlparse(url).netloc) print soup.find_all('a', href=is_relative) Both solutions print: [<a href="test2">test2</a>, <a href="here/we/go">test4</a>]
unknown
d15347
val
I agree with the suggestion given by Santiago. The correct command to disable the Internet Explorer using the Powershell is as below. Disable-WindowsOptionalFeature -online -FeatureName internet-explorer-optional-amd64 When you run the command, it will ask you whether you would like to restart the machine or later. You could enter the desired choice. Note: Make sure you are running the Powershell as Administrator.
unknown
d15348
val
Enter CollectinViewSource One thing you can do is connect your ListBox to your items through a CollectionViewSource. What you do is create the collectionViewSource in XAML: <Window.Resources> <CollectionViewSource x:Key="cvsItems"/> </Window.Resources> Connect to it in your CodeBehind or ViewModel Dim cvsItems as CollectionViewSource cvsItems = MyWindow.FindResource("cvsItems") and set it's source property to your collection of items. cvsItems.Source = MyItemCollection Then you can do filtering on it. The collectionViewSource maintains all of the items in the collection, but alters the View of those items based on what you tell it. Filtering To filter, create a CollectionView using your CollectionViewSource: Dim MyCollectionView as CollectionView = cvsItems.View Next write a filtering function: Private Function FilterDeleted(ByVal item As Object) As Boolean Dim MyObj = CType(item, MyObjectType) If MyObj.Deleted = True Then Return False Else Return True End If End Function Finally, write something that makes the magic happen: MyCollectionView .Filter = New Predicate(Of Object)(AddressOf FilterDeleted) I usually have checkboxes or Radiobuttons in a hideable expander that lets me change my filtering options back and forth. Those are bound to properties each of which runs the filter function which evaluates all the filters and then returns whether the item should appear or not. Let me know if this works for you. Edit: I almost forgot: <ListBox ItemsSource="{Binding Source={StaticResource cvsItems}}"/> A: The answer is to set the VirtualizingStackPanel.IsVirtual="False" in your listbox. Why don't my listboxitems collapse?
unknown
d15349
val
you seem to have ";" set as DELIMETER, which causes the query to execute once it sees a ";". try changing it first: DELIMITER // CREATE TRIGGER check_null_x2 BEFORE INSERT ON variations FOR EACH ROW BEGIN IF NEW.x2 IS NULL THEN SET NEW.x2_option1 = NULL; SET NEW.x2_option2 = NULL; END IF; END;// DELIMITER ; A: This is syntax for trigger: delimiter // CREATE TRIGGER upd_check BEFORE UPDATE ON account FOR EACH ROW BEGIN IF NEW.amount < 0 THEN SET NEW.amount = 0; ELSEIF NEW.amount > 100 THEN SET NEW.amount = 100; END IF; END;// delimiter ; ...and your code is here: DELIMITER // CREATE TRIGGER check_null_x2 BEFORE INSERT ON variations FOR EACH ROW BEGIN IF NEW.x2 IS NULL THEN SET NEW.x2_option1 = NULL; SET NEW.x2_option2 = NULL; END IF; END$$ -- THIS LINE SHOULD BE: "END;//" DELIMITER ; EDIT: The official Documentation says the following: If you use the mysql client program to define a stored program containing semicolon characters, a problem arises. By default, mysql itself recognizes the semicolon as a statement delimiter, so you must redefine the delimiter temporarily to cause mysql to pass the entire stored program definition to the server. To redefine the mysql delimiter, use the delimiter command. The following example shows how to do this for the dorepeat() procedure just shown. The delimiter is changed to // to enable the entire definition to be passed to the server as a single statement, and then restored to ; before invoking the procedure. This enables the ; delimiter used in the procedure body to be passed through to the server rather than being interpreted by mysql itself. A: CREATE TRIGGER `XXXXXX` BEFORE INSERT ON `XXXXXXXXXXX` FOR EACH ROW BEGIN IF ( NEW.aaaaaa IS NULL ) THEN SET NEW.XXXXXX = NULL; SET NEW.YYYYYYYYY = NULL; END IF; END Worked for me....
unknown
d15350
val
You can simply do draw the text using the pictureBox1_Paint event private void pictureBox1_Paint(object sender, PaintEventArgs e) { using (Font yourFont = new Font("Arial", 12)) { if (textBox1.Text != null) { string yourtext = textBox1.Text; e.Graphics.DrawString(yourtext, yourFont, Brushes.Red, new Point(5, 5)); this.Refresh(); //add this in your button click event if you want to perform it on a click event instead. } } } or, if you want to do this using a button click, then add this line this.Refresh(); on your button_Click event rather than applying directly in your pictureBox1_Paint event. private void button2_Click(object sender, EventArgs e) { this.Refresh(); } As per your new query... If you just want to display your image URL in the picturebox by just entering the URL in the textbox on a button click, then try: private void button1_Click(object sender, EventArgs e) { string str = textBox1.Text; pictureBox1.ImageLocation = str; } Alternatively, for displaying the image in the picturebox, use: private void button1_Click(object sender, EventArgs e) { string str = textBox1.Text; Image img = Image.FromFile(str); pictureBox1.Image = img; } A: On the click event of the submit button add the following code pictureBox.ImageLocation = textBox.Text;
unknown
d15351
val
d3 is good for generating charts. * *Stacked Area Chart example *Stacked Bar Chart example *more examples... A: The google Charts is very good. link here They also have a very cool playground, where you can see all kind of charts available, their code, examples, live demos and some fun stuff to try out. click here for playgound
unknown
d15352
val
The math here sounds complex enough that you're probably better off doing the complex stuff (averaging the values and determining whether a value is unique) in PHP, then finishing off with a couple simple MySQL statements. This can probably be done in pure MySQL with a bit of trickery, but frequently it isn't worth the time and complexity it creates. (Imagine you'll have to debug that monster SQL query six months from now!) By contrast, it's trivial to take a handful of values in PHP and average them; it's also trivial to run a quick MySQL query to determine whether a value is unique. So if you're unsure how to mash these together into one big SQL statement, start out by just handling them in the PHP code as separate steps! Then later on, if performance issues come up, you can think about how to combine them (but at least by that point you already have something that works).
unknown
d15353
val
~ Simple solution. Just doesn't work in the simulator.
unknown
d15354
val
You're pointing to master branch in your BuildConfig: source: git: ref: master uri: http://git-ooo-labs.apps.10.2.2.2.xip.io/ooo/lol.git secrets: null type: Git but should rather point to dev, as you're saying. Generally you need separate BC for the master and dev branches and each will have the webhook configured accordingly. Additionally the format for the branch is refs/heads/dev, since that's the information OpenShift gets from github. In the code we're checking for matching branches and ignore the hook if it doesn't match. Please check once again, and if you're still experiencing problem I'd ask you to open a bug against https://github.com/openshift/origin with detailed description. A: I created an issue on Github related to this behavior (GitHub issue #8600). I've been said I need to use a Github webhook, and not a generic webhook in this case. I switched the webhooks to github type, and it works like a charm.
unknown
d15355
val
=INDEX($A$1:$A$4,AGGREGATE(14,6,ROW($B$1:$H$4)/(L3=$B$1:$H$4),1)) assuming your example data is in the A1:H4 Range When you have duplicate value that can be found this formula will return the one in the largest row number. If you want the value in the first row number you can change the 14 to 15. EDIT Option 1 =INDEX($A$1:$A$21,AGGREGATE(14,6,ROW($B$18:$L$21)/(L3=$B$18:$L$21),1)) Option 2 =INDEX($A$18:$A$21,AGGREGATE(14,6,ROW($B$18:$L$21)/(L3=$B$18:$L$21),1)-ROW($A$18)+1) The problem you had when you moved it was most likely because of your range reference changes. The row number that is returned from the aggregate check has to be a row within the index range. So option one keep the index range large but matches all possible rows from the aggregate results. Option two reduces the range to just your data and adjust the results to subtract the number of rows before your data so its really referring to which row within the index range you want to look at. Option 3 Thanks to Scott Craner indicating the full column reference is perfectly acceptable outside the aggregate function, you could also use: =INDEX($A:$A,AGGREGATE(14,6,ROW($B$18:$L$21)/(L3=$B$18:$L$21‌​),1)
unknown
d15356
val
If you change your array_filter to the following the filter method will give you the values you want: $array2 = array_filter($fridaysUnique, function ($val) use ($productMonth) { return (DateTime::createFromFormat('l jS F', $val))->format('F') === $productMonth); }); What the code above does is it runs through all the values in your $fridaysUnique array and converts each value to a DateTime object that is formatted to a string for comparison with the value in $productMonth (note the use of use allowing you to use the $productMonth variable inside your anonymous filtering method). However instead of converting dates twice like this I would suggest you store DateTime objects in your array to start with.
unknown
d15357
val
Consider Amazon S3. I have used it several times in the past and it is very reliable both for processing a lot of files and for processing large files
unknown
d15358
val
Problem here is both thread working on same instance variable k of your class. So, when one thread modifies the value, it gets reflected in other thread. The output will always be indeterministic. Like i got this output - thread 18 valu= 10 thread 21 valu= 10 thread 18 valu= 9 thread 18 valu= 7 thread 18 valu= 6 thread 18 valu= 5 thread 18 valu= 4 thread 18 valu= 3 thread 18 valu= 2 thread 18 valu= 1 thread 21 valu= 8 You should used local variable inside aki method - public void aki(object ab) { int k = 10; // <---- HERE do { this.SetText1(textBox1.Text + " thread " + Thread.CurrentThread.GetHashCode() + " valu= " + k + Environment.NewLine); k--; } while (k >= 0); // It should be less than and equal to 0 to print 0. if (k < 0) Thread.CurrentThread.Abort(); }
unknown
d15359
val
What do the first brackets mean in the expression? It's the lambda syntax for a method that takes no parameters. If it took 1 parameter, it'd be: SomeMethod(x => x.Something); If it took n + 1 arguments, then it'd be: SomeMethod((x, y, ...) => x.Something); I'm also curious how you can get the property name from argument that is being passed in. Is this possible? If your SomeMethod takes an Expression<Func<T>>, then yes: void SomeMethod<T>(Expression<Func<T>> e) { MemberExpression op = (MemberExpression)e.Body; Console.WriteLine(op.Member.Name); } A: The () is an empty argument list. You're defining an anonymous function that takes no arguments and returns x.Something. Edit: It differs from x => x.Something in that the latter requires an argument and Something is called on that argument. With the former version x has to exist somewhere outside the function and Something is called on that outside x. With the latter version there does not have to be an outside x and even if there is, Something is still called on the argument to the function and nothing else. A: It's a lambda expression. That is, it's a way to create an anonymous function or delegate. The general form is: (input parameters) => expression If you have () => expression then you have created a function that takes no arguments, and returns the result of the expression. C# uses type inference to figure out what the types of the values are, and it captures local variables (like your "x" variable) by means of a lexical closure. A: I assume x is declared in somewhere inside your method, if yes, you can compare this lambda expression with a delegate that has no paramaters and return the type of x.someproperty delegate{ return x.someproperty; } that is the same as: () => x.someproperty A: the () mean that this method doesn't take any parameters. for example, if you assign a normal event handler using a lambda expression, it would look like this: someButton.Click += (s, e) => DoSomething(); A: See also the following two blog posts that discuss exactly your second question and provide alternative approaches: How to Find Out Variable or Parameter Name in C#? How to Get Parameter Name and Argument Value From C# Lambda via IL? (Or "How NOT to Use .NET Linq Expressions in Order to Get Parameter Name and Argument Value From C# Lambda?") A: To get the name of the property you need SomeMethod to have an argument of the type of System.Linq.Expressions.Expression<System.Func<object>>. You can then go through the expression to determine the property name.
unknown
d15360
val
$5.4/5 is about explicit type conversion (which is what is being used here) The conversions performed by — a const_cast (5.2.11), — a static_cast (5.2.9), — a static_cast followed by a const_cast, — a reinterpret_cast (5.2.10), or — a reinterpret_cast followed by a const_cast, can be performed using the cast notation of explicit type conversion. The same semantic restrictions and behaviors apply. If a conversion can be interpreted in more than one of the ways listed above, the interpretation that appears first in the list is used, even if a cast resulting from that interpretation is ill-formed. If a conversion can be interpreted in more than one way as a static_cast followed by a const_cast, the conversion is ill-formed. In this case, ((temp*)this) got treated as (const_cast<temp *>(this)) and was well-formed. This removed away the constness, thereby allowing to change the class member value. A: C++ tries to prevent accidental errors, but it doesn't go out of its way to fight a programmer who's determined to have things their own way. If you use cast operators you're telling it "trust me, I know what's there", demanding it ignore it's own knowledge of the program. It's precisely because the C-style casting operator you've used is dangerous and can be easily misused that C++ introduces static_cast, const_cast and reinterpret_cast, which communicate the programmer's intent in such a way that the compiler can still say "hey, hold on there, that'd require more than just the type of leniency you're asking for". reinterpret_cast is the big daddy though... no arguing with that... just as brutal as the C-cast and rarely needed in a high-level application. Precisely because it's rarely needed, verbose and easily seen, it draws scrutiny. Code littered with C-style casts can easily hide bugs. A: Because you're casting away const... When you cast something, the responsibility is yours for making sure that it doesn't do something dumb. Note that if temp t; is changed to const temp t;, you get undefined behavior, for modifying a const value. Coincidentally I literally just touched on this in my blog. (Almost the same function, too.)
unknown
d15361
val
Basically what you want is to be able to know that the data hasn't been loaded yet, and render differently based on that. A simple check would be see if the menu is empty. Something like this: export const Menu = ({ menu, fetchMenu }) => { useEffect(() => { fetchMenu(); }, []); if ( menu.length > 0 ) { return <Routes menu={menu} /> } else { return <MenuLoading /> } } A more advanced setup would be able to tell the difference between an empty menu due to an API error and a menu that's empty because it's still loading, but to do that you would need to store information about the status of the API call in the state.
unknown
d15362
val
Either m_KilledActors or tuple is not defined. In this case the bug is in your constructor List<Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>>> m_KilledActors = new List<Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>>>(); This causes a duplicate definition of m_KilledActors.. change it to just m_KilledActors = new List<Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>>>();
unknown
d15363
val
Looks like you're missing the escape character from the period ^(example)\..*$ should work A: It seems that a simple ^example\. is enough. Or use string methods, depending on your language: url.indexOf('example.') === 0 If input such as example.org is also possible, you can use ^example\..+\. to force the appearance of two dots. But this would still fail for example.co.uk. It depends on your input. A: A simple way might be to break it up into two: * *^.+\.example\.org$ *^(www)?\.example\.org$ If 1) matches and 2) does not, it's a subdomain of example.org; otherwise, it's not. (Although www technically is a subdomain, but you understand.)
unknown
d15364
val
Lets start with, left button is normally represented by MouseEvent.BUTTON1, then move onto MouseEvent#getModifiers is usually used to provide information about what keys are currently pressed and we begin to see the major problems. The method you really want is MouseEvent#getButton Try run the following example for some ideas ;) public class TestMouseClicked { public static void main(String[] args) { new TestMouseClicked(); } public TestMouseClicked() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException ex) { } catch (InstantiationException ex) { } catch (IllegalAccessException ex) { } catch (UnsupportedLookAndFeelException ex) { } JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(new MousePane()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class MousePane extends JPanel { private JToggleButton leftButton; private JToggleButton middleButton; private JToggleButton rightButton; public MousePane() { setLayout(new GridBagLayout()); leftButton = new JToggleButton("Left"); middleButton = new JToggleButton("Middle"); rightButton = new JToggleButton("Right"); add(leftButton); add(middleButton); add(rightButton); ButtonGroup bg = new ButtonGroup(); bg.add(leftButton); bg.add(middleButton); bg.add(rightButton); addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { System.out.println(e.getButton()); if (e.getButton() == MouseEvent.BUTTON1) { leftButton.setSelected(true); } else if (e.getButton() == MouseEvent.BUTTON2) { middleButton.setSelected(true); } else if (e.getButton() == MouseEvent.BUTTON3) { rightButton.setSelected(true); } } }); } } } A: Concerning the clicking only of a specific column: 1. create the table using you own model. final JTable table = new JTable( new MyTableModel(data, columnNames)); 2. create the new model overriding the function you need (i.e. isCellEditable) public class MyTableModel extends DefaultTableModel { private static final long serialVersionUID = -8422360723278074044L; MyTableModel(Object[][] data, Object[] columnNames ) { super(data,columnNames); } public boolean isCellEditable(int row,int cols) { if(cols==1 ){return true;} return false; } }
unknown
d15365
val
I am a little confused as to why you have any pages which are not registered using the WordPress functions. If the plugin/theme is complicated enough to need several distinct pages (not just one page with some tabs) then I suggest you add a standalone page using: http://codex.wordpress.org/Function_Reference/add_menu_page and then have several sub pages using: http://codex.wordpress.org/Function_Reference/add_submenu_page
unknown
d15366
val
in android manifest I added: android:hardwareAccelerated="true" solved the problem got 15fps higher.
unknown
d15367
val
I'm not sure if you're going to use a "real" camera and pictures or 3D renderings, but for rendering you should: * *render each side on a square texture *set X and Y fov to 90deg. *point the camera exactly along each axis: +X,-X,+Y,-Y,+Z,-Z This way you should get 6 pictures that work quite well together. If you want to do this for a "real" pictures, then you'll need some mapping from your distorted images to a cube map. This will depend on your lens, so it's not so easy; I think that professional apps for this task do this by comparing pictures, rather than just math.
unknown
d15368
val
Your question seems to rather compare dynamically allocated C-style arrays with variable-length arrays, which means that this might be what you are looking for: Why aren't variable-length arrays part of the C++ standard? However the c++ tag yields the ultimate answer: use std::vector object instead. As long as it is possible, avoid dynamic allocation and responsibility for ugly memory management ~> try to take advantage of objects with automatic storage duration instead. Another interesting reading might be: Understanding the meaning of the term and the concept - RAII (Resource Acquisition is Initialization) "And suppose we replace sizeof(int) * n with just n in the above code and then try to store integer values, what problems might i be facing?" - If you still consider n to be the amount of integers that it is possible to store in this array, you will most likely experience undefined behavior. A: The answer is simple. Local1 arrays are allocated on your stack, which is a small pre-allocated memory for your program. Beyond a couple thousand data, you can't really do much on a stack. For higher amounts of data, you need to allocate memory out of your stack. This is what malloc does. malloc allocates a piece of memory as big as you ask it. It returns a pointer to the start of that memory, which could be treated similar to an array. If you write beyond the size of that memory, the result is undefined behavior. This means everything could work alright, or your computer may explode. Most likely though you'd get a segmentation fault error. Reading values from the memory (for example for printing) is the same as reading from an array. For example printf("%d", list[5]);. Before C99 (I know the question is tagged C++, but probably you're learning C-compiled-in-C++), there was another reason too. There was no way you could have an array of variable length on the stack. (Even now, variable length arrays on the stack are not so useful, since the stack is small). That's why for variable amount of memory, you needed the malloc function to allocate memory as large as you need, the size of which is determined at runtime. Another important difference between local arrays, or any local variable for that matter, is the life duration of the object. Local variables are inaccessible as soon as their scope finishes. malloced objects live until they are freed. This is essential in practically all data structures that are not arrays, such as linked-lists, binary search trees (and variants), (most) heaps etc. An example of malloced objects are FILEs. Once you call fopen, the structure that holds the data related to the opened file is dynamically allocated using malloc and returned as a pointer (FILE *). 1 Note: Non-local arrays (global or static) are allocated before execution, so they can't really have a length determined at runtime. A: More fundamentally, I think, apart from the stack vs heap and variable vs constant issues (and apart from the fact that you shouldn't be using malloc() in C++ to begin with), is that a local array ceases to exist when the function exits. If you return a pointer to it, that pointer is going to be useless as soon as the caller receives it, whereas memory dynamically allocated with malloc() or new will still be valid. You couldn't implement a function like strdup() using a local array, for instance, or sensibly implement a linked representation list or tree. A: I assume you are asking what is the purpose of c maloc(): Say you want to take an input from user and now allocate an array of that size: int n; scanf("%d",&n); int arr[n]; This will fail because n is not available at compile time. Here comes malloc() you may write: int n; scanf("%d",&n); int* arr = malloc(sizeof(int)*n); Actually malloc() allocate memory dynamically in the heap area A: Some older programming environments did not provide malloc or any equivalent functionality at all. If you needed dynamic memory allocation you had to code it yourself on top of gigantic static arrays. This had several drawbacks: * *The static array size put a hard upper limit on how much data the program could process at any one time, without being recompiled. If you've ever tried to do something complicated in TeX and got a "capacity exceeded, sorry" message, this is why. *The operating system (such as it was) had to reserve space for the static array all at once, whether or not it would all be used. This phenomenon led to "overcommit", in which the OS pretends to have allocated all the memory you could possibly want, but then kills your process if you actually try to use more than is available. Why would anyone want that? And yet it was hyped as a feature in mid-90s commercial Unix, because it meant that giant FORTRAN simulations that potentially needed far more memory than your dinky little Sun workstation had, could be tested on small instance sizes with no trouble. (Presumably you would run the big instance on a Cray somewhere that actually had enough memory to cope.) *Dynamic memory allocators are hard to implement well. Have a look at the jemalloc paper to get a taste of just how hairy it can be. (If you want automatic garbage collection it gets even more complicated.) This is exactly the sort of thing you want a guru to code once for everyone's benefit. So nowadays even quite barebones embedded environments give you some sort of dynamic allocator. However, it is good mental discipline to try to do without. Over-use of dynamic memory leads to inefficiency, of the kind that is often very hard to eliminate after the fact, since it's baked into the architecture. If it seems like the task at hand doesn't need dynamic allocation, perhaps it doesn't. However however, not using dynamic memory allocation when you really should have can cause its own problems, such as imposing hard upper limits on how long strings can be, or baking nonreentrancy into your API (compare gethostbyname to getaddrinfo). So you have to think about it carefully. A: we could have used an ordinary array In C++ (this year, at least), arrays have a static size; so creating one from a run-time value: int lis[n]; is not allowed. Some compilers allow this as a non-standard extension, and it's due to become standard next year; but, for now, if we want a dynamically sized array we have to allocate it dynamically. In C, that would mean messing around with malloc; but you're asking about C++, so you want std::vector<int> lis(n, 1); to allocate an array of size n containing int values initialised to 1. (If you like, you could allocate the array with new int[n], and remember to free it with delete [] lis when you're finished, and take extra care not to leak if an exception is thrown; but life's too short for that nonsense.) Well I don't understand exactly how malloc works, what is actually does. So explaining them would be more beneficial for me. malloc in C and new in C++ allocate persistent memory from the "free store". Unlike memory for local variables, which is released automatically when the variable goes out of scope, this persists until you explicitly release it (free in C, delete in C++). This is necessary if you need the array to outlive the current function call. It's also a good idea if the array is very large: local variables are (typically) stored on a stack, with a limited size. If that overflows, the program will crash or otherwise go wrong. (And, in current standard C++, it's necessary if the size isn't a compile-time constant). And suppose we replace sizeof(int) * n with just n in the above code and then try to store integer values, what problems might i be facing? You haven't allocated enough space for n integers; so code that assumes you have will try to access memory beyond the end of the allocated space. This will cause undefined behaviour; a crash if you're lucky, and data corruption if you're unlucky. And is there a way to print the values stored in the variable directly from the memory allocated space, for example here it is lis? You mean something like this? for (i = 0; i < len; ++i) std::cout << lis[i] << '\n';
unknown
d15369
val
regex_match The algorithm regex_match determines whether a given regular expression matches all of a given character sequence denoted by a pair of bidirectional-iterators, the algorithm is defined as follows, the main use of this function is data input validation. regex_search The algorithm regex_search will search a range denoted by a pair of bidirectional-iterators for a given regular expression. The algorithm uses various heuristics to reduce the search time by only checking for a match if a match could conceivably start at that position. The algorithm is defined as follows: So, use boost::regex_search. Example. http://liveworkspace.org/code/fa35778995c4bd1e191c785671ab94b6
unknown
d15370
val
The java property user.home performs the same role as the ~ from *NIX systems. (Note: On windows, the USERPROFILE environment variable fills this role) Ivy can work with java system properties, just use the ${user.home} notation as you would in Ant. References: * *http://www.mindspring.com/~mgrand/java-system-properties.htm *http://www.wilsonmar.com/1envvars.htm#WinVars *http://ant.apache.org/ivy/history/2.0.0-rc1/settings.html
unknown
d15371
val
setAudioEncodingBitRate(int bitRate) is not decreased, it is working since API 8 (2.2), and some encoding formats and frequencies, like AAC 44,1KHz, only since API 10 (2.3.3) :(
unknown
d15372
val
Contentful DevRel here. There has been a breaking change in the gatsby-source-contentful in v4. It's now recommended to use raw. You can find more information in the changelog. A recommended Gatsby query from the changelog: export const pageQuery = graphql` query pageQuery($id: String!) { contentfulPage(id: { eq: $id }) { title slug description { raw references { ... on ContentfulPage { # contentful_id is required to resolve the references contentful_id title slug } ... on ContentfulAsset { # contentful_id is required to resolve the references contentful_id fluid(maxWidth: 600) { ...GatsbyContentfulFluid_withWebp } } } } } } `
unknown
d15373
val
From the official page, you create a browser object by br = mechanize.Browser() and follow a link with the object - br.open("http://www.example.com/"), and then you select a form by br.select_form(name="searchform") and you can pass an input by br["s"] = #something and submit it resp = br.submit() use the resp object like you wish.
unknown
d15374
val
$("#map_link").one('click', function(event) { A: Keep track of whether or not it has been clicked and return false if it has been clicked $(function() { var click_limit = 1, clicks = 0; $("#map_link").click(function(event) { if (clicks++ === click_limit){ return false; } event.preventDefault(); $("#map").slideToggle(); $("#map").html('Iframe_code_is_situated_here').css('display','block'); }); });
unknown
d15375
val
You can use ruby plugin to do it. input { stdin {} } filter { ruby { code => " fieldArray = event['message'].split(' '); for field in fieldArray name = field.split('=')[0]; value = field.split('=')[1]; if value =~ /\A\d+\Z/ event[name] = value.to_i else event[name] = value end end " } } output { stdout { codec => rubydebug } } First, split the message to an array by SPACE. Then, for each k,v mapping, check whether the value is numberic, if YES, convert it to Integer. Here is the sample output for your input: { "message" => "name=johnny amount=30 uuid=2039248934", "@version" => "1", "@timestamp" => "2015-06-25T08:24:39.755Z", "host" => "BEN_LIM", "name" => "johnny", "amount" => 30, "uuid" => 2039248934 } Update Solution for Logstash 5: input { stdin {} } filter { ruby { code => " fieldArray = event['message'].split(' '); for field in fieldArray name = field.split('=')[0]; value = field.split('=')[1]; if value =~ /\A\d+\Z/ event.set(name, value.to_i) else event.set(name, value) end end " } } output { stdout { codec => rubydebug } } A: Note, if you decide to upgrade to Logstash 5, there are some breaking changes: https://www.elastic.co/guide/en/logstash/5.0/breaking-changes.html In particular, it is the event that needs to be modified to use either event.get or event.set. Here is what I used to get it working (based on Ben Lim's example): input { stdin {} } filter { ruby { code => " fieldArray = event.get('message').split(' '); for field in fieldArray name = field.split('=')[0]; value = field.split('=')[1]; if value =~ /\A\d+\Z/ event.set(name, value.to_i) else event.set(name, value) end end " } } output { stdout { codec => rubydebug } }
unknown
d15376
val
The 4th argument of query() is the WHERE clause of the query (without the keyword WHERE) and for it you pass "row". Also, the 2nd argument is the table's name for which you pass "r_id", but the error message does not contain ...FROM r_id... (although it should), so I guess that the code you posted is not your actual code. So your query (translated in SQL) is: SELECT DISTINCT r_id FROM my_table WHERE row LIMIT 1 which is invalid. But you don't need a WHERE clause if you want just the min value of the column r_id. You can do it with a query like: SELECT MIN(r_id) AS r_id FROM my_table without DISTINCT and a WHERE clause. Or: SELECT r_id FROM my_table ORDER BY r_id LIMIT 1; So your java code should be: public String getSetting() { SQLiteDatabase db = databaseHelper.getReadableDatabase(); Cursor c = db.rawQuery("SELECT MIN(r_id) AS r_id FROM my_table", null); String result = c.moveToFirst() ? c.getString(0) : "result not found"; c.close(); databaseHelper.close(); return result; } I used rawQuery() here instead of query(). Or: public String getSetting() { SQLiteDatabase db = databaseHelper.getReadableDatabase(); Cursor c = db.query(false, "my_table", new String[] {"r_id"}, null, null, null, null, "r_id", "1"); String result = c.moveToFirst() ? c.getString(0) : "result not found"; c.close(); databaseHelper.close(); return result; }
unknown
d15377
val
Just edit your TFSBuild.proj file for the build, and add this to opne of the property groups: <CustomizableOutDir>true</CustomizableOutDir> This will automatically then cause the build to output the build output as per normal (like Visual Studio).
unknown
d15378
val
There is a skip method in BufferedReader. Probably you would like to have look at it. BufferedReader#skip (long) A: use fis.skip(12); Or create a counter int count = 12; while (..) { count--; if (count > 0) continue; // your code } A: You should be able to just do: fis.read(new byte[12]); A: Loop over fis.read() by skipNumberOFCharacter. for(int i = 0; i < skipNumberOfCharacter; i++) fis.read();
unknown
d15379
val
You could take the lineHeight of the UIFont that the label's using and make its frame's height that times three. A: I had a similar case where I needed to have a cell with a constant height, but the contents of a label could be shorter than what was needed to have it always have three lines. I duplicated the label, set the contents to "1\n2\n3" to give it the three lines required, set it to hidden, and then gave it the top and bottom constraints of the label I wanted to have a consistent height. Then I set the visible label top constraint to my placeholder and removed its bottom constraint. Now the placeholder fixes the height at the required amount and the visible label will grow down (to the maximum of three lines) as needed while staying fixed to the top (and not centering verticaly if it doesn't have content for three lines).
unknown
d15380
val
You might have to remove some old files: # If errors are found, do this # clear contents of C:\Users\<username>\AppData\Local\Temp\gen_py # that should fix it, to test it type import win32com.client app = win32com.client.gencache.EnsureDispatch("Outlook.Application") app.Visible = True This gist also has other solutions that remove the files automatically. Application needs to be adjusted. 1.) from pathlib import Path try: xl = win32.gencache.EnsureDispatch('Excel.Application') except AttributeError: f_loc = r'C:\Users\<username>\AppData\Local\Temp\gen_py' for f in Path(f_loc): Path.unlink(f) Path.rmdir(f_loc) xl = win32.gencache.EnsureDispatch('Excel.Application') 2.) try: xl = client.gencache.EnsureDispatch('Excel.Application') except AttributeError: # Corner case dependencies. import os import re import sys import shutil # Remove cache and try again. MODULE_LIST = [m.__name__ for m in sys.modules.values()] for module in MODULE_LIST: if re.match(r'win32com\.gen_py\..+', module): del sys.modules[module] shutil.rmtree(os.path.join(os.environ.get('LOCALAPPDATA'), 'Temp', 'gen_py')) from win32com import client xl = client.gencache.EnsureDispatch('Excel.Application') A: I was having the same issue and managed to resolve it by doing the following from win32com.client import gencache.py gencache._Dump() The _Dump() command will print the location of the cache directory. Deleting the directory resolved the issue for me.
unknown
d15381
val
@James R. Perkins Thanks for pointing me in the right direction. I stopped Wildfly 13 and sure enough, I still had something listening on Port 8080 MacBook-Pro:bin NOTiFY$ sudo lsof -i :8080 Password: COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME java 437 NOTiFY 163u IPv6 0x299d8c12df3e5311 0t0 TCP localhost:http-alt (LISTEN) Killed the PID and ran my JUnit test again and (as hoped) got: org.apache.http.conn.HttpHostConnectException: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1, localhost/fe80:0:0:0:0:0:0:1%1] failed: Connection refused Restarted WildFly 13 and successfully re-ran my JUnit test: test01GetListEnumbers url = http://localhost:8080/NOTiFYwell/notifywell/get-all-enumbers/ test01GetListEnumbers response getStatus = 200 test01GetListEnumbers response getEntity = [ { "id": "5b6c5dbefac4f7105b3cca2e", "code": "E100", "name": "Curcumin (from turmeric)", "colour": "Yellow-orange", "status": "Approved in the EU.Approved in the US." }, Still not sure where Jetty 9.x has come from. This corresponds with having to reboot my Mac after I used 'Migration Assistant' to copy everything from my old MacBook to the new. Jetty appears to start on reboot. Will investigate.
unknown
d15382
val
Found out the answer: {{ url_for('login', user='foo', name='test') }} This will create a query like this: http://127.0.0.1:10000/login?user=foo&name=test
unknown
d15383
val
try Bamini, it works for my application. http://www.jagatheswara.com/tamil.php
unknown
d15384
val
After extensively trying out things, I stumbled upon a thread in a foreign language which I cannot find it. The thread said something about the artifact being passed to the action cannot be larger than 3 MB. I solved my problem by reducing the size of the artifact (config). The configuration repository is shared among many projects and by moving those items to another project, I decreased the compressed artifact size from 14 MB to 3 kB. Miraculously, everything worked fine. AWS if you are reading this, please add more documentation about the artifact size limits to ECS CodeDeploy as I don't see any mention about this and I have no way of debugging this problem with such a general error message. A: As far as I understand there are three major things we have to check as even if there is a syntax issue on file we might get the exception * *Files exists on correct path and you have already verified this. *Content of the both taskdef.json file and appspec.yaml is proper without any syntax error and we can always refer to this document [1] for it. *Also make sure that image has correct place holder "<IMAGE1_NAME>". *Also if these options don't work then you may try to create on test public github repo just put taskdef.json and appspec.yaml file in it and test the same thing. [1] Tutorial: Create a Pipeline with an Amazon ECR Source and ECS-to-CodeDeploy Deployment - https://docs.aws.amazon.com/codepipeline/latest/userguide/tutorials-ecs-ecr-codedeploy.html A: Thought I know a little about artifact config and could not found any help. I created another codecommit repo where i stored appspec.yml and taskdef.json file only and followed this aws userguide. And this worked Previously I was committing those file with main project repo. But every time it failed in deploy state with this message.[Exception while trying to read the task definition artifact file from ...] I felt safe this way in production codebuild and codedeploy are separated in pipeline. I created artifact pipeline and build pipeline. Two pipeline. To blue/green ECS service.
unknown
d15385
val
To get the total count use {$smarty.section.customer.total} A: By 'count' do you mean the current index of the loop? If so you can use this {section name=customer loop=$custid} {$smarty.section.customer.index} id: {$custid[customer]}<br /> {/section} http://www.smarty.net/docsv2/en/language.function.section.tpl#section.property.index A: Try {counter} http://www.smarty.net/docsv2/en/language.function.counter.tpl Exapmle: {counter start=0 print=false name=bla} {section name=i loop=$getFriends start=0 step=1} {counter} {/section} A: {assign var=val value=0} {section name=i loop=$data} {assign var=val value=$val+1} {/section}
unknown
d15386
val
XNA is an interesting platform, but I have noticed it having some performance issues when loading in models. I have not used WPF to do this, but XNA does also require installing of its framework, to run the application. I suggest you avoid it, for the hurdles you must jump to get what you want out of it. DirectX libraries are a good way to accomplish this, there are thousands of examples of this being used out there. Very Good,Good, Ok You can also use a .X exporter for Maya to import your models. Something like this DirectX Maya Exporter
unknown
d15387
val
Here's a simple function which returns the dominant color given an ImageProvider. This shows the basic usage of Palette Generator without all the boilerplate. import 'package:palette_generator/palette_generator.dart'; // Calculate dominant color from ImageProvider Future<Color> getImagePalette (ImageProvider imageProvider) async { final PaletteGenerator paletteGenerator = await PaletteGenerator .fromImageProvider(imageProvider); return paletteGenerator.dominantColor.color; } Then use FutureBuilder on the output to build a Widget. A: I probably think you got a fix but for future searches to this question, I suggest you check Pallete Generator by the flutter team. I will try and give a simple explanation of how the code works but for a detailed example head over to the plugin's GitHub repo. The example below is going to take an image then select the dominant colors from it and then display the colors First, we add the required imports import 'package:palette_generator/palette_generator.dart'; After that let's create the main application class. class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( ... home: const HomePage( title: 'Colors from image', image: AssetImage('assets/images/artwork_default.png',), imageSize: Size(256.0, 170.0), ... ), ); } } In the image field above, place the image that you want to extract the dominant colors from, i used the image shown here. Next, we create the HomePage class @immutable class HomePage extends StatefulWidget { /// Creates the home page. const HomePage({ Key key, this.title, this.image, this.imageSize, }) : super(key: key); final String title; //App title final ImageProvider image; //Image provider to load the colors from final Size imageSize; //Image dimensions @override _HomePageState createState() { return _HomePageState(); } } Lets create the _HomePageState too class _HomePageState extends State<HomePage> { Rect region; PaletteGenerator paletteGenerator; final GlobalKey imageKey = GlobalKey(); @override void initState() { super.initState(); region = Offset.zero & widget.imageSize; _updatePaletteGenerator(region); } Future<void> _updatePaletteGenerator(Rect newRegion) async { paletteGenerator = await PaletteGenerator.fromImageProvider( widget.image, size: widget.imageSize, region: newRegion, maximumColorCount: 20, ); setState(() {}); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: _kBackgroundColor, appBar: AppBar( title: Text(widget.title), ), body: Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ new AspectRatio( aspectRatio: 15 / 15, child: Image( key: imageKey, image: widget.image, ), ), Expanded(child: Swatches(generator: paletteGenerator)), ], ), ); } } The code above just lays out the image and the Swatches which is a class defined below. In initState, we first select a region which the colors will be derived from which in our case is the whole image. After that we create a class Swatches which receives a PalleteGenerator and draws the swatches for it. class Swatches extends StatelessWidget { const Swatches({Key key, this.generator}) : super(key: key); // The PaletteGenerator that contains all of the swatches that we're going // to display. final PaletteGenerator generator; @override Widget build(BuildContext context) { final List<Widget> swatches = <Widget>[]; //The generator field can be null, if so, we return an empty container if (generator == null || generator.colors.isEmpty) { return Container(); } //Loop through the colors in the PaletteGenerator and add them to the list of swatches above for (Color color in generator.colors) { swatches.add(PaletteSwatch(color: color)); } return Column( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ //All the colors, Wrap( children: swatches, ), //The colors with ranking Container(height: 30.0), PaletteSwatch(label: 'Dominant', color: generator.dominantColor?.color), PaletteSwatch( label: 'Light Vibrant', color: generator.lightVibrantColor?.color), PaletteSwatch(label: 'Vibrant', color: generator.vibrantColor?.color), PaletteSwatch( label: 'Dark Vibrant', color: generator.darkVibrantColor?.color), PaletteSwatch( label: 'Light Muted', color: generator.lightMutedColor?.color), PaletteSwatch(label: 'Muted', color: generator.mutedColor?.color), PaletteSwatch( label: 'Dark Muted', color: generator.darkMutedColor?.color), ], ); } } After that lets create a PaletteSwatch class. A palette swatch is just a square of color with an optional label @immutable class PaletteSwatch extends StatelessWidget { // Creates a PaletteSwatch. // // If the [color] argument is omitted, then the swatch will show a // placeholder instead, to indicate that there is no color. const PaletteSwatch({ Key key, this.color, this.label, }) : super(key: key); // The color of the swatch. May be null. final Color color; // The optional label to display next to the swatch. final String label; @override Widget build(BuildContext context) { // Compute the "distance" of the color swatch and the background color // so that we can put a border around those color swatches that are too // close to the background's saturation and lightness. We ignore hue for // the comparison. final HSLColor hslColor = HSLColor.fromColor(color ?? Colors.transparent); final HSLColor backgroundAsHsl = HSLColor.fromColor(_kBackgroundColor); final double colorDistance = math.sqrt( math.pow(hslColor.saturation - backgroundAsHsl.saturation, 2.0) + math.pow(hslColor.lightness - backgroundAsHsl.lightness, 2.0)); Widget swatch = Padding( padding: const EdgeInsets.all(2.0), child: color == null ? const Placeholder( fallbackWidth: 34.0, fallbackHeight: 20.0, color: Color(0xff404040), strokeWidth: 2.0, ) : Container( decoration: BoxDecoration( color: color, border: Border.all( width: 1.0, color: _kPlaceholderColor, style: colorDistance < 0.2 ? BorderStyle.solid : BorderStyle.none, )), width: 34.0, height: 20.0, ), ); if (label != null) { swatch = ConstrainedBox( constraints: const BoxConstraints(maxWidth: 130.0, minWidth: 130.0), child: Row( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ swatch, Container(width: 5.0), Text(label), ], ), ); } return swatch; } } Hope this helps, thank you. A: ////////////////////////////// // // 2019, roipeker.com // screencast - demo simple image: // https://youtu.be/EJyRH4_pY8I // // screencast - demo snapshot: // https://youtu.be/-LxPcL7T61E // ////////////////////////////// import 'dart:async'; import 'dart:typed_data'; import 'dart:ui' as ui; import 'dart:math'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:image/image.dart' as img; import 'package:flutter/services.dart' show rootBundle; void main() => runApp(const MaterialApp(home: MyApp())); class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override State<StatefulWidget> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { String imagePath = 'assets/5.jpg'; GlobalKey imageKey = GlobalKey(); GlobalKey paintKey = GlobalKey(); // CHANGE THIS FLAG TO TEST BASIC IMAGE, AND SNAPSHOT. bool useSnapshot = true; // based on useSnapshot=true ? paintKey : imageKey ; // this key is used in this example to keep the code shorter. late GlobalKey currentKey; final StreamController<Color> _stateController = StreamController<Color>(); //late img.Image photo ; img.Image? photo; @override void initState() { currentKey = useSnapshot ? paintKey : imageKey; super.initState(); } @override Widget build(BuildContext context) { final String title = useSnapshot ? "snapshot" : "basic"; return SafeArea( child: Scaffold( appBar: AppBar(title: Text("Color picker $title")), body: StreamBuilder( initialData: Colors.green[500], stream: _stateController.stream, builder: (buildContext, snapshot) { Color selectedColor = snapshot.data as Color ?? Colors.green; return Stack( children: <Widget>[ RepaintBoundary( key: paintKey, child: GestureDetector( onPanDown: (details) { searchPixel(details.globalPosition); }, onPanUpdate: (details) { searchPixel(details.globalPosition); }, child: Center( child: Image.asset( imagePath, key: imageKey, //color: Colors.red, //colorBlendMode: BlendMode.hue, //alignment: Alignment.bottomRight, fit: BoxFit.contain, //scale: .8, ), ), ), ), Container( margin: const EdgeInsets.all(70), width: 50, height: 50, decoration: BoxDecoration( shape: BoxShape.circle, color: selectedColor!, border: Border.all(width: 2.0, color: Colors.white), boxShadow: [ const BoxShadow( color: Colors.black12, blurRadius: 4, offset: Offset(0, 2)) ]), ), Positioned( child: Text('${selectedColor}', style: const TextStyle( color: Colors.white, backgroundColor: Colors.black54)), left: 114, top: 95, ), ], ); }), ), ); } void searchPixel(Offset globalPosition) async { if (photo == null) { await (useSnapshot ? loadSnapshotBytes() : loadImageBundleBytes()); } _calculatePixel(globalPosition); } void _calculatePixel(Offset globalPosition) { RenderBox box = currentKey.currentContext!.findRenderObject() as RenderBox; Offset localPosition = box.globalToLocal(globalPosition); double px = localPosition.dx; double py = localPosition.dy; if (!useSnapshot) { double widgetScale = box.size.width / photo!.width; print(py); px = (px / widgetScale); py = (py / widgetScale); } int pixel32 = photo!.getPixelSafe(px.toInt(), py.toInt()); int hex = abgrToArgb(pixel32); _stateController.add(Color(hex)); } Future<void> loadImageBundleBytes() async { ByteData imageBytes = await rootBundle.load(imagePath); setImageBytes(imageBytes); } Future<void> loadSnapshotBytes() async { RenderRepaintBoundary boxPaint = paintKey.currentContext!.findRenderObject() as RenderRepaintBoundary; //RenderObject? boxPaint = paintKey.currentContext.findRenderObject(); ui.Image capture = await boxPaint.toImage(); ByteData? imageBytes = await capture.toByteData(format: ui.ImageByteFormat.png); setImageBytes(imageBytes!); capture.dispose(); } void setImageBytes(ByteData imageBytes) { List<int> values = imageBytes.buffer.asUint8List(); photo; photo = img.decodeImage(values)!; } } // image lib uses uses KML color format, convert #AABBGGRR to regular #AARRGGBB int abgrToArgb(int argbColor) { int r = (argbColor >> 16) & 0xFF; int b = argbColor & 0xFF; return (argbColor & 0xFF00FF00) | (b << 16) | r; }
unknown
d15388
val
Solution is to define arr differently, i.e.: arr = [400 200; 100 50];
unknown
d15389
val
I ended up with following factory class as shown below being used for animations[]:- This is used as below: @Component({ selector: 'my-app-header', moduleId: module.id, templateUrl: './app-header.component.html', styleUrls: ['./app-header.component.scss'], animations: [ MyToolbarAnimator.createTrigger('appHeaderState', '50px', '0') ] }) Defined MyToolbarAnimator with a static method createTrigger which returns AnimationTriggerMetadata as shown below MyToolbarAnimator import {trigger, state, style, animate, transition, AnimationTriggerMetadata} from '@angular/animations'; export const HEADER_SHRINK_TRANSITION = '250ms cubic-bezier(0.4,0.0,0.2,1)'; export class MyToolbarAnimator { static createTrigger(triggerName: string, initialTop: string, upTop: string): AnimationTriggerMetadata { return trigger(triggerName, [ state('initial', style({top: initialTop})), state('up', style({top: upTop})), transition('initial => up, up => initial', animate(HEADER_SHRINK_TRANSITION)) ]); } } UPDATE: Or if your animation parameters are very dynamic and changes based on the component behavior use https://angular.io/api/animations/AnimationBuilder#usage-notes This // import the service from BrowserAnimationsModule import {AnimationBuilder} from '@angular/animations'; // require the service as a dependency class MyCmp { width = 100; constructor(private _builder: AnimationBuilder) {} changeWidth(aWidth:number) { this.width = aWidth; } makeAnimation(element: any) { // first define a reusable animation const myAnimation = this._builder.build([ style({ width: 0 }), animate(1000, style({ width: `${this.width}px` })) ]); // use the returned factory object to create a player const player = myAnimation.create(element); player.play(); } }
unknown
d15390
val
Using perl: perl -F, -lane 'my %s; print if grep { $s{$_}++ } @F' Uses: * *-F, to set field separator to , *-l to automatically handle linefeeds *-a to autosplit *-n to wrap it in a while ( <> ) { loop. *-e to specify code to exec. Incoming data is autosplit on , into @F and we use a %s hash to spot if there's a dupe. If — based on your comment — you need to skip empty fields (which this would count as dupes): perl -F, -lane 'my %s; print if grep { /./ ? $s{$_}++ : () } @F' This includes a ternary operator to test if a field is empty. Testing with Windows (which isn't quite the same, because of quotes): C:\Users\me>perl -F, -lane "my %s; print qq{line matches:$_} if grep { /./ ? $s{$_}++ : () } @F" line matches:John,Smith,Smith,21 line matches:John,42,42,42 If written longhand, it looks more like this: #!/usr/bin/env perl use strict; use warnings; while ( my $line = <DATA> ) { my %seen; chomp($line); my @fields = split /,/, $line; if ( grep { /./ and $seen{$_}++ } @fields ) { print $line,"\n"; } } __DATA__ John,Smith,Smith,21 Mary,Jones,Smith,32 John,42,42,42 Henry,Brown,Jones,31 Mary,,,21 You could use the Text::CSV module to parse it, but I would suggest not doing so, unless you're specifically dealing with quoting/embedded linefeeds etc. E.g.: #!/usr/bin/env perl use strict; use warnings; use Data::Dumper; use Text::CSV; my $csv = Text::CSV -> new ( {sep_char => ',', eol => "\n", binary => 1} ); while ( my $row = $csv -> getline ( \*DATA ) ) { my %seen; if ( grep { /./ and $seen{$_}++ } @$row ) { print join ",", @$row, "\n"; } } __DATA__ John,Smith,Smith,21 Mary,Jones,Smith,32 John,42,42,42 Henry,Brown,Jones,31 Mary,,,21 A: Using awk you can do: awk -F, '{delete a; for (i=1;i<=NF;i++) if ($i!="") if ($i in a) {print; next} else a[$i]}' file John,Smith,Smith,21 John,42,42,42 A: $ awk -F, '{delete seen; for (i=1;i<=NF;i++) if ( ($i!="") && seen[$i]++ ) { print; next } }' file John,Smith,Smith,21 John,42,42,42 A: If you'd like a Perl solution that you can integrate into a larger script (and doesn't quite so closely resemble line noise), and that correctly handles CSV data where a field contains a comma, I'd use the Text::CSV module: #!/usr/bin/perl use strict; use warnings; use Text::CSV; my $file = shift or die "Usage: $0 <file>\n"; open my $fh, '<', $file or die "Cannot open $file: $!\n"; my $csv = Text::CSV->new(); while (my $row = $csv->getline($fh)) { my %h; $h{$_}++ for @{$row}; for my $dup_field (grep { $h{$_} > 1 } keys %h) { if (length $dup_field) { print $csv->string(); next; } } } A: If you like perl and regex, then this looks good : perl -ne 'print if /(?:^|,)([^,]+),(?:.*,)?\1(?:,|$)/' If you need explanations : ([^,]+) matches a "word" (in that context, I use "word" to mean "the data of a row"), and \1 will see if it is repeated. (?:.*,)? allows other words to be between the repetitions of your data. And finally (?:^|,) and (?:,|$) ensure that the 2 repeated words are the same, and no one is a substring of the other.
unknown
d15391
val
If the following code for index, column in enumerate(columns): print "In column %s, Max = %s, Min = %s" % (index, max(column), min(column)) you provided gives you correct answers and I understand you correctly, than getting min value (for example) from specific column should be easy enough, along the lines of min(columns[index_of_column]), for example: min(columns[4]) For max value in column, replace min() with max(). And, remember, index_of_column is zero based (first column has index of 0, so 5th column would have an index of 4). So, to get both min and max value, you would do: print "In column %s, Max = %s, Min = %s" % (5, max(columns[4]), min(columns[4]))
unknown
d15392
val
You can do with $project and $lookup. * *$project to include or exclude the fields $project *$lookup to join collections. Here I have used uncorrelated-sub-queries. But there is a standard $lookup too Here is the code db.Employees.aggregate([ { "$project": { _id: 1, emp_id: 1, first_name: 1, last_name: 1 } }, { "$lookup": { "from": "Salaries", let: { eId: "$emp_id" }, pipeline: [ { $match: { $expr: { $and: [ { $eq: [ "$$eId", "$emp_id" ] }, { $gt: [ "$salary", 80000 ] }, { $eq: [ "$to_date", "2002-06-22" ] } ] } } } ], "as": "salary" } } ]) Working Mongo playground
unknown
d15393
val
You can use stack and rework the index: B = A.stack() B.index = B.index.map('_'.join) out = B.to_frame('Values') output: Values aa_ba 2.0 aa_bb 4.2 aa_bc 8.1 ab_ba 9.4 ab_bb 7.1 ab_bc 9.5 ac_ba 10.8 ac_bb 3.0 ac_bc 6.1 A: Since you have your indexes set, you can do this most easily with a .stack operation. This results in a pd.Series with a MultiIndex, we can use a "_".join to join each level of the MultiIndex by an underscore and create a flat Index. Lastly, since you wanted a single column DataFrame you can use .to_frame() to convert the Series into a DataFrame out = A.stack() out.index = out.index.map("_".join) out = out.to_frame("values") print(out) values aa_ba 2.0 aa_bb 4.2 aa_bc 8.1 ab_ba 9.4 ab_bb 7.1 ab_bc 9.5 ac_ba 10.8 ac_bb 3.0 ac_bc 6.1 You can also use a method chained approach- just need to use .pipe to access the stacked index: out = ( A.stack() .pipe(lambda s: s.set_axis(s.index.map("_".join))) .to_frame("values") ) print(out) values aa_ba 2.0 aa_bb 4.2 aa_bc 8.1 ab_ba 9.4 ab_bb 7.1 ab_bc 9.5 ac_ba 10.8 ac_bb 3.0 ac_bc 6.1 A: Stack, use list comprehension and fstrings to compute new index . s = A.stack().to_frame('values') s.index=([f'{a}_{b}' for a,b in s.index]) values aa_ba 2.0 aa_bb 4.2 aa_bc 8.1 ab_ba 9.4 ab_bb 7.1 ab_bc 9.5 ac_ba 10.8 ac_bb 3.0 ac_bc 6.1
unknown
d15394
val
input() will always return a string unless you explicity convert it. So using ask_option = int(input("Your option: ")) will already satisfy checking if ask_option is an integer as an exception will be raised otherwise. As for evaluating the integer, you can accomplish this in a single line such as: if not 1 <= ask_option <= 4: print("Not a valid option") A: If you try to convert string input into an int, the program will throw ValueError. ask_option = input("Your option: ") try: val = int(ask_option) if val <= 1 or val => 4: print("Not a valid option!") except ValueError: print("Not a valid option!") A: ask_option = input("Your option: ") if len(ask_option) != 1 or ask_option < '1' or ask_option > '4': print("Not a valid option") else: print( "valid option") Edit: OP: "I want to display an invalid option message if the input is a string or it is not a number between 1 to 4." Therefore we need to accept values ranging from 1 - 4 We know that input() accepts everything as a string so in the if statement first condition: len(ask_option) != 1 We invalidate any string whose length is not equal to 1 ( since we need to accept values ranging from 1-4 which are of a length 1 ) And now we are left to deal with the input value whose length is just 1 which could be anything and will be checked with the next 2 conditions. second and third condition: ask_option < '1' or ask_option > '4' We do string comparison ( which is done using their ASCII values ) more on string comparison: String comparison technique used by Python I would not recommend using this approach since it's hard to tell what it does on the first look, so it's better if you use try except instead as suggested in other answers. See this solution as just a different approach to solve OP's problem ( but not recommended to implement. )
unknown
d15395
val
Have you tried to truncate text using ellipsizeMode A: There are at least two different solutions. * *Render custom list item https://github.com/hossein-zare/react-native-dropdown-picker/issues/460 *Following pull gets merged or you make such changes manually before it happends https://github.com/hossein-zare/react-native-dropdown-picker/pull/542 As I'm aware of labelProps with numberOfLines: 1 should work when picker is not open so that text would not wrap. But for it to work in list items there is no prop yet to easily achieve this.
unknown
d15396
val
You can define the centroids as the means of variables, per cluster, in DATABASE. mydist <- dist(DATABASE) clusters <- cutree(hclust(mydist), k = 3) ## Col means in each cluster apply(DATABASE, 2, function (x) tapply(x, clusters, mean)) ## or DATABASE$cluster <- clusters # add cluster to DATABASE # Now take means per group library(dplyr) centroids <- DATABASE %>% group_by(cluster) %>% summarise_all(funs(mean)) ## Distance between centroids dist(centroids[, -1], method = "euclidean") ## Example for distance in cluster 1 (distance between all observations of cluster 1) DATABASE %>% filter(cluster == 1) %>% select(-cluster) %>% dist() A: you might want to specify your k value into 1:3 not just 3 here is the code and how to find the center (mean)
unknown
d15397
val
The controller within the GUI is not the same controller that is created in main. Note how many times you call new MVCController() in your code above -- it's twice. Each time you do this, you're creating a new and distinct controller -- not good. Use only one. You've got to pass the one controller into the view. You can figure out how to do this. (hint, a setter or constructor parameter would work). hint 2: this could work: MVCViews myViews = new MVCViews(myMVC); one solution: import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class MVCTester { public static void main(String[] args) { MVCController myMVC = new MVCController(); MVCViews myViews = new MVCViews(myMVC); myMVC.attach(myViews); // myViews.setController(myMVC); // or this could do it } } class MVCController { MVCModel model; ArrayList<ChangeListener> listeners; public MVCController() { model = new MVCModel(); listeners = new ArrayList<ChangeListener>(); } public void update(String input) { model.setInputs(input); for (ChangeListener l : listeners) { l.stateChanged(new ChangeEvent(this)); } } public void attach(ChangeListener c) { listeners.add(c); } } class MVCModel { private ArrayList<String> inputs; MVCModel() { inputs = new ArrayList<String>(); } public ArrayList<String> getInputs() { return inputs; } public void setInputs(String input) { inputs.add(input); } } class MVCViews implements ChangeListener { private JTextField input; private JTextArea echo; private ArrayList<String> toPrint = new ArrayList<String>(); MVCController controller; MVCViews(final MVCController controller) { // !! controller = new MVCController(); this.controller = controller; JPanel myPanel = new JPanel(); JButton addButton = new JButton("add"); echo = new JTextArea(10, 20); echo.append("Hello there! \n"); echo.append("Type something below!\n"); myPanel.setLayout(new BorderLayout()); myPanel.add(addButton, BorderLayout.NORTH); input = new JTextField(); final JFrame frame = new JFrame(); frame.add(myPanel, BorderLayout.NORTH); frame.add(echo, BorderLayout.CENTER); frame.add(input, BorderLayout.SOUTH); addButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (controller != null) { controller.update(input.getText()); } } }); frame.pack(); frame.setVisible(true); } public void setController(MVCController controller) { this.controller = controller; } @Override public void stateChanged(ChangeEvent e) { if (controller != null) { toPrint = controller.model.getInputs(); for (String s : toPrint) { echo.append(s + "\n"); } } } }
unknown
d15398
val
Try this, Customize AlertDialog Theme Create a new Android XML resource file under res/values/ You'll want to create a new style that inherits from the default alertdialog theme: <style name="CustomDialogTheme" parent="@android:style/Theme.Dialog"> <item name="android:bottomBright">@color/white</item> <item name="android:bottomDark">@color/white</item> <item name="android:bottomMedium">@color/white</item> <item name="android:centerBright">@color/white</item> <item name="android:centerDark">@color/white</item> <item name="android:centerMedium">@color/white</item> <item name="android:fullBright">@color/orange</item> <item name="android:fullDark">@color/orange</item> <item name="android:topBright">@color/blue</item> <item name="android:topDark">@color/blue</item> </style> You can specify either colors or drawable for each section of the AlertDialog. An AlertDialog will build it's display by combining 3 drawables/colors (top, center, bottom) or a single drawable/color (full). In a theme of your own override the android:alertDialogStyle style (you can do this within the same XML file): @style/CustomDialogTheme Override your application's theme in the AndroidManifest within the application tag: <application android:icon="@drawable/icon" android:label="@string/app_name" android:theme="@style/MyTheme"> Now that you've defined your application's theme, any attributes overridden in your theme will resonate throughout your app. For example if you also wanted to change the color of your application's title bar: You would first define a new style that inherits from the default attribute @color/blue and just add the new overridden item to your theme: <style name="MyTheme"> <item name="android:windowTitleBackgroundStyle">@style/MyBackground</item> <item name="android:alertDialogStyle">@style/CustomDialogTheme</item> </style>
unknown
d15399
val
Try the following: [\\[(][^\\])]*[\\])] A: Try the following: (\\(.*?\\)|\\[.*?\\])*?
unknown
d15400
val
You need to customize UISlider. You can do it like this: [slider setMinimumTrackImage:[[UIImage imageNamed:@"redSlider.png"] stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0] forState:UIControlStateNormal]; Result: Here is some backgrounds for sliders and example image how they looks: Slider backgrounds: Example: More information here. A: After you alloc volumeView = [[MPVolumeView alloc] initWithFrame:CGRectMake(40, 145, 270, 23)]; Just search the MPVolumeView subviews and get the slider for (id current in volumeView.subviews) { if ([current isKindOfClass:[UISlider class]]) { UISlider *volumeSlider = (UISlider *)current; volumeSlider.minimumTrackTintColor = [UIColor redColor]; volumeSlider.maximumTrackTintColor = [UIColor lightGrayColor]; } Put the colors you like in UIColor and all done. If you need to customize further, treat volumeSlider as a standard UISlider.
unknown