_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d13901
train
How about a following modification? Modification points : * *In order to retrieve messages from threads, getMessages() is used. *In order to retrieve each message from messages retrieved by getMessages(), it retrieves using one more "for loop". *For each mail, the Date, From, Subject and Body can be retrieved by getDate(), getFrom(), getSubject() and getPlainBody(), respecrively. Modified script : function getGmailData() { var sheet = SpreadsheetApp.getActiveSheet(); var threads = GmailApp.search("is:unread in:inbox", 0, 1); var res = []; for (var t=0; t<threads.length; t++) { var msgs = threads[t].getMessages(); for (var u=0; u<msgs.length; u++) { var m = msgs[u]; res.push([m.getDate(), m.getFrom(), m.getSubject(), m.getPlainBody()]); } } sheet.getRange(sheet.getLastRow() + 1, 1, res.length, res[0].length).setValues(res); } If I misunderstand your question, I'm sorry. Edit : When you want to retrieve mails from today, you can use newer_than: and after: operators. In the case of using newer_than: var threads = GmailApp.search("newer_than:1d in:inbox", 0, 1); In the case of using after: var today = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'yyyy/MM/dd'); var threads = GmailApp.search("after:" + today + " in:inbox", 0, 1);
unknown
d13902
train
Based on the documentation you could use the following: setFormat12Hour( "K:m" );
unknown
d13903
train
Using cp unix command, you can copy and rename at same time. I changed a bit your script to reduce it and I set the copy/rename inside the main loop. remove the "--" before the "set location" and the do shell script "rm". I leave them to be more safe for debugging. On first row, I assigned, for my tests, the Newdirectory to my desktop. you must adjust this. set NewDirectory to (path to desktop folder from user domain) as string -- my desktop for example tell application "iTunes" ok_v(get version) of me set selectedTracks to selection if selectedTracks is {} then return if (get class of (item 1 of selectedTracks)) is not file track then return set originalLocs to {} repeat with i from 1 to (count of selectedTracks) tell item i of selectedTracks to set {TName, Tloc, Tartist} to {get name, get location, get artist} if Tloc is missing value then display dialog "The file for \"" & TName & "\" appears to be missing. ..." buttons {"Cancel", "OK, Skip It"} default button 1 with icon 2 giving up after 30 with title "Need a decision..." end if tell application "Finder" to set FExt to name extension of Tloc set NewName to NewDirectory & Tartist & "_" & TName & "." & FExt do shell script "cp " & quoted form of (POSIX path of Tloc) & " " & quoted form of (POSIX path of NewName) --set location of (item i of selectedTracks) to NewName --do shell script "rm " & quoted form of (posix path of Tloc) end repeat end tell on ok_v(v) if (do shell script ("echo " & quoted form of (v as text) & "|cut -d . -f 1")) as integer < 10 then display dialog return & "This script requires iTunes v10.0 or better..." buttons {"Cancel"} default button 1 with icon 0 giving up after 15 --with title my_title end if end ok_v
unknown
d13904
train
You'll need to use a jQuery plugin of some kind to help close all those gaps you're seeing. As James mentioned, masonry is a very popular option. Another plugin (without as many options/features) is jQuery Waterfall. Both have lots of examples to help get you up and running. A: You should insert the code that you have found in to an .css file, then link to it from your html file and use the classes/id's provided (eg. ".pin" "#columns") on the elemts you want to stylize with the code you found A: This is small library which implements Pinterest layout. Filling the grid goes from left to right. Count of columns can be customized in config for each resolution. Columns adaptive changes on resize. Image can be at up or down of pin. https://github.com/yury-egorenkov/pins-grid
unknown
d13905
train
Finally got it working! Thanks to @zgoda and this link. Here are the steps I ended up with for those of you who have the same problem: First make sure PIL is not installed. Download libjpeg from http://www.ijg.org/files/jpegsrc.v8c.tar.gz, unpacked it, ./configure, and make. When I tried to make install it couldn't find the directory to store the man pages so installation failed. I looked at the information on the above link and decided to cp -r ~/Downloads/jpeg-6d/ /usr/local/jpeg I suspect if the installation goes fine than that line isn't necessary. Then edit the following line in PIL's setup.py: JPEG_ROOT = None to JPEG_ROOT = "/usr/local/jpeg" finally: $ python setup.py build $ python setup.py install A: PIL did not found libjpeg headers during compilation. Consult your build system documentation on how to specify headers ("includes") location, eg. as environment variables.
unknown
d13906
train
Mat::convertTo function should be safe to use when using inplace calls (i.e. same input and output Mat objects). According to OpenCV DevZone, this function did have a bug when using inplace calls, but it was fixed a few years ago.
unknown
d13907
train
Copy the downloaded DLL file in a custom folder on your drive, hopefully at the root of your solution maybe in a libs folder, then add the reference to your project using the Browse button in the Add Reference dialog. Make sure that the new reference has Copy Local = True set within its properties once added to the solution, which is found when un-collapsing and right-clicking on the References item in your project within Solution Explorer. A: You can host it creating a XBAP, silverlight or clickonce application. The created application will run clientside. Hope this helps. Regards.
unknown
d13908
train
Check if overflow: hidden; or overflow: auto is set in the parent div. That could prevent it from showing up.
unknown
d13909
train
Here is how I would do this. It's not exactly like you wanted, but IMHO its a better user experience. // this timer function allows us to wait till the user is done typing, // rather than calling our code on every keypress which can be quite annoying var keyupDelay = (function(){ var timer = 0; return function(callback, ms){ clearTimeout (timer); timer = setTimeout(callback, ms); }; })(); $('#input_10_4').keyup(function() { var $this = $(this); // use our timer function keyupDelay(function(){ // user has stopped typing, now we can do stuff var max_limit = 8; var words = $this.val().trim().replace(/,/g, ' ').replace(/,?\s+/g, ' ').trim().split(' '); words = words.slice(0, max_limit); // get all the words up to our limit console.log(words); var wordString = words.join(', '); $this.val(wordString); var remainingWords = max_limit - words.length; $('#remainingChars').text('Words remaining: '+remainingWords); }, 800 ); // number of milliseconds after typing stops, this is equal to .8 seconds }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input name="input_4" type="text" id="input_10_4" size="100" /> <br> <div id="remainingChars"></div>
unknown
d13910
train
I've only tested quickly on mobile, but stopping the background image from scrolling with the page seemed to fix it. To do this I added background-attachment: fixed; to the CSS for body, html
unknown
d13911
train
put it in a function, and call it on an onclick event on an element function myEvent() { j=parseInt(Math.random()*ranobjList.length); j=(isNaN(j))?0:j; document.write(unescape(ranobjList[j])); } then in your html <input type='button' value='Click Me' onclick='myEvent();' /> A: The code example you have isn't actually running on page load. It's running as it's interpreted by the DOM. But here is a solution to your request. The HTML button must be above the script tag. So you'll want something just like this: <input type="button" value="Click me for action" id="actionButton" /> <script type="text/javascript"> document.getElementById("actionButton").addEventListener("click", function() { j=parseInt(Math.random()*ranobjList.length); j=(isNaN(j))?0:j; document.write(unescape(ranobjList[j])); }, false); </script>
unknown
d13912
train
I would not combine data files with R source. Much easier to keep them separate. You put your functions in separate script files and then source() them as needed, and load your data with read.csv() etc. "Keep It Simple" :-) I am sure there's a contorted way of reading in the source code of a function from a text file and then eval() it somehow -- but I am not sure it would be worth the effort.
unknown
d13913
train
I tried to solve this through JS. Here is my code: function paint() { let txt = ""; for (let j = 0; j < 100; j++) { txt += "<div>" for (let i = 0; i < 100; i++) { txt += `<span onmouseout="hoverOut()" onmouseover="hover(this)" onmouseuop id="overlay-${i}-${j}">@</span>` } txt += "</div>" } document.getElementById('painting').innerHTML += txt } function hover(x) { let id = x.id; let i = x.id.split('-')[1]; let j = x.id.split('-')[2]; for (let a = -2; a <= 2; a++) { for (let b = -1; b <= 1; b++) { const elem = document.getElementById(`overlay-${i-a}-${j-b}`); elem ? elem.style.opacity = 0 : null; } } x.style.opacity = '0'; } function hoverOut() { for (let i = 0; i < document.getElementsByTagName('span').length; i++) { document.getElementsByTagName('span')[i].style.opacity = 1; } } <body onload="paint()"> <div id="painting"> </div> </body> A: Another approach without using ids would be to use Element.getBoundingClientRect() to get the size and position of the hovered element and then use Document.elementFromPoint() inside a loop to access elements near the hovered one: const main = document.querySelector('main') for (let i = 0; i < 800; i++) main.innerHTML += '<span>@</span>' const spans = document.querySelectorAll('span') const areaWidth = 50 const areaHeight = 50 const hidden = [] function getElements(currentSpan, color) { const { top, right, bottom, left, width, height } = currentSpan.getBoundingClientRect() for (let col = left - areaWidth / 2; col < right + areaWidth / 2; col += width || 14) { for (let row = top - areaHeight / 2; row < bottom + areaHeight / 2; row += height || 14) { const el = document.elementFromPoint(col, row) if (el?.tagName === 'SPAN') { el.style.color = color hidden.push(el) } } } } spans.forEach(span => { span.addEventListener('mouseover', () => getElements(span, 'transparent')) span.addEventListener('mouseout', () => { hidden.forEach(el => (el.style.color = '')) hidden.length = 0 }) }) main { display: flex; flex-wrap: wrap; width: 640px; cursor: default; } <main></main> A: You could use a CSS solution - overwrite the adjacent characters with a pseudo element on the clicked character. This snippet uses a monospace font and it's set line height and letter spacing as CSS variables so you can alter them as required. function clicked(ev) { ev.target.classList.add('obscure'); } const container = document.querySelector('.container'); for (let i = 0; i < 200; i++) { const span = document.createElement('span'); span.innerHTML = '@'; if (i % 10 == 0) { container.innerHTML += '<br>'; } container.appendChild(span); } container.addEventListener('click', clicked); .container { width: 50vw; height: auto; font-family: Courier, monospace; --line-height: 20px; --letter-spacing: 5px; line-height: var(--line-height); letter-spacing: var(--letter-spacing); } .container span { position: relative; margin: 0; padding: 0; } .obscure::before { content: ''; width: calc(5ch + (6 * var(--letter-spacing))); height: calc(3 * var(--line-height)); background-color: white; position: absolute; top: 0; transform: translate(calc(-50% + 0.5ch), calc(-50% + (1ch))); left: 0; z-index: 1; display: inline-block; } <body> <div class="container"></div> </body> A: If I understand you right, you want the span to vanish, but you don't want its space to also vanish. display:none is the wrong solution. you need visibility:hidden. hiding the hovered element and elements before and after it is easy. the difficulty is in hiding element that are above or below it. to do that, you would need to do some math. assuming the answer doesn't need to be exact, you could do it something like this: * *calculate the centre positions of all spans and keep them in an array (so you don't need to recalculate every time) *when a span is mouse-entered, check the array and calculate all spans that are within radius r of that span's centre point - or just above/below/left/right - whatever works. *create a new array of spans that should be hidden *check all hidden spans - if any of them are not in that new array, unhide them (visibility:visible) *finally, go through the new array and set visibility:hidden on all spans in that array A: Here is a bit diffrent and custumisable aproch: // Variables const ROW = 10; // Total number of rows const COL = 35; // Total number of items in a row (i.e. columns) const RANGE = 2; // Total number of items to be selected in each direction const values = []; // To colect ids of items to be selected // Utility Function const push = (value) => { if (value > 0 && value <= ROW * COL && !values.includes(value)) values.push(value); }; // Add items in the root div const root = document.querySelector("#root"); for (let i = 0; i < ROW; i++) { root.innerHTML += `<div id="row-${i + 1}"></div>`; for (let j = 0; j < COL; j++) { document.querySelector(`#row-${i + 1}`).innerHTML += `<span id="item-${COL * i + (j + 1)}">@</span>`; } } // Add class to the items as per the RANGE root.addEventListener("mouseover", (e) => { values.length = 0; const id = e.target.id; if (!id.includes("item-")) return; const current = +id.replace("item-", ""); push(current); for (let i = -RANGE; i < RANGE; i++) { push(current + i); for (let j = -RANGE; j <= RANGE; j++) { push(current + COL * i + j); push(current - COL * i + j); } } for (let i = 0; i < values.length; i++) { const item = document.querySelector(`#item-${values[i]}`); item.classList.add("selected"); } }); // Remove class from the items as per the RANGE root.addEventListener("mouseout", () => { for (let i = 0; i < values.length; i++) { const item = document.querySelector(`#item-${values[i]}`); item.classList.remove("selected"); } }); /* Just for styling purposes */ body { background-color: #111; color: #fff; } #root [id*="item-"] { padding: 1px; } /* Styles for the selected item */ #root [id*="item-"].selected { /* color: transparent; */ /* Use this to get your intended effect */ color: #ffa600; } <div id="root"></div>
unknown
d13914
train
Use alertview like this UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Enter Name" message:@"" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Submit", nil]; alert.alertViewStyle=UIAlertViewStylePlainTextInput; UITextField *textField=[alert textFieldAtIndex:0]; textField.delegate=self; [alert show]; [alert release]; And access the value of textfield like this #pragma mark alert button view button - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { if(buttonIndex==1) { UITextField *textField=[alertView textFieldAtIndex:0]; } } A: In iOS 8 UIAlertview has been deprecated. UIAlertController is used instead of that. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Add Fruit" message:@"Type to add a fruit" preferredStyle:UIAlertControllerStyleAlert]; [alert addTextFieldWithConfigurationHandler:^(UITextField *textField){ textField.placeholder = @"Fruit"; }]; UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { UITextField *textFiel = [alert.textFields firstObject]; [fruits addObject:textFiel.text]; }]; [alert addAction:okAction]; [self presentViewController:alert animated:YES completion:nil];
unknown
d13915
train
PhoneGap give you a layer of abstraction so that you app is going to have access to non browserView accessible functionality like the camera for example. And those will be the same on all mobile plateforme. A: You can create application with pure html5 with webview and piece of java methods used to handle mobile events like Calling, Messaging, Sensors, etc,. When you are using phonegap libraries, no need to do much work with java methods. The phonegap libraries will handle the java and you can only work with html5 and java script with little bit help of jquery mobile framework. All mobile events you can call directly in the javascript of html page. A: Using HTML5 and PhoneGap you can implement different kinds of applications: * *Mobile applications using HTML5. You will need a server to back up your application and the users will run it through the device's browser. *Native application using HTML5 and WebView. Using a server isn't necessary. In this case you write HTML5 code (HTML, CSS, Javascript) and you use a WebView to display it. You can interact with Java using a special interface. *PhoneGap makes the above case easier. You don't need to know the details of WebView. You need PhoneGap APIs to interact with the phone's resources. As an added bonus you can easily port the application to other platforms. PhoneGap also creates native applications.
unknown
d13916
train
You can try and use renewLockForMessage to extend the lock. Hope it helps!
unknown
d13917
train
The problem for example with this typedef declaration typedef struct { A(int a) : a_var(a) {} int a_var; } A; is that within the unnamed structure there is used undeclared name A as a name of a constructor. So this declaration is invalid. By the way the same problem exists else in C. Consider for example a typedef declaration of a structure used to define a node of a linked list. typedef struct { int data; A *next; } A; Again the name A within the structure definition is undefined. Even if you will write like typedef struct A { int data; A *next; } A; nevertheless the name A is still undeclared within the structure in C. You have to write in C typedef struct A { int data; struct A *next; } A; On the other hand, in C++ such a typedef declaration is valid. A: Yes, you can, but it's not possible to make use of the type name inside the structure, as you said. // this is valid typedef struct{ int x; void set(int n){x=n;} } A; // this is not typedef struct{ int x; B(int n){x = n;} } B; // you can only have constructor with named structs typedef struct st_C{ int x; st_C(int n){x = n;} } C; // this is valid C *foo = new C(3); A: In C, you often have to write typdefs like this: typedef struct { int val; } Foo_t; to avoid having to write struct Foo_t f; every time, which soon becomes quite tedious. In C++, all structs unions and enums declarations act as though they are implicitly typedefed. So you can declare a struct like this: struct A { A(int a) : a_var(a) {} int a_var; }; However, structs in C++ are often aggregates (a simple collection of data), and you don't need the constructors. So the following is fine: struct A { int a_var; int b_var; }; The constructor is implicitly defined by the compiler, and when you use value initialisation with braces: A a{}; all the members of the struct will be zeroed out.
unknown
d13918
train
Try: /^[\p{L}-. ]*$/u This says: ^ Start of the string [ ... ]* Zero or more of the following: \p{L} Unicode letter characters - dashes . periods spaces $ End of the string /u Enable Unicode mode in PHP A: /^[a-zàâçéèêëîïôûùüÿñæœ .-]*$/i Use of /i for case-insensitivity to make things simpler. If you don't want to allow empty strings, change * to +. A: The character class I've been using is the following: [\wÀ-Üà-øoù-ÿŒœ]. This covers a slightly larger character set than only French, but excludes a large portion of Eastern European and Scandinavian diacriticals and letters that are not relevant to French. I find this a decent compromise between brevity and exclusivity. To match/validate complete sentences, I use this expression: [\w\s.,!?:;&#%’'"()«»À-Üà-øoù-ÿŒœ], which includes punctuation and French style quotation marks. A: Simplified solution: /^[a-zA-ZÀ-ÿ-. ]*$/ Explanation: ^ Start of the string [ ... ]* Zero or more of the following: a-z lowercase alphabets A-Z Uppercase alphabets À-ÿ Accepts lowercase and uppercase characters including letters with an umlaut - dashes . periods spaces $ End of the string A: Simply use the following code : /[\u00C0-\u017F]/ A: This line of regex pass throug all of cirano de bergerac french text: (you will need to remove markup language characters http://www.gutenberg.org/files/1256/1256-8.txt ^([0-9A-Za-z\u00C0-\u017F\ ,.\;'\-()\s\:\!\?\"])+ A: All French and Spanish accents /^[a-zA-ZàâäæáãåāèéêëęėēîïīįíìôōøõóòöœùûüūúÿçćčńñÀÂÄÆÁÃÅĀÈÉÊËĘĖĒÎÏĪĮÍÌÔŌØÕÓÒÖŒÙÛÜŪÚŸÇĆČŃÑ .-]*$/ A: /[A-Za-z-\.\s]/u should work.. /u switch is for UTF-8 encoding A: This might suit: /^[ a-zA-Z\xBF-\xFF\.-]+$/ It lets a few extra chars in, like ÷, but it handles quite a few of the accented characters.
unknown
d13919
train
Here is an example (completely neglecting error handling): request, _ := http.Get("https://api.github.com/repos/openebs/openebs") defer request.Body.Close() bytes, _ := ioutil.ReadAll(request.Body) var apiResponse struct { StargazersCount int `json:"stargazers_count"` } json.Unmarshal(bytes, &apiResponse) fmt.Println(apiResponse.StargazersCount) Playground
unknown
d13920
train
I believe you are interested in knowing the properties of the each AWS Resource / Service and not the meta-data. I don't think there is a straight answer. The work around what I can recommend is using the AWS CloudFormation's Syntax definition of each AWS Resource. For Example : EC2 Instance is represented by the following syntax. Not all of them are mandatory. http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html Look at the KEYS of the Key:Value pair provided below [ "AvailabilityZone" : String ] { "Type" : "AWS::EC2::Instance", "Properties" : { "AvailabilityZone" : String, "BlockDeviceMappings" : [ EC2 Block Device Mapping, ... ], "DisableApiTermination" : Boolean, "EbsOptimized" : Boolean, "IamInstanceProfile" : String, "ImageId" : String, "InstanceInitiatedShutdownBehavior" : String, "InstanceType" : String, "KernelId" : String, "KeyName" : String, "Monitoring" : Boolean, "NetworkInterfaces" : [ EC2 Network Interface, ... ], "PlacementGroupName" : String, "PrivateIpAddress" : String, "RamdiskId" : String, "SecurityGroupIds" : [ String, ... ], "SecurityGroups" : [ String, ... ], "SourceDestCheck" : Boolean, "SsmAssociations" : [ SSMAssociation, ... ] "SubnetId" : String, "Tags" : [ Resource Tag, ... ], "Tenancy" : String, "UserData" : String, "Volumes" : [ EC2 MountPoint, ... ], "AdditionalInfo" : String } } For VPC [http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html] { "Type" : "AWS::EC2::VPC", "Properties" : { "CidrBlock" : String, "EnableDnsSupport" : Boolean, "EnableDnsHostnames" : Boolean, "InstanceTenancy" : String, "Tags" : [ Resource Tag, ... ] } } For EBS Volume [http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html] { "Type":"AWS::EC2::Volume", "Properties" : { "AutoEnableIO" : Boolean, "AvailabilityZone" : String, "Encrypted" : Boolean, "Iops" : Number, "KmsKeyId" : String, "Size" : String, "SnapshotId" : String, "Tags" : [ Resource Tag, ... ], "VolumeType" : String } } The CloudFormation Resource Page has details for most of the items [http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html]. Below is the current list as of today [7 Jan 2016] * *AWS::AutoScaling::AutoScalingGroup *AWS::AutoScaling::LaunchConfiguration *AWS::AutoScaling::LifecycleHook *AWS::AutoScaling::ScalingPolicy *AWS::AutoScaling::ScheduledAction *AWS::CloudFormation::Authentication *AWS::CloudFormation::CustomResource *AWS::CloudFormation::Init *AWS::CloudFormation::Interface *AWS::CloudFormation::Stack *AWS::CloudFormation::WaitCondition *AWS::CloudFormation::WaitConditionHandle *AWS::CloudFront::Distribution *AWS::CloudTrail::Trail *AWS::CloudWatch::Alarm *AWS::CodeDeploy::Application *AWS::CodeDeploy::DeploymentConfig *AWS::CodeDeploy::DeploymentGroup *AWS::CodePipeline::CustomActionType *AWS::CodePipeline::Pipeline *AWS::Config::ConfigRule *AWS::Config::ConfigurationRecorder *AWS::Config::DeliveryChannel *AWS::DataPipeline::Pipeline *AWS::DirectoryService::MicrosoftAD *AWS::DirectoryService::SimpleAD *AWS::DynamoDB::Table *AWS::EC2::CustomerGateway *AWS::EC2::DHCPOptions *AWS::EC2::EIP *AWS::EC2::EIPAssociation *AWS::EC2::Instance *AWS::EC2::InternetGateway *AWS::EC2::NetworkAcl *AWS::EC2::NetworkAclEntry *AWS::EC2::NetworkInterface *AWS::EC2::NetworkInterfaceAttachment *AWS::EC2::PlacementGroup *AWS::EC2::Route *AWS::EC2::RouteTable *AWS::EC2::SecurityGroup *AWS::EC2::SecurityGroupEgress *AWS::EC2::SecurityGroupIngress *AWS::EC2::SpotFleet *AWS::EC2::Subnet *AWS::EC2::SubnetNetworkAclAssociation *AWS::EC2::SubnetRouteTableAssociation *AWS::EC2::Volume *AWS::EC2::VolumeAttachment *AWS::EC2::VPC *AWS::EC2::VPCDHCPOptionsAssociation *AWS::EC2::VPCEndpoint *AWS::EC2::VPCGatewayAttachment *AWS::EC2::VPCPeeringConnection *AWS::EC2::VPNConnection *AWS::EC2::VPNConnectionRoute *AWS::EC2::VPNGateway *AWS::EC2::VPNGatewayRoutePropagation *AWS::ECS::Cluster *AWS::ECS::Service *AWS::ECS::TaskDefinition *AWS::EFS::FileSystem *AWS::EFS::MountTarget *AWS::ElastiCache::CacheCluster *AWS::ElastiCache::ParameterGroup *AWS::ElastiCache::ReplicationGroup *AWS::ElastiCache::SecurityGroup *AWS::ElastiCache::SecurityGroupIngress *AWS::ElastiCache::SubnetGroup *AWS::ElasticBeanstalk::Application *AWS::ElasticBeanstalk::ApplicationVersion *AWS::ElasticBeanstalk::ConfigurationTemplate *AWS::ElasticBeanstalk::Environment *AWS::ElasticLoadBalancing::LoadBalancer *AWS::IAM::AccessKey *AWS::IAM::Group *AWS::IAM::InstanceProfile *AWS::IAM::ManagedPolicy *AWS::IAM::Policy *AWS::IAM::Role *AWS::IAM::User *AWS::IAM::UserToGroupAddition *AWS::Kinesis::Stream *AWS::KMS::Key *AWS::Lambda::EventSourceMapping *AWS::Lambda::Function *AWS::Lambda::Permission *AWS::Logs::Destination *AWS::Logs::LogGroup *AWS::Logs::LogStream *AWS::Logs::MetricFilter *AWS::Logs::SubscriptionFilter *AWS::OpsWorks::App *AWS::OpsWorks::ElasticLoadBalancerAttachment *AWS::OpsWorks::Instance *AWS::OpsWorks::Layer *AWS::OpsWorks::Stack *AWS::RDS::DBCluster *AWS::RDS::DBClusterParameterGroup *AWS::RDS::DBInstance *AWS::RDS::DBParameterGroup *AWS::RDS::DBSecurityGroup *AWS::RDS::DBSecurityGroupIngress *AWS::RDS::DBSubnetGroup *AWS::RDS::EventSubscription *AWS::RDS::OptionGroup *AWS::Redshift::Cluster *AWS::Redshift::ClusterParameterGroup *AWS::Redshift::ClusterSecurityGroup *AWS::Redshift::ClusterSecurityGroupIngress *AWS::Redshift::ClusterSubnetGroup *AWS::Route53::HealthCheck *AWS::Route53::HostedZone *AWS::Route53::RecordSet *AWS::Route53::RecordSetGroup *AWS::S3::Bucket *AWS::S3::BucketPolicy *AWS::SDB::Domain A: Try using AWS CLI. You can execute the describe commands of the various services to see and understand the metadata
unknown
d13921
train
Approximately 3:4:6:8 for the ldpi mdpi hdpi and xhdpi ratios.
unknown
d13922
train
Ok so there was an answer before, but because two people asked the same/similar question, I just posted the same thing twice. Anyhow, the duplicate answer was deleted by the mod, but I would have at least expected them to link you the other question after deleting the answer here. Alas, people are not perfect. However since the other question was badly worded anyway, I have since deleted the answer off of the other post, and I have added in the answer here again. Interactions Actions was moved from selenium-remote-driver to selenium-api. I had the same issue and then noticed while I was using v3.14.0 for everything else, my selenium-api was on v3.12.0. It worked after I explicitly set the version in my POM: <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-api</artifactId> <version>3.14.0</version> </dependency> Hope it works for you.
unknown
d13923
train
Firstly, you are getting incorrect results as some of the names contain spaces (Eric, Marry, Heather, ...). So, let mat <- gsub(" ", "", mat) g1 <- graph_from_edgelist(mat) degree.cent <- centr_degree(g1, mode = "all") Now we may extract the corresponding names of vertices and combine them with your result: setNames(degree.cent$res, V(g1)$name) # Jim Eric Mary Tim Erica Matt Loranda Beth Heather # 4 5 2 4 1 6 2 2 2 # Patrick Courtney John # 2 1 1
unknown
d13924
train
If I take this tweet, I can find it's id in the URL witch is "1294917318405836802" You can update your code and try to retrieve it id_ = "1294917318405836802" exp_tweet = api.get_status(id_, tweet_mode = 'extended') content = exp_tweet._json
unknown
d13925
train
Use a function to insert the variable... notEqualSerie: function() { return series; }
unknown
d13926
train
.vimrc should be in your home directory. .vimrc is there to make more interactive according to your need. Here is an example of .vimrc filetype indent on set ai set mouse=a set incsearch set confirm set number set ignorecase set smartcase set wildmenu set wildmode=list:longest,full A: Where: On UN*X systems your .vimrc belongs in your home directory. At a terminal, type: cd $HOME vim .vimrc This will change to your home directory and open .vimrc using vim. In vim, add the commands that you know you want to put in, then type :wq to save the file. Now open vim again. Once in vim you can just type: :scriptnames to print a list of scripts that have been sourced. The full path to your .vimrc should be in that list. As an additional check that your commands have been executed, you can: * *add an echo "MY VIMRC LOADED" command to the .vimrc, and when you run vim again, you should see MY VIMRC LOADED printed in the terminal. Remove the echo command once you've verified that your.vimrc is loading. *set a variable in your .vimrc that you can echo once vim is loaded. In the .vimrc add a line like let myvar="MY VIMRC LOADED". Then once you've opened vim type echo myvar in the command line. You should see your message. The Format: The format of your .vimrc is that it contains Ex commands: anything that you might type in the vim command-line following :, but in your .vimrc, leave off the :. You've mentioned :set ruler: a .vimrc with only this command looks like: set ruler Search for example vimrc and look over the results. This link is a good starting point. A: The ".vimrc"(vim resource configuration) file provides initialization settings that configure Vim every time it starts. This file can be found in "$HOME/.vimrc" for linux/OSX and "$HOME/_vimrc" for Window users. Inside Vim, type ":echo $HOME" to see the value of $HOME for your system For example, we can do following settings in your .vimrc file. set hlsearch: Enable search highlighting set ignorecase: Ignore case when searching set incsearch: Incremental search that shows partial matches. A: Open vim ~/.vimrc using vim ~/.vimrc, put this in it: set paste set nonumber set hlsearch Save the file and quit using :wq. Changes in this .vimrc will be used when reopening your Vim editor.
unknown
d13927
train
The only way I managed to make it work was by only providing the username to the git clone command: git clone https://[email protected] Once I did that, a login pop up appeared and I was able to insert my password unencoded, managing to clone it. So from my point of view it might be a documentation error since adding the encoded password did not work. I have to mention that I encoded the password because the git bash stated that some of the passwords characters were not allowed in there
unknown
d13928
train
<img> elements have height and width properties that are automatically populated by the browser when it determines the dimensions of an image. .height() and .width() map to the more generic offsetHeight and offsetWidth properties that return 0 when an element is hidden. Accessing the height and width properties directly should allow your code to work correctly: //Takes the number of pixesl to resize the x-axis of the image to $.fn.resizeImage = function(newX) { return this.each(function() { var $this = $(this); //The load event is defined via plugin and takes care of the problem of the load event //not firing for elements that have been cached by the browser. $this.bind('load', function() { var y = this.height; var x = this.width; //return if image does not for some reason if (x == 0 || y == 0) { return; } //alert('y: ' + y + ' x: ' + x); var ratio = y / x; var newY = Math.floor(newX * ratio); $this.height(newY); $this.width(newX); }); }); };
unknown
d13929
train
You can’t access the theme state variable from the global scope where you are using it. I.e. the Stylesheet.create method call. You can just use the themeState in the components instead of calling in the StyleSheet.create call.
unknown
d13930
train
Solved it for now, since I had just one certificate I put it in emulator's keystore. If somebody has better solution, please let me know.
unknown
d13931
train
Short answer, it is distributed separately. Servlets are a specification and an API. If you want the JAR, download it from the spec site Servlet Spec 3.0. Obviously if you want to actually deploy your application, you'll still need an implementation (i.e. a server). A: The servlet API is available through some jar and you can do with it what you want. On maven it is here. You can compile the code without any application server but it probably won't do what you want. It is only an interface afterall Servlets are only really relevant in the context of a Web Application and this is why Servlet Containers exist. They are the implementation. Take a look at all the work the container does before a request reaches the servlet: Tomcat Sequence Diagram. A: Servlets like other Java EE technology like EJB are Specification from JSR(Java Specification Requests) from Java Community Process Program The onus is on the Application Server vendor to provide the implementation based on the specifications released.In this case - for Servlet 2.5 - for Servlet 3.0 Sun / now Oracle does release the javax.servlet package separately and you can download it from Maven Repository also its available within the lib folder of any J2ee complaint application server/web container . i.e for Tomcat its available in TOMCAT_HOMEDIR/lib/servlet-api So for developing and compiling , this jar is sufficient , you would only need the Application server only when you want to actually deploy your application.
unknown
d13932
train
Terminology about correlations is confusing, so let me take care in defining what it sounds like you want to compute. Autocorrelation matrix of a random signal "Autocorrelation matrix" is usually understood as a characterization of random vectors: for a random vector (X[1], ..., X[N]) where each element is a real-valued random variable, the autocorrelation matrix is an NxN symmetric matrix R_XX whose (i,j)th element is R_XX[i,j] = E[X[i] ⋅ X[j]] and E[⋅] denotes expectation. To reasonably estimate an autocorrelation matrix, you need multiple observations of random vector X to estimate the expectations. But it sounds like you have only one 1D array x. If we nevertheless apply the above formula, expectations simplify away to R_XX[i,j] = E[X[i] ⋅ X[j]] ~= x[i] ⋅ x[j]. In other words, the matrix degenerates to the outer product np.outer(x, x), a rank-1 matrix with one nonzero eigenvalue. But this is an awful estimate of R_XX and doesn't reveal new insight about the signal. Autocorrelation for a WSS signal In signal processing, a common modeling assumption is that a signal is "wide-sense-stationary or WSS", meaning that any time shift of the signal has the same statistics. This assumption is particularly such that the expectations above can be estimated from a single observation of the signal: R_XX[i,j] = E[X[i] ⋅ X[j]] ~= sum_n (x[i + n] ⋅ x[j + n]) where the sum over n is over all samples. For simplicity, imagine in this description that x is a signal that goes on infinitely. In practice on a finite-length signal, something has to be done at the signal edges, but I'll gloss over this. Equivalently by the change of variable m = i + n we have R_XX[i,j] = E[X[i] ⋅ X[j]] ~= sum_m (x[m] ⋅ x[j - i + m]), with i and j only appearing together as a difference (j - i) in the right-hand side. So this autocorrelation is usually indexed in terms of the "lag" k = j - i, R_xx[k] = sum_m (x[m] ⋅ x[j - i + m]). Note that this results in a 1D array rather than a matrix. You can compute it for instance with scipy.signal.correlate(x, x) in Python or xcorr(x, x) in Matlab. Again, I'm glossing over boundary handling considerations at the signal edges. Please follow these links to read about the options that these implementations provide. You can relate the 1D correlation array R_xx[k] with the matrix R_XX[i,j] by R_XX[i,j] ~= R_xx[j - i] which like you said is Toeplitz.
unknown
d13933
train
You can do this with very little code in jQuery 1.4+ using .delay(), like this: $(function() { $(".secretpopout").delay(120000).fadeIn(); }); This would show it after 2 minutes, just give it some CSS so it's hidden initially: .secretpopout { display: none; }
unknown
d13934
train
Look also at VisualVM, shipped with latest Java releases. A: Oh shoot, looking through the source code I noticed the thread class has a method public StackTraceElement[] getStackTrace(), it just wasn't in the documentation I was reading. Now I feel dumb. So yeah, that seems to be the solution. A: One approach might be to use something like BCEL to preprocess the target bytecode to insert calls to your own code on every method entry and exit (probably best to do exit by wrapping the whole method in a try/finally block, to catch exception exits). From this, you can deduce the call tree exactly as it happens. A: You could use AspectJ for that. Have a look at this description of exactly your use case. A: Have a look at the ThreadMXBean class -- it my provide what you need. Essentially, you: * *call ManagementFactory.getThreadMXBean() to get an instance of ThreadMXBean; *call getAllThreadIds() on the resulting ThreadMXBean to enumerate current threads; *call getThreadInfo() to get the top n stack trace elements from a given list of threads.
unknown
d13935
train
According to the directories, I believe it is a problem with the Android SDK. Try reinstalling Android Studio (but keep the project files), which will also reinstall the Android SDK with it. If that doesn't work, go to https://developer.android.com/studio/#downloads, scroll down to command-line tools only, and download the right version of the Android SDK based on your OS. Go through the install process and hopefully that should fix your issue.
unknown
d13936
train
As Jimmy points out, you do indeed miss even long runs of the same character as long as the run isn't of the character that starts the sequence you are testing. Here's a solution that I believe works in all cases: public static int lengthOfLongestSubstring(String s) { if (s.length() == 0) return 0; if (s.length() == 1) return 1; int max = 0; for (int i = 0;i<s.length();i++){ Set<Character> chars = new HashSet<>(); chars.add(s.charAt(i)); for (int j = i+1; j< s.length(); j++){ Character b = s.charAt(j); if (chars.contains(b)) break; chars.add(b); } if (chars.size() > max) max = chars.size(); } return max; } A: The reason you are not getting the right answer here I believe is an algorithmic flaw. Your nested loops check to see if any character in a string is different from the first character. This does not check to see if there are any repeating characters in a substring. For example, in the example "abcabcbb," starting at the second 'a' there are no more 'a's, so your program will count the entire rest of the string. You will need to make some algorithmic modifications to solve your problem.
unknown
d13937
train
Resolution: using "elastic" user account instead of kibana fixed this issue. A: Configuring security in Kibana To use Kibana with X-Pack security: Update the following settings in the kibana.yml configuration file: elasticsearch.username: "kibana" elasticsearch.password: "kibanapassword" Set the xpack.security.encryptionKey property in the kibana.yml configuration file. xpack.security.encryptionKey: "something_at_least_32_characters" Optional: Change the default session duration. xpack.security.sessionTimeout: 600000 Restart Kibana. Please follow this link using-kibana-with-security
unknown
d13938
train
The first time the callback is called first is a string (the first element in the array), and your function makes sense when first and last are both strings, so it works when the callback is only called once (the array has at most 2 elements). The second time it is called it is the result of the previous call, a number. When you call first.length on a number you get undefined and when you call Math.max on that you get NaN. If you want to find the length of the longest string in your array, you could use: Math.max.apply(Math, this.text.map(function (str) { return str.length; })); A: Some good answers already. :-) The simple way to fix your problem is to supply an initial value of 0, then compare the returned value with the length of the new string, so: Str.prototype.reduceIt = function() { return this.text.reduce(function(first,last,index,arr) { // Compare current value (first) with length of string return Math.max(first,last.length); }, 0); // supply 0 as the initial value }; It might make things clearer to rename first to maxSoFar and last to currentString. A: Why it returns NAN for array having more than two elements?? Because number.length is undefined, let's name your function foo and follow how it's invoked * *foo(0, "i am a boy") gives NaN *foo(NaN, " she loves cats") gives NaN *foo(NaN, " a goat ate my flower garden ") gives NaN Giving a final result of NaN. This happens because number.length is undefined and Math.max(undefined, x) is NaN It looks like you wanted to write a function which only takes the length of the second arg function foo(a, b) { return Math.max(a, b.length); } In this case, you'll get * *foo(0, "i am a boy") gives 10 *foo(10, " she loves cats") gives 15 *foo(15, " a goat ate my flower garden ") gives 29 Giving a final result of 29.
unknown
d13939
train
It shows because your router expect 2 parameter but you are giving 1 parameter seats Define your route this way $route['category/(:any)/(:num)'] = 'public_controller/category/$1/$2'; Now call your route http://localhost/ecom/category/seats/0 for category page http://localhost/ecom/category/seats/1 for first pagination if you want to separate your category route Define two route one for category page and other for category pagination For category page $route['category/(:any)'] = 'public_controller/category/$1'; For category pagination $route['category/(:any)/(:num)'] = 'public_controller/category/$1/$2'; A: So, I created a demo for your problem and this is what worked for me ↓↓ $route['category'] = 'my_controller/category'; // this route handles all the requests without any additional segments $route['category/(:any)'] = 'my_controller/category/$1'; // this route handles the requests when only one segment is present $route['category/(:any)/(:num)'] = 'my_controller/category/$1/$2'; // this route handles the requests when there are two segments(2nd parameter being a number) This is possible because Routes will run in the order they are defined. Higher routes will always take precedence over lower ones.(Reference) I also found a similar question you might wanna take a look at. Hope this resolves your issue.
unknown
d13940
train
I think there are two different concepts in here: * *The inner representation of a Room in your service (The classes you use and their relations) *The outer representation (The one exposed by your API) If you want those two representation to be the same, you could just serialize/deserialize data using the Room class directly (which I assume is what you are currently doing). For example: @Controller class MyController { @PostMapping @ResponseStatus(HttpStatus.CREATED) @ResponseBody public Room createRoom(@RequestBody Room room) { // Here room will be automatically deserialized from the request body // Do stuff with the received room in here // ... // Here the returned room will be automatically serialized to // the response body return createdRoom; } } However, if you don't want the inner and outer representations to be the same, you can use the DTO pattern (Data Transfer Object). Example in Spring here. Now, you would have three different classes, Room and it's DTOs: public class RoomRequestDTO { private String room_id; private Boolean status; private Double price; private Long type; private Long occupancy; private Integer roomType; // This is now an Integer // Setters and Getters ... } public class RoomResponseDTO { private String room_id; private Boolean status; private Double price; private Long type; private Long occupancy; private RoomType roomType; // This is a RoomType instance // Setters and Getters ... } Now, your controller would receive RoomRequestDTOs and send RoomResponseDTOs: @Controller class MyController { @PostMapping @ResponseStatus(HttpStatus.CREATED) @ResponseBody public RoomResponseDTO createRoom(@RequestBody RoomRequestDTO roomReqDTO) { Room room = ... // Convert from DTO to Room // Do stuff with the received room in here RoomResponseDTO roomRespDTO = ... // Convert to the DTO return roomRespDTO; } } This approach also has the advantage that you can now change the inner representaion of Room without afecting the API. This is, you could decide to merge the Room and RoomType classes in one, without affecting the outer representation. Note: In the example I have linked, they use the ModelMapper library. If you do not desire to introduce that dependecy, you could simple add a contructor and a method to the DTOs as such public RoomResponseDTO(Room room) { // Manually asign the desired fields in here this.id = room.getId(); // ... } public Room toRoom() { Room room = new Room(); // Manually asing the desired field in here room.setId(this.id); // ... return room; } However, this approach would make you have to change these methods whenever you want to change the representations of Room. The ModeMapper library does this for you.
unknown
d13941
train
You can find the duplicate elements by using a Set as the accumlator and then utilise Collections.frequency to check if a given number occurs more than once within the List<Integer> like this: List<Integer> elements = new ArrayList<>(Arrays.asList(1,2,5,4,7,6,4,7,6,4,7)); Set<Integer> accumulator = new LinkedHashSet<>(); for (Integer number : elements) { if(Collections.frequency(elements, number) > 1) accumulator.add(number); } now the accumulator contains: [4, 7, 6] LinkedHashSet is utilised here to maintain insertion order. if that is not required then you can use a HashSet instead. or a better performant solution as suggested by JB Nizet: List<Integer> elements = new ArrayList<>(Arrays.asList(1,2,5,4,7,6,4,7,6,4,7)); Set<Integer> tempAccumulator = new LinkedHashSet<>(); Set<Integer> resultSet = new LinkedHashSet<>(); for (Integer number : elements) { if(!tempAccumulator.add(number)) resultSet.add(number); }
unknown
d13942
train
Is there a way, on Linux/X, to map certain key combos to other key combos? In the tradition of all open source projects, there's not a way, there are several. At the lowest level you've got kernel keybindings, which is probably not what you want. At the X server level you've got xkb with its myriad utilities. And then it seems that every window manager - gnome, kde, xfce or other - also has a keymapping utility. xkb seems to have lots of utils and such around it, and is likely more complete than any random window manager's keymapping utils, so I'd look at that first. A: KDE 3 is probably the most flexible here; there's a pre-defined keyboard shortcut scheme named "Mac Scheme". You can set it through KControl Control Center > Regional & Accessibility > Keyboard Shortcuts or kcmshell keys and it will have effect on almost all KDE applications immediately. You might miss some of those Emacs-like "Ctrl-*" shortcuts that OS X has, but that aside, it works well (as long as your X modifiers are mapped correctly). And if it's not to your liking, it's easily customizable. You can also set Control Center > Desktop > Behavior to enable a Mac OS-like menubar; all KDE applications will then share a menubar at the top of the screen instead of being individually attached to each window. A: Update 02/03/2020 Kinto has now been rewritten in C for Ubuntu/Debian systems using x11. It also uses json config files, making it easier to manage and extend to other applications than just terminals. The app no longer maps to Super in the Terminal apps, it will now properly map to Ctrl+Shift to create the exact same feel as having a Cmd key. Please checkout the latest release. https://github.com/rbreaves/kinto The main change to allow for the Super = Ctrl+Shift change is in this symbols file. default partial xkb_symbols "mac_levelssym" { key <LWIN> { repeat= no, type= "ONE_LEVEL", symbols[Group1]= [ Hyper_L ], actions[group1]=[ SetMods(modifiers=Shift+Control) ] }; key <RWIN> { repeat= no, type= "ONE_LEVEL", symbols[Group1]= [ Hyper_R ], actions[group1]=[ SetMods(modifiers=Shift+Control) ] }; }; Pjz's answer is correct in saying that an xkb solution would be ideal, sadly few have taken that route, most likely due to the difficulty of learning xkb and it seems many have gone the route of using Xmodmap files which is being deprecated while we are on our way to Wayland. This answer may be several years too late, but here it is any ways. Kinto is a tool I recently created that will address this problem and does so by using xkb and by listening to what app you are currently using, as it also changes the keymap while using terminals so the mac like experience can be consistent. https://github.com/rbreaves/kinto https://medium.com/@benreaves/kinto-a-mac-inspired-keyboard-mapping-for-linux-58f731817c0 Here's a Gist as well, if you just want to see what is at the heart of it all, it will not alternate your keymap when needed though. The Gist also does not include custom xkb keymap files that setup macOS style cursors/word-wise manipulations that use Cmd and the arrow keys. https://gist.github.com/rbreaves/f4cf8a991eaeea893999964f5e83eebb Edit: Posting the contents of the gist as well. I cannot realistically post the contents of Kinto. # permanent apple keyboard keyswap echo "options hid_apple swap_opt_cmd=1" | sudo tee -a /etc/modprobe.d/hid_apple.conf update-initramfs -u -k all # Temporary & instant apple keyboard keyswap echo '1' | sudo tee -a /sys/module/hid_apple/parameters/swap_opt_cmd # Windows and Mac keyboards - GUI (Physical Alt is Ctrl, Physical Super is Alt, Physical Ctrl is Super) setxkbmap -option;setxkbmap -option altwin:ctrl_alt_win # Windows and Mac keyboards - Terminal Apps (Physical Alt is Super, Physical Super is Alt, Physical Ctrl is Ctrl) setxkbmap -option;setxkbmap -option altwin:swap_alt_win # # If you want a systemd service and bash script to help toggle between # GUI and Terminal applications then look at project Kinto. # https://github.com/rbreaves/kinto # # Note: The above may not work for Chromebooks running Linux, please look # at project Kinto for that. # # If anyone would like to contribute to the project then please do! # A: You'll get almost all of the way there if you switch Cmd and Ctrl A: xmodmap -e "keycode 63 = Control_L" That way Cmd will be Control. No other keys will be swapped Edited: I forgot the "-e"
unknown
d13943
train
All controls refresh/update whether visible or not. It's generally considered good practice to not load recordsets until they are needed. If you have many subforms in a tab control, you can use the tab control's OnChange event to load/unload your subforms, or, alternatively, to set the recordsources. However, with only a couple of subforms, this is not likely to be a big help. But with a half dozen or so, it's a different issue. A: You can remove the recordsource from the subform and add it back when the form is made visible, or simply remove the whole subform and add that back.
unknown
d13944
train
SqlDataAdapter does not have asynchronous methods. You will have to implement it yourself which I don't recommend. sample await Task.Run(() =>_adapter.Fill(ParentManager.MainDataSet, TableName)); But I would look into an alternative solution using other ADO.NET libraries like using an async SqlDataReader. sample public async Task SomeAsyncMethod() { using (var connection = new SqlConnection("YOUR CONNECTION STRING")) { await connection.OpenAsync(); using (var command = connection.CreateCommand()) { command.CommandText = "YOUR QUERY"; var reader = await command.ExecuteReaderAsync(); while (await reader.ReadAsync()) { // read from reader } } } } Look at section Asynchronous Programming Features Added in .NET Framework 4.5 https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/asynchronous-programming But I would probably not even bother with any of this and just use Dapper which has support for async methods without you having to write all the boilerplate code. https://dapper-tutorial.net/async A: Implement the async versions of your methods like this: public async Task LoadElementsAsync() { await Task.Factory.StartNew(LoadElements); }
unknown
d13945
train
Use the DATETIME type and the following code : $lastSeen= mysqli_query($con, "UPDATE ws_users SET us_lastseen=NOW() WHERE us_id=$user_id"); Or add quotes : $now = date("Y-m-d H:i:s"); $lastSeen= mysqli_query($con, "UPDATE ws_users SET us_lastseen='$now' WHERE us_id=$user_id"); You should debug your query and execute it to see if it throws an error (using phpmyadmin i.e.)
unknown
d13946
train
You should use requests as such: requests.post(url, files=files, data=data)
unknown
d13947
train
I get an error 17:28:46 [SEVERE] com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MyS QL server version for the right syntax to use near ' NOW(), DATE_ADD( now(), INT ERVAL 1 MONTH )' at line 1 – sanchixx It was due to error in SELECT .. statement. Modified statement is: INSERT INTO vips( memberId, gotten, expires ) SELECT name, NOW(), DATE_ADD( now(), INTERVAL 1 MONTH ) FROM members WHERE id = ? * *You don't require VALUES key word when inserting with a select. *You used a wrong DATEADD function syntax. Correct syntax is Date_add( date_expr_or_col, INTERVAL number unit_on_interval). You can try your insert statement as corrected below: INSERT INTO vips( memberId, gotten, expires ) SELECT name FROM members WHERE id = ?, NOW(), DATE_ADD( now(), INTERVAL 1 MONTH ) Refer to: * *INSERT ... SELECT Syntax *DATE_ADD(date,INTERVAL expr unit)
unknown
d13948
train
When performing operations in the console, the return value of the last executed line is always output. That means that simply writing var counter = 0; ++counter; will log 1 to the console. The same is happening in your loop, the return value of the last counter++ is output to the console as the value of the last executed expression. A: The output of the log method depends on the javascript engine of the browser. The last value printed is not output of the loop itself. Try: var counter=0; while(counter<5){ console.log(counter++); }
unknown
d13949
train
I think this sample code should solve your problem. You get spaces by having spaces between your formats. You need to use \r\n to get a new line on Windows machines. strings = {'hello','how','are','you'}; numbers = [1, 2, 3, 4]; fileID = fopen('tester.txt','w'); format = '%s %f \r\n'; for i = 1:length(numbers) fprintf(fileID,format,strings{i},numbers(i)); end fclose(fileID);
unknown
d13950
train
You can get the JSON representation of an arbitrary product in your store by fetching data from /products/<some-product-handle>.js. When using the .js endpoint, the product object will include a number of aggregate parameters, including product.available which will be true if at least 1 variant in the product is available. Note that Shopify has 2* different product representations, one at the /products/<some-product-handle>.js endpoint and one at the /products/<some-product-handle.json endpoint. These two objects are surprisingly different, and one of those differences is that the .json endpoint does not have the aggregate product.available value - you would have to determine that yourself by checking the availability of all the variants within if using this endpoint. This is one of the reasons why I generally recommend using the .js endpoint for all your Javascript needs. * Strictly speaking, there's actually 3 different product representations: the output from a {{ product | json }} drop from Liquid is slightly different from both endpoints but largely the same as the .js endpoint, with the exception being how the product.options array is structured A: You have four options for getting data into javascript in Shopify: * *If the javascript is included as an inline script tag / a snippet in the liquid file then you’d be writing javascript liquid and you can interpolate directly e.g. var product = "{{ product | json}}". *You can update the liquid document to include e.g. attributes with the required data, e.g ‘data-‘ attributes, and then read those with javascript from the document. You’ve said this is not an option. *Re-fetch some data about entities on the current page using a Shopify API: e.g Ajax / Storefront / Shopify Buy SDK. *Add an alternative liquid page for an existing theme page that formats the data you need to json (e.g. {{ product | json }}) but name it e.g. product.ajax.liquid - this will make it into a custom view. Then you can fetch this pages url with the query parameter ?view=ajax and returned document will include the rendered json. This effectively creates a custom API for you. Those are the options.
unknown
d13951
train
As pointed out in the comments it seems like Add Username into Serilog would serve your purpose and would also be the duplicate of this issue.
unknown
d13952
val
USE MAX AND MIN SELECT dbo.product_img.p_id , dbo.products.name , MAX(dbo.product_img.path) , MIN(dbo.product_img.path) FROM dbo.product_img INNER JOIN dbo.products ON dbo.product_img.p_id = dbo.products.p_id GROUP BY dbo.product_img.p_id , dbo.products.name A: If you can have more than two images per product you can do this to get one column with the img path's. select p.p_id, p.name, stuff((select ', '+i.path from product_img as i where p.p_id = i.p_id for xml path(''), type).value('text()[1]', 'nvarchar(max)'), 1, 2, '') as path from products as p Result p_id name path ----- ----- ------------ 15 name1 1.jpg, 2.jpg 17 name2 3.jpg, 4.jpg
unknown
d13953
val
It's definitely possible to update the publisher chain and to try to decode an array of [SomeDecodable], and failing that, fallback on decoding the SomeDecodable itself. The pattern would be to wrap it in a FlatMap, and to deal with a failure inside of it. So, let's say you have some upstream publisher with an output of Data and failure of Error, and you're trying to decode some generic type T: Decodable, this could be a way to approach: upstream .flatMap { data in Just(data) // attempt to decode as [T] .decode(type: [T].self, decoder: JSONDecoder()) // if successful, publish each element one-by-one .flatMap { arr -> AnyPublisher<T, Error> in Publishers.Sequence(sequence: arr).eraseToAnyPublisher() } // if error, attempt to decode as T, possibly failing .tryCatch { _ in Just(data).decode(type: T.self, decoder: JSONDecoder()) } } // this will be an AnyPublisher<T, Error> .eraseToAnyPublisher()
unknown
d13954
val
It should be coming from the SDK that you are using to build the wrapper. It'll be somewhere like... ${FLEX_HOME}/templates/express-installation/index.template.html A: As of Flex SDK 4.5: The template file used when building your project via html-wrapper ant task unfortunately does NOT come from ${FLEX_SDK_HOME}/templates/swfobject. The template file used by the ant task is actually baked into the flexTasks.jar file found in ${FLEX_SDK_HOME}/ant/lib. As you know, there is no convenient option you can apply on the task to use a different template. Because my needed changes were minor (and presumably useful on all of my projects) I simply unzipped flexTasks.jar and re-zipped it with my modified template. A: Since you did use the history="true" you need change the template inside P:\ath\to\sdks\X.Y.Z\templates\express-installation-with-history as documented here.
unknown
d13955
val
The version of CsvHelper you are using uses CurrentCulture to get the delimiter. It appears your are in Germany, so your delimiter would be ";" instead of ",". The current version of CsvHelper forces you to pass in a CultureInfo object to CsvReader and CsvWriter with the suggestion of CultureInfo.InvariantCulture to try and mediate this issue. In your CsvParserService try adding the following to both the ReadCsvFileToJobApplicationModel() and WriteNewCsvFile() methods. csv.Configuration.Delimiter = ",";
unknown
d13956
val
SELECT A.AttendanceID,A.Date,A.Present,A.ModuleID,S.StudentID,S.Name FROM attendance A ,student S WHERE A.StudentID = S.StudentID AND S.StudentID = "Your Value from the textbox"; INNER JOIN I prefer to use objectDataSource rather than SQLDataSource. to separate your layers.and use parameterized query to avoid sql injection and validate the user entry.
unknown
d13957
val
If you ARE using Add -> Class OR Add -> New Item and then selecting Class, and you're still only getting an empty code file, then your default "class" template is missing or messed up. If you are using Add -> Code OR Add -> New Item and selecting Code, the "Code" template is simply an empty ".cs" file, and will be given to you empty as such. In C# Express, this file should be located at "C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VCSExpress\ItemTemplates\1033\". The template for the full (paid) version of Visual Studio will be the exact same file, only the folder location will differ. The file should be a standard zip file named "Class.zip". This zip file should contain two files, as follows: First file should be named "Class.cs" and contain: using System; using System.Collections.Generic; $if$ ($targetframeworkversion$ == 3.5)using System.Linq; $endif$using System.Text; namespace $rootnamespace$ { class $safeitemrootname$ { } } Second file should be named "Class.vstemplate" and contain: <?xml version="1.0" encoding="utf-8"?> <VSTemplate Version="3.0.0" Type="Item" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005"> <TemplateData> <Name Package="{FAE04EC1-301F-11d3-BF4B-00C04F79EFBC}" ID="2245" /> <Description Package="{FAE04EC1-301F-11d3-BF4B-00C04F79EFBC}" ID="2262" /> <Icon Package="{FAE04EC1-301F-11d3-BF4B-00C04F79EFBC}" ID="4515" /> <TemplateID>Microsoft.CSharp.Class</TemplateID> <ProjectType>CSharp</ProjectType> <RequiredFrameworkVersion>2.0</RequiredFrameworkVersion> <NumberOfParentCategoriesToRollUp>1</NumberOfParentCategoriesToRollUp> <DefaultName>Class.cs</DefaultName> </TemplateData> <TemplateContent> <References> <Reference> <Assembly>System</Assembly> </Reference> <Reference> <Assembly>System.Data</Assembly> </Reference> <Reference> <Assembly>System.Xml</Assembly> </Reference> </References> <ProjectItem ReplaceParameters="true">Class.cs</ProjectItem> </TemplateContent> </VSTemplate> If you put all of this in place, and you still get a blank code file, consider reinstalling Visual Studio. A: Check you have the following file on your system. C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip If not check out this Blog Post which has a brief explaination on running devenv /installvstemplates or google with bing devenv /installvstemplates I once had a similiar issue when I had visual webdeveloper installed and then upgraded to full visual studio pro. If the files are in fact there I am sorry I have not had that issue and you might want to search T4 templates as I think this is what Visual Studio uses to take the template file and make it your new class file complete with class name etc. A: You mentioned in the comments you were pressing "New->Code", dont, thats supposed to be blank. click Add>NewItem>Class , Make sure its a "Class" you select not just a code file. A: Just to cover all bases... The template for "Code File" is blank and the template for "Class" has what you expect. Are you sure you're selecting the template for Class and not Code File? A: It could be possible that your default language has not been set. This link should help you change the default language to c# (which I am assuming from your question is the language you are going to use in Visual Studio). A: try on the vs command prompt: devenv.exe /installvstemplates A: try to run devenv /resetsettings it has to be run from the Visual Studio command prompt
unknown
d13958
val
Make sure the Content-Type metadata is set properly for your CSS files via the Developer Console. If not, you should manually edit the metadata to set the proper type, which is text/css for CSS files. If the type is neither not specified nor auto-detected at upload time, Google Cloud Storage serves files as binary/octet-stream which may prevent the browser from properly rendering it. Alternatively, you can also specify the MIME type in HTML, e.g., <link rel="stylesheet" href="css/theme.css" type="text/css"> to make sure that the browser handles it appropriately.
unknown
d13959
val
The suggestion would be to use the IdentityServer (http://thinktecture.github.com/Thinktecture.IdentityServer.v2/), a replacement for ADFS, which uses the same authentication protocol (WS-Federation) but allows you to plugin your custom membership provider. In addition, the IdentityServer supports some features ADFS lacks and is quite extensible. A: Are your applications in the same domain? If so, can you use Forms Authentication Across Applications?
unknown
d13960
val
I think OpenCV fullfills your requirements. See the thread here about decreasing the resolution and read the OpenCV documentation.
unknown
d13961
val
Since there's a bounty, I'll repost this as a reply as well -- but in reality I would like to flag this as a duplicate, since the actual Exception is the one covered in another question, and answered: It is caused by hdp.version not getting substituted correctly. You have to set hdp.version in the file java-opts under $SPARK_HOME/conf. Alternatively, use --driver-java-options="-Dhdp.version=INSERT_VERSION_STRING_HERE" --conf "spark.executor.extraJavaOptions=-Dhdp.version=INSERT_VERSION_STRING_HERE" in your spark-submit and make sure to use the correct version string, as in the subdirectory of /usr/hdp. If you want to stick with calling client.submit from your code, then you need to put those lines into the --arg you build in your code.
unknown
d13962
val
In the build.gradle file, I deleted implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'. Android Studio had warned in uncertain terms (as usual) that putting different versions in the dependencies "might produce some bugs". The said dependency was the first that could be deleted without causing any compile errors. And waddayou know, the backspace/shift bug disappeared immediately...
unknown
d13963
val
Right now, you are converting the strings to uppercase, but that's it. There is no actual renaming being done. In order to rename, you need to use os.rename If you were to wrap your code with os.rename, it should solve your problem, like so: [os.rename("parallel_universe/" + x, "parallel_universe/" + os.path.splitext(x)[0].upper() + os.path.splitext(x)[1]) for x in universe] I have removed the assignment universe= because this line no longer returns a list and you will instead get a bunch on None objects. Docs for os.rename: https://docs.python.org/3/library/os.html#os.rename
unknown
d13964
val
I did part of what you are asking for a customer weeks ago. Your question is to broad, very extensive, it will take months to accomplishes the job. Start your project with the basic that you can find at http://wiki.mikrotik.com/wiki/API_PHP_class, then you can grow your application and post specific questions about your problems in places like stackoverflow or reddit. Follow a sample to connect to the API, then execute commands and then disconnect. $API = new RouterosAPI(); $API->debug = true; // turn debug on to learn more about your api if ($API->connect($server , $username , $passwd, $port)) { // wireless registration table $API->write('/interface/wireless/registration-table/print',false); $API->write('=stats='); // print output here } else { // connection fails } $API->disconnect(); Ref.: * *https://www.reddit.com/r/mikrotik/ *http://wiki.mikrotik.com/wiki/API_PHP_class A: You should either use APIs or a remote command protocols like ssh/telnet(PHP-SSH2). This is a PHP API project you could use: https://github.com/BenMenking/routeros-api After connecting you can commit commands just like you do on mikrotik console. Mikrotik commands wiki A: In my opinion you better use Radius server with database on MySQL. Mikrotik works perfect with Radius. In application implement interface with the database and all interaction with Mikrotik leaves to Radius. Read about FreeRadius for example: https://www.howtoforge.com/authentication-authorization-and-accounting-with-freeradius-and-mysql-backend-and-webbased-management-with-daloradius
unknown
d13965
val
To get a list of cats that have never been requested you'd go with: Cat.includes(:cat_requests).where(cat_requests: { id: nil }) # or, if `cat_requests` table does not have primary key (id): Cat.includes(:cat_requests).where(cat_requests: { cat_id: nil }) The above assumes you have the corresponding association: class Cat has_many :cat_requests end A: It sounds like what you need is an outer join, and then to thin out the cats rows that don't have corresponding data for the requests? If that's the case, you might consider using Arel. It supports an outer join and can probably be used to get what you're looking for. Here is a link to a guide that has a lot of helpful information on Arel: http://jpospisil.com/2014/06/16/the-definitive-guide-to-arel-the-sql-manager-for-ruby.html Search the page for "The More the Merrier" section which is where joins are discussed.
unknown
d13966
val
if(Plane.isLanded = true) Note that this is assigning the value true to Plane.isLanded. You want to use the comparison operator == instead of =. if(Plane.isLanded == true) And since this is a boolean already, you should actually leave out the == true completely: if(Plane.isLanded) A: You are assigning to Plane.isLanded, not testing for equality if(Plane.isLanded = true) should be if(Plane.isLanded == true) You could avoid this altogether with simply if (Plane.isLanded) or put the constant term on the left if (true == Plane.isLanded) which would not have compiled had you made your initial mistake of = instead of ==
unknown
d13967
val
The cart object is null until the service getPosts$ returns (callback). Therefore, the code *ngIf="cart.vegetable ... is equal to *ngIf="null.vegetable ... until that happens. That is what is happening. What you could do is put a DOM element with *ngIf="cart" containing the other *ngIf. For example: <div *ngIf="cart"> <h2 *ngIf="cart.vegetable == 'carrot' ">{{cart.vegetable}}</h2> </div> *Edit: As it is said in the next answer, a good alternative (and good practice) is the following: <h2 *ngIf="cart?.vegetable == 'carrot' ">{{cart.vegetable}}</h2> A: Use the safe-navigation operator to guard against null or undefined for async fetched data: <h2 *ngIf="cart?.vegetable == 'carrot' ">{{cart.vegetable}}</h2> A: I used {{ }} while they are not needed. Getting rid of them fixed it for me. So this <li *ngIf="{{house}}"> Should be <li *ngIf="house">
unknown
d13968
val
Just add the xml file inside app_data folder and read it using XDocument. You can event use Cache with FileDependency to improve performance.
unknown
d13969
val
You should be looking at SAX parsers in Java. DOM parsers are built to read the entire XMLs, load into memory, and create java objects out of them. SAX parsers serially parse XML files and use an event based mechanism to process the data. Look at the differences here. Here's a link to a SAX tutorial. Hope it helps. A: If you're prepared to buy a Saxon-EE license, then you can issue the simple query "copy-of(//page)", with execution options set to enable streaming, and it will return you an iterator over a sequence of trees each rooted at a page element; each of the trees will be fetched when you advance the iterator, and will be garbage-collected when you have finished with it. (That's assuming you really want to do the processing in Java; you could also do the processing in XQuery or XSLT, of course, which would probably save you many lines of code.) If you have more time than money, and want a home-brew solution, then write a SAX filter which accepts parsing events from the XML parser and sends them on to a DocumentBuilder; every time you hit a startElement event for a page element, open a new DocumentBuilder; when the corresponding endElement event is notified, grab the tree that has been built by the DocumentBuilder, and pass it to your Java application for processing.
unknown
d13970
val
A exemple add and remove divs by id (jquery) $( '#add' ).click(function() { var n = 0; n = $( "div" ).length; if(n!=1){ n = n-2; } n = n+1; var div_id = "div_"+n; $( document.body ).append( $( '<div id = "'+ div_id+ '">' )); $( "#count" ).val("There are " + n + " divs."); }) // Trigger the click to start //.trigger( "click" ); $( '#remove' ).click(function() { var n = 0; n = $( "div" ).length; if(n!=1){ n = n-2; } var div_id = "div_"+n; $( "#"+div_id ).remove( ); if(n!=0){ n = n-1; } $( "#count" ).val("There are " + n + " divs."); }) body { cursor: pointer; } div { width: 50px; height: 30px; margin: 5px; float: left; background: blue; } span { color: red; } <meta charset="utf-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> Create and remove divs by id </p> <input id = "count" type = "text" val = "0"> <button id = "remove" >Remove</button> <button id = "add" >Add</button> <br> </br> To add div with id: $( document.body ).append( $( '<div id = "'+ div_id+ '">' )); To remove div with id: $( "#"+div_id ).remove( ); To calculate the number of divs: n = $( "div" ).length; For a specific type of class: var numItems = $('.clas').length;
unknown
d13971
val
You need learn more about $scope. We never user {{$scope.key}} in view. Instead we we use just {{key}} in View Your code should be <div class="container" ng-app="App"> <div class="row" ng-controller="catControl"> <div class="col-md-12"> <div class="well"> {{2 + 2}} </br> {{'cat'}} </br> {{$scope.cat}} <!-- This will not work --> {{cat}} <!-- This will work --> </div> </div> </div> </div> learn more about scope at This link & This Link
unknown
d13972
val
your not very clear with what you want exactly. so I've made some assumptions. (all of those assumptions can be corrected if I assumed wrong). Assumptions: * *Header should scroll with the content. (that behavior can be changed if you want) *the scroll should be applied on the 'Content Zone' only. (that behavior can be changed if you want) *the content wrapper should always span to the end of the page, even if the physical content is smaller then that. and should have a scrolling only when the physical content is larger than the available space. (that behavior can be changed if you want) [as you can see, all of those behaviors can be changed with the correct CSS] Here is a Working Fiddle * *this is a pure CSS solution. (I always avoid scripts if I can) *cross browser (Tested on: IE10, IE9, IE8, Chrome, FF) HTML: (I've added a wrapper for the scroll-able content) <div class="scollableContent"> <div class="header"> <h1>header</h1> </div> <div class="main"> <h1>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque lacinia tempus diam in malesuada. Aliquam id enim nisl. Integer hendrerit adipiscing quam, fermentum pellentesque nisl. Integer consectetur hendrerit sapien nec vestibulum. Vestibulum ac diam in arcu feugiat fermentum nec id nibh. Proin id laoreet dui, quis accumsan nisi. Quisque eget sem ut arcu faucibus convallis. Sed sed nisl commodo, faucibus leo sed, egestas est. Cras at nibh et erat ullamcorper sollicitudin vitae non nibh.</h1> </div> </div> <div class="footer"> <h2>footer</h2> </div> CSS: * { padding: 0; margin: 0; } .scollableContent { position: absolute; top: 0; bottom: 25px; /*.footer height*/ overflow: auto; } .scollableContent:before { content: ''; height: 100%; float: left; } .header { /*Addition*/ background-color: red; } .main { /*Addition*/ background-color: yellow; } .main:after { content: ''; display: block; clear: both; } .footer { position: fixed; width: 100%; bottom: 0px; height: 25px; /*Addition*/ color: white; background-color: blue; } Explanation: The .footer is fixed to the view port bottom, with a fix height. and spans the whole view port width. the .scollableContent is absolutely positioned to span exactly all the space between the top of the view port, and the top of the footer. with automatic overflow that allow scrolling if the content is bigger than the available space. inside the .scollableContent we have a simple block element for the header, that will span his content height. after him we have another block element for the content itself. now we want the content to always stretch to the end of the container, regardless of the header height (so we can't apply it with a fixed height). we achieve this using floating & clearing techniques. we create a floating element before the .scollableContent, with no content (so it's invisible and doesn't really take any place at all) but with 100% height. and at the end of the content div, we create a block with clear instruction. now: this new block cannot be position in the same line with the floating element. so he has to be moved down, dragging the content div along with him. Et voilà! EDIT: you're probably going to use this solution inside some existing Container in your website. (and not as the whole website layout). I've updated the fiddle so that the content is enclosed within a container. that way it will be easier for you to port this solution to your working website. here is the Updated Fiddle A: <style> div { border: 3px solid black; height: 300px; width: 100%; position: absolute; bottom: 25px; } </style> <div></div>
unknown
d13973
val
Try this class CreateJoinTableArticleCategory < ActiveRecord::Migration def change create_join_table :articles, :categories do |t| t.index :article_id t.index :category_id end end end Ref: api doc Edit: No need to add index and primary key into join table. Ref: see this answer
unknown
d13974
val
if(userNum != 11) || (userNum != 22) || (userNum != 33) || (userNum != 44) || (userNum != 55) || (userNum != 66) || (userNum != 77) || (userNum != 88) || (userNum != 99) Will always be true, because userNum cannot be all of those values at once. Substitute || for &&: if(userNum != 11) && (userNum != 22) && (userNum != 33) && (userNum != 44) && (userNum != 55) && (userNum != 66) && (userNum != 77) && (userNum != 88) && (userNum != 99) This can be made easier using the modulus operator: if(userNum % 11 != 0) A: The problem lies in this line. if(userNum != 11) || (userNum != 22) || (userNum != 33) || (userNum != 44) || (userNum != 55) || (userNum != 66) || (userNum != 77) || (userNum != 88) || (userNum != 99) If userNum is any number, it cannot be 11, 22, 33, 44, 55, 66, 77, 88, and 99 at once, which means your program will keep running. As @Carcigenicate stated, you want && (and) operators. A: Try using the && operator here instead of OR import java.util.Scanner; public class LabProgram { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int userNum = scan.nextInt(); if ((userNum >= 20) && (userNum <= 98)){ System.out.print(userNum + " "); while (userNum != 11 && userNum != 22&& userNum != 33 && userNum != 44 && userNum != 55 && userNum != 66 && userNum != 77&& userNum != 88 && userNum != 99){ userNum = userNum - 1; System.out.print(userNum + " "); } } else{ System.out.print("Input must be 20-98"); } System.out.print("\n"); } } A: Your code appears to be searching for multiples of 11, so I would prefer testing the remainder of eleven. Also, you can use x-- instead of x = x - 1. Finally, a do-while loop would make this a bit cleaner. Like, Scanner scan = new Scanner(System.in); int userNum = scan.nextInt(); if (userNum >= 20 && userNum <= 98) { do { System.out.print(userNum + " "); userNum--; } while (userNum % 11 != 0); System.out.println(); } A: You can use following code to ending a while loop when it reaches matching numbers using array. public class stopWhileTest{ public static void main(String arg[]) { int[] number = {11, 22, 33, 44, 55, 66, 77, 88}; Scanner scan = new Scanner(System.in); int userNum = scan.nextInt(); if ((userNum >= 20) && (userNum <= 98)){ System.out.print(userNum + " "); while(!contains(number,userNum)){ userNum = userNum - 1; System.out.print(userNum + " "); } } else{ System.out.print("Input must be 20-98"); } System.out.print("\n"); scan.close(); } public static boolean contains(final int[] array, final int v) { boolean result = false; for(int i : array){ if(i == v){ result = true; break; } } return result; } } Hope this solution works.
unknown
d13975
val
Oracle doesn't have a built-in month function so I'm assuming that is a user-defined function that you've created. Assuming that's the case, it sounds like you want where start_date > (case when month(sysdate) > 6 then trunc(sysdate,'yyyy') + interval '6' month else trunc(sysdate,'yyyy') - interval '6' month end) A: Just subtract six months and compare the dates: SELECT * FROM ORDERS WHERE trunc(add_months(sysdate, -6), 'YYYY') = trunc(start_date, 'YYYY') This compares the year of the date six months ago to the year on the record -- which seems to be the logic you want.
unknown
d13976
val
Without seeing the form I can only theorize what happens: * *You started with a clean slate, the form shows, you enter the username and password and submit it *The code passes the condition and then performs the login *The result of login(...) !== true for whatever reason (wrong password or bug in the code) *The page redirects to login.php?error=1. Now, the $_POST is empty and $_REQUEST contains array('error' => 1). Perhaps the login.php shouldn't redirect to itself but rather redirect back to the page where you show the form.
unknown
d13977
val
I solved this kind of problem before by simply considering the received array of bytes as a bit flow. So it's quite easy to read 3 bits, then 7 bits, then 10 bits, then 2 bits, etc. until the end of the buffer. You simply need to keep an index to the current bit: struct bitflow { unsigned char* data ; // Received data size_t datasize ; // Data size, in bytes. size_t pc ; // Current bit pointer, initialize it to zero. } To get the next bit (0/1=bit, -1=error): int getnextbit (struct bitflow* b) { // Check if we didn't already reached the end of buffer. // "pc" must be stricly below (classic C indexes) than the number of bytes (datasize) multiplied by 8 (number of bits per byte). // A shift of 3 ranks to the left is the same as multiplying by 8, but is faster and will be faster even without any enabled optimization from compiler. if (pc>=(datasize<<3)) return -1 ; // Where is the bit: // - Targeted byte is the integer part of "pc/8". Again, a shift to accelerate that. // - Targeted bit is the remainder of "pc/8". A binary mask with 7 do the same, again faster than a modulo even without optimizations. // We then shift a bit (1) to the position of the remainder, and with a bitwise "AND", we extract the bit. // If the result is zero, the bit wasn't set, we return zero. // If non-zero (equal to (1<<((b->pc) & 7)), in fact), we return "1". int result = (((b->data[(b->pc)>>3]) & (1<<((b->pc) & 7))) ? 1 : 0) ; // We extracted a bit, so we increment the pointer to next bit. b->pc++ ; return result ; } To get the next N bits (max. 31 bits, >=0 = OK, <0=error): // l2m==0: read from LSB to MSB, otherwise, read from MSB to LSB. int getnextbits (struct bitflow* b, int nbbits, int l2m) { if ((nbbits<0) || (nbbits>31)) return -2 ; if ((pc+nbbits)>=(datasize<<3)) return -1 ; int result = 0 ; size_t j=b->pc ; // Alternatives for endianness (depends on both CPU used and I2C data format, read both datasheets and/or simply test): if (l2m) { // 1st read bit is LSB (least significant bit), last read bit is MSB (most significant bit). for (int i=0 ; i<nbbits ; i++, j++) result |= (((b->data[j>>3]) & (1<<(j & 7))) ? (1<<i) : 0) ; } else { // 1st read bit is MSB, last read bit is LSB. for (int i=(nbbits-1) ; i>=0 ; i--, j++) result |= (((b->data[j>>3]) & (1<<(j & 7))) ? (1<<i) : 0) ; } b->pc += nbbits ; return result ; } This last function can be heavily optimized by getting directly all possible remaining bits of the current byte, if nbbits (or the number of bits still to extract) is greater or equal to the number of bits left in the current byte. But it shouldn't be needed if you don't have a huge load of data, which is quite unlikely if you get these data from I²C. Endianness can complexify things a bit, but it's not impossible to solve - I usually do the endianness swap directly at reception when needed. Finally, you can read data this way: // Considering structure is filled by reception routine. struct bitflow b = getdatafromi2c() ; // Number of bits for each consecutive element. int format[10] = { 4, 4, 2, 2, 4, 16, 10, 2, 1, 1 } ; unsigned short int result[10] ; for (int i=0 ; i<10 ; i++ ) { int v = getnextbits(&b, format[i]) ; if (v<0) { // Error handling .... } result[i] = (unsigned short int)v ; } // Use result array normally from now. A: uint8_t input_array[4]; uint16_t output_array[4]; // I have to make an assumption that the two fours are filled little-endian. If it's wrong, it's wrong. // You will generally have this problem whenever parameters span bytes. You have to know. output_array[0] = input_array[0] & 0xF; output_array[1] = input_array[0] >> 4; output_array[2] = input_array[1]; // Similar story here. I assume that input_array's bytes are little endian. // You normally find bit-endian and byte-endian are the same but a contrary system could exist. output_array[3] = input_array[2] | (input_array[3] << 8); In the old days people used to do this with structs. Somebody's going to come by and tell me this is undefined, etc; it doesn't really matter. A compiler that emits terrible code for the above emits good code for the below. It's the modern optimizing compilers that an figure the most efficient way for the above that will mess up the below. This has all kinds of alignment and endian assumptions built into it; however where it works, it works well. Where it doesn't work it's undefined. union u { uint8_t input_array[4]; struct input { unsigned char param0 : 4; unsigned char param1 : 4; unsigned char param2 : 8; unsigned char param3 : 6; } } input_form; union input_form input; uint16_t output_array[4]; output_array[0] = input.input.param0; output_array[1] = input.input.param1; output_array[2] = input.input.param2; output_array[3] = input.input.param3;
unknown
d13978
val
select() can accept an array, so try: DB::table('users')->select($arr); This is source code of select() method: public function select($select = null) { .... // In this line Laravel checks if $select is an array. If not, it creates an array from arguments. $selects = is_array($select) ? $select : func_get_args(); A: You can do this in Laravel 5.8 as follows: DB::table('users')->select('username')->pluck('username')->unique()->flatten(); Hope this helps.
unknown
d13979
val
You simply use logging.FileHandler(). I tried to implement it in your method: def pipe_logs_to_terminal(self, level=logging.INFO): log_path = "." # cwd file_name = "my_app" # configure root logger api_logger = logging.getLogger("bgapi") api_logger.setLevel(level=level) # set format formatter = logging.Formatter(self._api._serial.portstr + ': %(asctime)s - %(name)s - %(levelname)s - %(message)s') # configure file handler file_handler = logging.FileHandler("{0}/{1}.log".format(log_path, file_name)) file_handler.setFormatter(formatter) api_logger.addHandler(file_handler) # configure console handler console_handler = logging.StreamHandler(sys.stdout) console_handler.setFormatter(formatter) api_logger.addHandler(console_handler) Optionally you could omit the console_handler (called term in your example) part, if you choose to only pipe your logging into a file.
unknown
d13980
val
You should take a look at that blog. http://mateuszstankiewicz.eu/?p=189 You will find a start of Answer. Moreover I think there is a specific module for video analysis in Opencv. A: You said it looks like transparent. This is what you saw right?→ See YouTube Video - Background Subtraction (approximate median) The reason is you use the median value of all frames to create the background. What you saw in white in your video is the difference of your foreground(average image) and your background. Actually, median filtered background subtraction method is simple, but it's not a robust method. You can try another background subtraction method like Gaussian Mixture Models(GMMs), Codebook, SOBS-Self-organization background subtraction and ViBe background subtraction method. See YouTube Video - Background Subtraction using Gaussian Mixture Models (GMMs) A: Try these papers: * *Improved adaptive Gaussian mixture model for background subtraction *Efficient Adaptive Density Estimapion per Image Pixel for the Task of Background Subtraction
unknown
d13981
val
If you would like to use dplyr, you can find an example here, especially mpalanco's answer. Briefly, after using rowwise to indicate that the operation should be applied by row (rather than to the entire data frame, as by default), you can use mutate to calculate and name a new column off of a selection of existing columns. Check out the documentation on each of those functions for more details. E.g., library(dplyr) DF %>% rowwise() %>% mutate(CM = median(c(C1, C2, C3), na.rm = TRUE)) will yield the output: # A tibble: 5 x 5 ID C1 C2 C3 CM <fct> <dbl> <dbl> <dbl> <dbl> 1 A 3 3 5 3 2 B 2 7 4 4 3 C 4 3 3 3 4 D 4 4 6 4 5 E 5 5 3 5 A: Just a little bit more flexible and up to date. We use c_across with rowwise function and it allows to use tidy-select semantics. Here we choose where to specify we only want the numeric column to calculate the median. library(dplyr) DF %>% rowwise() %>% mutate(med = median(c_across(where(is.numeric)), na.rm = TRUE)) # A tibble: 5 x 5 # Rowwise: ID C1 C2 C3 med <chr> <dbl> <dbl> <dbl> <dbl> 1 A 3 3 5 3 2 B 2 7 4 4 3 C 4 3 3 3 4 D 4 4 6 4 5 E 5 5 3 5 A: To calculate the median of df, you can do the following df$median = apply(df, 1, median, na.rm=T) A: Oneliner that allows you to pick your desired columns: apply(DF[, c("C1", "C2", "C3")], 1, median) ID C1 C2 C3 CM 1 A 3 3 5 3 2 B 2 7 4 4 3 C 4 3 3 3 4 D 4 4 6 4 5 E 5 5 3 5
unknown
d13982
val
This is how I do it.. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url { NSMutableDictionary *dict = [NSMutableDictionary dictionary]; //get parameters [self goResetPassword:dict]; } return YES; } - (void) goResetPassword:(NSDictionary*) dict{ UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil]; UINavigationController *root = [[UINavigationController alloc]initWithRootViewController:[storyboard instantiateViewControllerWithIdentifier:@"resetPasswordView"]]; self.window.rootViewController= root; ResetPasswordViewController *vc = (ResetPasswordViewController*)[[root viewControllers] objectAtIndex:0]; [vc loadData:dict]; } hope it helps... GL HF A: According to your comment your initial ViewController is NavigationController. This is how you can push the required ViewController. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url { // same code UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle:nil]; // Get instance of initial Viewcontroller from storyboard UINavigationController *navController = [storyboard instantiateInitialViewController ]; // Get instance of desired viewcontroller ViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"VideoController"]; // Push ViewController on to NavigationController [navController pushViewController:viewController animated:NO]; return YES; } A: Check It UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]]; UINavigationController *nav = [[UINavigationController alloc] init]; [nav setNavigationBarHidden:NO]; IntroVC *initailView = [board instantiateViewControllerWithIdentifier:@"Intro"]; [nav pushViewController:initailView animated:YES]; self.window.rootViewController = nav; [self.window makeKeyAndVisible]; UIApplication *sharedApplication = [UIApplication sharedApplication]; [sharedApplication unregisterForRemoteNotifications];
unknown
d13983
val
Implement a filter which does basically the following job: HttpSession session = request.getSession(); if (session.isNew()) { session.setAttribute("start", System.currentTimeMillis()); } else { long start = (Long) session.getAttribute("start"); if (System.currentTimeMillis() - start > (30 * 60 * 1000)) { session.invalidate(); response.sendRedirect("expired.xhtml"); return; } } chain.doFilter(request, response); Map this on the servlet name or URL pattern of interest. This is only sensitive to changes in system clock, make sure that your server runs UTC all the time. Otherwise better grab System#nanoTime() instead.
unknown
d13984
val
You can use urllib.request.urlretrieve(url, path_to_file) All code: import urllib.request urllib.request.urlretrieve("https://www.python.org", "/home/user/ne.txt")
unknown
d13985
val
The code I suggested in the comments would work (not sure what you're saying doesn't work about it) - but it has a flaw If greetings were something "I have a lot of phlegm" - it would match with gm so lets try another way function fn(keywords, target) { const res = keywords.map(s => new RegExp(`\\b${s}\\b`)); return res.some(re => target.match(re)); } client.on('message', message =>{ if (message.author.bot) return; const fixgreet = message.content.slice(); const greetings = fixgreet.toLowerCase(); const gnvars = fs.readFileSync('./commands/urls/gn.txt').toString('utf-8'); const gnraw = gnvars.split('\n'); if (fn(gnraw, greetings)) { client.responds.get('gn').execute(message, fixgreet); } so .. fn returns a boolean, that is true if one of the gnraw values is found in the greetings string
unknown
d13986
val
Inside your Service.js, first factory is missing the closing }) paranthesis, check the updated Service.js var app = angular.module("ServiceApp", ["ngResource"]); app.factory('GetPortfolios', function ($resource) { return $resource("http://localhost:61347/api/PortfolioManager/GetPortfolios/", {}, {}); }); app.factory('GetOrders', function ($resource) { return $resource("http://localhost:61347/api/PortfolioManager/GetPortfolioOrders/"); });
unknown
d13987
val
Apparently the :hashtag has two different encodings for me, seems like one is stored as US-ASCII, and one (the parsed) in UTF-8. Funny that I was able to reproduce this only by pasting this into my irb. To solve this, make sure they have the same encoding
unknown
d13988
val
You need to either explicitly cast a value to a non-integer form, e.g. double, or use a non-integer in the calculation. For example: var pc = (p * 100/ (double)c).ToString(); or this (not 100.0 rather than 100): var pc = (p * 100.0/ c).ToString(); Next you need to round the result: var pc = Math.Round(p * 100 / (double)c, 1).ToString(); But as Tetsuya states, you could use the P1 format string (which would output something like 5.0% - culture dependent - for p = 5, c = 100): var pc = (p / (double)c).ToString("P1");
unknown
d13989
val
If your "Service" is just Java classes/package/modules then you can use Spring or any other DI container that supports lifecycle hookups. If by "Service" you mean something big/bloated/enterprise you can also look into OSGI. But for a small/library engine I suggest you look at plexus and picocontainer.
unknown
d13990
val
Figured out: processor.save(...) and learn.preprocessing.VocabularyProcessor.restore(...)
unknown
d13991
val
You can try the steps below: * *Backup the solution *Open VSS Explorer, move project2 folder *Open VS, go to File->Source Control->Change Source Control, update the server path of Project2 *Save the solution.
unknown
d13992
val
I took the liberty of formatting your code. This is how the method looks: double suma (int num [ ]) { int i=num.length; int j=0; int s=0; for(j=0;j < i;j++) { return (double)(s); } } I suspect you attempted to write a sum-method, started with a stub, and didn't get it to compile. This is probably what you had in mind: double suma (int num [ ]) { int i=num.length; int j=0; int s=0; for(j=0;j < i;j++) { // here you probably want s += num[j]; } return (double)(s); } The Java compiler can only deduce that a statement (such as a return) is reachable in very simple cases. (To illustrate: this method does compile. Still not very useful though!) double suma (int num [ ]) { int i=num.length; int j=0; int s=0; for(j=0; true; j++) { return (double)(s); } } A: for(j=0;j < i;j++) {return (double)(s);}}} // here appears the error "missing return statement" There might be case when it doesn't get into loop so it won't return anything. You need to make sure that it should return for all the case
unknown
d13993
val
Solution 1: You could create a user that has access to both databases and then use fully qualified table names when querying for the external table. MySQL supports the dbname.tablename syntax to access tables outside the current database scope. This requires that the currently connected user has the appropriate rights to read from the requested table in another physical db. Solution 2: You can configure two datasources as described here: https://docs.spring.io/spring-boot/docs/current/reference/html/howto-data-access.html#howto-two-datasources A: (Not a direct answer.) If you will be using text other than plain English, consider these settings: Hibernate XML: <property name="hibernate.connection.CharSet">utf8mb4</property> <property name="hibernate.connection.characterEncoding">UTF-8</property> <property name="hibernate.connection.useUnicode">true</property> Connection url: db.url=jdbc:mysql://localhost:3306/db_name?useUnicode=true&character_set_server=utf8mb4 A: @Table(name="tablename", catalog="db2") worked for me
unknown
d13994
val
Is this what you are after?? CREATE TABLE view_data_main ( module_name VARCHAR(30), module_title VARCHAR(30), module_images VARCHAR(30), module_scripts VARCHAR(30) ) INSERT INTO `view_data_main` (module_name,module_title,module_images,module_scripts) VALUES ('welcome','main','http://www.test.com','http://www.test2.com'), (NULL,NULL,'http://www.test.com','http://www.test2.com'), (NULL,NULL,'http://www.test.com','http://www.test2.com') SELECT module_name,module_title,GROUP_CONCAT(module_images),GROUP_CONCAT(module_scripts) FROM `view_data_main` WHERE module_images IS NOT NULL AND module_scripts IS NOT NULL GROUP BY CONCAT(module_images,',',module_scripts) Having re-read the question I don't think the subquery is necessary unless I'm missing something?
unknown
d13995
val
Install a local forwarding nameserver on the computers that need to make a choice between the local nameserver and Internet nameserver. Use Unbound because it's lightweight and easy to configure for this task. Put this into the Unbound config: stub-zone: name: "internal.example.com" stub-host: internal.nameserver.ip.address forward-zone: name: "." forward-host: internet.nameserver.ip.address Put nameserver 127.0.0.1 into /etc/resolv.conf so that application on the local host wil use this instance of Unbound. Now when you try to resolve myhost.internal.example.com it will send the query to internal.nameserve.ip.address and when you try to resolve www.google.com it will send the query to internet.nameserver.ip.address. Hopefully all of your local hosts are grouped under a single local domain (internal.example.com) above. Unfortunately, it is all too likely that your cheap router+DHCPserver+DNSserver sticks all of the hostnames it knows right into its synthesized root zone. If that's the case then you'll have to list them all one by one as follows: stub-zone: name: "hostname1" stub-host: internal.nameserver.ip.address stub-zone: name: "hostname2" stub-host: internal.nameserver.ip.address stub-zone: name: "hostname3" stub-host: internal.nameserver.ip.address forward-zone: name: "." forward-host: internet.nameserver.ip.address The problem with this is of course that now you have a bunch of Unbound instances on different machines that you have to configure and set up. You could avoid this by having just one host on your LAN provide this service and act as a recursive nameserver for all the other hosts, but if you're going to do that then you might as well make that host the DHCP server and authoritative nameserver for local hosts too and get rid of your slow embedded DHCP+DNS server in the first place.
unknown
d13996
val
Take a look at the HyperLinkField class. This should provide exactly what you're looking for. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hyperlinkfield.aspx
unknown
d13997
val
I had the same problem, and found a solution in another answer: Instead of --log-cli-level=DEBUG, use --log-level DEBUG. It disables all third-party module logs (in my case, I had plenty of matplotlib logs), but still outputs your app logs for each test that fails. A: I got this working by writing a factory class and using it to set the level of the root logger to logger.INFO and use the logging level from the command line for all the loggers obtained from the factory. If the logging level from the command line is higher than the minimum global log level you specify in the class (using constant MINIMUM_GLOBAL_LOG_LEVEL), the global log level isn't changed. import logging MODULE_FIELD_WIDTH_IN_CHARS = '20' LINE_NO_FIELD_WIDTH_IN_CHARS = '3' LEVEL_NAME_FIELD_WIDTH_IN_CHARS = '8' MINIMUM_GLOBAL_LOG_LEVEL = logging.INFO class EasyLogger(): root_logger = logging.getLogger() specified_log_level = root_logger.level format_string = '{asctime} ' format_string += '{module:>' + MODULE_FIELD_WIDTH_IN_CHARS + 's}' format_string += '[{lineno:' + LINE_NO_FIELD_WIDTH_IN_CHARS + 'd}]' format_string += '[{levelname:^' + LEVEL_NAME_FIELD_WIDTH_IN_CHARS + 's}]: ' format_string += '{message}' level_change_warning_sent = False @classmethod def get_logger(cls, logger_name): if not EasyLogger._logger_has_format(cls.root_logger, cls.format_string): EasyLogger._setup_root_logger() logger = logging.getLogger(logger_name) logger.setLevel(cls.specified_log_level) return logger @classmethod def _setup_root_logger(cls): formatter = logging.Formatter(fmt=cls.format_string, style='{') if not cls.root_logger.hasHandlers(): handler = logging.StreamHandler() cls.root_logger.addHandler(handler) for handler in cls.root_logger.handlers: handler.setFormatter(formatter) cls.root_logger.setLevel(MINIMUM_GLOBAL_LOG_LEVEL) if (cls.specified_log_level < MINIMUM_GLOBAL_LOG_LEVEL and cls.level_change_warning_sent is False): cls.root_logger.log( max(cls.specified_log_level, logging.WARNING), "Setting log level for %s class to %s, all others to %s" % ( __name__, cls.specified_log_level, MINIMUM_GLOBAL_LOG_LEVEL ) ) cls.level_change_warning_sent = True @staticmethod def _logger_has_format(logger, format_string): for handler in logger.handlers: return handler.format == format_string return False The above class is then used to send logs normally as you would with a logging.logger object as follows: from EasyLogger import EasyLogger class MySuperAwesomeClass(): def __init__(self): self.logger = EasyLogger.get_logger(__name__) def foo(self): self.logger.debug("debug message") self.logger.info("info message") self.logger.warning("warning message") self.logger.critical("critical message") self.logger.error("error message") A: Enable/Disable/Modify the log level of any module in Python: logging.getLogger("module_name").setLevel(logging.log_level)
unknown
d13998
val
Sorry not an answer, but too long for a comment. I built a debug version for our users that experienced crashes, that swizzles the _updateEscapeKeyItem method, in an attempt to pinpoint the crash origin, which isn't visible due to the bottom of the stack being blown away by the infinite recursion. My guess is they changed the 10.13 implementation radically (they mentioned something about "KVO running amok"), and might not look into 10.12 crashes unless they have a solid clue. This is the quick and dirty code in you can drop in (mostly borrowed from How to swizzle a method of a private class), that stops the infinite recursion. The resulting crash reports might be more useful. @interface NSObject (swizzle_touchbar_stuff) @end static NSInteger updateEscapeKeyItem = 0; @implementation NSObject (swizzle_touchbar_stuff) + (void)load { static dispatch_once_t onceToken = 0; dispatch_once(&onceToken, ^{ Method original, swizzled; original = class_getInstanceMethod(objc_getClass("NSApplicationFunctionRowController"), NSSelectorFromString(@"_updateEscapeKeyItem")); swizzled = class_getInstanceMethod(self, @selector(sparkle_updateEscapeKeyItem)); method_exchangeImplementations(original, swizzled); }); } - (void)sparkle_updateEscapeKeyItem { updateEscapeKeyItem++; NSLog(@"sparkle_updateEscapeKeyItem %ld", updateEscapeKeyItem); assert(updateEscapeKeyItem < 10); [(NSObject *)self sparkle_updateEscapeKeyItem]; updateEscapeKeyItem--; } @end
unknown
d13999
val
Just use regular expressions: import re result = re.sub('>\s*<', '><', text, 0, re.M)
unknown
d14000
val
A lot of answers are returning the Index as an array, which loses information about the index name etc (though you could do pd.Series(index.map(myfunc), name=index.name)). It also won't work for a MultiIndex. The way that I worked with this is to use "rename": mix = pd.MultiIndex.from_tuples([[1, 'hi'], [2, 'there'], [3, 'dude']], names=['num', 'name']) data = np.random.randn(3) df = pd.Series(data, index=mix) print(df) num name 1 hi 1.249914 2 there -0.414358 3 dude 0.987852 dtype: float64 # Define a few dictionaries to denote the mapping rename_dict = {i: i*100 for i in df.index.get_level_values('num')} rename_dict.update({i: i+'_yeah!' for i in df.index.get_level_values('name')}) df = df.rename(index=rename_dict) print(df) num name 100 hi_yeah! 1.249914 200 there_yeah! -0.414358 300 dude_yeah! 0.987852 dtype: float64 The only trick with this is that your index needs to have unique labels b/w different multiindex levels, but maybe someone more clever than me knows how to get around that. For my purposes this works 95% of the time. A: You can convert an index using its to_series() method, and then either apply or map, according to your needs. ret = df.index.map(foo) # Returns pd.Index ret = df.index.to_series().map(foo) # Returns pd.Series ret = df.index.to_series().apply(foo) # Returns pd.Series All of the above can be assigned directly to a new or existing column of df: df["column"] = ret Just for completeness: pd.Index.map, pd.Series.map and pd.Series.apply all operate element-wise. I often use map to apply lookups represented by dicts or pd.Series. apply is more generic because you can pass any function along with additional args or kwargs. The differences between apply and map are further discussed in this SO thread. I don't know why pd.Index.apply was omitted. A: As already suggested by HYRY in the comments, Series.map is the way to go here. Just set the index to the resulting series. Simple example: df = pd.DataFrame({'d': [1, 2, 3]}, index=['FOO', 'BAR', 'BAZ']) df d FOO 1 BAR 2 BAZ 3 df.index = df.index.map(str.lower) df d foo 1 bar 2 baz 3 Index != Series As pointed out by @OP. the df.index.map(str.lower) call returns a numpy array. This is because dataframe indices are based on numpy arrays, not Series. The only way of making the index into a Series is to create a Series from it. pd.Series(df.index.map(str.lower)) Caveat The Index class now subclasses the StringAccessorMixin, which means that you can do the above operation as follows df.index.str.lower() This still produces an Index object, not a Series. A: Assuming that you want to make a column in you're current DataFrame by applying your function "foo" to the index. You could write... df['Month'] = df.index.map(foo) To generate the series alone you could instead do ... pd.Series({x: foo(x) for x in foo.index})
unknown