_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d4901
train
How about: diff -I '^time.*' file1 file2? Please note it doesn't always work as expected as per diffutils manual: However, -I only ignores the insertion or deletion of lines that contain the regular expression if every changed line in the hunk (every insertion and every deletion) matches the regular expression. In other words, for each non-ignorable change, diff prints the complete set of changes in its vicinity, including the ignorable ones. You can specify more than one regular expression for lines to ignore by using more than one -I option. diff tries to match each line against each regular expression, starting with the last one given. A: What about this? diff <(grep -v '^time:' file1) <(grep -v '^time:' file2)
unknown
d4902
train
You were doing the right thing. For the nested dictionary, if you can't understand it, print it out to see how it's structured. Here is a way to get your values that you should be able to manipulate to get whatever you want. for k,v in a.items(): # get the keys and values in the dict a. k, v are not special names. for e in v: # now lets get all of the elements in each value, which is a list of dicts print(e.get('tcase_name')) # use the dict method get to retrieve the value for a particular key of interest.
unknown
d4903
train
Filter on pd.Series.notnull and call mean. c = ['cs', 'fhfa', 'sz'] df['final'] = df[df[c].notnull().all(1)][c].mean(1) A: IIUC: df.loc[:, 'final'] = df.loc[df[['cs','fhfa','sz']].notnull().all(1), ['cs','fhfa','sz']].sum(1)/3 .all(1) - is the same as .all(axis=1), which means - all values in each row must be True
unknown
d4904
train
You are getting this error because you are not using any observable list inside your ListView.builder. But before that you should convert your StatefullWidget to a StatelessWidget because in GetX, we don't need any StatefullWidget. You can try the following code. Controller class FeedsController extends GetxController { final Rx<List<Stories>> _stories = Rx<List<Stories>>([]); List<Stories> currUserstories = []; RxBool isLoading = false.obs; @override void onInit() { super.onInit(); getActiveStories(); } List<Stories> get getStories { return _stories.value; } Future<List<Stories>> getActiveStories() async { isLoading.value = true; var url = Uri.parse("storiesURL"); Map<String, Object> params = {'apikey': apiKey, 'userid': "8"}; await http.post(url, body: params).then((value) { StoriesResponse storiesResponse = storiesResponseFromJson(value.body); _stories.value = storiesResponse.stories; _stories.value = _stories.value.where((story) => story.userId == '8').toList(); currUserstories = _stories.value[0]; }).onError((error, stackTrace) { debugPrint( 'Error occurred while fetching stories response: ${error.toString()}'); }); isLoading.value = false; return _stories.value; } } View file: class ActiveStoriesList extends StatelessWidget { ActiveStoriesList({super.key}); final FeedsController _feedsController = Get.find(); @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Active Stories', style: titleLargeTextStyle.copyWith( fontSize: 22, fontWeight: FontWeight.w600), ), const SizedBox(height: 10), SizedBox( height: 100, child: Obx( () => _feedsController.isLoading.value ? const Center( child: CircularProgressIndicator(), ) : ListView.builder( shrinkWrap: true, scrollDirection: Axis.horizontal, itemBuilder: (ctx, index) => ActiveStoriesWidget( story: _feedsController.currUserstories[index]), itemCount: _feedsController.currUserstories.length, ), )), ], ); } } You might have to tweak the code a bit but the core concept it you should do all your work inside the controller and only fetch the data in view file. Also, you should only use the lifecycle which controller provides. Eg. onInit instead of initState. If this dosen't work, try to modify your controller file such that you get the value in the list as you want in the controller file itself and you the list which was preseneted in controller in your view file. Hope it helps.
unknown
d4905
train
This appears to be to do with the loop inside your move function. You call it with the parameter m representing the lengh of the ball array - but the function checkCollisionPlayer which is called within that can remove a ball from the array if there is a collision. This means that the array is now shorter, so whenever you try to access a property on ball[m-1] later in the loop, as you will, you'll get this error. I'm sure there are lots of different ways to fix this. The easiest I can think of (which I have successfully used myself in making a browser game) is to, instead of directly deleting the balls from the array upon collision, set a property on them to mark them as "deleted". Then add a "cleanup" function onto the end of the loop to filter the array into only those that are not marked as deleted. This ensures that every object you are looping over actually exists, while still changing the length dynamically to reflect the game state. A: var canvas,cxt,h,w,mousePos; var player= { x: 10, y: 10, height: 20, width: 20, color: 'black' }; function init(){ canvas= document.querySelector('#style'); cxt= canvas.getContext('2d'); h= canvas.height; w= canvas.width; createBalls(10); main(); } function createBalls(c){ ball= []; var i; for(i=0;i<c;i++){ var k= { x: h/2, y: w/2, color: colorGenerate(), radius: 5+Math.round(30*Math.random()), a: -5+Math.round(10*Math.random()), b: -5+Math.round(10*Math.random()) } ball.push(k); } } function main(){ cxt.clearRect(0,0,h,w); canvas.addEventListener('mousemove',function(evt){ mousePos= getMousePos(canvas,evt); }); createPlayer(); draw(ball.length); ballAlive(); move(ball); movePlayer(); requestAnimationFrame(main); } function ballAlive(){ cxt.save(); cxt.font="30px Arial"; if(ball.length==0) cxt.fillText("You Win",20,20); else cxt.fillText(ball.length,20,40); cxt.restore(); } function getMousePos(canvas,evt){ var rect= canvas.getBoundingClientRect(); return{ x: evt.clientX-rect.left, y: evt.clientY-rect.top } } function createPlayer(){ cxt.save(); cxt.translate(0,0); cxt.fillStyle= player.color; cxt.fillRect(player.x,player.y,player.height,player.width); cxt.restore(); } function movePlayer(){ if(mousePos !== undefined){ player.x= mousePos.x; player.y= mousePos.y; } } function draw(d){ var i; for(i=0;i<d;i++){ cxt.save(); cxt.translate(0,0); cxt.beginPath(); cxt.fillStyle= ball[i].color; cxt.arc(ball[i].x,ball[i].y,ball[i].radius,0,2*Math.PI) cxt.fill(); cxt.restore(); } } function move(m){ var i; for(i=0;i<m.length;i++){ ball[i].x+= ball[i].a; ball[i].y+= ball[i].b; checkCollision(ball[i]); checkCollisionPlayer(ball[i],i); } } function checkCollision(n){ if(n.x+n.radius>w){ n.a= -n.a; n.x= w-n.radius; } else if(n.x-n.radius<0){ n.a= -n.a; n.x= n.radius; } if(n.y+n.radius>h){ n.b= -n.b; n.y= h-n.radius; } else if(n.y-n.radius<0){ n.b= -n.b; n.y= n.radius; } } function checkCollisionPlayer(n,j){ if(overlap(n.x,n.y,n.radius,player.x,player.y,player.height,player.width)){ ball.splice(j,1); } } function overlap(cx,cy,r,px,py,ph,pw){ var testX= cx; var testY= cy; // THESE LINES ARE FOR MOVING THE BALLS TOWARDS THE PLAYER if(testX<px) testX=px; if(testX>(px+pw)) testX=px+pw; if(testY<py) testy=py; if(testY>(py+ph)) testY=py+ph; //DISTANCE FORMULA FOR CHECKING THE OVERLAPING BETWEEN THE BOX AND CIRCLE return((cx-px)*(cx-px)+(cy-py)*(cy-py)<r*r); } function colorGenerate(){ var col= ['green','blue','pink','red','brown','yellow','black','orange','grey','golden']; var i= Math.round((col.length-1)*Math.random()); //RETURN VALUES FROM 0 TO 9 return col[i]; } #style{ border: 4px dotted green; } <!DOCTYPE html> <html lang= 'en-us'> <head> <title>Feed The Monster</title> </head> <body onload= 'init();'> <canvas id= 'style' height= '400' width= '400'> Your browser does not support canvas... </canvas> </body> </html> If you pass the array as an argument in the move() function not the length of the array then your code will work perfectly.
unknown
d4906
train
You can try getting the latest release tag, rather than the HEAD code, like this: git clone https://github.com/Itseez/opencv.git cd opencv && git checkout 3.2.0
unknown
d4907
train
The best way to achieve your UI/UX requirement is to use TabLayout with a vertical recycler view. Both list items in the recycler view and tabs in the tab layout can be set up as a dynamic number of items/tabs When you scroll up and down and reach the respective category, update the tab layout using the following code. You can identify each category from the TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); // Once for the Activity of Fragment TabLayout.Tab tab = tabLayout.getTabAt(someIndex); // Some index should be obtain from the dataset tab.select(); In the same way, when clicking on a tab or scrolling the tab layout, Update the RecyclerVew accordingly./ recyclerView.smoothScrollToPosition(itemCount) Hope this will help, Cheers!!
unknown
d4908
train
You are very close indeed! You should join both ranges in order to sort them by the first column: =SORT({Performance!$B$2:$B;Performance!$C$2:$C;'Contributions/Withdrawals'!$A$2:$A,Performance!$F$2:$F;Performance!$H$2:$H;'Contributions/Withdrawals'!$B$2:$B}) (You may need to change that only comma to a inverted slash if you have another locale settings)
unknown
d4909
train
You can collect all tasks, then count them, compute some other metric of "loop length" or perform inspection. asyncio.Task.all_tasks(loop=loop) A: In python 3.10, you can get the number of tasks in the current thread like that : len(asyncio.all_tasks(asyncio.get_running_loop()))
unknown
d4910
train
The file you are invoking seems not to be a valid ELF executable, bash tries to process it as a bash script and fails. You can check for sure by using file command, e.g. file modeset. Check for the errors during your GCC build. Note that you try to compile modeset.h, not modeset.c.
unknown
d4911
train
How about setting a socket timeout. It sets the timeout on all the read operations on that socket
unknown
d4912
train
"Stop the world" rebalances are a known issue with Kafka Connect. The good news is that with KIP-415 which is due in Apache Kafka 2.3 there is a new incremental rebalance feature which should make things much better. In the meantime the only other option is to partition your Kafka Connect workers and have separate clusters, splitting the 500 connectors up over them (e.g. by function, type, or other arbitrary factor).
unknown
d4913
train
I have seen the same issue. However, I suggest this answer : https://stackoverflow.com/a/25658026/6157415 The "@Entry base=" parameter is used by LdapRepository not by LdapTemplate.
unknown
d4914
train
You can write each line independantly. This way you can check if the line itself is empty before writing. foreach ($textAr as $line) { $saveresult = ""; $line = str_replace(' ', '', $line); $line = preg_replace('/\D/', '', $line); $result = httpPost($url, $line); $showID = ($showID ? "".$result['id']." -" : ''); $notexisting = ($showasnull ? 0 : "N/A"); if ($result['manual'] == true) { $saveresult .= "".$showID." Manual"; } if ($result['hit'] == true && $result['manual'] != true) { $saveresult .= "".$showID." " . $result['price']; } else if ($result['hit'] == false) { $saveresult .= "".$showID." ".$notexisting; } $saveresult = trim($saveresult); if (!empty($saveresult)) { fwrite($handle, $saveresult.PHP_EOL); } } fclose($handle);
unknown
d4915
train
I found a solution for this, though is not the most elegant. I couldn't find a way to make a predicate to work as the one I had in UI Automation, so I used a couple of for loops to check the value of the cell labels. NSPredicate *enabledCellsPredicate = [NSPredicate predicateWithFormat:@"enabled == true "]; XCUIElementQuery *enabledCellsQuery = [classScheduleTableView.cells matchingPredicate:enabledCellsPredicate]; int cellCount = enabledCellsQuery.count; for (int i = 0; i < cellCount; i++) { XCUIElement *cellElement = [enabledCellsQuery elementBoundByIndex:i]; XCUIElementQuery *cellStaticTextsQuery = cellElement.staticTexts; int textCount = cellStaticTextsQuery.count; BOOL foundNoClasses = NO; for (int j = 0; j < textCount; j++) { XCUIElement *textElement = [cellStaticTextsQuery elementBoundByIndex:j]; if (textElement.value && [textElement.value rangeOfString:NSLocalizedString(@"No classes", nil) options:NSCaseInsensitiveSearch].location != NSNotFound) { foundNoClasses = YES; break; } } if (foundNoClasses == NO) { [cellElement tap]; break; } } Thanks @joe-masilotti for your help anyway. A: I don't believe your exact predicate is possible with UI Testing. UI Testings vs UI Automation Matching predicates with UI Testing (UIT) behaves a little differently than UI Automation (UIA) did. UIA had more access to the actual UIKit elements. UIT is a more black-box approach, only being able to interact with elements via the accessibility APIs. NOT Predicate Breaking down your query I'm assuming the second part is trying to find the first cell not titled 'No classes'. First, let's just match staticTexts. let predicate = NSPredicate(format: "NOT label BEGINSWITH 'No classes'") let firstCell = app.staticTexts.elementMatchingPredicate(predicate) XCTAssert(firstCell.exists) firstCell.tap() // UI Testing Failure: Multiple matches found As noted in the comment, trying to tap the "first" cell raises an exception. This is because there is more than one match for a text label that starts with "No classes". NONE Predicate Using the NONE operator of NSPredicate leads us down a different path. let predicate = NSPredicate(format: "NONE label BEGINSWITH 'No classes'") let firstCell = app.staticTexts.elementMatchingPredicate(predicate) XCTAssert(firstCell.exists)// XCTAssertTrue failed: throwing "The left hand side for an ALL or ANY operator must be either an NSArray or an NSSet." - This approach can't even find the cell. This is because the elementMatchingPredicate() expects the predict to return a single instance, not an array or set. I couldn't figure out how to make the query select the first element. And once you get an XCUIElement there are no ways to farther restrict it. Different Approach That said I suggest you take a slightly different approach for your test. If your tests are deterministic, and they should be, just tap the first known cell. This means you don't have to worry about ambiguous matchers nor chaining predicates. let firstCell = app.staticTexts["Biology"] XCTAssert(firstCell.exists) firstCell.tap()
unknown
d4916
train
What you have done above looks alright, but still if it doesn't work, then try this: FileOutputStream fos = context.openFileOutput("filename", Context.MODE_PRIVATE); This will create a file from non-activity class.
unknown
d4917
train
def cesar_encryption (message, offset = 1): encrypted_message = "" for char in message: encrypted_message += chr(ord(char) + offset) return encrypted_message print (cesar_encryption("I LOVE NATURE", 1)) # J!MPWF!OBUVSF Just remove .islower(), because you don't need it. More about this can be learned at - https://www.geeksforgeeks.org/caesar-cipher-in-cryptography/
unknown
d4918
train
I was using hector 1.1.4 but it is taken care in hector 1.1.5.
unknown
d4919
train
I'd use http://json2csharp.com/ (or any other json to c# parser) and then use C# objects (it's just easier for me) This would look like that for this case: namespace jsonTests { public class DeviceTypeWithResponseTypeMapper { public string DeviceType { get; set; } public List<string> ResponseTypes { get; set; } } public class RootObject { public List<DeviceTypeWithResponseTypeMapper> DeviceTypeWithResponseTypeMapper { get; set; } } } and the use it like that in code: var rootob = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(str); var thoseThatHaveNotUsed = rootob.DeviceTypeWithResponseTypeMapper.Where(dtwrtm => dtwrtm.ResponseTypes.Any(rt => rt == "NotUsed")); foreach (var one in thoseThatHaveNotUsed) { Console.WriteLine(one.DeviceType); } this code lists all the Device types that have "NotUsed" among the responses. version 2 (extending your code) would look like that, i believe: static void Main(string[] args) { var json = str; // below json is stored in file jsonFile var jObject = JObject.Parse(json); JArray ZoneMappingArray = (JArray)jObject["DeviceTypeWithResponseTypeMapper"]; string strDeviceType = "Police"; string strResponseType = "NotUsed"; var JToken = ZoneMappingArray.Where(obj => obj["DeviceType"].Value<string>() == strDeviceType).ToList(); var isrespTypeThere = JToken[0].Last().Values().Any(x => x.Value<string>() == strResponseType); Console.WriteLine($"Does {strDeviceType} have response type with value {strResponseType}? {yesorno(isrespTypeThere)}"); } private static object yesorno(bool isrespTypeThere) { if (isrespTypeThere) { return "yes!"; } else { return "no :("; } } result: and if you'd like to list all devices that have response type equal to wanted you can use this code: var allWithResponseType = ZoneMappingArray.Where(jt => jt.Last().Values().Any(x => x.Value<string>() == strResponseType)); foreach (var item in allWithResponseType) { Console.WriteLine(item["DeviceType"].Value<string>()); }
unknown
d4920
train
You may checkout this project. Sample usage: object value = ... string plist = Plist.PlistDocument.CreateDocument(value); The only requirement is to decorate your object with [Serializable] attribute. A: If you're using WebObjects, the appserver from apple, there's a java mirror class of NSPropertyListSerialization that does all of this for you; you can pass it NSArray's, NSDictionaries, etc and it will just work. Not sure if that's what you're talking about; confused as to the WebObjects in your question. HTH's.
unknown
d4921
train
The id you're passing to <FormControlLabel id="someId"/> component, is NOT the id of the <input> HTML element but the id of its <label> element. So when you check for document.getElementById("someId").checked you always get undefined and then you'll never go through your if - else checks.
unknown
d4922
train
I found a way using SqlGeographyBuilder, there may be a more efficient way but this works: List<SqlGeography> areaPolygons = GetAreaPolygons() SqlGeography multiPoly = null; SqlGeographyBuilder sqlbuilder = new SqlGeographyBuilder(); sqlbuilder.SetSrid(4326); sqlbuilder.BeginGeography(OpenGisGeographyType.MultiPolygon); foreach (SqlGeography geog in areaPolygons) { sqlbuilder.BeginGeography(OpenGisGeographyType.Polygon); for (int i = 1; i <= geog.STNumPoints(); i++) { if (i == 1) sqlbuilder.BeginFigure((double)geog.STPointN(i).Lat, (double)geog.STPointN(i).Long); else sqlbuilder.AddLine((double)geog.STPointN(i).Lat, (double)geog.STPointN(i).Long); } sqlbuilder.EndFigure(); sqlbuilder.EndGeography(); } sqlbuilder.EndGeography(); multiPoly = sqlbuilder.ConstructedGeography;
unknown
d4923
train
I have the route configured as from(fromEndPoint) .onCompletion() .doSomething() .split() // each Line .streaming() .parallelProcessing() .unmarshal().bindy .aggregate() .completionSize(100) .completionTimeout(5000) .to(toEndpoint) Assume if the split was done on 405 lines, the first 4 sets of aggregated exchanges go to the to endpoint completing 400 lines(exchanges) . And then, it immediately triggers the onCompletion. But there are still 5 more aggregated exchanges which would be triggered when the completionTimeout criteria is met. It didn't trigger the onCompletion after the 5 exchanges are routed to the to endpoint. My question here is , either the onCompletion should be triggered for each exchange or once after all. Note:- My from endpoint here is a File.
unknown
d4924
train
Are you talking about the Facebook API? Anyway: http://www.test-cors.org
unknown
d4925
train
how could a child class know (without taking a look at base class implementation) which order (or option) is being expected by the parent class? There is no way to "know" this when you are subclassing and overriding a method. Proper documentation is really the only option here. Is there a way in which parent class could enforce one of the three alternates to all the deriving classes? The only option here is to avoid the issue. Instead of allowing the subclass to override the method, it can be declared non-virtual, and call a virtual method in the appropriate place. For example, if you want to enforce that subclasses "call your version first", you could do: public class BaseClass { public void Method() // Non-virtual { // Do required work // Call virtual method now... this.OnMethod(); } protected virtual void OnMethod() { // Do nothing } } The subclasses can then "override" OnMethod, and provide functionality that happens after "method"'s work. The reason this is required is that virtual methods are designed to allow a subclass to completely replace the implementation of the parent class. This is done on purpose. If you want to prevent this, it's better to make the method non-virtual. A: This is why I feel virtual methods are dangerous when you ship them in a library. The truth is you never really know without looking at the base class, sometimes you have to fire up reflektor, read documentation or approach it with trial and error. When writing code myself I've always tired to follow the rule that says: Derived classes that override the protected virtual method are not required to call the base class implementation. The base class must continue to work correctly even if its implementation is not called. This is taken from http://msdn.microsoft.com/en-us/library/ms229011.aspx, however this is for Event design though I believe I read this in the Framework Design Guidelines book (http://www.amazon.com/Framework-Design-Guidelines-Conventions-Libraries/dp/0321246756). However, this is obviously not true, ASP.NET web forms for example require a base call on Page_Load. So, long and short, it varies and unfortunately there is no instant way of knowing. If I'm in doubt I will omit the call initially. A: The short answer is no. You can't enforce in what order the child calls the base method, or if it calls it at all. Technically this information should be included in the base object's documentation. If you absolutely must have some code run before or after the child class' code than you can do the following: 1) Create a non-virtual function in the base class. Let's call it MyFunction 2) Create a protected virtual function in the base class. Let's call it _MyFunction 3) Have deriving classes extend the _MyFunction method. 4) Have MyFunction call _MyFunction and run the code it needs to run before or after calling it. This method is ugly and would require a lot of extra code, so I recommend just putting a notice in the documentation. A: The requirements of the base class should be documented by the library designer. This issue is the reason why some libraries contain mainly sealed classes.
unknown
d4926
train
Well instead of using an if statement, you can always use the ternary operator ?: @Html.PasswordFor( model => model.Password, new { required = Model.UserName != null ? "This field is required" : null } ) Alternatively (if setting required as null does not work) then you could use it one level up: @Html.PasswordFor( model => model.Password, Model.UserName != null ? new { required = "This field is required" } : new { } ) A: You can simply use if(Model.UserName != null) { @Html.PasswordFor(model => model.Password, new { required = "This fiels is required"}) } else { @Html.PasswordFor(model => model.Password) } Why do you need to complicate thing?
unknown
d4927
train
You can do like this: print(driver.find_element_by_css_selector(".xxxx a").get_attribute('href')) A: Try the below: pName = driver.find_element_by_css_selector(".xxxx").text print(pName) or pName = driver.find_element_by_css_selector(".xxxx").get_attribute("href") print(pName) A: div.xxxx a first, check if this CSS_SELECTOR is representing the desired element. Steps to check: Press F12 in Chrome -> go to element section -> do a CTRL + F -> then paste the css and see, if your desired element is getting highlighted with 1/1 matching node. If yes, then use explicit waits: wait = WebDriverWait(driver, 20) print(wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.xxxx a"))).get_attribute('href')) Imports: from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC A: The value of the href attribute i.e. aaaaa.pdf is within the <a> tag which is the only descendant of the <div> tag. Solution To print the value of the href attribute you can use either of the following locator strategies: * *Using css_selector: print(driver.find_element(By.CSS_SELECTOR, "div.xxxx > a").get_attribute("href")) *Using xpath: print(driver.find_element(By.XPATH, "//div[@class='xxxx']/a").get_attribute("href")) To extract the value ideally you have to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies: * *Using CSS_SELECTOR: print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.xxxx > a"))).get_attribute("href")) *Using XPATH: print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='xxxx']/a"))).get_attribute("href")) *Note : You have to add the following imports : from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
unknown
d4928
train
You can pass your any number of variables/arrays using a single array. In Controller: public function display() { $id = $this->session->userdata('user_id'); $data['var1'] = $this->jobseeker_model->result_getall($id); $data['var2'] = $this->jobseeker_model->select($id); $this->load->view('jobseeker_display.php', $data); } In View: `$var1` and `$var2` will be available. A: You can pass your two variable using single srray public function display() { $id = $this->session->userdata('user_id'); $data['row'] = $this->jobseeker_model->result_getall($id); $data['a'] = $this->jobseeker_model->select($id); $this->load->view('jobseeker_display.php', $data); } Views foreach($a as $data){ // your code } echo $row->column_name; A: Try this public function display() { $id = $this->session->userdata('user_id'); $data['row'] = $this->jobseeker_model->result_getall($id); $data['a'] = $this->jobseeker_model->select($id); $this->load->view('jobseeker_display.php', $data); }
unknown
d4929
train
First you should make a test on the location and the location.state objects because they may be undefined because this method is called immediately after any update in the state or in the props from the parent component. you can see the Official doc. Rather you should do this: componentDidUpdate(prevProps) { if (this.props.location && this.props.location.state && typeof this.props.location.state.serial === "undefined"){ const database = db.ref().child("Devices/" + prevProps.location.state.serial); ... Or if you'd like to take advantage of new EcmaScript syntax Optional chaining: componentDidUpdate(prevProps) { if (typeof this.props.location?.state?.serial === "undefined"){ const database = db.ref().child("Devices/" + prevProps.location.state.serial); ...
unknown
d4930
train
You should try using the following line: deviceId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID); This will get the device ID from tablets, the code you're using only works on phones (it will return null on tablets) A: put <uses-permission android:name="android.permission.READ_PHONE_STATE" /> then try this: public String deviceId; then: // ------------- get UNIQUE device ID deviceId = String.valueOf(System.currentTimeMillis()); // -------- // backup for // tablets etc try { final TelephonyManager tm = (TelephonyManager) getBaseContext() .getSystemService(Main.TELEPHONY_SERVICE); final String tmDevice, tmSerial, tmPhone, androidId; tmDevice = "" + tm.getDeviceId(); tmSerial = "" + tm.getSimSerialNumber(); androidId = "" + android.provider.Settings.Secure.getString( getContentResolver(), android.provider.Settings.Secure.ANDROID_ID); UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode()); deviceId = deviceUuid.toString(); } catch (Exception e) { Log.v("Attention", "Nu am putut sa iau deviceid-ul !?"); } // ------------- END get UNIQUE device ID from here -> Is there a unique Android device ID?
unknown
d4931
train
One of the oid seem to trigger the error (cf. '.1.3.6.1.2.1.43.10.2.1.4.1.1' # SNMPv2-SMI::mib-2.43.10.2.1.4.1.1 page count), moving it to last fix the error. But this is a dubious solution. oids = [ '.1.3.6.1.2.1.25.3.2.1.3.1', # HOST-RESOURCES-MIB::hrDeviceDescr.1 '.1.3.6.1.2.1.1.4.0', # SNMPv2-MIB::sysContact.0 '.1.3.6.1.2.1.1.1.0', # SNMPv2-MIB::sysDescr.0 '.1.3.6.1.2.1.1.5.0', # SNMPv2-MIB::sysName.0 '.1.3.6.1.2.1.1.3.0', # DISMAN-EVENT-MIB::sysUpTimeInstance # ugly duckling '.1.3.6.1.2.1.43.10.2.1.4.1.1' # SNMPv2-SMI::mib-2.43.10.2.1.4.1.1 page count ]
unknown
d4932
train
Where do you set the todo? A put request replaces the current values with new ones. If you only set the description property but leave the todo out, it will overwrite it with an empty string, clearing any data you had in there. Either set the old value of the todo before making your put request or use a patch instead. A patch only affect certain selected values instead of everything. Anyway, it's still very possible to do this with a put instead. Try creating a useEffect where you set your todo to state. Something like this: const todoVar = description.find((desc)=> desc.id === todo.id); useEffect(()=>{ if(todoVar){ setDescription(description.todo) } },[todoVar, setDescription]) Basically, you want to set the todo value from your database to it's original value before making your PUT request. This way it won't be empty/null.
unknown
d4933
train
You can use IRBuilder's CreateGlobalStringPtr which is a convenience wrapper for creating a global string constant and returning an i8* pointing to its first character.
unknown
d4934
train
Take a look at this. I have had success using it and found it to be the best framework out there for box-api and php https://github.com/golchha21/BoxPHPAPI
unknown
d4935
train
These are objects that represent the same underlying entity, namely an HTTP cookie as defined by the RFC. Both "do" the same thing, representing a cookie header in an HTTP response (a request cookie is a name=value pair only, whereas response cookies can have several additional attributes as described in the RFC). Where you use one vs the other is simply a matter of what you are coding. If you are writing a JAX-RS provider, then the JAX-RS apis will use javax.ws.core.Cookie. If you are writing an HttpServlet, then you use the javax.servlet.http.Cookie. JAX-RS implementations will also allow you to use context injection so that you can have direct access to the HttpServlet objects within your JAX-RS service provider A: javax.servlet.http.Cookie is created and placed on the HTTP response object with the addCookie method. Instead, the description for javax.ws.core.Cookie reads: Represents the value of a HTTP cookie, transferred in a request … so you'd expect the getCookies method on the HTTP request object to return an array of that type of cookies, but no, it returns an array of javax.servlet.http.Cookie. Apparently javax.ws.core.Cookie is used by some methods in the javax.ws.rs packages. So you use javax.ws.core.Cookie with jax-rs web services and javax.servlet.http.Cookie with HttpServlets and their request / response objects.
unknown
d4936
train
You're not adding four new RSTRule instances to the list, you're adding the same RSTRule instance four times and modifying it each time through. Since it's the same instance stored four times, the modifications show up in every position of the list.
unknown
d4937
train
You have to add AccountManager.getInstance(connection) .sensitiveOperationOverInsecureConnection(true); to disable your ACL while you are registering a new user, then switch back to default settings: AccountManager.getInstance(connection) .sensitiveOperationOverInsecureConnection(false);
unknown
d4938
train
File and security systems are operating system specific. Go is modeled on Linux, Darwin, and other Unix-like operating systems. The Go Windows port emulates most things, but, as you have discovered, not everything (some are just stubs). If the features you need are not in the Go standard library, look for independently written, open-source Go packages. The last resort is to write your own interface to the Microsoft Windows API.
unknown
d4939
train
You can get the relative .album_holders using this, and then find the .title_holder within it. $(".image_holder").on("mouseover", function () { $(this).closest('.album_holders').find('.title_holder').animate({ "opacity": 1 },1500,$easing2); }); A: you can do this $(".image_holder").on("mouseover", function () { $(this).next(".title_holder").animate({ "opacity": 1 },1500,$easing2); });
unknown
d4940
train
I found the solution: add rpath option to CMakelists.txt for the executable, not for the shared library.
unknown
d4941
train
First, web APIs can not be called as script source. The output from a web API is the data as a string. Because the web API does not know (and doesn't want to assume) how the data is being called, it just dumps it. That way a CURL request can handle it just as well as an AJAX. It is up to you to determine how best to request the data for your needs. The blogger API for comments is very well handled. Check it out. If you update your question with some code and specific questions, I am positive the community will help with specific help. SO answer on PHP CURL jQUery documentation on getJson() function
unknown
d4942
train
Most likely this file is on a remote/mounted filesystem. Can you check that with either "df" or "mount" command? If it is remote filesystem then possibly the mount options disallow changing the file.
unknown
d4943
train
by: account.UserID = userid I assume you meant: account.UserID = user.user_id() The user id is a string, not a key, so you can't use a KeyProperty here. In fact, AFAIK, User objects as returned from users.get_current_user() don't have a key (at least not one that is documented) since they aren't datastore entries. There is an ndb.UserProperty, but I don't think it's use is generally encouraged. What performance reasons are you referring to? A: I think what you want is something like this UserAccounts(id=user_id), this way the user_id is the key. With this approach you can remove the userid field from the model definition
unknown
d4944
train
"Content pages to subscribe to change events" doesn't seem to be either a benefit or a drawback without further elaboration. You cannot really morph it to either category by prefixing "Do" or "Don't". The logic above (if you agree) leaves us with the following choices: 1 * *Pros - More maintainable because they live on a single master page instead of on each content page *Cons - None 2 * *Pros - None *Cons - less maintainable, because each content page has to figure out what to do with the selections. The choice is rather clear if you don't want to throw in more criteria.
unknown
d4945
train
Have you tried to call initModule_nonfree()? #include <opencv2/nonfree/nonfree.hpp> using namespace std; using namespace cv; int main(int argc, char *argv[]) { initModule_nonfree(); Mat image = imread("TestImage.jpg"); // Create smart pointer for SIFT feature detector. Ptr<FeatureDetector> featureDetector = FeatureDetector::create("SIFT"); vector<KeyPoint> keypoints; // Detect the keypoints featureDetector->detect(image, keypoints); // here crash // ... } Also, you didnt check the pointer featureDetector which is probably null (since you have not called initModule).
unknown
d4946
train
Try this: public class Issue { [XmlAttribute] public string Type { get; set; } [XmlAnyElement("Record")] public List<XElement> Record { get; set; } } I think that tells the serializer that multiple Record elements will go in the list. A: Implement Record class which has ID, Name_First, Name_Last and Company fields
unknown
d4947
train
\ backslash is an escape character. Escape sequences are used to represent certain special characters within string literals and character literals. Read here So you should do: if (c == '\\'){ } A: You need escape sequences: \\ backslash byte 0x5c in ASCII encoding Change the code to if (c == '\\') A: Backslash is used as the escape character in C++, as it is in many other languages. If you want a literal backslash, you need to use \\: if (c == '\\') { }
unknown
d4948
train
how can I call specific method of portlet.java class on ajax call? I think we can't have two different versions of serveResource methods like we do for action methods atleast not with the default implementation. If you want different methods you would have to go the Spring MVC (@ResourceMapping) way to have that. Still, you can define different logic in your serveResource method using the resourceId as follows (a full example): In the JSP: <portlet:resourceURL var="myResourceURL" id="myResourceID01" /> In the portlet class the serveResource method will contain the following code: String resourceID = request.getResourceID(); if(resoureID.equals("myResourceID01")) { // do myResourceID01 specific logic } else { // else do whatever you want } Please keep in mind [Important] In a portlet you should not use <html>, <head>, <body> tags since portlets generate fragment of the page and not the whole page. Even if it is allowed your resultant page will not be well-formed and will behave differently on different browsers. And moreover the javascript which modifies DOM element will be totally useless. Edit after this comment: You can also use ajax with action methods: People use <portlet:actionURL> with ajax generally for <form>-POST. For this the actionURL is generated in a slightly different way in your jsp like this: <portlet:actionURL name="ajax_AddAdvertise" var="addToDo" windowState="<%= LiferayWindowState.EXCLUSIVE.toString()%>"> </portlet:actionURL> And in your portlet you can have (as in the question): @ProcessAction(name = "ajax_AddAdvertise") public void ajax_AddAdvertise(ActionRequest request, ActionResponse response) { // ... your code }
unknown
d4949
train
I know this may be silly, but do you happen to save the view after cloning? Also, make sure that the path is not already existing within you Drupal site. A view creates a menu entry, check within you menu items listing that this entry is enabled.
unknown
d4950
train
In this case, in main(), Node *root; Why do you need to use a "double" pointer ( Node ** ) in functions that alter root is because root value as to be set in these functions. For instance, say you want to allocate a Node and set it into root. If you do the following void alloc_root(Node *root) { root = malloc(sizeof (Node)); // root is a function parameter and has nothing to do // with the 'main' root } ... // then in main alloc_root( root ); // here main's root is not set Using a pointer to pointer (that you call "double pointer") void alloc_root(Node **root) { *root = malloc(sizeof (Node)); // note the * } ... // then in main allow_root( &root ); // here main's root is set The confusion comes probably from the Node *root in main, root being a pointer to a Node. How would you set an integer int i; in a function f? You would use f(&i) to call the function f(int *p) { *p = 31415; } to set i to the value 31415. Consider root to be a variable that contains an address to a Node, and to set its value in a function you have to pass &root. root being a Node *, that makes another *, like func(Node **p).
unknown
d4951
train
You should: * *update the adapter with the new data *call myAdapter.notifyDataSetChanged() to update the GridView Better, you should use a RecyclerView with a GridLayoutManager instead of a GridView
unknown
d4952
train
To use libraries (or executables) built on Windows in Linux environment you need to cross-compile your code. GCC is capable of cross compilation - so you can research the topic, there is plenty of information.
unknown
d4953
train
Replace function Card({props},{image, title,author,price}) { with function Card(props) { I recommend working through the official React tutorial before using Redux.
unknown
d4954
train
ZZZZ in base 36 is 1679615 in base 10 (36^4 - 1). So you can simply test if the number is greater than this and reject it. To pad you can use String.PadLeft. A: If there are always going to be exactly four digits, it's really easy: const long MaxBase36Value = (36L * 36L * 36L * 36L) - 1L; public static string EncodeBase36(long input) { if (input < 0L || input > MaxBase36Value) { throw new ArgumentOutOfRangeException(); } char[] chars = new char[4]; chars[3] = CharList[(int) (input % 36)]; chars[2] = CharList[(int) ((input / 36) % 36)]; chars[1] = CharList[(int) ((input / (36 * 36)) % 36)]; chars[0] = CharList[(int) ((input / (36 * 36 * 36)) % 36)]; return new string(chars); } Or using a loop: const long MaxBase36Value = (36L * 36L * 36L * 36L) - 1L; public static string EncodeBase36(long input) { if (input < 0L || input > MaxBase36Value) { throw new ArgumentOutOfRangeException(); } char[] chars = new char[4]; for (int i = 3; i >= 0; i--) { chars[i] = CharList[(int) (input % 36)]; input = input / 36; } return new string(chars); }
unknown
d4955
train
You are describing what Numpy calls a Generalized Universal FUNCtion, or gufunc. As it name suggests, it is an extension of ufuncs. You probably want to start by reading these two pages: * *Writing your own ufunc *Building a ufunc from scratch The second example uses Cython and has some material on gufuncs. To fully go down the gufunc road, you will need to read the corresponding section in the numpy C API documentation: * *Generalized Universal Function API I do not know of any example of gufuncs being coded in Cython, although it shouldn't be too hard to do following the examples above. If you want to look at gufuncs coded in C, you can take a look at the source code for np.linalg here, although that can be a daunting experience. A while back I bored my local Python User Group to death giving a talk on extending numpy with C, which was mostly about writing gufuncs in C, the slides of that talk and a sample Python module providing a new gufunc can be found here. A: If you want to stick with nditer, here's a way using your example dimensions. It's pure Python here, but shouldn't be hard to implement with cython (though it still has the tuple iterator). I'm borrowing ideas from ndindex as described in shallow iteration with nditer The idea is to find the common broadcasting shape, sz, and construct a multi_index iterator over it. I'm using as_strided to expand X and Y to usable views, and passing the appropriate vectors (actually (1,n) arrays) to the f(x,y) function. import numpy as np from numpy.lib.stride_tricks import as_strided def f(x,y): # sample that takes (10,) and (3,) arrays, and returns (10,) array assert x.shape==(1,10), x.shape assert y.shape==(1,3), y.shape z = x*10 + y.mean() return z def brdcast(X, X1): # broadcast X to shape of X1 (keep last dim of X) # modeled on np.broadcast_arrays shape = X1.shape + (X.shape[-1],) strides = X1.strides + (X.strides[-1],) X1 = as_strided(X, shape=shape, strides=strides) return X1 def F(X, Y): X1, Y1 = np.broadcast_arrays(X[...,0], Y[...,0]) Z = np.zeros(X1.shape + (10,)) it = np.nditer(X1, flags=['multi_index']) X1 = brdcast(X, X1) Y1 = brdcast(Y, Y1) while not it.finished: I = it.multi_index + (None,) Z[I] = f(X1[I], Y1[I]) it.iternext() return Z sx = (2,3) # works with (2,1) sy = (1,3) # X, Y = np.ones(sx+(10,)), np.ones(sy+(3,)) X = np.repeat(np.arange(np.prod(sx)).reshape(sx)[...,None], 10, axis=-1) Y = np.repeat(np.arange(np.prod(sy)).reshape(sy)[...,None], 3, axis=-1) Z = F(X,Y) print Z.shape print Z[...,0]
unknown
d4956
train
How about this .. this works, you have manually copy all the changed/selected options from actual row to cloned row $(document).ready(function(){ $("#DuplicateRow").click(function(){ var checkboxValues = []; $('input[type="checkbox"]:checked').each(function(){ var $chkbox=$(this); var $actualrow = $chkbox.closest('tr'); var $clonedRow = $actualrow.clone(); $clonedRow.find("select").each(function(i){ this.selectedIndex = $actualrow.find("select")[i].selectedIndex; }) $chkbox.closest('#tabletomodify').append( $clonedRow ); }); }); });
unknown
d4957
train
You can't have variables in your bower.json file, so its not supported out of the box. See: https://groups.google.com/forum/#!msg/twitter-bower/OvMPG6KS3OM/eo6L2VadxI8J As a workaround if you have sed you can run something like: # update 1.2.5 -> 1.2.7 in test.json sed -i '' 's/1.2.5/1.2.7/' test.json
unknown
d4958
train
Firstly, your example has syntax errors. Should be: $userId = $_POST["userId"]; print '<input type="hidden" name="userId" value="'.$userId.'" />'; ------------------------------------------------------------------------------------ Basic Explanation: If $userId = 123 (ie. $_POST['userId'] = 123), all that it's saying is add all the parts together using the .: /* Piece 1->*/ '<input type="hidden" name="userId" value="' PLUS ( . ): /*Piece 2->*/ 123 PLUS ( . ): /* Piece 3->*/ '" />' Would print to the browser: <input type="hidden" name="userId" value="123" /> See the manual: http://php.net/manual/en/language.operators.string.php
unknown
d4959
train
use <f:param> It's explained in this article from BalusC http://balusc.blogspot.in/2011/09/communication-in-jsf-20.html#ProcessingGETRequestParameters A: I do not need a bazooka to kill a mouse. The answer is very simple. bind a javascript function to the onclick of the button, and in that function, retrieve the value of the input field by its id, then assemble URL with the parameters and navigate away from within the javascript function. JSF code (assume they are inside a form with myForm as its id): <p:inputText id="myInput" style="width:75px;" /> <p:commandButton id="myButton" value="Ir" onclick="navega();" title="Ir" ajax="false" proces="@none" /> Javascript script, declared on a separate file or later on in the xhtml document: function navega() { var submittedInputValue = $('#myForm\\:myInput').val(); window.location.href = "/site/mypage.xhtml?param1=whatever&amp;id=" + submittedInputValue ; } Take note of the prepend id (myForm:myInput), of using \\ to escape the : in jQuery, and using &amp; instead of & in the xhtml so its not treated as an entity. Note: probably not all of those commandButton attributes are required, feel free to edit this answer and remove the useless ones. EDIT: removed the submit and changed process to @none on the command button.
unknown
d4960
train
Well you should prefer to use Google Cloud Messaging GCM for push notifications rather than using 3rd Parties like Parse etc. GCM is super fast and i am using in all my apps which are live. Here are Good Links to Startoff with GCM http://developer.android.com/google/gcm/index.html http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/ A: I am aware about the parse notification.I am also having same problem,but the problem is because of the Wifi. It means when you send an parse notification from panel it would take some time to deliver because of wifi is enable on your mobile. So go with your mobile 3G connection it works within less time. A: Turns out, Parse has a GCM handler, and it also needs to be added to the manifest. Otherwise Parse uses its own service, which can be very slow. Enabling GCM, I now have the notifications arriving in under 20 seconds.
unknown
d4961
train
The basic concept would look something like... import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.Vector; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; public class Test { public static void main(String[] args) { new Test(); } public Test() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new TestPane()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class TestPane extends JPanel { private JTextField field; private JTable table; public TestPane() { setLayout(new BorderLayout()); field = new JTextField(20); table = new JTable(); add(field, BorderLayout.NORTH); add(new JScrollPane(table)); JButton update = new JButton("Update"); add(update, BorderLayout.SOUTH); update.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { TableModel model = executeQueryWith(field.getText()); table.setModel(model); } catch (SQLException ex) { JOptionPane.showMessageDialog(TestPane.this, "Failed to execute query", "Error", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); } } }); } protected TableModel executeQueryWith(String value) throws SQLException { String url = "jdbc:mysql://localhost:3306/cinema"; String userid = "root"; String password = "root"; String sql = "SELECT movie_title, timetable_starttime, timetable_movietype " + "FROM Movies INNER JOIN TimeTable on timetable_movie_ID = ?"; DefaultTableModel model = new DefaultTableModel(); try (Connection connection = DriverManager.getConnection(url, userid, password)) { try (PreparedStatement stmt = connection.prepareStatement(sql)) { stmt.setString(1, value); try (ResultSet rs = stmt.executeQuery()) { ResultSetMetaData md = rs.getMetaData(); int columns = md.getColumnCount(); // Get column names for (int i = 1; i <= columns; i++) { model.addColumn(md.getColumnName(i)); } // Get row data while (rs.next()) { Vector<Object> row = new Vector(columns); for (int i = 1; i <= columns; i++) { row.add(rs.getObject(i)); } model.addRow(row); } } } } return model; } } } You might also like to have a look at: * *Using Prepared Statements *How to Use Tables *Concepts: Editors and Renderers *Using Custom Renderers *How to Use Buttons, Check Boxes, and Radio Buttons *How to Write an Action Listeners
unknown
d4962
train
Here is my version of an OpenFileDialog for Java ME. public class OpenFileDialog extends List implements CommandListener { public static final String PREFIX = "file:///"; private static final String UP = "[ .. ]"; private static final String DIR = " + "; private Stack stack = new Stack(); private OpenFileListener listener; private CommandListener commandListener; private String extension; public OpenFileDialog (OpenFileListener listener, String title, String extension) { super(title, List.IMPLICIT); super.setCommandListener(this); this.listener = listener; this.extension = extension; addRoots(); } public void setCommandListener(CommandListener l) { this.commandListener = l; } public void commandAction(Command c, Displayable d) { if (c == List.SELECT_COMMAND) { this.changeSelection(); } else { if (this.commandListener != null) { this.commandListener.commandAction(c, d); } } } private String getSelectedText () { int index = getSelectedIndex(); if (index < 0 || index >= this.size()) { return ""; } return this.getString(index); } private void changeSelection () { String target = this.getSelectedText(); String parent = null; boolean goingUp = false; if (UP.equals(target)) { goingUp = true; stack.pop(); if (stack.isEmpty() == false) { target = (String) stack.peek(); } else { super.deleteAll(); addRoots(); this.setTicker(null); return; } } else { if (stack.isEmpty() == false) { parent = stack.peek().toString(); } } try { if (target.startsWith(DIR)) { target = target.substring(3); } if (parent != null) { target = parent + target; } this.setTicker(new Ticker(target)); FileConnection fc = (FileConnection) Connector.open(PREFIX + target, Connector.READ); if (fc.isDirectory()) { super.deleteAll(); if (goingUp == false) { stack.push(target); } super.append(UP, null); Enumeration entries = fc.list(); while (entries.hasMoreElements()) { String entry = (String) entries.nextElement(); FileConnection fc2 = (FileConnection) Connector.open(PREFIX + target + entry, Connector.READ); if (fc2.isDirectory()) { super.append(DIR + entry, null); } else if (entry.toLowerCase().endsWith(extension)) { super.append(entry, null); } fc2.close(); } fc.close(); } else { this.listener.fileSelected(fc); } } catch (IOException e) { e.printStackTrace(); } } private void addRoots() { Enumeration roots = FileSystemRegistry.listRoots(); while (roots.hasMoreElements()) { super.append(DIR + roots.nextElement().toString(), null); } } } interface OpenFileListener { void fileSelected(FileConnection fc); } It was first presented at http://smallandadaptive.blogspot.com.br/2009/08/open-file-dialog.html A: i find my problem, maybe this is your problem too, i just Use thread in commandAction function and it works. here is the code that changed: if (c==read) { new Thread(new Runnable() { public void run() { try { ReadFile(path); } catch (IOException ex) { ex.printStackTrace(); } } }).start(); }
unknown
d4963
train
After numerous searches for ways to utilize OpenSSL from Java I have ended up with JNA wrapper implementation, which, suprisingly, appeared to be pretty simple. Fortunately, OpenSSL is designed in such way that in vast majority of use-cases we do not need to exactly know the type of the value, returned from the call to OpenSSL function (e.g. OpenSSL does not require to call any methods from structures or work with structure fields directly) so there is no need in huge and complex wrappings for OpenSSL's data types. Most of OpenSSL's functions operate with pointers, which may be wrapped into an instance of com.sun.jna.Pointer class, which is equivalent to casting to void* in terms of C, and the callee will determine the correct type and de-reference the given pointer correctly. Here is a small code example of how to load ssleay32.dll, initialize the library and create a context: 1) Define the interface to ssleay32.dll library (functions list may be obtained from OpenSSL GitHub repo or by studying the export section of the dll): import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.Pointer; public interface OpenSSLLib extends Library { public OpenSSLLib INSTANCE = (OpenSSLLib) Native.loadLibrary("ssleay32", OpenSSLLib.class); // Non-re-enterable! Should be called once per a thread (process). public void SSL_library_init(); public void SSL_load_error_strings(); // Supported context methods. public Pointer TLSv1_method(); ... // Context-related methods. public Pointer SSL_CTX_new(Pointer method); public void SSL_CTX_free(Pointer context); public int SSL_CTX_use_PrivateKey_file(Pointer context, String filePath, int type); public int SSL_CTX_use_certificate_file(Pointer context, String filePath, int type); public int SSL_CTX_check_private_key(Pointer context); public int SSL_CTX_ctrl(Pointer context, int cmd, int larg, Pointer arg); public void SSL_CTX_set_verify(Pointer context, int mode, Pointer verifyCallback); public int SSL_CTX_set_cipher_list(Pointer context, String cipherList); public Pointer SSL_new(Pointer context); public void SSL_free(Pointer ssl); ... } 2) Initialize the library: ... public static OpenSSLLib libSSL; public static LibEayLib libEay; ... static { libSSL = OpenSSLLib.INSTANCE; libEay = LibEayLib.INSTANCE; libSSL.SSL_library_init(); libEay.OPENSSL_add_all_algorithms_conf(); // This function is called from // libeay32.dll via another JNA interface. libSSL.SSL_load_error_strings(); } ... 3) Create and initialize SSL_CTX and SSL objects: public class SSLEndpoint { public Pointer context; // SSL_CTX* public Pointer ssl; // SSL* ... } ... SSLEndpoint endpoint = new SSLEndpoint(); ... // Use one of supported SSL/TLS methods; here is the example for TLSv1 Method endpoint.context = libSSL.SSL_CTX_new(libSSL.TLSv1_method()); if(endpoint.context.equals(Pointer.NULL)) { throw new SSLGeneralException("Failed to create SSL Context!"); } int res = libSSL.SSL_CTX_set_cipher_list(endpoint.context, OpenSSLLib.DEFAULT_CIPHER_LIST); if(res != 1) { throw new SSLGeneralException("Failed to set the default cipher list!"); } libSSL.SSL_CTX_set_verify(endpoint.context, OpenSSLLib.SSL_VERIFY_NONE, Pointer.NULL); // pathToCert is a String object, which defines a path to a cerificate // in PEM format. res = libSSL.SSL_CTX_use_certificate_file(endpoint.context, pathToCert, certKeyTypeToX509Const(certType)); if(res != 1) { throw new SSLGeneralException("Failed to load the cert file " + pathToCert); } // pathToKey is a String object, which defines a path to a priv. key // in PEM format. res = libSSL.SSL_CTX_use_PrivateKey_file(endpoint.context, pathToKey, certKeyTypeToX509Const(keyType)); if(res != 1) { throw new SSLGeneralException("Failed to load the private key file " + pathToKey); } res = libSSL.SSL_CTX_check_private_key(endpoint.context); if(res != 1) { throw new SSLGeneralException("Given key " + pathToKey + " seems to be not valid."); } SSLGeneralException is the custom exception, simply inherited from RuntimeException. ... // Create and init SSL object with given SSL_CTX endpoint.ssl = libSSL.SSL_new(endpoint.context); ... Next steps may be creating of BIO objects and linking them to the SSL object. Regarding to the original question, client/server secure randoms and the master key may be obtained via such methods: public int SSL_get_client_random(Pointer ssl, byte[] out, int outLen); public int SSL_get_server_random(Pointer ssl, byte[] out, int outLen); public int SSL_SESSION_get_master_key(Pointer session, byte[] out, int outLen); Please, note, that JNA will search dlls to load looking into jna.library.path parameter. So, if the dlls are located, for example in directory D:\dlls, you must specify such VM option: -Djna.library.path="D:/dll" Also, JNA requires 32-bit JRE for 32-bit dlls (probably, libffi constraint?). If you try to load a 32-bit dll using 64-bit JRE, you'll get an exception.
unknown
d4964
train
Maybe you're overthinking this. If I understand what you want correctly, you could just do something like this: from datetime import datetime, timedelta days = { '1': _('Monday'), '2': _('Tuesday'), '3': _('Wednesday'), '4': _('Thursday'), '5': _('Friday'), '6': _('Saturday'), '7': _('Sunday') } DOW_CHOICES = [] today = datetime.today() for i in range(7): day_number = (today + timedelta(days=i)).isoweekday() day = days[str(day_number)] DOW_CHOICES.append((day_number, day)) This gets the today's date and creates a list of tuples with day number and day. The result will be: [ (3, 'Wednesday'), (4, 'Thursday'), (5, 'Friday'), (6, 'Saturday'), (7, 'Sunday'), (1, 'Monday'), (2, 'Tuesday') ]
unknown
d4965
train
One way you can do this is by using a recursive function. Where each iteration of the function goes 1 level deeper until it reaches the desired level to set the value. This is a basic version assuming objects exists with correct depth before calling the function. As it is now, there can be multiple errors if used incorrectly, should be amended to add more error checks. var veryDeepTree = { branch : { branch : { branch : { } } } }; function assignByDepth(subTree, currentTreeDepth, objProperty, value){ if(currentTreeDepth == 1){ subTree[objProperty] = value; }else{ assignByDepth(subTree[objProperty], --currentTreeDepth, objProperty, value); } } assignByDepth(veryDeepTree, 3, "branch", {branch:10}); console.log(veryDeepTree); assignByDepth(veryDeepTree, 4, "branch", 5555); console.log(veryDeepTree);
unknown
d4966
train
After some investigation, this is the command which fix my issue: proc = subprocess.Popen('npm install -g appium',shell=True,stdin=None, stdout=True, stderr=None, close_fds=True)
unknown
d4967
train
You have encountered a FileNotFoundException, which means the file you search doesn't exist in the path you have declared. Check whether you have given the correct path. And if you are sure about the path, then make sure the file you search is available in that path.
unknown
d4968
train
c() creates a vector. - makes the numbers in the vector negative. The vector is in the "row" position of [, so it is omitting the rows from 1 to k, and from nrow(SN) - k + 1 to the end of the data frame. So it's chopping off the first k and last k - 1 rows of the data frame.
unknown
d4969
train
I was also facing same issue and I followed these steps and problem went away: 1.close all program in your system then 2.then go to start button and search for %temp% then delete all files inside this folder 3.install Cclean software and clean your system. 4.restart your system A: I was facing same issue in win7 and I took these steps to resolve the problem: When starting Android Studio, it warns you with ADB not responding. If you'd like to retry, then please manually kill the process. You should enter cmd, and input adb kill-server for ten times or more. When the building has finished, input adb start-server and you will see daemon not running. starting it now on port 5037 daemon started successfully
unknown
d4970
train
$size = 32; $pascal = array( array(1), ); for ($i = 1; $i <= $size; ++$i) { $prevCount = count($pascal[$i-1]); for ($j = 0; $j <= $prevCount; ++$j) { $pascal[$i][$j] = ( (isset($pascal[$i-1][$j-1]) ? $pascal[$i-1][$j-1] : 0) + (isset($pascal[$i-1][$j]) ? $pascal[$i-1][$j] : 0) ); } } var_dump($pascal);
unknown
d4971
train
The simple answer: "Because that is the way Microsoft implemented it". The goal is to just respond to the event... whenever it happens... however often it occurs. We can't make any assumptions. There are cases where you might get called six times on the same event. We just have to roll with it and continue to be awesome.
unknown
d4972
train
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <a class="btn btn-primary" style="color: white" href="#">Previous</a> <a class="btn btn-primary" style="color: white" href="<?php echo $this->basePath('calendar/details/index').'?month='.$this->previousMonth?>">Previous</a>
unknown
d4973
train
You could try fetching the data from the database. Check out the doc here. Here is some sample code witch should help $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('COUNT(*)'); $query->from($db->quoteName('#__tablename')); $query->where($db->quoteName('published') . ' = 1'); $row = $db->loadRow(); print_r($row); You will need to find the table where the data is stored and replace __tablename accordingly (and maybe change the column name "published" if needed)
unknown
d4974
train
.parent:hover .child{ some props } A: try this: using the normal pseudo element in css :hover, adding the child element .child to add his style .parent:hover .child{ background-color:red; }
unknown
d4975
train
Its the subquery that is killing it - if you add a current field on the player_team table, where you give it value = 1 if it is current, and 0 if it is old you could simplify this alot by just doing: SELECT COUNT(*) AS total, pt.team_id, p.facebook_uid AS owner_uid, t.color FROM player_team pt JOIN player p ON (p.id = pt.player_id) JOIN team t ON (t.id = pt.team_id) WHERE player_team.current = 1 GROUP BY pt.team_id ORDER BY total DESC LIMIT 50 Having multiple entries in the player_team table for the same relationship where the only way to distinguish which one is the 'current' record is by comparing two (or more) rows I think is bad practice. I have been in this situation before and the workarounds you have to do to make it work really kill performance. It is far better to be able to see which row is current by doing a simple lookup (in this case, where current=1) - or by moving historical data into a completely different table (depending on your situation this might be overkill). A: Try this: SELECT t.*, cnt FROM ( SELECT team_id, COUNT(*) AS cnt FROM ( SELECT player_id, MAX(id) AS mid FROM player_team GROUP BY player_id ) q JOIN player_team pt ON pt.id = q.mid GROUP BY team_id ) q2 JOIN team t ON t.id = q2.team_id ORDER BY cnt DESC LIMIT 50 Create an index on player_team (player_id, id) (in this order) for this to work fast. A: I sometimes find that more complex queries in MySQL need to be broken into two pieces. The first piece would pull the data required into a temporary table and the second piece would be the query that attempts to manipulate the dataset created. Doing this definitely results in a significant performance gain. A: This will get the current teams with colours ordered by size: SELECT team_id, COUNT(player_id) c AS total, t.color FROM player_team pt JOIN teams t ON t.team_id=pt.team_id GROUP BY pt.team_id WHERE current=1 ORDER BY pt.c DESC LIMIT 50; But you've not given a condition for which player should be considered owner of the team. Your current query is arbitrarily showing one player as owner_id because of the grouping, not because that player is the actual owner. If your player_team table contained an 'owner' column, you could join the above query to a query of owners. Something like: SELECT o.facebook_uid, a.team_id, a.color, a.c FROM player_teams pt1 JOIN players o ON (pt1.player_id=o.player_id AND o.owner=1) JOIN (...above query...) a ON a.team_id=pt1.team_id; A: You could add a column "last_playteam_id" to player table, and update it each time a player changes his team with the pk from player_team table. Then you can do this: SELECT COUNT(*) AS total, pt.team_id, p.facebook_uid AS owner_uid, t.color FROM player_team pt JOIN player p ON (p.id = pt.player_id) and p.last_playteam_id = pt.id JOIN team t ON (t.id = pt.team_id) GROUP BY pt.team_id ORDER BY total DESC LIMIT 50 This could be fastest because you don't have to update the old player_team rows to current=0. You could also add instead a column "last_team_id" and keep it's current team there, you get the fastest result for the above query, but it could be less helpful with other queries.
unknown
d4976
train
The problem is mismatch between json structure and object structure. The object you deserialize into must represent correctly the json. It's an object with a field drinks, which is an array of objects(drinks in your case). Correct java class would be: public class Wrapper { private List<Drink> drinks; //getters and setters @Override public String toString() { return "Wrapper{" + "drinks=" + drinks + '}'; } } Other option would be to write custom deserializer, which can extract drinks from the tree before deserializing directly into a list.] Edit: Added toString() override for debugging purposes.
unknown
d4977
train
Django has inbuilt messaging support for this type of flash messages. You can add a success message like this in the view: messages.success(request, 'Profile details updated.') In your template, you can render it as follows: {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} This is documented in this link: https://docs.djangoproject.com/en/1.8/ref/contrib/messages/ A: If you are using class based views, then use the already implemented mixin from django.contrib.messages.views import SuccessMessageMixin from django.views.generic.edit import CreateView from myapp.models import Author class AuthorCreate(SuccessMessageMixin, CreateView): model = Author success_url = '/success/' success_message = "%(name)s was created successfully" A: How about passing a variable to the template ? (@ views.py) return render(request, "some_app/some_template.html", context={ 'sent': True }) and then somewhere in (@ some_template.html) {% if sent %} <div> blah blah</div> {% endif %} Edit: fixed typos :/ A: Here's a basic version using a class based view for a contact page. It shows a success message above the original form. mywebapp/forms.py ### forms.py from django import forms class ContactForm(forms.Form): contact_name = forms.CharField(label='Your Name', max_length=40, required=True) contact_email = forms.EmailField(label='Your E-Mail Address', required=True) content = forms.CharField(label='Message', widget=forms.Textarea, required=True) mywebapp/views.py ### views.py from django.contrib.messages.views import SuccessMessageMixin from django.core.mail import EmailMessage from django.core.urlresolvers import reverse_lazy from django.template.loader import get_template from django.views.generic import TemplateView, FormView from mywebapp.forms import ContactForm class ContactView(SuccessMessageMixin, FormView): form_class = ContactForm success_url = reverse_lazy('contact') success_message = "Your message was sent successfully." template_name = 'contact.html' def form_valid(self, form): contact_name = form.cleaned_data['contact_name'] contact_email = form.cleaned_data['contact_email'] form_content = form.cleaned_data['content'] to_recipient = ['Jane Doe <[email protected]>'] from_email = 'John Smith <[email protected]>' subject = 'Website Contact' template = get_template('contact_template.txt') context = { 'contact_name': contact_name, 'contact_email': contact_email, 'form_content': form_content } content = template.render(context) email = EmailMessage( subject, content, from_email, to_recipient, reply_to=[contact_name + ' <' +contact_email + '>'], ) email.send() return super(ContactView, self).form_valid(form) templates/contact.html ### templates/contact.html {% extends 'base.html' %} {% block title %}Contact{% endblock %} {% block content %} {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} <form role="form" action="" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% endblock %} templates/contact_template.txt ### templates/contact_template.txt ### used to render the body of the email Contact Name: {{contact_name}} Email: {{contact_email}} Content: {{form_content}} config/urls.py ### config/urls.py from mywebapp.views import * urlpatterns = [ url(r'^about/', AboutView.as_view(), name='about'), url(r'^contact/$', ContactView.as_view(), name='contact'), url(r'^$', IndexView.as_view()), ]
unknown
d4978
train
Your wire:model and wire:change are not on your select tag, but on the div below it. Move it to your select tag: <select wire:model="tag_id" wire:change="filter"> <option>Select an option</option> </select> <div class="overSelect"></div>
unknown
d4979
train
You should look into creating a Universal app which basically has shared code and libraries for the iPhone and iPad but different view layers (views or XIBs). In that model you have different interfaces for both which you should. The paradigms are different - in iPhone you have small real estate so you have navigators that drill in and pop out. In iPad, you have more real estate so you have master/detail splitter views with pop-over controls. As you pointed out, even the web views are different sizes at a minimum. If you start fresh you can create a universal app and get a feel for how it's laid out. File, new project, iOS, pick app type, next. For device family select Universal. If you are converting, there's some resources out there. Here's some: http://useyourloaf.com/blog/2010/4/7/converting-to-a-universal-app-part-i.html How to convert iPhone app to universal in xcode4, if I previously converted, but deleted MainWindow-iPad? Convert simple iPhone app to Universal app A: I find it easiest to open the xibs in the separate Interface Builder that came with previous (3.2?) XCode and use its "convert to iPad using autoresize masks" option. Then I include the new separate XIBS in the project and do conditional loading (eg - use the UI_USER_INTERFACE_IDIOM() makro to load one xib or another.)
unknown
d4980
train
Solution import numpy as np import pandas as pd df = pd.DataFrame(np.random.randint(0,20,size=(20, 4)), columns=list('abcd')) df['op'] = (np.random.randint(0,20, size=20)) def lookback_window(row, values, lookback, method='mean', *args, **kwargs): loc = values.index.get_loc(row.name) lb = lookback.loc[row.name] return getattr(values.iloc[loc - lb: loc + 1], method)(*args, **kwargs) df['SMA'] = df.apply(lookback_window, values=df['a'], lookback=df['op'], axis=1) df a b c d op SMA 0 17 19 11 9 0 17.000000 1 0 10 9 11 19 NaN 2 13 8 11 2 16 NaN 3 9 2 4 4 8 NaN 4 11 10 0 17 18 NaN 5 14 19 17 10 17 NaN 6 6 12 17 1 4 10.600000 7 10 1 3 18 2 10.000000 8 7 6 12 3 19 NaN 9 1 9 7 5 9 8.800000 10 17 1 3 13 1 9.000000 11 19 17 0 2 7 10.625000 12 18 5 2 4 12 10.923077 13 18 5 4 2 1 18.000000 14 5 11 17 11 11 11.250000 15 16 9 2 11 16 NaN 16 15 17 1 8 14 11.933333 17 15 2 0 3 6 15.142857 18 18 3 18 3 10 13.545455 19 7 0 12 15 3 13.750000
unknown
d4981
train
I've successfully used Adblock plus to remove elements from the view. The action column has a unique class (x-grid3-td-ACTION_COLUMN) so if you add the rule ##td.x-grid3-td-ACTION_COLUMN it should remove the column.
unknown
d4982
train
To answer and share how I resolved my question I found that when I created the connection I can still select sheets 2 to 6 in the dropdown from existing connections. So I tried this code .........and resolved the error :). Select [Sheet1$].* From [Sheet1$] UNION ALL Select [Sheet2$].* FROM [Shee2$] UNION ALL Select [Sheet3$].* FROM [Shee3$] UNION ALL Select [Sheet4$].* FROM [Shee4$] UNION ALL Select [Sheet5$].* FROM [Shee5$] UNION ALL Select [Sheet6$].* FROM [Shee6$]
unknown
d4983
train
Maybe You can try something like this <div class="single-welcome-slides bg-img bg-overlay jarallax" style="background-image: url({% static 'img/bg-img/1.jpg' %});" /> Happy Coding!
unknown
d4984
train
I would probably iterate of every found element and append it to a list. Something like this maybe (untested): date_list = [] date_raw = html.find_all('strong',string='Date:') for d in date_raw: date = str(d.p.nextSibling).strip() date_list.append(date) print date_list A: Rookie mistake...fixed it: for x in range(0,len(date_raw)): date_add = date_raw[x].next_sibling.strip() date_list.append(date_add) print (date_add)
unknown
d4985
train
Based on this topic you can try <input name="first" ngModel [required]="isRequired">
unknown
d4986
train
A simple example if you don't want to use RotatingFileHandler. You should use os.stat('filename').st_size to check file sizes. import os import sys class RotatingFile(object): def __init__(self, directory='', filename='foo', max_files=sys.maxint, max_file_size=50000): self.ii = 1 self.directory, self.filename = directory, filename self.max_file_size, self.max_files = max_file_size, max_files self.finished, self.fh = False, None self.open() def rotate(self): """Rotate the file, if necessary""" if (os.stat(self.filename_template).st_size>self.max_file_size): self.close() self.ii += 1 if (self.ii<=self.max_files): self.open() else: self.close() self.finished = True def open(self): self.fh = open(self.filename_template, 'w') def write(self, text=""): self.fh.write(text) self.fh.flush() self.rotate() def close(self): self.fh.close() @property def filename_template(self): return self.directory + self.filename + "_%0.2d" % self.ii if __name__=='__main__': myfile = RotatingFile(max_files=9) while not myfile.finished: myfile.write('this is a test') After running this... [mpenning@Bucksnort ~]$ ls -la | grep foo_ -rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_01 -rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_02 -rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_03 -rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_04 -rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_05 -rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_06 -rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_07 -rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_08 -rw-r--r-- 1 mpenning mpenning 50008 Jun 5 06:51 foo_09 [mpenning@Bucksnort ~]$ A: Another way (a bit shorter) would be to use a with clause having an if condition checking for the file size:- def RotateFile(count, file_size, file_name): indX = 0 while indX < count: with open(file_name,"a") as fd: ## fd.write("DUMMY TEXT\n") ## if int(os.path.getsize(file_name)) > file_size: indX += 1 file_name = "new_file"+str(indX)+".txt" with statement creates a context manager, so by the time you reach the end of if condition , the file object in fd will have been automatically closed. Next is to specify the options you need and pass on to the method: if __name__ == "__main__": count = 10 ## 10 number of files file_size = 10000 ## 10KB in size file_name = "new_file.txt" ## with this name RotateFile(count, file_size, file_name) After execution, it will give 10 files of size 10KB each (in the current dir)...
unknown
d4987
train
You can configure what you want to happen when a mass assignment happens by setting Player.mass_assignment_sanitizer (or set it on ActiveRecord::Base for it to apply to all AR models) You can also set it in your configuration files via config.active_record.mass_assignment_sanitizer Our of the box you can set it to either :logger, which just logs when these things happen or :strict which raises exceptions. You can also provide your own custom sanitizer. The current application template sets it to strict, although that used not to be the case A: Comment out this line in development.rb: config.active_record.mass_assignment_sanitizer = :strict The strict setting will raise an error and the default setting will just log a warning.
unknown
d4988
train
paper_numbers = tree.xpath('//div[@onclick]/div/@id') print(paper_numbers) would give you ['maincard_9202'] It selects the id attributes of all divs inside a div with the onclick attribute...
unknown
d4989
train
The issue is min <- which.min(hospital_data$outcome) and 'outcome' is passed as a string, but it is just literally using 'outcome' instead of the value passed in the function. It looks for the column 'outcome' in the data.frame and couldn't find it. df1 <- data.frame(col1 = 1:5) outcome <- 'col1' df1$outcome #NULL df1[[outcome]] Use [[ instead of $ min <- which.min(hospital_data[[outcome]])
unknown
d4990
train
Consider the below approach. I used timestamp functions to create the query. with sample_data as ( select date('2017-08-04') as date, time(10,00,00) as hour ) select format_timestamp( "%d-%b-%y %H%M%S", timestamp_trunc(timestamp(concat(date, ' ',hour),"UTC"),DAY,"America/New_York")) as out_format from sample_data NOTE: I created the sample data based from the query you have presented on your question. Let me know if I used incorrect data so I can edit the answer. Output:
unknown
d4991
train
Are you drawing a rectangle within your context? Try something like this: var canvas = document.getElementById('test-canvas'); var ctx = (canvas !== null ? canvas.getContext('2d') : null); var grd = (ctx !== null ? ctx.createLinearGradient(0.000, 150.000, 300.000, 150.000) : null); if (grd) { ctx.rect(0, 0, canvas.width, canvas.height); grd.addColorStop(0.000, 'rgba(0, 0, 0, 1.000)'); grd.addColorStop(1.000, 'rgba(255, 255, 255, 1.000)'); ctx.fillStyle = grd; ctx.fill(); } I have posted a working example at JSFiddle: http://jsfiddle.net/briansexton/e6rC3/
unknown
d4992
train
UIKit does not support that. The only possibilities are sheet to full screen and page sheet to form sheet on iPad. As specified in the documentation : In a horizontally compact environment, this option behaves the same as UIModalPresentationFullScreen. So UIKit already adapts it. Unfortunately you will have to implement your own custom transition controller. A: As GaétanZ said, better use another modal presentation style like overFullScreen for compact horizontal size clases and leave the formSheet for the horizontally regular ones. func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { if controller.traitCollection.horizontalSizeClass == .regular { return .formSheet } return .overFullScreen }
unknown
d4993
train
Items in STL containers are expected to be copied around all the time; think about when a vector has to be reallocated, for example. So, your example is fine, except that it only works with random iterators. But I suspect the latter is probably by design. :-P A: Do you want your range to be usable in STL algorithms? Wouldn't it be better off with the first and last elements? (Considering the fact that end() is oft required/used, you will have to pre-calculate it for performance.) Or, are you counting on the contiguous elements (which is my second point)? A: The standard algorithms don't really use operator[], they're all defined in terms of iterators unless I've forgotten something significant. Is the plan to re-implement the standard algorithms on top of operator[] for your "ranges", rather than iterators? Where non-mutating algorithms do use iterators, they're all defined in terms of *it being assignable to whatever it needs to be assignable to, or otherwise valid for some specified operation or function call. I think all or most such ops are fine with a value. The one thing I can think of, is that you can't pass a value where a non-const reference is expected. Are there any non-mutating algorithms which require a non-const reference? Probably not, provided that any functor parameters etc. have enough const in them. So sorry, I can't say definitively that there are no odd corners that go wrong, but it sounds basically OK to me. Even if there are any niggles, you may be able to fix them with very slight differences in the requirements between your versions of the algorithms and the standard ones. Edit: a second thing that could go wrong is taking pointers/references and keeping them too long. As far as I can remember, standard algorithms don't keep pointers or references to elements - the reason for this is that it's containers which guarantee the validity of pointers to elements, iterator types only tell you when the iterator remains valid (for instance a copy of an input iterator doesn't necessarily remain valid when the original is incremented, whereas forward iterators can be copied in this way for multi-pass algorithms). Since the algorithms don't see containers, only iterators, they have no reason that I can think of to be assuming the elements are persistent. A: Since you put "container" in "quotes" you can do whatever you want. STL type things (iterators, various member functions on containers..) return references because references are lvalues, and certain constructs (ie, myvec[i] = otherthing) can compile then. Think of operator[] on std::map. For const references, it's not a value just to avoid the copy, I suppose. This rule is violated all the time though, when convenient. It's also common to have iterator classes store the current value in a member variable purely for the purpose of returning a reference or const reference (yes, this reference would be invalid if the iterator is advanced). If you're interested in this sort of stuff you should check out the boost iterator library.
unknown
d4994
train
Older versions of Greasemonkey will ignore the @match directive, but will not break. For maximum compatibility, use the @include and @exclude directives to control where/when a script runs. Update: As of Greasemonkey 0.9.8, GM fully supports the @match directive.
unknown
d4995
train
I have got it working as mentioned It seems that the processing via ffmpeg needs to be done before model.save A: It's not implemented actually on Carrierwave. So you need code it yourself by some process action in your Upload Class.
unknown
d4996
train
Here is the RubyGems guide for how to add an executable. The primary steps are: * *Add your script to the gem's /bin directory *Your script must be executable in the filesystem chmod a+x bin/<yourfile> *Make sure your script starts with a proper shebang *Add the script to the .executables section of your gemspec Note you will still have to build and install your gem locally to run the command without a path as you are trying to do in the screenshot. More info in building executable gems.
unknown
d4997
train
Peter, I believe your problem has to do with the width of your logo under the class "navbar-brand". I had a similar issue, but fixed it by controlling the width of my logo under the Navbar-brand. According to bootstrap, "Adding images to the .navbar-brand will likely always require custom styles or utilities to properly size." Below is bootstraps example: <!-- Just an image --> <nav class="navbar navbar-light bg-light"> <a class="navbar-brand" href="#"> <img src="/docs/4.4/assets/brand/bootstrap-solid.svg" width="30" height="30" alt=""> </a> </nav> Notice the width and height settings after the image. In my case I was able to change the width of my logo image in CSS within my media query for small screen sizes.
unknown
d4998
train
I got the admin guy to copy SDK folder from his directory under C:\Users\adminguy\AppData to somewhere I can read. Now it works ok.
unknown
d4999
train
Thats what directives are designed for, point is to figure out best way to pass and evaluate those attributes of fields, in plnkr i made a possible solution. Here you have a starting point: PLNKR app.directive('cmsInput', function() { return { restrict: 'E', template: '<label ng-if=(exists(label))>{{label}}</label>', controller: function($scope) { $scope.exists = function(a) { if(a && a.length>0) { return true; } return false; } }, link: function(scope, elem, attr) { scope.label = attr.label; } } }) It requires work, but you'll get the point. EDIT: You could use 'scope' field of directives to bind values, but for purpose of finding solution I wanted to make it as clear as possible. EDIT2: Angular directive is being define with a rule "camelCase" in javascript(directive name) is eaxctly "camel-case" in html, as a directive call. Angular matches correct js code to called directive and puts exactly in that place in DOM your template. One of the parameters of link method are attributes, those are the same values that you have in html, so under: 'attr.label' you get value of 'label' in html, in this case string "header". The template attribute of directive is a string with bindigs to variables that were set in scope and and when we combine it all together we get: * *Angular "finds" a directive *Directive code is being fired *Link function is being called - inside which we set to field named "label" value of attribute named "label" *Template compiles - under {{ }} markers correct variables are being set. *vio'la - in place of this cms-input element you get normal html
unknown
d5000
train
As you mentioned combination of best and worst player. Your data is already sorted on descending index. Say, the data is in A,B and C Columns. Just put A in D2 and B in D3. Select D2 and D3 and once you get + cursor on the bottom right of the selection, double click. Filter A for group A and B for group B.
unknown