text:
Q: How to make error message to display for that particular input field using angular2 i have multiple input fields, adding and changing are working fine with that particular fieds, but when coming to error message section, if there is input field eror in one field it is shown in all other fields. But, i want error to display for that particular field.
HTML:
<md-card-content>

        <input type="text" name="{{media._id}}[i]" id="{{media._id}}[i]" class="form-control form-textbox input-text" [(ngModel)]="media.editText" #editText pattern="/^(ftp|http|https):\/\/[^ ]+$/" style="width: 58%;margin-left: 1%;">

        {{errorMsg}}

        Change Link
        Add Link

</md-card-content>

TS:
    change(event: any, media) {
    if (media.editText.indexOf('https://www.youtube.com/embed') != -1) {
      this.errorMsg="";
      if (!media._id) {
        var data:any = {
          pin_id: this.pin_id,
          media_type: "video",
          image_path: media.editText
        }
        this.ApiService
            .addLinkMedia(data)
            .subscribe(
              media => {
              })
      } else if(media._id) {
        var data:any = {
          media_id: media._id,
          image_path: media.editText
        }
        this.ApiService
            .addLinkMedia(data)
            .subscribe(
              media => {
                this.loadMedias()
              }, error => {
              })
      }
    } else {
      this.errorMsg = "Please enter valid URL";
    }
}

here i havent used any form validations.

A: Take a variable, which stores the id of media and display error message accordingly depending on the media ID.

*

*I m assigning this.errorDiv[media._id] = true;; so that I can use
errorDiv in *ngIf

*In HTML I used *ngIf="errorMsg[media._id] && (errorDiv[media._id])" which checks the error message and specific Id and display error message accordingly

HTML:

    <input type="text" name="{{media._id}}[i]" id="{{media._id}}[i]" class="form-control form-textbox input-text" [(ngModel)]="media.editText" #editText pattern="/^(ftp|http|https):\/\/[^ ]+$/" style="width: 58%;margin-left: 1%;">

    {{errorMsg[media._id]}}

    Change Link
    Add Link

Component:
public errorDiv = {};
public errorMsg = {};

    change(event: any, media) {
        if (media.editText.indexOf('https://www.youtube.com/embed') != -1) {
          this.errorMsg[media._id] = "";
          this.errorDiv[media._id] = "";
          if (!media._id) {
            var data:any = {
              pin_id: this.pin_id,
              media_type: "video",
              image_path: media.editText
            }
            this.ApiService
                .addLinkMedia(data)
                .subscribe(
                  media => {
                  })
          } else if(media._id) {
            var data:any = {
              media_id: media._id,
              image_path: media.editText
            }
            this.ApiService
                .addLinkMedia(data)
                .subscribe(
                  media => {
                    this.loadMedias()
                  }, error => {
                  })
          }
        } else {
          this.errorMsg[media._id] = "Please enter valid URL";
          this.errorDiv[media._id] = true;
        }
    }

A: Try binding the error message to each media object separately:
HTML:
<md-card-content>

        <input type="text" name="{{media._id}}[i]" id="{{media._id}}[i]" class="form-control form-textbox input-text" [(ngModel)]="media.editText" #editText pattern="/^(ftp|http|https):\/\/[^ ]+$/" style="width: 58%;margin-left: 1%;">

        {{media.errorMsg}}

        Change Link
        Add Link

</md-card-content>

TS:
    change(event: any, media) {
    if (media.editText.indexOf('https://www.youtube.com/embed') != -1) {
      media.errorMsg="";
      if (!media._id) {
        var data:any = {
          pin_id: this.pin_id,
          media_type: "video",
          image_path: media.editText
        }
        this.ApiService
            .addLinkMedia(data)
            .subscribe(
              media => {
              })
      } else if(media._id) {
        var data:any = {
          media_id: media._id,
          image_path: media.editText
        }
        this.ApiService
            .addLinkMedia(data)
            .subscribe(
              media => {
                this.loadMedias()
              }, error => {
              })
      }
    } else {
      media.errorMsg = "Please enter valid URL";
    }
}

A: You can do soething like this. Without doing anything in ts file. You can validate and show validation messages just using form controls.
<input id="name" name="name" class="form-control"
       required minlength="4" appForbiddenName="bob"
       [(ngModel)]="hero.name" #name="ngModel" >

    Name is required.

    Name must be at least 4 characters long.

    Name cannot be Bob.

Taken from angular official doc

A: See the code below and you will realize your mistake. You must add condition that is for the current input only.

          First Name
          <input type="text" name="firstName" [(ngModel)]="model.firstName" #firstName="ngModel" required />

First Name is required

          Last Name
          <input type="text" name="lastName" [(ngModel)]="model.lastName" #lastName="ngModel" required />

Last Name is required

A: Best is you create a custom validator checking your input, you were pointed to the right direction but only very briefly. Create a new directive and provide it in your app module.
@Directive({
    selector: '[appValidURL]',
    providers: [{provide: NG_VALIDATORS, useExisting: URLValidatorDirective, multi: true}]
})
export class URLValidatorDirective implements Validator {
    @Input('appValidURL') url: string;

    validate(control: AbstractControl): {[key: string]: any} {
        return this.url && this.url.startsWith("https://www.youtube.com/embed") ? {value: control.value}}: null;
    }
}

Then in your input code use something like this.
<input type="text" name="videourl" id="videourl" class="form-control" required appValidURL [(ngModel)]="media.editText">

        VideoURL is required!

       It must be an embedded youtube video!

I have never used it like this, but it should work maybe with some minor tweeks.
Edit:
This is only for a single input field, your can try tho to use your array names instead of "videourl", not sure how this works out.


text:
Q: Rails 3 Routing - How to use scope to create admin prefix I'm using this Rails Guide to create a scope in order to create an "/admin" prefix for some controllers.
So I have a controller named Pages, I want to access it via "/admin/pages".
scope "/admin" do
    resources :pages
end

