text:
Q: Rails updating multiple models on a single form Im writing a form which uses formtastic to manage the BusinessUnit model, however when creating a new BusinessUnit it also has to create a number of other record types. The associations between the models are as below:
class BusinessUnit < ActiveRecord::Base
  has_many :business_unit_sites
  has_many :locations

class BusinessUnitSite < ActiveRecord::Base
  belongs_to :site
  belongs_to :business_unit

class Site < ActiveRecord::Base
  has_many :locations
  has_many :business_unit_sites

class Location < ActiveRecord::Base
  belongs_to :business_unit
  belongs_to :site

When a BusinessUnit is created, a Site must also be created using BusinessUnitSite as a join table. In addition a Location record should be created which must hold a foreign key to the new Site record and this is where Im having problems.
I can create a new Location using a nested form (below) but the Site will have to be created manually.
<%= semantic_form_for @business_unit do |f| %>
  <%= f.inputs do %>
    <%= f.input :name %>
    <%= f.input :business_unit_id %>
    <%= f.input :business_unit_group, :include_blank => false %>
    <%= f.input :business_unit_type %>
    <%= f.input :tax_region, :include_blank => false %>
    <%= f.semantic_fields_for :locations do |l| %>
      <%= l.input :name, :label => "Location Name" %>
    <% end %>
  <% end %>
  <%= f.buttons %>
<% end %>

What is the best way to create the Location, Site records and ensure that Location holds the foreign key of the newly created Site?

A: You probably want to do something like using the "fields_for" approach for the sub-objects in your form.
See this related answer:
Multiple objects in a Rails form
More info about fields_for:
http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html
http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for


text:
Q: UITableView Loaded from MutableArray turn in to a tickbox list I have an tableview which is loaded from a mutablearray as listed below. However I need to asign each item in the array an ID and have a tickbox next to the item. Basically it's preferences for our search, it lets users prioritise by whichever tickboxes are ticked. So I'll want to save which items are ticked to a plist or similar.
Heres how the array is loaded:
arryTableIconsText =     [[NSMutableArray alloc] init];

[arryTableIconsText addObject:@"Facilities for partially sighted or blind people"];
[arryTableIconsText addObject:@"An 'assistance dogs welcome' policy"];
[arryTableIconsText addObject:@"Disabled access facilities for wheelchair users (with assistance)"];
*more items added here*

arryTableIcons = [[NSMutableArray alloc] init];

[arryTableIcons addObject:@"visuallyImpaired_off.png"];
[arryTableIcons addObject:@"guidedogs_off.png"];
[arryTableIcons addObject:@"wheelchairassist_off.png"];
    *more items added here*

And then loaded in to a table like so:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }

    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0];

    cell.textLabel.text = [arryTableIconsText objectAtIndex:indexPath.row];
    cell.imageView.image = [UIImage imageNamed:[arryTableIcons objectAtIndex:indexPath.row]];

    return cell;
}

The result is the following:

But I don't know where to go from here to convert it in to a checkbox to the right of each cell with the ID saved?
Any tips really will be appreciated, Tom

A: Use an NSMutableIndexSet instance variable and populate it with the index of the cells being checked.
Then in the cellForRowAtIndexPath method, set the accessory type of the cell to UITableViewCellAccessoryTypeCheckmark or UITableViewCellAccessoryTypeNone depending on whereas the indexPath.row is in the NSMutableIndexSet or not.
Finally, when the cell is tapped, add the indexPath.row to the indexset if not alread, or remove it if it already was present, to toggle the status of the corresponding cell, then call reloadData on the tableView.
I see in your code too that you are not familiar with the reuse mechanism of UITableViewCells. You should read the "Table View Programming Guide" in Apple's documentation and learn how to implement cellForRowAtIndexPath in a more efficient and reactive way (in term of reactivity and memory footprint)

Example
// Let selectedCellIndexes be an instance variable in your .h of type NSMutableIndexSet*
// Initialize it (probably at the same place you initialise your texts & icons, once for all, probably in your init method
selectedCellIndexes = [[NSMutableIndexSet alloc] init];

Then to fill the cells:
-(UITableViewCell*)tableView:(UITableView*)tv cellForRowAtIndexPath:(NSIndexPath*)indexPath {
  // Try to recycle and already allocated cell (but not used anymore so we can reuse it)
  UITableViewCell* cell = [tv dequeueCellWithReuseIdentifier:...];
  if (cell == nil) {
    // If we didn't manage to get a reusable (existing) cell to recycle it
    // then allocate a new one and configure its general properties common to all cells
    cell = [[[UITableViewCell alloc] initWithStyle:... reuseIdentifier:...] autorelease];

    // ... configure stuff that are common to all your cells : lineBreakMode, numberOfLines, font... once for all
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0];
  }

  // Then here change the stuff that are different between each cell
  // (this code will be executed if the cell has just been allocated as well as if the cell is an old cell being recycled)
  cell.textLabel.text = [arryTableIconsText objectAtIndex:indexPath.row];
  cell.imageView.image = [UIImage imageNamed:[arryTableIcons objectAtIndex:indexPath.row]];
  cell.accessoryType = [selectedCellIndexes containsIndex:indexPath.row] ? UITableViewCellAccessoryTypeCheckmark : UITableViewCellAccessoryTypeNone;

  return cell;
}

And finally, to toggle the checkmarks:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  if ([selectedCellIndexes containsIndex:indexPath.row]) {
    [selectedCellIndexes removeIndex:indexPath.row];
  } else {
    [selectedCellIndexes addIndex:indexPath.row];
  }
  [tableView reloadData];
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Chow ring of projective bundle Given $X$, and a locally free sheaf $\mathcal{F}$ of rank $n$ on it. We have the induced map
$f:\mathbb{P}(\mathcal{F})\rightarrow X$. Let $\phi$ be the divisor associated to the line bundle $\mathcal{O}_{\mathbb{P}(\mathcal{F})}(1) $.
Is it true $f_{\ast}(\phi^{n-1})=[X]$ in the Chow ring $A^\ast(X)$? Also, is trace map $A^{top}(.)\rightarrow\mathbb{Q}$ compatible with pushforward $f_{\ast}$?
Thank you.

A: The class $\phi^{n-1}$ has degree $1$ when restricted to each fibre of $f$ since $H^{n-1}$ has degree $1$ on $\mathbb{P}^{n-1}$, where $H$ is the class of a hyperplane, i.e. a divisor associated to $\mathcal{O}(1)$. It follows that $f_*(\phi^{n-1})$  is indeed $[X]$ in $A^*(X)$.
I suppose what you call the trace map is just the degree map $A^{top}(X) \to \mathbb{Z}$ (for a proper variety $X$). It follows immediately from the definition of proper pushforward that it is compatible with $f_*$.


text:
Q: @Context HttpServletRequest scope in Jersey ContainerResponseFilter I am writing an Jersey Response filter. I am using Jersey 1.17. I want to get access to some attributes of the httpServletRequest in the filter API.  The way what i am doing right now is as below.  Is it safe to inject the servletRequest like in the snippet below or will this cause some kind of concurrency issues? If there are multiple requests coming in conncurrently, will the servletRequest  in different requests overwrite each other?  Thanks for your hlep.
public class LoggingFilter implements ContainerResponseFilter {
@Context private HttpServletRequest servletRequest;
@Override
public ContainerResponse filter(final ContainerRequest req, final ContainerResponse resp) {
String s =  this.servletRequest.getAttribute("xxx");
....
}
}

A: You're safe. When you're injecting HttpServletRequest / HttpServletResponse you're not dealing with a particular instance but rather with a proxy through which you're invoking calls on a real instance stored in a ThreadLocal object. Each request is processed by a separate thread which has access to it's own HttpServletRequest / HttpServletResponse. Beside injecting HttpServletRequest / HttpServletResponse you can also inject ThreadLocal<HttpServletRequest> / ThreadLocal<HttpServletResponse> and through '#get()` method you can obtain the real request / response instances intead of proxies.

A: Section 9.1 (latest, 5.1 previously) Concurrency of the JAX-RS specification states:

Context is specific to a particular request but instances of certain
  JAX-RS components (providers and resource classes with a lifecycle
  other than per-request) may need to support multiple concurrent
  requests. When injecting an instance of one of the types listed in
  Section 9.2, the instance supplied MUST be capable of selecting the
  correct context for a particular request. Use of a thread-local proxy is a common way to
  achieve this.

So, as per the specification, JAX-RS implementations (e.g. Jersey) are required to ensure that the context is safe. Keep doing what you're doing.
See also: Extract request attributes from container request of Jersey


text:
Q: Flutter - Resume a screen after navigating back to it I have two screens: Screen A (List of chats), Screen B (a chat with many messages)
I am looking for a way to save the scrolling position of screen B, after I navigate to screen A then navigate back to screen B
I investigated the use of ScrollablePositionedList to listen to the scrolling and save it somewhere in the state. Then jumps back the index of the message when coming back to screen B. But I feel this will very heavy on the performance.
That's why I am wondering if there is a way, to Resume a screen (not the whole app) and save the scrolling position and everything when navigating back/forth.


text:
Q: why I get this error: Maximum call stack size exceeded I use react native toast message.
https://github.com/calintamas/react-native-toast-message

It works but I got this error:
why I get this error: Maximum call stack size exceeded

App.tsx
  return (
  <Suspense fallback={<Text>Loading...</Text>}>
    <Provider store={store}>
      <NavigationContainer>
        <Host>
          <NativeStackWrapper />
          <Toast position='bottom' ref={(ref) => Toast.setRef(ref)} />
        </Host>
      </NavigationContainer>
    </Provider>
  </Suspense>
  );

