text:
Q: Deserializar um Objeto de Outro Estou tentando deserializar três classes DTOS para exportar para um arquivo JSON, consegui fazer boa parte do processo mas quando tento exportar uma classe dentro de outra não consigo.
segue os seguinte cenarios:
public class TakeOffPoliciesDto {

private List<ExportTakeOffDto> exportTakeOffDto;

public List<ExportTakeOffDto> getExportTakeOffDto() {
    return exportTakeOffDto;
}

public void setExportTakeOffDto(List<ExportTakeOffDto> exportTakeOffDto) {
    this.exportTakeOffDto = exportTakeOffDto;
}

public class ExportTakeOffDto {

private List<FamilyTypeDto> familyTypeDtos;
private List<AirportPolicieDto> airportPolicieDtos;

public List<FamilyTypeDto> getFamilyTypeDtos() {
    return familyTypeDtos;
}

public void setFamilyTypeDtos(List<FamilyTypeDto> familyTypeDtos) {
    this.familyTypeDtos = familyTypeDtos;
}

public List<AirportPolicieDto> getAirportPolicieDtos() {
    return airportPolicieDtos;
}

public void setAirportPolicieDtos(List<AirportPolicieDto> airportPolicieDtos) {
    this.airportPolicieDtos = airportPolicieDtos;
}

private void exportToJSonFile() {

    ObjectMapper objectMapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);

    TakeOffPoliciesDto takeOffPoliciesDto = new TakeOffPoliciesDto();

    takeOffPoliciesDto.setExportTakeOffDto(Arrays.asList("1111", "9998887654", "1234567890"));

    ExportTakeOffDto exportDto = new ExportTakeOffDto();

    exportDto.setFamilyTypeDtos( Arrays.asList("8095185442", "9998887654", "1234567890"));
    exportDto.setAirportPolicieDtos( Arrays.asList("8095185442", "9998887654", "1234567890"));