That works great, but it is still accessible via "/pages" ... How do I prevent that? (I'm using Rails 3)
Here's my routes file:
devise_for :users

scope "/admin" do

    resources :pages

    resources :contents

end

root :to => "index#index"

match ':controller(/:action(/:id(.:format)))'

A: Your syntax for the namespace is correct, but you need to remove the catch-all match from the last line because, according to the default routes.rb file,
# This is a legacy wild controller route that's not recommended for RESTful applications.
# Note: This route will make all actions in every controller accessible via GET requests.

If the requested URL does not match the namespace you have declared, it will still match against the catch-all route at the end.

A: Try this should work
namespace :admin do

  resources :pages

end

http://edgeguides.rubyonrails.org/routing.html

A: Try this:
scope "/admin", as: :admin do
  resources :pages
end

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google Drive API thumbnail parameters I'm using Google Drive API (v3) with Google's PHP api client to list and display videos from my Drive, where I'm also displaying thumbnails for said videos. I have difficulties getting thumbnail urls back from the API, although I enabled thumbnailLink in request parameters:
'fields' => 'nextPageToken, files(id, name, thumbnailLink, webContentLink, webViewLink)'

Value for thumbnailLink is still empty, other values are returned successfully. I looked for thumbnail settings in api documentation, without success. API also doesn't return any error. What could it be?
Here's the code I'm using:
$drive_service = new Google_Service_Drive($client);

$optParams = array(
'pageSize' => 4,
'q' => "'0B_nSMgQioOWwNy1ha0tFWEE0QWs' in parents and mimeType contains 'video/'",
'fields' => 'nextPageToken, files(id, name, modifiedTime, mimeType, createdTime, thumbnailLink, webContentLink, webViewLink)'
);

return $files_list = $drive_service->files->listFiles($optParams)->getFiles();

and var_dump of response
array(4) {
[0]=>
object(Google_Service_Drive_DriveFile)#590 (56) {
["collection_key":protected]=>
string(6) "spaces"
["appProperties"]=>
NULL
["capabilitiesType":protected]=>
string(42) "Google_Service_Drive_DriveFileCapabilities"
["capabilitiesDataType":protected]=>
string(0) ""
["contentHintsType":protected]=>
string(42) "Google_Service_Drive_DriveFileContentHints"
["contentHintsDataType":protected]=>
string(0) ""
["createdTime"]=>
string(24) "2016-09-12T19:54:22.000Z"
["description"]=>
NULL
["explicitlyTrashed"]=>
NULL
["fileExtension"]=>
NULL
["folderColorRgb"]=>
NULL
["fullFileExtension"]=>
NULL
["headRevisionId"]=>
NULL
["iconLink"]=>
NULL
["id"]=>
string(35) "1St7nQ3X3-ocrMUC2t-r6NOVc4xIdfhbIgg"
["imageMediaMetadataType":protected]=>
string(48) "Google_Service_Drive_DriveFileImageMediaMetadata"
["imageMediaMetadataDataType":protected]=>
string(0) ""
["isAppAuthorized"]=>
NULL
["kind"]=>
NULL
["lastModifyingUserType":protected]=>
string(25) "Google_Service_Drive_User"
["lastModifyingUserDataType":protected]=>
string(0) ""
["md5Checksum"]=>
NULL
["mimeType"]=>
string(9) "video/mp4"
["modifiedByMeTime"]=>
NULL
["modifiedTime"]=>
string(24) "2016-12-27T11:55:43.958Z"
["name"]=>
string(12) "MOV_1950.mp4"
["originalFilename"]=>
NULL
["ownedByMe"]=>
NULL
["ownersType":protected]=>
string(25) "Google_Service_Drive_User"
["ownersDataType":protected]=>
string(5) "array"
["parents"]=>
NULL
["permissionsType":protected]=>
string(31) "Google_Service_Drive_Permission"
["permissionsDataType":protected]=>
string(5) "array"
["properties"]=>
NULL
["quotaBytesUsed"]=>
NULL
["shared"]=>
NULL
["sharedWithMeTime"]=>
NULL
["sharingUserType":protected]=>
string(25) "Google_Service_Drive_User"
["sharingUserDataType":protected]=>
string(0) ""
["size"]=>
NULL
["spaces"]=>
NULL
["starred"]=>
NULL
["thumbnailLink"]=>
NULL
["trashed"]=>
NULL
["version"]=>
NULL
["videoMediaMetadataType":protected]=>
string(48) "Google_Service_Drive_DriveFileVideoMediaMetadata"
["videoMediaMetadataDataType":protected]=>
string(0) ""
["viewedByMe"]=>
NULL
["viewedByMeTime"]=>
NULL
["viewersCanCopyContent"]=>
NULL
["webContentLink"]=>
string(82) "https://drive.google.com/uc?id=1St7nQ3X3-ocrMUC2t-r6NOVc4xIdfhbIgg&export=download"
["webViewLink"]=>
string(85) "https://drive.google.com/file/d/1St7nQ3X3-ocrMUC2t-r6NOVc4xIdfhbIgg/view?usp=drivesdk"
["writersCanShare"]=>
NULL
["internal_gapi_mappings":protected]=>
array(0) {
}
["modelData":protected]=>
array(0) {
}
["processed":protected]=>
array(0) {
}
}...

A: Try to double check if you properly use a correct scope. I suggest you to use the https://www.googleapis.com/auth/drive for full permissive scope to access all of a user's files. If it's still not working, then try the suggested solution here.

A: Try items.thumbnailLink
This is what the response from the Drive API looks like.
{
 "kind": "drive#fileList",
 "etag": "\"m64ksZC09nG4-fB1IRF3vg/1C1ON4SO5V-To1u55k7dU\"",
 "selfLink": "https://www.googleapis.com/drive/v2/files?corpus=DEFAULT",
 "nextPageToken": "V1*3|0|ChwwQjdXTWpmWkhhWHllTW1ObtQq",
 "nextLink": "https://www.googleapis.com/drive/v2/files?corpus=DEFAULT&pageToken=V1*3%7C0%7CChwwQjdVUnFTR05mZGpREgcQsonGqtQq",
 "items": [
  {
   "kind": "drive#file",
   "id": "1DpsZKiII1pOsHxDrJDzBb_aW841Ovhm8pE5FCI",
   "etag": "\"m64ksZC09nG4-fB1IRF3vg/1C1ON4SO5V-To1u55k7dU\"",
   "selfLink": "https://www.googleapis.com/drive/v2/files/1DpsZKiII1pOsHbrEzvxDrJDzBb_aW841Ovhm8pE5FCI"...

   },
   "defaultOpenWithLink": "https://docs.google.com/spreadsheets/d/1DpsZKihm8pE5FCI/edit?usp=drivesdk",
   "iconLink": "https://ssl.gstatic.com/docs/doclist/images/icon_11_spreadsheet_list.png",
   "thumbnailLink": "https://docs.google.com/feeds/vt?gd=true&id=1DpsZKiInoAAAAAWGPVboChWb270pOAY0M5hMr3FNa-IX6G&sz=s220",
   "title": "Document Title",
   "mimeType": "application/vnd.google-apps.spreadsheet",
   "labels": {
    "starred": false,
    "hidden": false,
    "trashed": false,
    "restricted": false,
    "viewed": true
   },...

Hope this helps!

A: I know you're trying to get a list of files, and this only retrieves a link from one, but this would have helped me a lot, and I think it's similar enough in concept to be potentially helpful to others:
function getThumbnailUrl($fileId)
{
    $service = new Google_Service_Drive($this->client());
    $params = array('fields' => 'hasThumbnail, thumbnailLink');
    $file = $service->files->get($fileId, $params);
    $url = $file->getThumbnailLink();

    return $url;
}

I am still interested in whether you were able to get thumbnail links for multiple files using getFiles().


text:
Q: proper method to identify a particular plant in the video when the taken video is fast? I am new to machine learning. I want to run a classifier (machine-learning-based or deep learning based) on the video to identify one Plant in a grass video.
I have some issues in the taken video:

*

*The video is fast and sometimes it is even difficult for me to identify the plant in the video.

*The resolution or video quality is very high (taken by camera RGB - 12 Mega Pixel)

What would be the best approach to identify this plant? what machine learning approach will provide a more accurate result?

A: Every deep learning architecture takes frames for processing, so video is converted into frames, so it does not depend on video speed.
Accuracy depends on deep learning architecture.
you can check some deep learning architecture such as (YOLO and SSD).


text:
Q: Excel changes a formular I define with the Range.FormulaLocal into a Formula with structured references. I do not want that, how can I change it? I want to insert a formula into a sequence of cells by using a "for-loop". My formula references other cells that change for each loop. The formula itself works but when I enter it with Range.FormulaLocal it changes and my references to other workSheets become structured references. I do not want that because my formula wont work with them. How can I change this behaviour or do I have to change my formula?
    Dim aus As Range
    Dim Nr As Long
    Dim Bux As String
    Set aus = Range("C3")
    For Spalte = 3 To 15 Step 2
    For Zeile = 3 To 10 Step 1
    Nr = aus.Row
    Bux = Buchstabe(aus.Column)
    aus.Select
    Formel = "= VLOOKUP(Auswertung!A" & Nr & "&B" & Nr & "&" & Bux & "1;CHOOSE({1,2,3};Daten!A:A&Daten!B:B&Daten!C:C;Daten!D:D);2;FALSE)"
    Selection.Formula2 = Formel
    Set aus = aus.Offset(1, 0)
    Next
    Set aus = Range(Bux & "3")
    Set aus = aus.Offset(, 2)
    Next

The Formula shoudl look like this:
=SVERWEIS(Auswertung!A3&B3&C1;WAHL({1.2.3};Daten!A:A&Daten!B:B&Daten!C:C;Daten!D:D);2;FALSCH)

but ends up looking like this:
=SVERWEIS(Auswertung!A3&B3&C1;WAHL({1.2.3};@Daten!A:A&@Daten!B:B&@Daten!C:C;Daten!D:D);2;FALSCH)

English version: Expectation
=VLOOKUP(Auswertung!A3&B3&C1;CHOOSE({1.2.3};Daten!A:A&Daten!B:B&Daten!C:C;Daten!D:D);2;FALSE)

Reality:
=@ VLOOKUP(Auswertung!A4&B4&C1;CHOOSE({1.2.3};@Daten!A:A&@Daten!B:B&@Daten!C:C;Daten!D:D);2;FALSE)

Thanks in advance.


text:
Q: Advice on the free and stable react library for creating grid and tabular data in reactjs I am very new to ReactJs, we are developing a reactjs UI with tabular data with check boxes and drop down and editable links to popup a modal for editing and columns.
can anybody advice me on the best and stable library for creating Table.
Since we are new to React, it would be great if it has good documentation.
Below are some of them noticed while searching
1, https://www.ag-grid.com/
2, https://react-table.tanstack.com/
Thanks,
Have nice day ahead.

A: If you are very new to React, react-table might become overwhelming with the amount of customizability and extensibility it offers. It would be easy to render a simple table following the guides but you would probably need a decent enough understanding of React Hooks to implement the custom functionality you want.
If you are short on time, building a custom component which renders a CSS Grid layout might be faster than using a full blown library. You can use render props to render your checkboxes, dropdowns and editable links.


text:
Q: Using python RE to replace a string in Word Document? So i am trying to run through a word document to replace all text strings with 'aaa' (just for example) to replace it with a variable from user input, i have been bashing my head with a few answers on stackoverflow to figure out and came across Regular expressions which i have never used before, after using a tutorial for a bit I just can't seem to get my head round it.
This is all the code i have tried exampling but just can't seem to get python to actually change the text string in this Word Document.
 from docx import Document
 import re

 signature = Document ('test1.docx')
 person = raw_input('Name?')
 person = person+('.docx')
 save = signature.save(person)

 name_change = raw_input('Change name?')
 line = re.sub('[a]{3}',name_change,signature)
 print line
 save
 for line in signature.paragraphs:
     line = re.sub('[a]{3}',name_change,signature)

 for table in signature.tables:
     for cell in table.cells:
        for paragraph in cell.paragraphs:
            if 'aaa' in paragraph.text:
                print paragraph.text
                paragraph.text= replace('aaa',name_change)

  save

Thank you in advance for any help.

A: for line in signature.paragraphs:
    line = re.sub('[a]{3}',name_change,signature)

The above code is redundant since you update the variable line with the re.sub, but it doesn't cause an update in the actual origin, as shown below:
data = ['aaa', 'baaa']
for item in data:
    item = re.sub('[a]{3}', 't', item)

print(data)
#['aaa', 'baaa']

Also, you are iterating over signature.paragraphs but just calling re.sub on the entirety of signature everytime. Try something like this:
signature = re.sub('[a]{3}', name_change, signature)
save


text:
Q: How can I check with the calling URL domain with interceptors.request I am new in exploring axios.
I would like to append Authorization for specific url I am calling
with ininterceptors.request.
Is it possible to check with what url I am calling ?
Let's take a look of my code right now.
service.interceptors.request.use(
  config => {

    config.headers["Authorization"] = "bearer " + getTokenA(); <---- Do this only when the api is /ApiA/
    config.headers["Authorization"] = "bearer " + getTokenB(); <---- Do this only when the api is /ApiB/
    return config;
  },
  error => {
    Promise.reject(error);
  }
);


text:
Q: iOS Array of Colors Retrieval Error I am trying have a button that switches the color of a button. For some reason the code below isn't working...
**//Header (.h)**
    @property UIColor *imageColor1;
    @property UIColor *imageColor2;
    @property UIButton *button1;
    @property UIButton *button2;
    @property CGRect viewBounds;
    -(IBAction)changeColor:(id)sender;
    -(IBAction)createButton;

**//Implementation (.m)**
    @synthesize imageColor1;
    @synthesize imageColor2;
    @synthesize button1;
    @synthesize button2;
    @synthesize viewBounds;

    -(IBAction)createButton{
        self.viewBounds = self.view.bounds;

        self.button1 = [UIButton buttonWithType:UIButtonTypeCustom];
        self.button1.frame = CGRectMake(CGRectGetMidX(self.viewBounds)-30, CGRectGetMidY(viewBounds)-15, 60, 30);
        self.button1.backgroundColor = self.imageColor1;
        [self.view addSubview:button1];

        self.button2 = [UIButton buttonWithType:UIButtonTypeCustom];
        self.button2.frame = CGRectMake(CGRectGetMidX(self.viewBounds)-15, CGRectGetMidY(viewBounds)-30, 30, 60);
        self.button2.backgroundColor = self.imageColor2;
        [self.view addSubview:button2];

    }

    -(IBAction)changeColor:(id)sender{

       int changeCount = 0;
       int changeCount1 = 1;
       NSArray *colors = [[NSArray alloc] initWithObjects:[UIColor redColor],[UIColor blueColor],[UIColor yellowColor],[UIColor                  magentaColor],[UIColor greenColor],[UIColor orangeColor],[UIColor purpleColor], nil];
       if(changeCount < 7){
          imageColor1 = [colors objectAtIndex:changeCount];
       }
       else{
          changeCount = changeCount - 5;
          imageColor1 = [colors objectAtIndex:changeCount];
       }
       if(changeCount1 < 7){
          imageColor2 = [colors objectAtIndex:changeCount1];
       }
       else{
          changeCount1 = changeCount1 - 5;
          imageColor2 = [colors objectAtIndex:changeCount1];
       }
       changeCount++;
       changeCount1++;
    }

Basically, whenever the user taps the "Change Color" button, the variables changeCount and changeCount1 increase their count, and the values in self.imageColor1 and self.imageColor2 are changed to the subsequent values in the array colors. For some reason, this code isn't working and the colors don't change. The createButton method works because whenever I press it, a new button appears, but if I create a button and then press the change color button and then create another button, the color of the new button is still the same. So basically I need to know what's wrong with my code. Thanks in advance.

A: That's because you reset the changeCount and changeCount1 variables every time.  Notice you recreate them and set them to 0 and 1 at the beginning?  So of course they are never going to change.  You are creating them as if they are static variables, but they are not.  They are local variables.  The NSArray could be static, but the count variables are better off as member variables (i.e. defined in your interface).


text:
Q: Launching Sublime Text detached from MSYS bash on Windows Bash is my shell on Windows. How do I launch Sublime Text from the MSYS bash prompt detached from the console similar to launching it using "start /i " on a regular DOS prompt? This is my alias line in my ~/.bashrc file:
alias subl="/c/Program\ Files/Sublime\ Text\ 3/sublime_text.exe"

But this does not detach from the console and I have to close the Sublime Text window or run a new console instance.


text:
Q: Filtering by date (ignoring time-of-day) I'm not getting date filter using JPA.
For example my database table data are using this date format:
id=22001     2012-05-24 01:18:44.459000  -3.72562176     -38.55413138
id=22002     2012-05-24 01:19:58.369000  -3.72556951     -38.55412081
id=22003     2012-05-24 01:20:11.509000  -3.72554203     -38.5541338
id=22004     2012-05-24 01:20:43.832000  -3.72556247     -38.55411875
id=22005     2012-05-27 21:31:31.179000  -3.73500586     -38.5359234
id=22006     2012-05-28 22:41:21.072000  -3.76651343     -38.49477246
id=22007     2012-05-28 22:44:37.100000  -3.76582333     -38.49650576
id=22008     2012-05-28 22:46:47.878000  -3.76732246     -38.49688336
id=22009     2012-05-28 22:48:11.118000  -3.76437084     -38.50487202
id=22010     2012-05-28 22:48:30.419000  -3.76383159     -38.50810391
id=22011     2012-05-28 22:50:21.972000  -3.76130886     -38.50585614
id=22012     2012-05-28 22:51:56.787000  -3.75217442     -38.50331619
id=22013     2012-05-28 22:52:59.405000  -3.7531888  -38.50264043
id=22014     2012-05-28 22:53:48.185000  -3.75311701     -38.50296631
id=22015     2012-05-28 22:54:53.602000  -3.75311704     -38.5029654

This is my code that filter the rows:
public List<GeoLocation> getAll(Date date) {

     javax.persistence.Query q = entityManager
        .createQuery("SELECT g FROM  GeoLocation g where g.criationDate = :data");
     q.setParameter("data", date,TemporalType.DATE);

     @SuppressWarnings("unchecked")
     List<GeoLocation> result  =  q.getResultList();

     return result;
 }

This is my Entity. The date field have TemporalTime annotation
package br.com.drover.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
public class GeoLocation {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(nullable=false)
private Double latitude;

@Column(nullable=false)
private Double longitude;

@Column(nullable=false)
@Temporal(TemporalType.DATE)
private Date creationDate;

//..Some getters and setters

}

A: Assuming that this is going to be a common query, the approach that I'd use would be to add a second 'date party only' column, which could be a TemporalType.DATE with time of day zeroed out. This lets you do an exact filter, which is going to get you good query performance from the datastore at the expense of an extra pair of index writes when you add data.


text:
Q: Trying to get more than 20 followers to display, how can i loop this to give me more? My code reads
    long cursor = -1;
    String userID = "username";
    PagableResponseList<User> followers = twitter1.getFollowersList(userID, cursor);

    for(User follower : followers) {

        String followersList = follower.getScreenName();
        System.out.println(followersList);

    }

This will give me a list of twenty followers, and I understand that I can get more but I cant figure out how to.


text:
Q: Java Jpanel print empty page private void cmdprintActionPerformed(java.awt.event.ActionEvent evt) {

         PrinterJob job = PrinterJob.getPrinterJob();
        job.setJobName("Outside Processing System");

                job.setPrintable (new Printable() {

                @Override
                public int print(Graphics pg, PageFormat pf, int pageNum){

                if (pageNum > 0){
                return Printable.NO_SUCH_PAGE;
                }

                OPSPrintPanel panel = new OPSPrintPanel();
                Graphics2D g2 =(Graphics2D)pg;
                g2.translate(pf.getImageableX(), pf.getImageableY());
                panel.paint(pg);
                return Printable.PAGE_EXISTS;

                }

                });
                boolean ok = job.printDialog();
                if (ok) {
                try {

                job.print();

                } catch (PrinterException ex) {
                JOptionPane.showMessageDialog(null, ex);
                }

                }

          }

I'm trying to print a panel and the codes seems okay but when I click print and view it to pdf its only a blank page. I tried so many codes that can print panel but it doesn't print. Even I reinstall my NetBeans and install an updated jdk it won't work.
Blank page

A: You didn't dispose object g2 and use try catch block when you print as pdf. First you have to print the image as it is and then try to translate it.
Try this, i hope it would works.
        OPSPrintPanel panel = new OPSPrintPanel();
        //print the panel to pdf
        Document document = new Document();
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\temp\\test.pdf"));
            document.open();
    // PdfContentByte is an object containing the user positioned text and
     // graphic contents of a page. It knows how to apply the proper font encoding.
            PdfContentByte contentByte = writer.getDirectContent();
            PdfTemplate template = contentByte.createTemplate(500, 500);
            Graphics2D g2 = template.createGraphics(500, 500);
        // First print the panel as it is and then try to translate it by removing comments
       // g2.translate(pf.getImageableX(), pf.getImageableY());
            panel.print(g2);
            g2.dispose();
      // Adds a template to this content.
            contentByte.addTemplate(template, 30, 300);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if(document.isOpen())
        {
                document.close();
            }
        }


text:
Q: Сокращение document.all?1:0 Вопрос чисто из любопытства: часто в коде встречаю такую конструкцию - var ie = document.all?1:0; Если заранее известно, что переменная ie будет использоваться только для проверки на true/false, не проще ли ее объявить var ie = document.all; ? В чем разница-то?
A: В случае, если document.all определен, в переменную ie запишется document.all, а не true. Тернарный оператор делают, чтобы не таскать в переменной ie объект.
A: Лучше тогда

var ie = !!document.all;

А ещё лучше вообще не использовать проверки на определённый браузер, да и к IE это всё не имеет никакого отношения.


text:
Q: Finding the number of real solutions to $\cos(\cos (\cos x))=\sin(\sin(\sin x))$
The number of real solution of $$\cos(\cos (\cos x))=\sin(\sin(\sin x))$$

Try: Let $f(x)=\sin(\sin x))$ and $g(x)=\cos(\cos x)$
Then $$f(x)-g(x)=\sin(\sin x)-\cos(\cos x)$$
$$=\sin(\sin x)-\sin\bigg(\frac{\pi}{2}-\cos x\bigg)$$
$$=2\cos\bigg(\frac{\sin x-\cos x+90^\circ}{2}\bigg)\sin\bigg(\frac{\sin x+\cos x-90^\circ}{2} \bigg)$$
Could some help me to solve it, Thanks

A: They are infinite. Note that
$$f(x)=\cos(\cos (\cos x))-\sin(\sin(\sin x))$$
is a continuous $2\pi$-periodic function. Moreover
$$f(0)=f(\pi)=\cos(\cos(1))>0\quad\text{and}\quad f(\pi/2)=\cos(1)-\sin(\sin(1))<0,$$ so, by continuity, in each interval $[2\pi k,2\pi(k+1))$ with $k\in\mathbb{Z}$, there are at least two solutions: $x_k\in (2\pi k,2\pi k +\pi/2)$ and $y_k\in (2\pi k +\pi/2, 2\pi k+\pi)$.


text:
Q: how to add Indian rupee symbol in prestashop how to add indian rupee symbol to prestashop?

A: Can you include a custom CSS stylesheet to your PrestaShop deployment? Perhaps JavaScript is an option for you?
This article shows how to do both: How to Add India Rupee Font Symbol

A: visit this site, http://webrupee.com/
and add the javascript code into the  section of your themes/prestashop/header.tpl

A: If you have any font which supports unicode standard you can add the rupee symbol easily by holding the ctrl+shift keys and typing u20b9 which is the unicode value for the symbol.
In prestashop just go to payment > currencies and edit your currency and use the above key and character combination in the space provided for the currency symbol.
Ubuntu font has built in support for the rupee symbol.
Late reply i know but i was struggling with this problem for some time and found this just today. Hope someone finds it. This is the best and simplest way to add the symbol insead of using some third party website API which might be risky for a commercial website.

A: You can simply put unicode of ruppee sign in back office.
While displaying convert that into html unicode.
Or you can display Rs.
we at http://www.mebelkart.com does the same thing.

A: In your shop database search for " _currency" table.In the same table change the value of "sign" field to "&#2352" without quotes.
It will work for the shop.
Enjoy.

A: This can be done by adding javascript code the header.tpl
Or you can change the value of "sign" field to in the _currency table to "&#2352".
We at trodly.com are also doing the 2nd thing.


text:
Q: How can I setState on just one array element at once? I'm a beginner of ReactJS and javascript
I have ask a question about How can I setState on two array elements at once?
At that question the responder tell me don't mutate the state anyway.
But I have another question, If I want to stop the countdown timer by using clearInterval(), when the timer is arrived 0.
In my new attempt at codePen Timer Demo 2,
I use the find() method to find the element which time is 0, and use clearInterval to stop count down, but if one element's time is arrived 0 and another is not, there are all stopped.
How can I do to fix it?
const timers = [
  {
    id: 1,
    time: 5,
    timeIsUp: false,
  },
  {
    id: 2,
    time: 10,
    timeIsUp: false,
  },
];
class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state= {
      timers,
    }
    this.time_controller = 0;

  }
  componentDidMount(){
    this.time_controller = setInterval(() =>{
      this.countDown();
    }, 1000)
  }
  countDown(){
    const foundTimers = this.state.timers.map(timer => ({
      ...timer,
      time: timer.time-1
    }));
    this.setState({timers: foundTimers});
    const foundTimer = foundTimers.find(timer => timer.time === 0 );
    if(!!foundTimer){
      clearInterval(this.time_controller);
    }
  }

  renderTimers(){
    return(
     this.state.timers.map((timer) =>{
      return(

{timer.time}

      )
    })
    )
  }

  render() {

    return (

        {this.renderTimers()}

    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

A: This has nothing to do with state management, it's simple logic:

*

*Don't turn off the interval until you've counted down all the timers.

*Don't reduce the time of timers that have already reached zero.

Side note: There isn't really any reason for the timeIsUp flags, is there? time === 0 means time is up, doesn't it? Duplicating state opens the door to bugs where you update it in one place but not others.
Something along these lines, but the details aren't as important as the concepts:
countDown() {
  let updated = false;
  let keepTicking = false;
  const updatedTimers = this.state.timers.map(timer => {
    // Note that if we don't modify `timer`, we return it for reuse
    if (timer.time > 0) {
      timer = {...timer, time: timer.time - 1};
      updated = true;
      keepTicking = timer.time > 0;
    }
    return timer;
  });
  if (updated) {
    // We changed somthing, update
    this.setState({timers: updatedTimers});
  }
  if (this.time_controller !== 0 && !keepTicking) {
    // No more active timers, stop ticking
    clearInterval(this.time_controller);
    this.time_controller = 0;
  }
}

Note that I clear the timer handle when we clear the timer, so we know whether it's running.
Note that in that example, I take the pragmatic approach of a map callback with side-effects (setting the updated and keepTicking flags). I don't have a problem with localized side-effects like that, but there is a significant movement out there that would.
The non-side-effecty version would at least partially loop the timers more than once:
countDown() {
  const timers = this.state.timers;
  // Need to update?
  if (timers.find(t => t.time > 0)) {
    const updatedTimers = timers.map(timer => (
      // If we don't change a timer, we can reuse it
      timer.time === 0 ? timer : {...timer, time: timer.time - 1}
    );
    this.setState({timers: updatedTimers});
  }
  // Done ticking?
  if (this.time_controller !== 0 && updatedTimers.every(t => t.time === 0)) {
    clearInterval(this.time_controller);
    this.time_controller = 0;
  }
}

Note how the code is cleaner (because we express each thing we're doing on its own only when we need to) but less efficient (we may have to work hard to find that timer near the end that needs updating and keeps us ticking). 90% of the time, efficiency doesn't matter, timers will be less than several thousand entries long. So there's an argument for it.


text:
Q: jquery animation reset after event not working I have this script that works perfectly to animate my elements but when the function is called again after a timer the elements go to the position they need to be but dont start a new animation.
function updateFlights(){
    var sector = window.localStorage.getItem("sector");
        $.ajax({
            type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
            url         : 'http://192.168.1.112/www/php/galaxy/getFlights.php', // the url where we want to POST
            data:{ sector : sector, tiles : 'true' }, // our data object
            dataType    : 'json', // what type of data do we expect back from the server
            encode          : true
        })
            .done(function(data) {
                if ( ! data.success) {
                       console.log('ajax error');
                }
                else{

            console.log(data);
            var keys = Object.keys(data['flight']).length;

            for(i=0;i<keys;i++){

                $("#ship"+i).finish();
                console.log('clear');
            }
            $("#flightsBox").html(" ");
            $("#lineBox").html(" ");

            for (i=0; i<keys; i++){
                if(data['flight'][i].ended){}
                else{

                        var lineColor = 'white';
                        if(data['flight'][i]['type'] == 0){
                            lineColor = 'yellow';
                        }
                        if(data['flight'][i]['type'] == 1){
                            lineColor = 'yellow';
                        }
                        if(data['flight'][i]['type'] == 2){
                            lineColor = 'red';
                        }
                        if(data['flight'][i]['type'] == 3){
                            lineColor = 'red';
                        }
                        if(data['flight'][i]['type'] == 4){
                            lineColor = 'blue';
                        }

                        var startX = parseInt(data['flight'][i]['xPos']);
                        var endX = parseInt(data['flight'][i]['endX']);

                        var startY = parseInt(data['flight'][i]['yPos'])-10;
                        var endY = parseInt(data['flight'][i]['endY']);

                        var startX1 = parseInt(data['flight'][i]['xPos']);
                        var endX1 = parseInt(data['flight'][i]['endX'])-10;

                        var startY1 = parseInt(data['flight'][i]['yPos']);
                        var endY1 = parseInt(data['flight'][i]['endY'])-10;

                            // DRAW LINE
                            $('.lineBox').line(startX1, startY1, endX, endY, {color: lineColor, stroke:1, zindex:1001});

                        if(data['flight'][i].type == 4){

                            // ANIMATE RETURN SHIP
                            $(".flightsBox").append("

");
                            $("#ship"+data['flight'][i]['id']).css({
                                'top' : endY1,
                                'left' : endX1
                            });

                            $( "#ship"+data['flight'][i]['id'] ).animate({
                              'left' : startX,
                              'top' : startY
                            }, data['flight'][i]['remainingTime'], "linear"
                            );

                        }
                        else{

                            // ANIMATE SHIP
                            $(".flightsBox").append("

");
                            $("#ship"+data['flight'][i]['id']).stop(true).css({
                                'top' : startY,
                                'left' : startX
                            });

                            $( "#ship"+data['flight'][i]['id'] ).animate({
                              'left' : endX1,
                              'top' : endY1
                            }, data['flight'][i]['remainingTime'], "linear"
                            );
                        }
                }
        }
        }

        });

}
I am trying to clear all of the animations and start new ones because the data that is sent back will contain more/less ships and different types.
Thanks

A: I solved this by using velocity.js which allows chaining animations and a lot of other useful functions for this type of project.


text:
Q: how can I make Join on different data types of column I have two tables student and student card . in student I have student Id which is number having values 112, 113, 114 but in student card, I have student id with character S like S112, S113.
Is there anyway I can put join on both table by trimming S in the statement .
Not sure if its possible and how?

A: Try this
SELECT * FROM studdent s INNER JOIN student_card sc on 'S'||s.id=sc.student_id

A: You can replace the S character using replace() and then convert it to int like below -
select * from student s inner join studentcard sc
on s.studentid=cast(replace(sc.studentid,'S','') as UNSIGNED)

A: You could just use the correct logic in your join condition:
SELECT *
FROM student s
INNER JOIN student_card sc
    ON SUBSTRING(sc.student_id, 2) = s.id;

This compares the student ID in the student card table from the second character onwards against the full student ID in the student table.  Note that strictly speaking we should do a cast from text to integer, or maybe vice-versa, but MySQL is able to handle implicit conversions, so the above logic alone should be sufficient.


text:
Q: H2 - How to create a database trigger that log a row change to another table? How to create a database trigger that log a row change to another table in H2?
In MySQL, this can be done easily:
CREATE TRIGGER `trigger` BEFORE UPDATE ON `table`
  FOR EACH ROW BEGIN
    INSERT INTO `log`
    (
      `field1`
      `field2`,
      ...
    )
    VALUES
    (
      NEW.`field1`,
      NEW.`field2`,
      ...
    ) ;
    END;

A: Shorter version of Lukas Eder's answer:
CREATE TRIGGER my_trigger
BEFORE UPDATE
ON my_table
FOR EACH ROW
CALL "com.example.MyTrigger"

public class MyTrigger extends TriggerAdapter {

    @Override
    public void fire(Connection conn, ResultSet oldRow, ResultSet newRow) throws SQLException {
        // mannipulate the rows here by using the methods on the oldRow and newRow objects
    }
}

A: Declare this trigger:
CREATE TRIGGER my_trigger
BEFORE UPDATE
ON my_table
FOR EACH ROW
CALL "com.example.MyTrigger"

Implementing the trigger with Java/JDBC:
public class MyTrigger implements Trigger {

    @Override
    public void init(Connection conn, String schemaName,
                     String triggerName, String tableName, boolean before, int type)
    throws SQLException {}

    @Override
    public void fire(Connection conn, Object[] oldRow, Object[] newRow)
    throws SQLException {
        try (PreparedStatement stmt = conn.prepareStatement(
            "INSERT INTO log (field1, field2, ...) " +
            "VALUES (?, ?, ...)")
        ) {
            stmt.setObject(1, newRow[0]);
            stmt.setObject(2, newRow[1]);
            ...

            stmt.executeUpdate();
        }
    }

    @Override
    public void close() throws SQLException {}

    @Override
    public void remove() throws SQLException {}
}

Implementing the trigger with jOOQ:
Since you added the jOOQ tag to the question, I suspect this alternative might be relevant, too. You can of course use jOOQ inside of an H2 trigger:
    @Override
    public void fire(Connection conn, Object[] oldRow, Object[] newRow)
    throws SQLException {
        DSL.using(conn)
           .insertInto(LOG, LOG.FIELD1, LOG.FIELD2, ...)
           .values(LOG.FIELD1.getDataType().convert(newRow[0]),
                   LOG.FIELD2.getDataType().convert(newRow[1]), ...)
           .execute();
    }


text:
Q: Test sending email in django from another thread I'm trying to test my code that sends emails. More or less my unit test looks like:
class EmailTest(TestCase):
    def test_send_email(self):
        my_send_mail_method()
        self.assertEqual(len(mail.outbox), 1)

This code works perfectly fine as long as my_send_mail_method sends email in the same thread. However, when I change the code in a way that my_send_mail_method will send mail from another thread len(mail.outbox) is equal to 0. my_send_mail_method waits until the sending email is finished so I don't think it's a concurrency problem.

EDIT
The code that sends emails looks like assuming it's run in the same thread:
import timeout_decorator
from django.core import mail
from django.test import TestCase

@timeout_decorator.timeout(120, use_signals=False)
def test_send_email():
    mail.send_mail('Subject here', 'Here is the message.',
        'from@example.com', ['to@example.com'],
        fail_silently=False)

The thing is that my method has timeout_decorator (there are more things going on in the method that might hang the processing and I just wanted to kill the process after some time).
I checked the code of the decorator and as far as I can tell it creates a new thread executes it, waits for response and returns it. However, I'm not very proficient in Python and might have missed something obvious here.


text:
Q: xpst0003 xquery syntax error I want to query a webpage through following x query code. please help me.
And it gives me following errors:
 XPST0003: XQuery syntax error in #...//json//sentences//trans); let#:
    expected "return", found ";".
<?xml version="1.0" encoding="UTF-8"?>
<config charset="UTF-8">
<var-def name="scrappedContent">
<xquery>
<xq-param name="doc">
    <html-to-xml outputtype="browser-compact" prunetags="yes">
      <http url="${url}"/>
    </html-to-xml>
  </xq-param>

  <xq-expression><![CDATA[
     declare variable $doc as node() external;
     let $transl := data($doc//query//results//json//sentences//trans);
     let $translitl := data($doc//query//results//json//sentences//translit);

     let $data  := data($doc//div[@id="defId"])
     return
        <myContent>
          <transl>{$transl}</transl>
          <translitl>{$translitl}</translitl>
          <data>{$data}</data>
        </myContent>
   ]]>
</xq-expression>
</xquery>
</var-def>
</config>

A: Replace:
 let $transl := data($doc//query//results//json//sentences//trans);
 let $translitl := data($doc//query//results//json//sentences//translit);

With:
 let $transl := data($doc//query//results//json//sentences//trans)
 let $translitl := data($doc//query//results//json//sentences//translit)

(No semi-colon after let's)
That should improve things..
HTH!


text:
Q: Haskell inline-c multi-step build/link with Cabal I am writing an FFI-heavy library that uses inline-c, and the build process is:

*

*run GHC on the inline-c files, produce C

*compile C produced in previous step into dynamic libraries

*compile Haskell interface while linking both the object files produced in step 2 and the dynlibs of the wrapped library.

QUESTION: Currently I'm doing the above in a makefile (see https://github.com/ocramz/petsc-hs/blob/master/makefile ), but I'd like to package it up in a Cabal file (working version : https://github.com/ocramz/petsc-hs/blob/master/petsc-hs.cabal).
SUB-QUESTIONS:

*

*How does one control the build/link sequence in Cabal?

*Are relative paths supported in Cabal? couldn't find this mentioned in the guide and bash-like ~ doesn't work

Thank you in advance for all pointers

A:
How does one control the build/link sequence in Cabal?

You can use Build-Type: Custom in your cabal file and control everything with a custom Setup.hs.
Have a look at the UserHooks data type for all of the phases of cabal which you can control.
Some examples:

*

*SDL - uses autoconfUserHooks to have cabal run a configure script

*this SO answer contains links to packages which override the confHook: https://stackoverflow.com/a/32679607/866915

*See this paste for links to more custom Setup.hs files: http://lpaste.net/142696

Are relative paths supported in Cabal? couldn't find this mentioned in the guide and bash-like ~ doesn't work

If your library is external to your cabal package, I would consider using pkg-config on Unix/Linux systems to have cabal locate the library. See the answers to this SO question: How to specify dependency on external C library in .cabal?
If your library is part of your cabal package, check out this blog post and related github repo which shows how to write a custom Setup.hs file to build and install the library in the right place for cabal:

*

*Haskell and external C++ library - the easy way

*https://github.com/jakubfijalkowski/haskell-and-cpp


text:
Q: Sorting update history in MySQL table Basically, I am keeping a record of update history for my software in a MySQL table. When I output this data, I want the data to be sorted by the software version in descending order i.e. the newest version update information is outputted first.
I am using the following query:
SELECT * FROM updates WHERE productId='$productId' ORDER BY version DESC

on the following test data:
1.0.0
0.9.8
2.4.2
1.7.0
1.7.1
17.2.1

The output is:
2.4.2
17.2.1
1.7.1
1.7.0
1.0.0
0.9.8

Because of the 2 'decimal points' in the data, I can't store it in the table as double, float etc. so is stored as varchar.
I tried putting ORDER BY version+0 DESC in the query, which does move the 17.2.1 to the top of the list, but moves the 1.7.0 above the 1.7.1 because the casting breaks when it reaches the second decimal point, so is just outputting the data in the order of the table.
Any suggestions on how to sort the data so that it would come out as:
17.2.1
2.4.2
1.7.1
1.7.0
1.0.0
0.9.8

Cheers!

A: select * from Table1
order by CAST(version  AS DECIMAL) DESC;

fiddle

A: SELECT * FROM Table1 ORDER BY inet_aton(version);

A: SELECT VERSION,
CAST(SUBSTRING_INDEX(VERSION,'.',1) AS UNSIGNED) v1,
CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(VERSION,'.',2),'.',-1) AS UNSIGNED) v2,
CAST(SUBSTRING_INDEX(VERSION,'.',-1) AS UNSIGNED) v3
FROM UPDATES
ORDER BY v1 DESC, v2 DESC, v3 DESC

A: This will work
select * from Table1
order by CAST(SUBSTRING_INDEX(version, '.', 1) as DECIMAL) DESC,
CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(version, '.', 2), '.', -1) as DECIMAL DESC,
CAST(SUBSTRING_INDEX(version, '.', -1) as DECIMAL) DESC;

Check Fiddle

A: Not ORDER BY version but:
extract number until full stop and order by first number, second and third
like this:
ORDER BY firstVersionNumber, secondVersionNumber, thirdVersionNumber.

To extract number use string function


text:
Q: Is it best practice to use Vue component in blade template? I'm using multiple Vue components in Laravel blade template like below

        <user-list></user-list>
        <first-component></first-component>
        <seconde-component>

{{ $name }}

{{ $bio }}

        </seconde-component>

I want to know if it's best practice to use Vue like this or not?  If
not, what is best practice for using Vue components in Laravel?

A: Laravel has VueJS support right out of the box. You can you use any front-end library like AngularJS or ReactJS too inside if you Laravel app. According to the Laravel docs there is not a "best practice or method" to using VueJS in Laravel. It it just supported if you choose to use the library.
To help  your Laravel application you can setup a VueJS router for live loading, use ajax to get json from your laravel app without refreshing, est.


text:
Q: If a sequence $(x_n)$ in $\mathbb{R}$ is eventually non-negative and convergent, then the limit of the sequence is non-negative. My attempt at proving "if a sequence is convergent and eventually non-negative, then the limit of that sequence must be non-negative. Does it check out?
Let $(x_n)$ be convergent in R and let $∃m∈\mathbb{N}$ such that $x_n≥0 \ ∀n≥m$. WTS $\lim(x_n)=L≥0$.
Suppose for the sake of contradiction that $lim(x_n )=L<0$.
Then $∀ε_o>0,∃k∈N$ s.t. if $n≥k$ then $|x_n-L|< ε_o$ (1)
Since we know (1) holds for all $ε_o>0$, it must hold for $ε_o= -L$.
Choose $ε_o≔-L$. Suppose $n≥\max\{m,k\}$.
Then it follows from (1) that \begin{aligned}|x_n-L| &< ε_o
\\ L-ε_o <x_n &<L+ε_o  \\ x_n&<L+(-L) \\ x_n&<0
\end{aligned}
But we also have $x_n≥0$ since $n≥max{\{m,k\}}≥m$. $⇒⇐$
Contradiction, therefore, we have $\lim(x_n)≥0$.


text:
Q: Read a collection of dates How to read a number of dates and store them in a array/vector in C++? For examples I have:
6
20 1 2014
25 3 2010
3 12 2001
18 11 2001
19 4 2015
9 7 2005

where 6 is the number of given dates. Each date is separated by a space.
This is my attempt:
std::cout << "Enter the number of dates to enter : ";
int num_dates;
std::cin >> num_dates;

std::vector<std::string> dates;
for ( int i= 0; i < num_dates; i++)
{
  std::cout << "Enter date number " << ii+1 << ": ";
  std::string date;
  getline( std::cin , date);
  dates.push_back(date);}

A: #include <iostream>
#include <list>
// Just create a dates object which should store the dates as in the constructer
// Create a arraylist of type dates to store them.
class dates {

public:

    int day;
    int month;
    int year;

    dates(int day, int month, int year) {
        this->day = day;
        this->month = month;
        this->year = month;
    }

    int setDay(int day) {
        this->day = day;
    }

    int setMonth(int month) {
        this->month = month;
    }

    int setYear(int year) {
        this->year = year;
    }

    int getDay() {
        return day;
    }

    int getMonth() {
        return month;
    }

    int getYear() {
        return year;
    }
};

int main()
{

    std::cout << "Hello World!\n";
    std::list<dates> myDates = {};

    dates newDate = dates(20, 4, 2020);

    myDates.push_back(newDate);

}

A: I believe that you don't want to separate the date to day, month and year, but just save it into array. My solution:
#include <iostream>
#include <string>
#include <vector>

int main()
{
    std::cout << "Enter the number of dates to enter: ";
    int num_dates;
    std::cin >> num_dates;

    std::vector<std::string> dates;
    for (int i = 1; i <= num_dates; i++)
    {
        std::cout << "Enter date number " << i << ": ";
        if (!(i - 1))
            std::cin.get();
        std::string date;
        std::getline(std::cin, date);
        dates.push_back(date);
    }
}

I added std::cin.get() when i = 1.


text:
Q: Switch seaborn x and y axes but compute standard deviation on original orientation I have data in a simple pandas table with two columns: depth and a datum. There are multiple samples per depth. Using seaborn's relplot, I can produce a nice plot of the data using:
import seaborn as sns
sns.relplot(x='depth', y='datum', ci='sd', kind='line', data=myData)

This works as expected. However, it makes a lot more sense for depth to be on the y axis, because that represents the earth more faithfully. If I tell seaborn to swap the axes like this:
sns.relplot(y='depth', x='datum', ci='sd', kind='line', data=myData)

it does not work, of course, because the standard deviation is computed with respect to the x-axis. Is there a way to swap the axes, yet compute and plot the standard deviation with respect to what is now the y-axis?

A: I found a solution. I copied the relevant bits from seaborn's source and altered them.
grouped = myData['myColumn'].groupby(myData['depth'])
est = grouped.agg("mean")
sd = grouped.std()
cis = pd.DataFrame(np.c_[est - sd, est + sd], index=est.index, columns=["low", "high"]).stack()
if cis.notnull().any():
    cis = cis.unstack().reindex(est.index)
else:
    cis = None
x = est.index
y = est
y_ci = cis
x, y = np.asarray(x), np.asarray(y)
low, high = np.asarray(y_ci["low"]), np.asarray(y_ci["high"])
fig = plt.figure(figsize=(8, 8))
ax = fig.gca()
plt.plot(y, x)
plt.fill_betweenx(x, low, high, alpha=0.2)
plt.gca().invert_yaxis()
plt.xlabel('My Column [units]')
plt.ylabel('Depth [m]')

Some of the variables are a bit redundant, but that was to avoid altering seaborn's code and introducing inadvertent bugs.


text:
Q: Do I have to use container or container-fluid in grid system? I know the similar questions already exist on Stackoverflow but I think the exact one doesn't exist.
Most people say
"You should place .row in .container and .col should be wrapped by .row".
But I don't perfectly get it.
I am aware of I should wrap .col with .row
BUT Do I have to wrap .row with .container or .container-fluid?
Is it mandatory?
I think the code below does work well as grid system.

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

      A

      B

      C

      D

A: container and container-fluid provide the necessary horizontal padding (15px) for the negative margins added to row.
If you put row within an element with less-than 15px horizontal padding, it will overflow horizontally.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

      One of three columns

      One of three columns

      One of three columns

      One of three columns

      One of three columns

      One of three columns

      One of three columns

      One of three columns

      One of three columns

A: There is no need of having container or container-fluid as parent of a .row
but as you know .row has -15px margin left and right so you need a parent with 15px padding left and right, If you don't use that your row will be overflown.
but if you have a parent with at least 15px or more padding left and right then you are good to go.


text:
Q: Many stacked ybars side-by-side at the same coordinate I have several ybar stacked plots and I would like to put them together in one plot.
However, since the ybars of the different plots share the same coordinates, when I put them in one plot, they just stack up into a single ybar. However, I would like to have the original stacked ybars be displayed side by side at the given coordinate (just as non-stacked ybars do).
Anybody got an idea how to do that?

A: It is very simple: use two axis environments and shift the bars a bit. If you are very picky, you need to change the unit vector ratio of one of the plots a bit.
\documentclass[tikz,border=3.14mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\begin{document}
\begin{tikzpicture}
    \begin{axis}[
    width=8cm,
    unit vector ratio=1 0.5,
    symbolic x coords={a,b,c,d,e},
    xtick=data,
    ybar stacked,
    ytick pos=left,
    ]
        \addplot[ybar,fill=blue!30,mark=no,bar shift=-3mm] coordinates {
         (a,3.5)
         (b,0.75)
         (c,4.85)
         (d,3.33)
         (e,7)
        };
        \addplot[ybar,fill=orange,mark=no,bar shift=-3mm] coordinates {
         (a,2.5)
         (b,1.75)
         (c,1.85)
         (d,2.33)
         (e,1)
        };
    \end{axis}
    \begin{axis}[ytick=\empty,
    width=8cm,
    unit vector ratio=1 0.5,
    symbolic x coords={a,b,c,d,e},
    xtick=data,
    ybar stacked,
    ytick pos=left,
    ]
        \addplot[ybar,fill=green!30,mark=no,bar shift=3mm] coordinates {
         (a,2.5)
         (b,1.75)
         (c,1.85)
         (d,2.33)
         (e,1)
        };
        \addplot[ybar,fill=red,mark=no,bar shift=3mm] coordinates {
         (a,3.5)
         (b,0.75)
         (c,4.85)
         (d,3.33)
         (e,7)
        };
    \end{axis}
\end{tikzpicture}
\end{document}


text:
Q: Trying to intall GLFW on Linux from Source Original Question:
I am trying to install GLFW from source on Linux.
I have downloaded and extracted the files from www.glfw.org, and according to the documentation on the Code::Blocks website, all I have to do is enter the directory and type 'make'. I installed cmake and the other dependencies specified inside the readme file.
Typing 'make' gives me the error: No targets specified and no makefile found.
I have an approximate idea as to how cmake works, but probably don't understand it fully. I read the target should be 'x11' or 'x11-install', do I tried 'make x11' and 'make x11-install'.
I also tried a few other things which I had as wild guesses as to what might work. (For example 'make x86_64' but the chances of that working... laughable perhaps.)
So yeah, how do I use cmake to install glfw, on Linux, KUbuntu 13.04... 64 bit...
Answer:
I have written a write-up here:
(How to build & install GLFW 3 and use it in a Linux project)


text:
Q: Convert a value with a regex to a real value I have a huge file containing values with a regex in it, like this:
LGP0041_\d{4}\.dta
objd135a_\S{3}.txt

Now I need to convert these to a valid example value, like this:
LGP0041_1234.dta
objd135a_abc.txt

I know of the RegExp object to check if there is a match, but is there also a way to create valid values?

A: A regular grammar can be used to recognize or produce words of its language, but the VBScript regexp engine does not implement producing. So you have to roll your own.
Your sample does not contain contain regular patterns. \S can't mean 'non-whitespace' because you won't like characters illegal in a file name and a representative sample of file names should contain elements with spaces. The fact that the first sample escapes the extension dot and the second one doesn't makes me think that your syntax specs aren't really thought out. If you come up with a (regular) grammar of your inputs, I'm willing to give your problem further thought.
Some code to base the thinking on:
Option Explicit

Function rndInt(lowerbound, upperbound)
  rndInt = Int((upperbound - lowerbound + 1) * Rnd + lowerbound)
End Function

Sub shuffleAD(aX)
' Durstenfeld's Permutation Algorithm
    Dim J, K, Temp
    For J = UBound(aX) To 1 Step -1
        K = Int((J + 1) * Rnd) ' random number 0 - J
        Temp  = aX(J)
        aX(J) = aX(K)
        aX(K) = Temp
    Next
End Sub ' shuffleAD

Class cRGen
  Private m_
  Public Function init(s)
    Set init = Me
    ReDim m_(Len(s) - 1)
    Dim i
    For i = 0 To UBound(m_)
        m_(i) = Mid(s, i + 1, 1)
    Next
  End Function
  Public Function getNext(mi, ma)
    shuffleAD m_
    getNext = Mid(Join(m_, ""), 1, rndInt(mi, ma))
  End Function
End Class

Dim goRpl : Set goRpl = Nothing
Function magic(m, w, mi, ma, p, src)
  If IsEmpty(ma) Then ma = mi
  magic = goRpl.m_dicGens(w).getNext(mi, ma)
End Function

Class cRpl
  Private m_fRpl
  Private m_r
  Public  m_dicGens
  Private Sub Class_Initialize()
    Set m_fRpl    = GetRef("magic")
    Set m_r       = New RegExp
    m_r.Pattern   = "\\(\w){(\d+)(?:,(\d+))?}"
    Set m_dicGens = CreateObject("Scripting.Dictionary")
    Set m_dicGens("d") = New cRGen.init("0123456789")
    Set m_dicGens("S") = New cRGen.init("abcdefghij")
  End Sub
  Public Function rpl(s)
    Set goRpl = me
    rpl = m_r.Replace(s, m_fRpl)
  End Function
End Class

Randomize
Dim aTests : aTests = Array( _
      "LGP0041_\d{4}.dta" _
    , "objd135a_\S{3}.txt" _
    , "x_\S{3,8}.txt" _
)
Dim oRpl : Set oRpl = New cRpl
Dim sTest
For Each sTest In aTests
    WScript.Echo sTest, "=>", oRpl.rpl(sTest)
Next

output:
cscript 28936688.vbs
LGP0041_\d{4}.dta => LGP0041_4317.dta
objd135a_\S{3}.txt => objd135a_cea.txt
x_\S{3,8}.txt => x_jgcfidh.txt

cscript 28936688.vbs
LGP0041_\d{4}.dta => LGP0041_8054.dta
objd135a_\S{3}.txt => objd135a_eci.txt
x_\S{3,8}.txt => x_ahfgd.txt

This should at least identify the needed components:

*

*generators that deliver strings of specific character sets

*a (sorry: global) replace function that maps 'type letters' to generators, handles 'width specs', and build the output

*a regular pattern to parse the specs from your inputs


text:
Q: Chrome bug on button animation I have a small problem on a Wordpress site, I had to make an animation to go from the left to the right for buttons. So I use "linear-gradient", the problem is that, on Chrome ONLY, there are times (not on all buttons (?????)) a small line of color to the right or left of the button (sometimes you only see it when you hover the mouse)
Here is the code of one of the buttons that bug for example on the site :

a {
    text-decoration: none;
    display: inline-block;
    font-size: 12px;
    line-height: 12px;
    color: #FFF;
    font-weight: 400;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    padding: 12px 35px;
        -webkit-transition: all 0.3s ease 0s;
    -o-transition: all 0.3s ease 0s;
    transition: all 0.3s ease 0s;
    background: -webkit-gradient(linear, left top, right top, color-stop(50%, #515050), color-stop(50%, #ddc39f));
    background: -webkit-linear-gradient(left, #515050 50%, #ddc39f 50%);
    background: -o-linear-gradient(left, #515050 50%, #ddc39f 50%);
    background: linear-gradient(to right, #515050 50%, #ddc39f 50%);
    background-size: 200% 100%;
    background-position: left bottom;
}

a:hover {
    background-position: -100% 0;
}
En savoir plus

Here, you can see it don't bug for some reason, but in the website (when I hover it) :
Chrome button bug
So, I tried to do the animation an other way, with pseudo element, like that :

a {
    text-decoration: none;
    color: #ffffff;
    font-size: 13px;
    font-weight: 500;
    background-color: #ddc39f;
    font-family: 'Roboto', sans-serif;
    letter-spacing: 0.5px;
    padding: 8px 20px 8px 11px;
    -webkit-transition: all .3s ease;
    -o-transition: all .3s ease;
    transition: all .3s ease;
    position: relative;
}

a:after {
    content: '';
    position: absolute;
    background: #515050;
    top: 0;
    bottom: 0;
    left: 0;
    right: 100%;
    transition: all 0.3s ease 0s;
    z-index: -1;
}

a:hover {
    background: transparent;
}

a:hover:after {
  right: 0;
}
En savoir plus

But the problem of this animation is that the background must pass transparent, otherwise the animation (the pseudo element) cannot be shown.
So I ask you if possible, is there a way to debug the first solution, the one that only bugs on chrome or is there a way to reproduce exactly the same effect as the first one with pseudo element? Knowing that I can't add text in the  because I'm on a WordPress and that would complicate everything for not much.
Thanks for your help

A: For those who one day have the same problem. Apparently the problem is with the display, try putting :
display: inline-table;

and it should do the trick.


text:
Q: Avoid previous ajax request on calling the same ajax request again in jquery I want to avoid previous ajax request on calling the same ajax request again in jquery
<input type="text" id="username" onkeyup = "userName(this)" >

function userName(e) {
    $.ajax({
        type:"POST",
        url:BasePath + "/users/userName",
        data:"name=" + $.trim($(e).val()),
        success:function (resp) {
        if (resp == 1) {
            $('#div.error_message').html('Username already taken...').show();
        } else {
            $('#div.error_message').hide();
        }
        }
    });
}

A: You can use .abort()
<input type="text" id="username" onkeyup = "userName(this)" >

<script>var xhr=null;
function userName(e) {
     if(xhr)xhr.abort();//first time it will not be aborted
     xhr=$.post(BasePath + "/users/userName",{"name": $.trim($(e).val())},function (resp) {
        if (resp == 1) {
            $('#div.error_message').html('Username already taken...').show();
        } else {
            $('#div.error_message').hide();
        }
        });
}</script>

Use $.post in place of $.ajax as it is simplified and short form of $.ajax

A: var ajaxReq;
function userName(e) {

    if(ajaxReq){
       ajaxReq.abort();
       //OR you may return from here as
       //another request is already in progress
    }

    ajaxReq = $.ajax({
        type:"POST",
        url:BasePath + "/users/userName",
        data:"name=" + $.trim($(e).val()),
        success:function (resp) {
            if (resp == 1) {
               $('#div.error_message').html('Username already taken...').show();
           } else {
               $('#div.error_message').hide();
          }
          ajaxReq=null;
        }
    });
}


text:
Q: Show per category metrics in Tensorboard I am training an object detection model using tensorflow object detection api. The eval config is like this:

eval_config: {
  num_examples: 8000
  max_evals: 10
  num_visualizations: 20
  include_metrics_per_category: true
}

However, tensorboard doesn't show any per category metrics.
Is there anything else I need to do?

A: The following steps helped me to display the metrics per category successfully (tested on faster_rccn and mobilenet):
1. install updated pycocotools from my git repo:

pip install
  "git+https://github.com/philippschw/cocoapi.git#egg=pycocotools&subdirectory=PythonAPI"

2. Edit this file in the tensorflow api:

"tensorflow/models/research/object_detetcion/metrics/coco_tools.py":from
  line 240 to line 244

add the following lines of code:
# add for metrics per catergory from here
if include_metrics_per_category is True:
    self.summarize_per_category()
# add for metrics per category end here

3.Edit the config file for Tensorflow API to include:

{
      metrics_set: "coco_detection_metrics"
      include_metrics_per_category: true  }

For example:
eval_config: {
  num_examples: 8000
  # Note: The below line limits the evaluation process to 10 evaluations.
  # Remove the below line to evaluate indefinitely.
  max_evals: 10
  num_visualizations: 20
  metrics_set: "coco_detection_metrics"
  include_metrics_per_category: true
}

Note, an issue for this has already been opened on tensorflow and my solution for now is taken from  there.

A: Ah I think the pycocotools from github doesn't support this feature. We had this implemented inside of Google, but it's not available outside.

A: As @zhichau Lu already said, for some reason this feature does not exist outside of google. I was able to get it to work by making the code changes proposed by this Github answer.
Here is a pic of my results in Tensorboard:


text:
Q: Map generation - Rain, Wind, and Weather I am making a world generator that will generate terrain using perlin noise and a weighted gradient favoring pangea shaped islands to form. I have gotten to the point where I can create a temperature map of the world where lower altitudes closer to the equator are favored, and water is always colder. But I am having trouble approaching the best way to deal with wind and rain. I figure that I can maybe create a humidity map then somehow play it into wind. This video is where most of my inspiration is coming from. Elsewhere he briefly talked about how whenever wind would hit a mountain, the area behind it would be left with no rain. One big question I have about his wind is how does he decide what direction it comes from.
So basically what I am asking is how can I extend off my world generator to simulate wind, rain and weather? Since rain and weather are arguably the same thing, another question that comes up is how can I generate a humidity map based on a world? Once a simulation starts, how does one deal with weather?
Here is a picture of my tempurature map. I am thinking of making it less continuous.

A: I'm the author of the video you link to in your question.
I'm sorry that I didn't reply to this when you asked three months ago but I've only just seen your message on Reddit. Your account seems to have been deleted so I'm copying my reply here.
In terms of wind direction, this was only a simple model so I cheated and picked an angle randomly. A simulation that "evolves" with changing wind and weather is something I'm working on but the biggest problem is making it fast enough to use.
For wind and rain, what I did was simulate a square of particles, all one pixel apart and implemented as an array of floats for wind elevation and an array of floats for wind moisture. The wind moisture at the start is set quite high to represent the fact that it is moist air carried over the sea.
I then move the cloud along the wind direction over the map. When the elevation (height) of the map is greater than the wind height, then the wind height is moved up to this elevation. Otherwise, the height of the wind decreases slowly. This simple model can be used as a very simple approximation of air pressure when the elevation of the world is much less than the elevation of the wind. My video colours the raw wind elevation blue but you could colour the difference between wine elevation and land elevation instead for a more interesting effect.
Each point in the cloud loses some moisture at each step depending on temperature (cold areas losing more rain i.e. particularly over mountains). Once it has lost all of its moisture it is out of rain, so a "rain shadow" develops, represented by a desert if the temperature is hot. You could improve this model by having wind gain more moisture over lakes or sea.
Finding the best constants for how quickly wind particles lose moisture, or how much moisture they have initially, was just trial and error until I found a combination that looked good and gave me a full range of terrain types on a typical map.
Hope that helps -- good luck with your project! Let me know how you get on.

A: Wind is caused by differences in air pressure. I.e. some air will move from a high pressure areas into a neighboring low pressure area to even it out.
The air pressure at a location is influenced by several factors like air temperature, ground temperature, cloudiness, amount of sunshine, air humidity, etc.
Also multiple layers of atmosphere need to be taken into account.
It is quite complex but at the very least, you will need to simulate air pressure.
EDIT: As an introduction into this matter I suggest: https://en.wikipedia.org/wiki/Numerical_weather_prediction


text:
Q: how to set maxHeight on a TextInputLayout I don't want to limit the number of lines, I want to limit the TextInputLayout maximum height such that if it's too long it becomes vertically scrolling.
I'm fine with in code solutions.
currently maxHeight attribute has no effect either on TextInputLayout or EditText.
Here is my layout
<com.google.android.material.textfield.TextInputLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:hint="@string/address"
    android:paddingTop="@dimen/margin_8"
    android:paddingBottom="@dimen/margin_8">

    <com.mamamia.mamamiarestaurant.ui.MultiLineTextInputEditText
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:imeOptions="actionNext"
        android:inputType="text|textPostalAddress|textMultiLine"
        android:maxLength="@integer/address_max_length" />
</com.google.android.material.textfield.TextInputLayout>

And I include it in a constraint layout
<include
    android:id="@+id/text_input_layout_address"
    layout="@layout/view_text_input_layout_address"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    app:layout_constrainedHeight="true"
    app:layout_constraintHeight_max="200dp" />

layout_constraintHeight_max has no effect. but layout_constrainedHeight if set to true will make the layout fixed height (not the one specified by layout_constraintHeight_max but the fixed default edit text height)

A: layout_constraintHeight_max does not work if the view does not have top or bottom constraints, so you can either put android:maxHeight on the InputEditText, or adjust the constraints on TextInputLayout:
<include
        layout="@layout/view_text_input_layout_address"
        android:id="@+id/text_input_layout_address"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHeight_default="wrap"
        app:layout_constraintHeight_max="200dp" />

You probably only need app:layout_constraintHeight_default="wrap" if the parent has a height of match_parent.


text:
Q: Python Priority Queue with objects heappush does not support '>' between objects In my attempt to implement a simple version of A* Search, I am trying to enqueue the following in a priority queue:

*

*Priority: sum of heuristic value and cost from source to current element

*Queue Node: Object of class queue node with data members point and cost
The code goes something like this:
'''s = queueNode(start, 0)
q.put((s.dist + heuristics[s.pt[0]][s.pt[1]],s))  # Enqueue source cell'''

However, it gives the following error:
in _put
heappush(self.queue, item)
TypeError: '<' not supported between instances of 'queueNode' and 'queueNode'
Here is the code for class Queue Node
class queueNode:
    def __init__(self, pt, dist: int):
        self.pt = pt  # The cordinates of the cell
        self.dist = dist  # Cell's distance from the source

update:
I tried to make the classes comparable by these two Implementations
First
class queueNode:
def __init__(self, pt, dist):
    self.pt = pt  # The cordinates of the cell
    self.dist = dist  # Cell's distance from the source

def __it__(self,other):
    return self.dist < other.dist

Second
class queueNode:
def __init__(self, pt, dist):
    self.pt = pt  # The cordinates of the cell
    self.dist = dist  # Cell's distance from the source

def __it__(self,other):
    return id(self) < id(other)

it still gives the same error
Update:
A workaround to this is to use a list object instead of priority queue and sort it everytime you enter a new element.
CODE
q=[]
APPENDING
q.append((heuristics[i][j],queueNodeObject))
SORTING ON BASIS OF COST
def sort(q):
    #start stop step
    for i in range(0,q.__len__(),1):
        for j in range(i+1,q.__len__()-1,1):
            if q[i][0]<q[j][0]:
#q[i] returns the element in queue list i.e tuple=(cost, object) q[i][0] returns #the cost
                temp=q[i]
                q[i]=q[j]
                q[j]=temp


text:
Q: Using tie/knot as a verb in a sentence Tie (verb):
to fasten together two ends of a piece of string or other long, thin material, or to (cause to) hold together with a long, thin piece of string, material, etc.
Example:
- Could you tie this piece of string for me?
Knot (verb):
 to tie in or with a knot:
Example:
- He caught the rope and knotted it around a post.
Based on these definitions, what word as a verb can be used in a figurative sense in the following sentence:

Language and culture are inseparably .............. to each other.

Connotation: "culture" and "language" are severely related to each other and each one has considerable influence into the other one.
I think, "tie" is a better choice and I can say:

Language and culture are inseparably tied to each other.

But I don't know if a native would use this word in this sense. Meanwhile, I need to know whether "knot" can be used in this sense too.

A:
Language and culture are inseparably tied to each other.

I would use this sentence, but I agree with Edward Barnard that "connected" could be used instead. Remember that even in the purely physical realm, one can speak of two beams being tied together by bots or by crossbars. When used metaphorically, "tie" does primarily mean "connect". Even where the image is of joining two cords with a knot (as in "tie the knot" as an idiom for "get married") the emphasis is on the connection, not the method of making it.
I would not recast the example sentence to use "knot" as a verb. "Knot" tends to suggest complication and often confusion, as in "knotted hair", "a knotty problem" and those are not the image wanted here.
One might use "intertwined" to suggest separate strands that have joined into a single thing, particularly "inextricably intertwined".

A: Language and culture are inseparably .............. to each other.
= tied [as with have a bond or tie" but not as in **tie a knot]
= bound [as in bind, bound, bound, meaning going together or connected to each
  other]
= connected
= related
= joined
To have strong ties to a community.
To be closely tied to a community.
To have close bonds (ties) to the community.
To have bonds and ties to something does not actually imply knotting.
This works in all major varieties of English.


text:
Q: Koltin multiplatform Javascript IR build creates empty module I have added the JS target for our Kotlin Multi platform project.  The project is named STT.
  js(IR) {
        binaries.executable()
        browser {
            commonWebpackConfig {
                cssSupport.enabled = true
            }
            webpackTask {
                output.libraryTarget = "umd"
            }
        }
    }

When I look at the build folder or when I run the JS task jsRun the JS lib looks empty.
Here is for example the stt.js from the build folder
(function (root, factory) {
  if (typeof define === 'function' && define.amd)
    define(['exports'], factory);
  else if (typeof exports === 'object')
    factory(module.exports);
  else
    root.stt = factory(typeof sttalg === 'undefined' ? {} : stt);
}(this, function (_) {
  'use strict';
  return _;
}));

That essentially is an empty object
However, when I use the BOTH or Legacy that file looks ok
js(LEGACY) {
        binaries.executable()
        browser {
            commonWebpackConfig {
                cssSupport.enabled = true
            }
            webpackTask {
                output.libraryTarget = "umd"
            }
        }
    }

What am I missing ?

A: The IR backend doesn't export any code to js by default. You need to add @JsExport to the declarations you want accessible. See https://kotlinlang.org/docs/js-to-kotlin-interop.html#jsexport-annotation


text:
Q: Play framework weblogic 10.3.3.0 deployment I built a Play app and tried to deploy on weblogic using the following commands:
play war -o myApp myApp

Later I just deployed the exploded war directory to weblogic, everything worked fine but everytime I try to access a route. I get the following error:
Not found

GET /myApp/params

This is a rest service not an application with UI's. I tried to deploy on tomcat and everything worked fine but I had to make the application context root to be /. I tried the same thing with weblogic but it did not work.
Here is my route file:
GET     /                                        Application.index

GET  /sectorinformer/{telephone}  Application.show

GET     /sectorinformer/public/                     staticDir:public

*       /{controller}/{action}                  {controller}.{action}

And here is my controller code:
package controllers;

import models.InstalAddress;
import models.SectorInfo;
import play.Logger;
import play.mvc.Controller;

public class Application extends Controller {

    public static void index() {
       render();
}

public static void show(String telephone) {
    Logger.debug("Starting request");
    Logger.debug("domain: '%s'", request.domain);
    String instalAddressId = InstalAddress.getInstalAddressId(telephone);
    SectorInfo si = new SectorInfo();
    si.initializeSectorInfo(instalAddressId);
    renderXml(si.generateXmlResponse());
}

}

Thanks in advance for any help.

A: Weblogic 10 is a fully compliant J2EE 5 application server, as a consequence it is bundled with JPA 1.0.
There are two little issues to get Play running on weblogic.

*

*Applying an Oracle patch to have weblogic support JPA 2.0

*Adding a deployment descriptor property to prioritize class resolution from web-inf

Both are trivial and the Play documentation should probably mark weblogic 10 as a working deployment target.
To fix #1, open to following oracle link.
For the lazy readers, add this declaration at the top of wlserver/common/bin/commEnv.sh
export PRE_CLASSPATH=$MW_HOME/modules/javax.persistence_1.0.0.0_2-0-0.jar:$MW_HOME/modules/com.oracle.jpa2support_1.0.0.0_2-0.jar

for windows, the file is wlserver/common/bin/commEnv.bat
set PRE_CLASSPATH=%MW_HOME%/modules/javax.persistence_1.0.0.0_2-0-0.jar;%MW_HOME%/modules/com.oracle.jpa2support_1.0.0.0_2-0.jar

To fix #2, create the file weblogic.xml at the following location myplayapp/war/WEB-INF/weblogic.xml
<?xml version="1.0" encoding="UTF-8"?>
<weblogic-web-app>
    <container-descriptor>
            <prefer-web-inf-classes>true</prefer-web-inf-classes>
    </container-descriptor>
</weblogic-web-app>

The war folder is automatically picked up by play war when the web archive is built.
That's it!
I personally believe Play should create weblogic.xml itself, but that's not how it works as of 1.2.1

A: Unfortunately I don't have either weblogic know nor time to investigate in you interesting problem. I can only can give you some hints what I would do:
Try to connect the app with a debugger or if this doesn't work checkout the Code and build your own version, with a lot of log-statements.
As far as I know every request will handled by ActionInvoker. invoke. Look how the argument comes in. The other point is the Router, which has still a lot of trace-logs. So perhaps you start first and let the whole stuff run on trace-level. Perhaps that give you some hint's where to look in more detail.
To do this start with a clean app and make no configuration tricks, specially don't run it in ROOT-Context. Just create play war myapp -o myapp.war --zip and deploy it (Don't forget --zip). Then analyze the log.
Good look.
Niels

A: I deployed my Play app (play 1.1.1) to Websphere 6.1 and I encountered some issues. Not sure you have the same issues but here there are (hope it can help you):
1- JDK version: My "play war xxxx --zip" use a JDK 1.6, and Websphere 6.1 uses a JDK 1.5. When I tried to launch my webapp an UnsupportedClassVersionException was thrown. I regenerated my war file using the correct JDK et voilà !
2- When you deploy a war aplication to Websphere, you can specify the context's name. I don't know how to do it with Weblogic, but did you set the correct value ?
As Niels said, analyze logs files: you should find what happens !

A: Unfortunately, Play! doesn't support Weblogic.
See: http://www.playframework.org/documentation/1.2/deployment


text:
Q: Detecting normal minus and numpad minus in JavaScript onKeyDown In JavaScript's event onKeyDown, is there anyway to differentiate a minus sign pressed in the "normal" keyboard area from one pressed in the numpad? I think they generate the same which code (at least in FireFox).
I'm trying to map an standard qwerty layout to a different keyboard mapping in a text area as a user types in, and want to ignore anything on the numeric pad.
Let me know if I'm unclear.

A: I doubt you'll be able to do it reliably cross-browser. There's an excellent writeup of keyboard events and the codes generated on various browsers on this page. I think it's getting pretty dated now, though.


text:
Q: Cannot read property of 'fn' of undefined? Getting these error codes on my github pages. I have these as my order of loading scripts:
<script src="../../node_modules/jquery/dist/jquery.js"></script>
<script src="../../js/bootstrap.min.js"></script>
<script src="../../js/index.js"></script>

Here are the error messages:
GET https://tmolano.github.io/CareerMod4/node_modules/jquery/dist/jquery.js 404 ()
index.html:115 GET https://tmolano.github.io/CareerMod4/node_modules/popper.js/dist/popper.min.js 404 ()
util.js:56 Uncaught TypeError: Cannot read property 'fn' of undefined
    at util.js:56
    at util.js:10
    at bootstrap.min.js:6
    at bootstrap.min.js:6
(anonymous) @ util.js:56
(anonymous) @ util.js:10
(anonymous) @ bootstrap.min.js:6
(anonymous) @ bootstrap.min.js:6

Heres my page: https://tmolano.github.io/CareerMod4/
Other than the order of loading, what else could be causing this?

A: Possible reasons for this error:

Uncaught TypeError: Cannot read property 'fn' of undefined

*

*invalid reference to the file addresses or missing files (Your case).

*Duplicate reference to the Jquery.

*Overriding $ sign of Jquery in 3rd party libraries.

*Using Jquery functions before inserting Jquery (Not your case).

*Using deprecated syntax for load,error,unload on WINDOW element in jquery without on


text:
Q: Listen to Postgresql Notify channel in FastApi I am currently having a small backend using FastApi and PostgresQl. I want to add some realtime chat capabilities. I use sqlalchemy for the database interactions. I read up on Postgres Notify and Listen and it seems like exactly what I need.
But I am struggling to implement it in my application. Do you know how to listen to Postgres channels, preferably using sqlachemy and utilizing FastApi's async capabilities?
I tried to find a sqlachemy function that implements the desired behavior and I couldn't find one. I found an example with psycopg2 but I don't know how to implement it in a non blocking async manner.
Any help will be much appreciated :)


text:
Q: conflict with foreign key constraint when inserting data These are my tables and they got created but when I am inserting data in AMI tables it gives me foreign key conflict error. I understand that the before inserting into child table , parent should have that value. Here my AMI table is dependent on both household_income and location and both has data. So why I am getting the error:
Insert into AMI values('CONTROL','ZIP','PER','L30','L50','L80');

Msg 547, Level 16, State 0, Line 1 The INSERT statement conflicted with the >FOREIGN KEY constraint "FK__AMI__7908F585". The conflict occurred in database >"mydatabase_old", table "dbo.household_income".
  The statement has been terminated.

create table admin
(control   varchar(15),
status     varchar(3),
weight     float(24),
metro3     varchar(3),
PRIMARY KEY (control)
);

create table AMI
(control varchar(15),
zip    varchar(8),
per     VARCHAR(15),
L30         int,
L50         int,
L80         int,
PRIMARY KEY(zip, per),
foreign key (zip, control) references location on delete cascade,
foreign key (per, control) references household_income ON UPDATE NO ACTION
);

create table location
(region varchar(5),
control   varchar(15),
zip    varchar(8),
PRIMARY KEY(zip, control),
foreign key (control) references admin on delete cascade
);

create table household_income
(control   varchar(15),
age1    int,
per    varchar(15),
ownrent     varchar(3),
totalsal    float(24),
zinc2       float(24),
type        varchar(15),
PRIMARY KEY(control, per),
foreign key (control) references admin on delete cascade,
foreign key (type, control) references structure ON UPDATE NO ACTION,
);

A: First you need to insert into location table
and then into household_income
and then do your insert
Insert into AMI values('CONTROL','ZIP','PER','L30','L50','L80');


text:
Q: passing arguments to the bind() function i have this programm which should only bind a socket to a port and i always get

failure while binding.

I can compile it without a problem.
should i add something to the servAddr?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Practical.h"

int main(int argc , char* argv[]){

    if(argc!=2){
        printf("Parameters : <server Port>");
    }

    in_port_t servPort=atoi(argv[1]);

    int servSock;
    if(servSock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)<0){
        printf("error socket");
    }

    struct sockaddr_in servAddr;
    memset(&servAddr,0,sizeof(servAddr));
    servAddr.sin_family=AF_INET;
    servAddr.sin_addr.s_addr=htonl(INADDR_ANY);
    servAddr.sin_port=htons(servPort);

    if(bind(servSock,(struct sockaddr*) &servAddr,sizeof(servAddr)) < 0){
        printf("failure while binding");
    }
}

A: = has priority lower than <, add extra braces:
if((servSock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))<0){
  printf("error socket");}

Without these braces servSock is 1 or 0, that is definitely not what you want. Also note that without priviledges you can not bind to ports lower that 1024.


text:
Q: Redirect dynamic url to home page I want to redirect dynamic URL to homepage, URL has 4 parameters

http://example.com/abc.php?slug=Adjective&getId=2&sub_id=1&inner_id=67

A: To redirect the dynamic URL to homepage , you can use the following rule,
 RewriteEngine on

RewriteCond ℅{THE_REQUEST} /abc.php\?slug=Adjective&getId=2&sub_id=1&inner_id=67\s [NC]
 RewriteRule ^ /? [L,R]

This will redirect http://abc.php?slug=Adjective&getId=2&sub_id=1&inner_id=67 to http://example.com/ .
Do not remove the question mark ? from the Rewrite destination as this discards the old querystring.


text:
Q: Dynamically find last cell with text in every row I need to add a feature to a macro I created and I am having some trouble doing so.  This is my first post on here!  My macro is a SLA report for tickets.  The last columns (furthest to the right in the spreadsheet) have repeating headers of ACTION TYPE, and ACTION DATE as seen below:
ACTION DATE | ACTION TYPE | ACTION DATE | ACTION TYPE | ACTION DATE | ACTION TYPE

This is where it becomes dynamic because for every row, there is a unique # of columns which is dependent on the number of Action's performed.
Below would be a simple example where 3 actions occur with a ticket, ie: 1. Submit from requester, 2. Comment, and 3. Close of ticket -- Note: This is 6 columns because before every ACTION TYPE column there is the corresponding ACTION DATE showing when the action occurred:
7/14/2015 6:21:19 PM | Submitted | 7/15/2015 9:35 | Commented | 7/15/2015 9:17 | Approved/Closed

WHAT I NEED VBA TO DO for this portion is to find when every ticket was closed.  This would be the last populated ACTION DATE cell in every row, assuming the ticket was closed.  This could be done a number of different ways, but I was thinking to find the last cell that contains data (furthest to right) in every row (this would always be the ACTION TYPE column).  Once this is found, verify that the value has "Approved/Closed" in it (not all tickets are closed), and THEN offset one column to the left to copy the closed time. (paste into a new column, say column A for example).
If the ticket is still open, there will not be an "Approved/Closed" action type as the last used cell in the row..I cant simply just go to the last cell in a row with data and assume that it is closed.
Is this possible to do?  Is there a better way?
The # of rows and columns is always changing (typically around 100 columns and 6000 rows.  The Action Date and Action Type columns usually account for the last 60-70 columns in the report.

A: Entered in (eg) A3 this will pick up the "closed" date provided the last populated column in the row is "Approved/Closed"
=IF(INDEX(3:3,1,MAX((LEN(B3:KZ3)>0)*COLUMN(B3:KZ3)))="Approved/Closed",
    INDEX(3:3,1,MAX((LEN(B3:KZ3)>0)*COLUMN(B3:KZ3))-1),"")

An array formula, so use Ctrl+Shift+Enter when entering it.

A: If you want it in VBA You could do something like this
Dim rw As Range
For Each rw In Range(Range("A1"), Range("A1").End(xlDown)).Cells
    If rw.End(xlToRight).Value = "Approved/Closed" Then
        MsgBox rw.End(xlToRight).Offset(, -1).Value 'put the value anywhere you want.
    End If
Next

It will loop through all the rows and check if the last column is equal to "Approved/Closed".  Then you can do what ever wanted with the offset value.
This only works if there are no blank cells in the table.