Register.tsx
    onSubmit: (val) => {
      Toast.show({
        type: 'success',
        position: 'bottom',
        text1: 'Du hast erfolgreich ein Account erstellt!',
        text2: 'Du kannst nun ungestört unsere Platform nutzen.',
        visibilityTime: 4000,
        autoHide: true,
        topOffset: 20,
        bottomOffset: 40,
        onShow: () => {},
        onHide: () => Toast.hide(),
      });

    }

How can I solve this issue ?
.......................................................................................................................


text:
Q: Convert video from .mp4 to .ogg I am using ffmpeg version 0.11.1 Copyright (c) 2000-2012 the FFmpeg developers . I need to convert a file .mp4, to .ogg format. I am on Mac OS X, and I have tried this so far:
ffmpeg -i sample_mpeg4.mp4 -acodec vorbis -vcodec libtheora -f ogg output.ogv

I am getting: Unknown encoder 'libtheora'
ffmpeg -i sample_mpeg4.mp4 -acodec libvorbis -vcodec --enable-libtheora output.ogv

I am getting: Unknown encoder '--enable-libtheora'
ffmpeg -i sample_mpeg4.mp4 -acodec libvorbis -vcodec libtheora -f ogv output.ogv

I am getting:
[NULL @ 0x7f81bb00f800] Requested output format 'ogv' is not a suitable output format
output.ogv: Invalid argument

ffmpegtheora is not an option as it can not be install on the server.

A: Use Homebrew package manager
Install Homebrew in command line
$ ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"

Install ffmpeg with libtheora support
$ brew install ffmpeg --with-theora --with-libvorbis

Other options are listed here
$ brew options ffmpeg

Hope it helps others or future me ;)

A: Your FFmpeg version is missing the required encoders, libtheora for Theora video and libvorbis for Vorbis audio.
You can only add these encoders by either

*

*compiling them with FFmpeg, or

*installing an executable that bundles them already.

For you the easiest choice would be to download a static version from the FFmpeg download page. They all come with libtheora and libvorbis, regardless of the operating system they were built for.
What you then need to do is extract the download archive and simply run the ffmpeg binary that was included. The correct syntax would be:
ffmpeg -i in.mp4 -c:v libtheora -c:a libvorbis out.ogv

If you want to change the quality for either audio or video, you can change the bit rate, e.g. with -b:v 1M or -b:a 192k. Play with those values and use a higher or lower bitrate depending on the quality or file size constraints you have.
You can also use VBR (constant quality) with -q:v, where values range from 0 to 10 (higher is better), with 7 being recommended. The audio quality can be set with -q:a, again with values from 0 to 10, where 4 is recommended and corresponds to roughly 128 kBit/s.
Note that --enable-libtheora is a configuration option and doesn't work when calling ffmpeg.

A: --enable-libtheora should be used when building ffmpeg from source, not while trying to run the program. You should try rebuilding ffmpeg (using the latest source of course ) and adding support for libtheora during configure (./configure --enable-libtheora etc....)
If you need help on building from source, there's lots of stuff on google, but it boils down (for you) enabling the libraries you need, you can see here and _http://jungels.net/articles/ffmpeg-howto.html for starters.


text:
Q: Setting Ace Editor Cursor Position After Page Load Question: Is there a way to execute Ace editor commands after the editor has been fully loaded?
I am attempting to set the cursor position of the Ace editor after a page load/re-load. The content of the editor is set in one of the callbacks as the editor is being loaded. Setting the cursor position here doesn't work, since the rest of the editor is still being loaded (like the VirtualRenderer), and it resets the editor content to display from the top.
The code below works, it sets the content, code folds, and cursor position. However, the cursor ends up off the screen, with the content displayed from the top. After the editor fully loads, I would like it to scroll to the cursor.
//Put the content of the file into the editor
editor.session.setValue(content);

//Restore code folds
for(var i = 0; i < folds.length; i++) {
  editor.session.addFold("...",folds[i]);
}

//Put the cursor in the correct place
editor.gotoLine(cursor.row,cursor.column, true);
editor.renderer.scrollToRow(cursor.row);

A: Could you try this
//Put the content of the file into the editor
editor.session.setValue(content);

//Restore code folds
for(var i = 0; i < folds.length; i++) {
  editor.session.addFold("...",folds[i]);
}

//Put the cursor in the correct place
editor.focus();
editor.gotoLine(cursor.row,cursor.column, true);
editor.renderer.scrollToRow(cursor.row);