    try {
    objectMapper.writeValue(new File(file.getAbsolutePath(), "teste.json"), takeOffPoliciesDto);

    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

A: Consegui usando o ModelMapper uma biblioteca que copia os dados dos meus models e transfere para os DTOS, ficou assim :
     private void exportToJSonFile() {

      ObjectMapper objectMapper = new
     ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);

    ExportAllDTo exportAllDTo = new ExportAllDTo();

    List<FamilyPoliciesEntity> familyPoliciesEntities =
    familyPoliciesService.findAll();
    List<FamilyPolicieDto> familyPoliciesDtoList = new ArrayList<>();

    ModelMapper mapper = new ModelMapper();
  for (FamilyPoliciesEntity familyPoliciesEntity : familyPoliciesEntities) {

        try {

            FamilyPolicieDto familyPoliciesDto = mapper.map(familyPoliciesEntity,
            FamilyPolicieDto.class);

            TakeoffConfigurationEntity takeoffConfigurationEntity =
           takeoffConfigurationService
                    .recoverByPolicy(familyPoliciesEntity);

    try {

        exportAllDTo.setTakeoff(familyPoliciesDtoList);
        objectMapper.writeValue(new File(file.getAbsolutePath(), "teste.json"),
        exportAllDTo);
        String jsonString = objectMapper.writeValueAsString(exportAllDTo);


text:
Q: Resolution troubles after upgrading to Ubuntu 17.10, xrandr will not add resolution I upgraded last weekend, and my monitor (since long having run fine on 2560x1080_60.00) couldn´t get any higher 1920x1080. I tried adding a new resolution using xrandr but failed every time again.
A work around was returning to another kernel. Grub has available:
Found linux image: /boot/vmlinuz-4.13.0-16-generic
Found initrd image: /boot/initrd.img-4.13.0-16-generic
Found linux image: /boot/vmlinuz-4.10.0-37-generic
Found initrd image: /boot/initrd.img-4.10.0-37-generic
Found linux image: /boot/vmlinuz-4.4.0-97-generic
Found initrd image: /boot/initrd.img-4.4.0-97-generic

And returning to linux image: /boot/vmlinuz-4.4.0-97-generic helped me to get the higher resolution back into the settings menu.
With the newer kernel, it returned errors when trying to add modeline using xrandr.
I saw multiple questions on this, none of them (other than switching back to an older kernel) helped solve the problem.
Thanks and regards,
Bill

redpajama_set_name: RedPajamaStackExchange


text:
Q: Parallel ForEach with SQL inserts c# I have an object like the below but with a huge amount of data, we observed that it takes a long to be inserted into our SQL database as we were using normal foreach, the main idea is to insert each Department and get the generated identity number, then insert the nested employees assigned with that department ID.
<Sample>
    <Departments>
        <Department>
            <Name>HR</Name>
            <Employees>
                <Employee>
                    <Name>Marco</Name>
                </Employee>
                <Employee>
                    <Name>John</Name>
                </Employee>
                <Employee>
                    <Name>Sarah</Name>
                </Employee>
            </Employees>
        </Department>
        <Department>
            <Name>IT</Name>
            <Employees>
                <Employee>
                    <Name>Ali</Name>
                </Employee>
                <Employee>
                    <Name>Roberto</Name>
                </Employee>
                <Employee>
                    <Name>Franco</Name>
                </Employee>
            </Employees>
        </Department>
    </Departments>
</Sample>

We tried to use Parallel.ForEach to enhance the performance, and it does, but we got another issue with @@IDENTITY because there is an overlap between the running tasks in Parallel.ForEach as we found an employee is assigned to another department.
The need ... I need to speed the process up either I use Parallel.ForEach or foreach ... any ideas?
BTW ... we are calling a stored procedures which contains normal INSERT INTO command using classing ADO.NET

A: You could use guid as primary key into your table. It would help you to avoid problem with @@IDENTITY.
At first you should generate new guid-identity, thank insert the generated value into a  row


text:
Q: Why isn't my canvas working with 2 particles? I have a codepen: http://goo.gl/jatUZC and I want to combine 2 particle effects onto one webpage. Only one particle canvas is showing.

A: The issue seems to be one overlays the other. I can see that you set confetti's z-index to be behind the other one.
Mistake! That other one seems to have a black background which will cover everything else.
Meanwhile if you invert the roles, #confetti's background covers the top one.
What to do? make #confetti z-index 0 and remove background.
Fork: http://codepen.io/anon/pen/VeJeRq


text:
Q: Spring MVC integration with Tiles I am using tiles as a viewResolver with Spring 3 MVC. I have a home page which needs to be invoked for which there wont be any controller. I found the syntax for mapping URLs without the controller for other view resolver. How can i achieve this with the tiles view resolver?

A: What i understand you want to serve a page as static source(without interact controller) if so this process doesnt change with view resolver you  should use resource mapping tag
<mvc:resources mapping="/resources/**" location="/resources/" />


text:
Q: Getter returning correctly, then changes to null So I'm having an unusual issue where code is detecting the current user with the method getCurrentUser() but when I use it later to check which user borrowed a book it returns null.
I also attempted changing line 3 of borrowBook method to the currentUser variable, and also tried getting the info through usernameTxtField.getText()
public class Controller {
private Book HFJ = new Book("HFJ", "SI & BA","5678",3, 1);

@FXML
private void attemptLogin(ActionEvent event) throws IOException {
    String usernameInput = usernameTxtField.getText();
    String passwordInput = passwordTxtField.getText();
    boolean loginSuccessful = false;

    switch (usernameInput.toLowerCase()) {
        case "user1":
            if (passwordInput.equals("Password1")) {
                System.out.println("Login Successful");
                informationLabel.setText("Login Successful");
                loginSuccessful = true;
                currentUser = usernameInput.toLowerCase();
            }
            break;
        case "user2":
            if (passwordInput.equals("Password2")) {
                System.out.println("Login Successful");
                informationLabel.setText("Login Successful");
                loginSuccessful = true;
                currentUser = usernameInput.toLowerCase();
            }
            break;
        case "user3":
            if (passwordInput.equals("Password3")) {
                System.out.println("Login Successful");
                informationLabel.setText("Login Successful");
                loginSuccessful = true;
                currentUser = usernameInput.toLowerCase();
            }
            break;
        case "user4":
            if (passwordInput.equals("Password4")) {
                System.out.println("Login Successful");
                informationLabel.setText("Login Successful");
                loginSuccessful = true;
                currentUser = usernameInput.toLowerCase();
            }
            break;
        default:
            System.out.println("Incorrect username or Password");
            informationLabel.setText("Incorrect username or Password");
            break;
    }

    if (loginSuccessful == true) {
        Parent home = FXMLLoader.load(getClass().getResource("home.fxml"));
        Scene home_scene = new Scene(home);
        Stage primaryStage = (Stage) ((Node) event.getSource()).getScene().getWindow();
        primaryStage.setScene(home_scene);
        primaryStage.show();
        currentUser = usernameInput.toLowerCase();
        System.out.println(getCurrentUser());
        homeLoginInfoLabel.setText("Login Successful");
    }
}
@FXML private Label HFJQuantity = new Label();
@FXML private Button HFJBorrowBtn = new Button();
@FXML
private void borrowBook(ActionEvent event) throws IOException{
    if(HFJ.getQuantity()>=1){
        HFJ.setQuantity(HFJ.getQuantity() -1);
        System.out.println("Book Borrowed By: " + getCurrentUser());//CONSOLE PRINT
        HFJQuantity.setText("" + HFJ.getQuantity());
        Parent borrowSuccessful = FXMLLoader.load(getClass().getResource("borrowSuccess.fxml"));
        Scene success_scene = new Scene(borrowSuccessful);
        Stage primaryStage = (Stage) ((Node) event.getSource()).getScene().getWindow();
        primaryStage.setScene(success_scene);
        primaryStage.show();
    }else{
        System.out.println("Not enough books");
        HFJBorrowBtn.setDisable(true);
    }

}

private String getCurrentUser() {
    return currentUser;
}

When I run the code and login this is what the console prints:
Login Successful
user1
Book Borrowed By: null

Why isn't it recognising the current user? Any help would be great

A: I think the problem you are having is down to scope. I can't see in this class where you have declared currentUser outside of the switch statement or the if/else. Try initialising currentUser at the top with your other class variable.


text:
Q: Scroll to anchor in Prestashop (Jquery) please can you help me with small function - Im not skilled in JS / Jquery. I need scroll to anchor in Prestashop, all codes are function only in index.php, not at another pages (product page, category page ..)..
So I need rule for this function be active only on index.php page ..but code bellow is not function:(
jQuery(function($) {
    var url = window.location.pathname;
    var string = "index.php";
    if(url.indexOf(string) !== -1) {
       $("a.linkscroll").live('click',function(event){
          event.preventDefault();
          var target_offset = $(this.hash).offset() ? $(this.hash).offset().top : 0;
          var customoffset = 120;
          $('html, body').animate({scrollTop:target_offset - customoffset}, 2000);
        });
    }
    else {
       echo "nothing there?"
    }
    }(jQuery));

Please, can you help me? (in menu a links I have class a.linkscroll = a href="index.php#some-anchor", so I can use this = another anchors I dont need to be use) ..scroll function I have used only in main page (index.php), anchors have ID (for example a id="some-anchor").
Thank you for your help!

A: Helllo Jiri
In Prestashop, you can find page name and its associate controller in <body> id.
You can pass the $pagename from your controller file, by assigning it to smarty variable.
The code to get a pagename is below:
$pagename = Dispatcher::getInstance()->getController();

You can override your classes/controller/FrontController.php file and inside it find setMedia function.
There you can write your code to add JS for only home page.
$pagename = Dispatcher::getInstance()->getController();
if ($pagename  == 'index') {
$this->addJS(_THEME_JS_DIR_.'custom.js');
}

Add your JS in your theme JS folder and you will see your JS only in homepage.
If you can not find your JS loaded then remove cache/class_index.php file.
After it will be display.

A: Probably the easiest way without any override is to target the index.php page from the tpl files.
You can add it in any file, for example on the footer.
So I'll start targeting the index.php page and it's as easy as.
{if $page_name =='index'}
    <script type="text/javascript">
        $(document).ready(function() {
            $("a.linkscroll").on('click',function(event){
                event.preventDefault();
                var customoffset = 120;
                $('html, body').animate({
                    scrollTop: $($.attr(this, 'href')).offset().top - customoffset,
                }, 2000);
            });
        });
    </scrpt>
{/if}

You can see a live example here: JS Fiddle Example
With that your code should work and only in the home page.


text:
Q: Deriving the formula of a sequence Let $(a,b)\in\mathbb{C^2}$ such that $(a,b)\neq0$
Let $x\in\mathbb{C/\{0\}}$ such that $x^2=ax+b$
Now, $$x^2=ax+b$$
$$\iff x^3= ax^2+bx$$
$$\iff x^3 = a(ax+b)+bx$$
$$\iff x^3 = (a^2+b)x+ab$$
$$\iff x^4 = (a^2+b)x^2 +abx$$
$$\iff x^4 = (a^2+b)(ax+b)+abx$$
$$\iff x^4 = (a^3+2ab)x + a^{2}b + b^2$$
and so on we can go on writing $x^n$; where $n\in\mathbb{N}\space|\space n \geq 3$; as a linear expression in $x$
Is there a way to derive the coefficient of $x$ and the constant term in this linear expression for $x^n$ . If yes, can I get a hint on how to do so?  I can observe that these coefficients and constant terms form a sequence so there must be some general expression for them.
Any hint will be appreciated, Thank You.

A: Let
$$ x^n=a_nx+b_n. $$
and then
$$ x^{n+1}=a_{n+1}x+b_{n+1}=xx^n=x(a_nx+b_n)=a_nx^2+b_nx=a_n(ax+b)+b_nx. $$
So
$$ a_{n+1}=aa_n+b_n, b_{n+1}=ba_n $$
for $n=2,3,\cdots$. Here $a_2=a,b_2=b$.


text:
Q: Titanium: integration of admob module manifest error while trying to integrate admob in my current app, after unzipping the module in my folder, I edited my tiapp.xml and added:
<modules>
    <module version="2.0" platform="android">ti.admob</module>
</modules>

after trying to run the app i got the following error:
Error: String types not allowed (at 'configChanges' with value 'keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize'). [ERROR] Error generating R.java from manifest

any thoughts about how to fix this?

A: try this
change in tiapp.xml
<android xmlns:android="http://schemas.android.com/apk/res/android">
        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
            <tool-api-level>14</tool-api-level>
 </android>
<modules>
        <module platform="android" version="2.0.1">ti.admob</module>
    </modules>

A: well, I found the answer.
Titanium wrote in their Github that this is version 2.0 when actually it's 1.1
changing the XML to

WTH Titanium?!?!?!?!


text:
Q: getDate Function python Having trouble trying to get the date. All the libraries are installed but once I try and run the print(getDate()) function I get a error: NameError: name 'calender' is not defined. The code is below. Any help is greatly appreciated.
now = datetime.datetime.now()
my_date = datetime.datetime.today()
weekday = calender.day_name[my_date.weekday()]
monthNum = now.month
dayNum = now.day

#List of months
month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
'September', 'October', 'November', 'December']

#List of ordinal numbers
ordinalNumbers = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th',
'11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th', '20th', '21st',
'22nd', '23rd', '24th', '25th', '26th', '27th', '28th', '29th', '30th', '31st']

return 'Today is '+weekday+' '+ month_names[monthNum - 1]+' the '+ ordinalNumbers[dayNum -
1]+'. '

A: You only have one misspelling. Import and use calendar instead of calender.

A: it works fine you just have a spelling mistake the module name is calendar not calender


text:
Q: Rails 6 Bulma integration Undefined variable in CSS I want to use Bulma CSS framework in my Rails 6 application and for that I am following this tutorial but there are a few differences in my context:

*

*I want to use bulma-rails gem.

*I don't want to use webpack and thus I have removed webpacker from my application and made related changes such that the application uses the asset pipeline which was the default in Rails versions less than 6.
With that when I access the root page in my application I am facing following error
Started GET "/" for 127.0.0.1 at 2021-08-03 20:24:35 +0530
Processing by WelcomeController#index as HTML
  Rendering layout layouts/application.html.haml
  Rendering welcome/index.html.haml within layouts/application
  Rendered welcome/index.html.haml within layouts/application (Duration: 6.5ms | Allocations: 3376)
  Rendered layout layouts/application.html.haml (Duration: 94.4ms | Allocations: 21476)
Completed 500 Internal Server Error in 108ms (ActiveRecord: 0.0ms | Allocations: 24374)

ActionView::Template::Error (Error: Undefined variable: "$white-bis".
        on line 9:20 of app/assets/stylesheets/_layout.scss
>>   background-color:$white-bis;

   -------------------^
):

app/assets/stylesheets/_layout.scss:9
127.0.0.1 - - [03/Aug/2021:20:24:35 IST] "GET / HTTP/1.1" 500 123078
- -> /

If I comment out the following part
background-color:$white-bis;

from the .header style defined in app/assets/stylesheets/_layout.scss (shown ahead) then the page loads successfully
But I would like to retain that style. Can anybody please help me in identifying the problem and fixing it?
In my understanding the following import in my app/assets/stylesheets/main.scss (shown ahead)
   @import 'bulma';

should import the file app/assets/stylesheets/bulma.sass which is part of bulma-rails gem version 0.9.1 I am using. If that is correct, then that file already has following import in it
@import "sass/utilities/_all"

and the variable I am seeing error about is defined in one of the files imported in turn by the above shown import. Then why I am getting error?
Below I am sharing my code
Gemfile
ruby '3.0.2'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 6.1', '>= 6.1.4'

# Use SCSS for stylesheets
gem 'sass-rails', '~> 6.0'

gem 'bulma-rails', '~> 0.9.1'
gem 'font-awesome-rails', '~> 4.7', '>= 4.7.0.7'

app/assets/stylesheets/_layout.scss
body {
  display:flex;
  flex-direction:column;
  justify-content:space-between;
  height:100vh;
}

.header {
  background-color:$white-bis;
  padding:2rem 1.5rem;
}

.section {
  display:flex;
  flex:1 0 auto;
}

app/assets/stylesheets/main.scss
@import 'font-awesome';
@import 'bulma';
@import '_layout';

app/assets/stylesheets/application.css
/*
 *
 *= require main
 *= require_self
 */

config/initializers/assets.rb
# Be sure to restart your server when you modify this file.

# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = '1.0'

# Add additional assets to the asset load path.
# Rails.application.config.assets.paths << Emoji.images_path

# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in the app/assets
# folder are already added.
Rails.application.config.assets.precompile += %w(  )

app/views/layouts/application.html.haml
- app_name = 'MyApp'

!!!
%html<
  %head<
    %meta{ content: "text/html; charset=UTF-8", "http-equiv" => "Content-Type" }
    %meta{ name: "viewport", content: "width=device-width, initial-scale=1" }
    %title= app_name
    = csrf_meta_tags
    = csp_meta_tag
    = stylesheet_link_tag 'application', media: 'all'
    = javascript_include_tag 'application'
  %body<
    %header.header<
      .container<
        %nav.level<
          .level-left<
            .level-item<
              = app_name
          .level-right<
            %p.level-item<
              %a.button<
                %span.icon<
                  %i.fa.fa-github
                %span GitHub

            %p.level-item
              = link_to("Manage Users", nil, :class => "button is-dark is-outlined")
    %section.section<
      .container<
        = yield
    %footer.footer
      .container<
        = "Copyright © 2021 #{app_name}. All rights reserved."

  [1]: https://blackninjadojo.com/css/bulma/2019/02/27/how-to-create-a-layout-for-your-rails-application-using-bulma.html
  [2]: https://github.com/joshuajansen/bulma-rails/blob/f731ffcf1b4c5b6691a819746469672a30839d72/app/assets/stylesheets/bulma.sass

A: Finally I found a solution to resolve the error I shared in my post above. Sharing the answer below.
In app/assets/config/manifest.js replaced following
//= link_directory ../javascripts .js
//= link_directory ../stylesheets .css

WITH
//= link application.js
//= link application.css

Solution References
Found the above solution from https://github.com/rails/sprockets/issues/474. To be specific following comments in the referenced link helped
https://github.com/rails/sprockets/issues/474#issuecomment-374958102
https://github.com/rails/sprockets/issues/474#issuecomment-597563991
https://github.com/rails/sprockets/blob/master/UPGRADING.md#manifestjs (found the reference to this in https://github.com/rails/sprockets/issues/474#issuecomment-554535369)
Thanks.


text:
Q: Python tkinter How to make a label transparent? I have to make window blur. When the user clicks a button, popup_window shows up and background of window changes with blur.
root = tk.Tk()
## when button shows up,
root.attributes('-alpha', 0.3)

This works on Windows perfectly. However, I have to do it same on linux, debian.
I know, on Tkinter 8.6, that should work on linux. But. in my case, debian linux, it's not.
So, I tried in many ways.

*

*Make the label with window geometry size (whole size) and overlap the root_window and change the color or label with transparent color, and put the blurred dark image on label. However, I don't know how to set "transparent color" on the label.

*I tried to make canvas to do it. But similar issues about transparent color still happened.
Can I make the label transparent? or make the window blur on linux? in another way? not attributes('-alpha')


text:
Q: Ax Trace Parser Doesnt Show SQL Queries Configuring the tracing cockpit to show sql events, traceparser doesn't show the sql tab, how can I get the sql queries from trace parser?
And one second question, It also shows only my queries,is there a way to make it show all queries running in ax?

A: See how to Install the Trace Parser.
Also ensure you run it from the AOS server and that the correct event selection is provided.
Also start AX with escalated privileges (Run as administrator).


text:
Q: How to display a plot in fullscreen i am trying to display a plot but in fullscreen. This is my code :
import numpy as np
import pylab as plt
a = np.array([1,2,3,4])
b = np.array([1,2,3,4])
plt.plot(a,b,'.')
plt.show()

But the problem is : this does not display with the fullscreen. Any ideas to solve this ? Thank you.

A: It is depend on your matplotlib backend.
For Qt you may write this codeto maximize your plotting window:
manager = plt.get_current_fig_manager()
manager.window.showMaximized()

And read this question: Saving Matplotlib graphs to image as full screen

A: The code provided in the accepted answer will maximize the figure, but won't display it in fullscreen mode.
If you are keeping a reference to the figure, this is how you can toggle fullscreen mode:
import matplotlib.pyplot as plt

fig = plt.figure()
fig.canvas.manager.full_screen_toggle() # toggle fullscreen mode
fig.show()

alternatively, if you're not keeping a reference:
import matplotlib.pyplot as plt

plt.figure()
plt.get_current_fig_manager().full_screen_toggle() # toggle fullscreen mode
plt.show()

To toggle fullscreen mode using your keyboard, simply press f or Ctrl+f.

A: If you also want to remove tool and status bar, with the full_screen_toggle mode you can prove:
fig, ax = plt.subplots()
plt.rcParams['toolbar'] = 'None' # Remove tool bar (upper)
fig.canvas.window().statusBar().setVisible(False) # Remove status bar (bottom)

manager = plt.get_current_fig_manager()
manager.full_screen_toggle()

Taken from http://matplotlib.1069221.n5.nabble.com/Image-full-screen-td47276.html


text:
Q: Google Docs python gdata 2.0.16 upload file to existing collection I have managed to create a simple app which deletes (bypassing the recycle bin) any files I want to.  It can also upload files.  The problem I am having is that I cannot specify which collection the new file should be uploaded to.
def UploadFile(folder, filename, local_file, client):
    print "Upload Resource"
    doc = gdata.docs.data.Resource(type='document', title=filename)
    path = _GetDataFilePath(local_file)
    media = gdata.data.MediaSource()
    media.SetFileHandle(path, 'application/octet-stream')
    create_uri = gdata.docs.client.RESOURCE_UPLOAD_URI + '?convert=false'
    collection_resource = folder
    upload_doc = client.CreateResource(doc, create_uri=create_uri, collection=collection_resource, media=media)
    print 'Created, and uploaded:', upload_doc.title, doc.resource_id

From what I understand the function CreateResources requires a resource object representing the collection.  How do I get this object?  The variable folder is currently just a string which says 'daily' which is the name of the collection, it is this variable which I need to replace with the collection resource.

A: From various sources, snippets and generally stuff all over the place I managed to work this out.  You need to pass a uri to the FindAllResources function (one which I found no mention of in the sample code from gdata).
I have written up in more detail how I managed to upload, delete (bypassing the bin), search for and move files into collections
here


text:
Q: Use column names as values in pandas depending on whether value is true or false I have a df thats look like this
   500  600  700  800
0   Tr  Fls  Fls  Fls
1   Tr  Tr   Tr   Fls
2 ...

And I want to turn it into this
   Value
0  500
1  500
1  600
1  700
2 ....

How would I go about doing this?

A: Example
data = {'500': {0: 'Tr', 1: 'Tr'},
        '600': {0: 'Fls', 1: 'Tr'},
        '700': {0: 'Fls', 1: 'Tr'},
        '800': {0: 'Fls', 1: 'Fls'}}
df = pd.DataFrame(data)

output(df):
    500 600 700 800
0   Tr  Fls Fls Fls
1   Tr  Tr  Tr  Fls

Code
When df value is 'Tr':
df[df=='Tr'].stack().reset_index(level=1)['level_1'].to_frame('Value')

result:
    Value
0   500
1   500
1   600
1   700


text:
Q: SQL get last purchase price of a product from weak purchase detail table I have two date variables: @date1 and @date2. @date1 is always greater than @date2.
I have the following two tables:
+--------+
|purchase|
+--------+
|purch_id|
|date    |
+--------+

+-------------+
|purch_details|
+-------------+
|purch_id     |
|product_id   |
|product_price|
+-------------+

Table "purchase" stores the purchase date and an unique identifier (purch_id).
Purch_details is a weak table with no unique identifier. It contains the details of the puchase which include the product id (product_id), the price I paid for the product (product_price) and an identifier to the "puchase" table (purch_id).
With an SQL statement, in the date range @date1-@date2, I want to get the price of every product at which I last purchased.
In other words, I want the last price I agreed to purchase every product in table purch_details during the date range @date-@date2. The result must not contain product_id duplicates. Therefore, the outcome should be something like:
+-----------------------------------------+
|product_id | product_price |purchase_date|
|00001      | $10.10        |2014-01-01   |
|00002      | $12.45        |2014-04-30   |
|00003      | $9.20         |2014-04-30   |
+-----------------------------------------+

(on 2014-01-01 I last purchased product 00001 at $10.10. On 2014-04-30 I last purchased product 00002 and 00003 at $12.24 and $9.20 respectively)
I tried the following SQL:
SELECT
    purch_details.purch_id,
    purch_details.purch_price,
    purchase.date
FROM
    purchase
    INNER JOIN
    purch_details ON purchase.purch_id=purch_details.purch_id
WHERE
    purchase.date>=@date1 AND purchase.date<=@date2
GROUP BY
    purch_details.purch_id,
    purch_details.purch_price,
    purchase.date

The problem with the above SQL is that it returns rows with duplicate product_id.

A: I think this should work:
;WITH CTE AS
(
    SELECT purch_details.purch_id,
           purch_details.purch_price,
           purchase.date,
           ROW_NUMBER() OVER(PARTITION BY purch_details.purch_id
                                 ORDER BY purchase.date DESC) RN
    FROM purchase
    INNER JOIN purch_details
    ON purchase.purch_id=purch_details.purch_id
    WHERE purchase.date BETWEEN @date1 AND @date2
)
SELECT purch_id,
       purch_price,
       [date]
FROM CTE
WHERE RN = 1;


text:
Q: Struts 2 jquery sj:select and json result I am using struts 2 jquery plugin select component.
The action is:
SampleAction {

       private List<SampleVO> samples; //With setters and getters
       private List<AnotherVO> anotherList; //With setters and getters
       private String anString; //With setters and getters

       @Action(value = "/loadSelect", results = {
       @Result(name = "success", type = "json")})
             public String loadSomeSamples() {
                samples = new ArrayList<SampleVO>();
                //Put some object in samples.
                return SUCCESS;
              }
    }

The jsp is
<sj:select list="samples" />

The problem is that the json plugin will serialize all the properties in action ( anotherList, anString etc...), as below
{
  "samples": {
    "0": {"property":"a"},
    "1": {"property":"b"},
    "2": {"property":"c"}
  },
  "anString": "hello",
  "anotherList": {
    "0": {"prop1":"a","prop2":"b"},
    "1": {"prop1":"c","prop2":"d"}
  }
}

If I change the json root parameter to samples, then the js:select will not work as it can not find any list named samples in the returned json. The returned json is:
{
    "0": {"property":"a"},
    "1": {"property":"b"},
    "2": {"property":"c"}
}

Can this be fixed ?! Is there any way I can configure struts 2 json plugin to generate
 {
  "samples": {
        "0": {"property":"a"},
        "1": {"property":"b"},
        "2": {"property":"c"}
      }
  }

Or is there any why struts 2 jquery plugin in accept the simple json array

A: You can use includeProperties parameter to json result. For example
@Result(type="json", params = {"includeProperties", "samples.*" })

one more sample
@Result(type="json", params = {"root", "samples", "wrapPrefix", "{\"samples\":", "wrapSuffix", "}"})


text:
Q: "There is to be no more loss today" sentence
There is to be no more loss today.

In this sentence, I don't understand the grammar structure. Why does "to be" come after "there is"?

A:
There is [to be no more loss today.]

You asked about the grammar.
"There" is the raised subject of the (catenative) matrix verb "be", but the NP "no more loss today" is the displaced subject of the second "be".
The embedded "be" clause is best analysed as existential even though "there" does not appear as subject of that clause but is located higher in the constituent structure of the sentence.


text:
Q: XML parsing as  I built a Twilio app in Phpstorm and I'm uploading everything normal and the application is working just fine, but randomly, Twilio will throw errors that it had an issue parsing the xml and shows this in the error:
12100 Document parse failure
Error on line 1 of document  : The value following "version" in the XML declaration must be a quoted string.  Please ensure that the response body is a valid XML document.

<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<Response>
    <Redirect>NOCC.php</Redirect>
</Response>

So I checked on the server and the code is still correct
<?php

session_start();
require '../../../Services/phpmailer/PHPMailerAutoload.php';
include '../../../Services/session.php';

$callerid = $_REQUEST['From'];
$callsid=$_SESSION['callsid'];

$mail = new PHPMailer;

//$mail->SMTPDebug = 3;                               // Enable verbose debug output

$mail->isSMTP();              // Set mailer to use SMTP
$mail->Host = ''; // Specify main and backup SMTP servers
$mail->SMTPAuth = false;      // Enable SMTP authentication
$mail->Username = '';         // SMTP username
$mail->Password = '';         // SMTP password
$mail->SMTPSecure = '';       // Enable TLS encryption, `ssl` also accepted
$mail->Port = ;           // TCP port to connect to

$mail->From = '';
$mail->FromName = '';
$mail->addAddress('');     // Add a recipient

$mail->addAttachment("../../../uploads/images/$callsid.png", "$callsid.png");    // Optional name
$mail->addEmbeddedImage("../../../uploads/images/$callsid.png", "$callsid.png");    // Optional name
$mail->isHTML(true);                                  // Set email format to HTML

$mail->Subject = "$site_name | ARM | $title | $first_name | $last_name | $account_number | FAILED PIN AUTH";
$mail->Body = "";
$mail->AltBody = "";

header('content-type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<Response>';

if(!$mail->send()) {
echo '<Redirect>alarm.php</Redirect>';
} else {

echo '<Redirect>NOCC.php</Redirect>';
}
echo '</Response>';

Any suggestions why it would be throwing the error sometimes?


text:
Q: Is it true that $(A\times A)-(B\times B) = (A - B)\times (A -B)$ for any two sets A,B? I don't know how to prove set inclusions with Cartesian products, can someone explain how?

A: This is not true: let $A=\{1,2\}$ and $B=\{1\}$. Then $(A×A)\setminus (B×B)=\{(1,2),(2,1),(2,2)\}$ but $(A\setminus B)×(A\setminus B)=\{(2,2)\}$.

A: Let's see. Suppose $A$ is a finite set with $a$ elements, $B$ is a finite set with $b$ elements, and $B$ is a subset of $A$. Then $(A\times A)\setminus(B\times B)$ has $a^2-b^2$ elements, while $(A\setminus B)\times(A\setminus B)$ has $(a-b)^2$ elements. Is $a^2-b^2=(a-b)^2$?


text:
Q: Check if ID exists in database How can i check if a id exists in a mysql database, and if it does: create a new id and check over again. I have the following code to create a id:
$length = 10;
$id = '';
for ($i = 0; $i < $length; $i++) {
    $id .= chr(rand(ord('0'), ord('9')));
}

To check if the id exists i use the code below:
$database->query('SELECT user_id FROM users
                  WHERE public_id = ':public_id',array(':public_id' => $public_id)');

if($database->count() >= '1') {
//create a new id
} else { }

A: What you're trying to do is not considered a "best practice", as (theoretically) you could create an infinite loop (creating a random ID, then checking for existence could "hit" on each iteration).
A better solution to create unique IDs is to set a column as your primary key, and increment upon each new insert.
If you want another column to be unique, you can define that column to be unique as well, but you won't have to rely on "random" strings.


text:
Q: Fail2ban with Hipchat server Has anyone managed to get fail2ban working with hipchat server?
I've found the log file and here's an example of a failure;
Authentication for 'user@domain.com' failed. HTTP code: 403, XMPP error: not-authorized, message: null

Any pointers on writing the filter.d file ?

A: If that is the full log messages then fail2ban will not work with it. Fail2ban requires that a log message contains a datetime which it can parse. The regex you supply is then matched against what is left once the datetime has been parsed and removed. Your log message appears to be missing the relevant datetime.


text:
Q: How to keep localStorage values after refresh? This is my ctrl:
app.controller('ctrl', function ($window, $scope) {

    $scope.initData = [
        {
            firstName: "John",
            lastName: "Doe",
        },
        {
            firstName: "Jane",
            lastName: "Doe",
        },
        {
            firstName: "John",
            lastName: "Smith",
        }
    ];

    $window.localStorage.setItem('initData', JSON.stringify($scope.initData));
    $scope.retrievedData = JSON.parse($window.localStorage.getItem('initData'));
    $scope.sortedType = 'firstName';
    $scope.sortedReverse = false;
    //Remove Rows and Update localStorage Key Values
    $scope.removeRow = function(row) {
        $scope.retrievedData.splice(row, 1);
        $scope.initData.splice(row, 1);
        $window.localStorage.setItem('initData', JSON.stringify($scope.initData));
    }
});

HTML:

                        First Name

                        Last Name

                {{v.firstName}}
                {{v.lastName}}

                    <button class="btn btn-primary">Edit</button>
                    <button class="btn btn-primary" ng-click="removeRow();">Delete</button>

Now, I believe it is clear what this does. It is assigning a data from $scope.initData to localStorage and then interpolate it into the HTML. the function removeRow() deletes the row in the table and updates the localStorage with the latest action. The issue with this is that each time I reload the HTML the initial localStorage data gets loaded and not the updated one. I know that this is because I'm assigning it here: $window.localStorage.setItem('initData', JSON.stringify($scope.initData)); but I don't know how to keep it updated after the refresh.
Please advise.
Thanks.

A: On every page load you are setting new initData and updating the local storage... Instead you should check for existing localstorage data and use that before using the mocked initData

A: Your line $window.localStorage.setItem('initData', JSON.stringify($scope.initData)); is resetting the data each time you refresh.
Replace the line with this:
if(!localStorage.getItem('initData')){
    $window.localStorage.setItem('initData', JSON.stringify($scope.initData));
}

More over you should not have that line at all. Start with an empty local storage and add new entries from UI only.
The above code only run it once, for the first time the application is run.
If yo want to re-insert the data every time the list is empty then try following
if(!localStorage.getItem('initData') || JSON.parse(localStorage.getItem('initData')).length === 0){
    $window.localStorage.setItem('initData', JSON.stringify($scope.initData));
}

A: You need to check first if your localStorage is empty on load
if (localStorage == null) {//setItem() ...};

A: delete data from local storage using JavaScript
Here is your code without error passed.
use function for delete
       function deleteRow(index){
              dataList.splice(index, 1);
              console.log('====>', dataList)
              localStorage.setItem('items', JSON.stringify(dataList));
}

A: I was facing the same issue for months. And finally I found the solution. ( I am not sure whether this is the same problem for you, anyway sharing my scenario )
When I was testing on my local host, I was using the URL as http://localhost:3000/ for loading the page. But during login, after page refresh,  I was using actually the IP address to redirect the page, which was like http://192.163.1.31:3000/.
So the result, the local storage of http://localhost:3000/ contains the values I saved, but the local storage of http://192.163.1.31:3000/ doesn't contain the values I saved.
So I fixed the solution by simply using same URL across the launch till page load. And the problem was fixed. ( I used http://192.163.1.31:3000/ instead of http://localhost:3000/)
For your case, check whether the URL is different after the page reload.If yes, fix it, and your problem may not persist

A: This code will help you to understand.....
<!DOCTYPE html>

    <button onclick="clickCounter()" type="button">Click me!</button>
    <button onclick="fun()" type="button">Click me! Array</button>

A: In Simple Steps in matters how you need your page to refresh using afunction to refresh comes handy and effective for me and keeps the locaStorage values set.. i used.... the function below by calling it as load() and it worked for me
    function load()
{
  console.log("loading")
  setTimeout("window.location.assign('samepage.html');", 1000);

}


text:
Q: Looking for the label that books get when they out of use (at the library) When a library has a lot of books or when a library doesn't want the book for any reason, then they used to put a stamp with a label that says that these books are not already belong to the library, and the person which hold them, hold them or buy or sell it, do it honestly. But there are specific words which accepted in this field in my language, it's something like "out of use in x library" or "taken out of the x library.
Can I know what's the normal or parallel way in the library of English spoken countries to do this label, that I talked about?

A: It really depends on the library. I've seen several ways this can be done from different libraries.
In our local (community) library, they cross out the bar code and in several places they stamp the phrase: "Sold to the public, and removed from [Library Name] collection". I've also seen some stamps that say "Discarded from library stock."
So, there isn't a universal way that this is done. In many cases, books get sold in batches and no stamp is ever made on the book.

A: Books that a library does not want to keep in its system are, in the USA,  called discards are are usually stamped DISCARD or maybe WITHDRAWN. You can see some images here.
The process of withdrawing a book from circulation is described here at Making Discards (American Library Association).
The nomenclature may differ in other English speaking countries.

A: I think you're looking for "removed from circulation".
Sometimes they will simply have a stamp that reads "withdrawn"

Or "discarded"

Some libraries use much longer phrases:

There's no one set phrase for this, though.

A: I believe the phrase you're looking for is "out of circulation". If a book is in the library system, (checked out, or available to be checked out) it is "in circulation". If, for whatever reason, it isn't, it is "out of circulation".
I can't think of it being used as a stamp though.
Edit: As far as a stamp explicitly saying a book no longer belongs to a library, I don't recall ever seeing one (I'm not saying they don't exist though). When I was a kid I had lots of former library books, most of which still had the "Property of X Public Library" stamp, although sometimes that stamp was crossed out in black marker.

A: Just to add another perspective, 'discarded' and 'withdrawn' are possible labels to use, and "weeding" is the process. It is one of the vital processes in collection development.
'Discarded' books are usually sold or donated, while 'withdrawn' books are usually placed in a separate warehouse as they may have historical value (or something to that effect). (I am speaking in a general sense, some libraries have their own term definitions for such)
I won't use "out of circulation" as it may also imply that the book is for room use only (i.e., it [the book] could be a part of some special collection.)
I worked as a volunteer librarian long ago.

A: The term in question is "deaccession."


text:
Q: (python) Xlib.display.Display() throwing AttributeError module 'socket' has no attribute 'AF_UNIX' I am running a Windows 10 machine with python 3.11 installed, and am facing an unexpected error.
The issue arose when I was attempting to lock my mouse, I've been tackling this issue for a while now, and I've finally found a good lead.
I tried this code:
from Xlib.display import Display
from Xlib import X
import contextlib
from time import sleep

DISPLAY=":0"

disp = Display(DISPLAY)
screen = disp.screen()
root = screen.root

@contextlib.contextmanager
root.grab_pointer(owner_events=True,
    event_mask=0,
    time=X.CurrentTime,
    pointer_mode=X.GrabModeAsync,
    keyboard_mode=X.GrabModeAsync,
    confine_to=0,
    cursor=0)

sleep(5)

disp.ungrab_pointer(time=X.CurrentTime)

It seems to be Display(DISPLAY) causing the issue, the whole error being:
Exception has occurred: AttributeError
module 'socket' has no attribute 'AF_UNIX'
  File "G:\Downloads\PY SCRIPTS\mouselock.py", line 8, in <module>
    disp = Display(DISPLAY)

Leaving Display empty ( as "Display()" ) will not work, though I have seen it used in others' scripts- it does not work in my case. This has led me to believe this is an issue with me operating on Windows 10, and/or python 3.11.
Anything I can do to resolve this issue?
Any help is appreciated.


text:
Q: Implementation of a context-free grammar for logical operators with parentheses I'm trying to implement a context-free grammar for the language of logical operators with parentheses including operator precedence.
For example, the follows:
{1} or {2}
{1} and {2} or {3}
({1} or {2}) and {3}
not {1} and ({2} or {3})
...

I've started from the following grammar:
expr := control | expr and expr | expr or expr | not expr | (expr)
control := {d+}

To implement operator precedence and eliminate left recursion, I changed it in the following way:
S ::= expr
expr ::= control or expr1 | expr1
expr1 ::= control and expr2 | expr2
expr2 ::= not expr3 | expr3
expr3 ::= (expr) | expr | control
control := {d+}

But such grammar doesn't support examples like: ({1} or {2}) and {3} that contain 'and' / 'or' after parentheses.
For now, I have the following grammar:
S ::= expr
expr ::= control or expr1 | expr1
expr1 ::= control and expr2 | expr2
expr2 ::= not expr3 | expr3
expr3 ::= (expr) | (expr) expr4 | expr | control
expr4 :: = and expr | or expr
control := {d+}

Is this grammar correct?
Can it be simplified in some way?
Thanks!

A: To implement your operator precedence, you want just:
S ::= expr
expr ::= expr or expr1 | expr1
expr1 ::= expr1 and expr2 | expr2
expr2 ::= not expr2 | expr3
expr3 ::= (expr) | control
control := {d+}

This is left-recursive in order to be left-associative, as that's generally what you want (both for correctness and most parser-generators), but if you need to avoid left recursion for some reason, you can use a right-recursive, right associative grammar:
S ::= expr
expr ::= expr1 or expr | expr1
expr1 ::= expr2 and expr1 | expr2
expr2 ::= not expr2 | expr3
expr3 ::= (expr) | control
control := {d+}

as both and and or are associative operators, so left-vs-right doesn't matter.
In both cases, you can "simplify" it by folding expr3 and control into expr2:
expr2 ::= not expr2 | ( expr ) | {d+}


text:
Q: Filebeat - Logstash - Multiple Config Files - Duplicate data I am new to logstash and filebeat. I am trying to set up multiple config files for my logstash instance.
Using filebeat to send data to logstash. Even if I have filters created for both the logstash config files, I am getting duplicate data.
Logstash config file - 1:
input {
  beats {
    port => 5045
  }
}

filter {
   if [fields][env] == "prod" {
     grok {   match => { "message" => "%{LOGLEVEL:loglevel}] %{GREEDYDATA:message}$" }
     overwrite => [ "message" ]
     }
   }
}

output {
  stdout {
    codec => rubydebug
  }

  elasticsearch {
    hosts => ["https://172.17.0.2:9200"]
    index => "logstash-myapp-%{+YYYY.MM.dd}"
    user => "elastic"
    password => "password"
    ssl => true
    cacert => "/usr/share/logstash/certs/http_ca.crt"
  }
}

logstash config file-2
input {
  beats {
    port => 5044
  }
}

filter {
   if [fields][env] == "dev" {
     grok {   match => { "message" => "%{LOGLEVEL:loglevel}] %{GREEDYDATA:message}$" }
     overwrite => [ "message" ]
     }
   }
}

output {
  stdout {
    codec => rubydebug
  }

  elasticsearch {
    hosts => ["https://172.17.0.2:9200"]
    index => "logstash-myapp-%{+YYYY.MM.dd}"
    user => "elastic"
    password => "password"
    ssl => true
    cacert => "/usr/share/logstash/certs/http_ca.crt"
  }
}

Logfile Content:
[INFO] First Line
[INFO] Second Line
[INFO] Third Line

Filebeat config:
filebeat.inputs:
- type: filestream
  enabled: true
  paths:
    - /root/data/logs/*.log
  fields:
    app: test
    env: dev

output.logstash:
  # The Logstash hosts
    hosts: ["172.17.0.4:5044"]

I know that even if we have multiple files for config, logstash processes each and every line of the data against all the filters present in all the config files. Hence we have put filters in each of the config files for "fields.env".
I am expecting 3 lines to be sent to Elasticsearch because "fields.env" is "dev", but it is sending 6 lines to Elasticsearch and duplicate data.
Pleas help.

A: The problem is that your two configuration files get merged, not only the filters but also the outputs.
So each log line making it into the pipeline through any of the input, will go through all filters (bearing any conditions of course) and all outputs (no conditions possible in output).
So the first log line [INFO] First Line coming in from port 5044, will only go through the filter guarded by [fields][env] == "dev", but then will go through each of the two outputs, hence why it ends up twice in your ES.
So the easy solution is to remove the output section from one of the configuration file, so that log lines only go through a single output.
The better solution is to create separate pipelines.


text:
Q: Twitter's typeahead-bloodhound: What is the equivalent of "%QUERY" when using ajax.data and POST? If one uses Bloodhound with GET:
// Typeahead
personsBloodhound = new Bloodhound({
    datumTokenizer: function (person) { return person.name; },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: '/ajax/Persons/List?nameContains=%QUERY',
        ajax: {
            beforeSend: function(xhr) {
                $(".searching-person").show();
            },
            data: {
                "pageSize": 4,
                "otherParam1": "blah",
                "otherParam2": "bleh",
            }
        },
        filter: function (response) {
            $(".searching-person").hide();
            return response.persons;
        }
    }
});

One simply uses %QUERY in the URL.

Now....
If one uses Bloodhound with POST, what should I use instead of %QUERY?

// Typeahead
personsBloodhound = new Bloodhound({
    datumTokenizer: function (person) { return person.name; },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: '/ajax/Persons/List',
        ajax: {
            type: "POST",
            beforeSend: function(xhr) {
                $(".searching-person").show();
            },
            data: {
                "nameContains": ....WHAT GOES HERE?????......
                "pageSize": 4,
                "otherParam1": "blah",
                "otherParam2": "bleh",
            }
        },
        filter: function (response) {
            $(".searching-person").hide();
            return response.persons;
        }
    }
});

If it was not clear, the question is:
What is the equivalent of %QUERY when using POST within Bloodhound's remote?
The documentation isn't clear about this, (proof):
https://github.com/twitter/typeahead.js/blob/master/doc/bloodhound.md#remote
Also tried using:
 "nameContains": $("#my-input-that-uses-typeahead").val(),

But didn't work.

A: Equivalent of %QUERY when using POST within Bloodhound's remote is query.
Here is a simple example (with detailed explanation) where you can use it for both GET and POST. As you can see I have declared a variable isExtendUrl. If this is set to true then the query (what you type) will be added to the end of the url (you have to give the myurl somehow).
The next variable is isRequestMethod. If this is set to POST, you can use bloodhound for POST calls else you can use it for GET calls. As you can see prepare function has two parameters query and setting. query is the one what you type. If you just want the POST call without GET move prepare key value pair inside remote object.
So, if you have to use JSON body as {gender: 'MALE', name: 'what is typed'} for your POST call. You can have an initial query object with all your key value pairs eg: initialQuery = {gender: 'MALE'}, and the key searchKey which should be added to initialQuery when searching, could be added on prepare like initialQuery[searchKey] = query.
Finally, if the response object of your POST call is an object and you have to extract a specific key value use filter. Eg: Say your response object is
{
  status: 'some status',
  content: [{array}, {of}, {objects}, ...],
  someKey: someValue
}

and you have to get content, then return data.content. Here is a full example
let isExtendUrl = true; //to add query at the end of the url, usually used with GET
let isRequestMethod = 'POST';
let initialQuery = {gender: 'MALE'};
let searchKey = 'name';

let bloodhound = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.whitespace,
    queryTokenizer: Bloodhound.tokenizers.whitespace,

    remote: {
        url: isExtendUrl ? myurl + '%QUERY' : myurl,
        wildcard: '%QUERY',
        filter: function (data) {
            return $.map(data.content, function (obj) {
                return obj;
            });
        }
    }
});

if (isRequestMethod == 'POST') {
    let prepare = function (query, settings) {
        initialQuery[searchKey] = query;
        settings.type = "POST";
        settings.contentType = "application/json; charset=UTF-8";
        settings.data = JSON.stringify(initialQuery);

        return settings;
    }
    bloodhound.remote.prepare = prepare;
}

A: Right, after further looking at bloodhound the wildcard is just what to replace not the value.
It doesn't store the query string anywhere. On queryChanged fires and filters remote response. Looks like you'll have to get the query yourself.
"nameContains": $('input#search').val()

A: You have to alter the URL somehow, otherwise the bloodhound wont send an other request (see https://stackoverflow.com/a/24025789/2175370) and livesearch/typeahead wont work.
So ("#my-input-that-uses-typeahead").val() works just fine in combination with a dynamic URL (e.g.http://127.0.0.1:1234/REST_API/_search?useless=%QUERY) and a beforeSend-function in the ajax setttings.
I gonna file an issue about this behaviour. Using the bloodhound for POST-requests ist VERY awkward and takes away the simplicity intended with typeahead.js.
EDIT:
Also make sure you set the new value for the data in beforeSend and set settings.hasContent = true. Otherwise the initial data will be used.
Example on how it's done: https://github.com/twitter/typeahead.js/issues/542#issuecomment-29995960.


text:
Q: Creating AJAX data string I'm submitting a form via AJAX to a PHP script that sends an email to me with the form details. The form is pretty straight forward, except that I have a group of checkboxes that signify the type of project(s) the person filling out the form wants. I know how to assemble a datastring with a simple form, but I am having difficulty figuring out the best approach to adding the checkboxes with name equal to projecttype[]. In theory, I think I want something like:
website=example.com&projecttype=1,2,4,6&budget=$500-$1000.

You can find the form and Javascript in this jfiddle: http://jsfiddle.net/H5MF8/

A: jQuery has a function exactly for that purpose: .serialize(). It takes every element in your form and creates a query string. The below snippet should be enough.
$("#submit").click(function() {
  $.ajax({
    type: "POST",
    url: "/bin/send_form_email.php",
    data: $('#contactform').serialize(),
    cache: false,
    success: function() {
    //    ...
    },
    return false;
  });
});


text:
Q: How to center a tree diagram in D3.js using CSS? I am using D3.js to make a hierarchical tree diagram. But I cannot seem to figure out how to set the x and y of the tree in the manner I want. Currently as the image below shows it shoots off vertically.
Edit:
It works on my monitor with a screen of 27' but on my 13' laptop it looks like this
I am using this example to try and get it to look the same.
#root {
  display: flex;
  flex-direction: column;
  align-items: stretch;
  align-content: center;
  justify-content: center;
  height: 100vh;
  padding: 0 50px 150px;
  text-align: center;
  box-sizing: border-box;
}

A: Well it was a mistake on my half assuming it was not an issue with the CSS.
I am not too familiar with CSS but the following fix of altering the padding from padding: 0 50px 150px to padding: 400px 50px worked.


text:
Q: Making a HTML Button rounded I need to make the button rounded, however, can't use the <input> attribute as I already have a div with that, so i had to use the <button type> attribute. Here's what I've got:

.button2 {
 padding:0px;
 text-align:center;
 }

    <button type="button">Sign up</button>

A: Change class to button, not button2, as that's changing the actual div which has no properties, and the button does.

    <button class="button">Sign Up</button>

A: You could just add a class to the input.
<input type="" class="whatever" />
input.whatever { border-radius:5px; }

Edit:
Actually if it's a sign-up button you probably want an
Sign Up
a.whatever { dislay:inline-block; border-radius:5px; padding:5px; }

A: "border-radius" is the CSS property you're looking for.

A: .button2 {
  padding:0px;
  text-align:center;
  border-radius: 10px;   <--- this rounds the corners
}


text:
Q: different ways to create string in C I'm looking for understand the pros and cons of every method to create a string, can someone help me?
char x[] = {'a', 'b', 'c', '\0'};

or
char x[]="abc";

or
char *p;
p="abc";

Do i forgot other methods? Thank you.

A: char x[]={{'a'},{'b'},{'c'},{'\0}};

In addition to the missing apostrophe after '\0, this should normally be char x[] = {'a', 'b', 'c', '\0'};. The C grammar allows extra braces with single scalar initializers, but compilers will generally warn about this because it is indicative of an error—braces are usually used to indicate the composition of aggregate objects such as arrays or structures.
With the apostrophe fixed, this defines x to be an array of four characters, which are a, b, c, and the null character. This format is tedious, so effectively nobody defines an array this way unless there is some special circumstance, such as needing to define one of the characters using an expression or perhaps when the array is being defined for some purpose other than use as a character string and one wishes to emphasize that.
char x[]="abc";

This defines x to be the same of four characters as above. This is the usual way to define an array of characters.
There are no differences between these two initialization methods in the C semantics; both define the same array, and so the only reasons for choosing between them are how humans interact with them—which is easier to read, easier to edit without making mistakes, and so on.
char *p;
p="abc";

This is a definition and an assignment. It is better written as char *p = "abc"; unless there is reason not to do so.
This defines p to be a pointer to a static array of the same four characters as above. It is not common to use this merely to define an array because it creates a needless pointer, p. It is generally used only when one wants a pointer that initially points to the static array but that may be changed later.

A: There is another way of course as well. You can instantly initialize or assign pointers with compound literals. This kind of initialisations creates pointer to amendable string.
char *p = (char[]){"ASDF"};

int main()
{
    p[2] = 'X';
    printf("%s\n", p);
}

https://onlinegdb.com/H19BLahy8

A:
char x[] = {'a', 'b', 'c', '\0'};
char x[] = "abc";

using malloc() (and friends)
char *p = malloc(4);
if (!p) { /* error; */ exit(EXIT_FAILURE); }
strcpy(p, "abc");
free(p);

using compound literal (different than a string literal)
char *example(char *p) {
    p[0] = 'A';
    p[2] = 'C';
    return p;
}
example((char[4]){"abc"}); // unnamed object


text:
Q: Get yaw to point at X and Y values (2D) I have $X$ and $Y$ coordinates. I also have another object. I need to figure out how set the yaw of the second object to point at the $X$ and $Y$ coordinates. How can I go about doing this?

A: If the first object is at $(X,Y)$ and the second is at $(a,b)$, the vector from the second to the first is $(X-a,Y-b)$  To get the angle of that vector from the $+x$ axis (is that what you want?) you can use atan2(Y-b,X-a).  It worries about the quadrants, unlike $\arctan$


text:
Q: how to sequence varying function calls with promises with a queue I have a function that returns a promise
function ajax() { sideeffect(); return new Promise() }

I call this function at various times, what I want is this function to queue the calls and only run after the previous call is resolved.
If I call ajax three times in a row ajax(); ajax(); ajax() I want this to be
ajax.then(ajax).then(ajax) or if i call four times it chains accordingly.

A: Create a persistent variable representing the last Promise created, chain onto it when ajax is called, reassign the persistent variable to the new chain, and return the new chain:

let lastProm = Promise.resolve();
function ajax(ms) {
  // sideeffect();
  lastProm = lastProm.then(() => (
    new Promise(resolve => setTimeout(resolve, ms))
  ));
  return lastProm;
}

ajax(1000).then(() => console.log('resolved 1'));
ajax(1000).then(() => console.log('resolved 2'));
ajax(3000).then(() => console.log('resolved 3'));
ajax(1000).then(() => console.log('resolved 4'));


text:
Q: Spool Results from Cursor Into Table I have a cursor that I'm using to find NULL columns in a database.  I'm using this to eliminate NULL Columns from an upload of this data to Salesforce using dbAMP. I'd like to modify this to spool the results into a Table and include the Table Name and Column name.
declare @col varchar(255), @cmd varchar(max)

DECLARE getinfo cursor for
SELECT c.name FROM sys.tables t JOIN sys.columns c ON t.Object_ID =
c.Object_ID
WHERE t.Name = 'Account'

OPEN getinfo

FETCH NEXT FROM getinfo into @col

WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @cmd = 'IF NOT EXISTS (SELECT top 1 * FROM Account WHERE [' + @col +
'] IS NOT NULL) BEGIN print ''' + @col + ''' end'
EXEC(@cmd)

FETCH NEXT FROM getinfo into @col
END

CLOSE getinfo
DEALLOCATE getinfo

I've have not had any success in modifying this cursor to put results in a table.  Any guidance would be appreciated.

A: Make the Print a Select then Insert into (tbl with same column definition).
Create a table with the same columns in the same order.
Then put an Insert into yourtable(your columns in the same order as output from the exec().
Any change in table columns in the future may break this. The table and the query should have the same columns. If you are cautious and control the order of columns in the select and insert, it shouldn't matter about the table column order, but it is still good practice imho.
Example (insert into table with dynamic sql)
if object_id('dbo.ColumnMatch','U') is not null drop table dbo.ColumnMatch;
create table dbo.ColumnMatch (
     id int identity(1,1) not null primary key
    ,column_name varchar(512)
);

declare @col varchar(256) = 'This Column Name'
declare @s varchar(max) = 'select ''' + @col + '''';

insert into ColumnMatch (column_name)
exec(@s);

select * from ColumnMatch;

Not Print but select and fix the Insert Into statement. :)
if object_id('dbo.ColumnMatch','U') is not null drop table dbo.ColumnMatch;
create table dbo.ColumnMatch (
     id int identity(1,1) not null primary key
    ,column_name varchar(512)
);
declare @col varchar(255), @cmd varchar(max)

DECLARE getinfo cursor for
SELECT c.name FROM sys.tables t JOIN sys.columns c ON t.Object_ID =
c.Object_ID
WHERE t.Name = 'Account'

OPEN getinfo

FETCH NEXT FROM getinfo into @col

WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @cmd = 'IF NOT EXISTS (SELECT top 1 * FROM Account WHERE [' + @col +
'] IS NOT NULL) BEGIN select ''' + @col + ''' column_name end'
Insert into ColumnMatch (column_name)
EXEC(@cmd)

FETCH NEXT FROM getinfo into @col
END

CLOSE getinfo
DEALLOCATE getinfo

select * from ColumnMatch;


text:
Q: How to use only one node for a Condor cluster job? I need to run lots of jobs (a pipeline) on a Condor cluster but it has to be on one node. So I need to do 2 things:

*

*How do I ask Condor for an available node?

*How do I tell Condor to run a job on that node?
I imagine this is very simple, but I'm deep in the docs with no luck.

A: Simply set a job requirement to run on a specific node.
requirements = $(requirements) && (TARGET.Machine == "somenode")

Selection of that node is up to you. If you use a DAG you can have a "node selection" job and then rewrite submit files as I outline here https://stackoverflow.com/a/27590992/174430.


text:
Q: How to delete image associated with a document in mongodb using s3 bucket? I am saving user data with their image and for storage, I am using s3 bucket of aws. In my upload API, I am saving the URL of the image in the database. I want to implement that if I delete the user the image also be deleted from the s3 bucket. I wrote the delete API too but I need some guidance on how to use it?
here is my s3 delete API code.
// delete a file from s3
function deleteFileStream(fileKey, next) {
    const deleteParams = {
        Key: fileKey,
        Bucket: bucket_name,
    }
    s3.deleteObject(deleteParams, (error, data) => {
        next(error, data)
    })
}
exports.deleteFileStream = deleteFileStream;

// my router controller
router.delete("/deleteImage/:key", (req, res) => {
    const key = req.params.key
    deleteFileStream(key, (error, data) => {
        if (error) {
            return res.send({ error: "Can not delete file, Please try again later" });
        }
        return res.send({ message: "File has been deleted successfully" });
    });
});

those apis are working fine in postman. I need some guidance on how to use it in my delete user route so that if I delete a user the image associated with also deleted from my s3 bucket.
// my delete user api
function user_delete(req, res) {
    User.findByIdAndRemove(req.params.id)
        .then(data => {
            if (!data) {
                return res.status(404).send({
                    success: false,
                    message: "User not found with id " + req.params.id
                });
            }
            res.send({
                success: true,
                message: "User successfully deleted!"
            });
        })
};
router.delete('/delete/:id', deleteUser);


text:
Q: Erlang MQTT configuration broken? There is a way (according to this and this) in Erlang eMQ to enable in my MQTT Broker a plugin for the emq_auth_username, meaning I can config my broker to allow connections bases on my etc/emq_auth_username.conf file.
I did create the file and put inside similar entries...
however myclient is not comming in:

my file looks like:

auth.user.$N.username = admin
auth.user.$N.password = public
auth.user.$1.username = dummy_username
auth.user.$1.password = dummy_password
auth.user.$N.username = dummy_username
auth.user.$N.password = dummy_password

since am trying to get how it works....
any hint how can  I add a new credential here in this file???
Thanks!

A: I think you actually need something like this...
auth.user.1.username=fred
auth.user.1.password=bl0665
auth.user.2.username=jane
auth.user.2.password=j4n3
auth.user.3.username=...
...etc..


text:
Q: How do I achieve consistent highlighting of QListWidget items across widget states? I am using PyQT 4.8.3 to create a dialog with two QListWidgets both allowing multiple selection.

*

*I find that if these QListWidgets are enabled, the selected items are highlighted in blue only when the QListWidget has focus, without focus the highlight is light-grey.

*I also find that if the QListWidgets are disabled, the selected items are highlighted in blue despite lack of focus.

As the users go from one list to the other they will find this very confusing.
As a developer I find the light-grey/unfocused, blue/disabled behaviours undesirable.  I would appreciate any advice on modifying them.
I've looked through the docs for QListWidget, QListView and QAbstractView without finding anything applicable, I have also looked through the stylesheet documentation without having any luck.

A: The simplest approach is alter QPalette (if style sheet doesn't work for you).
Just set palette for QListView with values you want to alter (only).
Do something like that:
QPalette customPalette;
QPalette orginalPallete = listView->palette();
customPalette->setBrush(QPalette::Disabled, QPalette::Highlight,
                        orginalPallete.brush(QPalette::Active, QPalette::Highlight));
listView->setPalette(customPalette);

I recommend to read how palette property works (it merges values from parents and QApplication so you need set only thing you want to change).
You can also change this colors globally by changing palette for QApplication.

A: I would use stylesheets here. In this example, the selected items in this QListWidget will he highlighted in blue, and when the QListWidget is disabled or without focus they will turn gray:
#!/usr/bin/env python
#-*- coding:utf-8 -*-

from PyQt4 import QtCore, QtGui

class myWindow(QtGui.QWidget):

    def __init__(self, parent=None):
        super(myWindow, self).__init__(parent)

        self.setStyleSheet( """ QListWidget:item:selected:active {
                                     background: blue;
                                }
                                QListWidget:item:selected:!active {
                                     background: gray;
                                }
                                QListWidget:item:selected:disabled {
                                     background: gray;
                                }
                                QListWidget:item:selected:!disabled {
                                     background: blue;
                                }
                                """
                                )

        self.listWidget = QtGui.QListWidget(self)
        self.listWidget.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)

        self.button = QtGui.QPushButton(self)
        self.button.setText("Disable the list!")
        self.button.clicked.connect(self.on_button_clicked)

        self.layout = QtGui.QVBoxLayout(self)
        self.layout.addWidget(self.button)
        self.layout.addWidget(self.listWidget)

        for itemNumber in range(5):
            item = QtGui.QListWidgetItem(self.listWidget)
            item.setText("Item {0}".format(itemNumber))
            self.listWidget.addItem(item)

    @QtCore.pyqtSlot()
    def on_button_clicked(self):
        enable = False if self.listWidget.isEnabled() else True

        self.listWidget.setEnabled(enable)

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('myWindow')

    main = myWindow()
    main.show()

    sys.exit(app.exec_())

A: QItemDelegate can be used to provide custom display features. I hope it will help you. You can reimplement
virtual void paint( QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const


text:
Q: Use a index and column from one lookup dataframe to create a new column in another dataframe I have a dataframe for looking up values:
ruralw2 = [[0.1,0.3,0.5], [0.1,0.2,0.8], [0.1,0.2,0.7], [0.1,0,0.3]]
rw2 = pd.DataFrame(data=ruralw2, columns=['city','suburbs','rural'],index=['low','med','high','v-high'])

and then I have a another dataframe where I want to get 'p' values based on data in rw2 dataframe:
df = pd.DataFrame(columns=['location','income','p'])
df['location'] = ['city','city','suburbs','rural','rural']
df['income'] = ['low','med','high','v-high','med']

What I expect is this:

It's possible to use for loop but its an antipattern in Pandas and I think there should be a better way.
for i in np.arange(df.shape[0]):
    df['p'][i] = rw2.loc[df['income'][i],df['location'][i]]

Another possibility is to write very long np.where(... logic but it doesn't feel right either and it wouldn't be very scalable.

A: you can use stack on rw2 and reindex with both columns income and location of df like:
df['p'] = rw2.stack().reindex(df[['income', 'location']]).to_numpy()
  location  income    p
0     city     low  0.1
1     city     med  0.1
2  suburbs    high  0.2
3    rural  v-high  0.3
4    rural     med  0.8

A: You can use reset_index to bring the income values into the data frame, followed by pd.melt to restructure it in your result format. You can then merge this new data frame with df
Step 1:
rw2_reset = rw2.reset_index()
rw2_reset

Step2:
rw2_melt = pd.melt(rw2_reset, id_vars='index', value_vars=['city', 'suburbs', 'rural'])
rw2_melt.rename(columns={'index':'income', 'variable':'location','value':'p'}, inplace=True)
rw2_melt

Step3:
result = pd.merge(df, rw2_melt, on=['location', 'income'], how='left').drop(columns='p_x').rename(columns={'p_y':'p'})
result


text:
Q: Autowiring in concrete classes of an abstract class than implements an interface I am using Spring boot and I have the following Task model
public class Task {
    private String name;
    private TaskType type; // ManualTask, AutomatedTask
    private boolean completed;
    //....other fields

    //getters and setters
}

A controller
@Controller
@RequestMapping("/api/task")
public class TaskController {

    @Autowired
    private TaskService taskService;

    @GetMapping("/{taskId}/handle")
    public String handle(Model model, @PathVariable("taskId") Long taskId) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        try {
            Task task = taskService.handle(taskId);
            model.addAttribute("task", task);
        } catch (Exception e) {
            return "errorpage";
        }
        return "successpage";
    }
}

I have an interface
public interface TaskService {

    Task findById(Long taskId);

    Task handleTask(Long taskId) throws ClassNotFoundException, InstantiationException, IllegalAccessException;

}

An abstract class implements the interface:
@Service
public abstract class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskRepository taskRepository;

    private static final String PATH_OF_CLASS = "com.task.service.impl";

    protected abstract Task doTypeSpecificTask(Long taskId);

    @Override
    public Task findById(Long taskId) {
        return taskRepository.findById(taskId).get();
    }

    @Override
    public Task handleTask(Long taskId) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        Task task = findById(taskId);
        TaskServiceImpl service = getHandlerService(task);
        return service.doTypeSpecificTask(taskId);
    }

    private TaskServiceImpl getHandlerService(Task task) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        String serviceClassName = PATH_OF_CLASS.concat(".").concat(task.getTaskType().getName()).concat("Service");
        Class<?> serviceClass = Class.forName(serviceClassName);
        if (!TaskServiceImpl.class.isAssignableFrom(serviceClass)) {
            throw new RuntimeException("Service class " + serviceClassName + " did not implements " + TaskServiceImpl.class.getName());
        }
        Object serviceObject = serviceClass.newInstance();
        TaskServiceImpl service = (TaskServiceImpl) serviceObject;
        return service;
    }

}

And concrete services that extend the abstract class
@Service
@Primary
public class ManualTaskService extends TaskServiceImpl {

    @Autowired
    private TaskRepository taskRepository;

    @Autowired
    private ManualTaskHandlerService manualTaskHandlerService;

    @Override
    protected Task doTypeSpecificTask(Long taskId) {
        Task task = findById(taskId);
        manualTaskHandlerService.handleManualTask(task);
        task.setCompleted(true);
        return taskRepository.save(task);
    }
}

@Service
public class AutomatedTaskService extends TaskServiceImpl {

    @Autowired
    private TaskRepository taskRepository;

    @Autowired
    private AutomatedTaskHandlerService automatedTaskHandlerService;

    @Override
    protected Task doTypeSpecificTask(Long taskId) {
        Task task = findById(taskId);
        automatedTaskHandlerService.handleAutomatedTask(task);
        task.setCompleted(true);
        return taskRepository.save(task);
    }
}

public interface TaskRepository extends JpaRepository<Task, Long> {

}

The ManualTaskService or AutomatedTaskService is selected dynamically based on the type of task on runtime.
Now, without the @Primary, I get the following error:
Field taskService in com.test.controller.TaskController required a single bean, but 2 were found:
- manualTaskService
- automatedTaskService

Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

With @Primary set in ManualTaskService, doTypeSpecificTask in ManualTaskService works but in AutomatedTaskService it fails because of automatedTaskHandlerService.handleAutomatedTask(task). Also calls to taskRepository from AutomatedTaskService fail.
I've tried using @Qualifier as well as defining all @Autowired in the abstract class as protected but nothing works. What am I doing wrong?

A: You should have different names to each Qualifier:
@Autowired
@Qualifier("manualTaskService")
private TaskServiceImpl manualTaskService;

@Autowired
@Qualifier("automatedTaskService")
private TaskServiceImpl automatedTaskService;

Which is defined in services:
@Service("manualTaskService")
public class ManualTaskService extends TaskServiceImpl {

@Service("automatedTaskService")
public class AutomatedTaskService extends TaskServiceImpl {

A: I solved the issue by using the factory pattern as mentioned in this link (thanks to @user7294900 for providing the link)
I completely removed the abstract class TaskServiceImpl. Instead I created two new interfaces ManualTaskService and AutomatedTaskService both extending TaskService interface
public interface ManualTaskService extends TaskService {
}

public interface AutomatedTaskService extends TaskService {
}

Then I created a TaskServiceFactory
@Component
public class TaskServiceFactory {

    @Autowired
    private ManualTaskService manualTaskService;

    @Autowired
    private AutomatedTaskService automatedTaskService;

    public TaskService getService(TaskType type) throws Exception {
        switch (type) {
        case MANUAL_TASK:
            return manualTaskService;
        case AUTOMATED_TASK:
            return automatedTaskService;
        default:
            throw new Exception("Unrecognized task type");
        }
    }
}

Next I created implementations for both ManualTaskService and AutomatedTaskService
@Service
public class ManualTaskServiceImpl implements ManualTaskService {

    @Autowired
    private TaskRepository taskRepository;

    @Autowired
    private ManualTaskHandlerService manualTaskHandlerService;

    @Override
    public Task findById(Long taskId) {
        return taskRepository.findById(taskId).get();
    }

    @Override
    public Task handleTask(Long taskId) throws Exception {
        Task task = findById(taskId);
        manualTaskHandlerService.handleManualTask(task);
        task.setCompleted(true);
        return taskRepository.save(task);
    }
}

@Service
public class AutomatedTaskServiceImpl implements AutomatedTaskService {

    @Autowired
    private TaskRepository taskRepository;

    @Autowired
    private AutomatedTaskHandlerService automatedTaskHandlerService;

    @Override
    public Task findById(Long taskId) {
        return taskRepository.findById(taskId).get();
    }

    @Override
    public Task handleTask(Long taskId) throws Exception {
        Task task = findById(taskId);
        automatedTaskHandlerService.handleAutomatedTask(task);
        task.setCompleted(true);
        return taskRepository.save(task);
    }

}

Finally I updated the controller to get the task type from the user and then use the TaskServiceFactory to get the correct service instance based on the type
@Controller
@RequestMapping("/api/task")
public class TaskController {

    @Autowired
    private TaskServiceFactory taskServiceFactory;

    @PostMapping("/{taskId}/handle")
    public String handle(Model model, @PathVariable("taskId") Long taskId, HttpServletRequest request) throws Exception {
        try {
            TaskType type = TaskType.valueOf(request.getParameter("type"));
            Task task = taskServiceFactory.getService(type).handleTask(taskId, request);
            model.addAttribute("task", task);
        } catch (Exception e) {
            return "errorpage";
        }
        return "successpage";
    }
}


text:
Q: Error in creating object of Class A with named variable A I have below class
export class TechnicalContactInfo {
    constructor(){
       this.Communication = [];
    }
/** @description ContactFunctionCode */PER01;
/** @description ContactName */PER02;
/** @description Communication */Communication: Communication[];
}

When i trying to create object of it as below
var TechnicalContactInfo:TechnicalContactInfo = new TechnicalContactInfo();

it is giving me error as below

[ts] Cannot use 'new' with an expression whose type lacks a call or
  construct signature.

Can someone help me to find why ?

A: The error is cause by the fact that you name the variable the same as the class. If we look at how a class is down-compiled to ES5, it may be a bit more obvious why the class declaration and the variable declaration cause a conflict:
var TechnicalContactInfo = /** @class */ (function () {
    function TechnicalContactInfo() {
    }
    return TechnicalContactInfo;
}());
var TechnicalContactInfo = new TechnicalContactInfo();

You can't define the TechnicalContactInfo because there already is a variable named TechnicalContactInfo holding the class constructor function. While for ES6 we can use the class syntax the same holds true, variables and classes share the current naming scope, and if you define a variable and a class with the same name you will get into problems.


text:
Q: Problem with retrieving XML via HTTP and writing to file I've written a small scraper that is meant to open up a connection to a PHP script on a remote server via HTTP and pump some XML it finds there into a local file.
Not exactly rocket science, I know.
The code below is the scraper in its entirety (cleaned up and anonymized).
This code works fine except for one small detail, it seems that no matter the size of the XML file (1 MB or 7 MB) the resulting XML file is always missing a small section at the end (600-800 characters).
Notes:

*

*If I open the php page in Firefox - I get the whole doc no problem.

*If I fire up wireshark and run the program below, I see the whole doc transferred across the wire, but not written down into the file.

using System;
using System.IO;
using System.Collections.Generic;
using System.Text;

namespace myNameSpace
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("BEGIN TRANSMISSION\n");
                writeXMLtoFile();
            Console.Write("END TRANSMISSION\n");
        }

        public static void writeXMLtoFile()
        {
            String url = "http://somevalidurl.com/dataPage.php?lotsofpars=true";
            TextWriter tw = new StreamWriter("xml\\myFile.xml");
            tw.Write(ScreenScrape(url));
            Console.Write(" ... DONE\n");
            tw.Close();
        }
        public static string ScreenScrape(string url)
        {
            System.Net.WebRequest request = System.Net.WebRequest.Create(url);
            using (System.Net.WebResponse response = request.GetResponse())
            {
                using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream()))
                {
                    return reader.ReadToEnd();

                }
            }
        }
    }
}

Should I be using a different Writer? I've tried both TextWriter and StreamWriter to the same effect.
Kind regards from Iceland,
Gzur

A: Try:
XmlDocument doc = new XmlDocument();
doc.Load(url);
doc.Save(filename);

It really is that easy (with some error handling obviously). The .Net framework should do everything for you. I jumped through hoops a month or so ago trying to do the same thing and kicked myself when I read the help file on XmlDocument ;)

A: Additionally, if really all you want to do is download a page to the file system, investigate the WebClient.DownloadFile method :)

A: It could be as simple as not calling Flush() on your StreamWriter, but why make life hard for yourself? Replace the whole writeXMLtoFile function with this:
public static void writeXMLtoFile()
{
    string url = "http://somevalidurl.com/dataPage.php?lotsofpars=true";
    string xml = ScreenScrape(url);
    File.WriteAllText("xml\\myFile.xml", xml);
}

This way, you can also use the debugger to see what's going on (inspect the xml variable).


text:
Q: Scattering of light rays off a corrugated surface I am currently facing the following problem:
Suppose I describe the shape of a corrugated surface with a certain function:
\begin{equation}
y_\mathrm{surf}=A\sin(kx);
\qquad
x\in(-\infty,\infty)
\end{equation}
Further supposing that there is an observer, positioned at a point $P=(x_0,y_0)$ somewhere above the surface. If light rays are arriving at an angle $\theta_i$ with respect to e.g. the $x$ axis and are scattered from the surface, what is the average angle of scattered light rays $\theta_{f,\mathrm{avg}}$ (with respect to e.g. the $x$ axis) the observer will measure at point $P$?
EDIT: Furthermore, suppose that $y_0 \gg A$.


text:
Q: How can I get the list of flavor dimensions in build.gradle? In my build.gradle, I have
android {
    flavorDimensions "first", "second"
    productFlavors {
        a {
            dimension "first"
        }
...
}

How can I get the list of flavorDimensions in the same order that gradle will use when creating the combinations of flavors?

A: It's available as an ArrayList from android.flavorDimensionList.


text:
Q: Connect to Apache Kafka brokers running in Docker Container I am trying to deploy Apache Kafka (not Confluent Kafka) on docker containers and connect to it using kafka-python's producer and consumer api. The producer api and consumer api should be able to run outside the docker container.

The pipeline consists a zookeeper instance and 3 Kafka brokers, each residing in a separate container. The following is the docker-compose code which I use to initialize the containers.
services:
zookeeper-1:
    container_name: zookeeper-1
    image: zookeeper:2.7.0
    build:
      context: ./zookeeper
    volumes:
    - ./config/zookeeper-1/zookeeper.properties:/kafka/config/zookeeper.properties

kafka-1:
    container_name: kafka-1
    image: kafka:2.7.0
    build:
        context: .
    volumes:
    - ./config/kafka-1/server.properties:/kafka/config/server.properties
    - ./data/kafka-1/:/tmp/kafka-logs/

kafka-2:
    container_name: kafka-2
    image: kafka:2.7.0
    build:
        context: .
    volumes:
    - ./config/kafka-2/server.properties:/kafka/config/server.properties
    - ./data/kafka-2/:/tmp/kafka-logs/

kafka-3:
    container_name: kafka-3
    image: kafka:2.7.0
    build:
        context: .
    volumes:
    - ./config/kafka-3/server.properties:/kafka/config/server.properties
    - ./data/kafka-3/:/tmp/kafka-logs/

I am able to produce and consume message using cli within docker image.

I would like to be able to access it from outside the docker containers. I know that it requires modifying the docker-compose script by adding listeners but I am new to Docker and have not been able to correctly add the listeners.
Please suggest the additions that are required so that I may access Kafka from outside the containers, on the same machine.

P.S.: I have already visited most of the kafka docker container discussions on SO, including "Connect to Kafka running in Docker","Interact with kafka docker container from outside of docker host [duplicate]", and they do not answer my query.

A: You can add environmental variables to each Kafka build that allow internal DNS access via one port and external access via another. For example, for kafka-1 we can expose a port and add environmental variables that will make Kafka listen for connections via the localhost (i.e. Python producer running on your host machine):
kafka-1:
  container_name: kafka-1
  image: kafka:2.7.0
  build:
    context: .
  volumes:
  - ./config/kafka-1/server.properties:/kafka/config/server.properties
  - ./data/kafka-1/:/tmp/kafka-logs/
ports:
  - 9092:9092
environment:
  KAFKA_ADVERTISED_HOST_NAME: kafka-1
  KAFKA_BROKER_ID: 1
  KAFKA_ZOOKEEPER_CONNECT: zookeeper-1:2181
  KAFKA_LISTENERS: PLAINTEXT://kafka-1:29092,PLAINTEXT_HOST://localhost:9092
  KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka-1:29092,PLAINTEXT_HOST://localhost:9092
  KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
  KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
  KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1

I do see that you are doing a docker build so can't be sure of your configuration and setup, but you can add the same settings to your mounted configuration file server.properties instead if environmental variables are not suitable.
I'm also assuming zookeeper is serving on port 2181, and the above does not consider security requirements etc.
Kafka listeners use the same name they are connected to with, and when connection is made, it will only succeed if the name associated with that listener matches the name it was connected with. For example:

*

*Kafka-python client connects to "localhost:9092" running on host machine

*Kafka server relays "localhost" back as that is the name associated with 9092

*Connection succeeds

However, this will not work:

*

*Kafka-python client running remotely, connecting via "SERVERIP:9092" to host machine

*Kafka server relays "localhost" back as that is the name associated with 9092

*Connection fails as the names do not match

If you need remote access, change localhost to 0.0.0.0 in your Kafka configuration instead.
To use multiple brokers in this docker-compose setup, use something like 9092 for kafka-1, 9093 for kafka-2 and 9094 for kafka-3, and expose those ports respectively. Then your bootstrap servers are just:
localhost:9092, localhost:9093, localhost:9094
You can setup multiple listeners too, so you can have one port for localhost access, one for internal network DNS access (within docker-compose) and another for remote access, and change security settings for each type. This link provides more information on that.


text:
Q: Why can't the Yesod session cookie be hijacked? The Yesod book says

The encryption prevents the user from inspecting the data, and the
  signature ensures that the session can be neither hijacked nor
  tampered with.

It's not clear to me why this is the case. If an eavesdropper gets hold of the cookie as it is sent from the server and uses it before the legitimate user makes another request, won't the session end up being hijacked?
It seems to me that the only way to really prevent session hijacking is to use SSL throughout. But if I do so then the signing and encryption done by Yesod ends up being unnecessary overhead (EDIT: overhead as far as preventing hijacking is concerned. As @sr_ points out in the comments, it is still useful otherwise).

A: That's a good catch. This used to be more accurate, when we would include the IP address of the client in the cookie to prevent hijacking. Combined with the anti-tampering protections, this made it basically impossible for a MITM attack to work unless you were NATed behind the same router or using the same proxy.
Unfortunately, we had to disable that protection due to concerns about proxies as well. It's possible for a single user's requests to come from multiple IP addresses due to intermediate proxy servers. I don't have data to tell how often this happens, but there was enough concern about this security feature causing breakage that we disabled it.
Thank you for bringing this up, I've corrected the book.


text:
Q: Flutter/Firestore - Error: A value of type 'List Function(QuerySnapshot)' can't be assigned to a variable of type 'List' I am trying to create a dynamic list view which displays document ids from Firebase. I have created the list of events from snapshot:
    List<String> _eventListFromSnapshot(QuerySnapshot snapshot) {
  return snapshot.documents.map((doc) {
    return doc.documentID == null ? doc.documentID : ' ';
  }).toList();
}

But when I come to build the stream using this code:
    Stream<List<String>> get events {
  return DatabaseService().eventsCollection.snapshots().map((event) => _eventListFromSnapshot);
}

I get the following error:
Error: A value of type 'List<String> Function(QuerySnapshot)' can't be assigned to a variable of type 'List<String>'.

A: You forgot calling function _eventListFromSnapshot.
Fix like this
Stream<List<String>> get events {
  return DatabaseService()
    .eventsCollection
    .snapshots()
    .map((snapshot) => _eventListFromSnapshot(snapshot));
}

or simpler:
Stream<List<String>> get events {
  return DatabaseService()
    .eventsCollection
    .snapshots().map(_eventListFromSnapshot);
}

A: I think we have to do it explicitly.
Try something like this in your method.

List<String> _eventListFromSnapshot(QuerySnapshot snapshot) {
    List<String> docIDs = [];
    for(int i = 0; i < snapshot.documents.length; i++){
        String value = snapshot.documents[i].documentID ?? " ";
        docIDs.add(value);
    }
    return docIDs;
}

or else, we might have an issue in this line,
Stream<List<String>> get events {
  return DatabaseService().eventsCollection.snapshots().map((event) => _eventListFromSnapshot(event));
}

We have to call the function, instead of assigning it maybe.
Hope this solves your issue.


text:
Q: Angular 4 Server-side rendering with Node.js (ReferenceError: document is not defined) I followed the tutorial here to implement a server-side rendering Angular 4 app. However, I don't know how to solve the problem related to "document is not defined" in Node.js. I know that Node.js doesn't have a DOM since it is not a "browser". However, I seriously need to render the app in server for SEO, yet I don't know how to solve these problem. I can't change the code as it is a third party code, hmmm... any suggestion?
/var/www/nodejs/example.com/node_modules/custom-event/index.js:24
'function' === typeof document.createEvent ? function CustomEvent (type, params) {
                  ^
ReferenceError: document is not defined at Object.<anonymous> (/var/www/nodejs/example.com/node_modules/custom-event/index.js:24:23)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Module.require (module.js:513:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/var/www/nodejs/example.com/node_modules/crossvent/src/crossvent.js:3:19)
    at Module._compile (module.js:569:30)

I search quite a few posts related to "document is not defined", and most of them just explain that node.js doesn't have a DOM, but without any solution provided.
If you need my server.ts, then here is it.
import 'reflect-metadata';
import 'zone.js/dist/zone-node';
import { platformServer, renderModuleFactory } from '@angular/platform-server';
import { enableProdMode } from '@angular/core';
import { AppServerModuleNgFactory } from '../dist/ngfactory/src/app/app.server.module.ngfactory';
import * as express from 'express';
import { readFileSync } from 'fs';
import { join } from 'path';
const PORT = 4000;

enableProdMode();

const app = express();

let template = readFileSync(join(__dirname, '..', 'dist', 'index.html')).toString();

app.engine('html', (_, options, callback) => {
    const opts = { document: template, url: options.req.url };
    renderModuleFactory(AppServerModuleNgFactory, opts)
        .then(html => callback(null, html));
});

app.set('view engine', 'html');
app.set('views', 'src')

app.get('*.*', express.static(join(__dirname, '..', 'dist')));

app.get('*', (req, res) => {
    res.render('index', { req });
});

app.listen(PORT, () => {
    console.log(`listening on http://localhost:${PORT}!`);
});

Thanks in advance.

A: NodeJs does not support window, document, navigator types. So, the solution would be to copy the folder into another directory for example in src/server-mocks/ and replace all document types with global in the index.js file and configure webpack.server.config.js by adding the following code..
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');

 new NormalModuleReplacementPlugin(
      /crossvent(\\|\/)src(\\|\/)crossvent.js/,
      path.join(__dirname, 'src/server-mocks/crossvent/src/crossvent.js')
    ),