text:
Q: What source to use for data grid when items will be removed? I have a project (WPF, c#) where I input some data press a button and create a "Ticket" class item and add take item to the ObservableCollection which puts them on the datagrid.
This is working fine, but I now have cause to remove certain items from the Collection where there is an error in the data. This has then led to problems to being able to iterate through the collection, as in I can not!
Reading around it seems that I am misusing the ObservableCollection by removing items from it, so my question is what should I be using in this case?


text:
Q: How can I make an element as wide as the page width including scrolling? In the snippet below, the footer takes the whole width of the visible part of the page, but as soon as scrolling happens, it is apparent that the footer is shorter than the whole page, because of the scrolling.
How can I express the intent of "making a element as wide as the whole page, incuding the area not visible because of scrolling"?

<style type="text/css" media="screen">
* {
  margin: 0;
}
footer {
  width: 100%;
  border: 1px solid black;
}
</style>
<main>
mainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmain
</main>
<footer>
  footer content
</footer>

What puzzles me, is that, as far as I can tell from the dev tools, the whole html element is just as wide as the initially visible area; if I scoll a bit to the right and then hover with the mouse on the <html> element in the Elements tab of Chrome dev tools, I see the the blue-ish overlay only covers the original part of the view, and not the part become visible after scrolling:

A: The issue isn't that the footer isn't extending the full width: it's that the text element you have is wider than its container.
The width % of the footer is being defined by its parent element (in this case main HTML element, which is getting its width from the screen). The text, on the other hand, is not being contained and is running "out of bounds" so to speak. If you hide the overflow on the parent element of the text the issue is fixed.
One reason not to use breakword is that I'm assuming your real-life use case isn't a single line of text with no breaks and is more likely an image or other element that is extending beyond the document width.

<style type="text/css" media="screen">
main {
  overflow-x: hidden; //hide the page overflow
}
* {
  margin: 0;
}
footer {
  width: 100%;
  border: 1px solid black;
}
</style>
<main>
mainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmain
</main>
<footer>
  footer content
</footer>

A: The problem is that 'mainmain...' is considered as one word as it has no intervals. Adding word-wrap: break-word; solves the problem.

main {
    word-wrap: break-word;
}
footer {
  width: 100%;
  border: 1px solid black;
}
<main>
mainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmainmain
</main>
<footer>
  footer content
</footer>

A: go to your css code and do.
/* Changing a little bit of CSS code */
main {
   /* Setting The Word Warp To Break Word. */
   word-wrap: break-word;
}

Cheers..
Ben.


text:
Q: Vim popup window not showing on successive events I have the following plugin I wrote to test popup windows
"plugin/morning/morning.vim"
augroup morning_command_line_popup
    autocmd!
    au CmdlineLeave * call morning#close()
    au CmdlineEnter * call morning#open()
    au CmdlineChanged * call morning#update()
augroup END

"autoload/morning.vim"
function morning#open()
    let opt = {}
    let opt.border = []
    let opt.minwidth = &columns / 3
    let g:morning_window_handle = popup_create(":echo 'hi'", opt)
endfunction

function morning#close()
    call popup_close(g:morning_window_handle)
endfunction

function morning#update()
    call popup_show(g:morning_window_handle)
endfunction

The first time I enter the command line, the popup window appears. Every successive time that I enter the command line, it doesn't appear. I know the events are being fired and the functions are being called because if I put echom commands in the functions the messages show. Anyone know what could be wrong?

A: I figured out that if I redraw after showing the popup window, it seems to work consistently. I don't know if there's a reason why it won't redraw normally, or if doing this is extremely inefficient. This also has the side effect of overwriting wildmenu.
function morning#open()
    let opt = {}
    let opt.border = []
    let opt.minwidth = &columns / 3
    let g:morning_window_handle = popup_create(":echo 'hi'", opt)
    redraw
endfunction

function morning#close()
    call popup_close(g:morning_window_handle)
endfunction

function morning#update()
    call popup_settext(g:morning_window_handle, string(getcmdline()))
    call popup_show(g:morning_window_handle)
    redraw
endfunction


text:
Q: How can I program MATLAB to calculate the argument of a cubed tangent function? I need to solve tan^3(w)=tan(s) for w where s= 1.5 radians or 16.845 degrees. I need to write a line of MATLAB code for this operation but do not know an equivalent form of the equation.

A: solve('tan(x)^3==tan(1.5)','x')

Answer:
                                      1.1783511187702876557436189917532
- 1.3391755593851438278718094958766 + 0.35610550401885024116569451380696*i
- 1.3391755593851438278718094958766 - 0.35610550401885024116569451380696*i

One real solution, and two complex solutions.
(This was tested in Matlab R2012a)

A: To solve the equation without toolboxes, you can use e.g. fzero to find where both sides of the equation are equal.
%# define the function that should be equal to zero
%# i.e. subtract the sides of the equation from one another
fun = @(x)tan(x)^3-tan(1.5)

%# solve the function with initial guess 0
fzero(fun,0)
ans =
    1.1784

A: You could also use:
w = atan(tan(1.5)^(1/3))


text:
Q: How to calculate what percentage of 228 is 199? I'm a simple man who doesn't know much math. Sometimes in my work and life I've to do math calculations. Today was one of those days and I've spent the last hour trying to figure this out.
Look. Let's say the old pricing of a set of screwdrivers was \$228. I want to sell them for a new price of \$199. What is the discount that I apply?
I'm using various methods to find it, but I've no idea what I'm doing and which is the right way.
Method 1
I divide the discount \$29 by the old price:
$$\frac{228-199}{228}$$
I get 13% off.
Method 2
I divide the discount \$29 by the new price:
$$\frac{228-199}{199}$$
I get 15% off.
Method 3
I divide the new price \$199 by the old price \$228
$$\frac{199}{228}$$
I get 13% off.
Method 4
I divide the discount \$29 by the old:
$$\frac{228-199}{228}$$
I get 13% off.
So the discount is either 13% or 15%. Which is it and which is the right method?

A: You would normally (probably always) measure a discount as a fraction of the original price. In your example, 13%
If we measure the discount as a fraction of the new price, the discount could be more than 100% which doesn't sound right. (Old price \$100, new price \$50. You would probably agree that this is a 50% discount, not a 100%.)

A: Methods 1 and 4 (have you noticed?) are identical, and both are correct.
A discount is always written as a percentage of the original price. If the original price is A and the new price is B, then the discount = 1 - B / A.  This is equivalent to your methods 1, 3, and 4.
For example:
A = 100
B = 25
Discount = 1 - (25 / 100) = 1 - 1/4 = .75, or 75%.

A: The original price is 228\$, the new price is 199\$. Therefore, the discount is 29\$ in absolute terms.
Measured again by the original price (the one you are giving a discount on), the relative discount is
$$\frac{29$}{228$}\times 100\% \approx 12.7\% $$
which I feel is fair to round up to $13\%$ for the purposes of advertising (beware, though, that laws may apply which say otherwise).
The general method to calculate the relative (percentage) discount on the original price is to divide the absolute discount by the original price (after all, you are giving "X % off the original price").

A:
How to calculate what percentage of 228 is 199?

Algebra simplifies the question. Let the percentage be $x$. Now, ask $what~\%$ of Original Price (228) is equal to the discounted price. Assign a variable (say $x$) to this. Therefore:
$$\frac{x}{100}\times 228 = 199$$
$$x=\frac{199\times 100}{228}=87.28\%$$
To find discount %, you can let discount % be $y$ and proceed similarly :
$$\frac{y}{100}\times228=228-199=29$$
$$y=\frac{2900}{228}=12.719\%$$


text:
Q: Help on understanding how _id works for Mongoose So I've got a schema for a record  that is shown below that will record three different types of events:
(an example of one record that would be created that would be a segment in the test log) (log just holds an array of objects)
{
                        date_started: {type: Date, default: Date.now},
                        date_ended: null,
                        _id: //idk,
                        type: 'test',
                        log: [],
}

When one is created it receives its specific type (of which there are 3). How would I set up unique serial ids for each type? Would I need to use individual schemas?
Trying to explain in a different way:
I've got three logs to keep that all take identical inputs. How would I keep the serial number separate if I used _id? I'm rather new to MongoDB and any direction you can point me in would help. Thank you!


text:
Q: How to exclude vendor module peerDependencies from export in Webpack? Question
When exporting a bundle in Webpack, how can I exclude 3rd-party module's peerDependency? (not 3rd-party module itself)
Background
I would like to create an UIkit with customized components on top of angular-material framework. With Webpack, I can bundle my customzied components and angular-material together into something like uikit.js, and then port to other application later on. However, I don't want to include angular module itself into this uikit.js.
Issue
It seems that Webpack is "clever" enough to notice that angular module is a dependency of angular-material module, and thus would export both angular module and angular-material module to the bundle. One can either use config.externals: {'angular': 'angular'} or new webpack.IgnorePlugin(/angular$/) to exclude angular module which are explicitly require in the app, but for peerDependency (i.e. the one require inside angular-material), it would still include it.
So, how could I exclude this 3rd-party depended modules out from export?
Example:
// app.js
var angular = require('angular');
var material = require('angular-material');

// ... other application logic

// webpack.config.js
var webpack = require('webpack');

module.exports = {
  entry: {
    app: './app.js'
  },
  module: {
    loaders: [
      // some module loaders
    ]
  },

  // This only excludes the angular module require by the app, not the one require by the angular-material
  externals: {'angular': 'angular'},

  plugins: [
    // This is the same as externals, only the one required by app.js would be excluded
    new webpack.IgnorePlugin(/angular$/)
  ]
};

A: In the webpack (version 4) config, I export vendor apps into a vendor bundle and chunk all like this:
entry: {
  app: './app.js',
  vendor: [ 'angular', 'angular-material', '...' ],
},
optimization: {
  splitChunks: {
    chunks: 'all',
  }
},

Basically, this  indicates which chunks will be selected for optimization and all means that chunks can be shared even between async and non-async chunks.  Furthermore, How your modules are built and how you handle dependancies can further streamline your chunk size.
In addition you can provide a function whose return value will indicate whether to include each chunk:
module.exports = {
  //...
  optimization: {
    splitChunks: {
      chunks (chunk) {
        // exclude `my-excluded-chunk`
        return chunk.name !== 'my-excluded-chunk';
      }
    }
  }
};

Here is a link to webpack explaining the splitChunks plugin.


text:
Q: Using a user key in a service request? I am coding a SOAP/WSDL Web Service.
And I am connecting to the server via:
Service s = Service.create(url, qname);
So for authentification I have a user key.
How to put it as attribute in the Service request?


text:
Q: Invalid argument supplied for foreach() - using glob Today i have a problem with my script, my script should search for (.css files)
I've used a code to:

*

*Search for all subfolders in a root folder

*Make all paths of subfolders in an array

*by using foreach(){glob....}, the script should found all paths of css files

Here is my code :
$path = '';
$stack[] = $dir;

while ($stack) {
    $thisdir = array_pop($stack);

    if ($dircont = scandir($thisdir)) {
        $i=0;

        while (isset($dircont[$i])) {
            if ($dircont[$i] !== '.' && $dircont[$i] !== '..') {
                $current_file = "{$thisdir}/{$dircont[$i]}";

                if (is_dir($current_file)) {
                    $path[] = "{$thisdir}/{$dircont[$i]}";
                    $stack[] = $current_file;
                }
            }
            $i++;
        }
    }
}

$path[] = $dir;
foreach($path as $dirname){
    $add = glob($dirname . '/*.css');

    foreach($add as $file){
        $code = file_get_contents($file);
        $code_arab = arabicer($code);
        file_put_contents($file,$code_arab);
    }
}

When i start my script i found an waning message:

Warning: Invalid argument supplied for foreach() in /home/u274517531/public_html/libs/functions.php on line 131

I'm sure my array is not empty.
So, anyone can help me how to solve this problem ?
Thanks.

A: You say you are sure that your array is not empty, but what the Invalid argument supplied for foreach() error message means is that it is not even an array. Try it youself if you don't believe it:
var_dump($add);

Most likely, there was an error finding files and glob() is returning FALSE:

Returns an array containing the
  matched files/directories, an empty
  array if no file matched or FALSE on
  error.

A: Change this:
$path[] = $dir;
foreach($path as $dirname){
    $add = glob($dirname . '/*.css');
    foreach($add as $file){

to this:
$path[] = $dir;
var_dump($path);
foreach($path as $dirname){
    $add = glob($dirname . '/*.css');
    var_dump($add);
    foreach($add as $file){

We don't know which line 131 is, so I don't know which foreach fails.
(I'm guessing the 2nd, because the first is practically forced to array by $path[] = ..)

A: I found the same issue with a PHP script today and it took switching from a foreach loop to a for loop to fix it. Not sure what means, the array looks and works the same.
// Errors out
$files = glob($directory.'*.html');
foreach($files as $file){
    echo($file);
}

// No error
$files = glob($directory.'*.html');
for($i=0; $i<count($files); $i++){
    echo($files[$i]);
}


text:
Q: Mongoose save date in ddmmyyyy format I have a few fields in my mongo database that are of type Date.
Using Node and Express I can pull and display the dates using "moment" in any format I want.
When I save them back using "findByIdAndUpdate" either the date will be reversed or return a not valid error.
message: 'Cast to date failed for value "29-12-2018" at path

My issue is that the form returns the date back in ddmmyyyy format whereas I think mongo requires the date to be sent back in mmddyyyy format.
There must be a simple solution to this.

A: I managed to write the solution to this using the Moment package. See my final code in the original post above
router.put("/user/:id", function(req, res){
req.body.user.weddingDate = moment(req.body.user.weddingDate, 'DD-MM-YYYY').format('MM-DD-YYYY');
User.findByIdAndUpdate(req.params.id, req.body.user, function(err, updatedUser)
{
   if(err){
       console.log(err);
       res.redirect("/admin");
   }  else {
       res.redirect("/admin");
  }
 });
});


text:
Q: AWS "sam deploy" function times out. Stack stays in "REVIEW_IN_PROGRESS" status I'm trying to deploy a very simple function as shown in below template.yaml file. It creates a "samcli-deploy1629444458" changeset and it stays in "CREATE_IN_PROGRESS" status. When I check details of it there is no changes in it. There is nothing in Events, Resources, Output sections of the stack too. "sam deploy" command fails with attached output and stack stays in "REVIEW_IN_PROGRESS" status and I need to manually delete it.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  AWS Test backend.

Globals:
  Function:
    Timeout: 3
    Runtime: nodejs12.x

Resources:
  HelloWorldApi:
    Type: AWS::Serverless:Api
    Properties:
      Name:API
      StageName: Prod

  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello-world/
      Handler: app.lambdaHandler
      Events:
        HelloWorld:
          Type: Api
          Properties:
            RestApiId: !Ref HelloWorldApi
            Path: /hello
            Method: get

Output of "sam deploy" command.
Waiting for changeset to be created..
Traceback (most recent call last):
  File "/usr/local/Cellar/aws-sam-cli/1.28.0/libexec/lib/python3.8/site-packages/samcli/lib/deploy/deployer.py", line 292, in wait_for_changeset
    waiter.wait(ChangeSetName=changeset_id, StackName=stack_name, WaiterConfig=waiter_config)
  File "/usr/local/Cellar/aws-sam-cli/1.28.0/libexec/lib/python3.8/site-packages/botocore/waiter.py", line 53, in wait
    Waiter.wait(self, **kwargs)
  File "/usr/local/Cellar/aws-sam-cli/1.28.0/libexec/lib/python3.8/site-packages/botocore/waiter.py", line 362, in wait
    raise WaiterError(
botocore.exceptions.WaiterError: Waiter ChangeSetCreateComplete failed: Max attempts exceeded

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/bin/sam", line 8, in <module>
    sys.exit(cli())
  File "/usr/local/Cellar/aws-sam-cli/1.28.0/libexec/lib/python3.8/site-packages/click/core.py", line 829, in __call__
    return self.main(*args, **kwargs)
  File "/usr/local/Cellar/aws-sam-cli/1.28.0/libexec/lib/python3.8/site-packages/click/core.py", line 782, in main
    rv = self.invoke(ctx)
  File "/usr/local/Cellar/aws-sam-cli/1.28.0/libexec/lib/python3.8/site-packages/click/core.py", line 1259, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/usr/local/Cellar/aws-sam-cli/1.28.0/libexec/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/usr/local/Cellar/aws-sam-cli/1.28.0/libexec/lib/python3.8/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/usr/local/Cellar/aws-sam-cli/1.28.0/libexec/lib/python3.8/site-packages/samcli/lib/cli_validation/image_repository_validation.py", line 76, in wrapped
    return func(*args, **kwargs)
  File "/usr/local/Cellar/aws-sam-cli/1.28.0/libexec/lib/python3.8/site-packages/click/decorators.py", line 73, in new_func
    return ctx.invoke(f, obj, *args, **kwargs)
  File "/usr/local/Cellar/aws-sam-cli/1.28.0/libexec/lib/python3.8/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/usr/local/Cellar/aws-sam-cli/1.28.0/libexec/lib/python3.8/site-packages/samcli/lib/telemetry/metric.py", line 153, in wrapped
    raise exception  # pylint: disable=raising-bad-type
  File "/usr/local/Cellar/aws-sam-cli/1.28.0/libexec/lib/python3.8/site-packages/samcli/lib/telemetry/metric.py", line 122, in wrapped
    return_value = func(*args, **kwargs)
  File "/usr/local/Cellar/aws-sam-cli/1.28.0/libexec/lib/python3.8/site-packages/samcli/lib/utils/version_checker.py", line 42, in wrapped
    actual_result = func(*args, **kwargs)
  File "/usr/local/Cellar/aws-sam-cli/1.28.0/libexec/lib/python3.8/site-packages/samcli/cli/main.py", line 90, in wrapper
    return func(*args, **kwargs)
  File "/usr/local/Cellar/aws-sam-cli/1.28.0/libexec/lib/python3.8/site-packages/samcli/commands/deploy/command.py", line 206, in cli
    do_cli(
  File "/usr/local/Cellar/aws-sam-cli/1.28.0/libexec/lib/python3.8/site-packages/samcli/commands/deploy/command.py", line 345, in do_cli
    deploy_context.run()
  File "/usr/local/Cellar/aws-sam-cli/1.28.0/libexec/lib/python3.8/site-packages/samcli/commands/deploy/deploy_context.py", line 155, in run
    return self.deploy(
  File "/usr/local/Cellar/aws-sam-cli/1.28.0/libexec/lib/python3.8/site-packages/samcli/commands/deploy/deploy_context.py", line 229, in deploy
    result, changeset_type = self.deployer.create_and_wait_for_changeset(
  File "/usr/local/Cellar/aws-sam-cli/1.28.0/libexec/lib/python3.8/site-packages/samcli/lib/deploy/deployer.py", line 458, in create_and_wait_for_changeset
    self.wait_for_changeset(result["Id"], stack_name)
  File "/usr/local/Cellar/aws-sam-cli/1.28.0/libexec/lib/python3.8/site-packages/samcli/lib/deploy/deployer.py", line 297, in wait_for_changeset
    reason = resp["StatusReason"]
KeyError: 'StatusReason'

Update:
If I wait long enough after "sam deploy" command failed and not manually delete the stack, it finally fails with following error:
 1 validation error detected: Value '[AWS::Serverless:Api, AWS::IAM::Role, AWS::Lambda::Function, AWS::Lambda::Permission]' at 'typeNameList' failed to satisfy constraint: Member must satisfy constraint: [Member must have length less than or equal to 204, Member must have length greater than or equal to 10, Member must satisfy regular expression pattern: [A-Za-z0-9]{2,64}::[A-Za-z0-9]{2,64}::[A-Za-z0-9]{2,64}(::MODULE){0,1}]

I couldn't find any long name in the .yaml file which may cause this error.

A: It's a simple typo, you're missing a colon:
Type: AWS::Serverless:Api

Should be
Type: AWS::Serverless::Api


text:
Q: How to send authorization header to a http request in angular js (version 1.4.8) snapshot on server side
The above screenshot is while I debug the web service which is hit during my javascript call. I want to set the authorization header of the http request which is returning null. Can you please suggest me for this

A:  var config = {
      method: 'POST',
      url: 'https://somesite.com/',
      headers: {
            // key value pair of headers
            'Authorization': 'Your auth key'
      },
      data: body of request
  };
 $http(config)
         .success(function(){})
         .error(function(){})

A: You can add this in your http request:
headers: {'Authorization': 'Basic key'}

Examples
GET request:
$http.get('url', { //same for post also
    headers: {'Authorization': 'Basic key'}
});

Post Request:
$http.post("url", requestData, {
    headers: { 'Authorization': 'Basic yourkey'}
}).success(function(responseData) {
    //do stuff with response
});


text:
Q: Как из txt файла выбрать значения между определенными строками в python? Я только начал изучать программирование (начал изучение с python).
Сейчас хочу обработать txt файлы полученные в результате обработки аудиофайлов при помощи VOSK-API, а именно:
У меня есть много txt файлов содержащие примерно такие строки:
  "partial" : "текст"
}
{
  "partial" : "текст текст"
}
  "result" : [{
      "conf" : 0.378535,
      "end" : 1.140000,
      "start" : 0.870000,
      "word" : "текст"
    }, {
      "conf" : 0.988076,
      "end" : 1.589016,
      "start" : 1.145362,
      "word" : "текст текст"
    }],
  "text" : "текст текст текст"
}
{
  "partial" : "текст_2"
}
{
  "partial" : "текст_2 текст_2"
}
  "result" : [{
      "conf" : 0.704822,
      "end" : 6.717415,
      "start" : 6.240000,
      "word" : "текст_2"
    }, {
      "conf" : 0.991954,
      "end" : 6.990000,
      "start" : 6.740945,
      "word" : "текст_2 текст_2"
   }],
  "text" : "текст_2 текст_2 текст_2"

И мне необходимо получить из них следующее:
- текст(указываем значение "conf") текст(указываем значение "conf") текст(указываем значение "conf")
- текст_2(указываем значение "conf") текст_2(указываем значение "conf") текст_2(указываем значение "conf")

Большая просьба оказать помощь в решении данной задачи.
Своего варианта к сожалению, нет, так как даже не представляю, как это реализовать.
Заранее всем большое спасибо!

A: Данный текстовый файл хранит данные в формате JSON. Для работы с этим форматом в Python есть библиотека json
Подключаем ее и считываем данные в словарь (dict) при помощи json.loads(содержимое текста):
import json

with open('Тектовый файл.txt', 'r', encoding = 'utf-8') as file:
    data = json.loads(file.read())
    file.close()

Далее можем работать с объектом data как со словарем. Подробнее о словарях.
Например, получить conf можно так:
conf = data['result'][0]['conf']

A: Регулярным выражением выделяем нужные куски из текста и парсим их при помощи json:
import json, re

def get_data(text_data):
    result = []
    for m in re.finditer(r'^\s*\{\s*"result".+?^\s*"text"\s*:.*?\}', text_data, flags=re.M+re.S):
        j = json.loads(m.group(0))
        result.append([(info["word"], info["conf"]) for info in j["result"]])
    return result

text = '''
{
  "partial" : "текст"
}
{
  "partial" : "текст текст"
}
{
  "result" : [{
      "conf" : 0.378535,
      "end" : 1.140000,
      "start" : 0.870000,
      "word" : "текст"
    }, {
      "conf" : 0.988076,
      "end" : 1.589016,
      "start" : 1.145362,
      "word" : "текст текст"
    }],
  "text" : "текст текст текст"
}
{
  "partial" : "текст_2"
}
{
  "partial" : "текст_2 текст_2"
}
{
  "result" : [{
      "conf" : 0.704822,
      "end" : 6.717415,
      "start" : 6.240000,
      "word" : "текст_2"
    }, {
      "conf" : 0.991954,
      "end" : 6.990000,
      "start" : 6.740945,
      "word" : "текст_2 текст_2"
   }],
  "text" : "текст_2 текст_2 текст_2"
}
'''

data = get_data(text)
print("-", "\n- ".join(map(str, data)))

На выходе:
- [('текст', 0.378535), ('текст текст', 0.988076)]
- [('текст_2', 0.704822), ('текст_2 текст_2', 0.991954)]

- [('добрый', 0.675097), ('день', 0.673823), ('вас', 0.927409), ('приветствовать', 0.735118), ('компании', 0.577527), ('перед', 0.262191), ('вами', 0.2617)]
- [('а', 0.713988), ('скажите', 0.939162), ('как', 0.952058), ('вам', 0.907947), ('могу', 0.874466), ('обращаться', 1.0)]
- [('мой', 1.0), ('господин', 1.0)]
- [('мой', 1.0), ('господин', 1.0), ('хорошо', 0.944449), ('замечательно', 0.977677), ('господина', 0.33661), ('пару', 0.989326), ('минут', 1.0), ('сможете', 0.987912), ('уделить', 0.829497), ('конечно', 0.997882), ('хорошо', 0.948283), ('спасибо', 0.977629), ('большое', 0.590951), ('буквально', 1.0), ('пару', 0.913501), ('вопросов', 0.983437), ('скажите', 0.976819), ('пожалуйста', 1.0), ('ваш', 0.996072), ('телефон', 1.0), ('поддерживает', 0.975375), ('три', 0.633331), ('или', 0.541369), ('четыре', 0.917025), ('же', 0.478112), ('конечно', 1.0), ('замечательно', 1.0)]
- [('вопрос', 0.957119), ('каким', 0.963909), ('провайдером', 0.627245), ('сколько', 1.0), ('примерно', 1.0), ('месяц', 0.566976), ('плащ', 0.475217), ('перед', 1.0), ('каждым', 1.0), ('вопросом', 0.978447), ('необходимо', 1.0), ('говорить', 1.0), ('мой', 1.0), ('господин', 1.0)]
- [('хорошо', 1.0), ('мой', 0.923967), ('господин', 1.0), ('каким', 0.976793), ('провайдерам', 0.567223), ('пользуясь', 0.420532), ('билайн', 0.890181), ('билайн', 0.978282), ('хорошо', 1.0), ('мой', 1.0), ('господин', 1.0), ('извините', 0.836975), ('пожалуйста', 1.0)]
- [('а', 0.583045), ('сколько', 1.0), ('вы', 0.987925), ('платите', 0.997781), ('каждый', 1.0), ('месяц', 1.0)]
- [('где', 0.87797), ('то', 0.87797), ('около', 1.0), ('шести', 0.961093), ('ста', 0.378545), ('рублей', 1.0), ('около', 1.0), ('шести', 0.877064), ('ста', 0.962923), ('рублей', 0.971753), ('отлично', 0.728312), ('именно', 1.0), ('для', 1.0), ('вас', 1.0), ('наша', 1.0), ('компания', 1.0), ('предоставляет', 1.0), ('именно', 0.948491), ('для', 0.871826), ('вас', 0.82166), ('очень', 0.894104), ('мой', 1.0), ('господин', 1.0)]
- [('извините', 1.0), ('я', 1.0), ('перезвоню', 0.99192)]

Зачитывание файлов уж как-нибудь сами...


text:
Q: textarea counts characters length wrong When I typed the first character in textarea it still shows 0 and count gets 1 for the second character. Not sure why? I'm using keydown event for this.
$(".textArea").keydown(updateCount());

function updateCount() {
    count = $(".textArea").val().length;
    this.$countDiv.text(count + " of 240");
};

A: Use the input event.  This will cover all changes to the textbox value, including copy & paste etc. (even with the mouse)...

$("#text").on("input", updateCount);

function updateCount() {
    count = $("#text").val().length;
    $("#count").text(count + " of 240");
}

<textarea id="text"></textarea>

There were also some other issues, like the fact that you executed the updateCount function, rather than assigned it to the event handler (you had () after the function name.  If you remove that then it becomes a reference to the function, rather than executes it there and then).
I also used an id for the textarea element, rather than a class, but that's just me - if a class works in your scenario then it's fine.

A: You need to pass function to $.keydown, not a result of execution:
$(".textArea").keydown(updateCount);

function updateCount() {
    count = $('.textArea').val().length;
    this.$countDiv.text(count + ' of 240');
}

When you pass result of execution, it must be executed before keydown processing. Because keydown depends to result of execution of updateCount, so updateCount is always executed before keydown, so you got length of string state before keydown.

A: For the use case you're trying to implement, the keydown event isn't sufficient for it. You'd have to use the keyup event. At that point the key press is complete.
Regards.

A: $(".textArea").on('keydown', function(event) {
     updateCount();
 });

function updateCount() {
var count = $(".textArea").val().length;
console.log("count",count);
}

A: fire event on all 3 change keyup paste. It will also handle if someone tries to paste in text box
like below
$('.textArea').on('change keyup paste', updateCount());


text:
Q: Regex: Alternatives Asserting $ at the End of the Pattern currently I'm working on a Regex pattern, and when asserting "$" at the end of the line, it's causing issues for it not to grab anything. When I plug it into regex101, it shows that it should be working and grabbing my sample data, however, when testing it myself I've had zero luck. So I was just curious if there was an alternative solution for declaring the end of my regex pattern. My current example pattern is below.
^\W*((?i)Test(?-i))\W*\d{2}[\-]\d{2}[\-]\d{5}$

And using a regex tester shows that it should grab the value below.
Test 99-99-32123

However when attempting to test myself, when declaring $ at the end, it doesn't select any data. When I remove the $ though, then it grabs the above test data. I would still like to declare the end though to remove the chance of it grabbing false positives. So I was just curious if anyone sees an issue with what I'm doing, or has any alternative work arounds they could provide. Thanks!

A: Thanks to Wiktor's recommendation, changing the code to the below did the trick.
^\W*((?i)Test(?-i))\W*\d{2}[\-]\d{2}[\-]\d{5}\r?$

By using \r?$ instead of simply asserting $, it resolved the issue.


text:
Q: Should sentiment analysis training data be evenly distributed? If I am training a sentiment classifier off of a tagged dataset where most documents are negative, say ~95%, should the classifier be trained with the same distribution of negative comments? If not, what would be other options to "normalize" the data set?

A: You don't say what type of classifier you have but in general you don't have to normalize the distribution of the training set. However, usually the more data the better but you should always do blind tests to prevent over-fitting.
In your case you will have a strong classifier for negative comments and unless you have a very large sample size, a weaker positive classifier. If your sample size is large enough it won't really matter since you hit a point where you might start over-fitting your negative data anyway.
In short, it's impossible to say for sure without knowing the actual algorithm and the size of the data sets and the diversity within the dataset.
Your best bet is to carve off something like 10% of your training data (randomly) and just see how the classifier performs after being trained on the 90% subset.


text:
Q: Error, 'ASK CLI v1 is not functional' in Visual Studio Code Here's the entire error message....
Command 'ASK: Deploy the skill' resulted in an error (ASK CLI v1 is not functional. Command failed: C:\WINDOWS\system32\cmd.exe /q /s /c "ask init -l" error: unknown option '-l' )
Happens when I 'ASK deploy' or any ASK command. Anybody have any ideas what that means?
TIA!!

A: I figured it out and assuming you are a windows user, this may be your issue.
Before you install ASK-CLI on Windows, you must install the Node.js windows-build-tools package. Before you install windows-build-tools, make sure you have the version of Node.js that the package requires. If you have already installed ASK-CLI you need to uninstall it. Then install it again after you have installed windows-build-tools.
To install windows-build-tools, first open PowerShell with the Run as Administrator option, then type npm install -g --production windows-build-tools.
After I did this, I had to delete and recreate my ASK project, then my ASK deployments started working.
Reference: https://developer.amazon.com/en-US/docs/alexa/smapi/quick-start-alexa-skills-kit-command-line-interface.html

A: I have a step by step to setup a new environment:

*

*npm install -g --production windows-build-tools

*npm install -g ask-cli

*ask configure

*npm install -g lambda-local

Please assure that you are running the command as Administrator or using sudo on Linux.


text:
Q: NoClassDefFoundError in Spark Submit I am working on a spark application . I am using a third party jar. I added it in my sbt file. The compilation was successful
> libraryDependencies += "org.springframework.security" %
> "spring-security-web" % "3.0.7.RELEASE

But when i submit spark job
spark-submit --master yarn-client --class MyClass target/scala-2.10/my-app.jar

It fails with following error:
Exception in thread "main" org.apache.spark.SparkException: Job aborted due to
stage failure: Task 0 in stage 48.0 failed 1 times, most recent failure: Lost task 0.0 in stage 48.0 (TID 3216, localhost):
`java.lang.NoClassDefFoundError:` org/springframework/security/web/util/IpAddressMatcher

I also tried explicitly passing jar in spark-submit jar
spark-submit --master yarn-client --jars third-party-jars/spring-security-web-3.0.7.RELEASE.jar --class MyClass target/scala-2.10/my-app.jar

But then it fails with following error:
java.lang.NoClassDefFoundError: org/springframework/util/StringUtils
    at org.springframework.security.web.util.IpAddressMatcher.<init>(IpAddressMatcher.java:33)

Its similar error but on another class.
Any suggestion on how to resolve this?
Thanks

A: Also you can use IntelijIDE. You will not need to adjust it always. You can download here for Ubuntu.
https://apps.ubuntu.com/cat/applications/intellij-idea-ce/


text:
Q: How do I parse a question that contains escape sequences from Microsoft QnA Maker in my bot project? I'm testing and training a new QnA bot for my web application and I want to print out the right answer format when it encounters escape sequences. How can I implement such approach in order to have the bot recognize the escape sequences that I have added? The bot emulator adds an extra '\' at the beginning of '\n\n'
I am using Bot Framework emulator for sdvk 3 and QnA Maker website
My answer is as follows:
\n\n 1. Visit the heroes Portal website.\n\n 2. Select the create button.\n\n 3. Click "choose class" under the classes \n your heroes section.\n\n 4. Follow the instructions provided.\n If you require further assistance, please email us \n at ###@$$$.com\n

using Microsoft.Bot.Builder.CognitiveServices.QnAMaker;
using System;

namespace heroes.ChatBot.Dialogs.QnA
{
    [Serializable]
    [QnAMaker("####", "###",
        "Sorry I could not find an answer to your  question", 0.5, 1, "website" )]
    public class QnAHeroesDialog : QnAMakerDialog
    {

    }
}

1.Visit the heroes Portal website.

2.Select the create button.

3.Click "choose class" under the classes \n your heroes section.

4.Follow the instructions provided.\n
  If you require further assistance,\n
  please follow instruction.

A: What you are looking for is an override of the response provided by QnAMaker. There are some samples available in the official Github repo: https://github.com/Microsoft/BotBuilder-CognitiveServices/blob/master/CSharp/Samples/QnAMaker/QnABotWithOverrides/Dialogs/QnADialogWithOverrides.cs
In a few words, override RespondFromQnAMakerResultAsync to handle this "double \n" problem
It will look like the following:
[Serializable]
[QnAMaker("####", "###",
    "Sorry I could not find an answer to your  question", 0.5, 1, "website" )]
public class QnAHeroesDialog : QnAMakerDialog
{
    protected override async Task RespondFromQnAMakerResultAsync(IDialogContext context, IMessageActivity message, QnAMakerResults results)
    {
        if (results.Answers.Count > 0)
        {
            var foundReply = results.Answers.First().Answer;
            var response = $"{foundReply.Replace("\n\n", "\n")}";
            await context.PostAsync(response);
        }
    }
}

My code may need a quick tuning for the Replace as I don't have the exact format of your response value


text:
Q: property of the javascript object is undefined I use React js. I have an object like this inside data.js. I write content because there is personal information.
const experience = {
    work: [
        {
            content
        },
        {
            content
        }
    ],
    event: [
        {
            content
        },
        {
            content
        },
        {
            content
        }
    ]
}

And then I import the data.js into experience.js and I want to check the data using console log. But the output is just empty object. When I try to access the data.work or data["work"] the output is undefined. I also try using JSON stringify. Does anyone know where did I go wrong? Is the way I access the property correct?
console.log("data : "+JSON.stringify(data.work));

A: You need to export your experience object from data.js file
export const experience = { // your data here };

And then import experience object in experience.js file
import { experience } from './data.js'


text:
Q: Trigonometric Prοof How can one show that for any angle $\theta$ such that $0<\theta<2\pi/5$ the following equation is true?
$\sqrt{1-\cos\theta} +\sqrt{1-\cos(\theta-\frac{2\pi}{5})}+\sqrt{1-\cos(\theta+\frac{4\pi}{5})}=\sqrt{1-\cos(\theta+\frac{2\pi}{5})}+\sqrt{1-\cos(\theta-\frac{4\pi}{5})}$

A: Note that $$\sqrt{1 - \cos(2x)} = \sqrt{2}\,|\sin(x)|.$$  So for $x \in (0, \frac{\pi}{5})$ we have to show $$\sin(x) - \sin(x - \frac{\pi}{5}) + \sin(x + \frac{2\pi}{5}) - \sin(x + \frac{\pi}{5}) + \sin(x - \frac{2 \pi}{5}) = 0.$$ Using that $\sin(x + 2\pi) = \sin(x)$ and $\sin(x + \pi) = -\sin(x)$ this can be rewritten as $$\sin(x) + \sin(x + \frac{4\pi}{5}) + \sin(x + \frac{2\pi}{5}) + \sin(x + \frac{6\pi}{5}) + \sin(x + \frac{8 \pi}{5}) = 0.$$ Now the left hand side is the sum of the $y$-coordinates of a regular pentagon centred at the origin and tilted at an angle $x$.  Since the vertices of such a pentagon sum up to the zero vector the sum of the $y$-coordinates equals $0$.


text:
Q: Factorisation question. I was going through a math worksheet and I am stuck at this question:

Factors of $(x^4 + 4)$:

Can someone tell me how to factorise this?
Thanks for your help.

A: Hint:
$$x^4+4=(x^4+4x^2+4)-4x^2$$
Difference of squares.

A: This is a special case of the Sophie Germain Identity which states that $$a^4+4\cdot b^4 = (a^2+2ab+2b^2)(a^2-2ab+2b^2)$$
Applied to the case $x^4+4$ we have the factorization $(x^2+2x+2)(x^2-2x+2)$.

A: You can address this using complex numbers.
$$x^4+4=0\iff x^4=-4$$so you need to consider the fourth roots of $-4$.
These are $\sqrt2e^{i\pi/4+ik\pi}$, i.e. $1+i,-1+i,-1-i,1-i$.
Taking them in conjugate pairs,
$$(x-1-i)(x-1+i)=(x^2-2x+2)$$and$$(x+1-i)(x+1+i)=(x^2+2x+2).$$
These are the requested factors.

A: By indeterminate coefficients.
You see that the polynomial has no real roots, and it will factor as two quadratic trinomials.
$$x^4+1=(x^2+ax+b)(x^2+cx+d)=x^4+(a+c)x^3+(ac+b+d)x^2+(ad+bc)x+bd.$$
Then by identification,
$$\begin{align}a+c&=0\\ac+b+d&=0\\ad+bc&=0\\bd&=4.\end{align}$$
Observe $c=-a$, then $ad-ab=0\implies d=b$, $b^2=4\implies b=2$, $-a^2+2b=0\implies a=2$.
Solution:
$$(x^2+2x+2)(x^2-2x+2).$$


text:
Q: Count the number of unique values appearing a set number of times in a range I have a dataset in Excel that is structured as follows:
A    B            C
ID   Start_date   End_date
1    01/01/2000   05/01/2000
1    06/01/2000   15/05/2000
1    16/05/2000   07/04/2018
2    06/07/2016   09/10/2019
2    10/10/2019   14/12/2019
3    02/08/2000   06/08/2006
3    07/08/2006   15/02/2020
4    05/09/2012   09/11/2017

I would like to create a time series of the number of unique values in the above dataset that occur more than 3 times in the 12 months prior to any month in the date range covered by the dataset (in this case 01/01/2000 - 15/02/2020). So, for example, the number of unique values appearing more than three times in the 12 months prior to January 2001 would be 1 (ID = 1).
I've tried this in Excel using the following formula:
{=SUM(--(FREQUENCY(IF(($B$2:$B$8<=EOMONTH('Time Series'!A2,0))*($C$2:$C$8>=EOMONTH('Time Series'!A2,-12),$A$2:$A$8),$A$2:$A$8)>0))}

Where the value in 'Time Series'!A2 is January 2001.
However, this only returns the number of unique values that occur in the 12 months prior to January 2001, not how many unique values occur more than three times in the period.
Any help on this would be greatly appreciated - while I have been doing this in Excel so far, I would be open to performing the calculation in R if that would prove simpler.

A: I am not sure if I understood your question correctly:
1.Create minimal reproducible example:
df <-structure(list(ID = c(1L, 1L, 1L, 2L, 2L, 3L, 3L, 4L),
               Start_date = c("01/01/2000", "06/01/2000", "16/05/2000", "06/07/2016", "10/10/2019", "02/08/2000", "07/08/2006", "05/09/2012"),
               End_date = c("05/01/2000", "15/05/2000","07/04/2018", "09/10/2019", "14/12/2019", "06/08/2006", "15/02/2020", "09/11/2017")),
          class = "data.frame", row.names = c(NA, -8L))

head(df)

Returns:
  ID Start_date   End_date
1  1 01/01/2000 05/01/2000
2  1 06/01/2000 15/05/2000
3  1 16/05/2000 07/04/2018
4  2 06/07/2016 09/10/2019
5  2 10/10/2019 14/12/2019
6  3 02/08/2000 06/08/2006

*Suggested solution using dplyr

Format date columns as.Date:
library(dplyr)
df_formated <- df %>%
  mutate(Start_date = as.Date(Start_date, "%d/%m/%Y"),
         End_date = as.Date(End_date, "%d/%m/%Y"))

str(df)

Returns:
'data.frame':   8 obs. of  3 variables:
 $ ID        : int  1 1 1 2 2 3 3 4
 $ Start_date: chr  "01/01/2000" "06/01/2000" "16/05/2000" "06/07/2016" ...
 $ End_date  : chr  "05/01/2000" "15/05/2000" "07/04/2018" "09/10/2019" ...

Filter by cutoff_date and count occurences and filter by min_number_of_occurences:
cutoff_date <- as.Date("01/01/2001", "%d/%m/%Y")
min_number_of_occurences <- 3

df_formated %>%
  filter(Start_date < cutoff_date) %>%
  group_by(ID) %>%
  summarise(N = n()) %>%
  filter(N >= min_number_of_occurences)

Returns:
# A tibble: 1 x 2
     ID     N
  <int> <int>
1     1     3


text:
Q: Custom resolution in Fedora 11 I am currently building a custom embedded project for which I need to display Fedora 11 on a small screen 800*480 pixels.
Can anyone one suggest to me a way of doing it. I tried to change the .conf file of xorg server but it is of no help.
Also it is not updating. Also can anyone tell how to update the packages as currently package updating is not working.

A: Fedora 11's support ended on 2010-06-25.  That is why you aren't getting software updates.  Try using a supported version of Fedora (16 or 17).
You might be able to create a file in /etc/X11/xorg.conf.d/ with this as the contents:
Section "Screen"
    Identifier "Screen0"
    Device     "Videocard0"
    Monitor    "Monitor0"
    SubSection "Display"
        Modes "800x480"
    EndSubSection
EndSection

I'm not sure if F11 supported the /etc/X11/xorg.conf.d directory, you might need to put that in your /etc/X11/xorg.conf if not.


text:
Q: Traversing JSON object only get the first 2 values I'm trying to write some code in PowerShell v5.1 that recurses through a parsed JSON object to get its property names. An example JSON object is below:
{
    "str1": "Hello World!",
    "strings": {
        "strA": "Foo!",
        "strB": "Bar!"
    },
    "others": {
        "myBool": true,
        "myInt": 42
    }
}

First I read and parse the object into a PSObject:
$jsonString = '{"str1": "Hello World!", "strings":{"strA": "Foo!","strB": "Bar!"}, "others":{"myBool": true,"myInt": 42}}'
$json = $jsonString | ConvertFrom-Json

Next I can use $json.PSobject.properties.name to get a list of all the top-level property names:

PS> $json.PSobject.properties.name
str1
strings
others

However, if I use $json.PSobject.properties.value, I only see the first two values output:

PS> $json.PSobject.properties.value
Hello World!

strA strB
---- ----
Foo! Bar!

I would expect to see the others property included here too. Is there a reason I'm not seeing it?


text:
Q: Authorize only email from specific domain asp.net MVC I'm trying to limit access to one controller to users from one specific domain. I thought the following would work :
[Authorize(Users = "*@domain.com")]

But it doesn't. Is there a way to do this out of the box or I need to develop my own attribute?
Thanks

A: I finally created an attribute that inherits from AuthorizeAttribute.
public class AuthorizeEmailDomainAttribute : AuthorizeAttribute
    {
        // Custom property
        public string EmailDomain { get; set; }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var isAuthorized = base.AuthorizeCore(httpContext);
            if (!isAuthorized)
            {
                return false;
            }

            bool isGoodDomain= httpContext.User.Identity.Name.Contains("@" + EmailDomain);
            return isGoodDomain;
        }
    }

Have a nice day


text:
Q: iOS unzip .gz file
Possible Duplicate:
How to uncompress a gzip file and write that out to an uncompressed file, on iPhone

Im trying to unzip a .gz sqlite file in iOS, but until now I did not found a good library for that.
I tried SSZipArchive like that:
path = [[NSBundle bundleForClass:[self class]] pathForResource:@"test.sqlite" ofType:@"gz"];

NSString *documentsDir = (NSString *)[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
destination = documentsDir;
NSError *error;

BOOL success =  [SSZipArchive unzipFileAtPath:path toDestination:destination overwrite:YES password:nil error: &error];

That works for a zipped sqlite database file, but not if I gzip the sqlite database. Then everytime the error "cant open zip file" is returning.
Then I tried this GZIP approach from https://github.com/nicklockwood/GZIP.
I used the code like that:
path = [[NSBundle bundleForClass:[self class]] pathForResource:@"test.sqlite" ofType:@"gz"];

NSString *documentsDir = (NSString *)[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
destination = [documentsDir stringByAppendingPathComponent:@"test.sqlite"];

NSData *gzData = [NSData dataWithContentsOfFile:path];
NSData *ungzippedData = [gzData gunzippedData];

return [ungzippedData writeToFile:destination atomically:YES];

After that I got a file named test.sqlite in my Documents folder, but if I try to open it, it fails because the fail is corrupt.
And my last  try was ZipArchive from http://code.google.com/p/ziparchive/.
I used it like that:
ZipArchive* za = [[ZipArchive alloc] init];
if( [za UnzipOpenFile:path] ){
    BOOL success = [za UnzipFileTo:destination overWrite:YES];
    [za UnzipCloseFile];
    return success;
}

But this also cant open the file.
Can someone help me?

A: There is zlib library use can add to your target in linker settings in Xcode.
Here you can find example on how to use zlib. http://zlib.net/zlib_how.html


text:
Q: Need help using 'char tkn' I have to make a program that asks for the number of rows and number of columns and prints a rectangle based on these values.
The only clue I got was:

Note that char tkn can be used to declare a character.

And I received an example of how input and output should look:
The number of lines: 3

The number of columns: 4

Which characters do you want to use: #

####
####
####

This is what I got so far (I'm just guessing how to do the char bit at the moment):
#include <iostream>
using namespace std;
int main()
{
    int lines, columns, character;
    char tkn;
    cout<<"The number of lines: ";
    cin>>lines;
    cout<<"The number of columns ";
    cin>>columns;
    cout<<"What character do you want to use? ";
    cin>>tkn;

    cin.ignore();
    getchar();
    return 0;
}

A: Add header
#include <iomanip>

and include the following loop
std::cout << std::setfill( tkn );
while ( lines-- )
{
    std::cout << std::setw( columns + 1 ) << '\n';
}

Also it would be better to use identifier character (or simply c) or filler instead of this strange identifier tkn

A:     #include <iostream>
    #include <iomanip>
    using namespace std;
    int main()
    {
        int lines, columns, character, i=0, l=0;
        char tkn;
        cout<<"The number of lines: ";
        cin>>lines;
        cout<<"The number of columns ";
        cin>>columns;
        cout<<"What character do you want to use? ";
        cin>>tkn;

        for(l=0;l<lines;l++;)
        {
        {
         cout<<tkn;
        }
        for(i=0;i<columns;i++)
        {
        cout<<tkn;
        }
        cout<<endl;
        }
        cin.ignore();
        getchar();
        return 0;
    }


text:
Q: How to return value from Node.js function which contains DB query I'm learning Node.js and I'm just starting to work with some MySQL connections. I have a function which is supposed to get a set of rows from the database, which it does correctly. However, I don't know how to return that set of rows afterwards. I tried two options (both explained in comments within the code segment below.
function fetchGameList(){
    var ret = 0;

    connection.query("SELECT * from tbl", function(err, rows, fields) {
        //some stuff happens here, and 'ret' is set to a vlue, for instance
            //ret = 7;
        //ret has the value 7 here, but if I put 'return ret' here, nothing is returned
    });

    return ret; //returns 0 because Node is asynchronous and the query hasn't finished yet
}

So, the question is, how do I return the correct value of ret (7 in this case)? Am I even structuring this properly?

A: You need to pass a callback into your function. Convention is that the callback takes an error (or null if none happened) as the first argument, and results as other arguments.
function fetchGameList(callback) {
    var ret;

    connection.query("SELECT * from tbl", function(err, rows, fields) {
        if (err) {
            // You must `return` in this branch to avoid using callback twice.
            return callback(err);
        }

        // Do something with `rows` and `fields` and assign a value to ret.

        callback(null, ret);
    });
}

You can now do something along the lines of:
function handleResult(err, result) {
    if (err) {
        // Just an example. You may want to do something with the error.
        console.error(err.stack || err.message);

        // You should return in this branch, since there is no result to use
        // later and that could cause an exception.
        return;
    }

    // All your logic with the result.
}

fetchGameList(handleResult);


text:
Q: How to determine optimal fault tolerant memory for filex? in filex example file, given to fx_fault_tolerant_enable function RAM buffer in size of FX_FAULT_TOLERANT_MAXIMUM_LOG_FILE_SIZE which is 3K.
I would want to reduce this define and the RAM buffer as much as I can.
What are the parameters I need to decide what is the needed size for FX_FAULT_TOLERANT_MAXIMUM_LOG_FILE_SIZE? can I reduce the RAM buffer more?
I suppose it should be some function of how many open files I have in parallel and how much I am writing to them but I don't know how to really calculate it.
EDIT
In the read fault tolerance function it looks like it is expected that the cache size is at least the size of the log in the file system, for example if FX_FAULT_TOLERANT_MAXIMUM_LOG_FILE_SIZE is 3K so the cache is also at least 3K. Am I right??

A: The requirement of RAM buffer size for fault tolerant feature is at least bytes_per_sector. The symbol FX_FAULT_TOLERANT_MAXIMUM_LOG_FILE_SIZE is not user configurable. It covers the worst case of file renaming. The log file will occupy 3K data in the file system. Do you intend to save disk usage for fault tolerant?


text:
Q: Create new Attribute in Weka (String) So my question is how do I declare a new attribute for weka when all my data is a collection of texts.
My goal is to create new attributes, so that I can use a decision tree algorithm.
For example, I want an attribute that Filters for all these Keywords (Winner, Free, Subscription)
ARFF File viewed in Notepad++

A: If you are thinking of generating new attributes from the textual data in your STRING attribute, then you can use the StringToWordVector filter.
For general info on handling textual data, have a look at the Text categorization with Weka wiki article.


text:
Q: How to test a REST service that uses JWT in SoapUI? I'm implementing some REST services. All my tests are made using SoapUI.
Recently I decided to adopt JSON Web Token (JWT) for authentication but I could not find any support for this on SoapUI (native install or plugins, nothing).
I found some online generators like http://jwtbuilder.jamiekurtz.com/ but fill all fields, copy/paste on SoapUI again and again for every testcase is not productive at all.
I'm wondering if there is a way to test JWT stuff in SoapUI or if maybe I need another tool. Any advice?
Thanks!

A: I've found a semi-automatic way to keep a valid JWT token across TestCases without losing too much time, using an external file containing the token.

*

*Have an external tool generating a valid JWT token into a file.

*Open your project in SoapUI and add a jwt variable with the value

${=new File('/path/to/token_file.txt').text}

*In your requests, reference your variable as a JWT header with the value

${#Project#jwt}

When the token expire, just relaunch the generator script, and SoapUI will automatically load the new token.

A: SoapUI will call your authentication server and fetch the token, then it will automatically put that token into authorization header (Bearer <token>).
Add new authorization>OAuth 2>Resource owner password credential grant

Then add your username and password into both client and resource section. Finally , put your token end-point as access token url and save the authorization  profile to use in other test cases.


text:
Q: Ubuntu 12.04 Boot Freeze At Purple Screen
Possible Duplicate:
What should I do when Ubuntu freezes?

In the last week or so Ubuntu has started freezing on boot, showing only a purple screen. It freezes before the screen saying Ubuntu with small dots under it comes up. The keyboard and mouse doesn't seem to respond to anyting and nothing happens if I just wait some time.
It seems to be coming at almost random but usually with a few days in between.
I have been running Ubuntu since it was first released and before the freezes started happening I had no problems at all. But now when I hover an application in the launcher bar, the popup with the name on it will sometimes act weird or not show properly. I don't know if that has anything to do with the freezing.
Any help? Thanks.
I'm running Ubuntu 12.04 with Bumblebee and only a few other applications installed. My computer is a Samsung Q330:
Intel® Core™ i3 Processor 330M (2.13 GHz, 3 MB)
4GB (DDR3 / 2GB x 2)
nVIDIA GeForce 310M
320 GB (5400 opm S-ATA)

A: try "sudo update-grub" (without quotes)when you have booted in terminal
also try hitting arrow down or arrow left on your keyboard when grub enter load your ubuntu
that will show you a text message about grub processes
see if that something wrong with your grub
or you can simply enter "gksu xdiagnose"(without quotes) in terminal
then checklist all the checkbox except the first one
hope that can solve your problem


text:
Q: Autowiring not working after adding spring security I'm working on a spring project and I'm trying to apply sprin security.The problem is that when I add spring-security.xml at contextConfigurationLocation parameters for some reason I can't figure out service beans are not autowired at controllers and I get
org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.ibios.services.ArticleCategoryService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:952)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:821)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:735)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:609)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
at javax.servlet.GenericServlet.init(GenericServlet.java:212)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1173)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:993)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4149)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4458)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:722)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:516)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:583)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)

spring security xml file is:
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.1.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util-3.1.xsd">

<debug/>
<http pattern="/resources" security="none" />

<http auto-config="true"  use-expressions="true">
    <intercept-url pattern="/login" access="permitAll"/>
    <intercept-url pattern="/logout" access="permitAll"/>
    <intercept-url pattern="/denied" access="hasRole('ROLE_USER')"/>
    <intercept-url pattern="/" access="hasRole('ROLE_ADMIN')"/>
    <intercept-url pattern="/user" access="hasRole('ROLE_USER')"/>
    <intercept-url pattern="/admin" access="hasRole('ROLE_ADMIN')"/>

    <form-login login-page="/login"
        authentication-failure-url="/login/failure"
        default-target-url="/"/>

    <access-denied-handler error-page="/denied"/>

    <logout invalidate-session="true"
        logout-success-url="/logout/success"
        logout-url="/logout"/>
</http>

<authentication-manager>
        <authentication-provider user-service-ref="customUserDetailsService">

        </authentication-provider>
</authentication-manager>
<beans:bean id="customUserDetailsService" class="com.ibios.services.impl.CustomUserDetailService"/>

root-context xml is:
    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="
       http://www.springframework.org/schema/beans      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
       http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
       http://www.springframework.org/schema/context    http://www.springframework.org/schema/context/spring-context-3.2.xsd
       http://www.springframework.org/schema/tx         http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
       http://www.springframework.org/schema/data/jpa   http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd">

    <bean id="jdbcPropertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="classpath:project.properties" />

    <bean id="datasource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}"
        p:username="${jdbc.username}" p:password="${jdbc.password}"/>

    <bean id="persistenceUnitManager"
        class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">

        <property name="persistenceXmlLocations">
            <list>
                <value>classpath:/META-INF/persistence.xml</value>
            </list>
        </property>
    </bean>

    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitManager" ref="persistenceUnitManager" />
        <property name="persistenceUnitName" value="entityManager" />
        <property name="dataSource" ref="datasource" />
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />

    </bean>

    <bean id="terminologyService" class="com.ibios.services.impl.TerminologyServiceImpl" />
    <bean id="articleCategoryService" class="com.ibios.services.impl.ArticleCategoryServiceImpl" />
    <bean id="exerciseCategoryService" class="com.ibios.services.impl.ExerciseCategoryServiceImpl"/>
    <bean id="exerciseService" class="com.ibios.services.impl.ExerciseServiceImpl"/>
    <bean id="articleService" class="com.ibios.services.impl.ArticleServiceImpl"/>
    <bean id="customUserDetailsService" class="com.ibios.services.impl.CustomUserDetailService"/>
    <tx:annotation-driven transaction-manager="transactionManager"   />

    <jpa:repositories base-package="com.ibios.repositories" />

    <context:component-scan base-package="com.ibios.web" />

</beans>

articleCategory service impl class is:
  public class ArticleCategoryServiceImpl implements ArticleCategoryService{

    @Resource
    ArticleCategoryRepository articleCategoryRepository;

    @Override
    public void create(ArticleCategory articleCategory) {
        articleCategoryRepository.saveAndFlush(articleCategory);
    }
    @Override
    public void update(ArticleCategory articleCategory) {
        articleCategoryRepository.saveAndFlush(articleCategory);

    }
    @Override
    public void delete(ArticleCategory articleCategory) {
        articleCategoryRepository.delete(articleCategory);

    }
    @Transactional
    @Override
    public List<ArticleCategory> findAll() {
        List<ArticleCategory> articleCategories = articleCategoryRepository.findAll();
        return articleCategories;
    }
    @Override
    public Page<ArticleCategory> findAll(Pageable pageable) {
        PageRequest page1 = new PageRequest(pageable.getPageNumber(),
                pageable.getPageSize(), Direction.DESC, "id");
        Page<ArticleCategory> categories = articleCategoryRepository.findAll(page1);
        return categories;
    }
    @Override
    public ArticleCategory getById(Integer id) {
        ArticleCategory articleCategory = articleCategoryRepository.findOne(id);
        return articleCategory;
    }
    @Override
    public List<ArticleCategory> findLatest() {
        List<ArticleCategory> latest=articleCategoryRepository.findLatest();
        return latest;
    }
}

and the controller class is
   @Controller
public class AddArticleCategoryController {

    @Autowired

    private ArticleCategoryService articleCategoryService;

    @RequestMapping(value = "/addArticleCategory", method = RequestMethod.POST)
    public String addArticleCategory(@ModelAttribute("articleCategory") ArticleCategory articleCategory, BindingResult result) {
        articleCategory.setCreated(Calendar.getInstance());
        articleCategoryService.create(articleCategory);
        return "addArticleCategory";
    }

    @RequestMapping(value = "/addArticleCategory", method = RequestMethod.GET)
    public ModelAndView showrticleCategory(@ModelAttribute ArticleCategory articleCategory, BindingResult result) {

        return new ModelAndView("addArticleCategory", "articleCategory", new ArticleCategory());

    }

    @RequestMapping(value = "/showArticleCategories", method = RequestMethod.GET)
    public String showArticleCategories(Model model, @PageableDefaults(pageNumber = 0, value = 15) Pageable pageable) {
        Page<ArticleCategory> page = articleCategoryService.findAll(pageable);
        model.addAttribute("page", page);
        return "showArticleCategories";
    }

    @RequestMapping(value = "/editArticleCategory", method = RequestMethod.GET)
    public String editArticleCategory(@RequestParam("id") String id, Model model) {
        ArticleCategory articleCategory = articleCategoryService.getById(Integer.parseInt(id));
        model.addAttribute("articleCategory", articleCategory);
        return "editArticleCategory";
    }

    @RequestMapping(value = "/editArticleCategory", method = RequestMethod.POST)
    public String editArticleCategorires(@ModelAttribute("articleCategory") ArticleCategory articleCategory, BindingResult result) {
        System.out.println("CREATED:" + (String) result.getFieldValue("created"));
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        try {
            Date createdDate = formatter.parse((String) result.getFieldValue("created"));
            Calendar created = Calendar.getInstance();
            created.setTime(createdDate);
            articleCategory.setCreated(created);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        articleCategoryService.update(articleCategory);
        return "showArticleCategories";
    }

    public ArticleCategoryService getArticleCategoryService() {
        return articleCategoryService;
    }

    public void setArticleCategoryService(ArticleCategoryService articleCategoryService) {
        this.articleCategoryService = articleCategoryService;
    }
}

the web.xml part for spring security is:
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/root-context.xml</param-value>
    <param-value>/WEB-INF/spring/spring-security.xml</param-value>
</context-param>

<!-- Creates the Spring Container shared by all Servlets and Filters -->

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Up until now I've tried to use ArticleCategoryService interface instead of the implementing class,I've set proxy-target-class to "true" at the transaction manager all of them with no results.

A: Try to add the @Service annotation to the ArticleCategoryServiceImpl
Change your web.xml from
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/root-context.xml</param-value>
    <param-value>/WEB-INF/spring/spring-security.xml</param-value>
</context-param>

To:
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/root-context.xml, /WEB-INF/spring/spring-security.xml</param-value>
</context-param>


text:
Q: How to export data into a specific extension ? like PDF I'm trying to program an app that let users write their novels or notes with fun features like listening to piano and raining sounds while writing...etc. Everything works fine and great but the problem is how can i turn those novels to PDF? ... I store everything as a "String" data type...ofc the user want to save his work which obviously I can do (Local storage or firebase) however i don't know about exporting data as a specific extension. how can I export the data as a PDF file if the user wanted to do that? is there a general way to do it?

A: One possible solution can be pdf Flutter plugin. You can create and save a pdf file from strings. I tried this sample code and pdf is created:
//get the directory to save pdf file
late Directory? directory;
if (Platform.isIOS) {
  directory = await getApplicationDocumentsDirectory();
} else {
  directory = await getExternalStorageDirectory();
}
var path = directory?.path;

//create pdf file
final pdf = pw.Document();
pdf.addPage(
  pw.Page(
    build: (pw.Context context) => pw.Center(
      child: pw.Text('Hello World!'),
    ),
  ),
);

//save pdf file
await File('$path/test.pdf').writeAsBytes(await pdf.save());

You can use path_provider Flutter plugin to get the directory location